MMDPhysics.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  1. /**
  2. * @author takahiro / https://github.com/takahirox
  3. *
  4. * Dependencies
  5. * - Ammo.js https://github.com/kripken/ammo.js
  6. *
  7. * MMD specific Physics class.
  8. *
  9. * See THREE.MMDLoader for the passed parameter list of RigidBody/Constraint.
  10. *
  11. * Requirement:
  12. * - don't change object's scale from (1,1,1) after setting physics to object
  13. *
  14. * TODO
  15. * - optimize for the performance
  16. * - use Physijs http://chandlerprall.github.io/Physijs/
  17. * and improve the performance by making use of Web worker.
  18. * - if possible, make this class being non-MMD specific.
  19. * - object scale change support
  20. */
  21. THREE.MMDPhysics = function ( mesh, params ) {
  22. if ( params === undefined ) params = {};
  23. this.mesh = mesh;
  24. this.helper = new THREE.MMDPhysics.ResourceHelper();
  25. /*
  26. * I don't know why but 1/60 unitStep easily breaks models
  27. * so I set it 1/65 so far.
  28. * Don't set too small unitStep because
  29. * the smaller unitStep can make the performance worse.
  30. */
  31. this.unitStep = ( params.unitStep !== undefined ) ? params.unitStep : 1 / 65;
  32. this.maxStepNum = ( params.maxStepNum !== undefined ) ? params.maxStepNum : 3;
  33. this.world = params.world !== undefined ? params.world : null;
  34. this.bodies = [];
  35. this.constraints = [];
  36. this.init( mesh );
  37. };
  38. THREE.MMDPhysics.prototype = {
  39. constructor: THREE.MMDPhysics,
  40. init: function ( mesh ) {
  41. var parent = mesh.parent;
  42. if ( parent !== null ) {
  43. parent.remove( mesh );
  44. }
  45. var currentPosition = mesh.position.clone();
  46. var currentRotation = mesh.rotation.clone();
  47. var currentScale = mesh.scale.clone();
  48. mesh.position.set( 0, 0, 0 );
  49. mesh.rotation.set( 0, 0, 0 );
  50. mesh.scale.set( 1, 1, 1 );
  51. mesh.updateMatrixWorld( true );
  52. if ( this.world === null ) this.initWorld();
  53. this.initRigidBodies();
  54. this.initConstraints();
  55. if ( parent !== null ) {
  56. parent.add( mesh );
  57. }
  58. mesh.position.copy( currentPosition );
  59. mesh.rotation.copy( currentRotation );
  60. mesh.scale.copy( currentScale );
  61. mesh.updateMatrixWorld( true );
  62. this.reset();
  63. },
  64. initWorld: function () {
  65. var config = new Ammo.btDefaultCollisionConfiguration();
  66. var dispatcher = new Ammo.btCollisionDispatcher( config );
  67. var cache = new Ammo.btDbvtBroadphase();
  68. var solver = new Ammo.btSequentialImpulseConstraintSolver();
  69. var world = new Ammo.btDiscreteDynamicsWorld( dispatcher, cache, solver, config );
  70. world.setGravity( new Ammo.btVector3( 0, -9.8 * 10, 0 ) );
  71. this.world = world;
  72. },
  73. initRigidBodies: function () {
  74. var bodies = this.mesh.geometry.rigidBodies;
  75. for ( var i = 0; i < bodies.length; i++ ) {
  76. var b = new THREE.MMDPhysics.RigidBody( this.mesh, this.world, bodies[ i ], this.helper );
  77. this.bodies.push( b );
  78. }
  79. },
  80. initConstraints: function () {
  81. var constraints = this.mesh.geometry.constraints;
  82. for ( var i = 0; i < constraints.length; i++ ) {
  83. var params = constraints[ i ];
  84. var bodyA = this.bodies[ params.rigidBodyIndex1 ];
  85. var bodyB = this.bodies[ params.rigidBodyIndex2 ];
  86. var c = new THREE.MMDPhysics.Constraint( this.mesh, this.world, bodyA, bodyB, params, this.helper );
  87. this.constraints.push( c );
  88. }
  89. },
  90. update: function ( delta ) {
  91. this.updateRigidBodies();
  92. this.stepSimulation( delta );
  93. this.updateBones();
  94. },
  95. stepSimulation: function ( delta ) {
  96. var unitStep = this.unitStep;
  97. var stepTime = delta;
  98. var maxStepNum = ( ( delta / unitStep ) | 0 ) + 1;
  99. if ( stepTime < unitStep ) {
  100. stepTime = unitStep;
  101. maxStepNum = 1;
  102. }
  103. if ( maxStepNum > this.maxStepNum ) {
  104. maxStepNum = this.maxStepNum;
  105. }
  106. this.world.stepSimulation( stepTime, maxStepNum, unitStep );
  107. },
  108. updateRigidBodies: function () {
  109. for ( var i = 0; i < this.bodies.length; i++ ) {
  110. this.bodies[ i ].updateFromBone();
  111. }
  112. },
  113. updateBones: function () {
  114. for ( var i = 0; i < this.bodies.length; i++ ) {
  115. this.bodies[ i ].updateBone();
  116. }
  117. },
  118. reset: function () {
  119. for ( var i = 0; i < this.bodies.length; i++ ) {
  120. this.bodies[ i ].reset();
  121. }
  122. },
  123. warmup: function ( cycles ) {
  124. for ( var i = 0; i < cycles; i++ ) {
  125. this.update( 1 / 60 );
  126. }
  127. }
  128. };
  129. /**
  130. * This helper class responsibilies are
  131. *
  132. * 1. manage Ammo.js and Three.js object resources and
  133. * improve the performance and the memory consumption by
  134. * reusing objects.
  135. *
  136. * 2. provide simple Ammo object operations.
  137. */
  138. THREE.MMDPhysics.ResourceHelper = function () {
  139. // for Three.js
  140. this.threeVector3s = [];
  141. this.threeMatrix4s = [];
  142. this.threeQuaternions = [];
  143. this.threeEulers = [];
  144. // for Ammo.js
  145. this.transforms = [];
  146. this.quaternions = [];
  147. this.vector3s = [];
  148. };
  149. THREE.MMDPhysics.ResourceHelper.prototype = {
  150. allocThreeVector3: function () {
  151. return ( this.threeVector3s.length > 0 ) ? this.threeVector3s.pop() : new THREE.Vector3();
  152. },
  153. freeThreeVector3: function ( v ) {
  154. this.threeVector3s.push( v );
  155. },
  156. allocThreeMatrix4: function () {
  157. return ( this.threeMatrix4s.length > 0 ) ? this.threeMatrix4s.pop() : new THREE.Matrix4();
  158. },
  159. freeThreeMatrix4: function ( m ) {
  160. this.threeMatrix4s.push( m );
  161. },
  162. allocThreeQuaternion: function () {
  163. return ( this.threeQuaternions.length > 0 ) ? this.threeQuaternions.pop() : new THREE.Quaternion();
  164. },
  165. freeThreeQuaternion: function ( q ) {
  166. this.threeQuaternions.push( q );
  167. },
  168. allocThreeEuler: function () {
  169. return ( this.threeEulers.length > 0 ) ? this.threeEulers.pop() : new THREE.Euler();
  170. },
  171. freeThreeEuler: function ( e ) {
  172. this.threeEulers.push( e );
  173. },
  174. allocTransform: function () {
  175. return ( this.transforms.length > 0 ) ? this.transforms.pop() : new Ammo.btTransform();
  176. },
  177. freeTransform: function ( t ) {
  178. this.transforms.push( t );
  179. },
  180. allocQuaternion: function () {
  181. return ( this.quaternions.length > 0 ) ? this.quaternions.pop() : new Ammo.btQuaternion();
  182. },
  183. freeQuaternion: function ( q ) {
  184. this.quaternions.push( q );
  185. },
  186. allocVector3: function () {
  187. return ( this.vector3s.length > 0 ) ? this.vector3s.pop() : new Ammo.btVector3();
  188. },
  189. freeVector3: function ( v ) {
  190. this.vector3s.push( v );
  191. },
  192. setIdentity: function ( t ) {
  193. t.setIdentity();
  194. },
  195. getBasis: function ( t ) {
  196. var q = this.allocQuaternion();
  197. t.getBasis().getRotation( q );
  198. return q;
  199. },
  200. getBasisAsMatrix3: function ( t ) {
  201. var q = this.getBasis( t );
  202. var m = this.quaternionToMatrix3( q );
  203. this.freeQuaternion( q );
  204. return m;
  205. },
  206. getOrigin: function( t ) {
  207. return t.getOrigin();
  208. },
  209. setOrigin: function( t, v ) {
  210. t.getOrigin().setValue( v.x(), v.y(), v.z() );
  211. },
  212. copyOrigin: function( t1, t2 ) {
  213. var o = t2.getOrigin();
  214. this.setOrigin( t1, o );
  215. },
  216. setBasis: function( t, q ) {
  217. t.setRotation( q );
  218. },
  219. setBasisFromMatrix3: function( t, m ) {
  220. var q = this.matrix3ToQuaternion( m );
  221. this.setBasis( t, q );
  222. this.freeQuaternion( q );
  223. },
  224. setOriginFromArray3: function ( t, a ) {
  225. t.getOrigin().setValue( a[ 0 ], a[ 1 ], a[ 2 ] );
  226. },
  227. setBasisFromArray3: function ( t, a ) {
  228. var thQ = this.allocThreeQuaternion();
  229. var thE = this.allocThreeEuler();
  230. thE.set( a[ 0 ], a[ 1 ], a[ 2 ] );
  231. this.setBasisFromArray4( t, thQ.setFromEuler( thE ).toArray() );
  232. this.freeThreeEuler( thE );
  233. this.freeThreeQuaternion( thQ );
  234. },
  235. setBasisFromArray4: function ( t, a ) {
  236. var q = this.array4ToQuaternion( a );
  237. this.setBasis( t, q );
  238. this.freeQuaternion( q );
  239. },
  240. array4ToQuaternion: function( a ) {
  241. var q = this.allocQuaternion();
  242. q.setX( a[ 0 ] );
  243. q.setY( a[ 1 ] );
  244. q.setZ( a[ 2 ] );
  245. q.setW( a[ 3 ] );
  246. return q;
  247. },
  248. multiplyTransforms: function ( t1, t2 ) {
  249. var t = this.allocTransform();
  250. this.setIdentity( t );
  251. var m1 = this.getBasisAsMatrix3( t1 );
  252. var m2 = this.getBasisAsMatrix3( t2 );
  253. var o1 = this.getOrigin( t1 );
  254. var o2 = this.getOrigin( t2 );
  255. var v1 = this.multiplyMatrix3ByVector3( m1, o2 );
  256. var v2 = this.addVector3( v1, o1 );
  257. this.setOrigin( t, v2 );
  258. var m3 = this.multiplyMatrices3( m1, m2 );
  259. this.setBasisFromMatrix3( t, m3 );
  260. this.freeVector3( v1 );
  261. this.freeVector3( v2 );
  262. return t;
  263. },
  264. inverseTransform: function ( t ) {
  265. var t2 = this.allocTransform();
  266. var m1 = this.getBasisAsMatrix3( t );
  267. var o = this.getOrigin( t );
  268. var m2 = this.transposeMatrix3( m1 );
  269. var v1 = this.negativeVector3( o );
  270. var v2 = this.multiplyMatrix3ByVector3( m2, v1 );
  271. this.setOrigin( t2, v2 );
  272. this.setBasisFromMatrix3( t2, m2 );
  273. this.freeVector3( v1 );
  274. this.freeVector3( v2 );
  275. return t2;
  276. },
  277. multiplyMatrices3: function ( m1, m2 ) {
  278. var m3 = [];
  279. var v10 = this.rowOfMatrix3( m1, 0 );
  280. var v11 = this.rowOfMatrix3( m1, 1 );
  281. var v12 = this.rowOfMatrix3( m1, 2 );
  282. var v20 = this.columnOfMatrix3( m2, 0 );
  283. var v21 = this.columnOfMatrix3( m2, 1 );
  284. var v22 = this.columnOfMatrix3( m2, 2 );
  285. m3[ 0 ] = this.dotVectors3( v10, v20 );
  286. m3[ 1 ] = this.dotVectors3( v10, v21 );
  287. m3[ 2 ] = this.dotVectors3( v10, v22 );
  288. m3[ 3 ] = this.dotVectors3( v11, v20 );
  289. m3[ 4 ] = this.dotVectors3( v11, v21 );
  290. m3[ 5 ] = this.dotVectors3( v11, v22 );
  291. m3[ 6 ] = this.dotVectors3( v12, v20 );
  292. m3[ 7 ] = this.dotVectors3( v12, v21 );
  293. m3[ 8 ] = this.dotVectors3( v12, v22 );
  294. this.freeVector3( v10 );
  295. this.freeVector3( v11 );
  296. this.freeVector3( v12 );
  297. this.freeVector3( v20 );
  298. this.freeVector3( v21 );
  299. this.freeVector3( v22 );
  300. return m3;
  301. },
  302. addVector3: function( v1, v2 ) {
  303. var v = this.allocVector3();
  304. v.setValue( v1.x() + v2.x(), v1.y() + v2.y(), v1.z() + v2.z() );
  305. return v;
  306. },
  307. dotVectors3: function( v1, v2 ) {
  308. return v1.x() * v2.x() + v1.y() * v2.y() + v1.z() * v2.z();
  309. },
  310. rowOfMatrix3: function( m, i ) {
  311. var v = this.allocVector3();
  312. v.setValue( m[ i * 3 + 0 ], m[ i * 3 + 1 ], m[ i * 3 + 2 ] );
  313. return v;
  314. },
  315. columnOfMatrix3: function( m, i ) {
  316. var v = this.allocVector3();
  317. v.setValue( m[ i + 0 ], m[ i + 3 ], m[ i + 6 ] );
  318. return v;
  319. },
  320. negativeVector3: function( v ) {
  321. var v2 = this.allocVector3();
  322. v2.setValue( -v.x(), -v.y(), -v.z() );
  323. return v2;
  324. },
  325. multiplyMatrix3ByVector3: function ( m, v ) {
  326. var v4 = this.allocVector3();
  327. var v0 = this.rowOfMatrix3( m, 0 );
  328. var v1 = this.rowOfMatrix3( m, 1 );
  329. var v2 = this.rowOfMatrix3( m, 2 );
  330. var x = this.dotVectors3( v0, v );
  331. var y = this.dotVectors3( v1, v );
  332. var z = this.dotVectors3( v2, v );
  333. v4.setValue( x, y, z );
  334. this.freeVector3( v0 );
  335. this.freeVector3( v1 );
  336. this.freeVector3( v2 );
  337. return v4;
  338. },
  339. transposeMatrix3: function( m ) {
  340. var m2 = [];
  341. m2[ 0 ] = m[ 0 ];
  342. m2[ 1 ] = m[ 3 ];
  343. m2[ 2 ] = m[ 6 ];
  344. m2[ 3 ] = m[ 1 ];
  345. m2[ 4 ] = m[ 4 ];
  346. m2[ 5 ] = m[ 7 ];
  347. m2[ 6 ] = m[ 2 ];
  348. m2[ 7 ] = m[ 5 ];
  349. m2[ 8 ] = m[ 8 ];
  350. return m2;
  351. },
  352. quaternionToMatrix3: function ( q ) {
  353. var m = [];
  354. var x = q.x();
  355. var y = q.y();
  356. var z = q.z();
  357. var w = q.w();
  358. var xx = x * x;
  359. var yy = y * y;
  360. var zz = z * z;
  361. var xy = x * y;
  362. var yz = y * z;
  363. var zx = z * x;
  364. var xw = x * w;
  365. var yw = y * w;
  366. var zw = z * w;
  367. m[ 0 ] = 1 - 2 * ( yy + zz );
  368. m[ 1 ] = 2 * ( xy - zw );
  369. m[ 2 ] = 2 * ( zx + yw );
  370. m[ 3 ] = 2 * ( xy + zw );
  371. m[ 4 ] = 1 - 2 * ( zz + xx );
  372. m[ 5 ] = 2 * ( yz - xw );
  373. m[ 6 ] = 2 * ( zx - yw );
  374. m[ 7 ] = 2 * ( yz + xw );
  375. m[ 8 ] = 1 - 2 * ( xx + yy );
  376. return m;
  377. },
  378. matrix3ToQuaternion: function( m ) {
  379. var t = m[ 0 ] + m[ 4 ] + m[ 8 ];
  380. var s, x, y, z, w;
  381. if( t > 0 ) {
  382. s = Math.sqrt( t + 1.0 ) * 2;
  383. w = 0.25 * s;
  384. x = ( m[ 7 ] - m[ 5 ] ) / s;
  385. y = ( m[ 2 ] - m[ 6 ] ) / s;
  386. z = ( m[ 3 ] - m[ 1 ] ) / s;
  387. } else if( ( m[ 0 ] > m[ 4 ] ) && ( m[ 0 ] > m[ 8 ] ) ) {
  388. s = Math.sqrt( 1.0 + m[ 0 ] - m[ 4 ] - m[ 8 ] ) * 2;
  389. w = ( m[ 7 ] - m[ 5 ] ) / s;
  390. x = 0.25 * s;
  391. y = ( m[ 1 ] + m[ 3 ] ) / s;
  392. z = ( m[ 2 ] + m[ 6 ] ) / s;
  393. } else if( m[ 4 ] > m[ 8 ] ) {
  394. s = Math.sqrt( 1.0 + m[ 4 ] - m[ 0 ] - m[ 8 ] ) * 2;
  395. w = ( m[ 2 ] - m[ 6 ] ) / s;
  396. x = ( m[ 1 ] + m[ 3 ] ) / s;
  397. y = 0.25 * s;
  398. z = ( m[ 5 ] + m[ 7 ] ) / s;
  399. } else {
  400. s = Math.sqrt( 1.0 + m[ 8 ] - m[ 0 ] - m[ 4 ] ) * 2;
  401. w = ( m[ 3 ] - m[ 1 ] ) / s;
  402. x = ( m[ 2 ] + m[ 6 ] ) / s;
  403. y = ( m[ 5 ] + m[ 7 ] ) / s;
  404. z = 0.25 * s;
  405. }
  406. var q = this.allocQuaternion();
  407. q.setX( x );
  408. q.setY( y );
  409. q.setZ( z );
  410. q.setW( w );
  411. return q;
  412. }
  413. };
  414. THREE.MMDPhysics.RigidBody = function ( mesh, world, params, helper ) {
  415. this.mesh = mesh;
  416. this.world = world;
  417. this.params = params;
  418. this.helper = helper;
  419. this.body = null;
  420. this.bone = null;
  421. this.boneOffsetForm = null;
  422. this.boneOffsetFormInverse = null;
  423. this.init();
  424. };
  425. THREE.MMDPhysics.RigidBody.prototype = {
  426. constructor: THREE.MMDPhysics.RigidBody,
  427. init: function () {
  428. function generateShape( p ) {
  429. switch( p.shapeType ) {
  430. case 0:
  431. return new Ammo.btSphereShape( p.width );
  432. case 1:
  433. return new Ammo.btBoxShape( new Ammo.btVector3( p.width, p.height, p.depth ) );
  434. case 2:
  435. return new Ammo.btCapsuleShape( p.width, p.height );
  436. default:
  437. throw 'unknown shape type ' + p.shapeType;
  438. }
  439. }
  440. var helper = this.helper;
  441. var params = this.params;
  442. var bones = this.mesh.skeleton.bones;
  443. var bone = ( params.boneIndex === -1 ) ? new THREE.Bone() : bones[ params.boneIndex ];
  444. var shape = generateShape( params );
  445. var weight = ( params.type === 0 ) ? 0 : params.weight;
  446. var localInertia = helper.allocVector3();
  447. localInertia.setValue( 0, 0, 0 );
  448. if( weight !== 0 ) {
  449. shape.calculateLocalInertia( weight, localInertia );
  450. }
  451. var boneOffsetForm = helper.allocTransform();
  452. helper.setIdentity( boneOffsetForm );
  453. helper.setOriginFromArray3( boneOffsetForm, params.position );
  454. helper.setBasisFromArray3( boneOffsetForm, params.rotation );
  455. var boneForm = helper.allocTransform();
  456. helper.setIdentity( boneForm );
  457. helper.setOriginFromArray3( boneForm, bone.getWorldPosition().toArray() );
  458. var form = helper.multiplyTransforms( boneForm, boneOffsetForm );
  459. var state = new Ammo.btDefaultMotionState( form );
  460. var info = new Ammo.btRigidBodyConstructionInfo( weight, state, shape, localInertia );
  461. info.set_m_friction( params.friction );
  462. info.set_m_restitution( params.restitution );
  463. var body = new Ammo.btRigidBody( info );
  464. if ( params.type === 0 ) {
  465. body.setCollisionFlags( body.getCollisionFlags() | 2 );
  466. /*
  467. * It'd be better to comment out this line though in general I should call this method
  468. * because I'm not sure why but physics will be more like MMD's
  469. * if I comment out.
  470. */
  471. body.setActivationState( 4 );
  472. }
  473. body.setDamping( params.positionDamping, params.rotationDamping );
  474. body.setSleepingThresholds( 0, 0 );
  475. this.world.addRigidBody( body, 1 << params.groupIndex, params.groupTarget );
  476. this.body = body;
  477. this.bone = bone;
  478. this.boneOffsetForm = boneOffsetForm;
  479. this.boneOffsetFormInverse = helper.inverseTransform( boneOffsetForm );
  480. helper.freeVector3( localInertia );
  481. helper.freeTransform( form );
  482. helper.freeTransform( boneForm );
  483. },
  484. reset: function () {
  485. this.setTransformFromBone();
  486. },
  487. updateFromBone: function () {
  488. if ( this.params.boneIndex === -1 ) {
  489. return;
  490. }
  491. if ( this.params.type === 0 ) {
  492. this.setTransformFromBone();
  493. }
  494. },
  495. updateBone: function () {
  496. if ( this.params.type === 0 || this.params.boneIndex === -1 ) {
  497. return;
  498. }
  499. this.updateBoneRotation();
  500. if ( this.params.type === 1 ) {
  501. this.updateBonePosition();
  502. }
  503. this.bone.updateMatrixWorld( true );
  504. if ( this.params.type === 2 ) {
  505. this.setPositionFromBone();
  506. }
  507. },
  508. getBoneTransform: function () {
  509. var helper = this.helper;
  510. var p = this.bone.getWorldPosition();
  511. var q = this.bone.getWorldQuaternion();
  512. var tr = helper.allocTransform();
  513. helper.setOriginFromArray3( tr, p.toArray() );
  514. helper.setBasisFromArray4( tr, q.toArray() );
  515. var form = helper.multiplyTransforms( tr, this.boneOffsetForm );
  516. helper.freeTransform( tr );
  517. return form;
  518. },
  519. getWorldTransformForBone: function () {
  520. var helper = this.helper;
  521. var tr = helper.allocTransform();
  522. this.body.getMotionState().getWorldTransform( tr );
  523. var tr2 = helper.multiplyTransforms( tr, this.boneOffsetFormInverse );
  524. helper.freeTransform( tr );
  525. return tr2;
  526. },
  527. setTransformFromBone: function () {
  528. var helper = this.helper;
  529. var form = this.getBoneTransform();
  530. // TODO: check the most appropriate way to set
  531. //this.body.setWorldTransform( form );
  532. this.body.setCenterOfMassTransform( form );
  533. this.body.getMotionState().setWorldTransform( form );
  534. helper.freeTransform( form );
  535. },
  536. setPositionFromBone: function () {
  537. var helper = this.helper;
  538. var form = this.getBoneTransform();
  539. var tr = helper.allocTransform();
  540. this.body.getMotionState().getWorldTransform( tr );
  541. helper.copyOrigin( tr, form );
  542. // TODO: check the most appropriate way to set
  543. //this.body.setWorldTransform( tr );
  544. this.body.setCenterOfMassTransform( tr );
  545. this.body.getMotionState().setWorldTransform( tr );
  546. helper.freeTransform( tr );
  547. helper.freeTransform( form );
  548. },
  549. updateBoneRotation: function () {
  550. this.bone.updateMatrixWorld( true );
  551. var helper = this.helper;
  552. var tr = this.getWorldTransformForBone();
  553. var q = helper.getBasis( tr );
  554. var thQ = helper.allocThreeQuaternion();
  555. var thQ2 = helper.allocThreeQuaternion();
  556. var thQ3 = helper.allocThreeQuaternion();
  557. thQ.set( q.x(), q.y(), q.z(), q.w() );
  558. thQ2.setFromRotationMatrix( this.bone.matrixWorld );
  559. thQ2.conjugate();
  560. thQ2.multiply( thQ );
  561. //this.bone.quaternion.multiply( thQ2 );
  562. thQ3.setFromRotationMatrix( this.bone.matrix );
  563. this.bone.quaternion.copy( thQ2.multiply( thQ3 ) );
  564. helper.freeThreeQuaternion( thQ );
  565. helper.freeThreeQuaternion( thQ2 );
  566. helper.freeThreeQuaternion( thQ3 );
  567. helper.freeQuaternion( q );
  568. helper.freeTransform( tr );
  569. },
  570. updateBonePosition: function () {
  571. var helper = this.helper;
  572. var tr = this.getWorldTransformForBone();
  573. var thV = helper.allocThreeVector3();
  574. var o = helper.getOrigin( tr );
  575. thV.set( o.x(), o.y(), o.z() );
  576. var v = this.bone.worldToLocal( thV );
  577. this.bone.position.add( v );
  578. helper.freeThreeVector3( thV );
  579. helper.freeTransform( tr );
  580. }
  581. };
  582. THREE.MMDPhysics.Constraint = function ( mesh, world, bodyA, bodyB, params, helper ) {
  583. this.mesh = mesh;
  584. this.world = world;
  585. this.bodyA = bodyA;
  586. this.bodyB = bodyB;
  587. this.params = params;
  588. this.helper = helper;
  589. this.constraint = null;
  590. this.init();
  591. };
  592. THREE.MMDPhysics.Constraint.prototype = {
  593. constructor: THREE.MMDPhysics.Constraint,
  594. init: function () {
  595. var helper = this.helper;
  596. var params = this.params;
  597. var bodyA = this.bodyA;
  598. var bodyB = this.bodyB;
  599. var form = helper.allocTransform();
  600. helper.setIdentity( form );
  601. helper.setOriginFromArray3( form, params.position );
  602. helper.setBasisFromArray3( form, params.rotation );
  603. var formA = helper.allocTransform();
  604. var formB = helper.allocTransform();
  605. bodyA.body.getMotionState().getWorldTransform( formA );
  606. bodyB.body.getMotionState().getWorldTransform( formB );
  607. var formInverseA = helper.inverseTransform( formA );
  608. var formInverseB = helper.inverseTransform( formB );
  609. var formA2 = helper.multiplyTransforms( formInverseA, form );
  610. var formB2 = helper.multiplyTransforms( formInverseB, form );
  611. var constraint = new Ammo.btGeneric6DofSpringConstraint( bodyA.body, bodyB.body, formA2, formB2, true );
  612. var lll = helper.allocVector3();
  613. var lul = helper.allocVector3();
  614. var all = helper.allocVector3();
  615. var aul = helper.allocVector3();
  616. lll.setValue( params.translationLimitation1[ 0 ],
  617. params.translationLimitation1[ 1 ],
  618. params.translationLimitation1[ 2 ] );
  619. lul.setValue( params.translationLimitation2[ 0 ],
  620. params.translationLimitation2[ 1 ],
  621. params.translationLimitation2[ 2 ] );
  622. all.setValue( params.rotationLimitation1[ 0 ],
  623. params.rotationLimitation1[ 1 ],
  624. params.rotationLimitation1[ 2 ] );
  625. aul.setValue( params.rotationLimitation2[ 0 ],
  626. params.rotationLimitation2[ 1 ],
  627. params.rotationLimitation2[ 2 ] );
  628. constraint.setLinearLowerLimit( lll );
  629. constraint.setLinearUpperLimit( lul );
  630. constraint.setAngularLowerLimit( all );
  631. constraint.setAngularUpperLimit( aul );
  632. for ( var i = 0; i < 3; i++ ) {
  633. if( params.springPosition[ i ] !== 0 ) {
  634. constraint.enableSpring( i, true );
  635. constraint.setStiffness( i, params.springPosition[ i ] );
  636. }
  637. }
  638. for ( var i = 0; i < 3; i++ ) {
  639. if( params.springRotation[ i ] !== 0 ) {
  640. constraint.enableSpring( i + 3, true );
  641. constraint.setStiffness( i + 3, params.springRotation[ i ] );
  642. }
  643. }
  644. /*
  645. * Currently(10/31/2016) official ammo.js doesn't support
  646. * btGeneric6DofSpringConstraint.setParam method.
  647. * You need custom ammo.js (add the method into idl) if you wanna use.
  648. * By setting this parameter, physics will be more like MMD's
  649. */
  650. if ( constraint.setParam !== undefined ) {
  651. for ( var i = 0; i < 6; i ++ ) {
  652. // this parameter is from http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mmd.three.js
  653. constraint.setParam( 2, 0.475, i );
  654. }
  655. }
  656. this.world.addConstraint( constraint, true );
  657. this.constraint = constraint;
  658. helper.freeTransform( form );
  659. helper.freeTransform( formA );
  660. helper.freeTransform( formB );
  661. helper.freeTransform( formInverseA );
  662. helper.freeTransform( formInverseB );
  663. helper.freeTransform( formA2 );
  664. helper.freeTransform( formB2 );
  665. helper.freeVector3( lll );
  666. helper.freeVector3( lul );
  667. helper.freeVector3( all );
  668. helper.freeVector3( aul );
  669. }
  670. };
  671. THREE.MMDPhysicsHelper = function ( mesh ) {
  672. if ( mesh.physics === undefined || mesh.geometry.rigidBodies === undefined ) {
  673. throw 'THREE.MMDPhysicsHelper requires physics in mesh and rigidBodies in mesh.geometry.';
  674. }
  675. THREE.Object3D.call( this );
  676. this.root = mesh;
  677. this.matrix = mesh.matrixWorld;
  678. this.matrixAutoUpdate = false;
  679. this.materials = [];
  680. this.materials.push(
  681. new THREE.MeshBasicMaterial( {
  682. color: new THREE.Color( 0xff8888 ),
  683. wireframe: true,
  684. depthTest: false,
  685. depthWrite: false,
  686. opacity: 0.25,
  687. transparent: true
  688. } )
  689. );
  690. this.materials.push(
  691. new THREE.MeshBasicMaterial( {
  692. color: new THREE.Color( 0x88ff88 ),
  693. wireframe: true,
  694. depthTest: false,
  695. depthWrite: false,
  696. opacity: 0.25,
  697. transparent: true
  698. } )
  699. );
  700. this.materials.push(
  701. new THREE.MeshBasicMaterial( {
  702. color: new THREE.Color( 0x8888ff ),
  703. wireframe: true,
  704. depthTest: false,
  705. depthWrite: false,
  706. opacity: 0.25,
  707. transparent: true
  708. } )
  709. );
  710. this._init();
  711. this.update();
  712. };
  713. THREE.MMDPhysicsHelper.prototype = Object.create( THREE.Object3D.prototype );
  714. THREE.MMDPhysicsHelper.prototype.constructor = THREE.MMDPhysicsHelper;
  715. THREE.MMDPhysicsHelper.prototype._init = function () {
  716. var mesh = this.root;
  717. var rigidBodies = mesh.geometry.rigidBodies;
  718. function createGeometry( param ) {
  719. switch ( param.shapeType ) {
  720. case 0:
  721. return new THREE.SphereBufferGeometry( param.width, 16, 8 );
  722. case 1:
  723. return new THREE.BoxBufferGeometry( param.width * 2, param.height * 2, param.depth * 2, 8, 8, 8);
  724. case 2:
  725. return new createCapsuleGeometry( param.width, param.height, 16, 8 );
  726. default:
  727. return null;
  728. }
  729. }
  730. // copy from http://www20.atpages.jp/katwat/three.js_r58/examples/mytest37/mytest37.js?ver=20160815
  731. function createCapsuleGeometry( radius, cylinderHeight, segmentsRadius, segmentsHeight ) {
  732. var geometry = new THREE.CylinderBufferGeometry( radius, radius, cylinderHeight, segmentsRadius, segmentsHeight, true );
  733. var upperSphere = new THREE.Mesh( new THREE.SphereBufferGeometry( radius, segmentsRadius, segmentsHeight, 0, Math.PI * 2, 0, Math.PI / 2 ) );
  734. var lowerSphere = new THREE.Mesh( new THREE.SphereBufferGeometry( radius, segmentsRadius, segmentsHeight, 0, Math.PI * 2, Math.PI / 2, Math.PI / 2 ) );
  735. upperSphere.position.set( 0, cylinderHeight / 2, 0 );
  736. lowerSphere.position.set( 0, -cylinderHeight / 2, 0 );
  737. upperSphere.updateMatrix();
  738. lowerSphere.updateMatrix();
  739. geometry.merge( upperSphere.geometry, upperSphere.matrix );
  740. geometry.merge( lowerSphere.geometry, lowerSphere.matrix );
  741. return geometry;
  742. }
  743. for ( var i = 0, il = rigidBodies.length; i < il; i ++ ) {
  744. var param = rigidBodies[ i ];
  745. this.add( new THREE.Mesh( createGeometry( param ), this.materials[ param.type ] ) );
  746. }
  747. };
  748. THREE.MMDPhysicsHelper.prototype.update = function () {
  749. var mesh = this.root;
  750. var rigidBodies = mesh.geometry.rigidBodies;
  751. var bodies = mesh.physics.bodies;
  752. var matrixWorldInv = new THREE.Matrix4().getInverse( mesh.matrixWorld );
  753. var vector = new THREE.Vector3();
  754. var quaternion = new THREE.Quaternion();
  755. var quaternion2 = new THREE.Quaternion();
  756. function getPosition( origin ) {
  757. vector.set( origin.x(), origin.y(), origin.z() );
  758. vector.applyMatrix4( matrixWorldInv );
  759. return vector;
  760. }
  761. function getQuaternion( rotation ) {
  762. quaternion.set( rotation.x(), rotation.y(), rotation.z(), rotation.w() );
  763. quaternion2.setFromRotationMatrix( matrixWorldInv );
  764. quaternion2.multiply( quaternion );
  765. return quaternion2;
  766. }
  767. for ( var i = 0, il = rigidBodies.length; i < il; i ++ ) {
  768. var body = bodies[ i ].body;
  769. var mesh = this.children[ i ];
  770. var tr = body.getCenterOfMassTransform();
  771. mesh.position.copy( getPosition( tr.getOrigin() ) );
  772. mesh.quaternion.copy( getQuaternion( tr.getRotation() ) );
  773. }
  774. };