1
0

physics_rapier_terrain.html 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>Rapier.js terrain heightfield demo</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. <style>
  9. body {
  10. color: #333;
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <div id="container"></div>
  16. <div id="info">Rapier.js physics terrain heightfield demo</div>
  17. <script type="importmap">
  18. {
  19. "imports": {
  20. "three": "../build/three.module.js",
  21. "three/addons/": "./jsm/"
  22. }
  23. }
  24. </script>
  25. <script type="module">
  26. import * as THREE from 'three';
  27. import Stats from 'three/addons/libs/stats.module.js';
  28. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  29. import { RapierPhysics } from 'three/addons/physics/RapierPhysics.js';
  30. // Heightfield parameters
  31. const terrainWidthExtents = 100;
  32. const terrainDepthExtents = 100;
  33. const terrainWidth = 128;
  34. const terrainDepth = 128;
  35. const terrainHalfWidth = terrainWidth / 2;
  36. const terrainHalfDepth = terrainDepth / 2;
  37. const terrainMaxHeight = 8;
  38. const terrainMinHeight = - 2;
  39. // Graphics variables
  40. let container, stats;
  41. let camera, scene, renderer;
  42. let terrainMesh;
  43. const clock = new THREE.Clock();
  44. // Physics variables
  45. let physics;
  46. const dynamicObjects = [];
  47. let heightData = null;
  48. let time = 0;
  49. const objectTimePeriod = 3;
  50. let timeNextSpawn = time + objectTimePeriod;
  51. const maxNumObjects = 30;
  52. init();
  53. async function init() {
  54. heightData = generateHeight( terrainWidth, terrainDepth, terrainMinHeight, terrainMaxHeight );
  55. initGraphics();
  56. await initPhysics();
  57. // Start animation loop only after physics is initialized
  58. renderer.setAnimationLoop( animate );
  59. }
  60. function initGraphics() {
  61. container = document.getElementById( 'container' );
  62. renderer = new THREE.WebGLRenderer( { antialias: true } );
  63. renderer.setPixelRatio( window.devicePixelRatio );
  64. renderer.setSize( window.innerWidth, window.innerHeight );
  65. // Remove setAnimationLoop from here since we'll start it after physics init
  66. renderer.shadowMap.enabled = true;
  67. container.appendChild( renderer.domElement );
  68. stats = new Stats();
  69. stats.domElement.style.position = 'absolute';
  70. stats.domElement.style.top = '0px';
  71. container.appendChild( stats.domElement );
  72. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.2, 2000 );
  73. scene = new THREE.Scene();
  74. scene.background = new THREE.Color( 0xbfd1e5 );
  75. camera.position.y = heightData[ terrainHalfWidth + terrainHalfDepth * terrainWidth ] * ( terrainMaxHeight - terrainMinHeight ) + 5;
  76. camera.position.z = terrainDepthExtents / 2;
  77. camera.lookAt( 0, 0, 0 );
  78. const controls = new OrbitControls( camera, renderer.domElement );
  79. controls.enableZoom = false;
  80. const geometry = new THREE.PlaneGeometry( terrainWidthExtents, terrainDepthExtents, terrainWidth - 1, terrainDepth - 1 );
  81. geometry.rotateX( - Math.PI / 2 );
  82. const vertices = geometry.attributes.position.array;
  83. for ( let i = 0, j = 0, l = vertices.length; i < l; i ++, j += 3 ) {
  84. vertices[ j + 1 ] = heightData[ i ];
  85. }
  86. geometry.computeVertexNormals();
  87. const groundMaterial = new THREE.MeshPhongMaterial( { color: 0xC7C7C7 } );
  88. terrainMesh = new THREE.Mesh( geometry, groundMaterial );
  89. terrainMesh.receiveShadow = true;
  90. terrainMesh.castShadow = true;
  91. scene.add( terrainMesh );
  92. const textureLoader = new THREE.TextureLoader();
  93. textureLoader.load( 'textures/grid.png', function ( texture ) {
  94. texture.wrapS = THREE.RepeatWrapping;
  95. texture.wrapT = THREE.RepeatWrapping;
  96. texture.repeat.set( terrainWidth - 1, terrainDepth - 1 );
  97. groundMaterial.map = texture;
  98. groundMaterial.needsUpdate = true;
  99. } );
  100. const ambientLight = new THREE.AmbientLight( 0xbbbbbb );
  101. scene.add( ambientLight );
  102. const light = new THREE.DirectionalLight( 0xffffff, 3 );
  103. light.position.set( 100, 100, 50 );
  104. light.castShadow = true;
  105. const dLight = 200;
  106. const sLight = dLight * 0.25;
  107. light.shadow.camera.left = - sLight;
  108. light.shadow.camera.right = sLight;
  109. light.shadow.camera.top = sLight;
  110. light.shadow.camera.bottom = - sLight;
  111. light.shadow.camera.near = dLight / 30;
  112. light.shadow.camera.far = dLight;
  113. light.shadow.mapSize.x = 1024 * 2;
  114. light.shadow.mapSize.y = 1024 * 2;
  115. scene.add( light );
  116. window.addEventListener( 'resize', onWindowResize );
  117. }
  118. function onWindowResize() {
  119. camera.aspect = window.innerWidth / window.innerHeight;
  120. camera.updateProjectionMatrix();
  121. renderer.setSize( window.innerWidth, window.innerHeight );
  122. }
  123. async function initPhysics() {
  124. physics = await RapierPhysics();
  125. // Create the terrain body using RapierPhysics module
  126. physics.addHeightfield( terrainMesh, terrainWidth - 1, terrainDepth - 1, heightData, { x: terrainWidthExtents, y: 1.0, z: terrainDepthExtents } );
  127. // Continue with adding other dynamic objects as needed
  128. }
  129. function generateHeight( width, depth, minHeight, maxHeight ) {
  130. const size = width * depth;
  131. const data = new Float32Array( size );
  132. const hRange = maxHeight - minHeight;
  133. const w2 = width / 2;
  134. const d2 = depth / 2;
  135. const phaseMult = 12;
  136. let p = 0;
  137. for ( let j = 0; j < depth; j ++ ) {
  138. for ( let i = 0; i < width; i ++ ) {
  139. const radius = Math.sqrt( Math.pow( ( i - w2 ) / w2, 2.0 ) + Math.pow( ( j - d2 ) / d2, 2.0 ) );
  140. const height = ( Math.sin( radius * phaseMult ) + 1 ) * 0.5 * hRange + minHeight;
  141. data[ p ] = height;
  142. p ++;
  143. }
  144. }
  145. return data;
  146. }
  147. function generateObject() {
  148. const numTypes = 3; // cones not working
  149. const objectType = Math.ceil( Math.random() * numTypes );
  150. let threeObject = null;
  151. const objectSize = 3;
  152. let radius, height;
  153. switch ( objectType ) {
  154. case 1: // Sphere
  155. radius = 1 + Math.random() * objectSize;
  156. threeObject = new THREE.Mesh( new THREE.SphereGeometry( radius, 20, 20 ), createObjectMaterial() );
  157. break;
  158. case 2: // Box
  159. const sx = 1 + Math.random() * objectSize;
  160. const sy = 1 + Math.random() * objectSize;
  161. const sz = 1 + Math.random() * objectSize;
  162. threeObject = new THREE.Mesh( new THREE.BoxGeometry( sx, sy, sz, 1, 1, 1 ), createObjectMaterial() );
  163. break;
  164. case 3: // Cylinder
  165. radius = 1 + Math.random() * objectSize;
  166. height = 1 + Math.random() * objectSize;
  167. threeObject = new THREE.Mesh( new THREE.CylinderGeometry( radius, radius, height, 20, 1 ), createObjectMaterial() );
  168. break;
  169. default: // Cone
  170. radius = 1 + Math.random() * objectSize;
  171. height = 2 + Math.random() * objectSize;
  172. threeObject = new THREE.Mesh( new THREE.ConeGeometry( radius, height, 20, 2 ), createObjectMaterial() );
  173. break;
  174. }
  175. // Position objects higher and with more randomization to prevent clustering
  176. threeObject.position.set(
  177. ( Math.random() - 0.5 ) * terrainWidth * 0.6,
  178. terrainMaxHeight + objectSize + 15 + Math.random() * 5, // Even higher with randomization
  179. ( Math.random() - 0.5 ) * terrainDepth * 0.6
  180. );
  181. const mass = objectSize * 5;
  182. const restitution = 0.3; // Add some bounciness
  183. // Add to scene first
  184. scene.add( threeObject );
  185. // Add physics to the object
  186. physics.addMesh( threeObject, mass, restitution );
  187. // Store the object for later reference
  188. dynamicObjects.push( threeObject );
  189. // Force a small delay before adding the next object
  190. timeNextSpawn = time + 0.5;
  191. threeObject.receiveShadow = true;
  192. threeObject.castShadow = true;
  193. }
  194. function createObjectMaterial() {
  195. const c = Math.floor( Math.random() * ( 1 << 24 ) );
  196. return new THREE.MeshPhongMaterial( { color: c } );
  197. }
  198. function animate() {
  199. render();
  200. stats.update();
  201. }
  202. function render() {
  203. const deltaTime = clock.getDelta();
  204. // Generate new objects with a delay between them
  205. if ( dynamicObjects.length < maxNumObjects && time > timeNextSpawn ) {
  206. // Generate object directly in this frame
  207. generateObject();
  208. // timeNextSpawn is now set in generateObject()
  209. }
  210. // Clean up objects that have fallen off the terrain
  211. for ( let i = dynamicObjects.length - 1; i >= 0; i -- ) {
  212. const obj = dynamicObjects[ i ];
  213. if ( obj.position.y < terrainMinHeight - 10 ) {
  214. // Remove from scene and physics world
  215. scene.remove( obj );
  216. dynamicObjects.splice( i, 1 );
  217. }
  218. }
  219. updatePhysics();
  220. renderer.render( scene, camera );
  221. time += deltaTime;
  222. }
  223. function updatePhysics() {
  224. // Check for objects that might need help with physics
  225. for ( let i = 0, il = dynamicObjects.length; i < il; i ++ ) {
  226. const objThree = dynamicObjects[ i ];
  227. // If object is not moving but should be (based on height), try to fix it
  228. if ( objThree.position.y > 1.0 ) {
  229. // Check if physics body exists
  230. if ( objThree.userData && objThree.userData.physics && objThree.userData.physics.body ) {
  231. const body = objThree.userData.physics.body;
  232. // Make sure body is awake
  233. if ( typeof body.wakeUp === 'function' ) {
  234. body.wakeUp();
  235. }
  236. // Check velocity and apply impulse if needed
  237. if ( typeof body.linvel === 'function' ) {
  238. const velocity = body.linvel();
  239. const speed = Math.sqrt( velocity.x * velocity.x + velocity.y * velocity.y + velocity.z * velocity.z );
  240. // If object is very slow, give it a stronger impulse
  241. if ( speed < 0.5 ) {
  242. body.applyImpulse( { x: 0, y: - 2.0, z: 0 }, true );
  243. }
  244. }
  245. } else {
  246. // If the object doesn't have a physics body but should, recreate it
  247. const mass = 5; // Default mass
  248. const restitution = 0.3; // Default restitution
  249. // Recreate physics for the object
  250. physics.addMesh( objThree, mass, restitution );
  251. }
  252. }
  253. }
  254. }
  255. </script>
  256. </body>
  257. </html>
粤ICP备19079148号