1use super::*;
2use crate::modalities::manifold::ManifoldCoordinate10D;
3
4const C_LIGHT: f64 = 299_792_458.0;
6
7const MIN_DIST: f64 = 1e-12;
9
10#[derive(Clone, Copy, Debug)]
12pub struct EmfSource {
13 pub x: f64,
14 pub y: f64,
15 pub z: f64,
16 pub amplitude: f64,
17 pub frequency: f64,
18 pub phase: f64,
19}
20
21impl EmfSource {
22 pub fn parse_flat(flat: &[f64]) -> Result<Vec<Self>, PhysicsError> {
25 if flat.len() % 6 != 0 {
26 return Err(PhysicsError::InvalidConfiguration(format!(
27 "sources flat array length {} is not a multiple of 6",
28 flat.len()
29 )));
30 }
31 let n = flat.len() / 6;
32 let mut out = Vec::with_capacity(n);
33 for i in 0..n {
34 let base = i * 6;
35 out.push(Self {
36 x: flat[base],
37 y: flat[base + 1],
38 z: flat[base + 2],
39 amplitude: flat[base + 3],
40 frequency: flat[base + 4],
41 phase: flat[base + 5],
42 });
43 }
44 Ok(out)
45 }
46
47 #[inline]
49 pub fn distance_to(&self, x: f64, y: f64, z: f64) -> f64 {
50 let dx = x - self.x;
51 let dy = y - self.y;
52 let dz = z - self.z;
53 (dx * dx + dy * dy + dz * dz).sqrt()
54 }
55
56 #[inline]
58 pub fn wave_number(&self, c: f64) -> f64 {
59 2.0 * std::f64::consts::PI * self.frequency / c
60 }
61
62 #[inline]
65 pub fn field_at(&self, x: f64, y: f64, z: f64, t: f64, c: f64) -> f64 {
66 let r = self.distance_to(x, y, z).max(MIN_DIST);
67 let k = self.wave_number(c);
68 let omega = 2.0 * std::f64::consts::PI * self.frequency;
69 (self.amplitude / r) * (omega * t - k * r + self.phase).sin()
70 }
71}
72
73impl PhysicsSimulationLibrary {
74 pub fn run_emf_interference(
82 &self,
83 sources: &[EmfSource],
84 x: f64,
85 y: f64,
86 z: f64,
87 t: f64,
88 c: f64,
89 ) -> Result<EmfInterferenceResult, PhysicsError> {
90 if sources.is_empty() {
91 return Err(PhysicsError::InvalidConfiguration(
92 "emf_interference needs at least one source".to_string(),
93 ));
94 }
95 let c = if c > 0.0 { c } else { C_LIGHT };
96
97 let instant: f64 = sources.iter().map(|s| s.field_at(x, y, z, t, c)).sum();
98
99 let f_min = sources
101 .iter()
102 .map(|s| s.frequency.abs())
103 .filter(|f| *f > 0.0)
104 .min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
105 .unwrap_or(1.0);
106 let period = 1.0 / f_min;
107 let n_samples = 256;
108 let mut peak = 0.0f64;
109 for i in 0..n_samples {
110 let ti = t + (i as f64 / n_samples as f64) * period;
111 let val: f64 = sources.iter().map(|s| s.field_at(x, y, z, ti, c)).sum();
112 peak = peak.max(val.abs());
113 }
114
115 let (phase, freq_eff) = if sources.len() == 1
118 || sources.iter().all(|s| {
119 (s.frequency - sources[0].frequency).abs()
120 < 1e-10 * sources[0].frequency.abs().max(1e-10)
121 }) {
122 let mut re = 0.0f64;
126 let mut im = 0.0f64;
127 for s in sources {
128 let r = s.distance_to(x, y, z).max(MIN_DIST);
129 let k = s.wave_number(c);
130 let phi = s.phase - k * r;
131 let amp = s.amplitude / r;
132 re += amp * phi.cos();
133 im += amp * phi.sin();
134 }
135 let combined_phase = im.atan2(re);
136 (combined_phase, sources[0].frequency)
137 } else {
138 let dominant = sources
140 .iter()
141 .max_by(|a, b| {
142 let ra = a.distance_to(x, y, z).max(MIN_DIST);
143 let rb = b.distance_to(x, y, z).max(MIN_DIST);
144 (a.amplitude / ra)
145 .partial_cmp(&(b.amplitude / rb))
146 .unwrap_or(std::cmp::Ordering::Equal)
147 })
148 .unwrap();
149 let r_dom = dominant.distance_to(x, y, z).max(MIN_DIST);
150 let k_dom = dominant.wave_number(c);
151 let phase_dom = dominant.phase - k_dom * r_dom;
152
153 let beat_freq = if sources.len() == 2 {
155 (sources[0].frequency - sources[1].frequency).abs()
156 } else {
157 let mut freqs: Vec<f64> = sources.iter().map(|s| s.frequency).collect();
158 freqs.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
159 let mut min_diff = f64::MAX;
160 for i in 1..freqs.len() {
161 let d = (freqs[i] - freqs[i - 1]).abs();
162 if d > 0.0 && d < min_diff {
163 min_diff = d;
164 }
165 }
166 if min_diff < f64::MAX {
167 min_diff
168 } else {
169 0.0
170 }
171 };
172 (phase_dom, beat_freq)
173 };
174
175 Ok(EmfInterferenceResult {
176 instantaneous_value: instant,
177 amplitude: peak,
178 phase,
179 frequency_effective: freq_eff,
180 num_sources: sources.len(),
181 })
182 }
183
184 pub fn run_emf_attenuation(
190 &self,
191 source_power: f64,
192 frequency: f64,
193 distance: f64,
194 absorption_coeff: f64,
195 ) -> Result<EmfAttenuationResult, PhysicsError> {
196 if source_power <= 0.0 {
197 return Err(PhysicsError::InvalidConfiguration(
198 "source_power must be positive".to_string(),
199 ));
200 }
201 if distance < 0.0 {
202 return Err(PhysicsError::InvalidConfiguration(
203 "distance must be non-negative".to_string(),
204 ));
205 }
206 let r = distance.max(MIN_DIST);
207 let alpha = absorption_coeff.max(0.0);
208
209 let p_free_space = source_power / (4.0 * std::f64::consts::PI * r * r);
211 let p_received = p_free_space * (-alpha * r).exp();
213
214 let free_space_loss_db = if p_free_space > 0.0 {
216 10.0 * (source_power / p_free_space).log10()
217 } else {
218 f64::INFINITY
219 };
220 let absorption_loss_db = if p_received > 0.0 && p_free_space > 0.0 {
221 10.0 * (p_free_space / p_received).log10()
222 } else {
223 f64::INFINITY
224 };
225 let total_attenuation_db = if p_received > 0.0 {
226 10.0 * (source_power / p_received).log10()
227 } else {
228 f64::INFINITY
229 };
230
231 Ok(EmfAttenuationResult {
232 received_power: p_received,
233 attenuation_db: total_attenuation_db,
234 free_space_loss_db,
235 absorption_loss_db,
236 distance,
237 frequency,
238 })
239 }
240
241 pub fn run_doppler_shift(
248 &self,
249 source_frequency: f64,
250 relative_velocity: f64,
251 c: f64,
252 ) -> Result<DopplerShiftResult, PhysicsError> {
253 if source_frequency <= 0.0 {
254 return Err(PhysicsError::InvalidConfiguration(
255 "source_frequency must be positive".to_string(),
256 ));
257 }
258 let c = if c > 0.0 { c } else { C_LIGHT };
259 let beta = relative_velocity / c;
260 if beta.abs() >= 1.0 {
261 return Err(PhysicsError::InvalidConfiguration(format!(
262 "relative velocity |v|={abs} >= c={c}; beta={beta}",
263 abs = relative_velocity.abs(),
264 )));
265 }
266
267 let ratio = ((1.0 + beta) / (1.0 - beta)).sqrt();
270 let observed = source_frequency * ratio;
271
272 Ok(DopplerShiftResult {
273 observed_frequency: observed,
274 shift_ratio: ratio,
275 relative_velocity,
276 beta,
277 })
278 }
279
280 pub fn run_emf_field_grid_3d(
288 &self,
289 sources: &[EmfSource],
290 bounds: [f64; 6],
291 nx: usize,
292 ny: usize,
293 nz: usize,
294 nt: usize,
295 t_start: f64,
296 t_end: f64,
297 c: f64,
298 ) -> Result<EmfFieldGrid3DResult, PhysicsError> {
299 if sources.is_empty() {
300 return Err(PhysicsError::InvalidConfiguration(
301 "emf_field_grid_3d needs at least one source".to_string(),
302 ));
303 }
304 if nx == 0 || ny == 0 || nz == 0 || nt == 0 {
305 return Err(PhysicsError::InvalidConfiguration(
306 "grid dimensions must be non-zero".to_string(),
307 ));
308 }
309 let c = if c > 0.0 { c } else { C_LIGHT };
310
311 let [x_min, x_max, y_min, y_max, z_min, z_max] = bounds;
312 if !(x_max > x_min && y_max > y_min && z_max > z_min) {
313 return Err(PhysicsError::InvalidConfiguration(
314 "bounds must satisfy x_max > x_min, y_max > y_min, z_max > z_min".to_string(),
315 ));
316 }
317
318 let total = nx * ny * nz * nt;
319 let mut amplitudes = vec![0.0f64; total];
320 let mut phases = vec![0.0f64; total];
321 let mut frequencies = vec![0.0f64; total];
322 let mut manifold_coords = vec![ManifoldCoordinate10D::default(); total];
323 let mut times = Vec::with_capacity(nt);
324
325 let dx = (x_max - x_min) / nx.max(1) as f64;
326 let dy = (y_max - y_min) / ny.max(1) as f64;
327 let dz = (z_max - z_min) / nz.max(1) as f64;
328 let dt = if nt > 1 {
329 (t_end - t_start) / (nt - 1) as f64
330 } else {
331 0.0
332 };
333
334 let max_amp = sources
336 .iter()
337 .map(|s| s.amplitude)
338 .fold(0.0f64, f64::max)
339 .max(1e-12);
340 let max_freq = sources
341 .iter()
342 .map(|s| s.frequency.abs())
343 .fold(0.0f64, f64::max)
344 .max(1e-12);
345 let t_span = (t_end - t_start).abs().max(1e-12);
346
347 for it in 0..nt {
348 let t = t_start + it as f64 * dt;
349 times.push(t);
350 for iz in 0..nz {
351 let z = z_min + (iz as f64 + 0.5) * dz;
352 for iy in 0..ny {
353 let y = y_min + (iy as f64 + 0.5) * dy;
354 for ix in 0..nx {
355 let x = x_min + (ix as f64 + 0.5) * dx;
356 let idx = ((it * nz + iz) * ny + iy) * nx + ix;
357
358 let result = self.run_emf_interference(sources, x, y, z, t, c)?;
359
360 amplitudes[idx] = result.amplitude;
361 phases[idx] = result.phase;
362 frequencies[idx] = result.frequency_effective;
363
364 let normalized_amp = (result.amplitude / max_amp) as f32;
366 let normalized_freq = (result.frequency_effective / max_freq) as f32;
367 let normalized_phase = (result.phase / std::f64::consts::TAU) as f32;
368 let normalized_time = ((t - t_start) / t_span) as f32;
369
370 let cx = (x_min + x_max) * 0.5;
372 let cy = (y_min + y_max) * 0.5;
373 let cz = (z_min + z_max) * 0.5;
374 let dist_center =
375 ((x - cx).powi(2) + (y - cy).powi(2) + (z - cz).powi(2)).sqrt();
376 let max_dist = ((x_max - x_min).powi(2)
377 + (y_max - y_min).powi(2)
378 + (z_max - z_min).powi(2))
379 .sqrt();
380 let normalized_dist = (dist_center / max_dist.max(1e-12)) as f32;
381
382 manifold_coords[idx] = ManifoldCoordinate10D {
383 scale: normalized_amp,
384 attention_depth: normalized_dist,
385 epistemic_weight: 1.0,
386 topological_spin: normalized_phase,
387 temporal_decay: normalized_time,
388 entropy_bias: (result.instantaneous_value.abs() / max_amp) as f32,
389 spatial_phase: normalized_phase,
390 recurrence_frequency: normalized_freq,
391 density_threshold: (1.0 / (1.0 + result.amplitude)).min(1.0) as f32,
392 manifold_curvature: 0.0,
393 };
394 }
395 }
396 }
397 }
398
399 Ok(EmfFieldGrid3DResult {
400 nx,
401 ny,
402 nz,
403 nt,
404 bounds,
405 times,
406 amplitudes,
407 phases,
408 frequencies,
409 manifold_coords,
410 num_sources: sources.len(),
411 })
412 }
413
414 pub fn run_emf_sample_at_depth(
422 &self,
423 sources: &[EmfSource],
424 camera: [f64; 3],
425 direction: [f64; 3],
426 depths: &[f64],
427 t: f64,
428 c: f64,
429 ) -> Result<EmfSampleAtDepthResult, PhysicsError> {
430 if sources.is_empty() {
431 return Err(PhysicsError::InvalidConfiguration(
432 "emf_sample_at_depth needs at least one source".to_string(),
433 ));
434 }
435 if depths.is_empty() {
436 return Err(PhysicsError::InvalidConfiguration(
437 "depths must be non-empty".to_string(),
438 ));
439 }
440 let c = if c > 0.0 { c } else { C_LIGHT };
441
442 let [dx, dy, dz] = direction;
444 let dlen = (dx * dx + dy * dy + dz * dz).sqrt();
445 if dlen < MIN_DIST {
446 return Err(PhysicsError::InvalidConfiguration(
447 "direction must be non-zero".to_string(),
448 ));
449 }
450 let (dx, dy, dz) = (dx / dlen, dy / dlen, dz / dlen);
451 let [cx, cy, cz] = camera;
452
453 let max_amp = sources
454 .iter()
455 .map(|s| s.amplitude)
456 .fold(0.0f64, f64::max)
457 .max(1e-12);
458 let max_freq = sources
459 .iter()
460 .map(|s| s.frequency.abs())
461 .fold(0.0f64, f64::max)
462 .max(1e-12);
463
464 let mut samples = Vec::with_capacity(depths.len());
465 for &depth in depths {
466 let x = cx + depth * dx;
467 let y = cy + depth * dy;
468 let z = cz + depth * dz;
469
470 let result = self.run_emf_interference(sources, x, y, z, t, c)?;
471
472 let perspective_scale = 1.0 / depth.max(1e-3);
474
475 let display_attenuation = (-depth * 0.1).exp();
477
478 let lod_level = if depth < 10.0 {
480 0
481 } else if depth < 100.0 {
482 1
483 } else if depth < 1000.0 {
484 2
485 } else {
486 3
487 };
488
489 let normalized_amp = (result.amplitude / max_amp) as f32;
490 let normalized_freq = (result.frequency_effective / max_freq) as f32;
491 let normalized_phase = (result.phase / std::f64::consts::TAU) as f32;
492 let normalized_depth =
493 (depth / depths.iter().cloned().fold(0.0f64, f64::max).max(1e-12)) as f32;
494
495 let manifold_coord = ManifoldCoordinate10D {
496 scale: normalized_amp,
497 attention_depth: normalized_depth,
498 epistemic_weight: 1.0,
499 topological_spin: normalized_phase,
500 temporal_decay: (t.rem_euclid(1.0)) as f32,
501 entropy_bias: (result.instantaneous_value.abs() / max_amp) as f32,
502 spatial_phase: normalized_phase,
503 recurrence_frequency: normalized_freq,
504 density_threshold: (1.0 / (1.0 + depth)).min(1.0) as f32,
505 manifold_curvature: 0.0,
506 };
507
508 samples.push(DepthSample {
509 depth,
510 amplitude: result.amplitude,
511 phase: result.phase,
512 frequency: result.frequency_effective,
513 perspective_scale,
514 display_attenuation,
515 lod_level,
516 manifold_coord,
517 });
518 }
519
520 Ok(EmfSampleAtDepthResult {
521 num_depths: samples.len(),
522 samples,
523 time: t,
524 })
525 }
526}
527
528#[cfg(test)]
529mod tests {
530 use super::*;
531
532 fn lib() -> PhysicsSimulationLibrary {
533 let lib = PhysicsSimulationLibrary::new();
534 lib
537 }
538
539 #[test]
540 fn two_source_constructive_interference() {
541 let sources = vec![
543 EmfSource {
544 x: 0.0,
545 y: 0.0,
546 z: 0.0,
547 amplitude: 1.0,
548 frequency: 1.0,
549 phase: 0.0,
550 },
551 EmfSource {
552 x: 0.0,
553 y: 0.0,
554 z: 0.0,
555 amplitude: 1.0,
556 frequency: 1.0,
557 phase: 0.0,
558 },
559 ];
560 let r = lib()
561 .run_emf_interference(&sources, 1.0, 0.0, 0.0, 0.0, 1.0)
562 .unwrap();
563 assert!(
566 r.amplitude > 1.5,
567 "constructive interference amplitude should be ~2.0, got {}",
568 r.amplitude
569 );
570 }
571
572 #[test]
573 fn two_source_destructive_interference() {
574 let sources = vec![
576 EmfSource {
577 x: 0.0,
578 y: 0.0,
579 z: 0.0,
580 amplitude: 1.0,
581 frequency: 1.0,
582 phase: 0.0,
583 },
584 EmfSource {
585 x: 0.0,
586 y: 0.0,
587 z: 0.0,
588 amplitude: 1.0,
589 frequency: 1.0,
590 phase: std::f64::consts::PI,
591 },
592 ];
593 let r = lib()
594 .run_emf_interference(&sources, 1.0, 0.0, 0.0, 0.0, 1.0)
595 .unwrap();
596 assert!(
598 r.amplitude < 0.1,
599 "destructive interference amplitude should be ~0, got {}",
600 r.amplitude
601 );
602 }
603
604 #[test]
605 fn inverse_square_quarter_amplitude() {
606 let lib = lib();
608 let r1 = lib.run_emf_attenuation(100.0, 1e9, 1.0, 0.0).unwrap();
609 let r2 = lib.run_emf_attenuation(100.0, 1e9, 2.0, 0.0).unwrap();
610 let ratio = r2.received_power / r1.received_power;
611 assert!(
612 (ratio - 0.25).abs() < 1e-10,
613 "inverse-square: power at 2× distance should be ¼, got {}",
614 ratio
615 );
616 }
617
618 #[test]
619 fn doppler_approaching_increases_frequency() {
620 let r = lib()
622 .run_doppler_shift(1e9, 0.1 * C_LIGHT, C_LIGHT)
623 .unwrap();
624 let expected = 1e9_f64 * (1.1_f64 / 0.9_f64).sqrt();
625 assert!(
626 (r.observed_frequency - expected).abs() / expected < 1e-10,
627 "Doppler approaching: expected {}, got {}",
628 expected,
629 r.observed_frequency
630 );
631 assert!(r.shift_ratio > 1.0, "approaching should increase frequency");
632 }
633
634 #[test]
635 fn doppler_receding_decreases_frequency() {
636 let r = lib()
638 .run_doppler_shift(1e9, -0.1 * C_LIGHT, C_LIGHT)
639 .unwrap();
640 let expected = 1e9_f64 * (0.9_f64 / 1.1_f64).sqrt();
641 assert!(
642 (r.observed_frequency - expected).abs() / expected < 1e-10,
643 "Doppler receding: expected {}, got {}",
644 expected,
645 r.observed_frequency
646 );
647 assert!(r.shift_ratio < 1.0, "receding should decrease frequency");
648 }
649
650 #[test]
651 fn field_grid_finite_and_monotonic() {
652 let sources = vec![EmfSource {
654 x: -5.0,
655 y: -5.0,
656 z: -5.0,
657 amplitude: 1.0,
658 frequency: 1.0,
659 phase: 0.0,
660 }];
661 let r = lib()
662 .run_emf_field_grid_3d(
663 &sources,
664 [-5.0, 5.0, -5.0, 5.0, -5.0, 5.0],
665 4,
666 4,
667 4,
668 2,
669 0.0,
670 1.0,
671 1.0,
672 )
673 .unwrap();
674 assert_eq!(r.amplitudes.len(), 4 * 4 * 4 * 2);
675 assert!(
676 r.amplitudes.iter().all(|a| a.is_finite()),
677 "all amplitudes must be finite"
678 );
679 assert!(
680 r.phases.iter().all(|p| p.is_finite()),
681 "all phases must be finite"
682 );
683 let close_idx = 0 * (4 * 4 * 4) + 0 * (4 * 4) + 0 * 4 + 0;
685 let far_idx = 0 * (4 * 4 * 4) + 3 * (4 * 4) + 3 * 4 + 3;
687 assert!(
688 r.amplitudes[close_idx] > r.amplitudes[far_idx],
689 "amplitude should decrease with distance: close={}, far={}",
690 r.amplitudes[close_idx],
691 r.amplitudes[far_idx]
692 );
693 }
694
695 #[test]
696 fn sample_at_depth_perspective_scaling() {
697 let sources = vec![EmfSource {
698 x: 0.0,
699 y: 0.0,
700 z: 10.0,
701 amplitude: 1.0,
702 frequency: 1.0,
703 phase: 0.0,
704 }];
705 let r = lib()
706 .run_emf_sample_at_depth(
707 &sources,
708 [0.0, 0.0, 0.0],
709 [0.0, 0.0, 1.0],
710 &[1.0, 10.0, 100.0],
711 0.0,
712 1.0,
713 )
714 .unwrap();
715 assert_eq!(r.samples.len(), 3);
716 assert!(r.samples[0].perspective_scale > r.samples[1].perspective_scale);
718 assert!(r.samples[1].perspective_scale > r.samples[2].perspective_scale);
719 assert!(r.samples[0].display_attenuation > r.samples[2].display_attenuation);
721 assert!(r.samples[2].lod_level >= r.samples[0].lod_level);
723 for s in &r.samples {
725 let arr = s.manifold_coord.as_f32_array();
726 assert!(
727 arr.iter().all(|v| v.is_finite()),
728 "manifold coords must be finite"
729 );
730 }
731 }
732
733 #[test]
734 fn beat_frequency_two_sources() {
735 let sources = vec![
737 EmfSource {
738 x: 0.0,
739 y: 0.0,
740 z: 0.0,
741 amplitude: 1.0,
742 frequency: 100.0,
743 phase: 0.0,
744 },
745 EmfSource {
746 x: 0.0,
747 y: 0.0,
748 z: 0.0,
749 amplitude: 1.0,
750 frequency: 105.0,
751 phase: 0.0,
752 },
753 ];
754 let r = lib()
755 .run_emf_interference(&sources, 1.0, 0.0, 0.0, 0.0, 340.0)
756 .unwrap();
757 assert!(
758 (r.frequency_effective - 5.0).abs() < 1e-6,
759 "beat frequency should be 5 Hz, got {}",
760 r.frequency_effective
761 );
762 }
763
764 #[test]
765 fn empty_sources_errors() {
766 let r = lib().run_emf_interference(&[], 0.0, 0.0, 0.0, 0.0, 1.0);
767 assert!(r.is_err());
768 }
769
770 #[test]
771 fn doppler_superluminal_errors() {
772 let r = lib().run_doppler_shift(1.0, 2.0 * C_LIGHT, C_LIGHT);
773 assert!(r.is_err());
774 }
775}