ifc_lite_geometry_runtime/
worker_qualification.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Explicit same-incarnation numerical witnesses, never a capability-bit bypass.
3use super::{MeshLimits, SmlibWorker, WorkerError};
4use std::f64::consts::{PI, TAU};
5
6/// Observed runtime witness only. This does not certify source interpretation,
7/// appearance, face provenance, retained USD, or another native/browser target.
8#[derive(Debug)]
9pub struct RegionQualificationReport {
10    pub worker_incarnation: u64,
11    pub cases: usize,
12    pub volumes: Vec<f64>,
13}
14#[derive(Clone)]
15struct Curve {
16    kind: u32,
17    values: [f64; 12],
18}
19fn line(a: [f64; 2], b: [f64; 2]) -> Curve {
20    Curve {
21        kind: 1,
22        values: [a[0], a[1], 0., b[0], b[1], 0., 0., 0., 0., 0., 0., 0.],
23    }
24}
25fn arc(radius: f64, sweep: f64) -> Curve {
26    Curve {
27        kind: if sweep.abs() == TAU { 2 } else { 3 },
28        values: [0., 0., 0., 0., 0., 1., 1., 0., 0., radius, 0., sweep],
29    }
30}
31fn square(half: f64, inner: bool) -> Vec<Curve> {
32    let mut points = [[-half, -half], [half, -half], [half, half], [-half, half]];
33    if inner {
34        points.reverse();
35    }
36    (0..4)
37        .map(|i| line(points[i], points[(i + 1) % 4]))
38        .collect()
39}
40fn recipe(loops: &[Vec<Curve>], oblique: bool) -> (Vec<u8>, u32) {
41    let count = loops.iter().map(Vec::len).sum::<usize>() as u32;
42    let mut bytes = Vec::new();
43    for value in [1, loops.len() as u32, count, 0] {
44        bytes.extend(value.to_le_bytes());
45    }
46    for value in [
47        if oblique { 0.6f64 } else { 0. },
48        0.,
49        if oblique { 0.8 } else { 1. },
50        3.,
51    ] {
52        bytes.extend(value.to_le_bytes());
53    }
54    for (i, boundary) in loops.iter().enumerate() {
55        bytes.extend(u32::from(i != 0).to_le_bytes());
56        bytes.extend((boundary.len() as u32).to_le_bytes());
57        for curve in boundary {
58            bytes.extend(curve.kind.to_le_bytes());
59            bytes.extend(0u32.to_le_bytes());
60            for value in curve.values {
61                bytes.extend(value.to_le_bytes());
62            }
63        }
64    }
65    (bytes, count)
66}
67/// Axis-aligned bounds of flat XYZ positions.
68pub(super) fn bounds(positions: &[f64]) -> ([f64; 3], [f64; 3]) {
69    let mut min = [f64::INFINITY; 3];
70    let mut max = [f64::NEG_INFINITY; 3];
71    for point in positions.chunks_exact(3) {
72        for ((low, high), value) in min.iter_mut().zip(max.iter_mut()).zip(point) {
73            *low = low.min(*value);
74            *high = high.max(*value);
75        }
76    }
77    (min, max)
78}
79
80impl SmlibWorker {
81    /// Run real SDK uploads, positive volumes, manifold, independent cap bounds
82    /// and boundary mesh invariants on THIS actual process. No fixture
83    /// or protocol peer can manufacture the private qualified state. Failure
84    /// leaves the gate closed. A new process must qualify independently.
85    pub fn qualify_ordered_regions(&mut self) -> Result<RegionQualificationReport, WorkerError> {
86        self.regions_qualified = false;
87        let incarnation = self.incarnation();
88        if incarnation == 0 {
89            return Err(WorkerError::WrongWorker);
90        }
91        let cases = vec![
92            (vec![vec![arc(2., TAU)]], 4. * PI, false, 2., false),
93            (vec![vec![arc(2., -TAU)]], 4. * PI, false, 2., false),
94            (
95                vec![vec![arc(2., TAU)], vec![arc(1., -TAU)]],
96                3. * PI,
97                false,
98                2.,
99                false,
100            ),
101            (
102                vec![square(3., false), square(1., true)],
103                32.,
104                false,
105                3.,
106                false,
107            ),
108            (
109                vec![vec![arc(2., PI), line([-2., 0.], [2., 0.])]],
110                2. * PI,
111                false,
112                2.,
113                true,
114            ),
115            (
116                vec![vec![arc(2., TAU)], vec![arc(1., -TAU)]],
117                3. * PI,
118                true,
119                2.,
120                false,
121            ),
122        ];
123        let mut volumes = Vec::new();
124        for (loops, area, oblique, half, half_disk) in &cases {
125            let (bytes, segments) = recipe(loops, *oblique);
126            let solid = self.create_sweep(&bytes, 1, loops.len() as u32, segments)?;
127            let result = (|| {
128                let volume = self.volume(solid, 1e-8)?;
129                let height = if *oblique { 2.4 } else { 3. };
130                if !self.is_manifold(solid)?
131                    || (volume - area * height).abs() > area * height * 1e-5
132                {
133                    return Err(WorkerError::Unqualified(
134                        "ordered-region volume/manifold witness failed",
135                    ));
136                }
137                let mesh = self.tessellate(
138                    solid,
139                    0.0001,
140                    5.,
141                    MeshLimits {
142                        max_bytes: 16 * 1024 * 1024,
143                    },
144                )?;
145                let (min, max) = bounds(&mesh.positions);
146                let expected_min = [-half, if *half_disk { 0. } else { -half }, 0.];
147                let expected_max = [half + if *oblique { 1.8 } else { 0. }, *half, height];
148                if (0..3).any(|i| {
149                    (min[i] - expected_min[i]).abs() > 0.002
150                        || (max[i] - expected_max[i]).abs() > 0.002
151                }) {
152                    return Err(WorkerError::Unqualified(
153                        "ordered-region cap bounds witness failed",
154                    ));
155                }
156                // Circular annular caps cannot include a vertex inside the hole.
157                if loops.len() == 2 && loops[0].len() == 1 {
158                    for p in mesh.positions.chunks_exact(3) {
159                        let x = p[0] - if *oblique { p[2] * 0.75 } else { 0. };
160                        let r = x.hypot(p[1]);
161                        if !(0.999..=2.001).contains(&r) {
162                            return Err(WorkerError::Unqualified(
163                                "annular boundary witness failed",
164                            ));
165                        }
166                    }
167                }
168                Ok(volume)
169            })();
170            let cleanup = self.release(solid);
171            let volume = match (result, cleanup) {
172                (Ok(v), Ok(())) => v,
173                (Err(e), _) | (_, Err(e)) => return Err(e),
174            };
175            volumes.push(volume);
176        }
177        if self.incarnation() != incarnation {
178            return Err(WorkerError::WrongWorker);
179        }
180        self.regions_qualified = true;
181        Ok(RegionQualificationReport {
182            worker_incarnation: incarnation,
183            cases: cases.len(),
184            volumes,
185        })
186    }
187}