webgl_physics_volume.html 14 KB

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