physics_ammo_rope.html 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. <html lang="en">
  2. <head>
  3. <title>Amjs softbody rope 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 rope 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. // Graphics variables
  33. let container, stats;
  34. let camera, controls, scene, renderer;
  35. let textureLoader;
  36. const clock = new THREE.Clock();
  37. // Physics variables
  38. const gravityConstant = - 9.8;
  39. let collisionConfiguration;
  40. let dispatcher;
  41. let broadphase;
  42. let solver;
  43. let softBodySolver;
  44. let physicsWorld;
  45. const rigidBodies = [];
  46. const margin = 0.05;
  47. let hinge;
  48. let rope;
  49. let transformAux1;
  50. let armMovement = 0;
  51. Ammo().then( function ( AmmoLib ) {
  52. Ammo = AmmoLib;
  53. init();
  54. animate();
  55. } );
  56. function init() {
  57. initGraphics();
  58. initPhysics();
  59. createObjects();
  60. initInput();
  61. }
  62. function initGraphics() {
  63. container = document.getElementById( 'container' );
  64. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.2, 2000 );
  65. scene = new THREE.Scene();
  66. scene.background = new THREE.Color( 0xbfd1e5 );
  67. camera.position.set( - 7, 5, 8 );
  68. renderer = new THREE.WebGLRenderer();
  69. renderer.setPixelRatio( window.devicePixelRatio );
  70. renderer.setSize( window.innerWidth, window.innerHeight );
  71. renderer.shadowMap.enabled = true;
  72. container.appendChild( renderer.domElement );
  73. controls = new OrbitControls( camera, renderer.domElement );
  74. controls.target.set( 0, 2, 0 );
  75. controls.update();
  76. textureLoader = new THREE.TextureLoader();
  77. const ambientLight = new THREE.AmbientLight( 0x404040 );
  78. scene.add( ambientLight );
  79. const light = new THREE.DirectionalLight( 0xffffff, 1 );
  80. light.position.set( - 10, 10, 5 );
  81. light.castShadow = true;
  82. const 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. scene.add( light );
  92. stats = new Stats();
  93. stats.domElement.style.position = 'absolute';
  94. stats.domElement.style.top = '0px';
  95. container.appendChild( stats.domElement );
  96. //
  97. window.addEventListener( 'resize', onWindowResize );
  98. }
  99. function initPhysics() {
  100. // Physics configuration
  101. collisionConfiguration = new Ammo.btSoftBodyRigidBodyCollisionConfiguration();
  102. dispatcher = new Ammo.btCollisionDispatcher( collisionConfiguration );
  103. broadphase = new Ammo.btDbvtBroadphase();
  104. solver = new Ammo.btSequentialImpulseConstraintSolver();
  105. softBodySolver = new Ammo.btDefaultSoftBodySolver();
  106. physicsWorld = new Ammo.btSoftRigidDynamicsWorld( dispatcher, broadphase, solver, collisionConfiguration, softBodySolver );
  107. physicsWorld.setGravity( new Ammo.btVector3( 0, gravityConstant, 0 ) );
  108. physicsWorld.getWorldInfo().set_m_gravity( new Ammo.btVector3( 0, gravityConstant, 0 ) );
  109. transformAux1 = new Ammo.btTransform();
  110. }
  111. function createObjects() {
  112. const pos = new THREE.Vector3();
  113. const quat = new THREE.Quaternion();
  114. // Ground
  115. pos.set( 0, - 0.5, 0 );
  116. quat.set( 0, 0, 0, 1 );
  117. const ground = createParalellepiped( 40, 1, 40, 0, pos, quat, new THREE.MeshPhongMaterial( { color: 0xFFFFFF } ) );
  118. ground.castShadow = true;
  119. ground.receiveShadow = true;
  120. textureLoader.load( 'textures/grid.png', function ( texture ) {
  121. texture.colorSpace = THREE.SRGBColorSpace;
  122. texture.wrapS = THREE.RepeatWrapping;
  123. texture.wrapT = THREE.RepeatWrapping;
  124. texture.repeat.set( 40, 40 );
  125. ground.material.map = texture;
  126. ground.material.needsUpdate = true;
  127. } );
  128. // Ball
  129. const ballMass = 1.2;
  130. const ballRadius = 0.6;
  131. const ball = new THREE.Mesh( new THREE.SphereGeometry( ballRadius, 20, 20 ), new THREE.MeshPhongMaterial( { color: 0x202020 } ) );
  132. ball.castShadow = true;
  133. ball.receiveShadow = true;
  134. const ballShape = new Ammo.btSphereShape( ballRadius );
  135. ballShape.setMargin( margin );
  136. pos.set( - 3, 2, 0 );
  137. quat.set( 0, 0, 0, 1 );
  138. createRigidBody( ball, ballShape, ballMass, pos, quat );
  139. ball.userData.physicsBody.setFriction( 0.5 );
  140. // Wall
  141. const brickMass = 0.5;
  142. const brickLength = 1.2;
  143. const brickDepth = 0.6;
  144. const brickHeight = brickLength * 0.5;
  145. const numBricksLength = 6;
  146. const numBricksHeight = 8;
  147. const z0 = - numBricksLength * brickLength * 0.5;
  148. pos.set( 0, brickHeight * 0.5, z0 );
  149. quat.set( 0, 0, 0, 1 );
  150. for ( let j = 0; j < numBricksHeight; j ++ ) {
  151. const oddRow = ( j % 2 ) == 1;
  152. pos.z = z0;
  153. if ( oddRow ) {
  154. pos.z -= 0.25 * brickLength;
  155. }
  156. const nRow = oddRow ? numBricksLength + 1 : numBricksLength;
  157. for ( let i = 0; i < nRow; i ++ ) {
  158. let brickLengthCurrent = brickLength;
  159. let brickMassCurrent = brickMass;
  160. if ( oddRow && ( i == 0 || i == nRow - 1 ) ) {
  161. brickLengthCurrent *= 0.5;
  162. brickMassCurrent *= 0.5;
  163. }
  164. const brick = createParalellepiped( brickDepth, brickHeight, brickLengthCurrent, brickMassCurrent, pos, quat, createMaterial() );
  165. brick.castShadow = true;
  166. brick.receiveShadow = true;
  167. if ( oddRow && ( i == 0 || i == nRow - 2 ) ) {
  168. pos.z += 0.75 * brickLength;
  169. } else {
  170. pos.z += brickLength;
  171. }
  172. }
  173. pos.y += brickHeight;
  174. }
  175. // The rope
  176. // Rope graphic object
  177. const ropeNumSegments = 10;
  178. const ropeLength = 4;
  179. const ropeMass = 3;
  180. const ropePos = ball.position.clone();
  181. ropePos.y += ballRadius;
  182. const segmentLength = ropeLength / ropeNumSegments;
  183. const ropeGeometry = new THREE.BufferGeometry();
  184. const ropeMaterial = new THREE.LineBasicMaterial( { color: 0x000000 } );
  185. const ropePositions = [];
  186. const ropeIndices = [];
  187. for ( let i = 0; i < ropeNumSegments + 1; i ++ ) {
  188. ropePositions.push( ropePos.x, ropePos.y + i * segmentLength, ropePos.z );
  189. }
  190. for ( let i = 0; i < ropeNumSegments; i ++ ) {
  191. ropeIndices.push( i, i + 1 );
  192. }
  193. ropeGeometry.setIndex( new THREE.BufferAttribute( new Uint16Array( ropeIndices ), 1 ) );
  194. ropeGeometry.setAttribute( 'position', new THREE.BufferAttribute( new Float32Array( ropePositions ), 3 ) );
  195. ropeGeometry.computeBoundingSphere();
  196. rope = new THREE.LineSegments( ropeGeometry, ropeMaterial );
  197. rope.castShadow = true;
  198. rope.receiveShadow = true;
  199. scene.add( rope );
  200. // Rope physic object
  201. const softBodyHelpers = new Ammo.btSoftBodyHelpers();
  202. const ropeStart = new Ammo.btVector3( ropePos.x, ropePos.y, ropePos.z );
  203. const ropeEnd = new Ammo.btVector3( ropePos.x, ropePos.y + ropeLength, ropePos.z );
  204. const ropeSoftBody = softBodyHelpers.CreateRope( physicsWorld.getWorldInfo(), ropeStart, ropeEnd, ropeNumSegments - 1, 0 );
  205. const sbConfig = ropeSoftBody.get_m_cfg();
  206. sbConfig.set_viterations( 10 );
  207. sbConfig.set_piterations( 10 );
  208. ropeSoftBody.setTotalMass( ropeMass, false );
  209. Ammo.castObject( ropeSoftBody, Ammo.btCollisionObject ).getCollisionShape().setMargin( margin * 3 );
  210. physicsWorld.addSoftBody( ropeSoftBody, 1, - 1 );
  211. rope.userData.physicsBody = ropeSoftBody;
  212. // Disable deactivation
  213. ropeSoftBody.setActivationState( 4 );
  214. // The base
  215. const armMass = 2;
  216. const armLength = 3;
  217. const pylonHeight = ropePos.y + ropeLength;
  218. const baseMaterial = new THREE.MeshPhongMaterial( { color: 0x606060 } );
  219. pos.set( ropePos.x, 0.1, ropePos.z - armLength );
  220. quat.set( 0, 0, 0, 1 );
  221. const base = createParalellepiped( 1, 0.2, 1, 0, pos, quat, baseMaterial );
  222. base.castShadow = true;
  223. base.receiveShadow = true;
  224. pos.set( ropePos.x, 0.5 * pylonHeight, ropePos.z - armLength );
  225. const pylon = createParalellepiped( 0.4, pylonHeight, 0.4, 0, pos, quat, baseMaterial );
  226. pylon.castShadow = true;
  227. pylon.receiveShadow = true;
  228. pos.set( ropePos.x, pylonHeight + 0.2, ropePos.z - 0.5 * armLength );
  229. const arm = createParalellepiped( 0.4, 0.4, armLength + 0.4, armMass, pos, quat, baseMaterial );
  230. arm.castShadow = true;
  231. arm.receiveShadow = true;
  232. // Glue the rope extremes to the ball and the arm
  233. const influence = 1;
  234. ropeSoftBody.appendAnchor( 0, ball.userData.physicsBody, true, influence );
  235. ropeSoftBody.appendAnchor( ropeNumSegments, arm.userData.physicsBody, true, influence );
  236. // Hinge constraint to move the arm
  237. const pivotA = new Ammo.btVector3( 0, pylonHeight * 0.5, 0 );
  238. const pivotB = new Ammo.btVector3( 0, - 0.2, - armLength * 0.5 );
  239. const axis = new Ammo.btVector3( 0, 1, 0 );
  240. hinge = new Ammo.btHingeConstraint( pylon.userData.physicsBody, arm.userData.physicsBody, pivotA, pivotB, axis, axis, true );
  241. physicsWorld.addConstraint( hinge, true );
  242. }
  243. function createParalellepiped( sx, sy, sz, mass, pos, quat, material ) {
  244. const threeObject = new THREE.Mesh( new THREE.BoxGeometry( sx, sy, sz, 1, 1, 1 ), material );
  245. const shape = new Ammo.btBoxShape( new Ammo.btVector3( sx * 0.5, sy * 0.5, sz * 0.5 ) );
  246. shape.setMargin( margin );
  247. createRigidBody( threeObject, shape, mass, pos, quat );
  248. return threeObject;
  249. }
  250. function createRigidBody( threeObject, physicsShape, mass, pos, quat ) {
  251. threeObject.position.copy( pos );
  252. threeObject.quaternion.copy( quat );
  253. const transform = new Ammo.btTransform();
  254. transform.setIdentity();
  255. transform.setOrigin( new Ammo.btVector3( pos.x, pos.y, pos.z ) );
  256. transform.setRotation( new Ammo.btQuaternion( quat.x, quat.y, quat.z, quat.w ) );
  257. const motionState = new Ammo.btDefaultMotionState( transform );
  258. const localInertia = new Ammo.btVector3( 0, 0, 0 );
  259. physicsShape.calculateLocalInertia( mass, localInertia );
  260. const rbInfo = new Ammo.btRigidBodyConstructionInfo( mass, motionState, physicsShape, localInertia );
  261. const body = new Ammo.btRigidBody( rbInfo );
  262. threeObject.userData.physicsBody = body;
  263. scene.add( threeObject );
  264. if ( mass > 0 ) {
  265. rigidBodies.push( threeObject );
  266. // Disable deactivation
  267. body.setActivationState( 4 );
  268. }
  269. physicsWorld.addRigidBody( body );
  270. }
  271. function createRandomColor() {
  272. return Math.floor( Math.random() * ( 1 << 24 ) );
  273. }
  274. function createMaterial() {
  275. return new THREE.MeshPhongMaterial( { color: createRandomColor() } );
  276. }
  277. function initInput() {
  278. window.addEventListener( 'keydown', function ( event ) {
  279. switch ( event.keyCode ) {
  280. // Q
  281. case 81:
  282. armMovement = 1;
  283. break;
  284. // A
  285. case 65:
  286. armMovement = - 1;
  287. break;
  288. }
  289. } );
  290. window.addEventListener( 'keyup', function () {
  291. armMovement = 0;
  292. } );
  293. }
  294. function onWindowResize() {
  295. camera.aspect = window.innerWidth / window.innerHeight;
  296. camera.updateProjectionMatrix();
  297. renderer.setSize( window.innerWidth, window.innerHeight );
  298. }
  299. function animate() {
  300. requestAnimationFrame( animate );
  301. render();
  302. stats.update();
  303. }
  304. function render() {
  305. const deltaTime = clock.getDelta();
  306. updatePhysics( deltaTime );
  307. renderer.render( scene, camera );
  308. }
  309. function updatePhysics( deltaTime ) {
  310. // Hinge control
  311. hinge.enableAngularMotor( true, 1.5 * armMovement, 50 );
  312. // Step world
  313. physicsWorld.stepSimulation( deltaTime, 10 );
  314. // Update rope
  315. const softBody = rope.userData.physicsBody;
  316. const ropePositions = rope.geometry.attributes.position.array;
  317. const numVerts = ropePositions.length / 3;
  318. const nodes = softBody.get_m_nodes();
  319. let indexFloat = 0;
  320. for ( let i = 0; i < numVerts; i ++ ) {
  321. const node = nodes.at( i );
  322. const nodePos = node.get_m_x();
  323. ropePositions[ indexFloat ++ ] = nodePos.x();
  324. ropePositions[ indexFloat ++ ] = nodePos.y();
  325. ropePositions[ indexFloat ++ ] = nodePos.z();
  326. }
  327. rope.geometry.attributes.position.needsUpdate = true;
  328. // Update rigid bodies
  329. for ( let i = 0, il = rigidBodies.length; i < il; i ++ ) {
  330. const objThree = rigidBodies[ i ];
  331. const objPhys = objThree.userData.physicsBody;
  332. const ms = objPhys.getMotionState();
  333. if ( ms ) {
  334. ms.getWorldTransform( transformAux1 );
  335. const p = transformAux1.getOrigin();
  336. const 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>