//
//  SuperTuxKart - a fun racing game with go-kart
//  Copyright (C) 2004-2015 Steve Baker <sjbaker1@airmail.net>
//  Copyright (C) 2006-2015 SuperTuxKart-Team, Steve Baker
//
//  This program is free software; you can redistribute it and/or
//  modify it under the terms of the GNU General Public License
//  as published by the Free Software Foundation; either version 3
//  of the License, or (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

#include "camera.h"

#include <math.h>

#include "../config/user_config.h"
#include "irr_driver.h"
#include "../io/xml_node.h"

#include "../modes/world.h"
#include "../game/game_manager.h"
#include "../maps/map.h"
#include "../utils/aligned_array.h"
#include "../utils/constants.h"
#include "../utils/vs.h"

#include "ICameraSceneNode.h"
#include "ISceneManager.h"

using namespace irr;

std::vector<Camera*>                       Camera::m_all_cameras;

Camera* Camera::s_active_camera = NULL;

// ============================================================================
Camera::Camera(int camera_index)
{
    m_smooth        = false;
    m_attached      = false;
    m_mode          = CM_NORMAL;
    m_index         = camera_index;
    m_camera        = irr_driver->addCameraSceneNode();
    Log::info("Camera", "adding cam");

    //m_camera        = irr_driver->getSceneManager()->addCameraSceneNodeFPS(0, 70, 0.04);
    m_previous_pv_matrix = core::matrix4();



    setupCamera();

    m_distance = 1000.0f;

    m_ambient_light = World::getWorld()->getMap()->getDefaultAmbientColor();

    // TODO: Put these values into a config file
    //       Global or per split screen zone?
    //       Either global or per user (for instance, some users may not like
    //       the extra camera rotation so they could set m_rotation_range to
    //       zero to disable it for themselves).
    m_position_speed = 8.0f;
    m_target_speed   = 10.0f;
    m_rotation_range = 0.4f;
    m_rotation_range = 0.0f;
    m_lin_velocity = core::vector3df(0, 0, 0);
    m_target_velocity = core::vector3df(0, 0, 0);
    m_target_direction = core::vector3df(0, 0, 1);
    m_target_up_vector = core::vector3df(0, 1, 0);
    m_direction_velocity = core::vector3df(0, 0, 0);

    m_local_position = core::vector3df(0, 0, 0);
    m_local_direction = core::vector3df(0, 0, 1);
    m_local_up = core::vector3df(0, 1, 0);

    m_angular_velocity = 0;
    m_target_angular_velocity = 0;
    m_max_velocity = 15;
    reset();
}   // Camera

// ----------------------------------------------------------------------------
/** Removes the camera scene node from the scene.
 */
Camera::~Camera()
{
    irr_driver->removeCameraSceneNode(m_camera);

    if (s_active_camera == this)
        s_active_camera = NULL;
}   // ~Camera

//-----------------------------------------------------------------------------
/** Applies mouse movement to the first person camera.
 *  \param x The horizontal difference of the mouse position.
 *  \param y The vertical difference of the mouse position.
 */
void Camera::applyMouseMovement (float x, float y)
{
    irr::core::vector3df direction(m_target_direction);
    irr::core::vector3df up(m_camera->getUpVector());

    // Set local values if the camera is attached to the kart
    if (m_attached)
        up = m_local_up;

    direction.normalize();
    up.normalize();

    irr::core::vector3df side(direction.crossProduct(up));
    side.normalize();
    core::quaternion quat;
    quat.fromAngleAxis(y, side);

    core::quaternion quat_x;
    quat_x.fromAngleAxis(x, up);
    quat *= quat_x;

    direction = quat * direction;
    // Try to prevent toppling over
    // If the camera would topple over with the next movement, the vertical
    // movement gets reset close to the up vector
    if ((direction - up).getLengthSQ() + (m_target_direction - up).getLengthSQ()
        <= (direction - m_target_direction).getLengthSQ())
        direction = quat_x * ((m_target_direction - up).setLength(0.02f) + up);
    // Prevent toppling under
    else if ((direction + up).getLengthSQ() + (m_target_direction + up).getLengthSQ()
        <= (direction - m_target_direction).getLengthSQ())
        direction = quat_x * ((m_target_direction + up).setLength(0.02f) - up);
    m_target_direction = direction;

    // Don't do that because it looks ugly and is bad to handle ;)
    /*side = direction.crossProduct(up);
    // Compute new up vector
    up = side.crossProduct(direction);
    up.normalize();
    cam->setUpVector(up);*/
}




