MMDPhysics.js 28 KB

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