#include "flyingCamera.h"

// ----------------------------------------------------------------------------------------------------------------------------

CCamera::CCamera()
{
	ViewMatrix = NULL;

	X = vec3(1.0f, 0.0f, 0.0f);
	Y = vec3(0.0f, 1.0f, 0.0f);
	Z = vec3(0.0f, 0.0f, 1.0f);

	Position = vec3(0.0f, 1.75f, 0.0f);
}

void CCamera::OnMouseMove(int cx, int cy)
{
	float Sensitivity = 0.25f;

	float deltaX = (float)cx * Sensitivity;
	float deltaY = (float)cy * Sensitivity;

	if(deltaX != 0.0f)
	{
		X = rotate(X, deltaX, vec3(0.0f, 1.0f, 0.0f));
		Y = rotate(Y, deltaX, vec3(0.0f, 1.0f, 0.0f));
		Z = rotate(Z, deltaX, vec3(0.0f, 1.0f, 0.0f));
	}

	if(deltaY != 0.0f)
	{
		Y = rotate(Y, deltaY, X);
		Z = rotate(Z, deltaY, X);

		if(Y.y < 0.0f)
		{
			Z = vec3(0.0f, Z.y > 0.0f ? 1.0f : -1.0f, 0.0f);
			Y = cross(Z, X);
		}
	}

	CalculateViewMatrix();
}

void CCamera::OnKeys(BYTE Keys, float FrameTime)
{
	float Speed = 5.0f;

	if(Keys & 0x40) Speed *= 2.0f;

	float Distance = Speed * FrameTime;

	vec3 Up(0.0f, 1.0f, 0.0f);
	vec3 Right = X;
	vec3 Forward = cross(Up, Right);

	Up *= Distance;
	Right *= Distance;
	Forward *= Distance;

	vec3 Movement = vec3(0.0f);

	if(Keys & 0x01) Movement += Forward;
	if(Keys & 0x02) Movement -= Forward;
	if(Keys & 0x04) Movement -= Right;
	if(Keys & 0x08) Movement += Right;
	if(Keys & 0x10) Movement += Up;
	if(Keys & 0x20) Movement -= Up;

	if(Movement.x != 0.0f || Movement.y != 0.0f || Movement.z != 0.0f)
	{
		Position += Movement;
		CalculateViewMatrix();
	}
}

void CCamera::CalculateViewMatrix()
{
	if(ViewMatrix != NULL)
	{
		*ViewMatrix = mat4x4(X.x, Y.x, Z.x, 0.0f, X.y, Y.y, Z.y, 0.0f, X.z, Y.z, Z.z, 0.0f, -dot(X, Position), -dot(Y, Position), -dot(Z, Position), 1.0f);
	}
}

void CCamera::SetViewMatrixPointer(mat4x4 *ViewMatrix)
{
	this->ViewMatrix = ViewMatrix;
	CalculateViewMatrix();
}