#include "planets.h"
//#include "../glm/glm.hpp"

#define SLICES 100
#define STACKS 100

GLuint fb, fbTex, depth_rb;

#define OFF_SCREEN_RENDER_RATIO 1

void planets::initFbo()
{
	msys_debugPrintf("PLANETS: Init Fbo\n");
	// generate namespace for the frame buffer, colorbuffer and depthbuffer
	oglGenFramebuffersEXT(1, &fb);
	glGenTextures(1, &fbTex);
	oglGenRenderbuffersEXT(1, &depth_rb);

	//switch to our fbo so we can bind stuff to it
	oglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb);


	//create the colorbuffer texture and attach it to the frame buffer
	glBindTexture(GL_TEXTURE_2D, fbTex);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, globalScreenInfo.fboWidth, globalScreenInfo.fboHeight, 0, GL_BGRA, GL_INT, NULL);

	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); // Linear Filtering
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering
	// OpenGL will then generate all the required mipmap data for you so that your texture is ready to be used.
	oglGenerateMipmapEXT(GL_TEXTURE_2D); 

	oglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,	GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, fbTex, 0);

	// create a render buffer as our depth buffer and attach it
	oglBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depth_rb);
	oglRenderbufferStorageEXT(GL_RENDERBUFFER_EXT,
		GL_DEPTH_COMPONENT16,globalScreenInfo.fboWidth, globalScreenInfo.fboHeight);

	oglFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT,
		GL_DEPTH_ATTACHMENT_EXT,
		GL_RENDERBUFFER_EXT, depth_rb);

	// Go back to regular frame buffer rendering
	oglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);

	GLenum status = oglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
	if(status != GL_FRAMEBUFFER_COMPLETE_EXT)
	{
		msys_debugPrintf("PLANETS: INIT FBO FAILED...\n");
	}
}

GLint shaderGodRays;
float uniformLightX;
float uniformLightY;
float uniformExposure;
float uniformDecay;
float uniformDensity;
float uniformWeight;

unsigned int glsl_loc_light;
unsigned int glsl_loc_exposure;
unsigned int glsl_loc_decay;
unsigned int glsl_loc_density;
unsigned int glsl_loc_weight;
unsigned int glsl_loc_myTexture;

int glhProjectf(float objx, float objy, float objz, double *modelview, double *projection, int *viewport, double *windowCoordinate)
{
	//Transformation vectors
	double fTempo[8];
	//Modelview transform
	fTempo[0]=modelview[0]*objx+modelview[4]*objy+modelview[8]*objz+modelview[12];  //w is always 1
	fTempo[1]=modelview[1]*objx+modelview[5]*objy+modelview[9]*objz+modelview[13];
	fTempo[2]=modelview[2]*objx+modelview[6]*objy+modelview[10]*objz+modelview[14];
	fTempo[3]=modelview[3]*objx+modelview[7]*objy+modelview[11]*objz+modelview[15];
	//Projection transform, the final row of projection matrix is always [0 0 -1 0]
	//so we optimize for that.
	fTempo[4]=projection[0]*fTempo[0]+projection[4]*fTempo[1]+projection[8]*fTempo[2]+projection[12]*fTempo[3];
	fTempo[5]=projection[1]*fTempo[0]+projection[5]*fTempo[1]+projection[9]*fTempo[2]+projection[13]*fTempo[3];
	fTempo[6]=projection[2]*fTempo[0]+projection[6]*fTempo[1]+projection[10]*fTempo[2]+projection[14]*fTempo[3];
	fTempo[7]=-fTempo[2];
	//The result normalizes between -1 and 1
	if(fTempo[7]==0.0)	//The w value
		return 0;
	fTempo[7]=1.0/fTempo[7];
	//Perspective division
	fTempo[4]*=fTempo[7];
	fTempo[5]*=fTempo[7];
	fTempo[6]*=fTempo[7];
	//Window coordinates
	//Map x, y to range 0-1
	windowCoordinate[0]=(fTempo[4]*0.5+0.5)*viewport[2]+viewport[0];
	windowCoordinate[1]=(fTempo[5]*0.5+0.5)*viewport[3]+viewport[1];
	//This is only correct when glDepthRange(0.0, 1.0)
	windowCoordinate[2]=(1.0+fTempo[6])*0.5;	//Between 0 and 1
	return 1;
}

