webgl_physics_terrain.html 12 KB

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