webgl_physics_rope.html 13 KB

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