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