#include "main.h"
#include "windowing.h"
#include "renderer.h"
#include "quadtree.h"
#include "logger.h"
#include "camera.h"
#include "engine.h"
#include "text.h"

rText *t = 0;
HANDLE g_EndFrameSignal;
rRenderer *g_Renderer = 0;
rWindowing *w;
CCamera g_Camera;
Logger g_Logger;
rMath *m = InitMath();
char mapName[256];
rMap *g_Map = 0;
engine e;
HANDLE g_RenderStateMutex; 


void rInitFromGLThread()
{
	//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //lines
	//g_Renderer->enableMotionBlur(0.3f,0.7f);
	glEnable(GL_CULL_FACE);
	glEnable(GL_DEPTH_TEST);
	glCullFace(GL_BACK);

	if(g_Map)
		delete g_Map;

	g_Map = new rMap;

	if(g_Map->Load(mapName))
		exit(0);

	if(!t)
		t = new rOGLText;
}
void rDeInitFromGLThread()
{
	delete g_Map;
	delete t;	
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hprev, PSTR cmdline, int show)
{	
	g_Logger.Log("Application entry point");
	g_EndFrameSignal = CreateEvent(0,0,1,0);
	if(!cmdline[0])
		cmdline = "cfg.txt";
	if(!e.Init(cmdline))
		return 1;

	e.Update();

	rWindowing::SetHI(hInstance);
	g_RenderStateMutex = CreateMutex(NULL, FALSE, NULL);

	MSG msg;
	while(1)
	{
		if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) 
        {
			if(msg.message == WM_QUIT )	
				break;

            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }else
		{
			e.Update();
		}
	}

	g_Logger.Log("Shutting down...");
	
	g_Renderer->Kill();
	CloseHandle(g_RenderStateMutex);

	if(g_Renderer)
		delete g_Renderer;

	return 0;
}