physics_ammo_cloth.html 13 KB

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