physics_ammo_volume.html 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. <html lang="en">
  2. <head>
  3. <title>Ammo.js softbody volume demo</title>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  6. <meta property="og:title" content="Ammo.js softbody volume demo">
  7. <meta property="og:type" content="website">
  8. <meta property="og:url" content="https://threejs.org/examples/physics_ammo_volume.html">
  9. <meta property="og:image" content="https://threejs.org/examples/screenshots/physics_ammo_volume.jpg">
  10. <link type="text/css" rel="stylesheet" href="main.css">
  11. <style>
  12. body {
  13. color: #333;
  14. }
  15. </style>
  16. </head>
  17. <body>
  18. <div id="info">
  19. Ammo.js physics soft body volume demo<br/>
  20. Click to throw a ball
  21. </div>
  22. <div id="container"></div>
  23. <script src="jsm/libs/ammo.wasm.js"></script>
  24. <script type="importmap">
  25. {
  26. "imports": {
  27. "three": "../build/three.module.js",
  28. "three/addons/": "./jsm/"
  29. }
  30. }
  31. </script>
  32. <script type="module">
  33. import * as THREE from 'three';
  34. import Stats from 'three/addons/libs/stats.module.js';
  35. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  36. import * as BufferGeometryUtils from 'three/addons/utils/BufferGeometryUtils.js';
  37. // Graphics variables
  38. let container, stats;
  39. let camera, controls, scene, renderer;
  40. let textureLoader;
  41. const timer = new THREE.Timer();
  42. timer.connect( document );
  43. let clickRequest = false;
  44. const mouseCoords = new THREE.Vector2();
  45. const raycaster = new THREE.Raycaster();
  46. const ballMaterial = new THREE.MeshPhongMaterial( { color: 0x202020 } );
  47. const pos = new THREE.Vector3();
  48. const quat = new THREE.Quaternion();
  49. // Physics variables
  50. const gravityConstant = - 9.8;
  51. let physicsWorld;
  52. const rigidBodies = [];
  53. const softBodies = [];
  54. const margin = 0.05;
  55. let transformAux1;
  56. let softBodyHelpers;
  57. Ammo().then( function ( AmmoLib ) {
  58. Ammo = AmmoLib;
  59. init();
  60. } );
  61. function init() {
  62. initGraphics();
  63. initPhysics();
  64. createObjects();
  65. initInput();
  66. }
  67. function initGraphics() {
  68. container = document.getElementById( 'container' );
  69. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.2, 2000 );
  70. scene = new THREE.Scene();
  71. scene.background = new THREE.Color( 0xbfd1e5 );
  72. camera.position.set( - 7, 5, 8 );
  73. renderer = new THREE.WebGLRenderer( { antialias: true } );
  74. renderer.setPixelRatio( window.devicePixelRatio );
  75. renderer.setSize( window.innerWidth, window.innerHeight );
  76. renderer.setAnimationLoop( animate );
  77. renderer.shadowMap.enabled = true;
  78. container.appendChild( renderer.domElement );
  79. controls = new OrbitControls( camera, renderer.domElement );
  80. controls.target.set( 0, 2, 0 );
  81. controls.update();
  82. textureLoader = new THREE.TextureLoader();
  83. const ambientLight = new THREE.AmbientLight( 0xbbbbbb );
  84. scene.add( ambientLight );
  85. const light = new THREE.DirectionalLight( 0xffffff, 3 );
  86. light.position.set( - 10, 10, 5 );
  87. light.castShadow = true;
  88. const d = 20;
  89. light.shadow.camera.left = - d;
  90. light.shadow.camera.right = d;
  91. light.shadow.camera.top = d;
  92. light.shadow.camera.bottom = - d;
  93. light.shadow.camera.near = 2;
  94. light.shadow.camera.far = 50;
  95. light.shadow.mapSize.x = 1024;
  96. light.shadow.mapSize.y = 1024;
  97. scene.add( light );
  98. stats = new Stats();
  99. stats.domElement.style.position = 'absolute';
  100. stats.domElement.style.top = '0px';
  101. container.appendChild( stats.domElement );
  102. window.addEventListener( 'resize', onWindowResize );
  103. }
  104. function initPhysics() {
  105. // Physics configuration
  106. const collisionConfiguration = new Ammo.btSoftBodyRigidBodyCollisionConfiguration();
  107. const dispatcher = new Ammo.btCollisionDispatcher( collisionConfiguration );
  108. const broadphase = new Ammo.btDbvtBroadphase();
  109. const solver = new Ammo.btSequentialImpulseConstraintSolver();
  110. const softBodySolver = new Ammo.btDefaultSoftBodySolver();
  111. physicsWorld = new Ammo.btSoftRigidDynamicsWorld( dispatcher, broadphase, solver, collisionConfiguration, softBodySolver );
  112. physicsWorld.setGravity( new Ammo.btVector3( 0, gravityConstant, 0 ) );
  113. physicsWorld.getWorldInfo().set_m_gravity( new Ammo.btVector3( 0, gravityConstant, 0 ) );
  114. transformAux1 = new Ammo.btTransform();
  115. softBodyHelpers = new Ammo.btSoftBodyHelpers();
  116. }
  117. function createObjects() {
  118. // Ground
  119. pos.set( 0, - 0.5, 0 );
  120. quat.set( 0, 0, 0, 1 );
  121. const ground = createParalellepiped( 40, 1, 40, 0, pos, quat, new THREE.MeshPhongMaterial( { color: 0xFFFFFF } ) );
  122. ground.castShadow = true;
  123. ground.receiveShadow = true;
  124. textureLoader.load( 'textures/grid.png', function ( texture ) {
  125. texture.colorSpace = THREE.SRGBColorSpace;
  126. texture.wrapS = THREE.RepeatWrapping;
  127. texture.wrapT = THREE.RepeatWrapping;
  128. texture.repeat.set( 40, 40 );
  129. ground.material.map = texture;
  130. ground.material.needsUpdate = true;
  131. } );
  132. // Create soft volumes
  133. const volumeMass = 15;
  134. const sphereGeometry = new THREE.SphereGeometry( 1.5, 40, 25 );
  135. sphereGeometry.translate( 5, 5, 0 );
  136. createSoftVolume( sphereGeometry, volumeMass, 250 );
  137. const boxGeometry = new THREE.BoxGeometry( 1, 1, 5, 4, 4, 20 );
  138. boxGeometry.translate( - 2, 5, 0 );
  139. createSoftVolume( boxGeometry, volumeMass, 120 );
  140. // Ramp
  141. pos.set( 3, 1, 0 );
  142. quat.setFromAxisAngle( new THREE.Vector3( 0, 0, 1 ), 30 * Math.PI / 180 );
  143. const obstacle = createParalellepiped( 10, 1, 4, 0, pos, quat, new THREE.MeshPhongMaterial( { color: 0x606060 } ) );
  144. obstacle.castShadow = true;
  145. obstacle.receiveShadow = true;
  146. }
  147. function processGeometry( bufGeometry ) {
  148. // Ony consider the position values when merging the vertices
  149. const posOnlyBufGeometry = new THREE.BufferGeometry();
  150. posOnlyBufGeometry.setAttribute( 'position', bufGeometry.getAttribute( 'position' ) );
  151. posOnlyBufGeometry.setIndex( bufGeometry.getIndex() );
  152. // Merge the vertices so the triangle soup is converted to indexed triangles
  153. const indexedBufferGeom = BufferGeometryUtils.mergeVertices( posOnlyBufGeometry );
  154. // Create index arrays mapping the indexed vertices to bufGeometry vertices
  155. mapIndices( bufGeometry, indexedBufferGeom );
  156. }
  157. function isEqual( x1, y1, z1, x2, y2, z2 ) {
  158. const delta = 0.000001;
  159. return Math.abs( x2 - x1 ) < delta &&
  160. Math.abs( y2 - y1 ) < delta &&
  161. Math.abs( z2 - z1 ) < delta;
  162. }
  163. function mapIndices( bufGeometry, indexedBufferGeom ) {
  164. // Creates ammoVertices, ammoIndices and ammoIndexAssociation in bufGeometry
  165. const vertices = bufGeometry.attributes.position.array;
  166. const idxVertices = indexedBufferGeom.attributes.position.array;
  167. const indices = indexedBufferGeom.index.array;
  168. const numIdxVertices = idxVertices.length / 3;
  169. const numVertices = vertices.length / 3;
  170. bufGeometry.ammoVertices = idxVertices;
  171. bufGeometry.ammoIndices = indices;
  172. bufGeometry.ammoIndexAssociation = [];
  173. for ( let i = 0; i < numIdxVertices; i ++ ) {
  174. const association = [];
  175. bufGeometry.ammoIndexAssociation.push( association );
  176. const i3 = i * 3;
  177. for ( let j = 0; j < numVertices; j ++ ) {
  178. const j3 = j * 3;
  179. if ( isEqual( idxVertices[ i3 ], idxVertices[ i3 + 1 ], idxVertices[ i3 + 2 ],
  180. vertices[ j3 ], vertices[ j3 + 1 ], vertices[ j3 + 2 ] ) ) {
  181. association.push( j3 );
  182. }
  183. }
  184. }
  185. }
  186. function createSoftVolume( bufferGeom, mass, pressure ) {
  187. processGeometry( bufferGeom );
  188. const volume = new THREE.Mesh( bufferGeom, new THREE.MeshPhongMaterial( { color: 0xFFFFFF } ) );
  189. volume.castShadow = true;
  190. volume.receiveShadow = true;
  191. volume.frustumCulled = false;
  192. scene.add( volume );
  193. textureLoader.load( 'textures/colors.png', function ( texture ) {
  194. volume.material.map = texture;
  195. volume.material.needsUpdate = true;
  196. } );
  197. // Volume physic object
  198. const volumeSoftBody = softBodyHelpers.CreateFromTriMesh(
  199. physicsWorld.getWorldInfo(),
  200. bufferGeom.ammoVertices,
  201. bufferGeom.ammoIndices,
  202. bufferGeom.ammoIndices.length / 3,
  203. true );
  204. const sbConfig = volumeSoftBody.get_m_cfg();
  205. sbConfig.set_viterations( 40 );
  206. sbConfig.set_piterations( 40 );
  207. // Soft-soft and soft-rigid collisions
  208. sbConfig.set_collisions( 0x11 );
  209. // Friction
  210. sbConfig.set_kDF( 0.1 );
  211. // Damping
  212. sbConfig.set_kDP( 0.01 );
  213. // Pressure
  214. sbConfig.set_kPR( pressure );
  215. // Stiffness
  216. volumeSoftBody.get_m_materials().at( 0 ).set_m_kLST( 0.9 );
  217. volumeSoftBody.get_m_materials().at( 0 ).set_m_kAST( 0.9 );
  218. volumeSoftBody.setTotalMass( mass, false );
  219. Ammo.castObject( volumeSoftBody, Ammo.btCollisionObject ).getCollisionShape().setMargin( margin );
  220. physicsWorld.addSoftBody( volumeSoftBody, 1, - 1 );
  221. volume.userData.physicsBody = volumeSoftBody;
  222. // Disable deactivation
  223. volumeSoftBody.setActivationState( 4 );
  224. softBodies.push( volume );
  225. }
  226. function createParalellepiped( sx, sy, sz, mass, pos, quat, material ) {
  227. const threeObject = new THREE.Mesh( new THREE.BoxGeometry( sx, sy, sz, 1, 1, 1 ), material );
  228. const shape = new Ammo.btBoxShape( new Ammo.btVector3( sx * 0.5, sy * 0.5, sz * 0.5 ) );
  229. shape.setMargin( margin );
  230. createRigidBody( threeObject, shape, mass, pos, quat );
  231. return threeObject;
  232. }
  233. function createRigidBody( threeObject, physicsShape, mass, pos, quat ) {
  234. threeObject.position.copy( pos );
  235. threeObject.quaternion.copy( quat );
  236. const transform = new Ammo.btTransform();
  237. transform.setIdentity();
  238. transform.setOrigin( new Ammo.btVector3( pos.x, pos.y, pos.z ) );
  239. transform.setRotation( new Ammo.btQuaternion( quat.x, quat.y, quat.z, quat.w ) );
  240. const motionState = new Ammo.btDefaultMotionState( transform );
  241. const localInertia = new Ammo.btVector3( 0, 0, 0 );
  242. physicsShape.calculateLocalInertia( mass, localInertia );
  243. const rbInfo = new Ammo.btRigidBodyConstructionInfo( mass, motionState, physicsShape, localInertia );
  244. const body = new Ammo.btRigidBody( rbInfo );
  245. threeObject.userData.physicsBody = body;
  246. scene.add( threeObject );
  247. if ( mass > 0 ) {
  248. rigidBodies.push( threeObject );
  249. // Disable deactivation
  250. body.setActivationState( 4 );
  251. }
  252. physicsWorld.addRigidBody( body );
  253. return body;
  254. }
  255. function initInput() {
  256. window.addEventListener( 'pointerdown', function ( event ) {
  257. if ( ! clickRequest ) {
  258. mouseCoords.set(
  259. ( event.clientX / window.innerWidth ) * 2 - 1,
  260. - ( event.clientY / window.innerHeight ) * 2 + 1
  261. );
  262. clickRequest = true;
  263. }
  264. } );
  265. }
  266. function processClick() {
  267. if ( clickRequest ) {
  268. raycaster.setFromCamera( mouseCoords, camera );
  269. // Creates a ball
  270. const ballMass = 3;
  271. const ballRadius = 0.4;
  272. const ball = new THREE.Mesh( new THREE.SphereGeometry( ballRadius, 18, 16 ), ballMaterial );
  273. ball.castShadow = true;
  274. ball.receiveShadow = true;
  275. const ballShape = new Ammo.btSphereShape( ballRadius );
  276. ballShape.setMargin( margin );
  277. pos.copy( raycaster.ray.direction );
  278. pos.add( raycaster.ray.origin );
  279. quat.set( 0, 0, 0, 1 );
  280. const ballBody = createRigidBody( ball, ballShape, ballMass, pos, quat );
  281. ballBody.setFriction( 0.5 );
  282. pos.copy( raycaster.ray.direction );
  283. pos.multiplyScalar( 14 );
  284. ballBody.setLinearVelocity( new Ammo.btVector3( pos.x, pos.y, pos.z ) );
  285. clickRequest = false;
  286. }
  287. }
  288. function onWindowResize() {
  289. camera.aspect = window.innerWidth / window.innerHeight;
  290. camera.updateProjectionMatrix();
  291. renderer.setSize( window.innerWidth, window.innerHeight );
  292. }
  293. function animate() {
  294. timer.update();
  295. render();
  296. stats.update();
  297. }
  298. function render() {
  299. const deltaTime = timer.getDelta();
  300. updatePhysics( deltaTime );
  301. processClick();
  302. renderer.render( scene, camera );
  303. }
  304. function updatePhysics( deltaTime ) {
  305. // Step world
  306. physicsWorld.stepSimulation( deltaTime, 10 );
  307. // Update soft volumes
  308. for ( let i = 0, il = softBodies.length; i < il; i ++ ) {
  309. const volume = softBodies[ i ];
  310. const geometry = volume.geometry;
  311. const softBody = volume.userData.physicsBody;
  312. const volumePositions = geometry.attributes.position.array;
  313. const volumeNormals = geometry.attributes.normal.array;
  314. const association = geometry.ammoIndexAssociation;
  315. const numVerts = association.length;
  316. const nodes = softBody.get_m_nodes();
  317. for ( let j = 0; j < numVerts; j ++ ) {
  318. const node = nodes.at( j );
  319. const nodePos = node.get_m_x();
  320. const x = nodePos.x();
  321. const y = nodePos.y();
  322. const z = nodePos.z();
  323. const nodeNormal = node.get_m_n();
  324. const nx = nodeNormal.x();
  325. const ny = nodeNormal.y();
  326. const nz = nodeNormal.z();
  327. const assocVertex = association[ j ];
  328. for ( let k = 0, kl = assocVertex.length; k < kl; k ++ ) {
  329. let indexVertex = assocVertex[ k ];
  330. volumePositions[ indexVertex ] = x;
  331. volumeNormals[ indexVertex ] = nx;
  332. indexVertex ++;
  333. volumePositions[ indexVertex ] = y;
  334. volumeNormals[ indexVertex ] = ny;
  335. indexVertex ++;
  336. volumePositions[ indexVertex ] = z;
  337. volumeNormals[ indexVertex ] = nz;
  338. }
  339. }
  340. geometry.attributes.position.needsUpdate = true;
  341. geometry.attributes.normal.needsUpdate = true;
  342. }
  343. // Update rigid bodies
  344. for ( let i = 0, il = rigidBodies.length; i < il; i ++ ) {
  345. const objThree = rigidBodies[ i ];
  346. const objPhys = objThree.userData.physicsBody;
  347. const ms = objPhys.getMotionState();
  348. if ( ms ) {
  349. ms.getWorldTransform( transformAux1 );
  350. const p = transformAux1.getOrigin();
  351. const q = transformAux1.getRotation();
  352. objThree.position.set( p.x(), p.y(), p.z() );
  353. objThree.quaternion.set( q.x(), q.y(), q.z(), q.w() );
  354. }
  355. }
  356. }
  357. </script>
  358. </body>
  359. </html>
粤ICP备19079148号