/ proof-of-concept / cymbalsim
Sign in
proof-of-concept / cymbalsim
cymbalsim / tests / gpu.test.ts
184 lines · 9.5 KBCodeBlameHistory
5778036cymbalsim: scripted plate and cymbal designer with a modal linear model and a von Karman GPU modelJeremy Magland 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;
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 }
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 await page.evaluate(() => (window as unknown as { cymbalsim: { modesReady: () => Promise<void> } }).cymbalsim.modesReady());
71 let st = await status(page);
72 assert.equal(st.design, "Flat bronze disc");
73 assert.ok(st.modes && st.modes.count > 100, `modes ${st.modes?.count}`);
74 assert.equal(st.modes!.missing, 0);
75 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)`);
76 await page.evaluate(() => (window as unknown as { cymbalsim: { runLinear: () => Promise<void> } }).cymbalsim.runLinear());
77 st = await status(page);
78 assert.ok(st.synthesized);
79 assert.equal(st.source, "linear");
80 assert.equal(st.samples, 48000);
81 assert.equal(st.frames, 120);
82 assert.ok(st.peakPressure > 0.1 && st.peakPressure < 1000, `peak ${st.peakPressure} Pa`);
83 assert.ok(st.contact && st.contact.peakForce > 10);
84 assert.deepEqual(errors, []);
85 });
86});
88test("a script with an error is reported", async () => {
89 await withPage("preset=ellipse", async (page) => {
90 await page.evaluate(() => {
91 const app = (window as unknown as { cymbalsim: { app: { editor: { setSource: (s: string) => void }; onSource: (s: string) => void } } }).cymbalsim.app;
92 app.editor.setSource("design.material.E = 1;");
93 (app as unknown as { onSource: (s: string) => void }).onSource("design.material.E = 1;");
94 });
95 const st = await status(page);
96 assert.match(st.editorStatus, /design.material.E/);
97 });
98});
100test("the full simulation runs a short strike on a free plate and on a stand", async () => {
101 await withPage("preset=bowed-rectangle&mode=full&duration=0.05&spacing=0.012", async (page, errors) => {
102 if (!(await hasGpu(page))) { console.log("no WebGPU in this Chromium; skipping"); return; }
103 await page.evaluate(() => (window as unknown as { cymbalsim: { runFull: () => Promise<void> } }).cymbalsim.runFull());
104 const st = await status(page);
105 assert.equal(st.source, "full");
106 assert.ok(st.sim && st.sim.phase === "done");
107 assert.equal(st.samples, 2400);
108 assert.ok(st.sim!.stick.maxForce > 10, `force ${st.sim!.stick.maxForce}`);
109 assert.ok(st.sim!.wmax > 1e-5 && st.sim!.wmax < 0.05, `wmax ${st.sim!.wmax}`);
110 assert.ok(st.peakPressure > 0.01 && isFinite(st.peakPressure));
111 assert.deepEqual(errors, []);
112 });
113 await withPage("preset=crash-16&mode=full&duration=0.05&spacing=0.012", async (page, errors) => {
114 if (!(await hasGpu(page))) return;
115 await page.evaluate(() => (window as unknown as { cymbalsim: { runFull: () => Promise<void> } }).cymbalsim.runFull());
116 const st = await status(page);
117 assert.ok(st.sim && st.sim.phase === "done");
118 assert.ok(st.sim!.stick.maxForce > 10);
119 assert.ok(isFinite(st.peakPressure) && st.peakPressure > 0.01);
120 assert.deepEqual(errors, []);
121 });
122});
124test("a light hit sounds the same in the linear and the full model", async () => {
125 await withPage("preset=flat-disc&duration=0.25&strikeVelocity=0.05&spacing=0.012&fps=60", async (page, errors) => {
126 if (!(await hasGpu(page))) { console.log("no WebGPU in this Chromium; skipping"); return; }
127 const hooks = "(window as unknown as { cymbalsim: any }).cymbalsim";
128 await page.evaluate(() => (window as unknown as { cymbalsim: { modesReady: () => Promise<void> } }).cymbalsim.modesReady());
129 await page.evaluate(() => (window as unknown as { cymbalsim: { runLinear: () => Promise<void> } }).cymbalsim.runLinear());
130 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)); });
131 await page.evaluate(() => (window as unknown as { cymbalsim: { runFull: () => Promise<void> } }).cymbalsim.runFull());
132 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)); });
133 void hooks;
134 assert.equal(linear.length, full.length);
135 // Compare the spectra over 50 to 250 ms (after the attack, which the delay interpolation renders slightly differently).
136 const fs = 48000, n0 = Math.round(0.05 * fs), n1 = Math.round(0.25 * fs);
137 const N = 8192;
138 const spec = (x: number[]) => {
139 const re = new Float64Array(N), im = new Float64Array(N);
140 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));
141 // naive DFT on a subset of bins is too slow; use a simple radix-2 FFT here
142 fftInPlace(re, im);
143 const mag = new Float64Array(N / 2);
144 for (let k = 0; k < N / 2; k++) mag[k] = Math.hypot(re[k], im[k]);
145 return mag;
146 };
147 const a = spec(linear), b = spec(full);
148 // Normalized correlation of the magnitude spectra below 6 kHz.
149 const kmax = Math.round((6000 / fs) * N);
150 let ab = 0, aa = 0, bb = 0;
151 for (let k = 1; k < kmax; k++) { ab += a[k] * b[k]; aa += a[k] * a[k]; bb += b[k] * b[k]; }
152 const corr = ab / Math.sqrt(aa * bb);
153 // Level agreement: RMS over the window.
154 const rms = (x: number[]) => Math.sqrt(x.slice(n0, n1).reduce((s, v) => s + v * v, 0) / (n1 - n0));
155 const ratio = rms(linear) / rms(full);
156 console.log(`spectral correlation ${corr.toFixed(3)}, rms ratio linear/full ${ratio.toFixed(3)}`);
157 assert.ok(corr > 0.9, `spectral correlation ${corr}`);
158 assert.ok(ratio > 0.7 && ratio < 1.4, `rms ratio ${ratio}`);
159 assert.deepEqual(errors, []);
160 });
161});
163function fftInPlace(re: Float64Array, im: Float64Array): void {
164 const n = re.length;
165 for (let i = 1, j = 0; i < n; i++) {
166 let bit = n >> 1;
167 for (; j & bit; bit >>= 1) j ^= bit;
168 j ^= bit;
169 if (i < j) { [re[i], re[j]] = [re[j], re[i]]; [im[i], im[j]] = [im[j], im[i]]; }
170 }
171 for (let len = 2; len <= n; len <<= 1) {
172 const ang = (-2 * Math.PI) / len;
173 for (let i = 0; i < n; i += len) {
174 for (let k = 0; k < len / 2; k++) {
175 const c = Math.cos(ang * k), s = Math.sin(ang * k);
176 const ur = re[i + k], ui = im[i + k];
177 const vr = re[i + k + len / 2] * c - im[i + k + len / 2] * s;
178 const vi = re[i + k + len / 2] * s + im[i + k + len / 2] * c;
179 re[i + k] = ur + vr; im[i + k] = ui + vi;
180 re[i + k + len / 2] = ur - vr; im[i + k + len / 2] = ui - vi;
181 }
182 }
183 }
↑↓ move↵openescclose