AmmoPhysics.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. /**
  2. * @classdesc Can be used to include Ammo.js as a Physics engine into
  3. * `three.js` apps. Make sure to include `ammo.wasm.js` first:
  4. * ```
  5. * <script src="jsm/libs/ammo.wasm.js"></script>
  6. * ```
  7. * It is then possible to initialize the API via:
  8. * ```js
  9. * const physics = await AmmoPhysics();
  10. * ```
  11. *
  12. * @name AmmoPhysics
  13. * @class
  14. * @hideconstructor
  15. */
  16. async function AmmoPhysics() {
  17. if ( 'Ammo' in window === false ) {
  18. console.error( 'AmmoPhysics: Couldn\'t find Ammo.js' );
  19. return;
  20. }
  21. const AmmoLib = await Ammo(); // eslint-disable-line no-undef
  22. const frameRate = 60;
  23. const collisionConfiguration = new AmmoLib.btDefaultCollisionConfiguration();
  24. const dispatcher = new AmmoLib.btCollisionDispatcher( collisionConfiguration );
  25. const broadphase = new AmmoLib.btDbvtBroadphase();
  26. const solver = new AmmoLib.btSequentialImpulseConstraintSolver();
  27. const world = new AmmoLib.btDiscreteDynamicsWorld( dispatcher, broadphase, solver, collisionConfiguration );
  28. world.setGravity( new AmmoLib.btVector3( 0, - 9.8, 0 ) );
  29. const worldTransform = new AmmoLib.btTransform();
  30. //
  31. function getShape( geometry ) {
  32. const parameters = geometry.parameters;
  33. // TODO change type to is*
  34. if ( geometry.type === 'BoxGeometry' ) {
  35. const sx = parameters.width !== undefined ? parameters.width / 2 : 0.5;
  36. const sy = parameters.height !== undefined ? parameters.height / 2 : 0.5;
  37. const sz = parameters.depth !== undefined ? parameters.depth / 2 : 0.5;
  38. const shape = new AmmoLib.btBoxShape( new AmmoLib.btVector3( sx, sy, sz ) );
  39. shape.setMargin( 0.05 );
  40. return shape;
  41. } else if ( geometry.type === 'SphereGeometry' || geometry.type === 'IcosahedronGeometry' ) {
  42. const radius = parameters.radius !== undefined ? parameters.radius : 1;
  43. const shape = new AmmoLib.btSphereShape( radius );
  44. shape.setMargin( 0.05 );
  45. return shape;
  46. }
  47. return null;
  48. }
  49. const meshes = [];
  50. const meshMap = new WeakMap();
  51. function addScene( scene ) {
  52. scene.traverse( function ( child ) {
  53. if ( child.isMesh ) {
  54. const physics = child.userData.physics;
  55. if ( physics ) {
  56. addMesh( child, physics.mass );
  57. }
  58. }
  59. } );
  60. }
  61. function addMesh( mesh, mass = 0 ) {
  62. const shape = getShape( mesh.geometry );
  63. if ( shape !== null ) {
  64. if ( mesh.isInstancedMesh ) {
  65. handleInstancedMesh( mesh, mass, shape );
  66. } else if ( mesh.isMesh ) {
  67. handleMesh( mesh, mass, shape );
  68. }
  69. }
  70. }
  71. function handleMesh( mesh, mass, shape ) {
  72. const position = mesh.position;
  73. const quaternion = mesh.quaternion;
  74. const transform = new AmmoLib.btTransform();
  75. transform.setIdentity();
  76. transform.setOrigin( new AmmoLib.btVector3( position.x, position.y, position.z ) );
  77. transform.setRotation( new AmmoLib.btQuaternion( quaternion.x, quaternion.y, quaternion.z, quaternion.w ) );
  78. const motionState = new AmmoLib.btDefaultMotionState( transform );
  79. const localInertia = new AmmoLib.btVector3( 0, 0, 0 );
  80. shape.calculateLocalInertia( mass, localInertia );
  81. const rbInfo = new AmmoLib.btRigidBodyConstructionInfo( mass, motionState, shape, localInertia );
  82. const body = new AmmoLib.btRigidBody( rbInfo );
  83. // body.setFriction( 4 );
  84. world.addRigidBody( body );
  85. if ( mass > 0 ) {
  86. meshes.push( mesh );
  87. meshMap.set( mesh, body );
  88. }
  89. }
  90. function handleInstancedMesh( mesh, mass, shape ) {
  91. const array = mesh.instanceMatrix.array;
  92. const bodies = [];
  93. for ( let i = 0; i < mesh.count; i ++ ) {
  94. const index = i * 16;
  95. const transform = new AmmoLib.btTransform();
  96. transform.setFromOpenGLMatrix( array.slice( index, index + 16 ) );
  97. const motionState = new AmmoLib.btDefaultMotionState( transform );
  98. const localInertia = new AmmoLib.btVector3( 0, 0, 0 );
  99. shape.calculateLocalInertia( mass, localInertia );
  100. const rbInfo = new AmmoLib.btRigidBodyConstructionInfo( mass, motionState, shape, localInertia );
  101. const body = new AmmoLib.btRigidBody( rbInfo );
  102. world.addRigidBody( body );
  103. bodies.push( body );
  104. }
  105. if ( mass > 0 ) {
  106. meshes.push( mesh );
  107. meshMap.set( mesh, bodies );
  108. }
  109. }
  110. //
  111. function setMeshPosition( mesh, position, index = 0 ) {
  112. if ( mesh.isInstancedMesh ) {
  113. const bodies = meshMap.get( mesh );
  114. const body = bodies[ index ];
  115. body.setAngularVelocity( new AmmoLib.btVector3( 0, 0, 0 ) );
  116. body.setLinearVelocity( new AmmoLib.btVector3( 0, 0, 0 ) );
  117. worldTransform.setIdentity();
  118. worldTransform.setOrigin( new AmmoLib.btVector3( position.x, position.y, position.z ) );
  119. body.setWorldTransform( worldTransform );
  120. } else if ( mesh.isMesh ) {
  121. const body = meshMap.get( mesh );
  122. body.setAngularVelocity( new AmmoLib.btVector3( 0, 0, 0 ) );
  123. body.setLinearVelocity( new AmmoLib.btVector3( 0, 0, 0 ) );
  124. worldTransform.setIdentity();
  125. worldTransform.setOrigin( new AmmoLib.btVector3( position.x, position.y, position.z ) );
  126. body.setWorldTransform( worldTransform );
  127. }
  128. }
  129. //
  130. let lastTime = 0;
  131. function step() {
  132. const time = performance.now();
  133. if ( lastTime > 0 ) {
  134. const delta = ( time - lastTime ) / 1000;
  135. world.stepSimulation( delta, 10 );
  136. //
  137. for ( let i = 0, l = meshes.length; i < l; i ++ ) {
  138. const mesh = meshes[ i ];
  139. if ( mesh.isInstancedMesh ) {
  140. const array = mesh.instanceMatrix.array;
  141. const bodies = meshMap.get( mesh );
  142. for ( let j = 0; j < bodies.length; j ++ ) {
  143. const body = bodies[ j ];
  144. const motionState = body.getMotionState();
  145. motionState.getWorldTransform( worldTransform );
  146. const position = worldTransform.getOrigin();
  147. const quaternion = worldTransform.getRotation();
  148. compose( position, quaternion, array, j * 16 );
  149. }
  150. mesh.instanceMatrix.needsUpdate = true;
  151. mesh.computeBoundingSphere();
  152. } else if ( mesh.isMesh ) {
  153. const body = meshMap.get( mesh );
  154. const motionState = body.getMotionState();
  155. motionState.getWorldTransform( worldTransform );
  156. const position = worldTransform.getOrigin();
  157. const quaternion = worldTransform.getRotation();
  158. mesh.position.set( position.x(), position.y(), position.z() );
  159. mesh.quaternion.set( quaternion.x(), quaternion.y(), quaternion.z(), quaternion.w() );
  160. }
  161. }
  162. }
  163. lastTime = time;
  164. }
  165. // animate
  166. setInterval( step, 1000 / frameRate );
  167. return {
  168. /**
  169. * Adds the given scene to this physics simulation. Only meshes with a
  170. * `physics` object in their {@link Object3D#userData} field will be honored.
  171. * The object can be used to store the mass of the mesh. E.g.:
  172. * ```js
  173. * box.userData.physics = { mass: 1 };
  174. * ```
  175. *
  176. * @method
  177. * @name AmmoPhysics#addScene
  178. * @param {Object3D} scene The scene or any type of 3D object to add.
  179. */
  180. addScene: addScene,
  181. /**
  182. * Adds the given mesh to this physics simulation.
  183. *
  184. * @method
  185. * @name AmmoPhysics#addMesh
  186. * @param {Mesh} mesh The mesh to add.
  187. * @param {number} [mass=0] The mass in kg of the mesh.
  188. */
  189. addMesh: addMesh,
  190. /**
  191. * Set the position of the given mesh which is part of the physics simulation. Calling this
  192. * method will reset the current simulated velocity of the mesh.
  193. *
  194. * @method
  195. * @name AmmoPhysics#setMeshPosition
  196. * @param {Mesh} mesh The mesh to update the position for.
  197. * @param {Vector3} position - The new position.
  198. * @param {number} [index=0] - If the mesh is instanced, the index represents the instanced ID.
  199. */
  200. setMeshPosition: setMeshPosition
  201. // addCompoundMesh
  202. };
  203. }
  204. function compose( position, quaternion, array, index ) {
  205. const x = quaternion.x(), y = quaternion.y(), z = quaternion.z(), w = quaternion.w();
  206. const x2 = x + x, y2 = y + y, z2 = z + z;
  207. const xx = x * x2, xy = x * y2, xz = x * z2;
  208. const yy = y * y2, yz = y * z2, zz = z * z2;
  209. const wx = w * x2, wy = w * y2, wz = w * z2;
  210. array[ index + 0 ] = ( 1 - ( yy + zz ) );
  211. array[ index + 1 ] = ( xy + wz );
  212. array[ index + 2 ] = ( xz - wy );
  213. array[ index + 3 ] = 0;
  214. array[ index + 4 ] = ( xy - wz );
  215. array[ index + 5 ] = ( 1 - ( xx + zz ) );
  216. array[ index + 6 ] = ( yz + wx );
  217. array[ index + 7 ] = 0;
  218. array[ index + 8 ] = ( xz + wy );
  219. array[ index + 9 ] = ( yz - wx );
  220. array[ index + 10 ] = ( 1 - ( xx + yy ) );
  221. array[ index + 11 ] = 0;
  222. array[ index + 12 ] = position.x();
  223. array[ index + 13 ] = position.y();
  224. array[ index + 14 ] = position.z();
  225. array[ index + 15 ] = 1;
  226. }
  227. export { AmmoPhysics };
粤ICP备19079148号