Files
threejs-sound-sim/test/physics.test.ts
T
ddidderr 1a827b8b0d feat: add spatial audio simulator with camera-as-listener model
Implements the simulator described in README.md: a 3D room in which a
loudspeaker can be moved and aimed, heard binaurally from the camera's
position, with every acoustic term shown live so the user can read why it
sounds the way it does.

Only README.md was previously committed. An earlier AI-generated
implementation existed in the working tree but was never committed; it is
superseded rather than modified. That implementation did not work:
renderer.setSize() was never called and the stylesheet had no rule for
html, body or the canvas container, so the WebGL view rendered into a
300x150 box in the corner of an unstyled page. Its acoustics were also
wrong in ways that voided the stated goal, which is what motivated a
rewrite rather than a repair:

  - AudioContext.listener orientation (forwardX/Y/Z, upX/Y/Z) was never
    written, only position. Orbiting the camera therefore produced no
    change in the sound field at all.
  - The listener was a separate avatar mesh, not the camera, contradicting
    the README. Its syncFromCamera() had zero callers.
  - The reverb send was tapped after the distance, cone and occlusion
    gains, making the direct-to-reverberant ratio mathematically constant.
    Walking away sounded like a fader move rather than like distance.
  - Doppler was derived from a single-frame velocity finite difference
    smoothed with a per-frame (not per-second) lerp, so any drag produced
    an octave-wide pitch chirp and the response varied with refresh rate.

Design decisions worth recording, since each has a cheaper alternative
that was rejected:

The camera IS the Web Audio listener. Position and orientation are both
published every frame. OrbitControls panning is disabled on purpose: it
moves the orbit target without moving the camera, which would silently
desync the ear from the view and break that invariant.

Doppler is emergent, not computed. A DelayNode holds distance /
speedOfSound; chasing it resamples the signal exactly as air does. This
removes velocity estimation from the codebase entirely, which is what
eliminated the drag-chirp class of bug. The reported ratio is 1 - dD/dt,
the shift a delay line actually produces. The textbook moving-source form
1/(1 - v/c) agrees only to first order and has a pole that inverts the
sign of the shift when a source closes fast.

The reverb send is tapped BEFORE distance, directivity and occlusion,
because a room's reverberant field is roughly uniform: it depends on how
much power the source radiates, not on where the listener stands. This is
what makes the critical distance audible, and it is the one thing the
simulator teaches that a fader cannot fake.

Room acoustics are derived from geometry via Sabine (T60 = 0.161V/Sa)
rather than from named presets, so the room-size sliders genuinely change
the sound. The impulse response is normalised to unit energy per channel,
not unit peak, because a convolution's output level follows total energy;
peak normalisation would make a long tail far louder than a short one and
the send gain would stop meaning anything.

Source presets are built additively from a bounded harmonic series instead
of being sampled from ideal waveforms, leaving an octave of clean headroom
so Doppler can pitch them up without folding harmonics back down as
aliasing.

User-supplied audio files are summed to mono. A stereo mix fed into the
panner would leave part of the image fixed to the listener's ears no
matter where the source moved, which is precisely the illusion this app
exists to break.

Dark theme only. The viewport is a lit 3D room; a light chrome around it
reads as a white frame on a dark photograph, and re-lighting the scene for
a light theme would need a second set of materials for no real gain.

User-visible behaviour, relative to the uncommitted prior version:

  - The 3D view fills its pane and is sized on construction plus via a
    ResizeObserver.
  - Orbiting the view swings the sound between the ears (measured at
    roughly 14 dB of L-R swing across a full orbit in an anechoic room).
  - Walking away attenuates the direct path while the reverberant field
    holds steady, and a HUD chip reports which of the two dominates.
  - A signal-path table lists every stage between source and ear in dB on
    one shared -60..0 dB scale. The stage losses sum exactly to the total;
    air absorption deliberately reports no dB because it has no broadband
    loss, only a cutoff.
  - Audio files can be loaded by drop or picker and behave as the source.
  - Three guided demos, a first-run explainer, and a keyboard model.
  - Leaked agent artifacts are gone: the panel header no longer reads
    "M4 OVERLAY", sections are no longer lettered "A.", "B.", and the
    milestone scratch directories and docs are deleted.

