Skip to main content

brep_offset/offset/
thicken_faces.rs

1//! THICKEN a sheet of several faces into one solid.
2//!
3//! Each face is thickened by itself ([`crate::thicken_trimmed_sheet`]: the
4//! face, its offset and the walls ruled between their edges), and the slabs are
5//! united. Where two faces meet along a crease the slabs either overlap (the
6//! crease closes toward the side thickened, and the union trims each moved face
7//! where it meets the other) or leave a gap (the crease opens toward that
8//! side). A gap is filled as the caller asks:
9//!
10//! - [`OffsetCorners::Sharp`]: the moved faces are extended until they meet,
11//!   a prism on the kite between the crease, its two moved images and the line
12//!   the two moved planes share; where three such creases meet in a corner,
13//!   the block out to the point the three moved planes share.
14//! - [`OffsetCorners::Rounded`]: the gap is closed by the cylinder of the
15//!   thickness about the crease, between the two moved faces; where three such
16//!   creases meet in a corner, by the piece of the ball about the corner
17//!   between the three.
18//!
19//! A whole patch of a round cylinder thickened toward its axis by its radius
20//! or more is the wedge between it and its axis, with the like wedge opposite
21//! for what is left over.
22//!
23//! A whole patch of a ring (an arc turned about an axis: a bend between a
24//! floor and a wall of revolution) thickened toward its tube's centre circle by
25//! the tube's radius or more is likewise the arc's sector turned about that
26//! axis, with the like sector opposite for what is left over.
27//!
28//! Faces that meet smoothly along a crease (a bend and the flat it leaves)
29//! need no fill; such a crease may be a closed circle. Where a crease closes toward the side thickened at a right
30//! angle or wider, the slabs end on each other or overlap; tighter than a
31//! right angle their square ends are cut off behind the other face. Fills are built where the crease is a straight line along
32//! which both faces keep their normals; any other open crease is refused by
33//! name, as is a corner where the open creases are not exactly three.
34use crate::topology::FaceRecord;
35use crate::{
36    boolean_operation, boolean_operation_nary, extrude_profile_brep, AnalyticSurface, make_arc, make_line, make_sphere_brep_framed, project_point_to_surface,
37    solid_from_polygons, thicken_trimmed_sheet, BooleanOperation, BooleanOptions, BrepSolid, KernelRefusal, KernelStage, NurbsCurve, OffsetCorners,
38    OrRefuse, Vec3,
39};
40
41/// The prefix of every refusal of this operation.
42pub const THICKEN_FACES_REFUSAL: &str = "thickenFaces";
43
44fn input(what: &'static str, message: String) -> KernelRefusal {
45    KernelRefusal::input(KernelStage::Collect, what, format!("{THICKEN_FACES_REFUSAL}: {message}"))
46}
47
48fn refuse(what: &'static str, message: String) -> KernelRefusal {
49    KernelRefusal::unsupported(KernelStage::Classify, what, format!("{THICKEN_FACES_REFUSAL}: {message}"))
50}
51
52/// The sheet a chain of curves sweeps as it slides by `distance` along
53/// `direction`: one face per curve (the curve times the slide), each a sheet
54/// of its own, in the chain's order. Every face's normal is its curve's
55/// direction crossed with the slide's, so the faces of a chain run head to
56/// tail have their normals on one side of the sheet, as
57/// [`thicken_sheet_faces`] needs them; run the chain the other way for the
58/// other side.
59pub fn extrude_curves_to_sheet(curves: &[NurbsCurve], direction: Vec3, distance: f64) -> Result<Vec<BrepSolid>, KernelRefusal> {
60    if curves.is_empty() {
61        return Err(input("curves", "at least one curve is required".into()));
62    }
63    if !distance.is_finite() || distance.abs() <= 1e-12 {
64        return Err(input("distance", "distance must be a nonzero finite value".into()));
65    }
66    let slide = direction.normalized().map_err(|_| input("direction", "direction must be non-zero".into()))?.scale(distance);
67    curves
68        .iter()
69        .map(|curve| {
70            let net = curve
71                .control_points
72                .iter()
73                .map(|pole| vec![*pole, crate::Vec4 { x: pole.x + slide.x * pole.w, y: pole.y + slide.y * pole.w, z: pole.z + slide.z * pole.w, w: pole.w }])
74                .collect();
75            let surface = crate::NurbsSurface::new(curve.degree, 1, curve.knots.clone(), vec![0.0, 0.0, 1.0, 1.0], net).or_refuse(KernelStage::Collect, "thickenFaces.swept_face")?;
76            crate::face_from_surface(&surface)
77        })
78        .collect()
79}
80
81/// One use of an edge by a face: where it runs, and the face's normal there.
82struct Side {
83    face: usize,
84    start: Vec3,
85    middle: Vec3,
86    end: Vec3,
87    /// The face's normal at the start, the middle and the end.
88    normals: [Vec3; 3],
89    /// The way this use runs at its middle (a closed edge has no chord to say).
90    tangent: Vec3,
91}
92
93fn face_normal(face: &FaceRecord, point: Vec3) -> Result<Vec3, KernelRefusal> {
94    let surface = &face.surface;
95    let foot = project_point_to_surface(surface, point).or_refuse(KernelStage::Classify, "thickenFaces.project")?;
96    let normal = match surface.normal(foot.u, foot.v) {
97        Ok(normal) => normal,
98        // At a pole (a side of the patch collapsed to a point) the surface has no
99        // normal of its own: read it a little way in, where it has one.
100        Err(_) => {
101            let [u0, u1] = surface.domain_u().or_refuse(KernelStage::Classify, "thickenFaces.domain")?;
102            let [v0, v1] = surface.domain_v().or_refuse(KernelStage::Classify, "thickenFaces.domain")?;
103            let inward = |at: f64, low: f64, high: f64| at + (0.5 * (low + high) - at) * 1e-6;
104            surface.normal(inward(foot.u, u0, u1), inward(foot.v, v0, v1)).or_refuse(KernelStage::Classify, "thickenFaces.normal")?
105        }
106    };
107    Ok(if face.same_sense { normal } else { normal.scale(-1.0) })
108}
109
110/// The sheet `faces` thickened by `thickness` along the faces' normals
111/// (negative: against them), its open creases closed as `corners` says.
112///
113/// `faces` are sheets of one face or more ([`crate::face_from_surface`],
114/// [`crate::face_from_surface_trimmed`]) that meet along common edges, their
115/// normals all on one side of the sheet. The result is one solid.
116///
117/// Refuses faces whose normals disagree across a crease, a crease that is not
118/// a straight line with constant normals where it opens toward the thickened
119/// side or closes tighter than a right angle, a corner of other than three
120/// open creases, and whatever the single-face thicken or the union refuses.
121pub fn thicken_sheet_faces(faces: &[BrepSolid], thickness: f64, corners: OffsetCorners) -> Result<BrepSolid, KernelRefusal> {
122    if !thickness.is_finite() || thickness.abs() <= 1e-12 {
123        return Err(input("thickness", "thickness must be a nonzero finite value".into()));
124    }
125    let (t, sign) = (thickness.abs(), thickness.signum());
126    let mut records: Vec<(&BrepSolid, &FaceRecord)> = Vec::new();
127    for body in faces {
128        for face in body.shells.iter().flat_map(|shell| &shell.faces) {
129            records.push((body, face));
130        }
131    }
132    if records.is_empty() {
133        return Err(input("faces", "at least one face is required".into()));
134    }
135    let size = records
136        .iter()
137        .flat_map(|(body, _)| &body.vertices)
138        .map(|vertex| vertex.point.sub(records[0].0.vertices[0].point).length())
139        .fold(t, f64::max);
140    let tolerance = 1e-7 * size;
141    let near = |a: Vec3, b: Vec3| a.sub(b).length() <= tolerance;
142
143    // every use of an edge by a face, as that face's loop runs along it
144    let mut sides = Vec::new();
145    for (index, (body, face)) in records.iter().enumerate() {
146        for coedge in face.loops.iter().flat_map(|record| &record.coedges) {
147            let edge = body.edges.iter().find(|edge| edge.id == coedge.edge_id).ok_or_else(|| input("faces", "a face refers to a missing edge".into()))?;
148            if edge.degenerate {
149                continue;
150            }
151            let at = |fraction: f64| edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * fraction).or_refuse(KernelStage::Classify, "thickenFaces.edge");
152            let (mut start, middle, mut end) = (at(0.0)?, at(0.5)?, at(1.0)?);
153            if !coedge.forward {
154                std::mem::swap(&mut start, &mut end);
155            }
156            let normals = [face_normal(face, start)?, face_normal(face, middle)?, face_normal(face, end)?];
157            let along = edge.curve.derivatives(0.5 * (edge.t0 + edge.t1), 1).or_refuse(KernelStage::Classify, "thickenFaces.edge")?;
158            let tangent = along.get(1).copied().unwrap_or(end.sub(start)).scale(if coedge.forward { 1.0 } else { -1.0 });
159            sides.push(Side { face: index, start, middle, end, normals, tangent });
160        }
161    }
162
163    // the slabs, face by face
164    let mut parts = Vec::new();
165    // `BREP_THICKEN_GLUE`: each part's container (a point set whose hull holds
166    // it; `None` reads a polyhedral part's own vertices), and whether the
167    // parts can be glued at all
168    let mut glueable = thicken_glue_on();
169    for (_, face) in &records {
170        let loops: Vec<Vec<NurbsCurve>> = face.loops.iter().map(|record| record.coedges.iter().map(|coedge| coedge.pcurve.clone()).collect()).collect();
171        let along = if face.same_sense { thickness } else { -thickness };
172        let wedges = match past_its_axis(face, along, tolerance)? {
173            Some(wedges) => Some(wedges),
174            None => past_its_ring(face, along, tolerance)?,
175        };
176        match wedges {
177            Some(wedges) => {
178                glueable = false;
179                parts.extend(wedges)
180            }
181            None => parts.extend(thicken_trimmed_sheet(&face.surface, &loops, along, false)?),
182        }
183    }
184    let mut containers: Vec<Option<Vec<Vec3>>> = vec![None; parts.len()];
185
186    // the creases: two faces' uses of one edge, run opposite ways
187    struct Open {
188        faces: [usize; 2],
189        ends: [Vec3; 2],
190        moved: [Vec3; 2],
191    }
192    let mut open = Vec::new();
193    let mut cuts: Vec<BrepSolid> = Vec::new();
194    for (i, a) in sides.iter().enumerate() {
195        for b in sides.iter().skip(i + 1) {
196            if a.face == b.face || !near(a.middle, b.middle) {
197                continue;
198            }
199            // a closed crease starts where it ends: only the way it runs says how the two uses face
200            let closed = near(a.start, a.end);
201            let opposite = if closed { a.tangent.dot(b.tangent) < 0.0 } else { near(a.start, b.end) && near(a.end, b.start) };
202            if !opposite {
203                if closed || (near(a.start, b.start) && near(a.end, b.end)) {
204                    return Err(input("normals", format!("faces {} and {} have their normals on opposite sides of the sheet", a.face, b.face)));
205                }
206                continue;
207            }
208            let run = a.end.sub(a.start);
209            let tangent = if closed { a.tangent } else { run }.normalized().map_err(|_| refuse("crease", "a crease has no length".into()))?;
210            // toward face a's inside, across the crease, and how far face b's moved image leans that way
211            let inward = a.normals[1].cross(tangent);
212            let lean = b.normals[1].scale(sign).dot(inward);
213            let moved = [a.normals[1].scale(sign), b.normals[1].scale(sign)];
214            let straight = a.middle.sub(a.start).cross(tangent).length() <= tolerance;
215            let steady = |side: &Side| side.normals.iter().all(|normal| normal.sub(side.normals[1]).length() <= 1e-9);
216            if lean.abs() <= 1e-9 {
217                // the faces meet smoothly: the slabs' ends are one wall
218                glueable = false;
219                continue;
220            }
221            if lean > 0.0 {
222                glueable = false;
223                // the crease closes toward the thickened side. At a right angle, or wider, the
224                // slabs end on each other or overlap, and the union is the answer. Tighter than a
225                // right angle their square ends stand out behind the other face, and are cut off.
226                let cosine = moved[0].dot(moved[1]);
227                if cosine >= -1e-9 {
228                    continue;
229                }
230                if !straight || !steady(a) || !steady(b) {
231                    return Err(refuse("crease_closing", format!("the crease between faces {} and {} closes toward the thickened side tighter than a right angle and is not a straight line with constant normals", a.face, b.face)));
232                }
233                let inward_b = b.normals[1].cross(tangent.scale(-1.0));
234                for (own, other, into) in [(moved[0], moved[1], inward), (moved[1], moved[0], inward_b)] {
235                    let top = a.start.add(own.scale(t));
236                    let reach = top.add(into.scale(t * -cosine / into.dot(other)));
237                    let line = |from: Vec3, to: Vec3| make_line(from, to).or_refuse(KernelStage::Collect, "thickenFaces.cut_line");
238                    cuts.push(extrude_profile_brep(&[line(a.start, top)?, line(top, reach)?, line(reach, a.start)?], run, run.length())?);
239                }
240                continue;
241            }
242            // b runs the other way: its start is a's end
243            if !straight || !steady(a) || !steady(b) {
244                return Err(refuse("crease_curved", format!("the crease between faces {} and {} opens toward the thickened side and is not a straight line with constant normals", a.face, b.face)));
245            }
246            parts.push(crease_fill(a.start, run, moved, t, corners)?);
247            containers.push(crease_container(a.start, run, moved, t));
248            open.push(Open { faces: [a.face, b.face], ends: [a.start, a.end], moved });
249        }
250    }
251
252    // the corners: points where open creases end together
253    let mut points: Vec<Vec3> = Vec::new();
254    for crease in &open {
255        for end in crease.ends {
256            if !points.iter().any(|point| near(*point, end)) {
257                points.push(end);
258            }
259        }
260    }
261    for point in points {
262        let here: Vec<&Open> = open.iter().filter(|crease| crease.ends.iter().any(|end| near(*end, point))).collect();
263        if here.len() == 1 {
264            continue;
265        }
266        // three creases between three faces, each pair once
267        let mut around: Vec<(usize, Vec3)> = Vec::new();
268        for crease in &here {
269            for (face, moved) in crease.faces.iter().zip(crease.moved) {
270                if !around.iter().any(|(known, _)| known == face) {
271                    around.push((*face, moved));
272                }
273            }
274        }
275        if here.len() != 3 || around.len() != 3 {
276            return Err(refuse("corner", format!("{} open creases between {} faces meet in one corner; exactly three between three faces are built", here.len(), around.len())));
277        }
278        parts.push(corner_fill(point, [around[0].1, around[1].1, around[2].1], t, corners)?);
279        containers.push(corner_container(point, [around[0].1, around[1].1, around[2].1], t));
280    }
281
282    if glueable && cuts.is_empty() && parts.len() > 1 {
283        if let Some(glued) = glue_parts(&parts, &containers, tolerance)? {
284            return Ok(glued);
285        }
286    }
287    let united = if parts.len() == 1 { parts.remove(0) } else { boolean_operation_nary(&parts, BooleanOperation::Union)? };
288    if cuts.is_empty() {
289        return Ok(united);
290    }
291    let mut operands = vec![united];
292    operands.extend(cuts);
293    boolean_operation_nary(&operands, BooleanOperation::Subtract)
294}
295
296/// `BREP_THICKEN_GLUE` (default on since the promotion of
297/// 2026-11-20; `=0` restores the union): the parts of a sheet thickened across
298/// open creases only (slabs, crease fills, corner fills; no closing or smooth
299/// crease, no cut, no wedge past an axis) touch only along whole faces, a
300/// slab's end against a fill's flat side, a fill's end against a corner's.
301/// Their union is then their faces with each touching pair dropped, sewn and
302/// its coplanar neighbours merged, which [`glue_parts`] builds without the
303/// union's imprint. thicken/open-box-outward-rounded: seventeen parts, about
304/// 0.38 s of its 0.57 s in the union's imprint (host).
305fn thicken_glue_on() -> bool {
306    switch!("BREP_THICKEN_GLUE", true)
307}
308
309
310/// A crease fill's container: the sharp fill's section (the start, the two
311/// moved edges' points and the point at the thickness from both faces) at both
312/// ends of the crease. The rounded section's arc lies in it (the arc's
313/// tangents at its ends meet at that point). `None` when the faces turn so far
314/// that the point runs off.
315fn crease_container(start: Vec3, run: Vec3, moved: [Vec3; 2], t: f64) -> Option<Vec<Vec3>> {
316    let turn = 1.0 + moved[0].dot(moved[1]);
317    if turn <= 1e-6 {
318        return None;
319    }
320    let section = [start, start.add(moved[0].scale(t)), start.add(moved[0].add(moved[1]).scale(t / turn)), start.add(moved[1].scale(t))];
321    Some(section.iter().flat_map(|point| [*point, point.add(run)]).collect())
322}
323
324/// A corner fill's container: the sharp corner (the corner, the three moved
325/// faces' points, the points at the thickness from two faces and from all
326/// three), which is the cone of the moved directions cut by the three planes
327/// at the thickness; the rounded fill (the ball of radius `t` in that cone)
328/// lies in it. `None` when the directions do not span space.
329fn corner_container(corner: Vec3, moved: [Vec3; 3], t: f64) -> Option<Vec<Vec3>> {
330    let [a, b, c] = moved;
331    let volume = a.dot(b.cross(c));
332    if volume.abs() <= 1e-9 {
333        return None;
334    }
335    let at = |direction: Vec3, length: f64| corner.add(direction.scale(length));
336    let mut points = vec![corner, at(b.cross(c).add(c.cross(a)).add(a.cross(b)).scale(1.0 / volume), t)];
337    for (i, j) in [(0, 1), (1, 2), (2, 0)] {
338        let turn = 1.0 + moved[i].dot(moved[j]);
339        if turn <= 1e-6 {
340            return None;
341        }
342        points.push(at(moved[i], t));
343        points.push(at(moved[i].add(moved[j]), t / turn));
344    }
345    Some(points)
346}
347
348/// [`thicken_glue_on`]: the union of `parts` read as their faces with each
349/// touching pair dropped, sewn ([`crate::solid_from_sheets`]), its
350/// coplanar neighbours merged and the edges that continue each other joined,
351/// as the boolean finishes. `None` (the caller takes the union) unless:
352/// every touching is a whole planar face of one part against a whole planar
353/// face of another, facing it, with the same corners and edge midpoints;
354/// every part touches another; no other pair of the parts' planar faces lies
355/// coplanar facing across an overlap; and every two parts are apart, their
356/// containers (`containers`, or a polyhedral part's own vertices) on the two
357/// sides of one of their planar faces' planes or of a box gap. The sewing
358/// refuses any edge left open, so a partial touching declines too.
359fn glue_parts(parts: &[BrepSolid], containers: &[Option<Vec<Vec3>>], tolerance: f64) -> Result<Option<BrepSolid>, KernelRefusal> {
360    struct Flat {
361        part: usize,
362        face: u64,
363        normal: Vec3,
364        offset: f64,
365        corners: Vec<Vec3>,
366        middles: Vec<Vec3>,
367    }
368    let stage = KernelStage::Classify;
369    let near = |a: Vec3, b: Vec3| a.sub(b).length() <= tolerance;
370    let mut flats: Vec<Flat> = Vec::new();
371    let mut hulls: Vec<Vec<Vec3>> = Vec::with_capacity(parts.len());
372    for (index, part) in parts.iter().enumerate() {
373        let edges: std::collections::HashMap<u64, &crate::topology::EdgeRecord> = part.edges.iter().map(|edge| (edge.id, edge)).collect();
374        let straight = |edge: &crate::topology::EdgeRecord| -> Result<bool, KernelRefusal> {
375            let (from, to) = (edge.curve.evaluate(edge.t0).or_refuse(stage, "thickenFaces.glue")?, edge.curve.evaluate(edge.t1).or_refuse(stage, "thickenFaces.glue")?);
376            let chord = to.sub(from);
377            let length = chord.length();
378            if length <= tolerance {
379                return Ok(false);
380            }
381            for control in &edge.curve.control_points {
382                let point = control.point().or_refuse(stage, "thickenFaces.glue")?;
383                if point.sub(from).cross(chord).length() > tolerance * length {
384                    return Ok(false);
385                }
386            }
387            Ok(true)
388        };
389        let mut polyhedral = true;
390        for edge in &part.edges {
391            if !edge.degenerate && !straight(edge)? {
392                polyhedral = false;
393            }
394        }
395        for face in part.shells.iter().flat_map(|shell| &shell.faces) {
396            if !matches!(face.surface.analytic(), Some(AnalyticSurface::Plane { .. })) {
397                polyhedral = false;
398                continue;
399            }
400            if face.loops.len() != 1 {
401                continue;
402            }
403            let normal = crate::face_merge::outward_normal(face)?.normalized().or_refuse(stage, "thickenFaces.glue")?;
404            let (mut corners, mut middles) = (Vec::new(), Vec::new());
405            for coedge in &face.loops[0].coedges {
406                let edge = edges.get(&coedge.edge_id).ok_or_else(|| input("faces", "a part's face refers to a missing edge".into()))?;
407                corners.push(edge.curve.evaluate(if coedge.forward { edge.t0 } else { edge.t1 }).or_refuse(stage, "thickenFaces.glue")?);
408                middles.push(edge.curve.evaluate(0.5 * (edge.t0 + edge.t1)).or_refuse(stage, "thickenFaces.glue")?);
409            }
410            let Some(first) = corners.first().copied() else { continue };
411            flats.push(Flat { part: index, face: face.id, normal, offset: normal.dot(first), corners, middles });
412        }
413        hulls.push(match &containers[index] {
414            Some(points) => points.clone(),
415            None if polyhedral => part.vertices.iter().map(|vertex| vertex.point).collect(),
416            None => return Ok(None),
417        });
418    }
419    let same_set = |x: &[Vec3], y: &[Vec3]| x.len() == y.len() && x.iter().all(|p| y.iter().any(|q| near(*p, *q))) && y.iter().all(|q| x.iter().any(|p| near(*p, *q)));
420    let bounds = |points: &[Vec3]| {
421        points.iter().fold(([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]), |(low, high), point| {
422            let p = [point.x, point.y, point.z];
423            (std::array::from_fn(|k| low[k].min(p[k])), std::array::from_fn(|k| high[k].max(p[k])))
424        })
425    };
426    // touching faces, each once; a coplanar pair facing across an overlap that is not one declines
427    let mut partner: Vec<Option<usize>> = vec![None; flats.len()];
428    for i in 0..flats.len() {
429        for j in i + 1..flats.len() {
430            let (f, g) = (&flats[i], &flats[j]);
431            if f.part == g.part || f.normal.dot(g.normal) > -1.0 + 1e-9 || (f.offset + g.offset).abs() > tolerance {
432                continue;
433            }
434            if same_set(&f.corners, &g.corners) && same_set(&f.middles, &g.middles) {
435                if partner[i].is_some() || partner[j].is_some() {
436                    return Ok(None);
437                }
438                partner[i] = Some(j);
439                partner[j] = Some(i);
440                continue;
441            }
442            let (low_f, high_f) = bounds(&[f.corners.as_slice(), f.middles.as_slice()].concat());
443            let (low_g, high_g) = bounds(&[g.corners.as_slice(), g.middles.as_slice()].concat());
444            let shared = (0..3).filter(|&k| high_f[k].min(high_g[k]) - low_f[k].max(low_g[k]) > tolerance).count();
445            let apart = (0..3).any(|k| high_f[k].min(high_g[k]) - low_f[k].max(low_g[k]) < -tolerance);
446            if !apart && shared >= 2 {
447                return Ok(None);
448            }
449        }
450    }
451    if (0..parts.len()).any(|index| !flats.iter().zip(&partner).any(|(flat, other)| flat.part == index && other.is_some())) {
452        return Ok(None);
453    }
454    // every two parts apart
455    for i in 0..parts.len() {
456        for j in i + 1..parts.len() {
457            let ((low_i, high_i), (low_j, high_j)) = (bounds(&hulls[i]), bounds(&hulls[j]));
458            if (0..3).any(|k| low_i[k] > high_j[k] + tolerance || low_j[k] > high_i[k] + tolerance) {
459                continue;
460            }
461            let separated = flats.iter().filter(|flat| flat.part == i || flat.part == j).any(|flat| {
462                let (own, other) = if flat.part == i { (&hulls[i], &hulls[j]) } else { (&hulls[j], &hulls[i]) };
463                own.iter().all(|point| flat.normal.dot(*point) <= flat.offset + tolerance)
464                    && other.iter().all(|point| flat.normal.dot(*point) >= flat.offset - tolerance)
465            });
466            if !separated {
467                return Ok(None);
468            }
469        }
470    }
471    let mut bodies = Vec::with_capacity(parts.len());
472    for (index, part) in parts.iter().enumerate() {
473        let dropped: std::collections::HashSet<u64> =
474            flats.iter().zip(&partner).filter(|(flat, other)| flat.part == index && other.is_some()).map(|(flat, _)| flat.face).collect();
475        let mut body = part.clone();
476        for shell in &mut body.shells {
477            shell.faces.retain(|face| !dropped.contains(&face.id));
478        }
479        body.shells.retain(|shell| !shell.faces.is_empty());
480        let used: std::collections::HashSet<u64> =
481            body.shells.iter().flat_map(|shell| &shell.faces).flat_map(|face| &face.loops).flat_map(|record| &record.coedges).map(|coedge| coedge.edge_id).collect();
482        body.edges.retain(|edge| used.contains(&edge.id));
483        let ends: std::collections::HashSet<u64> = body.edges.iter().flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).collect();
484        body.vertices.retain(|vertex| ends.contains(&vertex.id));
485        body.mass_properties_cache = Default::default();
486        bodies.push(body);
487    }
488    let Ok(sewn) = crate::solid_from_sheets(&bodies, tolerance) else { return Ok(None) };
489    let Ok(merged) = crate::merge_same_surface_faces(&sewn, tolerance) else { return Ok(None) };
490    match crate::merge_curve_continuation_edges(&merged, tolerance) {
491        Ok(merged) if merged.validate().is_empty() => {
492            Ok(Some(merged))
493        }
494        _ => Ok(None),
495    }
496}
497
498/// A whole patch of a round cylinder (an arc along u, slid straight along v)
499/// thickened toward its axis by its radius or more: every point `p + s·n`
500/// then runs from the patch to the axis and, past it, out the other side. So
501/// the body is the wedge between the patch and its axis and, opposite it, the
502/// like wedge of what the thickness has left over the radius. `None` for any
503/// other face or a thickness short of the axis, which the single-face thicken
504/// takes.
505fn past_its_axis(face: &FaceRecord, along: f64, tolerance: f64) -> Result<Option<Vec<BrepSolid>>, KernelRefusal> {
506    let surface = &face.surface;
507    let stage = KernelStage::Classify;
508    if surface.degree_v != 1 || surface.control_points.first().map(Vec::len) != Some(2) || !whole_domain(face)? {
509        return Ok(None);
510    }
511    let [u0, u1] = surface.domain_u().or_refuse(stage, "thickenFaces.domain")?;
512    let [v0, v1] = surface.domain_v().or_refuse(stage, "thickenFaces.domain")?;
513    let point = |u: f64, v: f64| surface.evaluate(u, v).or_refuse(stage, "thickenFaces.point");
514    let normal = |u: f64, v: f64| surface.normal(u, v).or_refuse(stage, "thickenFaces.normal");
515    let slide = point(u0, v1)?.sub(point(u0, v0)?);
516    // the centre the normals at the two ends of the arc pass through, toward the side thickened
517    let toward = along.signum();
518    let (p0, n0, p1, n1) = (point(u0, v0)?, normal(u0, v0)?.scale(toward), point(u1, v0)?, normal(u1, v0)?.scale(toward));
519    let chord = p1.sub(p0);
520    let spread = n0.sub(n1);
521    if spread.length() <= 1e-9 {
522        return Ok(None);
523    }
524    // p0 + R·n0 = p1 + R·n1
525    let radius = chord.dot(spread) / spread.dot(spread);
526    if !(radius > 0.0) || along.abs() < radius - tolerance {
527        return Ok(None);
528    }
529    let centre = p0.add(n0.scale(radius));
530    const SAMPLES: usize = 16;
531    for i in 0..=SAMPLES {
532        let u = u0 + (u1 - u0) * i as f64 / SAMPLES as f64;
533        for (v, shift) in [(v0, Vec3::new(0.0, 0.0, 0.0)), (v1, slide)] {
534            let focus = point(u, v)?.add(normal(u, v)?.scale(toward * radius));
535            if focus.sub(centre.add(shift)).length() > tolerance {
536                return Ok(None);
537            }
538        }
539    }
540    if slide.cross(n0).length() < (1.0 - 1e-9) * slide.length() {
541        return Ok(None);
542    }
543    // the wedge on the arc scaled about the centre by `factor`, slid along the axis
544    let arc = surface.iso_curve_v(v0).or_refuse(stage, "thickenFaces.arc")?;
545    let wedge = |factor: f64| -> Result<BrepSolid, KernelRefusal> {
546        let scaled = |q: Vec3| centre.add(q.sub(centre).scale(factor));
547        let poles = arc
548            .control_points
549            .iter()
550            .map(|pole| crate::Vec4::from_point(scaled(Vec3::new(pole.x / pole.w, pole.y / pole.w, pole.z / pole.w)), pole.w))
551            .collect();
552        let rim = NurbsCurve::new(arc.degree, arc.knots.clone(), poles).or_refuse(stage, "thickenFaces.wedge_arc")?;
553        let section = vec![
554            make_line(centre, scaled(p0)).or_refuse(stage, "thickenFaces.wedge_side")?,
555            rim,
556            make_line(scaled(p1), centre).or_refuse(stage, "thickenFaces.wedge_side")?,
557        ];
558        extrude_profile_brep(&section, slide, slide.length())
559    };
560    let mut wedges = vec![wedge(1.0)?];
561    let over = along.abs() - radius;
562    if over > tolerance {
563        wedges.push(wedge(-over / radius)?);
564    }
565    Ok(Some(wedges))
566}
567
568/// Is the face its surface's whole domain (its one loop's corners the domain's), regular at its corners?
569fn whole_domain(face: &FaceRecord) -> Result<bool, KernelRefusal> {
570    let surface = &face.surface;
571    let stage = KernelStage::Classify;
572    if face.loops.len() != 1 || face.loops[0].coedges.len() != 4 {
573        return Ok(false);
574    }
575    let [u0, u1] = surface.domain_u().or_refuse(stage, "thickenFaces.domain")?;
576    let [v0, v1] = surface.domain_v().or_refuse(stage, "thickenFaces.domain")?;
577    let corners = [[u0, v0], [u1, v0], [u1, v1], [u0, v1]];
578    let slack = 1e-9 * ((u1 - u0).abs() + (v1 - v0).abs());
579    for coedge in &face.loops[0].coedges {
580        let [t0, t1] = coedge.pcurve.domain().or_refuse(stage, "thickenFaces.pcurve")?;
581        for t in [t0, t1] {
582            let at = coedge.pcurve.evaluate(t).or_refuse(stage, "thickenFaces.pcurve")?;
583            if !corners.iter().any(|corner| (at.x - corner[0]).abs() + (at.y - corner[1]).abs() <= slack) {
584                return Ok(false);
585            }
586        }
587        // and runs along one side of the domain between them, not across the face
588        const SAMPLES: usize = 16;
589        let mut on_side = [true; 4];
590        for index in 1..SAMPLES {
591            let at = coedge.pcurve.evaluate(t0 + (t1 - t0) * index as f64 / SAMPLES as f64).or_refuse(stage, "thickenFaces.pcurve")?;
592            for (side, off) in [(at.x - u0).abs(), (at.x - u1).abs(), (at.y - v0).abs(), (at.y - v1).abs()].into_iter().enumerate() {
593                on_side[side] &= off <= slack;
594            }
595        }
596        if !on_side.iter().any(|on| *on) {
597            return Ok(false);
598        }
599    }
600    // a patch with a pole (a side collapsed to a point, where it has no normal) is no arc slid or turned
601    Ok(corners.iter().all(|corner| surface.normal(corner[0], corner[1]).is_ok()))
602}
603
604/// Places along one parameter of a surface that no span of it can hide
605/// between: twice the degree and one more in every knot span, ends included.
606/// A span is a rational piece of that degree, so the square of a distance
607/// along it, cleared of its weight, is a polynomial of twice the degree: one
608/// that vanishes at these vanishes along the span.
609fn span_places(knots: &[f64], degree: usize, low: f64, high: f64) -> Vec<f64> {
610    let mut breaks = vec![low];
611    breaks.extend(knots.iter().copied().filter(|knot| *knot > low && *knot < high));
612    breaks.push(high);
613    breaks.dedup();
614    let per_span = 2 * degree + 1;
615    let mut places = vec![low];
616    for span in breaks.windows(2) {
617        for index in 1..=per_span {
618            places.push(span[0] + (span[1] - span[0]) * index as f64 / per_span as f64);
619        }
620    }
621    *places.last_mut().expect("places") = high;
622    places
623}
624
625/// A whole patch of a ring (a circular arc along one parameter, turned about
626/// an axis along the other: a quarter of a torus round a cup's floor)
627/// thickened toward its tube's centre circle by the tube's radius or more.
628/// Every point `p + s·n` then runs from the patch to that circle and, past it,
629/// out the other side, each in its own half-plane through the axis. So the
630/// body is the arc's sector (the arc and its centre) turned about the axis
631/// and, opposite it, the like sector of what the thickness has left over the
632/// radius. `None` for any other face, a thickness short of the centre circle,
633/// or a leftover that would reach the axis, which the single-face thicken
634/// takes.
635fn past_its_ring(face: &FaceRecord, along: f64, tolerance: f64) -> Result<Option<Vec<BrepSolid>>, KernelRefusal> {
636    if !whole_domain(face)? {
637        return Ok(None);
638    }
639    for arc_along_u in [false, true] {
640        if let Some(sectors) = ring_sectors(face, along, tolerance, arc_along_u)? {
641            return Ok(Some(sectors));
642        }
643    }
644    Ok(None)
645}
646
647fn ring_sectors(face: &FaceRecord, along: f64, tolerance: f64, arc_along_u: bool) -> Result<Option<Vec<BrepSolid>>, KernelRefusal> {
648    let surface = &face.surface;
649    let stage = KernelStage::Classify;
650    let [u0, u1] = surface.domain_u().or_refuse(stage, "thickenFaces.domain")?;
651    let [v0, v1] = surface.domain_v().or_refuse(stage, "thickenFaces.domain")?;
652    // (a, b): along the arc, round the axis
653    let ([a0, a1], [b0, b1]) = if arc_along_u { ([u0, u1], [v0, v1]) } else { ([v0, v1], [u0, u1]) };
654    let at = |a: f64, b: f64| if arc_along_u { (a, b) } else { (b, a) };
655    let point = |a: f64, b: f64| surface.evaluate(at(a, b).0, at(a, b).1).or_refuse(stage, "thickenFaces.point");
656    let toward = along.signum();
657    let normal = |a: f64, b: f64| surface.normal(at(a, b).0, at(a, b).1).map(|normal| normal.scale(toward)).or_refuse(stage, "thickenFaces.normal");
658    // the centre the normals at the two ends of the first arc pass through
659    let (p0, n0, p1, n1) = (point(a0, b0)?, normal(a0, b0)?, point(a1, b0)?, normal(a1, b0)?);
660    let spread = n0.sub(n1);
661    if spread.length() <= 1e-9 {
662        return Ok(None);
663    }
664    let radius = p1.sub(p0).dot(spread) / spread.dot(spread);
665    if !(radius > 0.0) || along.abs() < radius - tolerance {
666        return Ok(None);
667    }
668    // read in every span of the surface both ways, so nothing between the readings is taken on trust
669    let (arc_places, turn_places) = if arc_along_u {
670        (span_places(&surface.knots_u, surface.degree_u, a0, a1), span_places(&surface.knots_v, surface.degree_v, b0, b1))
671    } else {
672        (span_places(&surface.knots_v, surface.degree_v, a0, a1), span_places(&surface.knots_u, surface.degree_u, b0, b1))
673    };
674    let (arcs, turns) = (arc_places.len() - 1, turn_places.len() - 1);
675    let arc_at = |i: usize| arc_places[i];
676    let turn_at = |j: usize| turn_places[j];
677    // each arc has one centre, the tube's centre line at that turn
678    let mut centres = Vec::with_capacity(turns + 1);
679    for j in 0..=turns {
680        let centre = point(a0, turn_at(j))?.add(normal(a0, turn_at(j))?.scale(radius));
681        for i in 1..=arcs {
682            if point(arc_at(i), turn_at(j))?.add(normal(arc_at(i), turn_at(j))?.scale(radius)).sub(centre).length() > tolerance {
683                return Ok(None);
684            }
685        }
686        centres.push(centre);
687    }
688    // the centres lie on a circle: its axis from three of them
689    let (f0, f1, f2) = (centres[0], centres[turns / 3], centres[2 * turns / 3]);
690    let (e1, e2) = (f1.sub(f0), f2.sub(f0));
691    let across = e1.cross(e2);
692    if across.length() <= 1e-9 * e1.length() * e2.length() || across.length() <= tolerance * tolerance {
693        return Ok(None);
694    }
695    let axis = across.normalized().or_refuse(stage, "thickenFaces.ring_axis")?;
696    // circumcentre of the three
697    let middle = f0.add(
698        e2.scale(e1.dot(e1)).sub(e1.scale(e2.dot(e2))).cross(across).scale(1.0 / (2.0 * across.dot(across))),
699    );
700    let ring = f0.sub(middle).length();
701    let over = along.abs() - radius;
702    if !(ring > over + tolerance) {
703        return Ok(None);
704    }
705    // every arc is the first turned about that axis, by a growing angle
706    let mut angle = 0.0;
707    for j in 1..=turns {
708        let (before, here) = (centres[j - 1].sub(middle), centres[j].sub(middle));
709        if (here.length() - ring).abs() > tolerance || here.dot(axis).abs() > tolerance {
710            return Ok(None);
711        }
712        let step = axis.dot(before.cross(here)).atan2(before.dot(here));
713        if !(step > 0.0) {
714            return Ok(None);
715        }
716        angle += step;
717        for i in 0..=arcs {
718            let first = point(arc_at(i), b0)?.sub(middle);
719            let turned = middle.add(first.rotate_about(axis, angle));
720            if point(arc_at(i), turn_at(j))?.sub(turned).length() > tolerance {
721                return Ok(None);
722            }
723        }
724    }
725    // the first arc lies in a half-plane through the axis, off the axis itself
726    let square = axis.cross(f0.sub(middle));
727    for i in 0..=arcs {
728        let from_axis = point(arc_at(i), b0)?.sub(middle);
729        if from_axis.dot(square).abs() > tolerance * ring.max(1.0) || from_axis.sub(axis.scale(from_axis.dot(axis))).length() <= tolerance {
730            return Ok(None);
731        }
732    }
733    let arc = if arc_along_u { surface.iso_curve_v(b0) } else { surface.iso_curve_u(b0) }.or_refuse(stage, "thickenFaces.arc")?;
734    let turn = angle.min(std::f64::consts::TAU);
735    // the sector on the arc scaled about its centre by `factor`, turned about the axis
736    let sector = |factor: f64| -> Result<BrepSolid, KernelRefusal> {
737        let scaled = |q: Vec3| f0.add(q.sub(f0).scale(factor));
738        let poles = arc
739            .control_points
740            .iter()
741            .map(|pole| crate::Vec4::from_point(scaled(Vec3::new(pole.x / pole.w, pole.y / pole.w, pole.z / pole.w)), pole.w))
742            .collect();
743        let rim = NurbsCurve::new(arc.degree, arc.knots.clone(), poles).or_refuse(stage, "thickenFaces.sector_arc")?;
744        let section = vec![
745            make_line(f0, scaled(p0)).or_refuse(stage, "thickenFaces.sector_side")?,
746            rim,
747            make_line(scaled(p1), f0).or_refuse(stage, "thickenFaces.sector_side")?,
748        ];
749        crate::revolve_profile_brep(&section, middle, axis, turn).or_refuse(KernelStage::Fragment, "thickenFaces.sector")
750    };
751    let mut sectors = vec![sector(1.0)?];
752    if over > tolerance {
753        sectors.push(sector(-over / radius)?);
754    }
755    Ok(Some(sectors))
756}
757
758/// The fill of an open straight crease from `start` along `run`, between the
759/// two faces' moved images `moved` (unit vectors square to the crease).
760fn crease_fill(start: Vec3, run: Vec3, moved: [Vec3; 2], t: f64, corners: OffsetCorners) -> Result<BrepSolid, KernelRefusal> {
761    let collect = KernelStage::Collect;
762    let (a, b) = (start.add(moved[0].scale(t)), start.add(moved[1].scale(t)));
763    let line = |from: Vec3, to: Vec3| make_line(from, to).or_refuse(collect, "thickenFaces.fill_line");
764    let section = match corners {
765        OffsetCorners::Sharp => {
766            // the point at the thickness from both faces, in the section's plane
767            let apex = start.add(moved[0].add(moved[1]).scale(t / (1.0 + moved[0].dot(moved[1]))));
768            vec![line(start, a)?, line(a, apex)?, line(apex, b)?, line(b, start)?]
769        }
770        OffsetCorners::Rounded => {
771            let across = moved[1].sub(moved[0].scale(moved[1].dot(moved[0]))).normalized().or_refuse(collect, "thickenFaces.fill_frame")?;
772            let angle = moved[0].dot(moved[1]).clamp(-1.0, 1.0).acos();
773            vec![line(start, a)?, make_arc(start, moved[0], across, t, 0.0, angle).or_refuse(collect, "thickenFaces.fill_arc")?, line(b, start)?]
774        }
775    };
776    extrude_profile_brep(&section, run, run.length())
777}
778
779/// The fill of a corner where three open creases meet, between the three
780/// faces' moved images `moved` (unit vectors).
781fn corner_fill(corner: Vec3, moved: [Vec3; 3], t: f64, corners: OffsetCorners) -> Result<BrepSolid, KernelRefusal> {
782    let at = |direction: Vec3, length: f64| corner.add(direction.scale(length));
783    match corners {
784        OffsetCorners::Sharp => {
785            // the point at the thickness from all three faces: moved[i] · x = 1
786            let [a, b, c] = moved;
787            let volume = a.dot(b.cross(c));
788            if volume.abs() <= 1e-9 {
789                return Err(refuse("corner", "the three faces at a corner do not span space".into()));
790            }
791            let far = b.cross(c).add(c.cross(a)).add(a.cross(b)).scale(1.0 / volume);
792            let pair = |i: usize, j: usize| at(moved[i].add(moved[j]), t / (1.0 + moved[i].dot(moved[j])));
793            let tip = |i: usize| at(moved[i], t);
794            let far = at(far, t);
795            let mut faces = Vec::new();
796            for (i, j) in [(0, 1), (1, 2), (2, 0)] {
797                faces.push(vec![corner, tip(i), pair(i, j), tip(j)]);
798            }
799            for (i, j, k) in [(0, 1, 2), (1, 2, 0), (2, 0, 1)] {
800                faces.push(vec![tip(i), pair(i, j), far, pair(i, k)]);
801            }
802            solid_from_polygons(&faces)
803        }
804        OffsetCorners::Rounded => {
805            // the ball about the corner, kept between the three directions: its poles and its
806            // seam turned away from the piece kept
807            let middle = moved[0].add(moved[1]).add(moved[2]).normalized().or_refuse(KernelStage::Collect, "thickenFaces.corner_frame")?;
808            let pole = middle.cross(moved[0]).normalized().or_refuse(KernelStage::Collect, "thickenFaces.corner_frame")?;
809            let ball = make_sphere_brep_framed(corner, t, pole, Some(middle.scale(-1.0))).or_refuse(KernelStage::Collect, "thickenFaces.corner_ball")?;
810            let reach = 4.0 * t;
811            let tips = [at(moved[0], reach), at(moved[1], reach), at(moved[2], reach)];
812            let base = tips[1].sub(tips[0]).cross(tips[2].sub(tips[0]));
813            if (tips[0].sub(corner).dot(base) / base.length()).abs() <= t {
814                return Err(refuse("corner", "the three faces at a corner are too nearly flat for a ball between them".into()));
815            }
816            let wedge = solid_from_polygons(&[
817                vec![corner, tips[0], tips[1]],
818                vec![corner, tips[1], tips[2]],
819                vec![corner, tips[2], tips[0]],
820                vec![tips[0], tips[1], tips[2]],
821            ])?;
822            boolean_operation(&ball, &wedge, BooleanOperation::Intersect, &BooleanOptions::default())
823        }
824    }
825}
826