-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
651 lines (487 loc) · 19.7 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
<!DOCTYPE html>
<html lang="en">
<head>
<title>CS277 Simulation</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
color: #808080;
font-family:Monospace;
font-size:13px;
text-align:center;
background-color: #fff;
margin: 0px;
overflow: hidden;
}
#info {
position: absolute;
top: 0px; width: 100%;
padding: 5px;
}
a {
color: #0080ff;
}
</style>
</head>
<body>
<div id="container"></div>
<div id="info">
CS277 Dynamics Example by Adam Leeper
(clone on <a href="https://github.com/aleeper/tether_ball_simulation/">github</a>)
<br/>
<input type="button" value="Kick!" onclick="controls.kick()"></input>
<input type="button" value="Spin!" onclick="controls.spin()"></input>
<input type="button" value="Reset" onclick="controls.reset()"></input>
</div>
<script src="js/three.min.js"></script>
<script src="js/Detector.js"></script>
<script src="js/stats.min.js"></script>
<script src="js/dat.gui.min.js"></script>
<script>
RigidBody = function () {
this.position = new THREE.Vector3();
this.velocity = new THREE.Vector3();
this.quaternion = new THREE.Quaternion();
this.omega = new THREE.Vector3();
this.invMass = 1;
//this.inertia = new THREE.Matrix3(); // sets to identity by default.
this.Ixx = 1;
this.Iyy = 1;
this.Izz = 1;
this.force = new THREE.Vector3();
this.torque = new THREE.Vector3();
};
RigidBody.prototype = {
constructor: RigidBody,
clearState: function () {
this.position.set(0,0,0);
this.velocity.set(0,0,0);
this.quaternion.set(0,0,0,1);
this.omega.set(0,0,0);
},
setState: function (position, velocity, quaternion, omega) {
this.position.copy(position);
this.velocity.copy(velocity);
this.quaternion.copy(quaternion);
this.omega.copy(omega);
},
setInvMass: function (invMass) {
this.invMass = invMass;
},
setInertia: function (Ixx, Iyy, Izz) {
this.Ixx = Ixx;
this.Iyy = Iyy;
this.Izz = Izz;
},
addGravity: function (g_vector) {
if (this.invMass != 0.0)
this.force.add(g_vector.clone().multiplyScalar(1.0/this.invMass));
},
addForce: function (force) {
this.force.add(force);
},
addTorque: function (torque) {
this.torque.add(torque);
},
clearForceAndTorque: function () {
this.force.set(0,0,0);
this.torque.set(0,0,0);
},
// q must represent a_R_b and omega must be expressed in b
calculateNextQuaternion: function (q, w, delta) {
var e = new THREE.Quaternion();
e.w = q.w + delta * 0.5 * (-q.x* w.x - q.y * w.y - q.z * w.z);
e.x = q.x + delta * 0.5 * ( q.w* w.x - q.z * w.y + q.y * w.z);
e.y = q.y + delta * 0.5 * ( q.z* w.x + q.w * w.y - q.x * w.z);
e.z = q.z + delta * 0.5 * (-q.y* w.x + q.x * w.y + q.w * w.z);
e.normalize();
return e;
},
step: function (delta) {
var prev_pos = this.position.clone();
var prev_vel = this.velocity.clone();
var prev_quaternion = this.quaternion.clone();
var prev_omega = this.omega.clone();
// Get differential equations for velocity
// F = m * a
var accel = this.force.clone().multiplyScalar(this.invMass);
this.velocity = prev_vel.clone().add(accel.clone().multiplyScalar(delta));
this.position = prev_pos.clone().add(prev_vel.clone().multiplyScalar(delta));
// Get differential equations for angular velocity
// M = I . alpha * omega x I . omega
var w_R_b = new THREE.Matrix4();
w_R_b.makeRotationFromQuaternion(this.quaternion);
var b_R_w = w_R_b.clone().transpose();
var b_torque = this.torque.clone().applyMatrix4(b_R_w);
var b_omega = prev_omega.clone().applyMatrix4(b_R_w);
var Ixx = this.Ixx;
var Iyy = this.Iyy;
var Izz = this.Izz;
var b_omegadot = new THREE.Vector3(
((Iyy - Izz) * b_omega.z * b_omega.y + b_torque.x) / Ixx,
((Izz - Ixx) * b_omega.x * b_omega.z + b_torque.y) / Iyy,
((Ixx - Iyy) * b_omega.y * b_omega.x + b_torque.z) / Izz);
var b_omega_next = b_omega.clone().add(b_omegadot.clone().multiplyScalar(delta));
var w_omega_next = b_omega_next.clone().applyMatrix4(w_R_b);
// Simple dynamics
//var w_omegadot = this.torque.clone().multiplyScalar(1.0/this.Ixx);
//var w_omega_next = prev_omega.clone().add(w_omegadot.clone().multiplyScalar(delta));
// Quaternion Update
var b_prev_omega = prev_omega.clone().applyQuaternion(prev_quaternion.clone().conjugate());
var quaternion_next = this.calculateNextQuaternion(prev_quaternion, b_prev_omega, delta);
/// Actually update the rotational members.
this.omega.copy(w_omega_next);
this.quaternion.copy(quaternion_next);
}
};
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container, stats;
var camera, scene, renderer, clock;
var simParams, springParams, airParams, gravityParams, controls;
var mesh, group1, shadow, light;
var spring_arrow, debug_arrow;
var body1;
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
defineControls();
init();
animate();
function init() {
container = document.getElementById( 'container' );
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.set(3,2,8);
scene = new THREE.Scene();
light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 0, 0, 1 );
scene.add( light );
// shadow
var canvas = document.createElement( 'canvas' );
canvas.width = 128;
canvas.height = 128;
var context = canvas.getContext( '2d' );
var gradient = context.createRadialGradient( canvas.width / 2, canvas.height / 2, 0, canvas.width / 2, canvas.height / 2, canvas.width / 2 );
gradient.addColorStop( 0.1, 'rgba(210,210,210,1)' );
gradient.addColorStop( 1, 'rgba(255,255,255,1)' );
context.fillStyle = gradient;
context.fillRect( 0, 0, canvas.width, canvas.height );
var shadowTexture = new THREE.Texture( canvas );
shadowTexture.needsUpdate = true;
var shadowMaterial = new THREE.MeshBasicMaterial( { map: shadowTexture } );
var shadowGeo = new THREE.PlaneGeometry( 3, 3, 1, 1 );
shadow = new THREE.Mesh( shadowGeo, shadowMaterial );
shadow.position.y = - 6;
shadow.rotation.x = - Math.PI / 2;
scene.add( shadow );
var redMaterial = new THREE.MeshBasicMaterial( {color: 0xff0000} );
var greenMaterial = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
var blueMaterial = new THREE.MeshBasicMaterial( {color: 0x0000ff} );
var axisGeometry = new THREE.CylinderGeometry(0.02, 0.02, 10);
var x_axis = new THREE.Mesh( axisGeometry, redMaterial );
x_axis.rotateZ(-Math.PI/2);
scene.add(x_axis);
var y_axis = new THREE.Mesh( axisGeometry, greenMaterial );
scene.add(y_axis);
var z_axis = new THREE.Mesh( axisGeometry, blueMaterial );
z_axis.rotateX(Math.PI/2);
scene.add(z_axis);
spring_arrow = new THREE.ArrowHelper(
new THREE.Vector3(1,0,0), new THREE.Vector3(0,0,0), 2, 0x000000);
scene.add(spring_arrow);
debug_arrow = new THREE.ArrowHelper(
new THREE.Vector3(1,0,0), new THREE.Vector3(0,0,0), 2, 0x00ffff);
scene.add(debug_arrow);
// This is needlessly complicated, but I copied an example :)
var radius = 1;
var geometry = new THREE.IcosahedronGeometry( radius, 1 );
var faceIndices = [ 'a', 'b', 'c', 'd' ];
for ( var i = 0; i < geometry.faces.length; i ++ ) {
var color, f, f2, f3, p, n, vertexIndex;
f = geometry.faces[ i ];
n = ( f instanceof THREE.Face3 ) ? 3 : 4;
for( var j = 0; j < n; j++ ) {
vertexIndex = f[ faceIndices[ j ] ];
p = geometry.vertices[ vertexIndex ];
color = new THREE.Color( 0xffffff );
color.setHSL( ( p.y / radius + 1 ) / 2, 1.0, 0.5 );
f.vertexColors[ j ] = color;
}
}
var materials = [
new THREE.MeshLambertMaterial( { color: 0xffffff, shading: THREE.FlatShading, vertexColors: THREE.VertexColors } ),
new THREE.MeshBasicMaterial( { color: 0x000000, shading: THREE.FlatShading, wireframe: true, transparent: true } )
];
group1 = THREE.SceneUtils.createMultiMaterialObject( geometry, materials );
group1.position.x = 0;
group1.rotation.x = 0;
scene.add( group1 );
// =================================================
// Configure the rigid body
// =================================================
body1 = new RigidBody();
body1.invMass = 1;
body1.setInertia(1,1,1);
controls.reset();
// =================================================
// =================================================
// =================================================
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setClearColor( 0xffffff );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
container.appendChild( stats.domElement );
setupGui();
// Start our integration clock
clock = new THREE.Clock(true);
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
window.addEventListener( 'resize', onWindowResize, false );
}
function setupGui() {
simParams = {
mass: 1,
running: true,
step_size: 0.001
};
gravityParams = {
enabled: true,
gravity: 9.81
};
airParams = {
enabled: true,
b_trans: 0.4,
b_rot: 0.1
};
springParams = {
enabled: true,
is_string: true,
k: 1000.0,
Ln: 3,
b_damper: 20,
b_torsion: 0.5,
show_torque: false
};
var h;
var gui = new dat.GUI();
gui.add( simParams, "running", simParams.running);
gui.add( simParams, "step_size", 0.0001, 0.1, simParams.step_size);
gui.add( simParams, "mass", 0.1, 10, simParams.mass );
h = gui.addFolder("Air Resistance");
h.add( airParams, "enabled", true);
h.add( airParams, "b_trans", 0, 2, airParams.b_trans );
h.add( airParams, "b_rot", 0, 2, airParams.b_rot );
h = gui.addFolder("Gravity");
h.add( gravityParams, "enabled", gravityParams.enabled);
h.add( gravityParams, "gravity", 0, 100, gravityParams.gravity );
h = gui.addFolder( "Spring-Damper" );
h.add( springParams, "enabled", springParams.enabled);
h.add( springParams, "is_string", springParams.is_string);
h.add( springParams, "k", 0, 10000, springParams.k);
h.add( springParams, "Ln", 0, 10, springParams.Ln);
h.add( springParams, "b_damper", 0, 50, springParams.b_damper);
h.add( springParams, "b_torsion", 0, 50, springParams.b_torsion);
h.add( springParams, "show_torque", springParams.show_torque );
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function onDocumentMouseMove( event ) {
mouseX = ( event.clientX - windowHalfX );
mouseY = ( event.clientY - windowHalfY );
}
//
function runDynamics(delta) {
// This is the gravity vector. Needs to be multiplied by mass for any object.
var w_gravity = new THREE.Vector3(0, -gravityParams.gravity, 0);
// For each body...
body1.clearForceAndTorque();
body1.setInvMass(1.0/simParams.mass);
var I_sphere = 0.4*simParams.mass;
body1.setInertia(I_sphere, I_sphere, I_sphere);
// Get the pose of the ball in the world frame.
var w_T_b = new THREE.Matrix4();
w_T_b.makeRotationFromQuaternion(body1.quaternion);
w_T_b.setPosition(body1.position);
// Also useful to have just the orientation of the ball in the world frame.
var w_R_b = w_T_b.clone();
w_R_b.setPosition(new THREE.Vector3(0,0,0));
// ============================================================
// Calculate useful vectors for computing forces below.
// ============================================================
// Explanation of notation:
// w_r_No_P
// w is the frame in which this thing is expressed
// r is "what" this thing is, in this case a position vector
// No_P indicates this position vector points from No to P
// P is the tether connection in the world.
// For simplicity we'll just stick it at the world origin... which I called No.
var w_r_No_P = new THREE.Vector3(0,0,0);
// Q is the tether connection on the ball.
var b_r_Bo_Q = new THREE.Vector3(0, 1, 0);
// Get the same vector expressed in w instead of b.
var w_r_Bo_Q = b_r_Bo_Q.clone().applyMatrix4(w_R_b);
// Also get the position of Q measured from No, expressed in w.
var w_r_No_Q = b_r_Bo_Q.clone().applyMatrix4(w_T_b);
// Get vector from P to Q.
var w_r_P_Q = w_r_No_Q.clone().sub(w_r_No_P);
// Get unit vector from P to Q.
// Note: you need to handle the case when the length is zero (three.js does
// this internally), because dividing by zero is bad. One common approach
// is to simply divide by (magnitude + epsilon).
var w_r_P_Q_hat = w_r_P_Q.clone().normalize();
// ============================================================
// Now we'll start accumulating forces and torques on the body:
// ============================================================
// Gravity is easy!
if (gravityParams.enabled)
{
body1.addGravity(w_gravity);
}
// The spring is harder...
if (springParams.enabled)
{
// Spring force is F_spring_on_Q_from_P = -k*stretch*(unit vector from P to Q)
var stretch = w_r_P_Q.length() - springParams.Ln;
var w_F_spring_Q = w_r_P_Q_hat.clone().multiplyScalar(-springParams.k * stretch);
//printVector3("Force spring: ", w_F_spring_Q);
// Damper force is F_damper_on_Q_from_P = -b*Ldot*(unit vector from P to Q)
// Note that since B is spinning, the velocity of Q in the world frame is
// v_Q = v_Bcm + cross(omega_B , r_Bo_Q)
// Of course, you need to ensure everything is expressed in the same frame before
// you do the math.
var w_v_Bcm = body1.velocity.clone();
var w_omega_B = body1.omega.clone();
var w_v_Q_rel_P = w_v_Bcm.clone().add(w_omega_B.clone().cross(w_r_Bo_Q));
var Ldot = w_v_Q_rel_P.dot(w_r_P_Q_hat);
var w_F_damper_Q = w_r_P_Q_hat.clone().multiplyScalar(-springParams.b_damper * Ldot);
// Total spring-damper force
var w_F_total = w_F_spring_Q.clone().add(w_F_damper_Q);
// Compute the moment (torque) from the spring-damper on B, about Bcm.
var w_M_spring = w_r_Bo_Q.clone().cross(w_F_total);
// Let's add a (totally fake) moment/torque that attempts to discourage
// rotation of the ball around the vector pointing from Bcm to Q.
//var w_M_torsion_damper = w_r_P_Q_hat.multiplyScalar(-body1.omega.dot(w_r_P_Q_hat)*myParams.b_torsion);
var w_r_Bo_Q_hat = w_r_Bo_Q.clone().normalize();
var w_M_torsion_damper = w_r_Bo_Q_hat.clone().multiplyScalar(-body1.omega.dot(w_r_Bo_Q_hat)*springParams.b_torsion);
//var w_omega_B_axial = w_r_P_Q_hat.clone().multiplyScalar(body1.omega.dot(w_r_P_Q_hat));
//var w_omega_B_perp = body1.omega.clone().sub(w_omega_B_axial);
//var w_M_torsion_damper = w_omega_B_perp.clone().multiplyScalar(-springParams.b_torsion);
// Total moment (torque) on B:
var w_M_total = w_M_spring.clone().add(w_M_torsion_damper);
// If we want to model a string instead of a spring, we simply
// disable its ability to "push".
if (springParams.is_string && stretch < 0)
{
w_F_total.set(0,0,0);
w_M_total.set(0,0,0);
}
// Finally actually add the forces to the body.
body1.addForce(w_F_total);
body1.addTorque(w_M_total);
// Optionally a debugging arrow to show torque.
if (springParams.show_torque)
{
var vec = w_M_total;
debug_arrow.position.copy(w_r_No_Q);
debug_arrow.setDirection(vec.clone().normalize());
debug_arrow.setLength(vec.length() + 0.001);
} else {
debug_arrow.setLength(0.001);
}
}
// Air
if (airParams.enabled)
{
// Air resistance is simply modeled as opposing the velocity or
// angular velocity of the body.
// force_air = -b1 * w_v_Bcm
// torque_air = -b2 * w_omega_B
body1.addForce(body1.velocity.clone().multiplyScalar(-airParams.b_trans));
body1.addTorque(body1.omega.clone().multiplyScalar(-airParams.b_rot));
}
// We draw an arrow representing the spring/string:
if (springParams.enabled)
{
spring_arrow.setDirection(w_r_P_Q_hat);
spring_arrow.setLength(w_r_P_Q.length());
} else {
spring_arrow.setLength(0.001);
}
// Run the time integration!!
body1.step(delta);
}
function defineControls() {
controls = {
reset: function()
{
body1.clearState();
body1.position.set(0,-1,0);
body1.velocity.set(0,0,0);
body1.omega.set(0,0,0);
},
zeroVel: function () {
body1.velocity.set(0,0,0);
body1.omega.set(0,0,0);
},
kick: function() {
var velocity = new THREE.Vector3(
Math.random() - 0.5,
3 * Math.random(),
Math.random() - 0.5);
velocity.multiplyScalar(5);
body1.velocity.add(velocity);
},
spin: function() {
var omega = new THREE.Vector3(
4 * (Math.random() - 0.5),
2 * (Math.random() - 0.5),
4 * (Math.random() - 0.5));
//var omega = new THREE.Vector3(0, 2*Math.random(), 0);
omega.multiplyScalar(10);
body1.omega.add(omega);
}
};
}
function printVector3( text, v ) {
console.log(text + v.x + ", " + v.y + ", " + v.z);
}
function animate() {
requestAnimationFrame( animate );
var delta = clock.getDelta();
var elapsed = clock.getElapsedTime();
if (simParams.running === true)
{
// We want to take small steps rather than just taking one giant step
// indicated by the graphics update frame time.
var t = 0
while (t < delta)
{
t = t + simParams.step_size;
runDynamics(simParams.step_size);
}
}
// Now actually update the drawable object position
group1.position.copy(body1.position);
group1.setRotationFromQuaternion(body1.quaternion);
shadow.position.setX(body1.position.x);
shadow.position.setZ(body1.position.z);
render();
stats.update();
}
function render() {
// camera.position.x += ( mouseX - camera.position.x * 500 + 2000 ) * 0.0005;
// camera.position.y += ( - mouseY - camera.position.y * 500 + 800 ) * 0.0005;
//camera.lookAt( scene.position );
camera.lookAt( new THREE.Vector3(0, -2, 0) );
renderer.render( scene, camera );
}
</script>
</body>
</html>