
#include "qe3.h"

QEGlobals_t  g_qeglobals;

int g_autosave_interval;

int	currentdragselection = 0;
int dragselections[] = 
{
	ID_SELECTION_DRAGEDGES,
	ID_SELECTION_DRAGVERTECIES
};

int	currentinspector = 0;
int inspectorviews[] = 
{
	ID_VIEW_ENTITY,
	ID_VIEW_CONSOLE,
	ID_VIEW_TEXTURE
};

void QE_CheckOpenGLForErrors(void)
{
    int	    i;

    return;

    while ( ( i = glGetError() ) != GL_NO_ERROR )
    {
		char buffer[100];

		sprintf( buffer, "OpenGL Error: %s", gluErrorString( i ) );

		MessageBox( g_qeglobals.d_hwndMain, buffer , "KatanaEd Error", MB_OK | MB_ICONEXCLAMATION );
		exit( 1 );
    }
}


char *ExpandReletivePath(char *p, char *buffer)
{
	static char	tempbuf[1024];
	char	*base;

    if (buffer == NULL) {
        buffer = tempbuf;
    }

	if (!p || !p[0])
		return NULL;
	if (p[0] == '/' || p[0] == '\\')
		return p;

	base = ValueForKey(g_qeglobals.d_project_entity, "basepath");
	sprintf (buffer, "%s/%s", base, p);
	return buffer;
}



void *qmalloc (int size)
{
	void *b;
	b = malloc(size);
	memset (b, 0, size);
	return b;
}

char *copystring (char *s)
{
	char	*b;
	b = malloc(strlen(s)+1);
	strcpy (b,s);
	return b;
}

/*
===============
QE_CheckAutoSave

If five minutes have passed since making a change
and the map hasn't been saved, save it out.
===============
*/
void QE_CheckAutoSave( void )
{
	static clock_t	s_start;
	clock_t			now;
	char			filename[128];
	static int		count;

	now = clock();

	if ( modified != 1 || !s_start)
	{
		s_start = now;
		return;
	}

	if ( now - s_start > ( CLOCKS_PER_SEC * 60 * g_autosave_interval ) )
	{
		Sys_Printf ("Autosaving...\n");
		Sys_Status ("Autosaving...", 0 );

		sprintf (filename, "%s%d.map", ValueForKey(g_qeglobals.d_project_entity, "autosave"), count);

		Map_SaveFile (filename, false);

		Sys_Status ("Autosaving...Saved.", 0 );
		modified = 2;
		s_start = now;

		count ++;
		if (count >= 10)
			count = 0;
	}
}

///////////////////////////////////////////////////////////////////////////////
//	QE_LoadProject_DLL
///////////////////////////////////////////////////////////////////////////////

qboolean QE_LoadProject_DLL (char *projectfile)
{
	char	*data;
	char	DLL_path [1024];

	Sys_Printf ("QE_LoadProject_DLL (%s)\n", projectfile);

	if ( LoadFileNoCrash (projectfile, (void *)&data) == -1)
		return false;
	StartTokenParsing (data);
	g_qeglobals.d_project_entity = Entity_Parse (true);
	if (!g_qeglobals.d_project_entity)
		Error ("Couldn't parse %s", projectfile);
	free (data);

//	Eclass_InitForSourceDirectory (ValueForKey (g_qeglobals.d_project_entity, "entitypath"));
	
	//	NelnoFIXME:	hard coded this for now because I don't know how the hell the project
	//	stuff is organized
	//	Eclass_InitForSourceDirectory_DLL (ValueForKey (g_qeglobals.d_project_entity, "entitypath"));

	sprintf (DLL_path, "%s", ValueForKey (g_qeglobals.d_project_entity, "entitypath"));
	Eclass_InitForSourceDirectory_DLL (DLL_path);

	FillClassList ();		// list in entity window

	Map_New ();

	FillTextureMenu ();
	FillBSPMenu ();

	StripFilename (projectfile);
	strcpy (g_projectdir, projectfile);

	return true;
}

