MMDPhysics.js 30 KB

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