#include <stdlib.h>
#include <windows.h>		// Header File For Windows
#include <gl\gl.h>			// Header File For The OpenGL32 Library
#include <gl\glu.h>			// Header File For The GLu32 Library
#include <gl\glaux.h>		// Header File For The Glaux Library
//#include <gl\glut.h>
#include "glext.h"
#include <stdio.h>
#include <math.h>
#include <string.h>														// Header File For The String Library

#pragma comment(lib, "opengl32.lib")					// Link OpenGL32.lib
#pragma comment(lib, "glu32.lib")						// Link Glu32.lib

#define MAX_EMBOSS (GLfloat)0.008f	// Maximum Emboss-Translate. Increase To Get Higher Immersion
									// At A Cost Of Lower Quality (More Artifacts Will Occur!)
#define __ARB_ENABLE true											// Used To Disable ARB Extensions Entirely

#define EXT_INFO													// Do You Want To See Your Extensions At Start-Up?
#define MAX_EXTENSION_SPACE 10240									// Characters for Extension-Strings
#define MAX_EXTENSION_LENGTH 256									// Maximum Of Characters In One Extension-String
bool multitextureSupported=false;									// Flag Indicating Whether Multitexturing Is Supported
bool useMultitexture=true;											// Use It If It Is Supported?
GLint maxTexelUnits=1;												// Number Of Texel-Pipelines. This Is At Least 1.

#define		MAP_SIZE	  1024							// Size Of Our .RAW Height Map (NEW)
//#define		MAP_SIZE	  2048
#define		STEP_SIZE	  16							// Width And Height Of Each Quad (NEW)
#define		HEIGHT_RATIO  0.8f							// Ratio That The Y Is Scaled According To The X And Z (NEW)#define		HEIGHT_RATIO  1.0f							// Ratio That The Y Is Scaled According To The X And Z (NEW)


PFNGLMULTITEXCOORD1FARBPROC		glMultiTexCoord1fARB	= NULL;
PFNGLMULTITEXCOORD2FARBPROC		glMultiTexCoord2fARB	= NULL;
PFNGLMULTITEXCOORD3FARBPROC		glMultiTexCoord3fARB	= NULL;
PFNGLMULTITEXCOORD4FARBPROC		glMultiTexCoord4fARB	= NULL;
PFNGLACTIVETEXTUREARBPROC		glActiveTextureARB		= NULL;
PFNGLCLIENTACTIVETEXTUREARBPROC	glClientActiveTextureARB= NULL;	


HDC			hDC=NULL;		// Private GDI Device Context
HGLRC		hRC=NULL;		// Permanent Rendering Context
HWND		hWnd=NULL;		// Holds Our Window Handle
HINSTANCE	hInstance;		// Holds The Instance Of The Application

GLfloat a= 0.5f;
GLfloat d= 40.0f;
GLfloat b= 2.0f;
GLfloat i = 0.1f;
GLfloat j = 15.0f;
GLfloat k = 0.001f;
GLfloat z=  -15; 
GLfloat y=  -1;
GLfloat x=  -1;
GLfloat scenez1=  -40.0f; 
GLfloat scenez2=  12.0f; 
GLfloat scenex1=  -15.0f; 
GLfloat scenex2=  20.0f; 
GLfloat Kartz1=  -4.0f; 
GLfloat Kartx1=  -0.1f;
GLfloat Kartz2=  -4.5f;
GLfloat Kartx2=  0.4f;
GLfloat temp=0.0f;
GLfloat temp1=0.0f;
GLfloat fwallz=-40.0f;
GLfloat rwallx=20.0f;
GLfloat lwallx=-15.0f;
bool showmessage =true;

GLfloat forward=0.0;
GLfloat xterrain=1550.0;
GLfloat yterrain=545.0;
GLfloat xmove=0.0;
GLfloat xmove1=40.0;		// variable for translating x
GLfloat angle = 0.0;
//GLfloat angle1 = -35.0;
GLfloat angle1 = 0.0;
GLfloat Kartangle = 0.0;


GLuint	filter=1;													// Which Filter To Use
GLuint	top[3];													// Storage For 3 Textures
GLuint	bottom[3];													// Storage For 3 Textures
GLuint	right[3];													// Storage For 3 Textures
GLuint	front[3];													// Storage For 3 Textures
GLuint  point[3];		
GLuint  carside[3];	
GLuint  carback[3];	
GLuint  cartop[3];	
GLuint  finishing[3];	
double	totalmarks=100.0;
double	totalcollision=0.0;
double  steps=0.0;
double	wallhit=0.0;
double	patchhit=0.0;
int check;
int check1;
int check2;
int check3;
											// Inverted Bumpmaps
GLfloat Gray[]= {0.5f,0.5f,0.5f,1.0f};

GLUquadricObj *quad;	// Storage For Our Quadratic Objects
bool	keys[256];			// Array Used For The Keyboard Routine
bool	active=true;		// Window Active Flag Set To TRUE By Default
bool	fullscreen=true;	// Fullscreen Flag Set To Fullscreen Mode By Default
bool	light=false;				// Lighting ON/OFF
bool	bRender =true;								// Polygon Flag Set To TRUE By Default (NEW)
bool	lp;					// L Pressed?
bool    bumps=false;													// Do Bumpmapping?
char MsgText[100];
char scoretemp[5];
char collisiontemp[5];
char steptemp[5];
char wallhittemp[5];
char patchhittemp[5];

UINT TextureArray[2];

const float piover180 = 0.0174532925f;
float heading;
float xpos;
float zpos;

GLfloat	xrot;				// X Rotation
GLfloat	yrot;				// Y Rotation
GLfloat xspeed;				// X Rotation Speed
GLfloat yspeed;				// Y Rotation Speed
GLfloat	zmove=1570.0f;			// Depth Into The Screen
//GLfloat	zmove=0.0f;			// Depth Into The Screen

GLfloat walkbias = 0;
GLfloat walkbiasangle = 0;
GLfloat lookupdown = 0.0f;
	
GLfloat light_specular[]= {1.0f,1.0f,1.0f,k};
GLfloat light_ambient[]= {0.0,0.0,0.0,k};
GLfloat light_diffuse[]= {0.8f,0.8f,0.8f,k};

BYTE g_HeightMap[MAP_SIZE*MAP_SIZE];					// Holds The Height Map Data (NEW)
float scaleValue = 0.09f;								// Scale Value For The Terrain (NEW)


#define __ARB_ENABLE true											// Used To Disable ARB Extensions Entirely

LRESULT	CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);	// Declaration For WndProc

