/*------------------------------------------------------------------------ 
 * Copyright 2007-2008 (c) Dmitri Sviridov, cast3d.com.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *------------------------------------------------------------------------ */
 
	/**
	 *
	 * @author		Dmitri Sviridov - sds
	 * @version		.97
	 * @date 		NOvember, 20 2008
	 */
 
package {
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.*;
	import flash.utils.getTimer;
    import flash.utils.Timer;
    import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFieldType;
	import flash.display.MovieClip;
    import flash.net.URLRequest;
 
    // Cast3D dependencies
	import cast3d.core.Cast3d;
	import cast3d.core.events.LoadEvent;
	import cast3d.loader.Xc3Loader;
	import cast3d.utils.controls.*;
	import cast3d.utils.manipulators.Manipulator;
	import cast3d.utils.manipulators.ppv2.TrackBall;
	import cast3d.utils.controllers.NavigationController;
	import cast3d.utils.controllers.Positioner;
	import cast3d.nodes.Node3d;
	import cast3d.tracks.Track3d;
	import cast3d.frames.KeyFrame3d;
 
    // Papervision3d dependencies
	import org.papervision3d.scenes.Scene3D;
 
	// Import Papervision3D
	import org.papervision3d.cameras.*;
	import org.papervision3d.scenes.*;
 
	import org.papervision3d.cameras.*;
	import org.papervision3d.scenes.*;
	import org.papervision3d.lights.*;
	import org.papervision3d.render.*;
	import org.papervision3d.view.*;
	import org.papervision3d.materials.*;
	import org.papervision3d.core.proto.MaterialObject3D;	
 
 
	[SWF(backgroundColor="#335566", frameRate="30")]
 
	public class Sample extends Sprite
	{
		private var manipulator:TrackBall;
		private var animator:Cast3d;
		private var cp:ControlPanel;
 
		private var scene:Scene3D;
	        private var camera:Camera3D; 		    	
		private var viewport:Viewport3D;
		private var renderer:BasicRenderEngine;
 
		private var loader:Xc3Loader; 
		private var loaded:Boolean; 
 
		private var statusText:TextField; 
		private var statusTimer:Timer;
 
	       private var _navigations:Array =  new Array;
	       private var _current_nav:int = 0;
 
		public function Sample()
		{
 			setup3DScene();
			setupStage();			      
		}
 
		/**
		 * Configures the Stage object
		 */
		private function setupStage(): void
		{
			this.stage.scaleMode = StageScaleMode.NO_SCALE;
			this.stage.align = StageAlign.TOP_LEFT;
		}
 
		private function setup3DScene(): void
		{
			this.setupPpv3D();
			this.setupCast3D();
			this.setupControls();
			this.loadData();
 
			this.addEventListener(Event.ENTER_FRAME, this.handleEnterFrame);
			this.stage.addEventListener(MouseEvent.DOUBLE_CLICK, this.mouseDblClick);
		}
 
  		/**
		 * initial setup for Papervision3D.
		 */		
		public function setupPpv3D(): void
		{		
			this.viewport = new Viewport3D(300, 400, true, false,false,false);
	        addChild( viewport );
 
			this.scene = new Scene3D();
			this.camera = new Camera3D();			
			this.renderer = new BasicRenderEngine();			
		}
 
  		/**
		 * initial setup for Cast3D.
		 */		
		public function setupCast3D(): void
		{		
            this.loaded = false;
			this.animator = new Cast3d(this.scene, this.camera);
			this.animator.animationType = Cast3d.ANIMATION_TYPE_BYFRAME; //  ANIMATION_TYPE_REAL; //
			this.animator.animationStyle = Cast3d.ANIMATION_STYLE_FORWARD;
			Cast3d.fps = 22;
			this.animator.autoRewind = true;						
		}
 
  		/**
		 *  Function setups visual animation control panel.
		 */		
		public function setupControls(): void
		{		
			cp = new ControlPanel(animator);
			this.stage.addChild(cp);
//			cp.visible = false;	
 
			statusText = new TextField();
			statusText.textColor = 0x0000ff;
            statusText.autoSize = TextFieldAutoSize.LEFT; 
            statusText.type = TextFieldType.DYNAMIC;
            statusText.y = cp.height;
            this.stage.addChild(statusText);
		}
 
  		/**
		 *  Function performs 3D data  load from a X3c file.
		 */				
		private function loadData(): void
		{
			var modelpath:String = loaderInfo.parameters.model;
			var rpath:String = loaderInfo.parameters.rpath;
 
			this.loader = new Xc3Loader( modelpath ? modelpath:  "");
			this.loader.resourcePath = rpath ? rpath : "";
            if (!modelpath || modelpath.length == 0)
            {            
				this.loader = new Xc3Loader("../../cast3d/as3/samples/models/walk/fc_b.zc3");
				this.loader.resourcePath = "../../cast3d/as3/samples/models/walk";
            }
 
			statusText.text = "loading file: " + loader.sourceURL; 
			statusTimer = new Timer(1000, 0.2);
			// designates listeners for the interval and completion events
			statusTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);				 
			statusTimer.start();			
 
			this.loader.preCalcMotion = false;
			this.loader.addEventListener(LoadEvent.LOAD_COMPLETE, this.cast3dLoadComplete);
			this.loader.addEventListener(LoadEvent.LOAD_ERROR, this.cast3dLoadError);
			this.loader.addEventListener(LoadEvent.LOAD_PROGRESS, this.cast3dLoadProgress);
 
			/** Set Call back functions to modify, augumnet or subsitute
			 *  material or/and geometry data. */
 
//			this.loader.portLoader.onCreateAssetMaterial = onAssetMaterial;
 
			this.loader.load(this.animator.source);	
		}
 
		/**
		 * Overwrite material
		 */		
 		private function onAssetMaterial ( name:String, material:BitmapMaterial):MaterialObject3D
		{					
            return new WireframeMaterial(0x00FF00,1);
        }
 
		/**
		 * Timer handler
		 */		
       private function onTimerComplete(event:TimerEvent):void
       {
            trace("Time's Up!");
			statusText.textColor = 0xff0000;
            statusText.text = "Loading time exceeded 20 nimutes!"; 
            removeTimer();       	        	            
       }
 
		/**
		 * At the end of load, removes timer
		 */		
       private function removeTimer():void 
        {
           	statusTimer.stop();
 	   		statusTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,onTimerComplete);
    	}
 
		/**
		 * Handles the ENTER_FRAME event and updates the 3D scene.
		 */
		private function handleEnterFrame(event: Event): void
		{					
            if (!this.loaded) return;
 
			var time:Number = getTimer();	
 
			// Update cast3D first		
			this.animator.render();
 
			// then render scene 	
			this.renderer.renderScene(scene, camera, viewport);
 
			// Update stat data					
			if (this.animator.source && cp)
			{
				var frame:int = this.animator.source.currentFrame; 
				var kframe:int = this.animator.source.currentKeyFrame; 
				cp.setCurrentFrame(kframe,frame);
				cp.setCurrentTime(animator.currentTime);
				cp.currentFps = 1000.0/(getTimer() - time);
				if (this.manipulator) manipulator.update();
			}			
		}
 
		/**
		 * Handles the load complete event
		 */		