void planets::getLightScreenCoor(Light* light)
{
	double modelView[16];
    double projection[16];
    GLint viewport[4];
    double depthRange[2];

	glGetDoublev(GL_MODELVIEW_MATRIX, modelView);
    glGetDoublev(GL_PROJECTION_MATRIX, projection);
    glGetIntegerv(GL_VIEWPORT, viewport);
    glGetDoublev(GL_DEPTH_RANGE, depthRange);

	double winpos[3];

	glhProjectf(	light->lightPosition[0],
				light->lightPosition[1],
				light->lightPosition[2],
				&modelView[0],
				&projection[0],
				&viewport[0],
				&winpos[0]);
	
	
	uniformLightX = (float)winpos[0]/((float)globalScreenInfo.fboWidth);
	uniformLightY = (float)winpos[1]/((float)globalScreenInfo.fboHeight);

	//printf("Light position zz xo=%f, yo=%f, x=%f, y=%f\n",winX,winY,uniformLightX,uniformLightY);

	/*

		 // Get the matrices and viewport
    double modelView[16];
    double projection[16];
    double viewport[4];
    double depthRange[2];

    glGetDoublev(GL_MODELVIEW_MATRIX, modelView);
    glGetDoublev(GL_PROJECTION_MATRIX, projection);
    glGetDoublev(GL_VIEWPORT, viewport);
    glGetDoublev(GL_DEPTH_RANGE, depthRange);

    // Compose the matrices into a single row-major transformation
    Vector4 T[4];
    int r, c, i;
    for (r = 0; r < 4; ++r) {
        for (c = 0; c < 4; ++c) {
            T[r][c] = 0;
            for (i = 0; i < 4; ++i) {
                // OpenGL matrices are column major
                T[r][c] += projection[r + i * 4] * modelView[i + c * 4];
            }
        }
    }

    // Transform the vertex
    Vector4 result;
    for (r = 0; r < 4; ++r) {
        result[r] = T[r].dot(v);
    }

    // Homogeneous divide
    const double rhw = 1 / result.w;

    return Vector4(
        (1 + result.x * rhw) * viewport[2] / 2 + viewport[0],
        (1 - result.y * rhw) * viewport[3] / 2 + viewport[1],
        (result.z * rhw) * (depthRange[1] - depthRange[0]) + depthRange[0],
        rhw);
} 


	*/

	
}

