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