OSDN Git Service

three.jsをThirdPartyに追加
[webglgame/webgl_framework.git] / webglFramework / Thirdparty / three.js-master / examples / webgl_physics_rope.html
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
13                 background-color: #bfd1e5;
14                 margin: 0px;
15                 overflow: hidden;
16             }
17
18             #info {
19                 position: absolute;
20                 top: 0px; width: 100%;
21                 padding: 5px;
22             }
23
24             a {
25
26                 color: #a06851;
27             }
28
29         </style>
30     </head>
31     <body>
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>
34
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>
40
41         <script>
42
43                 // Detects webgl
44                 if ( ! Detector.webgl ) {
45                     Detector.addGetWebGLMessage();
46                     document.getElementById( 'container' ).innerHTML = "";
47                 }
48
49                 // - Global variables -
50
51                 // Graphics variables
52                 var container, stats;
53                 var camera, controls, scene, renderer;
54                 var textureLoader;
55                 var clock = new THREE.Clock();
56
57                 // Physics variables
58                 var gravityConstant = -9.8;
59                 var collisionConfiguration;
60                 var dispatcher;
61                 var broadphase;
62                 var solver;
63                 var softBodySolver;
64                 var physicsWorld;
65                 var rigidBodies = [];
66                 var margin = 0.05;
67                 var hinge;
68                 var rope;
69                 var transformAux1 = new Ammo.btTransform();
70
71                 var time = 0;
72                 var armMovement = 0;
73
74                 // - Main code -
75
76                 init();
77                 animate();
78
79
80                 // - Functions -
81
82                 function init() {
83
84                         initGraphics();
85
86                         initPhysics();
87
88                         createObjects();
89
90                         initInput();
91
92                 }
93
94                 function initGraphics() {
95
96                         container = document.getElementById( 'container' );
97
98                         camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.2, 2000 );
99
100                         scene = new THREE.Scene();
101                         scene.background = new THREE.Color( 0xbfd1e5 );
102
103                         camera.position.set( -7, 5, 8 );
104
105                         controls = new THREE.OrbitControls( camera );
106                         controls.target.set( 0, 2, 0 );
107                         controls.update();
108
109                         renderer = new THREE.WebGLRenderer();
110                         renderer.setPixelRatio( window.devicePixelRatio );
111                         renderer.setSize( window.innerWidth, window.innerHeight );
112                         renderer.shadowMap.enabled = true;
113
114                         textureLoader = new THREE.TextureLoader();
115
116                         var ambientLight = new THREE.AmbientLight( 0x404040 );
117                         scene.add( ambientLight );
118
119                         var light = new THREE.DirectionalLight( 0xffffff, 1 );
120                         light.position.set( -10, 10, 5 );
121                         light.castShadow = true;
122                         var d = 10;
123                         light.shadow.camera.left = -d;
124                         light.shadow.camera.right = d;
125                         light.shadow.camera.top = d;
126                         light.shadow.camera.bottom = -d;
127
128                         light.shadow.camera.near = 2;
129                         light.shadow.camera.far = 50;
130
131                         light.shadow.mapSize.x = 1024;
132                         light.shadow.mapSize.y = 1024;
133
134                         scene.add( light );
135
136
137                         container.innerHTML = "";
138
139                         container.appendChild( renderer.domElement );
140
141                         stats = new Stats();
142                         stats.domElement.style.position = 'absolute';
143                         stats.domElement.style.top = '0px';
144                         container.appendChild( stats.domElement );
145
146                         //
147
148                         window.addEventListener( 'resize', onWindowResize, false );
149
150                 }
151
152                 function initPhysics() {
153
154                         // Physics configuration
155
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 ) );
164
165                 }
166
167                 function createObjects() {
168
169                         var pos = new THREE.Vector3();
170                         var quat = new THREE.Quaternion();
171
172                         // Ground
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;
184                         } );
185
186
187                         // Ball
188                         var ballMass = 1.2;
189                         var ballRadius = 0.6;
190
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 );
196                         pos.set( -3, 2, 0 );
197                         quat.set( 0, 0, 0, 1 );
198                         createRigidBody( ball, ballShape, ballMass, pos, quat );
199                         ball.userData.physicsBody.setFriction( 0.5 );
200
201                         // Wall
202                         var brickMass = 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 ++ ) {
212
213                                 var oddRow = ( j % 2 ) == 1;
214
215                                 pos.z = z0;
216
217                                 if ( oddRow ) {
218                                         pos.z -= 0.25 * brickLength;
219                                 }
220
221                                 var nRow = oddRow? numBricksLength + 1 : numBricksLength;
222                                 for ( var i = 0; i < nRow; i ++ ) {
223
224                                         var brickLengthCurrent = brickLength;
225                                         var brickMassCurrent = brickMass;
226                                         if ( oddRow && ( i == 0 || i == nRow - 1 ) ) {
227                                                 brickLengthCurrent *= 0.5;
228                                                 brickMassCurrent *= 0.5;
229                                         }
230
231                                         var brick = createParalellepiped( brickDepth, brickHeight, brickLengthCurrent, brickMassCurrent, pos, quat, createMaterial() );
232                                         brick.castShadow = true;
233                                         brick.receiveShadow = true;
234
235                                         if ( oddRow && ( i == 0 || i == nRow - 2 ) ) {
236                                                 pos.z += 0.75 * brickLength;
237                                         }
238                                         else {
239                                                 pos.z += brickLength;
240                                         }
241
242                                 }
243                                 pos.y += brickHeight;
244                         }
245
246                         // The rope
247                         // Rope graphic object
248                         var ropeNumSegments = 10;
249                         var ropeLength = 4;
250                         var ropeMass = 3;
251                         var ropePos = ball.position.clone();
252                         ropePos.y += ballRadius;
253
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 = [];
259
260                         for ( var i = 0; i < ropeNumSegments + 1; i++ ) {
261                                 ropePositions.push( ropePos.x, ropePos.y + i * segmentLength, ropePos.z );
262                         }
263
264                         for ( var i = 0; i < ropeNumSegments; i++ ) {
265                                 ropeIndices.push( i, i + 1 );
266                         }
267
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;
274                         scene.add( rope );
275
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 );
290
291                         // The base
292                         var armMass = 2;
293                         var armLength = 3;
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;
309
310                         // Glue the rope extremes to the ball and the arm
311                         var influence = 1;
312                         ropeSoftBody.appendAnchor( 0, ball.userData.physicsBody, true, influence );
313                         ropeSoftBody.appendAnchor( ropeNumSegments, arm.userData.physicsBody, true, influence );
314
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 );
321
322
323                 }
324
325                 function createParalellepiped( sx, sy, sz, mass, pos, quat, material ) {
326
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 );
330
331                         createRigidBody( threeObject, shape, mass, pos, quat );
332
333                         return threeObject;
334
335                 }
336
337                 function createRigidBody( threeObject, physicsShape, mass, pos, quat ) {
338
339                         threeObject.position.copy( pos );
340                         threeObject.quaternion.copy( quat );
341
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 );
347
348                         var localInertia = new Ammo.btVector3( 0, 0, 0 );
349                         physicsShape.calculateLocalInertia( mass, localInertia );
350
351                         var rbInfo = new Ammo.btRigidBodyConstructionInfo( mass, motionState, physicsShape, localInertia );
352                         var body = new Ammo.btRigidBody( rbInfo );
353
354                         threeObject.userData.physicsBody = body;
355
356                         scene.add( threeObject );
357
358                         if ( mass > 0 ) {
359                                 rigidBodies.push( threeObject );
360
361                                 // Disable deactivation
362                                 body.setActivationState( 4 );
363                         }
364
365                         physicsWorld.addRigidBody( body );
366
367                 }
368
369                 function createRandomColor() {
370                         return Math.floor( Math.random() * ( 1 << 24 ) );
371                 }
372
373                 function createMaterial() {
374                         return new THREE.MeshPhongMaterial( { color: createRandomColor() } );
375                 }
376
377                 function initInput() {
378
379                         window.addEventListener( 'keydown', function( event ) {
380
381                                 switch ( event.keyCode ) {
382                                         // Q
383                                         case 81:
384                                                 armMovement = 1;
385                                         break;
386
387                                         // A
388                                         case 65:
389                                                 armMovement = - 1;
390                                         break;
391                                 }
392
393                         }, false );
394
395                         window.addEventListener( 'keyup', function( event ) {
396
397                                 armMovement = 0;
398
399                         }, false );
400
401                 }
402
403                 function onWindowResize() {
404
405                         camera.aspect = window.innerWidth / window.innerHeight;
406                         camera.updateProjectionMatrix();
407
408                         renderer.setSize( window.innerWidth, window.innerHeight );
409
410                 }
411
412                 function animate() {
413
414                         requestAnimationFrame( animate );
415
416                         render();
417                         stats.update();
418
419                 }
420
421                 function render() {
422
423                         var deltaTime = clock.getDelta();
424
425                         updatePhysics( deltaTime );
426
427                         renderer.render( scene, camera );
428
429                         time += deltaTime;
430
431                 }
432
433                 function updatePhysics( deltaTime ) {
434
435                         // Hinge control
436                         hinge.enableAngularMotor( true, 1.5 * armMovement, 50 );
437
438                         // Step world
439                         physicsWorld.stepSimulation( deltaTime, 10 );
440
441                         // Update rope
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();
446                         var indexFloat = 0;
447                         for ( var i = 0; i < numVerts; i ++ ) {
448
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();
454
455                         }
456                         rope.geometry.attributes.position.needsUpdate = true;
457
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();
463                                 if ( ms ) {
464
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() );
470
471                                 }
472                         }
473
474                 }
475
476         </script>
477
478     </body>
479 </html>