#include "stdafx.h"
#include "basic.h"
#include "Eroc.h"
#include "OGLState.h"
#include "Textures.h"

#ifdef import_globals
#undef import_globals
#endif
#include "globals.h"


// Gopher stuff
SDL_Surface ** mOutputSurfaces;
SDL_Surface ** mInputSurfaces;
long mCurrentOutputSurface;

// OpenGL stuff
OGLState* theMainWindowState = 0;


/////////////////////////////////////////////////////////////////////////////

BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) {
    switch ( ul_reason_for_call ) {
		case DLL_PROCESS_ATTACH:
		case DLL_THREAD_ATTACH:
		case DLL_THREAD_DETACH:
		case DLL_PROCESS_DETACH:
			break;
    }
    return TRUE;
}


EROC_API BOOL Gopher_Init ( SDL_Surface ** outputSurfaces, SDL_Surface ** inputSurfaces ) 
{
	mOutputSurfaces = outputSurfaces;
	mInputSurfaces = inputSurfaces;

	// Set correct Aspect ratio

	float theAspect = (float)gVScreenX/gVScreenY;

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glFrustum(-theAspect, theAspect, -1.0, 1.0, 1.0, 100);
	glMatrixMode(GL_MODELVIEW);

	// Check for extensions
	if (! (WGLEW_ARB_pbuffer &&
		   WGLEW_ARB_pixel_format && 
		   WGLEW_ARB_render_texture) )
		return false;

	// Check for Pbuffer pixel format
	HDC theHDC = wglGetCurrentDC();

	float fAttributes[] = {0, 0};
	int pixelFormat;
	UINT numFormats = 0;

	int iAttributes[] = {
		WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
		WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB,
		WGL_DOUBLE_BUFFER_ARB, GL_FALSE,
		WGL_COLOR_BITS_ARB,24,
		WGL_ALPHA_BITS_ARB,8,
		WGL_DEPTH_BITS_ARB,16,
		WGL_DRAW_TO_PBUFFER_ARB, GL_TRUE,
		WGL_BIND_TO_TEXTURE_RGBA_ARB, GL_TRUE,
		0,0};

	bool OK = wglChoosePixelFormatARB(theHDC, iAttributes, fAttributes,
			1, &pixelFormat, &numFormats);

	if ( !OK || numFormats < 1)
		return false;

	theMainWindowState = new OGLState();
	OGLState::SetState(theMainWindowState);


	// Clear the screen because some effects take a while to load and we don't want garbage on the screen.	
	Clear();

	// load the images
	FILE* BitMapList = fopen("ImageList.txt", "r");
	if (!BitMapList)
		return FALSE;

	char FileName[256];
	long int NeedSurface;
	while (2 == fscanf(BitMapList, "%s %ld", &FileName, &NeedSurface ))
	{
		int ImageNr = CreateTextureFromFile(FileName, (bool)NeedSurface);
		if (ImageNr >= eMaxBitMaps)
			break;
	}
	fclose(BitMapList);

	// Load the Anim lists

	LoadAnims();

	// Set remaining global OpenGL variables (should be removed)	
	glShadeModel(GL_SMOOTH);					// Enable Smooth Shading

	BuildFont();

	return true;
}

EROC_API BOOL Gopher_BeginNewFrame ( long currentOutputSurface ) 
{
	mCurrentOutputSurface = currentOutputSurface;
	return true;
}

EROC_API BOOL Gopher_Quit ( void ) 
{	
	KillFont();
	FreeAnims();
	FreeImages();

	OGLState::SetState(0);	
	theMainWindowState = 0;
	
	return true;
}