/*
===========
QE_LoadProject
===========
*/
qboolean QE_LoadProject (char *projectfile)
{
	char	*data;

#ifdef	DAIKATANA_MODE
	return	QE_LoadProject_DLL (projectfile);
#endif

	Sys_Printf ("QE_LoadProject (%s)\n", projectfile);

	if ( LoadFileNoCrash (projectfile, (void *)&data) == -1)
		return false;
	StartTokenParsing (data);
	g_qeglobals.d_project_entity = Entity_Parse (true);
	if (!g_qeglobals.d_project_entity)
		Error ("Couldn't parse %s", projectfile);
	free (data);

	Eclass_InitForSourceDirectory (ValueForKey (g_qeglobals.d_project_entity, "entitypath"));

	FillClassList ();		// list in entity window

	Map_New ();

	FillTextureMenu ();
	FillBSPMenu ();

	StripFilename (projectfile);
	strcpy (g_projectdir, projectfile);

	return true;
}

/*
===========
QE_SaveProject
===========
*/
extern char	*bsp_commands[256];

qboolean QE_SaveProject (void)
{
	char	filename[1024];
	FILE	*fp;
	epair_t	*ep;

	sprintf (filename, "%s\\%s.%s", g_projectdir, g_username, KED_PRJ_EXTENSION);

	if (!(fp = fopen (filename, "w+")))
		Error ("Could not open project file!");
	
	fprintf (fp, "{\n");
	for (ep = g_qeglobals.d_project_entity->epairs; ep; ep=ep->next)
		fprintf (fp, "\"%s\" \"%s\"\n", ep->key, ep->value);
	fprintf (fp, "}\n");

	fclose (fp);
	
	return TRUE;
}

/*
===========
QE_KeyDown
===========
*/
#define	SPEED_MOVE	32
#define	SPEED_TURN	22.5
double	cubicStart = 0;
double	cubicTime;

#define	CUBICWAIT	2