// Always Check For Extension-Availability During Run-Time!
bool isInString(char *string, const char *search) {
	int pos=0;
	int maxpos=strlen(search)-1;
	int len=strlen(string);	
	char *other;
	for (int i=0; i<len; i++) {
		if ((i==0) || ((i>1) && string[i-1]=='\n')) {				// New Extension Begins Here!
			other=&string[i];			
			pos=0;													// Begin New Search
			while (string[i]!='\n') {								// Search Whole Extension-String
				if (string[i]==search[pos]) pos++;					// Next Position
				if ((pos>maxpos) && string[i+1]=='\n') return true; // We Have A Winner!
				i++;
			}			
		}
	}	
	return false;													// Sorry, Not Found!
}

// isMultitextureSupported() Checks At Run-Time If Multitexturing Is Supported
bool initMultitexture(void) {
	char *extensions;	
	extensions=strdup((char *) glGetString(GL_EXTENSIONS));			// Fetch Extension String
	int len=strlen(extensions);
	for (int i=0; i<len; i++)										// Separate It By Newline Instead Of Blank
		if (extensions[i]==' ') extensions[i]='\n';

	if (isInString(extensions,"GL_ARB_multitexture")				// Is Multitexturing Supported?
		&& __ARB_ENABLE												// Override-Flag
		&& isInString(extensions,"GL_EXT_texture_env_combine"))		// Is texture_env_combining Supported?
	{	
		glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB,&maxTexelUnits);
		glMultiTexCoord1fARB	= (PFNGLMULTITEXCOORD1FARBPROC)		wglGetProcAddress("glMultiTexCoord1fARB");
		glMultiTexCoord2fARB	= (PFNGLMULTITEXCOORD2FARBPROC)		wglGetProcAddress("glMultiTexCoord2fARB");
		glMultiTexCoord3fARB	= (PFNGLMULTITEXCOORD3FARBPROC)		wglGetProcAddress("glMultiTexCoord3fARB");
		glMultiTexCoord4fARB	= (PFNGLMULTITEXCOORD4FARBPROC)		wglGetProcAddress("glMultiTexCoord4fARB");
		glActiveTextureARB		= (PFNGLACTIVETEXTUREARBPROC)		wglGetProcAddress("glActiveTextureARB");
		glClientActiveTextureARB= (PFNGLCLIENTACTIVETEXTUREARBPROC)	wglGetProcAddress("glClientActiveTextureARB");		
#ifdef EXT_INFO
	MessageBox(hWnd,"The GL_ARB_multitexture extension will be used.","feature supported!",MB_OK | MB_ICONINFORMATION);
#endif
		return true;
	}
	useMultitexture=false;											// We Can't Use It If It Isn't Supported!
	return false;
}


// Loads The .RAW File And Stores It In pHeightMap
void LoadRawFile(LPSTR strName, int nSize, BYTE *pHeightMap)
{
	FILE *pFile = NULL;

	// Open The File In Read / Binary Mode.
	pFile = fopen( strName, "rb" );

	// Check To See If We Found The File And Could Open It
	if ( pFile == NULL )	
	{
		// Display Error Message And Stop The Function
		MessageBox(NULL, "Can't Find The Height Map!", "Error", MB_OK);
		return;
	}

	fread( pHeightMap, 1, nSize, pFile );

	// After We Read The Data, It's A Good Idea To Check If Everything Read Fine
	int result = ferror( pFile );

	// Check If We Received An Error
	if (result)
	{
		MessageBox(NULL, "Failed To Get Data!", "Error", MB_OK);
	}

	// Close The File.
	fclose(pFile);
}


