// firstpersoncam.js
/*
Copyright 2008 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Code for a simple quake-style camera.
//
// Notes: This is a very simple camera and intended to be so. The
// camera's altitude is always 0, relative to the surface of the
// earth.
//

//----------------------------------------------------------------------------
// Global Variables
//----------------------------------------------------------------------------

var supressUpdateKluge = false;
var curMover = null;

INITIAL_CAMERA_ALTITUDE = 1.7; // Roughly 6 feet tall
//----------------------------------------------------------------------------
// Utility Functions
//----------------------------------------------------------------------------

// Keep an angle in [-180,180]
function fixAngle(a) {
  while (a < -180) {
    a += 360;
  }
  while (a > 180) {
    a -= 360;
  }
  return a;
}


function moverClass()
{
	// interactiveness
	this.turnLeft = false;
	this.turnRight = false;
	this.tiltUp = false;
	this.tiltDown = false;
	this.rollLeft = false;
	this.rollRight = false;
	this.moveForward = false;
	this.moveBackward = false;
	this.strafeLeft = false;
	this.strafeRight = false;
	this.altitudeUp = false;
	this.altitudeDown = false;

	this.geMover = null;
//	this.updateUI = updateUI;
	// The anchor point is where the camera is situated at. We store
	// the current position in lat, lon, altitude and in cartesian
	// coordinates.
	this.localAnchorLla = [37.79333, -122.40, 2, INITIAL_CAMERA_ALTITUDE];  // San Francisco
	this.localAnchorCartesian = V3.latLonAltToCartesian(this.localAnchorLla);
//	this.cameraAltitude = INITIAL_CAMERA_ALTITUDE;

	// Heading, tilt angle is relative to local frame
	this.headingAngle = 0;
	this.tiltAngle = 90;
	this.rollAngle = 0;
	this.turnSpeed = 60.0; // radians/sec
	this.tiltSpeed = 60.0; // radians/sec
	this.rollSpeed = 60.0; // radians/sec
	this.strafeVelocity = 100;
	this.forwardVelocity = 100;
	this.altitudeVelocity = 100;
	this.shakiness = 0;
	this.shakePos = [0, 0, 0, 0, 0, 0];
	this.shakeVel = [0.1, 0.2, 0.3, .1, .2, .3];
	this.shakeAcc = [0.01, 0.02, 0.03, .01, .02, .03];
	this.altMode = false; //true=absolute aka fly, false=relative or walk/drive(better default picking initial view)
	this.lastMillis = (new Date()).getTime();
}


FirstPersonCam = function (addListener)
{
	var me = this;

	this.geMover = null;
	this.updateUI = updateUI;
/*
	// The anchor point is where the camera is situated at. We store
	// the current position in lat, lon, altitude and in cartesian
	// coordinates.
	this.localAnchorLla = [37.79333, -122.40, 0];  // San Francisco
	this.localAnchorCartesian = V3.latLonAltToCartesian(this.localAnchorLla);
	this.cameraAltitude = INITIAL_CAMERA_ALTITUDE;

	// Heading, tilt angle is relative to local frame
	this.headingAngle = 0;
	this.tiltAngle = 90;
	this.rollAngle = 0;
	this.turnSpeed = 60.0; // radians/sec
	this.tiltSpeed = 60.0; // radians/sec
	this.rollSpeed = 60.0; // radians/sec
	this.strafeVelocity = 100;
	this.forwardVelocity = 100;
	this.altitudeVelocity = 100;
	this.shakiness = 0;
	this.shakePos = [0, 0, 0, 0, 0, 0];
	this.shakeVel = [0.1, 0.2, 0.3, .1, .2, .3];
	this.shakeAcc = [0.01, 0.02, 0.03, .01, .02, .03];
//	this.shakeRot = [0, 0, 0];

	this.altMode = false; //true=absolute aka fly, false=relative or walk/drive(better default picking initial view)
	// Initialize the time
	this.lastMillis = (new Date()).getTime();
	this.listener = null;

	// Updates should be called on frameend to help keep objects in sync.
	// GE does not propogate changes caused by KML objects until an
	// end of frathis.

	if (addListener)
	{
		this.listener = function()
		{
			this.update();
		};
		google.earth.addEventListener(ge, "frameend", this.listener);
	}
*/
	// google.earth.addEventListener(ge, "onkeydown", kmlKeyDown);
