1use crate::render::spectral_basis::{
16 evaluate_spectral_reflectance, JakobHanikaCoeffs, LAMBDA_MIN_NM,
17};
18
19#[repr(u8)]
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum OntologicalClass {
23 DarwinianTaxon = 1,
25 ManufacturedProperty = 2,
27 LiberalArtsWork = 3,
29 AbioticEnvironment = 4,
31 NaturalPerson = 5,
33}
34
35impl OntologicalClass {
36 pub fn from_u8(tag: u8) -> Option<Self> {
38 match tag {
39 1 => Some(Self::DarwinianTaxon),
40 2 => Some(Self::ManufacturedProperty),
41 3 => Some(Self::LiberalArtsWork),
42 4 => Some(Self::AbioticEnvironment),
43 5 => Some(Self::NaturalPerson),
44 _ => None,
45 }
46 }
47
48 pub fn from_str_name(name: &str) -> Option<Self> {
50 match name.to_lowercase().as_str() {
51 "darwiniantaxon" | "taxon" | "specimen" | "species" | "flora" | "fauna" => {
52 Some(Self::DarwinianTaxon)
53 }
54 "manufacturedproperty" | "property" | "construct" | "machine" | "tool" | "asset" => {
55 Some(Self::ManufacturedProperty)
56 }
57 "liberalartswork" | "cultural" | "work" | "expression" | "lore" => {
58 Some(Self::LiberalArtsWork)
59 }
60 "abioticenvironment" | "environment" | "terrain" | "feature" | "geology" => {
61 Some(Self::AbioticEnvironment)
62 }
63 "naturalperson" | "person" | "persona" | "likeness" | "human" => {
64 Some(Self::NaturalPerson)
65 }
66 _ => None,
67 }
68 }
69
70 pub fn embodiment_term(&self) -> &'static str {
72 match self {
73 Self::DarwinianTaxon => "Specimen",
74 Self::ManufacturedProperty => "Construct",
75 Self::LiberalArtsWork => "Expression",
76 Self::AbioticEnvironment => "Terrain",
77 Self::NaturalPerson => "Persona",
78 }
79 }
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum GateError {
84 SpectralEnergyViolation { lambda_nm: u32, reflectance: u32 },
86 BssrdfZeroOrNegative,
88 GeometryBoundsViolation,
90 ImpostorSphereMisaligned,
92 MalformedOntologicalClass,
94 MissingPhysicalConstants,
96 HumanPersonCannotBeCommodifiedAsAsset,
98 NonDeterministicScriptExecution,
100 BiosphereRequiresPermissiveCommons,
102 BiosphereCannotHavePerpetualFees,
104}
105
106impl core::fmt::Display for GateError {
107 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
108 match self {
109 Self::SpectralEnergyViolation {
110 lambda_nm,
111 reflectance,
112 } => {
113 write!(
114 f,
115 "spectral energy violation at {lambda_nm} nm: reflectance {reflectance}"
116 )
117 }
118 Self::BssrdfZeroOrNegative => {
119 write!(f, "BSSRDF mean free path must be strictly positive")
120 }
121 Self::GeometryBoundsViolation => {
122 write!(f, "lower-tier geometry spills outside Tier 1 Hero AABB")
123 }
124 Self::ImpostorSphereMisaligned => {
125 write!(f, "impostor bounding sphere misaligned with geometry")
126 }
127 Self::MalformedOntologicalClass => write!(f, "malformed or missing ontological class"),
128 Self::MissingPhysicalConstants => write!(f, "missing mandatory physical constants"),
129 Self::HumanPersonCannotBeCommodifiedAsAsset => {
130 write!(f, "anti-commodification violation: a NaturalPerson cannot be classified as property or an asset")
131 }
132 Self::NonDeterministicScriptExecution => {
133 write!(f, "script violates determinism or cycle limits")
134 }
135 Self::BiosphereRequiresPermissiveCommons => {
136 write!(f, "humanitarian ict gate violation: living biosphere entity must be governed under Permissive Commons")
137 }
138 Self::BiosphereCannotHavePerpetualFees => {
139 write!(f, "humanitarian ict gate violation: living biosphere entity cannot be encumbered with perpetual fees")
140 }
141 }
142 }
143}
144
145impl std::error::Error for GateError {}
146
147pub fn validate_spectral_coeffs(coeffs: &JakobHanikaCoeffs) -> Result<(), GateError> {
153 for lambda_step in 0..=40 {
154 let lambda_nm = LAMBDA_MIN_NM + (lambda_step as f32) * 10.0;
155 let r = evaluate_spectral_reflectance(coeffs, lambda_nm);
156 if r < -1e-6 || r > 1.00001 {
157 return Err(GateError::SpectralEnergyViolation {
158 lambda_nm: lambda_nm as u32,
159 reflectance: (r * 1000.0) as u32,
160 });
161 }
162 }
163 Ok(())
164}
165
166pub fn validate_bssrdf_parameters(mean_free_path_mm: [f32; 4]) -> Result<(), GateError> {
168 for &ld in &mean_free_path_mm {
169 if ld <= 1e-5 || !ld.is_finite() {
170 return Err(GateError::BssrdfZeroOrNegative);
171 }
172 }
173 Ok(())
174}
175
176pub fn validate_geometry_confinement(
182 hero_min: [f32; 3],
183 hero_max: [f32; 3],
184 child_min: [f32; 3],
185 child_max: [f32; 3],
186 sphere_center: [f32; 3],
187 sphere_radius: f32,
188) -> Result<(), GateError> {
189 const EPSILON: f32 = 0.05; for i in 0..3 {
192 if child_min[i] < hero_min[i] - EPSILON || child_max[i] > hero_max[i] + EPSILON {
193 return Err(GateError::GeometryBoundsViolation);
194 }
195 }
196
197 let aabb_center = [
199 (hero_min[0] + hero_max[0]) * 0.5,
200 (hero_min[1] + hero_max[1]) * 0.5,
201 (hero_min[2] + hero_max[2]) * 0.5,
202 ];
203 let dist_sq = (aabb_center[0] - sphere_center[0]).powi(2)
204 + (aabb_center[1] - sphere_center[1]).powi(2)
205 + (aabb_center[2] - sphere_center[2]).powi(2);
206
207 if dist_sq > (sphere_radius * 0.25).powi(2) {
208 return Err(GateError::ImpostorSphereMisaligned);
209 }
210
211 Ok(())
212}
213
214pub fn validate_ontological_integrity(
220 origin_tag: u8,
221 mass_kg: Option<f32>,
222) -> Result<(), GateError> {
223 match OntologicalClass::from_u8(origin_tag) {
224 Some(OntologicalClass::DarwinianTaxon) => Ok(()), Some(OntologicalClass::ManufacturedProperty) => {
226 if let Some(m) = mass_kg {
228 if m > 0.0 && m.is_finite() {
229 Ok(())
230 } else {
231 Err(GateError::MissingPhysicalConstants)
232 }
233 } else {
234 Err(GateError::MissingPhysicalConstants)
235 }
236 }
237 Some(OntologicalClass::LiberalArtsWork) => Ok(()), Some(OntologicalClass::AbioticEnvironment) => Ok(()), Some(OntologicalClass::NaturalPerson) => Ok(()), None => Err(GateError::MalformedOntologicalClass),
241 }
242}
243
244pub fn assert_person_anti_commodification(
246 entity_class: OntologicalClass,
247 as_property: bool,
248) -> Result<(), GateError> {
249 if entity_class == OntologicalClass::NaturalPerson && as_property {
250 Err(GateError::HumanPersonCannotBeCommodifiedAsAsset)
251 } else {
252 Ok(())
253 }
254}
255
256pub fn assert_biosphere_permissive_commons(
265 entity_class: OntologicalClass,
266 licence_tag: &str,
267 has_perpetual_royalties: bool,
268) -> Result<(), GateError> {
269 match entity_class {
270 OntologicalClass::DarwinianTaxon | OntologicalClass::AbioticEnvironment => {
271 if has_perpetual_royalties {
272 return Err(GateError::BiosphereCannotHavePerpetualFees);
273 }
274 let lic = crate::q42::asset_envelope::LicenceClass::parse(licence_tag);
275 match lic {
276 crate::q42::asset_envelope::LicenceClass::Cc0
277 | crate::q42::asset_envelope::LicenceClass::CcBy
278 | crate::q42::asset_envelope::LicenceClass::CcBySa
279 | crate::q42::asset_envelope::LicenceClass::SocialPermissiveCommons => Ok(()),
280 _ => Err(GateError::BiosphereRequiresPermissiveCommons),
281 }
282 }
283 _ => Ok(()),
284 }
285}
286
287pub fn validate_script_determinism(
289 instruction_count: u64,
290 has_unauthorized_host_calls: bool,
291) -> Result<(), GateError> {
292 const MAX_INSTRUCTION_BUDGET: u64 = 1_000_000;
293 if has_unauthorized_host_calls || instruction_count > MAX_INSTRUCTION_BUDGET {
294 return Err(GateError::NonDeterministicScriptExecution);
295 }
296 Ok(())
297}
298
299#[inline]
305pub fn xyz_to_oklab(xyz: [f32; 3]) -> [f32; 3] {
306 let l = 0.818_933 * xyz[0] + 0.361_866_74 * xyz[1] - 0.128_859_71 * xyz[2];
307 let m = 0.032_984_544 * xyz[0] + 0.929_311_9 * xyz[1] + 0.036_145_64 * xyz[2];
308 let s = 0.048_200_3 * xyz[0] + 0.264_366_27 * xyz[1] + 0.633_851_7 * xyz[2];
309
310 let l_ = if l > 0.0 { l.cbrt() } else { 0.0 };
311 let m_ = if m > 0.0 { m.cbrt() } else { 0.0 };
312 let s_ = if s > 0.0 { s.cbrt() } else { 0.0 };
313
314 let l_oklab = 0.210_454_26 * l_ + 0.793_617_8 * m_ - 0.004_072_047 * s_;
315 let a_oklab = 1.977_998_5 * l_ - 2.428_592_2 * m_ + 0.450_593_7 * s_;
316 let b_oklab = 0.025_904_037 * l_ + 0.782_771_77 * m_ - 0.808_675_77 * s_;
317
318 [l_oklab, a_oklab, b_oklab]
319}
320
321#[inline]
323pub fn oklab_to_xyz(oklab: [f32; 3]) -> [f32; 3] {
324 let l_ = oklab[0] + 0.396_337_78 * oklab[1] + 0.215_803_76 * oklab[2];
325 let m_ = oklab[0] - 0.105_561_346 * oklab[1] - 0.063_854_17 * oklab[2];
326 let s_ = oklab[0] - 0.089_484_18 * oklab[1] - 1.291_485_5 * oklab[2];
327
328 let l = l_ * l_ * l_;
329 let m = m_ * m_ * m_;
330 let s = s_ * s_ * s_;
331
332 let x = 1.227_013_8 * l - 0.557_797_7 * m + 0.281_256_15 * s;
333 let y = -0.040_580_18 * l + 1.112_256_9 * m - 0.071_676_68 * s;
334 let z = -0.076_381_284 * l - 0.421_481_98 * m + 1.586_163_2 * s;
335
336 [x, y, z]
337}
338
339#[inline]
342pub fn clamp_taa_history_oklab(
343 history_xyz: [f32; 3],
344 neighborhood_3x3_xyz: &[[f32; 3]; 9],
345 gamma: f32, ) -> [f32; 3] {
347 let mut mean = [0.0f32; 3];
348 let mut m2 = [0.0f32; 3];
349
350 for s in neighborhood_3x3_xyz.iter() {
351 let lab = xyz_to_oklab(*s);
352 for c in 0..3 {
353 mean[c] += lab[c];
354 m2[c] += lab[c] * lab[c];
355 }
356 }
357
358 let inv_9 = 1.0 / 9.0;
359 for c in 0..3 {
360 mean[c] *= inv_9;
361 m2[c] *= inv_9;
362 }
363
364 let mut min_bound = [0.0f32; 3];
365 let mut max_bound = [0.0f32; 3];
366 for c in 0..3 {
367 let variance = (m2[c] - mean[c] * mean[c]).max(0.0);
368 let std_dev = variance.sqrt();
369 min_bound[c] = mean[c] - gamma * std_dev;
370 max_bound[c] = mean[c] + gamma * std_dev;
371 }
372
373 let mut hist_lab = xyz_to_oklab(history_xyz);
374 for c in 0..3 {
375 hist_lab[c] = hist_lab[c].clamp(min_bound[c], max_bound[c]);
376 }
377
378 oklab_to_xyz(hist_lab)
379}
380
381#[inline]
383pub fn calculate_taa_blend_factor(screen_velocity_pixels: f32) -> f32 {
384 const ALPHA_STATIC: f32 = 0.05;
385 const ALPHA_DYNAMIC_MAX: f32 = 0.20;
386 const VELOCITY_RAMP_PIXELS: f32 = 4.0;
387
388 let t = (screen_velocity_pixels / VELOCITY_RAMP_PIXELS).clamp(0.0, 1.0);
389 ALPHA_STATIC + t * (ALPHA_DYNAMIC_MAX - ALPHA_STATIC)
390}
391
392#[inline]
394pub fn is_taa_history_disoccluded(current_linear_depth: f32, history_linear_depth: f32) -> bool {
395 const DEPTH_THRESHOLD_RATIO: f32 = 0.05; let diff = (current_linear_depth - history_linear_depth).abs();
397 diff > (current_linear_depth * DEPTH_THRESHOLD_RATIO)
398}
399
400#[cfg(test)]
401mod tests {
402 use super::*;
403
404 #[test]
405 fn anti_commodification_gate_protects_natural_persons() {
406 let err = assert_person_anti_commodification(OntologicalClass::NaturalPerson, true);
408 assert_eq!(err, Err(GateError::HumanPersonCannotBeCommodifiedAsAsset));
409
410 let ok = assert_person_anti_commodification(OntologicalClass::NaturalPerson, false);
412 assert!(ok.is_ok());
413
414 let prop = assert_person_anti_commodification(OntologicalClass::ManufacturedProperty, true);
416 assert!(prop.is_ok());
417 }
418
419 #[test]
420 fn oklab_roundtrip_is_lossless() {
421 let white_xyz = [0.950_47, 1.0, 1.088_83];
422 let lab = xyz_to_oklab(white_xyz);
423 let reconstructed = oklab_to_xyz(lab);
424
425 for c in 0..3 {
426 assert!((white_xyz[c] - reconstructed[c]).abs() < 1e-4);
427 }
428 }
429
430 #[test]
431 fn gate1_spectral_validation() {
432 let valid_coeffs = JakobHanikaCoeffs {
434 c0: 0.5,
435 c1: 0.0,
436 c2: 0.0,
437 }; assert!(validate_spectral_coeffs(&valid_coeffs).is_ok());
439
440 let invalid_mfp = [0.0f32, 1.0, 2.0, 1.0];
442 assert_eq!(
443 validate_bssrdf_parameters(invalid_mfp),
444 Err(GateError::BssrdfZeroOrNegative)
445 );
446
447 let valid_mfp = [0.5f32, 1.2, 3.4, 1.0];
448 assert!(validate_bssrdf_parameters(valid_mfp).is_ok());
449 }
450
451 #[test]
452 fn gate2_geometry_confinement() {
453 let hero_min = [-1.0f32, -1.0, -1.0];
454 let hero_max = [1.0f32, 1.0, 1.0];
455 let center = [0.0f32, 0.0, 0.0];
456 let radius = 1.732f32;
457
458 let lod_min = [-1.04f32, -1.0, -1.0];
460 let lod_max = [1.04f32, 1.0, 1.0];
461 assert!(validate_geometry_confinement(
462 hero_min, hero_max, lod_min, lod_max, center, radius
463 )
464 .is_ok());
465
466 let bad_min = [-1.10f32, -1.0, -1.0];
468 let bad_max = [1.0f32, 1.0, 1.0];
469 assert_eq!(
470 validate_geometry_confinement(hero_min, hero_max, bad_min, bad_max, center, radius),
471 Err(GateError::GeometryBoundsViolation)
472 );
473 }
474
475 #[test]
476 fn gate3_ontological_integrity() {
477 assert!(
479 validate_ontological_integrity(OntologicalClass::DarwinianTaxon as u8, None).is_ok()
480 );
481
482 assert_eq!(
484 validate_ontological_integrity(OntologicalClass::ManufacturedProperty as u8, None),
485 Err(GateError::MissingPhysicalConstants)
486 );
487
488 assert!(validate_ontological_integrity(
490 OntologicalClass::ManufacturedProperty as u8,
491 Some(42.0)
492 )
493 .is_ok());
494
495 assert_eq!(
497 validate_ontological_integrity(99, None),
498 Err(GateError::MalformedOntologicalClass)
499 );
500 }
501
502 #[test]
503 fn gate4_script_determinism() {
504 assert!(validate_script_determinism(500_000, false).is_ok());
505 assert_eq!(
506 validate_script_determinism(1_500_000, false),
507 Err(GateError::NonDeterministicScriptExecution)
508 );
509 assert_eq!(
510 validate_script_determinism(100, true),
511 Err(GateError::NonDeterministicScriptExecution)
512 );
513 }
514
515 #[test]
516 fn taa_clamping_and_blend_factor() {
517 let center = [0.5f32, 0.5, 0.5];
518 let neighborhood = [center; 9];
519 let outlier = [1.5f32, 1.5, 1.5];
520
521 let clamped = clamp_taa_history_oklab(outlier, &neighborhood, 1.0);
522 assert!(clamped[0] < outlier[0]);
523
524 assert_eq!(calculate_taa_blend_factor(0.0), 0.05);
526 assert_eq!(calculate_taa_blend_factor(10.0), 0.20);
528 }
529}