// Using auxDIBImageLoad's Own Error-Handler!
int LoadGLTextures(){												// Load Bitmaps And Convert To Textures
	bool status=true;												// Status Indicator
	AUX_RGBImageRec *Image=NULL;									// Create Storage Space For The Texture
	char *alpha=NULL;

	// Load The Tile-Bitmap For floorbase-Texture
	if (Image=auxDIBImageLoad("Pic/top3.bmp")) {											
		glGenTextures(3, top);									// Create Three Textures

		// Create Nearest Filtered Texture
		glBindTexture(GL_TEXTURE_2D, top[0]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, Image->sizeX, Image->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, Image->data);
		//                             ========
		// Use GL_RGB8 Instead Of "3" In glTexImage2D. Also Defined By GL: GL_RGBA8 Etc.
		// NEW: Now Creating GL_RGBA8 Textures, Alpha Is 1.0f Where Not Specified By Format.

		// Create Linear Filtered Texture
		glBindTexture(GL_TEXTURE_2D, top[1]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, Image->sizeX, Image->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, Image->data);

		// Create MipMapped Texture
		glBindTexture(GL_TEXTURE_2D, top[2]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST);
		gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB8, Image->sizeX, Image->sizeY, GL_RGB, GL_UNSIGNED_BYTE, Image->data);
	}
	else status=false;
	if (Image) {													// If Texture Exists
		if (Image->data) delete Image->data;						// If Texture Image Exists
		delete Image;
		Image=NULL;
	}	
	
	// Load The Tile-Bitmap For ceilingdaybase-Texture
	if (Image=auxDIBImageLoad("Pic/bottom1.bmp")) {											
		glGenTextures(3, bottom);									// Create Three Textures

		// Create Nearest Filtered Texture
		glBindTexture(GL_TEXTURE_2D, bottom[0]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, Image->sizeX, Image->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, Image->data);
		//                             ========
		// Use GL_RGB8 Instead Of "3" In glTexImage2D. Also Defined By GL: GL_RGBA8 Etc.
		// NEW: Now Creating GL_RGBA8 Textures, Alpha Is 1.0f Where Not Specified By Format.

		// Create Linear Filtered Texture
		glBindTexture(GL_TEXTURE_2D, bottom[1]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, Image->sizeX, Image->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, Image->data);

		// Create MipMapped Texture
		glBindTexture(GL_TEXTURE_2D, bottom[2]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST);
		gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB8, Image->sizeX, Image->sizeY, GL_RGB, GL_UNSIGNED_BYTE, Image->data);
	}
	else status=false;
	if (Image) {													// If Texture Exists
		if (Image->data) delete Image->data;						// If Texture Image Exists
		delete Image;
		Image=NULL;
	}	
	
	// Load The Tile-Bitmap For ceilingnightbase-Texture
	if (Image=auxDIBImageLoad("Pic/grassfront1.bmp")) {											
		glGenTextures(3, front);									// Create Three Textures

		// Create Nearest Filtered Texture
		glBindTexture(GL_TEXTURE_2D, front[0]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, Image->sizeX, Image->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, Image->data);
		//                             ========
		// Use GL_RGB8 Instead Of "3" In glTexImage2D. Also Defined By GL: GL_RGBA8 Etc.
		// NEW: Now Creating GL_RGBA8 Textures, Alpha Is 1.0f Where Not Specified By Format.

		// Create Linear Filtered Texture
		glBindTexture(GL_TEXTURE_2D, front[1]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, Image->sizeX, Image->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, Image->data);

		// Create MipMapped Texture
		glBindTexture(GL_TEXTURE_2D, front[2]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST);
		gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB8, Image->sizeX, Image->sizeY, GL_RGB, GL_UNSIGNED_BYTE, Image->data);
	}
	else status=false;
	if (Image) {													// If Texture Exists
		if (Image->data) delete Image->data;						// If Texture Image Exists
		delete Image;
		Image=NULL;
	}	

	// Load The Tile-Bitmap For ceilingnightbase-Texture
	if (Image=auxDIBImageLoad("Pic/side2.bmp")) {											
		glGenTextures(3, right);									// Create Three Textures

		// Create Nearest Filtered Texture
		glBindTexture(GL_TEXTURE_2D, right[0]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, Image->sizeX, Image->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, Image->data);
		//                             ========
		// Use GL_RGB8 Instead Of "3" In glTexImage2D. Also Defined By GL: GL_RGBA8 Etc.
		// NEW: Now Creating GL_RGBA8 Textures, Alpha Is 1.0f Where Not Specified By Format.

		// Create Linear Filtered Texture
		glBindTexture(GL_TEXTURE_2D, right[1]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, Image->sizeX, Image->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, Image->data);

		// Create MipMapped Texture
		glBindTexture(GL_TEXTURE_2D, right[2]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST);
		gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB8, Image->sizeX, Image->sizeY, GL_RGB, GL_UNSIGNED_BYTE, Image->data);
	}
	else status=false;
	if (Image) {													// If Texture Exists
		if (Image->data) delete Image->data;						// If Texture Image Exists
		delete Image;
		Image=NULL;
	}	


	// Load The Tile-Bitmap For ceilingnightbase-Texture
	if (Image=auxDIBImageLoad("Pic/finish.bmp")) {											
		glGenTextures(3, finishing);									// Create Three Textures

		// Create Nearest Filtered Texture
		glBindTexture(GL_TEXTURE_2D, finishing[0]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, Image->sizeX, Image->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, Image->data);
		//                             ========
		// Use GL_RGB8 Instead Of "3" In glTexImage2D. Also Defined By GL: GL_RGBA8 Etc.
		// NEW: Now Creating GL_RGBA8 Textures, Alpha Is 1.0f Where Not Specified By Format.

		// Create Linear Filtered Texture
		glBindTexture(GL_TEXTURE_2D, finishing[1]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, Image->sizeX, Image->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, Image->data);

		// Create MipMapped Texture
		glBindTexture(GL_TEXTURE_2D, finishing[2]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST);
		gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB8, Image->sizeX, Image->sizeY, GL_RGB, GL_UNSIGNED_BYTE, Image->data);
	}
	else status=false;
	if (Image) {													// If Texture Exists
		if (Image->data) delete Image->data;						// If Texture Image Exists
		delete Image;
		Image=NULL;
	}	




	// Load The Tile-Bitmap For right wallbase-Texture
	if (Image=auxDIBImageLoad("Pic/carside2.bmp")) {											
		glGenTextures(3, point);									// Create Three Textures

		// Create Nearest Filtered Texture
		glBindTexture(GL_TEXTURE_2D, point[0]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, Image->sizeX, Image->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, Image->data);
		//                             ========
		// Use GL_RGB8 Instead Of "3" In glTexImage2D. Also Defined By GL: GL_RGBA8 Etc.
		// NEW: Now Creating GL_RGBA8 Textures, Alpha Is 1.0f Where Not Specified By Format.

		// Create Linear Filtered Texture
		glBindTexture(GL_TEXTURE_2D, point[1]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, Image->sizeX, Image->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, Image->data);

		// Create MipMapped Texture
		glBindTexture(GL_TEXTURE_2D, point[2]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST);
		gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB8, Image->sizeX, Image->sizeY, GL_RGB, GL_UNSIGNED_BYTE, Image->data);
	}
	else status=false;
	if (Image) {													// If Texture Exists
		if (Image->data) delete Image->data;						// If Texture Image Exists
		delete Image;
		Image=NULL;
	}	
	// Load The Tile-Bitmap For right wallbase-Texture
	if (Image=auxDIBImageLoad("Pic/carback.bmp")) {											
		glGenTextures(3, carback);									// Create Three Textures

		// Create Nearest Filtered Texture
		glBindTexture(GL_TEXTURE_2D, carback[0]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, Image->sizeX, Image->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, Image->data);
		//                             ========
		// Use GL_RGB8 Instead Of "3" In glTexImage2D. Also Defined By GL: GL_RGBA8 Etc.
		// NEW: Now Creating GL_RGBA8 Textures, Alpha Is 1.0f Where Not Specified By Format.

		// Create Linear Filtered Texture
		glBindTexture(GL_TEXTURE_2D, carback[1]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, Image->sizeX, Image->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, Image->data);

		// Create MipMapped Texture
		glBindTexture(GL_TEXTURE_2D, carback[2]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST);
		gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB8, Image->sizeX, Image->sizeY, GL_RGB, GL_UNSIGNED_BYTE, Image->data);
	}
	else status=false;
	if (Image) {													// If Texture Exists
		if (Image->data) delete Image->data;						// If Texture Image Exists
		delete Image;
		Image=NULL;
	}	

	// Load The Tile-Bitmap For right wallbase-Texture
	if (Image=auxDIBImageLoad("Pic/carside1.bmp")) {											
		glGenTextures(3, carside);									// Create Three Textures

		// Create Nearest Filtered Texture
		glBindTexture(GL_TEXTURE_2D, carside[0]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, Image->sizeX, Image->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, Image->data);
		//                             ========
		// Use GL_RGB8 Instead Of "3" In glTexImage2D. Also Defined By GL: GL_RGBA8 Etc.
		// NEW: Now Creating GL_RGBA8 Textures, Alpha Is 1.0f Where Not Specified By Format.

		// Create Linear Filtered Texture
		glBindTexture(GL_TEXTURE_2D, carside[1]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, Image->sizeX, Image->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, Image->data);

		// Create MipMapped Texture
		glBindTexture(GL_TEXTURE_2D, carside[2]);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST);
		gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB8, Image->sizeX, Image->sizeY, GL_RGB, GL_UNSIGNED_BYTE, Image->data);
	}
	else status=false;
	if (Image) {													// If Texture Exists
		if (Image->data) delete Image->data;						// If Texture Image Exists
		delete Image;
		Image=NULL;
	}	
	
	return status;											// Return The Status
}


