physics_ammo_terrain.html 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>Ammo.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">Ammo.js physics terrain heightfield demo</div>
  17. <script src="jsm/libs/ammo.wasm.js"></script>
  18. <!-- Import maps polyfill -->
  19. <!-- Remove this when import maps will be widely supported -->
  20. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  21. <script type="importmap">
  22. {
  23. "imports": {
  24. "three": "../build/three.module.js",
  25. "three/addons/": "./jsm/"
  26. }
  27. }
  28. </script>
  29. <script type="module">
  30. import * as THREE from 'three';
  31. import Stats from 'three/addons/libs/stats.module.js';
  32. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  33. THREE.ColorManagement.enabled = true;
  34. // Heightfield parameters
  35. const terrainWidthExtents = 100;
  36. const terrainDepthExtents = 100;
  37. const terrainWidth = 128;
  38. const terrainDepth = 128;
  39. const terrainHalfWidth = terrainWidth / 2;
  40. const terrainHalfDepth = terrainDepth / 2;
  41. const terrainMaxHeight = 8;
  42. const terrainMinHeight = - 2;
  43. // Graphics variables
  44. let container, stats;
  45. let camera, scene, renderer;
  46. let terrainMesh;
  47. const clock = new THREE.Clock();
  48. // Physics variables
  49. let collisionConfiguration;
  50. let dispatcher;
  51. let broadphase;
  52. let solver;
  53. let physicsWorld;
  54. const dynamicObjects = [];
  55. let transformAux1;
  56. let heightData = null;
  57. let ammoHeightData = null;
  58. let time = 0;
  59. const objectTimePeriod = 3;
  60. let timeNextSpawn = time + objectTimePeriod;
  61. const maxNumObjects = 30;
  62. Ammo().then( function ( AmmoLib ) {
  63. Ammo = AmmoLib;
  64. init();
  65. animate();
  66. } );
  67. function init() {
  68. heightData = generateHeight( terrainWidth, terrainDepth, terrainMinHeight, terrainMaxHeight );
  69. initGraphics();
  70. initPhysics();
  71. }
  72. function initGraphics() {
  73. container = document.getElementById( 'container' );
  74. renderer = new THREE.WebGLRenderer();
  75. renderer.setPixelRatio( window.devicePixelRatio );
  76. renderer.setSize( window.innerWidth, window.innerHeight );
  77. renderer.shadowMap.enabled = true;
  78. container.appendChild( renderer.domElement );
  79. stats = new Stats();
  80. stats.domElement.style.position = 'absolute';
  81. stats.domElement.style.top = '0px';
  82. container.appendChild( stats.domElement );
  83. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.2, 2000 );
  84. scene = new THREE.Scene();
  85. scene.background = new THREE.Color( 0xbfd1e5 );
  86. camera.position.y = heightData[ terrainHalfWidth + terrainHalfDepth * terrainWidth ] * ( terrainMaxHeight - terrainMinHeight ) + 5;
  87. camera.position.z = terrainDepthExtents / 2;
  88. camera.lookAt( 0, 0, 0 );
  89. const controls = new OrbitControls( camera, renderer.domElement );
  90. controls.enableZoom = false;
  91. const geometry = new THREE.PlaneGeometry( terrainWidthExtents, terrainDepthExtents, terrainWidth - 1, terrainDepth - 1 );
  92. geometry.rotateX( - Math.PI / 2 );
  93. const vertices = geometry.attributes.position.array;
  94. for ( let i = 0, j = 0, l = vertices.length; i < l; i ++, j += 3 ) {
  95. // j + 1 because it is the y component that we modify
  96. vertices[ j + 1 ] = heightData[ i ];
  97. }
  98. geometry.computeVertexNormals();
  99. const groundMaterial = new THREE.MeshPhongMaterial( { color: 0xC7C7C7 } );
  100. terrainMesh = new THREE.Mesh( geometry, groundMaterial );
  101. terrainMesh.receiveShadow = true;
  102. terrainMesh.castShadow = true;
  103. scene.add( terrainMesh );
  104. const textureLoader = new THREE.TextureLoader();
  105. textureLoader.load( 'textures/grid.png', function ( texture ) {
  106. texture.wrapS = THREE.RepeatWrapping;
  107. texture.wrapT = THREE.RepeatWrapping;
  108. texture.repeat.set( terrainWidth - 1, terrainDepth - 1 );
  109. groundMaterial.map = texture;
  110. groundMaterial.needsUpdate = true;
  111. } );
  112. const light = new THREE.DirectionalLight( 0xffffff, 1 );
  113. light.position.set( 100, 100, 50 );
  114. light.castShadow = true;
  115. const dLight = 200;
  116. const sLight = dLight * 0.25;
  117. light.shadow.camera.left = - sLight;
  118. light.shadow.camera.right = sLight;
  119. light.shadow.camera.top = sLight;
  120. light.shadow.camera.bottom = - sLight;
  121. light.shadow.camera.near = dLight / 30;
  122. light.shadow.camera.far = dLight;
  123. light.shadow.mapSize.x = 1024 * 2;
  124. light.shadow.mapSize.y = 1024 * 2;
  125. scene.add( light );
  126. window.addEventListener( 'resize', onWindowResize );
  127. }
  128. function onWindowResize() {
  129. camera.aspect = window.innerWidth / window.innerHeight;
  130. camera.updateProjectionMatrix();
  131. renderer.setSize( window.innerWidth, window.innerHeight );
  132. }
  133. function initPhysics() {
  134. // Physics configuration
  135. collisionConfiguration = new Ammo.btDefaultCollisionConfiguration();
  136. dispatcher = new Ammo.btCollisionDispatcher( collisionConfiguration );
  137. broadphase = new Ammo.btDbvtBroadphase();
  138. solver = new Ammo.btSequentialImpulseConstraintSolver();
  139. physicsWorld = new Ammo.btDiscreteDynamicsWorld( dispatcher, broadphase, solver, collisionConfiguration );
  140. physicsWorld.setGravity( new Ammo.btVector3( 0, - 6, 0 ) );
  141. // Create the terrain body
  142. const groundShape = createTerrainShape();
  143. const groundTransform = new Ammo.btTransform();
  144. groundTransform.setIdentity();
  145. // Shifts the terrain, since bullet re-centers it on its bounding box.
  146. groundTransform.setOrigin( new Ammo.btVector3( 0, ( terrainMaxHeight + terrainMinHeight ) / 2, 0 ) );
  147. const groundMass = 0;
  148. const groundLocalInertia = new Ammo.btVector3( 0, 0, 0 );
  149. const groundMotionState = new Ammo.btDefaultMotionState( groundTransform );
  150. const groundBody = new Ammo.btRigidBody( new Ammo.btRigidBodyConstructionInfo( groundMass, groundMotionState, groundShape, groundLocalInertia ) );
  151. physicsWorld.addRigidBody( groundBody );
  152. transformAux1 = new Ammo.btTransform();
  153. }
  154. function generateHeight( width, depth, minHeight, maxHeight ) {
  155. // Generates the height data (a sinus wave)
  156. const size = width * depth;
  157. const data = new Float32Array( size );
  158. const hRange = maxHeight - minHeight;
  159. const w2 = width / 2;
  160. const d2 = depth / 2;
  161. const phaseMult = 12;
  162. let p = 0;
  163. for ( let j = 0; j < depth; j ++ ) {
  164. for ( let i = 0; i < width; i ++ ) {
  165. const radius = Math.sqrt(
  166. Math.pow( ( i - w2 ) / w2, 2.0 ) +
  167. Math.pow( ( j - d2 ) / d2, 2.0 ) );
  168. const height = ( Math.sin( radius * phaseMult ) + 1 ) * 0.5 * hRange + minHeight;
  169. data[ p ] = height;
  170. p ++;
  171. }
  172. }
  173. return data;
  174. }
  175. function createTerrainShape() {
  176. // This parameter is not really used, since we are using PHY_FLOAT height data type and hence it is ignored
  177. const heightScale = 1;
  178. // Up axis = 0 for X, 1 for Y, 2 for Z. Normally 1 = Y is used.
  179. const upAxis = 1;
  180. // hdt, height data type. "PHY_FLOAT" is used. Possible values are "PHY_FLOAT", "PHY_UCHAR", "PHY_SHORT"
  181. const hdt = 'PHY_FLOAT';
  182. // Set this to your needs (inverts the triangles)
  183. const flipQuadEdges = false;
  184. // Creates height data buffer in Ammo heap
  185. ammoHeightData = Ammo._malloc( 4 * terrainWidth * terrainDepth );
  186. // Copy the javascript height data array to the Ammo one.
  187. let p = 0;
  188. let p2 = 0;
  189. for ( let j = 0; j < terrainDepth; j ++ ) {
  190. for ( let i = 0; i < terrainWidth; i ++ ) {
  191. // write 32-bit float data to memory
  192. Ammo.HEAPF32[ ammoHeightData + p2 >> 2 ] = heightData[ p ];
  193. p ++;
  194. // 4 bytes/float
  195. p2 += 4;
  196. }
  197. }
  198. // Creates the heightfield physics shape
  199. const heightFieldShape = new Ammo.btHeightfieldTerrainShape(
  200. terrainWidth,
  201. terrainDepth,
  202. ammoHeightData,
  203. heightScale,
  204. terrainMinHeight,
  205. terrainMaxHeight,
  206. upAxis,
  207. hdt,
  208. flipQuadEdges
  209. );
  210. // Set horizontal scale
  211. const scaleX = terrainWidthExtents / ( terrainWidth - 1 );
  212. const scaleZ = terrainDepthExtents / ( terrainDepth - 1 );
  213. heightFieldShape.setLocalScaling( new Ammo.btVector3( scaleX, 1, scaleZ ) );
  214. heightFieldShape.setMargin( 0.05 );
  215. return heightFieldShape;
  216. }
  217. function generateObject() {
  218. const numTypes = 4;
  219. const objectType = Math.ceil( Math.random() * numTypes );
  220. let threeObject = null;
  221. let shape = null;
  222. const objectSize = 3;
  223. const margin = 0.05;
  224. let radius, height;
  225. switch ( objectType ) {
  226. case 1:
  227. // Sphere
  228. radius = 1 + Math.random() * objectSize;
  229. threeObject = new THREE.Mesh( new THREE.SphereGeometry( radius, 20, 20 ), createObjectMaterial() );
  230. shape = new Ammo.btSphereShape( radius );
  231. shape.setMargin( margin );
  232. break;
  233. case 2:
  234. // Box
  235. const sx = 1 + Math.random() * objectSize;
  236. const sy = 1 + Math.random() * objectSize;
  237. const sz = 1 + Math.random() * objectSize;
  238. threeObject = new THREE.Mesh( new THREE.BoxGeometry( sx, sy, sz, 1, 1, 1 ), createObjectMaterial() );
  239. shape = new Ammo.btBoxShape( new Ammo.btVector3( sx * 0.5, sy * 0.5, sz * 0.5 ) );
  240. shape.setMargin( margin );
  241. break;
  242. case 3:
  243. // Cylinder
  244. radius = 1 + Math.random() * objectSize;
  245. height = 1 + Math.random() * objectSize;
  246. threeObject = new THREE.Mesh( new THREE.CylinderGeometry( radius, radius, height, 20, 1 ), createObjectMaterial() );
  247. shape = new Ammo.btCylinderShape( new Ammo.btVector3( radius, height * 0.5, radius ) );
  248. shape.setMargin( margin );
  249. break;
  250. default:
  251. // Cone
  252. radius = 1 + Math.random() * objectSize;
  253. height = 2 + Math.random() * objectSize;
  254. threeObject = new THREE.Mesh( new THREE.ConeGeometry( radius, height, 20, 2 ), createObjectMaterial() );
  255. shape = new Ammo.btConeShape( radius, height );
  256. break;
  257. }
  258. threeObject.position.set( ( Math.random() - 0.5 ) * terrainWidth * 0.6, terrainMaxHeight + objectSize + 2, ( Math.random() - 0.5 ) * terrainDepth * 0.6 );
  259. const mass = objectSize * 5;
  260. const localInertia = new Ammo.btVector3( 0, 0, 0 );
  261. shape.calculateLocalInertia( mass, localInertia );
  262. const transform = new Ammo.btTransform();
  263. transform.setIdentity();
  264. const pos = threeObject.position;
  265. transform.setOrigin( new Ammo.btVector3( pos.x, pos.y, pos.z ) );
  266. const motionState = new Ammo.btDefaultMotionState( transform );
  267. const rbInfo = new Ammo.btRigidBodyConstructionInfo( mass, motionState, shape, localInertia );
  268. const body = new Ammo.btRigidBody( rbInfo );
  269. threeObject.userData.physicsBody = body;
  270. threeObject.receiveShadow = true;
  271. threeObject.castShadow = true;
  272. scene.add( threeObject );
  273. dynamicObjects.push( threeObject );
  274. physicsWorld.addRigidBody( body );
  275. }
  276. function createObjectMaterial() {
  277. const c = Math.floor( Math.random() * ( 1 << 24 ) );
  278. return new THREE.MeshPhongMaterial( { color: c } );
  279. }
  280. function animate() {
  281. requestAnimationFrame( animate );
  282. render();
  283. stats.update();
  284. }
  285. function render() {
  286. const deltaTime = clock.getDelta();
  287. if ( dynamicObjects.length < maxNumObjects && time > timeNextSpawn ) {
  288. generateObject();
  289. timeNextSpawn = time + objectTimePeriod;
  290. }
  291. updatePhysics( deltaTime );
  292. renderer.render( scene, camera );
  293. time += deltaTime;
  294. }
  295. function updatePhysics( deltaTime ) {
  296. physicsWorld.stepSimulation( deltaTime, 10 );
  297. // Update objects
  298. for ( let i = 0, il = dynamicObjects.length; i < il; i ++ ) {
  299. const objThree = dynamicObjects[ i ];
  300. const objPhys = objThree.userData.physicsBody;
  301. const ms = objPhys.getMotionState();
  302. if ( ms ) {
  303. ms.getWorldTransform( transformAux1 );
  304. const p = transformAux1.getOrigin();
  305. const q = transformAux1.getRotation();
  306. objThree.position.set( p.x(), p.y(), p.z() );
  307. objThree.quaternion.set( q.x(), q.y(), q.z(), q.w() );
  308. }
  309. }
  310. }
  311. </script>
  312. </body>
  313. </html>