Skip to main content

qualia_core_db/render/
portal_emf_state.rs

1//! One accepted current field and exact immutable source, independent of GPU life.
2use crate::q42::{
3    emf_container::{EmfContainerReader, EmfReadLimits},
4    field_spectrum::VACUUM_SPEED_OF_LIGHT_M_PER_S,
5};
6use std::sync::Arc;
7
8pub const MAX_DISPLAY_CELLS: usize = 1_048_576;
9/// Vacuum wave impedance Z0 = mu_0 * c in Ohms.
10pub const VACUUM_IMPEDANCE_OHM: f64 =
11    4.0e-7 * std::f64::consts::PI * VACUUM_SPEED_OF_LIGHT_M_PER_S;
12const MU_0_F64: f64 = 4.0e-7 * std::f64::consts::PI;
13
14/// Plain CPU display derivative, not a scientific record or a GPU ABI.
15#[derive(Clone, Copy, Debug, Default, PartialEq)]
16pub struct DisplayEmfCell {
17    pub magnitude_v_per_m: f64,
18    pub valid: bool,
19}
20
21/// Explicit scientific-to-display optical/polarimetric/spectral derivative per cell.
22/// Static or unpolarized fields carry `spectral_sigma == 0.0` and zero `stokes_q/u/v`.
23#[derive(Clone, Copy, Debug, Default, PartialEq)]
24pub struct DisplayOpticalCell {
25    pub stokes_i: f64,
26    pub stokes_q: f64,
27    pub stokes_u: f64,
28    pub stokes_v: f64,
29    pub spectral_sigma: f64,
30    pub carrier_hz: f64,
31    pub phase_rad: f64,
32    pub coherence: f64,
33    pub valid: bool,
34}
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub struct DisplaySelection {
38    pub descriptor_id: u32,
39    pub frame_id: u32,
40    pub clock_id: u32,
41    pub stream_id: u32,
42}
43
44pub struct LoadedEmf {
45    pub(super) nx: u32,
46    pub(super) ny: u32,
47    pub(super) nz: u32,
48    pub(super) nt: u32,
49    pub(super) cell_count: u32,
50    pub(super) bounds: [f32; 6],
51    pub(super) cells: Vec<DisplayEmfCell>,
52    pub(super) optical_cells: Vec<DisplayOpticalCell>,
53    pub(super) display_mode: u16,
54    pub(super) source: Arc<[u8]>,
55    pub(super) selection: DisplaySelection,
56    pub(super) ticks: Vec<i64>,
57    pub(super) temporal: bool,
58}
59
60impl LoadedEmf {
61    pub fn dimensions(&self) -> [u32; 4] {
62        [self.nx, self.ny, self.nz, self.nt]
63    }
64    pub fn cell_count(&self) -> u32 {
65        self.cell_count
66    }
67    /// Interleaved local cell-footprint bounds: xmin,xmax,ymin,ymax,zmin,zmax.
68    pub fn local_bounds(&self) -> [f32; 6] {
69        self.bounds
70    }
71    pub fn display_cells(&self) -> &[DisplayEmfCell] {
72        &self.cells
73    }
74    pub fn optical_cells(&self) -> &[DisplayOpticalCell] {
75        &self.optical_cells
76    }
77    pub fn display_mode(&self) -> u16 {
78        self.display_mode
79    }
80    pub fn source_bytes(&self) -> &[u8] {
81        &self.source
82    }
83    pub fn selection(&self) -> DisplaySelection {
84        self.selection
85    }
86    pub fn time_ticks(&self) -> &[i64] {
87        &self.ticks
88    }
89    pub fn is_temporal(&self) -> bool {
90        self.temporal
91    }
92    /// Decode a standalone verified `Q42EMF64` container (v2/v3) into `LoadedEmf`.
93    pub fn from_emf64(bytes: &[u8]) -> Result<Self, String> {
94        decode_emf64_display(bytes)
95    }
96}
97
98/// Compute physical Poynting irradiance W/m^2 from stored Poynting, E x B / mu_0, or |E|^2 / Z0.
99pub fn poynting_irradiance_w_per_m2(
100    e_v_per_m: [f64; 3],
101    b_tesla: Option<[f64; 3]>,
102    stored_poynting: Option<[f64; 3]>,
103) -> f64 {
104    if let Some([sx, sy, sz]) = stored_poynting {
105        return sx.hypot(sy).hypot(sz);
106    }
107    if let Some([bx, by, bz]) = b_tesla {
108        if bx != 0.0 || by != 0.0 || bz != 0.0 {
109            let cx = e_v_per_m[1] * bz - e_v_per_m[2] * by;
110            let cy = e_v_per_m[2] * bx - e_v_per_m[0] * bz;
111            let cz = e_v_per_m[0] * by - e_v_per_m[1] * bx;
112            return cx.hypot(cy).hypot(cz) / MU_0_F64;
113        }
114    }
115    let e_mag = e_v_per_m[0].hypot(e_v_per_m[1]).hypot(e_v_per_m[2]);
116    let scaled = e_mag / VACUUM_IMPEDANCE_OHM.sqrt();
117    scaled * scaled
118}
119
120/// Derive equivalent plane-wave electric-field magnitude V/m from irradiance I (W/m^2).
121pub fn e_magnitude_from_poynting(irradiance_w_per_m2: f64) -> f64 {
122    if irradiance_w_per_m2.is_nan() || irradiance_w_per_m2 <= 0.0 {
123        0.0
124    } else if irradiance_w_per_m2.is_infinite() {
125        f64::INFINITY
126    } else {
127        irradiance_w_per_m2.sqrt() * VACUUM_IMPEDANCE_OHM.sqrt()
128    }
129}
130
131/// Map a physical carrier frequency (Hz) to full-spectrum 6-band display `sigma in [0.0, 6.0)`.
132/// Returns `0.0` when static or absent (`carrier_hz <= 0.0`).
133pub fn carrier_hz_to_spectral_sigma(carrier_hz: f64) -> f64 {
134    if !carrier_hz.is_finite() || carrier_hz <= 0.0 {
135        return 0.0;
136    }
137    const F_RF_MAX: f64 = 3.0e11;
138    const F_VIS_LOW: f64 = VACUUM_SPEED_OF_LIGHT_M_PER_S / 700.0e-9;
139    const F_VIS_HIGH: f64 = VACUUM_SPEED_OF_LIGHT_M_PER_S / 400.0e-9;
140    const F_UV_MAX: f64 = 3.0e16;
141    const F_XRAY_MAX: f64 = 3.0e19;
142    if carrier_hz >= F_VIS_LOW && carrier_hz <= F_VIS_HIGH {
143        let lambda_nm = (VACUUM_SPEED_OF_LIGHT_M_PER_S * 1.0e9) / carrier_hz;
144        ((lambda_nm - 400.0) / 300.0).clamp(0.0, 0.999_999)
145    } else if carrier_hz < F_RF_MAX {
146        let t = (carrier_hz.max(1.0e-3).log10() + 3.0) / (F_RF_MAX.log10() + 3.0);
147        1.0 + t.clamp(0.0, 0.999_999)
148    } else if carrier_hz < F_VIS_LOW {
149        let lo = F_RF_MAX.log10();
150        let t = (carrier_hz.log10() - lo) / (F_VIS_LOW.log10() - lo);
151        2.0 + t.clamp(0.0, 0.999_999)
152    } else if carrier_hz < F_UV_MAX {
153        let lo = F_VIS_HIGH.log10();
154        let t = (carrier_hz.log10() - lo) / (F_UV_MAX.log10() - lo);
155        3.0 + t.clamp(0.0, 0.999_999)
156    } else if carrier_hz < F_XRAY_MAX {
157        let lo = F_UV_MAX.log10();
158        let t = (carrier_hz.log10() - lo) / (F_XRAY_MAX.log10() - lo);
159        4.0 + t.clamp(0.0, 0.999_999)
160    } else {
161        let t = (carrier_hz.log10() - F_XRAY_MAX.log10()) / 12.0;
162        5.0 + t.clamp(0.0, 0.999_999)
163    }
164}
165
166pub fn decode_emf64_display(bytes: &[u8]) -> Result<LoadedEmf, String> {
167    let reader = EmfContainerReader::parse_with_limits(bytes, EmfReadLimits::conservative())
168        .map_err(|e| format!("emf64: {e}"))?;
169    let version = reader.header().version;
170    let dense = reader.dense_volume().map_err(|e| format!("emf64: {e}"))?;
171    let total = usize::try_from(dense.nx)
172        .ok()
173        .and_then(|x| x.checked_mul(dense.ny as usize))
174        .and_then(|xy| xy.checked_mul(dense.nz as usize))
175        .and_then(|xyz| xyz.checked_mul(dense.nt as usize))
176        .ok_or_else(|| "emf64: dimension overflow".to_string())?;
177    if total == 0 || total > MAX_DISPLAY_CELLS || total != dense.cells.len() {
178        return Err("emf64: invalid dense display dimensions".into());
179    }
180    let bounds = dense.bounds_meters();
181    if bounds.iter().any(|v| !v.is_finite()) || (0..3).any(|i| bounds[i * 2] >= bounds[i * 2 + 1]) {
182        return Err("emf64: invalid display bounds".into());
183    }
184    let mut cells = Vec::new();
185    let mut optical_cells = Vec::new();
186    cells.try_reserve_exact(total).map_err(|_| "emf64: alloc".to_string())?;
187    optical_cells.try_reserve_exact(total).map_err(|_| "emf64: alloc".to_string())?;
188    for rec in &dense.cells {
189        let finite_ok = rec.e_field.iter().all(|v| v.is_finite())
190            && rec.b_field.iter().all(|v| v.is_finite())
191            && rec.poynting_flux.is_finite() && rec.poynting_flux >= 0.0
192            && rec.wavelength_nm.is_finite() && rec.wavelength_nm >= 0.0
193            && rec.coherence_phase.is_finite()
194            && rec.stokes_q.is_finite() && rec.stokes_u.is_finite() && rec.stokes_v.is_finite()
195            && rec.spectral_sigma.is_finite()
196            && rec.confidence_alpha.is_finite() && (0.0..=1.0).contains(&rec.confidence_alpha);
197        if !finite_ok {
198            return Err("emf64: non-finite or out-of-range cell record".into());
199        }
200        if rec.confidence_alpha == 0.0 {
201            cells.push(DisplayEmfCell::default());
202            optical_cells.push(DisplayOpticalCell::default());
203            continue;
204        }
205        let e = [rec.e_field[0] as f64, rec.e_field[1] as f64, rec.e_field[2] as f64];
206        let b = [rec.b_field[0] as f64, rec.b_field[1] as f64, rec.b_field[2] as f64];
207        let e_mag = e[0].hypot(e[1]).hypot(e[2]);
208        let flux = if rec.poynting_flux > 0.0 {
209            rec.poynting_flux as f64
210        } else {
211            poynting_irradiance_w_per_m2(e, Some(b), None)
212        };
213        let carrier_hz = if rec.wavelength_nm > 0.0 {
214            (VACUUM_SPEED_OF_LIGHT_M_PER_S * 1.0e9) / (rec.wavelength_nm as f64)
215        } else {
216            0.0
217        };
218        let sigma = if rec.spectral_sigma > 0.0 {
219            (rec.spectral_sigma as f64).clamp(0.0, 5.999_999)
220        } else {
221            carrier_hz_to_spectral_sigma(carrier_hz)
222        };
223        let (rq, ru, rv) = (rec.stokes_q as f64, rec.stokes_u as f64, rec.stokes_v as f64);
224        let pol_norm = rq.hypot(ru).hypot(rv);
225        let (stokes_q, stokes_u, stokes_v) = if pol_norm > flux && pol_norm <= 1.0 + 1.0e-5 && flux > 0.0 {
226            (rq * flux, ru * flux, rv * flux)
227        } else if pol_norm <= flux * (1.0 + 1.0e-5) + 1.0e-12 {
228            (rq, ru, rv)
229        } else if pol_norm == 0.0 {
230            (0.0, 0.0, 0.0)
231        } else {
232            return Err("emf64: Stokes polarization exceeds total irradiance I".into());
233        };
234        cells.push(DisplayEmfCell {
235            magnitude_v_per_m: if e_mag > 0.0 { e_mag } else { e_magnitude_from_poynting(flux) },
236            valid: true,
237        });
238        optical_cells.push(DisplayOpticalCell {
239            stokes_i: flux,
240            stokes_q,
241            stokes_u,
242            stokes_v,
243            spectral_sigma: sigma,
244            carrier_hz,
245            phase_rad: rec.coherence_phase as f64,
246            coherence: rec.confidence_alpha as f64,
247            valid: true,
248        });
249    }
250    let ticks: Vec<i64> = (0..dense.nt as i64).collect();
251    let mut source = Vec::new();
252    source.try_reserve_exact(bytes.len()).map_err(|_| "emf64: source alloc".to_string())?;
253    source.extend_from_slice(bytes);
254    Ok(LoadedEmf {
255        nx: dense.nx,
256        ny: dense.ny,
257        nz: dense.nz,
258        nt: dense.nt,
259        cell_count: total as u32,
260        bounds,
261        cells,
262        optical_cells,
263        display_mode: version,
264        source: Arc::from(source.into_boxed_slice()),
265        selection: DisplaySelection { descriptor_id: 0, frame_id: 0, clock_id: 0, stream_id: 0 },
266        ticks,
267        temporal: dense.nt > 1,
268    })
269}
270
271#[derive(Clone, Copy, Debug, PartialEq, Eq)]
272pub enum EmfBackend {
273    Pending,
274    WebGpu,
275    Unavailable,
276}
277
278#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
279#[repr(u8)]
280pub enum EmfDisplayStatus {
281    #[default]
282    Empty = 0,
283    Pending = 1,
284    Uploaded = 2,
285    Unavailable = 3,
286}
287
288impl EmfBackend {
289    pub fn accepted_status(self) -> EmfDisplayStatus {
290        match self {
291            Self::Pending => EmfDisplayStatus::Pending,
292            Self::WebGpu => EmfDisplayStatus::Uploaded,
293            Self::Unavailable => EmfDisplayStatus::Unavailable,
294        }
295    }
296}
297
298impl EmfDisplayStatus {
299    pub fn as_str(self) -> &'static str {
300        match self {
301            Self::Empty => "empty",
302            Self::Pending => "pending",
303            Self::Uploaded => "uploaded",
304            Self::Unavailable => "unavailable",
305        }
306    }
307}
308
309#[derive(Default)]
310pub struct RetainedEmf {
311    field: Option<LoadedEmf>,
312    status: EmfDisplayStatus,
313}
314
315impl RetainedEmf {
316    pub fn bounds(&self) -> Option<[f32; 6]> {
317        self.field.as_ref().map(|f| f.bounds)
318    }
319    pub fn status(&self) -> EmfDisplayStatus {
320        self.status
321    }
322    pub fn accepted(&self) -> Option<&LoadedEmf> {
323        self.field.as_ref()
324    }
325    /// Recheck bounded derivative shape at the ownership boundary. Scientific source
326    /// was fully admitted before construction; upload refusal never swaps old state.
327    pub fn accept(
328        &mut self,
329        field: LoadedEmf,
330        backend: EmfBackend,
331        upload: impl FnOnce(&LoadedEmf) -> Result<(), String>,
332    ) -> Result<(), String> {
333        let count = usize::try_from(field.nx)
334            .ok()
335            .and_then(|n| n.checked_mul(usize::try_from(field.ny).ok()?))
336            .and_then(|n| n.checked_mul(usize::try_from(field.nz).ok()?))
337            .and_then(|n| n.checked_mul(usize::try_from(field.nt).ok()?));
338        let shape_ok = matches!(
339            count,
340            Some(n) if n > 0 && n <= MAX_DISPLAY_CELLS
341                && n == field.cells.len()
342                && n == field.optical_cells.len()
343                && n == field.cell_count as usize
344        );
345        let cells_invalid = field.cells.iter().zip(field.optical_cells.iter()).any(|(c, o)| {
346            if c.valid != o.valid {
347                return true;
348            }
349            if c.valid {
350                let pol = o.stokes_q.hypot(o.stokes_u).hypot(o.stokes_v);
351                c.magnitude_v_per_m.is_nan()
352                    || c.magnitude_v_per_m < 0.0
353                    || o.stokes_i.is_nan()
354                    || o.stokes_i < 0.0
355                    || !o.stokes_q.is_finite()
356                    || !o.stokes_u.is_finite()
357                    || !o.stokes_v.is_finite()
358                    || pol > o.stokes_i * (1.0 + 1.0e-6) + 1.0e-12
359                    || !o.spectral_sigma.is_finite()
360                    || !(0.0..=6.0).contains(&o.spectral_sigma)
361                    || !o.carrier_hz.is_finite()
362                    || o.carrier_hz < 0.0
363                    || !o.phase_rad.is_finite()
364                    || !o.coherence.is_finite()
365                    || !(0.0..=1.0).contains(&o.coherence)
366            } else {
367                c.magnitude_v_per_m.to_bits() != 0
368                    || o.stokes_i.to_bits() != 0
369                    || o.stokes_q.to_bits() != 0
370                    || o.stokes_u.to_bits() != 0
371                    || o.stokes_v.to_bits() != 0
372                    || o.spectral_sigma.to_bits() != 0
373                    || o.carrier_hz.to_bits() != 0
374                    || o.phase_rad.to_bits() != 0
375                    || o.coherence.to_bits() != 0
376            }
377        });
378        if !shape_ok
379            || field.source.is_empty()
380            || field.ticks.len() != field.nt as usize
381            || field.ticks.windows(2).any(|p| p[0] >= p[1])
382            || field.bounds.iter().any(|v| !v.is_finite())
383            || (0..3).any(|i| field.bounds[i * 2] >= field.bounds[i * 2 + 1])
384            || cells_invalid
385        {
386            return Err("emf: invalid retained current display projection".into());
387        }
388        if backend == EmfBackend::WebGpu {
389            upload(&field)?;
390        }
391        self.field = Some(field);
392        self.status = backend.accepted_status();
393        Ok(())
394    }
395    pub fn invalidate(&mut self, pending: bool) {
396        if self.field.is_some() {
397            self.status = if pending {
398                EmfDisplayStatus::Pending
399            } else {
400                EmfDisplayStatus::Unavailable
401            }
402        }
403    }
404    pub fn replay(
405        &mut self,
406        upload: impl FnOnce(&LoadedEmf) -> Result<(), String>,
407    ) -> Result<(), String> {
408        if let Some(field) = &self.field {
409            if let Err(e) = upload(field) {
410                self.status = EmfDisplayStatus::Unavailable;
411                return Err(e);
412            }
413            self.status = EmfDisplayStatus::Uploaded;
414        }
415        Ok(())
416    }
417}
418
419/// Convert paired scalar and optical/polarimetric display cells into GPU `EmfFieldCell`.
420#[cfg(feature = "gpu-runtime")]
421pub fn display_optical_to_gpu_cell(
422    cell: &DisplayEmfCell,
423    opt: &DisplayOpticalCell,
424) -> crate::render::gpu::EmfFieldCell {
425    if !cell.valid || !opt.valid {
426        return crate::render::gpu::EmfFieldCell::default();
427    }
428    let amplitude = -(-cell.magnitude_v_per_m).exp_m1() as f32;
429    let attention_depth = if opt.stokes_i.is_infinite() {
430        1.0
431    } else {
432        (-(-opt.stokes_i).exp_m1() as f32).clamp(0.0, 1.0)
433    };
434    let frequency = if opt.carrier_hz.is_finite() && opt.carrier_hz > 0.0 {
435        opt.carrier_hz.min(f32::MAX as f64) as f32
436    } else {
437        0.0
438    };
439    let spectral_sigma = opt.spectral_sigma.clamp(0.0, 6.0) as f32;
440    let chromatic = opt.spectral_sigma > 0.0 || opt.carrier_hz > 0.0 || opt.phase_rad != 0.0;
441    let scale = if chromatic { 1.0 } else { 0.0 };
442    let sigma_phase = ((opt.spectral_sigma.fract() * std::f64::consts::TAU) as f32).max(0.0);
443    let phase = if opt.phase_rad != 0.0 {
444        opt.phase_rad.rem_euclid(std::f64::consts::TAU) as f32
445    } else if opt.spectral_sigma > 0.0 {
446        sigma_phase
447    } else {
448        0.0
449    };
450    let (mut sq, mut su, mut sv) = if opt.stokes_i.is_finite() && opt.stokes_i > 0.0 && amplitude > 0.0 {
451        let s = f64::from(amplitude) / opt.stokes_i;
452        let clamped = |v: f64| ((v / opt.stokes_i).clamp(-1.0, 1.0) * f64::from(amplitude)) as f32;
453        let _ = s;
454        (clamped(opt.stokes_q), clamped(opt.stokes_u), clamped(opt.stokes_v))
455    } else {
456        (0.0, 0.0, 0.0)
457    };
458    let pol_mag = (sq * sq + su * su + sv * sv).sqrt();
459    if pol_mag > amplitude && pol_mag > 0.0 {
460        let s = amplitude / pol_mag;
461        sq *= s;
462        su *= s;
463        sv *= s;
464    }
465    let dop = if amplitude > 0.0 { (pol_mag / amplitude).clamp(0.0, 1.0) } else { 0.0 };
466    crate::render::gpu::EmfFieldCell {
467        amplitude,
468        phase,
469        frequency,
470        scale,
471        attention_depth,
472        epistemic_weight: 1.0,
473        topological_spin: 0.0,
474        temporal_decay: 0.0,
475        entropy_bias: 0.0,
476        spatial_phase: sigma_phase,
477        recurrence_frequency: spectral_sigma,
478        density_threshold: opt.coherence.clamp(0.0, 1.0) as f32,
479        manifold_curvature: if chromatic { dop * 0.5 } else { 0.0 },
480        stokes_q: sq,
481        stokes_u: su,
482        stokes_v: sv,
483    }
484}
485
486#[cfg(all(target_arch = "wasm32", feature = "portal"))]
487pub(crate) fn upload(
488    gpu: &mut crate::render::gpu::PortalGpu,
489    field: &LoadedEmf,
490) -> Result<(), String> {
491    gpu.emf_upload_loaded(field)
492}