qboolean QE_KeyDown (int key)
{
	double	cubicEnd;
	brush_t	*b;
	vec3_t	delta;

	if (cubicClipping)
	{
		cubicTime = Sys_DoubleTime();
		cubicEnd = cubicTime - cubicStart;
	}

	switch (key)
	{
	case 'K': 
		if (xy_shearState == 2)
			XY_ShearSelectPoint();
		else if (yz_shearState == 2)
			YZ_ShearSelectPoint();
		else if (xz_shearState == 2)
			XZ_ShearSelectPoint();
		break;

	case 'B':
		PostMessage( g_qeglobals.d_hwndMain, WM_COMMAND, ID_MISC_SELECTENTITYCOLOR, 0 );
		break;
		
	case VK_RETURN:
		if (xy_shearState == 2)
			XY_ShearExecute();
		else if (yz_shearState == 2)
			YZ_ShearExecute();
		else if (xz_shearState == 2)
			XZ_ShearExecute();
		break;

	case VK_UP:
		VectorMA (camera.origin, SPEED_MOVE, camera.forward, camera.origin);
//		if (cubicClipping && cubicEnd < CUBICWAIT)
			Sys_UpdateWindows (W_CAMERA);
//		else
//			Sys_UpdateWindows (W_CAMERA|W_XY_OVERLAY|W_YZ_OVERLAY|W_XZ_OVERLAY);
		break;
	case VK_DOWN:
		VectorMA (camera.origin, -SPEED_MOVE, camera.forward, camera.origin);
//		if (cubicClipping && cubicEnd < CUBICWAIT)
			Sys_UpdateWindows (W_CAMERA);
//		else
//			Sys_UpdateWindows (W_CAMERA|W_XY_OVERLAY|W_YZ_OVERLAY|W_XZ_OVERLAY);
		break;
	case VK_LEFT:
		camera.angles[1] += SPEED_TURN;
//		if (cubicClipping && cubicEnd < CUBICWAIT)
			Sys_UpdateWindows (W_CAMERA);
//		else
//			Sys_UpdateWindows (W_CAMERA|W_XY_OVERLAY|W_YZ_OVERLAY|W_XZ_OVERLAY);
		break;
	case VK_RIGHT:
		camera.angles[1] -= SPEED_TURN;
//		if (cubicClipping && cubicEnd < CUBICWAIT)
			Sys_UpdateWindows (W_CAMERA);
//		else
//			Sys_UpdateWindows (W_CAMERA|W_XY_OVERLAY|W_YZ_OVERLAY|W_XZ_OVERLAY);
		break;
	case 'D':
		camera.origin[2] += SPEED_MOVE;
//		if (cubicClipping && cubicEnd < CUBICWAIT)
			Sys_UpdateWindows (W_CAMERA);
//		else
//			Sys_UpdateWindows (W_CAMERA|W_XY_OVERLAY|W_YZ_OVERLAY|W_XZ_OVERLAY|W_Z_OVERLAY);
		break;
	case 'C':
		camera.origin[2] -= SPEED_MOVE;
//		if (cubicClipping && cubicEnd < CUBICWAIT)
			Sys_UpdateWindows (W_CAMERA);
//		else
//			Sys_UpdateWindows (W_CAMERA|W_XY_OVERLAY|W_YZ_OVERLAY|W_XZ_OVERLAY|W_Z_OVERLAY);
		break;
	case 'A':
		camera.angles[0] += SPEED_TURN;
		if (camera.angles[0] > 85)
			camera.angles[0] = 85;
		Sys_UpdateWindows (W_CAMERA);
		break;
	case 'Z':
		camera.angles[0] -= SPEED_TURN;
		if (camera.angles[0] < -85)
			camera.angles[0] = -85;
		Sys_UpdateWindows (W_CAMERA);
		break;
	case VK_COMMA:
		VectorMA (camera.origin, -SPEED_MOVE, camera.right, camera.origin);
//		if (cubicClipping && cubicEnd < 0.5)
			Sys_UpdateWindows (W_CAMERA);
//		else
//			Sys_UpdateWindows (W_CAMERA|W_XY_OVERLAY|W_YZ_OVERLAY|W_XZ_OVERLAY);
		break;
	case VK_PERIOD:
		VectorMA (camera.origin, SPEED_MOVE, camera.right, camera.origin);
//		if (cubicClipping && cubicEnd < 0.5)
			Sys_UpdateWindows (W_CAMERA);
//		else
//			Sys_UpdateWindows (W_CAMERA|W_XY_OVERLAY|W_YZ_OVERLAY|W_XZ_OVERLAY);
		break;
		
	case 'W':
		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, ID_VIEW_PREVVIEW, 0);
		break;

	case 'Q':
		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, ID_VIEW_NEXTVIEW, 0);
		break;
	
	case '0':
		g_qeglobals.d_showgrid = !g_qeglobals.d_showgrid;
		PostMessage( g_qeglobals.d_hwndXY, WM_PAINT, 0, 0 );
		PostMessage( g_qeglobals.d_hwndYZ, WM_PAINT, 0, 0 );
		PostMessage( g_qeglobals.d_hwndXZ, WM_PAINT, 0, 0 );
		break;
	case '1':
		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, ID_GRID_1, 0);
		break;
	case '2':
		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, ID_GRID_2, 0);
		break;
	case '3':
		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, ID_GRID_4, 0);
		break;
	case '4':
		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, ID_GRID_8, 0);
		break;
	case '5':
		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, ID_GRID_16, 0);
		break;
	case '6':
		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, ID_GRID_32, 0);
		break;
	case '7':
		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, ID_GRID_64, 0);
		break;
		
	case 'E':
		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, ID_SELECTION_DRAGEDGES, 0);
		break;
	case 'V':