GLvoid ReSizeGLScene(GLsizei width, GLsizei height)		// Resize And Initialize The GL Window
{
	if (height==0)										// Prevent A Divide By Zero By
	{
		height=1;										// Making Height Equal One
	}

	glViewport(0,0,width,height);						// Reset The Current Viewport

	glMatrixMode(GL_PROJECTION);						// Select The Projection Matrix
	glLoadIdentity();									// Reset The Projection Matrix to centre of screen

	// Calculate The Aspect Ratio Of The Window
	gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);

	glMatrixMode(GL_MODELVIEW);							// Select The Modelview Matrix
	glLoadIdentity();									// Reset The Modelview Matrix
}


int InitGL(GLvoid)										// All Setup For OpenGL Goes Here
{
	multitextureSupported=initMultitexture();
	if (!LoadGLTextures()) return false;				// Jump To Texture Loading Routine
	
	glEnable(GL_TEXTURE_2D);							// Enable Texture Mapping
	glShadeModel(GL_SMOOTH);							// Enable Smooth Shading
	glClearColor(0.0f, 0.0f, 0.0f, 0.5f);				// Black Background
	glClearDepth(1.0f);									// Depth Buffer Setup
	glEnable(GL_DEPTH_TEST);							// Enables Depth Testing
	glDepthFunc(GL_LEQUAL);								// The Type Of Depth Testing To Do
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);	// Really Nice Perspective Calculations

	LoadRawFile("Data/Terrain.raw", MAP_SIZE * MAP_SIZE, g_HeightMap);

	return TRUE;										// Initialization Went OK
}

int Height(BYTE *pHeightMap, int X, int Y)				// This Returns The Height From A Height Map Index
{
	int x = X % MAP_SIZE;								// Error Check Our x Value
	int y = Y % MAP_SIZE;								// Error Check Our y Value

	if(!pHeightMap) return 0;							// Make Sure Our Data Is Valid

	return pHeightMap[x + (y * MAP_SIZE)];				// Index Into Our Height Array And Return The Height
}

void SetTextureCoord(float x, float z)
{
   
    // Give OpenGL the current texture coordinate for our height map
    glTexCoord2f(   (float)x / (float)MAP_SIZE, 
                  - (float)z / (float)MAP_SIZE  );
}

														
void RenderHeightMap(BYTE pHeightMap[])
{
    int X = 0, Y = 0;                       // Create some variables to walk the array with.
    int x, y, z;                            // Create some variables for readability
    bool bSwitchSides = false;

    // Make sure our height data is valid
    if(!pHeightMap) return;     
    

    // Bind the terrain texture to our terrain
    //glBindTexture(GL_TEXTURE_2D, front[0]);
	glEnable(GL_TEXTURE_2D);
	 glBindTexture(GL_TEXTURE_2D, bottom[filter]);
		//SetVertexColor(pHeightMap, x, z);

    // We want to render triangle strips
    glBegin( GL_TRIANGLE_STRIP );           

    // Go through all of the rows of the height map
    for ( X = 0; X <= MAP_SIZE; X += STEP_SIZE )
    {
        // Chechk if we need to render the opposite way for this column
        if(bSwitchSides)
        {   
            // Render a column of the terrain, for this current X.
            // We start at MAP_SIZE and render down to 0.
            for ( Y = MAP_SIZE; Y >= 0; Y -= STEP_SIZE )
            {
                // Get the (X, Y, Z) value for the bottom left vertex       
                x = X;                          
                y = Height(pHeightMap, X, Y );  
                z = Y;                          

                // Set the current texture coordinate and render the vertex
                SetTextureCoord( (float)x, (float)z );
                glVertex3i(x, y, z);        

                // Get the (X, Y, Z) value for the bottom right vertex      
                x = X + STEP_SIZE; 
                y = Height(pHeightMap, X + STEP_SIZE, Y ); 
                z = Y;


                // Set the current texture coordinate and render the vertex
                SetTextureCoord( (float)x, (float)z );
                glVertex3i(x, y, z);            
            }
        }
        else
        {   
            // Render a column of the terrain, for this current X.
            // We start at 0 and render down up to MAP_SIZE.
            for ( Y = 0; Y <= MAP_SIZE; Y += STEP_SIZE )
            {
                // Get the (X, Y, Z) value for the bottom right vertex      
                x = X + STEP_SIZE; 
                y = Height(pHeightMap, X + STEP_SIZE, Y ); 
                z = Y;

                // Set the current texture coordinate and render the vertex
                SetTextureCoord( (float)x, (float)z );
                glVertex3i(x, y, z);

                // Get the (X, Y, Z) value for the bottom left vertex       
                x = X;                          
                y = Height(pHeightMap, X, Y );  
                z = Y;                          

                // Set the current texture coordinate and render the vertex
                SetTextureCoord( (float)x, (float)z );
                glVertex3i(x, y, z);        
            }
        }

        // Switch the direction the column renders to allow the fluid tri strips
        bSwitchSides = !bSwitchSides;
    }

    // Stop rendering triangle strips
    glEnd();
}


//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% START DRAWING%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void drawceiling() {

	glBegin(GL_QUADS);
		
			glNormal3f( 0.0f, -1.0f,0.0f);
			
			glTexCoord2f(1.0f, 0.0f);    glVertex3f( scenex2, 8.5,  scenez1);		// Bottom Right
			glTexCoord2f(1.0f, 1.0f);    glVertex3f( scenex2, 8.5,  scenez2);			// Upper Right
		    glTexCoord2f(0.0f, 1.0f);    glVertex3f( scenex1, 8.5, scenez2);			// Upper Left
			glTexCoord2f(0.0f, 0.0f);	 glVertex3f( scenex1, 8.5, scenez1);			// Lower Left
		
	 glEnd();									// Finished Drawing The Ceiling
}

void drawfloor() {

	glBegin(GL_QUADS);
		for (z=scenez1;z<scenez2;z+=b){
			glNormal3f( 0.0f, 1.0f,0.0f);
			
			for(x=scenex1;x<scenex2;x+=a){
			glTexCoord2f(1.0f, 0.0f);  	glVertex3f( x+a, -9.5, z+b);	// Texture and Quad Bottom Right
			glTexCoord2f(1.0f, 1.0f);   glVertex3f( x+a, -9.5, z);		// Upper Right
		    glTexCoord2f(0.0f, 1.0f);   glVertex3f( x, -9.5, z);		// Texture Upper Left
			glTexCoord2f(0.0f, 0.0f);   glVertex3f( x, -9.5, z+b);		// Texture Lower Left
			}
	}
		
	glEnd();
}


