MMDPhysics.js 25 KB

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