AmmoPhysics.js 9.0 KB

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