#include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <math.h>
#include "globals.h"
#include "system.h"
#include "text.h"
#include "keys.h"
#include "bouncer.h"

void init_Bounce ()
{
	sphere->rX = sphere->rY = sphere->rZ = 0.0f;
	GLfloat fogCol[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
	glClearColor (0.0f, 0.0f, 0.0f, 1.0f);
	glFogfv (GL_FOG_COLOR, fogCol);
	cam.directional = false;
	cam.pos[0] = 0;
	cam.pos[1] = 0;
	cam.pos[2] = 100;
	cam.tgt[0] = 0;
	cam.tgt[1] = 0;
	cam.tgt[2] = 0;
	fov = 100;
	cube->textured = true;
	cube->texture = TID_ATG[2];
	for (int i = 0; i < 8; i++)
	{
		b[i] = new Bouncer (i*0.4f+10.0f, sin(i)*5.0f + 12.0f, cos(i)*4.0f + 10.0f);
		b[i]->start ();
	}
}

void drawFloor ()
{
	glPushAttrib (GL_ALL_ATTRIB_BITS);
	glDisable (GL_BLEND);
	glDisable (GL_LIGHTING);
	glDisable (GL_TEXTURE_GEN_S);
	glDisable (GL_TEXTURE_GEN_T);
	glBindTexture (GL_TEXTURE_2D, TID_ATG[3]);

	int size = 80;
	int xmax = 20;
	int zmax = 10;
	int xoffset = (int)(size*xmax*0.5);
	int zoffset = (int)(size*zmax*0.5);
 
	glColor4f (1.0f, 1.0f, 1.0f, 1.0f);

	for (int x = 0; x < xmax; x++)
	{
		for (int z = -zmax; z < zmax; z++)
		{
			glBegin (GL_QUADS);
				glTexCoord2f ( 1.0f, 0.0f);
				glVertex3f ( (float)(x*size + size - xoffset),  0.0f, (float)(-(z*size + zoffset)));

				glTexCoord2f ( 1.0f, 1.0f);
				glVertex3f ( (float)(x*size+size - xoffset),  0.0f, (float)(-(z*size+size + zoffset)));
				
				glTexCoord2f ( 0.0f, 1.0f);
				glVertex3f ( (float)(x*size - xoffset),  0.0f, (float)(-(z*size+size + zoffset)));

				glTexCoord2f ( 0.0f, 0.0f);
				glVertex3f ( (float)(x*size - xoffset),  0.0f, (float)(-(z*size + zoffset)));
			glEnd ();
		}
	}

	glPopAttrib ();
}

void part_Bouncepart ()
{
	static bool first = true;

	if (first)
	{
		init_Bounce ();
		first = false;
	}
	
	cam.pos[0] = (GLfloat)(cos(time)*(sin(time*0.5)*4+5));
	cam.pos[1] = (GLfloat)(cos(time*0.6+1)*4+7);
	cam.pos[2] = (GLfloat)(sin(time)*(sin(time*0.5)*4+5));

	cam.tgt[0] = 0;
	cam.tgt[1] = 5;
	cam.tgt[2] = 0;

	SetProjection ();
	glEnable (GL_TEXTURE_2D);
	glDisable (GL_TEXTURE_GEN_S);
	glDisable (GL_TEXTURE_GEN_T);
	glDisable (GL_BLEND);
	glEnable (GL_LIGHTING);
	glFogf (GL_FOG_START, 20.0);
	glFogf (GL_FOG_END, 100.0);
	glEnable (GL_FOG);
	glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);

	glDisable (GL_LIGHTING);
//	glEnable (GL_TEXTURE_GEN_S);
//	glEnable (GL_TEXTURE_GEN_T);

	glFrontFace (GL_CW);
	cube->pY = 10;
	cube->render ();

	glDisable (GL_TEXTURE_GEN_S);
	glDisable (GL_TEXTURE_GEN_T);
	glFrontFace (GL_CCW);
	glEnable (GL_LIGHTING);

	sphere->textured = true;

	sphere->rY = 0;
	sphere->sX = sphere->sY = sphere->sZ = 0.01f;

	for (int i = 0; i < 8; i++)
	{	
		b[i]->move ();
		sphere->sX = b[i]->sX;
		sphere->sY = b[i]->sY;
		sphere->sZ = b[i]->sZ;
		sphere->pX = b[i]->currentX;
		sphere->pY = b[i]->currentY;
		sphere->pZ = b[i]->currentZ;
		sphere->render ();
	}
}