void drawfrontwall()
{
	glBegin(GL_QUADS);						// Drawing Using Quads
			for(x=scenex1;x<scenex2;x+=d){
			glNormal3f( 0.0f, 0.0f,1.0f);		
			glTexCoord2f(1.0f, 1.0f);		glVertex3f( x+d, 8.5f, fwallz);		// Upper Right
			glTexCoord2f(1.0f, 0.0f);		glVertex3f( x+d,  -9.5f, fwallz);		// Upper Left
			glTexCoord2f(0.0f, 0.0f);       glVertex3f( x,  -9.5f, fwallz);		// Bottom Right
			glTexCoord2f(0.0f, 1.0f);       glVertex3f( x, 8.5f, fwallz);		// Bottom Left
			}
	 glEnd();	
}

void drawfinishing()
{
	glBegin(GL_QUADS);						// Drawing Using Quads
		for(x=-8.0f;x<8.0f;x+=4.0f){
			glNormal3f( 0.0f, 0.0f,1.0f);		
			glTexCoord2f(1.0f, 1.0f);		glVertex3f( x+4.0f, 2.7f, -55.0f);		// Upper Right
			glTexCoord2f(1.0f, 0.0f);		glVertex3f( x+4.0f, 0.5f, -55.0f);		// Upper Left
			glTexCoord2f(0.0f, 0.0f);       glVertex3f( x,  0.5f, -55.0f);		// Bottom Right
			glTexCoord2f(0.0f, 1.0f);       glVertex3f( x, 2.7f, -55.0f);		// Bottom Left
		}
	 glEnd();	
}


void drawleftwall()
{
	  glBegin(GL_QUADS);	  // Drawing Using Quads
	  for (z=scenez1;z<scenez2;z+=j){
			glNormal3f( 1.0f, 0.0f, 0.0f);
				glTexCoord2f(1.0f, 0.0f);				glVertex3f( lwallx, -9.5, z+j);
				glTexCoord2f(1.0f, 1.0f);              	glVertex3f( lwallx, 8.5,  z+j);		
				glTexCoord2f(0.0f, 1.0f);              	glVertex3f( lwallx, 8.5,  z);				
				glTexCoord2f(0.0f, 0.0f);              	glVertex3f( lwallx, -9.5, z);	
	  }			
	 glEnd(); 
}

void drawrightwall()
{
	glBegin(GL_QUADS);// Drawing Using Quads
	 for (z=scenez1;z<scenez2;z+=j){
			glNormal3f( -1.0f, 0.0f, 0.0f);			
			glTexCoord2f(1.0f, 0.0f); 	glVertex3f( rwallx, -9.5, z+j);				// Bottom Right
			glTexCoord2f(1.0f, 1.0f);   glVertex3f( rwallx, 8.5, z+j);				// Upper Right
		    glTexCoord2f(0.0f, 1.0f);   glVertex3f( rwallx, 8.5, z);				// Upper Left
			glTexCoord2f(0.0f, 0.0f);   glVertex3f( rwallx, -9.5, z);					 // Lower Left
	 }
	 glEnd();				
}

// Draw bounding box.
void DrawGoKart()
{
	
	//glBindTexture(GL_TEXTURE_2D, NULL);
	
		glEnable(GL_TEXTURE_2D);						// Enable Texture Mapping 		
		glBindTexture(GL_TEXTURE_2D, carback[filter]);
	glBegin(GL_QUADS);
		// Front Face facing front wall	
		glNormal3f( 0.0f, 0.0f, -1.0f);
		glTexCoord2f(0.0f, 0.0f); glVertex3f( Kartx1, -1.5f,  Kartz2);
		glTexCoord2f(1.0f, 0.0f); glVertex3f( Kartx2, -1.5f,  Kartz2);
		glTexCoord2f(1.0f, 1.0f); glVertex3f( Kartx2, -1.1f,	Kartz2);
		glTexCoord2f(0.0f, 1.0f); glVertex3f( Kartx1, -1.1f,  Kartz2);
		// Back Face  facing the camera
		glNormal3f( 0.0f, 0.0f,1.0f);
		glTexCoord2f(1.0f, 0.0f); glVertex3f( Kartx2, -1.5f, Kartz1);
		glTexCoord2f(1.0f, 1.0f); glVertex3f( Kartx2, -1.1f, Kartz1);
		glTexCoord2f(0.0f, 1.0f); glVertex3f( Kartx1, -1.1f, Kartz1);
		glTexCoord2f(0.0f, 0.0f); glVertex3f( Kartx1, -1.5f, Kartz1);
	glEnd();
	
		glDisable(GL_TEXTURE_2D);						// Enable Texture Mapping 		
		
		glEnable(GL_TEXTURE_2D);						// Enable Texture Mapping 		
		glBindTexture(GL_TEXTURE_2D, bottom[filter]);
	
	glBegin(GL_QUADS);
		// Top Face
		glNormal3f( 0.0f, 1.0f, 0.0f);
		glTexCoord2f(0.0f, 1.0f); glVertex3f(Kartx1, -1.1f, Kartz2);
		glTexCoord2f(0.0f, 0.0f); glVertex3f(Kartx1, -1.1f, Kartz1);
		glTexCoord2f(1.0f, 0.0f); glVertex3f(Kartx2, -1.1f, Kartz1);
		glTexCoord2f(1.0f, 1.0f); glVertex3f(Kartx2, -1.1f, Kartz2);
		// Bottom Face
		glNormal3f( 0.0f,-1.0f, 0.0f);
		glTexCoord2f(1.0f, 1.0f); glVertex3f(Kartx2, -1.5f, Kartz2);
		glTexCoord2f(0.0f, 1.0f); glVertex3f(Kartx1,-1.5f,  Kartz2);
		glTexCoord2f(0.0f, 0.0f); glVertex3f(Kartx1, -1.5f, Kartz1);
		glTexCoord2f(1.0f, 0.0f); glVertex3f(Kartx2, -1.5f, Kartz1);
	glEnd();	
		
		glDisable(GL_TEXTURE_2D);						// Enable Texture Mapping 		
		
		glEnable(GL_TEXTURE_2D);						// Enable Texture Mapping 		
		glBindTexture(GL_TEXTURE_2D, point[filter]);
		
	glBegin(GL_QUADS);
		// Right face
		glNormal3f( 1.0f, 0.0f, 0.0f);
		glTexCoord2f(1.0f, 0.0f); glVertex3f(Kartx2, -1.5f, Kartz2);
		glTexCoord2f(1.0f, 1.0f); glVertex3f(Kartx2, -1.1f, Kartz2);
		glTexCoord2f(0.0f, 1.0f); glVertex3f(Kartx2, -1.1f, Kartz1);
		glTexCoord2f(0.0f, 0.0f); glVertex3f(Kartx2, -1.5f, Kartz1);
	glEnd();

		glDisable(GL_TEXTURE_2D);						// Enable Texture Mapping 		
		
		glEnable(GL_TEXTURE_2D);						// Enable Texture Mapping 		
		glBindTexture(GL_TEXTURE_2D, carside[filter]);
		// Left Face
	glBegin(GL_QUADS);
		glNormal3f(-1.0f, 0.0f, 0.0f);
		glTexCoord2f(0.0f, 0.0f); glVertex3f(Kartx1, -1.5f, Kartz2);
		glTexCoord2f(1.0f, 0.0f); glVertex3f(Kartx1, -1.5f, Kartz1);
		glTexCoord2f(1.0f, 1.0f); glVertex3f(Kartx1, -1.1f, Kartz1);
		glTexCoord2f(0.0f, 1.0f); glVertex3f(Kartx1, -1.1f, Kartz2);	
	
	glEnd();
		
		glDisable(GL_TEXTURE_2D);						// Enable Texture Mapping 		

}

