Repository navigation
Expand file tree
/
Copy pathpolar_decomposition.html
More file actions
743 lines (671 loc) · 33.6 KB
/
Copy pathpolar_decomposition.html
File metadata and controls
743 lines (671 loc) · 33.6 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
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
<!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>Polar Decomposition</title>
</head>
<body>
<header class="page-header">
<h1>Polar Decomposition</h1>
</header>
<main>
<!-- Simulation panel: canvas + controls -->
<table style="align_center;border-radius: 20px;padding: 20px;margin:auto">
<col width="70%">
<col width="30%">
<tr>
<td>
<div class="card sim-panel">
<div class="sim-canvas-wrap">
<canvas id="simCanvas" width="1024" height="700" style="border:2px solid #000000;border-radius: 20px;background-color:#FFFFFF">Your browser does not support the HTML5 canvas tag.</canvas>
</div>
<p class="canvas-hint">
Drag the red and green handles to change the columns of the deformation gradient $\mathbf F$ (the handles are the images of the edge midpoints $(L, 0)^T$ and $(0, L)^T$).
Drag the body to rotate it, i.e. to multiply $\mathbf F$ by a rotation from the left: $\mathbf R$ changes, $\mathbf S$ stays the same.
Zoom with the mouse wheel, drag on an empty area to pan, double-click to reset the view.
"Play" animates the decomposition: first the stretch $\mathbf S$, then the rotation $\mathbf R$.
</p>
<div class="sim-canvas-wrap" style="margin-top:6px">
<canvas id="stepsCanvas" width="1024" height="435" style="border:2px solid #000000;border-radius: 20px;background-color:#FFFFFF"></canvas>
</div>
<p class="canvas-hint">
<b>Two ways to read the same decomposition.</b> Top: $\mathbf F = \mathbf R\,\mathbf S$ first stretches the body along the principal directions $\mathbf v_1, \mathbf v_2$ of the rest shape, then rotates it.
Bottom: $\mathbf F = \hat{\mathbf S}\,\mathbf R$ first rotates, then stretches along the rotated directions $\mathbf u_i = \mathbf R\,\mathbf v_i$. Both rows end with the same shape $\mathbf F\mathbf X$.
</p>
</div>
</td>
<td>
<div class="controls-panel">
<h3>Controls</h3>
<div class="controls-grid">
<label>det F</label>
<span class="stat-value"><span id="detF">-</span></span>
<label>R</label>
<span class="stat-value"><span id="rotInfo">-</span></span>
<label>Stretches σ₁, σ₂</label>
<span class="stat-value"><span id="stretchInfo">-</span></span>
<label for="presetInput">Preset</label>
<select onchange="gui.setPreset(this.value)" id="presetInput">
<option value="stretchrot" selected="selected">Stretch + rotation</option>
<option value="identity">Identity</option>
<option value="stretch">Uniaxial stretch</option>
<option value="rotation">Pure rotation</option>
<option value="shear">Simple shear</option>
</select>
<label for="F00">F₁₁</label>
<input onchange="gui.readInputs()" id="F00" type="number" step="0.05">
<label for="F01">F₁₂</label>
<input onchange="gui.readInputs()" id="F01" type="number" step="0.05">
<label for="F10">F₂₁</label>
<input onchange="gui.readInputs()" id="F10" type="number" step="0.05">
<label for="F11">F₂₂</label>
<input onchange="gui.readInputs()" id="F11" type="number" step="0.05">
<label for="orderInput">Animation order</label>
<select id="orderInput">
<option value="RS" selected="selected">F = R S (stretch first)</option>
<option value="SR">F = Ŝ R (rotate first)</option>
</select>
<div class="full-width">
<button onclick="gui.togglePlay()" id="playButton">▶ Play</button>
</div>
<label for="tInput">Animation t</label>
<input oninput="gui.setT(parseFloat(this.value))" id="tInput" type="range" min="0" max="2" step="0.01" value="2">
<label for="restInput">Rest shape</label>
<input onchange="gui.show.rest = this.checked" id="restInput" type="checkbox" checked>
<label for="axesInput">Principal axes</label>
<input onchange="gui.show.axes = this.checked" id="axesInput" type="checkbox" checked>
<label for="frameInput">Rotation frame R</label>
<input onchange="gui.show.frame = this.checked" id="frameInput" type="checkbox" checked>
<label for="interInput">Intermediate shape</label>
<input onchange="gui.show.inter = this.checked" id="interInput" type="checkbox">
</div>
</div>
</td>
</tr>
</table>
<!-- Theory section -->
<div class="card theory">
<h2>Polar decomposition: rotation and stretch</h2>
<p>
Every square matrix $\mathbf F$, e.g. the deformation gradient of a deformable body, can be split into a rotation and a stretch:
$$\mathbf F = \mathbf R\,\mathbf S, \qquad \mathbf S = \sqrt{\mathbf F^T\mathbf F}, \qquad \mathbf R = \mathbf F\,\mathbf S^{-1},$$
where $\mathbf S$ is symmetric positive definite and $\mathbf R$ is orthogonal ($\mathbf R^T\mathbf R = \mathbf I$). If $\mathbf F$ is invertible, both factors are unique, and for $\det\mathbf F > 0$, $\mathbf R$ is a rotation (for $\det\mathbf F < 0$ it contains a reflection). In the example, the rest shape $\mathbf X$ is a square with side length $2L = 0.24\,\text{m}$ and an inscribed circle, and the transformed shape is $\mathbf F\mathbf X$.
</p>
<h3>Geometric meaning</h3>
<p>
The symmetric matrix $\mathbf S$ has orthonormal eigenvectors $\mathbf v_1, \mathbf v_2$ (<b>principal directions</b>) and eigenvalues $\sigma_1 \ge \sigma_2 > 0$ (<b>principal stretches</b>):
$$\mathbf S = \sigma_1\, \mathbf v_1 \mathbf v_1^T + \sigma_2\, \mathbf v_2 \mathbf v_2^T.$$
So $\mathbf F = \mathbf R\,\mathbf S$ means: first stretch the body by $\sigma_i$ along the orthogonal directions $\mathbf v_i$, then rotate it rigidly by $\mathbf R$. The circle becomes an ellipse with the semi-axes $\sigma_i L$ in the directions $\mathbf u_i = \mathbf R\,\mathbf v_i$. The directions $\mathbf v_i$ are in general not the coordinate axes: a simple shear contains no explicit rotation, but its $\mathbf R$ is not the identity.
</p>
<p>
If the transformed body is rotated by $\mathbf Q$ (drag the body), only the rotation part changes: $\mathbf Q\mathbf F = (\mathbf Q\mathbf R)\,\mathbf S$. Therefore, $\mathbf S$ measures the actual deformation, independent of the orientation.
</p>
<p>
<b>Left decomposition.</b> The rotation can also be applied first: $\mathbf F = \hat{\mathbf S}\,\mathbf R$ with the same $\mathbf R$ and $\hat{\mathbf S} = \mathbf R\,\mathbf S\,\mathbf R^T = \sqrt{\mathbf F\mathbf F^T}$, which stretches by the same factors $\sigma_i$ along the rotated directions $\mathbf u_i$ (bottom row of the second panel).
</p>
<p>
<b>Relation to the SVD.</b> With $\mathbf F = \mathbf U\,\boldsymbol\Sigma\,\mathbf V^T$, we get $\mathbf R = \mathbf U\mathbf V^T$, $\mathbf S = \mathbf V\boldsymbol\Sigma\mathbf V^T$ and $\hat{\mathbf S} = \mathbf U\boldsymbol\Sigma\mathbf U^T$: the principal stretches are the singular values, and $\mathbf v_i$, $\mathbf u_i$ are the right and left singular vectors. In 3D, the polar decomposition is usually computed in this way; in 2D, $\mathbf R$ is simply the rotation by $\theta = \mathrm{atan2}(F_{21} - F_{12},\; F_{11} + F_{22})$, and $\mathbf S = \mathbf R^T\mathbf F$.
</p>
</div>
</main>
<script id="simulation_code" type="text/javascript">
// =====================================================================================
// Overview
// --------
// 1. 2x2 matrix helpers, polar decomposition F = R S (closed form in 2D), interpolation
// of the two steps (stretch, rotation) for the animation.
// 2. Drawing of the body (square with grid, inscribed circle, marked corner cell, axes).
// 3. GUI: main view (edit F by dragging), the two decompositions R S and Ŝ R side by
// side.
//
// Units: positions in meters, x right, y UP (math convention, so that positive angles
// are counterclockwise). F, R, S are dimensionless. Matrices are arrays [[a, b], [c, d]]
// (row-major), points are objects { x, y }. The view maps meters to pixels
// (VIEW.scale pixels per meter); it can be zoomed (mouse wheel) and panned.
// =====================================================================================
const L = 0.12; // half side length of the rest square [m] (= radius of the circle)
const TOP = 86; // height of the header in the main canvas [px]
const VIEW_DEFAULT = { x0: 355, y0: 398, scale: 1150 }; // canvas position of the world origin [px] and pixels per meter
let VIEW = { ...VIEW_DEFAULT };
// world (m) <-> canvas (px), the y axis is flipped
function toScreen(p) { return { x: VIEW.x0 + p.x * VIEW.scale, y: VIEW.y0 - p.y * VIEW.scale }; }
function toWorldPos(s) { return { x: (s.x - VIEW.x0) / VIEW.scale, y: (VIEW.y0 - s.y) / VIEW.scale }; }
const COL = {
e1: "#dc2626", e2: "#16a34a", // columns of F (handles)
r1: "#7f1d1d", r2: "#14532d", // columns of R
v1: "#9333ea", v2: "#0d9488", // principal directions
body: "#1d4ed8", bodyFill: "rgba(37,99,235,0.13)", marker: "rgba(249,115,22,0.55)",
rest: "#94a3b8", text: "#111827", text2: "#374151", active: "#eab308"
};
// =====================================================================================
// 1. Matrices and polar decomposition
// =====================================================================================
const I2 = [[1, 0], [0, 1]];
function mul(A, B) { return [[A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1]],
[A[1][0] * B[0][0] + A[1][1] * B[1][0], A[1][0] * B[0][1] + A[1][1] * B[1][1]]]; }
function transpose(A) { return [[A[0][0], A[1][0]], [A[0][1], A[1][1]]]; }
function det(A) { return A[0][0] * A[1][1] - A[0][1] * A[1][0]; }
function apply(M, p) { return { x: M[0][0] * p.x + M[0][1] * p.y, y: M[1][0] * p.x + M[1][1] * p.y }; }
function rot(a) { let c = Math.cos(a), s = Math.sin(a); return [[c, -s], [s, c]]; }
function lerpM(A, B, t) { return A.map((row, i) => row.map((x, j) => x + (B[i][j] - x) * t)); }
function symmetrize(A) { let o = 0.5 * (A[0][1] + A[1][0]); return [[A[0][0], o], [o, A[1][1]]]; }
function frob2(A) { return A[0][0] ** 2 + A[0][1] ** 2 + A[1][0] ** 2 + A[1][1] ** 2; }
function sub(A, B) { return A.map((row, i) => row.map((x, j) => x - B[i][j])); }
function wrapAngle(a) { while (a > Math.PI) a -= 2 * Math.PI; while (a <= -Math.PI) a += 2 * Math.PI; return a; }
function deg(a) { let v = a * 180 / Math.PI; return (Math.abs(v) < 0.05 ? 0 : v).toFixed(1) + "°"; }
function smooth(t) { return t * t * (3 - 2 * t); }
function clamp01(t) { return Math.min(1, Math.max(0, t)); }
// eigendecomposition of a symmetric 2x2 matrix: S = l1 v1 v1^T + l2 v2 v2^T with l1 >= l2
function symEig(S)
{
let p = S[0][0], q = S[0][1], r = S[1][1];
let m = 0.5 * (p + r), rad = Math.hypot(0.5 * (p - r), q), psi = 0.5 * Math.atan2(2 * q, p - r);
return { l1: m + rad, l2: m - rad, v1: { x: Math.cos(psi), y: Math.sin(psi) }, v2: { x: -Math.sin(psi), y: Math.cos(psi) } };
}
// 2D polar decomposition F = R S.
// R is the orthogonal matrix that maximizes tr(R^T F) (= closest to F in the Frobenius norm):
// - rotation R(theta): tr = (F11 + F22) cos(theta) + (F21 - F12) sin(theta) -> theta = atan2(F21 - F12, F11 + F22)
// - reflection [[cos phi, sin phi], [sin phi, -cos phi]] (mirror at phi/2):
// tr = (F11 - F22) cos(phi) + (F21 + F12) sin(phi) -> phi = atan2(F21 + F12, F11 - F22)
// For det F >= 0 the rotation is the polar factor, for det F < 0 the reflection.
// S = R^T F (symmetric), left stretch Ŝ = R S R^T.
function polarDecomposition(F)
{
let res = { det: det(F) };
if (res.det >= 0)
{
res.theta = Math.atan2(F[1][0] - F[0][1], F[0][0] + F[1][1]);
res.R = rot(res.theta);
res.reflection = false;
}
else
{
let phi = Math.atan2(F[1][0] + F[0][1], F[0][0] - F[1][1]);
res.R = [[Math.cos(phi), Math.sin(phi)], [Math.sin(phi), -Math.cos(phi)]];
res.reflection = true;
res.mirror = 0.5 * phi; // angle of the mirror line
}
res.S = symmetrize(mul(transpose(res.R), F));
res.Sh = symmetrize(mul(mul(res.R, res.S), transpose(res.R)));
res.eig = symEig(res.S);
res.u1 = apply(res.R, res.eig.v1);
res.u2 = apply(res.R, res.eig.v2);
return res;
}
// orthogonal part for the animation, tau in [0, 1]: rotation by tau theta, or a reflection that
// "flips" the body through the mirror line (I - 2 tau n n^T, n = mirror normal; not orthogonal in between)
function orthoInterp(pd, tau)
{
if (!pd.reflection) return rot(tau * pd.theta);
let n = { x: -Math.sin(pd.mirror), y: Math.cos(pd.mirror) };
return [[1 - 2 * tau * n.x * n.x, -2 * tau * n.x * n.y], [-2 * tau * n.x * n.y, 1 - 2 * tau * n.y * n.y]];
}
// matrix of the animation at time t in [0, 2]
// 'RS': t in [0,1]: S(t) = (1-t) I + t S, t in [1,2]: R(t) S
// 'SR': t in [0,1]: R(t), t in [1,2]: Ŝ(t) R
function stageMatrix(pd, order, t)
{
let t1 = smooth(clamp01(t)), t2 = smooth(clamp01(t - 1));
if (order === 'RS') return mul(orthoInterp(pd, t2), lerpM(I2, pd.S, t1));
return mul(lerpM(I2, pd.Sh, t2), orthoInterp(pd, t1));
}
function makePreset(kind)
{
let d2r = Math.PI / 180;
if (kind === 'identity') return [[1, 0], [0, 1]];
if (kind === 'stretch') return [[1.6, 0], [0, 1]];
if (kind === 'rotation') return rot(40 * d2r);
if (kind === 'shear') return [[1, 0.8], [0, 1]];
// stretch along directions rotated by 20°, then rotation by 30°
let S0 = mul(mul(rot(20 * d2r), [[1.6, 0], [0, 0.7]]), rot(-20 * d2r));
return mul(rot(30 * d2r), S0);
}
// =====================================================================================
// 2. Drawing helpers
// =====================================================================================
function drawArrow(c, a, b, color, lw, head, dash)
{
let dx = b.x - a.x, dy = b.y - a.y, len = Math.hypot(dx, dy);
c.save();
c.strokeStyle = color; c.fillStyle = color; c.lineWidth = lw; c.lineCap = "round";
c.setLineDash(dash || []);
c.beginPath(); c.moveTo(a.x, a.y); c.lineTo(b.x, b.y); c.stroke();
c.setLineDash([]);
if (len > 1.5 * head)
{
let ux = dx / len, uy = dy / len;
c.beginPath();
c.moveTo(b.x, b.y);
c.lineTo(b.x - head * ux - 0.45 * head * uy, b.y - head * uy + 0.45 * head * ux);
c.lineTo(b.x - head * ux + 0.45 * head * uy, b.y - head * uy - 0.45 * head * ux);
c.closePath(); c.fill();
}
c.restore();
}
function drawLine(c, a, b, color, lw, dash)
{
c.save();
c.strokeStyle = color; c.lineWidth = lw; c.setLineDash(dash || []);
c.beginPath(); c.moveTo(a.x, a.y); c.lineTo(b.x, b.y); c.stroke();
c.restore();
}
// the body M X: square [-L, L]^2 with a 4x4 grid, inscribed circle, marked corner cell (shows
// the orientation / a reflection) and the images of the axes e1, e2 (length L).
// T maps world coordinates [m] to the canvas.
function drawBody(c, M, T, st)
{
const P = (x, y) => T(apply(M, { x, y }));
const poly = (pts) => { c.beginPath(); pts.forEach((q, k) => k ? c.lineTo(q.x, q.y) : c.moveTo(q.x, q.y)); c.closePath(); };
c.save();
let sq = [P(-L, -L), P(L, -L), P(L, L), P(-L, L)];
if (st.fill) { poly(sq); c.fillStyle = st.fill; c.fill(); }
if (st.marker) { poly([P(L / 2, L / 2), P(L, L / 2), P(L, L), P(L / 2, L)]); c.fillStyle = st.marker; c.fill(); }
c.setLineDash(st.dash || []);
if (st.grid)
{
c.strokeStyle = st.grid; c.lineWidth = 1;
c.beginPath();
for (let k = 1; k < 4; k++)
{
let s = -L + k * L / 2, a = P(s, -L), b = P(s, L), e = P(-L, s), f = P(L, s);
c.moveTo(a.x, a.y); c.lineTo(b.x, b.y); c.moveTo(e.x, e.y); c.lineTo(f.x, f.y);
}
c.stroke();
}
if (st.circle)
{
let pts = [];
for (let k = 0; k < 96; k++) { let a = 2 * Math.PI * k / 96; pts.push(P(L * Math.cos(a), L * Math.sin(a))); }
poly(pts); c.strokeStyle = st.circle; c.lineWidth = st.lw ? 0.75 * st.lw : 1.5; c.stroke();
}
poly(sq); c.strokeStyle = st.stroke; c.lineWidth = st.lw || 2; c.stroke();
c.setLineDash([]);
c.restore();
if (st.axes)
{
let o = P(0, 0), h = st.head || 11, w = st.axesLw || 3;
drawArrow(c, o, P(L, 0), COL.e1, w, h);
drawArrow(c, o, P(0, L), COL.e2, w, h);
}
}
// principal axes of the (deformed) circle: lines along M v_i through the center
function drawPrincipal(c, M, pd, T, lw, labels)
{
[[pd.eig.v1, COL.v1, "1"], [pd.eig.v2, COL.v2, "2"]].forEach(([v, col, k]) =>
{
let a = apply(M, { x: L * v.x, y: L * v.y });
let p = T(a), q = T({ x: -a.x, y: -a.y });
drawLine(c, q, p, col, lw, [7, 5]);
if (labels)
{
c.fillStyle = col; c.font = "bold 15px Inter, sans-serif";
let o = T({ x: 0, y: 0 }), dx = p.x - o.x, dy = p.y - o.y, len = Math.hypot(dx, dy) || 1;
c.fillText(labels[k - 1], p.x + 12 * dx / len - 8, p.y + 12 * dy / len + 5);
}
});
}
// 2x2 matrix with a label; numbers right-aligned in two columns
function drawMatrix(c, x, y, label, M, color)
{
c.save();
c.fillStyle = color || COL.text;
c.font = "bold 16px Inter, sans-serif";
c.fillText(label, x, y + 16);
let bx = x + c.measureText(label).width + 8, cw = 68;
c.strokeStyle = color || COL.text; c.lineWidth = 1.5;
[[bx + 5, bx], [bx + 2 * cw + 11, bx + 2 * cw + 16]].forEach(([u, w]) =>
{
c.beginPath(); c.moveTo(u, y - 8); c.lineTo(w, y - 8); c.lineTo(w, y + 30); c.lineTo(u, y + 30); c.stroke();
});
c.font = "15px Consolas, monospace"; c.textAlign = "right";
for (let i = 0; i < 2; i++)
for (let j = 0; j < 2; j++)
{
let v = M[i][j], s = v.toFixed(3);
if (s === "-0.000") s = "0.000";
c.fillText(s, bx + 8 + (j + 1) * cw, y + 8 + 20 * i);
}
c.restore();
}
// =====================================================================================
// 3. GUI
// =====================================================================================
class GUI
{
constructor()
{
this.canvas = document.getElementById("simCanvas");
this.c = this.canvas.getContext("2d");
this.stepsCanvas = document.getElementById("stepsCanvas");
this.sc = this.stepsCanvas.getContext("2d");
this.show = { rest: true, axes: true, frame: true, inter: false };
this.t = 2; // animation time in [0, 2]; 2 = final state F X
this.playing = false;
this.drag = null; // main canvas: { kind: 'handle' | 'rotate' | 'pan', ... }
this.canvas.addEventListener("mousedown", this.mouseDown.bind(this), false);
window.addEventListener("mousemove", this.mouseMove.bind(this), false);
window.addEventListener("mouseup", this.mouseUp.bind(this), false);
this.canvas.addEventListener("wheel", this.wheel.bind(this), { passive: false });
this.canvas.addEventListener("dblclick", () => { VIEW = { ...VIEW_DEFAULT }; }, false);
this.canvas.addEventListener("touchstart", e => { e.preventDefault(); this.mouseDown(e.touches[0]); }, { passive: false });
this.canvas.addEventListener("touchmove", e => { e.preventDefault(); this.mouseMove(e.touches[0]); }, { passive: false });
this.canvas.addEventListener("touchend", e => { this.mouseUp(e.changedTouches[0]); }, false);
this.setPreset(document.getElementById("presetInput").value);
this.mainLoop();
}
setPreset(kind)
{
this.F = makePreset(kind);
this.syncInputs();
this.setT(2);
this.playing = false; this.updatePlayButton();
}
// F entries <-> number inputs
syncInputs()
{
[["F00", 0, 0], ["F01", 0, 1], ["F10", 1, 0], ["F11", 1, 1]].forEach(([id, i, j]) =>
{ document.getElementById(id).value = (+this.F[i][j].toFixed(3)).toString(); });
}
readInputs()
{
let v = id => parseFloat(document.getElementById(id).value) || 0;
this.F = [[v("F00"), v("F01")], [v("F10"), v("F11")]];
this.setT(2);
}
// ---- animation ----
setT(t) { this.t = t; document.getElementById("tInput").value = t; }
togglePlay()
{
if (!this.playing && this.t >= 2) this.setT(0);
this.playing = !this.playing;
this.updatePlayButton();
}
updatePlayButton() { document.getElementById("playButton").innerHTML = this.playing ? "Pause" : "▶ Play"; }
// ---- main loop ----
mainLoop()
{
this.order = document.getElementById("orderInput").value;
if (this.playing)
{
// two stages of 2 s each (at 60 fps)
let t = this.t + 1 / 120;
if (t >= 2) { t = 2; this.playing = false; this.updatePlayButton(); }
this.setT(t);
}
this.pd = polarDecomposition(this.F);
this.drawMain();
this.drawSteps();
this.updateStats();
window.requestAnimationFrame(this.mainLoop.bind(this));
}
updateStats()
{
let set = (id, text) => { document.getElementById(id).textContent = text; };
let pd = this.pd;
set("detF", pd.det.toFixed(3));
set("rotInfo", pd.reflection ? `reflection, mirror ${deg(pd.mirror)}` : `rotation by ${deg(pd.theta)}`);
set("stretchInfo", `${pd.eig.l1.toFixed(3)}, ${pd.eig.l2.toFixed(3)}`);
}
stageText()
{
let refl = this.pd.reflection, t = this.t;
if (t >= 2) return this.order === 'RS' ? "done: F X = R S X" : "done: F X = Ŝ R X";
let stretch = this.order === 'RS' ? "S(t) = (1−t) I + t S" : "Ŝ(t) = (1−t) I + t Ŝ";
let orth = refl ? "reflect at the mirror line" : "rotate by t·θ";
if (this.order === 'RS') return t < 1 ? `1. stretch: ${stretch}` : `2. ${orth}`;
return t < 1 ? `1. ${orth}` : `2. stretch: ${stretch}`;
}
// ---- main view ----
drawMain()
{
let c = this.c, W = this.canvas.width, H = this.canvas.height, pd = this.pd, F = this.F;
c.clearRect(0, 0, W, H);
c.fillStyle = "#ffffff"; c.fillRect(0, 0, W, H);
c.save();
c.beginPath(); c.rect(0, TOP, W, H - TOP); c.clip();
// coordinate axes through the origin
let o = toScreen({ x: 0, y: 0 });
c.strokeStyle = "rgba(100,116,139,0.25)"; c.lineWidth = 1;
c.beginPath(); c.moveTo(0, o.y); c.lineTo(W, o.y); c.moveTo(o.x, TOP); c.lineTo(o.x, H); c.stroke();
let final = this.t >= 2;
let M = final ? F : stageMatrix(pd, this.order, this.t);
if (this.show.rest)
{
drawBody(c, I2, toScreen, { stroke: COL.rest, grid: "rgba(148,163,184,0.45)", circle: COL.rest, dash: [6, 5], lw: 1.5 });
if (this.show.axes) drawPrincipal(c, I2, pd, toScreen, 1.2, ["v₁", "v₂"]);
}
// intermediate shape (S X or R X)
if (this.show.inter)
{
let Mi = this.order === 'RS' ? pd.S : orthoInterp(pd, 1);
drawBody(c, Mi, toScreen, { stroke: "#a855f7", grid: "rgba(168,85,247,0.25)", circle: "rgba(168,85,247,0.6)", dash: [3, 4], lw: 1.5 });
}
// mirror line of a reflection
if (pd.reflection)
{
let d = { x: Math.cos(pd.mirror), y: Math.sin(pd.mirror) }, R = 0.6;
drawLine(c, toScreen({ x: -R * d.x, y: -R * d.y }), toScreen({ x: R * d.x, y: R * d.y }), "#64748b", 1.5, [12, 4, 2, 4]);
let q = toScreen({ x: 0.33 * d.x, y: 0.33 * d.y });
c.fillStyle = "#64748b"; c.font = "14px Inter, sans-serif"; c.fillText("mirror", q.x + 6, q.y - 6);
}
drawBody(c, M, toScreen, { fill: COL.bodyFill, stroke: COL.body, grid: "rgba(29,78,216,0.35)", circle: COL.body, marker: COL.marker, axes: true, lw: 2.5 });
if (this.show.axes) drawPrincipal(c, M, pd, toScreen, 2, final ? ["σ₁u₁", "σ₂u₂"] : null);
if (final)
{
// rotation frame: R e1, R e2 (length L)
if (this.show.frame)
{
drawArrow(c, o, toScreen(apply(pd.R, { x: L, y: 0 })), COL.r1, 2, 10, [5, 4]);
drawArrow(c, o, toScreen(apply(pd.R, { x: 0, y: L })), COL.r2, 2, 10, [5, 4]);
c.font = "bold 14px Inter, sans-serif";
let a = toScreen(apply(pd.R, { x: 1.12 * L, y: 0 })), b = toScreen(apply(pd.R, { x: 0, y: 1.12 * L }));
c.fillStyle = COL.r1; c.fillText("R e₁", a.x - 12, a.y + 5);
c.fillStyle = COL.r2; c.fillText("R e₂", b.x - 12, b.y + 5);
}
// handles at F (L, 0) and F (0, L)
[[{ x: L, y: 0 }, COL.e1, "F e₁"], [{ x: 0, y: L }, COL.e2, "F e₂"]].forEach(([p, col, lab], k) =>
{
let q = toScreen(apply(F, p));
c.beginPath(); c.arc(q.x, q.y, 8, 0, 2 * Math.PI);
c.fillStyle = col; c.fill();
c.strokeStyle = "#ffffff"; c.lineWidth = 2; c.stroke();
if (this.drag && this.drag.kind === 'handle' && this.drag.k === k) { c.strokeStyle = COL.active; c.lineWidth = 3; c.stroke(); }
c.fillStyle = col; c.font = "bold 15px Inter, sans-serif";
c.fillText(lab, q.x + 11, q.y - 9);
});
}
c.restore();
// header
c.strokeStyle = "rgba(100,116,139,0.5)"; c.lineWidth = 1;
c.beginPath(); c.moveTo(0, TOP); c.lineTo(W, TOP); c.stroke();
c.fillStyle = COL.text;
c.font = "bold 19px Inter, sans-serif";
let kind = pd.det > 0 ? "R is a rotation" : "det F < 0: R contains a reflection";
c.fillText(`Polar decomposition F = R S: det F = ${pd.det.toFixed(3)}, ${kind}`, 14, 28);
c.font = "16px Inter, sans-serif";
c.fillStyle = COL.text2;
c.fillText(`Rest shape: square with side 2L = ${2 * L} m (gray, dashed). Blue: deformed shape F X, red/green: F e₁, F e₂.`, 14, 52);
c.fillText(`Purple/teal: principal directions v₁, v₂ (rest) and the ellipse axes σ₁u₁, σ₂u₂. Dark dashed: R e₁, R e₂.`, 14, 74);
// scale bar
let len = [0.5, 0.2, 0.1, 0.05, 0.02].find(l => l * VIEW.scale <= 130) || 0.02;
let sb = len * VIEW.scale, sx = W - 24 - sb, sy = H - 18;
c.strokeStyle = COL.text; c.lineWidth = 2;
c.beginPath(); c.moveTo(sx, sy - 5); c.lineTo(sx, sy); c.lineTo(sx + sb, sy); c.lineTo(sx + sb, sy - 5); c.stroke();
c.font = "14px Inter, sans-serif"; c.fillStyle = COL.text; c.textAlign = "center";
c.fillText(`${len} m`, sx + sb / 2, sy - 8);
c.font = "12px Inter, sans-serif"; c.fillStyle = "#6b7280";
c.fillText(`zoom ${+(VIEW.scale / VIEW_DEFAULT.scale).toFixed(1)}×`, sx + sb / 2, sy - 28);
c.textAlign = "left";
this.drawMatrixColumn(c, 718, TOP + 26);
c.strokeStyle = "#999999"; c.lineWidth = 1;
c.strokeRect(0, 0, W, H);
}
// right column of the main view: F, R, S, Ŝ and the animation stage
drawMatrixColumn(c, x, y)
{
let pd = this.pd;
c.fillStyle = "rgba(255,255,255,0.88)";
c.fillRect(x - 12, y - 18, this.canvas.width - x + 10, 500);
c.strokeStyle = "rgba(100,116,139,0.35)"; c.lineWidth = 1;
c.beginPath(); c.moveTo(x - 12, y - 18); c.lineTo(x - 12, y + 482); c.stroke();
let small = (text, yy, col) => { c.font = "14px Inter, sans-serif"; c.fillStyle = col || COL.text2; c.fillText(text, x, yy); };
drawMatrix(c, x, y, "F =", this.F, COL.body);
drawMatrix(c, x, y + 62, "R =", pd.R, COL.r1);
small(pd.reflection ? `reflection (det R = −1), mirror at ${deg(pd.mirror)}` : `rotation by θ = ${deg(pd.theta)}`, y + 112);
drawMatrix(c, x, y + 140, "S = RᵀF =", pd.S, COL.v1);
small(`eigenvalues σ₁ = ${pd.eig.l1.toFixed(3)}, σ₂ = ${pd.eig.l2.toFixed(3)}`, y + 190);
small(`v₁ at ${deg(Math.atan2(pd.eig.v1.y, pd.eig.v1.x))}`, y + 210);
drawMatrix(c, x, y + 240, "Ŝ = R S Rᵀ =", pd.Sh, COL.v2);
small(`same eigenvalues, u₁ = R v₁ at ${deg(Math.atan2(pd.u1.y, pd.u1.x))}`, y + 290);
c.font = "bold 15px Inter, sans-serif"; c.fillStyle = COL.text;
c.fillText(`Animation (${this.order === 'RS' ? "F = R S" : "F = Ŝ R"}), t = ${this.t.toFixed(2)}`, x, y + 335);
c.font = "15px Inter, sans-serif"; c.fillStyle = this.t < 2 ? "#a16207" : COL.text2;
c.fillText(this.stageText(), x, y + 357);
if (pd.reflection) small("det F < 0: R contains a reflection", y + 385, "#b91c1c");
}
// ---- second panel: F = R S and F = Ŝ R ----
drawSteps()
{
let c = this.sc, W = this.stepsCanvas.width, H = this.stepsCanvas.height, pd = this.pd, F = this.F;
c.clearRect(0, 0, W, H);
c.fillStyle = "#ffffff"; c.fillRect(0, 0, W, H);
let Rm = orthoInterp(pd, 1);
let rows = [
{ name: "F = R S", sub: "(right)", ops: ["S", pd.reflection ? "R (reflect)" : "R (rotate)"], order: 'RS',
panels: [[I2, "X (rest shape)"], [pd.S, "S X: stretch along v₁, v₂"], [F, "R S X = F X"]] },
{ name: "F = Ŝ R", sub: "(left)", ops: [pd.reflection ? "R (reflect)" : "R (rotate)", "Ŝ"], order: 'SR',
panels: [[I2, "X (rest shape)"], [Rm, pd.reflection ? "R X: reflect" : "R X: rotate"], [F, "Ŝ R X = F X: stretch along u₁, u₂"]] }
];
// common scale for all panels so that the sizes can be compared
let rMax = L * Math.SQRT2;
for (let M of [pd.S, F, Rm])
{
for (let [x, y] of [[-L, -L], [L, -L], [L, L], [-L, L]]) { let q = apply(M, { x, y }); rMax = Math.max(rMax, Math.hypot(q.x, q.y)); }
for (let v of [pd.eig.v1, pd.eig.v2]) { let q = apply(M, v); rMax = Math.max(rMax, L * Math.hypot(q.x, q.y)); }
}
let s = Math.min(420, 80 / rMax);
const PX = [112, 418, 724], PW = 280, PH = 196;
rows.forEach((row, r) =>
{
let y0 = 12 + r * 212;
c.fillStyle = COL.text; c.font = "bold 18px Inter, sans-serif";
c.fillText(row.name, 14, y0 + 92);
c.font = "13px Inter, sans-serif"; c.fillStyle = "#6b7280";
c.fillText(row.sub, 14, y0 + 112);
let animRow = this.order === row.order && this.t < 2;
row.panels.forEach(([M, title], k) =>
{
let x0 = PX[k], cx = x0 + PW / 2, cy = y0 + 112;
let T = p => ({ x: cx + s * p.x, y: cy - s * p.y });
c.fillStyle = "#f8fafc";
c.strokeStyle = "rgba(100,116,139,0.45)"; c.lineWidth = 1;
c.beginPath(); c.roundRect(x0, y0, PW, PH, 12); c.fill(); c.stroke();
c.save();
c.beginPath(); c.roundRect(x0, y0, PW, PH, 12); c.clip();
if (pd.reflection && M !== I2 && (k === 2 || r === 1))
{
let d = { x: Math.cos(pd.mirror), y: Math.sin(pd.mirror) };
drawLine(c, T({ x: -d.x, y: -d.y }), T({ x: d.x, y: d.y }), "#94a3b8", 1.2, [10, 4, 2, 4]);
}
if (k > 0) drawBody(c, I2, T, { stroke: "rgba(148,163,184,0.8)", dash: [4, 4], lw: 1 });
drawBody(c, M, T, { fill: COL.bodyFill, stroke: COL.body, grid: "rgba(29,78,216,0.3)", circle: COL.body, marker: COL.marker, axes: true, lw: 1.8, head: 8, axesLw: 2.2 });
drawPrincipal(c, M, pd, T, 1.5, null);
c.restore();
c.fillStyle = COL.text; c.font = "bold 14px Inter, sans-serif";
c.fillText(title, x0 + 10, y0 + 20);
});
// arrows between the panels; the current animation stage is highlighted
row.ops.forEach((op, k) =>
{
let x1 = PX[k] + PW + 3, x2 = PX[k + 1] - 3, y = y0 + PH / 2;
let active = animRow && (k === 0 ? this.t < 1 : this.t >= 1);
drawArrow(c, { x: x1, y }, { x: x2, y }, active ? COL.active : "#475569", active ? 4 : 2.5, 10);
c.save();
c.translate(0.5 * (x1 + x2), y - 12);
c.fillStyle = active ? "#a16207" : COL.text; c.font = "bold 15px Inter, sans-serif"; c.textAlign = "center";
c.fillText(op.split(" ")[0], 0, 0);
c.restore();
});
});
c.strokeStyle = "#999999"; c.lineWidth = 1;
c.strokeRect(0, 0, W, H);
}
// ---- mouse ----
getPos(canvas, e)
{
const r = canvas.getBoundingClientRect();
return { x: (e.clientX - r.left) * canvas.width / r.width, y: (e.clientY - r.top) * canvas.height / r.height };
}
// handle -> change a column of F; inside the body -> rotate the body; elsewhere -> pan
mouseDown(e)
{
if (this.t < 2) { this.playing = false; this.updatePlayButton(); this.setT(2); }
let s = this.getPos(this.canvas, e), p = toWorldPos(s);
let handles = [apply(this.F, { x: L, y: 0 }), apply(this.F, { x: 0, y: L })];
let k = handles.findIndex(h => { let q = toScreen(h); return Math.hypot(q.x - s.x, q.y - s.y) < 12; });
if (k >= 0) { this.drag = { kind: 'handle', k }; return; }
let d = det(this.F);
if (Math.abs(d) > 1e-6)
{
// position in the rest shape: X = F^-1 x
let X = { x: (this.F[1][1] * p.x - this.F[0][1] * p.y) / d, y: (-this.F[1][0] * p.x + this.F[0][0] * p.y) / d };
if (Math.abs(X.x) <= L && Math.abs(X.y) <= L && Math.hypot(p.x, p.y) > 0.01)
{
this.drag = { kind: 'rotate', angle: Math.atan2(p.y, p.x) };
return;
}
}
this.drag = { kind: 'pan', start: s, view: { ...VIEW } };
}
mouseUp(e) { this.drag = null; }
wheel(e)
{
e.preventDefault();
let s = this.getPos(this.canvas, e), p = toWorldPos(s);
let scale = Math.min(6 * VIEW_DEFAULT.scale, Math.max(0.3 * VIEW_DEFAULT.scale, VIEW.scale * Math.exp(-0.0015 * e.deltaY)));
VIEW = { x0: s.x - p.x * scale, y0: s.y + p.y * scale, scale };
}
mouseMove(e)
{
if (!this.drag) return;
let s = this.getPos(this.canvas, e), p = toWorldPos(s);
if (this.drag.kind === 'pan')
{
VIEW = { x0: this.drag.view.x0 + s.x - this.drag.start.x, y0: this.drag.view.y0 + s.y - this.drag.start.y, scale: VIEW.scale };
return;
}
if (this.drag.kind === 'handle')
{
// column k of F = handle position / L
let k = this.drag.k;
this.F[0][k] = p.x / L; this.F[1][k] = p.y / L;
}
else
{
// rotate the deformed body: F <- Q F
let a = Math.atan2(p.y, p.x);
this.F = mul(rot(a - this.drag.angle), this.F);
this.drag.angle = a;
}
this.syncInputs();
}
}
gui = new GUI();
</script>
</body>
</html>