JoltPhysics.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. import { Clock, Vector3, Quaternion, Matrix4 } from 'three';
  2. const JOLT_PATH = 'https://cdn.jsdelivr.net/npm/jolt-physics@0.23.0/dist/jolt-physics.wasm-compat.js';
  3. const frameRate = 60;
  4. let Jolt = null;
  5. function getShape( geometry ) {
  6. const parameters = geometry.parameters;
  7. // TODO change type to is*
  8. if ( geometry.type === 'BoxGeometry' ) {
  9. const sx = parameters.width !== undefined ? parameters.width / 2 : 0.5;
  10. const sy = parameters.height !== undefined ? parameters.height / 2 : 0.5;
  11. const sz = parameters.depth !== undefined ? parameters.depth / 2 : 0.5;
  12. return new Jolt.BoxShape( new Jolt.Vec3( sx, sy, sz ), 0.05 * Math.min( sx, sy, sz ), null );
  13. } else if ( geometry.type === 'SphereGeometry' || geometry.type === 'IcosahedronGeometry' ) {
  14. const radius = parameters.radius !== undefined ? parameters.radius : 1;
  15. return new Jolt.SphereShape( radius, null );
  16. }
  17. return null;
  18. }
  19. // Object layers
  20. const LAYER_NON_MOVING = 0;
  21. const LAYER_MOVING = 1;
  22. const NUM_OBJECT_LAYERS = 2;
  23. function setupCollisionFiltering( settings ) {
  24. const objectFilter = new Jolt.ObjectLayerPairFilterTable( NUM_OBJECT_LAYERS );
  25. objectFilter.EnableCollision( LAYER_NON_MOVING, LAYER_MOVING );
  26. objectFilter.EnableCollision( LAYER_MOVING, LAYER_MOVING );
  27. const BP_LAYER_NON_MOVING = new Jolt.BroadPhaseLayer( 0 );
  28. const BP_LAYER_MOVING = new Jolt.BroadPhaseLayer( 1 );
  29. const NUM_BROAD_PHASE_LAYERS = 2;
  30. const bpInterface = new Jolt.BroadPhaseLayerInterfaceTable( NUM_OBJECT_LAYERS, NUM_BROAD_PHASE_LAYERS );
  31. bpInterface.MapObjectToBroadPhaseLayer( LAYER_NON_MOVING, BP_LAYER_NON_MOVING );
  32. bpInterface.MapObjectToBroadPhaseLayer( LAYER_MOVING, BP_LAYER_MOVING );
  33. settings.mObjectLayerPairFilter = objectFilter;
  34. settings.mBroadPhaseLayerInterface = bpInterface;
  35. settings.mObjectVsBroadPhaseLayerFilter = new Jolt.ObjectVsBroadPhaseLayerFilterTable( settings.mBroadPhaseLayerInterface, NUM_BROAD_PHASE_LAYERS, settings.mObjectLayerPairFilter, NUM_OBJECT_LAYERS );
  36. }
  37. /**
  38. * @classdesc Can be used to include Jolt as a Physics engine into
  39. * `three.js` apps. The API can be initialized via:
  40. * ```js
  41. * const physics = await JoltPhysics();
  42. * ```
  43. * The component automatically imports Jolt from a CDN so make sure
  44. * to use the component with an active Internet connection.
  45. *
  46. * @name JoltPhysics
  47. * @class
  48. * @hideconstructor
  49. */
  50. async function JoltPhysics() {
  51. if ( Jolt === null ) {
  52. const { default: initJolt } = await import( `${JOLT_PATH}` );
  53. Jolt = await initJolt();
  54. }
  55. const settings = new Jolt.JoltSettings();
  56. setupCollisionFiltering( settings );
  57. const jolt = new Jolt.JoltInterface( settings );
  58. Jolt.destroy( settings );
  59. const physicsSystem = jolt.GetPhysicsSystem();
  60. const bodyInterface = physicsSystem.GetBodyInterface();
  61. const meshes = [];
  62. const meshMap = new WeakMap();
  63. const _position = new Vector3();
  64. const _quaternion = new Quaternion();
  65. const _scale = new Vector3( 1, 1, 1 );
  66. const _matrix = new Matrix4();
  67. function addScene( scene ) {
  68. scene.traverse( function ( child ) {
  69. if ( child.isMesh ) {
  70. const physics = child.userData.physics;
  71. if ( physics ) {
  72. addMesh( child, physics.mass, physics.restitution );
  73. }
  74. }
  75. } );
  76. }
  77. function addMesh( mesh, mass = 0, restitution = 0 ) {
  78. const shape = getShape( mesh.geometry );
  79. if ( shape === null ) return;
  80. const body = mesh.isInstancedMesh
  81. ? createInstancedBody( mesh, mass, restitution, shape )
  82. : createBody( mesh.position, mesh.quaternion, mass, restitution, shape );
  83. if ( mass > 0 ) {
  84. meshes.push( mesh );
  85. meshMap.set( mesh, body );
  86. }
  87. }
  88. function createInstancedBody( mesh, mass, restitution, shape ) {
  89. const array = mesh.instanceMatrix.array;
  90. const bodies = [];
  91. for ( let i = 0; i < mesh.count; i ++ ) {
  92. const position = _position.fromArray( array, i * 16 + 12 );
  93. const quaternion = _quaternion.setFromRotationMatrix( _matrix.fromArray( array, i * 16 ) ); // TODO Copilot did this
  94. bodies.push( createBody( position, quaternion, mass, restitution, shape ) );
  95. }
  96. return bodies;
  97. }
  98. function createBody( position, rotation, mass, restitution, shape ) {
  99. const pos = new Jolt.Vec3( position.x, position.y, position.z );
  100. const rot = new Jolt.Quat( rotation.x, rotation.y, rotation.z, rotation.w );
  101. const motion = mass > 0 ? Jolt.EMotionType_Dynamic : Jolt.EMotionType_Static;
  102. const layer = mass > 0 ? LAYER_MOVING : LAYER_NON_MOVING;
  103. const creationSettings = new Jolt.BodyCreationSettings( shape, pos, rot, motion, layer );
  104. creationSettings.mRestitution = restitution;
  105. const body = bodyInterface.CreateBody( creationSettings );
  106. bodyInterface.AddBody( body.GetID(), Jolt.EActivation_Activate );
  107. Jolt.destroy( creationSettings );
  108. return body;
  109. }
  110. function setMeshPosition( mesh, position, index = 0 ) {
  111. if ( mesh.isInstancedMesh ) {
  112. const bodies = meshMap.get( mesh );
  113. const body = bodies[ index ];
  114. bodyInterface.RemoveBody( body.GetID() );
  115. bodyInterface.DestroyBody( body.GetID() );
  116. const physics = mesh.userData.physics;
  117. const shape = body.GetShape();
  118. const body2 = createBody( position, { x: 0, y: 0, z: 0, w: 1 }, physics.mass, physics.restitution, shape );
  119. bodies[ index ] = body2;
  120. } else {
  121. // TODO: Implement this
  122. }
  123. }
  124. function setMeshVelocity( mesh, velocity, index = 0 ) {
  125. /*
  126. let body = meshMap.get( mesh );
  127. if ( mesh.isInstancedMesh ) {
  128. body = body[ index ];
  129. }
  130. body.setLinvel( velocity );
  131. */
  132. }
  133. //
  134. const clock = new Clock();
  135. function step() {
  136. let deltaTime = clock.getDelta();
  137. // Don't go below 30 Hz to prevent spiral of death
  138. deltaTime = Math.min( deltaTime, 1.0 / 30.0 );
  139. // When running below 55 Hz, do 2 steps instead of 1
  140. const numSteps = deltaTime > 1.0 / 55.0 ? 2 : 1;
  141. // Step the physics world
  142. jolt.Step( deltaTime, numSteps );
  143. //
  144. for ( let i = 0, l = meshes.length; i < l; i ++ ) {
  145. const mesh = meshes[ i ];
  146. if ( mesh.isInstancedMesh ) {
  147. const array = mesh.instanceMatrix.array;
  148. const bodies = meshMap.get( mesh );
  149. for ( let j = 0; j < bodies.length; j ++ ) {
  150. const body = bodies[ j ];
  151. const position = body.GetPosition();
  152. const quaternion = body.GetRotation();
  153. _position.set( position.GetX(), position.GetY(), position.GetZ() );
  154. _quaternion.set( quaternion.GetX(), quaternion.GetY(), quaternion.GetZ(), quaternion.GetW() );
  155. _matrix.compose( _position, _quaternion, _scale ).toArray( array, j * 16 );
  156. }
  157. mesh.instanceMatrix.needsUpdate = true;
  158. mesh.computeBoundingSphere();
  159. } else {
  160. const body = meshMap.get( mesh );
  161. const position = body.GetPosition();
  162. const rotation = body.GetRotation();
  163. mesh.position.set( position.GetX(), position.GetY(), position.GetZ() );
  164. mesh.quaternion.set( rotation.GetX(), rotation.GetY(), rotation.GetZ(), rotation.GetW() );
  165. }
  166. }
  167. }
  168. // animate
  169. setInterval( step, 1000 / frameRate );
  170. return {
  171. /**
  172. * Adds the given scene to this physics simulation. Only meshes with a
  173. * `physics` object in their {@link Object3D#userData} field will be honored.
  174. * The object can be used to store the mass and restitution of the mesh. E.g.:
  175. * ```js
  176. * box.userData.physics = { mass: 1, restitution: 0 };
  177. * ```
  178. *
  179. * @method
  180. * @name JoltPhysics#addScene
  181. * @param {Object3D} scene The scene or any type of 3D object to add.
  182. */
  183. addScene: addScene,
  184. /**
  185. * Adds the given mesh to this physics simulation.
  186. *
  187. * @method
  188. * @name JoltPhysics#addMesh
  189. * @param {Mesh} mesh The mesh to add.
  190. * @param {number} [mass=0] The mass in kg of the mesh.
  191. * @param {number} [restitution=0] The restitution/friction of the mesh.
  192. */
  193. addMesh: addMesh,
  194. /**
  195. * Set the position of the given mesh which is part of the physics simulation. Calling this
  196. * method will reset the current simulated velocity of the mesh.
  197. *
  198. * @method
  199. * @name JoltPhysics#setMeshPosition
  200. * @param {Mesh} mesh The mesh to update the position for.
  201. * @param {Vector3} position - The new position.
  202. * @param {number} [index=0] - If the mesh is instanced, the index represents the instanced ID.
  203. */
  204. setMeshPosition: setMeshPosition,
  205. // NOOP
  206. setMeshVelocity: setMeshVelocity
  207. };
  208. }
  209. export { JoltPhysics };
粤ICP备19079148号