void drawscene()
{

	GLfloat i = 0.1f;
	GLfloat j = 2.0f;
	GLfloat z=  -10;
	GLfloat y=  -1;
	GLfloat x=-1;

	
	glPushMatrix();
	glLoadIdentity();	
	glRotatef(angle, 0.0, 1.0, 0.0);
	glTranslatef(xmove, 0.0, forward);		// moving 0 unit into X, 0 unit into Y, forward(ie 0) deep into the screen.

	glClearColor(0.0,0.0,0.0,0.0);
	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
	glClearDepth(1.0);

//*******************************FLOOR*****************************************************
	
		glEnable(GL_TEXTURE_2D);						// Enable Texture Mapping 		
		glBindTexture(GL_TEXTURE_2D, bottom[filter]);
		drawfloor();									// Finished Drawing The Floor
		glDisable(GL_TEXTURE_2D);	

//*******************************FRONT WALL************************************************

	 glEnable(GL_TEXTURE_2D);						// Enable Texture Mapping ( NEW )
	 glBindTexture(GL_TEXTURE_2D, right[filter]);
	 drawfrontwall();	 							// Finished Drawing The Front Wall
	 glDisable(GL_TEXTURE_2D);						// Enable Texture Mapping ( NEW )	 	

//*******************************LEFT WALL*************************************************

	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, right[filter]);
	drawleftwall();	 							// Finished Drawing The Front Wall
	glDisable(GL_TEXTURE_2D);						// Enable Texture Mapping ( NEW )	 	

//*******************************BOTTOM RIGHT WALL******************************************
	
	 glEnable(GL_TEXTURE_2D);	
	 glBindTexture(GL_TEXTURE_2D, front[filter]);
	 drawrightwall();
	 glDisable(GL_TEXTURE_2D);

//*******************************CEILING****************************************************
		glEnable(GL_TEXTURE_2D);	
		glBindTexture(GL_TEXTURE_2D, top[filter]);
		drawceiling();
		glDisable(GL_TEXTURE_2D);						// Enable Texture Mapping ( NEW )	 	

//*****************************GO KART******************************************************
		glRotatef(Kartangle, 0.0, 1.0, 0.0);
		DrawGoKart();	
		glDisable(GL_TEXTURE_2D);	
		
		glEnable(GL_TEXTURE_2D);	
		glBindTexture(GL_TEXTURE_2D, finishing[filter]);
		drawfinishing();
		glDisable(GL_TEXTURE_2D);						// Enable Texture Mapping ( NEW )	 	
		
}
//*************************************END OF DRAWING!!!****************************************
//**********************************************************************************************

void crosspatch(GLfloat xloc1,GLfloat xloc2, GLfloat zloc1,GLfloat zloc2)
{
	if (xloc1<= -1.0f)	// collide with left wall
	{
		totalcollision+=2.0;
		wallhit+=1.0;
	}
	if (xloc2>= 1.1f)	// collide with right wall
	{
		totalcollision+=2.0;
		wallhit+=1.0;
	}
	if ((xloc2>=0.0 && zloc1<=-4 && zloc1>=-5) || (xloc2>=0.0 && zloc2<=-4 && zloc2>=-5))	//collide with 1st right patch
	{
		totalcollision+=3.0;
		patchhit+=1.0;
	}
	if ((xloc2>=0.0 && zloc1<=-8 && zloc1>=-9) || (xloc2>=0.0 && zloc2<=-8 && zloc2>=-9))	//collide with 2nd right patch
	{
		totalcollision+=3.0;
		patchhit+=1.0;
	}
	if ((xloc1<=-0.2 && zloc1<=-2 && zloc1>=-3) || (xloc1<=-0.2 && zloc2<=-2 && zloc2>=-3))	//collide with 1st left patch
	{
		totalcollision+=3.0;
		patchhit+=1.0;
	}
	if ((xloc1<=-0.2 && zloc1<=-6 && zloc1>=-7) || (xloc1<=-0.2 && zloc2<=-6 && zloc2>=-7))	//collide with 2nd left patch
	{
		totalcollision+=3.0;
		patchhit+=1.0;
	}
}



bool DrawGLScene(GLvoid)									// Here's Where We Do All The Drawing
{
		drawscene();
		gluLookAt(170, 70, 164,  164, 65, 160,  0, 1, 0);	// This Determines Where The Camera's Position And View Is
		//gluLookAt(173, 70, 164,  166, 65, 160,  0, 1, 0);	// This Determines Where The Camera's Position And View Is
		glScalef(scaleValue, scaleValue * HEIGHT_RATIO, scaleValue);

		glRotatef(angle1, 0.0, 1.0, 0.0);
		//glTranslatef(xmove1, -60.0, zmove);		// moving 0 unit into X, 0 unit into Y, forward(ie 0) deep into the screen.
		//glTranslatef(1650.0, 1025.0, zmove);		// moving 0 unit into X, 0 unit into Y, forward(ie 0) deep into the screen.
		glTranslatef(xterrain, yterrain, zmove);		// moving 0 unit into X, 0 unit into Y, forward(ie 0) deep into the screen.
		//glTranslatef(800.0, 490.0, zmove);		// moving 0 unit into X, 0 unit into Y, forward(ie 0) deep into the screen.
//		glRotatef(angle1, 1.0, 0.0, 0.0);
		RenderHeightMap(g_HeightMap);						// Render The Height Map
	
		return TRUE;										// Keep Going
}



