#include <math.h>
#include <stdio.h>
#include "dms/Camera.h"

#define DEG2RAD(a) (a*M_PI/180.0f)


namespace dms
{

Camera::Camera(void)
    {
    pos_.set(0,0,0);
    xRot_ = yRot_ = 0;
    }


Camera::~Camera(void)
    {
    }


void Camera::apply(void) const
    {
    applyProjection();
    glLoadIdentity();
    glRotatef(-xRot_, 1.0, 0.0, 0.0);
    glRotatef(-yRot_, 0.0, 1.0, 0.0);
    glTranslatef(-pos_.vec[0], -pos_.vec[1], -pos_.vec[2]);
    }


void Camera::turn(GLfloat angle)
    {
    yRot_ += angle;
    }


void Camera::pitch(GLfloat angle)
    {
    xRot_ += angle;
    }


void Camera::moveForward(GLfloat distance)
    {
    move(forward()*distance);
    }


void Camera::moveLeft(GLfloat distance)
    {
    move(left()*distance);
    }


void Camera::moveUp(GLfloat distance)
    {
    move(up()*distance);
    }


void Camera::move(const Vector3& delta)
    {
    pos_ += delta;
    }


Vector3 Camera::forward(void) const
    {
    float xr = DEG2RAD(xRot_), yr = DEG2RAD(yRot_);
    return Vector3(-sinf(yr) * cosf(xr),
                   sinf(xr),
                   -cosf(yr) * cosf(xr));
    }


Vector3 Camera::left(void) const
    {
    float xr = DEG2RAD(xRot_), yr = DEG2RAD(yRot_);
    return Vector3(-cosf(yr), 0.0, sinf(yr));
    }


Vector3 Camera::up(void) const
    {
    float xr = DEG2RAD(xRot_), yr = DEG2RAD(yRot_);
    return Vector3(sinf(yr) * sinf(xr),
                   cosf(xr),
                   cosf(yr) * sinf(xr));
    }


const dms::Vector3& Camera::position(void) const
    {
    return pos_;
    }


GLfloat Camera::xRotation(void) const
    {
    return xRot_;
    }


GLfloat Camera::yRotation(void) const
    {
    return yRot_;
    }


void Camera::setPosition(GLfloat x,GLfloat y,GLfloat z)
    {
    pos_.vec[0] = x;
    pos_.vec[1] = y;
    pos_.vec[2] = z;
    }


void Camera::setPosition(const Vector3& pos)
    {
    pos_ = pos;
    }


void Camera::setXRotation(GLfloat angle)
    {
    xRot_ = angle;
    }


void Camera::setYRotation(GLfloat angle)
    {
    yRot_ = angle;
    }


}
