#include "include.h"

#ifdef _3DS
Model_3DS * Nave::modelo = NULL;
#else
Model * Nave::modelo = NULL;
#endif

double a = 0, b = 0, c = 0;

const GLfloat esmeraldaAmb[4] = {0.2f, 0.2f, 1.0f, 1.0f};
const GLfloat esmeraldaDif[4] = {0.2f, 0.2f, 1.0f, 1.0f};
const GLfloat esmeraldaSpe[4] = {0.2f, 0.2f, 1.0f, 1.0};
GLfloat esmeraldaShi = 76.8f;

Nave::Nave() {
	this->vel = 0;
	this->front = Vector3D(1, 0, 0);
	this->up = Vector3D(0, 0, 1);
	this->right = Vector3D(0, -1, 0);
	this->acl = 0;
	this->radio = 1;
	this->vidas = 3;
	if (Nave::modelo == NULL) {
#ifdef _3DS
		Nave::modelo = new Model_3DS();
		Nave::modelo->Load("modelos/sf3.3DS");
		Nave::modelo->scale = this->radio * 2;
#else
		Nave::modelo = Model::readOBJ("modelos/boomerangShip.obj");
		Nave::modelo->unitize();
		Nave::modelo->trasladarOrigen(0, 0, 0.2);
#endif
	}
}

void Nave::addYaw(double yaw) {
	a += val(yaw);
	this->front.rotate(this->up, val(yaw));
	this->right.rotate(this->up, val(yaw));
	this->front.unitize();
	this->right.unitize();
}
void Nave::addPitch(double pitch) {
	b += val(pitch);
	this->up.rotate(this->right, val(pitch));
	this->front.rotate(this->right, val(pitch));
	this->front.unitize();
	this->up.unitize();
}
void Nave::addRoll(double roll) {
	c += val(roll);
	this->up.rotate(this->front, val(roll));
	this->right.rotate(this->front, val(roll));
	this->up.unitize();
	this->right.unitize();
}

void Nave::update() {
	this->vel += this->acl;
	if (this->vel > 1) this->vel = 1;
	if (this->vel < -1) this->vel = -1;

	this->pos += this->front * val(this->vel);
}

Nave::~Nave() {
}

void Nave::draw() {
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_CULL_FACE);

	if (Config::luzEnabled) {
		glColor3d(1.0, 1.0, 1.0);
		glEnable(GL_COLOR_MATERIAL);
		glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
		glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, esmeraldaAmb);
		glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, esmeraldaDif);
		glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, esmeraldaSpe);
		glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, esmeraldaShi);
	} else {
		glColor3f(0.7, 0.3, 0.3);
	}

#ifdef _3DS
	glTranslated(this->pos.x, this->pos.y, this->pos.z);
	glScaled(this->radio*2, this->radio*2, this->radio*2);

	Vector3D z(0, 0, 1);
	Vector3D nz = z.crossProduct(this->up);
	double angle = acos(z.dotProduct(this->up));
	glRotated(angle * 180 / PI, nz.x, nz.y, nz.z);

	// correccion del modelo
	Nave::modelo->scale = 0.2;
	glRotated(-90, 1, 0, 0);

	Nave::modelo->Draw();
#else
	glTranslated(this->pos.x, this->pos.y, this->pos.z);
	glScaled(this->radio*2, this->radio*2, this->radio*2);

	Vector3D z(0, 0, 1);
	Vector3D nz = z.crossProduct(this->up);
	double angle = acos(z.dotProduct(this->up));
	glRotated(angle * 180 / PI, nz.x, nz.y, nz.z);

	// correccion del modelo
	glRotated(90, 0, 0, -1);
	glRotated(-90, 1, 0, 0);

	Nave::modelo->draw();
#endif

	glDisable(GL_CULL_FACE);
	glDisable(GL_DEPTH_TEST);
	glDisable(GL_COLOR_MATERIAL);
}