GLvoid KillGLWindow(GLvoid)								// Properly Kill The Window
{

//	gluDeleteQuadric(quad);						// Delete The Quadratic To Free System Resources

	if (fullscreen)										// Are We In Fullscreen Mode?
	{
		ChangeDisplaySettings(NULL,0);					// If So Switch Back To The Desktop
		ShowCursor(TRUE);								// Show Mouse Pointer
	}

	if (hRC)											// Do We Have A Rendering Context?
	{
		if (!wglMakeCurrent(NULL,NULL))					// Are We Able To Release The DC And RC Contexts?
		{
			MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}

		if (!wglDeleteContext(hRC))						// Are We Able To Delete The RC?
		{
			MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}
		hRC=NULL;										// Set RC To NULL
	}

	if (hDC && !ReleaseDC(hWnd,hDC))					// Are We Able To Release The DC
	{
		MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hDC=NULL;										// Set DC To NULL
	}

	if (hWnd && !DestroyWindow(hWnd))					// Are We Able To Destroy The Window?
	{
		MessageBox(NULL,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hWnd=NULL;										// Set hWnd To NULL
	}
}

/*	This Code Creates Our OpenGL Window.  Parameters Are:					*
 *	title			- Title To Appear At The Top Of The Window				*
 *	width			- Width Of The GL Window Or Fullscreen Mode				*
 *	height			- Height Of The GL Window Or Fullscreen Mode			*
 *	bits			- Number Of Bits To Use For Color (8/16/24/32)			*
 *	fullscreenflag	- Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE)	*/
 
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)
{
	GLuint		PixelFormat;			// Holds The Results After Searching For A Match
	WNDCLASS	wc;						// Windows Class Structure
	DWORD		dwExStyle;				// Window Extended Style
	DWORD		dwStyle;				// Window Style
	RECT		WindowRect;				// Grabs Rectangle Upper Left / Lower Right Values
	WindowRect.left=(long)0;			// Set Left Value To 0
	WindowRect.right=(long)width;		// Set Right Value To Requested Width
	WindowRect.top=(long)0;				// Set Top Value To 0
	WindowRect.bottom=(long)height;		// Set Bottom Value To Requested Height

	fullscreen=fullscreenflag;			// Set The Global Fullscreen Flag

	hInstance			= GetModuleHandle(NULL);				// Grab An Instance For Our Window
	wc.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;	// Redraw On Size, And Own DC For Window.
	wc.lpfnWndProc		= (WNDPROC) WndProc;					// WndProc Handles Messages
	wc.cbClsExtra		= 0;									// No Extra Window Data
	wc.cbWndExtra		= 0;									// No Extra Window Data
	wc.hInstance		= hInstance;							// Set The Instance
	wc.hIcon			= LoadIcon(NULL, IDI_WINLOGO);			// Load The Default Icon
	wc.hCursor			= LoadCursor(NULL, IDC_ARROW);			// Load The Arrow Pointer
	wc.hbrBackground	= NULL;									// No Background Required For GL
	wc.lpszMenuName		= NULL;									// We Don't Want A Menu
	wc.lpszClassName	= "OpenGL";								// Set The Class Name

	if (!RegisterClass(&wc))									// Attempt To Register The Window Class
	{
		MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;											// Return FALSE
	}
	
	if (fullscreen)												// Attempt Fullscreen Mode?
	{
		DEVMODE dmScreenSettings;								// Device Mode
		memset(&dmScreenSettings,0,sizeof(dmScreenSettings));	// Makes Sure Memory's Cleared
		dmScreenSettings.dmSize=sizeof(dmScreenSettings);		// Size Of The Devmode Structure
		dmScreenSettings.dmPelsWidth	= width;				// Selected Screen Width
		dmScreenSettings.dmPelsHeight	= height;				// Selected Screen Height
		dmScreenSettings.dmBitsPerPel	= bits;					// Selected Bits Per Pixel
		dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

		// Try To Set Selected Mode And Get Results.  NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
		if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
		{
			// If The Mode Fails, Offer Two Options.  Quit Or Use Windowed Mode.
			if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","NeHe GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
			{
				fullscreen=FALSE;		// Windowed Mode Selected.  Fullscreen = FALSE
			}
			else
			{
				// Pop Up A Message Box Letting User Know The Program Is Closing.
				MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP);
				return FALSE;									// Return FALSE
			}
		}
	}

	if (fullscreen)												// Are We Still In Fullscreen Mode?
	{
		dwExStyle=WS_EX_APPWINDOW;								// Window Extended Style
		dwStyle=WS_POPUP;										// Windows Style
		ShowCursor(FALSE);										// Hide Mouse Pointer
	}
	else
	{
		dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;			// Window Extended Style
		dwStyle=WS_OVERLAPPEDWINDOW;							// Windows Style
	}

	AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);		// Adjust Window To True Requested Size

	// Create The Window
	if (!(hWnd=CreateWindowEx(	dwExStyle,							// Extended Style For The Window
								"OpenGL",							// Class Name
								title,								// Window Title
								dwStyle |							// Defined Window Style
								WS_CLIPSIBLINGS |					// Required Window Style
								WS_CLIPCHILDREN,					// Required Window Style
								0, 0,								// Window Position
								WindowRect.right-WindowRect.left,	// Calculate Window Width
								WindowRect.bottom-WindowRect.top,	// Calculate Window Height
								NULL,								// No Parent Window
								NULL,								// No Menu
								hInstance,							// Instance
								NULL)))								// Dont Pass Anything To WM_CREATE
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	static	PIXELFORMATDESCRIPTOR pfd=				// pfd Tells Windows How We Want Things To Be
	{
		sizeof(PIXELFORMATDESCRIPTOR),				// Size Of This Pixel Format Descriptor
		1,											// Version Number
		PFD_DRAW_TO_WINDOW |						// Format Must Support Window
		PFD_SUPPORT_OPENGL |						// Format Must Support OpenGL
		PFD_DOUBLEBUFFER,							// Must Support Double Buffering
		PFD_TYPE_RGBA,								// Request An RGBA Format
		bits,										// Select Our Color Depth
		0, 0, 0, 0, 0, 0,							// Color Bits Ignored
		0,											// No Alpha Buffer
		0,											// Shift Bit Ignored
		0,											// No Accumulation Buffer
		0, 0, 0, 0,									// Accumulation Bits Ignored
		16,											// 16Bit Z-Buffer (Depth Buffer)  
		0,											// No Stencil Buffer
		0,											// No Auxiliary Buffer
		PFD_MAIN_PLANE,								// Main Drawing Layer
		0,											// Reserved
		0, 0, 0										// Layer Masks Ignored
	};
	
	if (!(hDC=GetDC(hWnd)))							// Did We Get A Device Context?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd)))	// Did Windows Find A Matching Pixel Format?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if(!SetPixelFormat(hDC,PixelFormat,&pfd))		// Are We Able To Set The Pixel Format?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if (!(hRC=wglCreateContext(hDC)))				// Are We Able To Get A Rendering Context?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if(!wglMakeCurrent(hDC,hRC))					// Try To Activate The Rendering Context
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	ShowWindow(hWnd,SW_SHOW);						// Show The Window
	SetForegroundWindow(hWnd);						// Slightly Higher Priority
	SetFocus(hWnd);									// Sets Keyboard Focus To The Window
	ReSizeGLScene(width, height);					// Set Up Our Perspective GL Screen

	if (!InitGL())									// Initialize Our Newly Created GL Window
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	return TRUE;									// Success
}