planets::planets(introText* introTextObj)
{
	planetMoveTime = 1000;
	_movePlanets = false;
	_rand = new RNG(0);
	sunScale = 0.5f;
		
	enabledGodRays = false;
	godRaysFadingUp = true;

	_introText = introTextObj;

	float speed = 1.2f;
	planetSun = new planet(0.5f, SLICES, STACKS, true, 0, 9, IDR_JPG_PLANET_SUN_TEXTURE, speed);
	planetSun->InitSun();
	planetSun->distanceModifier = 0;

	float distance = 0.48f;

	initFbo();

	msys_debugPrintf("  Create Skybox");
	sky = new skybox(100);

	planet *planetMercury = new planet(0.02f, SLICES, STACKS, false, distance, 0, IDR_JPG_PLANET_MERCURY_TEXTURE, speed-=0.1f);
	planetSun->satellites[0] = planetMercury;
	distance+=0.1f;

	
	planet *planetVenus = new planet(0.04f, SLICES, STACKS, false, distance, 0, IDR_JPG_PLANET_VENUS_TEXTURE, speed-=0.1f);
	planetSun->satellites[1] = planetVenus;
	distance+=0.2f;


	planet *planetEarth = new planet(0.06f, SLICES, STACKS, false, distance, 0, IDR_JPG_PLANET_EARTH_TEXTURE, speed-=0.1f);
	planetSun->satellites[2] = planetEarth;
	distance+=0.2f;


	planet *planetMars = new planet(0.05f, SLICES, STACKS, false, distance, 0, IDR_JPG_PLANET_MARS_TEXTURE, speed-=0.1f);
	planetSun->satellites[3] = planetMars;
	distance+=0.35f;

	planet *planetJupiter = new planet(0.15f, SLICES, STACKS, false, distance, 0, IDR_JPG_PLANET_JUPITER_TEXTURE, speed-=0.1f);
	planetSun->satellites[4] = planetJupiter;
	distance+=0.4f;

	planet *planetSaturn = new planet(0.1f, SLICES, STACKS, false, distance, 0, IDR_JPG_PLANET_SATURN_TEXTURE, speed-=0.1f);
	planetSun->satellites[5] = planetSaturn;
	distance+=0.3f;

	
	planet *planetUranus = new planet(0.09f, SLICES, STACKS, false, distance, 0, IDR_JPG_PLANET_URANUS_TEXTURE, speed-=0.1f);
	planetSun->satellites[6] = planetUranus;
	distance+=0.3f;


	planet *planetNeptune = new planet(0.08f, SLICES, STACKS, false, distance, 0, IDR_JPG_PLANET_NEPTUNE_TEXTURE, speed-=0.1f);
	planetSun->satellites[7] = planetNeptune;
	distance+=0.3f;


	planet *planetPluto = new planet(0.02f, SLICES, STACKS, false, distance, 0, IDR_JPG_PLANET_URANUS_TEXTURE, speed-=0.1f);
	planetSun->satellites[8] = planetPluto;
	distance+=0.5f;
	
#ifdef DEBUG
	initShader(&shaderGodRays, NULL, LoadShaderText("shaders\\godrays.fs"), "GODRAYS");
	//initShader(&shaderGodRays, NULL, shaderFragFromResource(IDS_SHADER_GODRAYS_FRAG), "Godrays FragOnly");
#else
#endif


	/*
	uniformExposure = 0.0034f;
	uniformDecay = 1.0f;
	uniformDensity = 0.84f;
	uniformWeight = 5.65f;	
	*/

	uniformExposure = 0.0014f;
	uniformDecay = 1.0f;
	uniformDensity = 0.84f;
	uniformWeight = 5.65f;	

	light = new Light();

	glsl_loc_light = oglGetUniformLocation(shaderGodRays,"lightPositionOnScreen");
	oglUniform2f(glsl_loc_light,uniformLightX,uniformLightY);

	glsl_loc_exposure = oglGetUniformLocation(shaderGodRays,"exposure");
	oglUniform1f(glsl_loc_exposure,uniformExposure);

	glsl_loc_decay = oglGetUniformLocation(shaderGodRays,"decay");
	oglUniform1f(glsl_loc_decay,uniformDecay);

	glsl_loc_density = oglGetUniformLocation(shaderGodRays,"density");
	oglUniform1f(glsl_loc_density,uniformDensity);

	glsl_loc_weight = oglGetUniformLocation(shaderGodRays,"weight");
	oglUniform1f(glsl_loc_weight,uniformWeight);

	glsl_loc_myTexture = oglGetUniformLocation(shaderGodRays,"myTexture");
	oglUniform1i(glsl_loc_myTexture,fbTex);

	LogGlError();
}

void planets::StartSunspots(float time)
{
	planetSun->EnableSunSpots(time);
}

void planets::StartGodRays(float time)
{
	if (enabledGodRays) return;
	startTimeGodRays = time;
	enabledGodRays = true;
}

void Material(void)
{
	// -------------------------------------------
	// Material parameters:

	GLfloat material_Ka[] = {0.0f, 0.0f, 0.0f, 1.0f};
	GLfloat material_Kd[] = {0.1f, 0.1f, 0.1f, 1.0f};
	GLfloat material_Ks[] = {1.0f, 1.0f, 1.0f, 1.0f};
	GLfloat material_Ke[] = {0.1f, 0.1f, 0.1f, 1.0f};
	GLfloat material_Se = 5.0f;

	glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, material_Ka);
	glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, material_Kd);
	glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, material_Ks);
	glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, material_Ke);
	glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, material_Se);
}

