/*****************************
File:      StickyDynamic.cpp
Language:   C++ (header)
Project:    H3DNetworkingUtils
The contents of this file are subject to the Mozilla Public License
Version 1.1 (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.mozilla.org/MPL/

Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.

The Original Code is H3DNetworkingUtils v1.0.

The Initial Developer of the Original Code is CSIRO.
Portions created by the Initial Developer are Copyright (C) 1009 CSIRO. All Rights Reserved.
Contributor(s):
    Chris Gunn  <Chris.Gunn@csiro.au> <ChrisJGunn@gmail.com>
***************************/

#include "H3DNetworkingUtils/StickyDynamic.h"
#include <H3DUtil/H3DBasicTypes.h>

using namespace H3D;
using namespace H3DUtil;
using namespace H3DNetworkingUtils;

// -----------------------------------------------------------------------------
H3DNodeDatabase StickyDynamic::database(
  "StickyDynamic", 
  &(newInstance<StickyDynamic>),
  typeid(StickyDynamic),
  &Dynamic::database);

namespace StickyDynamicInternals {
  FIELDDB_ELEMENT( StickyDynamic, locked, INPUT_OUTPUT );
  FIELDDB_ELEMENT( StickyDynamic, startForce, INPUT_OUTPUT );
  FIELDDB_ELEMENT( StickyDynamic, slideForce, INPUT_OUTPUT );
  FIELDDB_ELEMENT( StickyDynamic, friction, INPUT_OUTPUT );
  FIELDDB_ELEMENT( StickyDynamic, stopDelay, INPUT_OUTPUT );
}

// -----------------------------------------------------------------------------
StickyDynamic::StickyDynamic(Inst<SFBool> _locked,
                             Inst<SFFloat> _startForce,
                             Inst<SFFloat> _slideForce,
                             Inst<SFFloat> _friction,
                             Inst<SFTime> _stopDelay):
locked(_locked),
startForce(_startForce),
slideForce(_slideForce),
friction(_friction),
friction_force(new FrictionForce),
stopDelay (_stopDelay),
stopped (false) {
 
   type_name = "StickyDynamic";
   database.initFields( this );

   locked->setValue(false);
   startForce->setValue(40.0f);
   slideForce->setValue(0.05f);
   friction->setValue(50.0f);
	stopDelay->setValue(0.2);
   
   friction->route(friction_force);
   velocity->route(friction_force);
   
   friction_force->route(externalForces);
}

// -----------------------------------------------------------------------------
void StickyDynamic::traverseSG(TraverseInfo & ti){
   // let the parent class move the dynamic
   Dynamic::traverseSG(ti);

   bool stop_it = false;
   
   if (locked->getValue()) {
      stop_it = true;
		stopped = false;
   } else {
      Vec3f vel = velocity->getValue();
      H3DFloat velocity_mag = vel.length();
      
      bool sliding = velocity_mag > H3DUtil::Constants::f_epsilon;


      Vec3f haptic_force = force->getValue();
      H3DFloat hap_force_mag = haptic_force.length();
      
      // We need to make sure that it is really stopped - not just a momentary pause.
		// If we don't do this, movement can be jerky.
		H3DTime now = Scene::time->getValue();
		if (!sliding && (hap_force_mag > 0.0f) && (hap_force_mag < startForce->getValue())) {
			if (!stopped) {
				stop_time = now;
				stopped = true;
			}
      } else if (sliding && (hap_force_mag < slideForce->getValue())) {
			if (!stopped) {
				stop_time = now;
				stopped = true;
			}
		} else {
			stopped = false;
		}
   }
	if (stopped) {
		H3D::H3DTime delta_t = Scene::time->getValue() - stop_time;
		if (delta_t > stopDelay->getValue()) {
			stop_it = true;
		}
	}

   if (stop_it) {
      stopIt();
   } 
}

// -----------------------------------------------------------------------------
void StickyDynamic::FrictionForce::update() {
   SFFloat * friction = static_cast<SFFloat*>(routes_in[0]);
   SFVec3f * velocity = static_cast<SFVec3f*>(routes_in[1]);
   value = (-1.0 * friction->getValue()) * velocity->getValue();
}

// -----------------------------------------------------------------------------
void StickyDynamic::stopIt() {
   Vec3f prev_force;
   prev_force = force->getValue();
   force->setValue(Vec3f(0,0,0), id);
   momentum->setValue(Vec3f(0,0,0));
   velocity->setValue(Vec3f(0,0,0), id); 
   ///force->setValue(prev_force, id);  ??
}