1use super::EmfFieldCell;
5use crate::q42::{
6 emf_container::EmfCellRecord64,
7 field_spectrum::VACUUM_SPEED_OF_LIGHT_M_PER_S,
8};
9use crate::render::portal_emf_state::{
10 carrier_hz_to_spectral_sigma, display_optical_to_gpu_cell, e_magnitude_from_poynting,
11 poynting_irradiance_w_per_m2, DisplayEmfCell, DisplayOpticalCell, LoadedEmf,
12};
13use etalon_render::spectral::sigma::sigma_to_linear_rgb;
14
15pub fn emf_field_cell_from_optical(cell: &DisplayEmfCell, opt: &DisplayOpticalCell) -> EmfFieldCell {
17 display_optical_to_gpu_cell(cell, opt)
18}
19
20pub fn emf_cells_from_loaded(loaded: &LoadedEmf) -> Result<Vec<EmfFieldCell>, String> {
22 let cells = loaded.display_cells();
23 let optical = loaded.optical_cells();
24 if cells.len() != optical.len() {
25 return Err("emf: optical cell length mismatch".into());
26 }
27 let mut out = Vec::new();
28 out.try_reserve_exact(cells.len())
29 .map_err(|_| "emf: GPU cell buffer allocation failed".to_string())?;
30 out.extend(
31 cells
32 .iter()
33 .zip(optical.iter())
34 .map(|(c, o)| display_optical_to_gpu_cell(c, o)),
35 );
36 Ok(out)
37}
38
39pub fn emf_field_cell_from_record64(rec: &EmfCellRecord64) -> Result<EmfFieldCell, String> {
41 let finite = rec.e_field.iter().all(|v| v.is_finite())
42 && rec.b_field.iter().all(|v| v.is_finite())
43 && rec.poynting_flux.is_finite()
44 && rec.poynting_flux >= 0.0
45 && rec.wavelength_nm.is_finite()
46 && rec.wavelength_nm >= 0.0
47 && rec.coherence_phase.is_finite()
48 && rec.stokes_q.is_finite()
49 && rec.stokes_u.is_finite()
50 && rec.stokes_v.is_finite()
51 && rec.spectral_sigma.is_finite()
52 && rec.confidence_alpha.is_finite()
53 && (0.0..=1.0).contains(&rec.confidence_alpha);
54 if !finite {
55 return Err("emf64: non-finite or out-of-range cell record".into());
56 }
57 if rec.confidence_alpha == 0.0 {
58 return Ok(EmfFieldCell::default());
59 }
60 let e = [rec.e_field[0] as f64, rec.e_field[1] as f64, rec.e_field[2] as f64];
61 let b = [rec.b_field[0] as f64, rec.b_field[1] as f64, rec.b_field[2] as f64];
62 let e_mag = e[0].hypot(e[1]).hypot(e[2]);
63 let flux = if rec.poynting_flux > 0.0 {
64 rec.poynting_flux as f64
65 } else {
66 poynting_irradiance_w_per_m2(e, Some(b), None)
67 };
68 let carrier_hz = if rec.wavelength_nm > 0.0 {
69 (VACUUM_SPEED_OF_LIGHT_M_PER_S * 1.0e9) / (rec.wavelength_nm as f64)
70 } else {
71 0.0
72 };
73 let spectral_sigma = if rec.spectral_sigma > 0.0 {
74 (rec.spectral_sigma as f64).clamp(0.0, 5.999_999)
75 } else {
76 carrier_hz_to_spectral_sigma(carrier_hz)
77 };
78 let raw_q = rec.stokes_q as f64;
79 let raw_u = rec.stokes_u as f64;
80 let raw_v = rec.stokes_v as f64;
81 let pol_norm = raw_q.hypot(raw_u).hypot(raw_v);
82 let (stokes_q, stokes_u, stokes_v) = if pol_norm > flux && pol_norm <= 1.0 + 1.0e-5 && flux > 0.0 {
83 (raw_q * flux, raw_u * flux, raw_v * flux)
84 } else if pol_norm <= flux * (1.0 + 1.0e-5) + 1.0e-12 {
85 (raw_q, raw_u, raw_v)
86 } else if pol_norm == 0.0 {
87 (0.0, 0.0, 0.0)
88 } else {
89 return Err("emf64: Stokes polarization exceeds total irradiance I".into());
90 };
91 let cell = DisplayEmfCell {
92 magnitude_v_per_m: if e_mag > 0.0 { e_mag } else { e_magnitude_from_poynting(flux) },
93 valid: true,
94 };
95 let opt = DisplayOpticalCell {
96 stokes_i: flux,
97 stokes_q,
98 stokes_u,
99 stokes_v,
100 spectral_sigma,
101 carrier_hz,
102 phase_rad: rec.coherence_phase as f64,
103 coherence: rec.confidence_alpha as f64,
104 valid: true,
105 };
106 Ok(display_optical_to_gpu_cell(&cell, &opt))
107}
108
109fn mix_f32(a: f32, b: f32, t: f32) -> f32 {
110 a + (b - a) * t
111}
112
113pub fn full_spectrum_sigma_to_linear_rgb(sigma: f32) -> [f32; 3] {
116 let clamped = sigma.max(0.0);
117 let band = clamped.floor() as i32;
118 let s = clamped - clamped.floor();
119 match band {
120 0 => sigma_to_linear_rgb(s),
121 1 => [
122 mix_f32(0.35, 1.0, s),
123 mix_f32(0.02, 0.55, s * s),
124 mix_f32(0.05, 0.08, s),
125 ],
126 2 => {
127 let r = (s * 1.6).clamp(0.0, 1.0);
128 let g = ((s - 0.35) * 1.55).clamp(0.0, 1.0);
129 let b = ((s * std::f32::consts::PI).sin() * 0.75 + ((s - 0.75) * 4.0).max(0.0))
130 .clamp(0.0, 1.0);
131 [r, g, b]
132 }
133 3 => [
134 mix_f32(0.42, 0.05, s),
135 mix_f32(0.05, 0.92, s),
136 mix_f32(0.75, 1.0, s),
137 ],
138 4 => {
139 let c = s.powf(0.85);
140 [c * 0.75, c * 0.95, (c * 1.15).clamp(0.0, 1.0)]
141 }
142 _ => [
143 mix_f32(0.15, 0.95, s * s),
144 mix_f32(0.35, 0.98, s),
145 1.0,
146 ],
147 }
148}
149
150#[inline]
151fn linear_to_srgb_u8(c: f32) -> u8 {
152 let clamped = c.clamp(0.0, 1.0);
153 let gamma = if clamped <= 0.003_130_8 {
154 12.92 * clamped
155 } else {
156 1.055 * clamped.powf(1.0 / 2.4) - 0.055
157 };
158 (gamma * 255.0).round().clamp(0.0, 255.0) as u8
159}
160
161#[allow(clippy::too_many_arguments)]
164pub fn evaluate_display_slice_rgba8(
165 cells: &[DisplayEmfCell],
166 optical: &[DisplayOpticalCell],
167 nx: u32,
168 ny: u32,
169 nz: u32,
170 nt: u32,
171 slice_z: u32,
172 slice_t: u32,
173 amplitude_scale: f32,
174 phase_offset: f32,
175 manifold_gain: f32,
176 projection_mode: u32,
177) -> Result<Vec<u8>, String> {
178 let expected = (nx as usize)
179 .checked_mul(ny as usize)
180 .and_then(|v| v.checked_mul(nz as usize))
181 .and_then(|v| v.checked_mul(nt as usize))
182 .ok_or_else(|| "emf: slice dimension overflow".to_string())?;
183 if expected == 0 || cells.len() != expected || optical.len() != expected {
184 return Err("emf: invalid display slice buffer dimensions".into());
185 }
186 let sz = slice_z.min(nz - 1) as usize;
187 let st = slice_t.min(nt - 1) as usize;
188 let plane = (nx as usize) * (ny as usize);
189 let slice_base = (st * (nz as usize) + sz) * plane;
190 let mut rgba = Vec::new();
191 rgba.try_reserve_exact(plane * 4)
192 .map_err(|_| "emf: slice RGBA allocation failed".to_string())?;
193 for y in 0..ny as usize {
194 for x in 0..nx as usize {
195 let idx = slice_base + y * (nx as usize) + x;
196 let gpu = display_optical_to_gpu_cell(&cells[idx], &optical[idx]);
197 if projection_mode == 1 {
198 let g = linear_to_srgb_u8(gpu.amplitude);
199 let a = (gpu.epistemic_weight.clamp(0.0, 1.0) * 255.0).round() as u8;
200 rgba.extend_from_slice(&[g, g, g, a]);
201 continue;
202 }
203 if gpu.epistemic_weight <= 0.0 {
204 rgba.extend_from_slice(&[0, 0, 0, 0]);
205 continue;
206 }
207 let amp = (gpu.amplitude.abs() * amplitude_scale).clamp(0.0, 4.0);
208 let sigma = if gpu.recurrence_frequency > 0.0 || gpu.frequency > 0.0 {
209 (gpu.recurrence_frequency + phase_offset / std::f32::consts::TAU).max(0.0)
210 } else {
211 0.0
212 };
213 let base_rgb = full_spectrum_sigma_to_linear_rgb(sigma);
214 let sat = (gpu.scale * manifold_gain).clamp(0.0, 1.5);
215 let lum = base_rgb[0] * 0.2126 + base_rgb[1] * 0.7152 + base_rgb[2] * 0.0722;
216 let dop = gpu.degree_of_polarization();
217 let pol_highlight = 1.0 + 0.35 * dop;
218 let sat_rgb = [
219 mix_f32(lum, base_rgb[0], sat) * amp * pol_highlight,
220 mix_f32(lum, base_rgb[1], sat) * amp * pol_highlight,
221 mix_f32(lum, base_rgb[2], sat) * amp * pol_highlight,
222 ];
223 let a = (amp * 0.5 + 0.1).clamp(0.0, 1.0);
224 rgba.extend_from_slice(&[
225 linear_to_srgb_u8(sat_rgb[0]),
226 linear_to_srgb_u8(sat_rgb[1]),
227 linear_to_srgb_u8(sat_rgb[2]),
228 (a * 255.0).round() as u8,
229 ]);
230 }
231 }
232 Ok(rgba)
233}
234
235#[cfg(test)]
236mod tests {
237 use super::*;
238
239 #[test]
240 fn static_field_has_zero_sigma_and_grayscale_saturation() {
241 let cell = DisplayEmfCell {
242 magnitude_v_per_m: 3.0,
243 valid: true,
244 };
245 let opt = DisplayOpticalCell {
246 stokes_i: poynting_irradiance_w_per_m2([3.0, 0.0, 0.0], None, None),
247 spectral_sigma: carrier_hz_to_spectral_sigma(0.0),
248 carrier_hz: 0.0,
249 coherence: 1.0,
250 valid: true,
251 ..Default::default()
252 };
253 assert_eq!(opt.spectral_sigma, 0.0);
254 let gpu = emf_field_cell_from_optical(&cell, &opt);
255 assert_eq!(gpu.recurrence_frequency, 0.0);
256 assert_eq!(gpu.frequency, 0.0);
257 assert_eq!(gpu.scale, 0.0);
258 assert_eq!(gpu.epistemic_weight, 1.0);
259 assert!(gpu.amplitude > 0.9);
260 }
261
262 #[test]
263 fn full_spectrum_rf_ir_vis_uv_xray_gamma_have_no_visible_cutoff() {
264 let bands = [
265 (1.0e9_f64, 1), (10.0e12_f64, 2), (5.45e14_f64, 0), (1.5e15_f64, 3), (1.0e18_f64, 4), (1.0e21_f64, 5), ];
272 for (freq_hz, expected_band) in bands {
273 let sigma = carrier_hz_to_spectral_sigma(freq_hz);
274 assert_eq!(sigma.floor() as i32, expected_band, "freq={freq_hz}");
275 let cell = DisplayEmfCell {
276 magnitude_v_per_m: 1.5,
277 valid: true,
278 };
279 let opt = DisplayOpticalCell {
280 stokes_i: poynting_irradiance_w_per_m2([1.5, 0.0, 0.0], None, None),
281 spectral_sigma: sigma,
282 carrier_hz: freq_hz,
283 coherence: 1.0,
284 valid: true,
285 ..Default::default()
286 };
287 let gpu = emf_field_cell_from_optical(&cell, &opt);
288 assert!(gpu.amplitude > 0.5);
289 assert_eq!(gpu.scale, 1.0);
290 assert!((gpu.recurrence_frequency - sigma as f32).abs() < 1e-5);
291 let rgb = full_spectrum_sigma_to_linear_rgb(gpu.recurrence_frequency);
292 assert!(rgb[0] > 0.0 || rgb[1] > 0.0 || rgb[2] > 0.0, "band={expected_band}");
293 let rgba = evaluate_display_slice_rgba8(&[cell], &[opt], 1, 1, 1, 1, 0, 0, 1.0, 0.0, 1.0, 0)
294 .unwrap();
295 assert!(rgba[0] > 0 || rgba[1] > 0 || rgba[2] > 0);
296 assert!(rgba[3] > 0);
297 }
298 }
299
300 #[test]
301 fn stokes_polarization_and_record64_convert_with_causality_checks() {
302 let mut rec = EmfCellRecord64::default();
303 rec.e_field = [10.0, 0.0, 0.0];
304 rec.b_field = [0.0, 10.0 / 299_792_458.0, 0.0];
305 rec.poynting_flux = 0.265_441_87;
306 rec.wavelength_nm = 550.0;
307 rec.coherence_phase = 1.25;
308 rec.stokes_q = 0.6;
309 rec.stokes_u = 0.0;
310 rec.stokes_v = 0.8; let cell = emf_field_cell_from_record64(&rec).unwrap();
312 assert!((cell.degree_of_polarization() - 1.0).abs() < 1e-3);
313 assert!((cell.recurrence_frequency - 0.5).abs() < 1e-4);
314 assert!((cell.phase - 1.25).abs() < 1e-6);
315
316 let mut bad = rec;
317 bad.stokes_q = 2.0;
318 assert!(emf_field_cell_from_record64(&bad).is_err());
319 bad.e_field[0] = f32::NAN;
320 assert!(emf_field_cell_from_record64(&bad).is_err());
321 }
322
323 #[test]
324 fn cpu_slice_projection_modes_preserve_missing_zero_and_spectral_parity() {
325 let cells = [
326 DisplayEmfCell { magnitude_v_per_m: 0.0, valid: true },
327 DisplayEmfCell::default(),
328 DisplayEmfCell { magnitude_v_per_m: 2.0, valid: true },
329 ];
330 let opts = [
331 DisplayOpticalCell { coherence: 1.0, valid: true, ..Default::default() },
332 DisplayOpticalCell::default(),
333 DisplayOpticalCell {
334 stokes_i: poynting_irradiance_w_per_m2([2.0, 0.0, 0.0], None, None),
335 stokes_q: poynting_irradiance_w_per_m2([2.0, 0.0, 0.0], None, None) * 0.5,
336 spectral_sigma: 0.5,
337 carrier_hz: 5.450_771_963_6e14,
338 coherence: 1.0,
339 valid: true,
340 ..Default::default()
341 },
342 ];
343 let mode1 = evaluate_display_slice_rgba8(&cells, &opts, 3, 1, 1, 1, 0, 0, 1.0, 0.0, 1.0, 1).unwrap();
344 assert_eq!(&mode1[0..4], &[0, 0, 0, 255]); assert_eq!(&mode1[4..8], &[0, 0, 0, 0]); assert_eq!(mode1[8], mode1[9]); assert_eq!(mode1[9], mode1[10]);
348
349 let mode0 = evaluate_display_slice_rgba8(&cells, &opts, 3, 1, 1, 1, 0, 0, 1.0, 0.0, 1.0, 0).unwrap();
350 assert_eq!(&mode0[4..8], &[0, 0, 0, 0]); assert!(mode0[9] > mode0[8] && mode0[9] > mode0[10]); }
353
354 #[test]
355 fn c_emf_upload_emf64_and_render_volumetric_mode0() {
356 use crate::q42::emf_container::{
357 emf_brick_voxel_linear_index, EmfCellRecord64, EmfContainerWriter, EMF_BRICK_CELLS,
358 };
359 use crate::q42::m64_matter::brick3d::encode_hilbert3d_u64;
360
361 let mut writer = EmfContainerWriter::new([0.0, 0.0, 0.0], 0.25, [1, 1, 1], 0.0);
362 let mut cells = [EmfCellRecord64::default(); EMF_BRICK_CELLS];
363 for z in 0..8 {
364 for y in 0..8 {
365 for x in 0..8 {
366 let idx = emf_brick_voxel_linear_index(x, y, z);
367 cells[idx].e_field = [6.0, 8.0, 0.0];
368 cells[idx].wavelength_nm = 532.0;
369 cells[idx].stokes_q = 0.7;
370 cells[idx].stokes_u = 0.2;
371 }
372 }
373 }
374 writer
375 .add_brick_chunk(encode_hilbert3d_u64(0, 0, 0, 2), &cells, 0, 1, 0)
376 .unwrap();
377 let bytes = writer.to_bytes().unwrap();
378
379 let loaded = LoadedEmf::from_emf64(&bytes).unwrap();
380 assert_eq!(loaded.dimensions(), [8, 8, 8, 1]);
381 assert!((loaded.display_cells()[0].magnitude_v_per_m - 10.0).abs() < 1e-4);
382 assert!(loaded.optical_cells()[0].stokes_i > 0.0);
383 assert!(loaded.optical_cells()[0].spectral_sigma > 0.0);
384
385 if crate::gpu_context::try_shared_gpu().is_none() {
386 return;
387 }
388 let mut portal = crate::render::gpu::PortalGpu::new_offscreen(32, 32, 256).expect("offscreen");
389 portal.emf_upload_emf64(&bytes).expect("emf64 upload");
390 assert!(portal.emf_has_field());
391 assert_eq!(portal.emf_grid_dims(), (8, 8, 8, 1));
392 let (w, h, pixels) = portal.emf_render_slice_to_rgba8().expect("render+readback");
393 assert_eq!((w, h), (32, 32));
394 assert!(pixels.chunks(4).any(|px| px[0] > 0 || px[1] > 0 || px[2] > 0));
395 }
396}