Skip to main content

brep_kernel/
solid_face_calls.rs

1//! Public one-call operations on a solid's faces named by points.
2
3use crate::{thicken_sheet_faces, BrepSolid, KernelRefusal, KernelStage, OffsetCorners, Vec3};
4use std::collections::BTreeSet;
5
6/// The solid the faces of `solid` that `face_points` lie on sweep moving from 0
7/// to `thickness` along their outward normals (inward where it is negative);
8/// `solid` itself is not part of it. The faces are taken as one sheet, with the
9/// edges they share, and thickened by [`thicken_sheet_faces`] with sharp joins.
10pub fn thicken_faces(solid: &BrepSolid, face_points: &[Vec3], thickness: f64) -> Result<BrepSolid, KernelRefusal> {
11    if face_points.is_empty() {
12        return Err(KernelRefusal::input(KernelStage::Collect, "thicken_faces_points", "thicken_faces: no face named".to_string()));
13    }
14    let mut faces = BTreeSet::new();
15    for &point in face_points {
16        faces.insert(crate::resolve_face_by_point(solid, point)?);
17    }
18    let sheet = crate::feature_pipeline::features::sew_to_solid::extract(solid, &faces);
19    thicken_sheet_faces(&[sheet], thickness, OffsetCorners::Sharp)
20}
21
22/// How two solids meet, as they stand: the volume they share and the gap
23/// between them.
24#[derive(Clone, Copy, Debug, PartialEq)]
25pub struct Interference {
26    /// The volume of their intersection: above 0 where they overlap.
27    pub volume: f64,
28    /// The least distance from a point of one to a point of the other: 0
29    /// where they overlap or touch.
30    pub gap: f64,
31}
32
33/// How `a` and `b` meet: the volume of their intersection (the exact boolean's,
34/// 0 when their least boxes lie apart) and, when they share none, the least
35/// distance between their boundaries on their exact geometry
36/// ([`crate::solid_gap`]; 0 where they touch). `tolerance` (mm) is the band a
37/// point may stand past a face's trim and still count as on it.
38pub fn solid_interference(a: &BrepSolid, b: &BrepSolid, tolerance: f64) -> Result<Interference, KernelRefusal> {
39    let [la, ha] = crate::solid_least_box(a, tolerance)?;
40    let [lb, hb] = crate::solid_least_box(b, tolerance)?;
41    let apart = la.x > hb.x || lb.x > ha.x || la.y > hb.y || lb.y > ha.y || la.z > hb.z || lb.z > ha.z;
42    if apart {
43        return Ok(Interference { volume: 0.0, gap: crate::solid_gap(a, b, tolerance)? });
44    }
45    let scale = crate::solid_model_scale(a).max(crate::solid_model_scale(b)).max(1.0);
46    // Boundaries that stand apart leave each shell of one wholly inside or
47    // wholly outside the other, which one point of the shell tells; solids
48    // apart need no boolean (whose faces may lie too near one another for it
49    // to cut).
50    let gap = crate::solid_gap(a, b, tolerance)?;
51    let meet = gap <= tolerance.max(1e-9 * scale);
52    if !meet && !any_shell_inside(a, b, tolerance)? && !any_shell_inside(b, a, tolerance)? {
53        return Ok(Interference { volume: 0.0, gap });
54    }
55    let common = crate::boolean_operation(a, b, crate::BooleanOperation::Intersect, &crate::BooleanOptions::default())?;
56    let volume = if common.shells.iter().all(|shell| shell.faces.is_empty()) {
57        0.0
58    } else {
59        crate::solid_signed_volume(&common)
60            .map_err(|e| KernelRefusal::internal(KernelStage::Validate, "interference_volume", format!("interference: {e}")))?
61            .max(0.0)
62    };
63    // Where the boundaries meet, a shared volume no more than the smaller
64    // part's broadest side times the round-off of its coordinates is faces in
65    // contact, not an overlap; a part inside the other shares what it shares.
66    let side = |l: Vec3, h: Vec3| {
67        let mut e = [h.x - l.x, h.y - l.y, h.z - l.z];
68        e.sort_by(f64::total_cmp);
69        e[1] * e[2]
70    };
71    if volume > 0.0 && (!meet || volume > 1e-10 * scale * side(la, ha).min(side(lb, hb))) {
72        return Ok(Interference { volume, gap: 0.0 });
73    }
74    Ok(Interference { volume: 0.0, gap })
75}
76
77/// Whether a point of any shell of `inner` (where its first face's first trim
78/// begins, or its surface's middle for a face with no trim) lies inside `outer`.
79fn any_shell_inside(inner: &BrepSolid, outer: &BrepSolid, tolerance: f64) -> Result<bool, KernelRefusal> {
80    for shell in &inner.shells {
81        let Some(face) = shell.faces.first() else { continue };
82        let uv = match face.loops.iter().flat_map(|l| &l.coedges).next() {
83            Some(coedge) => coedge.pcurve.domain().and_then(|[t, _]| coedge.pcurve.evaluate(t)).map(|p| [p.x, p.y]),
84            None => face.surface.domain_u().and_then(|[u0, u1]| face.surface.domain_v().map(|[v0, v1]| [0.5 * (u0 + u1), 0.5 * (v0 + v1)])),
85        };
86        let point = uv.and_then(|[u, v]| face.surface.evaluate(u, v));
87        let point = point.map_err(|e| KernelRefusal::internal(KernelStage::Classify, "interference_inside", format!("interference: {e}")))?;
88        let class = crate::classify_point(point, outer, tolerance)
89            .map_err(|e| KernelRefusal::internal(KernelStage::Classify, "interference_inside", format!("interference: {e}")))?;
90        if class.class != crate::PointClass::Out {
91            return Ok(true);
92        }
93    }
94    Ok(false)
95}
96
97/// The faces of `solid` the points name, deduplicated in order: each point
98/// must lie inside one face's trim (within 1e-6 of the model's scale), not on
99/// an edge between faces, nor off them (a point in a hole's mouth names no
100/// face, though the cap's carrier runs through it).
101fn faces_named(solid: &BrepSolid, face_points: &[Vec3], what: &str) -> Result<Vec<u64>, KernelRefusal> {
102    if face_points.is_empty() {
103        return Err(KernelRefusal::input(KernelStage::Collect, format!("{what}_points"), format!("{what}: no face named")));
104    }
105    let tolerance = (crate::solid_model_scale(solid) * 1e-6).max(1e-9);
106    let mut seen = BTreeSet::new();
107    let mut faces = Vec::new();
108    for &point in face_points {
109        let foot = crate::nearest_boundary_point(solid, point, tolerance)?;
110        let face = match foot {
111            // Off the body first, whatever its nearest boundary point is.
112            Some(crate::BoundaryFoot { distance, .. }) if !(distance <= tolerance) => {
113                return Err(KernelRefusal::input(KernelStage::Collect, "point_off_faces", format!("{what}: the point {point:?} is {distance:e} from the boundary, off every face")));
114            }
115            Some(crate::BoundaryFoot { place: crate::BoundaryPlace::Face { face, .. }, .. }) => face,
116            // On an edge or vertex: it names a face only where every face
117            // round it is that one (a seam).
118            Some(foot) => {
119                let edges: Vec<u64> = match foot.place {
120                    crate::BoundaryPlace::Edge { edge, .. } => vec![edge],
121                    crate::BoundaryPlace::Vertex { vertex } => solid.edges.iter().filter(|e| e.start_vertex_id == vertex || e.end_vertex_id == vertex).map(|e| e.id).collect(),
122                    crate::BoundaryPlace::Face { face, .. } => vec![face],
123                };
124                let round: BTreeSet<u64> = solid
125                    .shells
126                    .iter()
127                    .flat_map(|shell| &shell.faces)
128                    .filter(|face| face.loops.iter().flat_map(|lp| &lp.coedges).any(|coedge| edges.contains(&coedge.edge_id)))
129                    .map(|face| face.id)
130                    .collect();
131                match (round.len(), round.iter().next()) {
132                    (1, Some(&face)) => face,
133                    _ => {
134                        return Err(KernelRefusal::input(KernelStage::Collect, "point_on_edge", format!("{what}: the point {point:?} lies on an edge or vertex between faces, naming none")));
135                    }
136                }
137            }
138            None => return Err(KernelRefusal::input(KernelStage::Collect, "no_faces", format!("{what}: the solid has no faces"))),
139        };
140        if seen.insert(face) {
141            faces.push(face);
142        }
143    }
144    Ok(faces)
145}
146
147/// `solid` with the faces `face_points` lie on each moved `distance` along
148/// its outward normal onto its offset surface (inward where it is negative),
149/// the faces round them extended or trimmed to meet them: Push Face's push
150/// (a plane translated, a cylinder, cone, sphere or torus offset exactly, a
151/// general revolution or free-form carrier within a bounded residual), then
152/// its acceptance. A plane landed exactly on a neighbour (two tops merged, a
153/// slot closed) is the boolean the push defines; a plane carried past one (an
154/// edge between them turned over) is refused as ill-posed. Exact to the push's tolerance, max(1e-7 of the model's
155/// scale, 1e-9); a nonzero distance below it is refused by name.
156pub fn offset_faces(solid: &BrepSolid, face_points: &[Vec3], distance: f64) -> Result<BrepSolid, KernelRefusal> {
157    if !distance.is_finite() {
158        return Err(KernelRefusal::input(KernelStage::Collect, "offset_faces_distance", "offset_faces: the distance must be finite"));
159    }
160    let faces = faces_named(solid, face_points, "offset_faces")?;
161    if distance == 0.0 {
162        return Ok(solid.clone());
163    }
164    // A distance the push's tolerance cannot tell from rest is refused by
165    // name, never returned as the body unmoved.
166    let resolution = (crate::solid_model_scale(solid) * 1e-7).max(1e-9);
167    if distance.abs() < resolution {
168        return Err(KernelRefusal::input(
169            KernelStage::Collect,
170            "motion_below_tolerance",
171            format!("offset_faces: the distance {distance:e} is below the {resolution:e} the push reads points to"),
172        ));
173    }
174    let mut notes = Vec::new();
175    crate::feature_pipeline::features::push_face::push_faces(solid.clone(), &faces, distance, &mut notes, false).map_err(|refusal| match refusal {
176        crate::feature_pipeline::FeatureRefusal::Typed(refusal) => refusal,
177        crate::feature_pipeline::FeatureRefusal::Text(message) => KernelRefusal::unsupported(KernelStage::Collect, "offset_faces", message),
178    })
179}
180
181/// The turn a rotation matrix makes: its unit axis and angle in (0, π], or
182/// None for the identity. Read from the skew part where the angle is clear of
183/// π, and from the symmetric part (its largest diagonal) near π, where the
184/// skew part vanishes.
185fn rotation_turn(r: &[[f64; 3]; 3]) -> Option<(Vec3, f64)> {
186    let trace = r[0][0] + r[1][1] + r[2][2];
187    let skew = Vec3::new(r[2][1] - r[1][2], r[0][2] - r[2][0], r[1][0] - r[0][1]);
188    // Its length scaled first, so a tiny turn's skew part does not square to zero.
189    let big = skew.x.abs().max(skew.y.abs()).max(skew.z.abs());
190    let skew_length = if big > 0.0 { big * Vec3::new(skew.x / big, skew.y / big, skew.z / big).length() } else { 0.0 };
191    let sine = 0.5 * skew_length;
192    let cosine = (0.5 * (trace - 1.0)).clamp(-1.0, 1.0);
193    let angle = sine.atan2(cosine);
194    if !(angle > 0.0) {
195        return None;
196    }
197    if cosine > -0.5 {
198        return Some((Vec3::new(skew.x / big, skew.y / big, skew.z / big).normalized().ok()?, angle));
199    }
200    // Near π: R + Rᵀ = 2 cos θ I + 2 (1 − cos θ) a aᵀ.
201    let k = 1.0 - cosine;
202    let column = (0..3).max_by(|&i, &j| r[i][i].total_cmp(&r[j][j])).unwrap_or(0);
203    let mut a = [0.0; 3];
204    a[column] = ((r[column][column] - cosine) / k).max(0.0).sqrt();
205    for i in 0..3 {
206        if i != column {
207            a[i] = (r[i][column] + r[column][i]) / (2.0 * k * a[column]);
208        }
209    }
210    let mut axis = Vec3::new(a[0], a[1], a[2]).normalized().ok()?;
211    // The skew part fixes the sign where it reads at all.
212    if axis.dot(skew) < 0.0 {
213        axis = axis.scale(-1.0);
214    }
215    Some((axis, angle))
216}
217
218/// `solid` with the faces `face_points` lie on moved rigidly by the rows
219/// `[R | t]` (a point x to R·x + t), the faces round them extended or trimmed
220/// to meet them: Transform Face's motion road (the turn and the slide solved
221/// in one re-intersection, its acceptance, and the re-cut and re-drill roads
222/// past a refusal). R must be a rotation (orthonormal, determinant +1).
223///
224/// The result is exact to the re-solve's tolerance, max(1e-7 of the model's
225/// scale, 1e-9): a part of the motion below it (a lift of 5e-10 riding on a
226/// slide along the face) may be read as rest. Within its envelope a whole
227/// motion below that tolerance, or a slide whose 1e-9 passes it, is refused
228/// by name; only R exactly the identity with no slide returns the body as it
229/// is.
230pub fn transform_faces(solid: &BrepSolid, face_points: &[Vec3], matrix: [[f64; 4]; 3]) -> Result<BrepSolid, KernelRefusal> {
231    if !matrix.iter().flatten().all(|x| x.is_finite()) {
232        return Err(KernelRefusal::input(KernelStage::Collect, "transform_faces_matrix", "transform_faces: the matrix must be finite"));
233    }
234    let r = [[matrix[0][0], matrix[0][1], matrix[0][2]], [matrix[1][0], matrix[1][1], matrix[1][2]], [matrix[2][0], matrix[2][1], matrix[2][2]]];
235    let t = Vec3::new(matrix[0][3], matrix[1][3], matrix[2][3]);
236    let mut off = 0.0f64;
237    for i in 0..3 {
238        for j in 0..3 {
239            let dot: f64 = (0..3).map(|k| r[k][i] * r[k][j]).sum();
240            off = off.max((dot - if i == j { 1.0 } else { 0.0 }).abs());
241        }
242    }
243    let det = r[0][0] * (r[1][1] * r[2][2] - r[1][2] * r[2][1]) - r[0][1] * (r[1][0] * r[2][2] - r[1][2] * r[2][0]) + r[0][2] * (r[1][0] * r[2][1] - r[1][1] * r[2][0]);
244    if !(off <= 1e-9 && det > 0.0) {
245        return Err(KernelRefusal::input(
246            KernelStage::Collect,
247            "transform_faces_rigid",
248            format!("transform_faces: the matrix's R is not a rotation (off orthonormal by {off:e}, determinant {det}): a face transform is a rigid motion"),
249        ));
250    }
251    let faces = faces_named(solid, face_points, "transform_faces")?;
252    // The turn about the selection's centre p (conditioning only: the motion
253    // is the same), the slide what is left: R(x − p) + p + s = R·x + t, so
254    // s = t + R·p − p carries all of a turn's displacement at p however small
255    // its angle. The turn itself is dropped only where it moves no corner of
256    // the body by more than 1e-12 of the model's scale.
257    let pivot = crate::feature_pipeline::features::transform_face::selection_centre(solid, &faces).unwrap_or(Vec3::new(0.0, 0.0, 0.0));
258    let turned = Vec3::new(
259        r[0][0] * pivot.x + r[0][1] * pivot.y + r[0][2] * pivot.z,
260        r[1][0] * pivot.x + r[1][1] * pivot.y + r[1][2] * pivot.z,
261        r[2][0] * pivot.x + r[2][1] * pivot.y + r[2][2] * pivot.z,
262    );
263    let slide = t.add(turned.sub(pivot));
264    // How far the body reaches from the pivot: its vertices and its faces'
265    // control points (a body without vertices, a whole torus, still turns).
266    let reach = solid
267        .vertices
268        .iter()
269        .map(|v| v.point)
270        .chain(solid.shells.iter().flat_map(|shell| &shell.faces).flat_map(|face| face.surface.control_points.iter().flatten()).filter_map(|p| p.point().ok()))
271        .map(|p| p.sub(pivot).length())
272        .fold(0.0f64, f64::max);
273    let scale = crate::solid_model_scale(solid).max(1e-300);
274    let read = rotation_turn(&r);
275    let swing = read.map_or(0.0, |(_, angle)| angle * reach);
276    let turn = read.filter(|_| swing > 1e-12 * scale).map(|(axis, angle)| (pivot, axis, angle));
277    // Exactly, by components (a length would square a tiny slide to zero).
278    let translates = slide.x != 0.0 || slide.y != 0.0 || slide.z != 0.0;
279    // Only the motion that moves nothing (R exactly the identity, element by
280    // element, and no slide) returns the body as it is; any other the turn's
281    // read cannot resolve falls to the refusal below.
282    let rest = (0..3).all(|i| (0..3).all(|j| r[i][j] == if i == j { 1.0 } else { 0.0 })) && t.x == 0.0 && t.y == 0.0 && t.z == 0.0;
283    if rest {
284        return Ok(solid.clone());
285    }
286    // A motion the re-solve's tolerance cannot tell from rest (it reads
287    // points to max(1e-7 of the scale, 1e-9)) is refused by name, never
288    // returned as the body unmoved.
289    let resolution = (scale * 1e-7).max(1e-9);
290    // The envelope: the re-solve reads a motion to 1e-9 of its length, so a
291    // slide whose 1e-9 passes the model's resolution could have a resolvable
292    // part read as rest; it is refused by name.
293    if slide.length() * 1e-9 > resolution {
294        return Err(KernelRefusal::input(
295            KernelStage::Collect,
296            "motion_out_of_envelope",
297            format!("transform_faces: the motion slides the faces {:e}, past what the re-solve reads to the model's resolution {resolution:e}", slide.length()),
298        ));
299    }
300    if turn.is_none() && slide.length() + swing < resolution {
301        return Err(KernelRefusal::input(
302            KernelStage::Collect,
303            "motion_below_tolerance",
304            format!("transform_faces: the motion moves the faces {:e}, below the {resolution:e} the re-solve reads points to", slide.length() + swing),
305        ));
306    }
307    // A motion every road refused for carrying a face past its neighbour (an
308    // edge between them turned over: the face pushed through the part) is the
309    // input's fault, not a shape the kernel lacks: refused as ill-posed, its
310    // message kept. A face landed exactly on a neighbour is answered above.
311    crate::feature_pipeline::features::transform_face::move_faces_road(solid, &faces, turn, translates, slide)
312        .map(|(body, _notes)| body)
313        .map_err(|(refusal, _step)| past_a_neighbour_is_ill_posed(refusal))
314}
315
316/// A refusal that a face was carried past its neighbour (a straight or curved
317/// edge turned over), in the ill-posed class; any other refusal as it is.
318fn past_a_neighbour_is_ill_posed(mut refusal: KernelRefusal) -> KernelRefusal {
319    use crate::face_refusal_slugs::{CURVED_EDGE_INVERSION, EDGE_INVERSION};
320    if matches!(&refusal.class, crate::RefusalClass::UnsupportedGeometry { what } if what == EDGE_INVERSION || what == CURVED_EDGE_INVERSION) {
321        refusal.class = crate::RefusalClass::IllPosed { what: "moved_past_a_neighbour".into() };
322    }
323    refusal
324}
325