webgl_physics_cloth.html 13 KB

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