#include "ExtendedCamera.h"

ExtendedCamera::ExtendedCamera( String name, SceneManager * sceneMgr, Camera * camera ) {
	m_camera = 0; 		
	m_name = name;
	m_sceneMgr = sceneMgr;

	// Creo la struttura dei nodi per gli spostamenti e l'autotracking
	m_cameraNode = m_sceneMgr->getRootSceneNode()->createChildSceneNode(m_name);
	m_TargetNode = m_sceneMgr->getRootSceneNode()->createChildSceneNode(m_name + "_target");
	m_cameraNode->setAutoTracking (true, m_TargetNode); // Autotracking della direzione della navicella "dove sta guardando la navicella"
	m_cameraNode->setFixedYawAxis (true); // ci vuole o č un casino

	// Se la camera non esiste gia, creala
	if (camera == 0) {
		mCamera = m_sceneMgr->createCamera (m_name);
		mOwnCamera = true;
	}
	else {
		mCamera = camera;
        mCamera->setPosition( 0.0, 0.0, 80.0 ); // Spostiamo un poco pių indietro la camera
		mOwnCamera = false;
	}
	
	m_cameraNode->attachObject(mCamera);

	// rigidita di default, per ora e' 0.09f
	m_tightness = 0.09f;
}

ExtendedCamera::~ExtendedCamera() {
	m_cameraNode->detachAllObjects ();
	if (mOwnCamera) delete mCamera;
	m_sceneMgr->destroySceneNode (m_name);
	m_sceneMgr->destroySceneNode (m_name + "_target");
}

void ExtendedCamera::setTightness(Real tightness) 
{
	m_tightness = tightness;
}

Real ExtendedCamera::getTightness() 
{
	return m_tightness;
}

Vector3 ExtendedCamera::getCameraPosition() 
{
	return m_cameraNode->getPosition();
}

void ExtendedCamera::instantUpdate(Vector3 cameraPosition, Vector3 targetPosition) {
	m_cameraNode->setPosition(cameraPosition);
	m_TargetNode->setPosition(targetPosition);
}

bool ExtendedCamera::update(Real elapsedTime, Vector3 cameraPosition, Vector3 targetPosition) {
	
	// Gestisco i movimenti della camera con il vettore di disposizione "ideale"
	Vector3 displacement;

	displacement = (cameraPosition - m_cameraNode->getPosition ()) * m_tightness;
	m_cameraNode->translate (displacement);

	displacement = (targetPosition - m_TargetNode->getPosition ()) * m_tightness;
	m_TargetNode->translate (displacement);

	return true;
}