physics_ammo_volume.html 14 KB

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