Skip to main content

roxlap_audio/
cavity.rs

1//! AU.1 — cavity estimation: reverb parameters from the space around
2//! the listener.
3//!
4//! A fixed golden-spiral fan of rays probes the free path in every
5//! direction ([`probe_cavity`], pure and deterministic); the mean free
6//! path reads as room size and the fraction of rays escaping the probe
7//! radius as openness. [`CavityEstimator`] wraps the probe with the
8//! heavy `(3·old + new) / 4`-style smoothing the prior art ships
9//! (Sound Filters, Teardown): the environment estimate converges over
10//! seconds and players read the lag as natural room acoustics, not as
11//! a parameter glitch.
12//!
13//! Cadence: the host calls [`CavityEstimator::update`] at a low rate
14//! (~2 Hz per the entry doc) — NOT per frame. Smoothing strength is
15//! per *update*, so a faster cadence converges faster.
16
17use glam::DVec3;
18use roxlap_formats::material::material_for_color;
19use roxlap_scene::{Rgb, Scene};
20
21/// Tuning knobs for the cavity probe + the reverb mapping.
22#[derive(Debug, Clone, PartialEq)]
23pub struct CavityConfig {
24    /// Rays in the golden-spiral fan. Default `32` (the Sound Physics
25    /// bounce budget). Clamped to at least 4.
26    pub rays: u32,
27    /// Probe radius, world/voxel units: rays that reach it without a
28    /// hit count as *escaped* (open sky / huge space). Also the free
29    /// path a miss contributes to the mean. Deliberately SEPARATE from
30    /// the occlusion budget (`AcousticsConfig::max_distance`, default
31    /// 128): occlusion reaches as far as sources are audible, the
32    /// reverb probe only needs the local room.
33    pub max_ray_dist: f64,
34    /// Reverb feedback (decay) in the smallest enclosed space.
35    pub min_feedback: f32,
36    /// Reverb feedback when the **enclosed** free path (walls actually
37    /// hit — escaped rays don't inflate room size) reaches
38    /// [`max_ray_dist`](Self::max_ray_dist).
39    pub max_feedback: f32,
40    /// Wet mix in a fully enclosed space.
41    pub max_wet: f32,
42    /// Openness at (and beyond) which the wet mix reaches zero. A
43    /// listener standing on open ground always has ~half the fan in
44    /// the ground, so raw openness tops out near `0.5` outdoors — this
45    /// threshold makes that read as *fully dry* instead of half-wet.
46    /// Default `0.5`; a sealed cavern (openness `0`) is unaffected.
47    pub outdoor_openness: f32,
48    /// Reverb damping (high-frequency loss) of the **default**
49    /// material — used verbatim when
50    /// [`damping_override`](Self::damping_override) is empty, and as
51    /// the fallback for unmapped materials / colour-less wall hits
52    /// when it is not (AU2.1).
53    pub damping: f32,
54    /// AU2.1 — the host's colour→material terrain map (the SAME map
55    /// [`crate::AcousticsConfig::material_map`] and the renderer
56    /// take), classifying the wall cells the probe rays hit. Only
57    /// consulted when [`damping_override`](Self::damping_override) is
58    /// non-empty.
59    pub material_map: Vec<(Rgb, u8)>,
60    /// AU2.1 — material id → reverb damping for walls of that
61    /// material: the probe's effective damping is the **mean over hit
62    /// rays** (a glass cavern at `0.1` rings brighter than stone at
63    /// the default). Unmapped materials and colour-less hits (carved
64    /// faces, bedrock) fall back to [`damping`](Self::damping).
65    /// **Empty (the default) keeps the exact legacy behaviour** —
66    /// `reverb_damping` passes [`damping`](Self::damping) through
67    /// bit-identically, no classification runs. Colours absent from
68    /// the map classify as material `0`, so an entry for id `0` here
69    /// re-damps every unmapped-but-coloured wall (the engine-wide
70    /// "0 = default material" convention).
71    pub damping_override: Vec<(u8, f32)>,
72    /// Fraction of the OLD smoothed value kept per
73    /// [`CavityEstimator::update`] — `0.75` is the prior art's
74    /// `(3·old + new) / 4`. `0` disables smoothing.
75    pub smoothing: f32,
76}
77
78impl Default for CavityConfig {
79    fn default() -> Self {
80        Self {
81            rays: 32,
82            max_ray_dist: 64.0,
83            min_feedback: 0.35,
84            max_feedback: 0.88,
85            max_wet: 0.5,
86            outdoor_openness: 0.5,
87            damping: 0.4,
88            material_map: Vec::new(),
89            damping_override: Vec::new(),
90            smoothing: 0.75,
91        }
92    }
93}
94
95/// Raw (unsmoothed) result of one [`probe_cavity`] fan.
96#[derive(Debug, Clone, Copy, PartialEq)]
97pub struct CavityProbe {
98    /// Mean free path across the WHOLE fan, world/voxel units — escaped
99    /// rays contribute [`CavityConfig::max_ray_dist`]. Diagnostic; the
100    /// reverb mapping does not use it (an open sky would masquerade as
101    /// a huge room).
102    pub mean_free_path: f32,
103    /// Mean free path across the rays that actually HIT a wall — the
104    /// room-size signal driving reverb feedback. Escaped rays don't
105    /// inflate it: on open ground only the short ground hits count, so
106    /// the "room" reads tiny. [`CavityConfig::max_ray_dist`] when no
107    /// ray hit anything (unbounded space; the wet mix is zero there
108    /// anyway).
109    pub enclosed_free_path: f32,
110    /// Fraction of rays that escaped the probe radius, `0..=1` —
111    /// `0` = sealed cavern, `~0.5` = standing on open ground.
112    pub openness: f32,
113    /// AU2.1 — effective reverb damping of the surrounding walls: the
114    /// mean per-material damping over hit rays (see
115    /// [`CavityConfig::damping_override`]). Exactly
116    /// [`CavityConfig::damping`] when the override table is empty or
117    /// no ray hit anything.
118    pub damping: f32,
119}
120
121/// Smoothed reverb parameters for the listener's surroundings,
122/// produced by [`CavityEstimator::update`]. Feed the reverb fields to
123/// the backend with long tweens (~1 s).
124#[derive(Debug, Clone, Copy, PartialEq)]
125pub struct ListenerAcoustics {
126    /// Smoothed mean free path (room size), world/voxel units.
127    pub mean_free_path: f32,
128    /// Smoothed openness, `0..=1`.
129    pub openness: f32,
130    /// Reverb feedback (decay): bigger enclosed space ⇒ longer tail.
131    pub reverb_feedback: f32,
132    /// Reverb damping — AU2.1: the smoothed per-material wall damping
133    /// (see [`CavityConfig::damping_override`]); exactly
134    /// [`CavityConfig::damping`] when no override table is set.
135    pub reverb_damping: f32,
136    /// Reverb wet mix, `0..=1`: scaled down by openness so outdoor
137    /// sound stays dry.
138    pub reverb_mix: f32,
139}
140
141/// Probe the space around `listener`: cast the golden-spiral fan and
142/// reduce it to a [`CavityProbe`]. Pure and deterministic — the fan is
143/// a fixed direction set, so tests pin exact values and the estimator
144/// can round-robin freely.
145///
146/// Two caveats:
147/// - A listener **inside solid** (camera clipped into rock) sees every
148///   ray hit at `t ≈ 0` and reads as a tiny sealed box (max wet, min
149///   feedback). Hosts whose listener can clip should guard or nudge
150///   the probe point out of solid first.
151/// - Rays go through `Scene::raycast`'s own march, NOT the
152///   chunk-borrow-cached thickness march `path_thickness` uses — when
153///   profiling, the fan's cost profile is `raycast`'s.
154#[must_use]
155pub fn probe_cavity(scene: &Scene, listener: DVec3, cfg: &CavityConfig) -> CavityProbe {
156    let rays = cfg.rays.max(4);
157    // AU2.1 — wall-material classification only runs with a non-empty
158    // override table; the empty default skips it entirely (legacy
159    // behaviour, `damping` passed through bit-identically).
160    let classify = !cfg.damping_override.is_empty();
161    let mut path_sum = 0.0f64;
162    let mut hit_sum = 0.0f64;
163    let mut damp_sum = 0.0f64;
164    let mut escaped = 0u32;
165    for k in 0..rays {
166        let dir = golden_spiral_dir(k, rays);
167        match scene.raycast(listener, dir, cfg.max_ray_dist) {
168            Some(hit) => {
169                path_sum += hit.t;
170                hit_sum += hit.t;
171                if classify {
172                    // Colour-less hits (carved faces, bedrock) fall
173                    // back to the default-material damping.
174                    let d = hit.color.map_or(cfg.damping, |c| resolve_damping(cfg, c.0));
175                    damp_sum += f64::from(d);
176                }
177            }
178            None => {
179                path_sum += cfg.max_ray_dist;
180                escaped += 1;
181            }
182        }
183    }
184    let hits = rays - escaped;
185    #[allow(clippy::cast_possible_truncation)]
186    CavityProbe {
187        mean_free_path: (path_sum / f64::from(rays)) as f32,
188        enclosed_free_path: if hits == 0 {
189            cfg.max_ray_dist as f32
190        } else {
191            (hit_sum / f64::from(hits)) as f32
192        },
193        openness: escaped as f32 / rays as f32,
194        damping: if !classify || hits == 0 {
195            cfg.damping
196        } else {
197            (damp_sum / f64::from(hits)) as f32
198        },
199    }
200}
201
202/// AU2.1 — the reverb damping of a wall colour: colour → material id
203/// (unmapped ⇒ `0`, the engine convention) → override entry, else the
204/// config's default damping.
205fn resolve_damping(cfg: &CavityConfig, colour: u32) -> f32 {
206    let id = material_for_color(&cfg.material_map, colour);
207    cfg.damping_override
208        .iter()
209        .find(|&&(m, _)| m == id)
210        .map_or(cfg.damping, |&(_, d)| d)
211}
212
213/// Direction `k` of an `n`-point golden-spiral sphere covering — the
214/// standard even covering of the unit sphere (unit length by
215/// construction).
216fn golden_spiral_dir(k: u32, n: u32) -> DVec3 {
217    const GOLDEN_ANGLE: f64 = 2.399_963_229_728_653; // π(3 − √5)
218    let z = 1.0 - 2.0 * (f64::from(k) + 0.5) / f64::from(n);
219    let r = (1.0 - z * z).sqrt();
220    let phi = GOLDEN_ANGLE * f64::from(k);
221    DVec3::new(r * phi.cos(), r * phi.sin(), z)
222}
223
224/// Stateful cavity estimator: [`probe_cavity`] plus the prior-art
225/// exponential smoothing, mapped to reverb parameters. One per
226/// listener; call [`update`](Self::update) at ~2 Hz and
227/// [`reset`](Self::reset) on teleports.
228#[derive(Debug, Clone)]
229pub struct CavityEstimator {
230    cfg: CavityConfig,
231    smoothed: Option<CavityProbe>,
232}
233
234impl CavityEstimator {
235    /// A fresh estimator; the first [`update`](Self::update) seeds the
236    /// smoothed state from the raw probe (no fade-in from a wrong
237    /// initial guess).
238    #[must_use]
239    pub fn new(cfg: CavityConfig) -> Self {
240        Self {
241            cfg,
242            smoothed: None,
243        }
244    }
245
246    /// The configuration this estimator was built with.
247    #[must_use]
248    pub fn config(&self) -> &CavityConfig {
249        &self.cfg
250    }
251
252    /// Drop the smoothed state — the next [`update`](Self::update)
253    /// re-seeds from the raw probe. Call on listener teleports so a
254    /// cavern's tail doesn't follow the player through a menu warp.
255    pub fn reset(&mut self) {
256        self.smoothed = None;
257    }
258
259    /// Probe, smooth, and map to reverb parameters.
260    pub fn update(&mut self, scene: &Scene, listener: DVec3) -> ListenerAcoustics {
261        let raw = probe_cavity(scene, listener, &self.cfg);
262        let s = self.cfg.smoothing.clamp(0.0, 1.0);
263        let sm = match self.smoothed {
264            None => raw,
265            Some(prev) => CavityProbe {
266                mean_free_path: prev.mean_free_path * s + raw.mean_free_path * (1.0 - s),
267                enclosed_free_path: prev.enclosed_free_path * s
268                    + raw.enclosed_free_path * (1.0 - s),
269                openness: prev.openness * s + raw.openness * (1.0 - s),
270                // AU2.1 — the material damping rides the same smoothing;
271                // with an empty override table the raw value IS the
272                // config constant, passed through untouched (blending a
273                // constant with itself could drift a ULP — the legacy
274                // contract is exact).
275                damping: if self.cfg.damping_override.is_empty() {
276                    raw.damping
277                } else {
278                    prev.damping * s + raw.damping * (1.0 - s)
279                },
280            },
281        };
282        self.smoothed = Some(sm);
283        self.params(sm)
284    }
285
286    /// Map a (smoothed) probe to reverb parameters — split out so the
287    /// mapping itself is testable without a scene.
288    ///
289    /// Room size comes from the **enclosed** free path only (escaped
290    /// rays must not read open sky as a huge hall), and the wet mix
291    /// hits zero at [`CavityConfig::outdoor_openness`] — a listener on
292    /// open ground (raw openness ~0.5, the ground owns the lower
293    /// hemisphere) is fully dry, not half-wet.
294    #[allow(clippy::cast_possible_truncation)]
295    fn params(&self, p: CavityProbe) -> ListenerAcoustics {
296        let size_norm =
297            (f64::from(p.enclosed_free_path) / self.cfg.max_ray_dist).clamp(0.0, 1.0) as f32;
298        let outdoor = self.cfg.outdoor_openness.max(1e-6);
299        let enclosure = ((outdoor - p.openness) / outdoor).clamp(0.0, 1.0);
300        ListenerAcoustics {
301            mean_free_path: p.mean_free_path,
302            openness: p.openness,
303            reverb_feedback: self.cfg.min_feedback
304                + (self.cfg.max_feedback - self.cfg.min_feedback) * size_norm,
305            // AU2.1 — the probe's material-classified damping (exactly
306            // `cfg.damping` when the override table is empty).
307            reverb_damping: p.damping,
308            reverb_mix: self.cfg.max_wet * enclosure,
309        }
310    }
311}
312
313#[cfg(test)]
314mod tests {
315    use super::*;
316    use glam::IVec3;
317    use roxlap_scene::{GridTransform, VoxColor};
318
319    const STONE: VoxColor = VoxColor(0x80_66_77_88);
320
321    /// A hollow cubic room of inner side `side`, centred at `c` (cell
322    /// coords), inside one identity grid; returns the scene + the room
323    /// centre as a world point.
324    fn room(side: i32, c: IVec3) -> (Scene, DVec3) {
325        let mut scene = Scene::new();
326        let id = scene.add_grid(GridTransform::identity());
327        let g = scene.grid_mut(id).expect("grid just added");
328        let h = side / 2;
329        let shell = 2;
330        g.set_rect(
331            c - IVec3::splat(h + shell),
332            c + IVec3::splat(h + shell),
333            Some(STONE),
334        );
335        g.set_rect(c - IVec3::splat(h), c + IVec3::splat(h), None);
336        let centre = DVec3::new(
337            f64::from(c.x) + 0.5,
338            f64::from(c.y) + 0.5,
339            f64::from(c.z) + 0.5,
340        );
341        (scene, centre)
342    }
343
344    #[test]
345    fn empty_scene_is_fully_open() {
346        let scene = Scene::new();
347        let cfg = CavityConfig::default();
348        let p = probe_cavity(&scene, DVec3::new(64.0, 64.0, 128.0), &cfg);
349        assert_eq!(p.openness, 1.0);
350        #[allow(clippy::cast_possible_truncation)]
351        let cap = cfg.max_ray_dist as f32;
352        assert!((p.mean_free_path - cap).abs() < 1e-4);
353        assert!((p.enclosed_free_path - cap).abs() < 1e-4, "no-hit sentinel");
354        // Mapping: unbounded space is bone dry regardless of feedback.
355        let a = CavityEstimator::new(cfg).params(p);
356        assert_eq!(a.reverb_mix, 0.0);
357    }
358
359    #[test]
360    fn bigger_room_reads_bigger_and_both_are_sealed() {
361        let cfg = CavityConfig::default();
362        let (small, sc) = room(8, IVec3::new(64, 64, 128));
363        let (big, bc) = room(40, IVec3::new(64, 64, 128));
364        let ps = probe_cavity(&small, sc, &cfg);
365        let pb = probe_cavity(&big, bc, &cfg);
366        assert_eq!(ps.openness, 0.0, "small room is sealed");
367        assert_eq!(pb.openness, 0.0, "big room is sealed");
368        assert!(
369            pb.mean_free_path > ps.mean_free_path * 2.0,
370            "room size ordering: big {} vs small {}",
371            pb.mean_free_path,
372            ps.mean_free_path
373        );
374
375        // Mapping: bigger sealed room ⇒ longer decay; both fully wet.
376        let est = CavityEstimator::new(cfg.clone());
377        let a_small = est.params(ps);
378        let a_big = est.params(pb);
379        assert!(a_big.reverb_feedback > a_small.reverb_feedback);
380        assert!((a_small.reverb_mix - cfg.max_wet).abs() < 1e-6);
381        assert!(a_small.reverb_feedback >= cfg.min_feedback);
382        assert!(a_big.reverb_feedback <= cfg.max_feedback);
383    }
384
385    #[test]
386    fn open_ground_is_much_drier_than_a_cavern() {
387        let cfg = CavityConfig::default();
388        // Flat ground: solid below z = 200, listener standing on it.
389        let mut scene = Scene::new();
390        let id = scene.add_grid(GridTransform::identity());
391        let g = scene.grid_mut(id).expect("grid");
392        g.set_rect(
393            IVec3::new(0, 0, 200),
394            IVec3::new(255, 255, 220),
395            Some(STONE),
396        );
397        let outdoors = probe_cavity(&scene, DVec3::new(128.0, 128.0, 198.0), &cfg);
398        assert!(
399            outdoors.openness > 0.4,
400            "standing on open ground, roughly the upper hemisphere escapes: {}",
401            outdoors.openness
402        );
403        // The room-size signal must NOT be inflated by the sky: only
404        // the short ground hits count.
405        assert!(
406            outdoors.enclosed_free_path < outdoors.mean_free_path * 0.6,
407            "enclosed path ({}) must ignore escaped rays (mean {})",
408            outdoors.enclosed_free_path,
409            outdoors.mean_free_path
410        );
411
412        let (cavern, cc) = room(40, IVec3::new(64, 64, 128));
413        let inside = probe_cavity(&cavern, cc, &cfg);
414        let est = CavityEstimator::new(cfg.clone());
415        let dry = est.params(outdoors);
416        let wet = est.params(inside);
417        // ABSOLUTE bounds — a relative comparison would let "audibly
418        // reverberant outdoors" hide behind an even wetter cavern.
419        assert!(
420            dry.reverb_mix < 0.05,
421            "open ground must be bone dry, got mix {}",
422            dry.reverb_mix
423        );
424        assert!(
425            dry.reverb_feedback < cfg.min_feedback + 0.15,
426            "open ground must not read as a big hall: feedback {}",
427            dry.reverb_feedback
428        );
429        assert!(
430            wet.reverb_mix > cfg.max_wet * 0.8,
431            "sealed cavern stays wet: {}",
432            wet.reverb_mix
433        );
434    }
435
436    #[test]
437    fn smoothing_seeds_raw_then_converges_monotonically() {
438        let cfg = CavityConfig::default();
439        let (small, sc) = room(8, IVec3::new(64, 64, 128));
440        let (big, bc) = room(40, IVec3::new(64, 64, 128));
441
442        let mut est = CavityEstimator::new(cfg.clone());
443        // First update seeds from raw — no fade-in from zero.
444        let first = est.update(&big, bc);
445        let raw_big = probe_cavity(&big, bc, &cfg);
446        assert!((first.mean_free_path - raw_big.mean_free_path).abs() < 1e-6);
447
448        // "Teleport" into the small room WITHOUT reset: the estimate
449        // must walk down monotonically toward the small-room value.
450        let raw_small = probe_cavity(&small, sc, &cfg);
451        let mut prev = first.mean_free_path;
452        for step in 0..12 {
453            let a = est.update(&small, sc);
454            assert!(
455                a.mean_free_path < prev,
456                "step {step}: estimate must decrease ({} vs {prev})",
457                a.mean_free_path
458            );
459            prev = a.mean_free_path;
460        }
461        assert!(
462            (prev - raw_small.mean_free_path).abs() < 2.0,
463            "after 12 updates the estimate ({prev}) nears the raw small-room value ({})",
464            raw_small.mean_free_path
465        );
466
467        // reset() re-seeds instantly.
468        est.reset();
469        let after = est.update(&big, bc);
470        assert!((after.mean_free_path - raw_big.mean_free_path).abs() < 1e-6);
471    }
472
473    #[test]
474    fn deterministic() {
475        let cfg = CavityConfig::default();
476        let (scene, c) = room(16, IVec3::new(64, 64, 128));
477        assert_eq!(probe_cavity(&scene, c, &cfg), probe_cavity(&scene, c, &cfg));
478    }
479
480    // ---------- AU2.1: per-material reverb character ----------
481
482    const GLASS: VoxColor = VoxColor(0x80_40_C0_E0);
483    const GLASS_ID: u8 = 7;
484
485    /// A sealed room built from six PAINTED slabs (never carved — a
486    /// carve leaves zero-RGB faces the probe couldn't classify): the
487    /// walls' surface cells keep their authored colour.
488    fn boxed_room(side: i32, c: IVec3, col: VoxColor) -> (Scene, DVec3) {
489        let mut scene = Scene::new();
490        let id = scene.add_grid(GridTransform::identity());
491        let g = scene.grid_mut(id).expect("grid just added");
492        let h = side / 2;
493        let (lo, hi) = (c - IVec3::splat(h), c + IVec3::splat(h));
494        for ax in 0..3 {
495            for side in 0..2 {
496                let mut slo = lo - IVec3::splat(2);
497                let mut shi = hi + IVec3::splat(2);
498                if side == 0 {
499                    shi[ax] = lo[ax] - 1;
500                } else {
501                    slo[ax] = hi[ax] + 1;
502                }
503                g.set_rect(slo, shi, Some(col));
504            }
505        }
506        let centre = DVec3::new(
507            f64::from(c.x) + 0.5,
508            f64::from(c.y) + 0.5,
509            f64::from(c.z) + 0.5,
510        );
511        (scene, centre)
512    }
513
514    fn glassy_cfg() -> CavityConfig {
515        CavityConfig {
516            material_map: vec![(GLASS.rgb_part(), GLASS_ID)],
517            damping_override: vec![(GLASS_ID, 0.1)],
518            ..CavityConfig::default()
519        }
520    }
521
522    /// Empty override table = the exact legacy path: probe damping and
523    /// the estimator's smoothed output both pass `cfg.damping` through
524    /// bit-for-bit (a map alone changes nothing).
525    #[test]
526    fn empty_override_damping_is_legacy_exact() {
527        let (scene, c) = boxed_room(16, IVec3::new(64, 64, 128), GLASS);
528        let cfg = CavityConfig {
529            material_map: vec![(GLASS.rgb_part(), GLASS_ID)],
530            ..CavityConfig::default()
531        };
532        let p = probe_cavity(&scene, c, &cfg);
533        assert_eq!(p.damping.to_bits(), cfg.damping.to_bits());
534
535        let mut est = CavityEstimator::new(cfg.clone());
536        let a = est.update(&scene, c);
537        let b = est.update(&scene, c); // second update takes the blend branch
538        assert_eq!(a.reverb_damping.to_bits(), cfg.damping.to_bits());
539        assert_eq!(b.reverb_damping.to_bits(), cfg.damping.to_bits());
540    }
541
542    /// A glass cavern rings brighter than a stone one: the override
543    /// classifies its walls to 0.1 damping, while the stone room's
544    /// unmapped colour keeps the default.
545    #[test]
546    fn glass_cavern_rings_brighter_than_stone() {
547        let cfg = glassy_cfg();
548        let (glass, gc) = boxed_room(16, IVec3::new(64, 64, 128), GLASS);
549        let (stone, sc) = boxed_room(16, IVec3::new(64, 64, 128), STONE);
550
551        let pg = probe_cavity(&glass, gc, &cfg);
552        let ps = probe_cavity(&stone, sc, &cfg);
553        assert_eq!(pg.openness, 0.0, "sealed glass box");
554        assert!(
555            (pg.damping - 0.1).abs() < 1e-4,
556            "all-glass walls take the override: {}",
557            pg.damping
558        );
559        assert_eq!(
560            ps.damping.to_bits(),
561            cfg.damping.to_bits(),
562            "unmapped stone keeps the default"
563        );
564
565        let mut est = CavityEstimator::new(cfg);
566        let a = est.update(&glass, gc);
567        assert!(
568            a.reverb_damping < 0.15,
569            "the mapped damping reaches the listener params: {}",
570            a.reverb_damping
571        );
572    }
573
574    /// A room with mixed walls averages: half glass, half stone lands
575    /// strictly between the two pure rooms.
576    #[test]
577    fn mixed_walls_average_damping() {
578        let cfg = glassy_cfg();
579        // Glass box, then repaint one half (x > centre) in stone by
580        // overlaying stone slabs on the inside faces of that half.
581        let c = IVec3::new(64, 64, 128);
582        let (mut scene, centre) = boxed_room(16, c, GLASS);
583        {
584            let id = scene.grids().next().expect("one grid").0;
585            let g = scene.grid_mut(id).expect("grid");
586            // A stone wall replacing the +x face, inside the room.
587            g.set_rect(
588                IVec3::new(c.x + 7, c.y - 10, c.z - 10),
589                IVec3::new(c.x + 7, c.y + 10, c.z + 10),
590                Some(STONE),
591            );
592        }
593        let p = probe_cavity(&scene, centre, &cfg);
594        assert!(
595            p.damping > 0.11 && p.damping < 0.39,
596            "mixed walls land between glass (0.1) and stone (0.4): {}",
597            p.damping
598        );
599    }
600}