2
0

MMDPhysics.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410
  1. console.warn( "THREE.MMDPhysics: As part of the transition to ES6 Modules, the files in 'examples/js' were deprecated in May 2020 (r117) and will be deleted in December 2020 (r124). You can find more information about developing using ES6 Modules in https://threejs.org/docs/#manual/en/introduction/Installation." );
  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 THREE.MMDLoader.
  8. *
  9. * TODO
  10. * - Physics in Worker
  11. */
  12. /* global Ammo */
  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. // Renormalizing quaternion here because repeatedly transforming
  691. // quaternion continuously accumulates floating point error and
  692. // can end up being overflow. See #15335
  693. this.bone.quaternion.copy( thQ2.multiply( thQ3 ).normalize() );
  694. manager.freeThreeQuaternion( thQ );
  695. manager.freeThreeQuaternion( thQ2 );
  696. manager.freeThreeQuaternion( thQ3 );
  697. manager.freeQuaternion( q );
  698. manager.freeTransform( tr );
  699. },
  700. _updateBonePosition: function () {
  701. var manager = this.manager;
  702. var tr = this._getWorldTransformForBone();
  703. var thV = manager.allocThreeVector3();
  704. var o = manager.getOrigin( tr );
  705. thV.set( o.x(), o.y(), o.z() );
  706. if ( this.bone.parent ) {
  707. this.bone.parent.worldToLocal( thV );
  708. }
  709. this.bone.position.copy( thV );
  710. manager.freeThreeVector3( thV );
  711. manager.freeTransform( tr );
  712. }
  713. };
  714. /**
  715. * @param {THREE.SkinnedMesh} mesh
  716. * @param {Ammo.btDiscreteDynamicsWorld} world
  717. * @param {RigidBody} bodyA
  718. * @param {RigidBody} bodyB
  719. * @param {Object} params
  720. * @param {ResourceManager} manager
  721. */
  722. function Constraint( mesh, world, bodyA, bodyB, params, manager ) {
  723. this.mesh = mesh;
  724. this.world = world;
  725. this.bodyA = bodyA;
  726. this.bodyB = bodyB;
  727. this.params = params;
  728. this.manager = manager;
  729. this.constraint = null;
  730. this._init();
  731. }
  732. Constraint.prototype = {
  733. constructor: Constraint,
  734. // private method
  735. _init: function () {
  736. var manager = this.manager;
  737. var params = this.params;
  738. var bodyA = this.bodyA;
  739. var bodyB = this.bodyB;
  740. var form = manager.allocTransform();
  741. manager.setIdentity( form );
  742. manager.setOriginFromArray3( form, params.position );
  743. manager.setBasisFromArray3( form, params.rotation );
  744. var formA = manager.allocTransform();
  745. var formB = manager.allocTransform();
  746. bodyA.body.getMotionState().getWorldTransform( formA );
  747. bodyB.body.getMotionState().getWorldTransform( formB );
  748. var formInverseA = manager.inverseTransform( formA );
  749. var formInverseB = manager.inverseTransform( formB );
  750. var formA2 = manager.multiplyTransforms( formInverseA, form );
  751. var formB2 = manager.multiplyTransforms( formInverseB, form );
  752. var constraint = new Ammo.btGeneric6DofSpringConstraint( bodyA.body, bodyB.body, formA2, formB2, true );
  753. var lll = manager.allocVector3();
  754. var lul = manager.allocVector3();
  755. var all = manager.allocVector3();
  756. var aul = manager.allocVector3();
  757. lll.setValue( params.translationLimitation1[ 0 ],
  758. params.translationLimitation1[ 1 ],
  759. params.translationLimitation1[ 2 ] );
  760. lul.setValue( params.translationLimitation2[ 0 ],
  761. params.translationLimitation2[ 1 ],
  762. params.translationLimitation2[ 2 ] );
  763. all.setValue( params.rotationLimitation1[ 0 ],
  764. params.rotationLimitation1[ 1 ],
  765. params.rotationLimitation1[ 2 ] );
  766. aul.setValue( params.rotationLimitation2[ 0 ],
  767. params.rotationLimitation2[ 1 ],
  768. params.rotationLimitation2[ 2 ] );
  769. constraint.setLinearLowerLimit( lll );
  770. constraint.setLinearUpperLimit( lul );
  771. constraint.setAngularLowerLimit( all );
  772. constraint.setAngularUpperLimit( aul );
  773. for ( var i = 0; i < 3; i ++ ) {
  774. if ( params.springPosition[ i ] !== 0 ) {
  775. constraint.enableSpring( i, true );
  776. constraint.setStiffness( i, params.springPosition[ i ] );
  777. }
  778. }
  779. for ( var i = 0; i < 3; i ++ ) {
  780. if ( params.springRotation[ i ] !== 0 ) {
  781. constraint.enableSpring( i + 3, true );
  782. constraint.setStiffness( i + 3, params.springRotation[ i ] );
  783. }
  784. }
  785. /*
  786. * Currently(10/31/2016) official ammo.js doesn't support
  787. * btGeneric6DofSpringConstraint.setParam method.
  788. * You need custom ammo.js (add the method into idl) if you wanna use.
  789. * By setting this parameter, physics will be more like MMD's
  790. */
  791. if ( constraint.setParam !== undefined ) {
  792. for ( var i = 0; i < 6; i ++ ) {
  793. // this parameter is from http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mmd.three.js
  794. constraint.setParam( 2, 0.475, i );
  795. }
  796. }
  797. this.world.addConstraint( constraint, true );
  798. this.constraint = constraint;
  799. manager.freeTransform( form );
  800. manager.freeTransform( formA );
  801. manager.freeTransform( formB );
  802. manager.freeTransform( formInverseA );
  803. manager.freeTransform( formInverseB );
  804. manager.freeTransform( formA2 );
  805. manager.freeTransform( formB2 );
  806. manager.freeVector3( lll );
  807. manager.freeVector3( lul );
  808. manager.freeVector3( all );
  809. manager.freeVector3( aul );
  810. }
  811. };
  812. /**
  813. * Visualize Rigid bodies
  814. *
  815. * @param {THREE.SkinnedMesh} mesh
  816. * @param {THREE.Physics} physics
  817. */
  818. function MMDPhysicsHelper( mesh, physics ) {
  819. THREE.Object3D.call( this );
  820. this.root = mesh;
  821. this.physics = physics;
  822. this.matrix.copy( mesh.matrixWorld );
  823. this.matrixAutoUpdate = false;
  824. this.materials = [];
  825. this.materials.push(
  826. new THREE.MeshBasicMaterial( {
  827. color: new THREE.Color( 0xff8888 ),
  828. wireframe: true,
  829. depthTest: false,
  830. depthWrite: false,
  831. opacity: 0.25,
  832. transparent: true
  833. } )
  834. );
  835. this.materials.push(
  836. new THREE.MeshBasicMaterial( {
  837. color: new THREE.Color( 0x88ff88 ),
  838. wireframe: true,
  839. depthTest: false,
  840. depthWrite: false,
  841. opacity: 0.25,
  842. transparent: true
  843. } )
  844. );
  845. this.materials.push(
  846. new THREE.MeshBasicMaterial( {
  847. color: new THREE.Color( 0x8888ff ),
  848. wireframe: true,
  849. depthTest: false,
  850. depthWrite: false,
  851. opacity: 0.25,
  852. transparent: true
  853. } )
  854. );
  855. this._init();
  856. }
  857. MMDPhysicsHelper.prototype = Object.assign( Object.create( THREE.Object3D.prototype ), {
  858. constructor: MMDPhysicsHelper,
  859. /**
  860. * Updates Rigid Bodies visualization.
  861. */
  862. updateMatrixWorld: function () {
  863. var position = new THREE.Vector3();
  864. var quaternion = new THREE.Quaternion();
  865. var scale = new THREE.Vector3();
  866. var matrixWorldInv = new THREE.Matrix4();
  867. return function updateMatrixWorld( force ) {
  868. var mesh = this.root;
  869. if ( this.visible ) {
  870. var bodies = this.physics.bodies;
  871. matrixWorldInv
  872. .copy( mesh.matrixWorld )
  873. .decompose( position, quaternion, scale )
  874. .compose( position, quaternion, scale.set( 1, 1, 1 ) )
  875. .getInverse( matrixWorldInv );
  876. for ( var i = 0, il = bodies.length; i < il; i ++ ) {
  877. var body = bodies[ i ].body;
  878. var child = this.children[ i ];
  879. var tr = body.getCenterOfMassTransform();
  880. var origin = tr.getOrigin();
  881. var rotation = tr.getRotation();
  882. child.position
  883. .set( origin.x(), origin.y(), origin.z() )
  884. .applyMatrix4( matrixWorldInv );
  885. child.quaternion
  886. .setFromRotationMatrix( matrixWorldInv )
  887. .multiply(
  888. quaternion.set(
  889. rotation.x(), rotation.y(), rotation.z(), rotation.w() )
  890. );
  891. }
  892. }
  893. this.matrix
  894. .copy( mesh.matrixWorld )
  895. .decompose( position, quaternion, scale )
  896. .compose( position, quaternion, scale.set( 1, 1, 1 ) );
  897. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  898. };
  899. }(),
  900. // private method
  901. _init: function () {
  902. var bodies = this.physics.bodies;
  903. function createGeometry( param ) {
  904. switch ( param.shapeType ) {
  905. case 0:
  906. return new THREE.SphereBufferGeometry( param.width, 16, 8 );
  907. case 1:
  908. return new THREE.BoxBufferGeometry( param.width * 2, param.height * 2, param.depth * 2, 8, 8, 8 );
  909. case 2:
  910. return new createCapsuleGeometry( param.width, param.height, 16, 8 );
  911. default:
  912. return null;
  913. }
  914. }
  915. // copy from http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mytest37.js?ver=20160815
  916. function createCapsuleGeometry( radius, cylinderHeight, segmentsRadius, segmentsHeight ) {
  917. var geometry = new THREE.CylinderBufferGeometry( radius, radius, cylinderHeight, segmentsRadius, segmentsHeight, true );
  918. var upperSphere = new THREE.Mesh( new THREE.SphereBufferGeometry( radius, segmentsRadius, segmentsHeight, 0, Math.PI * 2, 0, Math.PI / 2 ) );
  919. var lowerSphere = new THREE.Mesh( new THREE.SphereBufferGeometry( radius, segmentsRadius, segmentsHeight, 0, Math.PI * 2, Math.PI / 2, Math.PI / 2 ) );
  920. upperSphere.position.set( 0, cylinderHeight / 2, 0 );
  921. lowerSphere.position.set( 0, - cylinderHeight / 2, 0 );
  922. upperSphere.updateMatrix();
  923. lowerSphere.updateMatrix();
  924. geometry.merge( upperSphere.geometry, upperSphere.matrix );
  925. geometry.merge( lowerSphere.geometry, lowerSphere.matrix );
  926. return geometry;
  927. }
  928. for ( var i = 0, il = bodies.length; i < il; i ++ ) {
  929. var param = bodies[ i ].params;
  930. this.add( new THREE.Mesh( createGeometry( param ), this.materials[ param.type ] ) );
  931. }
  932. }
  933. } );
  934. return MMDPhysics;
  935. } )();