webgl_physics_cloth.html 13 KB

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