#include "camera.h"
#include <stdio.h>

#include "math.h"

CCamera::CCamera()
{
	pos = Vector3 (0.0,0.0,0.0);
	view_dir = Vector3 (0.0,0.0,-1.0);
	right_vec = Vector3 (1.0, 0.0, 0.0);
	up_vec = Vector3 (0.0, 1.0, 0.0);

	rotatedX = rotatedY = rotatedZ = 0.0;
}

void CCamera::move(Vector3 delta)
{
	pos = pos + delta;
}

void CCamera::rotateX (GLfloat angle)
{
	rotatedX += angle;
	update_view_vectors();

	/*
	//rotate view_dir around the right vector:
	view_dir =(view_dir*cos(angle*PIdiv180) + up_vec*sin(angle*PIdiv180)).normalize();

	//update up_vec
	up_vec = view_dir.cross(right_vec) *-1;
	*/

	
}

void CCamera::rotateY (GLfloat angle)
{
	rotatedY += angle;
	update_view_vectors();
	
	/*
	//rotate view_dir around the up vector:
	view_dir = (view_dir*cos(angle*PIdiv180) - right_vec*sin(angle*PIdiv180)).normalize();

	//update right_vec
	right_vec = view_dir.cross(up_vec);
	*/
}

void CCamera::rotateZ (GLfloat angle)
{
	rotatedZ += angle;
	
	//rotate view_dir around the right vector:
	right_vec = (right_vec*cos(angle*PIdiv180) + up_vec*sin(angle*PIdiv180)).normalize();

	//update up_vec
	up_vec = view_dir.cross(right_vec) *-1;
}

void CCamera::render( void )
{

	Vector3 point = pos + view_dir;
	glRotatef(rotatedX,-1.0,0.0,0.0);
	glRotatef(rotatedY,0.0,-1.0,0.0);
	gluLookAt(pos.x,pos.y,pos.z,
			  pos.x, pos.y, pos.z+1,
			  0,1,0);

}

void CCamera::move_forward( GLfloat delta )
{
	pos = pos + (view_dir*-delta);
}

void CCamera::strafe_right ( GLfloat delta )
{
	pos = pos+ (right_vec*delta);
}

void CCamera::move_up ( GLfloat delta )
{
	pos = pos + (up_vec*delta);
}

Vector3 CCamera::get_view_dir (void)
{
	return Vector3(view_dir.x,view_dir.y,view_dir.z);

}

void CCamera::update_view_vectors(){

	double rx = (rotatedX)*PIdiv180;
	double ry = (rotatedY)*PIdiv180;
	double ry90 = (rotatedY-90)*PIdiv180;

	view_dir.x = sin(ry)*cos(rx);
	view_dir.y = 0;
	view_dir.z = cos(ry);
	view_dir.normalize();

	right_vec.x = sin(ry90)*cos(rx);
	right_vec.y = 0;
	right_vec.z = cos(ry90);
	right_vec.normalize();
}