Known limitations, also listed in README.md:

  - Reverb is a single static impulse response per room; it does not vary
    with listener position, so walking into a corner is not audible.
  - No precedence effect. Real ears localise well beyond the critical
    distance because the first wavefront wins; here localisation degrades
    with the direct-to-reverberant ratio, so a very live room smears the
    image more than it would in life.
  - Occlusion tests one obstacle and models diffraction as a fixed
    broadband loss rather than as a function of the obstacle's size.
  - HRTF quality is whatever the browser's PannerNode provides.
  - Loaded files loop with an audible seam; the crossfade used on the
    generated presets would be wrong for music.

Test Plan

  npm test          116 unit tests. Physics and room acoustics are pure
                    functions. The audio graph is tested against a mock
                    AudioContext that records connections, so the suite
                    can assert topology directly: that the reverb send
                    hangs off the delay rather than the direct gain, and
                    that listener forward/up are published and not just
                    position. Both were silently wrong before.
  npm run test:e2e  47 checks driving real Chrome; starts its own dev
                    server. Covers what a mock cannot: that the view is
                    actually sized, that orbiting changes the ear balance,
                    that walking away attenuates the direct path while the
                    room holds steady, that each demo does what its
                    caption claims, that the panel follows the demos
                    rather than silently reverting them, and that a real
                    WAV decoded by the browser spatialises like any other
                    source while a non-audio file fails visibly.
  npm run build     tsc plus a production bundle, split so three.js gets
                    its own long-lived chunk (470 kB three, 99 kB app).

Manual check: load the page in a browser with headphones, press
"Enable audio & start", then press 3 and walk away with W/S. The Direct
row should fall while Room (wet) stays flat, and the HUD chip should flip
to room-dominant as you cross the ring drawn on the floor.

Refs: ORIGINAL_REQUEST.md
Docs: README.md
2026-07-26 14:50:23 +02:00

261 lines
9.0 KiB
TypeScript

