Skip to main content

qualia_core_db/audio/
scene_audio_graph.rs

1//! Scene-Synchronized 3D Holosonic Wavefield & HRTF Audio Graph with Shared SDF + BVH Acoustic Occlusion.
2//!
3//! Implements Epic 8 of the QualiaDB Superior Game Engine architecture:
4//! - Synchronizes observer [`AudioListenerPose`] directly from camera PGA [`Motor`] (`r`, `d`).
5//! - Manages up to [`MAX_SCENE_AUDIO_EMITTERS`] = 64 active scene emitters ([`HolosonicNode`]s + point/ambient emitters)
6//!   sharing analytical SDF geometry ([`HolographicNodeGpu`] / `PROC1`) and epistemic certainty $q$.
7//! - Evaluates zero-heap acoustic occlusion ([`evaluate_acoustic_occlusion_zero_heap`]) against analytical SDF
8//!   primitives (sphere, capsule, rounded box) and BVH AABB/triangle obstacles with material-specific
9//!   absorption coefficients (rock/lithology, timber/trunk, foliage canopy, water surface).
10//! - Computes frequency-dependent RBJ low-pass biquad coefficients, direct-path transmission loss,
11//!   Fresnel/grazing phase diffraction delay $\Delta\phi$, and 6-tap early reflection geometry delays.
12//! - Executes a zero-heap 4-bus effect graph ([`SceneAudioBusGraph`]):
13//!   1. [`DirectBinauralBus`]: Continuous Holosonic wave superposition, per-emitter DF2T biquad occlusion
14//!      low-pass filtering, and zero-heap HRIR FIR binaural convolution (ITD + ILD + head-shadow).
15//!   2. [`EarlyReflectionsBus`]: 6-tap stereo early reflection delay line driven by obstacle geometry.
16//!   3. [`LateReverbFreeverbBus`]: Zero-heap stereo Schroeder/Freeverb 4-comb + 2-allpass reverb network
17//!      modulated by canyon/canopy enclosure density and manifold weight $w$.
18//!   4. [`HolosonicTelemetryBus`]: Fixed ring buffer of 48-byte [`HolosonicSonicToken48`] records + SPSC
19//!      publication into the `Q42` U3 [`SonicTokenRing`].
20
21use std::f32::consts::{PI, TAU};
22
23// New PCM behavior is isolated from this legacy combined graph/DSP module.
24// Decomposition and ownership are tracked in Ecopunk's SF-03 receipt.
25pub mod pcm;
26pub mod pcm_schedule;
27pub mod source_coupling;
28
29use crate::audio::acoustic_plane::push_sonic_token;
30use crate::audio::dsp::biquad_df2t::{BiquadCoeffs, Df2tState, DENORMAL_DC_OFFSET};
31#[allow(unused_imports)]
32use crate::audio::holosonic::HolosonicModality;
33use crate::audio::holosonic::{
34    HolosonicEmitter, HolosonicPointSample, HolosonicSonicToken48, HolosonicWavefield,
35    SPEED_OF_SOUND_MPS,
36};
37use crate::audio::hrtf::{binaural_from_position, BinauralGains};
38use crate::container_10d::procedural_synthesis::evaluate_smooth_minimum_sdf;
39#[cfg(feature = "gpu-runtime")]
40use crate::render::gpu::holographic::HolographicNodeGpu;
41use crate::render::pga::{sandwich_point, Motor};
42use crate::sonic_token::{SonicEventType, SonicToken, SONIC_MAGIC};
43
44/// Maximum active scene audio emitters processed in the zero-heap audio graph.
45pub const MAX_SCENE_AUDIO_EMITTERS: usize = 64;
46
47/// Number of early reflection geometry delay taps per acoustic occlusion evaluation.
48pub const EARLY_REFLECTION_TAPS: usize = 6;
49
50/// Zero-heap per-emitter short HRIR FIR tap count for real-time binaural convolution.
51pub const ZERO_HEAP_HRIR_TAPS: usize = 16;
52
53/// Fixed capacity of the 48-byte `HolosonicSonicToken48` telemetry ring buffer.
54pub const HOLOSONIC_TELEMETRY_RING_CAP: usize = 64;
55
56/// Observer audio listener pose synchronized from the camera's 3D PGA [`Motor`].
57#[repr(C)]
58#[derive(Debug, Clone, Copy, PartialEq)]
59pub struct AudioListenerPose {
60    /// World-space listener position `[x, y, z]` in meters.
61    pub position: [f32; 3],
62    /// Unit forward look direction `[fx, fy, fz]`.
63    pub forward: [f32; 3],
64    /// Unit up direction `[ux, uy, uz]`.
65    pub up: [f32; 3],
66    /// Unit right ear direction `[rx, ry, rz]`.
67    pub right: [f32; 3],
68    /// Linear velocity `[vx, vy, vz]` in m/s for Doppler shift.
69    pub velocity: [f32; 3],
70    /// Horizontal yaw angle in radians around +Y.
71    pub yaw_rad: f32,
72    /// Manifold domain coordinate `w` (modulates high-frequency room damping).
73    pub manifold_w: f32,
74}
75
76impl Default for AudioListenerPose {
77    fn default() -> Self {
78        Self {
79            position: [0.0, 0.0, 0.0],
80            forward: [0.0, 0.0, -1.0],
81            up: [0.0, 1.0, 0.0],
82            right: [1.0, 0.0, 0.0],
83            velocity: [0.0, 0.0, 0.0],
84            yaw_rad: 0.0,
85            manifold_w: 0.0,
86        }
87    }
88}
89
90impl AudioListenerPose {
91    /// Extracts the world-space listener position and orthonormal basis vectors directly
92    /// from a PGA [`Motor`] using the null-vector sandwich product $P' = M P \widetilde{M}$.
93    #[inline]
94    pub fn from_pga_motor(motor: Motor, velocity: [f32; 3], manifold_w: f32) -> Self {
95        let origin = sandwich_point(motor, [0.0, 0.0, 0.0]);
96        let px = sandwich_point(motor, [1.0, 0.0, 0.0]);
97        let py = sandwich_point(motor, [0.0, 1.0, 0.0]);
98        let pz = sandwich_point(motor, [0.0, 0.0, -1.0]);
99
100        let right = normalize3(
101            [px[0] - origin[0], px[1] - origin[1], px[2] - origin[2]],
102            [1.0, 0.0, 0.0],
103        );
104        let up = normalize3(
105            [py[0] - origin[0], py[1] - origin[1], py[2] - origin[2]],
106            [0.0, 1.0, 0.0],
107        );
108        let forward = normalize3(
109            [pz[0] - origin[0], pz[1] - origin[1], pz[2] - origin[2]],
110            [0.0, 0.0, -1.0],
111        );
112        let yaw_rad = forward[0].atan2(-forward[2]);
113
114        Self {
115            position: origin,
116            forward,
117            up,
118            right,
119            velocity,
120            yaw_rad,
121            manifold_w,
122        }
123    }
124}
125
126/// Scene-synchronized Holosonic / point / ambient audio emitter node.
127#[repr(C)]
128#[derive(Debug, Clone, Copy, PartialEq)]
129pub struct HolosonicNode {
130    /// Core Holosonic wavefield emitter parameters.
131    pub emitter: HolosonicEmitter,
132    /// Scene `NodePool` index or entity slot.
133    pub node_id: u32,
134    /// 64-bit `NQuin` semantic identity hash.
135    pub origin_quin_hash: u64,
136    /// Deontic permission state (`0 = Permitted`, `1 = Obligatory`, `2 = Forbidden/Escrow`).
137    pub deontic_permit: u8,
138    /// True if emitter is an omnidirectional ambient bed rather than a localized SDF source.
139    pub is_ambient: bool,
140    /// Shared `HolographicPrimitive` SDF archetype (`0 = Sphere`, `1 = RoundedBox`, `2 = Capsule`, etc.).
141    pub sdf_primitive: u8,
142    /// Padding for alignment.
143    pub reserved_u8: u8,
144    /// World-space emitter velocity `[vx, vy, vz]` in m/s (drives Doppler shift).
145    pub velocity: [f32; 3],
146    /// Analytical SDF half-extents `[hx, hy, hz]` in meters (for volumetric emission).
147    pub sdf_half_extents: [f32; 3],
148}
149
150impl Default for HolosonicNode {
151    fn default() -> Self {
152        Self {
153            emitter: HolosonicEmitter::default(),
154            node_id: 0,
155            origin_quin_hash: 0,
156            deontic_permit: 0,
157            is_ambient: false,
158            sdf_primitive: 0, // HolographicPrimitive::Sphere as u8
159            reserved_u8: 0,
160            velocity: [0.0; 3],
161            sdf_half_extents: [0.5, 0.5, 0.5],
162        }
163    }
164}
165
166impl HolosonicNode {
167    /// Synchronizes a [`HolosonicNode`] directly from a [`HolographicNodeGpu`] SDF proxy lens.
168    #[inline]
169    #[cfg(feature = "gpu-runtime")]
170    pub fn from_holographic_node(
171        node_id: u32,
172        origin_quin_hash: u64,
173        holo: &HolographicNodeGpu,
174        modality: HolosonicModality,
175    ) -> Self {
176        let pos = [
177            holo.position_scale[0],
178            holo.position_scale[1],
179            holo.position_scale[2],
180        ];
181        let scale = holo.position_scale[3].max(0.1);
182        let freq_hz = (holo.frequency_amplitude[0] * 110.0).clamp(40.0, 4000.0);
183        let amp = holo.frequency_amplitude[1].clamp(0.0, 1.0);
184        let phase = holo.frequency_amplitude[2];
185        let epistemic_q = holo.manifold_tensor[0].clamp(0.0, 1.0);
186        let prim = (holo.half_extents_primitive[3] as u32).min(4) as u8;
187
188        Self {
189            emitter: HolosonicEmitter::new(
190                pos,
191                freq_hz,
192                amp,
193                phase,
194                epistemic_q,
195                (scale * 18.0).clamp(5.0, 150.0),
196                modality,
197            ),
198            node_id,
199            origin_quin_hash,
200            deontic_permit: 0,
201            is_ambient: false,
202            sdf_primitive: prim,
203            reserved_u8: 0,
204            velocity: [0.0; 3],
205            sdf_half_extents: [
206                holo.half_extents_primitive[0] * scale,
207                holo.half_extents_primitive[1] * scale,
208                holo.half_extents_primitive[2] * scale,
209            ],
210        }
211    }
212}
213
214/// Physical surface & volumetric material class governing acoustic absorption, transmission loss,
215/// and early reflection scattering.
216#[repr(u8)]
217#[derive(Debug, Clone, Copy, PartialEq, Eq)]
218pub enum AcousticMaterial {
219    /// Dense silicate/granite/sandstone canyon wall: high reflection, strong transmission block.
220    RockLithology = 0,
221    /// Hardwood tree trunk / structural timber (`Corymbia` / `Eucalyptus`): medium-high transmission loss.
222    TimberTrunk = 1,
223    /// Volumetric foliage canopy / scrub: soft high-frequency rolloff, porous transmission.
224    FoliageCanopy = 2,
225    /// River / billabong water surface: high specular acoustic reflection.
226    WaterSurface = 3,
227}
228
229impl AcousticMaterial {
230    /// Direct-path transmission absorption coefficient per meter of obstacle thickness.
231    #[inline]
232    pub const fn transmission_absorption_per_m(self) -> f32 {
233        match self {
234            Self::RockLithology => 0.82,
235            Self::TimberTrunk => 0.55,
236            Self::FoliageCanopy => 0.22,
237            Self::WaterSurface => 0.65,
238        }
239    }
240
241    /// Specular early-reflection albedo coefficient in `[0.0, 1.0]`.
242    #[inline]
243    pub const fn reflection_albedo(self) -> f32 {
244        match self {
245            Self::RockLithology => 0.88,
246            Self::TimberTrunk => 0.58,
247            Self::FoliageCanopy => 0.24,
248            Self::WaterSurface => 0.92,
249        }
250    }
251
252    /// High-frequency low-pass cutoff multiplier when occluded by this material.
253    #[inline]
254    pub const fn cutoff_attenuation_factor(self) -> f32 {
255        match self {
256            Self::RockLithology => 0.14,
257            Self::TimberTrunk => 0.28,
258            Self::FoliageCanopy => 0.58,
259            Self::WaterSurface => 0.22,
260        }
261    }
262}
263
264/// Shared analytical SDF and BVH B-Rep obstacle shapes for zero-heap acoustic ray/cone queries.
265#[derive(Debug, Clone, Copy, PartialEq)]
266pub enum AcousticObstacleShape {
267    /// Analytical SDF sphere (`sdf(p) = |p - c| - r`), matching `HolographicPrimitive::Sphere`.
268    AnalyticalSphere { center: [f32; 3], radius: f32 },
269    /// Analytical SDF capsule (`sdf_capsule(p, a, b, r)`), matching `HolographicPrimitive::Capsule` / trunks.
270    AnalyticalCapsule {
271        a: [f32; 3],
272        b: [f32; 3],
273        radius: f32,
274    },
275    /// Analytical SDF rounded box (`sdf_round_box(p - c, b, r)`), matching `HolographicPrimitive::RoundedBox`.
276    AnalyticalRoundedBox {
277        center: [f32; 3],
278        half_extents: [f32; 3],
279        round_radius: f32,
280    },
281    /// BVH axis-aligned bounding box obstacle.
282    Aabb { min: [f32; 3], max: [f32; 3] },
283    /// B-Rep mesh triangle obstacle (Möller–Trumbore intersection).
284    Triangle {
285        v0: [f32; 3],
286        v1: [f32; 3],
287        v2: [f32; 3],
288    },
289}
290
291impl AcousticObstacleShape {
292    /// Evaluates the exact signed distance $d = \text{sdf}(\mathbf{p})$ to the obstacle at world point `p`.
293    #[inline]
294    pub fn signed_distance(&self, p: [f32; 3]) -> f32 {
295        match *self {
296            Self::AnalyticalSphere { center, radius } => length3(sub3(p, center)) - radius,
297            Self::AnalyticalCapsule { a, b, radius } => {
298                let pa = sub3(p, a);
299                let ba = sub3(b, a);
300                let baba = dot3(ba, ba).max(1e-6);
301                let h = (dot3(pa, ba) / baba).clamp(0.0, 1.0);
302                let closest = [a[0] + ba[0] * h, a[1] + ba[1] * h, a[2] + ba[2] * h];
303                length3(sub3(p, closest)) - radius
304            }
305            Self::AnalyticalRoundedBox {
306                center,
307                half_extents,
308                round_radius,
309            } => {
310                let q = [
311                    (p[0] - center[0]).abs() - half_extents[0],
312                    (p[1] - center[1]).abs() - half_extents[1],
313                    (p[2] - center[2]).abs() - half_extents[2],
314                ];
315                let outside = length3([q[0].max(0.0), q[1].max(0.0), q[2].max(0.0)]);
316                let inside = q[0].max(q[1].max(q[2])).min(0.0);
317                outside + inside - round_radius
318            }
319            Self::Aabb { min, max } => {
320                let center = [
321                    0.5 * (min[0] + max[0]),
322                    0.5 * (min[1] + max[1]),
323                    0.5 * (min[2] + max[2]),
324                ];
325                let half = [
326                    0.5 * (max[0] - min[0]).max(0.0),
327                    0.5 * (max[1] - min[1]).max(0.0),
328                    0.5 * (max[2] - min[2]).max(0.0),
329                ];
330                let q = [
331                    (p[0] - center[0]).abs() - half[0],
332                    (p[1] - center[1]).abs() - half[1],
333                    (p[2] - center[2]).abs() - half[2],
334                ];
335                let outside = length3([q[0].max(0.0), q[1].max(0.0), q[2].max(0.0)]);
336                let inside = q[0].max(q[1].max(q[2])).min(0.0);
337                outside + inside
338            }
339            Self::Triangle { v0, v1, v2 } => {
340                // Distance from point to triangle plane / centroid proxy
341                let e1 = sub3(v1, v0);
342                let e2 = sub3(v2, v0);
343                let n = normalize3(cross3(e1, e2), [0.0, 1.0, 0.0]);
344                dot3(sub3(p, v0), n).abs()
345            }
346        }
347    }
348
349    /// Representative obstacle centroid for early reflection bounce estimation.
350    #[inline]
351    pub fn centroid(&self) -> [f32; 3] {
352        match *self {
353            Self::AnalyticalSphere { center, .. } => center,
354            Self::AnalyticalCapsule { a, b, .. } => [
355                0.5 * (a[0] + b[0]),
356                0.5 * (a[1] + b[1]),
357                0.5 * (a[2] + b[2]),
358            ],
359            Self::AnalyticalRoundedBox { center, .. } => center,
360            Self::Aabb { min, max } => [
361                0.5 * (min[0] + max[0]),
362                0.5 * (min[1] + max[1]),
363                0.5 * (min[2] + max[2]),
364            ],
365            Self::Triangle { v0, v1, v2 } => [
366                (v0[0] + v1[0] + v2[0]) / 3.0,
367                (v0[1] + v1[1] + v2[1]) / 3.0,
368                (v0[2] + v1[2] + v2[2]) / 3.0,
369            ],
370        }
371    }
372}
373
374/// An acoustic obstacle in the shared SDF + BVH scene.
375#[derive(Debug, Clone, Copy, PartialEq)]
376pub struct AcousticObstacle {
377    pub shape: AcousticObstacleShape,
378    pub material: AcousticMaterial,
379    /// Effective acoustic path thickness in meters when penetrated.
380    pub thickness_m: f32,
381    /// Optional `PROC1` smooth-minimum blend radius $r$ (`evaluate_smooth_minimum_sdf`).
382    pub smooth_blend_radius: f32,
383}
384
385impl AcousticObstacle {
386    /// Creates an obstacle directly from a [`HolographicNodeGpu`] SDF proxy lens so visual
387    /// raymarching and acoustic occlusion share the exact same SDF primitive parameters.
388    #[inline]
389    #[cfg(feature = "gpu-runtime")]
390    pub fn from_holographic_node(node: &HolographicNodeGpu, material: AcousticMaterial) -> Self {
391        let center = [
392            node.position_scale[0],
393            node.position_scale[1],
394            node.position_scale[2],
395        ];
396        let scale = node.position_scale[3].max(0.05);
397        let he = [
398            node.half_extents_primitive[0] * scale,
399            node.half_extents_primitive[1] * scale,
400            node.half_extents_primitive[2] * scale,
401        ];
402        let prim_id = node.half_extents_primitive[3] as u32;
403        let shape = match prim_id {
404            1 => AcousticObstacleShape::AnalyticalRoundedBox {
405                center,
406                half_extents: he,
407                round_radius: 0.1 * scale,
408            },
409            2 => AcousticObstacleShape::AnalyticalCapsule {
410                a: [center[0], center[1] - he[1], center[2]],
411                b: [center[0], center[1] + he[1], center[2]],
412                radius: he[0].max(he[2]),
413            },
414            _ => AcousticObstacleShape::AnalyticalSphere {
415                center,
416                radius: he[0].max(he[1]).max(he[2]),
417            },
418        };
419        Self {
420            shape,
421            material,
422            thickness_m: (2.0f32 * he[0].min(he[1]).min(he[2])).max(0.25f32),
423            smooth_blend_radius: 0.25,
424        }
425    }
426}
427
428/// Result of zero-heap acoustic occlusion evaluation between an emitter and the listener.
429#[repr(C)]
430#[derive(Debug, Clone, Copy, PartialEq)]
431pub struct AcousticOcclusionResult {
432    /// Direct-path amplitude multiplier in `[0.0, 1.0]` (`1.0` = unoccluded).
433    pub direct_gain: f32,
434    /// Frequency-dependent low-pass filter cutoff in Hz (`20000.0` = unoccluded).
435    pub lowpass_cutoff_hz: f32,
436    /// Precomputed RBJ low-pass biquad filter coefficients at 48 kHz.
437    pub lowpass_biquad: BiquadCoeffs,
438    /// Phase diffraction delay $\Delta\phi$ in radians induced by obstacle grazing / penetration.
439    pub diffraction_phase_rad: f32,
440    /// 6-tap early reflection arrival delays in seconds relative to direct sound.
441    pub early_reflection_delays_s: [f32; EARLY_REFLECTION_TAPS],
442    /// 6-tap early reflection linear gains.
443    pub early_reflection_gains: [f32; EARLY_REFLECTION_TAPS],
444    /// Local canyon/canopy enclosure metric in `[0.0, 1.0]` driving late Freeverb decay.
445    pub enclosure_density: f32,
446    /// Number of obstacles intersecting the direct acoustic ray.
447    pub hit_count: u32,
448}
449
450impl Default for AcousticOcclusionResult {
451    fn default() -> Self {
452        Self {
453            direct_gain: 1.0,
454            lowpass_cutoff_hz: 18_000.0,
455            lowpass_biquad: calc_rbj_lowpass_coeffs(48_000.0, 18_000.0, 0.7071),
456            diffraction_phase_rad: 0.0,
457            early_reflection_delays_s: [0.008, 0.014, 0.021, 0.029, 0.038, 0.049],
458            early_reflection_gains: [0.0; EARLY_REFLECTION_TAPS],
459            enclosure_density: 0.1,
460            hit_count: 0,
461        }
462    }
463}
464
465/// Computes normalized RBJ cookbook 2nd-order low-pass [`BiquadCoeffs`] in zero heap.
466#[inline]
467pub fn calc_rbj_lowpass_coeffs(sample_rate: f32, cutoff_hz: f32, q: f32) -> BiquadCoeffs {
468    let sr = sample_rate.max(8_000.0);
469    let fc = cutoff_hz.clamp(80.0, sr * 0.45);
470    let w0 = TAU * fc / sr;
471    let cos_w0 = w0.cos();
472    let sin_w0 = w0.sin();
473    let alpha = sin_w0 / (2.0 * q.max(0.1));
474
475    let b0 = (1.0 - cos_w0) * 0.5;
476    let b1 = 1.0 - cos_w0;
477    let b2 = (1.0 - cos_w0) * 0.5;
478    let a0 = 1.0 + alpha;
479    let a1 = -2.0 * cos_w0;
480    let a2 = 1.0 - alpha;
481
482    let inv_a0 = 1.0 / a0.max(1e-6);
483    BiquadCoeffs {
484        b0: b0 * inv_a0,
485        b1: b1 * inv_a0,
486        b2: b2 * inv_a0,
487        a1: a1 * inv_a0,
488        a2: a2 * inv_a0,
489    }
490}
491
492/// Evaluates zero-heap acoustic occlusion, Fresnel SDF grazing diffraction, low-pass biquad cutoff,
493/// and 6-tap early reflection geometry delays between `listener_pos` and `emitter_pos`.
494pub fn evaluate_acoustic_occlusion_zero_heap(
495    listener_pos: [f32; 3],
496    emitter_pos: [f32; 3],
497    obstacles: &[AcousticObstacle],
498    out_occlusion: &mut AcousticOcclusionResult,
499) {
500    let delta = sub3(listener_pos, emitter_pos);
501    let direct_dist = length3(delta);
502    if direct_dist < 1e-4 {
503        *out_occlusion = AcousticOcclusionResult::default();
504        return;
505    }
506    let ray_dir = [
507        delta[0] / direct_dist,
508        delta[1] / direct_dist,
509        delta[2] / direct_dist,
510    ];
511
512    let mut total_transmission_gain = 1.0_f32;
513    let mut cutoff_hz = 18_000.0_f32;
514    let mut diffraction_phase = 0.0_f32;
515    let mut hit_count = 0u32;
516    let mut enclosure_accum = 0.0_f32;
517
518    // Reset 6-tap early reflections (ground bounce + 5 obstacle/canyon reflections)
519    let ground_bounce_extra_m =
520        ((emitter_pos[1].max(0.5) + listener_pos[1].max(0.5)).hypot(direct_dist) - direct_dist)
521            .max(0.5);
522    out_occlusion.early_reflection_delays_s = [
523        (ground_bounce_extra_m / SPEED_OF_SOUND_MPS).clamp(0.002, 0.080),
524        0.013,
525        0.019,
526        0.027,
527        0.035,
528        0.046,
529    ];
530    out_occlusion.early_reflection_gains = [0.12, 0.0, 0.0, 0.0, 0.0, 0.0];
531
532    let mut reflection_slot = 1usize;
533    let mut combined_sdf_min = f32::MAX;
534
535    for obs in obstacles {
536        let (hit, penetration_m, min_sdf_dist) = intersect_or_graze_obstacle(
537            &obs.shape,
538            emitter_pos,
539            ray_dir,
540            direct_dist,
541            obs.thickness_m,
542        );
543
544        combined_sdf_min =
545            evaluate_smooth_minimum_sdf(combined_sdf_min, min_sdf_dist, obs.smooth_blend_radius);
546
547        if hit {
548            hit_count += 1;
549            let eff_thickness = penetration_m.max(0.15);
550            let absorption = obs.material.transmission_absorption_per_m();
551            let trans = (-absorption * eff_thickness).exp().clamp(0.03, 1.0);
552            total_transmission_gain *= trans;
553            cutoff_hz *= obs.material.cutoff_attenuation_factor();
554            // Detour phase delay around/through obstacle
555            let detour_m = (eff_thickness * 0.35).min(4.0);
556            diffraction_phase += TAU * 440.0 * (detour_m / SPEED_OF_SOUND_MPS);
557        } else if min_sdf_dist < 1.5 {
558            // Grazing Fresnel diffraction zone near analytical SDF surface
559            let graze_t = (1.0 - (min_sdf_dist.max(0.0) / 1.5)).clamp(0.0, 1.0);
560            total_transmission_gain *= 1.0 - 0.18 * graze_t;
561            cutoff_hz *= 1.0 - 0.25 * graze_t;
562            diffraction_phase += 0.45 * graze_t;
563        }
564
565        // Evaluate 1st-order specular reflection tap via obstacle centroid
566        let c = obs.shape.centroid();
567        let d_emit_c = length3(sub3(c, emitter_pos));
568        let d_c_list = length3(sub3(listener_pos, c));
569        let path_diff_m = (d_emit_c + d_c_list - direct_dist).max(0.35);
570        if path_diff_m < 45.0 {
571            enclosure_accum += obs.material.reflection_albedo() / (1.0 + 0.08 * path_diff_m);
572            if reflection_slot < EARLY_REFLECTION_TAPS {
573                let delay_s = (path_diff_m / SPEED_OF_SOUND_MPS).clamp(0.002, 0.085);
574                let refl_gain = (obs.material.reflection_albedo()
575                    / (1.0 + 0.12 * (d_emit_c + d_c_list)))
576                    .clamp(0.01, 0.45);
577                out_occlusion.early_reflection_delays_s[reflection_slot] = delay_s;
578                out_occlusion.early_reflection_gains[reflection_slot] = refl_gain;
579                reflection_slot += 1;
580            }
581        }
582    }
583
584    // If multiple smooth-filleted SDFs form a narrow aperture (`combined_sdf_min < 0.0`),
585    // apply smooth fillet occlusion continuity
586    if combined_sdf_min < 0.0 && hit_count == 0 {
587        total_transmission_gain *= 0.65;
588        cutoff_hz *= 0.55;
589    }
590
591    let final_cutoff = cutoff_hz.clamp(220.0, 18_000.0);
592    out_occlusion.direct_gain = total_transmission_gain.clamp(0.02, 1.0);
593    out_occlusion.lowpass_cutoff_hz = final_cutoff;
594    out_occlusion.lowpass_biquad = calc_rbj_lowpass_coeffs(48_000.0, final_cutoff, 0.7071);
595    out_occlusion.diffraction_phase_rad = diffraction_phase;
596    out_occlusion.enclosure_density = (0.12 + enclosure_accum * 0.25).clamp(0.05, 0.98);
597    out_occlusion.hit_count = hit_count;
598}
599
600/// Tests ray segment `origin + t * dir` (`t in [0, max_dist]`) against an [`AcousticObstacleShape`].
601/// Returns `(did_hit, penetration_thickness_m, closest_signed_distance_m)`.
602fn intersect_or_graze_obstacle(
603    shape: &AcousticObstacleShape,
604    origin: [f32; 3],
605    dir: [f32; 3],
606    max_dist: f32,
607    default_thickness: f32,
608) -> (bool, f32, f32) {
609    match *shape {
610        AcousticObstacleShape::AnalyticalSphere { center, radius } => {
611            let oc = sub3(origin, center);
612            let b = dot3(oc, dir);
613            let c = dot3(oc, oc) - radius * radius;
614            let t_closest = (-b).clamp(0.0, max_dist);
615            let closest_pt = [
616                origin[0] + dir[0] * t_closest,
617                origin[1] + dir[1] * t_closest,
618                origin[2] + dir[2] * t_closest,
619            ];
620            let min_sdf = length3(sub3(closest_pt, center)) - radius;
621            let disc = b * b - c;
622            if disc <= 0.0 {
623                return (false, 0.0, min_sdf);
624            }
625            let sqrt_d = disc.sqrt();
626            let t0 = (-b - sqrt_d).max(0.0);
627            let t1 = (-b + sqrt_d).min(max_dist);
628            if t1 > t0 {
629                (true, (t1 - t0).max(0.1), min_sdf)
630            } else {
631                (false, 0.0, min_sdf)
632            }
633        }
634        AcousticObstacleShape::AnalyticalCapsule { a, b, radius }
635        | AcousticObstacleShape::AnalyticalRoundedBox {
636            center: a,
637            half_extents: b,
638            round_radius: radius,
639        } => {
640            // Fixed-step zero-heap sphere-march / sample along the segment [0, max_dist]
641            let _ = (a, b, radius);
642            const STEPS: usize = 16;
643            let dt = max_dist / (STEPS as f32);
644            let mut min_sdf = f32::MAX;
645            let mut inside_steps = 0usize;
646            for s in 0..=STEPS {
647                let t = (s as f32) * dt;
648                let p = [
649                    origin[0] + dir[0] * t,
650                    origin[1] + dir[1] * t,
651                    origin[2] + dir[2] * t,
652                ];
653                let d = shape.signed_distance(p);
654                if d < min_sdf {
655                    min_sdf = d;
656                }
657                if d <= 0.0 {
658                    inside_steps += 1;
659                }
660            }
661            if inside_steps > 0 {
662                let chord = (inside_steps as f32 * dt).max(default_thickness * 0.5);
663                (true, chord, min_sdf)
664            } else {
665                (false, 0.0, min_sdf)
666            }
667        }
668        AcousticObstacleShape::Aabb { min, max } => {
669            let mut tmin = 0.0_f32;
670            let mut tmax = max_dist;
671            for axis in 0..3 {
672                if dir[axis].abs() < 1e-6 {
673                    if origin[axis] < min[axis] || origin[axis] > max[axis] {
674                        return (false, 0.0, 2.0);
675                    }
676                } else {
677                    let inv_d = 1.0 / dir[axis];
678                    let mut t1 = (min[axis] - origin[axis]) * inv_d;
679                    let mut t2 = (max[axis] - origin[axis]) * inv_d;
680                    if t1 > t2 {
681                        core::mem::swap(&mut t1, &mut t2);
682                    }
683                    tmin = tmin.max(t1);
684                    tmax = tmax.min(t2);
685                    if tmin > tmax {
686                        return (false, 0.0, 2.0);
687                    }
688                }
689            }
690            let chord = (tmax - tmin).max(default_thickness);
691            (true, chord, -0.5 * chord)
692        }
693        AcousticObstacleShape::Triangle { v0, v1, v2 } => {
694            // Möller–Trumbore ray-triangle intersection
695            let edge1 = sub3(v1, v0);
696            let edge2 = sub3(v2, v0);
697            let h = cross3(dir, edge2);
698            let a = dot3(edge1, h);
699            if a.abs() < 1e-6 {
700                return (false, 0.0, 2.0);
701            }
702            let f = 1.0 / a;
703            let s = sub3(origin, v0);
704            let u = f * dot3(s, h);
705            if !(0.0..=1.0).contains(&u) {
706                return (false, 0.0, 2.0);
707            }
708            let q = cross3(s, edge1);
709            let v = f * dot3(dir, q);
710            if v < 0.0 || u + v > 1.0 {
711                return (false, 0.0, 2.0);
712            }
713            let t = f * dot3(edge2, q);
714            if t > 1e-4 && t < max_dist {
715                (true, default_thickness.max(0.25), -0.1)
716            } else {
717                (false, 0.0, 2.0)
718            }
719        }
720    }
721}
722
723// ─────────────────────────────────────────────────────────────────────────────
724//  Zero-Heap Multi-Bus Effect Graph
725// ─────────────────────────────────────────────────────────────────────────────
726
727/// Bus 1: Direct Binaural Bus — per-emitter DF2T occlusion low-pass filter + zero-heap
728/// HRIR FIR convolution (ITD fractional delay + ILD + contralateral head-shadow).
729#[derive(Debug, Clone)]
730pub struct DirectBinauralBus {
731    /// Per-emitter DF2T biquad state registers.
732    pub biquad_states: [Df2tState; MAX_SCENE_AUDIO_EMITTERS],
733    /// Per-emitter circular mono history buffer for zero-heap HRIR FIR convolution.
734    pub fir_history: [[f32; ZERO_HEAP_HRIR_TAPS]; MAX_SCENE_AUDIO_EMITTERS],
735    /// Per-emitter write cursor into `fir_history`.
736    pub fir_cursor: [u8; MAX_SCENE_AUDIO_EMITTERS],
737}
738
739impl Default for DirectBinauralBus {
740    fn default() -> Self {
741        Self {
742            biquad_states: [Df2tState::default(); MAX_SCENE_AUDIO_EMITTERS],
743            fir_history: [[0.0; ZERO_HEAP_HRIR_TAPS]; MAX_SCENE_AUDIO_EMITTERS],
744            fir_cursor: [0; MAX_SCENE_AUDIO_EMITTERS],
745        }
746    }
747}
748
749impl DirectBinauralBus {
750    /// Resets all filter and FIR delay states.
751    pub fn reset(&mut self) {
752        self.biquad_states = [Df2tState::default(); MAX_SCENE_AUDIO_EMITTERS];
753        self.fir_history = [[0.0; ZERO_HEAP_HRIR_TAPS]; MAX_SCENE_AUDIO_EMITTERS];
754        self.fir_cursor = [0; MAX_SCENE_AUDIO_EMITTERS];
755    }
756
757    /// Filters a single mono emitter sample through its occlusion DF2T biquad and convolves
758    /// it with the synthesized left/right HRIR taps (`BinauralGains` from `hrtf.rs`).
759    #[inline]
760    pub fn process_emitter_sample(
761        &mut self,
762        emitter_idx: usize,
763        mono_input: f32,
764        coeffs: &BiquadCoeffs,
765        gains: &BinauralGains,
766        sample_rate: f32,
767    ) -> (f32, f32) {
768        let idx = emitter_idx % MAX_SCENE_AUDIO_EMITTERS;
769        let st = &mut self.biquad_states[idx];
770        let x = mono_input + DENORMAL_DC_OFFSET;
771        let filtered = coeffs.b0 * x + st.s1;
772        st.s1 = coeffs.b1 * x - coeffs.a1 * filtered + st.s2;
773        st.s2 = coeffs.b2 * x - coeffs.a2 * filtered;
774
775        // Write filtered sample into circular FIR history
776        let cur = (self.fir_cursor[idx] as usize) % ZERO_HEAP_HRIR_TAPS;
777        self.fir_history[idx][cur] = filtered;
778        self.fir_cursor[idx] = ((cur + 1) % ZERO_HEAP_HRIR_TAPS) as u8;
779
780        // Fractional ITD sample delay for contralateral ear (clamped to ZERO_HEAP_HRIR_TAPS - 2)
781        let delay_samples = (gains.itd_seconds.abs() * sample_rate.max(8_000.0))
782            .clamp(0.0, (ZERO_HEAP_HRIR_TAPS - 2) as f32);
783        let d_int = delay_samples.floor() as usize;
784        let d_frac = delay_samples - d_int as f32;
785
786        let idx0 = (cur + ZERO_HEAP_HRIR_TAPS - d_int) % ZERO_HEAP_HRIR_TAPS;
787        let idx1 = (cur + ZERO_HEAP_HRIR_TAPS - (d_int + 1)) % ZERO_HEAP_HRIR_TAPS;
788        let delayed =
789            self.fir_history[idx][idx0] * (1.0 - d_frac) + self.fir_history[idx][idx1] * d_frac;
790        // Gentle contralateral 2-tap head-shadow smoothing
791        let shadow_delayed = 0.65 * delayed + 0.35 * self.fir_history[idx][idx1];
792
793        if gains.itd_seconds <= 0.0 {
794            // Source to left: left ear immediate, right ear delayed + head-shadowed
795            (filtered * gains.gain_l, shadow_delayed * gains.gain_r)
796        } else {
797            // Source to right: right ear immediate, left ear delayed + head-shadowed
798            (shadow_delayed * gains.gain_l, filtered * gains.gain_r)
799        }
800    }
801}
802
803/// Bus 2: 6-Tap Early Reflections Bus — stereo multi-tap delay line driven by scene geometry.
804#[derive(Debug, Clone)]
805pub struct EarlyReflectionsBus {
806    buffer_l: [f32; 4096],
807    buffer_r: [f32; 4096],
808    write_pos: usize,
809}
810
811impl Default for EarlyReflectionsBus {
812    fn default() -> Self {
813        Self {
814            buffer_l: [0.0; 4096],
815            buffer_r: [0.0; 4096],
816            write_pos: 0,
817        }
818    }
819}
820
821impl EarlyReflectionsBus {
822    /// Clears early reflection delay lines.
823    pub fn reset(&mut self) {
824        self.buffer_l.fill(0.0);
825        self.buffer_r.fill(0.0);
826        self.write_pos = 0;
827    }
828
829    /// Advances one stereo sample through the 6-tap early reflection geometry delay line.
830    #[inline]
831    pub fn tick(
832        &mut self,
833        in_l: f32,
834        in_r: f32,
835        delays_s: &[f32; EARLY_REFLECTION_TAPS],
836        gains: &[f32; EARLY_REFLECTION_TAPS],
837        sample_rate: f32,
838    ) -> (f32, f32) {
839        let cap = self.buffer_l.len();
840        self.buffer_l[self.write_pos] = in_l + DENORMAL_DC_OFFSET;
841        self.buffer_r[self.write_pos] = in_r + DENORMAL_DC_OFFSET;
842
843        let mut out_l = 0.0_f32;
844        let mut out_r = 0.0_f32;
845        for tap in 0..EARLY_REFLECTION_TAPS {
846            let g = gains[tap];
847            if g <= 1e-5 {
848                continue;
849            }
850            let d_samples = ((delays_s[tap] * sample_rate) as usize).clamp(1, cap - 1);
851            let read_pos = (self.write_pos + cap - d_samples) % cap;
852            // Alternate cross-ear lateral reflections for spacious canyon image
853            if tap & 1 == 0 {
854                out_l += self.buffer_l[read_pos] * g;
855                out_r += self.buffer_r[read_pos] * (g * 0.85);
856            } else {
857                out_l += self.buffer_r[read_pos] * (g * 0.85);
858                out_r += self.buffer_l[read_pos] * g;
859            }
860        }
861
862        self.write_pos = (self.write_pos + 1) % cap;
863        (out_l, out_r)
864    }
865}
866
867/// Zero-heap Schroeder/Moorer low-pass feedback comb filter for Freeverb.
868#[derive(Debug, Clone)]
869pub struct ZeroHeapCombFilter<const N: usize> {
870    buffer: [f32; N],
871    idx: usize,
872    filter_store: f32,
873}
874
875impl<const N: usize> Default for ZeroHeapCombFilter<N> {
876    fn default() -> Self {
877        Self {
878            buffer: [0.0; N],
879            idx: 0,
880            filter_store: 0.0,
881        }
882    }
883}
884
885impl<const N: usize> ZeroHeapCombFilter<N> {
886    #[inline]
887    pub fn reset(&mut self) {
888        self.buffer.fill(0.0);
889        self.idx = 0;
890        self.filter_store = 0.0;
891    }
892
893    #[inline]
894    pub fn process(&mut self, input: f32, feedback: f32, damp1: f32, damp2: f32) -> f32 {
895        let output = self.buffer[self.idx];
896        self.filter_store = output * damp2 + self.filter_store * damp1 + DENORMAL_DC_OFFSET;
897        self.buffer[self.idx] = input + self.filter_store * feedback;
898        self.idx = (self.idx + 1) % N;
899        output
900    }
901}
902
903/// Zero-heap Schroeder all-pass diffuser stage for Freeverb.
904#[derive(Debug, Clone)]
905pub struct ZeroHeapAllpassFilter<const N: usize> {
906    buffer: [f32; N],
907    idx: usize,
908}
909
910impl<const N: usize> Default for ZeroHeapAllpassFilter<N> {
911    fn default() -> Self {
912        Self {
913            buffer: [0.0; N],
914            idx: 0,
915        }
916    }
917}
918
919impl<const N: usize> ZeroHeapAllpassFilter<N> {
920    #[inline]
921    pub fn reset(&mut self) {
922        self.buffer.fill(0.0);
923        self.idx = 0;
924    }
925
926    #[inline]
927    pub fn process(&mut self, input: f32) -> f32 {
928        let buf_out = self.buffer[self.idx];
929        let output = -input + buf_out;
930        self.buffer[self.idx] = input + buf_out * 0.5 + DENORMAL_DC_OFFSET;
931        self.idx = (self.idx + 1) % N;
932        output
933    }
934}
935
936/// Bus 3: Zero-Heap Stereo Freeverb Bus (4 parallel comb filters + 2 series all-pass filters per ear)
937/// driven by local canyon/canopy enclosure metrics.
938#[derive(Debug, Clone, Default)]
939pub struct LateReverbFreeverbBus {
940    comb_l0: ZeroHeapCombFilter<1116>,
941    comb_l1: ZeroHeapCombFilter<1188>,
942    comb_l2: ZeroHeapCombFilter<1277>,
943    comb_l3: ZeroHeapCombFilter<1356>,
944    comb_r0: ZeroHeapCombFilter<1139>,
945    comb_r1: ZeroHeapCombFilter<1211>,
946    comb_r2: ZeroHeapCombFilter<1300>,
947    comb_r3: ZeroHeapCombFilter<1379>,
948    allpass_l0: ZeroHeapAllpassFilter<556>,
949    allpass_l1: ZeroHeapAllpassFilter<441>,
950    allpass_r0: ZeroHeapAllpassFilter<579>,
951    allpass_r1: ZeroHeapAllpassFilter<464>,
952    pub room_size: f32,
953    pub damping: f32,
954    pub wet_level: f32,
955}
956
957impl LateReverbFreeverbBus {
958    /// Creates a new zero-heap stereo Freeverb bus.
959    pub fn new(room_size: f32, damping: f32, wet_level: f32) -> Self {
960        Self {
961            room_size: room_size.clamp(0.1, 0.98),
962            damping: damping.clamp(0.05, 0.95),
963            wet_level: wet_level.clamp(0.0, 1.0),
964            ..Default::default()
965        }
966    }
967
968    /// Updates reverb enclosure parameters from scene canyon/canopy enclosure density.
969    #[inline]
970    pub fn configure_from_enclosure(&mut self, enclosure_density: f32, manifold_w: f32) {
971        let enc = enclosure_density.clamp(0.0, 1.0);
972        self.room_size = (0.45 + enc * 0.48).clamp(0.2, 0.95);
973        self.damping = (0.25 + manifold_w.clamp(0.0, 4.0) * 0.12).clamp(0.15, 0.85);
974        self.wet_level = (0.08 + enc * 0.35).clamp(0.05, 0.55);
975    }
976
977    /// Resets all comb and all-pass delay buffers.
978    pub fn reset(&mut self) {
979        self.comb_l0.reset();
980        self.comb_l1.reset();
981        self.comb_l2.reset();
982        self.comb_l3.reset();
983        self.comb_r0.reset();
984        self.comb_r1.reset();
985        self.comb_r2.reset();
986        self.comb_r3.reset();
987        self.allpass_l0.reset();
988        self.allpass_l1.reset();
989        self.allpass_r0.reset();
990        self.allpass_r1.reset();
991    }
992
993    /// Processes a stereo input pair and returns the wet stereo reverb output.
994    #[inline]
995    pub fn tick(&mut self, in_l: f32, in_r: f32) -> (f32, f32) {
996        let input = (in_l + in_r) * 0.015;
997        let feedback = 0.70 + self.room_size * 0.28;
998        let damp1 = self.damping * 0.4;
999        let damp2 = 1.0 - damp1;
1000
1001        let mut out_l = self.comb_l0.process(input, feedback, damp1, damp2)
1002            + self.comb_l1.process(input, feedback, damp1, damp2)
1003            + self.comb_l2.process(input, feedback, damp1, damp2)
1004            + self.comb_l3.process(input, feedback, damp1, damp2);
1005
1006        let mut out_r = self.comb_r0.process(input, feedback, damp1, damp2)
1007            + self.comb_r1.process(input, feedback, damp1, damp2)
1008            + self.comb_r2.process(input, feedback, damp1, damp2)
1009            + self.comb_r3.process(input, feedback, damp1, damp2);
1010
1011        out_l = self.allpass_l0.process(out_l);
1012        out_l = self.allpass_l1.process(out_l);
1013        out_r = self.allpass_r0.process(out_r);
1014        out_r = self.allpass_r1.process(out_r);
1015
1016        (out_l * self.wet_level, out_r * self.wet_level)
1017    }
1018}
1019
1020/// Bus 4: Fixed-capacity ring buffer of 48-byte [`HolosonicSonicToken48`] telemetry tokens.
1021#[derive(Debug, Clone)]
1022pub struct HolosonicTelemetryBus {
1023    pub tokens: [HolosonicSonicToken48; HOLOSONIC_TELEMETRY_RING_CAP],
1024    pub write_idx: usize,
1025    pub read_idx: usize,
1026    pub count: usize,
1027}
1028
1029impl Default for HolosonicTelemetryBus {
1030    fn default() -> Self {
1031        Self {
1032            tokens: [HolosonicSonicToken48::default(); HOLOSONIC_TELEMETRY_RING_CAP],
1033            write_idx: 0,
1034            read_idx: 0,
1035            count: 0,
1036        }
1037    }
1038}
1039
1040impl HolosonicTelemetryBus {
1041    /// Pushes a 48-byte [`HolosonicSonicToken48`] into the local ring and forwards the packed
1042    /// 64-bit [`SonicToken`] to the process-global U3 [`SonicTokenRing`].
1043    #[inline]
1044    pub fn push(&mut self, token48: HolosonicSonicToken48, packed64: SonicToken) {
1045        self.tokens[self.write_idx] = token48;
1046        self.write_idx = (self.write_idx + 1) % HOLOSONIC_TELEMETRY_RING_CAP;
1047        if self.count < HOLOSONIC_TELEMETRY_RING_CAP {
1048            self.count += 1;
1049        } else {
1050            self.read_idx = (self.read_idx + 1) % HOLOSONIC_TELEMETRY_RING_CAP;
1051        }
1052        let _ = push_sonic_token(packed64);
1053    }
1054
1055    /// Pops the oldest 48-byte [`HolosonicSonicToken48`] from the telemetry ring.
1056    #[inline]
1057    pub fn pop(&mut self) -> Option<HolosonicSonicToken48> {
1058        if self.count == 0 {
1059            return None;
1060        }
1061        let tok = self.tokens[self.read_idx];
1062        self.read_idx = (self.read_idx + 1) % HOLOSONIC_TELEMETRY_RING_CAP;
1063        self.count -= 1;
1064        Some(tok)
1065    }
1066}
1067
1068/// Complete Scene-Synchronized 3D Holosonic Wavefield & Multi-Bus HRTF Audio Graph.
1069pub struct SceneAudioBusGraph {
1070    /// Observer listener pose synchronized from camera PGA `Motor`.
1071    pub listener: AudioListenerPose,
1072    /// Primary Holosonic wavefield engine (preserved and synchronized with `emitters`).
1073    pub wavefield: HolosonicWavefield,
1074    /// Up to 64 active scene audio emitters (`HolosonicNode`s + point/ambient sources).
1075    pub emitters: [HolosonicNode; MAX_SCENE_AUDIO_EMITTERS],
1076    /// Cached per-emitter acoustic occlusion state.
1077    pub occlusions: [AcousticOcclusionResult; MAX_SCENE_AUDIO_EMITTERS],
1078    /// Number of active emitters in `emitters`.
1079    pub emitter_count: usize,
1080    /// Bus 1: Direct binaural FIR + DF2T biquad occlusion bus.
1081    pub direct_binaural_bus: DirectBinauralBus,
1082    /// Bus 2: 6-tap early reflections bus.
1083    pub early_reflections_bus: EarlyReflectionsBus,
1084    /// Bus 3: Stereo Freeverb late reverb bus.
1085    pub late_reverb_bus: LateReverbFreeverbBus,
1086    /// Bus 4: 48-byte `SonicToken` telemetry ring buffer.
1087    pub telemetry_bus: HolosonicTelemetryBus,
1088}
1089
1090impl Default for SceneAudioBusGraph {
1091    fn default() -> Self {
1092        Self::new()
1093    }
1094}
1095
1096impl SceneAudioBusGraph {
1097    /// Creates an empty zero-heap scene audio bus graph.
1098    pub fn new() -> Self {
1099        Self {
1100            listener: AudioListenerPose::default(),
1101            wavefield: HolosonicWavefield::new(),
1102            emitters: [HolosonicNode::default(); MAX_SCENE_AUDIO_EMITTERS],
1103            occlusions: [AcousticOcclusionResult::default(); MAX_SCENE_AUDIO_EMITTERS],
1104            emitter_count: 0,
1105            direct_binaural_bus: DirectBinauralBus::default(),
1106            early_reflections_bus: EarlyReflectionsBus::default(),
1107            late_reverb_bus: LateReverbFreeverbBus::new(0.65, 0.35, 0.22),
1108            telemetry_bus: HolosonicTelemetryBus::default(),
1109        }
1110    }
1111
1112    /// Synchronizes the listener pose from the observer camera's PGA [`Motor`].
1113    #[inline]
1114    pub fn sync_listener_from_motor(
1115        &mut self,
1116        camera_motor: Motor,
1117        velocity: [f32; 3],
1118        manifold_w: f32,
1119    ) {
1120        self.listener = AudioListenerPose::from_pga_motor(camera_motor, velocity, manifold_w);
1121    }
1122
1123    /// Clears all scene emitters for a new scene sync pass.
1124    #[inline]
1125    pub fn clear_emitters(&mut self) {
1126        self.emitter_count = 0;
1127        self.wavefield.clear();
1128    }
1129
1130    /// Registers a [`HolosonicNode`] emitter into the scene graph and syncs [`HolosonicWavefield`].
1131    #[inline]
1132    pub fn push_emitter(&mut self, node: HolosonicNode) -> bool {
1133        if self.emitter_count >= MAX_SCENE_AUDIO_EMITTERS {
1134            return false;
1135        }
1136        self.emitters[self.emitter_count] = node;
1137        self.emitter_count += 1;
1138        let _ = self.wavefield.push(node.emitter);
1139        true
1140    }
1141
1142    /// Evaluates shared SDF + BVH acoustic occlusion for all active emitters in zero heap.
1143    pub fn update_occlusion_zero_heap(&mut self, obstacles: &[AcousticObstacle]) {
1144        let mut mean_enclosure = 0.0_f32;
1145        for i in 0..self.emitter_count {
1146            let emitter_pos = self.emitters[i].emitter.position;
1147            evaluate_acoustic_occlusion_zero_heap(
1148                self.listener.position,
1149                emitter_pos,
1150                obstacles,
1151                &mut self.occlusions[i],
1152            );
1153            mean_enclosure += self.occlusions[i].enclosure_density;
1154        }
1155        if self.emitter_count > 0 {
1156            mean_enclosure /= self.emitter_count as f32;
1157            self.late_reverb_bus
1158                .configure_from_enclosure(mean_enclosure, self.listener.manifold_w);
1159        }
1160    }
1161
1162    /// Synthesizes and mixes a stereo audio block (`out_l`, `out_r`) across all 4 buses in zero heap:
1163    /// 1. Continuous Holosonic wave superposition ($P_{\text{total}} = \sum p_i(t, \mathbf{x}_L)$)
1164    ///    with epistemic certainty $q$ harmonic purity modulation and Doppler pitch shift.
1165    /// 2. Per-emitter DF2T biquad occlusion low-pass filtering + `hrtf.rs` binaural FIR convolution.
1166    /// 3. 6-tap early reflections + stereo Freeverb late reverb tail.
1167    /// 4. Emits 48-byte [`HolosonicSonicToken48`] telemetry tokens into [`HolosonicTelemetryBus`].
1168    pub fn render_quantum_zero_heap(
1169        &mut self,
1170        start_time_s: f32,
1171        sample_rate: f32,
1172        obstacles: &[AcousticObstacle],
1173        out_l: &mut [f32],
1174        out_r: &mut [f32],
1175    ) -> HolosonicPointSample {
1176        self.update_occlusion_zero_heap(obstacles);
1177
1178        let n = out_l.len().min(out_r.len());
1179        let sr = sample_rate.max(8_000.0);
1180        let dt = 1.0 / sr;
1181
1182        // Precompute per-emitter spatial binaural gains, Doppler shift, and distance attenuation
1183        let mut emitter_gains = [BinauralGains::default(); MAX_SCENE_AUDIO_EMITTERS];
1184        let mut emitter_atten = [0.0_f32; MAX_SCENE_AUDIO_EMITTERS];
1185        let mut emitter_omega = [0.0_f32; MAX_SCENE_AUDIO_EMITTERS];
1186        let mut emitter_phase0 = [0.0_f32; MAX_SCENE_AUDIO_EMITTERS];
1187        let mut active_count = 0usize;
1188
1189        for idx in 0..self.emitter_count {
1190            let node = &self.emitters[idx];
1191            // Forbidden/Escrow deontic permit silences direct emission
1192            if node.deontic_permit >= 2 || node.emitter.amplitude <= 0.0 {
1193                continue;
1194            }
1195            let e = &node.emitter;
1196            let rel = sub3(e.position, self.listener.position);
1197            let dist = length3(rel);
1198            if !node.is_ambient && (dist > e.coherence_radius || dist < 0.001) {
1199                continue;
1200            }
1201            active_count += 1;
1202
1203            let falloff = if node.is_ambient {
1204                1.0
1205            } else {
1206                (1.0 - (dist / e.coherence_radius.max(0.1))).clamp(0.0, 1.0)
1207            };
1208            let dist_atten = if node.is_ambient {
1209                e.amplitude
1210            } else {
1211                (1.0 / (1.0 + dist * 0.45)) * falloff * e.amplitude
1212            };
1213            emitter_atten[idx] = dist_atten * self.occlusions[idx].direct_gain;
1214
1215            // Doppler shift from relative radial velocity
1216            let dir = if dist > 1e-4 {
1217                [rel[0] / dist, rel[1] / dist, rel[2] / dist]
1218            } else {
1219                [0.0, 0.0, -1.0]
1220            };
1221            let v_emit = dot3(node.velocity, dir);
1222            let v_list = dot3(self.listener.velocity, dir);
1223            let doppler = ((SPEED_OF_SOUND_MPS - v_list) / (SPEED_OF_SOUND_MPS + v_emit).max(20.0))
1224                .clamp(0.5, 2.0);
1225
1226            let omega = TAU * e.base_freq_hz * doppler;
1227            let wave_number = omega / SPEED_OF_SOUND_MPS;
1228            emitter_omega[idx] = omega;
1229            emitter_phase0[idx] =
1230                e.phase_rad - wave_number * dist - self.occlusions[idx].diffraction_phase_rad;
1231            emitter_gains[idx] = if node.is_ambient {
1232                BinauralGains {
1233                    gain_l: 0.707,
1234                    gain_r: 0.707,
1235                    itd_seconds: 0.0,
1236                    azimuth_rad: 0.0,
1237                    elevation_rad: 0.0,
1238                    distance: dist.max(1.0),
1239                }
1240            } else {
1241                binaural_from_position(rel, self.listener.yaw_rad)
1242            };
1243        }
1244
1245        let mut peak_l = 0.0_f32;
1246        let mut peak_r = 0.0_f32;
1247        let mut raw_energy_sum = 0.0_f32;
1248
1249        // Shared early-reflection tap configuration from emitter 0 (or default)
1250        let er_delays = if self.emitter_count > 0 {
1251            self.occlusions[0].early_reflection_delays_s
1252        } else {
1253            [0.008, 0.014, 0.021, 0.029, 0.038, 0.049]
1254        };
1255        let er_gains = if self.emitter_count > 0 {
1256            self.occlusions[0].early_reflection_gains
1257        } else {
1258            [0.0; EARLY_REFLECTION_TAPS]
1259        };
1260
1261        for sample_i in 0..n {
1262            let t = start_time_s + (sample_i as f32) * dt;
1263            let mut direct_sum_l = 0.0_f32;
1264            let mut direct_sum_r = 0.0_f32;
1265
1266            for idx in 0..self.emitter_count {
1267                let atten = emitter_atten[idx];
1268                if atten <= 1e-6 {
1269                    continue;
1270                }
1271                let e = &self.emitters[idx].emitter;
1272                let phase = emitter_phase0[idx] + emitter_omega[idx] * t;
1273                let q = e.epistemic_q.clamp(0.0, 1.0);
1274
1275                // Epistemic certainty q modulates harmonic purity vs FM/overtone dissonance
1276                let fundamental = phase.sin();
1277                let overtone_2 = (phase * 2.0 + 0.5).sin() * (1.0 - q) * 0.35;
1278                let overtone_3 = (phase * 3.01 + 1.1).sin() * (1.0 - q) * 0.18;
1279                let mono_wave = (fundamental + overtone_2 + overtone_3) * atten;
1280
1281                let (bin_l, bin_r) = self.direct_binaural_bus.process_emitter_sample(
1282                    idx,
1283                    mono_wave,
1284                    &self.occlusions[idx].lowpass_biquad,
1285                    &emitter_gains[idx],
1286                    sr,
1287                );
1288                direct_sum_l += bin_l;
1289                direct_sum_r += bin_r;
1290                if sample_i == 0 {
1291                    raw_energy_sum += atten;
1292                }
1293            }
1294
1295            let (er_l, er_r) = self.early_reflections_bus.tick(
1296                direct_sum_l,
1297                direct_sum_r,
1298                &er_delays,
1299                &er_gains,
1300                sr,
1301            );
1302            let (rev_l, rev_r) = self
1303                .late_reverb_bus
1304                .tick(direct_sum_l + er_l, direct_sum_r + er_r);
1305
1306            let total_l = (direct_sum_l + er_l + rev_l).clamp(-2.0, 2.0);
1307            let total_r = (direct_sum_r + er_r + rev_r).clamp(-2.0, 2.0);
1308            out_l[sample_i] = total_l;
1309            out_r[sample_i] = total_r;
1310
1311            if total_l.abs() > peak_l.abs() {
1312                peak_l = total_l;
1313            }
1314            if total_r.abs() > peak_r.abs() {
1315                peak_r = total_r;
1316            }
1317        }
1318
1319        let net_amp = (peak_l * peak_l + peak_r * peak_r).sqrt();
1320        let interference_gain = if raw_energy_sum > 0.001 {
1321            net_amp / raw_energy_sum
1322        } else {
1323            1.0
1324        };
1325
1326        let summary = HolosonicPointSample {
1327            pressure_l: peak_l,
1328            pressure_r: peak_r,
1329            interference_gain,
1330            active_emitter_count: active_count,
1331        };
1332
1333        // Emit 48-byte SonicToken telemetry for active emitters
1334        for idx in 0..self.emitter_count {
1335            if emitter_atten[idx] > 1e-4 {
1336                let node = &self.emitters[idx];
1337                let (tok48, packed64) = self.wavefield.emit_sonic_token(
1338                    idx.min(self.wavefield.len().saturating_sub(1)),
1339                    node.origin_quin_hash,
1340                    node.node_id,
1341                    node.deontic_permit,
1342                    self.occlusions[idx].direct_gain,
1343                    summary,
1344                    self.listener.position,
1345                    start_time_s,
1346                );
1347                let _ = (SonicEventType::Parametric, SONIC_MAGIC, PI);
1348                self.telemetry_bus.push(tok48, packed64);
1349            }
1350        }
1351
1352        summary
1353    }
1354}
1355
1356#[inline]
1357fn sub3(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
1358    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
1359}
1360
1361#[inline]
1362fn dot3(a: [f32; 3], b: [f32; 3]) -> f32 {
1363    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
1364}
1365
1366#[inline]
1367fn cross3(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
1368    [
1369        a[1] * b[2] - a[2] * b[1],
1370        a[2] * b[0] - a[0] * b[2],
1371        a[0] * b[1] - a[1] * b[0],
1372    ]
1373}
1374
1375#[inline]
1376fn length3(v: [f32; 3]) -> f32 {
1377    dot3(v, v).sqrt()
1378}
1379
1380#[inline]
1381fn normalize3(v: [f32; 3], fallback: [f32; 3]) -> [f32; 3] {
1382    let l = length3(v);
1383    if l > 1e-6 {
1384        [v[0] / l, v[1] / l, v[2] / l]
1385    } else {
1386        fallback
1387    }
1388}
1389
1390#[cfg(test)]
1391mod tests {
1392    use super::*;
1393    #[cfg(feature = "gpu-runtime")]
1394    use crate::render::gpu::HolographicPrimitive;
1395    use crate::render::pga::motor_translate;
1396
1397    #[test]
1398    fn listener_pose_from_pga_motor_extracts_position_and_basis() {
1399        let motor = motor_translate([4.0, 2.5, -7.0]);
1400        let pose = AudioListenerPose::from_pga_motor(motor, [0.0, 0.0, -2.0], 1.0);
1401        assert!((pose.position[0] - 4.0).abs() < 1e-4);
1402        assert!((pose.position[1] - 2.5).abs() < 1e-4);
1403        assert!((pose.position[2] + 7.0).abs() < 1e-4);
1404        assert!((pose.forward[2] + 1.0).abs() < 1e-4);
1405        assert!((pose.up[1] - 1.0).abs() < 1e-4);
1406        assert!((pose.right[0] - 1.0).abs() < 1e-4);
1407    }
1408
1409    #[test]
1410    fn analytical_sdf_and_bvh_occlusion_attenuates_direct_gain_and_cutoff() {
1411        let listener = [0.0, 1.5, 0.0];
1412        let emitter = [0.0, 1.5, -20.0];
1413
1414        let mut unoccluded = AcousticOcclusionResult::default();
1415        evaluate_acoustic_occlusion_zero_heap(listener, emitter, &[], &mut unoccluded);
1416        assert!((unoccluded.direct_gain - 1.0).abs() < 1e-5);
1417        assert_eq!(unoccluded.hit_count, 0);
1418
1419        // Place a rock SDF sphere directly between listener and emitter at z = -10
1420        let rock_sphere = AcousticObstacle {
1421            shape: AcousticObstacleShape::AnalyticalSphere {
1422                center: [0.0, 1.5, -10.0],
1423                radius: 2.0,
1424            },
1425            material: AcousticMaterial::RockLithology,
1426            thickness_m: 4.0,
1427            smooth_blend_radius: 0.25,
1428        };
1429        let canopy_box = AcousticObstacle {
1430            shape: AcousticObstacleShape::AnalyticalRoundedBox {
1431                center: [0.0, 1.5, -5.0],
1432                half_extents: [1.5, 1.5, 1.0],
1433                round_radius: 0.2,
1434            },
1435            material: AcousticMaterial::FoliageCanopy,
1436            thickness_m: 2.0,
1437            smooth_blend_radius: 0.25,
1438        };
1439
1440        let mut occluded = AcousticOcclusionResult::default();
1441        evaluate_acoustic_occlusion_zero_heap(
1442            listener,
1443            emitter,
1444            &[rock_sphere, canopy_box],
1445            &mut occluded,
1446        );
1447
1448        assert_eq!(occluded.hit_count, 2);
1449        assert!(
1450            occluded.direct_gain < unoccluded.direct_gain * 0.35,
1451            "Expected strong rock+canopy attenuation, got {}",
1452            occluded.direct_gain
1453        );
1454        assert!(
1455            occluded.lowpass_cutoff_hz < 3_000.0,
1456            "Expected low-pass cutoff drop, got {}",
1457            occluded.lowpass_cutoff_hz
1458        );
1459        assert!(occluded.diffraction_phase_rad > 0.0);
1460        assert!(occluded.early_reflection_gains[1] > 0.0);
1461    }
1462
1463    #[test]
1464    #[cfg(feature = "gpu-runtime")]
1465    fn scene_audio_bus_graph_renders_binaural_reverb_and_emits_48b_sonic_tokens() {
1466        let mut graph = SceneAudioBusGraph::new();
1467        graph.sync_listener_from_motor(Motor::identity(), [0.0, 0.0, 0.0], 1.0);
1468
1469        let holo = HolographicNodeGpu::new(
1470            [-3.0, 0.0, -5.0],
1471            1.0,
1472            [1.0, 1.0, 1.0],
1473            HolographicPrimitive::Sphere,
1474            4.0, // 440 Hz
1475            0.85,
1476            0.0,
1477            1.0,
1478            0.9,
1479            [0.0, 1.0, 1.0, 1.0],
1480        );
1481        let node = HolosonicNode::from_holographic_node(
1482            7,
1483            0xCAFE_BABE_1234_5678,
1484            &holo,
1485            HolosonicModality::LandmarkBeacon,
1486        );
1487        assert!(graph.push_emitter(node));
1488
1489        let obstacle = AcousticObstacle {
1490            shape: AcousticObstacleShape::Aabb {
1491                min: [-6.0, -2.0, -8.0],
1492                max: [-4.0, 2.0, -6.0],
1493            },
1494            material: AcousticMaterial::TimberTrunk,
1495            thickness_m: 1.0,
1496            smooth_blend_radius: 0.2,
1497        };
1498
1499        let mut out_l = [0.0_f32; 128];
1500        let mut out_r = [0.0_f32; 128];
1501        let sample =
1502            graph.render_quantum_zero_heap(0.0, 48_000.0, &[obstacle], &mut out_l, &mut out_r);
1503
1504        assert_eq!(sample.active_emitter_count, 1);
1505        let energy_l: f32 = out_l.iter().map(|x| x * x).sum();
1506        let energy_r: f32 = out_r.iter().map(|x| x * x).sum();
1507        assert!(energy_l > 0.001, "Expected audible left channel energy");
1508        assert!(
1509            energy_l > energy_r,
1510            "Left-positioned source (-3, 0, -5) should produce higher left ear energy ({energy_l} vs {energy_r})"
1511        );
1512
1513        let tok48 = graph
1514            .telemetry_bus
1515            .pop()
1516            .expect("Expected 48-byte HolosonicSonicToken48 emitted");
1517        assert_eq!(std::mem::size_of_val(&tok48), 48);
1518        assert_eq!(tok48.origin_quin_hash, 0xCAFE_BABE_1234_5678);
1519        assert_eq!(tok48.tensor_index, 7);
1520        assert_eq!(tok48.archetype, HolosonicModality::LandmarkBeacon as u8);
1521    }
1522}