void DemoLight(void)
{
	/*
	lookAt(0.0f,0.0f,4.0f, 
		0.0,0.0,-1.0,
		0.0f,1.0f,0.0f);*/

	glShadeModel(GL_SMOOTH);
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);
	glEnable(GL_NORMALIZE);

	// Light model parameters:
	// -------------------------------------------

	GLfloat lmKa[] = {0.0, 0.0, 0.0, 0.0 };
	glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmKa);

	glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, 1.0);
	glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, 0.0);

	// -------------------------------------------
	// Spotlight Attenuation

	GLfloat spot_direction[] = {1.0, -1.0, -1.0 };
	GLint spot_exponent = 30;
	GLint spot_cutoff = 180;

	glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, spot_direction);
	glLighti(GL_LIGHT0, GL_SPOT_EXPONENT, spot_exponent);
	glLighti(GL_LIGHT0, GL_SPOT_CUTOFF, spot_cutoff);

	GLfloat Kc = 1.0;
	GLfloat Kl = 0.0;
	GLfloat Kq = 0.0;

	glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION,Kc);
	glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, Kl);
	glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, Kq);


	// ------------------------------------------- 
	// Lighting parameters:

	GLfloat light_pos[] = {0.0f, 5.0f, 5.0f, 1.0f};
	GLfloat light_Ka[]  = {0.0f, 0.5f, 0.5f, 1.0f};
	GLfloat light_Kd[]  = {1.0f, 0.0f, 1.0f, 1.0f};
	GLfloat light_Ks[]  = {1.0f, 1.0f, 1.0f, 1.0f};

	glLightfv(GL_LIGHT0, GL_POSITION, light_pos);
	glLightfv(GL_LIGHT0, GL_AMBIENT, light_Ka);
	glLightfv(GL_LIGHT0, GL_DIFFUSE, light_Kd);
	glLightfv(GL_LIGHT0, GL_SPECULAR, light_Ks);
}

void DemoLight2(void)
{
	/*
	lookAt(0.0f,0.0f,4.0f, 
		0.0,0.0,-1.0,
		0.0f,1.0f,0.0f);*/

	glShadeModel(GL_SMOOTH);
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT1);
	glEnable(GL_NORMALIZE);

	// Light model parameters:
	// -------------------------------------------

	GLfloat lmKa[] = {0.0, 0.0, 0.0, 0.0 };
	glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmKa);

	glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, 1.0);
	glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, 0.0);

	// -------------------------------------------
	// Spotlight Attenuation

	GLfloat spot_direction[] = {0.0, -2.0, 0.0 };
	GLint spot_exponent = 30;
	GLint spot_cutoff = 180;

	glLightfv(GL_LIGHT1, GL_SPOT_DIRECTION, spot_direction);
	glLighti(GL_LIGHT1, GL_SPOT_EXPONENT, spot_exponent);
	glLighti(GL_LIGHT1, GL_SPOT_CUTOFF, spot_cutoff);

	GLfloat Kc = 1.0;
	GLfloat Kl = 0.0;
	GLfloat Kq = 0.0;

	glLightf(GL_LIGHT1, GL_CONSTANT_ATTENUATION,Kc);
	glLightf(GL_LIGHT1, GL_LINEAR_ATTENUATION, Kl);
	glLightf(GL_LIGHT1, GL_QUADRATIC_ATTENUATION, Kq);


	// ------------------------------------------- 
	// Lighting parameters:

	GLfloat light_pos[] = {15.0f, 15.0f, 0.0f, 1.0f};
	GLfloat light_Ka[]  = {1.0f, 1.0f, 1.0f, 1.0f};
	GLfloat light_Kd[]  = {1.0f, 1.0f, 1.0f, 1.0f};
	GLfloat light_Ks[]  = {1.0f, 1.0f, 1.0f, 1.0f};

	glLightfv(GL_LIGHT1, GL_POSITION, light_pos);
	glLightfv(GL_LIGHT1, GL_AMBIENT, light_Ka);
	glLightfv(GL_LIGHT1, GL_DIFFUSE, light_Kd);
	glLightfv(GL_LIGHT1, GL_SPECULAR, light_Ks);
}

