#include <GL/glut.h>
#include <math.h>

// pretend we have a light defined with 3 floats

struct Pos
{
	float x, y, z;
};

struct Light
{
	float x, y, z;
};

Light g_Light0 = { 0.0f, 10.0f, -5.0f};

float M[] = 
{ 1, 0, 0, 0,
  0, 1, 0, 0,
  0, 0, 1, 0,
  0, 0, 0, 0};
	
float triRot = 0.0f;
	
void drawTriangle()
{
	
	float x = 2 * cos(triRot);
	float z = 2 * sin(triRot);

	glBegin(GL_TRIANGLES);
	glVertex3f(0,0,0);
	glVertex3f(x,2,z);
	glVertex3f(x,0,z);
	glEnd();
}

void display()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glColor3f(1,1,1);

	glLoadIdentity();
	glTranslatef(0,0,2);
	drawTriangle();
	//M[13] 
	M[7] 
	= (g_Light0.y == 0.0) ? 0 : -1/g_Light0.y;

	glPushMatrix();
	glTranslatef(g_Light0.x, g_Light0.y, g_Light0.z);
	glMultMatrixf(M);
	glTranslatef(-g_Light0.x, -g_Light0.y, -g_Light0.z);
	glColor3f(1,0,0);
	drawTriangle();
	glPopMatrix();

	glutSwapBuffers();
}

void idle()
{
	// use polar coords
	static float rot = 0.0f;
	//rot += 0.01f;
	triRot+= 0.005f;
	g_Light0.x = g_Light0.y * cos(rot);
	g_Light0.z = g_Light0.y * sin(rot);
	glutPostRedisplay();
}

void reshape(int w, int h)
{
	glMatrixMode(GL_PROJECTION);
	glViewport(0,0,w,h);
	glLoadIdentity();
	gluPerspective(60,(float)w/h, .1, 100);
	gluLookAt(0,5,15,0,0,0,0,1,0);
	glMatrixMode(GL_MODELVIEW);
}

void main()
{
	glutInitWindowSize(500,500);
	glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
	glutCreateWindow("Shadow Test");
	glutDisplayFunc(display);
	glutReshapeFunc(reshape);
	glutIdleFunc(idle);

	glClearColor(0,0,0,0);
	glEnable(GL_DEPTH_TEST);
	glutMainLoop();
}