webgl_physics_rope.html 12 KB

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