AmmoPhysics.js 8.3 KB

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