/ proof-of-concept / toy-instruments
Sign in
proof-of-concept / toy-instruments
toy-instruments / src / ui / instrumentPage.ts
521 lines · 23.5 KBCodeBlameHistory
2cd36faBead drum: hex-lattice round head, felt mallet contact, top view and cross-section; shared instrument pageJeremy Magland 1import { renderControls, type Section } from './controls';
2import { LinePlot, css, fmtNum, type Marker } from './plot';
3import { Spectrogram } from './spectrogram';
4import { spectrum } from './fft';
5import { encodeWav } from './wav';
6import { BeadScene, type SceneSpec } from './scene3d';
7import { Timeline } from './timeline';
a78afe0Add WebGPU solver with a toggle; faster CPU solverJeremy Magland 8import { timeStep } from '../sim/solver';
10import { checkPasscode, getPasscode, loadResult, probeResult, resultKey, setPasscode, storeResult, type Backend } from '../sim/cache';
2cd36faBead drum: hex-lattice round head, felt mallet contact, top view and cross-section; shared instrument pageJeremy Magland 11import type { BeadSystem, Excitation, SimResult } from '../sim/types';
13// The page every instrument shares: presets and control panel, 3D model,
14// setup summary, run summary, audio, waveform, spectrogram, spectrum, energy.
15// An instrument adds its own setup rows, extra result cards and views.
17export interface SimParams {
18 duration: number;
19 fs: number;
20 cfl: number;
21 frameRate: number;
24export interface Built {
25 sys: BeadSystem;
26 exc: Excitation;
27 pickup: Float64Array;
32export interface Preset<P> {
33 name: string;
34 description: string;
35 params: P;
38export interface Extras<P> {
39 show(p: P, built: Built, r: SimResult): void;
42export interface InstrumentConfig<P extends SimParams> {
43 title: string;
44 wavName: string;
c696b9aCymbal: plate bending via per-triangle shape operators, felt centre support, stick and mallet with angle and friction, far-field microphoneJeremy Magland 45 audioQuantity?: { label: string; unit: string }; // default: acceleration, m/s²
47 sections: Section<P>[];
a78afe0Add WebGPU solver with a toggle; faster CPU solverJeremy Magland 48 // WebGPU on by default (default true); off where the systems are too small to gain from it
49 webgpuDefault?: boolean;
2cd36faBead drum: hex-lattice round head, felt mallet contact, top view and cross-section; shared instrument pageJeremy Magland 50 // instrument-specific summary of the setup; built = null when the parameters are invalid
51 setup(p: P): { rows: [string, string][]; warnings: string[]; built: Built | null };
52 summaryRows?(p: P, built: Built, r: SimResult): [string, string][];
53 spectrumMarkers?(p: P): { markers: Marker[]; legend: string };
54 extraCards?: string; // cards with data-r="out" hidden, shown after a run
55 mountExtras?(q: <T extends HTMLElement>(r: string) => T, timeline: Timeline): Extras<P>;
58const statRows = (rows: [string, string][]) => rows.map(([k, v]) => `<div><span>${k}</span><b>${v}</b></div>`).join('');
60export function mountInstrumentPage<P extends SimParams>(root: HTMLElement, cfg: InstrumentConfig<P>) {
61 root.innerHTML = `
62 <div class="instrument">
63 <aside class="panel">
64 <a href="#/" class="back">← All instruments</a>
65 <h1>${cfg.title}</h1>
66 <label class="ctl preset"><span class="ctl-name">Preset</span><select data-r="preset"></select></label>
67 <p class="sub" data-r="preset-desc"></p>
2cd36faBead drum: hex-lattice round head, felt mallet contact, top view and cross-section; shared instrument pageJeremy Magland 69 <button class="btn" data-r="run">Run simulation</button>
70 <button class="btn-small" data-r="cancel" hidden>Cancel</button>
b51a77aShared result cache on artifact-cache: offer a cached result for the current settings next to Run; store runs when a passcode is setJeremy Magland 71 <button class="btn-small" data-r="load-cached" hidden>Load cached</button>
a78afe0Add WebGPU solver with a toggle; faster CPU solverJeremy Magland 72 <label class="inline gpu-toggle" data-r="gpu-label"><input type="checkbox" data-r="gpu"> WebGPU</label>
2cd36faBead drum: hex-lattice round head, felt mallet contact, top view and cross-section; shared instrument pageJeremy Magland 75 <progress data-r="progress" max="1" value="0" hidden></progress>
76 <p class="error" data-r="error" hidden></p>
78 <summary data-r="cache-state"></summary>
79 <p class="note">Results are shared: when someone has already computed a run with these settings, you can load it instead of running it again. With the passcode, this browser also stores its runs there.</p>
80 <div class="cache-form"><input type="password" data-r="cache-pass" placeholder="Passcode" autocomplete="off"><button class="btn-small" data-r="cache-save">Save</button><button class="btn-small" data-r="cache-forget">Forget</button></div>
81 <p class="note" data-r="cache-msg"></p>
82 </details>
85 <main class="results">
86 <section class="card"><h2>Model</h2><div data-r="scene"></div></section>
87 <section class="card"><h2>Setup</h2><div data-r="derived" class="stats"></div><ul data-r="warnings" class="warnings"></ul></section>
88 <section class="card" data-r="out" hidden>
89 <h2>Run</h2><div data-r="summary" class="stats"></div>
2cd36faBead drum: hex-lattice round head, felt mallet contact, top view and cross-section; shared instrument pageJeremy Magland 91 <div class="audio-row"><audio controls data-r="audio"></audio><a class="btn-small" data-r="download" download="${cfg.wavName}">Download .wav</a></div>
92 <p class="note" data-r="audio-note"></p>
93 </section>
94 <section class="card" data-r="out" hidden>
c696b9aCymbal: plate bending via per-triangle shape operators, felt centre support, stick and mallet with angle and friction, far-field microphoneJeremy Magland 95 <div class="card-head"><h2>${cap((cfg.audioQuantity ?? { label: 'pickup acceleration' }).label)}</h2>
2cd36faBead drum: hex-lattice round head, felt mallet contact, top view and cross-section; shared instrument pageJeremy Magland 96 <div class="seg" data-r="wave-range"><button data-v="0" class="on">Full</button><button data-v="0.05">First 50 ms</button><button data-v="0.005">First 5 ms</button></div></div>
97 <div class="canvas-wrap"><canvas data-r="wave"></canvas></div>
98 </section>
99 <section class="card" data-r="out" hidden>
100 <div class="card-head"><h2>Spectrogram</h2>
101 <label class="inline">up to <select data-r="fmax"><option>1000</option><option>2500</option><option selected>5000</option><option>10000</option><option>24000</option></select> Hz</label></div>
102 <div class="canvas-wrap tall"><canvas data-r="spec"></canvas></div>
103 </section>
104 <section class="card" data-r="out" hidden>
105 <div class="card-head"><h2>Spectrum</h2><div class="legend" data-r="spec-legend"></div></div>
106 <div class="canvas-wrap"><canvas data-r="spectrum"></canvas></div>
107 </section>
108 ${cfg.extraCards ?? ''}
110 <h2>Contact force</h2>
111 <div class="canvas-wrap short"><canvas data-r="contact"></canvas></div>
112 <p class="note" data-r="contact-note"></p>
113 </section>
115 <h2>Energy</h2>
116 <div class="canvas-wrap short"><canvas data-r="energy"></canvas></div>
117 <p class="note">Kinetic plus spring energy of the instrument, minus the energy stored by pre-tension at equilibrium. Without damping or forcing it stays flat; the run summary gives the error of the energy balance (energy + dissipated − work in − initial, mallet included).</p>
118 </section>
119 </main>
120 </div>`;
121 const q = <T extends HTMLElement>(r: string) => root.querySelector(`[data-r="${r}"]`) as T;
122 const presetSel = q<HTMLSelectElement>('preset');
123 cfg.presets.forEach((p, i) => presetSel.add(new Option(p.name, String(i))));
124 const presetDesc = q<HTMLParagraphElement>('preset-desc');
125 const runBtn = q<HTMLButtonElement>('run');
126 const cancelBtn = q<HTMLButtonElement>('cancel');
127 const progress = q<HTMLProgressElement>('progress');
128 const errorBox = q<HTMLParagraphElement>('error');
a78afe0Add WebGPU solver with a toggle; faster CPU solverJeremy Magland 129 const gpuBox = q<HTMLInputElement>('gpu');
131 const availNote = q<HTMLParagraphElement>('cached-avail');
132 const cacheNote = q<HTMLParagraphElement>('cache-note');
133 const instrumentId = cfg.wavName.replace(/\.wav$/, ''); // e.g. bead-cymbal
a78afe0Add WebGPU solver with a toggle; faster CPU solverJeremy Magland 134 const hasGpu = 'gpu' in navigator;
135 const gpuKey = `toy-instruments.webgpu.${cfg.wavName}`;
136 let gpuPref: string | null = null;
137 try {
138 gpuPref = localStorage.getItem(gpuKey);
139 } catch {
140 /* storage unavailable */
141 }
142 gpuBox.checked = hasGpu && (gpuPref ? gpuPref === 'on' : cfg.webgpuDefault !== false);
143 gpuBox.disabled = !hasGpu;
144 q('gpu-label').title = hasGpu
145 ? 'Run the solver on the GPU (single precision). Faster for meshes of a few hundred beads or more; slower for small systems. Falls back to the CPU if the GPU cannot run it.'
146 : 'This browser does not offer WebGPU; the solver runs on the CPU.';
147 gpuBox.addEventListener('change', () => {
148 try {
149 localStorage.setItem(gpuKey, gpuBox.checked ? 'on' : 'off');
150 } catch {
151 /* storage unavailable */
152 }
156 const wave = new LinePlot(q('wave'));
157 const spec = new Spectrogram(q('spec'));
158 const specPlot = new LinePlot(q('spectrum'));
159 const energyPlot = new LinePlot(q('energy'));
161 const quantity = cfg.audioQuantity ?? { label: 'acceleration', unit: 'm/s²' };
163 const scene = new BeadScene(q('scene'), timeline);
164 const extras = cfg.mountExtras?.(q, timeline);
165 let waveRange = 0;
166 let last: { p: P; r: SimResult } | null = null;
b51a77aShared result cache on artifact-cache: offer a cached result for the current settings next to Run; store runs when a passcode is setJeremy Magland 167 let cancelRun: (() => void) | null = null; // set while a run (or a cache download) is in progress
168 // the cached result for the current settings, if there is one
169 let cached: { p: P; built: Built; key: string; stored?: Date } | null = null;
170 let probeSeq = 0;
171 let probeTimer = 0;
87d896eShow partial results while a run is in progress: plots, replay and audio update every 2 s (CPU and WebGPU); a cancelled run keeps its last partial resultJeremy Magland 173 let pendingAudio: Blob | null = null; // a newer partial result's audio, held back while the player plays
175 const controls = renderControls(q('controls'), cfg.sections, cfg.presets[0].params, () => updateSetup());
176 presetDesc.textContent = cfg.presets[0].description;
177 presetSel.addEventListener('change', () => {
178 const pr = cfg.presets[Number(presetSel.value)];
179 presetDesc.textContent = pr.description;
180 controls.set(pr.params);
181 });
183 function updateSetup() {
184 const p = controls.get();
185 const { rows, warnings, built } = cfg.setup(p);
186 if (built) {
187 scene.showSetup(built.scene);
a78afe0Add WebGPU solver with a toggle; faster CPU solverJeremy Magland 188 const { omegaMax: wmax, stepsPerSample: spp } = timeStep(built.sys, built.exc.mallet, p.fs, p.cfl);
189 rows.push(['Highest frequency', `${fmtNum(wmax / (2 * Math.PI))} Hz`]);
2cd36faBead drum: hex-lattice round head, felt mallet contact, top view and cross-section; shared instrument pageJeremy Magland 190 rows.push(['Time step', `${fmtNum(1 / (p.fs * spp))} s (${spp} per sample)`]);
192 const elements = built.sys.si.length + 4 * (built.sys.bending?.w0.length ?? 0);
193 const work = spp * p.fs * p.duration * elements;
194 rows.push(['Element updates', fmtNum(work)]);
2cd36faBead drum: hex-lattice round head, felt mallet contact, top view and cross-section; shared instrument pageJeremy Magland 195 const frameMB = (Math.round(p.duration * p.frameRate) * 3 * built.sys.n * 4) / 1e6;
196 if (frameMB > 400) warnings.push(`Replay frames would take ${fmtNum(frameMB)} MB; lower the replay frame rate or the duration.`);
a78afe0Add WebGPU solver with a toggle; faster CPU solverJeremy Magland 197 if (work > 3e9) warnings.push(`This run is large (${fmtNum(work)} element updates): expect roughly ${fmtNum(work / 2.2e7 / 60)} min on a desktop CPU (WebGPU is usually much faster).`);
199 q('derived').innerHTML = statRows(rows);
200 q('warnings').innerHTML = warnings.map((w) => `<li>${w}</li>`).join('');
202 checkCache();
203 }
205 // what the solver gets for parameters p; null when they are invalid
206 function inputs(p: P) {
207 const { built } = cfg.setup(p);
208 if (!built) return null;
209 const opt = { duration: p.duration, fs: p.fs, cfl: p.cfl, frameRate: p.frameRate, pickup: built.pickup, pickupDelay: built.pickupDelay };
210 return { built, opt, backend: (gpuBox.checked ? 'gpu' : 'cpu') as Backend };
211 }
213 // Look up (debounced) whether the shared cache has a result for the current settings,
214 // and offer to load it next to Run.
215 function checkCache() {
216 const seq = ++probeSeq;
217 cached = null;
218 loadBtn.hidden = availNote.hidden = true;
219 clearTimeout(probeTimer);
220 probeTimer = window.setTimeout(async () => {
221 const p = controls.get();
222 const inp = inputs(p);
223 if (!inp) return;
224 try {
225 const key = await resultKey(instrumentId, inp.built.sys, inp.built.exc, inp.opt, inp.backend);
226 const hit = await probeResult(key);
227 if (seq !== probeSeq || !hit) return;
228 cached = { p, built: inp.built, key, stored: hit.stored };
229 const when = hit.stored ? `computed ${hit.stored.toISOString().slice(0, 10)}, ` : '';
230 availNote.textContent = `A cached result exists for these settings (${when}${fmtNum(hit.bytes / 1e6)} MB). Load it, or run the simulation again.`;
231 loadBtn.hidden = availNote.hidden = false;
232 loadBtn.disabled = !!cancelRun;
233 } catch {
234 /* cache unreachable: just don't offer it */
235 }
236 }, 250);
238 updateSetup();
240 q('wave-range').addEventListener('click', (e) => {
241 const b = (e.target as HTMLElement).closest('button');
242 if (!b) return;
243 waveRange = Number(b.dataset.v);
244 q('wave-range').querySelectorAll('button').forEach((x) => x.classList.toggle('on', x === b));
245 drawWave();
246 });
247 q<HTMLSelectElement>('fmax').addEventListener('change', (e) => {
248 spec.fmax = Number((e.target as HTMLSelectElement).value);
249 spec.draw();
250 drawSpectrum();
251 });
253 function drawWave() {
254 if (!last) return;
257 for (let i = 0; i < t.length; i++) t[i] = i / r.fs;
258 wave.set([{ x: t, y: r.audio, color: css('--series-1'), label: 'a' }], {
259 xLabel: 'time (s)',
262 xRange: [0, waveRange ? Math.min(waveRange, p.duration) : Math.max(p.duration, t[t.length - 1])],
264 }
266 function drawSpectrum() {
267 if (!last) return;
268 const { p, r } = last;
269 const s = spectrum(r.audio, r.fs);
270 let top = -Infinity;
271 for (const v of s.db) top = Math.max(top, v);
272 const db = s.db.map((v) => Math.max(v - top, -100));
273 const m = cfg.spectrumMarkers?.(p);
274 q('spec-legend').innerHTML =
275 `<span><i class="sw" style="background:var(--series-1)"></i>pickup signal</span>` + (m?.legend ?? '');
276 specPlot.set([{ x: s.freq, y: db, color: css('--series-1'), label: 'level (dB)' }], {
277 xLabel: 'frequency (Hz)',
278 yLabel: 'level (dB re max)',
279 xRange: [0, Math.min(spec.fmax, r.fs / 2)],
280 yRange: [-100, 5],
281 markers: m?.markers,
282 });
283 }
286 // extends the result already shown (same run), so the replay position, the
287 // exaggeration and the audio player's position are kept.
288 function show(p: P, built: Built, r: SimResult, partial = false, update = false) {
291 cacheNote.textContent = partial
292 ? `Partial result: ${fmtNum(simulated)} s of ${fmtNum(p.duration)} s simulated so far. It updates every few seconds while the run continues; the audio player picks up the newer sound when it is paused.`
293 : '';
2cd36faBead drum: hex-lattice round head, felt mallet contact, top view and cross-section; shared instrument pageJeremy Magland 294 root.querySelectorAll<HTMLElement>('[data-r="out"]').forEach((e) => (e.hidden = false));
295 let peak = 0;
296 for (const v of r.audio) peak = Math.max(peak, Math.abs(v));
297 const emax = Math.max(...r.energy);
298 let bal = 0;
299 for (const b of r.balance) bal = Math.max(bal, Math.abs(b));
87d896eShow partial results while a run is in progress: plots, replay and audio update every 2 s (CPU and WebGPU); a cancelled run keeps its last partial resultJeremy Magland 302 ...(partial ? ([['Simulated so far', `${fmtNum(simulated)} s of ${fmtNum(p.duration)} s`]] as [string, string][]) : []),
a78afe0Add WebGPU solver with a toggle; faster CPU solverJeremy Magland 303 ['Solver', (r.backend ?? 'CPU') + (r.fallback ? ` (WebGPU failed: ${r.fallback})` : '')],
2cd36faBead drum: hex-lattice round head, felt mallet contact, top view and cross-section; shared instrument pageJeremy Magland 304 ['Time step', `${fmtNum(r.dt)} s, ${r.stepsPerSample} per sample`],
87d896eShow partial results while a run is in progress: plots, replay and audio update every 2 s (CPU and WebGPU); a cancelled run keeps its last partial resultJeremy Magland 305 [partial ? 'Wall time so far' : 'Wall time', `${fmtNum(r.wallSeconds)} s (${rt >= 1 ? fmtNum(rt) + '× faster than' : fmtNum(1 / rt) + '× slower than'} real time)`],
2cd36faBead drum: hex-lattice round head, felt mallet contact, top view and cross-section; shared instrument pageJeremy Magland 306 ['Energy balance error', emax > 0 ? `${fmtNum((bal / emax) * 100)}% of peak energy` : '–'],
307 ...(cfg.summaryRows?.(p, built, r) ?? []),
309 [`Peak ${quantity.label}`, `${fmtNum(peak)} ${quantity.unit}`],
312 q('audio-note').textContent = `16-bit mono, ${r.fs} Hz, normalized so the peak is −1 dBFS${partial ? ' (of the sound so far)' : ''}.`;
314 spec.setSignal(r.audio, r.fs);
315 drawSpectrum();
317 else timeline.setTimes(r.frameTimes);
318 scene.showReplay({ ...built.scene, frames: r.frames, malletPos: r.malletPos }, update);
2cd36faBead drum: hex-lattice round head, felt mallet contact, top view and cross-section; shared instrument pageJeremy Magland 321 energyPlot.set([{ x: r.frameTimes, y: r.energy, color: css('--series-1'), label: 'energy (J)' }], {
322 xLabel: 'time (s)',
325 yRange: [0, emax * 1.05 || 1],
326 });
327 }
330 // until it pauses or ends (swapping the source would stop it); when it is
331 // paused partway, the new audio resumes from the same point.
332 const player = q<HTMLAudioElement>('audio');
333 function setAudio(wav: Blob, update: boolean) {
334 pendingAudio = null;
335 if (update && audioUrl && !player.paused && !player.ended) {
336 pendingAudio = wav;
337 return;
338 }
339 const at = update && !player.ended ? player.currentTime : 0;
340 if (audioUrl) URL.revokeObjectURL(audioUrl);
341 audioUrl = URL.createObjectURL(wav);
342 player.src = audioUrl;
343 q<HTMLAnchorElement>('download').href = audioUrl;
344 if (at > 0) player.addEventListener('loadedmetadata', () => (player.currentTime = Math.min(at, player.duration)), { once: true });
345 }
346 const flushAudio = () => {
347 if (pendingAudio) setAudio(pendingAudio, true);
348 };
349 player.addEventListener('pause', flushAudio);
350 player.addEventListener('ended', flushAudio);
353 const card = q('out-contact');
354 card.hidden = !r.contactForce;
355 if (!r.contactForce) return;
356 const cf = r.contactForce;
357 const c = contacts(cf, r.fs);
358 const end = c.length ? c[c.length - 1].start + c[c.length - 1].ms / 1000 : 0.01;
359 const nShow = Math.min(cf.length, Math.ceil((end * 1.3 + 0.002) * r.fs));
360 const t = new Float64Array(nShow);
361 for (let i = 0; i < nShow; i++) t[i] = (i / r.fs) * 1000;
362 contactPlot.set([{ x: t, y: cf.subarray(0, nShow), color: css('--series-2'), label: 'force (N)' }], {
363 xLabel: 'time (ms)',
364 yLabel: 'contact force (N)',
365 yRange: [0, Math.max(...cf.subarray(0, nShow)) * 1.08 || 1],
366 });
367 q('contact-note').textContent = c.length
368 ? `${c.length} contact${c.length > 1 ? 's' : ''}: ` +
369 c.map((k) => `${fmtNum(k.ms)} ms from ${fmtNum(k.start * 1000)} ms, peak ${fmtNum(k.peak)} N`).join('; ') +
370 '. During contact the instrument takes energy from the mallet and gives part of it back as the mallet rebounds, so the energy plot can spike first; the mallet then leaves at constant speed (no gravity).'
371 : 'The mallet never touched the instrument.';
372 }
375 cancelRun = cancel;
376 runBtn.disabled = loadBtn.disabled = !!cancel;
377 cancelBtn.hidden = !cancel;
378 progress.hidden = !cancel;
381 }
383 // Run the simulation and, if this browser has the passcode, store the result.
384 async function run() {
385 const p = controls.get();
386 const inp = inputs(p);
387 if (!inp) return;
388 const { built, opt, backend } = inp;
390 // page draws them, only the newest is drawn.
391 let shown = false; // a partial result of this run is on the page
392 let latest: SimResult | null = null;
393 let finished = false;
394 const onPartial = (r: SimResult) => {
395 if (!latest)
396 setTimeout(() => {
397 if (!latest || finished) return;
398 show(p, built, latest, true, shown);
399 shown = true;
400 latest = null;
401 });
402 latest = r;
403 };
404 const running = runInWorker(built.sys, built.exc, opt, backend === 'gpu', (f) => (progress.value = f), onPartial);
409 show(p, built, r, false, shown);
411 // a WebGPU run that fell back to the CPU is stored as a CPU result
412 const actual: Backend = r.backend?.startsWith('WebGPU') ? 'gpu' : 'cpu';
413 const key = await resultKey(instrumentId, built.sys, built.exc, opt, actual);
414 cacheNote.textContent = 'Storing in the shared cache…';
415 storeResult(key, r, { instrument: instrumentId, backend: r.backend, wallSeconds: r.wallSeconds })
416 .then(() => {
417 if (last?.r === r) cacheNote.textContent = 'Stored in the shared cache.';
418 checkCache();
419 })
420 .catch((e) => {
421 if (last?.r === r) cacheNote.textContent = `Not stored in the shared cache: ${(e as Error).message}`;
422 });
423 }
426 if (shown) cacheNote.textContent = `The run ${(e as Error).message === 'cancelled' ? 'was cancelled' : 'stopped'}; this is the partial result up to ${fmtNum(last!.r.audio.length / last!.r.fs)} s.`;
428 errorBox.textContent = `The simulation failed: ${(e as Error).message}`;
429 errorBox.hidden = false;
430 }
431 } finally {
436 // Download and show the cached result for the current settings.
437 async function loadCached() {
438 if (!cached) return;
439 const { p, built, key } = cached;
440 const abort = new AbortController();
441 setBusy(() => abort.abort());
442 try {
443 const hit = await loadResult(key, (f) => (progress.value = f), abort.signal);
444 if (!hit) throw new Error('the entry is no longer in the cache');
445 show(p, built, hit.result);
446 const when = hit.stored ? ` on ${hit.stored.toISOString().slice(0, 10)}` : '';
447 cacheNote.textContent = `Loaded from the shared cache (computed${when}; the wall time is that of the original run).`;
448 } catch (e) {
449 if (!abort.signal.aborted) {
450 errorBox.textContent = `Could not load the cached result: ${(e as Error).message}`;
451 errorBox.hidden = false;
452 checkCache();
453 }
454 } finally {
455 setBusy(null);
456 }
457 }
458 runBtn.addEventListener('click', run);
459 loadBtn.addEventListener('click', loadCached);
460 cancelBtn.addEventListener('click', () => cancelRun?.());
462 // passcode for writing to the shared cache
463 const passInput = q<HTMLInputElement>('cache-pass');
464 const cacheMsg = q<HTMLParagraphElement>('cache-msg');
465 const showCacheState = () =>
466 (q('cache-state').textContent = getPasscode() ? 'Shared cache: runs are stored' : 'Shared cache: read only');
467 showCacheState();
468 q('cache-save').addEventListener('click', async () => {
469 const pass = passInput.value.trim();
470 if (!pass) return;
471 cacheMsg.textContent = 'Checking…';
472 try {
473 const { valid, reason } = await checkPasscode(pass);
474 if (!valid) {
475 cacheMsg.textContent = `Not saved: ${reason ?? 'invalid passcode'}.`;
476 return;
477 }
478 setPasscode(pass);
479 passInput.value = '';
480 cacheMsg.textContent = 'Saved in this browser. Runs from now on are stored in the cache.';
481 } catch (e) {
482 cacheMsg.textContent = `Could not check the passcode: ${(e as Error).message}`;
483 }
484 showCacheState();
485 });
486 q('cache-forget').addEventListener('click', () => {
487 setPasscode(null);
488 cacheMsg.textContent = 'Passcode removed from this browser.';
489 showCacheState();
493// separate contact intervals in the contact-force record
494function contacts(cf: Float32Array, fs: number): { start: number; ms: number; peak: number }[] {
495 const out: { start: number; ms: number; peak: number }[] = [];
496 let i = 0;
497 while (i < cf.length) {
498 if (cf[i] > 0) {
499 const a = i;
500 let peak = 0;
501 while (i < cf.length && cf[i] > 0) peak = Math.max(peak, cf[i++]);
502 out.push({ start: a / fs, ms: ((i - a) / fs) * 1000, peak });
503 } else i++;
504 }
505 return out;
508function contactRows(r: SimResult): [string, string][] {
509 if (!r.contactForce) return [];
510 const c = contacts(r.contactForce, r.fs);
511 return [
512 [
513 'Contact',
514 c.length
515 ? `${fmtNum(c[0].ms)} ms, peak ${fmtNum(c[0].peak)} N${c.length > 1 ? ` (+${c.length - 1} more contact${c.length > 2 ? 's' : ''})` : ''}`
516 : 'none',
517 ],
518 ];
521const cap = (s: string) => s[0].toUpperCase() + s.slice(1);
↑↓ move↵openescclose