Skip to main content

qualia_core_db/container_10d/
metric_trait_gate.rs

1//! Fail-Closed QUDT Species-Trait & Artefact Dimensional Admission Gate (GAP-13 / G69).
2//!
3//! Validates every admitted `.10d` organism or vehicle asset's authored bounding box (AABB in SI metres),
4//! tissue/material density, and simulation mass against its `.q42` QUDT trait envelope
5//! (`AusTraits` / `AFD` / `AVONET` / `made:Artefact` specs per `DTA-ID-05`, `DTA-SEM-05`, `DTA-PHY-02`).
6//! Enforces zero-heap validation and relative scale invariants (e.g. preventing oversized fauna vs 4WD).
7//!
8//! The constants below are reference examples for when a species corpus has no assertion for a
9//! bound. Admission of a real subject uses [`super::corpus_envelope::cited_envelope_from_corpus`],
10//! which cites assertion ids and labels a silent bound as a model assumption.
11
12/// Normative QUDT species-trait and artefact dimensional admission envelope.
13///
14/// Governed by `https://ns.webizen.org/eco/traits#` / `AusTraits` / `AFD` / `AVONET` / `made:Artefact`
15/// under `DTA-ID-05`, `DTA-SEM-05`, `DTA-PHY-02`.
16#[repr(C)]
17#[derive(Clone, Copy, Debug, PartialEq)]
18pub struct MetricTraitEnvelope {
19    pub entity_class_id: u32,
20    /// Minimum horizontal longitudinal span in meters (major axis dx or dz).
21    pub min_length_m: f32,
22    /// Maximum horizontal longitudinal span in meters (major axis dx or dz).
23    pub max_length_m: f32,
24    /// Minimum horizontal lateral span in meters (minor axis dx or dz).
25    pub min_width_m: f32,
26    /// Maximum horizontal lateral span in meters (minor axis dx or dz).
27    pub max_width_m: f32,
28    /// Minimum vertical span in meters (dy axis).
29    pub min_height_m: f32,
30    /// Maximum vertical span in meters (dy axis).
31    pub max_height_m: f32,
32    /// Minimum physical mass in kilograms.
33    pub min_mass_kg: f32,
34    /// Maximum physical mass in kilograms.
35    pub max_mass_kg: f32,
36}
37
38/// Canonical 4WD field utility vehicle (Toyota Hilux / Land Cruiser 79 dual-cab archetype).
39pub const ENVELOPE_FIELD_UTILITY_4WD: MetricTraitEnvelope = MetricTraitEnvelope {
40    entity_class_id: 1,
41    min_length_m: 4.20,
42    max_length_m: 5.60,
43    min_width_m: 1.65,
44    max_width_m: 2.20,
45    min_height_m: 1.70,
46    max_height_m: 2.25,
47    min_mass_kg: 1800.0,
48    max_mass_kg: 3200.0,
49};
50
51/// Canonical Eastern Grey Kangaroo (Macropus giganteus).
52pub const ENVELOPE_MACROPUS_GIGANTEUS: MetricTraitEnvelope = MetricTraitEnvelope {
53    entity_class_id: 2,
54    min_length_m: 0.90,
55    max_length_m: 2.60,
56    min_width_m: 0.35,
57    max_width_m: 1.10,
58    min_height_m: 0.90,
59    max_height_m: 2.10,
60    min_mass_kg: 18.0,
61    max_mass_kg: 85.0,
62};
63
64/// Canonical Common Wombat (Vombatus ursinus).
65pub const ENVELOPE_VOMBATUS_URSINUS: MetricTraitEnvelope = MetricTraitEnvelope {
66    entity_class_id: 3,
67    min_length_m: 0.70,
68    max_length_m: 1.25,
69    min_width_m: 0.30,
70    max_width_m: 0.65,
71    min_height_m: 0.25,
72    max_height_m: 0.55,
73    min_mass_kg: 15.0,
74    max_mass_kg: 40.0,
75};
76
77/// Canonical Platypus (Ornithorhynchus anatinus).
78pub const ENVELOPE_ORNITHORHYNCHUS_ANATINUS: MetricTraitEnvelope = MetricTraitEnvelope {
79    entity_class_id: 4,
80    min_length_m: 0.35,
81    max_length_m: 0.65,
82    min_width_m: 0.12,
83    max_width_m: 0.35,
84    min_height_m: 0.10,
85    max_height_m: 0.28,
86    min_mass_kg: 0.7,
87    max_mass_kg: 2.5,
88};
89
90/// Canonical Wedge-Tailed Eagle (Aquila audax). Width represents wingspan.
91pub const ENVELOPE_AQUILA_AUDAX: MetricTraitEnvelope = MetricTraitEnvelope {
92    entity_class_id: 5,
93    min_length_m: 0.75,
94    max_length_m: 1.25,
95    min_width_m: 1.70,
96    max_width_m: 2.50,
97    min_height_m: 0.35,
98    max_height_m: 1.10,
99    min_mass_kg: 2.8,
100    max_mass_kg: 5.8,
101};
102
103/// Canonical Ghost Gum (Corymbia aparrerinja).
104pub const ENVELOPE_CORYMBIA_APARRERINJA: MetricTraitEnvelope = MetricTraitEnvelope {
105    entity_class_id: 6,
106    min_length_m: 4.0,
107    max_length_m: 28.0,
108    min_width_m: 4.0,
109    max_width_m: 28.0,
110    min_height_m: 6.0,
111    max_height_m: 35.0,
112    min_mass_kg: 500.0,
113    max_mass_kg: 25000.0,
114};
115
116/// Rejection reasons emitted when a mesh fails the dimensional admission gate.
117#[derive(Clone, Copy, Debug, PartialEq)]
118pub enum MetricTraitGateViolation {
119    EmptyVertexSlice,
120    NonFiniteCoordinate,
121    HeightOutOfBounds {
122        measured_m: f32,
123        min_m: f32,
124        max_m: f32,
125    },
126    LengthOutOfBounds {
127        measured_m: f32,
128        min_m: f32,
129        max_m: f32,
130    },
131    WidthOutOfBounds {
132        measured_m: f32,
133        min_m: f32,
134        max_m: f32,
135    },
136    RelativeScaleInversion {
137        fauna_max_extent_m: f32,
138        vehicle_length_m: f32,
139    },
140}
141
142impl std::fmt::Display for MetricTraitGateViolation {
143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        match self {
145            Self::EmptyVertexSlice => write!(f, "Empty vertex positions slice"),
146            Self::NonFiniteCoordinate => write!(f, "Non-finite coordinate encountered in mesh"),
147            Self::HeightOutOfBounds {
148                measured_m,
149                min_m,
150                max_m,
151            } => {
152                write!(
153                    f,
154                    "Height {measured_m:.3} m out of bounds [{min_m:.3}, {max_m:.3}] m"
155                )
156            }
157            Self::LengthOutOfBounds {
158                measured_m,
159                min_m,
160                max_m,
161            } => {
162                write!(
163                    f,
164                    "Length {measured_m:.3} m out of bounds [{min_m:.3}, {max_m:.3}] m"
165                )
166            }
167            Self::WidthOutOfBounds {
168                measured_m,
169                min_m,
170                max_m,
171            } => {
172                write!(
173                    f,
174                    "Width {measured_m:.3} m out of bounds [{min_m:.3}, {max_m:.3}] m"
175                )
176            }
177            Self::RelativeScaleInversion {
178                fauna_max_extent_m,
179                vehicle_length_m,
180            } => {
181                write!(
182                    f,
183                    "Relative scale inversion: fauna extent {fauna_max_extent_m:.3} m exceeds vehicle length {vehicle_length_m:.3} m"
184                )
185            }
186        }
187    }
188}
189
190impl std::error::Error for MetricTraitGateViolation {}
191
192/// Measures the axis-aligned bounding box (min, max, extents) across a slice of 3D positions with zero heap allocation.
193pub fn measure_aabb_extents_zero_heap(
194    positions: &[[f32; 3]],
195) -> Result<([f32; 3], [f32; 3], [f32; 3]), MetricTraitGateViolation> {
196    if positions.is_empty() {
197        return Err(MetricTraitGateViolation::EmptyVertexSlice);
198    }
199
200    let mut min_xyz = [f32::INFINITY; 3];
201    let mut max_xyz = [f32::NEG_INFINITY; 3];
202
203    for p in positions {
204        for axis in 0..3 {
205            let val = p[axis];
206            if !val.is_finite() {
207                return Err(MetricTraitGateViolation::NonFiniteCoordinate);
208            }
209            if val < min_xyz[axis] {
210                min_xyz[axis] = val;
211            }
212            if val > max_xyz[axis] {
213                max_xyz[axis] = val;
214            }
215        }
216    }
217
218    let extents = [
219        max_xyz[0] - min_xyz[0],
220        max_xyz[1] - min_xyz[1],
221        max_xyz[2] - min_xyz[2],
222    ];
223
224    Ok((min_xyz, max_xyz, extents))
225}
226
227/// Verifies that an asset's scaled bounding box extents conform to the normative QUDT trait envelope.
228///
229/// Returns the scaled extents `[dx, dy, dz]` in meters on admission, or a fail-closed violation.
230pub fn verify_metric_trait_bounds_zero_heap(
231    positions: &[[f32; 3]],
232    instance_scale: f32,
233    envelope: &MetricTraitEnvelope,
234) -> Result<[f32; 3], MetricTraitGateViolation> {
235    if !instance_scale.is_finite() || instance_scale <= 0.0 {
236        return Err(MetricTraitGateViolation::NonFiniteCoordinate);
237    }
238
239    let (_min, _max, extents) = measure_aabb_extents_zero_heap(positions)?;
240    let scaled_extents = [
241        extents[0] * instance_scale,
242        extents[1] * instance_scale,
243        extents[2] * instance_scale,
244    ];
245
246    // Vertical height is dy (index 1)
247    let scaled_height = scaled_extents[1];
248    if scaled_height < envelope.min_height_m || scaled_height > envelope.max_height_m {
249        return Err(MetricTraitGateViolation::HeightOutOfBounds {
250            measured_m: scaled_height,
251            min_m: envelope.min_height_m,
252            max_m: envelope.max_height_m,
253        });
254    }
255
256    // Horizontal spans: major dx.max(dz), minor dx.min(dz)
257    let horiz_major = scaled_extents[0].max(scaled_extents[2]);
258    let horiz_minor = scaled_extents[0].min(scaled_extents[2]);
259
260    // Check if envelope width is greater than length (e.g. raptor wingspan)
261    let (scaled_len, scaled_wid) = if envelope.max_width_m > envelope.max_length_m {
262        (horiz_minor, horiz_major)
263    } else {
264        (horiz_major, horiz_minor)
265    };
266
267    if scaled_len < envelope.min_length_m || scaled_len > envelope.max_length_m {
268        return Err(MetricTraitGateViolation::LengthOutOfBounds {
269            measured_m: scaled_len,
270            min_m: envelope.min_length_m,
271            max_m: envelope.max_length_m,
272        });
273    }
274
275    if scaled_wid < envelope.min_width_m || scaled_wid > envelope.max_width_m {
276        return Err(MetricTraitGateViolation::WidthOutOfBounds {
277            measured_m: scaled_wid,
278            min_m: envelope.min_width_m,
279            max_m: envelope.max_width_m,
280        });
281    }
282
283    Ok(scaled_extents)
284}
285
286/// Enforces the fail-closed relative scale invariant between terrestrial fauna and vehicles.
287///
288/// Prevents the "kangaroo twice the size of a 4WD" bug at the engine admission boundary.
289pub fn verify_fauna_vs_vehicle_scale_invariant_zero_heap(
290    fauna_extents_m: [f32; 3],
291    vehicle_extents_m: [f32; 3],
292) -> Result<(), MetricTraitGateViolation> {
293    for c in fauna_extents_m.iter().chain(vehicle_extents_m.iter()) {
294        if !c.is_finite() {
295            return Err(MetricTraitGateViolation::NonFiniteCoordinate);
296        }
297    }
298
299    let fauna_max_extent_m = fauna_extents_m[0]
300        .max(fauna_extents_m[1])
301        .max(fauna_extents_m[2]);
302    let vehicle_length_m = vehicle_extents_m[0].max(vehicle_extents_m[2]);
303
304    if fauna_max_extent_m > vehicle_length_m {
305        return Err(MetricTraitGateViolation::RelativeScaleInversion {
306            fauna_max_extent_m,
307            vehicle_length_m,
308        });
309    }
310
311    Ok(())
312}
313
314#[cfg(test)]
315mod tests {
316    use super::*;
317
318    #[test]
319    fn test_kangaroo_valid_and_out_of_bounds() {
320        // Authored at 1:1 metric scale: length (Z) = 1.4m, width (X) = 0.5m, height (Y) = 1.6m
321        let vertices = [
322            [-0.25, 0.0, -0.7],
323            [0.25, 0.0, -0.7],
324            [-0.25, 1.6, 0.7],
325            [0.25, 1.6, 0.7],
326        ];
327
328        let result = verify_metric_trait_bounds_zero_heap(
329            &vertices,
330            1.0,
331            &ENVELOPE_MACROPUS_GIGANTEUS,
332        );
333        assert!(result.is_ok());
334        let extents = result.unwrap();
335        assert!((extents[1] - 1.6).abs() < 1e-4);
336
337        // Scaled up by 4.0x -> oversized monster kangaroo (height 6.4m > 2.1m)
338        let oversized = verify_metric_trait_bounds_zero_heap(
339            &vertices,
340            4.0,
341            &ENVELOPE_MACROPUS_GIGANTEUS,
342        );
343        assert!(matches!(
344            oversized,
345            Err(MetricTraitGateViolation::HeightOutOfBounds { .. })
346        ));
347    }
348
349    #[test]
350    fn test_field_utility_4wd_bounds() {
351        // Vehicle length = 5.2m, width = 1.9m, height = 1.85m
352        let vertices = [
353            [-0.95, 0.0, -2.6],
354            [0.95, 0.0, -2.6],
355            [-0.95, 1.85, 2.6],
356            [0.95, 1.85, 2.6],
357        ];
358
359        let result = verify_metric_trait_bounds_zero_heap(
360            &vertices,
361            1.0,
362            &ENVELOPE_FIELD_UTILITY_4WD,
363        );
364        assert!(result.is_ok());
365
366        // Miniature vehicle (scale 0.1) -> length 0.52m < 4.20m
367        let miniature = verify_metric_trait_bounds_zero_heap(
368            &vertices,
369            0.1,
370            &ENVELOPE_FIELD_UTILITY_4WD,
371        );
372        assert!(matches!(
373            miniature,
374            Err(MetricTraitGateViolation::HeightOutOfBounds { .. })
375                | Err(MetricTraitGateViolation::LengthOutOfBounds { .. })
376        ));
377    }
378
379    #[test]
380    fn test_eagle_wingspan_major_span() {
381        // Eagle: length 0.9m (Z), wingspan 2.1m (X), height 0.6m (Y)
382        let vertices = [
383            [-1.05, 0.0, -0.45],
384            [1.05, 0.0, -0.45],
385            [-1.05, 0.6, 0.45],
386            [1.05, 0.6, 0.45],
387        ];
388
389        let result = verify_metric_trait_bounds_zero_heap(
390            &vertices,
391            1.0,
392            &ENVELOPE_AQUILA_AUDAX,
393        );
394        assert!(result.is_ok());
395    }
396
397    #[test]
398    fn test_relative_scale_inversion_fauna_vs_vehicle() {
399        let vehicle_extents = [1.9_f32, 1.85, 5.2]; // 4WD: length 5.2m
400
401        // Realistic kangaroo: 0.5m x 1.6m x 1.4m (max extent = 1.6m < 5.2m)
402        let normal_kangaroo = [0.5_f32, 1.6, 1.4];
403        assert!(verify_fauna_vs_vehicle_scale_invariant_zero_heap(
404            normal_kangaroo,
405            vehicle_extents
406        )
407        .is_ok());
408
409        // Broken scale: giant kangaroo with height 6.0m or length 6.5m (> 5.2m 4WD length)
410        let giant_kangaroo = [2.0_f32, 6.0, 5.5];
411        let err = verify_fauna_vs_vehicle_scale_invariant_zero_heap(
412            giant_kangaroo,
413            vehicle_extents,
414        );
415        assert_eq!(
416            err,
417            Err(MetricTraitGateViolation::RelativeScaleInversion {
418                fauna_max_extent_m: 6.0,
419                vehicle_length_m: 5.2,
420            })
421        );
422    }
423
424    #[test]
425    fn test_empty_and_non_finite_vertex_checks() {
426        let empty: &[[f32; 3]] = &[];
427        assert_eq!(
428            measure_aabb_extents_zero_heap(empty),
429            Err(MetricTraitGateViolation::EmptyVertexSlice)
430        );
431
432        let nan_vertices = [[0.0, f32::NAN, 1.0]];
433        assert_eq!(
434            measure_aabb_extents_zero_heap(&nan_vertices),
435            Err(MetricTraitGateViolation::NonFiniteCoordinate)
436        );
437    }
438}