/**
 * @author b2ox
 */
package vocaloplus.utils
{
	import flash.events.*;
	import org.b2ox.pv3d.*;
	import org.b2ox.pv3d.MikuMikuDance.*;
	import org.papervision3d.core.math.*;
	import vocaloplus.modules.IMotionModule;

	public class MotionTranslator
	{
		public static function attachMotion(mmd:MikuMikuDance, motionMod:IMotionModule):void
		{
			trace("[DEBUG] MotionTranslator");
			var _scaling:Number = mmd.vmdScaling;
			var _controller:VMDController = new VMDController(mmd.pmdController);

			//------------------------------------
			// 各種一時変数
			var i:int, frame:int;

			trace("--------------------------------------------------");
			trace("モーション " + motionMod.name + " 変換＆登録開始");

			//------------------------------------
			// ボーン
			var boneParams:Object = motionMod.content.boneParams;

			for (var boneName:String in boneParams)
			{
				for each (var boneParam:Object in (boneParams[boneName] as Array))
				{
					frame = boneParam.frame; // frame_no
					var move:Number3D = new Number3D(boneParam.move.x * _scaling, boneParam.move.y * _scaling, boneParam.move.z * _scaling);
					var rotation:Quaternion = new Quaternion(boneParam.rotation.x, boneParam.rotation.y, boneParam.rotation.z, boneParam.rotation.w);
					rotation.normalize();

					var param:VMDBoneParam = new VMDBoneParam(move, rotation);

					// interpolations
					param.setInterpolationsByCoeffs(boneParam.ipX, boneParam.ipY, boneParam.ipZ, boneParam.ipR);

					_controller.addBoneParam(boneName, frame, param);
				}
			}

			//------------------------------------
			// Skin
			var skinParams:Object = motionMod.content.skinParams;
			for (var skinName:String in skinParams)
			{
				for each (var skinParam:Object in (skinParams[skinName] as Array))
				{
					_controller.addSkinParam(skinName, skinParam.frame, skinParam.weight);
				}
			}

			// 終了処理
			_controller.fixFrameParams();

			mmd.addMotion(motionMod.name, _controller); // MMDにモーションを追加
			trace("モーション" + motionMod.name + " 処理完了")
			trace("--------------------------------------------------");
		}
	}
}

