MMDPhysics.js 30 KB

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