LRESULT CALLBACK WndProc(	HWND	hWnd,			// Handle For This Window
							UINT	uMsg,			// Message For This Window
							WPARAM	wParam,			// Additional Message Information
							LPARAM	lParam)			// Additional Message Information
{
	switch (uMsg)									// Check For Windows Messages
	{
		case WM_ACTIVATE:							// Watch For Window Activate Message
		{
			if (!HIWORD(wParam))					// Check Minimization State
			{
				active=TRUE;						// Program Is Active
			}
			else
			{
				active=FALSE;						// Program Is No Longer Active
			}

			return 0;								// Return To The Message Loop
		}

		case WM_SYSCOMMAND:
		{
			switch (wParam)
			{
				case SC_SCREENSAVE:
				case SC_MONITORPOWER:
					return 0;
			}
			break;
		}

		case WM_CLOSE:								// Did We Receive A Close Message?
		{
			PostQuitMessage(0);						// Send A Quit Message
			return 0;								// Jump Back
		}

		case WM_KEYDOWN:							// Is A Key Being Held Down?
		{
			keys[wParam] = TRUE;					// If So, Mark It As TRUE
			return 0;								// Jump Back
		}

		case WM_KEYUP:								// Has A Key Been Released?
		{
			keys[wParam] = FALSE;					// If So, Mark It As FALSE
			return 0;								// Jump Back
		}

		case WM_SIZE:								// Resize The OpenGL Window
		{
			ReSizeGLScene(LOWORD(lParam),HIWORD(lParam));  // LoWord=Width, HiWord=Height
			return 0;								// Jump Back
		}
	
	}

	// Pass All Unhandled Messages To DefWindowProc
	return DefWindowProc(hWnd,uMsg,wParam,lParam);
}

int WINAPI WinMain(	HINSTANCE	hInstance,			// Instance
					HINSTANCE	hPrevInstance,		// Previous Instance
					LPSTR		lpCmdLine,			// Command Line Parameters
					int			nCmdShow)			// Window Show State
{
	MSG		msg;									// Windows Message Structure
	BOOL	done=FALSE;								// Bool Variable To Exit Loop

	// Ask The User Which Screen Mode They Prefer
	if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)
	{
		fullscreen=FALSE;							// Windowed Mode
	}

	// Create Our OpenGL Window
	if (!CreateGLWindow("Assignment 5",640,480,16,fullscreen))
	{
		return 0;									// Quit If Window Was Not Created
	}

	while(!done)									// Loop That Runs While done=FALSE
	{
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	// Is There A Message Waiting?
		{
			if (msg.message==WM_QUIT)				// Have We Received A Quit Message?
			{
				done=TRUE;							// If So done=TRUE
			}
			else									// If Not, Deal With Window Messages
			{
				TranslateMessage(&msg);				// Translate The Message
				DispatchMessage(&msg);				// Dispatch The Message
			}
		}

		
		else										// If There Are No Messages
		{
			// Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()
			if ((active && !DrawGLScene()) || keys[VK_ESCAPE])	// Active?  Was There A Quit Received?
			{
				done=TRUE;							// ESC or DrawGLScene Signalled A Quit
			}
			else									// Not Time To Quit, Update Screen
			{
				SwapBuffers(hDC);					// Swap Buffers (Double Buffering)

			if (keys[VK_UP])
				{
					if (check<5)
					{
						forward+=0.2f; // comment off to stop scene moving
						Kartz2-=0.2f;
						Kartz1-=0.2f;						
						check+=1;
					}
				
				
				else if (check=5 )
					{
				
						scenez1-=1.0f;
						scenez2-=1.0f;
						fwallz-=1.0f;
						check=0;
						//xterrain-=10.0f;
						zmove-=5.0f;
						//yterrain-=5.0f;
						yterrain-=8.0f;
						xterrain-=15.f;
						//angle1-=0.2f;
					}				

				
				
					if ((Kartz2 <= -60.0) && (Kartx1 > -8.0f) && (Kartx2 < 8.0f) && showmessage)
					{
						 MessageBox(NULL,"You Win! You are the first to reach the finishing line!!!" ,"Information",MB_OK|MB_ICONEXCLAMATION);						 
						 showmessage=!showmessage;
						 KillGLWindow();									// Kill The Window
						return (msg.wParam);							// Exit The Program
					}
					
				}
				if (keys[VK_DOWN])
				{

					if (check1<5)
					{
						forward-=0.2f;	//comment off to stop scene moving
						Kartz2+=0.2f;
						Kartz1+=0.2f;
						check1+=1;
					}
				//	else if ((check1=5) && (Kartz1>=-3.0))
					else if (check1=5)
					{
						scenez1-=0.2f;
						scenez2+=1.0f;
						fwallz-=0.2f;
						check1=0;
					}

				}
				if (keys[VK_RIGHT])
				{
				
					if (check2<5)
					{
						xmove-=0.2f;
					//	angle+=2.5f;
						Kartx1+=0.2f;
						Kartx2+=0.2f;
						check2+=1;
					}

					else if (check2=5)
					{
					//	xmove-=0.2f;
						scenex1+=1.0f;
						scenex2+=1.0f;
						lwallx+=1.0f;
						rwallx+=1.0f;
						check2=0;
					}

				}
				if (keys[VK_LEFT])
				{

					if (check3<5)
					{
						xmove+=0.2f;
						Kartx1-=0.2f;
						Kartx2-=0.2f;
						check3+=1;
					}
					else if (check3=5)
					{
						//xmove-=0.2f;
						//xterrain-=10.0f;
						zmove+=2.0f;
						scenex1-=1.0f;
						scenex2-=1.0f;
						lwallx-=1.0f;
						rwallx-=1.0f;
						check3=0;
					}
				
				}

				if (keys[VK_F1])						// Is F1 Being Pressed?
				{
					keys[VK_F1]=FALSE;					// If So Make Key FALSE
					KillGLWindow();						// Kill Our Current Window
					fullscreen=!fullscreen;				// Toggle Fullscreen / Windowed Mode
					// Recreate Our OpenGL Window
					if (!CreateGLWindow("NeHe's Textures, Lighting & Keyboard Tutorial",640,480,16,fullscreen))
					{
						return 0;						// Quit If Window Was Not Created
					}
				}

				if (keys['S']) 
				{
					keys[VK_UP]=FALSE;
				}
			}
		}
	}

	// Shutdown
	KillGLWindow();									// Kill The Window
	return (msg.wParam);							// Exit The Program
}