//-----------------------------------------------------------------------------
/** Sets up the viewport, aspect ratio, field of view, and scaling for this
 *  camera.
 */
void Camera::setupCamera()
{
    m_aspect = (float)(irr_driver->getActualScreenSize().Width)/irr_driver->getActualScreenSize().Height;

    m_viewport = core::recti(0, 0,
                                     irr_driver->getActualScreenSize().Width,
                                     irr_driver->getActualScreenSize().Height);
            m_scaling  = core::vector2df(1.0f, 1.0f);
            m_fov      = DEGREE_TO_RAD*75.0f;



    m_camera->setFOV(m_fov);
    m_camera->setAspectRatio(m_aspect);
    //m_camera->setFarValue(World::getWorld()->getMap()->getCameraFar());
}   // setupCamera

// ----------------------------------------------------------------------------
/** Sets the mode of the camera.
 *  \param mode Mode the camera should be switched to.
 */
void Camera::setMode(Mode mode)
{
/*
    // If we switch from reverse view, move the camera immediately to the
    // correct position.
    if((m_mode==CM_REVERSE && mode==CM_NORMAL) || (m_mode==CM_FALLING && mode==CM_NORMAL))
    {
        Vec3 start_offset(0, 1.6f, -3);
        Vec3 current_position = m_kart->getTrans()(start_offset);
        m_camera->setPosition(  current_position.toIrrVector());
        m_camera->setTarget(m_camera->getPosition());
    }
    if(mode==CM_FINAL)
    {
        if(m_end_cameras.size()>0)
            m_camera->setPosition(m_end_cameras[0].m_position.toIrrVector());
        m_next_end_camera    = m_end_cameras.size()>1 ? 1 : 0;
        m_current_end_camera = 0;
        m_camera->setFOV(m_fov);
        handleEndCamera(0);
    }   // mode==CM_FINAL

    m_mode = CM_NORMAL;
*/
}   // setMode

// ----------------------------------------------------------------------------
/** Returns the current mode of the camera.
 */
Camera::Mode Camera::getMode()
{
    return m_mode;
}

//-----------------------------------------------------------------------------
/** Reset is called when a new race starts. Make sure that the camera
    is aligned neutral, and not like in the previous race
*/
void Camera::reset()
{
    setMode(CM_NORMAL);
    setInitialTransform();

}   // reset

//-----------------------------------------------------------------------------
/** Saves the current kart position as initial starting position for the
 *  camera.
 */
void Camera::setInitialTransform()
{


    m_camera->setPosition(core::vector3df(0.0, 70, 0.01));

    // value before the first frame is rendered
    //m_camera->setTarget(m_camera->getPosition());
    //m_camera->setRotation(core::vector3df(0, 0, 0));
    m_camera->setRotation( core::vector3df( 0.0f, 0.0f, 0.0f ) );
    //m_camera->setFOV(m_fov);

    assert(!isnan(m_camera->getPosition().X));
    assert(!isnan(m_camera->getPosition().Y));
    assert(!isnan(m_camera->getPosition().Z));

}   // setInitialTransform

//-----------------------------------------------------------------------------
/** Moves the camera smoothly from the current camera position (and target)
 *  to the new position and target.
 *  \param wanted_position The position the camera wanted to reach.
 *  \param wanted_target The point the camera wants to point to.
 */
