MMDAnimationHelper.js 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  1. ( function () {
  2. /**
  3. * MMDAnimationHelper handles animation of MMD assets loaded by MMDLoader
  4. * with MMD special features as IK, Grant, and Physics.
  5. *
  6. * Dependencies
  7. * - ammo.js https://github.com/kripken/ammo.js
  8. * - THREE.MMDPhysics
  9. * - THREE.CCDIKSolver
  10. *
  11. * TODO
  12. * - more precise grant skinning support.
  13. */
  14. var MMDAnimationHelper = function () {
  15. /**
  16. * @param {Object} params - (optional)
  17. * @param {boolean} params.sync - Whether animation durations of added objects are synched. Default is true.
  18. * @param {Number} params.afterglow - Default is 0.0.
  19. * @param {boolean} params.resetPhysicsOnLoop - Default is true.
  20. */
  21. function MMDAnimationHelper( params ) {
  22. params = params || {};
  23. this.meshes = [];
  24. this.camera = null;
  25. this.cameraTarget = new THREE.Object3D();
  26. this.cameraTarget.name = 'target';
  27. this.audio = null;
  28. this.audioManager = null;
  29. this.objects = new WeakMap();
  30. this.configuration = {
  31. sync: params.sync !== undefined ? params.sync : true,
  32. afterglow: params.afterglow !== undefined ? params.afterglow : 0.0,
  33. resetPhysicsOnLoop: params.resetPhysicsOnLoop !== undefined ? params.resetPhysicsOnLoop : true,
  34. pmxAnimation: params.pmxAnimation !== undefined ? params.pmxAnimation : false
  35. };
  36. this.enabled = {
  37. animation: true,
  38. ik: true,
  39. grant: true,
  40. physics: true,
  41. cameraAnimation: true
  42. };
  43. this.onBeforePhysics = function ( ) {}; // experimental
  44. this.sharedPhysics = false;
  45. this.masterPhysics = null;
  46. }
  47. MMDAnimationHelper.prototype = {
  48. constructor: MMDAnimationHelper,
  49. /**
  50. * Adds an Three.js Object to helper and setups animation.
  51. * The anmation durations of added objects are synched
  52. * if this.configuration.sync is true.
  53. *
  54. * @param {THREE.SkinnedMesh|THREE.Camera|THREE.Audio} object
  55. * @param {Object} params - (optional)
  56. * @param {THREE.AnimationClip|Array<THREE.AnimationClip>} params.animation - Only for THREE.SkinnedMesh and THREE.Camera. Default is undefined.
  57. * @param {boolean} params.physics - Only for THREE.SkinnedMesh. Default is true.
  58. * @param {Integer} params.warmup - Only for THREE.SkinnedMesh and physics is true. Default is 60.
  59. * @param {Number} params.unitStep - Only for THREE.SkinnedMesh and physics is true. Default is 1 / 65.
  60. * @param {Integer} params.maxStepNum - Only for THREE.SkinnedMesh and physics is true. Default is 3.
  61. * @param {Vector3} params.gravity - Only for THREE.SkinnedMesh and physics is true. Default ( 0, - 9.8 * 10, 0 ).
  62. * @param {Number} params.delayTime - Only for THREE.Audio. Default is 0.0.
  63. * @return {MMDAnimationHelper}
  64. */
  65. add: function ( object, params ) {
  66. params = params || {};
  67. if ( object.isSkinnedMesh ) {
  68. this._addMesh( object, params );
  69. } else if ( object.isCamera ) {
  70. this._setupCamera( object, params );
  71. } else if ( object.type === 'Audio' ) {
  72. this._setupAudio( object, params );
  73. } else {
  74. throw new Error( 'THREE.MMDAnimationHelper.add: ' + 'accepts only ' + 'THREE.SkinnedMesh or ' + 'THREE.Camera or ' + 'THREE.Audio instance.' );
  75. }
  76. if ( this.configuration.sync ) this._syncDuration();
  77. return this;
  78. },
  79. /**
  80. * Removes an Three.js Object from helper.
  81. *
  82. * @param {THREE.SkinnedMesh|THREE.Camera|THREE.Audio} object
  83. * @return {MMDAnimationHelper}
  84. */
  85. remove: function ( object ) {
  86. if ( object.isSkinnedMesh ) {
  87. this._removeMesh( object );
  88. } else if ( object.isCamera ) {
  89. this._clearCamera( object );
  90. } else if ( object.type === 'Audio' ) {
  91. this._clearAudio( object );
  92. } else {
  93. throw new Error( 'THREE.MMDAnimationHelper.remove: ' + 'accepts only ' + 'THREE.SkinnedMesh or ' + 'THREE.Camera or ' + 'THREE.Audio instance.' );
  94. }
  95. if ( this.configuration.sync ) this._syncDuration();
  96. return this;
  97. },
  98. /**
  99. * Updates the animation.
  100. *
  101. * @param {Number} delta
  102. * @return {MMDAnimationHelper}
  103. */
  104. update: function ( delta ) {
  105. if ( this.audioManager !== null ) this.audioManager.control( delta );
  106. for ( var i = 0; i < this.meshes.length; i ++ ) {
  107. this._animateMesh( this.meshes[ i ], delta );
  108. }
  109. if ( this.sharedPhysics ) this._updateSharedPhysics( delta );
  110. if ( this.camera !== null ) this._animateCamera( this.camera, delta );
  111. return this;
  112. },
  113. /**
  114. * Changes the pose of SkinnedMesh as VPD specifies.
  115. *
  116. * @param {THREE.SkinnedMesh} mesh
  117. * @param {Object} vpd - VPD content parsed MMDParser
  118. * @param {Object} params - (optional)
  119. * @param {boolean} params.resetPose - Default is true.
  120. * @param {boolean} params.ik - Default is true.
  121. * @param {boolean} params.grant - Default is true.
  122. * @return {MMDAnimationHelper}
  123. */
  124. pose: function ( mesh, vpd, params ) {
  125. params = params || {};
  126. if ( params.resetPose !== false ) mesh.pose();
  127. var bones = mesh.skeleton.bones;
  128. var boneParams = vpd.bones;
  129. var boneNameDictionary = {};
  130. for ( var i = 0, il = bones.length; i < il; i ++ ) {
  131. boneNameDictionary[ bones[ i ].name ] = i;
  132. }
  133. var vector = new THREE.Vector3();
  134. var quaternion = new THREE.Quaternion();
  135. for ( var i = 0, il = boneParams.length; i < il; i ++ ) {
  136. var boneParam = boneParams[ i ];
  137. var boneIndex = boneNameDictionary[ boneParam.name ];
  138. if ( boneIndex === undefined ) continue;
  139. var bone = bones[ boneIndex ];
  140. bone.position.add( vector.fromArray( boneParam.translation ) );
  141. bone.quaternion.multiply( quaternion.fromArray( boneParam.quaternion ) );
  142. }
  143. mesh.updateMatrixWorld( true ); // PMX animation system special path
  144. if ( this.configuration.pmxAnimation && mesh.geometry.userData.MMD && mesh.geometry.userData.MMD.format === 'pmx' ) {
  145. var sortedBonesData = this._sortBoneDataArray( mesh.geometry.userData.MMD.bones.slice() );
  146. var ikSolver = params.ik !== false ? this._createCCDIKSolver( mesh ) : null;
  147. var grantSolver = params.grant !== false ? this.createGrantSolver( mesh ) : null;
  148. this._animatePMXMesh( mesh, sortedBonesData, ikSolver, grantSolver );
  149. } else {
  150. if ( params.ik !== false ) {
  151. this._createCCDIKSolver( mesh ).update();
  152. }
  153. if ( params.grant !== false ) {
  154. this.createGrantSolver( mesh ).update();
  155. }
  156. }
  157. return this;
  158. },
  159. /**
  160. * Enabes/Disables an animation feature.
  161. *
  162. * @param {string} key
  163. * @param {boolean} enabled
  164. * @return {MMDAnimationHelper}
  165. */
  166. enable: function ( key, enabled ) {
  167. if ( this.enabled[ key ] === undefined ) {
  168. throw new Error( 'THREE.MMDAnimationHelper.enable: ' + 'unknown key ' + key );
  169. }
  170. this.enabled[ key ] = enabled;
  171. if ( key === 'physics' ) {
  172. for ( var i = 0, il = this.meshes.length; i < il; i ++ ) {
  173. this._optimizeIK( this.meshes[ i ], enabled );
  174. }
  175. }
  176. return this;
  177. },
  178. /**
  179. * Creates an GrantSolver instance.
  180. *
  181. * @param {THREE.SkinnedMesh} mesh
  182. * @return {GrantSolver}
  183. */
  184. createGrantSolver: function ( mesh ) {
  185. return new GrantSolver( mesh, mesh.geometry.userData.MMD.grants );
  186. },
  187. // private methods
  188. _addMesh: function ( mesh, params ) {
  189. if ( this.meshes.indexOf( mesh ) >= 0 ) {
  190. throw new Error( 'THREE.MMDAnimationHelper._addMesh: ' + 'SkinnedMesh \'' + mesh.name + '\' has already been added.' );
  191. }
  192. this.meshes.push( mesh );
  193. this.objects.set( mesh, {
  194. looped: false
  195. } );
  196. this._setupMeshAnimation( mesh, params.animation );
  197. if ( params.physics !== false ) {
  198. this._setupMeshPhysics( mesh, params );
  199. }
  200. return this;
  201. },
  202. _setupCamera: function ( camera, params ) {
  203. if ( this.camera === camera ) {
  204. throw new Error( 'THREE.MMDAnimationHelper._setupCamera: ' + 'Camera \'' + camera.name + '\' has already been set.' );
  205. }
  206. if ( this.camera ) this.clearCamera( this.camera );
  207. this.camera = camera;
  208. camera.add( this.cameraTarget );
  209. this.objects.set( camera, {} );
  210. if ( params.animation !== undefined ) {
  211. this._setupCameraAnimation( camera, params.animation );
  212. }
  213. return this;
  214. },
  215. _setupAudio: function ( audio, params ) {
  216. if ( this.audio === audio ) {
  217. throw new Error( 'THREE.MMDAnimationHelper._setupAudio: ' + 'Audio \'' + audio.name + '\' has already been set.' );
  218. }
  219. if ( this.audio ) this.clearAudio( this.audio );
  220. this.audio = audio;
  221. this.audioManager = new AudioManager( audio, params );
  222. this.objects.set( this.audioManager, {
  223. duration: this.audioManager.duration
  224. } );
  225. return this;
  226. },
  227. _removeMesh: function ( mesh ) {
  228. var found = false;
  229. var writeIndex = 0;
  230. for ( var i = 0, il = this.meshes.length; i < il; i ++ ) {
  231. if ( this.meshes[ i ] === mesh ) {
  232. this.objects.delete( mesh );
  233. found = true;
  234. continue;
  235. }
  236. this.meshes[ writeIndex ++ ] = this.meshes[ i ];
  237. }
  238. if ( ! found ) {
  239. throw new Error( 'THREE.MMDAnimationHelper._removeMesh: ' + 'SkinnedMesh \'' + mesh.name + '\' has not been added yet.' );
  240. }
  241. this.meshes.length = writeIndex;
  242. return this;
  243. },
  244. _clearCamera: function ( camera ) {
  245. if ( camera !== this.camera ) {
  246. throw new Error( 'THREE.MMDAnimationHelper._clearCamera: ' + 'Camera \'' + camera.name + '\' has not been set yet.' );
  247. }
  248. this.camera.remove( this.cameraTarget );
  249. this.objects.delete( this.camera );
  250. this.camera = null;
  251. return this;
  252. },
  253. _clearAudio: function ( audio ) {
  254. if ( audio !== this.audio ) {
  255. throw new Error( 'THREE.MMDAnimationHelper._clearAudio: ' + 'Audio \'' + audio.name + '\' has not been set yet.' );
  256. }
  257. this.objects.delete( this.audioManager );
  258. this.audio = null;
  259. this.audioManager = null;
  260. return this;
  261. },
  262. _setupMeshAnimation: function ( mesh, animation ) {
  263. var objects = this.objects.get( mesh );
  264. if ( animation !== undefined ) {
  265. var animations = Array.isArray( animation ) ? animation : [ animation ];
  266. objects.mixer = new THREE.AnimationMixer( mesh );
  267. for ( var i = 0, il = animations.length; i < il; i ++ ) {
  268. objects.mixer.clipAction( animations[ i ] ).play();
  269. } // TODO: find a workaround not to access ._clip looking like a private property
  270. objects.mixer.addEventListener( 'loop', function ( event ) {
  271. var tracks = event.action._clip.tracks;
  272. if ( tracks.length > 0 && tracks[ 0 ].name.slice( 0, 6 ) !== '.bones' ) return;
  273. objects.looped = true;
  274. } );
  275. }
  276. objects.ikSolver = this._createCCDIKSolver( mesh );
  277. objects.grantSolver = this.createGrantSolver( mesh );
  278. return this;
  279. },
  280. _setupCameraAnimation: function ( camera, animation ) {
  281. var animations = Array.isArray( animation ) ? animation : [ animation ];
  282. var objects = this.objects.get( camera );
  283. objects.mixer = new THREE.AnimationMixer( camera );
  284. for ( var i = 0, il = animations.length; i < il; i ++ ) {
  285. objects.mixer.clipAction( animations[ i ] ).play();
  286. }
  287. },
  288. _setupMeshPhysics: function ( mesh, params ) {
  289. var objects = this.objects.get( mesh ); // shared physics is experimental
  290. if ( params.world === undefined && this.sharedPhysics ) {
  291. var masterPhysics = this._getMasterPhysics();
  292. if ( masterPhysics !== null ) world = masterPhysics.world; // eslint-disable-line no-undef
  293. }
  294. objects.physics = this._createMMDPhysics( mesh, params );
  295. if ( objects.mixer && params.animationWarmup !== false ) {
  296. this._animateMesh( mesh, 0 );
  297. objects.physics.reset();
  298. }
  299. objects.physics.warmup( params.warmup !== undefined ? params.warmup : 60 );
  300. this._optimizeIK( mesh, true );
  301. },
  302. _animateMesh: function ( mesh, delta ) {
  303. var objects = this.objects.get( mesh );
  304. var mixer = objects.mixer;
  305. var ikSolver = objects.ikSolver;
  306. var grantSolver = objects.grantSolver;
  307. var physics = objects.physics;
  308. var looped = objects.looped;
  309. if ( mixer && this.enabled.animation ) {
  310. // alternate solution to save/restore bones but less performant?
  311. //mesh.pose();
  312. //this._updatePropertyMixersBuffer( mesh );
  313. this._restoreBones( mesh );
  314. mixer.update( delta );
  315. this._saveBones( mesh ); // PMX animation system special path
  316. if ( this.configuration.pmxAnimation && mesh.geometry.userData.MMD && mesh.geometry.userData.MMD.format === 'pmx' ) {
  317. if ( ! objects.sortedBonesData ) objects.sortedBonesData = this._sortBoneDataArray( mesh.geometry.userData.MMD.bones.slice() );
  318. this._animatePMXMesh( mesh, objects.sortedBonesData, ikSolver && this.enabled.ik ? ikSolver : null, grantSolver && this.enabled.grant ? grantSolver : null );
  319. } else {
  320. if ( ikSolver && this.enabled.ik ) {
  321. mesh.updateMatrixWorld( true );
  322. ikSolver.update();
  323. }
  324. if ( grantSolver && this.enabled.grant ) {
  325. grantSolver.update();
  326. }
  327. }
  328. }
  329. if ( looped === true && this.enabled.physics ) {
  330. if ( physics && this.configuration.resetPhysicsOnLoop ) physics.reset();
  331. objects.looped = false;
  332. }
  333. if ( physics && this.enabled.physics && ! this.sharedPhysics ) {
  334. this.onBeforePhysics( mesh );
  335. physics.update( delta );
  336. }
  337. },
  338. // Sort bones in order by 1. transformationClass and 2. bone index.
  339. // In PMX animation system, bone transformations should be processed
  340. // in this order.
  341. _sortBoneDataArray: function ( boneDataArray ) {
  342. return boneDataArray.sort( function ( a, b ) {
  343. if ( a.transformationClass !== b.transformationClass ) {
  344. return a.transformationClass - b.transformationClass;
  345. } else {
  346. return a.index - b.index;
  347. }
  348. } );
  349. },
  350. // PMX Animation system is a bit too complex and doesn't great match to
  351. // Three.js Animation system. This method attempts to simulate it as much as
  352. // possible but doesn't perfectly simulate.
  353. // This method is more costly than the regular one so
  354. // you are recommended to set constructor parameter "pmxAnimation: true"
  355. // only if your PMX model animation doesn't work well.
  356. // If you need better method you would be required to write your own.
  357. _animatePMXMesh: function () {
  358. // Keep working quaternions for less GC
  359. var quaternions = [];
  360. var quaternionIndex = 0;
  361. function getQuaternion() {
  362. if ( quaternionIndex >= quaternions.length ) {
  363. quaternions.push( new THREE.Quaternion() );
  364. }
  365. return quaternions[ quaternionIndex ++ ];
  366. } // Save rotation whose grant and IK are already applied
  367. // used by grant children
  368. var grantResultMap = new Map();
  369. function updateOne( mesh, boneIndex, ikSolver, grantSolver ) {
  370. var bones = mesh.skeleton.bones;
  371. var bonesData = mesh.geometry.userData.MMD.bones;
  372. var boneData = bonesData[ boneIndex ];
  373. var bone = bones[ boneIndex ]; // Return if already updated by being referred as a grant parent.
  374. if ( grantResultMap.has( boneIndex ) ) return;
  375. var quaternion = getQuaternion(); // Initialize grant result here to prevent infinite loop.
  376. // If it's referred before updating with actual result later
  377. // result without applyting IK or grant is gotten
  378. // but better than composing of infinite loop.
  379. grantResultMap.set( boneIndex, quaternion.copy( bone.quaternion ) ); // @TODO: Support global grant and grant position
  380. if ( grantSolver && boneData.grant && ! boneData.grant.isLocal && boneData.grant.affectRotation ) {
  381. var parentIndex = boneData.grant.parentIndex;
  382. var ratio = boneData.grant.ratio;
  383. if ( ! grantResultMap.has( parentIndex ) ) {
  384. updateOne( mesh, parentIndex, ikSolver, grantSolver );
  385. }
  386. grantSolver.addGrantRotation( bone, grantResultMap.get( parentIndex ), ratio );
  387. }
  388. if ( ikSolver && boneData.ik ) {
  389. // @TODO: Updating world matrices every time solving an IK bone is
  390. // costly. Optimize if possible.
  391. mesh.updateMatrixWorld( true );
  392. ikSolver.updateOne( boneData.ik ); // No confident, but it seems the grant results with ik links should be updated?
  393. var links = boneData.ik.links;
  394. for ( var i = 0, il = links.length; i < il; i ++ ) {
  395. var link = links[ i ];
  396. if ( link.enabled === false ) continue;
  397. var linkIndex = link.index;
  398. if ( grantResultMap.has( linkIndex ) ) {
  399. grantResultMap.set( linkIndex, grantResultMap.get( linkIndex ).copy( bones[ linkIndex ].quaternion ) );
  400. }
  401. }
  402. } // Update with the actual result here
  403. quaternion.copy( bone.quaternion );
  404. }
  405. return function ( mesh, sortedBonesData, ikSolver, grantSolver ) {
  406. quaternionIndex = 0;
  407. grantResultMap.clear();
  408. for ( var i = 0, il = sortedBonesData.length; i < il; i ++ ) {
  409. updateOne( mesh, sortedBonesData[ i ].index, ikSolver, grantSolver );
  410. }
  411. mesh.updateMatrixWorld( true );
  412. return this;
  413. };
  414. }(),
  415. _animateCamera: function ( camera, delta ) {
  416. var mixer = this.objects.get( camera ).mixer;
  417. if ( mixer && this.enabled.cameraAnimation ) {
  418. mixer.update( delta );
  419. camera.updateProjectionMatrix();
  420. camera.up.set( 0, 1, 0 );
  421. camera.up.applyQuaternion( camera.quaternion );
  422. camera.lookAt( this.cameraTarget.position );
  423. }
  424. },
  425. _optimizeIK: function ( mesh, physicsEnabled ) {
  426. var iks = mesh.geometry.userData.MMD.iks;
  427. var bones = mesh.geometry.userData.MMD.bones;
  428. for ( var i = 0, il = iks.length; i < il; i ++ ) {
  429. var ik = iks[ i ];
  430. var links = ik.links;
  431. for ( var j = 0, jl = links.length; j < jl; j ++ ) {
  432. var link = links[ j ];
  433. if ( physicsEnabled === true ) {
  434. // disable IK of the bone the corresponding rigidBody type of which is 1 or 2
  435. // because its rotation will be overriden by physics
  436. link.enabled = bones[ link.index ].rigidBodyType > 0 ? false : true;
  437. } else {
  438. link.enabled = true;
  439. }
  440. }
  441. }
  442. },
  443. _createCCDIKSolver: function ( mesh ) {
  444. if ( THREE.CCDIKSolver === undefined ) {
  445. throw new Error( 'THREE.MMDAnimationHelper: Import THREE.CCDIKSolver.' );
  446. }
  447. return new THREE.CCDIKSolver( mesh, mesh.geometry.userData.MMD.iks );
  448. },
  449. _createMMDPhysics: function ( mesh, params ) {
  450. if ( THREE.MMDPhysics === undefined ) {
  451. throw new Error( 'THREE.MMDPhysics: Import THREE.MMDPhysics.' );
  452. }
  453. return new THREE.MMDPhysics( mesh, mesh.geometry.userData.MMD.rigidBodies, mesh.geometry.userData.MMD.constraints, params );
  454. },
  455. /*
  456. * Detects the longest duration and then sets it to them to sync.
  457. * TODO: Not to access private properties ( ._actions and ._clip )
  458. */
  459. _syncDuration: function () {
  460. var max = 0.0;
  461. var objects = this.objects;
  462. var meshes = this.meshes;
  463. var camera = this.camera;
  464. var audioManager = this.audioManager; // get the longest duration
  465. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  466. var mixer = this.objects.get( meshes[ i ] ).mixer;
  467. if ( mixer === undefined ) continue;
  468. for ( var j = 0; j < mixer._actions.length; j ++ ) {
  469. var clip = mixer._actions[ j ]._clip;
  470. if ( ! objects.has( clip ) ) {
  471. objects.set( clip, {
  472. duration: clip.duration
  473. } );
  474. }
  475. max = Math.max( max, objects.get( clip ).duration );
  476. }
  477. }
  478. if ( camera !== null ) {
  479. var mixer = this.objects.get( camera ).mixer;
  480. if ( mixer !== undefined ) {
  481. for ( var i = 0, il = mixer._actions.length; i < il; i ++ ) {
  482. var clip = mixer._actions[ i ]._clip;
  483. if ( ! objects.has( clip ) ) {
  484. objects.set( clip, {
  485. duration: clip.duration
  486. } );
  487. }
  488. max = Math.max( max, objects.get( clip ).duration );
  489. }
  490. }
  491. }
  492. if ( audioManager !== null ) {
  493. max = Math.max( max, objects.get( audioManager ).duration );
  494. }
  495. max += this.configuration.afterglow; // update the duration
  496. for ( var i = 0, il = this.meshes.length; i < il; i ++ ) {
  497. var mixer = this.objects.get( this.meshes[ i ] ).mixer;
  498. if ( mixer === undefined ) continue;
  499. for ( var j = 0, jl = mixer._actions.length; j < jl; j ++ ) {
  500. mixer._actions[ j ]._clip.duration = max;
  501. }
  502. }
  503. if ( camera !== null ) {
  504. var mixer = this.objects.get( camera ).mixer;
  505. if ( mixer !== undefined ) {
  506. for ( var i = 0, il = mixer._actions.length; i < il; i ++ ) {
  507. mixer._actions[ i ]._clip.duration = max;
  508. }
  509. }
  510. }
  511. if ( audioManager !== null ) {
  512. audioManager.duration = max;
  513. }
  514. },
  515. // workaround
  516. _updatePropertyMixersBuffer: function ( mesh ) {
  517. var mixer = this.objects.get( mesh ).mixer;
  518. var propertyMixers = mixer._bindings;
  519. var accuIndex = mixer._accuIndex;
  520. for ( var i = 0, il = propertyMixers.length; i < il; i ++ ) {
  521. var propertyMixer = propertyMixers[ i ];
  522. var buffer = propertyMixer.buffer;
  523. var stride = propertyMixer.valueSize;
  524. var offset = ( accuIndex + 1 ) * stride;
  525. propertyMixer.binding.getValue( buffer, offset );
  526. }
  527. },
  528. /*
  529. * Avoiding these two issues by restore/save bones before/after mixer animation.
  530. *
  531. * 1. PropertyMixer used by THREE.AnimationMixer holds cache value in .buffer.
  532. * Calculating IK, Grant, and Physics after mixer animation can break
  533. * the cache coherency.
  534. *
  535. * 2. Applying Grant two or more times without reset the posing breaks model.
  536. */
  537. _saveBones: function ( mesh ) {
  538. var objects = this.objects.get( mesh );
  539. var bones = mesh.skeleton.bones;
  540. var backupBones = objects.backupBones;
  541. if ( backupBones === undefined ) {
  542. backupBones = new Float32Array( bones.length * 7 );
  543. objects.backupBones = backupBones;
  544. }
  545. for ( var i = 0, il = bones.length; i < il; i ++ ) {
  546. var bone = bones[ i ];
  547. bone.position.toArray( backupBones, i * 7 );
  548. bone.quaternion.toArray( backupBones, i * 7 + 3 );
  549. }
  550. },
  551. _restoreBones: function ( mesh ) {
  552. var objects = this.objects.get( mesh );
  553. var backupBones = objects.backupBones;
  554. if ( backupBones === undefined ) return;
  555. var bones = mesh.skeleton.bones;
  556. for ( var i = 0, il = bones.length; i < il; i ++ ) {
  557. var bone = bones[ i ];
  558. bone.position.fromArray( backupBones, i * 7 );
  559. bone.quaternion.fromArray( backupBones, i * 7 + 3 );
  560. }
  561. },
  562. // experimental
  563. _getMasterPhysics: function () {
  564. if ( this.masterPhysics !== null ) return this.masterPhysics;
  565. for ( var i = 0, il = this.meshes.length; i < il; i ++ ) {
  566. var physics = this.meshes[ i ].physics;
  567. if ( physics !== undefined && physics !== null ) {
  568. this.masterPhysics = physics;
  569. return this.masterPhysics;
  570. }
  571. }
  572. return null;
  573. },
  574. _updateSharedPhysics: function ( delta ) {
  575. if ( this.meshes.length === 0 || ! this.enabled.physics || ! this.sharedPhysics ) return;
  576. var physics = this._getMasterPhysics();
  577. if ( physics === null ) return;
  578. for ( var i = 0, il = this.meshes.length; i < il; i ++ ) {
  579. var p = this.meshes[ i ].physics;
  580. if ( p !== null && p !== undefined ) {
  581. p.updateRigidBodies();
  582. }
  583. }
  584. physics.stepSimulation( delta );
  585. for ( var i = 0, il = this.meshes.length; i < il; i ++ ) {
  586. var p = this.meshes[ i ].physics;
  587. if ( p !== null && p !== undefined ) {
  588. p.updateBones();
  589. }
  590. }
  591. }
  592. }; //
  593. /**
  594. * @param {THREE.Audio} audio
  595. * @param {Object} params - (optional)
  596. * @param {Nuumber} params.delayTime
  597. */
  598. function AudioManager( audio, params ) {
  599. params = params || {};
  600. this.audio = audio;
  601. this.elapsedTime = 0.0;
  602. this.currentTime = 0.0;
  603. this.delayTime = params.delayTime !== undefined ? params.delayTime : 0.0;
  604. this.audioDuration = this.audio.buffer.duration;
  605. this.duration = this.audioDuration + this.delayTime;
  606. }
  607. AudioManager.prototype = {
  608. constructor: AudioManager,
  609. /**
  610. * @param {Number} delta
  611. * @return {AudioManager}
  612. */
  613. control: function ( delta ) {
  614. this.elapsed += delta;
  615. this.currentTime += delta;
  616. if ( this._shouldStopAudio() ) this.audio.stop();
  617. if ( this._shouldStartAudio() ) this.audio.play();
  618. return this;
  619. },
  620. // private methods
  621. _shouldStartAudio: function () {
  622. if ( this.audio.isPlaying ) return false;
  623. while ( this.currentTime >= this.duration ) {
  624. this.currentTime -= this.duration;
  625. }
  626. if ( this.currentTime < this.delayTime ) return false; // 'duration' can be bigger than 'audioDuration + delayTime' because of sync configuration
  627. if ( this.currentTime - this.delayTime > this.audioDuration ) return false;
  628. return true;
  629. },
  630. _shouldStopAudio: function () {
  631. return this.audio.isPlaying && this.currentTime >= this.duration;
  632. }
  633. };
  634. /**
  635. * Solver for Grant (Fuyo in Japanese. I just google translated because
  636. * Fuyo may be MMD specific term and may not be common word in 3D CG terms.)
  637. * Grant propagates a bone's transform to other bones transforms even if
  638. * they are not children.
  639. * @param {THREE.SkinnedMesh} mesh
  640. * @param {Array<Object>} grants
  641. */
  642. function GrantSolver( mesh, grants ) {
  643. this.mesh = mesh;
  644. this.grants = grants || [];
  645. }
  646. GrantSolver.prototype = {
  647. constructor: GrantSolver,
  648. /**
  649. * Solve all the grant bones
  650. * @return {GrantSolver}
  651. */
  652. update: function () {
  653. var grants = this.grants;
  654. for ( var i = 0, il = grants.length; i < il; i ++ ) {
  655. this.updateOne( grants[ i ] );
  656. }
  657. return this;
  658. },
  659. /**
  660. * Solve a grant bone
  661. * @param {Object} grant - grant parameter
  662. * @return {GrantSolver}
  663. */
  664. updateOne: function ( grant ) {
  665. var bones = this.mesh.skeleton.bones;
  666. var bone = bones[ grant.index ];
  667. var parentBone = bones[ grant.parentIndex ];
  668. if ( grant.isLocal ) {
  669. // TODO: implement
  670. if ( grant.affectPosition ) {} // TODO: implement
  671. if ( grant.affectRotation ) {}
  672. } else {
  673. // TODO: implement
  674. if ( grant.affectPosition ) {}
  675. if ( grant.affectRotation ) {
  676. this.addGrantRotation( bone, parentBone.quaternion, grant.ratio );
  677. }
  678. }
  679. return this;
  680. },
  681. addGrantRotation: function () {
  682. var quaternion = new THREE.Quaternion();
  683. return function ( bone, q, ratio ) {
  684. quaternion.set( 0, 0, 0, 1 );
  685. quaternion.slerp( q, ratio );
  686. bone.quaternion.multiply( quaternion );
  687. return this;
  688. };
  689. }()
  690. };
  691. return MMDAnimationHelper;
  692. }();
  693. THREE.MMDAnimationHelper = MMDAnimationHelper;
  694. } )();