void DemoLight3(void)
{
	/*
	lookAt(0.0f,0.0f,4.0f, 
		0.0,0.0,-1.0,
		0.0f,1.0f,0.0f);*/

	glShadeModel(GL_SMOOTH);
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT3);
	glEnable(GL_NORMALIZE);

	// Light model parameters:
	// -------------------------------------------

	GLfloat lmKa[] = {0.0, 0.0, 0.0, 0.0 };
	glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmKa);

	glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, 1.0);
	glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, 0.0);

	// -------------------------------------------
	// Spotlight Attenuation

	GLfloat spot_direction[] = {2.0, 2.0, -10.0 };
	GLint spot_exponent = 30;
	GLint spot_cutoff = 180;

	glLightfv(GL_LIGHT3, GL_SPOT_DIRECTION, spot_direction);
	glLighti(GL_LIGHT3, GL_SPOT_EXPONENT, spot_exponent);
	glLighti(GL_LIGHT3, GL_SPOT_CUTOFF, spot_cutoff);

	GLfloat Kc = 1.0;
	GLfloat Kl = 0.0;
	GLfloat Kq = 0.0;

	glLightf(GL_LIGHT3, GL_CONSTANT_ATTENUATION,Kc);
	glLightf(GL_LIGHT3, GL_LINEAR_ATTENUATION, Kl);
	glLightf(GL_LIGHT3, GL_QUADRATIC_ATTENUATION, Kq);


	// ------------------------------------------- 
	// Lighting parameters:

	GLfloat light_pos[] = {-15.0f, -15.0f, 0.0f, 1.0f};
	GLfloat light_Ka[]  = {0.3f, 0.3f, 0.3f, 1.0f};
	GLfloat light_Kd[]  = {1.0f, 1.0f, 1.0f, 1.0f};
	GLfloat light_Ks[]  = {1.0f, 1.0f, 1.0f, 1.0f};

	glLightfv(GL_LIGHT3, GL_POSITION, light_pos);
	glLightfv(GL_LIGHT3, GL_AMBIENT, light_Ka);
	glLightfv(GL_LIGHT3, GL_DIFFUSE, light_Kd);
	glLightfv(GL_LIGHT3, GL_SPECULAR, light_Ks);
}
/*
glm::vec4 glToScreen(const glm::vec4& v)
{
   
   // Get the matrices and viewport
   double modelView[16];
   double projection[16];
   double viewport[4];
   double depthRange[2];

   glGetDoublev(GL_MODELVIEW_MATRIX, modelView);
   glGetDoublev(GL_PROJECTION_MATRIX, projection);
   glGetDoublev(GL_VIEWPORT, viewport);
   glGetDoublev(GL_DEPTH_RANGE, depthRange);

   // Compose the matrices into a single row-major transformation
   glm::vec4 T[4];
   int r, c, i;
   for (r = 0; r < 4; ++r)
   {
    for (c = 0; c < 4; ++c)
    {
      T[r][c] = 0;
      for (i = 0; i < 4; ++i)
      {
        // OpenGL matrices are column major
         T[r][c] += (float)(projection[r + i * 4] * modelView[i + c * 4]);
      }
    }
   }

   // Transform the vertex
   glm::vec4 result;
   for (r = 0; r < 4; ++r)
   {
	   //result[r] = T[r].dot(v);
	   result[r] = glm::dot(T[r], v);
   }

   // Homogeneous divide
   const double rhw = 1 / result.w;

   return glm::vec4(
   (1 + result.x * rhw) * viewport[2] / 2 + viewport[0],
   (1 - result.y * rhw) * viewport[3] / 2 + viewport[1],
   (result.z * rhw) * (depthRange[1] - depthRange[0]) + depthRange[0],
   rhw);
} */

