#include"opengl.h"

BOOL SetVideoMode(int iWidth,int iHeight,int iDepth,BOOL bFullScreen)
{
	int iCurWidth,iCurHeight,iCurDepth;
	DEVMODE dm;

	memset(&dm, 0, sizeof(dm));
	dm.dmSize = sizeof(dm);

	dm.dmFields = DM_BITSPERPEL;
	dm.dmBitsPerPel = iDepth;

	if (!bFullScreen)
	{
		LogMsg("...using current desktop resolution\n");
	}
	else
	{
		LogMsg("...trying fullscreen\n");

		dm.dmFields |= (DM_PELSWIDTH | DM_PELSHEIGHT);

		dm.dmPelsWidth  = iWidth;
		dm.dmPelsHeight = iHeight;
	}

	LogMsg("...calling CDS\n");

	if (ChangeDisplaySettings(&dm,CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
	{
		return FALSE;
	}

	return TRUE;
}

BOOL OpenGLInit(int *iDepth,int *iZDepth,int *iStencilDepth)
{
	int iPixelFormat;

	CfgVals glstr[3] =
	{
		{"GL_VENDOR",GL_VENDOR},
		{"GL_RENDERER",GL_RENDERER},
		{"GL_VERSION",GL_VERSION}
	};

	PIXELFORMATDESCRIPTOR pfd = 
	{
		sizeof(pfd),
		1,
		PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,  
		PFD_TYPE_RGBA,
		(*iDepth),
		0,0,0,0,0,0,
		0,
		0,
		0,
		0,0,0,0,
		(*iZDepth),
		(*iStencilDepth),
		0,
		PFD_MAIN_PLANE,
		0,
		0,0,0
	};

	LogMsg("...getting DC\n");

	g_hDc = GetDC(g_hWnd);

	if (!g_hDc)
	{
		return FALSE;
	}
	
	LogMsg("...choosing desired PF\n");

	iPixelFormat = ChoosePixelFormat(g_hDc,&pfd);

	if (!iPixelFormat)
	{
		return FALSE;
	}

	LogMsg("...getting information about PF\n");

	if (!DescribePixelFormat(g_hDc,iPixelFormat,sizeof(pfd),&pfd))
	{
		return FALSE;
	}

	LogMsg("...checking for hardware acceleration\n...choosed PFD=%d (bpp=%d zbuffer=%d stencil=%d)\n",iPixelFormat,pfd.cColorBits,pfd.cDepthBits,pfd.cStencilBits);

	if ((pfd.dwFlags)&PFD_GENERIC_FORMAT)
	{
		return FALSE;
	}

	LogMsg("...setting pixel format\n");

	if (!SetPixelFormat(g_hDc,iPixelFormat,&pfd))
	{
		return FALSE;
	}

	LogMsg("...creating OGLRC\n");

	g_hGlrc = wglCreateContext(g_hDc);

	if (!g_hGlrc)
	{
		return FALSE;
	}

	LogMsg("...making current\n");

	if (!wglMakeCurrent(g_hDc,g_hGlrc))
	{
		return FALSE;
	}

	LogMsg("...driver stats:\n");

	for(int j=0;j<3;j++)
	{
		LogMsg("%s:%s\n",glstr[j].lpszKeyName,glGetString(glstr[j].nDefault));
	}

	*iDepth			= pfd.cColorBits;
	*iZDepth		= pfd.cDepthBits;
	*iStencilDepth	= pfd.cStencilBits;

	return TRUE;
}

void OpenGLRelease(void)
{
	if (g_hGlrc)
	{
		LogMsg("...deleting OGLRC\n");

		wglMakeCurrent(NULL,NULL);
		wglDeleteContext(g_hGlrc);

		g_hGlrc = NULL;
	}

	if (g_hDc)
	{
		ReleaseDC(g_hWnd,g_hDc);
		g_hDc = NULL;
	}

	return;
}