//		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, ID_SELECTION_DRAGVERTECIES, 0);
		currentdragselection++;
		if (currentdragselection > 1)
			currentdragselection = 0;
		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, dragselections[currentdragselection], 0);
		break;
		
	case VK_TAB:
		currentinspector++;
		if (currentinspector > 2)
			currentinspector = 0;
		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, inspectorviews[currentinspector], 0);
		break;

	case 'N':
		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, ID_VIEW_ENTITY, 0);
		break;
	case 'O':
		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, ID_VIEW_CONSOLE, 0);
		break;
	case 'T':
		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, ID_VIEW_TEXTURE, 0);
		break;
	case 'P':
		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, ID_TEXTURES_INSPECTOR, 0);
		break;
		
	case ' ':
		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, ID_SELECTION_CLONE, 0);
		break;
		
	case VK_BACK:
		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, ID_SELECTION_DELETE, 0);
		xy_shearPos = xy_shearState = 0;
		yz_shearPos = yz_shearState = 0;
		xz_shearPos = xz_shearState = 0;
		break;

	case VK_ESCAPE:
		if (xy_shearState || yz_shearState || xz_shearState)
		{
			xy_shearPos = xy_shearState = 0;
			yz_shearPos = yz_shearState = 0;
			xz_shearPos = xz_shearState = 0;
			Sys_UpdateWindows (W_XY_OVERLAY|W_YZ_OVERLAY|W_XZ_OVERLAY|W_Z);
		}
		else
	case VK_END:
			PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, ID_SELECTION_DESELECT, 0);
		break;

	case VK_DELETE:
	case 'X':
		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, ID_VIEW_ZOOMIN, 0);
		break;
	case VK_INSERT:
	case 'S':
		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, ID_VIEW_ZOOMOUT, 0);
		break;
		
	case VK_NEXT:
		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, ID_VIEW_DOWNFLOOR, 0);
		break;
	case VK_PRIOR:
		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, ID_VIEW_UPFLOOR, 0);
		break;

	case VK_HOME:
		PostMessage (g_qeglobals.d_hwndMain, WM_COMMAND, ID_VIEW_CENTER, 0);
		break;
	
	case VK_ADD:
		for (b = selected_brushes.next;b != &selected_brushes; b=b->next)
		{
			delta[0] = delta[1] = 0;
			delta[2] = g_qeglobals.d_gridsize;
			Brush_Move(b, delta);
		}
//		Sys_UpdateWindows (W_CAMERA|W_XY_OVERLAY|W_YZ_OVERLAY|W_XZ_OVERLAY|W_Z_OVERLAY);
		Sys_UpdateWindows (W_CAMERA);
		break;

	case VK_SUBTRACT:
		for (b = selected_brushes.next;b != &selected_brushes; b=b->next)
		{
			delta[0] = delta[1] = 0;
			delta[2] = -g_qeglobals.d_gridsize;
			Brush_Move(b, delta);
		}
//		Sys_UpdateWindows (W_CAMERA|W_XY_OVERLAY|W_YZ_OVERLAY|W_XZ_OVERLAY|W_Z_OVERLAY);
		Sys_UpdateWindows (W_CAMERA);
		break;

	default:
		return false;
		
	}

	return true;
}

/*
===============
ConnectEntities

Sets target / targetname on the two entities selected
from the first selected to the secon
===============
*/

void	node_connect_nodes (entity_t *e1, entity_t *e2);

