ifc_lite_geometry/document/
retained_disk.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Rational swept-disk request encoding. The source recipe is never modified;
3//! this module grants no execution qualification.
4//!
5//! Supported family: a solid `IfcSweptDiskSolid` (no `InnerRadius`) whose
6//! directrix is one open rational B-spline (optionally parameter-trimmed), one
7//! line, or one partial circular arc. Lines and arcs are converted to their
8//! exact rational form (degree 1, or quadratic conics of at most a quarter
9//! turn each); nothing is fitted or sampled. Hollow disks, full circles,
10//! polylines with more than one segment and composite directrices are refused:
11//! their joints and seams need an additional qualified route.
12//!
13//! Wire format 2 (little-endian, evaluation frame in metres):
14//! - header: `u32` format = 2, loop count = 1, segment count = 1, reserved 0;
15//!   then `f64` radius and inner radius (always 0).
16//! - curve: `u32` kind = 4 (rational B-spline), reserved 0, degree, control
17//!   count, unique knot count, reserved 0; then `f64` active parameter start
18//!   and end.
19//! - per control point: `f64` x, y, z (relative to the first control point)
20//!   and weight. Points are Euclidean, not weight-multiplied.
21//! - per unique knot: `f64` knot, `u32` multiplicity, reserved `u32` 0.
22//!
23//! Rational directrices keep their original knots, weights and active range.
24//! A converted line or arc uses a derived parameter (`0..1` per line, `0..n`
25//! for `n` conic spans); the source keeps its authored circle, angles, trims
26//! and line magnitude unchanged.
27
28use super::retained_sweep::{array, RegionQualification, SweepPayload, MAX_LOCAL_M, MAX_SEGMENTS};
29use super::RetainedRefusal;
30use crate::analytic::{
31    AnalyticCurveSegment, AnalyticStatus, AnalyticSweptDisk, OwnedDirectrix, OwnedRationalCurve,
32};
33use crate::math::tol;
34use nalgebra::{Matrix4, Vector3};
35use std::f64::consts::{FRAC_PI_2, TAU};
36
37/// Wire kind of a rational B-spline curve (formats 1 use kinds 1 to 3).
38const RATIONAL_CURVE: u32 = 4;
39const MAX_DEGREE: u32 = 32;
40
41/// One authored `IfcSweptDiskSolid`, extracted inside
42/// [`crate::analytic::with_source_capture`] so its original records and owned
43/// directrix survive. Coefficients stay in raw IFC file length units.
44#[derive(Debug, Clone, PartialEq)]
45pub struct RetainedSweptDisk {
46    /// STEP id of the `IfcSweptDiskSolid`; must be the captured source root.
47    pub solid_id: u32,
48    pub source: AnalyticSweptDisk,
49    /// Raw IFC file length unit -> metres.
50    pub length_unit_scale: f64,
51}
52
53pub(super) fn lower(recipe: &RetainedSweptDisk) -> Result<SweepPayload, RetainedRefusal> {
54    let disk = &recipe.source;
55    let original = disk
56        .source
57        .as_ref()
58        .ok_or(RetainedRefusal::SourceNotCaptured)?;
59    if let AnalyticStatus::Unsupported(reason) = &original.capture_status {
60        return Err(RetainedRefusal::UnsupportedSource(format!(
61            "original disk capture: {reason}"
62        )));
63    }
64    if original.root_entity_id != recipe.solid_id
65        || !original.records.contains_key(&recipe.solid_id)
66    {
67        return invalid("invalid original solid metadata");
68    }
69    if disk.inner_radius.is_some() {
70        return Err(RetainedRefusal::UnsupportedSource(
71            "hollow swept disks are not supported by this request encoding".into(),
72        ));
73    }
74    let units = recipe.length_unit_scale;
75    let radius = disk.radius * units;
76    if !units.is_finite() || units <= 0.0 {
77        return invalid("invalid source length units");
78    }
79    if !radius.is_finite() || radius <= tol::RETAINED_MIN_LENGTH_M || radius > MAX_LOCAL_M {
80        return invalid("disk radius outside local numerical domain");
81    }
82    let path = match &disk.owned_directrix {
83        Some(OwnedDirectrix::Rational(path)) => path.clone(),
84        Some(OwnedDirectrix::Segments(segments)) => exact_path(segments, disk.directrix_id)?,
85        None => {
86            // A rational directrix the capture could not own keeps the
87            // extractor's reason; otherwise there is no exact route at all.
88            return Err(RetainedRefusal::UnsupportedSource(match &disk.status {
89                AnalyticStatus::Unsupported(reason) => reason.clone(),
90                AnalyticStatus::Complete => "directrix has no exact coefficient route".into(),
91            }));
92        }
93    };
94    validate(&path)?;
95    let anchor = path.control_points[0];
96    // Bounded by MAX_SEGMENTS in `validate`, so the counts fit in u32.
97    let (controls, knots) = (path.control_points.len(), path.knots.len());
98    let mut bytes = Vec::with_capacity(72 + controls * 32 + knots * 16);
99    for value in [2u32, 1, 1, 0] {
100        bytes.extend(value.to_le_bytes());
101    }
102    for value in [radius, 0.0] {
103        scalar(&mut bytes, value)?;
104    }
105    for value in [
106        RATIONAL_CURVE,
107        0,
108        path.degree,
109        controls as u32,
110        knots as u32,
111        0,
112    ] {
113        bytes.extend(value.to_le_bytes());
114    }
115    for value in path.parameter_range {
116        scalar(&mut bytes, value)?;
117    }
118    for (point, weight) in path.control_points.iter().zip(&path.weights) {
119        for axis in 0..3 {
120            scalar(&mut bytes, (point[axis] - anchor[axis]) * units)?;
121        }
122        scalar(&mut bytes, *weight)?;
123    }
124    for (knot, multiplicity) in path.knots.iter().zip(&path.multiplicities) {
125        scalar(&mut bytes, *knot)?;
126        bytes.extend(multiplicity.to_le_bytes());
127        bytes.extend(0u32.to_le_bytes());
128    }
129    // The disk has no Position: solid-local coordinates are directrix
130    // coordinates. Survey-scale anchors stay here in f64, outside the worker.
131    let source_from_evaluation =
132        Matrix4::new_translation(&Vector3::from(anchor)) * Matrix4::new_scaling(1.0 / units);
133    let evaluation_from_source =
134        Matrix4::new_scaling(units) * Matrix4::new_translation(&-Vector3::from(anchor));
135    if source_from_evaluation
136        .iter()
137        .chain(evaluation_from_source.iter())
138        .any(|v| !v.is_finite())
139    {
140        return invalid("disk evaluation frame overflows");
141    }
142    Ok(SweepPayload {
143        #[cfg(any(all(test, any(not(target_arch = "wasm32"), feature = "wasm_source_capture")), feature = "retained-runtime"))]
144        evaluation_bounds: super::EvaluationBounds::points(path.control_points.iter().map(|p| std::array::from_fn(|i| (p[i] - anchor[i]) * units))).and_then(|b| b.expanded(radius)),
145        format: 2,
146        bytes,
147        segments: 1,
148        loops: 1,
149        qualification: RegionQualification::RationalDisk,
150        source_from_evaluation: array(source_from_evaluation),
151        evaluation_from_source: array(evaluation_from_source),
152    })
153}
154
155/// Recipe fields are public, so the owned curve is re-checked here.
156fn validate(path: &OwnedRationalCurve) -> Result<(), RetainedRefusal> {
157    let count = path.control_points.len();
158    let degree = path.degree as usize;
159    if !(1..=MAX_DEGREE).contains(&path.degree)
160        || count <= degree
161        || count > MAX_SEGMENTS
162        || path.weights.len() != count
163        || path.knots.len() < 2
164        || path.knots.len() > MAX_SEGMENTS
165        || path.multiplicities.len() != path.knots.len()
166        || path.control_points.iter().flatten().any(|v| !v.is_finite())
167        || path.weights.iter().any(|w| !w.is_finite() || *w <= 0.0)
168        || path.knots.iter().any(|k| !k.is_finite())
169        || path.knots.windows(2).any(|pair| pair[0] >= pair[1])
170    {
171        return invalid("invalid exact rational coefficients");
172    }
173    let mut total = 0usize;
174    for (index, &multiplicity) in path.multiplicities.iter().enumerate() {
175        let clamped_end = index == 0 || index + 1 == path.knots.len();
176        let multiplicity = multiplicity as usize;
177        if (clamped_end && multiplicity != degree + 1)
178            || (!clamped_end && (multiplicity == 0 || multiplicity > degree))
179        {
180            return invalid("unsupported rational knot multiplicities");
181        }
182        total += multiplicity;
183    }
184    let [start, end] = path.parameter_range;
185    let (first, last) = (path.knots[0], path.knots[path.knots.len() - 1]);
186    if total != count + degree + 1
187        || start.is_nan()
188        || end.is_nan()
189        || start >= end
190        || start < first
191        || end > last
192    {
193        return invalid("invalid rational active domain");
194    }
195    Ok(())
196}
197
198/// Exact rational form of a single line or partial arc. This is DERIVED
199/// evaluation data; the recipe keeps the authored segment unchanged.
200fn exact_path(
201    segments: &[AnalyticCurveSegment],
202    source_entity_id: u32,
203) -> Result<OwnedRationalCurve, RetainedRefusal> {
204    let (degree, control_points, weights, knots, multiplicities) = match segments {
205        [AnalyticCurveSegment::Line { start, end }] => (
206            1,
207            vec![*start, *end],
208            vec![1.0, 1.0],
209            vec![0.0, 1.0],
210            vec![2, 2],
211        ),
212        [AnalyticCurveSegment::Arc {
213            center,
214            normal,
215            x_axis,
216            radius,
217            start_angle,
218            sweep_angle,
219        }] => {
220            let (n, x) = (Vector3::from(*normal), Vector3::from(*x_axis));
221            if (n.norm() - 1.0).abs() >= tol::RETAINED_CIRCLE_BASIS_EPS
222                || (x.norm() - 1.0).abs() >= tol::RETAINED_CIRCLE_BASIS_EPS
223                || n.dot(&x).abs() >= tol::RETAINED_CIRCLE_BASIS_EPS
224                || !radius.is_finite()
225                || *radius <= 0.0
226                || !start_angle.is_finite()
227            {
228                return invalid("invalid circular directrix basis");
229            }
230            let sweep = sweep_angle.abs();
231            if sweep.is_nan()
232                || sweep <= tol::RETAINED_ARC_INTERVAL_EPS_RAD
233                || sweep >= TAU - tol::RETAINED_ARC_INTERVAL_EPS_RAD
234            {
235                return Err(RetainedRefusal::UnsupportedSource(
236                    "closed circular directrix requires an additional qualified route".into(),
237                ));
238            }
239            arc(
240                Vector3::from(*center),
241                n,
242                x,
243                *radius,
244                *start_angle,
245                *sweep_angle,
246            )
247        }
248        _ => {
249            return Err(RetainedRefusal::UnsupportedSource(
250                "multi-segment disk directrix requires an additional qualified route".into(),
251            ))
252        }
253    };
254    let end = knots[knots.len() - 1];
255    Ok(OwnedRationalCurve {
256        source_entity_id,
257        degree,
258        control_points,
259        weights,
260        knots,
261        multiplicities,
262        expanded_knots: Vec::new(),
263        parameter_range: [0.0, end],
264    })
265}
266
267type RationalParts = (u32, Vec<[f64; 3]>, Vec<f64>, Vec<f64>, Vec<u32>);
268
269/// Quadratic rational conic spans of at most a quarter turn: span ends on the
270/// circle with weight 1, the middle control at `radius / cos(delta / 2)` with
271/// weight `cos(delta / 2)`.
272fn arc(
273    center: Vector3<f64>,
274    normal: Vector3<f64>,
275    x_axis: Vector3<f64>,
276    radius: f64,
277    start: f64,
278    sweep: f64,
279) -> RationalParts {
280    let y_axis = normal.cross(&x_axis);
281    let point = |angle: f64, distance: f64| -> [f64; 3] {
282        (center + (x_axis * angle.cos() + y_axis * angle.sin()) * distance).into()
283    };
284    // `sweep` is finite and below one turn, so at most four spans.
285    let spans = (sweep.abs() / FRAC_PI_2).ceil().max(1.0) as usize;
286    let delta = sweep / spans as f64;
287    let weight = (delta / 2.0).cos();
288    let mut controls = vec![point(start, radius)];
289    let mut weights = vec![1.0];
290    for span in 0..spans {
291        let base = start + delta * span as f64;
292        controls.push(point(base + delta / 2.0, radius / weight));
293        weights.push(weight);
294        controls.push(point(base + delta, radius));
295        weights.push(1.0);
296    }
297    let knots = (0..=spans).map(|i| i as f64).collect();
298    let multiplicities = (0..=spans)
299        .map(|i| if i == 0 || i == spans { 3 } else { 2 })
300        .collect();
301    (2, controls, weights, knots, multiplicities)
302}
303
304fn scalar(bytes: &mut Vec<u8>, value: f64) -> Result<(), RetainedRefusal> {
305    if !value.is_finite() || value.abs() > MAX_LOCAL_M {
306        return invalid("disk coefficient outside local numerical domain");
307    }
308    bytes.extend(value.to_le_bytes());
309    Ok(())
310}
311
312fn invalid<T>(message: &'static str) -> Result<T, RetainedRefusal> {
313    Err(RetainedRefusal::InvalidSource(message))
314}
315
316#[cfg(test)]
317#[path = "retained_disk_tests.rs"]
318mod tests;