Skip to main content

brep_topology/brep/
transform_topology.rs

1pub use crate::topology::BrepSolid;
2pub use 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    /// Whether this affine map is a finite, proper rigid placement.
11    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    /// Compose row-major transforms, applying `b` first.
32    pub fn compose(&self, b: &AffineTransform) -> Result<AffineTransform, String> {
33        // Iterator Sum starts at -0.0; the raw STEP loop starts at +0.0.
34        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    /// Invert a rigid map as `[Rᵀ | −Rᵀ·t]`. The caller must verify rigidity.
55    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]; // Rᵀ
63            }
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 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    .map(|moved| moved.with_provenance_of(curve))
104}
105
106pub fn transform_surface(
107    surface: &NurbsSurface,
108    transform: AffineTransform,
109) -> Result<NurbsSurface, String> {
110    NurbsSurface::new(
111        surface.degree_u,
112        surface.degree_v,
113        surface.knots_u.clone(),
114        surface.knots_v.clone(),
115        surface
116            .control_points
117            .iter()
118            .map(|row| {
119                row.iter()
120                    .map(|point| transform.homogeneous(*point))
121                    .collect::<Result<Vec<_>, _>>()
122            })
123            .collect::<Result<_, _>>()?,
124    )
125}
126
127/// Transform exact BREP geometry without changing entity IDs or parameter
128/// ranges. `reverse_orientation` is required for negative-determinant maps.
129pub fn transform_brep(
130    solid: &BrepSolid,
131    transform: AffineTransform,
132    reverse_orientation: bool,
133) -> Result<BrepSolid, String> {
134    let determinant = transform.determinant3();
135    if determinant < 0.0 && !reverse_orientation {
136        return Err("transformSolid: reflection requires orientation reversal".into());
137    }
138    if determinant > 0.0 && reverse_orientation {
139        return Err("transformSolid: orientation reversal requires a reflection".into());
140    }
141    let mut result = solid.clone();
142    for vertex in &mut result.vertices {
143        vertex.point = transform.point(vertex.point);
144    }
145    for edge in &mut result.edges {
146        edge.curve = transform_curve(&edge.curve, transform)?;
147    }
148    for shell in &mut result.shells {
149        for face in &mut shell.faces {
150            face.surface = transform_surface(&face.surface, transform)?;
151            if reverse_orientation {
152                face.same_sense = !face.same_sense;
153                for loop_record in &mut face.loops {
154                    loop_record.coedges.reverse();
155                    for coedge in &mut loop_record.coedges {
156                        coedge.forward = !coedge.forward;
157                        coedge.pcurve = coedge.pcurve.reversed()?;
158                    }
159                }
160            }
161        }
162    }
163    // Where the copy's coordinates are spaced finely, a placement moves the
164    // part faithfully. Farther out, rounding to the coordinates there can
165    // reshape or collapse it while every topological check still passes, so
166    // the move is measured against the part and the copy is validated itself.
167    let precise = arithmetic_spacing(solid, &result, transform) <= PRECISE_SPACING;
168    if !precise {
169        placement_resolves_the_part(solid, &result, transform)?;
170    }
171    let mode = carry_verdict_mode();
172    let carried = precise
173        && mode != crate::env_read::Mode::Off
174        && carries_clean_verdict(solid, transform, reverse_orientation);
175    if carried && mode == crate::env_read::Mode::On {
176        CARRIED_VERDICTS.with(|count| count.set(count.get() + 1));
177        if crate::profile::profile_enabled() {
178            profile_line!("transform.verdict carried=1");
179        }
180        return Ok(result);
181    }
182    let issues = result.validate();
183    if mode == crate::env_read::Mode::Check && crate::profile::profile_enabled() {
184        // What carrying would have answered, against the copy's own verdict.
185        profile_line!(
186            "transform.verdict check carried={} issues={} disagree={}",
187            u8::from(carried),
188            issues.len(),
189            u8::from(carried && !issues.is_empty())
190        );
191    }
192    if issues.is_empty() {
193        Ok(result)
194    } else {
195        Err(format!("transformed BREP is invalid: {issues:?}"))
196    }
197}
198
199/// Spacing of the coordinates a placement computes with, below which a moved
200/// copy is faithful to the model tolerance with room to spare (a tenth of
201/// it): within about 4.5e7 of the origin. Such copies keep the fast path
202/// unchanged.
203pub const PRECISE_SPACING: f64 = 0.1 * crate::tolerance::DEFAULT_MODEL;
204
205/// Every point a solid's geometry is stated by, in a fixed order: its
206/// vertices, then each edge curve's control points, then each face surface's.
207/// A source and its transformed copy list them in parallel. A pole that does
208/// not read as a point comes out non-finite.
209fn stated_points(solid: &BrepSolid) -> impl Iterator<Item = Vec3> + '_ {
210    let cartesian =
211        |point: &Vec4| point.point().unwrap_or(Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY));
212    solid
213        .vertices
214        .iter()
215        .map(|vertex| vertex.point)
216        .chain(solid.edges.iter().flat_map(move |edge| edge.curve.control_points.iter().map(cartesian)))
217        .chain(
218            solid
219                .shells
220                .iter()
221                .flat_map(|shell| &shell.faces)
222                .flat_map(move |face| face.surface.control_points.iter().flatten().map(cartesian)),
223        )
224}
225
226/// The farthest coordinate of `points` from the origin; infinite when one is
227/// not finite.
228fn reach(points: impl Iterator<Item = Vec3>) -> f64 {
229    points
230        .flat_map(|point| [point.x, point.y, point.z])
231        .fold(0.0f64, |reach, value| if value.is_finite() { reach.max(value.abs()) } else { f64::INFINITY })
232}
233
234/// The spacing of representable coordinates at the largest magnitude the
235/// placement computes with: the copy's points, the source's as the linear
236/// part scales them, and the translation. A far part brought back near the
237/// origin loses its precision on the way, so the copy alone cannot tell; a
238/// far pole loses it though every vertex is near.
239pub fn arithmetic_spacing(source: &BrepSolid, copy: &BrepSolid, transform: AffineTransform) -> f64 {
240    let m = transform.elements;
241    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);
242    let translation = m[3].abs().max(m[7].abs()).max(m[11].abs());
243    reach(stated_points(copy)).max(gain * reach(stated_points(source))).max(translation) * f64::EPSILON
244}
245
246/// The sum of `terms`, exact until its final rounding: a Shewchuk expansion
247/// keeps every bit any partial sum would lose, however the terms cancel.
248fn exact_sum(terms: impl IntoIterator<Item = f64>) -> f64 {
249    let mut partials: Vec<f64> = Vec::new();
250    for mut term in terms {
251        let mut kept = 0;
252        for index in 0..partials.len() {
253            let mut other = partials[index];
254            if term.abs() < other.abs() {
255                std::mem::swap(&mut term, &mut other);
256            }
257            let high = term + other;
258            let low = other - (high - term);
259            if low != 0.0 {
260                partials[kept] = low;
261                kept += 1;
262            }
263            term = high;
264        }
265        partials.truncate(kept);
266        partials.push(term);
267    }
268    // Smallest first: the large partials do not overlap, so this rounds once
269    // to within an ulp of the result.
270    partials.iter().sum()
271}
272
273/// How far a computed coordinate lies from the exact `A p + t` for one row:
274/// the three products split exactly (fused multiply-add), the translation and
275/// the computed value summed exactly, so the rounding is measured to its own
276/// precision whatever the magnitudes.
277pub fn coordinate_rounding(row: [f64; 4], point: Vec3, computed: f64) -> f64 {
278    let mut terms = [0.0f64; 8];
279    for (slot, (factor, value)) in [(row[0], point.x), (row[1], point.y), (row[2], point.z)].into_iter().enumerate() {
280        let product = factor * value;
281        terms[2 * slot] = product;
282        terms[2 * slot + 1] = factor.mul_add(value, -product);
283    }
284    terms[6] = row[3];
285    terms[7] = -computed;
286    -exact_sum(terms)
287}
288
289/// Whether a measured rounding is fine enough for roundings to be compared
290/// against the model tolerance: its own ulp must sit well below it. One past
291/// that (tens of kilometres of rounding, from coordinates near 1e23) has lost
292/// the part in any case.
293pub fn measurable(rounding: f64) -> bool {
294    rounding.is_finite() && rounding.abs() * f64::EPSILON <= 0.01 * crate::tolerance::DEFAULT_MODEL
295}
296
297/// Refuse a copy the placement could not carry at the precision the kernel
298/// models to. Each stated point of the copy is set against its exact image
299/// under the placement: the difference is that coordinate's rounding. Points
300/// rounded alike have only moved together, which changes nothing; the spread
301/// of the roundings across the part is how far it was moved out of shape. A
302/// spread past the model tolerance, the band vertex identity is judged in,
303/// has reshaped the part (a thin side or wall lost, a corner merged, a cavity
304/// shifted into its solid), however small that is next to the part, and
305/// validation cannot see it. No reference point is subtracted, so nothing the
306/// placement rounds away can be rounded away from the measure too.
307fn placement_resolves_the_part(
308    source: &BrepSolid,
309    copy: &BrepSolid,
310    transform: AffineTransform,
311) -> Result<(), String> {
312    let m = transform.elements;
313    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]]];
314    let mut low = [f64::INFINITY; 3];
315    let mut high = [f64::NEG_INFINITY; 3];
316    let mut lost = false;
317    for (from, to) in stated_points(source).zip(stated_points(copy)) {
318        for (axis, value) in [to.x, to.y, to.z].into_iter().enumerate() {
319            let rounding = coordinate_rounding(rows[axis], from, value);
320            if !measurable(rounding) {
321                lost = true;
322                continue;
323            }
324            low[axis] = low[axis].min(rounding);
325            high[axis] = high[axis].max(rounding);
326        }
327    }
328    let spread = (0..3).map(|axis| (high[axis] - low[axis]).max(0.0).powi(2)).sum::<f64>().sqrt();
329    let worst = if lost { f64::INFINITY } else { spread };
330    if worst > crate::tolerance::DEFAULT_MODEL {
331        return Err(format!(
332            "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",
333            arithmetic_spacing(source, copy, transform),
334            crate::tolerance::DEFAULT_MODEL
335        ));
336    }
337    Ok(())
338}
339
340/// Whether a rigid placement may keep its source's clean validation verdict
341/// instead of validating the moved copy. A proper rigid map (the shared
342/// `RIGID_TOL` band components are placed under) changes no distance, angle,
343/// parameter or topology. It does change one input of `validate`: the
344/// identity and pcurve bands are sized from the AXIS-ALIGNED bounding box of
345/// the vertices, whose diagonal moves under a rotation, so a copy read with
346/// its own (narrower) bands could report an issue its source does not. The
347/// carried verdict is the source's, read in the source's frame. The source's
348/// verdict comes from the content-keyed validate memo: the first placement of
349/// a part validates the part once, each further placement of the same
350/// content reads the memo. A source with issues is never carried; its copy is
351/// validated as before. `BREP_TRANSFORM_CARRY_VERDICT`: on by default (`0`
352/// validates every copy, as before), `check` validates every copy anyway and
353/// prints (`BREP_PROFILE`) whether carrying would have disagreed.
354fn carries_clean_verdict(
355    solid: &BrepSolid,
356    transform: AffineTransform,
357    reverse_orientation: bool,
358) -> bool {
359    !reverse_orientation
360        && transform.is_rigid(crate::RIGID_TOL)
361        && solid.validate_memoised().is_empty()
362}
363
364thread_local! {
365    /// Placements on this thread that kept their source's verdict.
366    static CARRIED_VERDICTS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
367}
368
369
370fn carry_verdict_mode() -> crate::env_read::Mode {
371    crate::mode_switch!("BREP_TRANSFORM_CARRY_VERDICT", true)
372}
373
374/// Reflect an exact BREP across the plane through `plane_point` with unit
375/// normal `n = plane_normal.normalized()`. The reflection is the affine map
376/// `p' = R p + t` with linear part `R = I - 2 n nᵀ` and translation
377/// `t = 2 (plane_point·n) n`, so points on the plane map to themselves. A
378/// reflection has negative determinant (it flips handedness), so faces are
379/// re-oriented via the existing transform with `reverse_orientation = true`,
380/// keeping outward normals.
381pub fn mirror_brep(
382    solid: &BrepSolid,
383    plane_point: Vec3,
384    plane_normal: Vec3,
385) -> Result<BrepSolid, String> {
386    let n = plane_normal.normalized()?;
387    let (nx, ny, nz) = (n.x, n.y, n.z);
388    let d = plane_point.dot(n);
389    let (tx, ty, tz) = (2.0 * d * nx, 2.0 * d * ny, 2.0 * d * nz);
390    let matrix = [
391        1.0 - 2.0 * nx * nx,
392        -2.0 * nx * ny,
393        -2.0 * nx * nz,
394        tx,
395        -2.0 * ny * nx,
396        1.0 - 2.0 * ny * ny,
397        -2.0 * ny * nz,
398        ty,
399        -2.0 * nz * nx,
400        -2.0 * nz * ny,
401        1.0 - 2.0 * nz * nz,
402        tz,
403        0.0,
404        0.0,
405        0.0,
406        1.0,
407    ];
408    let transform = AffineTransform::new(matrix)?;
409    transform_brep(solid, transform, true)
410}
411
412
413pub fn multiply_elements(a: &[f64; 16], b: &[f64; 16]) -> [f64; 16] {
414    multiply_elements_seeded(a, b, 0.0)
415}
416
417pub fn multiply_elements_seeded(a: &[f64; 16], b: &[f64; 16], seed: f64) -> [f64; 16] {
418    let mut out = [0.0f64; 16];
419    for row in 0..4 {
420        for col in 0..4 {
421            let mut sum = seed;
422            for k in 0..4 {
423                sum += a[row * 4 + k] * b[k * 4 + col];
424            }
425            out[row * 4 + col] = sum;
426        }
427    }
428    out
429}