void Camera::smoothMoveCamera(float dt)
{
/*
    Kart *kart = dynamic_cast<Kart*>(m_kart);
    if (kart->isFlying())
    {
        Vec3 vec3 = m_kart->getXYZ() + Vec3(sin(m_kart->getHeading()) * -4.0f, 0.5f, cos(m_kart->getHeading()) * -4.0f);
        m_camera->setTarget(m_kart->getXYZ().toIrrVector());
        m_camera->setPosition(vec3.toIrrVector());
        return;
    }


    core::vector3df current_position  =  m_camera->getPosition();
    // Smoothly interpolate towards the position and target
    const KartProperties *kp = m_kart->getKartProperties();
    float max_increase_with_zipper = kp->getZipperMaxSpeedIncrease();
    float max_speed_without_zipper = kp->getMaxSpeed();
    float current_speed = m_kart->getSpeed();

    const Skidding *ks = m_kart->getSkidding();
    float skid_factor = ks->getVisualSkidRotation();

    float skid_angle = asin(skid_factor);
    float ratio = (current_speed - max_speed_without_zipper) / max_increase_with_zipper;
    ratio = ratio > -0.12f ? ratio : -0.12f;
    float camera_distance = -3 * (0.5f + ratio);// distance of camera from kart in x and z plane
    if (camera_distance > -2.0f) camera_distance = -2.0f;
    Vec3 camera_offset(camera_distance * sin(skid_angle / 2),
                       1.1f * (1 + ratio / 2),
                       camera_distance * cos(skid_angle / 2));// defines how far camera should be from player kart.
    Vec3 m_kart_camera_position_with_offset = m_kart->getTrans()(camera_offset);



    core::vector3df current_target = m_kart->getXYZ().toIrrVector();// next target
    current_target.Y += 0.5f;
    core::vector3df wanted_position = m_kart_camera_position_with_offset.toIrrVector();// new required position of camera

    if ((m_kart->getSpeed() > 5 ) || (m_kart->getSpeed() < 0 ))
    {
        current_position += ((wanted_position - current_position) * dt
                          * (m_kart->getSpeed()>0 ? m_kart->getSpeed()/3 + 1.0f
                                                 : -1.5f * m_kart->getSpeed() + 2.0f));
    }
    else
    {
        current_position += (wanted_position - current_position) * dt * 5;
    }

    // Avoid camera crash: if the speed is negative, the current_position
    // can oscillate between plus and minus, getting bigger and bigger. If
    // this happens often enough, floating point overflow happens (large
    // negative speeds can happen when the kart is tumbling/falling)
    // To avoid this, we just move the camera to the wanted position if
    // the distance becomes too large (see #1356).
    if( (current_position - wanted_position).getLengthSQ() > 100)
    {
        Log::debug("camera", "Resetting camera position to avoid crash");
        current_position = wanted_position;
    }

    if(m_mode!=CM_FALLING)
        m_camera->setPosition(current_position);
    m_camera->setTarget(current_target);//set new target

    assert(!isnan(m_camera->getPosition().X));
    assert(!isnan(m_camera->getPosition().Y));
    assert(!isnan(m_camera->getPosition().Z));

    if (race_manager->getNumLocalPlayers() < 2)
    {
        SFXManager::get()->positionListener(current_position,
                                            current_target - current_position,
                                            Vec3(0,1,0));
    }
*/
}   // smoothMoveCamera

//-----------------------------------------------------------------------------
/** Determine the camera settings for the current frame.
 *  \param above_kart How far above the camera should aim at.
 *  \param cam_angle  Angle above the kart plane for the camera.
 *  \param sideway Sideway movement of the camera.
 *  \param distance Distance from kart.
 */