//	google.earth.addEventListener(ge, "onkeyup", kmlKeyUp);
};
FirstPersonCam.prototype = new moverClass();


model = function (addListener)
{
	this.url = '';
	this.geMover = null;
	this.updateUI = updateUI;
}
model.prototype = new moverClass();


moverClass.prototype.updateOrientation = function(dt) {
	var me = this;
	sanity();

	// Based on dt and input press, update turn angle.
	if (this.turnLeft || this.turnRight) {
		var turnSpeed = this.turnSpeed; // radians/sec
		if (this.turnLeft)
			turnSpeed *= -1.0;
		this.headingAngle += turnSpeed * dt;
	}

	if (this.tiltUp || this.tiltDown)
	{
		var tiltSpeed = this.tiltSpeed; // radians/sec
		if (this.tiltDown)
			tiltSpeed *= -1.0;
		this.tiltAngle = this.tiltAngle + tiltSpeed * dt;
		// Clamp
		var tiltMax = 180;
		var tiltMin = 0.0;
		if (this.tiltAngle > tiltMax)
			this.tiltAngle = tiltMax;
		if (this.tiltAngle < tiltMin)
			this.tiltAngle = tiltMin;
	}
	if (this.rollLeft || this.rollRight)
	{
		var rollSpeed = this.rollSpeed; // radians/sec
		if (this.rollLeft)
			rollSpeed *= -1.0;
		this.rollAngle = this.rollAngle + rollSpeed * dt;
		// Clamp
		var rollMax = 90.0;
		var rollMin = -90.0;
		if (this.rollAngle > rollMax)
			this.rollAngle = rollMax;
		if (this.rollAngle < rollMin)
			this.rollAngle = rollMin;
	}

	if (this.shakiness > 0)
	{
		this.headingAngle += this.shakeVel[3] * dt;
		this.tiltAngle += this.shakeVel[4] * dt;
		this.rollAngle += this.shakeVel[5] * dt;
		for (var i=3; i < 6; i++)
		{
			this.shakePos[i] += this.shakeVel[i] * dt;
			if (this.shakePos[i] > (this.shakiness * 3))
				 this.shakeVel[i] = Math.random() * this.shakiness  * -4;
			if (this.shakePos[i] < (this.shakiness * -3))
				 this.shakeVel[i] = Math.random() * this.shakiness * 4;
		}
//		for (var i=3; i < 6; i++)
//			this.shakeVel[i] += this.shakeAcc[i];

	}
	sanity();
};

moverClass.prototype.updatePosition = function(dt)
{
	sanity();
	var me = this;

	// Convert local lat/lon to a global matrix. The up vector is
	// vector = position - center of earth. And the right vector is a vector
	// pointing eastwards and the facing vector is pointing towards north.
/*
	if (this.localAnchorLla[0] == NaN || this.localAnchorLla[1] == NaN || this.localAnchorLla[2] == NaN || this.cameraAltitude == NaN ||
		this.localAnchorLla[0] == undefined || this.localAnchorLla[1] == undefined || this.localAnchorLla[2] == undefined || this.cameraAltitude == undefined)
	{
		this.localAnchorLla = [37.79333, -122.40, 0];  // San Francisco
		this.localAnchorCartesian = V3.latLonAltToCartesian(this.localAnchorLla);
		this.cameraAltitude = 0;
	}
*/
	var localToGlobalFrame = M33.makeLocalToGlobalFrame(this.localAnchorLla);

	// Move in heading direction by rotating the facing vector around
	// the up vector, in the angle specified by the heading angle.
	// Strafing is similar, except it's aligned towards the right vec.
	var headingVec = V3.rotate(localToGlobalFrame[1], localToGlobalFrame[2],
	                         -this.headingAngle * Math.PI / 180);
	var rightVec = V3.rotate(localToGlobalFrame[0], localToGlobalFrame[2],
	                         -this.headingAngle * Math.PI / 180);
	// Calculate strafe/forwards
	var strafe = 0;
	if (this.strafeLeft || this.strafeRight)
	{
		var strafeVelocity = this.strafeVelocity;
		if (this.strafeLeft)
			strafeVelocity *= -1;
		strafe = strafeVelocity * dt;
	}
	var forward = 0;
	if (this.moveForward || this.moveBackward)
	{
		var forwardVelocity = this.forwardVelocity;
		if (this.moveBackward)
			forwardVelocity *= -1;
		forward = forwardVelocity * dt;
	}
	if (this.altitudeUp || this.altitudeDown)
	{
		var altitudeVelocity = this.altitudeVelocity;
		if (this.altitudeDown)
			altitudeVelocity *= -1.0;
//		this.cameraAltitude += altitudeVelocity * dt;
		this.localAnchorLla[2] += altitudeVelocity * dt;
	}

	if (this.shakiness > 0)
	{
		strafe += this.shakeVel[0] * dt;
		forward += this.shakeVel[1] * dt;
//		this.cameraAltitude += this.shakeVel[2] * dt;
		this.localAnchorLla[2] += this.shakeVel[2] * dt;
		for (var i=0; i < 3; i++)
		{
			this.shakePos[i] += this.shakeVel[i] * dt;
			if (this.shakePos[i] > this.shakiness/3)
				 this.shakeVel[i] = Math.random() * this.shakiness  * -4;
			if (this.shakePos[i] < (-this.shakiness/3))
				 this.shakeVel[i] = Math.random() * this.shakiness  * 4;
		}
//		for (var i=0; i < 3; i++)
//			this.shakeVel[i] += this.shakeAcc[i];

	}

	// Add the change in position due to forward velocity and strafe velocity
	this.localAnchorCartesian = V3.add(this.localAnchorCartesian,
	                               V3.scale(rightVec, strafe));
	this.localAnchorCartesian = V3.add(this.localAnchorCartesian,
                                   V3.scale(headingVec, forward));
	var a = this.localAnchorLla[2];
	// Convert cartesian to Lat Lon Altitude for camera setup later on.
	this.localAnchorLla = V3.cartesianToLatLonAlt(this.localAnchorCartesian);
	this.localAnchorLla[2] = a;
	sanity();
};

