ifc_lite_geometry/document/
retained_sweep.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Ordered-region extrusion request encoding (wire format 1; the swept-disk
3//! format 2 lives in `retained_disk.rs`). The source recipe is never
4//! modified; this module grants no execution qualification.
5//!
6//! Supported family: a linear extrusion of one planar region (one outer and up
7//! to `MAX_LOOPS - 1` inner boundaries) whose boundaries are XY lines, partial
8//! circular arcs or isolated full circles, under rigid profile and solid
9//! placements. Everything else is refused.
10//!
11//! Wire format 1 (little-endian, evaluation frame in metres):
12//! - header: `u32` format = 1, loop count, segment count, reserved 0;
13//!   then `f64` unit extrusion direction x, y, z and depth.
14//! - per loop: `u32` role (0 outer, 1 inner) and segment count.
15//! - per segment: `u32` kind (1 line, 2 full circle, 3 arc), reserved 0, then
16//!   twelve `f64`. Line: start xyz, end xyz, six zeros. Circle/arc: centre
17//!   xyz, normal xyz, x-axis xyz, radius, start angle, signed sweep.
18//!
19//! Loops are emitted outer counter-clockwise and inner clockwise; the source
20//! keeps its authored order, winding, trims and composite metadata.
21
22use super::{RetainedExtrusion, RetainedRefusal};
23use crate::analytic::{AnalyticCurveSegment, AnalyticStatus, ProfileLoopKind};
24use crate::math::tol;
25use nalgebra::{Matrix4, Vector4};
26
27#[path = "retained_region.rs"]
28pub(super) mod region;
29
30pub(super) const MAX_LOOPS: usize = 128;
31pub(super) const MAX_SEGMENTS: usize = 8192;
32/// Largest admitted coordinate or depth in the local evaluation frame (metres).
33pub(super) const MAX_LOCAL_M: f64 = 1e9;
34
35/// Evidence the executing runtime must hold before evaluating a request. The
36/// variant is derived from geometry, never from a type name alone, and holding
37/// a request grants no execution authority.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39#[non_exhaustive]
40pub enum RegionQualification {
41    /// One parameterized rectangle with axis-aligned edges.
42    Rectangle,
43    /// Any other supported ordered region of lines, arcs and circles.
44    OrderedRegion,
45    /// One solid disk swept along one open rational B-spline (wire format 2).
46    RationalDisk,
47    /// Authored face-set triangles (wire format 3): source-exact, no kernel call.
48    SourceFaceSet,
49}
50
51/// One encoded retained request.
52#[derive(Debug)]
53#[non_exhaustive]
54pub struct SweepPayload {
55    #[cfg(any(all(test, any(not(target_arch = "wasm32"), feature = "wasm_source_capture")), feature = "retained-runtime"))]
56    pub evaluation_bounds: Option<super::EvaluationBounds>,
57    pub format: u32,
58    pub bytes: Vec<u8>,
59    pub segments: u32,
60    pub loops: u32,
61    pub qualification: RegionQualification,
62    /// Column-major evaluation metres -> raw solid-local file units. Profile
63    /// anchor, profile and solid placements stay here in f64, outside the
64    /// worker, including survey-scale origins.
65    pub source_from_evaluation: [f64; 16],
66    pub evaluation_from_source: [f64; 16],
67}
68
69pub(super) fn lower(recipe: &RetainedExtrusion) -> Result<SweepPayload, RetainedRefusal> {
70    validate_source(recipe)?;
71    let source = &recipe.source;
72    let profile = source
73        .profile
74        .as_ref()
75        .ok_or(RetainedRefusal::InvalidSource("missing profile"))?;
76    let p = rigid(profile.profile_position)?;
77    let solid = rigid(source.position_matrix)?;
78    let units = recipe.length_unit_scale;
79    let anchor = match profile.loops[0].segments.first() {
80        Some(AnalyticCurveSegment::Line { start, .. }) => *start,
81        Some(AnalyticCurveSegment::Arc { center, .. }) => *center,
82        None => return Err(RetainedRefusal::InvalidSource("empty boundary")),
83    };
84    if anchor[2] != 0.0 {
85        return Err(RetainedRefusal::InvalidSource(
86            "profile must be in its XY plane",
87        ));
88    }
89    let translation = Matrix4::new_translation(&nalgebra::Vector3::from(anchor));
90    let source_from_evaluation = solid * p * translation * Matrix4::new_scaling(1.0 / units);
91    let inverse = source_from_evaluation
92        .try_inverse()
93        .ok_or(RetainedRefusal::InvalidSource("singular evaluation frame"))?;
94    if source_from_evaluation
95        .iter()
96        .chain(inverse.iter())
97        .any(|v| !v.is_finite())
98    {
99        return Err(RetainedRefusal::InvalidSource("evaluation frame overflows"));
100    }
101    let axis = source
102        .axis_unit_vector
103        .ok_or(RetainedRefusal::InvalidSource("missing direction"))?;
104    // Direction lives in the solid frame, independently of profile Position.
105    let profile_inverse = p
106        .try_inverse()
107        .ok_or(RetainedRefusal::InvalidSource("singular profile frame"))?;
108    let vector = profile_inverse * Vector4::new(axis[0], axis[1], axis[2], 0.0);
109    let norm = vector[0].hypot(vector[1]).hypot(vector[2]);
110    let depth = source
111        .depth
112        .ok_or(RetainedRefusal::InvalidSource("missing depth"))?
113        * units;
114    if !norm.is_finite() || norm <= 0.0 || !depth.is_finite() || depth <= 0.0 || vector[2] == 0.0 {
115        return Err(RetainedRefusal::InvalidSource("invalid sweep extent"));
116    }
117    if depth > MAX_LOCAL_M || depth * (vector[2] / norm).abs() <= tol::RETAINED_MIN_LENGTH_M {
118        return Err(RetainedRefusal::InvalidSource(
119            "sweep outside local numerical domain",
120        ));
121    }
122    let (curves, qualification) = region::lower(profile, anchor, units)?;
123    let segments: usize = curves.iter().map(Vec::len).sum();
124    let mut bytes = Vec::with_capacity(48 + curves.len() * 8 + segments * 104);
125    // Bounded by MAX_LOOPS and MAX_SEGMENTS in validate_source.
126    let (loops, segments) = (curves.len() as u32, segments as u32);
127    for value in [1, loops, segments, 0] {
128        bytes.extend(value.to_le_bytes());
129    }
130    for value in [vector[0] / norm, vector[1] / norm, vector[2] / norm, depth] {
131        f64_bytes(&mut bytes, value)?;
132    }
133    for (index, boundary) in curves.iter().enumerate() {
134        bytes.extend(u32::from(index != 0).to_le_bytes());
135        bytes.extend((boundary.len() as u32).to_le_bytes());
136        for curve in boundary {
137            bytes.extend(curve.kind.to_le_bytes());
138            bytes.extend(0u32.to_le_bytes());
139            for value in curve.values {
140                f64_bytes(&mut bytes, value)?;
141            }
142        }
143    }
144    Ok(SweepPayload {
145        #[cfg(any(all(test, any(not(target_arch = "wasm32"), feature = "wasm_source_capture")), feature = "retained-runtime"))]
146        evaluation_bounds: super::EvaluationBounds::region(curves.iter().flatten().map(|c| (c.kind, c.values)), [vector[0] / norm, vector[1] / norm, vector[2] / norm], depth),
147        format: 1,
148        bytes,
149        segments,
150        loops,
151        qualification,
152        source_from_evaluation: array(source_from_evaluation),
153        evaluation_from_source: array(inverse),
154    })
155}
156
157/// Strict source admission: complete extraction, captured original records,
158/// outer-then-inner loops and bounded size. Numerical checks follow in lowering.
159fn validate_source(recipe: &RetainedExtrusion) -> Result<(), RetainedRefusal> {
160    if !recipe.length_unit_scale.is_finite() || recipe.length_unit_scale <= 0.0 {
161        return Err(RetainedRefusal::InvalidSource(
162            "invalid source length units",
163        ));
164    }
165    let source = &recipe.source;
166    if let AnalyticStatus::Unsupported(reason) = &source.status {
167        return Err(RetainedRefusal::UnsupportedSource(reason.clone()));
168    }
169    let original = source
170        .source
171        .as_ref()
172        .ok_or(RetainedRefusal::SourceNotCaptured)?;
173    if let AnalyticStatus::Unsupported(reason) = &original.capture_status {
174        return Err(RetainedRefusal::UnsupportedSource(format!(
175            "original solid capture: {reason}"
176        )));
177    }
178    if original.root_entity_id != source.solid_id
179        || !original.records.contains_key(&source.solid_id)
180    {
181        return Err(RetainedRefusal::InvalidSource(
182            "invalid original solid metadata",
183        ));
184    }
185    let profile = source
186        .profile
187        .as_ref()
188        .ok_or(RetainedRefusal::InvalidSource("missing profile"))?;
189    if let AnalyticStatus::Unsupported(reason) = &profile.status {
190        return Err(RetainedRefusal::UnsupportedSource(reason.clone()));
191    }
192    if profile.loops.is_empty() || profile.loops.len() > MAX_LOOPS {
193        return Err(RetainedRefusal::InvalidSource(
194            "invalid bounded region loop count",
195        ));
196    }
197    let mut count = 0;
198    for (index, boundary) in profile.loops.iter().enumerate() {
199        let expected = if index == 0 {
200            ProfileLoopKind::Outer
201        } else {
202            ProfileLoopKind::Inner
203        };
204        if boundary.kind != expected {
205            return Err(RetainedRefusal::InvalidSource(
206                "expected outer then inner boundaries",
207            ));
208        }
209        if boundary.segments.is_empty() || boundary.segments.len() > MAX_SEGMENTS - count {
210            return Err(RetainedRefusal::InvalidSource(
211                "curve count exceeds bounded recipe",
212            ));
213        }
214        count += boundary.segments.len();
215        let original = boundary
216            .source
217            .as_ref()
218            .ok_or(RetainedRefusal::SourceNotCaptured)?;
219        if let AnalyticStatus::Unsupported(reason) = &original.capture_status {
220            return Err(RetainedRefusal::UnsupportedSource(format!(
221                "original boundary capture: {reason}"
222            )));
223        }
224        if !original.plane_angle_to_radians.is_finite()
225            || original.plane_angle_to_radians <= 0.0
226            || !original.records.contains_key(&original.root_entity_id)
227        {
228            return Err(RetainedRefusal::InvalidSource(
229                "invalid original boundary metadata",
230            ));
231        }
232    }
233    Ok(())
234}
235
236/// Absent placements are identity; present ones must be proper rigid motions.
237fn rigid(values: Option<[f64; 16]>) -> Result<Matrix4<f64>, RetainedRefusal> {
238    let matrix = values.map_or_else(Matrix4::identity, |values| {
239        Matrix4::from_column_slice(&values)
240    });
241    let orthonormal = (0..3).all(|i| {
242        (0..3).all(|j| {
243            let dot = (0..3).map(|k| matrix[(k, i)] * matrix[(k, j)]).sum::<f64>();
244            (dot - if i == j { 1.0 } else { 0.0 }).abs() < tol::RETAINED_RIGID_DOT_EPS
245        })
246    });
247    if matrix.iter().any(|v| !v.is_finite())
248        || !orthonormal
249        || matrix.fixed_view::<1, 4>(3, 0) != nalgebra::RowVector4::new(0.0, 0.0, 0.0, 1.0)
250        || matrix.fixed_view::<3, 3>(0, 0).determinant() < 0.0
251    {
252        return Err(RetainedRefusal::InvalidSource(
253            "source placement must be rigid",
254        ));
255    }
256    Ok(matrix)
257}
258
259pub(super) fn array(matrix: Matrix4<f64>) -> [f64; 16] {
260    std::array::from_fn(|i| matrix.as_slice()[i])
261}
262
263pub(super) fn f64_bytes(bytes: &mut Vec<u8>, value: f64) -> Result<(), RetainedRefusal> {
264    if !value.is_finite() {
265        return Err(RetainedRefusal::InvalidSource(
266            "nonfinite curve coefficient",
267        ));
268    }
269    bytes.extend(value.to_le_bytes());
270    Ok(())
271}
272
273#[cfg(test)]
274#[path = "retained_sweep_tests.rs"]
275mod tests;
276
277#[cfg(test)]
278#[path = "retained_region_tests.rs"]
279mod region_tests;