MMDPhysics.js 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411
  1. /**
  2. * @author takahiro / https://github.com/takahirox
  3. *
  4. * Dependencies
  5. * - Ammo.js https://github.com/kripken/ammo.js
  6. *
  7. * MMDPhysics calculates physics with Ammo(Bullet based JavaScript Physics engine)
  8. * for MMD model loaded by THREE.MMDLoader.
  9. *
  10. * TODO
  11. * - Physics in Worker
  12. */
  13. /* global Ammo */
  14. THREE.MMDPhysics = ( function () {
  15. /**
  16. * @param {THREE.SkinnedMesh} mesh
  17. * @param {Array<Object>} rigidBodyParams
  18. * @param {Array<Object>} (optional) constraintParams
  19. * @param {Object} params - (optional)
  20. * @param {Number} params.unitStep - Default is 1 / 65.
  21. * @param {Integer} params.maxStepNum - Default is 3.
  22. * @param {THREE.Vector3} params.gravity - Default is ( 0, - 9.8 * 10, 0 )
  23. */
  24. function MMDPhysics( mesh, rigidBodyParams, constraintParams, params ) {
  25. if ( typeof Ammo === 'undefined' ) {
  26. throw new Error( 'THREE.MMDPhysics: Import ammo.js https://github.com/kripken/ammo.js' );
  27. }
  28. constraintParams = constraintParams || [];
  29. params = params || {};
  30. this.manager = new ResourceManager();
  31. this.mesh = mesh;
  32. /*
  33. * I don't know why but 1/60 unitStep easily breaks models
  34. * so I set it 1/65 so far.
  35. * Don't set too small unitStep because
  36. * the smaller unitStep can make the performance worse.
  37. */
  38. this.unitStep = ( params.unitStep !== undefined ) ? params.unitStep : 1 / 65;
  39. this.maxStepNum = ( params.maxStepNum !== undefined ) ? params.maxStepNum : 3;
  40. this.gravity = new THREE.Vector3( 0, - 9.8 * 10, 0 );
  41. if ( params.gravity !== undefined ) this.gravity.copy( params.gravity );
  42. this.world = params.world !== undefined ? params.world : null; // experimental
  43. this.bodies = [];
  44. this.constraints = [];
  45. this._init( mesh, rigidBodyParams, constraintParams );
  46. }
  47. MMDPhysics.prototype = {
  48. constructor: MMDPhysics,
  49. /**
  50. * Advances Physics calculation and updates bones.
  51. *
  52. * @param {Number} delta - time in second
  53. * @return {THREE.MMDPhysics}
  54. */
  55. update: function ( delta ) {
  56. var manager = this.manager;
  57. var mesh = this.mesh;
  58. // rigid bodies and constrains are for
  59. // mesh's world scale (1, 1, 1).
  60. // Convert to (1, 1, 1) if it isn't.
  61. var isNonDefaultScale = false;
  62. var position = manager.allocThreeVector3();
  63. var quaternion = manager.allocThreeQuaternion();
  64. var scale = manager.allocThreeVector3();
  65. mesh.matrixWorld.decompose( position, quaternion, scale );
  66. if ( scale.x !== 1 || scale.y !== 1 || scale.z !== 1 ) {
  67. isNonDefaultScale = true;
  68. }
  69. var parent;
  70. if ( isNonDefaultScale ) {
  71. parent = mesh.parent;
  72. if ( parent !== null ) mesh.parent = null;
  73. scale.copy( this.mesh.scale );
  74. mesh.scale.set( 1, 1, 1 );
  75. mesh.updateMatrixWorld( true );
  76. }
  77. // calculate physics and update bones
  78. this._updateRigidBodies();
  79. this._stepSimulation( delta );
  80. this._updateBones();
  81. // restore mesh if converted above
  82. if ( isNonDefaultScale ) {
  83. if ( parent !== null ) mesh.parent = parent;
  84. mesh.scale.copy( scale );
  85. }
  86. manager.freeThreeVector3( scale );
  87. manager.freeThreeQuaternion( quaternion );
  88. manager.freeThreeVector3( position );
  89. return this;
  90. },
  91. /**
  92. * Resets rigid bodies transorm to current bone's.
  93. *
  94. * @return {THREE.MMDPhysics}
  95. */
  96. reset: function () {
  97. for ( var i = 0, il = this.bodies.length; i < il; i ++ ) {
  98. this.bodies[ i ].reset();
  99. }
  100. return this;
  101. },
  102. /**
  103. * Warm ups Rigid bodies. Calculates cycles steps.
  104. *
  105. * @param {Integer} cycles
  106. * @return {THREE.MMDPhysics}
  107. */
  108. warmup: function ( cycles ) {
  109. for ( var i = 0; i < cycles; i ++ ) {
  110. this.update( 1 / 60 );
  111. }
  112. return this;
  113. },
  114. /**
  115. * Sets gravity.
  116. *
  117. * @param {THREE.Vector3} gravity
  118. * @return {MMDPhysicsHelper}
  119. */
  120. setGravity: function ( gravity ) {
  121. this.world.setGravity( new Ammo.btVector3( gravity.x, gravity.y, gravity.z ) );
  122. this.gravity.copy( gravity );
  123. return this;
  124. },
  125. /**
  126. * Creates MMDPhysicsHelper
  127. *
  128. * @return {MMDPhysicsHelper}
  129. */
  130. createHelper: function () {
  131. return new MMDPhysicsHelper( this.mesh, this );
  132. },
  133. // private methods
  134. _init: function ( mesh, rigidBodyParams, constraintParams ) {
  135. var manager = this.manager;
  136. // rigid body/constraint parameters are for
  137. // mesh's default world transform as position(0, 0, 0),
  138. // quaternion(0, 0, 0, 1) and scale(0, 0, 0)
  139. var parent = mesh.parent;
  140. if ( parent !== null ) parent = null;
  141. var currentPosition = manager.allocThreeVector3();
  142. var currentQuaternion = manager.allocThreeQuaternion();
  143. var currentScale = manager.allocThreeVector3();
  144. currentPosition.copy( mesh.position );
  145. currentQuaternion.copy( mesh.quaternion );
  146. currentScale.copy( mesh.scale );
  147. mesh.position.set( 0, 0, 0 );
  148. mesh.quaternion.set( 0, 0, 0, 1 );
  149. mesh.scale.set( 1, 1, 1 );
  150. mesh.updateMatrixWorld( true );
  151. if ( this.world === null ) {
  152. this.world = this._createWorld();
  153. this.setGravity( this.gravity );
  154. }
  155. this._initRigidBodies( rigidBodyParams );
  156. this._initConstraints( constraintParams );
  157. if ( parent !== null ) mesh.parent = parent;
  158. mesh.position.copy( currentPosition );
  159. mesh.quaternion.copy( currentQuaternion );
  160. mesh.scale.copy( currentScale );
  161. mesh.updateMatrixWorld( true );
  162. this.reset();
  163. manager.freeThreeVector3( currentPosition );
  164. manager.freeThreeQuaternion( currentQuaternion );
  165. manager.freeThreeVector3( currentScale );
  166. },
  167. _createWorld: function () {
  168. var config = new Ammo.btDefaultCollisionConfiguration();
  169. var dispatcher = new Ammo.btCollisionDispatcher( config );
  170. var cache = new Ammo.btDbvtBroadphase();
  171. var solver = new Ammo.btSequentialImpulseConstraintSolver();
  172. var world = new Ammo.btDiscreteDynamicsWorld( dispatcher, cache, solver, config );
  173. return world;
  174. },
  175. _initRigidBodies: function ( rigidBodies ) {
  176. for ( var i = 0, il = rigidBodies.length; i < il; i ++ ) {
  177. this.bodies.push( new RigidBody(
  178. this.mesh, this.world, rigidBodies[ i ], this.manager ) );
  179. }
  180. },
  181. _initConstraints: function ( constraints ) {
  182. for ( var i = 0, il = constraints.length; i < il; i ++ ) {
  183. var params = constraints[ i ];
  184. var bodyA = this.bodies[ params.rigidBodyIndex1 ];
  185. var bodyB = this.bodies[ params.rigidBodyIndex2 ];
  186. this.constraints.push( new Constraint(
  187. this.mesh, this.world, bodyA, bodyB, params, this.manager ) );
  188. }
  189. },
  190. _stepSimulation: function ( delta ) {
  191. var unitStep = this.unitStep;
  192. var stepTime = delta;
  193. var maxStepNum = ( ( delta / unitStep ) | 0 ) + 1;
  194. if ( stepTime < unitStep ) {
  195. stepTime = unitStep;
  196. maxStepNum = 1;
  197. }
  198. if ( maxStepNum > this.maxStepNum ) {
  199. maxStepNum = this.maxStepNum;
  200. }
  201. this.world.stepSimulation( stepTime, maxStepNum, unitStep );
  202. },
  203. _updateRigidBodies: function () {
  204. for ( var i = 0, il = this.bodies.length; i < il; i ++ ) {
  205. this.bodies[ i ].updateFromBone();
  206. }
  207. },
  208. _updateBones: function () {
  209. for ( var i = 0, il = this.bodies.length; i < il; i ++ ) {
  210. this.bodies[ i ].updateBone();
  211. }
  212. }
  213. };
  214. /**
  215. * This manager's responsibilies are
  216. *
  217. * 1. manage Ammo.js and Three.js object resources and
  218. * improve the performance and the memory consumption by
  219. * reusing objects.
  220. *
  221. * 2. provide simple Ammo object operations.
  222. */
  223. function ResourceManager() {
  224. // for Three.js
  225. this.threeVector3s = [];
  226. this.threeMatrix4s = [];
  227. this.threeQuaternions = [];
  228. this.threeEulers = [];
  229. // for Ammo.js
  230. this.transforms = [];
  231. this.quaternions = [];
  232. this.vector3s = [];
  233. }
  234. ResourceManager.prototype = {
  235. constructor: ResourceManager,
  236. allocThreeVector3: function () {
  237. return ( this.threeVector3s.length > 0 )
  238. ? this.threeVector3s.pop()
  239. : new THREE.Vector3();
  240. },
  241. freeThreeVector3: function ( v ) {
  242. this.threeVector3s.push( v );
  243. },
  244. allocThreeMatrix4: function () {
  245. return ( this.threeMatrix4s.length > 0 )
  246. ? this.threeMatrix4s.pop()
  247. : new THREE.Matrix4();
  248. },
  249. freeThreeMatrix4: function ( m ) {
  250. this.threeMatrix4s.push( m );
  251. },
  252. allocThreeQuaternion: function () {
  253. return ( this.threeQuaternions.length > 0 )
  254. ? this.threeQuaternions.pop()
  255. : new THREE.Quaternion();
  256. },
  257. freeThreeQuaternion: function ( q ) {
  258. this.threeQuaternions.push( q );
  259. },
  260. allocThreeEuler: function () {
  261. return ( this.threeEulers.length > 0 )
  262. ? this.threeEulers.pop()
  263. : new THREE.Euler();
  264. },
  265. freeThreeEuler: function ( e ) {
  266. this.threeEulers.push( e );
  267. },
  268. allocTransform: function () {
  269. return ( this.transforms.length > 0 )
  270. ? this.transforms.pop()
  271. : new Ammo.btTransform();
  272. },
  273. freeTransform: function ( t ) {
  274. this.transforms.push( t );
  275. },
  276. allocQuaternion: function () {
  277. return ( this.quaternions.length > 0 )
  278. ? this.quaternions.pop()
  279. : new Ammo.btQuaternion();
  280. },
  281. freeQuaternion: function ( q ) {
  282. this.quaternions.push( q );
  283. },
  284. allocVector3: function () {
  285. return ( this.vector3s.length > 0 )
  286. ? this.vector3s.pop()
  287. : new Ammo.btVector3();
  288. },
  289. freeVector3: function ( v ) {
  290. this.vector3s.push( v );
  291. },
  292. setIdentity: function ( t ) {
  293. t.setIdentity();
  294. },
  295. getBasis: function ( t ) {
  296. var q = this.allocQuaternion();
  297. t.getBasis().getRotation( q );
  298. return q;
  299. },
  300. getBasisAsMatrix3: function ( t ) {
  301. var q = this.getBasis( t );
  302. var m = this.quaternionToMatrix3( q );
  303. this.freeQuaternion( q );
  304. return m;
  305. },
  306. getOrigin: function ( t ) {
  307. return t.getOrigin();
  308. },
  309. setOrigin: function ( t, v ) {
  310. t.getOrigin().setValue( v.x(), v.y(), v.z() );
  311. },
  312. copyOrigin: function ( t1, t2 ) {
  313. var o = t2.getOrigin();
  314. this.setOrigin( t1, o );
  315. },
  316. setBasis: function ( t, q ) {
  317. t.setRotation( q );
  318. },
  319. setBasisFromMatrix3: function ( t, m ) {
  320. var q = this.matrix3ToQuaternion( m );
  321. this.setBasis( t, q );
  322. this.freeQuaternion( q );
  323. },
  324. setOriginFromArray3: function ( t, a ) {
  325. t.getOrigin().setValue( a[ 0 ], a[ 1 ], a[ 2 ] );
  326. },
  327. setOriginFromThreeVector3: function ( t, v ) {
  328. t.getOrigin().setValue( v.x, v.y, v.z );
  329. },
  330. setBasisFromArray3: function ( t, a ) {
  331. var thQ = this.allocThreeQuaternion();
  332. var thE = this.allocThreeEuler();
  333. thE.set( a[ 0 ], a[ 1 ], a[ 2 ] );
  334. this.setBasisFromThreeQuaternion( t, thQ.setFromEuler( thE ) );
  335. this.freeThreeEuler( thE );
  336. this.freeThreeQuaternion( thQ );
  337. },
  338. setBasisFromThreeQuaternion: function ( t, a ) {
  339. var q = this.allocQuaternion();
  340. q.setX( a.x );
  341. q.setY( a.y );
  342. q.setZ( a.z );
  343. q.setW( a.w );
  344. this.setBasis( t, q );
  345. this.freeQuaternion( q );
  346. },
  347. multiplyTransforms: function ( t1, t2 ) {
  348. var t = this.allocTransform();
  349. this.setIdentity( t );
  350. var m1 = this.getBasisAsMatrix3( t1 );
  351. var m2 = this.getBasisAsMatrix3( t2 );
  352. var o1 = this.getOrigin( t1 );
  353. var o2 = this.getOrigin( t2 );
  354. var v1 = this.multiplyMatrix3ByVector3( m1, o2 );
  355. var v2 = this.addVector3( v1, o1 );
  356. this.setOrigin( t, v2 );
  357. var m3 = this.multiplyMatrices3( m1, m2 );
  358. this.setBasisFromMatrix3( t, m3 );
  359. this.freeVector3( v1 );
  360. this.freeVector3( v2 );
  361. return t;
  362. },
  363. inverseTransform: function ( t ) {
  364. var t2 = this.allocTransform();
  365. var m1 = this.getBasisAsMatrix3( t );
  366. var o = this.getOrigin( t );
  367. var m2 = this.transposeMatrix3( m1 );
  368. var v1 = this.negativeVector3( o );
  369. var v2 = this.multiplyMatrix3ByVector3( m2, v1 );
  370. this.setOrigin( t2, v2 );
  371. this.setBasisFromMatrix3( t2, m2 );
  372. this.freeVector3( v1 );
  373. this.freeVector3( v2 );
  374. return t2;
  375. },
  376. multiplyMatrices3: function ( m1, m2 ) {
  377. var m3 = [];
  378. var v10 = this.rowOfMatrix3( m1, 0 );
  379. var v11 = this.rowOfMatrix3( m1, 1 );
  380. var v12 = this.rowOfMatrix3( m1, 2 );
  381. var v20 = this.columnOfMatrix3( m2, 0 );
  382. var v21 = this.columnOfMatrix3( m2, 1 );
  383. var v22 = this.columnOfMatrix3( m2, 2 );
  384. m3[ 0 ] = this.dotVectors3( v10, v20 );
  385. m3[ 1 ] = this.dotVectors3( v10, v21 );
  386. m3[ 2 ] = this.dotVectors3( v10, v22 );
  387. m3[ 3 ] = this.dotVectors3( v11, v20 );
  388. m3[ 4 ] = this.dotVectors3( v11, v21 );
  389. m3[ 5 ] = this.dotVectors3( v11, v22 );
  390. m3[ 6 ] = this.dotVectors3( v12, v20 );
  391. m3[ 7 ] = this.dotVectors3( v12, v21 );
  392. m3[ 8 ] = this.dotVectors3( v12, v22 );
  393. this.freeVector3( v10 );
  394. this.freeVector3( v11 );
  395. this.freeVector3( v12 );
  396. this.freeVector3( v20 );
  397. this.freeVector3( v21 );
  398. this.freeVector3( v22 );
  399. return m3;
  400. },
  401. addVector3: function ( v1, v2 ) {
  402. var v = this.allocVector3();
  403. v.setValue( v1.x() + v2.x(), v1.y() + v2.y(), v1.z() + v2.z() );
  404. return v;
  405. },
  406. dotVectors3: function ( v1, v2 ) {
  407. return v1.x() * v2.x() + v1.y() * v2.y() + v1.z() * v2.z();
  408. },
  409. rowOfMatrix3: function ( m, i ) {
  410. var v = this.allocVector3();
  411. v.setValue( m[ i * 3 + 0 ], m[ i * 3 + 1 ], m[ i * 3 + 2 ] );
  412. return v;
  413. },
  414. columnOfMatrix3: function ( m, i ) {
  415. var v = this.allocVector3();
  416. v.setValue( m[ i + 0 ], m[ i + 3 ], m[ i + 6 ] );
  417. return v;
  418. },
  419. negativeVector3: function ( v ) {
  420. var v2 = this.allocVector3();
  421. v2.setValue( - v.x(), - v.y(), - v.z() );
  422. return v2;
  423. },
  424. multiplyMatrix3ByVector3: function ( m, v ) {
  425. var v4 = this.allocVector3();
  426. var v0 = this.rowOfMatrix3( m, 0 );
  427. var v1 = this.rowOfMatrix3( m, 1 );
  428. var v2 = this.rowOfMatrix3( m, 2 );
  429. var x = this.dotVectors3( v0, v );
  430. var y = this.dotVectors3( v1, v );
  431. var z = this.dotVectors3( v2, v );
  432. v4.setValue( x, y, z );
  433. this.freeVector3( v0 );
  434. this.freeVector3( v1 );
  435. this.freeVector3( v2 );
  436. return v4;
  437. },
  438. transposeMatrix3: function ( m ) {
  439. var m2 = [];
  440. m2[ 0 ] = m[ 0 ];
  441. m2[ 1 ] = m[ 3 ];
  442. m2[ 2 ] = m[ 6 ];
  443. m2[ 3 ] = m[ 1 ];
  444. m2[ 4 ] = m[ 4 ];
  445. m2[ 5 ] = m[ 7 ];
  446. m2[ 6 ] = m[ 2 ];
  447. m2[ 7 ] = m[ 5 ];
  448. m2[ 8 ] = m[ 8 ];
  449. return m2;
  450. },
  451. quaternionToMatrix3: function ( q ) {
  452. var m = [];
  453. var x = q.x();
  454. var y = q.y();
  455. var z = q.z();
  456. var w = q.w();
  457. var xx = x * x;
  458. var yy = y * y;
  459. var zz = z * z;
  460. var xy = x * y;
  461. var yz = y * z;
  462. var zx = z * x;
  463. var xw = x * w;
  464. var yw = y * w;
  465. var zw = z * w;
  466. m[ 0 ] = 1 - 2 * ( yy + zz );
  467. m[ 1 ] = 2 * ( xy - zw );
  468. m[ 2 ] = 2 * ( zx + yw );
  469. m[ 3 ] = 2 * ( xy + zw );
  470. m[ 4 ] = 1 - 2 * ( zz + xx );
  471. m[ 5 ] = 2 * ( yz - xw );
  472. m[ 6 ] = 2 * ( zx - yw );
  473. m[ 7 ] = 2 * ( yz + xw );
  474. m[ 8 ] = 1 - 2 * ( xx + yy );
  475. return m;
  476. },
  477. matrix3ToQuaternion: function ( m ) {
  478. var t = m[ 0 ] + m[ 4 ] + m[ 8 ];
  479. var s, x, y, z, w;
  480. if ( t > 0 ) {
  481. s = Math.sqrt( t + 1.0 ) * 2;
  482. w = 0.25 * s;
  483. x = ( m[ 7 ] - m[ 5 ] ) / s;
  484. y = ( m[ 2 ] - m[ 6 ] ) / s;
  485. z = ( m[ 3 ] - m[ 1 ] ) / s;
  486. } else if ( ( m[ 0 ] > m[ 4 ] ) && ( m[ 0 ] > m[ 8 ] ) ) {
  487. s = Math.sqrt( 1.0 + m[ 0 ] - m[ 4 ] - m[ 8 ] ) * 2;
  488. w = ( m[ 7 ] - m[ 5 ] ) / s;
  489. x = 0.25 * s;
  490. y = ( m[ 1 ] + m[ 3 ] ) / s;
  491. z = ( m[ 2 ] + m[ 6 ] ) / s;
  492. } else if ( m[ 4 ] > m[ 8 ] ) {
  493. s = Math.sqrt( 1.0 + m[ 4 ] - m[ 0 ] - m[ 8 ] ) * 2;
  494. w = ( m[ 2 ] - m[ 6 ] ) / s;
  495. x = ( m[ 1 ] + m[ 3 ] ) / s;
  496. y = 0.25 * s;
  497. z = ( m[ 5 ] + m[ 7 ] ) / s;
  498. } else {
  499. s = Math.sqrt( 1.0 + m[ 8 ] - m[ 0 ] - m[ 4 ] ) * 2;
  500. w = ( m[ 3 ] - m[ 1 ] ) / s;
  501. x = ( m[ 2 ] + m[ 6 ] ) / s;
  502. y = ( m[ 5 ] + m[ 7 ] ) / s;
  503. z = 0.25 * s;
  504. }
  505. var q = this.allocQuaternion();
  506. q.setX( x );
  507. q.setY( y );
  508. q.setZ( z );
  509. q.setW( w );
  510. return q;
  511. }
  512. };
  513. /**
  514. * @param {THREE.SkinnedMesh} mesh
  515. * @param {Ammo.btDiscreteDynamicsWorld} world
  516. * @param {Object} params
  517. * @param {ResourceManager} manager
  518. */
  519. function RigidBody( mesh, world, params, manager ) {
  520. this.mesh = mesh;
  521. this.world = world;
  522. this.params = params;
  523. this.manager = manager;
  524. this.body = null;
  525. this.bone = null;
  526. this.boneOffsetForm = null;
  527. this.boneOffsetFormInverse = null;
  528. this._init();
  529. }
  530. RigidBody.prototype = {
  531. constructor: MMDPhysics.RigidBody,
  532. /**
  533. * Resets rigid body transform to the current bone's.
  534. *
  535. * @return {RigidBody}
  536. */
  537. reset: function () {
  538. this._setTransformFromBone();
  539. return this;
  540. },
  541. /**
  542. * Updates rigid body's transform from the current bone.
  543. *
  544. * @return {RidigBody}
  545. */
  546. updateFromBone: function () {
  547. if ( this.params.boneIndex !== - 1 &&
  548. this.params.type === 0 ) {
  549. this._setTransformFromBone();
  550. }
  551. return this;
  552. },
  553. /**
  554. * Updates bone from the current ridid body's transform.
  555. *
  556. * @return {RidigBody}
  557. */
  558. updateBone: function () {
  559. if ( this.params.type === 0 ||
  560. this.params.boneIndex === - 1 ) {
  561. return this;
  562. }
  563. this._updateBoneRotation();
  564. if ( this.params.type === 1 ) {
  565. this._updateBonePosition();
  566. }
  567. this.bone.updateMatrixWorld( true );
  568. if ( this.params.type === 2 ) {
  569. this._setPositionFromBone();
  570. }
  571. return this;
  572. },
  573. // private methods
  574. _init: function () {
  575. function generateShape( p ) {
  576. switch ( p.shapeType ) {
  577. case 0:
  578. return new Ammo.btSphereShape( p.width );
  579. case 1:
  580. return new Ammo.btBoxShape( new Ammo.btVector3( p.width, p.height, p.depth ) );
  581. case 2:
  582. return new Ammo.btCapsuleShape( p.width, p.height );
  583. default:
  584. throw 'unknown shape type ' + p.shapeType;
  585. }
  586. }
  587. var manager = this.manager;
  588. var params = this.params;
  589. var bones = this.mesh.skeleton.bones;
  590. var bone = ( params.boneIndex === - 1 )
  591. ? new THREE.Bone()
  592. : bones[ params.boneIndex ];
  593. var shape = generateShape( params );
  594. var weight = ( params.type === 0 ) ? 0 : params.weight;
  595. var localInertia = manager.allocVector3();
  596. localInertia.setValue( 0, 0, 0 );
  597. if ( weight !== 0 ) {
  598. shape.calculateLocalInertia( weight, localInertia );
  599. }
  600. var boneOffsetForm = manager.allocTransform();
  601. manager.setIdentity( boneOffsetForm );
  602. manager.setOriginFromArray3( boneOffsetForm, params.position );
  603. manager.setBasisFromArray3( boneOffsetForm, params.rotation );
  604. var vector = manager.allocThreeVector3();
  605. var boneForm = manager.allocTransform();
  606. manager.setIdentity( boneForm );
  607. manager.setOriginFromThreeVector3( boneForm, bone.getWorldPosition( vector ) );
  608. var form = manager.multiplyTransforms( boneForm, boneOffsetForm );
  609. var state = new Ammo.btDefaultMotionState( form );
  610. var info = new Ammo.btRigidBodyConstructionInfo( weight, state, shape, localInertia );
  611. info.set_m_friction( params.friction );
  612. info.set_m_restitution( params.restitution );
  613. var body = new Ammo.btRigidBody( info );
  614. if ( params.type === 0 ) {
  615. body.setCollisionFlags( body.getCollisionFlags() | 2 );
  616. /*
  617. * It'd be better to comment out this line though in general I should call this method
  618. * because I'm not sure why but physics will be more like MMD's
  619. * if I comment out.
  620. */
  621. body.setActivationState( 4 );
  622. }
  623. body.setDamping( params.positionDamping, params.rotationDamping );
  624. body.setSleepingThresholds( 0, 0 );
  625. this.world.addRigidBody( body, 1 << params.groupIndex, params.groupTarget );
  626. this.body = body;
  627. this.bone = bone;
  628. this.boneOffsetForm = boneOffsetForm;
  629. this.boneOffsetFormInverse = manager.inverseTransform( boneOffsetForm );
  630. manager.freeVector3( localInertia );
  631. manager.freeTransform( form );
  632. manager.freeTransform( boneForm );
  633. manager.freeThreeVector3( vector );
  634. },
  635. _getBoneTransform: function () {
  636. var manager = this.manager;
  637. var p = manager.allocThreeVector3();
  638. var q = manager.allocThreeQuaternion();
  639. var s = manager.allocThreeVector3();
  640. this.bone.matrixWorld.decompose( p, q, s );
  641. var tr = manager.allocTransform();
  642. manager.setOriginFromThreeVector3( tr, p );
  643. manager.setBasisFromThreeQuaternion( tr, q );
  644. var form = manager.multiplyTransforms( tr, this.boneOffsetForm );
  645. manager.freeTransform( tr );
  646. manager.freeThreeVector3( s );
  647. manager.freeThreeQuaternion( q );
  648. manager.freeThreeVector3( p );
  649. return form;
  650. },
  651. _getWorldTransformForBone: function () {
  652. var manager = this.manager;
  653. var tr = this.body.getCenterOfMassTransform();
  654. return manager.multiplyTransforms( tr, this.boneOffsetFormInverse );
  655. },
  656. _setTransformFromBone: function () {
  657. var manager = this.manager;
  658. var form = this._getBoneTransform();
  659. // TODO: check the most appropriate way to set
  660. //this.body.setWorldTransform( form );
  661. this.body.setCenterOfMassTransform( form );
  662. this.body.getMotionState().setWorldTransform( form );
  663. manager.freeTransform( form );
  664. },
  665. _setPositionFromBone: function () {
  666. var manager = this.manager;
  667. var form = this._getBoneTransform();
  668. var tr = manager.allocTransform();
  669. this.body.getMotionState().getWorldTransform( tr );
  670. manager.copyOrigin( tr, form );
  671. // TODO: check the most appropriate way to set
  672. //this.body.setWorldTransform( tr );
  673. this.body.setCenterOfMassTransform( tr );
  674. this.body.getMotionState().setWorldTransform( tr );
  675. manager.freeTransform( tr );
  676. manager.freeTransform( form );
  677. },
  678. _updateBoneRotation: function () {
  679. var manager = this.manager;
  680. var tr = this._getWorldTransformForBone();
  681. var q = manager.getBasis( tr );
  682. var thQ = manager.allocThreeQuaternion();
  683. var thQ2 = manager.allocThreeQuaternion();
  684. var thQ3 = manager.allocThreeQuaternion();
  685. thQ.set( q.x(), q.y(), q.z(), q.w() );
  686. thQ2.setFromRotationMatrix( this.bone.matrixWorld );
  687. thQ2.conjugate();
  688. thQ2.multiply( thQ );
  689. //this.bone.quaternion.multiply( thQ2 );
  690. thQ3.setFromRotationMatrix( this.bone.matrix );
  691. // Renormalizing quaternion here because repeatedly transforming
  692. // quaternion continuously accumulates floating point error and
  693. // can end up being overflow. See #15335
  694. this.bone.quaternion.copy( thQ2.multiply( thQ3 ).normalize() );
  695. manager.freeThreeQuaternion( thQ );
  696. manager.freeThreeQuaternion( thQ2 );
  697. manager.freeThreeQuaternion( thQ3 );
  698. manager.freeQuaternion( q );
  699. manager.freeTransform( tr );
  700. },
  701. _updateBonePosition: function () {
  702. var manager = this.manager;
  703. var tr = this._getWorldTransformForBone();
  704. var thV = manager.allocThreeVector3();
  705. var o = manager.getOrigin( tr );
  706. thV.set( o.x(), o.y(), o.z() );
  707. if ( this.bone.parent ) {
  708. this.bone.parent.worldToLocal( thV );
  709. }
  710. this.bone.position.copy( thV );
  711. manager.freeThreeVector3( thV );
  712. manager.freeTransform( tr );
  713. }
  714. };
  715. /**
  716. * @param {THREE.SkinnedMesh} mesh
  717. * @param {Ammo.btDiscreteDynamicsWorld} world
  718. * @param {RigidBody} bodyA
  719. * @param {RigidBody} bodyB
  720. * @param {Object} params
  721. * @param {ResourceManager} manager
  722. */
  723. function Constraint( mesh, world, bodyA, bodyB, params, manager ) {
  724. this.mesh = mesh;
  725. this.world = world;
  726. this.bodyA = bodyA;
  727. this.bodyB = bodyB;
  728. this.params = params;
  729. this.manager = manager;
  730. this.constraint = null;
  731. this._init();
  732. }
  733. Constraint.prototype = {
  734. constructor: Constraint,
  735. // private method
  736. _init: function () {
  737. var manager = this.manager;
  738. var params = this.params;
  739. var bodyA = this.bodyA;
  740. var bodyB = this.bodyB;
  741. var form = manager.allocTransform();
  742. manager.setIdentity( form );
  743. manager.setOriginFromArray3( form, params.position );
  744. manager.setBasisFromArray3( form, params.rotation );
  745. var formA = manager.allocTransform();
  746. var formB = manager.allocTransform();
  747. bodyA.body.getMotionState().getWorldTransform( formA );
  748. bodyB.body.getMotionState().getWorldTransform( formB );
  749. var formInverseA = manager.inverseTransform( formA );
  750. var formInverseB = manager.inverseTransform( formB );
  751. var formA2 = manager.multiplyTransforms( formInverseA, form );
  752. var formB2 = manager.multiplyTransforms( formInverseB, form );
  753. var constraint = new Ammo.btGeneric6DofSpringConstraint( bodyA.body, bodyB.body, formA2, formB2, true );
  754. var lll = manager.allocVector3();
  755. var lul = manager.allocVector3();
  756. var all = manager.allocVector3();
  757. var aul = manager.allocVector3();
  758. lll.setValue( params.translationLimitation1[ 0 ],
  759. params.translationLimitation1[ 1 ],
  760. params.translationLimitation1[ 2 ] );
  761. lul.setValue( params.translationLimitation2[ 0 ],
  762. params.translationLimitation2[ 1 ],
  763. params.translationLimitation2[ 2 ] );
  764. all.setValue( params.rotationLimitation1[ 0 ],
  765. params.rotationLimitation1[ 1 ],
  766. params.rotationLimitation1[ 2 ] );
  767. aul.setValue( params.rotationLimitation2[ 0 ],
  768. params.rotationLimitation2[ 1 ],
  769. params.rotationLimitation2[ 2 ] );
  770. constraint.setLinearLowerLimit( lll );
  771. constraint.setLinearUpperLimit( lul );
  772. constraint.setAngularLowerLimit( all );
  773. constraint.setAngularUpperLimit( aul );
  774. for ( var i = 0; i < 3; i ++ ) {
  775. if ( params.springPosition[ i ] !== 0 ) {
  776. constraint.enableSpring( i, true );
  777. constraint.setStiffness( i, params.springPosition[ i ] );
  778. }
  779. }
  780. for ( var i = 0; i < 3; i ++ ) {
  781. if ( params.springRotation[ i ] !== 0 ) {
  782. constraint.enableSpring( i + 3, true );
  783. constraint.setStiffness( i + 3, params.springRotation[ i ] );
  784. }
  785. }
  786. /*
  787. * Currently(10/31/2016) official ammo.js doesn't support
  788. * btGeneric6DofSpringConstraint.setParam method.
  789. * You need custom ammo.js (add the method into idl) if you wanna use.
  790. * By setting this parameter, physics will be more like MMD's
  791. */
  792. if ( constraint.setParam !== undefined ) {
  793. for ( var i = 0; i < 6; i ++ ) {
  794. // this parameter is from http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mmd.three.js
  795. constraint.setParam( 2, 0.475, i );
  796. }
  797. }
  798. this.world.addConstraint( constraint, true );
  799. this.constraint = constraint;
  800. manager.freeTransform( form );
  801. manager.freeTransform( formA );
  802. manager.freeTransform( formB );
  803. manager.freeTransform( formInverseA );
  804. manager.freeTransform( formInverseB );
  805. manager.freeTransform( formA2 );
  806. manager.freeTransform( formB2 );
  807. manager.freeVector3( lll );
  808. manager.freeVector3( lul );
  809. manager.freeVector3( all );
  810. manager.freeVector3( aul );
  811. }
  812. };
  813. /**
  814. * Visualize Rigid bodies
  815. *
  816. * @param {THREE.SkinnedMesh} mesh
  817. * @param {THREE.Physics} physics
  818. */
  819. function MMDPhysicsHelper( mesh, physics ) {
  820. THREE.Object3D.call( this );
  821. this.root = mesh;
  822. this.physics = physics;
  823. this.matrix.copy( mesh.matrixWorld );
  824. this.matrixAutoUpdate = false;
  825. this.materials = [];
  826. this.materials.push(
  827. new THREE.MeshBasicMaterial( {
  828. color: new THREE.Color( 0xff8888 ),
  829. wireframe: true,
  830. depthTest: false,
  831. depthWrite: false,
  832. opacity: 0.25,
  833. transparent: true
  834. } )
  835. );
  836. this.materials.push(
  837. new THREE.MeshBasicMaterial( {
  838. color: new THREE.Color( 0x88ff88 ),
  839. wireframe: true,
  840. depthTest: false,
  841. depthWrite: false,
  842. opacity: 0.25,
  843. transparent: true
  844. } )
  845. );
  846. this.materials.push(
  847. new THREE.MeshBasicMaterial( {
  848. color: new THREE.Color( 0x8888ff ),
  849. wireframe: true,
  850. depthTest: false,
  851. depthWrite: false,
  852. opacity: 0.25,
  853. transparent: true
  854. } )
  855. );
  856. this._init();
  857. }
  858. MMDPhysicsHelper.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), {
  859. constructor: MMDPhysicsHelper,
  860. /**
  861. * Updates Rigid Bodies visualization.
  862. */
  863. updateMatrixWorld: function () {
  864. var position = new THREE.Vector3();
  865. var quaternion = new THREE.Quaternion();
  866. var scale = new THREE.Vector3();
  867. var matrixWorldInv = new THREE.Matrix4();
  868. return function updateMatrixWorld( force ) {
  869. var mesh = this.root;
  870. if ( this.visible ) {
  871. var bodies = this.physics.bodies;
  872. matrixWorldInv
  873. .copy( mesh.matrixWorld )
  874. .decompose( position, quaternion, scale )
  875. .compose( position, quaternion, scale.set( 1, 1, 1 ) )
  876. .getInverse( matrixWorldInv );
  877. for ( var i = 0, il = bodies.length; i < il; i ++ ) {
  878. var body = bodies[ i ].body;
  879. var child = this.children[ i ];
  880. var tr = body.getCenterOfMassTransform();
  881. var origin = tr.getOrigin();
  882. var rotation = tr.getRotation();
  883. child.position
  884. .set( origin.x(), origin.y(), origin.z() )
  885. .applyMatrix4( matrixWorldInv );
  886. child.quaternion
  887. .setFromRotationMatrix( matrixWorldInv )
  888. .multiply(
  889. quaternion.set(
  890. rotation.x(), rotation.y(), rotation.z(), rotation.w() )
  891. );
  892. }
  893. }
  894. this.matrix
  895. .copy( mesh.matrixWorld )
  896. .decompose( position, quaternion, scale )
  897. .compose( position, quaternion, scale.set( 1, 1, 1 ) );
  898. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  899. };
  900. }(),
  901. // private method
  902. _init: function () {
  903. var bodies = this.physics.bodies;
  904. function createGeometry( param ) {
  905. switch ( param.shapeType ) {
  906. case 0:
  907. return new THREE.SphereBufferGeometry( param.width, 16, 8 );
  908. case 1:
  909. return new THREE.BoxBufferGeometry( param.width * 2, param.height * 2, param.depth * 2, 8, 8, 8 );
  910. case 2:
  911. return new createCapsuleGeometry( param.width, param.height, 16, 8 );
  912. default:
  913. return null;
  914. }
  915. }
  916. // copy from http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mytest37.js?ver=20160815
  917. function createCapsuleGeometry( radius, cylinderHeight, segmentsRadius, segmentsHeight ) {
  918. var geometry = new THREE.CylinderBufferGeometry( radius, radius, cylinderHeight, segmentsRadius, segmentsHeight, true );
  919. var upperSphere = new THREE.Mesh( new THREE.SphereBufferGeometry( radius, segmentsRadius, segmentsHeight, 0, Math.PI * 2, 0, Math.PI / 2 ) );
  920. var lowerSphere = new THREE.Mesh( new THREE.SphereBufferGeometry( radius, segmentsRadius, segmentsHeight, 0, Math.PI * 2, Math.PI / 2, Math.PI / 2 ) );
  921. upperSphere.position.set( 0, cylinderHeight / 2, 0 );
  922. lowerSphere.position.set( 0, - cylinderHeight / 2, 0 );
  923. upperSphere.updateMatrix();
  924. lowerSphere.updateMatrix();
  925. geometry.merge( upperSphere.geometry, upperSphere.matrix );
  926. geometry.merge( lowerSphere.geometry, lowerSphere.matrix );
  927. return geometry;
  928. }
  929. for ( var i = 0, il = bodies.length; i < il; i ++ ) {
  930. var param = bodies[ i ].params;
  931. this.add( new THREE.Mesh( createGeometry( param ), this.materials[ param.type ] ) );
  932. }
  933. }
  934. } );
  935. return MMDPhysics;
  936. } )();