1// Mass on a frictionless spring. Positions are in units of the maximum
2// swing drawn on screen, so q lies in [-1, 1].
4function color(name) {
5 return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
6}
8// Slides are laid out at 1920 x 1080 and the whole deck is scaled to fit the
9// window (see fitDeck below). Diagrams are drawn in units of DRAW_SCALE slide
10// pixels, so their geometry and fonts read well on a full-size slide.
11const DRAW_SCALE = 1.5;
12let deckScale = 1;
14// Size a canvas's backing store to its on-screen pixels (slide size x deck
15// scale x device pixel ratio) and return a context and size in drawing units.
16function prepare(canvas) {
17 const ctx = canvas.getContext('2d');
18 const k = deckScale * (window.devicePixelRatio || 1);
19 const bw = Math.max(1, Math.round(canvas.clientWidth * k));
20 const bh = Math.max(1, Math.round(canvas.clientHeight * k));
21 if (canvas.width !== bw || canvas.height !== bh) {
22 canvas.width = bw;
23 canvas.height = bh;
24 }
25 ctx.setTransform(k * DRAW_SCALE, 0, 0, k * DRAW_SCALE, 0, 0);
26 const w = canvas.clientWidth / DRAW_SCALE;
27 const h = canvas.clientHeight / DRAW_SCALE;
28 ctx.clearRect(0, 0, w, h);
29 return { ctx, w, h };
30}
32// Horizontal layout shared by the spring diagram, the q0 slider and the phase plot,
33// so that a given q sits at the same x on all of them.
34function layout(w) {
35 const rest = w * 0.5;
36 const swing = Math.min(w * 0.3, 200);
37 return { rest, swing, qToX: (q) => rest + q * swing };
38}
40// Wall, floor and a spring reaching a block centered at position q. drawBody
41// draws whatever is attached (it gets the scene geometry), before the
42// rest-position marker goes on top. Returns the geometry for labels.
43function drawSpringScene(ctx, w, h, q, drawBody) {
44 const fg = color('--fg');
45 const { rest, swing, qToX } = layout(w);
46 const wallX = 20;
47 const floorY = h * 0.62;
48 const box = 50;
49 const center = qToX(q);
50 const springY = floorY - box / 2;
52 // wall and floor
53 ctx.strokeStyle = fg;
54 ctx.lineWidth = 2;
55 ctx.beginPath();
56 ctx.moveTo(wallX, floorY - box * 1.6);
57 ctx.lineTo(wallX, floorY);
58 ctx.lineTo(w - 10, floorY);
59 ctx.stroke();
61 // spring (zig-zag)
62 const coils = 12;
63 const amp = 10;
64 const start = wallX;
65 const end = center - box / 2;
66 const lead = 12;
67 ctx.lineWidth = 1.5;
68 ctx.beginPath();
69 ctx.moveTo(start, springY);
70 ctx.lineTo(start + lead, springY);
71 const len = end - start - 2 * lead;
72 for (let i = 0; i < coils; i++) {
73 const sx = start + lead + ((i + 0.5) / coils) * len;
74 ctx.lineTo(sx, springY + (i % 2 ? amp : -amp));
75 }
76 ctx.lineTo(end - lead, springY);
77 ctx.lineTo(end, springY);
78 ctx.stroke();
80 const scene = { rest, swing, qToX, floorY, box, springY, amp, start, end, center };
81 drawBody(scene);
83 // rest position marker
84 ctx.strokeStyle = fg;
85 ctx.globalAlpha = 0.3;
86 ctx.setLineDash([4, 4]);
87 ctx.beginPath();
88 ctx.moveTo(rest, floorY - box * 1.4);
89 ctx.lineTo(rest, floorY + 34);
90 ctx.stroke();
91 ctx.setLineDash([]);
92 ctx.globalAlpha = 1;
93 return scene;
94}
96// params: { k, m, q0, b }, read live so sliders can change them; the damping
97// coefficient b is optional (default 0, no damping).
98// labels: which of 'm', 'k', 'q', 'F', 'p', 'q0' to draw.
99// pScale: length of the p arrow per unit momentum, as a fraction of the swing;
100// by default the arrow peaks at the same length as q.
101function createSpring({ canvas, button, params, labels = [], speed = 1, pScale, onDraw = () => {} }) {
102 let q = params.q0;
103 let p = 0;
105 function step(dt) {
106 // velocity Verlet on dq/dt = p/m, dp/dt = -k q. Damping, dp/dt = -(b/m) p,
107 // is solved exactly and split around it (Strang splitting), so phase-space
108 // area shrinks at exactly the rate exp(-b t / m).
109 const { k, m, b = 0 } = params;
110 const decay = Math.exp((-0.5 * b * dt) / m);
111 p *= decay;
112 const f = -k * q;
113 q += (p / m) * dt + (0.5 * f / m) * dt * dt;
114 p += 0.5 * (f - k * q) * dt;
115 p *= decay;
116 }
118 function draw() {
119 if (!canvas.clientWidth) return;
120 const { ctx, w, h } = prepare(canvas);
122 const fg = color('--fg');
123 const { rest, swing, qToX, floorY, box, springY, amp, start, end, center } = drawSpringScene(ctx, w, h, q, (sc) => {
124 ctx.fillStyle = color('--accent');
125 ctx.fillRect(sc.center - sc.box / 2, sc.floorY - sc.box, sc.box, sc.box);
126 });
128 onDraw(q, p);
130 if (!labels.length) return;
132 ctx.font = 'italic 18px Georgia, serif';
133 ctx.textAlign = 'center';
135 if (labels.includes('m')) {
136 ctx.fillStyle = color('--bg');
137 ctx.textBaseline = 'middle';
138 ctx.fillText('m', center, floorY - box / 2);
139 }
140 if (labels.includes('k')) {
141 ctx.fillStyle = fg;
142 ctx.textBaseline = 'bottom';
143 ctx.fillText('k', (start + end) / 2, springY - amp - 4);
144 }
145 if (labels.includes('q0')) {
146 // where the block was let go from
147 const x0 = qToX(params.q0);
148 ctx.strokeStyle = fg;
149 ctx.globalAlpha = 0.5;
150 ctx.setLineDash([2, 3]);
151 ctx.beginPath();
152 ctx.moveTo(x0, floorY - box - 48);
153 ctx.lineTo(x0, floorY);
154 ctx.stroke();
155 ctx.setLineDash([]);
156 ctx.globalAlpha = 1;
157 ctx.fillStyle = fg;
158 ctx.textBaseline = 'bottom';
159 // the serif font has no subscript zero, so draw it smaller and lower
160 ctx.fillText('q', x0 - 4, floorY - box - 52);
161 ctx.font = 'italic 12px Georgia, serif';
162 ctx.fillText('0', x0 + 5, floorY - box - 48);
163 ctx.font = 'italic 18px Georgia, serif';
164 }
166 // q below the floor; F and p above the block
167 const { k, m } = params;
168 const pLen = (pScale ?? 1 / Math.sqrt(k * m)) * swing;
169 if (labels.includes('q')) arrow(ctx, rest, center, floorY + 22, fg, 'q', 'below');
170 if (labels.includes('F')) arrow(ctx, center, center - q * swing, floorY - box - 40, color('--force'), 'F', 'above');
171 if (labels.includes('p')) arrow(ctx, center, center + p * pLen, floorY - box - 14, color('--momentum'), 'p', 'above');
172 }
174 function setLabels(value) {
175 labels = value;
176 draw();
177 }
179 const loop = createLoop({ button, step, draw, speed });
181 // Back to being held at q0, at rest.
182 function reset() {
183 q = params.q0;
184 p = 0;
185 loop.reset();
186 }
188 return { draw, setLabels, reset, pause: loop.pause };
189}
191// Animation driven by a Start / Stop / Continue button.
192function createLoop({ button, step, draw, speed = 1 }) {
193 let running = false;
194 let lastTime = null;
195 let rafId = null;
197 function frame(t) {
198 if (!running) return;
199 if (lastTime !== null) {
200 const dt = speed * Math.min((t - lastTime) / 1000, 0.05);
201 const n = 4;
202 for (let i = 0; i < n; i++) step(dt / n);
203 }
204 lastTime = t;
205 draw();
206 rafId = requestAnimationFrame(frame);
207 }
209 function setRunning(value) {
210 running = value;
211 cancelAnimationFrame(rafId);
212 if (running) {
213 lastTime = null;
214 rafId = requestAnimationFrame(frame);
215 }
216 if (running || button.textContent !== 'Start') {
217 button.textContent = running ? 'Stop' : 'Continue';
218 }
219 }
221 button.addEventListener('click', () => setRunning(!running));
223 return {
224 pause: () => running && setRunning(false),
225 reset: () => {
226 setRunning(false);
227 button.textContent = 'Start';
228 draw();
229 },
230 };
231}
233// Pendulum: a bob of mass m on a massless rod of length L, angle theta from
234// straight down, kept in [-pi, pi].
235// params: { m, L, g, theta0, p0 }, read live so sliders can change them.
236// labels: which of 'm', 'L', 'theta', 'p', 'g' to draw.
237// centered: put the pivot mid-canvas so the bob can go over the top; the rod
238// is then drawn to scale, with L = 1.2 (the slider's maximum) filling the canvas.
239// pScale: length of the p arrow in px per unit momentum; by default the arrow
240// peaks at 70px when let go from theta0 at rest.
241function createPendulum({ canvas, button, params, labels = [], centered = false, pScale, onDraw = () => {} }) {
242 let theta = params.theta0;
243 let p = params.p0;
245 function step(dt) {
246 // leapfrog on dtheta/dt = p / (m L^2), dp/dt = -m g L sin(theta)
247 const { m, L, g } = params;
248 p -= 0.5 * dt * m * g * L * Math.sin(theta);
249 theta += dt * p / (m * L * L);
250 p -= 0.5 * dt * m * g * L * Math.sin(theta);
251 if (theta > Math.PI) theta -= 2 * Math.PI;
252 if (theta < -Math.PI) theta += 2 * Math.PI;
253 }
255 function draw() {
256 if (!canvas.clientWidth) return;
257 const { ctx, w, h } = prepare(canvas);
258 const fg = color('--fg');
259 const accent = color('--accent');
260 const { m, L, g } = params;
261 const px = w / 2;
262 const py = centered ? h / 2 : 30;
263 const maxRod = centered ? h / 2 - 28 : Math.min(h - 80, w * 0.4);
264 const rod = centered ? maxRod * L / 1.2 : maxRod;
265 const bx = px + rod * Math.sin(theta);
266 const by = py + rod * Math.cos(theta);
267 const r = 18;
269 // ceiling (only when hanging from the top) and pivot
270 ctx.strokeStyle = fg;
271 ctx.lineWidth = 2;
272 if (!centered) {
273 ctx.beginPath();
274 ctx.moveTo(px - 50, py);
275 ctx.lineTo(px + 50, py);
276 ctx.stroke();
277 }
279 // vertical reference
280 ctx.globalAlpha = 0.3;
281 ctx.setLineDash([4, 4]);
282 ctx.beginPath();
283 ctx.moveTo(px, py);
284 ctx.lineTo(px, py + rod + r + 10);
285 ctx.stroke();
286 ctx.setLineDash([]);
287 ctx.globalAlpha = 1;
289 // rod and bob
290 ctx.lineWidth = 2;
291 ctx.beginPath();
292 ctx.moveTo(px, py);
293 ctx.lineTo(bx, by);
294 ctx.stroke();
295 ctx.fillStyle = fg;
296 ctx.beginPath();
297 ctx.arc(px, py, 4, 0, 2 * Math.PI);
298 ctx.fill();
299 ctx.fillStyle = accent;
300 ctx.beginPath();
301 ctx.arc(bx, by, r, 0, 2 * Math.PI);
302 ctx.fill();
304 onDraw(theta, p);
306 ctx.font = 'italic 18px Georgia, serif';
307 ctx.textAlign = 'center';
308 ctx.textBaseline = 'middle';
310 if (labels.includes('m')) {
311 ctx.fillStyle = color('--bg');
312 ctx.fillText('m', bx, by);
313 }
315 if (labels.includes('L')) {
316 // beside the middle of the rod, on the side away from the vertical
317 const side = theta >= 0 ? 1 : -1;
318 ctx.fillStyle = fg;
319 ctx.fillText('L', (px + bx) / 2 + side * 14 * Math.cos(theta), (py + by) / 2 - side * 14 * Math.sin(theta));
320 }
322 if (labels.includes('theta')) {
323 // arc from the vertical to the rod
324 const arcR = Math.min(44, rod * 0.45);
325 ctx.strokeStyle = fg;
326 ctx.fillStyle = fg;
327 ctx.lineWidth = 1.5;
328 ctx.beginPath();
329 ctx.arc(px, py, arcR, Math.PI / 2, Math.PI / 2 - theta, theta > 0);
330 ctx.stroke();
331 const mid = Math.PI / 2 - theta / 2;
332 ctx.fillText('θ', px + (arcR + 14) * Math.cos(mid), py + (arcR + 14) * Math.sin(mid));
333 }
335 if (labels.includes('p')) {
336 // along the direction of motion, perpendicular to the rod
337 const peak = Math.sqrt(2 * m * m * g * L * L * L * (1 - Math.cos(params.theta0)));
338 const len = p * (pScale ?? (peak ? 70 / peak : 0));
339 const tx = Math.cos(theta);
340 const ty = -Math.sin(theta);
341 const momentum = color('--momentum');
342 ctx.strokeStyle = momentum;
343 ctx.fillStyle = momentum;
344 ctx.lineWidth = 1.5;
345 ctx.beginPath();
346 ctx.moveTo(bx, by);
347 ctx.lineTo(bx + tx * len, by + ty * len);
348 ctx.stroke();
349 if (Math.abs(len) > 8) {
350 const d = Math.sign(len);
351 const ex = bx + tx * len;
352 const ey = by + ty * len;
353 ctx.beginPath();
354 ctx.moveTo(ex, ey);
355 ctx.lineTo(ex - d * 8 * tx - 4 * ty, ey - d * 8 * ty + 4 * tx);
356 ctx.lineTo(ex - d * 8 * tx + 4 * ty, ey - d * 8 * ty - 4 * tx);
357 ctx.closePath();
358 ctx.fill();
359 ctx.fillText('p', ex + d * 12 * tx, ey + d * 12 * ty);
360 }
361 }
363 if (labels.includes('g')) {
364 // gravity, pointing down, off to the side
365 const gx = Math.min(px + maxRod + 50, w - 20);
366 ctx.strokeStyle = fg;
367 ctx.fillStyle = fg;
368 ctx.lineWidth = 1.5;
369 ctx.beginPath();
370 ctx.moveTo(gx, py + 40);
371 ctx.lineTo(gx, py + 90);
372 ctx.stroke();
373 ctx.beginPath();
374 ctx.moveTo(gx, py + 90);
375 ctx.lineTo(gx - 4, py + 82);
376 ctx.lineTo(gx + 4, py + 82);
377 ctx.closePath();
378 ctx.fill();
379 ctx.fillText('g', gx + 14, py + 65);
380 }
381 }
383 const loop = createLoop({ button, step, draw });
385 function setLabels(value) {
386 labels = value;
387 draw();
388 }
390 // Back to the initial state, held still.
391 function reset() {
392 theta = params.theta0;
393 p = params.p0;
394 loop.reset();
395 }
397 return { draw, setLabels, reset, pause: loop.pause };
398}
400function arrow(ctx, from, to, y, col, label, side) {
401 const dir = Math.sign(to - from);
402 ctx.strokeStyle = col;
403 ctx.fillStyle = col;
404 ctx.lineWidth = 1.5;
405 ctx.beginPath();
406 ctx.moveTo(from, y);
407 ctx.lineTo(to, y);
408 ctx.stroke();
409 if (Math.abs(to - from) > 8) {
410 ctx.beginPath();
411 ctx.moveTo(to, y);
412 ctx.lineTo(to - dir * 8, y - 4);
413 ctx.lineTo(to - dir * 8, y + 4);
414 ctx.closePath();
415 ctx.fill();
416 }
417 ctx.textBaseline = side === 'above' ? 'bottom' : 'top';
418 ctx.fillText(label, (from + to) / 2, side === 'above' ? y - 4 : y + 4);
419}
421// Horizontal bars for kinetic, potential and total energy, scaled to the total.
422function drawEnergyBars(canvas, params, q, p) {
423 if (!canvas.clientWidth) return;
424 const { ctx, w } = prepare(canvas);
425 const { k, m, q0 } = params;
426 const kinetic = (p * p) / (2 * m);
427 const potential = 0.5 * k * q * q;
428 const total = 0.5 * k * q0 * q0;
430 const fg = color('--fg');
431 const kColor = color('--momentum');
432 const pColor = color('--potential');
433 const labelW = 90;
434 const barW = Math.min(w - labelW - 10, 400);
435 const left = Math.max(0, (w - labelW - barW) / 2);
436 const barX = left + labelW;
437 const rowH = 30;
438 const barH = 18;
440 ctx.font = `15px ${color('--font-body')}`;
441 ctx.textBaseline = 'middle';
442 ctx.textAlign = 'right';
444 const rows = [
445 ['Kinetic', [[kinetic, kColor]]],
446 ['Potential', [[potential, pColor]]],
447 ['Total', [[kinetic, kColor], [potential, pColor]]],
448 ];
449 rows.forEach(([label, segments], i) => {
450 const y = 10 + i * rowH;
451 ctx.fillStyle = fg;
452 ctx.fillText(label, barX - 12, y + barH / 2);
454 // outline at full scale, then filled segments
455 ctx.strokeStyle = fg;
456 ctx.globalAlpha = 0.25;
457 ctx.lineWidth = 1;
458 ctx.strokeRect(barX + 0.5, y + 0.5, barW, barH);
459 ctx.globalAlpha = 1;
460 let sx = barX;
461 for (const [value, col] of segments) {
462 const sw = Math.min(value / total, 1) * barW;
463 ctx.fillStyle = col;
464 ctx.fillRect(sx, y, sw, barH);
465 sx += sw;
466 }
467 });
468}
470// Phase plot: q horizontal (lined up with the spring diagram), p vertical.
471// The axes are fixed so changing k and m visibly reshapes the orbit.
472const pMax = 3;
474// Draw the q and p axes; returns the mapping from (q, p) to canvas coordinates.
475function springAxes(ctx, w, h) {
476 const { rest, swing, qToX } = layout(w);
477 const mid = h / 2;
478 const pToY = (pv) => mid - (pv / pMax) * (h / 2 - 16);
479 const fg = color('--fg');
480 ctx.strokeStyle = fg;
481 ctx.fillStyle = fg;
482 ctx.globalAlpha = 0.5;
483 ctx.lineWidth = 1;
484 ctx.beginPath();
485 ctx.moveTo(rest - swing - 20, mid);
486 ctx.lineTo(rest + swing + 20, mid);
487 ctx.moveTo(rest, 8);
488 ctx.lineTo(rest, h - 8);
489 ctx.stroke();
490 ctx.globalAlpha = 1;
491 ctx.font = 'italic 18px Georgia, serif';
492 ctx.textAlign = 'left';
493 ctx.textBaseline = 'middle';
494 ctx.fillText('q', rest + swing + 26, mid);
495 ctx.textBaseline = 'top';
496 ctx.fillText('p', rest + 8, 6);
497 return { rest, swing, mid, qToX, pToY };
498}
500function drawPhase(canvas, params, trail, q, p) {
501 if (!canvas.clientWidth) return;
502 const { ctx, w, h } = prepare(canvas);
503 const { rest, swing, mid, qToX, pToY } = springAxes(ctx, w, h);
504 const fg = color('--fg');
505 const accent = color('--accent');
507 // level curve H = k q0^2 / 2: an ellipse with semi-axes q0 and q0 sqrt(k m)
508 const { k, m, q0 } = params;
509 const rx = Math.abs(q0) * swing;
510 const ry = Math.abs(pToY(Math.abs(q0) * Math.sqrt(k * m)) - mid);
511 ctx.strokeStyle = fg;
512 ctx.globalAlpha = 0.35;
513 ctx.setLineDash([4, 4]);
514 ctx.beginPath();
515 ctx.ellipse(rest, mid, rx, ry, 0, 0, 2 * Math.PI);
516 ctx.stroke();
517 ctx.setLineDash([]);
518 ctx.globalAlpha = 1;
520 // trail, then the current state
521 ctx.strokeStyle = accent;
522 ctx.lineWidth = 2;
523 ctx.beginPath();
524 trail.forEach(([tq, tp], i) => {
525 if (i === 0) ctx.moveTo(qToX(tq), pToY(tp));
526 else ctx.lineTo(qToX(tq), pToY(tp));
527 });
528 ctx.stroke();
529 ctx.fillStyle = accent;
530 ctx.beginPath();
531 ctx.arc(qToX(q), pToY(p), 6, 0, 2 * Math.PI);
532 ctx.fill();
533}
535// Page 1: the spring and its equations of motion
536const springParams = { k: 6.25, m: 1, q0: 0.6 };
537const spring = createSpring({
538 canvas: document.getElementById('spring-canvas'),
539 button: document.getElementById('spring-toggle'),
540 params: springParams,
541});
543// Page 2: the same spring, with energy bars. Slower and without the arrows,
544// so the moving bars are the only thing to watch.
545const energyBars = document.getElementById('energy-bars');
546const energy = createSpring({
547 canvas: document.getElementById('energy-canvas'),
548 button: document.getElementById('energy-toggle'),
549 params: springParams,
550 speed: 0.5,
551 onDraw: (q, p) => drawEnergyBars(energyBars, springParams, q, p),
552});
554// The spring in phase space, with a slider for each of the named params.
555// Elements are found by id: `${id}-canvas`, `${id}-plot`, `${id}-${name}`.
556// Reset clears the trail as well.
557function createSpringPhase({ id, params, names }) {
558 const canvas = document.getElementById(`${id}-canvas`);
559 const plot = document.getElementById(`${id}-plot`);
560 const q0Slider = document.getElementById(`${id}-q0`);
561 let trail = [];
562 const sim = createSpring({
563 canvas,
564 button: document.getElementById(`${id}-toggle`),
565 params,
566 labels: ['q', 'p', 'k', 'q0'],
567 pScale: 1 / pMax,
568 onDraw: (q, p) => {
569 trail.push([q, p]);
570 if (trail.length > 2000) trail.shift();
571 drawPhase(plot, params, trail, q, p);
572 alignSlider();
573 },
574 });
576 // Stretch the q0 slider so its thumb sits directly under q0 on the diagram.
577 // The thumb is 30 slide pixels wide (style.css).
578 function alignSlider() {
579 const { rest, swing } = layout(canvas.clientWidth / DRAW_SCALE);
580 const thumb = 30;
581 q0Slider.style.width = `${2 * swing * DRAW_SCALE + thumb}px`;
582 q0Slider.style.marginLeft = `${(rest - swing) * DRAW_SCALE - thumb / 2}px`;
583 }
585 function reset() {
586 trail = [];
587 sim.reset();
588 }
590 for (const name of names) {
591 const input = document.getElementById(`${id}-${name}`);
592 const output = document.getElementById(`${id}-${name}-value`);
593 input.value = params[name];
594 output.textContent = params[name];
595 input.addEventListener('input', () => {
596 params[name] = Number(input.value);
597 output.textContent = input.value;
598 reset();
599 });
600 }
602 return { ...sim, reset };
603}
605// Page 4: phase space, with adjustable q0, k and m
606const phase = createSpringPhase({ id: 'phase', params: { k: 4, m: 1, q0: 0.6 }, names: ['q0', 'k', 'm'] });
608// Page 5: the pendulum
609const pendulum = createPendulum({
610 canvas: document.getElementById('pendulum-canvas'),
611 button: document.getElementById('pendulum-toggle'),
612 params: { m: 1, L: 1, g: 9.8, theta0: 1.0, p0: 0 },
613});
615// Page 6: pendulum phase space. theta runs across [-pi, pi]; p is fixed at
616// +/- pendulumPMax. The separatrix peaks at p = 2 m L sqrt(g L), and the m, L
617// and g slider ranges keep that under 12 even at their maximums.
618const pendulumPMax = 12;
619const pendulumDefaults = { m: 1, L: 1, g: 9.8 };
620const pendulumParams = { ...pendulumDefaults, theta0: 0.3, p0: 0 };
621const pendulumPresets = {
622 small: { theta0: 0.3, p0: 0 },
623 large: { theta0: 2.5, p0: 0 },
624 top: { theta0: 3.1, p0: 0 },
625 rotation: { theta0: 0, p0: 8 },
626 balanced: { theta0: Math.PI - 1e-6, p0: 0 }, // a tiny nudge, so it falls after a few seconds
627 rest: { theta0: 0, p0: 0 },
628};
629const pendulumPlot = document.getElementById('pendulum-plot');
630let pendulumTrail = [];
631const pendulumPhase = createPendulum({
632 canvas: document.getElementById('pendulum-phase-canvas'),
633 button: document.getElementById('pendulum-phase-toggle'),
634 params: pendulumParams,
635 labels: ['theta', 'p'],
636 centered: true,
637 pScale: 60 / pendulumPMax,
638 onDraw: (theta, p) => {
639 pendulumTrail.push([theta, p]);
640 if (pendulumTrail.length > 3000) pendulumTrail.shift();
641 drawPendulumPhase(pendulumPlot, pendulumParams, pendulumTrail, theta, p);
642 },
643});
645// Draw the pendulum phase portrait (level curves of H) and the theta and p
646// axes; returns the mapping from (theta, p) to canvas coordinates.
647function pendulumAxes(ctx, w, h, params) {
648 const { m, L, g } = params;
649 const halfW = Math.min(w / 2 - 30, 300);
650 const cx = w / 2;
651 const mid = h / 2;
652 const thetaToX = (t) => cx + (t / Math.PI) * halfW;
653 const pToY = (pv) => mid - (pv / pendulumPMax) * (h / 2 - 16);
654 const fg = color('--fg');
656 ctx.save();
657 ctx.beginPath();
658 ctx.rect(cx - halfW, 0, 2 * halfW, h);
659 ctx.clip();
660 // background phase portrait: level curves of H, in units of m g L.
661 // Level 1 is the separatrix between swinging and rotating.
662 const levels = [-0.9, -0.6, -0.2, 0.3, 0.7, 1, 1.5, 2.5, 4];
663 const n = 300;
664 for (const c of levels) {
665 ctx.strokeStyle = fg;
666 ctx.globalAlpha = c === 1 ? 0.45 : 0.15;
667 ctx.lineWidth = c === 1 ? 1.5 : 1;
668 for (const sign of [1, -1]) {
669 ctx.beginPath();
670 let drawing = false;
671 for (let i = 0; i <= n; i++) {
672 const t = -Math.PI + (2 * Math.PI * i) / n;
673 // p^2 / (2 m L^2) - m g L cos(t) = c m g L
674 const p2 = 2 * m * L * L * m * g * L * (c + Math.cos(t));
675 if (p2 < 0) { drawing = false; continue; }
676 const x = thetaToX(t);
677 const y = pToY(sign * Math.sqrt(p2));
678 if (drawing) ctx.lineTo(x, y);
679 else ctx.moveTo(x, y);
680 drawing = true;
681 }
682 ctx.stroke();
683 }
684 }
685 ctx.globalAlpha = 1;
687 ctx.restore();
689 // axes
690 ctx.strokeStyle = fg;
691 ctx.fillStyle = fg;
692 ctx.globalAlpha = 0.5;
693 ctx.lineWidth = 1;
694 ctx.beginPath();
695 ctx.moveTo(cx - halfW, mid);
696 ctx.lineTo(cx + halfW, mid);
697 ctx.moveTo(cx, 8);
698 ctx.lineTo(cx, h - 8);
699 ctx.stroke();
700 ctx.globalAlpha = 1;
701 ctx.font = 'italic 18px Georgia, serif';
702 ctx.textBaseline = 'middle';
703 ctx.textAlign = 'left';
704 ctx.fillText('θ', cx + halfW + 6, mid);
705 ctx.textBaseline = 'top';
706 ctx.fillText('p', cx + 8, 6);
707 ctx.font = `13px ${color('--font-body')}`;
708 ctx.textAlign = 'center';
709 ctx.fillText('−π', cx - halfW, mid + 6);
710 ctx.fillText('π', cx + halfW, mid + 6);
711 return { thetaToX, pToY };
712}
714function drawPendulumPhase(canvas, params, trail, theta, p) {
715 if (!canvas.clientWidth) return;
716 const { ctx, w, h } = prepare(canvas);
717 const { thetaToX, pToY } = pendulumAxes(ctx, w, h, params);
718 const accent = color('--accent');
720 // trail, broken where theta wraps around
721 ctx.strokeStyle = accent;
722 ctx.lineWidth = 2;
723 ctx.beginPath();
724 trail.forEach(([tt, tp], i) => {
725 const jump = i > 0 && Math.abs(tt - trail[i - 1][0]) > Math.PI;
726 if (i === 0 || jump) ctx.moveTo(thetaToX(tt), pToY(tp));
727 else ctx.lineTo(thetaToX(tt), pToY(tp));
728 });
729 ctx.stroke();
730 ctx.fillStyle = accent;
731 ctx.beginPath();
732 ctx.arc(thetaToX(theta), pToY(p), 6, 0, 2 * Math.PI);
733 ctx.fill();
734}
736const pendulumPreset = document.getElementById('pendulum-preset');
737const pendulumInputs = ['theta0', 'p0', 'm', 'L', 'g'].map((name) => ({
738 name,
739 input: document.getElementById(`pendulum-${name}`),
740 output: document.getElementById(`pendulum-${name}-value`),
741}));
743function syncPendulumInputs() {
744 for (const { name, input, output } of pendulumInputs) {
745 input.value = pendulumParams[name];
746 output.textContent = pendulumParams[name].toFixed(2);
747 }
748}
750function resetPendulumPhase() {
751 pendulumTrail = [];
752 pendulumPhase.reset();
753}
755for (const { name, input, output } of pendulumInputs) {
756 input.addEventListener('input', () => {
757 pendulumParams[name] = Number(input.value);
758 output.textContent = pendulumParams[name].toFixed(2);
759 pendulumPreset.value = 'custom';
760 resetPendulumPhase();
761 });
762}
764// A preset restores the default m, L and g along with its initial state.
765pendulumPreset.addEventListener('change', () => {
766 const preset = pendulumPresets[pendulumPreset.value];
767 if (!preset) return;
768 Object.assign(pendulumParams, pendulumDefaults, preset);
769 syncPendulumInputs();
770 resetPendulumPhase();
771});
772syncPendulumInputs();
774// Liouville's theorem: a disk of starting points evolves under the flow, and
775// the area enclosed by its boundary stays constant.
776// force(q) gives dp/dt; m is the mass term in dq/dt = p / m.
777// center and radii set the disk in (q, p); the single simulation started from
778// the center is evolved alongside it. drawDiagram(ctx, w, h, points, jitter,
779// central) and axes(ctx, w, h) draw the physical picture and the phase-plane axes.
780function createLiouville({ id, force, m, center, radii, drawDiagram, axes }) {
781 const canvas = document.getElementById(`${id}-canvas`);
782 const diagram = document.getElementById(`${id}-diagram`);
783 const areaOut = document.getElementById(`${id}-area`);
784 const [rq, rp] = radii;
785 // a fine boundary, so the area stays accurate as the disk stretches
786 const nb = 2000;
787 let boundary;
788 let interior;
789 let jitter;
790 let central;
792 function makeDisk() {
793 central = [center[0], center[1]];
794 boundary = [];
795 for (let i = 0; i < nb; i++) {
796 const a = (2 * Math.PI * i) / nb;
797 boundary.push([center[0] + rq * Math.cos(a), center[1] + rp * Math.sin(a)]);
798 }
799 interior = [];
800 while (interior.length < 600) {
801 const u = 2 * Math.random() - 1;
802 const v = 2 * Math.random() - 1;
803 if (u * u + v * v <= 1) interior.push([center[0] + rq * u, center[1] + rp * v]);
804 }
805 // each point gets a fixed random offset on the diagram, so they form a cloud
806 jitter = interior.map(() => Math.random());
807 }
808 makeDisk();
810 function step(dt) {
811 // leapfrog on dq/dt = p / m, dp/dt = force(q), for every point
812 for (const pts of [boundary, interior, [central]]) {
813 for (const pt of pts) {
814 pt[1] += 0.5 * dt * force(pt[0]);
815 pt[0] += dt * pt[1] / m;
816 pt[1] += 0.5 * dt * force(pt[0]);
817 }
818 }
819 }
821 // shoelace formula on the boundary polygon
822 function area() {
823 let a = 0;
824 for (let i = 0; i < nb; i++) {
825 const [q1, p1] = boundary[i];
826 const [q2, p2] = boundary[(i + 1) % nb];
827 a += q1 * p2 - q2 * p1;
828 }
829 return Math.abs(a) / 2;
830 }
832 function draw() {
833 if (!canvas.clientWidth) return;
834 const d = prepare(diagram);
835 drawDiagram(d.ctx, d.w, d.h, interior, jitter, central);
837 const { ctx, w, h } = prepare(canvas);
838 const { toX, toY } = axes(ctx, w, h);
839 const accent = color('--accent');
840 ctx.fillStyle = accent;
841 ctx.globalAlpha = 0.15;
842 ctx.beginPath();
843 boundary.forEach(([q, p], i) => (i ? ctx.lineTo(toX(q), toY(p)) : ctx.moveTo(toX(q), toY(p))));
844 ctx.closePath();
845 ctx.fill();
846 ctx.globalAlpha = 1;
847 ctx.strokeStyle = accent;
848 ctx.lineWidth = 1.5;
849 ctx.stroke();
850 for (const [q, p] of interior) ctx.fillRect(toX(q) - 1, toY(p) - 1, 2, 2);
852 areaOut.textContent = area().toFixed(4);
853 }
855 const loop = createLoop({ button: document.getElementById(`${id}-toggle`), step, draw, speed: 0.5 });
857 function reset() {
858 makeDisk();
859 loop.reset();
860 }
862 return { draw, reset, pause: loop.pause };
863}
865// Page 7: the spring, with every block drawn as a point and the spring
866// reaching the block simulated from the disk's center. The disk's radii look
867// round at the default scale.
868const liouvilleSpringK = 4;
869const liouville = createLiouville({
870 id: 'liouville',
871 force: (q) => -liouvilleSpringK * q,
872 m: 1,
873 center: [0.5, 0],
874 radii: [0.15, 0.6],
875 drawDiagram: (ctx, w, h, points, jitter, [centralQ]) => {
876 drawSpringScene(ctx, w, h, centralQ, ({ qToX, floorY, box }) => {
877 ctx.fillStyle = color('--accent');
878 points.forEach(([q], i) => ctx.fillRect(qToX(q) - 1, floorY - 4 - jitter[i] * (box - 8), 2, 2));
879 });
880 },
881 axes: (ctx, w, h) => {
882 const { qToX, pToY } = springAxes(ctx, w, h);
883 return { toX: qToX, toY: pToY };
884 },
885});
887// Page 8: the pendulum, with every bob drawn as a point and the rod pointing
888// at the bob simulated from the disk's center. With m = L = 1, p = dtheta/dt.
889const liouvillePendulumParams = { m: 1, L: 1, g: 9.8 };
890const liouvillePendulum = createLiouville({
891 id: 'liouville-pendulum',
892 force: (theta) => -liouvillePendulumParams.g * Math.sin(theta),
893 m: 1,
894 center: [1.2, 0],
895 radii: [0.35, 3.5],
896 drawDiagram: (ctx, w, h, points, jitter, [centralTheta]) => {
897 const fg = color('--fg');
898 const px = w / 2;
899 const py = 30;
900 const rod = Math.min(h - 80, w * 0.4);
902 ctx.strokeStyle = fg;
903 ctx.lineWidth = 2;
904 ctx.beginPath();
905 ctx.moveTo(px - 50, py);
906 ctx.lineTo(px + 50, py);
907 ctx.stroke();
908 ctx.globalAlpha = 0.3;
909 ctx.setLineDash([4, 4]);
910 ctx.beginPath();
911 ctx.moveTo(px, py);
912 ctx.lineTo(px, py + rod + 28);
913 ctx.stroke();
914 ctx.setLineDash([]);
915 ctx.globalAlpha = 1;
916 ctx.beginPath();
917 ctx.moveTo(px, py);
918 ctx.lineTo(px + (rod - 18) * Math.sin(centralTheta), py + (rod - 18) * Math.cos(centralTheta));
919 ctx.stroke();
921 ctx.fillStyle = color('--accent');
922 points.forEach(([theta], i) => {
923 const r = rod + (jitter[i] - 0.5) * 30;
924 ctx.fillRect(px + r * Math.sin(theta) - 1, py + r * Math.cos(theta) - 1, 2, 2);
925 });
926 },
927 axes: (ctx, w, h) => {
928 const { thetaToX, pToY } = pendulumAxes(ctx, w, h, liouvillePendulumParams);
929 return { toX: thetaToX, toY: pToY };
930 },
931});
933// Page 9: the spring in phase space again, with damping
934const damped = createSpringPhase({ id: 'damped', params: { k: 4, m: 1, q0: 0.6, b: 0.3 }, names: ['q0', 'k', 'm', 'b'] });
936// Double pendulum: rod angles theta1, theta2 from straight down and their
937// momenta p1, p2, as the state z = [theta1, theta2, p1, p2].
938// params: { m1, m2, L1, L2, g } plus the initial state { theta1, theta2, p1, p2 }.
940function doubleKinetic({ m1, m2, L1, L2 }, delta, p1, p2) {
941 const D = m1 + m2 * Math.sin(delta) ** 2;
942 return (m2 * L2 * L2 * p1 * p1 + (m1 + m2) * L1 * L1 * p2 * p2 - 2 * m2 * L1 * L2 * p1 * p2 * Math.cos(delta))
943 / (2 * m2 * L1 * L1 * L2 * L2 * D);
944}
946function doublePotential({ m1, m2, L1, L2, g }, t1, t2) {
947 return -(m1 + m2) * g * L1 * Math.cos(t1) - m2 * g * L2 * Math.cos(t2);
948}
950function doubleEnergy(params, [t1, t2, p1, p2]) {
951 return doubleKinetic(params, t1 - t2, p1, p2) + doublePotential(params, t1, t2);
952}
954// Hamilton's equations, as written in the recipe: the rates of change of
955// (theta1, theta2, p1, p2), written into out.
956function doubleRates(params, t1, t2, p1, p2, out) {
957 const { m1, m2, L1, L2, g } = params;
958 const delta = t1 - t2;
959 const s = Math.sin(delta);
960 const c = Math.cos(delta);
961 const D = m1 + m2 * s * s;
962 const T = doubleKinetic(params, delta, p1, p2);
963 const dTdDelta = (p1 * p2 * s / (L1 * L2) - m2 * T * Math.sin(2 * delta)) / D;
964 out[0] = (L2 * p1 - L1 * p2 * c) / (L1 * L1 * L2 * D);
965 out[1] = ((m1 + m2) * L1 * p2 - m2 * L2 * p1 * c) / (m2 * L1 * L2 * L2 * D);
966 out[2] = -(m1 + m2) * g * L1 * Math.sin(t1) - dTdDelta;
967 out[3] = -m2 * g * L2 * Math.sin(t2) + dTdDelta;
968}
970// One step of the implicit midpoint rule, z' = z + h f((z + z') / 2), solved by
971// fixed-point iteration, updating z in place. It is symplectic, and unlike
972// leapfrog it does not need H to split into a kinetic part in p and a
973// potential part in q (here the kinetic energy depends on the angles too).
974// Allocation-free, since the Liouville slide steps hundreds of these per frame.
975const doubleRate = [0, 0, 0, 0];
976function doubleStep(params, z, h) {
977 const [t1, t2, p1, p2] = z;
978 let a1 = t1;
979 let a2 = t2;
980 let b1 = p1;
981 let b2 = p2;
982 for (let it = 0; it < 20; it++) {
983 doubleRates(params, 0.5 * (t1 + a1), 0.5 * (t2 + a2), 0.5 * (p1 + b1), 0.5 * (p2 + b2), doubleRate);
984 const n1 = t1 + h * doubleRate[0];
985 const n2 = t2 + h * doubleRate[1];
986 const n3 = p1 + h * doubleRate[2];
987 const n4 = p2 + h * doubleRate[3];
988 const change = Math.max(Math.abs(n1 - a1), Math.abs(n2 - a2), Math.abs(n3 - b1), Math.abs(n4 - b2));
989 a1 = n1;
990 a2 = n2;
991 b1 = n3;
992 b2 = n4;
993 if (change < 1e-12) break;
994 }
995 z[0] = wrapAngle(a1);
996 z[1] = wrapAngle(a2);
997 z[2] = b1;
998 z[3] = b2;
999}
1001function wrapAngle(t) {
1002 return t - 2 * Math.PI * Math.round(t / (2 * Math.PI));
1003}
1005function doubleInitial({ theta1, theta2, p1, p2 }) {
1006 return [theta1, theta2, p1, p2];
1007}
1009// A label with a subscript, e.g. m with 1, centered at (x, y). The serif font
1010// has no subscript digits, so the digit is drawn smaller and lower.
1011function subText(ctx, base, sub, x, y) {
1012 const font = 'italic 18px Georgia, serif';
1013 const small = 'italic 12px Georgia, serif';
1014 ctx.font = font;
1015 const bw = ctx.measureText(base).width;
1016 ctx.font = small;
1017 const sw = ctx.measureText(sub).width;
1018 const left = x - (bw + sw + 1) / 2;
1019 const align = ctx.textAlign;
1020 ctx.textAlign = 'left';
1021 ctx.font = font;
1022 ctx.fillText(base, left, y);
1023 ctx.font = small;
1024 ctx.fillText(sub, left + bw + 1, y + 5);
1025 ctx.font = font;
1026 ctx.textAlign = align;
1027}
1029// L1 + L2 at the slider maximums. The rods are drawn to scale, with a total
1030// length of maxLength reaching from the pivot (mid-canvas) to the edge, so
1031// either bob can go over the top.
1032const DOUBLE_REACH = 2.5;
1034// labels: which of 'm', 'L', 'theta', 'g' to draw.
1035function drawDoublePendulum(ctx, w, h, params, [t1, t2], labels, maxLength = DOUBLE_REACH) {
1036 const fg = color('--fg');
1037 const accent = color('--accent');
1038 const { L1, L2 } = params;
1039 const px = w / 2;
1040 const py = h / 2;
1041 const reach = Math.min(h, w) / 2 - 8;
1042 const r = Math.max(9, Math.min(18, reach * 0.1));
1043 const unit = (reach - r) / maxLength;
1044 const x1 = px + unit * L1 * Math.sin(t1);
1045 const y1 = py + unit * L1 * Math.cos(t1);
1046 const x2 = x1 + unit * L2 * Math.sin(t2);
1047 const y2 = y1 + unit * L2 * Math.cos(t2);
1049 // vertical reference through the pivot
1050 ctx.strokeStyle = fg;
1051 ctx.lineWidth = 1;
1052 ctx.globalAlpha = 0.3;
1053 ctx.setLineDash([4, 4]);
1054 ctx.beginPath();
1055 ctx.moveTo(px, py);
1056 ctx.lineTo(px, py + unit * (L1 + L2) + r);
1057 if (labels.includes('theta')) {
1058 // and through the upper bob, for theta2
1059 ctx.moveTo(x1, y1);
1060 ctx.lineTo(x1, y1 + unit * L2 * 0.7);
1061 }
1062 ctx.stroke();
1063 ctx.setLineDash([]);
1064 ctx.globalAlpha = 1;
1066 // rods, pivot and bobs
1067 ctx.lineWidth = 2;
1068 ctx.beginPath();
1069 ctx.moveTo(px, py);
1070 ctx.lineTo(x1, y1);
1071 ctx.lineTo(x2, y2);
1072 ctx.stroke();
1073 ctx.fillStyle = fg;
1074 ctx.beginPath();
1075 ctx.arc(px, py, 4, 0, 2 * Math.PI);
1076 ctx.fill();
1077 ctx.fillStyle = accent;
1078 for (const [bx, by] of [[x1, y1], [x2, y2]]) {
1079 ctx.beginPath();
1080 ctx.arc(bx, by, r, 0, 2 * Math.PI);
1081 ctx.fill();
1082 }
1084 ctx.font = 'italic 18px Georgia, serif';
1085 ctx.textAlign = 'center';
1086 ctx.textBaseline = 'middle';
1088 if (labels.includes('m')) {
1089 ctx.fillStyle = color('--bg');
1090 subText(ctx, 'm', '1', x1, y1);
1091 subText(ctx, 'm', '2', x2, y2);
1092 }
1094 if (labels.includes('L')) {
1095 // beside the middle of each rod, on the side away from the vertical
1096 ctx.fillStyle = fg;
1097 for (const [sub, ax, ay, bx, by, t] of [['1', px, py, x1, y1, t1], ['2', x1, y1, x2, y2, t2]]) {
1098 const side = t >= 0 ? 1 : -1;
1099 subText(ctx, 'L', sub, (ax + bx) / 2 + side * 16 * Math.cos(t), (ay + by) / 2 - side * 16 * Math.sin(t));
1100 }
1101 }
1103 if (labels.includes('theta')) {
1104 // arcs from the vertical to each rod
1105 ctx.strokeStyle = fg;
1106 ctx.fillStyle = fg;
1107 ctx.lineWidth = 1.5;
1108 for (const [sub, cx, cy, t, len] of [['1', px, py, t1, L1], ['2', x1, y1, t2, L2]]) {
1109 const arcR = Math.min(40, unit * len * 0.45);
1110 ctx.beginPath();
1111 ctx.arc(cx, cy, arcR, Math.PI / 2, Math.PI / 2 - t, t > 0);
1112 ctx.stroke();
1113 const mid = Math.PI / 2 - t / 2;
1114 subText(ctx, 'θ', sub, cx + (arcR + 14) * Math.cos(mid), cy + (arcR + 14) * Math.sin(mid));
1115 }
1116 }
1118 if (labels.includes('g')) {
1119 // gravity, pointing down, in the bottom-right corner
1120 const gx = w - 24;
1121 const gy = h - 40;
1122 ctx.strokeStyle = fg;
1123 ctx.fillStyle = fg;
1124 ctx.lineWidth = 1.5;
1125 ctx.beginPath();
1126 ctx.moveTo(gx, gy - 25);
1127 ctx.lineTo(gx, gy + 25);
1128 ctx.stroke();
1129 ctx.beginPath();
1130 ctx.moveTo(gx, gy + 25);
1131 ctx.lineTo(gx - 4, gy + 17);
1132 ctx.lineTo(gx + 4, gy + 17);
1133 ctx.closePath();
1134 ctx.fill();
1135 ctx.fillText('g', gx - 14, gy);
1136 }
1137}
1139// onStep(z) is called after every time step, for recording trails.
1140// maxLength: see drawDoublePendulum; a number, or a function read at each draw.
1141function createDoublePendulum({ canvas, button, params, labels = [], maxLength, onStep = () => {}, onDraw = () => {} }) {
1142 let state = doubleInitial(params);
1144 function step(dt) {
1145 const n = Math.ceil(dt / 0.0025);
1146 for (let i = 0; i < n; i++) doubleStep(params, state, dt / n);
1147 onStep(state);
1148 }
1150 function draw() {
1151 if (!canvas.clientWidth) return;
1152 const { ctx, w, h } = prepare(canvas);
1153 drawDoublePendulum(ctx, w, h, params, state, labels, typeof maxLength === 'function' ? maxLength() : maxLength);
1154 onDraw(state);
1155 }
1157 const loop = createLoop({ button, step, draw });
1159 function setLabels(value) {
1160 labels = value;
1161 draw();
1162 }
1164 // Back to the initial state, held still.
1165 function reset() {
1166 state = doubleInitial(params);
1167 loop.reset();
1168 }
1170 return { draw, setLabels, reset, pause: loop.pause };
1171}
1173// Page 10: the double pendulum, let go with both rods horizontal
1174const doubleDefaults = { m1: 1, m2: 1, L1: 1, L2: 1, g: 9.8 };
1175const doublePendulum = createDoublePendulum({
1176 canvas: document.getElementById('double-canvas'),
1177 button: document.getElementById('double-toggle'),
1178 params: { ...doubleDefaults, theta1: Math.PI / 2, theta2: Math.PI / 2, p1: 0, p2: 0 },
1179 maxLength: doubleDefaults.L1 + doubleDefaults.L2, // lengths are fixed here, so fill the canvas
1180});
1182// Page 11: double pendulum phase space, projected onto the (theta1, p1) and
1183// (theta2, p2) planes. The p axes cover the momentum sliders' range, which the
1184// spinning preset needs; page 12 uses the same axes.
1185const DOUBLE_PMAX = 20;
1187// Draw the theta_k and p_k axes; returns the mapping to canvas coordinates.
1188function doubleAxes(ctx, w, h, k) {
1189 const halfW = w / 2 - 30;
1190 const cx = w / 2;
1191 const mid = h / 2;
1192 const thetaToX = (t) => cx + (t / Math.PI) * halfW;
1193 const pToY = (pv) => mid - (pv / DOUBLE_PMAX) * (h / 2 - 16);
1194 const fg = color('--fg');
1195 ctx.strokeStyle = fg;
1196 ctx.fillStyle = fg;
1197 ctx.globalAlpha = 0.5;
1198 ctx.lineWidth = 1;
1199 ctx.beginPath();
1200 ctx.moveTo(cx - halfW, mid);
1201 ctx.lineTo(cx + halfW, mid);
1202 ctx.moveTo(cx, 8);
1203 ctx.lineTo(cx, h - 8);
1204 ctx.stroke();
1205 ctx.globalAlpha = 1;
1206 ctx.textAlign = 'center';
1207 ctx.textBaseline = 'middle';
1208 subText(ctx, 'θ', String(k), cx + halfW + 16, mid);
1209 subText(ctx, 'p', String(k), cx + 18, 16);
1210 ctx.font = `13px ${color('--font-body')}`;
1211 ctx.textBaseline = 'top';
1212 ctx.fillText('−π', cx - halfW, mid + 6);
1213 ctx.fillText('π', cx + halfW, mid + 6);
1214 return { thetaToX, pToY };
1215}
1217// The trail in the (theta_k, p_k) plane (k = 0 or 1), fading with age and
1218// broken where theta wraps around, then the current state.
1219function drawDoublePlane(canvas, k, trail, state) {
1220 if (!canvas.clientWidth) return;
1221 const { ctx, w, h } = prepare(canvas);
1222 const { thetaToX, pToY } = doubleAxes(ctx, w, h, k + 1);
1223 const accent = color('--accent');
1224 ctx.save();
1225 ctx.beginPath();
1226 ctx.rect(0, 0, w, h);
1227 ctx.clip();
1228 ctx.strokeStyle = accent;
1229 ctx.lineWidth = 1.5;
1230 const chunks = 6;
1231 for (let c = 0; c < chunks; c++) {
1232 const from = Math.floor((trail.length * c) / chunks);
1233 const to = Math.min(trail.length, Math.floor((trail.length * (c + 1)) / chunks) + 1);
1234 ctx.globalAlpha = 0.15 + (0.75 * (c + 1)) / chunks;
1235 ctx.beginPath();
1236 for (let i = from; i < to; i++) {
1237 const z = trail[i];
1238 const x = thetaToX(z[k]);
1239 const y = pToY(z[k + 2]);
1240 if (i === from || Math.abs(z[k] - trail[i - 1][k]) > Math.PI) ctx.moveTo(x, y);
1241 else ctx.lineTo(x, y);
1242 }
1243 ctx.stroke();
1244 }
1245 ctx.restore();
1246 ctx.fillStyle = accent;
1247 ctx.beginPath();
1248 ctx.arc(thetaToX(state[k]), pToY(state[k + 2]), 6, 0, 2 * Math.PI);
1249 ctx.fill();
1250}
1252const doublePresets = {
1253 inphase: { theta1: 0.25, theta2: 0.25 * Math.SQRT2, p1: 0, p2: 0 },
1254 outphase: { theta1: 0.25, theta2: -0.25 * Math.SQRT2, p1: 0, p2: 0 },
1255 small: { theta1: 0.4, theta2: 0, p1: 0, p2: 0 },
1256 large: { theta1: Math.PI / 2, theta2: Math.PI / 2, p1: 0, p2: 0 },
1257 balanced: { theta1: Math.PI - 1e-6, theta2: Math.PI, p1: 0, p2: 0 }, // a tiny nudge, so it falls after a few seconds
1258 spinning: { theta1: 0, theta2: 0, p1: 18, p2: 12 }, // both rods turning together at 6 rad/s
1259 rest: { theta1: 0, theta2: 0, p1: 0, p2: 0 },
1260};
1261const doubleParams = { ...doubleDefaults, ...doublePresets.small };
1262const doublePlanes = [1, 2].map((k) => document.getElementById(`double-plane${k}`));
1263const doubleEnergyOut = document.getElementById('double-energy');
1264let doubleTrail = [];
1266const doublePhaseSim = createDoublePendulum({
1267 canvas: document.getElementById('double-phase-canvas'),
1268 button: document.getElementById('double-phase-toggle'),
1269 params: doubleParams,
1270 // the canvas is short, so fill it: the rods are drawn to scale relative to
1271 // each other, but not across changes of L1 + L2
1272 maxLength: () => doubleParams.L1 + doubleParams.L2,
1273 onStep: (z) => {
1274 doubleTrail.push(z.slice());
1275 if (doubleTrail.length > 36000) doubleTrail = doubleTrail.slice(-24000);
1276 },
1277 onDraw: (z) => {
1278 doublePlanes.forEach((canvas, k) => drawDoublePlane(canvas, k, doubleTrail, z));
1279 const e = doubleEnergy(doubleParams, z);
1280 doubleEnergyOut.textContent = (Math.abs(e) < 0.005 ? 0 : e).toFixed(2);
1281 },
1282});
1284function resetDoublePhase() {
1285 doubleTrail = [];
1286 doublePhaseSim.reset();
1287}
1289const doublePhase = { ...doublePhaseSim, reset: resetDoublePhase };
1291const doublePreset = document.getElementById('double-preset');
1292const doubleInputs = ['theta1', 'theta2', 'p1', 'p2', 'm1', 'm2', 'L1', 'L2', 'g'].map((name) => ({
1293 name,
1294 input: document.getElementById(`double-${name}`),
1295 output: document.getElementById(`double-${name}-value`),
1296}));
1298function syncDoubleInputs() {
1299 for (const { name, input, output } of doubleInputs) {
1300 input.value = doubleParams[name];
1301 output.textContent = doubleParams[name].toFixed(2);
1302 }
1303}
1305for (const { name, input, output } of doubleInputs) {
1306 input.addEventListener('input', () => {
1307 doubleParams[name] = Number(input.value);
1308 output.textContent = doubleParams[name].toFixed(2);
1309 doublePreset.value = 'custom';
1310 resetDoublePhase();
1311 });
1312}
1314// A preset restores the default masses, lengths and g along with its initial state.
1315doublePreset.addEventListener('change', () => {
1316 const preset = doublePresets[doublePreset.value];
1317 if (!preset) return;
1318 Object.assign(doubleParams, doubleDefaults, preset);
1319 syncDoubleInputs();
1320 resetDoublePhase();
1321});
1322syncDoubleInputs();
1324// Page 12: Liouville's theorem for the double pendulum. A small 4D ball of
1325// starting points around a preset state disperses; it is shown projected onto
1326// the (theta1, p1) and (theta2, p2) planes, with every pendulum's bobs drawn
1327// as points.
1329// The pivot, rods for the central simulation (started from the ball's
1330// center), and every pendulum's two bobs as points.
1331function drawDoubleCloud(ctx, w, h, params, points, [t1, t2]) {
1332 const fg = color('--fg');
1333 const { L1, L2 } = params;
1334 const px = w / 2;
1335 const py = h / 2;
1336 const unit = (Math.min(h, w) / 2 - 8) / (L1 + L2);
1337 const x1 = px + unit * L1 * Math.sin(t1);
1338 const y1 = py + unit * L1 * Math.cos(t1);
1340 ctx.strokeStyle = fg;
1341 ctx.lineWidth = 1;
1342 ctx.globalAlpha = 0.3;
1343 ctx.setLineDash([4, 4]);
1344 ctx.beginPath();
1345 ctx.moveTo(px, py);
1346 ctx.lineTo(px, py + unit * (L1 + L2));
1347 ctx.stroke();
1348 ctx.setLineDash([]);
1349 ctx.globalAlpha = 1;
1350 ctx.lineWidth = 2;
1351 ctx.beginPath();
1352 ctx.moveTo(px, py);
1353 ctx.lineTo(x1, y1);
1354 ctx.lineTo(x1 + unit * L2 * Math.sin(t2), y1 + unit * L2 * Math.cos(t2));
1355 ctx.stroke();
1356 ctx.fillStyle = fg;
1357 ctx.beginPath();
1358 ctx.arc(px, py, 4, 0, 2 * Math.PI);
1359 ctx.fill();
1361 ctx.fillStyle = color('--accent');
1362 for (const [a1, a2] of points) {
1363 const bx = px + unit * L1 * Math.sin(a1);
1364 const by = py + unit * L1 * Math.cos(a1);
1365 ctx.fillRect(bx - 1, by - 1, 2, 2);
1366 ctx.fillRect(bx + unit * L2 * Math.sin(a2) - 1, by + unit * L2 * Math.cos(a2) - 1, 2, 2);
1367 }
1368}
1370function createDoubleLiouville() {
1371 const id = 'liouville-double';
1372 const diagram = document.getElementById(`${id}-diagram`);
1373 const planes = [1, 2].map((k) => document.getElementById(`${id}-plane${k}`));
1374 const preset = document.getElementById(`${id}-preset`);
1375 const params = { ...doubleDefaults };
1376 // half-widths of the ball in theta1, theta2, p1, p2; roughly round on screen
1377 const radii = [0.2, 0.2, 1.2, 1.2];
1378 let points;
1379 let central;
1381 function makeCloud() {
1382 const center = doubleInitial(doublePresets[preset.value]);
1383 central = center.slice();
1384 points = [];
1385 while (points.length < 600) {
1386 const u = [0, 1, 2, 3].map(() => 2 * Math.random() - 1);
1387 if (u.reduce((sum, v) => sum + v * v, 0) > 1) continue;
1388 const z = center.map((c, i) => c + radii[i] * u[i]);
1389 z[0] = wrapAngle(z[0]);
1390 z[1] = wrapAngle(z[1]);
1391 points.push(z);
1392 }
1393 }
1394 makeCloud();
1396 function step(dt) {
1397 const n = Math.ceil(dt / 0.0025);
1398 for (const z of [central, ...points]) {
1399 for (let i = 0; i < n; i++) doubleStep(params, z, dt / n);
1400 }
1401 }
1403 function draw() {
1404 if (!diagram.clientWidth) return;
1405 const d = prepare(diagram);
1406 drawDoubleCloud(d.ctx, d.w, d.h, params, points, central);
1407 const accent = color('--accent');
1408 planes.forEach((canvas, k) => {
1409 const { ctx, w, h } = prepare(canvas);
1410 const { thetaToX, pToY } = doubleAxes(ctx, w, h, k + 1);
1411 ctx.save();
1412 ctx.beginPath();
1413 ctx.rect(0, 0, w, h);
1414 ctx.clip();
1415 ctx.fillStyle = accent;
1416 for (const z of points) ctx.fillRect(thetaToX(z[k]) - 1, pToY(z[k + 2]) - 1, 2, 2);
1417 ctx.restore();
1418 });
1419 }
1421 const loop = createLoop({ button: document.getElementById(`${id}-toggle`), step, draw, speed: 0.5 });
1423 function reset() {
1424 makeCloud();
1425 loop.reset();
1426 }
1428 preset.addEventListener('change', reset);
1430 return { draw, reset, pause: loop.pause };
1431}
1433const liouvilleDouble = createDoubleLiouville();
1435const sims = {
1436 spring, energy, phase, pendulum, 'pendulum-phase': pendulumPhase, liouville, 'liouville-pendulum': liouvillePendulum, damped,
1437 double: doublePendulum, 'double-phase': doublePhase, 'liouville-double': liouvilleDouble,
1438};
1440// Reset buttons next to Start: back to the initial state, with trails cleared.
1441const resets = {
1442 'pendulum-phase': resetPendulumPhase,
1443};
1444for (const [name, sim] of Object.entries(sims)) {
1445 document.getElementById(`${name}-reset`).addEventListener('click', resets[name] ?? sim.reset);
1446}
1448const pages = [...document.querySelectorAll('.page')];
1449const pageIds = pages.map((p) => p.id);
1450const navPrev = document.getElementById('nav-prev');
1451const navNext = document.getElementById('nav-next');
1452const navPos = document.getElementById('nav-pos');
1454// Flatiron logo on every slide.
1455pages.forEach((p) => {
1456 const img = document.createElement('img');
1457 img.className = 'logo';
1458 img.alt = 'Flatiron Institute';
1459 img.src = 'assets/flatiron-logo.png';
1460 p.appendChild(img);
1461});
1463// Table of contents: the slide counter in the nav bar opens a list of slide
1464// titles; T toggles it and Escape closes it.
1465const toc = document.getElementById('toc');
1466const tocList = document.getElementById('toc-list');
1468pages.forEach((p) => {
1469 const li = document.createElement('li');
1470 const b = document.createElement('button');
1471 b.textContent = p.querySelector('h1, h2').textContent;
1472 b.addEventListener('click', () => {
1473 location.hash = p.id;
1474 setTocOpen(false);
1475 });
1476 li.appendChild(b);
1477 tocList.appendChild(li);
1478});
1480function setTocOpen(open) {
1481 toc.hidden = !open;
1482 navPos.setAttribute('aria-expanded', String(open));
1483 if (open) tocList.querySelector('.current')?.scrollIntoView({ block: 'nearest' });
1484}
1486navPos.addEventListener('click', (e) => {
1487 e.stopPropagation();
1488 setTocOpen(toc.hidden);
1489});
1490document.addEventListener('click', (e) => {
1491 if (!toc.hidden && !toc.contains(e.target)) setTocOpen(false);
1492});
1494function show(id) {
1495 pages.forEach((p) => p.classList.toggle('active', p.id === id));
1496 const i = pageIds.indexOf(id);
1497 const prev = pages[i - 1];
1498 const next = pages[i + 1];
1499 // label each button with a one-word hint of where it goes
1500 navPrev.textContent = prev ? `← ${prev.dataset.hint}` : '←';
1501 navNext.textContent = next ? `${next.dataset.hint} →` : '→';
1502 navPrev.disabled = !prev;
1503 navNext.disabled = !next;
1504 navPos.textContent = `${i + 1} / ${pages.length} \u2630`;
1505 tocList.querySelectorAll('button').forEach((b, j) => b.classList.toggle('current', j === i));
1506 for (const [name, sim] of Object.entries(sims)) {
1507 if (name === id) sim.draw();
1508 else sim.pause();
1509 }
1510}
1512// Scale the 1920 x 1080 deck to the largest size that fits, centered, and
1513// redraw the visible diagram at the new resolution.
1514const SLIDE_W = 1920;
1515const SLIDE_H = 1080;
1516const MARGIN = 16;
1517const stage = document.querySelector('main');
1518const deck = document.getElementById('deck');
1520function fitDeck() {
1521 stage.style.bottom = `${document.querySelector('.pager').offsetHeight}px`;
1522 const w = stage.clientWidth;
1523 const h = stage.clientHeight;
1524 deckScale = Math.min((w - 2 * MARGIN) / SLIDE_W, (h - 2 * MARGIN) / SLIDE_H);
1525 deck.style.transform = `scale(${deckScale})`;
1526 deck.style.left = `${(w - SLIDE_W * deckScale) / 2}px`;
1527 deck.style.top = `${(h - SLIDE_H * deckScale) / 2}px`;
1528 const active = document.querySelector('.page.active');
1529 if (active) sims[active.id]?.draw();
1530}
1532window.addEventListener('resize', fitDeck);
1533// Canvas text uses the bundled fonts, so redraw once they have loaded.
1534document.fonts?.ready.then(fitDeck);
1536document.querySelectorAll('[data-tex]').forEach((el) => {
1537 katex.render(el.dataset.tex, el, { displayMode: el.tagName === 'DIV' });
1538});
1540document.querySelectorAll('[data-solution]').forEach((toggle) => {
1541 toggle.addEventListener('click', () => {
1542 const solution = document.getElementById(toggle.dataset.solution);
1543 solution.hidden = !solution.hidden;
1544 toggle.textContent = solution.hidden ? 'Show solution' : 'Hide solution';
1545 });
1546});
1548// Pages that start centered: revealing splits them into text and diagram
1549// panels and labels the diagram.
1550const revealLabels = {
1551 spring: ['m', 'k', 'q', 'F', 'p'],
1552 energy: [], // stays unlabeled, so the bars are the only thing moving
1553 pendulum: ['m', 'L', 'theta', 'p', 'g'],
1554 double: ['m', 'L', 'theta', 'g'],
1555};
1557document.querySelectorAll('[data-reveal]').forEach((button) => {
1558 button.addEventListener('click', () => {
1559 const id = button.dataset.reveal;
1560 const section = document.getElementById(id);
1561 button.hidden = true;
1562 section.classList.add('split');
1563 section.querySelector('.text').hidden = false;
1564 sims[id].setLabels(revealLabels[id]);
1565 });
1566});
1568// Replay of how recipe.md was written, from app/crafted-link.js (npm run crafted-link).
1569if (window.CRAFTED_LINK) {
1570 const link = document.getElementById('crafted-link');
1571 link.href = window.CRAFTED_LINK;
1572 link.hidden = false;
1573}
1575// The current page lives in the URL hash, so reloading stays put.
1576function showFromHash() {
1577 const id = location.hash.slice(1);
1578 show(document.getElementById(id)?.classList.contains('page') ? id : 'landing');
1579 window.scrollTo(0, 0);
1580}
1582window.addEventListener('hashchange', showFromHash);
1583fitDeck();
1584showFromHash();
1586document.querySelectorAll('[data-goto]').forEach((el) => {
1587 el.addEventListener('click', () => {
1588 location.hash = el.dataset.goto;
1589 });
1590});
1592function goToIndex(i) {
1593 location.hash = pageIds[Math.max(0, Math.min(pageIds.length - 1, i))];
1594}
1596function currentIndex() {
1597 return pageIds.indexOf(document.querySelector('.page.active').id);
1598}
1600navPrev.addEventListener('click', () => goToIndex(currentIndex() - 1));
1601navNext.addEventListener('click', () => goToIndex(currentIndex() + 1));
1603document.addEventListener('keydown', (e) => {
1604 if (e.altKey || e.ctrlKey || e.metaKey) return;
1605 if (e.target.closest?.('input, select, textarea')) return; // arrow keys belong to the control
1606 if (e.key === 't' || e.key === 'T') {
1607 setTocOpen(toc.hidden);
1608 return;
1609 }
1610 if (e.key === 'Escape' && !toc.hidden) {
1611 setTocOpen(false);
1612 return;
1613 }
1614 const target = {
1615 ArrowLeft: currentIndex() - 1,
1616 ArrowRight: currentIndex() + 1,
1617 Home: 0,
1618 End: pageIds.length - 1,
1619 }[e.key];
1620 if (target === undefined) return;
1621 e.preventDefault();
1622 goToIndex(target);
1623});