moverClass.prototype.update = function()
{
	if (!catchKeys)
		return;
	sanity();
	var me = this;

	ge.getWindow().blur();

	// Update delta time (dt in seconds)
	var now = (new Date()).getTime();
	var dt = (now - this.lastMillis) / 1000.0;
//	if (dt > 0.25)
//		dt = 0.25;
	if (this.playback)
	{
		var dtfrac = dt / this.duration;
		// this.lastMillis set to time at start of span

		// Update orientation and then position  of camera based
		//  from/to
		// NOTE: precompute as much of this as possible
		for (var i=0; i < 6; i++)
			this.dist[i] = to[i] - from[i];

		for (var i=0; i < 6; i++)
			this.cupos[i] = dist[i] * dtfrac + from[i];

		for (var i=0; i < 3; i++)
			this.localAnchorLla[i] = this.curpos[i];

		this.headingAngle = dist[3] * dtfrac + from[3];
		this.tiltAngle = dist[4] * dtfrac + from[4];
		this.rollAngle = dist[5] * dtfrac + from[5];
	}
	else
	{
		this.lastMillis = now;

		// Update orientation and then position  of camera based
		// on user input
		this.updateOrientation(dt);
		this.updatePosition(dt);
	}
//	sanity();
	this.updateGE();
	if (this.updateUI)
		this.updateUI();
//	sanity();
}

FirstPersonCam.prototype.updateGE = function()
{
//	sanity();
	var me = this;

	var lla = this.localAnchorLla;
//	if (!me.geMover)
//		me.geMover = ge.createCamera('');
	var la = ge.createCamera('');
	la.set(this.localAnchorLla[0], this.localAnchorLla[1],
			this.localAnchorLla[2],
//			this.cameraAltitude,
			this.altMode ? ge.ALTITUDE_ABSOLUTE : ge.ALTITUDE_RELATIVE_TO_GROUND,
			fixAngle(this.headingAngle), /* heading */
			this.tiltAngle, /* tilt */
			this.rollAngle /* roll */
         );
	ge.getView().setAbstractView(la);
//	sanity();
};

model.prototype.updateGE = function()
{
	sanity();
	var me = this;
	if (!me.geMover)
		return;
	var lla = this.localAnchorLla;
	me.location.setLatLngAlt (lla[0],lla[1],lla[2]);
//	me.location.setLatLngAlt (lla[0],lla[1],this.cameraAltitude);

	me.geMover.setAltitudeMode(ge.ALTITUDE_RELATIVE_TO_GROUND);
	me.orientation.setHeading(me.headingAngle);
	me.orientation.setTilt(me.tiltAngle);
	me.orientation.setRoll(me.rollAngle);
	me.geMover.setOrientation(me.orientation);
	sanity();

};

