RapierPhysics.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. import { Clock, Vector3, Quaternion, Matrix4 } from 'three';
  2. const RAPIER_PATH = 'https://cdn.skypack.dev/@dimforge/rapier3d-compat@0.12.0';
  3. const frameRate = 60;
  4. const _scale = new Vector3( 1, 1, 1 );
  5. const ZERO = new Vector3();
  6. let RAPIER = null;
  7. function getShape( geometry ) {
  8. const parameters = geometry.parameters;
  9. // TODO change type to is*
  10. if ( geometry.type === 'BoxGeometry' ) {
  11. const sx = parameters.width !== undefined ? parameters.width / 2 : 0.5;
  12. const sy = parameters.height !== undefined ? parameters.height / 2 : 0.5;
  13. const sz = parameters.depth !== undefined ? parameters.depth / 2 : 0.5;
  14. return RAPIER.ColliderDesc.cuboid( sx, sy, sz );
  15. } else if ( geometry.type === 'SphereGeometry' || geometry.type === 'IcosahedronGeometry' ) {
  16. const radius = parameters.radius !== undefined ? parameters.radius : 1;
  17. return RAPIER.ColliderDesc.ball( radius );
  18. } else if ( geometry.type === 'BufferGeometry' ) {
  19. const vertices = [];
  20. const vertex = new Vector3();
  21. const position = geometry.getAttribute( 'position' );
  22. for ( let i = 0; i < position.count; i ++ ) {
  23. vertex.fromBufferAttribute( position, i );
  24. vertices.push( vertex.x, vertex.y, vertex.z );
  25. }
  26. // if the buffer is non-indexed, generate an index buffer
  27. const indices = geometry.getIndex() === null
  28. ? Uint32Array.from( Array( parseInt( vertices.length / 3 ) ).keys() )
  29. : geometry.getIndex().array;
  30. return RAPIER.ColliderDesc.trimesh( vertices, indices );
  31. }
  32. return null;
  33. }
  34. /**
  35. * @classdesc Can be used to include Rapier as a Physics engine into
  36. * `three.js` apps. The API can be initialized via:
  37. * ```js
  38. * const physics = await RapierPhysics();
  39. * ```
  40. * The component automatically imports Rapier from a CDN so make sure
  41. * to use the component with an active Internet connection.
  42. *
  43. * @name RapierPhysics
  44. * @class
  45. * @hideconstructor
  46. */
  47. async function RapierPhysics() {
  48. if ( RAPIER === null ) {
  49. RAPIER = await import( `${RAPIER_PATH}` );
  50. await RAPIER.init();
  51. }
  52. // Docs: https://rapier.rs/docs/api/javascript/JavaScript3D/
  53. const gravity = new Vector3( 0.0, - 9.81, 0.0 );
  54. const world = new RAPIER.World( gravity );
  55. const meshes = [];
  56. const meshMap = new WeakMap();
  57. const _vector = new Vector3();
  58. const _quaternion = new Quaternion();
  59. const _matrix = new Matrix4();
  60. function addScene( scene ) {
  61. scene.traverse( function ( child ) {
  62. if ( child.isMesh ) {
  63. const physics = child.userData.physics;
  64. if ( physics ) {
  65. addMesh( child, physics.mass, physics.restitution );
  66. }
  67. }
  68. } );
  69. }
  70. function addMesh( mesh, mass = 0, restitution = 0 ) {
  71. const shape = getShape( mesh.geometry );
  72. if ( shape === null ) return;
  73. shape.setMass( mass );
  74. shape.setRestitution( restitution );
  75. const body = mesh.isInstancedMesh
  76. ? createInstancedBody( mesh, mass, shape )
  77. : createBody( mesh.position, mesh.quaternion, mass, shape );
  78. if ( mass > 0 ) {
  79. meshes.push( mesh );
  80. meshMap.set( mesh, body );
  81. }
  82. }
  83. function createInstancedBody( mesh, mass, shape ) {
  84. const array = mesh.instanceMatrix.array;
  85. const bodies = [];
  86. for ( let i = 0; i < mesh.count; i ++ ) {
  87. const position = _vector.fromArray( array, i * 16 + 12 );
  88. bodies.push( createBody( position, null, mass, shape ) );
  89. }
  90. return bodies;
  91. }
  92. function createBody( position, quaternion, mass, shape ) {
  93. const desc = mass > 0 ? RAPIER.RigidBodyDesc.dynamic() : RAPIER.RigidBodyDesc.fixed();
  94. desc.setTranslation( ...position );
  95. if ( quaternion !== null ) desc.setRotation( quaternion );
  96. const body = world.createRigidBody( desc );
  97. world.createCollider( shape, body );
  98. return body;
  99. }
  100. function setMeshPosition( mesh, position, index = 0 ) {
  101. let body = meshMap.get( mesh );
  102. if ( mesh.isInstancedMesh ) {
  103. body = body[ index ];
  104. }
  105. body.setAngvel( ZERO );
  106. body.setLinvel( ZERO );
  107. body.setTranslation( position );
  108. }
  109. function setMeshVelocity( mesh, velocity, index = 0 ) {
  110. let body = meshMap.get( mesh );
  111. if ( mesh.isInstancedMesh ) {
  112. body = body[ index ];
  113. }
  114. body.setLinvel( velocity );
  115. }
  116. //
  117. const clock = new Clock();
  118. function step() {
  119. world.timestep = clock.getDelta();
  120. world.step();
  121. //
  122. for ( let i = 0, l = meshes.length; i < l; i ++ ) {
  123. const mesh = meshes[ i ];
  124. if ( mesh.isInstancedMesh ) {
  125. const array = mesh.instanceMatrix.array;
  126. const bodies = meshMap.get( mesh );
  127. for ( let j = 0; j < bodies.length; j ++ ) {
  128. const body = bodies[ j ];
  129. const position = body.translation();
  130. _quaternion.copy( body.rotation() );
  131. _matrix.compose( position, _quaternion, _scale ).toArray( array, j * 16 );
  132. }
  133. mesh.instanceMatrix.needsUpdate = true;
  134. mesh.computeBoundingSphere();
  135. } else {
  136. const body = meshMap.get( mesh );
  137. mesh.position.copy( body.translation() );
  138. mesh.quaternion.copy( body.rotation() );
  139. }
  140. }
  141. }
  142. // animate
  143. setInterval( step, 1000 / frameRate );
  144. return {
  145. /**
  146. * Adds the given scene to this physics simulation. Only meshes with a
  147. * `physics` object in their {@link Object3D#userData} field will be honored.
  148. * The object can be used to store the mass and restitution of the mesh. E.g.:
  149. * ```js
  150. * box.userData.physics = { mass: 1, restitution: 0 };
  151. * ```
  152. *
  153. * @method
  154. * @name RapierPhysics#addScene
  155. * @param {Object3D} scene The scene or any type of 3D object to add.
  156. */
  157. addScene: addScene,
  158. /**
  159. * Adds the given mesh to this physics simulation.
  160. *
  161. * @method
  162. * @name RapierPhysics#addMesh
  163. * @param {Mesh} mesh The mesh to add.
  164. * @param {number} [mass=0] The mass in kg of the mesh.
  165. * @param {number} [restitution=0] The restitution/friction of the mesh.
  166. */
  167. addMesh: addMesh,
  168. /**
  169. * Set the position of the given mesh which is part of the physics simulation. Calling this
  170. * method will reset the current simulated velocity of the mesh.
  171. *
  172. * @method
  173. * @name RapierPhysics#setMeshPosition
  174. * @param {Mesh} mesh The mesh to update the position for.
  175. * @param {Vector3} position - The new position.
  176. * @param {number} [index=0] - If the mesh is instanced, the index represents the instanced ID.
  177. */
  178. setMeshPosition: setMeshPosition,
  179. /**
  180. * Set the velocity of the given mesh which is part of the physics simulation.
  181. *
  182. * @method
  183. * @name RapierPhysics#setMeshVelocity
  184. * @param {Mesh} mesh The mesh to update the velocity for.
  185. * @param {Vector3} velocity - The new velocity.
  186. * @param {number} [index=0] - If the mesh is instanced, the index represents the instanced ID.
  187. */
  188. setMeshVelocity: setMeshVelocity
  189. };
  190. }
  191. export { RapierPhysics };
粤ICP备19079148号