void planets::HandleCamera(float time)
{

	eyeX = 0;
	eyeY = 5;
	eyeZ = 5;

	centerX = 0;
	centerY = 0;
	centerZ = 0;

	upX = 0;
	upY = 1;
	upZ = 0;

	float timeMoveIn = 50;

	if (time <= timeMoveIn)
	{
		eyeY = timeMoveIn - time;
	}else{
		eyeY = 0;
	}

	if (time <= timeMoveIn)
	{
		eyeZ = timeMoveIn - time + 5;
	}else{
		eyeZ = 5;
	}

	sky->_size = eyeZ * 2;

	gluLookAt( eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ );
}

void planets::EffectKickDrum(float time)
{
	timeKickStart = time;
}

void planets::EffectChime(float time)
{
	timeChimeStart = time;
	int planetIndex = _rand->rInt(0,5);
	planet *p = planetSun->satellites[planetIndex];
	p->EnableEffect(time);
}

void planets::EffectSnareDrum(float time)
{

}

void planets::MovePlanetsOutFromSun(float time)
{
	_movePlanets = true;
	planetMoveTime = time;
}

void planets::Draw(float time)
{
	Material();
	DemoLight();
	DemoLight2();
	DemoLight3();

	glDisable(GL_BLEND);
	glDisable(GL_LIGHTING);
	glClearColor(0.0f, 0.0f, 0.0f, 1);

	// set up godrays shader params
	if (enabledGodRays)
	{
		if (godRaysFadingUp)
		{
			float dif = (time - startTimeGodRays) * 0.75f;
			if (uniformWeight + dif <50.0f)
			{
				uniformWeight += dif;
			}else{
				uniformWeight = 50.0f;
				startTimeGodRays = time;
				godRaysFadingUp = false;
			}

			float sizedif =  (time - startTimeGodRays) * 0.005f;
			if (sunScale + sizedif < 1.0f)
			{
				sunScale+=sizedif;
			}else{
				sunScale = 1.0f;
			}
		}else{
			float dif = (time - startTimeGodRays) * 0.5f;
			if (uniformWeight - dif > 5.65f)
			{
				uniformWeight-=dif;
			}else{
				uniformWeight = 5.65f;	

				float t = time - timeKickStart;
				if (t < 1)
				{
					uniformWeight = 5.65f+ (1-t*3);
				}
			}
		}
	}

	// do light and silhouette masks
	//glDepthMask(false); // don't write to depth buffer for silhouette masks
	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	{
		glLoadIdentity();
		/*
		float pos[3] = { 3.0f*cosf( time*1.0f ), 
			3.0f*cosf( time*0.6f ), 
			3.0f*sinf( time*1.0f ) };*/

		//gluLookAt( pos[0], pos[1], pos[2], tar[0], tar[1], tar[2], 0.0f, 1.0f, 0.0f );
		HandleCamera(time);

		glRotatef(-time*10, 0, 0, 1);

		// move planets out from sun
		float planetMoveLength = 2;
		if (time > planetMoveTime)
		{
			float amt = time - planetMoveTime;

			if (amt < planetMoveLength)
			{
				planetSun->distanceModifier = amt / planetMoveLength;
			}else{
				planetSun->distanceModifier = 1.0f;
			}
		}

		// draw bg to buffer
		glPushMatrix();
		{
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
			sky->Draw(time);
			/*
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
			ViewOrtho(_screenWidth, _screenHeight);
			glColor4f(1,1,1,1);
			glEnable(GL_TEXTURE_2D);
			glBindTexture(GL_TEXTURE_2D, bgTex);
			glBegin(GL_QUADS);
			{
				glTexCoord2f(0,0);
				glVertex2i(0,0);

				glTexCoord2f(0,1);
				glVertex2i(0,_screenHeight);

				glTexCoord2f(1,1);
				glVertex2i(_screenWidth, _screenHeight);

				glTexCoord2f(1,0);
				glVertex2i(_screenWidth,0);
			}		
			glEnd();
			ViewPerspective();*/
		}
		glPopMatrix();

		// shadows and objects
		glPushMatrix();
		{
			//glTranslatef(0, 0, -6);
			
			// draw sun highlight and planets silhouettes to fbo render texture
			glPushMatrix();
			{	
				glScalef(sunScale, sunScale, sunScale); // scale sun

				// draw sunspots to ss fbo
				planetSun->DrawSunSpots(time);

				glViewport(0, 0, globalScreenInfo.fboWidth, globalScreenInfo.fboHeight); // change viewport to match fbo size

				oglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb);
				glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

				planetSun->Draw(time, true);

				oglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);

				glViewport(0, 0, globalScreenInfo.width, globalScreenInfo.height); // change viewport to match screen size
			}
			glPopMatrix();

			glEnable(GL_LIGHTING);
			glClear(GL_DEPTH_BUFFER_BIT);
			
			// draw sun and planets to buffer
			glEnable(GL_LIGHTING);
			glClear(GL_DEPTH_BUFFER_BIT);
			glPushMatrix();
			{	
				glScalef(sunScale, sunScale, sunScale); // scale sun
				planetSun->Draw(time, false);
				glDisable(GL_LIGHTING);
				glEnable(GL_BLEND);
				glDisable(GL_BLEND);
				glEnable(GL_LIGHTING);
			}
			glPopMatrix();
		}
		glPopMatrix();

		//return;

		uniformLightX = 0.5f;
		uniformLightY = 0.5f;

		glEnable(GL_TEXTURE_2D);
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE);
		
		if (enabledGodRays && globalScreenInfo.shaderLevel != ShaderlLevel_None)
		{
			vertex sunPos = planetSun->ScreenSpacePosition();
			uniformLightX = sunPos.x;
			uniformLightY = sunPos.y;
			oglUseProgram(shaderGodRays);
			oglUniform2f(glsl_loc_light,uniformLightX,uniformLightY);
			oglUniform1f(glsl_loc_exposure,uniformExposure);
			oglUniform1f(glsl_loc_decay,uniformDecay);
			oglUniform1f(glsl_loc_density,uniformDensity);
			oglUniform1f(glsl_loc_weight,uniformWeight);
			oglUniform1i(glsl_loc_myTexture,0);

			glPushMatrix();
			{
				glLoadIdentity();	
				glColor4f(1,1,1,1);
				glEnable(GL_TEXTURE_2D);
				glBindTexture(GL_TEXTURE_2D, fbTex);
				//glRectf( -_aspect, -1, _aspect, 1 );
				
				//glTranslatef(-0.5,- 0.5, -1);
				ViewOrtho(globalScreenInfo.width, globalScreenInfo.height);
				glColor4f(1,1,1,1);
				glEnable(GL_TEXTURE_2D);
				glBindTexture(GL_TEXTURE_2D, fbTex);
				glBegin(GL_QUADS);
				{
					glTexCoord2f(0,1);
					glVertex2i(0,0);

					glTexCoord2f(0,0);
					glVertex2i(0,globalScreenInfo.height);

					glTexCoord2f(1,0);
					glVertex2i(globalScreenInfo.width, globalScreenInfo.height);

					glTexCoord2f(1,1);
					glVertex2i(globalScreenInfo.width,0);
				}		
				glEnd();
				ViewPerspective();
			}
			glPopMatrix();
			oglUseProgram(0);
		}	

		_introText->Draw(time);
		
		/*
		// ss test
		glPushMatrix();
		{
			glDisable(GL_LIGHTING);
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
			glLoadIdentity();	
			ViewOrtho(_screenInfo->width, _screenInfo->height);
			glColor4f(1,1,1,1);
			glEnable(GL_TEXTURE_2D);

			glBindTexture(GL_TEXTURE_2D, planetSun->fboTextureSunspotsPass1);
			glBegin(GL_QUADS);
			{
				glTexCoord2f(0,0);
				glVertex2i(0,0);

				glTexCoord2f(0,1);
				glVertex2i(0,_screenInfo->height);

				glTexCoord2f(1,1);
				glVertex2i(_screenInfo->width, _screenInfo->height);

				glTexCoord2f(1,0);
				glVertex2i(_screenInfo->width,0);
			}		
			glEnd();

			ViewPerspective();
		}
		glPopMatrix();
		// end ss test*/

	}
	glPopMatrix();
}


planets::~planets(void)
{
}
