ifc_lite_geometry/document/
retained_disk.rs1use 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
37const RATIONAL_CURVE: u32 = 4;
39const MAX_DEGREE: u32 = 32;
40
41#[derive(Debug, Clone, PartialEq)]
45pub struct RetainedSweptDisk {
46 pub solid_id: u32,
48 pub source: AnalyticSweptDisk,
49 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 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 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 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
155fn 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
198fn 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
269fn 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 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;