/*
  prototype for 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 double sintbl[91], costbl[91];

// Functions

void Precompute()
{
	 for(int i=0;i<=90;i++)
	 {
		  sintbl[i] = sin((i * M_PI)/180);
		  costbl[i] = cos((i * M_PI)/180);
	 }
}

static void Init(void)
{
	glClearColor(0.0, 0.0, 0.0, 1.0);
	glShadeModel( GL_FLAT );
	glOrtho(0.0, 800.0, 0.0, 400.0, -5.0, 5.0);
}

void DrawTraj()
{
	int dist, range, theta, wallx, wally, wallh;
	double t=0, tstep=0.001, a=32, v, vx, vy, x, y, wallt;

	cout<<"velocity: ";
	cin>>v;
	cout<<"theta: ";
	cin>>theta;
	cout<<"target distance: ";
	cin>>dist;
	cout<<"hit range:";
	cin>>range;
	cout<<"wall position (x y): ";
	cin>>wallx>>wally;
	cout<<"height :";
	cin>>wallh;
	vy=v*sintbl[theta];
	vx=v*costbl[theta];

	glBegin(GL_POINTS);
	for(int i=0;i<wallh;i++)
		 glVertex3f(wallx, i, 0.0);
	glEnd();

	glBegin(GL_POINTS);
	do
	{
		 t+=tstep;
		 y = (vy * t) - (0.5 * a * t * t);
		 x = x + vx * tstep;
		 if((x<wallx+5)&&(x>wallx-5)&&(y>wally)&&(y<(wally+wallh)))
		 {
			  vx = -(vx / 2.0);
		 }
		 glVertex3f(x, y, 0.0);
	}
	while(y>0);

	glEnd();
	if(fabs(x-dist) < range)
		 cout<<"Hit! Good Job!"<<endl;
	else
		 cout<<"Miss! Hahahahahahahaha!"<<endl;
}

static void display()
{
//	glClear( GL_COLOR_BUFFER_BIT );
	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)
{
	Precompute();
    glutInit(&argc, argv);
	glutInitDisplayMode( GLUT_SINGLE | GLUT_RGB );
	glutInitWindowSize(400, 200);
	glutInitWindowPosition(50,250);
	glutCreateWindow(argv[0]);
	Init();
//  glutKeyboardFunc(keypress);
//	glutMouseFunc(mouseclick);
	glutDisplayFunc(display);
	glutReshapeFunc(Reshape);
	glutMainLoop();
	return 0;	
}
