MMDPhysics.js 30 KB

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