physics_ammo_terrain.html 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. <meta property="og:title" content="Ammo.js terrain heightfield demo">
  8. <meta property="og:type" content="website">
  9. <meta property="og:url" content="https://threejs.org/examples/physics_ammo_terrain.html">
  10. <meta property="og:image" content="https://threejs.org/examples/screenshots/physics_ammo_terrain.jpg">
  11. <link type="text/css" rel="stylesheet" href="main.css">
  12. <style>
  13. body {
  14. color: #333;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="container"></div>
  20. <div id="info">Ammo.js physics terrain heightfield demo</div>
  21. <script src="jsm/libs/ammo.wasm.js"></script>
  22. <script type="importmap">
  23. {
  24. "imports": {
  25. "three": "../build/three.module.js",
  26. "three/addons/": "./jsm/"
  27. }
  28. }
  29. </script>
  30. <script type="module">
  31. import * as THREE from 'three';
  32. import Stats from 'three/addons/libs/stats.module.js';
  33. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  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 timer = new THREE.Timer();
  48. timer.connect( document );
  49. // Physics variables
  50. let collisionConfiguration;
  51. let dispatcher;
  52. let broadphase;
  53. let solver;
  54. let physicsWorld;
  55. const dynamicObjects = [];
  56. let transformAux1;
  57. let heightData = null;
  58. let ammoHeightData = null;
  59. let time = 0;
  60. const objectTimePeriod = 3;
  61. let timeNextSpawn = time + objectTimePeriod;
  62. const maxNumObjects = 30;
  63. Ammo().then( function ( AmmoLib ) {
  64. Ammo = AmmoLib;
  65. init();
  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( { antialias: true } );
  75. renderer.setPixelRatio( window.devicePixelRatio );
  76. renderer.setSize( window.innerWidth, window.innerHeight );
  77. renderer.setAnimationLoop( animate );
  78. renderer.shadowMap.enabled = true;
  79. container.appendChild( renderer.domElement );
  80. stats = new Stats();
  81. stats.domElement.style.position = 'absolute';
  82. stats.domElement.style.top = '0px';
  83. container.appendChild( stats.domElement );
  84. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.2, 2000 );
  85. scene = new THREE.Scene();
  86. scene.background = new THREE.Color( 0xbfd1e5 );
  87. camera.position.y = heightData[ terrainHalfWidth + terrainHalfDepth * terrainWidth ] * ( terrainMaxHeight - terrainMinHeight ) + 5;
  88. camera.position.z = terrainDepthExtents / 2;
  89. camera.lookAt( 0, 0, 0 );
  90. const controls = new OrbitControls( camera, renderer.domElement );
  91. controls.enableZoom = false;
  92. const geometry = new THREE.PlaneGeometry( terrainWidthExtents, terrainDepthExtents, terrainWidth - 1, terrainDepth - 1 );
  93. geometry.rotateX( - Math.PI / 2 );
  94. const vertices = geometry.attributes.position.array;
  95. for ( let i = 0, j = 0, l = vertices.length; i < l; i ++, j += 3 ) {
  96. // j + 1 because it is the y component that we modify
  97. vertices[ j + 1 ] = heightData[ i ];
  98. }
  99. geometry.computeVertexNormals();
  100. const groundMaterial = new THREE.MeshPhongMaterial( { color: 0xC7C7C7 } );
  101. terrainMesh = new THREE.Mesh( geometry, groundMaterial );
  102. terrainMesh.receiveShadow = true;
  103. terrainMesh.castShadow = true;
  104. scene.add( terrainMesh );
  105. const textureLoader = new THREE.TextureLoader();
  106. textureLoader.load( 'textures/grid.png', function ( texture ) {
  107. texture.wrapS = THREE.RepeatWrapping;
  108. texture.wrapT = THREE.RepeatWrapping;
  109. texture.repeat.set( terrainWidth - 1, terrainDepth - 1 );
  110. groundMaterial.map = texture;
  111. groundMaterial.needsUpdate = true;
  112. } );
  113. const ambientLight = new THREE.AmbientLight( 0xbbbbbb );
  114. scene.add( ambientLight );
  115. const light = new THREE.DirectionalLight( 0xffffff, 3 );
  116. light.position.set( 100, 100, 50 );
  117. light.castShadow = true;
  118. const dLight = 200;
  119. const 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 );
  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. const groundShape = createTerrainShape();
  146. const 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. const groundMass = 0;
  151. const groundLocalInertia = new Ammo.btVector3( 0, 0, 0 );
  152. const groundMotionState = new Ammo.btDefaultMotionState( groundTransform );
  153. const 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. const size = width * depth;
  160. const data = new Float32Array( size );
  161. const hRange = maxHeight - minHeight;
  162. const w2 = width / 2;
  163. const d2 = depth / 2;
  164. const phaseMult = 12;
  165. let p = 0;
  166. for ( let j = 0; j < depth; j ++ ) {
  167. for ( let i = 0; i < width; i ++ ) {
  168. const radius = Math.sqrt(
  169. Math.pow( ( i - w2 ) / w2, 2.0 ) +
  170. Math.pow( ( j - d2 ) / d2, 2.0 ) );
  171. const 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. const heightScale = 1;
  181. // Up axis = 0 for X, 1 for Y, 2 for Z. Normally 1 = Y is used.
  182. const upAxis = 1;
  183. // hdt, height data type. "PHY_FLOAT" is used. Possible values are "PHY_FLOAT", "PHY_UCHAR", "PHY_SHORT"
  184. const hdt = 'PHY_FLOAT';
  185. // Set this to your needs (inverts the triangles)
  186. const 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. let p = 0;
  191. let p2 = 0;
  192. for ( let j = 0; j < terrainDepth; j ++ ) {
  193. for ( let 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. const 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. const scaleX = terrainWidthExtents / ( terrainWidth - 1 );
  215. const 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. const numTypes = 4;
  222. const objectType = Math.ceil( Math.random() * numTypes );
  223. let threeObject = null;
  224. let shape = null;
  225. const objectSize = 3;
  226. const margin = 0.05;
  227. let radius, height;
  228. switch ( objectType ) {
  229. case 1:
  230. // Sphere
  231. radius = 1 + Math.random() * objectSize;
  232. threeObject = new THREE.Mesh( new THREE.SphereGeometry( radius, 20, 20 ), createObjectMaterial() );
  233. shape = new Ammo.btSphereShape( radius );
  234. shape.setMargin( margin );
  235. break;
  236. case 2:
  237. // Box
  238. const sx = 1 + Math.random() * objectSize;
  239. const sy = 1 + Math.random() * objectSize;
  240. const sz = 1 + Math.random() * objectSize;
  241. threeObject = new THREE.Mesh( new THREE.BoxGeometry( sx, sy, sz, 1, 1, 1 ), createObjectMaterial() );
  242. shape = new Ammo.btBoxShape( new Ammo.btVector3( sx * 0.5, sy * 0.5, sz * 0.5 ) );
  243. shape.setMargin( margin );
  244. break;
  245. case 3:
  246. // Cylinder
  247. radius = 1 + Math.random() * objectSize;
  248. height = 1 + Math.random() * objectSize;
  249. threeObject = new THREE.Mesh( new THREE.CylinderGeometry( radius, radius, height, 20, 1 ), createObjectMaterial() );
  250. shape = new Ammo.btCylinderShape( new Ammo.btVector3( radius, height * 0.5, radius ) );
  251. shape.setMargin( margin );
  252. break;
  253. default:
  254. // Cone
  255. radius = 1 + Math.random() * objectSize;
  256. height = 2 + Math.random() * objectSize;
  257. threeObject = new THREE.Mesh( new THREE.ConeGeometry( radius, height, 20, 2 ), createObjectMaterial() );
  258. shape = new Ammo.btConeShape( radius, height );
  259. break;
  260. }
  261. threeObject.position.set( ( Math.random() - 0.5 ) * terrainWidth * 0.6, terrainMaxHeight + objectSize + 2, ( Math.random() - 0.5 ) * terrainDepth * 0.6 );
  262. const mass = objectSize * 5;
  263. const localInertia = new Ammo.btVector3( 0, 0, 0 );
  264. shape.calculateLocalInertia( mass, localInertia );
  265. const transform = new Ammo.btTransform();
  266. transform.setIdentity();
  267. const pos = threeObject.position;
  268. transform.setOrigin( new Ammo.btVector3( pos.x, pos.y, pos.z ) );
  269. const motionState = new Ammo.btDefaultMotionState( transform );
  270. const rbInfo = new Ammo.btRigidBodyConstructionInfo( mass, motionState, shape, localInertia );
  271. const body = new Ammo.btRigidBody( rbInfo );
  272. threeObject.userData.physicsBody = body;
  273. threeObject.receiveShadow = true;
  274. threeObject.castShadow = true;
  275. scene.add( threeObject );
  276. dynamicObjects.push( threeObject );
  277. physicsWorld.addRigidBody( body );
  278. }
  279. function createObjectMaterial() {
  280. const c = Math.floor( Math.random() * ( 1 << 24 ) );
  281. return new THREE.MeshPhongMaterial( { color: c } );
  282. }
  283. function animate() {
  284. timer.update();
  285. render();
  286. stats.update();
  287. }
  288. function render() {
  289. const deltaTime = timer.getDelta();
  290. if ( dynamicObjects.length < maxNumObjects && time > timeNextSpawn ) {
  291. generateObject();
  292. timeNextSpawn = time + objectTimePeriod;
  293. }
  294. updatePhysics( deltaTime );
  295. renderer.render( scene, camera );
  296. time += deltaTime;
  297. }
  298. function updatePhysics( deltaTime ) {
  299. physicsWorld.stepSimulation( deltaTime, 10 );
  300. // Update objects
  301. for ( let i = 0, il = dynamicObjects.length; i < il; i ++ ) {
  302. const objThree = dynamicObjects[ i ];
  303. const objPhys = objThree.userData.physicsBody;
  304. const ms = objPhys.getMotionState();
  305. if ( ms ) {
  306. ms.getWorldTransform( transformAux1 );
  307. const p = transformAux1.getOrigin();
  308. const q = transformAux1.getRotation();
  309. objThree.position.set( p.x(), p.y(), p.z() );
  310. objThree.quaternion.set( q.x(), q.y(), q.z(), q.w() );
  311. }
  312. }
  313. }
  314. </script>
  315. </body>
  316. </html>
粤ICP备19079148号