/*****************************
File:      Hinge.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/Hinge.h"
#include "H3D/H3DHapticsDevice.h"
#include "H3D/X3DGeometryNode.h"
#include "H3D/X3DShapeNode.h"
#include "H3D/Inline.h"

using namespace H3D;
using namespace H3DNetworkingUtils;

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

namespace HingeInternals {   
  FIELDDB_ELEMENT( Dynamic, linearDamping, INPUT_OUTPUT );
  FIELDDB_ELEMENT( Dynamic, rotationalDamping, INPUT_OUTPUT );
  FIELDDB_ELEMENT( Dynamic, contactForces, OUTPUT_ONLY );
  FIELDDB_ELEMENT( Dynamic, contactTorques, OUTPUT_ONLY );
  FIELDDB_ELEMENT( Dynamic, totalContactForce, OUTPUT_ONLY );
  FIELDDB_ELEMENT( Dynamic, totalContactTorque, OUTPUT_ONLY );
  FIELDDB_ELEMENT( Dynamic, externalForces, INPUT_OUTPUT );
  FIELDDB_ELEMENT( Dynamic, externalTorques, INPUT_OUTPUT );
  FIELDDB_ELEMENT( Dynamic, linearSpringStiffness, INPUT_OUTPUT );
  FIELDDB_ELEMENT( Dynamic, angularSpringStiffness, INPUT_OUTPUT );
  FIELDDB_ELEMENT( Hinge, maxAngle, INPUT_OUTPUT );
  FIELDDB_ELEMENT( Dynamic, globalPosition, OUTPUT_ONLY );
}

// -------------------------------------------------
Hinge::Hinge( Inst< AddChildren        > _addChildren,
                  Inst< RemoveChildren     > _removeChildren,
                  Inst< MFChild            > _children,
                  Inst< SFNode             > _metadata,
                  Inst< SFBound            > _bound,  
                  Inst< SFVec3f            > _bboxCenter,
                  Inst< SFVec3f            > _bboxSize,
                  Inst< SFTransformedBound > _transformedBound,
                  Inst< SFMatrix4f         > _matrix,
                  Inst< SFMatrix4f         > _accumulatedForward,
                  Inst< SFMatrix4f         > _accumulatedInverse,
                  Inst< SFVec3f            > _position,
                  Inst< SFRotation         > _orientation,
                  Inst< SFVelocity         > _velocity,
                  Inst< SFVec3f            > _momentum,
                  Inst< SFVec3f            > _force,
                  Inst< SFAngularVelocity  > _angularVelocity,
                  Inst< SFVec3f            > _angularMomentum,
                  Inst< SFSpin             > _spin,
                  Inst< SFVec3f            > _torque,
                  Inst< SFFloat            > _mass,
                  Inst< SFMatrix3f         > _inertiaTensor,
                  Inst< SFMotion           > _motion,
                  Inst<MFVec3f>         _contactForces,
                  Inst<MFVec3f>         _contactTorques,
                  Inst<SumMFVec3f>      _totalContactForce,
                  Inst<SumMFVec3f>      _totalContactTorque,
                  Inst<SumForces>       _externalForces,
                  Inst<SumTorques>      _externalTorques,
                  Inst<SFVec3f>         _freedom,
                  Inst<SFVec3f>         _angularFreedom,
                  Inst<SFFloat>         _linearDamping,
                  Inst<SFFloat>         _rotationalDamping,
                  Inst<SFFloat>         _linearSpringStiffness,
                  Inst<SFFloat>         _angularSpringStiffness,
                  Inst<SFVec3f>         _globalPosition,
                  Inst<SFFloat>         _maxAngle) :
Dynamic(_addChildren, _removeChildren, _children, _metadata, _bound, _bboxCenter, _bboxSize,
                 _transformedBound, _matrix, _accumulatedForward, _accumulatedInverse, _position,
                 _orientation, _velocity, _momentum, _force, _angularVelocity, _angularMomentum,
                 _spin, _torque, _mass, _inertiaTensor, _motion,
                 _contactForces, _contactTorques, _totalContactForce, _totalContactTorque, _externalForces, _externalTorques,
                 _freedom, _angularFreedom, _linearDamping, _rotationalDamping, _linearSpringStiffness,
                 _angularSpringStiffness, _globalPosition),
maxAngle  (_maxAngle),
axis_flipped (false) {
   
   type_name = "Hinge";
   database.initFields( this );

   maxAngle->setValue(0);
   orientation->setValue(Rotation(1, 0, 0, 0));
   angularFreedom->setValue(Vec3f(1, 0, 0));
}

// -------------------------------------------------
void Hinge::initialize() {
   Rotation rot = orientation->getValue();
   rot.axis = Vec3f(1, 0, 0);
   orientation->setValue(rot);
   angularFreedom->setValue(Vec3f(1, 0, 0));
   Dynamic::initialize();
   prev_rot = rot;
}

// ---------------------------------
void Hinge::traverseSG(TraverseInfo & ti) {
   Dynamic::traverseSG(ti);
   Rotation rot = orientation->getValue();

   H3DFloat angle = rot.angle;
   bool changed = false;
   if (rot.axis.x == -prev_rot.axis.x) {
      axis_flipped = !axis_flipped;
   }
   if (axis_flipped) {
      angle = -angle;
   }
   if (angle > maxAngle->getValue()) {
      angle = maxAngle->getValue();
      changed = true;
   } else if (angle < 0) {
      angle = 0;
      changed = true;
   }
   if (changed) {
      if (axis_flipped) {
         rot.angle = -angle;
      } else {
         rot.angle = angle;
      }
      orientation->setValue(rot);
      torque->setValue(Vec3f(0,0,0));
      angularMomentum->setValue(Vec3f(0,0,0));
   }

   prev_rot = rot;

}

