webgl_physics_terrain.html 12 KB

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