// Author : Chris Tolley
// Date   : 8/17/2004
// ScreenWriter.cpp contains the class definition for a static class that
// allows the user to print text onto an orthographic screen

#include <windows.h>
#include <gl/gl.h>
#include <gl/glu.h>
#include <stdarg.h>

#include "ScreenWriter.h"
#include "logger.h"

// Declare the static variables
unsigned int ScreenWriter::m_uiBase = 0;
HDC			 ScreenWriter::m_hdc    = NULL;

// Constructor
ScreenWriter::ScreenWriter()
{}


// Destructor
ScreenWriter::~ScreenWriter()
{}


// Initializes the screen writer
bool ScreenWriter::Initialize( int point, const char* fontType )
{
	// Check to see if we already had a list at some other point
	if( m_uiBase != 0 )
	{
		// Delete the list
		glDeleteLists( m_uiBase, 1 );
	}// End if

	// Create a list for the screen writer to use to render text
	m_uiBase = glGenLists( 96 );

	// Create the font
	HFONT font = CreateFont( point, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,
							 ANSI_CHARSET, OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS,
							 ANTIALIASED_QUALITY, FF_DONTCARE | DEFAULT_PITCH,
							 fontType );

	// Verify that the font was created or not
	if( font )
	{
		logger::event( "ScreenWriter::Initialize", "Font initialized", 0 );
	}// End if
	else
	{
		logger::event( "ScreenWriter::Initialize",
					   "Unable to initialize font", 0 );
		return false;
	}// End else

	// Select the device context to use when rendering text
	SelectObject( m_hdc, font );
	wglUseFontBitmaps( m_hdc, 32, 96, m_uiBase );

	// Return true
	return true;
}// End ScreenWriter::Initialize


// Allows the user to write text to the screen.  x,y is the position
// on the screen, text is the text to write, point is the font point,
// fontType is the name of the font type.
void ScreenWriter::Render( float x, float y, float* color, const char* text, ... )
{
	// Get the arguments from the argument list
	char final[1024];
	va_list ap;
	va_start( ap, text );
	vsprintf( final, text, ap );
	va_end( ap );

	// Set the current color
	glColor3fv( color );

	// Save and reset the modelview matrix
	glPushMatrix();
	glLoadIdentity();

	// Select the projection matrix stack
	glMatrixMode( GL_PROJECTION );
	// Save and reset the projection matrix stack
	glPushMatrix();
	glLoadIdentity();

	// Set up an orthographic projection
	gluOrtho2D( 0, 200, 0, 200 );

	// Select the modelview matrix stack
	glMatrixMode( GL_MODELVIEW );

	// Set up the current raster position and color
	glRasterPos2f( x, y );

	glListBase( m_uiBase - 32 );
	glCallLists( strlen( final ), GL_UNSIGNED_BYTE, final );

	// Select the projection matrix stack and restore the settings
	glMatrixMode( GL_PROJECTION );
	glPopMatrix();

	// Select the modelview matrix stack and restore the settings
	glMatrixMode( GL_MODELVIEW );
	glPopMatrix();

	// Restore the color
	glColor3f( 1, 1, 1 );
}// End ScreenWriter::Write
