Skip to main content

brep_kernel/offset/offset_shell/
solid.rs

1//! Whole-solid offset (D3).
2//!
3//! `offset_solid` runs the shell pipeline in its WHOLE-BODY mode
4//! (`Body::Whole`): every face is retained, there is no opening and no wall,
5//! the source's own faces are not assembled, and the body is the offset
6//! carriers alone, closed at every sharp junction by the extend-and-intersect
7//! the pipeline already does for a shell's retained faces.
8//!
9//! The sign is the natural one: a positive distance grows the body along its
10//! outward normals, a negative one shrinks it. `offset_shell` takes the
11//! opposite sign (positive = inward wall), so the pipeline is asked for
12//! `-distance`.
13//!
14//! `OffsetCorners::Rounded` (D3) is the true parallel body, the Minkowski sum
15//! with a ball of radius `|d|`: the sharp body with every convex edge image
16//! (outward) or concave edge image (inward) rolled by the blend network at
17//! radius `|d|`, which is what puts the exact cylinder or torus cap on each
18//! straight or circular edge and the corner ball at each vertex. The blend's
19//! constructions are reused through `fillet_edges`, never rebuilt here.
20use super::debug_enabled;
21use super::pipeline::{offset_body, Body};
22use super::{OffsetFaceRole, OffsetShellFaceImageRecord, OffsetShellResultRecord};
23use crate::classification::PolygonClass;
24use crate::topology::{BrepSolid, EdgeRecord, FaceRecord};
25use crate::{
26    boolean_operation, fillet_edges, project_point_to_surface, BooleanOperation, BooleanOptions,
27    KernelRefusal, KernelStage, OrRefuse, RefusalClass, Vec2, Vec3,
28};
29use rustc_hash::FxHashMap as HashMap;
30use serde::{Deserialize, Serialize};
31
32/// How the offset body closes the joins between offset faces.
33#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
34#[serde(rename_all = "lowercase")]
35pub enum OffsetCorners {
36    #[default]
37    Sharp,
38    /// The exact parallel body: convex joins (outward) or concave joins
39    /// (inward) carry the rolling ball's cylinder, torus or sphere.
40    Rounded,
41}
42
43/// Offset every face of `source` by `distance` (positive grows) and join the
44/// offset faces into a closed body.
45pub fn offset_solid(
46    source: &BrepSolid,
47    distance: f64,
48    corners: OffsetCorners,
49) -> Result<OffsetShellResultRecord, KernelRefusal> {
50    if let Some(scaled) = crate::rescale::ScaledOffset::of(source, distance, "offset_solid")? {
51        let mut record = offset_solid(&scaled.source, scaled.distance, corners).map_err(|error| scaled.refusal(error))?;
52        record.solid = scaled.back(&record.solid, "offset_solid")?;
53        return Ok(record);
54    }
55    let built = offset_solid_unread(source, distance, corners)?;
56    if corners == OffsetCorners::Rounded {
57        if let Some(refusal) = super::rim_witness::rim_witness_refusal(source, &built.solid, distance) {
58            return Err(refusal);
59        }
60    }
61    Ok(built)
62}
63
64/// [`offset_solid`] before its result is read back ([`super::rim_witness`]).
65fn offset_solid_unread(
66    source: &BrepSolid,
67    distance: f64,
68    corners: OffsetCorners,
69) -> Result<OffsetShellResultRecord, KernelRefusal> {
70    let grown = offset_solid_joined(source, distance, corners)?;
71    if corners == OffsetCorners::Rounded && distance > 0.0 {
72        if let Some(carved) = super::bore_dimples::carve_bore_dimples(source, &grown.solid, distance) {
73            let operands = grown
74                .solid
75                .shells
76                .iter()
77                .flat_map(|shell| &shell.faces)
78                .zip(&grown.face_images)
79                .map(|(face, image)| (face, image.clone()))
80                .collect::<Vec<_>>();
81            let cap = OffsetShellFaceImageRecord { role: OffsetFaceRole::Offset, source_face_id: 0 };
82            if let Ok(face_images) = provenance_by_surface(&carved, &operands, Some(&cap)) {
83                return Ok(OffsetShellResultRecord { solid: carved, face_images });
84            }
85        }
86    }
87    Ok(grown)
88}
89
90/// [`offset_solid`] before the bore dimples ([`super::bore_dimples`]): the
91/// sharp body, or its rounding, or a decomposition's.
92fn offset_solid_joined(
93    source: &BrepSolid,
94    distance: f64,
95    corners: OffsetCorners,
96) -> Result<OffsetShellResultRecord, KernelRefusal> {
97    if corners == OffsetCorners::Rounded && distance > 0.0 {
98        if let Some(grown) = grown_across_reflex_edges(source, distance) {
99            return Ok(grown);
100        }
101    }
102    let sharp = match offset_body(source, &[], -distance, Body::Whole, "offset_solid") {
103        Ok(sharp) => sharp,
104        Err(error) => {
105            if corners == OffsetCorners::Rounded {
106                if let Some(grown) = grown_by_pieces(source, distance) {
107                    return Ok(grown);
108                }
109                if let Some(grown) = super::revolved_parallel::revolved_parallel(source, distance) {
110                    return Ok(grown);
111                }
112            }
113            return Err(error);
114        }
115    };
116    match corners {
117        OffsetCorners::Sharp => Ok(sharp),
118        OffsetCorners::Rounded => match round_offset_joins(sharp, distance) {
119            Ok(rounded) => Ok(rounded),
120            // A mitred body cannot carry the ball over a vertex of degree four
121            // or more; a convex polyhedron's parallel body is built directly.
122            Err(error) => match crate::blend::convex_parallel::convex_polyhedron_parallel(source, distance) {
123                Ok(Some((solid, images))) if solid.validate().is_empty() => {
124                    let face_images = images
125                        .into_iter()
126                        .map(|image| OffsetShellFaceImageRecord { role: OffsetFaceRole::Offset, source_face_id: image.unwrap_or(0) })
127                        .collect();
128                    Ok(OffsetShellResultRecord { solid, face_images })
129                }
130                _ => super::revolved_parallel::revolved_parallel(source, distance).ok_or(error),
131            },
132        },
133    }
134}
135
136/// `BREP_OFFSET_GROW_BY_PIECES` (default on; `=0` restores): [`grown_by_pieces`].
137fn grow_by_pieces_enabled() -> bool {
138    switch!("BREP_OFFSET_GROW_BY_PIECES", true)
139}
140
141
142/// The ROUNDED growth of a body whose own offset body the pipeline could not
143/// assemble, as the union of its pieces' growths: the parallel body of a
144/// union is the union of the parallel bodies, `(A ∪ B) ⊕ D = (A ⊕ D) ∪
145/// (B ⊕ D)`, for any pieces whose union is the body.
146///
147/// Cause (a drum with a groove 1.6 wide grown by 1, brep-bench
148/// offset/grooved-drum-grown): the groove's walls offset across each other,
149/// "a skin partly shadowed that way is not yet assembled", and even assembled
150/// the sharp body would have no groove left to round, while the case's notch
151/// is the two tori about the groove's outer rims. Cut at the planes of its
152/// planar faces the drum is three cylinders; each grows by the pipeline's own
153/// rounded offset, and their union carries the notch where the two rim tori
154/// cross.
155///
156/// The cuts are chosen by [`thin_pair_planes`] (the planes parallel to a pair
157/// of planar faces whose offsets cross), each kept only where it divides a
158/// piece (`split_solid_by_plane`). A SHRINK runs the same construction on the
159/// body's complement in a frame box ([`shrunk_by_pieces`]). Every piece must
160/// grow and the union must validate; anything else declines and the
161/// pipeline's own refusal stands. The faces are all `Offset` images with
162/// `source_face_id` 0, as the rounded caps are: a face of the union may carry
163/// the growth of several source faces' pieces.
164fn grown_by_pieces(source: &BrepSolid, distance: f64) -> Option<OffsetShellResultRecord> {
165    if !grow_by_pieces_enabled() {
166        return None;
167    }
168    match grown_by_pieces_impl(source, distance) {
169        Ok(result) => result,
170        Err(error) => {
171            os_debug!("grow by pieces declined: {error}");
172            None
173        }
174    }
175}
176
177fn grown_by_pieces_impl(source: &BrepSolid, distance: f64) -> Result<Option<OffsetShellResultRecord>, KernelRefusal> {
178    if distance < 0.0 {
179        return shrunk_by_pieces(source, -distance);
180    }
181    let Some(sets) = thin_pair_planes(source, distance, true)? else {
182        return Ok(None);
183    };
184    let mut answer = None;
185    for planes in &sets {
186        match grown_union(source, planes, distance) {
187            Ok(Some(solid)) => {
188                answer = Some(solid);
189                break;
190            }
191            Ok(None) => {}
192            Err(error) => os_debug!("grow by pieces: {} plane(s) declined: {error}", planes.len()),
193        }
194    }
195    let Some(solid) = answer else {
196        return Ok(None);
197    };
198    let face_images = solid
199        .shells
200        .iter()
201        .flat_map(|shell| &shell.faces)
202        .map(|_| OffsetShellFaceImageRecord { role: OffsetFaceRole::Offset, source_face_id: 0 })
203        .collect();
204    Ok(Some(OffsetShellResultRecord { solid, face_images }))
205}
206
207/// Roll the sharp body's joins that the ball of radius `|distance|` rounds:
208/// the convex edges of an outward offset, the concave edges of an inward one.
209/// A body with no such edge is already the parallel body and is returned as
210/// it is. Provenance: a face still on a sharp-body surface keeps that face's
211/// image; a cap (a cylinder, torus or corner ball the blend built, which lies
212/// on no offset face) is an `Offset` image with `source_face_id` 0, because it
213/// rounds a JOIN between source faces and has no single source face.
214fn round_offset_joins(
215    sharp: OffsetShellResultRecord,
216    distance: f64,
217) -> Result<OffsetShellResultRecord, KernelRefusal> {
218    let wanted_convex = distance > 0.0;
219    let midpoints = sharp_join_midpoints(&sharp.solid, wanted_convex)?;
220    if midpoints.is_empty() {
221        return Ok(sharp);
222    }
223    let solid = fillet_edges(&sharp.solid, &midpoints, None, distance.abs(), false, None)
224        .map_err(|error| {
225            error.with_message(|message| {
226                format!(
227                    "offset_solid: the rounded joins of the offset body could not be built \
228                     ({} edge(s) at radius {:.6}): {message}",
229                    midpoints.len(),
230                    distance.abs()
231                )
232            })
233        })?;
234    let operands = sharp
235        .solid
236        .shells
237        .iter()
238        .flat_map(|shell| &shell.faces)
239        .zip(&sharp.face_images)
240        .map(|(face, image)| (face, image.clone()))
241        .collect::<Vec<_>>();
242    let cap = OffsetShellFaceImageRecord {
243        role: OffsetFaceRole::Offset,
244        source_face_id: 0,
245    };
246    let face_images = provenance_by_surface(&solid, &operands, Some(&cap))?;
247    Ok(OffsetShellResultRecord { solid, face_images })
248}
249
250/// Per-face provenance of a body whose faces lie on its operands' surfaces (a
251/// boolean result, a blend's untouched faces): each result face takes the
252/// image of the FIRST operand face whose surface carries an interior point of
253/// it and whose trim contains that point's foot. Operands are matched in the
254/// order given, so a coincident pair (a held face and the opening it copies)
255/// resolves to whichever is listed first. A face on no operand surface takes
256/// `unmatched`, or refuses by name when there is none.
257pub(super) fn provenance_by_surface(
258    result: &BrepSolid,
259    operands: &[(&FaceRecord, OffsetShellFaceImageRecord)],
260    unmatched: Option<&OffsetShellFaceImageRecord>,
261) -> Result<Vec<OffsetShellFaceImageRecord>, KernelRefusal> {
262    let band = 1e-6 * crate::solid_scale(result).max(1.0);
263    let mut images = Vec::new();
264    for face in result.shells.iter().flat_map(|shell| &shell.faces) {
265        let seeds = super::source_seeds(result, face.id)?;
266        let seed = seeds[0];
267        let point = face.surface.evaluate(seed.x, seed.y).or_refuse(KernelStage::Sew, "evaluate")?;
268        let mut found = None;
269        for (operand, image) in operands {
270            let Ok(foot) = project_point_to_surface(&operand.surface, point) else { continue };
271            if foot.distance > band {
272                continue;
273            }
274            let inside = super::parameter_point_in_face(operand, Vec2 { x: foot.u, y: foot.v }, 1e-8)
275                .is_ok_and(|class| class != PolygonClass::Outside);
276            if inside {
277                found = Some(image.clone());
278                break;
279            }
280        }
281        match found.or_else(|| unmatched.cloned()) {
282            Some(image) => images.push(image),
283            None => {
284                return Err(KernelRefusal::internal(
285                    KernelStage::Sew,
286                    "offset_shell_provenance_lost",
287                    format!(
288                        "offset_shell: result face {} at ({:.4}, {:.4}, {:.4}) lies on no operand face",
289                        face.id, point.x, point.y, point.z
290                    ),
291                ))
292            }
293        }
294    }
295    Ok(images)
296}
297
298/// Midpoints of the SHARP edges of `solid` whose convexity is `convex`: an
299/// edge bordering two different faces whose outward normals differ there, read
300/// at the edge midpoint. Tangent junctions (a blend face meeting its support)
301/// and face-local seams are not joins and are skipped.
302fn sharp_join_midpoints(solid: &BrepSolid, convex: bool) -> Result<Vec<Vec3>, KernelRefusal> {
303    // Cosine of the dihedral angle above which two faces read as tangent.
304    const TANGENT_COSINE: f64 = 1.0 - 1e-6;
305    let faces = solid
306        .shells
307        .iter()
308        .flat_map(|shell| &shell.faces)
309        .collect::<Vec<_>>();
310    let mut uses = HashMap::<u64, Vec<(&FaceRecord, bool)>>::default();
311    for face in &faces {
312        for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
313            uses.entry(coedge.edge_id).or_default().push((face, coedge.forward));
314        }
315    }
316    let mut midpoints = Vec::new();
317    for edge in &solid.edges {
318        if edge.degenerate {
319            continue;
320        }
321        let Some(pair) = uses.get(&edge.id) else { continue };
322        if pair.len() != 2 || pair[0].0.id == pair[1].0.id {
323            continue;
324        }
325        if edge_is_convex_join(edge, pair[0], pair[1].0, TANGENT_COSINE)? == Some(convex) {
326            midpoints.push(edge.curve.evaluate(0.5 * (edge.t0 + edge.t1)).or_refuse(KernelStage::Classify, "evaluate")?);
327        }
328    }
329    Ok(midpoints)
330}
331
332/// `Some(true)` for a convex join, `Some(false)` for a concave one, `None` for
333/// a tangent junction. With `t` the direction the first face's coedge runs
334/// along the edge and `n_a` that face's outward normal, `n_a × t` points into
335/// the first face; the join is convex when the second face's outward normal
336/// points away from there.
337fn edge_is_convex_join(
338    edge: &EdgeRecord,
339    (first, first_forward): (&FaceRecord, bool),
340    second: &FaceRecord,
341    tangent_cosine: f64,
342) -> Result<Option<bool>, KernelRefusal> {
343    let t = 0.5 * (edge.t0 + edge.t1);
344    let derivatives = edge.curve.derivatives(t, 1).or_refuse(KernelStage::Classify, "derivatives")?;
345    let point = derivatives[0];
346    let mut tangent = derivatives[1].normalized().or_refuse(KernelStage::Classify, "normalized")?;
347    if !first_forward {
348        tangent = tangent.scale(-1.0);
349    }
350    let normal_a = outward_normal_at(first, point)?;
351    let normal_b = outward_normal_at(second, point)?;
352    if normal_a.dot(normal_b) >= tangent_cosine {
353        return Ok(None);
354    }
355    Ok(Some(normal_b.dot(normal_a.cross(tangent)) < 0.0))
356}
357
358fn outward_normal_at(face: &FaceRecord, point: Vec3) -> Result<Vec3, KernelRefusal> {
359    let foot = project_point_to_surface(&face.surface, point).or_refuse(KernelStage::Classify, "project_point_to_surface")?;
360    super::face_normal(face, foot.u, foot.v)
361}
362
363// ---------------------------------------------------------------------------
364// Shell as a boolean
365// ---------------------------------------------------------------------------
366
367/// The textbook shell: the offset body with the opening faces HELD (copied at
368/// distance zero, so they cancel in the difference), then `source − body` for
369/// an inward shell and `body − source` for an outward one. The walls at the
370/// openings come out of the boolean. `distance` carries `offset_shell`'s sign
371/// (positive inward).
372///
373/// This is the lane `offset_shell` falls back to when its direct construction
374/// refuses by one of its own names (`direct_refusal_takes_the_boolean_lane`);
375/// it is public so the two can be compared on any fixture. The result's
376/// `face_images` are read back from the operands by surface
377/// (`provenance_by_surface`): `Offset` for a face of the body's skins,
378/// `Wall` for a held opening face, `Source` for a face of the source.
379pub fn offset_shell_by_boolean(
380    source: &BrepSolid,
381    opening_face_ids: &[u64],
382    distance: f64,
383) -> Result<OffsetShellResultRecord, KernelRefusal> {
384    if let Some(scaled) = crate::rescale::ScaledOffset::of(source, distance, "offset_shell")? {
385        let mut record = offset_shell_by_boolean(&scaled.source, opening_face_ids, scaled.distance)
386            .map_err(|error| scaled.refusal(error))?;
387        record.solid = scaled.back(&record.solid, "offset_shell")?;
388        return Ok(record);
389    }
390    if opening_face_ids.is_empty() {
391        return Err(KernelRefusal::input(
392            KernelStage::Collect,
393            "offset_shell_no_opening",
394            "offset_shell: at least one opening face is required",
395        ));
396    }
397    let body = offset_body(source, opening_face_ids, distance, Body::Whole, "offset_shell_by_boolean")
398        .or_else(|error| {
399            if !direct_refusal_takes_the_boolean_lane(&error) {
400                return Err(error);
401            }
402            let result = super::joint_offset::build(source, opening_face_ids, distance);
403            if let Err(reason) = &result {
404                os_debug!("joint offset refused: {reason}");
405            }
406            result.map_err(|_| error)
407        })?;
408    let (kept, removed) = if distance > 0.0 { (source, &body.solid) } else { (&body.solid, source) };
409    let solid = boolean_operation(kept, removed, BooleanOperation::Subtract, &BooleanOptions::default())
410        .map_err(|error| {
411            error.with_message(|message| {
412                format!("offset_shell: the boolean lane's difference could not be built: {message}")
413            })
414        })?;
415    // The body's faces first, so the ring on a held face's plane reads as
416    // that face's `Wall` rather than as the coincident source opening.
417    let mut operands = body
418        .solid
419        .shells
420        .iter()
421        .flat_map(|shell| &shell.faces)
422        .zip(&body.face_images)
423        .map(|(face, image)| (face, image.clone()))
424        .collect::<Vec<_>>();
425    operands.extend(source.shells.iter().flat_map(|shell| &shell.faces).map(|face| {
426        (
427            face,
428            OffsetShellFaceImageRecord {
429                role: OffsetFaceRole::Source,
430                source_face_id: face.id,
431            },
432        )
433    }));
434    let face_images = provenance_by_surface(&solid, &operands, None)?;
435    Ok(OffsetShellResultRecord { solid, face_images })
436}
437
438/// Lane O row 34: the CLOSED hollow, a shell with no openings. The offset
439/// body, the whole source grown or shrunk with sharp joins, against the
440/// source: `source − body` inward and `body − source` outward, so the result
441/// is the outer shell and the inner void's shell, with the walls of the band
442/// between them. `distance` carries `offset_shell`'s sign (positive inward).
443/// `face_images` are read back from the operands by surface as in
444/// [`offset_shell_by_boolean`]: `Offset` for the body's faces, `Source` for
445/// the source's.
446///
447/// The construction checks itself: the result is exactly two shells and its
448/// volume is the difference of the operands' volumes.
449pub fn offset_shell_closed(source: &BrepSolid, distance: f64) -> Result<OffsetShellResultRecord, KernelRefusal> {
450    if let Some(scaled) = crate::rescale::ScaledOffset::of(source, distance, "offset_shell_closed")? {
451        let mut record = offset_shell_closed(&scaled.source, scaled.distance).map_err(|error| scaled.refusal(error))?;
452        record.solid = scaled.back(&record.solid, "offset_shell_closed")?;
453        return Ok(record);
454    }
455    let body = offset_body(source, &[], distance, Body::Whole, "offset_shell_closed")?;
456    let (kept, removed) = if distance > 0.0 { (source, &body.solid) } else { (&body.solid, source) };
457    let solid = boolean_operation(kept, removed, BooleanOperation::Subtract, &BooleanOptions::default())
458        .map_err(|error| {
459            error.with_message(|message| format!("offset_shell: the closed hollow's difference could not be built: {message}"))
460        })?;
461    let volume = |solid: &BrepSolid| {
462        crate::solid_mass_properties(solid)
463            .map(|properties| properties.volume)
464            .or_refuse(KernelStage::Validate, "solid_mass_properties")
465    };
466    let expected = volume(kept)? - volume(removed)?;
467    let measured = volume(&solid)?;
468    if solid.shells.len() != 2 || !(expected > 0.0) || !((measured - expected).abs() <= 1e-9 * expected) {
469        return Err(KernelRefusal::internal(
470            KernelStage::Validate,
471            "offset_shell_closed_hollow",
472            format!(
473                "offset_shell: the closed hollow is not the band between its operands ({} shells, volume {measured} against {expected})",
474                solid.shells.len()
475            ),
476        ));
477    }
478    let mut operands = body
479        .solid
480        .shells
481        .iter()
482        .flat_map(|shell| &shell.faces)
483        .zip(&body.face_images)
484        .map(|(face, image)| (face, image.clone()))
485        .collect::<Vec<_>>();
486    operands.extend(source.shells.iter().flat_map(|shell| &shell.faces).map(|face| {
487        (face, OffsetShellFaceImageRecord { role: OffsetFaceRole::Source, source_face_id: face.id })
488    }));
489    let face_images = provenance_by_surface(&solid, &operands, None)?;
490    Ok(OffsetShellResultRecord { solid, face_images })
491}
492
493/// Whether a refusal of the direct pipeline is one of its OWN named
494/// inabilities, the ones the boolean recipe can answer differently: an
495/// `offset_shell_*` unsupported-geometry or internal refusal, or the
496/// assembler's typed non-integral-genus and degenerate-arrangement refusals
497/// that `cause_in_front` carries a shell cause through. Input refusals
498/// (distance, foreign opening, no retained face) and soundness refusals are
499/// not: the first name a caller's mistake, the second a body that must not be
500/// shipped by any route.
501pub(super) fn direct_refusal_takes_the_boolean_lane(refusal: &KernelRefusal) -> bool {
502    match &refusal.class {
503        RefusalClass::UnsupportedGeometry { what } | RefusalClass::Internal { what } => {
504            what.starts_with("offset_shell_")
505        }
506        RefusalClass::NonIntegralGenus { .. } => {
507            refusal.message.starts_with("offset_shell")
508                || (bare_genus_takes_the_boolean_lane() && refusal.message.starts_with("boolean assembly:"))
509        }
510        RefusalClass::DegenerateArrangement { .. } => refusal.message.starts_with("offset_shell"),
511        _ => false,
512    }
513}
514
515/// `BREP_OFFSET_BARE_GENUS_BOOLEAN_LANE` (default on; `=0` restores): the
516/// direct pipeline's assembly refusing a non-integral genus takes the boolean
517/// lane even with no shell cause put in front of it. Which sentence a refusal
518/// carries says nothing about whether the lane can answer:
519/// `inbox_20261017_negative_shell` only reached the lane through the note of
520/// an omission, and the omission was a misread fillet's true skin; reading
521/// that skin correctly (`BREP_OFFSET_TANGENT_EDGE_EUCLID`) left the same
522/// failed assembly with no note, and the shell was refused.
523fn bare_genus_takes_the_boolean_lane() -> bool {
524    crate::switch!("BREP_OFFSET_BARE_GENUS_BOOLEAN_LANE", true)
525}
526
527/// The cut planes: every planar face's plane parallel to a THIN PAIR, two
528/// planar faces with opposite outward normals closer than `2·amount` that face
529/// each other across void (`grow`) or across material (shrink) — the pair
530/// whose offsets cross. Deduplicated. Two sets are offered in turn: every
531/// planar face's plane parallel to a thin pair, then the thin pairs' own
532/// planes alone (when fewer), because the boolean that unions the grown
533/// pieces can fail on where one set's pieces meet and not the other's (the
534/// dumbbell's complement cut at all four y planes left sliver edges where the
535/// neck-mouth rounds of adjacent pieces cross). `None` when there is no thin
536/// pair or every set has more than eight planes.
537fn thin_pair_planes(solid: &BrepSolid, amount: f64, grow: bool) -> Result<Option<Vec<Vec<(Vec3, Vec3)>>>, KernelRefusal> {
538    let band = 1e-9 * crate::solid_scale(solid).max(1.0);
539    // Each planar face's plane, its OUTWARD normal.
540    let mut faces: Vec<(Vec3, Vec3)> = Vec::new();
541    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
542        let Some((point, normal)) = super::rim_welds::planar_surface_frame(&face.surface, band)? else {
543            continue;
544        };
545        let [u0, u1] = face.surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
546        let [v0, v1] = face.surface.domain_v().or_refuse(KernelStage::Refine, "domain_v")?;
547        let Ok(outward) = super::face_normal(face, 0.5 * (u0 + u1), 0.5 * (v0 + v1)) else {
548            continue;
549        };
550        faces.push((point, if outward.dot(normal) < 0.0 { normal.scale(-1.0) } else { normal }));
551    }
552    let mut directions: Vec<Vec3> = Vec::new();
553    let mut pairs: Vec<(usize, usize)> = Vec::new();
554    for (index, (point, normal)) in faces.iter().enumerate() {
555        for (offset, (other, other_normal)) in faces[index + 1..].iter().enumerate() {
556            if normal.dot(*other_normal) > -1.0 + 1e-12 {
557                continue;
558            }
559            // Signed gap from this face's plane to the other's, along this
560            // face's outward normal: positive across void, negative across
561            // material.
562            let gap = other.sub(*point).dot(*normal);
563            let thin = if grow { gap > band && gap < 2.0 * amount } else { gap < -band && -gap < 2.0 * amount };
564            if thin {
565                pairs.push((index, index + 1 + offset));
566                if !directions.iter().any(|axis| axis.dot(*normal).abs() >= 1.0 - 1e-12) {
567                    directions.push(*normal);
568                }
569            }
570        }
571    }
572    if directions.is_empty() {
573        return Ok(None);
574    }
575    let push = |planes: &mut Vec<(Vec3, Vec3)>, point: Vec3, normal: Vec3| {
576        let seen = planes
577            .iter()
578            .any(|(other, axis)| axis.dot(normal).abs() >= 1.0 - 1e-12 && point.sub(*other).dot(*axis).abs() <= band);
579        if !seen {
580            planes.push((point, normal));
581        }
582    };
583    let mut parallel: Vec<(Vec3, Vec3)> = Vec::new();
584    for (point, normal) in &faces {
585        if directions.iter().any(|axis| axis.dot(*normal).abs() >= 1.0 - 1e-12) {
586            push(&mut parallel, *point, *normal);
587        }
588    }
589    let mut paired: Vec<(Vec3, Vec3)> = Vec::new();
590    for (first, second) in &pairs {
591        push(&mut paired, faces[*first].0, faces[*first].1);
592        push(&mut paired, faces[*second].0, faces[*second].1);
593    }
594    let mut sets = Vec::new();
595    if parallel.len() <= 8 {
596        sets.push(parallel.clone());
597    }
598    if paired.len() <= 8 && paired.len() < parallel.len() {
599        sets.push(paired);
600    }
601    Ok((!sets.is_empty()).then_some(sets))
602}
603
604/// `solid` cut by every plane that divides a piece of it.
605fn cut_by_planes(solid: &BrepSolid, planes: &[(Vec3, Vec3)]) -> Vec<BrepSolid> {
606    let mut pieces = vec![solid.clone()];
607    for (point, normal) in planes {
608        let mut next = Vec::with_capacity(pieces.len() * 2);
609        for piece in pieces {
610            match crate::split_solid_by_plane(&piece, *point, *normal) {
611                Ok((below, above)) => {
612                    next.push(below);
613                    next.push(above);
614                }
615                Err(_) => next.push(piece),
616            }
617        }
618        pieces = next;
619    }
620    pieces
621}
622
623/// The SHRINK by `amount` through the complement: `S ⊖ D = S − ((F − S) ⊕ D)`
624/// for a frame box `F` reaching past `S` by more than `amount`, where the
625/// complement's growth is the union of its pieces' growths, the pieces cut at
626/// the planes of `S`'s planar faces.
627///
628/// Cause (a drum with a flange 1.6 thick shrunk by 1, brep-bench
629/// offset/flanged-drum-shrunk): the flange's two faces offset across each
630/// other ("a skin partly shadowed that way is not yet assembled"), and the
631/// low ridge the case reads is the two concave tori about the flange's inner
632/// rims, which the complement's pieces carry as the rounds of their own
633/// convex rims.
634fn shrunk_by_pieces(source: &BrepSolid, amount: f64) -> Result<Option<OffsetShellResultRecord>, KernelRefusal> {
635    let Some(sets) = thin_pair_planes(source, amount, false)? else {
636        return Ok(None);
637    };
638    let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
639    let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
640    for face in source.shells.iter().flat_map(|shell| &shell.faces) {
641        for control in face.surface.control_points.iter().flatten() {
642            let Ok(point) = control.point() else { return Ok(None) };
643            low = Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z));
644            high = Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z));
645        }
646    }
647    let margin = 3.0 * amount;
648    let corner = low.sub(Vec3::new(margin, margin, margin));
649    let size = high.sub(low).add(Vec3::new(2.0 * margin, 2.0 * margin, 2.0 * margin));
650    let frame = crate::make_box_brep(corner, size.x, size.y, size.z).or_refuse(KernelStage::Refine, "make_box_brep")?;
651    let options = BooleanOptions::default();
652    let outside = boolean_operation(&frame, source, BooleanOperation::Subtract, &options)?;
653    let mut answer = None;
654    for planes in &sets {
655        let attempt = grown_union(&outside, planes, amount).and_then(|reach| match reach {
656            Some(reach) => boolean_operation(source, &reach, BooleanOperation::Subtract, &options).map(Some),
657            None => Ok(None),
658        });
659        match attempt {
660            Ok(Some(solid)) if solid.validate().is_empty() => {
661                answer = Some(solid);
662                break;
663            }
664            Ok(_) => {}
665            Err(error) => os_debug!("shrink by pieces: {} plane(s) declined: {error}", planes.len()),
666        }
667    }
668    if answer.is_none() && shrink_by_subtraction_enabled() {
669        for planes in &sets {
670            match subtracted_one_by_one(source, &outside, planes, amount) {
671                Ok(Some(solid)) => {
672                    answer = Some(solid);
673                    break;
674                }
675                Ok(None) => {}
676                Err(error) => os_debug!("shrink by subtraction: {} plane(s) declined: {error}", planes.len()),
677            }
678        }
679    }
680    let Some(solid) = answer else {
681        return Ok(None);
682    };
683    let face_images = solid
684        .shells
685        .iter()
686        .flat_map(|shell| &shell.faces)
687        .map(|_| OffsetShellFaceImageRecord { role: OffsetFaceRole::Offset, source_face_id: 0 })
688        .collect();
689    Ok(Some(OffsetShellResultRecord { solid, face_images }))
690}
691
692/// `solid` cut at `planes`, each piece grown by `amount` with rounded joins,
693/// and the growths' union; `None` when the planes leave one piece or the
694/// union does not validate.
695fn grown_union(solid: &BrepSolid, planes: &[(Vec3, Vec3)], amount: f64) -> Result<Option<BrepSolid>, KernelRefusal> {
696    let Some(grown) = grown_pieces(solid, planes, amount)? else {
697        return Ok(None);
698    };
699    let union = crate::boolean_operation_nary(&grown, BooleanOperation::Union)?;
700    Ok(union.validate().is_empty().then_some(union))
701}
702
703/// `solid` cut at `planes`, each piece grown by `amount` with rounded joins;
704/// `None` when the planes leave one piece.
705fn grown_pieces(solid: &BrepSolid, planes: &[(Vec3, Vec3)], amount: f64) -> Result<Option<Vec<BrepSolid>>, KernelRefusal> {
706    let pieces = cut_by_planes(solid, planes);
707    if pieces.len() < 2 {
708        return Ok(None);
709    }
710    os_debug!("by pieces: {} plane(s) cut the body into {} piece(s)", planes.len(), pieces.len());
711    let mut grown = Vec::with_capacity(pieces.len());
712    for (index, piece) in pieces.iter().enumerate() {
713        let sharp = offset_body(piece, &[], -amount, Body::Whole, "offset_solid_piece")
714            .map_err(|error| error.with_message(|message| format!("piece {index}: {message}")))?;
715        grown.push(round_offset_joins(sharp, amount)?.solid);
716    }
717    Ok(Some(grown))
718}
719
720/// `BREP_OFFSET_SHRINK_BY_SUBTRACTION` (default on; `=0` restores): where the union of a
721/// shrink's grown complement pieces cannot be assembled, the pieces are
722/// subtracted from the body one at a time instead.
723///
724/// Cause (the dumbbell plate shrunk by 1.5, brep-bench
725/// shell/dumbbell-neck-filled): the grown pieces' concave rounds about the
726/// neck mouths cross at y = 5, and their n-ary union failed ("boolean assembly
727/// produced invalid topology (S=3 genus=2)", one-use edges ~3e-5 long near
728/// (8.882, 5, 1.5)) for every plane set. `S − (A ∪ B) = (S − A) − B`.
729fn shrink_by_subtraction_enabled() -> bool {
730    switch!("BREP_OFFSET_SHRINK_BY_SUBTRACTION", true)
731}
732
733
734fn subtracted_one_by_one(source: &BrepSolid, outside: &BrepSolid, planes: &[(Vec3, Vec3)], amount: f64) -> Result<Option<BrepSolid>, KernelRefusal> {
735    let Some(grown) = grown_pieces(outside, planes, amount)? else {
736        return Ok(None);
737    };
738    let options = BooleanOptions::default();
739    let mut body = source.clone();
740    for (index, piece) in grown.iter().enumerate() {
741        body = boolean_operation(&body, piece, BooleanOperation::Subtract, &options)
742            .map_err(|error| error.with_message(|message| format!("subtracting grown piece {index}: {message}")))?;
743    }
744    Ok(body.validate().is_empty().then_some(body))
745}
746
747/// `BREP_OFFSET_REFLEX_BY_PIECES` (default on; `=0` restores): [`grown_across_reflex_edges`].
748fn reflex_by_pieces_enabled() -> bool {
749    switch!("BREP_OFFSET_REFLEX_BY_PIECES", true)
750}
751
752
753/// The ROUNDED growth of a body with CONCAVE (reflex) edges between planar
754/// faces, as the union of its pieces' growths, the pieces cut at those
755/// faces' planes; `None` (and the ordinary sharp body + rounds) where the body
756/// has none, or a piece or the union fails.
757///
758/// Cause (an L-shaped plate grown by 1, brep-bench offset/l-block-grown, read
759/// volume +0.041 and area −0.061 against the closed form): the sharp body is
760/// right, but where its reflex edge meets the top and bottom, the rounds of
761/// the two convex edges beside it must meet in a sharp concave crease, and
762/// `fillet_edges` blends that corner instead. Cut at x = 5 the plate is two
763/// boxes; each grows to a rounded box exactly, and their union carries the
764/// crease as the two rounds' own intersection.
765fn grown_across_reflex_edges(source: &BrepSolid, distance: f64) -> Option<OffsetShellResultRecord> {
766    if !reflex_by_pieces_enabled() {
767        return None;
768    }
769    let attempt = || -> Result<Option<OffsetShellResultRecord>, KernelRefusal> {
770        let band = 1e-9 * crate::solid_scale(source).max(1.0);
771        let faces = source.shells.iter().flat_map(|shell| &shell.faces).collect::<Vec<_>>();
772        let mut uses = HashMap::<u64, Vec<(&FaceRecord, bool)>>::default();
773        for face in &faces {
774            for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
775                uses.entry(coedge.edge_id).or_default().push((face, coedge.forward));
776            }
777        }
778        let mut planes: Vec<(Vec3, Vec3)> = Vec::new();
779        for edge in &source.edges {
780            if edge.degenerate {
781                continue;
782            }
783            let Some(pair) = uses.get(&edge.id) else { continue };
784            if pair.len() != 2 || pair[0].0.id == pair[1].0.id {
785                continue;
786            }
787            if edge_is_convex_join(edge, pair[0], pair[1].0, 1.0 - 1e-6)? != Some(false) {
788                continue;
789            }
790            for (face, _) in pair {
791                let Some((point, normal)) = super::rim_welds::planar_surface_frame(&face.surface, band)? else {
792                    continue;
793                };
794                let seen = planes
795                    .iter()
796                    .any(|(other, axis)| axis.dot(normal).abs() >= 1.0 - 1e-12 && point.sub(*other).dot(*axis).abs() <= band);
797                if !seen {
798                    planes.push((point, normal));
799                }
800            }
801        }
802        if planes.is_empty() || planes.len() > 8 {
803            return Ok(None);
804        }
805        // One plane per reflex edge is enough, and fewer pieces meet in fewer
806        // places: try each plane alone first, then all of them.
807        let mut sets = planes.iter().map(|plane| vec![*plane]).collect::<Vec<_>>();
808        if planes.len() > 1 {
809            sets.push(planes.clone());
810        }
811        for set in &sets {
812            match grown_union(source, set, distance) {
813                Ok(Some(solid)) => {
814                    os_debug!("reflex by pieces: {} plane(s)", set.len());
815                    let face_images = solid
816                        .shells
817                        .iter()
818                        .flat_map(|shell| &shell.faces)
819                        .map(|_| OffsetShellFaceImageRecord { role: OffsetFaceRole::Offset, source_face_id: 0 })
820                        .collect();
821                    return Ok(Some(OffsetShellResultRecord { solid, face_images }));
822                }
823                Ok(None) => {}
824                Err(error) => os_debug!("reflex by pieces: {} plane(s) declined: {error}", set.len()),
825            }
826        }
827        Ok(None)
828    };
829    match attempt() {
830        Ok(result) => result,
831        Err(error) => {
832            os_debug!("reflex by pieces declined: {error}");
833            None
834        }
835    }
836}