1// Browser tests: serve the app with Vite's dev server, open it in a headless
2// Chromium with WebGPU through Playwright, and drive it through the hooks
3// on window.cymbalsim: the in-page self-test of the WGSL kernel against the
4// float64 reference, a linear synthesis, a short full run, and a light hit
5// simulated both ways, whose signals must agree.
7import { test } from "node:test";
8import assert from "node:assert/strict";
9import { fileURLToPath } from "node:url";
10import { dirname, join } from "node:path";
11import { createServer } from "vite";
12import { chromium, type Page } from "playwright";
14const root = join(dirname(fileURLToPath(import.meta.url)), "..");
15const ARGS = ["--enable-unsafe-webgpu", "--enable-features=Vulkan", "--use-angle=vulkan", "--ignore-gpu-blocklist", "--no-sandbox"];
17interface Status {
18 design: string | null;
19 modes: { count: number; missing: number; first: number[] } | null;
20 synthesized: boolean;
21 running: boolean;
22 samples: number;
23 frames: number;
24 source: string | null;
25 peakPressure: number;
26 sim: { phase: string; t: number; totalSteps: number; stick: { maxForce: number; withdrawn: boolean }; wmax: number } | null;
27 contact: { peakForce: number; contactTime: number } | null;
28 editorStatus: string;
29}
31async function withPage(query: string, body: (page: Page, errors: string[]) => Promise<void>): Promise<void> {
32 const server = await createServer({ root, logLevel: "silent", server: { port: 0, strictPort: false } });
33 await server.listen();
34 const url = server.resolvedUrls?.local[0];
35 assert.ok(url, "dev server URL");
36 const browser = await chromium.launch({ headless: true, args: ARGS });
37 try {
38 const page = await browser.newPage();
39 const errors: string[] = [];
40 page.on("pageerror", (e) => errors.push(e.message));
41 page.on("console", (msg) => { if (msg.type() === "error") errors.push(`console.error: ${msg.text()}`); });
42 await page.goto(`${url}?${query}`);
43 await page.waitForFunction(() => (window as unknown as { cymbalsim?: unknown }).cymbalsim !== undefined, null, { timeout: 30000 });
44 await body(page, errors);
45 } finally {
46 await browser.close();
47 await server.close();
48 }
49}
51const status = (page: Page) => page.evaluate(() => (window as unknown as { cymbalsim: { status: () => Status } }).cymbalsim.status());
52const hasGpu = (page: Page) => page.evaluate(() => (window as unknown as { cymbalsim: { app: { device: unknown } } }).cymbalsim.app.device !== null);
54test("the WGSL step agrees with the float64 reference on several presets", async () => {
55 await withPage("preset=flat-rectangle&nogpuview=0", async (page, errors) => {
56 if (!(await hasGpu(page))) { console.log("no WebGPU in this Chromium; skipping"); return; }
57 const text = await page.evaluate(() => (window as unknown as { cymbalsim: { selftest: () => Promise<string> } }).cymbalsim.selftest());
58 console.log(text);
59 for (const line of text.split("\n")) {
60 const m = /max relative error ([0-9.e+-]+)/.exec(line);
61 assert.ok(m, line);
62 assert.ok(Number(m![1]) < 2e-4, line);
63 }
64 assert.deepEqual(errors, []);
65 });
66});
68test("the linear model computes the modes and synthesizes a strike", async () => {
69 await withPage("preset=flat-disc&duration=1", async (page, errors) => {
70 let st = await status(page);
71 assert.equal(st.design, "Flat bronze disc");
72 assert.equal(st.modes, null, "the modes are computed when Synthesize is pressed");
73 await page.evaluate(() => (window as unknown as { cymbalsim: { runLinear: () => Promise<void> } }).cymbalsim.runLinear());
74 st = await status(page);
75 assert.ok(st.modes && st.modes.count > 100, `modes ${st.modes?.count}`);
76 assert.equal(st.modes!.missing, 0);
77 assert.ok(st.modes!.first[0] > 1 && st.modes!.first[0] < 200, `first mode ${st.modes!.first[0]} Hz (the rock or the bounce on the stand)`);
78 // A second synthesis reuses the cached modes.
79 const t0 = Date.now();
80 await page.evaluate(() => (window as unknown as { cymbalsim: { runLinear: () => Promise<void> } }).cymbalsim.runLinear());
81 assert.ok(Date.now() - t0 < 4000, "cached modes");
82 assert.ok(st.synthesized);
83 assert.equal(st.source, "linear");
84 assert.equal(st.samples, 48000);
85 assert.equal(st.frames, 120);
86 assert.ok(st.peakPressure > 0.1 && st.peakPressure < 1000, `peak ${st.peakPressure} Pa`);
87 assert.ok(st.contact && st.contact.peakForce > 10);
88 assert.deepEqual(errors, []);
89 });
90});
92test("the tutorial opens, typesets its mathematics, and its actions drive the application", async () => {
93 await withPage("preset=flat-rectangle&tutorial=modes&spacing=0.016", async (page, errors) => {
94 const opened = await page.evaluate(() => {
95 const t = document.getElementById("tutorial")!;
96 return { hidden: t.hidden, katex: t.querySelectorAll(".katex").length, title: t.querySelector("h2")?.textContent ?? "", buttons: Array.from(t.querySelectorAll(".tut-actions button")).map((b) => b.textContent) };
97 });
98 assert.equal(opened.hidden, false);
99 assert.ok(opened.katex > 2, `math typeset: ${opened.katex}`);
100 assert.equal(opened.title, "Modes: the standing waves of the plate");
101 assert.ok(opened.buttons.includes("Compute the modes"));
102 // The action computes the modes; the page then shows their count.
103 await page.click("#tutorial .tut-actions button:has-text('Compute the modes')");
104 await page.waitForFunction(() => (window as unknown as { cymbalsim: { status: () => { modes: unknown } } }).cymbalsim.status().modes !== null, null, { timeout: 60000 });
105 await page.waitForFunction(() => !document.querySelector("#tutorial .tut-actions button")!.hasAttribute("disabled"), null, { timeout: 60000 });
106 const st = await status(page);
107 assert.ok(st.modes && st.modes.count > 50);
108 const text = await page.evaluate(() => document.querySelector("#tutorial .tut-live")?.textContent ?? "");
109 assert.match(text, /unknowns/);
110 assert.match(text, new RegExp(`${st.modes!.count} modes`));
111 // Showing a mode selects it in the browser and draws it.
112 await page.click("#tutorial .tut-actions button:has-text('Show mode 1')");
113 const overlay = await page.evaluate(() => document.getElementById("viewOverlay")!.textContent);
114 assert.match(overlay!, /Mode 1/);
115 // Next goes to the next page and the table of contents follows.
116 await page.click("#tutorial .tut-foot button:has-text('Next')");
117 const next = await page.evaluate(() => ({ title: document.querySelector("#tutorial h2")?.textContent, sel: (document.querySelector("#tutorial select") as HTMLSelectElement).selectedOptions[0].textContent }));
118 assert.equal(next.title, "Scaling laws");
119 assert.equal(next.sel, "Scaling laws");
120 assert.deepEqual(errors, []);
121 });
122});
124test("a loud recording warns before playing and plays once accepted", async () => {
125 await withPage("preset=flat-rectangle&duration=0.5&spacing=0.016", async (page, errors) => {
126 await page.evaluate(() => (window as unknown as { cymbalsim: { runLinear: () => Promise<void> } }).cymbalsim.runLinear());
127 // The page's App, with the private members the test pokes at.
128 type A = { gainDb: number; player: { playing: boolean }; levelMode: string; updatePeak: () => void; togglePlay: () => void; loudWarn: HTMLElement };
129 const run = (script: string) => page.evaluate((s: string) => {
130 const a = (window as unknown as { cymbalsim: { app: A } }).cymbalsim.app;
131 new Function("a", s)(a);
132 return { playing: a.player.playing, warn: !a.loudWarn.hidden, text: a.loudWarn.textContent ?? "" };
133 }, script);
134 // Normalizing the peak puts it at -1 dBFS: Play warns instead of playing.
135 let r = await run(`a.levelMode = "peak"; a.updatePeak(); a.togglePlay();`);
136 assert.equal(r.playing, false);
137 assert.equal(r.warn, true);
138 assert.match(r.text, /-1\.0 dBFS/);
139 assert.match(r.text, /volume/);
140 // Cancel hides it; Play anyway plays and remembers the level, so the next Play needs no prompt.
141 await page.click("#movieToolbar .loud-warn button:has-text('Cancel')");
142 r = await run("");
143 assert.equal(r.warn, false);
144 assert.equal(r.playing, false);
145 await run("a.togglePlay();");
146 await page.click("#movieToolbar .loud-warn button:has-text('Play anyway')");
147 r = await run("");
148 assert.equal(r.playing, true);
149 assert.equal(r.warn, false);
150 r = await run("a.togglePlay(); a.togglePlay();");
151 assert.equal(r.playing, true, "the accepted level plays without a prompt");
152 assert.equal(r.warn, false);
153 // A quiet signal never prompts.
154 r = await run(`a.togglePlay(); a.levelMode = "absolute"; a.gainDb = -60; a.updatePeak(); a.togglePlay();`);
155 assert.equal(r.playing, true);
156 assert.equal(r.warn, false);
157 assert.deepEqual(errors, []);
158 });
159});
161test("a script with an error is reported", async () => {
162 await withPage("preset=ellipse", async (page) => {
163 await page.evaluate(() => {
164 const app = (window as unknown as { cymbalsim: { app: { editor: { setSource: (s: string) => void }; onSource: (s: string) => void } } }).cymbalsim.app;
165 app.editor.setSource("design.material.E = 1;");
166 (app as unknown as { onSource: (s: string) => void }).onSource("design.material.E = 1;");
167 });
168 const st = await status(page);
169 assert.match(st.editorStatus, /design.material.E/);
170 });
171});
173test("the full simulation runs a short strike on a free plate and on a stand", async () => {
174 await withPage("preset=bowed-rectangle&mode=full&duration=0.05&spacing=0.012", async (page, errors) => {
175 if (!(await hasGpu(page))) { console.log("no WebGPU in this Chromium; skipping"); return; }
176 await page.evaluate(() => (window as unknown as { cymbalsim: { runFull: () => Promise<void> } }).cymbalsim.runFull());
177 const st = await status(page);
178 assert.equal(st.source, "full");
179 assert.ok(st.sim && st.sim.phase === "done");
180 assert.equal(st.samples, 2400);
181 assert.ok(st.sim!.stick.maxForce > 10, `force ${st.sim!.stick.maxForce}`);
182 assert.ok(st.sim!.wmax > 1e-5 && st.sim!.wmax < 0.05, `wmax ${st.sim!.wmax}`);
183 assert.ok(st.peakPressure > 0.01 && isFinite(st.peakPressure));
184 assert.deepEqual(errors, []);
185 });
186 await withPage("preset=crash-16&mode=full&duration=0.05&spacing=0.012", async (page, errors) => {
187 if (!(await hasGpu(page))) return;
188 await page.evaluate(() => (window as unknown as { cymbalsim: { runFull: () => Promise<void> } }).cymbalsim.runFull());
189 const st = await status(page);
190 assert.ok(st.sim && st.sim.phase === "done");
191 assert.ok(st.sim!.stick.maxForce > 10);
192 assert.ok(isFinite(st.peakPressure) && st.peakPressure > 0.01);
193 assert.deepEqual(errors, []);
194 });
195});
197test("a light hit sounds the same in the linear and the full model", async () => {
198 await withPage("preset=flat-disc&duration=0.25&strikeVelocity=0.05&spacing=0.012&fps=60", async (page, errors) => {
199 if (!(await hasGpu(page))) { console.log("no WebGPU in this Chromium; skipping"); return; }
200 const hooks = "(window as unknown as { cymbalsim: any }).cymbalsim";
201 await page.evaluate(() => (window as unknown as { cymbalsim: { runLinear: () => Promise<void> } }).cymbalsim.runLinear());
202 const linear = await page.evaluate(() => { const a = (window as unknown as { cymbalsim: { app: { rec: { audio: Float32Array; samples: number } } } }).cymbalsim.app; return Array.from(a.rec.audio.subarray(0, a.rec.samples)); });
203 await page.evaluate(() => (window as unknown as { cymbalsim: { runFull: () => Promise<void> } }).cymbalsim.runFull());
204 const full = await page.evaluate(() => { const a = (window as unknown as { cymbalsim: { app: { rec: { audio: Float32Array; samples: number } } } }).cymbalsim.app; return Array.from(a.rec.audio.subarray(0, a.rec.samples)); });
205 void hooks;
206 assert.equal(linear.length, full.length);
207 // Compare the spectra over 50 to 250 ms (after the attack, which the delay interpolation renders slightly differently).
208 const fs = 48000, n0 = Math.round(0.05 * fs), n1 = Math.round(0.25 * fs);
209 const N = 8192;
210 const spec = (x: number[]) => {
211 const re = new Float64Array(N), im = new Float64Array(N);
212 for (let i = 0; i < N && n0 + i < n1; i++) re[i] = x[n0 + i] * (0.5 - 0.5 * Math.cos((2 * Math.PI * i) / N));
213 // naive DFT on a subset of bins is too slow; use a simple radix-2 FFT here
214 fftInPlace(re, im);
215 const mag = new Float64Array(N / 2);
216 for (let k = 0; k < N / 2; k++) mag[k] = Math.hypot(re[k], im[k]);
217 return mag;
218 };
219 const a = spec(linear), b = spec(full);
220 // Normalized correlation of the magnitude spectra below 6 kHz.
221 const kmax = Math.round((6000 / fs) * N);
222 let ab = 0, aa = 0, bb = 0;
223 for (let k = 1; k < kmax; k++) { ab += a[k] * b[k]; aa += a[k] * a[k]; bb += b[k] * b[k]; }
224 const corr = ab / Math.sqrt(aa * bb);
225 // Level agreement: RMS over the window.
226 const rms = (x: number[]) => Math.sqrt(x.slice(n0, n1).reduce((s, v) => s + v * v, 0) / (n1 - n0));
227 const ratio = rms(linear) / rms(full);
228 console.log(`spectral correlation ${corr.toFixed(3)}, rms ratio linear/full ${ratio.toFixed(3)}`);
229 assert.ok(corr > 0.9, `spectral correlation ${corr}`);
230 assert.ok(ratio > 0.7 && ratio < 1.4, `rms ratio ${ratio}`);
231 assert.deepEqual(errors, []);
232 });
233});
235function fftInPlace(re: Float64Array, im: Float64Array): void {
236 const n = re.length;
237 for (let i = 1, j = 0; i < n; i++) {
238 let bit = n >> 1;
239 for (; j & bit; bit >>= 1) j ^= bit;
240 j ^= bit;
241 if (i < j) { [re[i], re[j]] = [re[j], re[i]]; [im[i], im[j]] = [im[j], im[i]]; }
242 }
243 for (let len = 2; len <= n; len <<= 1) {
244 const ang = (-2 * Math.PI) / len;
245 for (let i = 0; i < n; i += len) {
246 for (let k = 0; k < len / 2; k++) {
247 const c = Math.cos(ang * k), s = Math.sin(ang * k);
248 const ur = re[i + k], ui = im[i + k];
249 const vr = re[i + k + len / 2] * c - im[i + k + len / 2] * s;
250 const vi = re[i + k + len / 2] * s + im[i + k + len / 2] * c;
251 re[i + k] = ur + vr; im[i + k] = ui + vi;
252 re[i + k + len / 2] = ur - vr; im[i + k + len / 2] = ui - vi;
253 }
254 }
255 }
256}