import { describe, expect, it } from 'vitest';
import {
airAbsorptionCutoff,
coneGain,
distanceGain,
dopplerRatio,
gainToDb,
inverseDistanceGain,
linearDistanceGain,
occlusionResponse,
offAxisAngle,
ratioToCents,
smoothingAlpha,
} from '../src/physics';
const at = (x: number, y = 0, z = 0) => ({ x, y, z });
const params = { refDistance: 1, maxDistance: 100, rolloffFactor: 1 };
describe('distance attenuation', () => {
it('holds unity gain inside the reference distance', () => {
expect(inverseDistanceGain(0, params)).toBe(1);
expect(inverseDistanceGain(0.5, params)).toBe(1);
expect(inverseDistanceGain(1, params)).toBe(1);
});
it('loses 6 dB per doubling of distance, the inverse-distance law', () => {
const near = gainToDb(inverseDistanceGain(4, params));
const far = gainToDb(inverseDistanceGain(8, params));
expect(near - far).toBeCloseTo(6.02, 1);
});
it('never attenuates when rolloff is zero', () => {
const flat = { ...params, rolloffFactor: 0 };
expect(inverseDistanceGain(50, flat)).toBe(1);
});
it('reaches silence at maxDistance under the linear model', () => {
expect(linearDistanceGain(100, params)).toBe(0);
expect(linearDistanceGain(1000, params)).toBe(0);
});
it('degrades gracefully when maxDistance is below refDistance', () => {
const inverted = { refDistance: 10, maxDistance: 2, rolloffFactor: 1 };
expect(linearDistanceGain(1, inverted)).toBe(1);
expect(linearDistanceGain(5, inverted)).toBe(0);
});
it('stays within [0, 1] for every model across a wide sweep', () => {
for (const model of ['inverse', 'exponential', 'linear'] as const) {
for (const d of [0, 0.001, 1, 7, 99, 1e4]) {
for (const rolloff of [0, 1, 5]) {
const gain = distanceGain(d, model, { ...params, rolloffFactor: rolloff });
expect(gain).toBeGreaterThanOrEqual(0);
expect(gain).toBeLessThanOrEqual(1);
expect(Number.isFinite(gain)).toBe(true);
}
}
}
});
it('decreases monotonically with distance', () => {
for (const model of ['inverse', 'exponential', 'linear'] as const) {
let previous = Infinity;
for (let d = 0; d <= 60; d += 2) {
const gain = distanceGain(d, model, params);
expect(gain).toBeLessThanOrEqual(previous + 1e-12);
previous = gain;
}
}
});
});
describe('air absorption', () => {
it('is transparent at zero strength or zero distance', () => {
expect(airAbsorptionCutoff(50, 0)).toBe(22050);
expect(airAbsorptionCutoff(0, 4)).toBe(22050);
});
it('rolls the cutoff down as distance grows', () => {
const near = airAbsorptionCutoff(5, 1);
const far = airAbsorptionCutoff(80, 1);
expect(far).toBeLessThan(near);
expect(far).toBeGreaterThan(200);
});
it('is barely audible at realistic strength across a room', () => {
// Real air costs very little treble over 20 m; the default must reflect that.
expect(airAbsorptionCutoff(20, 1)).toBeGreaterThan(15000);
});
it('never falls below the floor even at extreme strength', () => {
expect(airAbsorptionCutoff(1000, 8)).toBeGreaterThanOrEqual(200);
});
});
describe('directivity cone', () => {
const cone = { innerAngle: 60, outerAngle: 180, outerGain: 0.1 };
const source = at(0, 0, 0);
const forward = at(0, 0, -1);
it('is at full level dead ahead', () => {
expect(coneGain(source, forward, at(0, 0, -5), cone)).toBe(1);
});
it('is at full level anywhere inside the inner cone', () => {
// 25° off-axis, inside the 30° inner half-angle.
const listener = at(Math.sin(0.436) * 5, 0, -Math.cos(0.436) * 5);
expect(coneGain(source, forward, listener, cone)).toBe(1);
});
it('falls to the floor gain directly behind the source', () => {
expect(coneGain(source, forward, at(0, 0, 5), cone)).toBeCloseTo(0.1, 6);
});
it('interpolates across the transition band', () => {
// 60° off-axis: past the 30° inner half-angle, short of the 90° outer one.
const listener = at(Math.sin(Math.PI / 3) * 5, 0, -Math.cos(Math.PI / 3) * 5);
const gain = coneGain(source, forward, listener, cone);
expect(gain).toBeGreaterThan(0.1);
expect(gain).toBeLessThan(1);
});
it('reaches the floor exactly at the outer half-angle', () => {
expect(coneGain(source, forward, at(5, 0, 0), cone)).toBeCloseTo(0.1, 6);
});
it('falls monotonically as the listener swings off-axis', () => {
let previous = Infinity;
for (let deg = 0; deg <= 180; deg += 10) {
const rad = (deg * Math.PI) / 180;
const listener = at(Math.sin(rad) * 5, 0, -Math.cos(rad) * 5);
const gain = coneGain(source, forward, listener, cone);
expect(gain).toBeLessThanOrEqual(previous + 1e-9);
previous = gain;
}
});
it('is omnidirectional at 360 degrees', () => {
const omni = { innerAngle: 360, outerAngle: 360, outerGain: 0 };
for (const listener of [at(5), at(-5), at(0, 5), at(0, 0, 5)]) {
expect(coneGain(source, forward, listener, omni)).toBe(1);
}
});
it('treats a coincident listener as on-axis rather than dividing by zero', () => {
expect(coneGain(source, forward, source, cone)).toBe(1);
});
it('survives a degenerate forward vector', () => {
const gain = coneGain(source, at(0, 0, 0), at(0, 0, -5), cone);
expect(Number.isFinite(gain)).toBe(true);
});
it('reports the off-axis angle in degrees', () => {
expect(offAxisAngle(source, forward, at(0, 0, -5))).toBeCloseTo(0, 6);
expect(offAxisAngle(source, forward, at(5, 0, 0))).toBeCloseTo(90, 6);
expect(offAxisAngle(source, forward, at(0, 0, 5))).toBeCloseTo(180, 6);
});
});
describe('doppler', () => {
const still = at(0, 0, 0);
it('is unity when nothing moves', () => {
expect(dopplerRatio(at(0), still, at(10), still)).toBe(1);
});
it('raises pitch when the source approaches', () => {
// Source at origin, listener at +10 x, source moving towards it.
expect(dopplerRatio(at(0), at(30), at(10), still)).toBeGreaterThan(1);
});
it('lowers pitch when the source recedes', () => {
expect(dopplerRatio(at(0), at(-30), at(10), still)).toBeLessThan(1);
});
it('lowers pitch when the listener flees', () => {
expect(dopplerRatio(at(0), still, at(10), at(30))).toBeLessThan(1);
});
it('matches the textbook ratio for an approaching source', () => {
// f'/f = c / (c - v) = 343 / (343 - 34.3) = 1.1111…
expect(dopplerRatio(at(0), at(34.3), at(10), still, 343)).toBeCloseTo(1.1111, 3);
});
it('ignores motion perpendicular to the line of sight', () => {
expect(dopplerRatio(at(0), at(0, 0, 40), at(10), still)).toBeCloseTo(1, 6);
});
it('stays finite and bounded at and beyond the speed of sound', () => {
for (const v of [343, 400, 5000]) {
const ratio = dopplerRatio(at(0), at(v), at(10), still, 343);
expect(Number.isFinite(ratio)).toBe(true);
expect(ratio).toBeLessThanOrEqual(4);
expect(ratio).toBeGreaterThanOrEqual(0.25);
}
});
it('falls back to a sane medium when given a nonsense speed of sound', () => {
expect(dopplerRatio(at(0), still, at(10), still, 0)).toBe(1);
});
it('returns unity for a coincident source and listener', () => {
expect(dopplerRatio(at(5), at(10), at(5), still)).toBe(1);
});
});
describe('occlusion', () => {
it('is transparent with a clear line of sight', () => {
const clear = occlusionResponse(0);
expect(clear.gain).toBe(1);
expect(clear.cutoff).toBeCloseTo(22050, 0);
});
it('muffles but does not silence a fully blocked path', () => {
const blocked = occlusionResponse(1);
expect(blocked.cutoff).toBeCloseTo(350, 0);
expect(blocked.gain).toBeGreaterThan(0);
expect(blocked.gain).toBeLessThan(0.3);
});
it('sweeps the cutoff monotonically and geometrically', () => {
let previous = Infinity;
for (let t = 0; t <= 1; t += 0.1) {
const { cutoff } = occlusionResponse(t);
expect(cutoff).toBeLessThan(previous);
previous = cutoff;
}
// Geometric interpolation puts the halfway point at the geometric mean,
// which is what keeps the sweep sounding even.
expect(occlusionResponse(0.5).cutoff).toBeCloseTo(Math.sqrt(350 * 22050), 0);
});
it('clamps out-of-range input', () => {
expect(occlusionResponse(-3).gain).toBe(1);
expect(occlusionResponse(9).gain).toBeCloseTo(occlusionResponse(1).gain, 12);
});
});
describe('unit helpers', () => {
it('converts gain to decibels', () => {
expect(gainToDb(1)).toBeCloseTo(0, 9);
expect(gainToDb(0.5)).toBeCloseTo(-6.02, 2);
expect(gainToDb(0)).toBe(-120);
});
it('converts frequency ratios to cents', () => {
expect(ratioToCents(1)).toBeCloseTo(0, 9);
expect(ratioToCents(2)).toBeCloseTo(1200, 6);
expect(ratioToCents(0.5)).toBeCloseTo(-1200, 6);
});
it('produces frame-rate independent smoothing', () => {
// Two 8 ms steps must land where one 16 ms step lands.
const single = smoothingAlpha(0.016, 0.1);
const a = smoothingAlpha(0.008, 0.1);
const twice = 1 - (1 - a) * (1 - a);
expect(twice).toBeCloseTo(single, 9);
});
});