private var loadcount:int = 0;
 
		private function cast3dLoadComplete(event: LoadEvent): void
		{
			if (loadcount == 0 )
			{							
				trace("cast3dLoadComplete "); 
				this.manipulator = new TrackBall(this.animator,this.stage,
										 this.viewport.viewportWidth, this.viewport.viewportHeight,
										 Manipulator.Y_UP,
										 Manipulator.X_S,Manipulator.Z_S,Manipulator.NY_S
										 );
 
				cp.manipulator = this.manipulator;
				this.animator.play();								
				setupNavigator();	
			}
 
			if ( this.loader.sourceURL == "/demos/models/walkload/pawn.zc3" )
			{				
				positionNode("Circle", {x: 0, y:4, z:17}, null);
			}
 
			if ( this.loader.sourceURL == "/demos/models/walkload/bunny.zc3")
			{
				positionNode("Bunny",{x:-20, y:-17, z:-15}, null);
			}							
 
            removeTimer();       	        	            
			loadcount++;
            if (loader.loaderror.length)
            {
	 			statusText.textColor = 0xff0000;       	        	            
				statusText.text = loader.loaderror;            
            }
            else
            {       	        	            
		   		statusText.visible = false;
            }
 
	        this.loaded = true;				
			this.loader = null;
		}
 
		private function cast3dLoadProgress(event: LoadEvent): void
		{
            var n:Number = event.scenesTotal != 0.0 ? event.scenesLoaded/event.scenesTotal : 0;
            var percent:int = n*100;
 			statusText.text = "Loading " + event.file + " ....... "+ percent.toString() + "%";
		}		
 
		/**
		 * Handles the load Error event
		 */		
		private function cast3dLoadError(event: LoadEvent): void
		{
			trace("cast3dLoadError ", event.message );
            removeTimer();
   			statusText.textColor = 0xff0000;       	        	            
			statusText.text = event.message;
	        this.loaded = true;				
			this.loader = null;
		}				
 
		/**
		 * Sets up Navigation Controller for Character node
		 */			    
      private function setupNavigator():void
       {
        	// First lets find the root node of a character
       	    // we know by looking at source file,  its Id is 'Cube'
      	    var nodename:String = "Cube";
	        var node:Node3d = this.animator.source.find(nodename) as Node3d;
	        if (!node)
	        {
		   		statusText.visible = true;
	        	statusText.text = "Failed to set Navigation control for node: " + nodename;
	            return;
	        }
 
	        // Attach camera to character node
       	    var camnodename:String = "Camera";
	        var camnode:Node3d = this.animator.source.find(camnodename) as Node3d;
	        if (camnode)
	        {	        	        	
	        	var parentnode:Node3d = camnode.parent;
	        	if (parentnode)
	        	{
			    	var node_idx:int = parentnode.children.indexOf(camnode);
					if ( node_idx != -1) parentnode.children.splice(node_idx,1);
	        	}
	        	else
	        	{
		       	    var kfname:String = "Scene_kf";
		 	        var kf:KeyFrame3d = this.animator.source.find(kfname) as KeyFrame3d;
			        if (kf)
			        {
				    	node_idx = kf.nodes.indexOf(camnode);
						if ( node_idx != -1) kf.nodes.splice(node_idx,1);
			        }
			    }		    
//	        	camnode.tracks.splice(0,camnode.tracks.length);	
	        	node.children.push(camnode);
	        }	        	
 
           // create navigation conrloller fo this node.
	        var nc:NavigationController = new NavigationController(node,"navigator");
	        _navigations.push(nc); 
 
           // We know that "Cube" node actually represents Skinned geometry, which means
           // the motion is controlled by another skeleton node(s), in this case "lowerBack" node is
           // root skeleton node( see source file)
	        nodename = "lowerBack";
	        node = this.animator.source.find(nodename) as Node3d;
	        if (!node)
	        {
		   		statusText.visible = true;
	        	statusText.text = "Failed to set Navigation control for node: " + nodename;
	            return;
	        }
 
	        var tarck_id:String;
	        var motionAlias:String;
 
	        // now we add a 'walking' motion which is represented by MotionGroup class instance with id == "lowerBack_motion"
	        // again, we know that by looking at source file.
	        // Notice that 'motion' is produced by different node that we created nvigation controlled, which in that case "cube"
	        tarck_id = "lowerBack_motion311";
	        motionAlias = "walk";	        
	        if (!nc.addMotion(node, tarck_id, motionAlias))
	        {
		   		statusText.visible = true;
	        	statusText.text = "Failed to add Motion " + motionAlias + " for track: " + tarck_id;
	            return;
	        }
 
	        // another motion
	        motionAlias = "jump";
	        tarck_id = "lowerBack_motionjump";
	        if (!nc.addMotion(node, tarck_id, motionAlias))
	        {
		   		statusText.visible = true;
	        	statusText.text = "Failed to add Motion " + motionAlias + " for track: " + tarck_id;
	            return;
	        }
	        nc.position.x -= 5.0; 
	        nc.rotation.x = 0; nc.rotation.y = 0; nc.rotation.z = 1; nc.rotation.w = 30 * Math.PI/180.0 ; 
 
		    this.stage.addEventListener(KeyboardEvent.KEY_DOWN, this.keyDownHandler);
       }
 
		public function keyDownHandler( event :KeyboardEvent ):void
		{
	       var nc:NavigationController = _navigations[_current_nav];
	       if (!nc) return;
 
           trace(event.target + "(" + event.currentTarget + "): " + event.keyCode + "/" + event.charCode);
			switch( event.keyCode )
			{
				case 9: // TAB	
					_current_nav++;		    
	        		if (_current_nav >= _navigations.length) _current_nav = 0;
					break;	
 
				case 37: // left	
 
				   // start walking motion ant rotate  model over 1/4 of motion cycle ( which is one step)
				   // in local coordinates by 30 degree rotation about Z
	        		nc.run("walk",0.25, null, { x:0, y:0, z:1, w: 30.0*Math.PI/180.0 });
					break;	
 
				case 38: // up
 
				   // start walking motion by moving model over 1/4 of motion cycle ( which is one step)
				   // and propogation node forward in local coordinates by Y = -0.33
	        		nc.run("walk",.25,{x:0, y:-1.0, z:0});
					break;	
 
				case 39: // right
 
				   // start walking motion ant rotate  model over 1/4 of motion cycle ( which is one step)
				   // in local coordinates by 30 degree rotation about -Z
	        		nc.run("walk",.25, null, {x:0, y:0, z:-1, w:30.0*Math.PI/180.0 });
					break;	
 
				case 40: // down
 
				   // start walking motion by moving model over 1/4 of motion cycle ( which is one step)
				   // and propogation node backwards in local coordinates by Y = 0.33
				   // also we reverse timing (last argument) for that motion so characted walks backwards.
	        		nc.run("walk",.25,{x:0, y:1.0, z:0}, null, true);
					break;	
 
				case 32: // space
 
	        		nc.run("jump",1.0);
					break;	
			}
		}
 
		/**
		 * mouse DblClick handler
		 */		
 		public function mouseDblClick(event: MouseEvent): void
		{
			if ( this.loader  || loadcount == 0 || loadcount > 2) return;
			if ( loadcount == 1)
			{			
				this.loader = new Xc3Loader("/demos/models/walkload/pawn.zc3");
				this.loader.resourcePath = "/demos/models/walkload";
	        	this.loaded = false;				
			}
			else if ( loadcount == 2)
		    {				
				this.loader = new Xc3Loader("/demos/models/walkload/bunny.zc3");
				this.loader.resourcePath = "/demos/models/walkload";
	        	this.loaded = false;				
		    }
			this.loader.useCurrentScene = true;
 
			statusText.visible = true;
			statusText.text = "loading file: " + loader.sourceURL; 
			statusTimer = new Timer(1000, 0.2);
			// designates listeners for the interval and completion events
			statusTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);				 
			statusTimer.start();			
 
			this.loader.preCalcMotion = false;
			this.loader.addEventListener(LoadEvent.LOAD_COMPLETE, this.cast3dLoadComplete);
			this.loader.addEventListener(LoadEvent.LOAD_ERROR, this.cast3dLoadError);
			this.loader.addEventListener(LoadEvent.LOAD_PROGRESS, this.cast3dLoadProgress);
			this.loader.load(this.animator.source);				
		}
 
		/**
		 * sets node position / orientation in 3D scene
		 */		
 		public function positionNode(nodeId:String, position:Object, rotation:Object): Boolean
		{
      	    var nodename:String = nodeId;
	        var node:Node3d = this.animator.source.find(nodeId) as Node3d;
			if (!node) return false;
 
			var p:Positioner = new Positioner(node);
			if (position) p.updatePosition(position.x, position.y,position.z);
			if (rotation) p.upadetRotation(rotation.x, rotation.y ,rotation.z , rotation.w);
 
			return true;
		}
 
	}
}