//********************************************
// Looping path shape
//********************************************


// this is an example of how to trigger the pathshape to move. you can do it
// anyway you like, i simply decided to trigger it's movement on a collision, so a jump on it
// may be required to make it "go"
// The state must be set to make it function. "forward" "back" or "stopped" are the three
// states a pathshape can be in.

datablock PathShapeData(LoopingShape)
{
//This is the Path this shape will follow
// It's best to assign this in script or in the mission editor after it's been created
// in the oncollision, it will look for this path
   Path="";
   emap = true;
   category = "Pathshapes";

   // put path to your shape here!!
   shapefile = "~/data/shapes/platform/platform.dts";
   mode = "";
};

function LoopingShape::onCollision(%this,%obj,%col){
    error("A collsion with a loopingshape has occurred");
	%state = %obj.getstate();
	if (%state == 2)  // 2 == stopped.
	{
		%obj.setState("forward");
		%obj.followpath(%obj.Path);
	}
}

function LoopingShape::onAdd(%this,%obj)
{
   // do whatever you want with that shape, e.g. play animations:
}

function LoopingShape::onNode(%this,%theshape,%node) {
   echo("PathShape::onNode(" @ %this @ "," SPC %theshape @ "," SPC %node@")");
   if(%theshape.path.isLooping && (%node == %theshape.loopNode)) {
       echo("At end of path, setting position back to starting node.");
	   %theshape.setPosition(0);
   }

}

function PathShape::followPath(%this,%path) {
   echo("PathShape::followPath(" @ %this @ "," SPC %path @")");

   %this.path = %path;
   if (!(%this.speed = %path.speed))
      %this.speed = 1;

   if (%path.isLooping) {
      %this.loopNode = %path.getCount();  
   } else {
      %this.loopNode = -1;
   }

   echo("PathShape::followPath() loopNode == ", %this.loopNode);
   
   %this.pushPath(%path);   
   %this.popFront(); // This pop removes initial DUMMY node.
}

function PathShape::pushPath(%this,%path) {
   echo("PathShape::pushPath(" @ %this @ "," SPC %path @")");
   for (%i = 0; %i < %path.getCount(); %i++) {
      %this.pushNode(%path.getObject(%i));
   }
   // If looping, push the starting node on to end to make this a loop
   if(%this.path.isLooping) {
       %this.pushNode(%path.getObject(0));
   }
}
function PathShape::pushNode(%this,%node)
{
   if (!(%speed = %node.speed))
      %speed = %this.speed;
   if ((%type = %node.type) $= "")
      %type = "Normal";
   if ((%smoothing = %node.smoothing) $= "")
      %smoothing = "Linear";
   %this.pushBack(%node.getTransform(),%speed,%type,%smoothing);
}

function makeMover(%path)
{
    %a = new PathShape() {
    dataBlock = LoopingShape;
    // set position to whatever suits your needs
    position = "85.46 -216.34 0.02";
    };
    // give it a path to follow:
    %a.followPath("MissionGroup/"@ %path);
    // cleanup
    movers.add(%a);
}