MMDPhysics.js 28 KB

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