3 <title>Amjs softbody rope demo</title>
5 <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
13 background-color: #bfd1e5;
20 top: 0px; width: 100%;
32 <div id="info">Ammo.js physics soft body rope demo<br>Press Q or A to move the arm.</div>
33 <div id="container"><br /><br /><br /><br /><br />Loading...</div>
35 <script src="../build/three.js"></script>
36 <script src="js/libs/ammo.js"></script>
37 <script src="js/controls/OrbitControls.js"></script>
38 <script src="js/Detector.js"></script>
39 <script src="js/libs/stats.min.js"></script>
44 if ( ! Detector.webgl ) {
45 Detector.addGetWebGLMessage();
46 document.getElementById( 'container' ).innerHTML = "";
49 // - Global variables -
53 var camera, controls, scene, renderer;
55 var clock = new THREE.Clock();
58 var gravityConstant = -9.8;
59 var collisionConfiguration;
69 var transformAux1 = new Ammo.btTransform();
94 function initGraphics() {
96 container = document.getElementById( 'container' );
98 camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.2, 2000 );
100 scene = new THREE.Scene();
101 scene.background = new THREE.Color( 0xbfd1e5 );
103 camera.position.set( -7, 5, 8 );
105 controls = new THREE.OrbitControls( camera );
106 controls.target.set( 0, 2, 0 );
109 renderer = new THREE.WebGLRenderer();
110 renderer.setPixelRatio( window.devicePixelRatio );
111 renderer.setSize( window.innerWidth, window.innerHeight );
112 renderer.shadowMap.enabled = true;
114 textureLoader = new THREE.TextureLoader();
116 var ambientLight = new THREE.AmbientLight( 0x404040 );
117 scene.add( ambientLight );
119 var light = new THREE.DirectionalLight( 0xffffff, 1 );
120 light.position.set( -10, 10, 5 );
121 light.castShadow = true;
123 light.shadow.camera.left = -d;
124 light.shadow.camera.right = d;
125 light.shadow.camera.top = d;
126 light.shadow.camera.bottom = -d;
128 light.shadow.camera.near = 2;
129 light.shadow.camera.far = 50;
131 light.shadow.mapSize.x = 1024;
132 light.shadow.mapSize.y = 1024;
137 container.innerHTML = "";
139 container.appendChild( renderer.domElement );
142 stats.domElement.style.position = 'absolute';
143 stats.domElement.style.top = '0px';
144 container.appendChild( stats.domElement );
148 window.addEventListener( 'resize', onWindowResize, false );
152 function initPhysics() {
154 // Physics configuration
156 collisionConfiguration = new Ammo.btSoftBodyRigidBodyCollisionConfiguration();
157 dispatcher = new Ammo.btCollisionDispatcher( collisionConfiguration );
158 broadphase = new Ammo.btDbvtBroadphase();
159 solver = new Ammo.btSequentialImpulseConstraintSolver();
160 softBodySolver = new Ammo.btDefaultSoftBodySolver();
161 physicsWorld = new Ammo.btSoftRigidDynamicsWorld( dispatcher, broadphase, solver, collisionConfiguration, softBodySolver);
162 physicsWorld.setGravity( new Ammo.btVector3( 0, gravityConstant, 0 ) );
163 physicsWorld.getWorldInfo().set_m_gravity( new Ammo.btVector3( 0, gravityConstant, 0 ) );
167 function createObjects() {
169 var pos = new THREE.Vector3();
170 var quat = new THREE.Quaternion();
173 pos.set( 0, - 0.5, 0 );
174 quat.set( 0, 0, 0, 1 );
175 var ground = createParalellepiped( 40, 1, 40, 0, pos, quat, new THREE.MeshPhongMaterial( { color: 0xFFFFFF } ) );
176 ground.castShadow = true;
177 ground.receiveShadow = true;
178 textureLoader.load( "textures/grid.png", function( texture ) {
179 texture.wrapS = THREE.RepeatWrapping;
180 texture.wrapT = THREE.RepeatWrapping;
181 texture.repeat.set( 40, 40 );
182 ground.material.map = texture;
183 ground.material.needsUpdate = true;
189 var ballRadius = 0.6;
191 var ball = new THREE.Mesh( new THREE.SphereGeometry( ballRadius, 20, 20 ), new THREE.MeshPhongMaterial( { color: 0x202020 } ) );
192 ball.castShadow = true;
193 ball.receiveShadow = true;
194 var ballShape = new Ammo.btSphereShape( ballRadius );
195 ballShape.setMargin( margin );
197 quat.set( 0, 0, 0, 1 );
198 createRigidBody( ball, ballShape, ballMass, pos, quat );
199 ball.userData.physicsBody.setFriction( 0.5 );
203 var brickLength = 1.2;
204 var brickDepth = 0.6;
205 var brickHeight = brickLength * 0.5;
206 var numBricksLength = 6;
207 var numBricksHeight = 8;
208 var z0 = - numBricksLength * brickLength * 0.5;
209 pos.set( 0, brickHeight * 0.5, z0 );
210 quat.set( 0, 0, 0, 1 );
211 for ( var j = 0; j < numBricksHeight; j ++ ) {
213 var oddRow = ( j % 2 ) == 1;
218 pos.z -= 0.25 * brickLength;
221 var nRow = oddRow? numBricksLength + 1 : numBricksLength;
222 for ( var i = 0; i < nRow; i ++ ) {
224 var brickLengthCurrent = brickLength;
225 var brickMassCurrent = brickMass;
226 if ( oddRow && ( i == 0 || i == nRow - 1 ) ) {
227 brickLengthCurrent *= 0.5;
228 brickMassCurrent *= 0.5;
231 var brick = createParalellepiped( brickDepth, brickHeight, brickLengthCurrent, brickMassCurrent, pos, quat, createMaterial() );
232 brick.castShadow = true;
233 brick.receiveShadow = true;
235 if ( oddRow && ( i == 0 || i == nRow - 2 ) ) {
236 pos.z += 0.75 * brickLength;
239 pos.z += brickLength;
243 pos.y += brickHeight;
247 // Rope graphic object
248 var ropeNumSegments = 10;
251 var ropePos = ball.position.clone();
252 ropePos.y += ballRadius;
254 var segmentLength = ropeLength / ropeNumSegments;
255 var ropeGeometry = new THREE.BufferGeometry();
256 var ropeMaterial = new THREE.LineBasicMaterial( { color: 0x000000 } );
257 var ropePositions = [];
258 var ropeIndices = [];
260 for ( var i = 0; i < ropeNumSegments + 1; i++ ) {
261 ropePositions.push( ropePos.x, ropePos.y + i * segmentLength, ropePos.z );
264 for ( var i = 0; i < ropeNumSegments; i++ ) {
265 ropeIndices.push( i, i + 1 );
268 ropeGeometry.setIndex( new THREE.BufferAttribute( new Uint16Array( ropeIndices ), 1 ) );
269 ropeGeometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( ropePositions ), 3 ) );
270 ropeGeometry.computeBoundingSphere();
271 rope = new THREE.LineSegments( ropeGeometry, ropeMaterial );
272 rope.castShadow = true;
273 rope.receiveShadow = true;
276 // Rope physic object
277 var softBodyHelpers = new Ammo.btSoftBodyHelpers();
278 var ropeStart = new Ammo.btVector3( ropePos.x, ropePos.y, ropePos.z );
279 var ropeEnd = new Ammo.btVector3( ropePos.x, ropePos.y + ropeLength, ropePos.z );
280 var ropeSoftBody = softBodyHelpers.CreateRope( physicsWorld.getWorldInfo(), ropeStart, ropeEnd, ropeNumSegments - 1, 0 );
281 var sbConfig = ropeSoftBody.get_m_cfg();
282 sbConfig.set_viterations( 10 );
283 sbConfig.set_piterations( 10 );
284 ropeSoftBody.setTotalMass( ropeMass, false );
285 Ammo.castObject( ropeSoftBody, Ammo.btCollisionObject ).getCollisionShape().setMargin( margin * 3 );
286 physicsWorld.addSoftBody( ropeSoftBody, 1, -1 );
287 rope.userData.physicsBody = ropeSoftBody;
288 // Disable deactivation
289 ropeSoftBody.setActivationState( 4 );
294 var pylonHeight = ropePos.y + ropeLength;
295 var baseMaterial = new THREE.MeshPhongMaterial( { color: 0x606060 } );
296 pos.set( ropePos.x, 0.1, ropePos.z - armLength );
297 quat.set( 0, 0, 0, 1 );
298 var base = createParalellepiped( 1, 0.2, 1, 0, pos, quat, baseMaterial );
299 base.castShadow = true;
300 base.receiveShadow = true;
301 pos.set( ropePos.x, 0.5 * pylonHeight, ropePos.z - armLength );
302 var pylon = createParalellepiped( 0.4, pylonHeight, 0.4, 0, pos, quat, baseMaterial );
303 pylon.castShadow = true;
304 pylon.receiveShadow = true;
305 pos.set( ropePos.x, pylonHeight + 0.2, ropePos.z - 0.5 * armLength );
306 var arm = createParalellepiped( 0.4, 0.4, armLength + 0.4, armMass, pos, quat, baseMaterial );
307 arm.castShadow = true;
308 arm.receiveShadow = true;
310 // Glue the rope extremes to the ball and the arm
312 ropeSoftBody.appendAnchor( 0, ball.userData.physicsBody, true, influence );
313 ropeSoftBody.appendAnchor( ropeNumSegments, arm.userData.physicsBody, true, influence );
315 // Hinge constraint to move the arm
316 var pivotA = new Ammo.btVector3( 0, pylonHeight * 0.5, 0 );
317 var pivotB = new Ammo.btVector3( 0, -0.2, - armLength * 0.5 );
318 var axis = new Ammo.btVector3( 0, 1, 0 );
319 hinge = new Ammo.btHingeConstraint( pylon.userData.physicsBody, arm.userData.physicsBody, pivotA, pivotB, axis, axis, true );
320 physicsWorld.addConstraint( hinge, true );
325 function createParalellepiped( sx, sy, sz, mass, pos, quat, material ) {
327 var threeObject = new THREE.Mesh( new THREE.BoxGeometry( sx, sy, sz, 1, 1, 1 ), material );
328 var shape = new Ammo.btBoxShape( new Ammo.btVector3( sx * 0.5, sy * 0.5, sz * 0.5 ) );
329 shape.setMargin( margin );
331 createRigidBody( threeObject, shape, mass, pos, quat );
337 function createRigidBody( threeObject, physicsShape, mass, pos, quat ) {
339 threeObject.position.copy( pos );
340 threeObject.quaternion.copy( quat );
342 var transform = new Ammo.btTransform();
343 transform.setIdentity();
344 transform.setOrigin( new Ammo.btVector3( pos.x, pos.y, pos.z ) );
345 transform.setRotation( new Ammo.btQuaternion( quat.x, quat.y, quat.z, quat.w ) );
346 var motionState = new Ammo.btDefaultMotionState( transform );
348 var localInertia = new Ammo.btVector3( 0, 0, 0 );
349 physicsShape.calculateLocalInertia( mass, localInertia );
351 var rbInfo = new Ammo.btRigidBodyConstructionInfo( mass, motionState, physicsShape, localInertia );
352 var body = new Ammo.btRigidBody( rbInfo );
354 threeObject.userData.physicsBody = body;
356 scene.add( threeObject );
359 rigidBodies.push( threeObject );
361 // Disable deactivation
362 body.setActivationState( 4 );
365 physicsWorld.addRigidBody( body );
369 function createRandomColor() {
370 return Math.floor( Math.random() * ( 1 << 24 ) );
373 function createMaterial() {
374 return new THREE.MeshPhongMaterial( { color: createRandomColor() } );
377 function initInput() {
379 window.addEventListener( 'keydown', function( event ) {
381 switch ( event.keyCode ) {
395 window.addEventListener( 'keyup', function( event ) {
403 function onWindowResize() {
405 camera.aspect = window.innerWidth / window.innerHeight;
406 camera.updateProjectionMatrix();
408 renderer.setSize( window.innerWidth, window.innerHeight );
414 requestAnimationFrame( animate );
423 var deltaTime = clock.getDelta();
425 updatePhysics( deltaTime );
427 renderer.render( scene, camera );
433 function updatePhysics( deltaTime ) {
436 hinge.enableAngularMotor( true, 1.5 * armMovement, 50 );
439 physicsWorld.stepSimulation( deltaTime, 10 );
442 var softBody = rope.userData.physicsBody;
443 var ropePositions = rope.geometry.attributes.position.array;
444 var numVerts = ropePositions.length / 3;
445 var nodes = softBody.get_m_nodes();
447 for ( var i = 0; i < numVerts; i ++ ) {
449 var node = nodes.at( i );
450 var nodePos = node.get_m_x();
451 ropePositions[ indexFloat++ ] = nodePos.x();
452 ropePositions[ indexFloat++ ] = nodePos.y();
453 ropePositions[ indexFloat++ ] = nodePos.z();
456 rope.geometry.attributes.position.needsUpdate = true;
458 // Update rigid bodies
459 for ( var i = 0, il = rigidBodies.length; i < il; i++ ) {
460 var objThree = rigidBodies[ i ];
461 var objPhys = objThree.userData.physicsBody;
462 var ms = objPhys.getMotionState();
465 ms.getWorldTransform( transformAux1 );
466 var p = transformAux1.getOrigin();
467 var q = transformAux1.getRotation();
468 objThree.position.set( p.x(), p.y(), p.z() );
469 objThree.quaternion.set( q.x(), q.y(), q.z(), q.w() );