1// The background portrait of the section (grey), plus optional "tracks": the orbit each live
2// pendulum is on at the moment the portrait was computed, drawn in the pendulum's color.
3// Both are computed at frozen energy in a throttled worker (see orbitWorker.ts); when the energy
4// has moved enough, a new portrait starts and the old one crossfades out.
6import type { OrbitBatch, OrbitConfig, TrackSeed } from "./orbitWorker.ts";
7import type { SectionFrame } from "./section.ts";
9export interface PortraitSettings {
10 show: boolean;
11 count: number;
12 cpu: number;
13 life: number;
14 band: number;
15 minHold: number;
16 maxPoints: number;
17 xfade: number;
18 alpha: number;
19 size: number;
20 /** trace each live pendulum's current orbit */
21 tracks: boolean;
22 trackMax: number;
23 trackAlpha: number;
24 trackSize: number;
25}
27interface Portrait {
28 gen: number;
29 energy: number;
30 pts: number[]; // [θ2, p2, …]
31 tracks: Map<number, number[]>;
32 retiredAt: number | null;
33}
35export class PortraitLayer {
36 private worker: Worker | null = null;
37 private portraits: Portrait[] = [];
38 private resetPending = false;
39 private latestGen = 0;
40 private ignoreBelow = 0; // batches from portraits started before the last reset
41 private rate = 0; // points per second, for the readout
42 private newPts = 0;
43 private rateT = 0;
44 private now: () => number;
45 private live: () => boolean;
47 /** now: piece time; live: whether the piece is playing (batches are ignored otherwise) */
48 constructor(now: () => number, live: () => boolean) {
49 this.now = now;
50 this.live = live;
51 }
53 /** New play or seek: drop what's shown; the worker starts a fresh portrait. */
54 reset() {
55 this.portraits = [];
56 this.ignoreBelow = this.latestGen + 1;
57 this.resetPending = true;
58 }
60 private ensureWorker(): Worker {
61 if (!this.worker) {
62 this.worker = new Worker(new URL("./orbitWorker.ts", import.meta.url), { type: "module" });
63 this.worker.onmessage = (ev: MessageEvent<OrbitBatch>) => this.receive(ev.data);
64 }
65 return this.worker;
66 }
68 private receive({ gen, energy, pts, tracks }: OrbitBatch) {
69 if (!this.live()) return;
70 this.latestGen = Math.max(this.latestGen, gen);
71 if (gen < this.ignoreBelow) return;
72 let cur = this.portraits[this.portraits.length - 1];
73 if (!cur || gen > cur.gen) {
74 const t = this.now();
75 for (const p of this.portraits) p.retiredAt ??= t;
76 cur = { gen, energy, pts: [], tracks: new Map(), retiredAt: null };
77 this.portraits.push(cur);
78 } else if (gen < cur.gen) return; // stale batch
79 for (let i = 0; i < pts.length; i++) cur.pts.push(pts[i]);
80 for (const tb of tracks) {
81 let arr = cur.tracks.get(tb.id);
82 if (!arr) cur.tracks.set(tb.id, (arr = []));
83 for (let i = 0; i < tb.pts.length; i++) arr.push(tb.pts[i]);
84 }
85 this.newPts += pts.length / 2 + tracks.reduce((s, tb) => s + tb.pts.length / 2, 0);
86 }
88 /** Send the current state; call every tick while playing (running=false pauses the worker). */
89 post(running: boolean, s: PortraitSettings, energy: number, m2: number, l2: number, tracks: TrackSeed[]) {
90 if (!s.show && !s.tracks && !this.worker) return;
91 const msg: OrbitConfig = {
92 running: running && (s.show || s.tracks),
93 reset: this.resetPending,
94 energy,
95 m2,
96 l2,
97 count: s.show ? Math.round(s.count) : 0,
98 life: s.life,
99 band: s.band,
100 minHold: s.minHold,
101 maxPoints: s.show ? s.maxPoints : 0,
102 cpu: s.cpu,
103 tracks: s.tracks ? tracks : [],
104 trackMax: s.trackMax,
105 };
106 this.resetPending = false;
107 this.ensureWorker().postMessage(msg);
108 }
110 /** Draw the grey portrait and the colored tracks (call before drawing the live crossings). */
111 draw(f: SectionFrame, t: number, s: PortraitSettings, grey: string, trackColor: (id: number) => string) {
112 const { g, sx, sy } = f;
113 this.portraits = this.portraits.filter((p) => p.retiredAt === null || t - p.retiredAt < s.xfade);
114 for (const p of this.portraits) {
115 const k = p.retiredAt === null ? 1 : Math.max(0, 1 - (t - p.retiredAt) / s.xfade);
116 if (s.show && p.pts.length) {
117 const sz = s.size;
118 g.fillStyle = grey;
119 g.globalAlpha = s.alpha * k;
120 g.beginPath();
121 const d = p.pts;
122 for (let i = 0; i < d.length; i += 2) g.rect(sx(d[i]) - sz / 2, sy(d[i + 1]) - sz / 2, sz, sz);
123 g.fill();
124 }
125 if (s.tracks) {
126 const sz = s.trackSize;
127 for (const [id, d] of p.tracks) {
128 g.fillStyle = trackColor(id);
129 g.globalAlpha = s.trackAlpha * k;
130 g.beginPath();
131 for (let i = 0; i < d.length; i += 2) g.rect(sx(d[i]) - sz / 2, sy(d[i + 1]) - sz / 2, sz, sz);
132 g.fill();
133 }
134 }
135 }
136 g.globalAlpha = 1;
137 }
139 describe(): string {
140 const wall = performance.now() / 1000;
141 if (wall - this.rateT > 1) {
142 this.rate = this.newPts / (wall - this.rateT || 1);
143 this.newPts = 0;
144 this.rateT = wall;
145 }
146 const p = this.portraits.find((q) => q.retiredAt === null);
147 if (!p) return "–";
148 const tr = [...p.tracks.values()].reduce((s, a) => s + a.length / 2, 0);
149 return `E ${p.energy.toFixed(4)}, ${p.pts.length / 2} pts${p.tracks.size ? ` + ${tr} traced` : ""}, ${Math.round(this.rate)}/s`;
150 }
152 dispose() {
153 this.worker?.terminate();
154 this.worker = null;
155 }
156}