Skip to main content

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