webgl_physics_volume.html 14 KB

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