1use crate::audio::hrtf::binaural_from_position;
11use crate::sonic_token::{SonicEventType, SonicToken, SONIC_MAGIC};
12use bytemuck::{Pod, Zeroable};
13use std::f32::consts::TAU;
14
15#[repr(C)]
17#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
18pub struct HolosonicSonicToken48 {
19 pub origin_quin_hash: u64,
21 pub archetype: u8,
23 pub deontic_permit: u8,
25 pub flags: u16,
27 pub tensor_index: u32,
29 pub fundamental_hz: f32,
31 pub phase_rad: f32,
33 pub epistemic_q: f32,
35 pub interference_gain: f32,
37 pub occlusion_gain: f32,
39 pub position: [f32; 3],
41}
42
43const _: [(); 48] = [(); core::mem::size_of::<HolosonicSonicToken48>()];
44
45impl Default for HolosonicSonicToken48 {
46 fn default() -> Self {
47 Self::zeroed()
48 }
49}
50
51
52pub const MAX_HOLOSONIC_EMITTERS: usize = 32;
54
55pub const SPEED_OF_SOUND_MPS: f32 = 343.0;
57
58#[repr(u8)]
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum HolosonicModality {
62 VectorCorridor = 0,
64 WaterResonance = 1,
66 FloraWind = 2,
68 Bioacoustic = 3,
70 LandmarkBeacon = 4,
72}
73
74#[repr(C)]
76#[derive(Debug, Clone, Copy, PartialEq)]
77pub struct HolosonicEmitter {
78 pub position: [f32; 3],
80 pub base_freq_hz: f32,
82 pub amplitude: f32,
84 pub phase_rad: f32,
86 pub epistemic_q: f32,
88 pub coherence_radius: f32,
90 pub modality: HolosonicModality,
92}
93
94impl Default for HolosonicEmitter {
95 fn default() -> Self {
96 Self {
97 position: [0.0; 3],
98 base_freq_hz: 440.0,
99 amplitude: 0.0,
100 phase_rad: 0.0,
101 epistemic_q: 1.0,
102 coherence_radius: 25.0,
103 modality: HolosonicModality::VectorCorridor,
104 }
105 }
106}
107
108impl HolosonicEmitter {
109 #[inline]
111 pub const fn new(
112 position: [f32; 3],
113 base_freq_hz: f32,
114 amplitude: f32,
115 phase_rad: f32,
116 epistemic_q: f32,
117 coherence_radius: f32,
118 modality: HolosonicModality,
119 ) -> Self {
120 Self {
121 position,
122 base_freq_hz,
123 amplitude,
124 phase_rad,
125 epistemic_q,
126 coherence_radius,
127 modality,
128 }
129 }
130}
131
132#[derive(Debug, Clone, Copy, PartialEq)]
134pub struct HolosonicPointSample {
135 pub pressure_l: f32,
137 pub pressure_r: f32,
139 pub interference_gain: f32,
141 pub active_emitter_count: usize,
143}
144
145pub struct HolosonicWavefield {
147 emitters: [HolosonicEmitter; MAX_HOLOSONIC_EMITTERS],
148 count: usize,
149}
150
151impl Default for HolosonicWavefield {
152 fn default() -> Self {
153 Self::new()
154 }
155}
156
157impl HolosonicWavefield {
158 #[inline]
160 pub const fn new() -> Self {
161 Self {
162 emitters: [HolosonicEmitter {
163 position: [0.0; 3],
164 base_freq_hz: 440.0,
165 amplitude: 0.0,
166 phase_rad: 0.0,
167 epistemic_q: 1.0,
168 coherence_radius: 25.0,
169 modality: HolosonicModality::VectorCorridor,
170 }; MAX_HOLOSONIC_EMITTERS],
171 count: 0,
172 }
173 }
174
175 #[inline]
177 pub fn clear(&mut self) {
178 self.count = 0;
179 }
180
181 #[inline]
183 pub const fn len(&self) -> usize {
184 self.count
185 }
186
187 #[inline]
189 pub const fn is_empty(&self) -> bool {
190 self.count == 0
191 }
192
193 #[inline]
195 pub fn push(&mut self, emitter: HolosonicEmitter) -> bool {
196 if self.count >= MAX_HOLOSONIC_EMITTERS {
197 return false;
198 }
199 self.emitters[self.count] = emitter;
200 self.count += 1;
201 true
202 }
203
204 #[inline]
206 pub fn as_slice(&self) -> &[HolosonicEmitter] {
207 &self.emitters[..self.count]
208 }
209
210 #[inline]
213 pub fn emit_sonic_token(
214 &self,
215 emitter_idx: usize,
216 origin_quin_hash: u64,
217 tensor_index: u32,
218 deontic_permit: u8,
219 occlusion_gain: f32,
220 sample: HolosonicPointSample,
221 listener_pos: [f32; 3],
222 time_s: f32,
223 ) -> (HolosonicSonicToken48, SonicToken) {
224 let e = if emitter_idx < self.count {
225 self.emitters[emitter_idx]
226 } else {
227 HolosonicEmitter::default()
228 };
229 let dx = e.position[0] - listener_pos[0];
230 let dy = e.position[1] - listener_pos[1];
231 let dz = e.position[2] - listener_pos[2];
232 let dist = (dx * dx + dy * dy + dz * dz).sqrt();
233 let omega = TAU * e.base_freq_hz;
234 let phase_rad = e.phase_rad + omega * time_s - (omega / SPEED_OF_SOUND_MPS) * dist;
235 let tok48 = HolosonicSonicToken48 {
236 origin_quin_hash,
237 archetype: e.modality as u8,
238 deontic_permit,
239 flags: SONIC_MAGIC as u16,
240 tensor_index,
241 fundamental_hz: e.base_freq_hz,
242 phase_rad,
243 epistemic_q: e.epistemic_q,
244 interference_gain: sample.interference_gain,
245 occlusion_gain: (e.amplitude * occlusion_gain).clamp(0.0, 1.0),
246 position: e.position,
247 };
248 let midi_note = (69.0 + 12.0 * (e.base_freq_hz.max(20.0) / 440.0).log2())
249 .round()
250 .clamp(0.0, 127.0) as u8;
251 let velocity = ((e.amplitude * occlusion_gain * sample.interference_gain * 96.0)
252 .clamp(1.0, 127.0)) as u8;
253 let packed = SonicToken::pack(
254 0,
255 SonicEventType::Parametric,
256 e.modality as u8 & 0x0f,
257 midi_note,
258 velocity,
259 tensor_index,
260 (SONIC_MAGIC as u16) | ((deontic_permit as u16) << 8),
261 );
262 (tok48, packed)
263 }
264
265 pub fn evaluate_point(
270 &self,
271 listener_pos: [f32; 3],
272 listener_yaw: f32,
273 time_s: f32,
274 ) -> HolosonicPointSample {
275 let mut sum_l = 0.0_f32;
276 let mut sum_r = 0.0_f32;
277 let mut raw_energy = 0.0_f32;
278 let mut active = 0usize;
279
280 for i in 0..self.count {
281 let e = &self.emitters[i];
282 if e.amplitude <= 0.0 {
283 continue;
284 }
285
286 let dx = e.position[0] - listener_pos[0];
287 let dy = e.position[1] - listener_pos[1];
288 let dz = e.position[2] - listener_pos[2];
289 let dist = (dx * dx + dy * dy + dz * dz).sqrt();
290
291 if dist > e.coherence_radius || dist < 0.001 {
292 continue;
293 }
294 active += 1;
295
296 let falloff = (1.0 - (dist / e.coherence_radius)).clamp(0.0, 1.0);
298 let atten = (1.0 / (1.0 + dist * 0.45)) * falloff * e.amplitude;
299
300 let omega = TAU * e.base_freq_hz;
302 let wave_number = omega / SPEED_OF_SOUND_MPS;
303 let phase = e.phase_rad + omega * time_s - wave_number * dist;
304
305 let q = e.epistemic_q.clamp(0.0, 1.0);
308
309 let unit_dir = [dx / dist, dy / dist, dz / dist];
312 let gains = binaural_from_position(unit_dir, listener_yaw);
313
314 let ear_delay_phase = wave_number * gains.itd_seconds * SPEED_OF_SOUND_MPS;
316 let phase_l = phase + ear_delay_phase * 0.5;
317 let phase_r = phase - ear_delay_phase * 0.5;
318 let harmonic_l = (phase_l * 2.0 + 0.5).sin() * (1.0 - q) * 0.35;
319 let harmonic_r = (phase_r * 2.0 + 0.5).sin() * (1.0 - q) * 0.35;
320 let sample_l = (phase_l.sin() + harmonic_l) * atten * gains.gain_l;
321 let sample_r = (phase_r.sin() + harmonic_r) * atten * gains.gain_r;
322
323 sum_l += sample_l;
324 sum_r += sample_r;
325 raw_energy += atten;
326 }
327
328 let net_amplitude = (sum_l * sum_l + sum_r * sum_r).sqrt();
329 let interference_gain = if raw_energy > 0.001 {
330 net_amplitude / raw_energy
331 } else {
332 1.0
333 };
334
335 HolosonicPointSample {
336 pressure_l: sum_l.clamp(-2.0, 2.0),
337 pressure_r: sum_r.clamp(-2.0, 2.0),
338 interference_gain,
339 active_emitter_count: active,
340 }
341 }
342
343 pub fn render_block(
347 &self,
348 listener_pos: [f32; 3],
349 listener_yaw: f32,
350 start_time_s: f32,
351 sample_rate: f32,
352 out_l: &mut [f32],
353 out_r: &mut [f32],
354 ) {
355 let n = out_l.len().min(out_r.len());
356 let dt = 1.0 / sample_rate.max(1.0);
357
358 for i in 0..n {
359 let t = start_time_s + i as f32 * dt;
360 let sample = self.evaluate_point(listener_pos, listener_yaw, t);
361 out_l[i] = sample.pressure_l;
362 out_r[i] = sample.pressure_r;
363 }
364 }
365
366 pub fn emit_tokens_from_sample(
370 &self,
371 sample: HolosonicPointSample,
372 out_tokens: &mut [SonicToken],
373 ) -> usize {
374 if out_tokens.is_empty() {
375 return 0;
376 }
377
378 if sample.interference_gain > 1.25 && sample.active_emitter_count > 0 {
380 let midi_note = 60u8; let velocity = (sample.interference_gain * 40.0).clamp(20.0, 127.0) as u8;
382 out_tokens[0] =
383 SonicToken::pack(0, SonicEventType::NoteOn, 0, midi_note, velocity, 0, 0);
384 1
385 } else {
386 0
387 }
388 }
389}
390
391#[cfg(test)]
392mod tests {
393 use super::*;
394
395 #[test]
396 fn empty_wavefield_produces_silence() {
397 let wf = HolosonicWavefield::new();
398 let sample = wf.evaluate_point([0.0, 0.0, 0.0], 0.0, 0.0);
399 assert_eq!(sample.pressure_l, 0.0);
400 assert_eq!(sample.pressure_r, 0.0);
401 assert_eq!(sample.active_emitter_count, 0);
402 }
403
404 #[test]
405 fn distance_attenuation_is_monotonic() {
406 let mut wf = HolosonicWavefield::new();
407 wf.push(HolosonicEmitter::new(
408 [0.0, 0.0, 10.0],
409 220.0,
410 1.0,
411 0.0,
412 1.0,
413 50.0,
414 HolosonicModality::LandmarkBeacon,
415 ));
416
417 let near = wf.evaluate_point([0.0, 0.0, 8.0], 0.0, 0.0);
418 let far = wf.evaluate_point([0.0, 0.0, 0.0], 0.0, 0.0);
419
420 let near_mag = (near.pressure_l.powi(2) + near.pressure_r.powi(2)).sqrt();
421 let far_mag = (far.pressure_l.powi(2) + far.pressure_r.powi(2)).sqrt();
422 assert!(
423 near_mag > far_mag,
424 "Near ({near_mag}) should exceed Far ({far_mag})"
425 );
426 }
427
428 #[test]
429 fn constructive_interference_amplifies_signal() {
430 let mut wf = HolosonicWavefield::new();
431 wf.push(HolosonicEmitter::new(
433 [2.0, 0.0, 5.0],
434 440.0,
435 0.5,
436 0.0,
437 1.0,
438 20.0,
439 HolosonicModality::LandmarkBeacon,
440 ));
441 wf.push(HolosonicEmitter::new(
442 [-2.0, 0.0, 5.0],
443 440.0,
444 0.5,
445 0.0,
446 1.0,
447 20.0,
448 HolosonicModality::LandmarkBeacon,
449 ));
450
451 let mut buf_l = [0.0_f32; 64];
453 let mut buf_r = [0.0_f32; 64];
454 wf.render_block([0.0, 0.0, 0.0], 0.0, 0.0, 48_000.0, &mut buf_l, &mut buf_r);
455
456 let max_val = buf_l
457 .iter()
458 .chain(buf_r.iter())
459 .fold(0.0_f32, |m, &x| m.max(x.abs()));
460 assert!(
461 max_val > 0.05,
462 "Constructive interference should yield audible peak"
463 );
464 }
465}