Skip to main content

roxlap_audio/
lib.rs

1//! Voxel-aware acoustics for the roxlap engine (stage AU —
2//! `docs/porting/PORTING-AUDIO.md`).
3//!
4//! This crate computes **acoustic parameters** from the voxel world; it
5//! deliberately owns no audio device and spawns no audio thread. The
6//! host feeds the numbers into whatever playback stack it uses (the
7//! optional `kira` backend lands in AU.2): per sound source an
8//! occlusion-driven gain + lowpass cutoff + reverb send, and (AU.1) per
9//! listener a cavity-driven reverb feedback/mix.
10//!
11//! The occlusion model follows the convergent games recipe (Sound
12//! Physics, Teardown, Overwatch — see the entry doc): a small fan of
13//! rays from the source to the listener, each accumulating the **solid
14//! path length** it crosses (voxel units, exact segment lengths from a
15//! DDA march — not a boolean hit test), averaged into a `0..=1`
16//! *transmission*. Thickness matters: one voxel of wall muffles less
17//! than five, and a doorway passes some rays untouched, so sound leaks
18//! around corners instead of gating on/off.
19//!
20//! Everything here is pure and deterministic — the jitter fan is a
21//! fixed ring, not RNG — so tests pin exact values and hosts can call
22//! it from any thread.
23
24use glam::{DVec3, IVec3};
25use roxlap_formats::material::material_for_color;
26use roxlap_scene::{FogOfWar, GridId, Rgb, Scene, VoxColor};
27
28mod backend;
29mod cavity;
30pub mod synth;
31
32#[cfg(feature = "kira")]
33mod kira_out;
34
35pub use backend::{
36    AudioOut, SoundKey, SourceId, SourcePool, LISTENER_LOWPASS_OPEN_HZ,
37    LISTENER_LOWPASS_SUBMERGED_HZ,
38};
39pub use cavity::{probe_cavity, CavityConfig, CavityEstimator, CavityProbe, ListenerAcoustics};
40pub use synth::SoundBuffer;
41
42#[cfg(feature = "kira")]
43pub use kira_out::{KiraAudio, DEFAULT_POOL};
44
45/// Tuning knobs for [`source_acoustics`]. The defaults are the cave-demo
46/// tuning; every field is plain data so hosts can persist or lerp them.
47#[derive(Debug, Clone, PartialEq)]
48pub struct AcousticsConfig {
49    /// Jittered rays per source→listener query, **including** the direct
50    /// ray. `1` = direct only; the default `9` (direct + an 8-point ring)
51    /// matches the Sound Physics budget and gives soft doorway
52    /// transitions. Clamped to at least 1.
53    pub rays: u32,
54    /// Radius (world/voxel units) of the jitter ring around the source,
55    /// perpendicular to the source→listener axis. Roughly "how big is
56    /// the emitter": bigger radii leak more around thin edges.
57    pub jitter_radius: f64,
58    /// Per-voxel absorption: a ray crossing `t` voxels of solid keeps
59    /// `exp(-absorption · t)` of its energy. `0.25` ⇒ ~78% through a
60    /// 1-voxel wall, ~29% through 5.
61    pub absorption_per_voxel: f64,
62    /// Lowpass cutoff at full transmission (unoccluded), Hz.
63    pub open_cutoff_hz: f32,
64    /// Lowpass cutoff at zero transmission (fully buried), Hz.
65    pub occluded_cutoff_hz: f32,
66    /// Gain applied at zero transmission, decibels (negative). Scales
67    /// linearly with `1 - transmission`; distance attenuation is NOT
68    /// included (that is the spatial backend's job).
69    pub max_occlusion_db: f32,
70    /// Fraction of the occlusion gain also applied to the reverb send —
71    /// a buried source still excites the room, just less. `0.5` halves
72    /// the dB loss on the send relative to the dry path.
73    pub send_occlusion_frac: f32,
74    /// Hard cap on the marched source→listener distance (world units);
75    /// beyond it no rays are cast and the source reports
76    /// [`SourceAcoustics::clear`] — distance attenuation is the spatial
77    /// backend's job, and a far-away source in open air must NOT come
78    /// back muffled. Bounds the DDA cost.
79    pub max_distance: f64,
80    /// AU2.0 — the host's colour→material terrain map (the SAME map the
81    /// renderer's `set_terrain_materials` and the debris system's
82    /// fracture tables take), classifying the voxels a thickness ray
83    /// crosses. Only consulted when [`absorption`](Self::absorption) is
84    /// non-empty.
85    pub material_map: Vec<(Rgb, u8)>,
86    /// AU2.0 — material id → **effective-thickness multiplier**: a ray
87    /// crossing one voxel of a `0.35` material accumulates 0.35 voxels
88    /// of muffling (glass/crystal), a `1.0` material the full voxel
89    /// (stone — also the default for unmapped materials). **Empty
90    /// (the default) keeps the exact legacy arithmetic** — bit-identical
91    /// to pre-AU2 output. Interior cells carry no colour in the `.vxl`
92    /// format; a ray reuses the last surface colour it crossed (1.0
93    /// until the first) — in practice deep interiors are rock, so the
94    /// default reads correctly.
95    ///
96    /// Note the engine-wide convention: colours absent from
97    /// [`material_map`](Self::material_map) classify as material `0`,
98    /// so an entry for id `0` here re-weights **every unmapped
99    /// voxel** — a deliberate global-default knob, not an accident.
100    pub absorption: Vec<(u8, f32)>,
101}
102
103/// The ONE definition of a fully-open (no muffle) lowpass cutoff,
104/// shared by every path that needs "not occluded / not submerged":
105/// [`AcousticsConfig::default`]'s `open_cutoff_hz`, the listener
106/// lowpass ([`LISTENER_LOWPASS_OPEN_HZ`] is this constant), and the
107/// kira backend's per-source filter rest position. One constant so
108/// the three can't drift apart silently.
109pub const OPEN_CUTOFF_HZ: f32 = 20_000.0;
110
111impl Default for AcousticsConfig {
112    fn default() -> Self {
113        Self {
114            rays: 9,
115            jitter_radius: 1.5,
116            absorption_per_voxel: 0.25,
117            open_cutoff_hz: OPEN_CUTOFF_HZ,
118            occluded_cutoff_hz: 800.0,
119            max_occlusion_db: -24.0,
120            send_occlusion_frac: 0.5,
121            max_distance: 128.0,
122            material_map: Vec::new(),
123            absorption: Vec::new(),
124        }
125    }
126}
127
128/// Occlusion-driven playback parameters for one source→listener pair,
129/// produced by [`source_acoustics`]. Feed them to the playback layer
130/// with short tweens (~120 ms) — never as raw jumps.
131#[derive(Debug, Clone, Copy, PartialEq)]
132pub struct SourceAcoustics {
133    /// Average transmitted energy across the ray fan, `0..=1`
134    /// (`1` = clear line of sound, `0` = buried).
135    pub transmission: f32,
136    /// Occlusion gain, decibels (`0` when clear, down to
137    /// [`AcousticsConfig::max_occlusion_db`]). Excludes distance
138    /// attenuation.
139    pub gain_db: f32,
140    /// Lowpass cutoff for the muffling filter, Hz (log-interpolated
141    /// between the config's occluded and open cutoffs).
142    pub lowpass_cutoff_hz: f32,
143    /// Gain for this source's reverb send, decibels.
144    pub reverb_send_db: f32,
145}
146
147impl SourceAcoustics {
148    /// The parameters of a fully unoccluded source under `cfg`.
149    #[must_use]
150    pub fn clear(cfg: &AcousticsConfig) -> Self {
151        Self {
152            transmission: 1.0,
153            gain_db: 0.0,
154            lowpass_cutoff_hz: cfg.open_cutoff_hz,
155            reverb_send_db: 0.0,
156        }
157    }
158}
159
160/// AU2.2 — default speed of sound for [`doppler_factor`], world
161/// units/second. Deliberately game-tuned, not physical: at the real
162/// 343 m/s a 60 u/s bullet would bend pitch by ~1.5 semitones; at 90
163/// the demo's speeds read clearly. Hosts pass their own value to
164/// retune.
165pub const DEFAULT_SPEED_OF_SOUND: f64 = 90.0;
166
167/// AU2.2 — the Doppler playback-rate factor for a moving
168/// source/listener pair: `> 1` approaching (pitch up), `< 1` receding,
169/// exactly `1.0` at rest. The classic two-sided formula
170/// `(c − v_l·n̂) / (c − v_s·n̂)` with `n̂` the source→listener
171/// direction, made monotone and finite at the edges: the denominator
172/// floors at `0.05·c` (a supersonic approach clamps instead of
173/// flipping sign) and the result clamps to `[0.5, 2.0]` — an octave
174/// down/up, past which game audio reads as a glitch.
175///
176/// Pure math over positions/velocities — no scene query. Feed the
177/// result to [`AudioOut::set_source_pitch`] (backends tween it).
178/// Pitch-bending a **one-shot** mid-envelope sounds like a defect, not
179/// physics: apply Doppler to loops and long tails (a hum, an engine),
180/// driven by whatever velocity the host tracks (a camera delta is
181/// fine).
182#[must_use]
183#[allow(clippy::cast_possible_truncation)]
184pub fn doppler_factor(
185    source_pos: DVec3,
186    source_vel: DVec3,
187    listener_pos: DVec3,
188    listener_vel: DVec3,
189    speed_of_sound: f64,
190) -> f32 {
191    let seg = listener_pos - source_pos;
192    let dist = seg.length();
193    if dist < 1e-9 || speed_of_sound <= 1e-9 {
194        return 1.0;
195    }
196    let n = seg / dist;
197    // `c/c == 1.0` exactly at rest (both dot products are 0.0).
198    let numer = (speed_of_sound - listener_vel.dot(n)).max(0.0);
199    let denom = (speed_of_sound - source_vel.dot(n)).max(speed_of_sound * 0.05);
200    ((numer / denom) as f32).clamp(0.5, 2.0)
201}
202
203/// Total **solid path length** (world/voxel units) the straight segment
204/// `a → b` crosses, summed over every grid in the scene. This is the
205/// thickness building block under [`source_acoustics`]: exact per-cell
206/// segment lengths from a voxel DDA against [`roxlap_scene::Grid::voxel_solid`]
207/// (a diagonal crossing of a 1-voxel wall correctly reports ~√2).
208///
209/// Grid transforms — including per-grid `voxel_world_size` — are honoured
210/// the same way `Scene::raycast` does it: the segment is rebased into each
211/// grid's voxel frame (un-rotate, un-translate, divide by vws), the DDA
212/// accumulates a voxel-unit solid length, and that is scaled back by vws to
213/// a world length. So a coarse grid's thicker voxels muffle proportionally
214/// more. Cost is O(segment length in voxels) per grid — audio queries are
215/// short and infrequent, so no chunk-level skip is attempted (noted future
216/// optimisation).
217#[must_use]
218pub fn path_thickness(scene: &Scene, a: DVec3, b: DVec3) -> f64 {
219    path_thickness_impl(scene, a, b, None)
220}
221
222/// AU2.0 — [`path_thickness`] with **per-material weighting**: each
223/// solid cell's segment length is multiplied by its material's
224/// absorption factor (`material_map` classifies the cell's colour the
225/// way the renderer's terrain map does; `absorption` maps material id
226/// → multiplier, unmapped = `1.0`). One voxel of `0.35` glass muffles
227/// like 0.35 voxels of stone. The `.vxl` format stores surface colours
228/// only, so an interior cell reuses the last surface colour the ray
229/// crossed in that grid (weight `1.0` before the first — deep
230/// interiors read as rock, which is what they are).
231///
232/// With an empty `absorption` table this is exactly
233/// [`path_thickness`] (same arithmetic, bit-identical).
234#[must_use]
235pub fn path_thickness_weighted(
236    scene: &Scene,
237    a: DVec3,
238    b: DVec3,
239    material_map: &[(Rgb, u8)],
240    absorption: &[(u8, f32)],
241) -> f64 {
242    if absorption.is_empty() {
243        return path_thickness_impl(scene, a, b, None);
244    }
245    path_thickness_impl(
246        scene,
247        a,
248        b,
249        Some(&Weights {
250            map: material_map,
251            table: absorption,
252        }),
253    )
254}
255
256/// FW.4 — reveal a heard sound source in the fog of war (decision 6):
257/// hearing something behind the back or through a wall lights a temporary
258/// "heard" pocket around it. Runs [`source_acoustics`] to measure how
259/// much of the source reaches the listener through the geometry, scales
260/// `base_loudness` by that transmission, and stamps a heard blob at the
261/// source's fog cell via [`FogOfWar::hear_world`].
262///
263/// - `fog_grid` — the grid the mask is grid-local to (the real / twin
264///   grid, which share coordinates); its transform + footprint place the
265///   source in the mask.
266/// - `base_loudness` — the source's intrinsic loudness: the heard-blob
267///   radius a FULLY-audible source (`transmission == 1`) reveals, in the
268///   [`FogOfWar`]'s `heard_radius` units.
269/// - Returns the loudness ACTUALLY stamped: `0.0` when the source is
270///   inaudible (buried), OUTSIDE the grid footprint (a passing ship's
271///   noise doesn't reveal this grid — review #2), or too faint to cover
272///   a cell (a barely-audible source reveals nothing rather than a
273///   crisp live actor — review #5). The return is now truthful, so a
274///   host can gate UI/logic on "a reveal happened" (review #8).
275///
276/// A muffled source (thick wall between) reveals a smaller pocket; a
277/// buried one reveals nothing. Distance attenuation is the host's job
278/// (fold it into `base_loudness`); this uses occlusion transmission only.
279pub fn hear_source(
280    scene: &Scene,
281    fow: &mut FogOfWar,
282    fog_grid: GridId,
283    source: DVec3,
284    listener: DVec3,
285    base_loudness: f32,
286    cfg: &AcousticsConfig,
287) -> f32 {
288    let Some((transform, footprint)) = scene
289        .grid(fog_grid)
290        .and_then(|g| g.footprint_cells().map(|fp| (g.transform, fp)))
291    else {
292        return 0.0;
293    };
294    let ac = source_acoustics(scene, source, listener, cfg);
295    let loudness = base_loudness * ac.transmission;
296    if loudness > 0.0 && fow.hear_world(&transform, footprint, source, loudness) {
297        loudness
298    } else {
299        0.0
300    }
301}
302
303/// Shared walk under [`path_thickness`] / [`path_thickness_weighted`].
304fn path_thickness_impl(scene: &Scene, a: DVec3, b: DVec3, weights: Option<&Weights<'_>>) -> f64 {
305    let mut total = 0.0;
306    // FW.1 — audio occlusion hears the REAL world: skip presentation-only
307    // fog-of-war twins (`query_grids`), whose copy-on-seen geometry would
308    // otherwise double-count solid thickness.
309    for (_, grid) in scene.query_grids() {
310        // SC — rebase into the grid's VOXEL frame: un-rotate, un-translate,
311        // then divide by `voxel_world_size` (the DDA below marches voxels).
312        // `grid_thickness` returns the solid length in voxel units, so scale
313        // it back by vws to a WORLD length (a vws=4 grid's voxels are 4×
314        // thicker). Mirrors `Scene::raycast`'s t-invariant. vws == 1 is
315        // unchanged.
316        let vws = grid.transform.voxel_world_size;
317        let inv = grid.transform.rotation.inverse();
318        let la = (inv * (a - grid.transform.origin)) / vws;
319        let lb = (inv * (b - grid.transform.origin)) / vws;
320        total += grid_thickness(grid, la, lb, weights) * vws;
321    }
322    total
323}
324
325/// AU2.0 — the per-material weighting tables, resolved once per query.
326struct Weights<'a> {
327    map: &'a [(Rgb, u8)],
328    table: &'a [(u8, f32)],
329}
330
331impl Weights<'_> {
332    /// The effective-thickness multiplier of a voxel colour.
333    fn resolve(&self, c: VoxColor) -> f64 {
334        let id = material_for_color(self.map, c.0);
335        self.table
336            .iter()
337            .find(|&&(m, _)| m == id)
338            .map_or(1.0, |&(_, w)| f64::from(w))
339    }
340}
341
342/// Solid path length of the grid-local segment `a → b` through one
343/// grid: an Amanatides–Woo cell walk accumulating the in-cell segment
344/// length wherever the voxel is solid. Consecutive steps share a
345/// one-entry chunk borrow (one HashMap probe per crossed chunk, not
346/// per voxel — the [`roxlap_scene::Grid::chunk_voxel_solid`] pattern).
347///
348/// CT.2 — the historical caveat about voxlap's bedrock placeholder
349/// plane (chunk-local z = 255 reading as solid in otherwise-empty
350/// chunks) is gone: empty chunks seed as sentinel columns, so a
351/// segment grazing the world bottom accumulates no phantom thickness.
352fn grid_thickness(
353    grid: &roxlap_scene::Grid,
354    a: DVec3,
355    b: DVec3,
356    weights: Option<&Weights<'_>>,
357) -> f64 {
358    let seg = b - a;
359    let len = seg.length();
360    if len < 1e-9 {
361        return 0.0;
362    }
363    let dir = seg / len;
364    // AU2.0 — carry-forward material weight along the ray: interior
365    // cells have no colour in the `.vxl` format, so they inherit the
366    // last surface colour crossed in THIS grid (1.0 before the first).
367    let mut last_weight = 1.0f64;
368
369    #[allow(clippy::cast_possible_truncation)]
370    let mut cell = IVec3::new(a.x.floor() as i32, a.y.floor() as i32, a.z.floor() as i32);
371
372    // Per-axis DDA state: t at the next cell boundary and t per cell.
373    let mut t_max = [f64::INFINITY; 3];
374    let mut t_delta = [f64::INFINITY; 3];
375    let mut step = [0i32; 3];
376    for ax in 0..3 {
377        let d = dir[ax];
378        if d.abs() < 1e-12 {
379            continue;
380        }
381        step[ax] = if d > 0.0 { 1 } else { -1 };
382        t_delta[ax] = 1.0 / d.abs();
383        let cell_f = f64::from(cell[ax]);
384        let next_boundary = if d > 0.0 { cell_f + 1.0 } else { cell_f };
385        t_max[ax] = (next_boundary - a[ax]) / d;
386    }
387
388    let mut thickness = 0.0;
389    let mut t_prev = 0.0;
390    // One-entry chunk cache: consecutive DDA cells overwhelmingly stay
391    // in the same 128×128×256 chunk, so the HashMap probe amortises to
392    // one per crossed chunk.
393    let mut cached_idx = IVec3::MAX;
394    // Inferred `Option<&Vxl>` (roxlap-scene doesn't re-export the type).
395    let mut cached_chunk = None;
396    // Step budget: a segment of length L crosses at most ~L+1 boundaries
397    // per axis. The +8 absorbs boundary-epsilon jitter.
398    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
399    let max_steps = (len * 3.0) as u32 + 8;
400    for _ in 0..max_steps {
401        let ax = min_axis(&t_max);
402        let t_next = t_max[ax].min(len);
403        let (chunk_idx, in_chunk) = roxlap_scene::voxel_split(cell);
404        if chunk_idx != cached_idx {
405            cached_idx = chunk_idx;
406            cached_chunk = grid.chunk(chunk_idx);
407        }
408        let solid =
409            cached_chunk.is_some_and(|vxl| roxlap_scene::Grid::chunk_voxel_solid(vxl, in_chunk));
410        if solid {
411            // `w == 1.0` on the unweighted path: `x * 1.0` is exact, so
412            // pre-AU2 output stays bit-identical (pinned tests).
413            let w = match weights {
414                None => 1.0,
415                Some(ws) => {
416                    if let Some(c) = cached_chunk
417                        .and_then(|vxl| vxl.voxel_color(in_chunk.x, in_chunk.y, in_chunk.z))
418                    {
419                        last_weight = ws.resolve(c);
420                    }
421                    last_weight
422                }
423            };
424            thickness += (t_next - t_prev) * w;
425        }
426        if t_max[ax] >= len {
427            break;
428        }
429        t_prev = t_next;
430        cell[ax] += step[ax];
431        t_max[ax] += t_delta[ax];
432    }
433    thickness
434}
435
436/// Index of the smallest component (the axis the DDA crosses next).
437fn min_axis(t: &[f64; 3]) -> usize {
438    if t[0] <= t[1] && t[0] <= t[2] {
439        0
440    } else if t[1] <= t[2] {
441        1
442    } else {
443        2
444    }
445}
446
447/// Occlusion parameters for one source heard from `listener`: a fan of
448/// [`AcousticsConfig::rays`] thickness rays (the direct segment plus a
449/// fixed jitter ring around the **source**, perpendicular to the
450/// source→listener axis), each converted to transmitted energy
451/// `exp(-absorption · thickness)` and averaged.
452///
453/// Deterministic — the ring is fixed 45° spokes, no RNG — and pure, so
454/// hosts may round-robin sources across ticks freely (the entry doc's
455/// ~4 Hz per source cadence).
456#[must_use]
457pub fn source_acoustics(
458    scene: &Scene,
459    source: DVec3,
460    listener: DVec3,
461    cfg: &AcousticsConfig,
462) -> SourceAcoustics {
463    let seg = listener - source;
464    let dist = seg.length();
465    // Beyond the march budget (or on top of the listener): report
466    // CLEAR, not buried — the backend's distance attenuation owns far
467    // sources, and clamping to "muffled" would put a step function at
468    // the boundary (a far source in open air is quiet, not lowpassed).
469    if dist > cfg.max_distance || dist < 1e-9 {
470        return SourceAcoustics::clear(cfg);
471    }
472    let dir = seg / dist;
473
474    // A stable perpendicular basis for the jitter ring.
475    let helper = if dir.x.abs() < 0.9 {
476        DVec3::X
477    } else {
478        DVec3::Y
479    };
480    let u = dir.cross(helper).normalize();
481    let v = dir.cross(u);
482
483    let rays = cfg.rays.max(1);
484    let mut energy = 0.0f64;
485    for i in 0..rays {
486        let origin = if i == 0 {
487            source
488        } else {
489            // Fixed ring: spoke k of (rays - 1) around the source.
490            let ang = std::f64::consts::TAU * f64::from(i - 1) / f64::from(rays - 1);
491            source + (u * ang.cos() + v * ang.sin()) * cfg.jitter_radius
492        };
493        // AU2.0 — per-material weighting when the config carries
494        // tables; the empty-table default routes through the exact
495        // legacy arithmetic (bit-identical, pinned tests).
496        let t =
497            path_thickness_weighted(scene, origin, listener, &cfg.material_map, &cfg.absorption);
498        energy += (-cfg.absorption_per_voxel * t).exp();
499    }
500    #[allow(clippy::cast_possible_truncation)]
501    let transmission = (energy / f64::from(rays)).clamp(0.0, 1.0) as f32;
502
503    // Log-space cutoff interpolation: T = 1 ⇒ open, T = 0 ⇒ occluded.
504    let ratio = cfg.open_cutoff_hz / cfg.occluded_cutoff_hz;
505    let lowpass_cutoff_hz = cfg.occluded_cutoff_hz * ratio.powf(transmission);
506    let gain_db = cfg.max_occlusion_db * (1.0 - transmission);
507    SourceAcoustics {
508        transmission,
509        gain_db,
510        lowpass_cutoff_hz,
511        reverb_send_db: gain_db * cfg.send_occlusion_frac,
512    }
513}
514
515#[cfg(test)]
516mod tests {
517    use super::*;
518    use roxlap_scene::{GridTransform, VoxColor};
519
520    const STONE: VoxColor = VoxColor(0x80_66_77_88);
521
522    /// A scene with one identity grid; `build` shapes it.
523    fn scene_with(build: impl FnOnce(&mut roxlap_scene::Grid)) -> Scene {
524        let mut scene = Scene::new();
525        let id = scene.add_grid(GridTransform::identity());
526        build(scene.grid_mut(id).expect("grid just added"));
527        scene
528    }
529
530    /// A y/z-spanning wall of `thick` voxels starting at `x0`, with a
531    /// generous extent so jitter rays can't slip around the edges.
532    fn wall(grid: &mut roxlap_scene::Grid, x0: i32, thick: i32) {
533        grid.set_rect(
534            IVec3::new(x0, 0, 100),
535            IVec3::new(x0 + thick - 1, 127, 180),
536            Some(STONE),
537        );
538    }
539
540    #[test]
541    fn open_air_is_clear() {
542        let scene = scene_with(|_| {});
543        let cfg = AcousticsConfig::default();
544        let a = source_acoustics(
545            &scene,
546            DVec3::new(10.0, 40.0, 140.0),
547            DVec3::new(60.0, 40.0, 140.0),
548            &cfg,
549        );
550        assert_eq!(a, SourceAcoustics::clear(&cfg));
551    }
552
553    /// FW.4 — `hear_source` reveals a heard pocket scaled by transmission:
554    /// an open-air source is fully audible; a wall between it and the
555    /// listener muffles the reveal; a fully buried source reveals nothing.
556    #[test]
557    fn hear_source_scales_reveal_by_transmission() {
558        use roxlap_scene::{DeckBand, FogOfWar, VisionConfig};
559        let deck = DeckBand {
560            z_top: 90,
561            z_bottom: 200,
562        };
563        let mk_fow = || FogOfWar::new(VisionConfig::for_decks(vec![deck]));
564        let cfg = AcousticsConfig::default();
565        let src = DVec3::new(20.5, 5.5, 140.5);
566        let listener = DVec3::new(60.0, 5.0, 140.0);
567        // A single-chunk footprint so `footprint_cells` covers the source
568        // cell (20, 5).
569        let footprint =
570            |g: &mut roxlap_scene::Grid| g.gpu_residency_hint = Some(([0, 0, 0], [1, 1, 1]));
571
572        // Open air → full transmission → full loudness, cell revealed.
573        let mut open = Scene::new();
574        let gid = open.add_grid(GridTransform::identity());
575        footprint(open.grid_mut(gid).unwrap());
576        let mut fow = mk_fow();
577        let loud = hear_source(&open, &mut fow, gid, src, listener, 1.0, &cfg);
578        assert!(loud > 0.0, "open-air source is audible ({loud})");
579        // One tick turns the stamped blob into a Heard cell. Observer
580        // faces AWAY so (20,5) is not Visible — the heard reveal wins.
581        let grid = open.grids().next().expect("one grid").1;
582        fow.update(
583            grid,
584            &roxlap_scene::FowObserver {
585                cell: glam::IVec2::new(0, 0),
586                facing: -glam::Vec2::X,
587                deck: 0,
588                eye_z: 102,
589            },
590            0.1,
591        );
592        assert_eq!(
593            fow.state(0, glam::IVec2::new(20, 5)).0,
594            roxlap_scene::CellState::Heard,
595            "the heard source lights its cell"
596        );
597
598        // A wall between source and listener muffles the reveal.
599        let mut walled = Scene::new();
600        let wgid = walled.add_grid(GridTransform::identity());
601        {
602            let g = walled.grid_mut(wgid).unwrap();
603            wall(g, 30, 8);
604            footprint(g);
605        }
606        let mut fow2 = mk_fow();
607        let loud2 = hear_source(&walled, &mut fow2, wgid, src, listener, 1.0, &cfg);
608        assert!(loud2 < loud, "walled source is muffled: {loud2} vs {loud}");
609
610        // A source OUTSIDE the footprint (cell 500, 500) stamps nothing.
611        let mut fow3 = mk_fow();
612        let out = hear_source(
613            &open,
614            &mut fow3,
615            gid,
616            DVec3::new(500.5, 500.5, 140.5),
617            listener,
618            1.0,
619            &cfg,
620        );
621        assert_eq!(out, 0.0, "off-footprint source reveals nothing");
622    }
623
624    #[test]
625    fn thickness_is_exact_for_perpendicular_and_diagonal_crossings() {
626        let scene = scene_with(|g| wall(g, 30, 3));
627        // Perpendicular: exactly the wall's 3 voxels.
628        let t = path_thickness(
629            &scene,
630            DVec3::new(10.0, 40.5, 140.5),
631            DVec3::new(60.0, 40.5, 140.5),
632        );
633        assert!((t - 3.0).abs() < 1e-6, "perpendicular thickness: {t}");
634        // 45° in the xy plane: path length through 3 voxels of x-extent
635        // is 3·√2.
636        let t = path_thickness(
637            &scene,
638            DVec3::new(10.0, 20.5, 140.5),
639            DVec3::new(60.0, 70.5, 140.5),
640        );
641        assert!((t - 3.0 * 2.0f64.sqrt()).abs() < 1e-6, "diagonal: {t}");
642    }
643
644    #[test]
645    fn thicker_walls_muffle_monotonically() {
646        let cfg = AcousticsConfig::default();
647        let src = DVec3::new(10.0, 64.0, 140.5);
648        let dst = DVec3::new(60.0, 64.0, 140.5);
649        let mut prev = 1.0f32;
650        for thick in [1, 2, 5] {
651            let scene = scene_with(|g| wall(g, 30, thick));
652            let a = source_acoustics(&scene, src, dst, &cfg);
653            assert!(
654                a.transmission < prev,
655                "{thick}-voxel wall must transmit less than the previous ({} vs {prev})",
656                a.transmission
657            );
658            assert!(a.gain_db < 0.0 && a.gain_db >= cfg.max_occlusion_db);
659            assert!(a.lowpass_cutoff_hz < cfg.open_cutoff_hz);
660            assert!(a.lowpass_cutoff_hz > cfg.occluded_cutoff_hz);
661            prev = a.transmission;
662        }
663    }
664
665    #[test]
666    fn doorway_leaks_more_than_sealed_wall() {
667        let src = DVec3::new(10.0, 64.0, 140.5);
668        let dst = DVec3::new(60.0, 64.0, 140.5);
669        let cfg = AcousticsConfig::default();
670
671        let sealed = scene_with(|g| wall(g, 30, 2));
672        let sealed_a = source_acoustics(&sealed, src, dst, &cfg);
673
674        // Same wall with a slot punched just off the direct line. The
675        // ring converges toward the listener, so at the wall plane
676        // (40% of the way) the ±1.5 jitter has shrunk to ±0.9 voxels:
677        // the slot at cell y=63 (z 139..141) is inside that reach for
678        // the three −y spokes while the direct ray still hits rock.
679        let doorway = scene_with(|g| {
680            wall(g, 30, 2);
681            g.set_rect(IVec3::new(30, 63, 139), IVec3::new(31, 63, 141), None);
682        });
683        let door_a = source_acoustics(&doorway, src, dst, &cfg);
684        assert!(
685            door_a.transmission > sealed_a.transmission,
686            "doorway must leak: {} vs sealed {}",
687            door_a.transmission,
688            sealed_a.transmission
689        );
690        assert!(
691            door_a.transmission < 1.0,
692            "off-axis doorway is not fully clear"
693        );
694    }
695
696    #[test]
697    fn cross_chunk_wall_counts_once() {
698        // Wall straddling the x = 128 chunk seam: thickness must not
699        // double-count or drop the seam cell.
700        let scene = scene_with(|g| {
701            g.set_rect(
702                IVec3::new(126, 0, 100),
703                IVec3::new(129, 255, 180),
704                Some(STONE),
705            );
706        });
707        let t = path_thickness(
708            &scene,
709            DVec3::new(100.0, 64.5, 140.5),
710            DVec3::new(160.0, 64.5, 140.5),
711        );
712        assert!((t - 4.0).abs() < 1e-6, "seam-straddling wall: {t}");
713    }
714
715    #[test]
716    fn cross_grid_thickness_sums() {
717        // Two grids, one wall each, both crossed by the same segment.
718        let mut scene = Scene::new();
719        let id_a = scene.add_grid(GridTransform::identity());
720        wall(scene.grid_mut(id_a).expect("grid a"), 20, 2);
721        let id_b = scene.add_grid(GridTransform::at(DVec3::new(20.0, 0.0, 0.0)));
722        wall(scene.grid_mut(id_b).expect("grid b"), 20, 2); // world x = 40..42
723        let t = path_thickness(
724            &scene,
725            DVec3::new(10.0, 64.5, 140.5),
726            DVec3::new(60.0, 64.5, 140.5),
727        );
728        assert!((t - 4.0).abs() < 1e-6, "two 2-voxel walls: {t}");
729    }
730
731    #[test]
732    fn beyond_max_distance_reports_clear_not_buried() {
733        // Distance attenuation belongs to the spatial backend: past the
734        // march budget a source must NOT come back muffled (that would
735        // put a lowpass step function at the boundary).
736        let scene = scene_with(|g| wall(g, 30, 5));
737        let cfg = AcousticsConfig::default();
738        let a = source_acoustics(
739            &scene,
740            DVec3::new(10.0, 64.0, 140.5),
741            DVec3::new(10.0 + cfg.max_distance + 10.0, 64.0, 140.5),
742            &cfg,
743        );
744        assert_eq!(a, SourceAcoustics::clear(&cfg));
745    }
746
747    #[test]
748    fn rotated_grid_thickness_is_world_true() {
749        use glam::{DQuat, DVec3};
750        // A grid rotated 90° about world Z, placed so its local wall
751        // (3 voxels along local x) lands across the world-Y axis: the
752        // rebased segment must report the same world-true 3 voxels.
753        let mut scene = Scene::new();
754        let rot = DQuat::from_rotation_z(std::f64::consts::FRAC_PI_2);
755        let id = scene.add_grid(GridTransform {
756            origin: DVec3::new(0.0, 0.0, 0.0),
757            rotation: rot,
758            voxel_world_size: 1.0,
759        });
760        wall(scene.grid_mut(id).expect("rotated grid"), 30, 3);
761        // Local +x maps to world +y: the local x = 30..33 wall lies at
762        // world y = 30..33 (local y spans map to world -x). Probe along
763        // world +y through it; local y = 40 ⇒ world x = -40.
764        let t = path_thickness(
765            &scene,
766            DVec3::new(-40.5, 10.0, 140.5),
767            DVec3::new(-40.5, 60.0, 140.5),
768        );
769        assert!(
770            (t - 3.0).abs() < 1e-6,
771            "rotated-grid wall must stay 3 world voxels thick: {t}"
772        );
773        // Control: the same segment misses the wall in an identity grid.
774        let control = scene_with(|g| wall(g, 30, 3));
775        let t = path_thickness(
776            &control,
777            DVec3::new(-40.5, 10.0, 140.5),
778            DVec3::new(-40.5, 60.0, 140.5),
779        );
780        assert!(t.abs() < 1e-9, "identity control must miss: {t}");
781    }
782
783    #[test]
784    fn scaled_grid_thickness_is_world_scaled() {
785        // SC — a vws=2.0 grid: its voxels are 2× the world size, so a wall of
786        // 3 local voxels muffles 6 WORLD units of solid. Local x 30..32 → world
787        // x 60..66; local y 0..127 → world y 0..254; local z 100..180 → world
788        // z 200..360. A world +x probe through it must report 6, not 3.
789        let mut scene = Scene::new();
790        let id = scene.add_grid(GridTransform::at_scale(DVec3::ZERO, 2.0));
791        wall(scene.grid_mut(id).expect("scaled grid"), 30, 3);
792        let t = path_thickness(
793            &scene,
794            DVec3::new(40.0, 80.0, 280.0),
795            DVec3::new(140.0, 80.0, 280.0),
796        );
797        assert!(
798            (t - 6.0).abs() < 1e-6,
799            "vws=2 wall of 3 voxels must be 6 world units thick: {t}"
800        );
801    }
802
803    #[test]
804    fn empty_chunk_bottom_plane_is_acoustically_air() {
805        // CT.2 — inverted from `bedrock_plane_counts_as_solid_documented`:
806        // the z=255 bedrock placeholder is retired (empty chunks seed
807        // as sentinel columns), so a ray along the old bedrock plane
808        // accumulates NO thickness and the `grid_thickness` caveat is
809        // gone.
810        let scene = scene_with(|g| {
811            g.ensure_chunk(IVec3::ZERO);
812        });
813        let t = path_thickness(
814            &scene,
815            DVec3::new(10.0, 64.0, 255.5),
816            DVec3::new(20.0, 64.0, 255.5),
817        );
818        assert!(
819            t.abs() < 1e-9,
820            "empty chunk must be acoustically transparent, got thickness {t}"
821        );
822    }
823
824    #[test]
825    fn deterministic() {
826        let scene = scene_with(|g| wall(g, 30, 2));
827        let cfg = AcousticsConfig::default();
828        let src = DVec3::new(10.0, 64.0, 140.5);
829        let dst = DVec3::new(60.0, 64.0, 140.5);
830        let a = source_acoustics(&scene, src, dst, &cfg);
831        let b = source_acoustics(&scene, src, dst, &cfg);
832        assert_eq!(a, b);
833    }
834
835    // ---------- AU2.0: per-material absorption ----------
836
837    const GLASS: VoxColor = VoxColor(0x80_40_C0_E0);
838    const GLASS_ID: u8 = 7;
839
840    /// A thin (1-voxel-tall) wall at the ray height, `thick` voxels
841    /// along x — every cell is a surface cell, so every crossing
842    /// samples a colour (no carry-forward in play).
843    fn thin_wall(grid: &mut roxlap_scene::Grid, x0: i32, thick: i32, c: VoxColor) {
844        grid.set_rect(
845            IVec3::new(x0, 0, 140),
846            IVec3::new(x0 + thick - 1, 127, 140),
847            Some(c),
848        );
849    }
850
851    /// Empty tables route through the exact legacy arithmetic:
852    /// `path_thickness_weighted` equals `path_thickness` bit-for-bit,
853    /// and a config with a map but no absorption is byte-identical to
854    /// the default.
855    #[test]
856    fn empty_tables_are_bit_identical() {
857        let scene = scene_with(|g| wall(g, 30, 3));
858        let src = DVec3::new(10.0, 64.0, 140.5);
859        let dst = DVec3::new(60.0, 64.0, 140.5);
860        let plain = path_thickness(&scene, src, dst);
861        let weighted =
862            path_thickness_weighted(&scene, src, dst, &[(GLASS.rgb_part(), GLASS_ID)], &[]);
863        assert_eq!(
864            plain.to_bits(),
865            weighted.to_bits(),
866            "empty absorption = legacy path"
867        );
868
869        let cfg = AcousticsConfig {
870            material_map: vec![(GLASS.rgb_part(), GLASS_ID)],
871            ..AcousticsConfig::default()
872        };
873        let a = source_acoustics(&scene, src, dst, &AcousticsConfig::default());
874        let b = source_acoustics(&scene, src, dst, &cfg);
875        assert_eq!(a, b, "map without absorption changes nothing");
876    }
877
878    /// A glass wall muffles less than the same wall in stone: the
879    /// weighted thickness scales by the absorption factor (all cells
880    /// are surface cells here), and the transmission rises with it.
881    #[test]
882    fn glass_wall_transmits_more_than_stone() {
883        let scene = scene_with(|g| thin_wall(g, 30, 4, GLASS));
884        let src = DVec3::new(10.0, 64.0, 140.5);
885        let dst = DVec3::new(60.0, 64.0, 140.5);
886        let map = [(GLASS.rgb_part(), GLASS_ID)];
887        let table = [(GLASS_ID, 0.3f32)];
888
889        let plain = path_thickness(&scene, src, dst);
890        let weighted = path_thickness_weighted(&scene, src, dst, &map, &table);
891        assert!((plain - 4.0).abs() < 1e-6, "4 voxels of wall: {plain}");
892        assert!(
893            (weighted - plain * 0.3).abs() < 1e-6,
894            "glass counts at 0.3×: {weighted} vs {plain}"
895        );
896
897        let mut cfg = AcousticsConfig::default();
898        let base = source_acoustics(&scene, src, dst, &cfg);
899        cfg.material_map = map.to_vec();
900        cfg.absorption = table.to_vec();
901        let glass = source_acoustics(&scene, src, dst, &cfg);
902        assert!(
903            glass.transmission > base.transmission,
904            "glass passes more sound: {} vs {}",
905            glass.transmission,
906            base.transmission
907        );
908        // An unmapped material keeps stone weight: same wall colour but
909        // an absorption table for a DIFFERENT id changes nothing.
910        cfg.absorption = vec![(GLASS_ID + 1, 0.3)];
911        let unmapped = source_acoustics(&scene, src, dst, &cfg);
912        assert_eq!(unmapped.transmission, base.transmission);
913    }
914
915    /// Manual perf probe (release, `--ignored --nocapture`) — the AU2
916    /// profiling debt: the cost of `source_acoustics` and
917    /// `probe_cavity` with the material tables ACTIVE vs empty, on a
918    /// wall-heavy scene (the per-cell `voxel_color` slab walk is the
919    /// suspect).
920    #[test]
921    #[ignore = "manual perf probe — cargo test -p roxlap-audio --release weighted_tables_probe -- --ignored --nocapture"]
922    fn weighted_tables_probe() {
923        let scene = scene_with(|g| {
924            for x in [20, 30, 40, 50] {
925                wall(g, x, 3);
926            }
927        });
928        let src = DVec3::new(10.0, 64.0, 140.5);
929        let dst = DVec3::new(60.0, 64.0, 140.5);
930        let plain_cfg = AcousticsConfig::default();
931        let glass_cfg = AcousticsConfig {
932            material_map: vec![(GLASS.rgb_part(), GLASS_ID)],
933            absorption: vec![(GLASS_ID, 0.35)],
934            ..AcousticsConfig::default()
935        };
936        const N: u32 = 1_000;
937        let time = |cfg: &AcousticsConfig| {
938            let t0 = std::time::Instant::now();
939            for _ in 0..N {
940                std::hint::black_box(source_acoustics(&scene, src, dst, cfg));
941            }
942            t0.elapsed() / N
943        };
944        eprintln!(
945            "source_acoustics, 4 walls, tables empty:  {:?}",
946            time(&plain_cfg)
947        );
948        eprintln!(
949            "source_acoustics, 4 walls, tables ACTIVE: {:?}",
950            time(&glass_cfg)
951        );
952
953        let cav_plain = crate::CavityConfig::default();
954        let cav_glass = crate::CavityConfig {
955            material_map: vec![(GLASS.rgb_part(), GLASS_ID)],
956            damping_override: vec![(GLASS_ID, 0.1)],
957            ..crate::CavityConfig::default()
958        };
959        let listener = DVec3::new(25.0, 64.0, 140.5);
960        let time_cav = |cfg: &crate::CavityConfig| {
961            let t0 = std::time::Instant::now();
962            for _ in 0..N {
963                std::hint::black_box(crate::probe_cavity(&scene, listener, cfg));
964            }
965            t0.elapsed() / N
966        };
967        eprintln!("probe_cavity, tables empty:  {:?}", time_cav(&cav_plain));
968        eprintln!("probe_cavity, tables ACTIVE: {:?}", time_cav(&cav_glass));
969    }
970
971    // ---------- AU2.2: Doppler ----------
972
973    /// Approaching pitches up, receding down, rest is exactly neutral,
974    /// perpendicular motion is (numerically) neutral too.
975    #[test]
976    fn doppler_signs_and_rest() {
977        let c = DEFAULT_SPEED_OF_SOUND;
978        let s = DVec3::new(0.0, 0.0, 0.0);
979        let l = DVec3::new(50.0, 0.0, 0.0);
980        let at_rest = doppler_factor(s, DVec3::ZERO, l, DVec3::ZERO, c);
981        assert_eq!(at_rest.to_bits(), 1.0f32.to_bits(), "rest is exactly 1");
982
983        // Source flying toward the listener (+x) pitches up; away, down.
984        let up = doppler_factor(s, DVec3::new(30.0, 0.0, 0.0), l, DVec3::ZERO, c);
985        let down = doppler_factor(s, DVec3::new(-30.0, 0.0, 0.0), l, DVec3::ZERO, c);
986        assert!(up > 1.0 && down < 1.0, "source motion: {up} / {down}");
987
988        // Listener closing on the source pitches up symmetrically.
989        let l_up = doppler_factor(s, DVec3::ZERO, l, DVec3::new(-30.0, 0.0, 0.0), c);
990        let l_down = doppler_factor(s, DVec3::ZERO, l, DVec3::new(30.0, 0.0, 0.0), c);
991        assert!(
992            l_up > 1.0 && l_down < 1.0,
993            "listener motion: {l_up} / {l_down}"
994        );
995
996        // Perpendicular motion has no radial component.
997        let perp = doppler_factor(s, DVec3::new(0.0, 30.0, 0.0), l, DVec3::ZERO, c);
998        assert!((perp - 1.0).abs() < 1e-6, "perpendicular ≈ neutral: {perp}");
999    }
1000
1001    /// Extreme speeds clamp to the octave bounds instead of flipping
1002    /// sign or diverging; degenerate inputs are neutral.
1003    #[test]
1004    fn doppler_clamps_and_degenerates() {
1005        let c = DEFAULT_SPEED_OF_SOUND;
1006        let s = DVec3::ZERO;
1007        let l = DVec3::new(50.0, 0.0, 0.0);
1008        // Supersonic approach: clamps at 2.0, never negative.
1009        let mach2 = doppler_factor(s, DVec3::new(2.0 * c, 0.0, 0.0), l, DVec3::ZERO, c);
1010        assert_eq!(mach2, 2.0);
1011        // Supersonic retreat: floor at 0.5.
1012        let away = doppler_factor(s, DVec3::new(-3.0 * c, 0.0, 0.0), l, DVec3::ZERO, c);
1013        assert_eq!(away, 0.5);
1014        // Listener fleeing faster than sound: silence would be right,
1015        // pitch-wise we floor at 0.5 (the backend's distance
1016        // attenuation owns the rest).
1017        let flee = doppler_factor(s, DVec3::ZERO, l, DVec3::new(2.0 * c, 0.0, 0.0), c);
1018        assert_eq!(flee, 0.5);
1019        // Coincident points / zero speed of sound: neutral.
1020        assert_eq!(doppler_factor(s, DVec3::X, s, DVec3::ZERO, c), 1.0);
1021        assert_eq!(doppler_factor(s, DVec3::X, l, DVec3::ZERO, 0.0), 1.0);
1022    }
1023
1024    /// A ray descending through a tall run: only the run's surface
1025    /// cells carry colour (`.vxl` stores surface lists); the interior
1026    /// inherits the last surface colour crossed — a glass monolith
1027    /// stays glass all the way down.
1028    #[test]
1029    fn interior_inherits_surface_colour() {
1030        let scene = scene_with(|g| {
1031            g.set_rect(
1032                IVec3::new(40, 60, 100),
1033                IVec3::new(44, 68, 180),
1034                Some(GLASS),
1035            );
1036        });
1037        // Precondition: mid-run cells really are colour-less interior.
1038        let g = scene.grids().next().expect("one grid").1;
1039        assert_eq!(
1040            g.voxel_color(IVec3::new(42, 64, 140)),
1041            None,
1042            "test premise: interior cells carry no colour"
1043        );
1044
1045        let src = DVec3::new(42.5, 64.5, 90.0); // above the monolith
1046        let dst = DVec3::new(42.5, 64.5, 140.0); // buried inside it
1047        let map = [(GLASS.rgb_part(), GLASS_ID)];
1048        let table = [(GLASS_ID, 0.3f32)];
1049        let plain = path_thickness(&scene, src, dst);
1050        let weighted = path_thickness_weighted(&scene, src, dst, &map, &table);
1051        assert!((plain - 40.0).abs() < 1e-6, "40 buried voxels: {plain}");
1052        assert!(
1053            (weighted - plain * 0.3).abs() < 1e-6,
1054            "interior inherited the glass surface weight: {weighted}"
1055        );
1056    }
1057}