RapierPhysics.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. import { Clock, Vector3, Quaternion, Matrix4 } from 'three';
  2. const RAPIER_PATH = 'https://cdn.skypack.dev/@dimforge/rapier3d-compat@0.17.3';
  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 === 'RoundedBoxGeometry' ) {
  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. const radius = parameters.radius !== undefined ? parameters.radius : 0.1;
  15. return RAPIER.ColliderDesc.roundCuboid( sx - radius, sy - radius, sz - radius, radius );
  16. } else if ( geometry.type === 'BoxGeometry' ) {
  17. const sx = parameters.width !== undefined ? parameters.width / 2 : 0.5;
  18. const sy = parameters.height !== undefined ? parameters.height / 2 : 0.5;
  19. const sz = parameters.depth !== undefined ? parameters.depth / 2 : 0.5;
  20. return RAPIER.ColliderDesc.cuboid( sx, sy, sz );
  21. } else if ( geometry.type === 'SphereGeometry' || geometry.type === 'IcosahedronGeometry' ) {
  22. const radius = parameters.radius !== undefined ? parameters.radius : 1;
  23. return RAPIER.ColliderDesc.ball( radius );
  24. } else if ( geometry.type === 'CylinderGeometry' ) {
  25. const radius = parameters.radiusBottom !== undefined ? parameters.radiusBottom : 0.5;
  26. const length = parameters.height !== undefined ? parameters.height : 0.5;
  27. return RAPIER.ColliderDesc.cylinder( length / 2, radius );
  28. } else if ( geometry.type === 'CapsuleGeometry' ) {
  29. const radius = parameters.radius !== undefined ? parameters.radius : 0.5;
  30. const length = parameters.height !== undefined ? parameters.height : 0.5;
  31. return RAPIER.ColliderDesc.capsule( length / 2, radius );
  32. } else if ( geometry.type === 'BufferGeometry' ) {
  33. const vertices = [];
  34. const vertex = new Vector3();
  35. const position = geometry.getAttribute( 'position' );
  36. for ( let i = 0; i < position.count; i ++ ) {
  37. vertex.fromBufferAttribute( position, i );
  38. vertices.push( vertex.x, vertex.y, vertex.z );
  39. }
  40. // if the buffer is non-indexed, generate an index buffer
  41. const indices = geometry.getIndex() === null
  42. ? Uint32Array.from( Array( parseInt( vertices.length / 3 ) ).keys() )
  43. : geometry.getIndex().array;
  44. return RAPIER.ColliderDesc.trimesh( vertices, indices );
  45. }
  46. return null;
  47. }
  48. /**
  49. * @classdesc Can be used to include Rapier as a Physics engine into
  50. * `three.js` apps. The API can be initialized via:
  51. * ```js
  52. * const physics = await RapierPhysics();
  53. * ```
  54. * The component automatically imports Rapier from a CDN so make sure
  55. * to use the component with an active Internet connection.
  56. *
  57. * @name RapierPhysics
  58. * @class
  59. * @hideconstructor
  60. * @three_import import { RapierPhysics } from 'three/addons/physics/RapierPhysics.js';
  61. */
  62. async function RapierPhysics() {
  63. if ( RAPIER === null ) {
  64. RAPIER = await import( `${RAPIER_PATH}` );
  65. await RAPIER.init();
  66. }
  67. // Docs: https://rapier.rs/docs/api/javascript/JavaScript3D/
  68. const gravity = new Vector3( 0.0, - 9.81, 0.0 );
  69. const world = new RAPIER.World( gravity );
  70. const meshes = [];
  71. const meshMap = new WeakMap();
  72. const _vector = new Vector3();
  73. const _quaternion = new Quaternion();
  74. const _matrix = new Matrix4();
  75. function addScene( scene ) {
  76. scene.traverse( function ( child ) {
  77. if ( child.isMesh ) {
  78. const physics = child.userData.physics;
  79. if ( physics ) {
  80. addMesh( child, physics.mass, physics.restitution );
  81. }
  82. }
  83. } );
  84. }
  85. function addMesh( mesh, mass = 0, restitution = 0 ) {
  86. const shape = getShape( mesh.geometry );
  87. if ( shape === null ) return;
  88. shape.setMass( mass );
  89. shape.setRestitution( restitution );
  90. const { body, collider } = mesh.isInstancedMesh
  91. ? createInstancedBody( mesh, mass, shape )
  92. : createBody( mesh.position, mesh.quaternion, mass, shape );
  93. if ( ! mesh.userData.physics ) mesh.userData.physics = {};
  94. mesh.userData.physics.body = body;
  95. mesh.userData.physics.collider = collider;
  96. if ( mass > 0 ) {
  97. meshes.push( mesh );
  98. meshMap.set( mesh, { body, collider } );
  99. }
  100. }
  101. function removeMesh( mesh ) {
  102. const index = meshes.indexOf( mesh );
  103. if ( index !== - 1 ) {
  104. meshes.splice( index, 1 );
  105. meshMap.delete( mesh );
  106. if ( ! mesh.userData.physics ) return;
  107. const body = mesh.userData.physics.body;
  108. const collider = mesh.userData.physics.collider;
  109. if ( body ) removeBody( body );
  110. if ( collider ) removeCollider( collider );
  111. }
  112. }
  113. function createInstancedBody( mesh, mass, shape ) {
  114. const array = mesh.instanceMatrix.array;
  115. const bodies = [];
  116. const colliders = [];
  117. for ( let i = 0; i < mesh.count; i ++ ) {
  118. const position = _vector.fromArray( array, i * 16 + 12 );
  119. const { body, collider } = createBody( position, null, mass, shape );
  120. bodies.push( body );
  121. colliders.push( collider );
  122. }
  123. return { body: bodies, collider: colliders };
  124. }
  125. function createBody( position, quaternion, mass, shape ) {
  126. const desc = mass > 0 ? RAPIER.RigidBodyDesc.dynamic() : RAPIER.RigidBodyDesc.fixed();
  127. desc.setTranslation( ...position );
  128. if ( quaternion !== null ) desc.setRotation( quaternion );
  129. const body = world.createRigidBody( desc );
  130. const collider = world.createCollider( shape, body );
  131. return { body, collider };
  132. }
  133. function removeBody( body ) {
  134. if ( Array.isArray( body ) ) {
  135. for ( let i = 0; i < body.length; i ++ ) {
  136. world.removeRigidBody( body[ i ] );
  137. }
  138. } else {
  139. world.removeRigidBody( body );
  140. }
  141. }
  142. function removeCollider( collider ) {
  143. if ( Array.isArray( collider ) ) {
  144. for ( let i = 0; i < collider.length; i ++ ) {
  145. world.removeCollider( collider[ i ] );
  146. }
  147. } else {
  148. world.removeCollider( collider );
  149. }
  150. }
  151. function setMeshPosition( mesh, position, index = 0 ) {
  152. let { body } = meshMap.get( mesh );
  153. if ( mesh.isInstancedMesh ) {
  154. body = body[ index ];
  155. }
  156. body.setAngvel( ZERO );
  157. body.setLinvel( ZERO );
  158. body.setTranslation( position );
  159. }
  160. function setMeshVelocity( mesh, velocity, index = 0 ) {
  161. let { body } = meshMap.get( mesh );
  162. if ( mesh.isInstancedMesh ) {
  163. body = body[ index ];
  164. }
  165. body.setLinvel( velocity );
  166. }
  167. function addHeightfield( mesh, width, depth, heights, scale ) {
  168. const shape = RAPIER.ColliderDesc.heightfield( width, depth, heights, scale );
  169. const bodyDesc = RAPIER.RigidBodyDesc.fixed();
  170. bodyDesc.setTranslation( mesh.position.x, mesh.position.y, mesh.position.z );
  171. bodyDesc.setRotation( mesh.quaternion );
  172. const body = world.createRigidBody( bodyDesc );
  173. world.createCollider( shape, body );
  174. if ( ! mesh.userData.physics ) mesh.userData.physics = {};
  175. mesh.userData.physics.body = body;
  176. return body;
  177. }
  178. //
  179. const clock = new Clock();
  180. function step() {
  181. world.timestep = clock.getDelta();
  182. world.step();
  183. //
  184. for ( let i = 0, l = meshes.length; i < l; i ++ ) {
  185. const mesh = meshes[ i ];
  186. if ( mesh.isInstancedMesh ) {
  187. const array = mesh.instanceMatrix.array;
  188. const { body: bodies } = meshMap.get( mesh );
  189. for ( let j = 0; j < bodies.length; j ++ ) {
  190. const body = bodies[ j ];
  191. const position = body.translation();
  192. _quaternion.copy( body.rotation() );
  193. _matrix.compose( position, _quaternion, _scale ).toArray( array, j * 16 );
  194. }
  195. mesh.instanceMatrix.needsUpdate = true;
  196. mesh.computeBoundingSphere();
  197. } else {
  198. const { body } = meshMap.get( mesh );
  199. mesh.position.copy( body.translation() );
  200. mesh.quaternion.copy( body.rotation() );
  201. }
  202. }
  203. }
  204. // animate
  205. setInterval( step, 1000 / frameRate );
  206. return {
  207. RAPIER,
  208. world,
  209. /**
  210. * Adds the given scene to this physics simulation. Only meshes with a
  211. * `physics` object in their {@link Object3D#userData} field will be honored.
  212. * The object can be used to store the mass and restitution of the mesh. E.g.:
  213. * ```js
  214. * box.userData.physics = { mass: 1, restitution: 0 };
  215. * ```
  216. *
  217. * @method
  218. * @name RapierPhysics#addScene
  219. * @param {Object3D} scene The scene or any type of 3D object to add.
  220. */
  221. addScene: addScene,
  222. /**
  223. * Adds the given mesh to this physics simulation.
  224. *
  225. * @method
  226. * @name RapierPhysics#addMesh
  227. * @param {Mesh} mesh The mesh to add.
  228. * @param {number} [mass=0] The mass in kg of the mesh.
  229. * @param {number} [restitution=0] The restitution/friction of the mesh.
  230. */
  231. addMesh: addMesh,
  232. /**
  233. * Removes the given mesh from this physics simulation.
  234. *
  235. * @method
  236. * @name RapierPhysics#removeMesh
  237. * @param {Mesh} mesh The mesh to remove.
  238. */
  239. removeMesh: removeMesh,
  240. /**
  241. * Set the position of the given mesh which is part of the physics simulation. Calling this
  242. * method will reset the current simulated velocity of the mesh.
  243. *
  244. * @method
  245. * @name RapierPhysics#setMeshPosition
  246. * @param {Mesh} mesh The mesh to update the position for.
  247. * @param {Vector3} position - The new position.
  248. * @param {number} [index=0] - If the mesh is instanced, the index represents the instanced ID.
  249. */
  250. setMeshPosition: setMeshPosition,
  251. /**
  252. * Set the velocity of the given mesh which is part of the physics simulation.
  253. *
  254. * @method
  255. * @name RapierPhysics#setMeshVelocity
  256. * @param {Mesh} mesh The mesh to update the velocity for.
  257. * @param {Vector3} velocity - The new velocity.
  258. * @param {number} [index=0] - If the mesh is instanced, the index represents the instanced ID.
  259. */
  260. setMeshVelocity: setMeshVelocity,
  261. /**
  262. * Adds a heightfield terrain to the physics simulation.
  263. *
  264. * @method
  265. * @name RapierPhysics#addHeightfield
  266. * @param {Mesh} mesh - The Three.js mesh representing the terrain.
  267. * @param {number} width - The number of vertices along the width (x-axis) of the heightfield.
  268. * @param {number} depth - The number of vertices along the depth (z-axis) of the heightfield.
  269. * @param {Float32Array} heights - Array of height values for each vertex in the heightfield.
  270. * @param {Object} scale - Scale factors for the heightfield dimensions.
  271. * @param {number} scale.x - Scale factor for width.
  272. * @param {number} scale.y - Scale factor for height.
  273. * @param {number} scale.z - Scale factor for depth.
  274. * @returns {RigidBody} The created Rapier rigid body for the heightfield.
  275. */
  276. addHeightfield: addHeightfield
  277. };
  278. }
  279. export { RapierPhysics };
粤ICP备19079148号