webgl_physics_cloth.html 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. <html lang="en">
  2. <head>
  3. <title>Ammo.js softbody cloth 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">Ammo.js physics soft body cloth demo<br>Press Q or A to move the arm.</div>
  15. <div id="container"></div>
  16. <script src="../build/three.js"></script>
  17. <script src="js/libs/ammo.js"></script>
  18. <script src="js/controls/OrbitControls.js"></script>
  19. <script src="js/WebGL.js"></script>
  20. <script src="js/libs/stats.min.js"></script>
  21. <script>
  22. // Detects webgl
  23. if ( WEBGL.isWebGLAvailable() === false ) {
  24. document.body.appendChild( WEBGL.getWebGLErrorMessage() );
  25. }
  26. // Graphics variables
  27. var container, stats;
  28. var camera, controls, scene, renderer;
  29. var textureLoader;
  30. var clock = new THREE.Clock();
  31. // Physics variables
  32. var gravityConstant = - 9.8;
  33. var physicsWorld;
  34. var rigidBodies = [];
  35. var margin = 0.05;
  36. var hinge;
  37. var cloth;
  38. var transformAux1;
  39. var armMovement = 0;
  40. Ammo().then( function( AmmoLib ) {
  41. Ammo = AmmoLib;
  42. init();
  43. animate();
  44. } );
  45. function init() {
  46. initGraphics();
  47. initPhysics();
  48. createObjects();
  49. initInput();
  50. }
  51. function initGraphics() {
  52. container = document.getElementById( 'container' );
  53. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.2, 2000 );
  54. scene = new THREE.Scene();
  55. scene.background = new THREE.Color( 0xbfd1e5 );
  56. camera.position.set( - 12, 7, 4 );
  57. renderer = new THREE.WebGLRenderer();
  58. renderer.setPixelRatio( window.devicePixelRatio );
  59. renderer.setSize( window.innerWidth, window.innerHeight );
  60. renderer.shadowMap.enabled = true;
  61. container.appendChild( renderer.domElement );
  62. controls = new THREE.OrbitControls( camera, renderer.domElement );
  63. controls.target.set( 0, 2, 0 );
  64. controls.update();
  65. textureLoader = new THREE.TextureLoader();
  66. var ambientLight = new THREE.AmbientLight( 0x404040 );
  67. scene.add( ambientLight );
  68. var light = new THREE.DirectionalLight( 0xffffff, 1 );
  69. light.position.set( - 7, 10, 15 );
  70. light.castShadow = true;
  71. var d = 10;
  72. light.shadow.camera.left = - d;
  73. light.shadow.camera.right = d;
  74. light.shadow.camera.top = d;
  75. light.shadow.camera.bottom = - d;
  76. light.shadow.camera.near = 2;
  77. light.shadow.camera.far = 50;
  78. light.shadow.mapSize.x = 1024;
  79. light.shadow.mapSize.y = 1024;
  80. light.shadow.bias = - 0.003;
  81. scene.add( light );
  82. stats = new Stats();
  83. stats.domElement.style.position = 'absolute';
  84. stats.domElement.style.top = '0px';
  85. container.appendChild( stats.domElement );
  86. window.addEventListener( 'resize', onWindowResize, false );
  87. }
  88. function initPhysics() {
  89. // Physics configuration
  90. var collisionConfiguration = new Ammo.btSoftBodyRigidBodyCollisionConfiguration();
  91. var dispatcher = new Ammo.btCollisionDispatcher( collisionConfiguration );
  92. var broadphase = new Ammo.btDbvtBroadphase();
  93. var solver = new Ammo.btSequentialImpulseConstraintSolver();
  94. var softBodySolver = new Ammo.btDefaultSoftBodySolver();
  95. physicsWorld = new Ammo.btSoftRigidDynamicsWorld( dispatcher, broadphase, solver, collisionConfiguration, softBodySolver );
  96. physicsWorld.setGravity( new Ammo.btVector3( 0, gravityConstant, 0 ) );
  97. physicsWorld.getWorldInfo().set_m_gravity( new Ammo.btVector3( 0, gravityConstant, 0 ) );
  98. transformAux1 = new Ammo.btTransform();
  99. }
  100. function createObjects() {
  101. var pos = new THREE.Vector3();
  102. var quat = new THREE.Quaternion();
  103. // Ground
  104. pos.set( 0, - 0.5, 0 );
  105. quat.set( 0, 0, 0, 1 );
  106. var ground = createParalellepiped( 40, 1, 40, 0, pos, quat, new THREE.MeshPhongMaterial( { color: 0xFFFFFF } ) );
  107. ground.castShadow = true;
  108. ground.receiveShadow = true;
  109. textureLoader.load( "textures/grid.png", function ( texture ) {
  110. texture.wrapS = THREE.RepeatWrapping;
  111. texture.wrapT = THREE.RepeatWrapping;
  112. texture.repeat.set( 40, 40 );
  113. ground.material.map = texture;
  114. ground.material.needsUpdate = true;
  115. } );
  116. // Wall
  117. var brickMass = 0.5;
  118. var brickLength = 1.2;
  119. var brickDepth = 0.6;
  120. var brickHeight = brickLength * 0.5;
  121. var numBricksLength = 6;
  122. var numBricksHeight = 8;
  123. var z0 = - numBricksLength * brickLength * 0.5;
  124. pos.set( 0, brickHeight * 0.5, z0 );
  125. quat.set( 0, 0, 0, 1 );
  126. for ( var j = 0; j < numBricksHeight; j ++ ) {
  127. var oddRow = ( j % 2 ) == 1;
  128. pos.z = z0;
  129. if ( oddRow ) {
  130. pos.z -= 0.25 * brickLength;
  131. }
  132. var nRow = oddRow ? numBricksLength + 1 : numBricksLength;
  133. for ( var i = 0; i < nRow; i ++ ) {
  134. var brickLengthCurrent = brickLength;
  135. var brickMassCurrent = brickMass;
  136. if ( oddRow && ( i == 0 || i == nRow - 1 ) ) {
  137. brickLengthCurrent *= 0.5;
  138. brickMassCurrent *= 0.5;
  139. }
  140. var brick = createParalellepiped( brickDepth, brickHeight, brickLengthCurrent, brickMassCurrent, pos, quat, createMaterial() );
  141. brick.castShadow = true;
  142. brick.receiveShadow = true;
  143. if ( oddRow && ( i == 0 || i == nRow - 2 ) ) {
  144. pos.z += 0.75 * brickLength;
  145. } else {
  146. pos.z += brickLength;
  147. }
  148. }
  149. pos.y += brickHeight;
  150. }
  151. // The cloth
  152. // Cloth graphic object
  153. var clothWidth = 4;
  154. var clothHeight = 3;
  155. var clothNumSegmentsZ = clothWidth * 5;
  156. var clothNumSegmentsY = clothHeight * 5;
  157. var clothPos = new THREE.Vector3( - 3, 3, 2 );
  158. //var clothGeometry = new THREE.BufferGeometry();
  159. var clothGeometry = new THREE.PlaneBufferGeometry( clothWidth, clothHeight, clothNumSegmentsZ, clothNumSegmentsY );
  160. clothGeometry.rotateY( Math.PI * 0.5 );
  161. clothGeometry.translate( clothPos.x, clothPos.y + clothHeight * 0.5, clothPos.z - clothWidth * 0.5 );
  162. //var clothMaterial = new THREE.MeshLambertMaterial( { color: 0x0030A0, side: THREE.DoubleSide } );
  163. var clothMaterial = new THREE.MeshLambertMaterial( { color: 0xFFFFFF, side: THREE.DoubleSide } );
  164. cloth = new THREE.Mesh( clothGeometry, clothMaterial );
  165. cloth.castShadow = true;
  166. cloth.receiveShadow = true;
  167. scene.add( cloth );
  168. textureLoader.load( "textures/grid.png", function ( texture ) {
  169. texture.wrapS = THREE.RepeatWrapping;
  170. texture.wrapT = THREE.RepeatWrapping;
  171. texture.repeat.set( clothNumSegmentsZ, clothNumSegmentsY );
  172. cloth.material.map = texture;
  173. cloth.material.needsUpdate = true;
  174. } );
  175. // Cloth physic object
  176. var softBodyHelpers = new Ammo.btSoftBodyHelpers();
  177. var clothCorner00 = new Ammo.btVector3( clothPos.x, clothPos.y + clothHeight, clothPos.z );
  178. var clothCorner01 = new Ammo.btVector3( clothPos.x, clothPos.y + clothHeight, clothPos.z - clothWidth );
  179. var clothCorner10 = new Ammo.btVector3( clothPos.x, clothPos.y, clothPos.z );
  180. var clothCorner11 = new Ammo.btVector3( clothPos.x, clothPos.y, clothPos.z - clothWidth );
  181. var clothSoftBody = softBodyHelpers.CreatePatch( physicsWorld.getWorldInfo(), clothCorner00, clothCorner01, clothCorner10, clothCorner11, clothNumSegmentsZ + 1, clothNumSegmentsY + 1, 0, true );
  182. var sbConfig = clothSoftBody.get_m_cfg();
  183. sbConfig.set_viterations( 10 );
  184. sbConfig.set_piterations( 10 );
  185. clothSoftBody.setTotalMass( 0.9, false );
  186. Ammo.castObject( clothSoftBody, Ammo.btCollisionObject ).getCollisionShape().setMargin( margin * 3 );
  187. physicsWorld.addSoftBody( clothSoftBody, 1, - 1 );
  188. cloth.userData.physicsBody = clothSoftBody;
  189. // Disable deactivation
  190. clothSoftBody.setActivationState( 4 );
  191. // The base
  192. var armMass = 2;
  193. var armLength = 3 + clothWidth;
  194. var pylonHeight = clothPos.y + clothHeight;
  195. var baseMaterial = new THREE.MeshPhongMaterial( { color: 0x606060 } );
  196. pos.set( clothPos.x, 0.1, clothPos.z - armLength );
  197. quat.set( 0, 0, 0, 1 );
  198. var base = createParalellepiped( 1, 0.2, 1, 0, pos, quat, baseMaterial );
  199. base.castShadow = true;
  200. base.receiveShadow = true;
  201. pos.set( clothPos.x, 0.5 * pylonHeight, clothPos.z - armLength );
  202. var pylon = createParalellepiped( 0.4, pylonHeight, 0.4, 0, pos, quat, baseMaterial );
  203. pylon.castShadow = true;
  204. pylon.receiveShadow = true;
  205. pos.set( clothPos.x, pylonHeight + 0.2, clothPos.z - 0.5 * armLength );
  206. var arm = createParalellepiped( 0.4, 0.4, armLength + 0.4, armMass, pos, quat, baseMaterial );
  207. arm.castShadow = true;
  208. arm.receiveShadow = true;
  209. // Glue the cloth to the arm
  210. var influence = 0.5;
  211. clothSoftBody.appendAnchor( 0, arm.userData.physicsBody, false, influence );
  212. clothSoftBody.appendAnchor( clothNumSegmentsZ, arm.userData.physicsBody, false, influence );
  213. // Hinge constraint to move the arm
  214. var pivotA = new Ammo.btVector3( 0, pylonHeight * 0.5, 0 );
  215. var pivotB = new Ammo.btVector3( 0, - 0.2, - armLength * 0.5 );
  216. var axis = new Ammo.btVector3( 0, 1, 0 );
  217. hinge = new Ammo.btHingeConstraint( pylon.userData.physicsBody, arm.userData.physicsBody, pivotA, pivotB, axis, axis, true );
  218. physicsWorld.addConstraint( hinge, true );
  219. }
  220. function createParalellepiped( sx, sy, sz, mass, pos, quat, material ) {
  221. var threeObject = new THREE.Mesh( new THREE.BoxBufferGeometry( sx, sy, sz, 1, 1, 1 ), material );
  222. var shape = new Ammo.btBoxShape( new Ammo.btVector3( sx * 0.5, sy * 0.5, sz * 0.5 ) );
  223. shape.setMargin( margin );
  224. createRigidBody( threeObject, shape, mass, pos, quat );
  225. return threeObject;
  226. }
  227. function createRigidBody( threeObject, physicsShape, mass, pos, quat ) {
  228. threeObject.position.copy( pos );
  229. threeObject.quaternion.copy( quat );
  230. var transform = new Ammo.btTransform();
  231. transform.setIdentity();
  232. transform.setOrigin( new Ammo.btVector3( pos.x, pos.y, pos.z ) );
  233. transform.setRotation( new Ammo.btQuaternion( quat.x, quat.y, quat.z, quat.w ) );
  234. var motionState = new Ammo.btDefaultMotionState( transform );
  235. var localInertia = new Ammo.btVector3( 0, 0, 0 );
  236. physicsShape.calculateLocalInertia( mass, localInertia );
  237. var rbInfo = new Ammo.btRigidBodyConstructionInfo( mass, motionState, physicsShape, localInertia );
  238. var body = new Ammo.btRigidBody( rbInfo );
  239. threeObject.userData.physicsBody = body;
  240. scene.add( threeObject );
  241. if ( mass > 0 ) {
  242. rigidBodies.push( threeObject );
  243. // Disable deactivation
  244. body.setActivationState( 4 );
  245. }
  246. physicsWorld.addRigidBody( body );
  247. }
  248. function createRandomColor() {
  249. return Math.floor( Math.random() * ( 1 << 24 ) );
  250. }
  251. function createMaterial() {
  252. return new THREE.MeshPhongMaterial( { color: createRandomColor() } );
  253. }
  254. function initInput() {
  255. window.addEventListener( 'keydown', function ( event ) {
  256. switch ( event.keyCode ) {
  257. // Q
  258. case 81:
  259. armMovement = 1;
  260. break;
  261. // A
  262. case 65:
  263. armMovement = - 1;
  264. break;
  265. }
  266. }, false );
  267. window.addEventListener( 'keyup', function () {
  268. armMovement = 0;
  269. }, false );
  270. }
  271. function onWindowResize() {
  272. camera.aspect = window.innerWidth / window.innerHeight;
  273. camera.updateProjectionMatrix();
  274. renderer.setSize( window.innerWidth, window.innerHeight );
  275. }
  276. function animate() {
  277. requestAnimationFrame( animate );
  278. render();
  279. stats.update();
  280. }
  281. function render() {
  282. var deltaTime = clock.getDelta();
  283. updatePhysics( deltaTime );
  284. renderer.render( scene, camera );
  285. }
  286. function updatePhysics( deltaTime ) {
  287. // Hinge control
  288. hinge.enableAngularMotor( true, 0.8 * armMovement, 50 );
  289. // Step world
  290. physicsWorld.stepSimulation( deltaTime, 10 );
  291. // Update cloth
  292. var softBody = cloth.userData.physicsBody;
  293. var clothPositions = cloth.geometry.attributes.position.array;
  294. var numVerts = clothPositions.length / 3;
  295. var nodes = softBody.get_m_nodes();
  296. var indexFloat = 0;
  297. for ( var i = 0; i < numVerts; i ++ ) {
  298. var node = nodes.at( i );
  299. var nodePos = node.get_m_x();
  300. clothPositions[ indexFloat ++ ] = nodePos.x();
  301. clothPositions[ indexFloat ++ ] = nodePos.y();
  302. clothPositions[ indexFloat ++ ] = nodePos.z();
  303. }
  304. cloth.geometry.computeVertexNormals();
  305. cloth.geometry.attributes.position.needsUpdate = true;
  306. cloth.geometry.attributes.normal.needsUpdate = true;
  307. // Update rigid bodies
  308. for ( var i = 0, il = rigidBodies.length; i < il; i ++ ) {
  309. var objThree = rigidBodies[ i ];
  310. var objPhys = objThree.userData.physicsBody;
  311. var ms = objPhys.getMotionState();
  312. if ( ms ) {
  313. ms.getWorldTransform( transformAux1 );
  314. var p = transformAux1.getOrigin();
  315. var q = transformAux1.getRotation();
  316. objThree.position.set( p.x(), p.y(), p.z() );
  317. objThree.quaternion.set( q.x(), q.y(), q.z(), q.w() );
  318. }
  319. }
  320. }
  321. </script>
  322. </body>
  323. </html>