-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathpbd.html
More file actions
615 lines (535 loc) · 22.7 KB
/
Copy pathpbd.html
File metadata and controls
615 lines (535 loc) · 22.7 KB
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
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://interactivecomputergraphics.github.io/physics-simulation/examples/style.css">
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX", "output/HTML-CSS"],
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
processEscapes: true
},
"HTML-CSS": { fonts: ["TeX"] }
});
</script>
<script type="text/javascript" async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js"></script>
<title>Position-Based Dynamics</title>
</head>
<body>
<header class="page-header">
<h1>Position-Based Dynamics</h1>
</header>
<main>
<!-- Simulation panel: canvas + controls -->
<table style="align_center;border-radius: 20px;padding: 20px;margin:auto">
<col width="75%">
<col width="25%">
<tr>
<td>
<div class="card sim-panel">
<div class="sim-canvas-wrap">
<canvas id="simCanvas" width="1024" height="960" style="border:2px solid #000000;border-radius: 20px;background-color:#EEEEEE">Your browser does not support the HTML5 canvas tag.</canvas>
</div>
</div>
</td>
<td>
<div class="controls-panel">
<h3>Controls</h3>
<div class="controls-grid">
<label>Current time</label>
<span class="stat-value"><span id="time">0.00</span> s</span>
<label>Time per sim. step</label>
<span class="stat-value"><span id="timePerStep">0.00</span> ms</span>
<label># particles</label>
<span class="stat-value"><span id="numParticles">0</span></span>
<label># constraints</label>
<span class="stat-value"><span id="numConstraints">0</span></span>
<label for="widthInput">Width</label>
<input onchange="gui.restart()" id="widthInput" type="number" value="40" step="1">
<label for="heightInput">Height</label>
<input onchange="gui.restart()" id="heightInput" type="number" value="30" step="1">
<label for="fixedParticlesInput"># fixed particles</label>
<select onchange="gui.restart()" id="fixedParticlesInput">
<option value="1">1</option>
<option value="2" selected="selected">2</option>
<option value="4">4</option>
</select>
<label for="timeStepSizeInput">Time step size</label>
<input onchange="gui.sim.timeStepSize=parseFloat(value)" id="timeStepSizeInput" type="number" value="0.005" step="0.001">
<label for="iterationsInput">Iterations</label>
<input onchange="gui.sim.numIterations=parseInt(value)" id="iterationsInput" type="number" value="2" step="1">
<label for="gravityInput">Gravity</label>
<input onchange="gui.sim.gravity=parseFloat(value)" id="gravityInput" type="number" value="-9.81" step="0.01">
<label for="massInput">Mass</label>
<input onchange="gui.sim.mass=parseFloat(value)" id="massInput" type="number" value="0.5" step="0.01">
<div class="full-width">
<button onclick="gui.restart()" id="restart">▶ Restart</button>
</div>
<div class="full-width">
<button onclick="gui.doPause()" id="Pause" class="btn-secondary">▮▮ Pause</button>
</div>
</div>
</div>
</td>
</tr>
</table>
<!-- Theory section -->
<div class="card theory">
<h2>PBD algorithm:</h2>
Instead of computing forces and integrating accelerations, as in classical force-based simulation, <b>position-based dynamics (PBD)</b> [MHHR06,BMM17] formulates physical relationships as geometric <b>constraints</b> and enforces them by directly displacing particle positions. This example simulates a piece of cloth: a regular grid of particles connected by distance constraints and hanging under gravity from one or more fixed corners. You can grab and drag any of the free particles with the mouse.
<p>Every time step the following steps are performed:</p>
<ol>
<li>time integration to predict particle positions</li>
<li class="nostyle"><b>loop</b></li>
<li style="margin-left:40px">compute Lagrange multipliers</li>
<li style="margin-left:40px">determine position correction</li>
<li>update velocities</li>
</ol>
In this example we use distance constraints
$$C_i(\mathbf{x}_{i_1}, \mathbf{x}_{i_2}) = \| \mathbf x_{i_1} -\mathbf x_{i_2} \|-d,$$
where $d$ is the rest length between particles $\mathbf{x}_{i_1}$ and $\mathbf{x}_{i_2}$; a constraint is satisfied once $C_i = 0$. Besides the horizontal and vertical structural constraints along the grid, diagonal constraints are added within each grid cell to resist shearing and keep the cloth from collapsing sideways.
<h3>1. Time integration</h3>
In the first step the particle positions are advected using a symplectic Euler method to obtain predicted positions $\mathbf x^*$:
$$\begin{align*}
\mathbf v^* &= \mathbf v(t) + \Delta t \mathbf a_\text{ext}(t) \\
\mathbf x^* &= \mathbf x(t) + \Delta t \mathbf v^*,
\end{align*}$$
where $\mathbf a_\text{ext}$ are accelerations due to external forces (here: gravity). Note that this prediction ignores the distance constraints entirely, so $\mathbf x^*$ will generally violate them — correcting this is exactly the job of the solver loop below.
<h3>2. Solver loop</h3>
The position corrections of all constraints are computed and applied one after another in a single sweep, and this sweep is repeated for a fixed number of iterations (Gauss-Seidel-style relaxation). Because each correction immediately updates the positions seen by the next constraint in the sweep, more iterations propagate the corrections further through the cloth and bring the particles closer to satisfying <em>all</em> constraints simultaneously. Unlike a spring stiffness constant in a force-based model, here it is the <b>number of iterations</b> (relative to the time step) that determines how stretchy or stiff the cloth appears — try reducing it in the controls panel and observe the effect.
<h3>3. Compute Lagrange multipliers</h3>
<p>The general form to compute the Lagrange multipliers in position-based dynamics is
$$\mathbf J \mathbf M^{-1} \mathbf J^T \boldsymbol \lambda = -\mathbf C(\mathbf p),$$
where $\mathbf J = (\partial C / \partial \mathbf x)^T$ is the Jacobian of the constraint function and $\mathbf M$ denotes the mass matrix.</p>
<p>Since the distance constraint is a scalar function the Lagrange multiplier is determined as
$$\lambda_i = - \frac{C_i(\mathbf x)}{\sum_j \frac{1}{m_j} \| \partial C_i(\mathbf x) / \partial \mathbf x_j\|^2},$$
where $j$ denotes the indices of the particles which are influenced by the constraint. Fixed particles are excluded from this sum (their inverse mass is treated as zero), which is why they do not move under the correction below.
</p>
<p>To compute the Lagrange multipliers, the constraint gradients are required which are computed as: </p>
<h4>Constraint gradients:</h4>
$$\begin{align*}
\frac{\partial C_i}{\partial \mathbf x_{i_1}} &= \frac{\mathbf x_{i_1} -\mathbf x_{i_2}}{\| \mathbf x_{i_1} -\mathbf x_{i_2} \|} \\
\frac{\partial C_i}{\partial \mathbf x_{i_2}} &= - \frac{\mathbf x_{i_1} -\mathbf x_{i_2}}{\| \mathbf x_{i_1} -\mathbf x_{i_2} \|}
\end{align*}$$
<h3>4. Position correction:</h3>
The position correction for a particle is determined using the Lagrange multiplier:
$$\begin{align*}
\Delta \mathbf x_{i_1} &= \frac{1}{m_{i_1}} \frac{\partial C_i}{\partial \mathbf x_{i_1}} \lambda_i = -\frac{\frac{1}{m_{i_1}}}{\frac{1}{m_{i_1}} + \frac{1}{m_{i_2}}}(\|\mathbf{x}_{i_1} - \mathbf{x}_{i_2}\|-d)\frac{\mathbf{x}_{i_1}- \mathbf{x}_{i_2}}{\|\mathbf{x}_{i_1} - \mathbf{x}_{i_2}\|} \\
\Delta \mathbf x_{i_2} &= \frac{1}{m_{i_2}} \frac{\partial C_i}{\partial \mathbf x_{i_2}} \lambda_i = +\frac{\frac{1}{m_{i_1}}}{\frac{1}{m_{i_1}} + \frac{1}{m_{i_2}}}(\|\mathbf{x}_{i_1} - \mathbf{x}_{i_2}\|-d)\frac{\mathbf{x}_{i_1}- \mathbf{x}_{i_2}}{\|\mathbf{x}_{i_1} - \mathbf{x}_{i_2}\|}
\end{align*}$$
and the correction is applied to update $\mathbf x^*$ as
$$\mathbf x^* := \mathbf x^* + \Delta \mathbf x.$$
Note that heavier particles (larger mass $m$) receive a proportionally smaller correction — this is what makes the constraint respect the mass ratio between the two particles instead of always splitting the correction evenly.
<h3>5. Velocity update:</h3>
The final positions and velocities are computed as:
$$\begin{align*}
\mathbf x_i(t+\Delta t) &= \mathbf x_i^* \\
\mathbf v_i(t+\Delta t) &= \frac{1}{\Delta t} (\mathbf x_i(t+\Delta t) - \mathbf x_i(t))
\end{align*}
$$
Rather than integrating forces, the velocity is simply reconstructed from how far the position moved during the step. This automatically accounts for all constraint corrections as if they had been caused by impulses, and it introduces a mild, built-in numerical damping (energy is removed whenever a correction shortens a particle's displacement) that contributes to the method's robustness.
<h3>Properties</h3>
<ul>
<li><b>Stable:</b> since a solver iteration always projects positions towards the constraint manifold rather than integrating a (possibly stiff) restoring force, PBD cannot blow up numerically even for large time steps or arbitrarily "stiff" constraints — unlike an explicit force-based spring model, which requires a very small time step to remain stable for stiff springs.</li>
<li><b>No physical stiffness parameter:</b> constraints are treated as hard constraints; the perceived stiffness of the cloth is governed by the number of solver iterations relative to the time step, not by a spring constant. Many iterations converge towards an inextensible cloth, while few iterations yield a visibly softer, more elastic look.</li>
<li><b>Simple and fast:</b> each iteration only evaluates constraint functions and their gradients directly on the positions; no force assembly or (potentially large, implicit) linear system needs to be built and solved. This simplicity is a key reason why PBD (and its successor, XPBD) is widely used for cloth, hair, and soft bodies in real-time applications such as games.</li>
<li><b>Approximate and iteration-dependent:</b> with only a fixed, small number of Gauss-Seidel sweeps, constraints are in general not fully satisfied. Corrections propagate only one constraint "hop" per iteration, so particles far away from a fixed point need more iterations before they feel its influence — increase the grid size in the controls and watch how much longer the cloth needs to settle.</li>
</ul>
The panel on the right also reports the measured time per simulation step, which grows with the number of particles, constraints and iterations — try increasing the grid resolution or the iteration count to see this trade-off between accuracy and performance directly.
<h3>References</h3>
<ul>
<li>[MHHR06] Matthias Müller, Bruno Heidelberger, Marcus Hennix, John Ratcliff. Position Based Dynamics. In Proceedings of Virtual Realitiy, Interactions, and Physical Simulation, 2006. Eurographics Association.</li>
<li>[BMM17] Jan Bender, Matthias Müller, Miles Macklin. A Survey on Position Based Dynamics, 2017. Eurographics Tutorials, 2017</li>
</ul>
</div>
</main>
<script id="simulation_code" type="text/javascript">
class Particle
{
constructor (x, y)
{
this.x = x
this.y = y
this.xOld = x
this.yOld = y
this.vx = 0
this.vy = 0
}
}
class Constraint
{
constructor (index1, index2, restLength)
{
this.index1 = index1
this.index2 = index2
this.length = restLength
}
}
class Simulation
{
constructor(width, height, fixed)
{
this.constraints = [];
this.particles = [];
this.width = width;
this.height = height;
this.numIterations = 2;
this.mass = 0.5;
this.gravity = -9.81;
this.timeStepSize = 0.05;
this.time = 0;
this.numFixedParticles = fixed;
this.init();
}
init()
{
// create particles
let i;
let j;
let w = this.width;
let h = this.height;
let s = 0.1;
for (i = 0; i < h; i++)
for (j = 0; j < w; j++)
this.particles.push(new Particle(s*2*j, -s*2*i))
// create horizontal constraints
for (i = 0; i < h; i++)
for (j = 0; j < w - 1; j++)
this.constraints.push(new Constraint(i*w + j, i*w + j + 1, s*2.0));
// create vertical constraints
for (i = 0; i < h-1; i++)
for (j = 0; j < w; j++)
this.constraints.push(new Constraint(i*w + j, i*w + j + w, s*2.0));
// create diagonal constraints
for (i = 0; i < h-1; i++)
{
for (j = 0; j < w-1; j++)
{
this.constraints.push(new Constraint(i*w + j, i*w + j + w + 1, s*Math.sqrt(8)));
this.constraints.push(new Constraint(i*w + j +1, i*w + j + w, s*Math.sqrt(8)));
}
}
}
isActive(i)
{
// particle 0 and the selected particle are fixed
if (this.numFixedParticles == 1)
return (i != 0) && (i != gui.selectedParticle);
else if (this.numFixedParticles == 2)
return (i != 0) && (i != this.width-1) && (i != gui.selectedParticle);
else
return (i != 0) && (i != this.width-1) && (i != (this.height-1)*this.width) && (i != this.height*this.width-1) && (i != gui.selectedParticle);
}
// simulation step
simulationStep()
{
let dt = this.timeStepSize;
// compute preview using symplectic Euler
for (let i = 0; i < this.particles.length; i++)
{
if (this.isActive(i))
{
let p = this.particles[i];
// store old position for velocity update after the position correction
p.xOld = p.x;
p.yOld = p.y;
// integrate velocity considering gravitational acceleration
p.vy = p.vy + dt * this.gravity
// integrate position
p.x = p.x + dt * p.vx;
p.y = p.y + dt * p.vy;
}
}
// constraint handling
for (let iter = 0; iter < this.numIterations; iter++)
{
for (let i = 0; i < this.constraints.length; i++)
{
let index1 = this.constraints[i].index1;
let index2 = this.constraints[i].index2;
let p1 = this.particles[index1];
let p2 = this.particles[index2];
// compute length of constraint
let dx = p1.x - p2.x;
let dy = p1.y - p2.y;
let dl = Math.sqrt(dx*dx + dy*dy)
// compute displacement: C = ||x1-x2|| - restLength
let C = dl - this.constraints[i].length;
// determine gradient
let gradC_x = 0.0;
let gradC_y = 0.0;
if (dl > 0.001)
{
gradC_x = dx/dl;
gradC_y = dy/dl;
let K = (gradC_x*gradC_x + gradC_y*gradC_y) / this.mass;
if ((this.isActive(index1) && this.isActive(index2)))
K = 2*K;
// comute Lagrange multiplier
let lambda = -C / K;
// determine position correction
if (this.isActive(index1))
{
p1.x = p1.x + 1.0/this.mass*lambda * gradC_x;
p1.y = p1.y + 1.0/this.mass*lambda * gradC_y;
}
if (this.isActive(index2))
{
p2.x = p2.x - 1.0/this.mass*lambda * gradC_x;
p2.y = p2.y - 1.0/this.mass*lambda * gradC_y;
}
}
}
}
// update velocities
for (let i = 0; i < this.particles.length; i++)
{
if (this.isActive(i))
{
let p = this.particles[i];
p.vx = 1.0/dt * (p.x - p.xOld);
p.vy = 1.0/dt * (p.y - p.yOld);
}
}
// update simulation time
this.time = this.time + dt;
}
}
class GUI
{
constructor()
{
this.canvas = document.getElementById("simCanvas");
this.c = this.canvas.getContext("2d");
this.requestID = -1;
this.timeSum = 0.0;
this.counter = 0;
this.pause = false;
this.origin = { x : this.canvas.width / 2, y : this.canvas.height/2-200};
this.zoom = 50;
this.particleRadius = 0.025;
this.selectedParticle = -1;
// register mouse event listeners (zoom/selection)
this.canvas.addEventListener("mousedown", this.mouseDown.bind(this), false);
this.canvas.addEventListener("mousemove", this.mouseMove.bind(this), false);
this.canvas.addEventListener("mouseup", this.mouseUp.bind(this), false);
this.canvas.addEventListener("wheel", this.wheel.bind(this), false);
// register touch event listeners (mobile / tablet)
// passive:false is required so we can call preventDefault() to suppress scrolling
this.canvas.addEventListener("touchstart", this.touchStart.bind(this), { passive: false });
this.canvas.addEventListener("touchmove", this.touchMove.bind(this), { passive: false });
this.canvas.addEventListener("touchend", this.touchEnd.bind(this), { passive: false });
}
// set simulation parameters from GUI and start mainLoop
restart()
{
window.cancelAnimationFrame(this.requestID);
let w = parseInt(document.getElementById('widthInput').value);
let h = parseInt(document.getElementById('heightInput').value);
let f = parseInt(document.getElementById('fixedParticlesInput').value);
delete this.sim;
this.sim = new Simulation(w, h, f);
this.timeSum = 0.0;
this.counter = 0;
this.sim.numIterations = parseInt(document.getElementById('iterationsInput').value);
this.sim.gravity = parseFloat(document.getElementById('gravityInput').value);
this.sim.timeStepSize = parseFloat(document.getElementById('timeStepSizeInput').value);
this.sim.mass = parseFloat(document.getElementById('massInput').value);
document.getElementById("numParticles").innerHTML = this.sim.particles.length;
document.getElementById("numConstraints").innerHTML = this.sim.constraints.length;
this.mainLoop();
}
drawCoordinateSystem()
{
// draw x-axis
this.c.strokeStyle = "#FF0000";
this.c.beginPath();
this.c.moveTo(this.origin.x, this.origin.y);
this.c.lineTo(this.origin.x+1*this.zoom, this.origin.y);
this.c.stroke();
// draw y-axis
this.c.strokeStyle = "#00FF00";
this.c.beginPath();
this.c.moveTo(this.origin.x, this.origin.y);
this.c.lineTo(this.origin.x, this.origin.y-1*this.zoom);
this.c.stroke();
}
draw()
{
this.c.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.drawCoordinateSystem();
// draw constraints as lines
this.c.strokeStyle = "#666666";
for (let i = 0; i < this.sim.constraints.length; i++)
{
let index1 = this.sim.constraints[i].index1;
let index2 = this.sim.constraints[i].index2;
let p1 = this.sim.particles[index1];
let p2 = this.sim.particles[index2];
this.c.beginPath();
this.c.moveTo(this.origin.x + p1.x*this.zoom, this.origin.y - p1.y*this.zoom);
this.c.lineTo(this.origin.x + p2.x*this.zoom, this.origin.y - p2.y*this.zoom);
this.c.stroke();
}
// draw particles as circles
for (let i = 0; i < this.sim.particles.length; i++)
{
let p = this.sim.particles[i];
let r = this.particleRadius;
if (i == this.selectedParticle)
{
// draw selected particle in red with larger radius
this.c.fillStyle = "#FF0000";
r = 3*r;
}
else
this.c.fillStyle = "#0000FF";
let px = this.origin.x + p.x * this.zoom;
let py = this.origin.y - p.y * this.zoom;
this.c.beginPath();
this.c.arc(px, py, r * this.zoom, 0, Math.PI*2, true);
this.c.closePath();
this.c.fill();
}
}
mainLoop()
{
// perform multiple sim steps per render step
for (let i=0; i < 8; i++)
{
let t0 = performance.now();
this.sim.simulationStep();
let t1 = performance.now();
this.timeSum += t1 - t0;
this.counter += 1;
if (this.counter % 50 == 0)
{
this.timeSum /= this.counter;
document.getElementById("timePerStep").innerHTML = this.timeSum.toFixed(2);
this.timeSum = 0.0;
this.counter = 0;
}
document.getElementById("time").innerHTML = this.sim.time.toFixed(2);
}
this.draw();
if (!this.pause)
this.requestID = window.requestAnimationFrame(this.mainLoop.bind(this));
}
doPause()
{
this.pause = !this.pause;
if (!this.pause)
this.mainLoop();
}
mouseDown(event)
{
// left mouse button down
if (event.which == 1)
{
let mousePos = this.getMousePos(this.canvas, event);
for (let i = 0; i < this.sim.particles.length; i++)
{
let p = this.sim.particles[i];
let px = this.origin.x + p.x * this.zoom;
let py = this.origin.y - p.y * this.zoom;
let dx = px - mousePos.x
let dy = py - mousePos.y
let dist2 = Math.sqrt(dx * dx + dy * dy)
if (dist2 < 10)
{
this.selectedParticle = i;
break;
}
}
}
}
getMousePos(canvas, event)
{
const rect = canvas.getBoundingClientRect();
const scaleX = canvas.width / rect.width; // buffer / displayed size
const scaleY = canvas.height / rect.height;
return {
x: (event.clientX - rect.left) * scaleX,
y: (event.clientY - rect.top) * scaleY
};
}
mouseMove(event)
{
if (this.selectedParticle != -1)
{
let mousePos = this.getMousePos(this.canvas, event);
this.sim.particles[this.selectedParticle].x = (mousePos.x - this.origin.x) / this.zoom;
this.sim.particles[this.selectedParticle].y = -(mousePos.y - this.origin.y) / this.zoom;
}
}
mouseUp(event)
{
this.selectedParticle = -1;
}
wheel(event)
{
event.preventDefault();
this.zoom += event.deltaY * -0.05;
if (this.zoom < 1)
this.zoom = 1;
}
// Convert the first touch point to a plain {clientX, clientY} object
// so it can be passed directly to the existing mouse handlers.
getTouchClient(event)
{
const t = event.touches.length > 0 ? event.touches[0] : event.changedTouches[0];
return { clientX: t.clientX, clientY: t.clientY };
}
touchStart(event)
{
event.preventDefault();
if (event.touches.length === 1)
this.mouseDown({ which: 1, ...this.getTouchClient(event) });
else if (event.touches.length === 2)
this.lastPinchDist = this.getPinchDist(event);
}
touchMove(event)
{
event.preventDefault();
if (event.touches.length === 1)
{
this.lastPinchDist = null;
this.mouseMove(this.getTouchClient(event));
}
else if (event.touches.length === 2)
{
// deselect any dragged particle while pinching
this.selectedParticle = -1;
const dist = this.getPinchDist(event);
if (this.lastPinchDist !== null)
{
this.zoom += (dist - this.lastPinchDist) * 0.3;
if (this.zoom < 1) this.zoom = 1;
}
this.lastPinchDist = dist;
}
}
touchEnd(event)
{
event.preventDefault();
if (event.touches.length < 2)
this.lastPinchDist = null;
if (event.touches.length === 0)
this.mouseUp(event);
}
getPinchDist(event)
{
const dx = event.touches[0].clientX - event.touches[1].clientX;
const dy = event.touches[0].clientY - event.touches[1].clientY;
return Math.sqrt(dx*dx + dy*dy);
}
}
gui = new GUI();
gui.restart();
</script>
</body>
</html>