physics_ammo_rope.html 13 KB

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