void ConnectEntities (void)
{
	entity_t	*e1, *e2, *e;
	char		*target, *tn;
	int			maxtarg, targetnum;
	char		newtarg[32];

	if (g_qeglobals.d_select_count != 2)
	{
		Sys_Status ("Must have two brushes selected.", 0);
		Sys_Beep ();
		return;
	}

	e1 = g_qeglobals.d_select_order[0]->owner;
	e2 = g_qeglobals.d_select_order[1]->owner;

	//	Nelno:	if connecting two nodes, then connect with linkX instead of target/targetname
	if (!stricmp (e1->eclass->name, "node_node") && !stricmp (e2->eclass->name, "node_node"))
	{
		node_connect_nodes (e1, e2);
		return;
	}

	if (e1 == world_entity || e2 == world_entity)
	{
		Sys_Status ("Can't connect to the world.", 0);
		Sys_Beep ();
		return;
	}

	if (e1 == e2)
	{
		Sys_Status ("Brushes are from same entity.", 0);
		Sys_Beep ();
		return;
	}

	target = ValueForKey (e1, "target");
	if (target && target[0])
		strcpy (newtarg, target);
	else
	{
		target = ValueForKey (e2, "targetname");
		if (target && target[0])
			strcpy (newtarg, target);
		else
		{
			// make a unique target value
			maxtarg = 0;
			for (e=entities.next ; e != &entities ; e=e->next)
			{
				tn = ValueForKey (e, "targetname");
				if (tn && tn[0])
				{
					targetnum = atoi(tn+1);
					if (targetnum > maxtarg)
						maxtarg = targetnum;
				}
			}
			sprintf (newtarg, "t%i", maxtarg+1);
		}
	}

	SetKeyValue (e1, "target", newtarg);
	SetKeyValue (e2, "targetname", newtarg);
	Sys_UpdateWindows (W_XY | W_CAMERA);

	Select_Deselect();
	Select_Brush (g_qeglobals.d_select_order[1]);
}

qboolean QE_SingleBrush (void)
{
	if ( (selected_brushes.next == &selected_brushes)
		|| (selected_brushes.next->next != &selected_brushes) )
	{
		Sys_Printf ("Error: you must have a single brush selected\n");
		return false;
	}
	if (selected_brushes.next->owner->eclass->fixedsize)
	{
		Sys_Printf ("Error: you cannot manipulate fixed size entities\n");
		return false;
	}

	return true;
}

void QE_Init (void)
{
	/*
	** initialize variables
	*/
	g_qeglobals.d_gridsize = 8;
	g_qeglobals.d_showgrid = true;

	/*
	** other stuff
	*/
	Undo_Init ();
	Texture_Init ();
	Cam_Init ();
	XY_Init ();
	YZ_Init ();
	XZ_Init ();
	Z_Init ();
}

void QE_ConvertDOSToUnixName( char *dst, const char *src )
{
	while ( *src )
	{
		if ( *src == '\\' )
			*dst = '/';
		else
			*dst = *src;
		dst++; src++;
	}
	*dst = 0;
}

int g_numbrushes, g_numentities;

void QE_CountBrushesAndUpdateStatusBar( void )
{
	static int      s_lastbrushcount, s_lastentitycount;
	static qboolean s_didonce;
	
	entity_t   *e;
	brush_t	   *b, *next;

	g_numbrushes = 0;
	g_numentities = 0;
	
	if ( active_brushes.next != NULL )
	{
		for ( b = active_brushes.next ; b != NULL && b != &active_brushes ; b=next)
		{
			next = b->next;
			if (b->brush_faces )
			{
				if ( !b->owner->eclass->fixedsize)
					g_numbrushes++;
				else
					g_numentities++;
			}
		}
	}

	if ( entities.next != NULL )
	{
		for ( e = entities.next ; e != &entities && g_numentities != MAX_MAP_ENTITIES ; e = e->next)
		{
			g_numentities++;
		}
	}

	if ( ( ( g_numbrushes != s_lastbrushcount ) || ( g_numentities != s_lastentitycount ) ) || ( !s_didonce ) )
	{
		Sys_UpdateStatusBar();

		s_lastbrushcount = g_numbrushes;
		s_lastentitycount = g_numentities;
		s_didonce = true;
	}
}

