1use crate::topology::BrepSolid;
2use crate::{NurbsCurve, NurbsSurface, Vec3, Vec4};
3
4#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
5pub struct AffineTransform {
6 pub elements: [f64; 16],
7}
8
9impl AffineTransform {
10 pub fn is_rigid(&self, tolerance: f64) -> bool {
12 let m = &self.elements;
13 if !tolerance.is_finite() || tolerance < 0.0 || m.iter().any(|x| !x.is_finite()) {
14 return false;
15 }
16 if m[12].abs() > tolerance || m[13].abs() > tolerance || m[14].abs() > tolerance
17 || (m[15] - 1.0).abs() > tolerance {
18 return false;
19 }
20 let rows = [[m[0], m[1], m[2]], [m[4], m[5], m[6]], [m[8], m[9], m[10]]];
21 for i in 0..3 {
22 for j in i..3 {
23 let dot: f64 = (0..3).map(|k| rows[i][k] * rows[j][k]).sum();
24 let expected = if i == j { 1.0 } else { 0.0 };
25 if (dot - expected).abs() > tolerance { return false; }
26 }
27 }
28 (self.determinant3() - 1.0).abs() <= tolerance
29 }
30
31 pub fn compose(&self, b: &AffineTransform) -> Result<AffineTransform, String> {
33 AffineTransform::new(multiply_elements_seeded(&self.elements, &b.elements, -0.0))
35 }
36
37 pub fn new(elements: [f64; 16]) -> Result<Self, String> {
38 if elements.iter().any(|value| !value.is_finite()) {
39 return Err("AffineTransform: matrix must be finite".into());
40 }
41 if elements[12].abs() > 1e-12
42 || elements[13].abs() > 1e-12
43 || elements[14].abs() > 1e-12
44 || (elements[15] - 1.0).abs() > 1e-12
45 {
46 return Err("AffineTransform: projective matrices are unsupported".into());
47 }
48 if (Self { elements }).determinant3().abs() <= 1e-14 {
49 return Err("AffineTransform: singular matrix".into());
50 }
51 Ok(Self { elements })
52 }
53
54 pub fn rigid_inverse(&self) -> Result<Self, String> {
56 let m = &self.elements;
57 let r = [[m[0], m[1], m[2]], [m[4], m[5], m[6]], [m[8], m[9], m[10]]];
58 let t = [m[3], m[7], m[11]];
59 let mut out = [0.0f64; 16];
60 for row in 0..3 {
61 for col in 0..3 {
62 out[row * 4 + col] = r[col][row]; }
64 out[row * 4 + 3] = -(0..3).map(|k| r[k][row] * t[k]).sum::<f64>();
65 }
66 out[15] = 1.0;
67 AffineTransform::new(out)
68 }
69
70 pub fn determinant3(self) -> f64 {
71 let m = self.elements;
72 m[0] * (m[5] * m[10] - m[6] * m[9]) - m[1] * (m[4] * m[10] - m[6] * m[8])
73 + m[2] * (m[4] * m[9] - m[5] * m[8])
74 }
75
76 pub fn point(self, point: Vec3) -> Vec3 {
77 let m = self.elements;
78 Vec3::new(
79 m[0] * point.x + m[1] * point.y + m[2] * point.z + m[3],
80 m[4] * point.x + m[5] * point.y + m[6] * point.z + m[7],
81 m[8] * point.x + m[9] * point.y + m[10] * point.z + m[11],
82 )
83 }
84
85 fn homogeneous(self, point: Vec4) -> Result<Vec4, String> {
86 Ok(Vec4::from_point(self.point(point.point()?), point.w))
87 }
88}
89
90pub(crate) fn transform_curve(
91 curve: &NurbsCurve,
92 transform: AffineTransform,
93) -> Result<NurbsCurve, String> {
94 NurbsCurve::new(
95 curve.degree,
96 curve.knots.clone(),
97 curve
98 .control_points
99 .iter()
100 .map(|point| transform.homogeneous(*point))
101 .collect::<Result<_, _>>()?,
102 )
103}
104
105pub(crate) fn transform_surface(
106 surface: &NurbsSurface,
107 transform: AffineTransform,
108) -> Result<NurbsSurface, String> {
109 NurbsSurface::new(
110 surface.degree_u,
111 surface.degree_v,
112 surface.knots_u.clone(),
113 surface.knots_v.clone(),
114 surface
115 .control_points
116 .iter()
117 .map(|row| {
118 row.iter()
119 .map(|point| transform.homogeneous(*point))
120 .collect::<Result<Vec<_>, _>>()
121 })
122 .collect::<Result<_, _>>()?,
123 )
124}
125
126pub fn transform_brep(
129 solid: &BrepSolid,
130 transform: AffineTransform,
131 reverse_orientation: bool,
132) -> Result<BrepSolid, String> {
133 let determinant = transform.determinant3();
134 if determinant < 0.0 && !reverse_orientation {
135 return Err("transformSolid: reflection requires orientation reversal".into());
136 }
137 if determinant > 0.0 && reverse_orientation {
138 return Err("transformSolid: orientation reversal requires a reflection".into());
139 }
140 let mut result = solid.clone();
141 for vertex in &mut result.vertices {
142 vertex.point = transform.point(vertex.point);
143 }
144 for edge in &mut result.edges {
145 edge.curve = transform_curve(&edge.curve, transform)?;
146 }
147 for shell in &mut result.shells {
148 for face in &mut shell.faces {
149 face.surface = transform_surface(&face.surface, transform)?;
150 if reverse_orientation {
151 face.same_sense = !face.same_sense;
152 for loop_record in &mut face.loops {
153 loop_record.coedges.reverse();
154 for coedge in &mut loop_record.coedges {
155 coedge.forward = !coedge.forward;
156 coedge.pcurve = coedge.pcurve.reversed()?;
157 }
158 }
159 }
160 }
161 }
162 let precise = arithmetic_spacing(solid, &result, transform) <= PRECISE_SPACING;
167 if !precise {
168 placement_resolves_the_part(solid, &result, transform)?;
169 }
170 let mode = carry_verdict_mode();
171 let carried = precise
172 && mode != crate::env_read::Mode::Off
173 && carries_clean_verdict(solid, transform, reverse_orientation);
174 if carried && mode == crate::env_read::Mode::On {
175 CARRIED_VERDICTS.with(|count| count.set(count.get() + 1));
176 if crate::profile::profile_enabled() {
177 profile_line!("transform.verdict carried=1");
178 }
179 return Ok(result);
180 }
181 let issues = result.validate();
182 if mode == crate::env_read::Mode::Check && crate::profile::profile_enabled() {
183 profile_line!(
185 "transform.verdict check carried={} issues={} disagree={}",
186 u8::from(carried),
187 issues.len(),
188 u8::from(carried && !issues.is_empty())
189 );
190 }
191 if issues.is_empty() {
192 Ok(result)
193 } else {
194 Err(format!("transformed BREP is invalid: {issues:?}"))
195 }
196}
197
198const PRECISE_SPACING: f64 = 0.1 * crate::tolerance::DEFAULT_MODEL;
203
204fn stated_points(solid: &BrepSolid) -> impl Iterator<Item = Vec3> + '_ {
209 let cartesian =
210 |point: &Vec4| point.point().unwrap_or(Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY));
211 solid
212 .vertices
213 .iter()
214 .map(|vertex| vertex.point)
215 .chain(solid.edges.iter().flat_map(move |edge| edge.curve.control_points.iter().map(cartesian)))
216 .chain(
217 solid
218 .shells
219 .iter()
220 .flat_map(|shell| &shell.faces)
221 .flat_map(move |face| face.surface.control_points.iter().flatten().map(cartesian)),
222 )
223}
224
225fn reach(points: impl Iterator<Item = Vec3>) -> f64 {
228 points
229 .flat_map(|point| [point.x, point.y, point.z])
230 .fold(0.0f64, |reach, value| if value.is_finite() { reach.max(value.abs()) } else { f64::INFINITY })
231}
232
233fn arithmetic_spacing(source: &BrepSolid, copy: &BrepSolid, transform: AffineTransform) -> f64 {
239 let m = transform.elements;
240 let gain = (0..3).map(|row| m[row * 4].abs() + m[row * 4 + 1].abs() + m[row * 4 + 2].abs()).fold(0.0f64, f64::max);
241 let translation = m[3].abs().max(m[7].abs()).max(m[11].abs());
242 reach(stated_points(copy)).max(gain * reach(stated_points(source))).max(translation) * f64::EPSILON
243}
244
245fn exact_sum(terms: impl IntoIterator<Item = f64>) -> f64 {
248 let mut partials: Vec<f64> = Vec::new();
249 for mut term in terms {
250 let mut kept = 0;
251 for index in 0..partials.len() {
252 let mut other = partials[index];
253 if term.abs() < other.abs() {
254 std::mem::swap(&mut term, &mut other);
255 }
256 let high = term + other;
257 let low = other - (high - term);
258 if low != 0.0 {
259 partials[kept] = low;
260 kept += 1;
261 }
262 term = high;
263 }
264 partials.truncate(kept);
265 partials.push(term);
266 }
267 partials.iter().sum()
270}
271
272fn coordinate_rounding(row: [f64; 4], point: Vec3, computed: f64) -> f64 {
277 let mut terms = [0.0f64; 8];
278 for (slot, (factor, value)) in [(row[0], point.x), (row[1], point.y), (row[2], point.z)].into_iter().enumerate() {
279 let product = factor * value;
280 terms[2 * slot] = product;
281 terms[2 * slot + 1] = factor.mul_add(value, -product);
282 }
283 terms[6] = row[3];
284 terms[7] = -computed;
285 -exact_sum(terms)
286}
287
288fn measurable(rounding: f64) -> bool {
293 rounding.is_finite() && rounding.abs() * f64::EPSILON <= 0.01 * crate::tolerance::DEFAULT_MODEL
294}
295
296fn placement_resolves_the_part(
307 source: &BrepSolid,
308 copy: &BrepSolid,
309 transform: AffineTransform,
310) -> Result<(), String> {
311 let m = transform.elements;
312 let rows = [[m[0], m[1], m[2], m[3]], [m[4], m[5], m[6], m[7]], [m[8], m[9], m[10], m[11]]];
313 let mut low = [f64::INFINITY; 3];
314 let mut high = [f64::NEG_INFINITY; 3];
315 let mut lost = false;
316 for (from, to) in stated_points(source).zip(stated_points(copy)) {
317 for (axis, value) in [to.x, to.y, to.z].into_iter().enumerate() {
318 let rounding = coordinate_rounding(rows[axis], from, value);
319 if !measurable(rounding) {
320 lost = true;
321 continue;
322 }
323 low[axis] = low[axis].min(rounding);
324 high[axis] = high[axis].max(rounding);
325 }
326 }
327 let spread = (0..3).map(|axis| (high[axis] - low[axis]).max(0.0).powi(2)).sum::<f64>().sqrt();
328 let worst = if lost { f64::INFINITY } else { spread };
329 if worst > crate::tolerance::DEFAULT_MODEL {
330 return Err(format!(
331 "transformSolid: the placement computes with coordinates spaced {:.1e}, too coarse to hold the part: it moves its points against one another by up to {worst:.1e}, past the {:.0e} modelling tolerance",
332 arithmetic_spacing(source, copy, transform),
333 crate::tolerance::DEFAULT_MODEL
334 ));
335 }
336 Ok(())
337}
338
339fn carries_clean_verdict(
354 solid: &BrepSolid,
355 transform: AffineTransform,
356 reverse_orientation: bool,
357) -> bool {
358 !reverse_orientation
359 && transform.is_rigid(crate::RIGID_TOL)
360 && solid.validate_memoised().is_empty()
361}
362
363thread_local! {
364 static CARRIED_VERDICTS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
366}
367
368
369fn carry_verdict_mode() -> crate::env_read::Mode {
370 crate::mode_switch!("BREP_TRANSFORM_CARRY_VERDICT", true)
371}
372
373pub fn mirror_brep(
381 solid: &BrepSolid,
382 plane_point: Vec3,
383 plane_normal: Vec3,
384) -> Result<BrepSolid, String> {
385 let n = plane_normal.normalized()?;
386 let (nx, ny, nz) = (n.x, n.y, n.z);
387 let d = plane_point.dot(n);
388 let (tx, ty, tz) = (2.0 * d * nx, 2.0 * d * ny, 2.0 * d * nz);
389 let matrix = [
390 1.0 - 2.0 * nx * nx,
391 -2.0 * nx * ny,
392 -2.0 * nx * nz,
393 tx,
394 -2.0 * ny * nx,
395 1.0 - 2.0 * ny * ny,
396 -2.0 * ny * nz,
397 ty,
398 -2.0 * nz * nx,
399 -2.0 * nz * ny,
400 1.0 - 2.0 * nz * nz,
401 tz,
402 0.0,
403 0.0,
404 0.0,
405 1.0,
406 ];
407 let transform = AffineTransform::new(matrix)?;
408 transform_brep(solid, transform, true)
409}
410
411
412pub(crate) fn multiply_elements(a: &[f64; 16], b: &[f64; 16]) -> [f64; 16] {
413 multiply_elements_seeded(a, b, 0.0)
414}
415
416fn multiply_elements_seeded(a: &[f64; 16], b: &[f64; 16], seed: f64) -> [f64; 16] {
417 let mut out = [0.0f64; 16];
418 for row in 0..4 {
419 for col in 0..4 {
420 let mut sum = seed;
421 for k in 0..4 {
422 sum += a[row * 4 + k] * b[k * 4 + col];
423 }
424 out[row * 4 + col] = sum;
425 }
426 }
427 out
428}
429