physics_ammo_terrain.html 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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( { antialias: true } );
  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 ambientLight = new THREE.AmbientLight( 0xbbbbbb );
  112. scene.add( ambientLight );
  113. const light = new THREE.DirectionalLight( 0xffffff, 3 );
  114. light.position.set( 100, 100, 50 );
  115. light.castShadow = true;
  116. const dLight = 200;
  117. const sLight = dLight * 0.25;
  118. light.shadow.camera.left = - sLight;
  119. light.shadow.camera.right = sLight;
  120. light.shadow.camera.top = sLight;
  121. light.shadow.camera.bottom = - sLight;
  122. light.shadow.camera.near = dLight / 30;
  123. light.shadow.camera.far = dLight;
  124. light.shadow.mapSize.x = 1024 * 2;
  125. light.shadow.mapSize.y = 1024 * 2;
  126. scene.add( light );
  127. window.addEventListener( 'resize', onWindowResize );
  128. }
  129. function onWindowResize() {
  130. camera.aspect = window.innerWidth / window.innerHeight;
  131. camera.updateProjectionMatrix();
  132. renderer.setSize( window.innerWidth, window.innerHeight );
  133. }
  134. function initPhysics() {
  135. // Physics configuration
  136. collisionConfiguration = new Ammo.btDefaultCollisionConfiguration();
  137. dispatcher = new Ammo.btCollisionDispatcher( collisionConfiguration );
  138. broadphase = new Ammo.btDbvtBroadphase();
  139. solver = new Ammo.btSequentialImpulseConstraintSolver();
  140. physicsWorld = new Ammo.btDiscreteDynamicsWorld( dispatcher, broadphase, solver, collisionConfiguration );
  141. physicsWorld.setGravity( new Ammo.btVector3( 0, - 6, 0 ) );
  142. // Create the terrain body
  143. const groundShape = createTerrainShape();
  144. const groundTransform = new Ammo.btTransform();
  145. groundTransform.setIdentity();
  146. // Shifts the terrain, since bullet re-centers it on its bounding box.
  147. groundTransform.setOrigin( new Ammo.btVector3( 0, ( terrainMaxHeight + terrainMinHeight ) / 2, 0 ) );
  148. const groundMass = 0;
  149. const groundLocalInertia = new Ammo.btVector3( 0, 0, 0 );
  150. const groundMotionState = new Ammo.btDefaultMotionState( groundTransform );
  151. const groundBody = new Ammo.btRigidBody( new Ammo.btRigidBodyConstructionInfo( groundMass, groundMotionState, groundShape, groundLocalInertia ) );
  152. physicsWorld.addRigidBody( groundBody );
  153. transformAux1 = new Ammo.btTransform();
  154. }
  155. function generateHeight( width, depth, minHeight, maxHeight ) {
  156. // Generates the height data (a sinus wave)
  157. const size = width * depth;
  158. const data = new Float32Array( size );
  159. const hRange = maxHeight - minHeight;
  160. const w2 = width / 2;
  161. const d2 = depth / 2;
  162. const phaseMult = 12;
  163. let p = 0;
  164. for ( let j = 0; j < depth; j ++ ) {
  165. for ( let i = 0; i < width; i ++ ) {
  166. const radius = Math.sqrt(
  167. Math.pow( ( i - w2 ) / w2, 2.0 ) +
  168. Math.pow( ( j - d2 ) / d2, 2.0 ) );
  169. const height = ( Math.sin( radius * phaseMult ) + 1 ) * 0.5 * hRange + minHeight;
  170. data[ p ] = height;
  171. p ++;
  172. }
  173. }
  174. return data;
  175. }
  176. function createTerrainShape() {
  177. // This parameter is not really used, since we are using PHY_FLOAT height data type and hence it is ignored
  178. const heightScale = 1;
  179. // Up axis = 0 for X, 1 for Y, 2 for Z. Normally 1 = Y is used.
  180. const upAxis = 1;
  181. // hdt, height data type. "PHY_FLOAT" is used. Possible values are "PHY_FLOAT", "PHY_UCHAR", "PHY_SHORT"
  182. const hdt = 'PHY_FLOAT';
  183. // Set this to your needs (inverts the triangles)
  184. const flipQuadEdges = false;
  185. // Creates height data buffer in Ammo heap
  186. ammoHeightData = Ammo._malloc( 4 * terrainWidth * terrainDepth );
  187. // Copy the javascript height data array to the Ammo one.
  188. let p = 0;
  189. let p2 = 0;
  190. for ( let j = 0; j < terrainDepth; j ++ ) {
  191. for ( let i = 0; i < terrainWidth; i ++ ) {
  192. // write 32-bit float data to memory
  193. Ammo.HEAPF32[ ammoHeightData + p2 >> 2 ] = heightData[ p ];
  194. p ++;
  195. // 4 bytes/float
  196. p2 += 4;
  197. }
  198. }
  199. // Creates the heightfield physics shape
  200. const heightFieldShape = new Ammo.btHeightfieldTerrainShape(
  201. terrainWidth,
  202. terrainDepth,
  203. ammoHeightData,
  204. heightScale,
  205. terrainMinHeight,
  206. terrainMaxHeight,
  207. upAxis,
  208. hdt,
  209. flipQuadEdges
  210. );
  211. // Set horizontal scale
  212. const scaleX = terrainWidthExtents / ( terrainWidth - 1 );
  213. const scaleZ = terrainDepthExtents / ( terrainDepth - 1 );
  214. heightFieldShape.setLocalScaling( new Ammo.btVector3( scaleX, 1, scaleZ ) );
  215. heightFieldShape.setMargin( 0.05 );
  216. return heightFieldShape;
  217. }
  218. function generateObject() {
  219. const numTypes = 4;
  220. const objectType = Math.ceil( Math.random() * numTypes );
  221. let threeObject = null;
  222. let shape = null;
  223. const objectSize = 3;
  224. const margin = 0.05;
  225. let radius, height;
  226. switch ( objectType ) {
  227. case 1:
  228. // Sphere
  229. radius = 1 + Math.random() * objectSize;
  230. threeObject = new THREE.Mesh( new THREE.SphereGeometry( radius, 20, 20 ), createObjectMaterial() );
  231. shape = new Ammo.btSphereShape( radius );
  232. shape.setMargin( margin );
  233. break;
  234. case 2:
  235. // Box
  236. const sx = 1 + Math.random() * objectSize;
  237. const sy = 1 + Math.random() * objectSize;
  238. const sz = 1 + Math.random() * objectSize;
  239. threeObject = new THREE.Mesh( new THREE.BoxGeometry( sx, sy, sz, 1, 1, 1 ), createObjectMaterial() );
  240. shape = new Ammo.btBoxShape( new Ammo.btVector3( sx * 0.5, sy * 0.5, sz * 0.5 ) );
  241. shape.setMargin( margin );
  242. break;
  243. case 3:
  244. // Cylinder
  245. radius = 1 + Math.random() * objectSize;
  246. height = 1 + Math.random() * objectSize;
  247. threeObject = new THREE.Mesh( new THREE.CylinderGeometry( radius, radius, height, 20, 1 ), createObjectMaterial() );
  248. shape = new Ammo.btCylinderShape( new Ammo.btVector3( radius, height * 0.5, radius ) );
  249. shape.setMargin( margin );
  250. break;
  251. default:
  252. // Cone
  253. radius = 1 + Math.random() * objectSize;
  254. height = 2 + Math.random() * objectSize;
  255. threeObject = new THREE.Mesh( new THREE.ConeGeometry( radius, height, 20, 2 ), createObjectMaterial() );
  256. shape = new Ammo.btConeShape( radius, height );
  257. break;
  258. }
  259. threeObject.position.set( ( Math.random() - 0.5 ) * terrainWidth * 0.6, terrainMaxHeight + objectSize + 2, ( Math.random() - 0.5 ) * terrainDepth * 0.6 );
  260. const mass = objectSize * 5;
  261. const localInertia = new Ammo.btVector3( 0, 0, 0 );
  262. shape.calculateLocalInertia( mass, localInertia );
  263. const transform = new Ammo.btTransform();
  264. transform.setIdentity();
  265. const pos = threeObject.position;
  266. transform.setOrigin( new Ammo.btVector3( pos.x, pos.y, pos.z ) );
  267. const motionState = new Ammo.btDefaultMotionState( transform );
  268. const rbInfo = new Ammo.btRigidBodyConstructionInfo( mass, motionState, shape, localInertia );
  269. const body = new Ammo.btRigidBody( rbInfo );
  270. threeObject.userData.physicsBody = body;
  271. threeObject.receiveShadow = true;
  272. threeObject.castShadow = true;
  273. scene.add( threeObject );
  274. dynamicObjects.push( threeObject );
  275. physicsWorld.addRigidBody( body );
  276. }
  277. function createObjectMaterial() {
  278. const c = Math.floor( Math.random() * ( 1 << 24 ) );
  279. return new THREE.MeshPhongMaterial( { color: c } );
  280. }
  281. function animate() {
  282. requestAnimationFrame( animate );
  283. render();
  284. stats.update();
  285. }
  286. function render() {
  287. const deltaTime = clock.getDelta();
  288. if ( dynamicObjects.length < maxNumObjects && time > timeNextSpawn ) {
  289. generateObject();
  290. timeNextSpawn = time + objectTimePeriod;
  291. }
  292. updatePhysics( deltaTime );
  293. renderer.render( scene, camera );
  294. time += deltaTime;
  295. }
  296. function updatePhysics( deltaTime ) {
  297. physicsWorld.stepSimulation( deltaTime, 10 );
  298. // Update objects
  299. for ( let i = 0, il = dynamicObjects.length; i < il; i ++ ) {
  300. const objThree = dynamicObjects[ i ];
  301. const objPhys = objThree.userData.physicsBody;
  302. const ms = objPhys.getMotionState();
  303. if ( ms ) {
  304. ms.getWorldTransform( transformAux1 );
  305. const p = transformAux1.getOrigin();
  306. const q = transformAux1.getRotation();
  307. objThree.position.set( p.x(), p.y(), p.z() );
  308. objThree.quaternion.set( q.x(), q.y(), q.z(), q.w() );
  309. }
  310. }
  311. }
  312. </script>
  313. </body>
  314. </html>