/*
  Sean Dobbs
  Period 4
  Missle trajectory simulation
*/

#include <iostream.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include "glaux.h"
#include "GL/gl.h"
#include "GL/glu.h"
#include "GL/glut.h"

// Globals
static int dist, range;

// Functions
static void Init(void)
{
	glClearColor(0.0, 0.0, 0.0, 1.0);
	glShadeModel( GL_FLAT );
	glOrtho(0.0, 1000.0, 0.0, 90.0, -5.0, 5.0);
}

void DrawTraj()
{
	double t=0, tstep=0.005, a=32, vx, vy, x, y, closeness;

	glBegin(GL_POINTS);
	for(double v = 0; v<=1000; v+=.1)
	{
		 for(double theta = 0; theta <= 90; theta+=.1)
		 {
			  vy=v*sin((theta * M_PI)/180);
			  vx=v*cos((theta * M_PI)/180);
			  do
			  {
				   t+=tstep;
				   y = (vy * t) - (0.5 * a * t * t);
				   x = vx * t;
			  }
			  while(y>0);
			  closeness = fabs(x-dist);
			  if( closeness < range)
			  {
				   glColor3f(0.0, 0.0, 1.0);
				   glVertex3f(v, theta, 0.0);
			  } else if( closeness < range*2)
			  {
				   glColor3f(0.0, 0.0, 0.8);
				   glVertex3f(v, theta, 0.0);
			  } else if( closeness < range*4)
			  {
				   glColor3f(0.0, 0.0, 0.7);
				   glVertex3f(v, theta, 0.0);
			  } else if( closeness < range*8)
			  {
				   glColor3f(0.0, 0.0, 0.6);
				   glVertex3f(v, theta, 0.0);
			  } else if( closeness < range*16)
			  {
				   glColor3f(0.0, 0.0, 0.5);
				   glVertex3f(v, theta, 0.0);
			  }
		 }
	}
	glEnd();
}

static void display()
{
	glClear( GL_COLOR_BUFFER_BIT );
	cout<<"target distance: ";
	cin>>dist;
	cout<<"hit range:";
	cin>>range;
	DrawTraj();
	glFlush();
	glutPostRedisplay();
}

static void Reshape( int width, int height )
{
	 glClear( GL_COLOR_BUFFER_BIT );
	 glViewport(0, 0, (GLint)width, (GLint)height);
	 glMatrixMode( GL_PROJECTION );
 	 glLoadIdentity();
	 glMatrixMode(GL_MODELVIEW);
}

int main(int argc, char **argv)
{
    glutInit(&argc, argv);
	glutInitDisplayMode( GLUT_SINGLE | GLUT_RGB );
	glutInitWindowSize(750, 270);
	glutInitWindowPosition(50,250);
	glutCreateWindow(argv[0]);
	Init();
//  glutKeyboardFunc(keypress);
//	glutMouseFunc(mouseclick);
	glutDisplayFunc(display);
	glutReshapeFunc(Reshape);
	glutMainLoop();
	return 0;	
}
