physics_ammo_terrain.html 12 KB

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