void Camera::getCameraSettings(float *above_kart, float *cam_angle,
                               float *sideway, float *distance,
                               bool *smoothing)
{
/*
    const KartProperties *kp = m_kart->getKartProperties();

    switch(m_mode)
    {
    case CM_NORMAL:
    case CM_FALLING:
        {
            if(UserConfigParams::m_camera_debug==2)
            {
                *above_kart = 0;
                *cam_angle  = 0;
            }
            else
            {
                *above_kart    = 0.75f;
                *cam_angle     = kp->getCameraForwardUpAngle();
            }
            float steering = m_kart->getSteerPercent()
                           * (1.0f + (m_kart->getSkidding()->getSkidFactor()
                                      - 1.0f)/2.3f );
            // quadratically to dampen small variations (but keep sign)
            float dampened_steer = fabsf(steering) * steering;
            *sideway             = -m_rotation_range*dampened_steer*0.5f;
            *distance            = -m_distance;
            *smoothing           = true;
            break;
        }   // CM_FALLING
    case CM_REVERSE: // Same as CM_NORMAL except it looks backwards
        {
            *above_kart = 0.75f;
            *cam_angle  = kp->getCameraBackwardUpAngle();
            *sideway    = 0;
            *distance   = 2.0f*m_distance;
            *smoothing  = false;
            break;
        }
    case CM_CLOSEUP: // Lower to the ground and closer to the kart
        {
            *above_kart = 0.75f;
            *cam_angle  = 20.0f*DEGREE_TO_RAD;
            *sideway    = m_rotation_range
                        * m_kart->getSteerPercent()
                        * m_kart->getSkidding()->getSkidFactor();
            *distance   = -0.5f*m_distance;
            *smoothing  = false;
            break;
        }
    case CM_LEADER_MODE:
        {
            *above_kart = 0.0f;
            *cam_angle  = 40*DEGREE_TO_RAD;
            *sideway    = 0;
            *distance   = 2.0f*m_distance;
            *smoothing  = true;
            break;
        }
    case CM_FINAL:
    case CM_SIMPLE_REPLAY:
        // TODO: Implement
        break;
    }
*/
}   // getCameraSettings

//-----------------------------------------------------------------------------
/** Called once per time frame to move the camera to the right position.
 *  \param dt Time step.
 */
void Camera::update(float dt)
{
    Log::info("camera","update cam");
    //no update yet

}   // update

// ----------------------------------------------------------------------------
/** Actually sets the camera based on the given parameter.
 *  \param above_kart How far above the camera should aim at.
 *  \param cam_angle  Angle above the kart plane for the camera.
 *  \param sideway Sideway movement of the camera.
 *  \param distance Distance from kart.
*/
void Camera::positionCamera(float dt, float above_kart, float cam_angle,
                           float side_way, float distance, float smoothing)
{
    //no positioning yet

}   // positionCamera

// ----------------------------------------------------------------------------
/** This function handles the end camera. It adjusts the camera position
 *  according to the current camera type, and checks if a switch to the
 *  next camera should be made.
 *  \param dt Time step size.
*/


// ----------------------------------------------------------------------------
/** Sets viewport etc. for this camera. Called from irr_driver just before
 *  rendering the view for this kart.
 */
void Camera::activate(bool alsoActivateInIrrlicht)
{
    s_active_camera = this;
    //if (alsoActivateInIrrlicht)
    //{
        irr::scene::ISceneManager *sm = irr_driver->getSceneManager();
        sm->setActiveCamera(m_camera);
        irr_driver->getVideoDriver()->setViewPort(m_viewport);
    //}
}   // activate

// ----------------------------------------------------------------------------
/** Sets the angular velocity for this camera. */
void Camera::setAngularVelocity(float vel)
{
    if (m_smooth)
        m_target_angular_velocity = vel;
    else
        m_angular_velocity = vel;
}   // setAngularVelocity

// ----------------------------------------------------------------------------
/** Returns the current target angular velocity. */
float Camera::getAngularVelocity()
{
    if (m_smooth)
        return m_target_angular_velocity;
    else
        return m_angular_velocity;
}   // getAngularVelocity

// ----------------------------------------------------------------------------
/** Sets the linear velocity for this camera. */
void Camera::setLinearVelocity(core::vector3df vel)
{
    if (m_smooth)
        m_target_velocity = vel;
    else
        m_lin_velocity = vel;
}   // setLinearVelocity

// ----------------------------------------------------------------------------
/** Returns the current linear velocity. */
const core::vector3df &Camera::getLinearVelocity()
{
    if (m_smooth)
        return m_target_velocity;
    else
        return m_lin_velocity;
}   // getLinearVelocity

