2
0

MMDPhysics.js 30 KB

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