#include "position.h"

#include "SDL_opengl.h"

#include "tweak/tweak.h"

#include "random.h"

Position::Position() {
	pos.y=0.4f;
}

Position::~Position() {
}



void Position::set_movement(C3f d) { dir=d; }
C3f Position::get_movement() const{ return dir; }
C3f Position::get_rotation() const{ return rot; }
void Position::set_rotation(C3f r) { rot=r; }
C3f Position::get_position() const{ return pos; }
void Position::set_position(C3f p) { pos=p; }


void Position::rotate(float x,float y) {
	rot.y+=x;
	rot.x+=y;
	cap_rot();
}

void Position::cap_rot() {
   float f;
   f=Tweak::rot_max_x_f();
   if (rot.x>f) rot.x=f;
   f=Tweak::rot_min_x_f();
   if (rot.x<f) rot.x=f;
}


C3f Position::nextpos() {
	C3f npos;
	npos=pos+dir;
	return npos;
}

void Position::move_backward(float ticks) {
	move_rel_direction(C3f(0,0,0),ticks*-1);
}
void Position::move_left(float ticks) {
	move_rel_direction(C3f(0,-90,0),ticks);
}
void Position::move_right(float ticks) {
	move_rel_direction(C3f(0,90,0),ticks);
}

void Position::move_forward(float ticks) {
	move_rel_direction(C3f(),ticks);
}
void Position::move_rel_direction(C3f r,float ticks) {
	C3f nr;
	nr=rot+r;


	move_direction(nr,ticks);
}

void Position::move_direction(C3f r,float ticks) {
	C3f npos;
	C3f ndir;
	GLfloat matrix[16];
	Quaternion q;


	Quaternion rotquatx,rotquaty;

	rotquatx.from_axisangle(C3f(1,0,0), r.x);
	rotquaty.from_axisangle(C3f(0,1,0), r.y);

	rotquatx.to_matrix(matrix);
	ndir.y = matrix[9];

	q = rotquaty * rotquatx;
	q.to_matrix(matrix);
	ndir.x = matrix[8];
	ndir.z = matrix[10];

	ndir.z*=-1;
	ndir *= ticks*Tweak::player_speed_f();

	dir+=ndir;
}


void Position::rotate() {
	GLfloat matrix[16];
	Quaternion q;
	Quaternion rotquatx,rotquaty;

	rotquatx.from_axisangle(C3f(1,0,0), rot.x);
	rotquaty.from_axisangle(C3f(0,1,0), rot.y);
	
	q = rotquatx * rotquaty;
	q.to_matrix(matrix);

	glMultMatrixf(matrix);
}
void Position::movement_clear(C3 c) {
	if (c.x) dir.x=0;
	if (c.y) dir.y=0;
	if (c.z) dir.z=0;
}


void Position::translate() {
    glTranslatef(-pos.x, -pos.y, -pos.z);
}
void Position::translate2() {
    glTranslatef(pos.x, pos.y, pos.z);
}
void Position::rotrans2()  {
	rotate();
	translate2();
}

void Position::rotrans()  {
	rotate();
	translate();
}

