MMDPhysics.js 30 KB

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