Skip to main content

brep_offset/offset/offset_shell/
pipeline.rs

1use crate::{KernelRefusal, KernelStage, OrRefuse};
2use super::*;
3
4/// Put every face on one normal convention (surface normal on the CCW
5/// parameter-winding side) and then restore outward normals. The offset shell's
6/// source and offset skins are assembled as independent components whose
7/// per-face `same_sense` can follow opposite conventions; `validate()` only
8/// checks coedge-direction coherence (the `forward` flags), so a joined,
9/// watertight, coedge-coherent manifold can still be normal-incoherent and
10/// report the wrong volume. Re-deriving `same_sense` from the loop winding makes
11/// the coedge-coherent manifold normal-coherent; the signed-volume flip then
12/// orients it outward. Only invoked after a non-coplanar rim weld, so the
13/// coplanar cylinder/prism shells keep their exact assembled orientation.
14/// `BREP_OFFSET_ONE_CALL_IMPRINT` (lane P3b row 6, 2026-10-26): one
15/// `build_imprints` over a composite of every carrier instead of one call per
16/// pair. On by default (promoted 2026-10-27 after the 98 + 144 case oracle
17/// census); `0`/`off` retains the per-pair calls. Re-pinned by independent
18/// oracles, not byte-identical (piece and vertex numbering is the single
19/// call's).
20fn one_call_imprint_enabled() -> bool {
21    switch!("BREP_OFFSET_ONE_CALL_IMPRINT", true)
22}
23
24thread_local! {
25    static ONE_CALL_RUNS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
26}
27
28
29fn coheres_face_normals(solid: &mut BrepSolid) -> Result<(), KernelRefusal> {
30    for face in solid.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
31        face.same_sense = parameter_space_area(face).or_refuse(KernelStage::Sew, "parameter_space_area")? > 0.0;
32    }
33    // Outward is a PER-SHELL property: a through-hole shelled at both ends
34    // legitimately produces two disjoint closed components (the outer wall
35    // tube and the hole wall tube), and a single global signed-volume flip
36    // cannot orient both.
37    for shell_index in 0..solid.shells.len() {
38        let single = BrepSolid {
39            mass_properties_cache: Default::default(),
40            cells: Default::default(),
41            id: solid.id,
42            vertices: solid.vertices.clone(),
43            edges: solid.edges.clone(),
44            shells: vec![solid.shells[shell_index].clone()],
45            genus: 0,
46            kind: crate::BodyKind::Solid,
47        };
48        // Read for its SIGN only, through the per-face term memo
49        // (`solid_signed_volume_for_sign`: the verdict against the bar is the
50        // exact integral's, and a face read about the same reference before —
51        // the next feature's push, the boolean assembler's own check — is
52        // served its term). The exact read here cost 0.26 s on the shelled-box
53        // report's 34-face shell, 42 of its faces fitted.
54        if crate::signed_volume_against(&single, 0.0).or_refuse(KernelStage::Sew, "solid_signed_volume")? < 0.0 {
55            flip_shell_faces(&mut solid.shells[shell_index])?;
56        }
57    }
58    Ok(())
59}
60
61/// Mint a vertex at every SELF-TOUCH of the source's faces before the shell
62/// reads their trims.
63///
64/// A face whose loops touch at an EDGE INTERIOR is a pinched region: the
65/// reported 2026-09-09 document's r = 6 through-hole kisses both r = 4 fillet
66/// setbacks on the top face, at (16, 20, 10) and (10, 20, 16), with no vertex
67/// there.  The fragment stage's 2D arrangement resolves such a pinch by
68/// carving the touched-off corner into its own region, whose loop walks the
69/// closed hole chain in a PARTIAL run — which `build_loop` can only assemble
70/// when the touch is a vertex of both touching edges, and otherwise refuses
71/// with "chain N fragmented into an incomplete run".
72///
73/// The boolean lane mints that vertex inside `build_imprints`
74/// (`imprint/self_touch.rs`).  Nothing minted it here: the shell fragments
75/// its SOURCE against an EMPTY imprint, and its offset carriers — whose trims
76/// are copied from the source faces — deliberately keep their boundaries
77/// un-split, so both arrived at the arrangement pinched.  Splitting the
78/// source once, before the carriers are built from it, fixes both: every
79/// carrier inherits the split trim by construction.
80///
81/// Returns `None` when no face self-touches, so every part that was never
82/// pinched keeps its exact previous path.  Escape hatch:
83/// `BREP_SELF_TOUCH_SPLIT=0`, the same one the imprint lane honours.
84fn split_self_touching_source(source: &BrepSolid) -> Result<Option<BrepSolid>, KernelRefusal> {
85    if std::env::var("BREP_SELF_TOUCH_SPLIT").as_deref() == Ok("0") {
86        return Ok(None);
87    }
88    // The same derivation `offset_shell_impl` uses for every other band, so
89    // the source scan and the carrier-pair scans agree on what "touching"
90    // means.
91    let scale = crate::solid_scale(source);
92    let tolerance = 1e-7f64.max(scale * 1e-9);
93    let edge_splits = crate::imprint::self_touch_edge_splits(source, SOURCE_OPERAND, tolerance, scale)?;
94    if edge_splits.is_empty() {
95        return Ok(None);
96    }
97    os_debug!(
98        "self-touch: source split on {} edge(s): {:?}",
99        edge_splits.len(),
100        edge_splits
101            .iter()
102            .map(|split| split.edge_id)
103            .collect::<Vec<_>>(),
104    );
105    let mut imprint = empty_imprint();
106    imprint.edge_splits = edge_splits;
107    Ok(Some(apply_edge_splits(source, SOURCE_OPERAND, &imprint)?))
108}
109
110/// How far past the grown outline a planar opening wall that meets a RULED
111/// opening is padded, in units of the offset-skin band the wall selection reads
112/// (see the wall construction).
113///
114/// Measured on the torus wedge through the pipeline, grown by 0.05, 0.1, 0.5
115/// and 0.999 (band 2e-3): a clearance of 2 or 2.5 bands still shreds the cap
116/// into 22 to 36 faces with the area 5% to 11% high; from 4 bands on every
117/// member builds its 6 faces, and from 4 to 32 bands each member's volume moves
118/// by at most 1.2e-7. 16 sits four times above the first clean reading.
119const RULED_NEIGHBOUR_CLEARANCE_BANDS: f64 = 16.0;
120
121/// How far past its opening plane an inward carrier is grown, as a fraction of
122/// the shell distance (see the fall-short reach in the carrier loop).
123const REACH_CLEARANCE: f64 = 0.25;
124
125/// `BREP_OFFSET_EXACT_PLANAR_PCURVES` (default on since the 2026-11-18
126/// promotion; `=0` restores the imprint's pcurves): every
127/// coedge of a planar face the offset BUILT (an offset or a wall, never a
128/// retained source face) takes the EXACT affine image
129/// of its own 3D edge as its pcurve, where that edge lies on the plane.
130///
131/// A plane's trim may still carry the pcurve of the imprint section it was cut
132/// from, and that section need not be the edge the assembly kept: on a boss
133/// under a rim fillet shelled through its bottom, with the boss's one cylinder
134/// face extended to its full domain, the opening wall's arc sat 6.7e-6 off the
135/// cylinder's offset while the edge itself sat on both, and the shell's volume
136/// read up to 3.8e-5 off its oracle depending only on where the cylinder's
137/// seam sat. The image of an edge on its plane is exact (the inverse affine map
138/// of the edge's control net), so the trim no longer depends on the section.
139fn exact_planar_pcurves_on() -> bool {
140    switch!("BREP_OFFSET_EXACT_PLANAR_PCURVES", true)
141}
142
143/// The pass behind [`exact_planar_pcurves_on`]: the number of coedges whose
144/// pcurve changed. A loop with any edge not on its plane within `tolerance`
145/// (the exact lane declines it) keeps every pcurve it has.
146fn exact_planar_pcurves(solid: &mut BrepSolid, built: &HashSet<u64>, tolerance: f64) -> Result<usize, KernelRefusal> {
147    let edges: HashMap<u64, EdgeRecord> = solid.edges.iter().map(|edge| (edge.id, edge.clone())).collect();
148    let mut replaced = 0usize;
149    for shell in &mut solid.shells {
150        for face in &mut shell.faces {
151            if !built.contains(&face.id) || !face.surface.is_affine().or_refuse(KernelStage::Sew, "is_affine")? {
152                continue;
153            }
154            // All or nothing per loop: one declined edge beside replaced ones
155            // would leave a gap in the loop's parameter space.
156            for loop_record in &mut face.loops {
157                let mut exact = Vec::with_capacity(loop_record.coedges.len());
158                for coedge in &loop_record.coedges {
159                    let Some(edge) = edges.get(&coedge.edge_id) else { break };
160                    if edge.degenerate || !(edge.t0 < edge.t1) {
161                        break;
162                    }
163                    let Ok(Some(fit)) = brep_geometry::pcurve::affine_pcurve_on_range(&face.surface, &edge.curve, edge.t0, edge.t1, coedge.forward, tolerance) else {
164                        break;
165                    };
166                    exact.push(fit.curve);
167                }
168                if exact.len() != loop_record.coedges.len() {
169                    continue;
170                }
171                for (coedge, pcurve) in loop_record.coedges.iter_mut().zip(exact) {
172                    coedge.pcurve = pcurve;
173                    replaced += 1;
174                }
175            }
176        }
177    }
178    if replaced > 0 {
179        solid.mass_properties_cache = Default::default();
180    }
181    Ok(replaced)
182}
183
184/// What the pipeline assembles.
185#[derive(Clone, Copy, Debug, Eq, PartialEq)]
186pub(super) enum Body {
187    /// A shell: the retained source faces, their offset skins and the walls
188    /// at the openings, bounding the material between source and offset.
189    Shell,
190    /// The offset body itself: the offset skins alone, closed by their
191    /// mutual sections; `opening_face_ids` are HELD faces, copied at
192    /// distance zero as walls, with no source face assembled and no skin
193    /// flipped. The whole-solid offset and the boolean fallback's offset
194    /// body are built this way.
195    Whole,
196}
197
198
199#[cfg(not(test))]
200fn forced_direct_refusal() -> Option<KernelRefusal> {
201    None
202}
203
204/// `BREP_OFFSET_EVERY_SKIN_PIECE` (default on; `=0` keeps the seed's one
205/// piece): see EVERY SKIN PIECE in the offset selection.
206fn every_skin_piece_enabled() -> bool {
207    crate::switch!("BREP_OFFSET_EVERY_SKIN_PIECE", true)
208}
209
210/// `BREP_OFFSET_STAND_IN_ON_OWN_OFFSET` (default on since the 2026-11-18
211/// promotion; `=0` restores the largest piece): see ON ITS OWN OFFSET in the
212/// offset selection.
213fn stand_in_on_own_offset_on() -> bool {
214    crate::switch!("BREP_OFFSET_STAND_IN_ON_OWN_OFFSET", true)
215}
216
217/// `BREP_OFFSET_EVERY_SEEDED_SKIN_PIECE` (default on; `=0` restores): when an
218/// inward shell's assembly fails, EVERY SKIN PIECE is retried on the seeded
219/// path too. Past 2.0 a reported box and pin model's bore skin comes apart into one piece
220/// per corner channel and the seed answered for one of them. Only as a retry:
221/// a shell the seed's choice closes keeps that answer.
222fn every_seeded_skin_piece_enabled() -> bool {
223    crate::switch!("BREP_OFFSET_EVERY_SEEDED_SKIN_PIECE", true)
224}
225
226/// `BREP_OFFSET_WALL_INSIDE_SOURCE_LANE` (default on; `=0` restores): an
227/// outward shell whose wall selection keeps a fragment inside the source
228/// refuses by name (`offset_shell_wall_inside_source`), which takes the boolean
229/// lane, instead of returning a shell with a fin in it.
230fn wall_inside_source_lane_on() -> bool {
231    crate::switch!("BREP_OFFSET_WALL_INSIDE_SOURCE_LANE", true)
232}
233
234/// How [`offset_shell_with_options`] answers what [`offset_shell`] decides
235/// by convention. The default is [`offset_shell`]'s answer throughout.
236#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
237pub struct ShellOptions {
238    /// Refuse (IllPosed `offset_shell_no_cavity`) an inward shell whose walls
239    /// meet across the whole part, so that no cavity fits. By default the
240    /// kernel answers that with the part itself (the brepbench convention,
241    /// shell/box-walls-meeting); a caller whose shell must leave a cavity asks
242    /// for the refusal.
243    pub refuse_no_cavity: bool,
244}
245
246/// Whether `shelled` is `source` itself: as many faces, each carried on one
247/// of the source's own surfaces (every control point within 1e-12 of the
248/// model's scale of the source face's).
249fn is_the_part_itself(source: &BrepSolid, shelled: &BrepSolid) -> bool {
250    fn faces(solid: &BrepSolid) -> Vec<&FaceRecord> {
251        solid.shells.iter().flat_map(|shell| &shell.faces).collect()
252    }
253    let (before, after) = (faces(source), faces(shelled));
254    if before.len() != after.len() {
255        return false;
256    }
257    let tolerance = 1e-12 * crate::solid_model_scale(source).max(1.0);
258    let same = |a: &crate::NurbsSurface, b: &crate::NurbsSurface| {
259        a.degree_u == b.degree_u
260            && a.degree_v == b.degree_v
261            && a.control_points.len() == b.control_points.len()
262            && a.control_points.iter().zip(&b.control_points).all(|(ra, rb)| {
263                ra.len() == rb.len()
264                    && ra.iter().zip(rb).all(|(p, q)| (p.x - q.x).abs() <= tolerance && (p.y - q.y).abs() <= tolerance && (p.z - q.z).abs() <= tolerance && (p.w - q.w).abs() <= 1e-12)
265            })
266    };
267    after.iter().all(|face| before.iter().any(|original| same(&face.surface, &original.surface)))
268}
269
270/// [`offset_shell`] read with `options`.
271pub fn offset_shell_with_options(
272    source: &BrepSolid,
273    opening_face_ids: &[u64],
274    distance: f64,
275    options: ShellOptions,
276) -> Result<OffsetShellResultRecord, KernelRefusal> {
277    let shelled = offset_shell(source, opening_face_ids, distance)?;
278    // Walls that meet across the whole part answer with the part itself: as
279    // many faces as it has, each on one of its own carriers (a cavity however
280    // thin adds a face or moves one onto a carrier of its own), and its whole
281    // volume. That answer this caller refuses.
282    if options.refuse_no_cavity && distance > 0.0 && is_the_part_itself(source, &shelled.solid) {
283        let before = crate::solid_mass_properties(source).or_refuse(KernelStage::Validate, "solid_mass_properties")?.volume;
284        let after = crate::solid_mass_properties(&shelled.solid).or_refuse(KernelStage::Validate, "solid_mass_properties")?.volume;
285        if before > 0.0 && after >= before * (1.0 - 1e-9) {
286            return Err(KernelRefusal::ill_posed(KernelStage::Validate, "offset_shell_no_cavity", format!(
287                "offset_shell: walls {distance} thick meet across the whole part, leaving no cavity"
288            )));
289        }
290    }
291    Ok(shelled)
292}
293
294pub fn offset_shell(
295    source: &BrepSolid,
296    opening_face_ids: &[u64],
297    distance: f64,
298) -> Result<OffsetShellResultRecord, KernelRefusal> {
299    if let Some(scaled) = crate::rescale::ScaledOffset::of(source, distance, "offset_shell")? {
300        let mut record = offset_shell(&scaled.source, opening_face_ids, scaled.distance).map_err(|error| scaled.refusal(error))?;
301        record.solid = scaled.back(&record.solid, "offset_shell")?;
302        return Ok(record);
303    }
304    let direct = match forced_direct_refusal() {
305        Some(forced) => Err(forced),
306        None => offset_body(source, opening_face_ids, distance, Body::Shell, "offset_shell"),
307    };
308    let mut shelled = offset_shell_lanes(source, opening_face_ids, distance, direct)?;
309    if membrane_shells_on() {
310        // An unchanged body keeps the membrane reading taken on it (one mass
311        // pass instead of two: ~75 ms of shell/rounded-tray's 0.19 s).
312        let membranes = match drop_folded_shells_reading(&mut shelled.solid, distance) {
313            Some(unchanged) => unchanged,
314            None => membrane_shell_indices(&shelled.solid, distance),
315        };
316        let paired = paired_face_ids(&shelled.solid);
317        if !membranes.is_empty() || !paired.is_empty() {
318            for (first, second) in &paired {
319                let shell = shelled.solid.shells.iter().position(|shell| shell.faces.iter().any(|face| face.id == *first));
320                os_debug!(
321                    "membrane pair: faces {first} and {second} in shell {shell:?} of {:?} faces",
322                    shell.map(|index| shelled.solid.shells[index].faces.len())
323                );
324            }
325            return Err(KernelRefusal::unsupported(KernelStage::Validate, "offset_shell_membrane", format!(
326                "offset_shell: at this distance the result has {} shell(s) enclosing no volume and \
327                 {} pair(s) of faces bounded by the same edges{} (zero-thickness membranes \
328                 beside the cavity), which no solid carries",
329                membranes.len(),
330                paired.len(),
331                paired.first().map(|(a, b)| format!(", first faces {a} and {b}")).unwrap_or_default()
332            )));
333        }
334    }
335    Ok(shelled)
336}
337
338/// `BREP_OFFSET_MEMBRANE_SHELLS` (default on; `=0` restores): a shell of the
339/// result that encloses nothing (made only of FOLDED faces, each loop running
340/// along its edges once in each direction, closed by point edges; or of zero
341/// volume over its area; or a bag, its faces pairing up on the same edges) is
342/// removed with the edges and vertices only it used, when the
343/// rest still validates. Otherwise, and for two faces of one real shell bounded
344/// by the same edges (a zero-thickness fin), the shell is refused as a
345/// membrane.
346///
347/// Cause (a reported box and pin model): at 2.38 and 2.40 the result reported
348/// three shells, two of them single folded faces of about 6.5e-6 mm^2 at the
349/// floor/wall corner; at 2.46 (with the corner-debris switch) six more, folded
350/// faces and two-face bags of volume 1e-8 over area 4e-3. None shares an edge
351/// with the cavity's shell. `validate()` accepts them all and the volume is
352/// right, but the shell count is not, nor is anything that walks the shells.
353///
354/// Every test is scaled by the offset distance, since a real piece of the shell
355/// is about |distance| thick: a folded or bag shell is removed only when its
356/// volume is at most 1% of |distance| × its area (a sphere face, whose seam
357/// also runs both ways, encloses the sealed cavity of a sphere-cut shell), and
358/// the zero-volume bar never exceeds 1e-3 × |distance| (a shell 1e-7 thick is
359/// a real sliver, not a membrane).
360fn membrane_shells_on() -> bool {
361    switch!("BREP_OFFSET_MEMBRANE_SHELLS", true)
362}
363
364/// Whether every non-degenerate edge of `face`'s loops is used once forward
365/// and once reversed by the face itself.
366fn face_is_folded(face: &FaceRecord, edges: &HashMap<u64, &EdgeRecord>) -> bool {
367    let mut balance: HashMap<u64, (usize, usize)> = HashMap::default();
368    for coedge in face.loops.iter().flat_map(|l| &l.coedges) {
369        if edges.get(&coedge.edge_id).is_some_and(|edge| edge.degenerate) {
370            continue;
371        }
372        let entry = balance.entry(coedge.edge_id).or_default();
373        if coedge.forward {
374            entry.0 += 1;
375        } else {
376            entry.1 += 1;
377        }
378    }
379    !balance.is_empty() && balance.values().all(|&(forward, reversed)| forward == 1 && reversed == 1)
380}
381
382/// Whether every face of `shell` shares its whole set of non-degenerate edges
383/// with exactly one other face of it: two-sided sheets with nothing between.
384fn shell_is_bag(shell: &ShellRecord, edges: &HashMap<u64, &EdgeRecord>) -> bool {
385    let mut sets: HashMap<Vec<u64>, usize> = HashMap::default();
386    for face in &shell.faces {
387        let mut set: Vec<u64> = face
388            .loops
389            .iter()
390            .flat_map(|l| &l.coedges)
391            .map(|coedge| coedge.edge_id)
392            .filter(|id| !edges.get(id).is_some_and(|edge| edge.degenerate))
393            .collect();
394        set.sort_unstable();
395        set.dedup();
396        if set.is_empty() {
397            return false;
398        }
399        *sets.entry(set).or_default() += 1;
400    }
401    !sets.is_empty() && sets.values().all(|&count| count == 2)
402}
403
404/// Removes the shells made only of folded faces, then the edges and vertices
405/// no remaining face uses. Keeps `solid` unchanged when that would leave no
406/// shell or a result that does not validate. A folded or bag shell qualifies
407/// only when its volume is at most 1% of |distance| × its area.
408pub fn drop_folded_shells(solid: &mut BrepSolid, distance: f64) {
409    drop_folded_shells_reading(solid, distance);
410}
411
412
413/// [`drop_folded_shells`], returning [`membrane_shell_indices`] of `solid`
414/// when it is left unchanged (the reading taken here), `None` when shells
415/// were dropped.
416pub(crate) fn drop_folded_shells_reading(solid: &mut BrepSolid, distance: f64) -> Option<Vec<usize>> {
417    let edges: HashMap<u64, &EdgeRecord> = solid.edges.iter().map(|edge| (edge.id, edge)).collect();
418    let empty = membrane_shell_indices(solid, distance);
419    let folded: Vec<usize> = (0..solid.shells.len())
420        .filter(|&index| {
421            let shell = &solid.shells[index];
422            empty.contains(&index)
423                || ((shell.faces.iter().all(|face| face_is_folded(face, &edges)) || shell_is_bag(shell, &edges))
424                    && shell_volume_and_area(solid, index)
425                        .is_some_and(|(volume, area)| volume.abs() <= 1e-2 * distance.abs() * area))
426        })
427        .collect();
428    if folded.is_empty() || folded.len() == solid.shells.len() {
429        return Some(empty);
430    }
431    let mut trimmed = solid.clone();
432    let mut index = 0;
433    trimmed.shells.retain(|_| {
434        let keep = !folded.contains(&index);
435        index += 1;
436        keep
437    });
438    let used_edges: HashSet<u64> = trimmed
439        .shells
440        .iter()
441        .flat_map(|shell| &shell.faces)
442        .flat_map(|face| &face.loops)
443        .flat_map(|l| &l.coedges)
444        .map(|coedge| coedge.edge_id)
445        .collect();
446    trimmed.edges.retain(|edge| used_edges.contains(&edge.id));
447    let used_vertices: HashSet<u64> = trimmed
448        .edges
449        .iter()
450        .flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id])
451        .collect();
452    trimmed.vertices.retain(|vertex| used_vertices.contains(&vertex.id));
453    crate::boolean::refresh_derived_genus(&mut trimmed);
454    let issues = trimmed.validate();
455    if !issues.is_empty() {
456        os_debug!("folded shells {folded:?} kept: without them the result does not validate: {issues:?}");
457        return Some(empty);
458    }
459    os_debug!("dropped folded shells {folded:?}");
460    *solid = trimmed;
461    None
462}
463
464/// Pairs of faces of one shell bounded by exactly the same non-degenerate
465/// edges: two sides of a zero-thickness fin. By face id.
466pub fn paired_face_ids(solid: &BrepSolid) -> Vec<(u64, u64)> {
467    let mut pairs = Vec::new();
468    let degenerate: HashSet<u64> = solid.edges.iter().filter(|edge| edge.degenerate).map(|edge| edge.id).collect();
469    for shell in &solid.shells {
470        let mut seen: HashMap<Vec<u64>, u64> = HashMap::default();
471        for face in &shell.faces {
472            let mut edges: Vec<u64> = face
473                .loops
474                .iter()
475                .flat_map(|l| &l.coedges)
476                .map(|c| c.edge_id)
477                .filter(|id| !degenerate.contains(id))
478                .collect();
479            edges.sort_unstable();
480            if edges.len() < 2 {
481                continue;
482            }
483            match seen.get(&edges) {
484                Some(&other) => pairs.push((other, face.id)),
485                None => {
486                    seen.insert(edges, face.id);
487                }
488            }
489        }
490    }
491    pairs
492}
493
494/// The volume and area of shell `index` of `solid` on its own.
495fn shell_volume_and_area(solid: &BrepSolid, index: usize) -> Option<(f64, f64)> {
496    let mut alone = solid.clone();
497    alone.shells = vec![solid.shells[index].clone()];
498    crate::solid_mass_properties(&alone).ok().map(|mass| (mass.volume, mass.surface_area))
499}
500
501/// The shells of `solid` that enclose no volume, by index: |V| at most
502/// min(1e-6 × the bounding-box diagonal, 1e-3 × |distance|) × the shell's
503/// area. A shell whose mass properties cannot be measured is never reported.
504pub fn membrane_shell_indices(solid: &BrepSolid, distance: f64) -> Vec<usize> {
505    if solid.vertices.is_empty() {
506        return Vec::new();
507    }
508    let mut lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
509    let mut hi = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
510    for vertex in &solid.vertices {
511        lo = Vec3::new(lo.x.min(vertex.point.x), lo.y.min(vertex.point.y), lo.z.min(vertex.point.z));
512        hi = Vec3::new(hi.x.max(vertex.point.x), hi.y.max(vertex.point.y), hi.z.max(vertex.point.z));
513    }
514    let thickness = (1e-6 * hi.sub(lo).length()).min(1e-3 * distance.abs());
515    (0..solid.shells.len())
516        .filter(|&index| {
517            shell_volume_and_area(solid, index).is_some_and(|(volume, area)| volume.abs() <= thickness * area)
518        })
519        .collect()
520}
521
522fn offset_shell_lanes(
523    source: &BrepSolid,
524    opening_face_ids: &[u64],
525    distance: f64,
526    direct: Result<OffsetShellResultRecord, KernelRefusal>,
527) -> Result<OffsetShellResultRecord, KernelRefusal> {
528    match direct {
529        Ok(result) => Ok(result),
530        // The boolean lane answers the direct construction's own named
531        // refusals; when it refuses too, the direct refusal is the one
532        // reported, because it names the cause.
533        Err(direct) if super::solid::direct_refusal_takes_the_boolean_lane(&direct) => {
534            os_debug!("direct pipeline refused ({direct}); taking the boolean lane");
535            match super::solid::offset_shell_by_boolean(source, opening_face_ids, distance) {
536                Ok(result) => Ok(result),
537                Err(boolean) => {
538                    os_debug!("boolean lane refused too ({boolean})");
539                    // An outward wall through a curved opening on a sphere or
540                    // a cylinder: the grown body cut by the opening's own
541                    // surface (`opening_surface_cut`).
542                    if distance < 0.0
543                        && super::opening_surface_cut::answers(&direct)
544                        && super::opening_surface_cut::opening_surface_cut_on()
545                    {
546                        match super::opening_surface_cut::build(source, opening_face_ids, distance) {
547                            Ok(result) => return Ok(result),
548                            Err(cut) => os_debug!("opening-surface cut refused too ({cut})"),
549                        }
550                    }
551                    Err(direct)
552                }
553            }
554        }
555        Err(direct) => Err(direct),
556    }
557}
558
559/// The pipeline's one timed entry: `offset_shell` and `offset_solid` both run
560/// through it, so the `timing.*` split and the acceptance step are the same.
561/// Lane O row 38's switch, default on since batch 17 (`0`/`off` restores the fit): it asks the offset pipeline's
562/// imprints for the planar-iso lane's exact pcurves (`ImprintOptions::
563/// exact_iso_pcurves`, parity slice 1): a section the lane answers is an
564/// iso-curve of the ruled carrier and an affine image on the plane, so its
565/// pcurves are written down instead of fitted. Booleans keep their own
566/// default; `BREP_EXACT_ISO_PCURVES` still overrides every imprint.
567fn offset_exact_iso_pcurves_on() -> bool {
568    switch!("BREP_OFFSET_EXACT_ISO_PCURVES", true)
569}
570
571
572pub(super) fn offset_body(
573    source: &BrepSolid,
574    opening_face_ids: &[u64],
575    distance: f64,
576    body: Body,
577    entry: &str,
578) -> Result<OffsetShellResultRecord, KernelRefusal> {
579    profile::reset();
580    let full_turn = if super::full_turn::full_turn_revolutions_on() { super::full_turn::full_turn_revolution_source(source)? } else { None };
581    let source = full_turn.as_ref().unwrap_or(source);
582    // Lane P3b row 3: one stderr write per operation for every profile line
583    // emitted below (`crate::imprint::ProfileSink`).
584    let _profile_sink = crate::imprint::ProfileSink::open();
585    let started = web_time::Instant::now();
586    let result = match offset_shell_any_lane(source, opening_face_ids, distance, body) {
587        // A cylinder split along its own seam: refused with the seam where it
588        // is, retried with the two pieces joined on the full turn seamed in
589        // their gap (`full_turn.rs`). Only a refusal is retried.
590        Err(error) if super::full_turn::full_turn_revolutions_on() => match super::full_turn::seam_pieces_joined(source, opening_face_ids)? {
591            Some(joined) => offset_shell_any_lane(&joined, opening_face_ids, distance, body).map_err(|_| error),
592            None => Err(error),
593        },
594        other => other,
595    }
596    .and_then(|result| {
597        let mut clock = web_time::Instant::now();
598        let connected = outward_shell_is_connected(source, distance, &result);
599        profile::lap(&mut clock, profile::ACCEPTANCE);
600        connected.map(|()| result)
601    });
602    profile::add(profile::TOTAL, started.elapsed());
603    profile::report(entry);
604    result
605}
606
607/// Every shell of an OUTWARD result must bound volume. The shell is the grown
608/// body less the source with the openings held, so it can be disconnected
609/// (opening a cylinder's lateral face leaves its two grown caps as two
610/// slabs), but each of its shells encloses material. A shell that encloses
611/// none, a lone face that happened to close, is a fragment of an assembly that
612/// went wrong and still validated. Measured on 2026-09-26: a free-form D whose
613/// fitted opening wall sat within the fit tolerance of its carriers' sections
614/// returned its body plus 62 single-face shells of volume under 3e-24, each
615/// valid, with the right total volume. So this refuses by name for EVERY
616/// outward shell, not only for the lane that produced those.
617pub fn outward_shell_is_connected(
618    source: &BrepSolid,
619    distance: f64,
620    result: &OffsetShellResultRecord,
621) -> Result<(), KernelRefusal> {
622    if distance >= 0.0 || result.solid.shells.len() <= 1 {
623        return Ok(());
624    }
625    let scale = crate::solid_scale(source).max(1.0);
626    let volumes = result
627        .solid
628        .shells
629        .iter()
630        .map(|shell| {
631            let mut one = result.solid.clone();
632            one.shells = vec![shell.clone()];
633            crate::solid_mass_properties(&one)
634                .map(|properties| properties.volume)
635                .or_refuse(KernelStage::Validate, "solid_mass_properties")
636        })
637        .collect::<Result<Vec<f64>, KernelRefusal>>()?;
638    let total = volumes.iter().map(|volume| volume.abs()).sum::<f64>();
639    let floor = (1e-9 * total).max(1e-12 * scale * scale * scale);
640    let empty = volumes.iter().filter(|volume| volume.abs() <= floor).count();
641    if empty == 0 {
642        return Ok(());
643    }
644    Err(refusals::empty_shell(result.solid.shells.len(), empty, floor).into())
645}
646
647fn offset_shell_any_lane(
648    source: &BrepSolid,
649    opening_face_ids: &[u64],
650    distance: f64,
651    body: Body,
652) -> Result<OffsetShellResultRecord, KernelRefusal> {
653    // Pinched source faces are un-modellable by the arrangement until the
654    // touch is a vertex; do it once here so BOTH `offset_shell_impl` attempts
655    // and every carrier built from the source see the same topology.
656    let prepared = split_self_touching_source(source)?;
657    let source = prepared.as_ref().unwrap_or(source);
658    // The revolved-wedge lane answers a SHELL question (the material between
659    // a revolve and its grown image); the offset body takes the pipeline.
660    if body == Body::Whole {
661        // Row 36 (`BREP_OFFSET_SPHERE_BODY`, default off): the offset body of a
662        // ball is the ball scaled about its centre (`sphere_body.rs`); it
663        // declines to the pipeline on anything else.
664        if opening_face_ids.is_empty() {
665            if let Some(result) = sphere_body::sphere_body(source, distance) {
666                return Ok(result);
667            }
668            // `BREP_OFFSET_TORUS_APPLE` (default on; `=0` restores): a whole torus grown
669            // past its hole is the revolved apple (`torus_body.rs`).
670            if let Some(result) = super::torus_body::torus_apple(source, distance) {
671                return Ok(result);
672            }
673        }
674        return imprint_attempts(source, opening_face_ids, distance, body);
675    }
676    // `BREP_OFFSET_BOX_EMPTY_CAVITY` (default on; `=0` restores): an inward shell of a box
677    // whose walls' reach meets across an axis is the box itself, read exactly
678    // (`box_cavity.rs`) in place of the cavity search and its proof.
679    if let Some(unchanged) = super::box_cavity::box_empty_cavity_shell(source, opening_face_ids, distance)? {
680        return Ok(unchanged);
681    }
682    // `BREP_OFFSET_REVOLVED_SHELL` (default on; `=0` restores): an inward shell of a convex
683    // solid of revolution is its section less the cavity, revolved
684    // (`revolved_shell.rs`).
685    if let Some(shell) = super::revolved_shell::revolved_shell(source, opening_face_ids, distance) {
686        return Ok(shell);
687    }
688    // An outward shell of the one circular face of a partial revolve is planar
689    // in the meridian half-plane, fold band and all: build it there and revolve
690    // it once (`revolved_wedge.rs`). Anything else declines and takes the
691    // imprint pipeline, unchanged.
692    if let Some(result) = revolved_wedge::retained_cap_shell(source, opening_face_ids, distance) {
693        return Ok(result);
694    }
695    match revolved_wedge::recognize(source, opening_face_ids, distance) {
696        Ok(revolved_wedge::Recognition::Wedge(wedge)) => {
697            os_debug!("revolved wedge lane: {}", wedge.report());
698            return revolved_wedge::build(&wedge, source);
699        }
700        Ok(revolved_wedge::Recognition::Declined(reason)) => {
701            os_debug!("revolved wedge lane declined: {reason}");
702        }
703        // A source the lane cannot even read is not one it takes; the pipeline
704        // owns every refusal.
705        Err(error) => {
706            os_debug!("revolved wedge lane declined: could not read the source ({error})");
707        }
708    }
709    // `BREP_OFFSET_SPHERE_CUT_SHELL` (default on; `=0` restores): an inward shell of a ball cut by
710    // planes is the source less the moved ball cut by the moved planes
711    // (`sphere_cut_shell.rs`); it declines to the pipeline on anything else.
712    if let Some(result) = sphere_cut_shell::sphere_cut_shell(source, opening_face_ids, distance) {
713        return Ok(result);
714    }
715    // Row 32 (`BREP_OFFSET_PLANAR_SHELL`, default on; `=0` restores): an outward shell of a
716    // convex polyhedron in closed form (`planar_shell.rs`); it declines to the
717    // pipeline on anything else.
718    if let Some(result) = planar_shell::planar_shell(source, opening_face_ids, distance) {
719        return Ok(result);
720    }
721    imprint_attempts(source, opening_face_ids, distance, body)
722}
723
724
725fn imprint_attempts(
726    source: &BrepSolid,
727    opening_face_ids: &[u64],
728    distance: f64,
729    body: Body,
730) -> Result<OffsetShellResultRecord, KernelRefusal> {
731    // An OUTWARD pass that refused after holding back a concave side runs once
732    // more with it continued round its arc (`concave_arc_retry_on`); the
733    // first refusal stands if that fails too.
734    let held = super::outward_side_widen::concave_held();
735    let first = imprint_attempts_once(source, opening_face_ids, distance, body);
736    match first {
737        Err(error) if distance < 0.0 || body == Body::Whole => {
738            if !super::outward_side_widen::concave_arc_retry_on() || super::outward_side_widen::concave_held() == held {
739                return Err(error);
740            }
741            os_debug!("outward pass refused with concave sides held back ({error}); retrying with them continued round their arc");
742            match super::outward_side_widen::with_concave_arc(|| imprint_attempts_once(source, opening_face_ids, distance, body)) {
743                Ok(result) => Ok(result),
744                Err(_) => Err(error),
745            }
746        }
747        other => other,
748    }
749}
750
751fn imprint_attempts_once(
752    source: &BrepSolid,
753    opening_face_ids: &[u64],
754    distance: f64,
755    body: Body,
756) -> Result<OffsetShellResultRecord, KernelRefusal> {
757    // First try with oblique hole-wall carriers extended past their opening
758    // planes (the lane that closes tilted/conical through-holes). If that
759    // extension fired but the arrangement could not assemble the harder
760    // configuration it produced (e.g. the extended bore genuinely intersects
761    // other offset walls), fall back to the un-extended pipeline so every
762    // previously-supported shape keeps its exact path and every refusal keeps
763    // the canonical honesty-gate message.
764    let mut extension_fired = false;
765    let mut reflex_rebuilds = 0usize;
766    let mut shadowed_points = Vec::new();
767    let mut omitted = HashSet::default();
768    let mut vacated_notes = Vec::new();
769    let result = match offset_shell_impl(
770        source,
771        opening_face_ids,
772        distance,
773        body,
774        true,
775        &mut extension_fired,
776        &mut reflex_rebuilds,
777        &HashSet::default(),
778        &HashSet::default(),
779        false,
780        &mut shadowed_points,
781        &mut omitted,
782        &mut vacated_notes,
783    ) {
784        Ok(result) => {
785            // Attribution marker: which pipeline produced this result. A
786            // retry-produced Ok can silently mask a broken extension lane —
787            // always say which attempt won. The reflex-rebuild count rides
788            // along because that lane fires on BOTH attempts: "extension
789            // idle" alone would misread as "the plain pipeline did this".
790            os_debug!(
791                "offset_shell result: FIRST attempt (extension {}, reflex-rebuilt {})",
792                if extension_fired { "fired" } else { "idle" },
793                reflex_rebuilds,
794            );
795            Ok(result)
796        }
797        Err(error) if extension_fired => {
798            os_debug!("extended pipeline failed ({error}); retrying without carrier extension");
799            let mut unused = false;
800            let mut retry_reflex = 0usize;
801            shadowed_points.clear();
802            omitted.clear();
803            let retried = offset_shell_impl(
804                source,
805                opening_face_ids,
806                distance,
807                body,
808                false,
809                &mut unused,
810                &mut retry_reflex,
811                &HashSet::default(),
812                &HashSet::default(),
813                false,
814                &mut shadowed_points,
815                &mut omitted,
816                &mut vacated_notes,
817            );
818            os_debug!(
819                "offset_shell result: RETRY without extension ({}, reflex-rebuilt {retry_reflex})",
820                if retried.is_ok() { "ok" } else { "err" },
821            );
822            retried
823        }
824        Err(error) => Err(error),
825    };
826    // A refusal from a shell whose selection saw two offsets CROSS inside
827    // material thinner than twice the distance says so first: a rib thinner
828    // than 2d shelled inward is that configuration, and the assembly's own
829    // message names only the symptom. A refusal that already names its cause
830    // keeps it. The crossing is looked for here, on the failure path only.
831    match result {
832        // A refusal that already names its CAUSE keeps its own sentence; one
833        // that names a symptom ("connector edge left its plane", an assembly
834        // message) is worth a cause in front of it. Reading the whole prefix as
835        // "anything this module wrote" was too wide: the twin bosses came out
836        // led by a notch sentence when their cause was the shadow cascade, and
837        // the partial cone lost its junction cause behind a connector's.
838        // Each cause is put IN FRONT of the symptom with `with_message`, so the
839        // symptom's class (an assembly's `NonIntegralGenus`, …) survives.
840        Err(error) if !refusal_names_its_cause(&error.message) => {
841            let crossing = name_offset_crossing(source, opening_face_ids, distance, &shadowed_points);
842            let junction = crossing
843                .is_none()
844                .then(|| name_retained_opening_junction(source, opening_face_ids, distance))
845                .flatten();
846            Err(cause_in_front(error, crossing, junction, vacated_notes.first()))
847        }
848        result => result,
849    }
850}
851
852/// The symptom `error` with the first named cause IN FRONT of it: an offset
853/// crossing, else a retained/opening junction, else a vacated rim's note.
854/// Each prefix is a `with_message`, so the symptom's CLASS (an assembly's
855/// `NonIntegralGenus`, …) survives the sentence put before it.
856pub fn cause_in_front(
857    error: KernelRefusal,
858    crossing: Option<String>,
859    junction: Option<String>,
860    note: Option<&String>,
861) -> KernelRefusal {
862    if let Some(crossing) = crossing {
863        return error.with_message(|error| {
864            format!(
865                "offset_shell: {crossing}; a skin partly shadowed that way is not yet \
866                 assembled ({error})"
867            )
868        });
869    }
870    if let Some(junction) = junction {
871        return error.with_message(|error| format!("offset_shell: {junction} ({error})"));
872    }
873    // A rim the closure could not bridge, with what it measured, in front of
874    // whatever the assembly then said about the hole it left.
875    match note {
876        Some(note) => error.with_message(|error| {
877            format!(
878                "offset_shell: a rim vacated by an omitted support was left open — {note} \
879                 ({error})"
880            )
881        }),
882        None => error,
883    }
884}
885
886/// The refusals this module's own cause-naming lanes produce. Anything else is
887/// a symptom another stage reported, and takes a cause in front of it.
888fn refusal_names_its_cause(error: &str) -> bool {
889    [
890        " coincide near ",
891        " touch tangentially near ",
892        "is sealed off from the opening",
893        "cannot tell whether",
894        "omitting the shadowed offsets of source faces",
895        "reads shadowed over its whole extent, so omitting it again",
896        "nested passes without settling",
897        "no retained face keeps any offset skin",
898        "is shadowed at every one of its",
899        "a rim vacated by an omitted support was left open",
900        "junction, so its offset ends inside the cavity",
901        "cross near",
902        "which meet tangentially along source edge",
903        // The opening-wall lane's own named refusals, so a cause of mine never
904        // arrives in front of one of theirs.
905        "folds where the carve",
906        "is curved and not a ruled surface",
907        "cannot be built",
908    ]
909    .iter()
910    .any(|name| error.contains(name))
911}
912
913/// The deepest nesting of `offset_shell_impl` passes one shell may take.
914/// Every re-run changes an input that only grows (the omitted supports, the
915/// cavity bounds, the every-seed flag), so the depth is bounded by the face
916/// count already; this bound makes a re-run that fails to grow its input a
917/// named refusal instead of a stack overflow, whatever the cause.
918pub(super) const MAXIMUM_PASS_DEPTH: usize = 24;
919
920std::thread_local! {
921    static PASS_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
922}
923
924/// One nested pass, counted while it lives.
925struct PassDepth;
926
927impl PassDepth {
928    fn enter() -> Result<Self, KernelRefusal> {
929        let depth = PASS_DEPTH.with(|cell| {
930            let depth = cell.get() + 1;
931            cell.set(depth);
932            depth
933        });
934        let pass = PassDepth;
935        if depth > MAXIMUM_PASS_DEPTH {
936            return Err(KernelRefusal::unsupported(KernelStage::Select, refusals::PASS_BUDGET, format!(
937                "offset_shell: the construction re-ran {MAXIMUM_PASS_DEPTH} nested passes without settling \
938                 which offset supports to omit"
939            )));
940        }
941        Ok(pass)
942    }
943}
944
945impl Drop for PassDepth {
946    fn drop(&mut self) {
947        PASS_DEPTH.with(|cell| cell.set(cell.get().saturating_sub(1)));
948    }
949}
950
951
952
953fn offset_shell_impl(
954    source: &BrepSolid,
955    opening_face_ids: &[u64],
956    distance: f64,
957    body: Body,
958    extend_oblique_carriers: bool,
959    extension_fired: &mut bool,
960    reflex_rebuilds: &mut usize,
961    shadowed_supports: &HashSet<u64>,
962    cavity_bounds: &HashSet<u64>,
963    every_seeded_piece: bool,
964    shadowed_points: &mut Vec<(Vec3, u64)>,
965    omitted_supports: &mut HashSet<u64>,
966    vacated_notes: &mut Vec<String>,
967) -> Result<OffsetShellResultRecord, KernelRefusal> {
968    let _pass = PassDepth::enter()?;
969    profile::attempt();
970    let _sharp_rims = super::carriers::SharpOpeningRims::set(if super::carriers::ruled_miter_on() {
971        super::carriers::sharp_opening_rims(source, opening_face_ids)
972    } else {
973        HashSet::default()
974    });
975    let mut clock = web_time::Instant::now();
976    omitted_supports.clone_from(shadowed_supports);
977    vacated_notes.clear();
978    if !distance.is_finite() || distance.abs() <= MINIMUM_DISTANCE {
979        return Err(KernelRefusal::input(KernelStage::Collect, "offset_shell_distance", "offset_shell: distance must be finite and non-zero"));
980    }
981    if opening_face_ids.is_empty() && body == Body::Shell {
982        return Err(KernelRefusal::input(KernelStage::Collect, "offset_shell_no_opening", "offset_shell: at least one opening face is required"));
983    }
984    let source_faces = source
985        .shells
986        .iter()
987        .flat_map(|shell| &shell.faces)
988        .collect::<Vec<_>>();
989    let opening_set = opening_face_ids.iter().copied().collect::<HashSet<_>>();
990    if opening_set
991        .iter()
992        .any(|id| !source_faces.iter().any(|face| face.id == *id))
993    {
994        return Err(KernelRefusal::input(KernelStage::Collect, "offset_shell_foreign_opening", "offset_shell: opening face does not belong to source"));
995    }
996    let retained = source_faces
997        .iter()
998        .filter(|face| !opening_set.contains(&face.id))
999        .map(|face| face.id)
1000        .collect::<Vec<_>>();
1001    if retained.is_empty() {
1002        return Err(refusals::no_retained_face().into());
1003    }
1004    let mut carriers = Vec::new();
1005    let mut open_section_reach = false;
1006    if distance < 0.0 && std::env::var("BREP_OFFSET_OPEN_SECTION_REACH").as_deref() != Ok("0") {
1007        for face in &source_faces {
1008            if retained.contains(&face.id) && open_profile_has_construction_headroom(face)? {
1009                open_section_reach = true;
1010                break;
1011            }
1012        }
1013    }
1014    // Faces whose folded part was carved away, by source face id. Later stages
1015    // that read a retained face's TRIM — the apex-cap scan below is the one —
1016    // must read the carved trim, not the one the source still carries.
1017    let mut carved_supports = HashMap::<u64, FaceRecord>::default();
1018    // Lane O item 705: (neighbour face, opening face, rim edge) of every
1019    // tangent junction with a curved opening the neighbour cannot reach.
1020    let mut tangent_rim_rounds: Vec<(u64, u64, u64)> = Vec::new();
1021    // Supports omitted because their offset collapsed (`planar_rim_tube`).
1022    let mut collapsed_supports: Vec<u64> = Vec::new();
1023    // The carriers that are such tubes, by index, with the opening each
1024    // tube's mouth lies on.
1025    let mut rim_tubes: HashMap<usize, u64> = HashMap::default();
1026    // The tubes of SURVIVING rounds, by carrier index: such a tube rides its
1027    // round's id, so reading it shadowed must drop only the tube, never the
1028    // round's own offset.
1029    let mut surviving_tubes = HashSet::<usize>::default();
1030    // The carriers of a BAND carve's kept pieces (whole body only), by index:
1031    // one wholly shadowed piece drops alone, never its source face's others.
1032    let mut band_pieces = HashSet::<usize>::default();
1033    let mut shielded_cusps = HashSet::<u64>::default();
1034
1035    for face_id in &retained {
1036        let face = source_faces.iter().find(|face| face.id == *face_id).unwrap();
1037        profile::lap(&mut clock, profile::CARRIER_TRIM);
1038        let collapsed = profile::detail("offset_support_collapsed", || offset_support_collapsed(face, distance))?;
1039        profile::lap(&mut clock, profile::CARRIER_REGULARITY);
1040        if collapsed {
1041            os_debug!("omitting collapsed offset support for source face {face_id}");
1042            collapsed_supports.push(*face_id);
1043            continue;
1044        }
1045        // A support a previous pass found SHADOWED contributes no skin, and its
1046        // carrier must not imprint its neighbours either — see the selection.
1047        if shadowed_supports.contains(face_id) {
1048            os_debug!("omitting shadowed offset support for source face {face_id}");
1049            continue;
1050        }
1051        // A planar carrier whose source face meets a neighbour at a REFLEX
1052        // (concave) edge extends its trim by |distance|: at such a junction
1053        // the offset skin must GROW past the source footprint to meet the
1054        // neighbour's offset (a pocket wall's source [5,15] → skin
1055        // [3.5,16.5]); a source-sized trim leaves a gap no miter can bridge.
1056        // The surplus at the face's convex ends is clipped by the imprints +
1057        // on-skin filter. Convex-only faces keep their exact source-sized
1058        // trim — extending them perturbs delicately-selected fragment
1059        // landscapes for no benefit.
1060        let miter = source_faces
1061            .iter()
1062            .find(|face| face.id == *face_id)
1063            .map(|face| face_reflex_miter_tan(source, face))
1064            .transpose()?
1065            .flatten();
1066        // The offsets of two faces joined at a reflex edge meet d·tan(θn/2)
1067        // past the source rim — d only for a perpendicular join. Scale the
1068        // extension to the worst sampled miter (×1.5 headroom so the true
1069        // intersection lands strictly INSIDE the extended trim, never on its
1070        // boundary where the arrangement drops boundary-coincident cuts) and
1071        // cap it: a near-tangential join would ask for an unbounded trim.
1072        let reflex_extension = miter.map(|worst_tan| {
1073            (distance.abs() * worst_tan * 1.5)
1074                .max(distance.abs())
1075                .min(distance.abs() * 12.0)
1076        });
1077        if let Some(extension) = reflex_extension {
1078            os_debug!("carrier for src face {face_id}: reflex-extended by {extension:.4}");
1079        }
1080        // OUTWARD: every retained carrier grows by |distance| across its
1081        // sharp and opening-facing sides (the offsets of a convex junction
1082        // meet past both source rims; a wall plane cuts the surplus), and
1083        // by nothing across a smooth junction into a retained neighbour —
1084        // see `outward_carrier_extension`. A reflex junction needs no
1085        // outward growth at all (those offsets cross inside the trims).
1086        let mut curved_reach = None;
1087        let planar_reach = planar_opening_reach(face, &source_faces, &opening_set, distance)?;
1088        let mut thin_padded = false;
1089        let extension = if distance < 0.0 {
1090            outward_carrier_extension(source, face, &source_faces, &opening_set, distance.abs())?
1091        } else {
1092            let mut inward = crate::CarrierExtension::uniform(reflex_extension.unwrap_or(0.0));
1093            // Only a carrier that becomes its trim box's full rectangle (an
1094            // affine plane with a curved outline element, below) has the box's
1095            // room past a reflex rim INSIDE the box; a slid trim (a straight
1096            // L-shaped outline) needs every side's pad for its inner corners.
1097            if reflex_extension.is_some()
1098                && super::carrier_rebuild::reflex_pad_convex_sides_on()
1099                && face.surface.is_affine().or_refuse(KernelStage::Refine, "is_affine")?
1100                && outline_has_curved_element(source, face)?
1101            {
1102                let [u_min, u_max, v_min, v_max] = super::carrier_rebuild::convex_box_sides(source, face, reflex_extension.unwrap_or(0.0))?;
1103                // Never every side: an all-zero extension is not a carrier
1104                // the size of its trim but NO slide at all, which leaves an
1105                // affine plane at its whole source net (a boss's floor, a
1106                // third of its plane's domain, ran far past its convex rims
1107                // and the shell crossed itself). A face
1108                // whose sides are all convex keeps the uniform pad.
1109                if !(u_min && u_max && v_min && v_max) {
1110                    if u_min { inward.u_min = 0.0; }
1111                    if u_max { inward.u_max = 0.0; }
1112                    if v_min { inward.v_min = 0.0; }
1113                    if v_max { inward.v_max = 0.0; }
1114                }
1115                os_debug!("carrier for src face {face_id}: reflex pad u=({:.4},{:.4}) v=({:.4},{:.4})", inward.u_min, inward.u_max, inward.v_min, inward.v_max);
1116            }
1117            // `BREP_OFFSET_THIN_SKIN_PAD` (default on; `=0` restores): a skin thinner than
1118            // the fragmenter's graze band is padded past its source rims
1119            // (`thin_skin_pad`), so its sections end far from its corners.
1120            if let Some(pad) = thin_skin_pad(source, face, distance)? {
1121                inward = crate::CarrierExtension { u_min: inward.u_min.max(pad), u_max: inward.u_max.max(pad), v_min: inward.v_min.max(pad), v_max: inward.v_max.max(pad) };
1122                os_debug!("carrier for src face {face_id}: thin skin padded by {pad:.6}");
1123                thin_padded = true;
1124            }
1125            if let Some(reach) = planar_reach {
1126                let grown = reach + REACH_CLEARANCE * distance;
1127                inward = crate::CarrierExtension { u_min: inward.u_min.max(grown), u_max: inward.u_max.max(grown), v_min: inward.v_min.max(grown), v_max: inward.v_max.max(grown) };
1128                os_debug!("carrier for src face {face_id}: planar reach to its opening {reach:.6}");
1129            }
1130            if reflex_extension.is_some() {
1131                let [u_min, u_max, v_min, v_max] =
1132                    apex_corner_reach(source, face, &source_faces, &opening_set, distance)?;
1133                if u_min.max(u_max).max(v_min).max(v_max) > 0.0 {
1134                    inward.u_min = inward.u_min.max(u_min);
1135                    inward.u_max = inward.u_max.max(u_max);
1136                    inward.v_min = inward.v_min.max(v_min);
1137                    inward.v_max = inward.v_max.max(v_max);
1138                    os_debug!(
1139                        "carrier for src face {face_id}: apex corner reach u=({:.4},{:.4}) v=({:.4},{:.4})",
1140                        inward.u_min, inward.u_max, inward.v_min, inward.v_max,
1141                    );
1142                }
1143            }
1144            // An INWARD carrier that falls short of the planar opening it meets
1145            // is grown until it crosses that plane, so the imprint cuts the
1146            // skin there instead of leaving a rim for the ruled weld to cork
1147            // below the opening (`fallshort_opening_reach`).
1148            if let Some((at_v_max, reach)) =
1149                fallshort_opening_reach(source, face, &source_faces, &opening_set, distance)?
1150            {
1151                // Past the plane by a quarter of the shell's own thickness, so
1152                // the section is strictly inside the carrier's trim rather than
1153                // on its boundary. Measured 2026-09-17 over the offset-shell
1154                // suite: every fraction from 0.01 to 2.0 of |d| gives the same
1155                // 73 passing members, while a margin sized in COINCIDENCE BANDS
1156                // (1 to 32 of them, 2e-5 each here) breaks the sphere-under-
1157                // frustum member by 9.4e-2 — the fragile margins are the ones
1158                // far below the construction's own length.
1159                let grown = reach + REACH_CLEARANCE * distance.abs();
1160                if at_v_max {
1161                    inward.v_max = inward.v_max.max(grown);
1162                } else {
1163                    inward.v_min = inward.v_min.max(grown);
1164                }
1165                os_debug!(
1166                    "carrier for src face {face_id}: inward reach to its opening plane {reach:.6}                      at v_{} ",
1167                    if at_v_max { "max" } else { "min" },
1168                );
1169            }
1170            // A CURVED opening has no such construction, and the pipeline
1171            // closes the cavity with whatever completion reaches for: measured
1172            // 7.6% short on the hemisphere cup shelled through its dome.
1173            if let Some((opening, gap)) =
1174                offset_falls_short_of_curved_opening(source, face, &source_faces, &opening_set, distance)?
1175            {
1176                if std::env::var("BREP_OFFSET_CURVED_REACH").as_deref() != Ok("0") {
1177                    curved_reach = curved_opening_reach_source(source, face, distance)?;
1178                }
1179                // `BREP_OFFSET_CURVED_RULED_REACH` (default on; `=0` restores): where the
1180                // rectangle continuation declines (a u-closed band, a tangent
1181                // junction), a v-ruled carrier is grown along its rulings
1182                // until it crosses the curved opening, as the planar reach
1183                // does for a plane (`curved_fallshort_reach`).
1184                let mut ruled_reach = false;
1185                if curved_reach.is_none() {
1186                    if let Some((at_v_max, reach)) =
1187                        curved_fallshort_reach(source, face, &source_faces, &opening_set, distance)?
1188                    {
1189                        let grown = reach + REACH_CLEARANCE * distance.abs();
1190                        if at_v_max {
1191                            inward.v_max = inward.v_max.max(grown);
1192                        } else {
1193                            inward.v_min = inward.v_min.max(grown);
1194                        }
1195                        ruled_reach = true;
1196                        os_debug!(
1197                            "carrier for src face {face_id}: ruled reach to its curved opening {opening} {reach:.6} at v_{}",
1198                            if at_v_max { "max" } else { "min" },
1199                        );
1200                    }
1201                }
1202                // Lane O item 705 (`BREP_OFFSET_TANGENT_RIM_ROUND`, default off):
1203                // a face that meets its curved opening TANGENTIALLY never
1204                // reaches it — its skin runs parallel to the opening at
1205                // exactly d — and the wall there is a round of radius d about
1206                // the rim (`rim_round.rs`). Record the rim; the round carrier
1207                // is emitted beside the apex caps, and this face's carrier is
1208                // built as it is.
1209                if curved_reach.is_none() && !ruled_reach && super::rim_round::tangent_rim_round_enabled() {
1210                    for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
1211                        let Some((mate, mate_use)) = junction_mate(&source_faces, face, coedge.edge_id) else {
1212                            continue;
1213                        };
1214                        if mate.id != opening || !uses_are_tangent(face, coedge, mate, mate_use)? {
1215                            continue;
1216                        }
1217                        os_debug!("tangent rim round: source face {face_id} meets opening {opening} tangentially along edge {}", coedge.edge_id);
1218                        tangent_rim_rounds.push((*face_id, opening, coedge.edge_id));
1219                    }
1220                }
1221                if curved_reach.is_none() && !ruled_reach && !tangent_rim_rounds.iter().any(|(id, _, _)| id == face_id) {
1222                    return Err(KernelRefusal::unsupported(KernelStage::Refine, "offset_shell_curved_opening_short", format!(
1223                        "offset_shell: the offset skin of source face {face_id} stops {gap:.3e} short of \
1224                         curved opening face {opening}; only a planar opening's skin is grown to meet it"
1225                    )));
1226                }
1227            }
1228            inward
1229        };
1230        if distance < 0.0 {
1231            os_debug!(
1232                "carrier for src face {face_id}: outward extension u=({:.3},{:.3}) v=({:.3},{:.3})",
1233                extension.u_min,
1234                extension.u_max,
1235                extension.v_min,
1236                extension.v_max,
1237            );
1238        }
1239        // CARVE: a support whose offset folds over PART of its trim keeps the
1240        // regular part and drops the rest, instead of being built whole with
1241        // the fold in it. The carrier is built over the CARVED source, so the
1242        // trim it clones stops at the fold locus — and, because that trim no
1243        // longer reaches past the offset's pinch, `offset_surface`'s apex-cone
1244        // pinch retrim does not fire and the cloned pcurves still name the
1245        // pointwise offset.
1246        //
1247        // A carve that cannot be made is not a licence to build the folded
1248        // support anyway: the refusal is the answer, because a carrier with an
1249        // inverted patch in it welds into a shell that validates and bounds the
1250        // wrong solid.
1251        profile::lap(&mut clock, profile::CARRIER_TRIM);
1252        let carved = profile::detail("carve_folded_support", || carve_shell_support(source, face, distance, opening_face_ids, body == Body::Whole))?;
1253        profile::lap(&mut clock, profile::CARRIER_REGULARITY);
1254        // A CUT RIM — the face's rim with a planar opening running across
1255        // its surface rather than along a v end — has the trim rebuilt over
1256        // the surface's full rectangle so the opening plane truncates the
1257        // offset skin (`cut_rim_full_rectangle_source`); like the carve, a
1258        // substitute source the carrier is built over.
1259        let cut_rim = if carved.is_none() && curved_reach.is_none() {
1260            cut_rim_full_rectangle_source(source, face, &source_faces, &opening_set, distance)?
1261        } else {
1262            None
1263        };
1264        // A curved face's SHARP outward u-side: the carrier is built over the
1265        // surface continued past it, so it reaches the mitre with its sharp
1266        // neighbour's offset (`sharp_side_continued_source`). Its INWARD
1267        // reflex u-side widens the trim inside the surface's own domain
1268        // instead (`reflex_side_widened_source`).
1269        let sharp_side = if carved.is_none() && cut_rim.is_none() && curved_reach.is_none() {
1270            match sharp_side_continued_source(source, face, &source_faces, &opening_set, distance, &extension)? {
1271                Some(continued) => Some(continued),
1272                None => match band_reach_continued_source(source, face, distance, &extension)? {
1273                    Some(widened) => Some(widened),
1274                    None => match reflex_side_widened_source(source, face, &source_faces, &opening_set, distance, &extension)? {
1275                        Some(widened) => Some(widened),
1276                        None => super::outward_side_widen::outward_sharp_side_widened_source(
1277                            source,
1278                            face,
1279                            &source_faces,
1280                            &opening_set,
1281                            distance,
1282                            &extension,
1283                        )?,
1284                    },
1285                },
1286            }
1287        } else {
1288            None
1289        };
1290        let carrier_source = match (&carved, &cut_rim) {
1291            (None, None) if curved_reach.is_some() => curved_reach.as_ref().unwrap(),
1292            (None, None) if sharp_side.is_some() => sharp_side.as_ref().unwrap(),
1293            (None, Some(rebuilt)) => rebuilt,
1294            (Some(carved), _) => {
1295                os_debug!(
1296                    "carving the fold off source face {face_id}: {:.1}% of its trim kept, \
1297                     {} new boundary pcurve(s)",
1298                    carved.kept_fraction * 100.0,
1299                    carved.fold_boundary
1300                );
1301                carved_supports.insert(*face_id, carved.face.clone());
1302                if carved.shielded_cusp {
1303                    shielded_cusps.insert(*face_id);
1304                }
1305                &carved.solid
1306            }
1307            (None, None) => source,
1308        };
1309        profile::lap(&mut clock, profile::CARRIER_TRIM);
1310        let (mut carrier, lane) = carrier_solid_sided_lane(carrier_source, *face_id, distance, &extension)?;
1311        os_debug!(
1312            "carrier for src face {face_id}: lane {lane:?} carved {} surface u {:?} v {:?} source face u {:?} v {:?}",
1313            carved.is_some(),
1314            carrier.shells[0].faces[0].surface.domain_u().ok(),
1315            carrier.shells[0].faces[0].surface.domain_v().ok(),
1316            carrier_source.shells.iter().flat_map(|shell| &shell.faces).find(|f| f.id == *face_id).and_then(|f| f.surface.domain_u().ok()),
1317            carrier_source.shells.iter().flat_map(|shell| &shell.faces).find(|f| f.id == *face_id).and_then(|f| f.surface.domain_v().ok()),
1318        );
1319        profile::carrier_built(lane, clock.elapsed());
1320        clock = web_time::Instant::now();
1321        if (distance < 0.0 || reflex_extension.is_some()) && face.surface.is_affine().or_refuse(KernelStage::Sew, "is_affine")? {
1322            // PADDED planes: the pad slides the plane's net while the trim's
1323            // loops are cloned in uv, so an INTERIOR loop (a bore or boss rim
1324            // in the face) is carried outward with the grown outline instead
1325            // of following the neighbour's offset.
1326            //   OUTWARD: a bore's rim grew (r=4.68 → 5.15) while the shrunk
1327            //   offset bore (r=3.68) that must hole this plane fell inside the
1328            //   enlarged void, so neither the imprint nor the orphan-rim weld
1329            //   could cut it.
1330            //   INWARD, reflex-extended: the same slide moves a REFLEX hole
1331            //   rim the wrong way — a sphere sitting under a frustum's base
1332            //   annulus (the user's 2026-09-07 document) had its r=8.3 rim
1333            //   scaled to 9.22 while the shrunk offset sphere (r=7.3) crosses
1334            //   the offset plane at r=7.23, inside the enlarged hole: the
1335            //   pair imprint found nothing and the rim stayed one-use.
1336            // Drop the interior loops (as the wall carriers do): the
1337            // neighbour's carrier imprints — or its rim, welded in as a
1338            // hole — cut the true opening, and the seeded selection drops
1339            // the disk over it. A CONVEX interior rim on the same face (a
1340            // through-bore in a pocket floor) is safe to drop too: its
1341            // offset bore imprints at r+d and the ring inside is rejected by
1342            // class (Out) or by the on-skin filter, no seed involved.
1343            drop_wall_interior_loops(&mut carrier)?;
1344            // A free-form outline grown uniformly outward is trimmed by its
1345            // outline OFFSET, not the slid net's scaled trim
1346            // (`outline_offset_carrier`).
1347            let pads = [extension.u_min, extension.u_max, extension.v_min, extension.v_max];
1348            let widest = pads.iter().copied().fold(f64::NEG_INFINITY, f64::max);
1349            let narrowest = pads.iter().copied().fold(f64::INFINITY, f64::min);
1350            // `BREP_OFFSET_CONVEX_POLYGON_OUTLINE`: pads equal but for their last
1351            // bits (a tetrahedron's turned sides read 2.121 four ways, not
1352            // bit-equal) are the uniform pad too.
1353            let uniform = (extension.u_min == extension.u_max
1354                && extension.u_min == extension.v_min
1355                && extension.u_min == extension.v_max)
1356                || (convex_polygon_outline_enabled() && widest - narrowest <= 1e-9 * widest.abs());
1357            if distance < 0.0 && uniform {
1358                // Past the walls' sections by the same clearance a planar
1359                // neighbour of a ruled wall gets, so each section lies
1360                // strictly INSIDE the fitted trim rather than on it.
1361                let clearance =
1362                    RULED_NEIGHBOUR_CLEARANCE_BANDS * offset_skin_band(crate::solid_scale(source), distance);
1363                if let Some(rebuilt) = outline_offset_carrier(source, face, widest, clearance, &carrier)? {
1364                    os_debug!(
1365                        "carrier for src face {face_id}: outline trimmed by its offset by {:.4}",
1366                        widest + clearance
1367                    );
1368                    carrier = rebuilt;
1369                } else if super::outward_side_widen::slid_trim_falls_short(
1370                    source,
1371                    face,
1372                    &source_faces,
1373                    &carrier,
1374                    distance,
1375                    narrowest,
1376                )? {
1377                    // `BREP_OFFSET_OUTWARD_SIDE_WIDEN`: a slid trim short of
1378                    // its pad takes the plane's rectangle, and the
1379                    // neighbours' offsets cut the skin from it.
1380                    os_debug!("carrier for src face {face_id}: slid trim falls short, full rectangle");
1381                    carrier = full_rectangle_face(&carrier, &carrier.shells[0].faces[0])?;
1382                    // Only the rectangle's own edges: a section along the
1383                    // replaced trim's records would be dropped as lying on
1384                    // this carrier's boundary.
1385                    super::outward_side_widen::keep_used_edges(&mut carrier);
1386                }
1387            } else if distance < 0.0 && nonuniform_slid_trim_on() && super::outward_side_widen::slid_trim_falls_short(
1388                source,
1389                face,
1390                &source_faces,
1391                &carrier,
1392                distance,
1393                narrowest,
1394            )? {
1395                // The same fallback for a NON-uniform extension (a drafted
1396                // neighbour pads one side more): the rectangle does not depend
1397                // on the pads being equal. Measured on a block leaning out 1
1398                // over its height 6, opened through an end face, with a slot
1399                // through its top running out of the far end: the top's slid
1400                // trim kept its notch at the slot wall while the wall's offset
1401                // stood 1 past it, and the shell refused with open edges along
1402                // that line; with the side vertical the extension is uniform
1403                // and this fallback already built it.
1404                os_debug!("carrier for src face {face_id}: slid trim falls short (non-uniform extension), full rectangle");
1405                carrier = full_rectangle_face(&carrier, &carrier.shells[0].faces[0])?;
1406                super::outward_side_widen::keep_used_edges(&mut carrier);
1407            }
1408        }
1409        // An inward reflex junction needs a construction plane extending PAST
1410        // the source rim. Sliding the net under a free-form trim scales that
1411        // trim instead: a notched revolve cap's notch grows, and clips away the
1412        // sections with the box's offsets. Even its curved convex boundary can
1413        // fall inside the neighbouring offset section after that scaling.
1414        // Use the extended plane's full rectangle and let the neighbouring
1415        // carriers cut the skin. The source face and the offset surface stay
1416        // unchanged. Circular outlines need the same construction: scaling a
1417        // reflex arc can also clip away its offset cylinder's section. Unlike
1418        // an outline offset, this needs no approximation of
1419        // the planar rim's parallel curve (which may collapse at a tight turn).
1420        //
1421        // A THIN-SKIN pad (`thin_skin_pad`) slides the net the same way, by
1422        // much more than the distance, and a trim that is not star-shaped
1423        // about the slide's centre moves some of its sides INWARD: an end
1424        // wall joined to a disc had its straight side carried 0.084 into the
1425        // face at d = 0.06, short of the neighbouring wall's offset, and the
1426        // skin never reached it. Such a carrier takes the rectangle too.
1427        if distance > 0.0
1428            && face.surface.is_affine().or_refuse(KernelStage::Refine, "is_affine")?
1429            && ((reflex_extension.is_some() && outline_has_curved_element(source, face)?)
1430                || (thin_padded && thin_pad_rectangle_enabled() && outline_has_curved_element(source, face)?))
1431        {
1432            carrier = full_rectangle_face(&carrier, &carrier.shells[0].faces[0])?;
1433        }
1434        if planar_reach.is_some() {
1435            // A chamfer's trimmed polygon can cut diagonally across its
1436            // patch. Scaling that polygon with the net can still clip the
1437            // opening section. Let the opening and neighbouring offsets
1438            // trim the grown construction rectangle instead.
1439            carrier = full_rectangle_face(&carrier, &carrier.shells[0].faces[0])?;
1440        }
1441        if open_section_reach {
1442            if let Some(continued) = open_section_construction(source, face, &carrier, &extension, distance)? {
1443                carrier = continued;
1444                os_debug!("carrier for src face {face_id}: open section uses its natural construction rectangle");
1445            }
1446        }
1447        // The rim a shadowed support's removal VACATED in this carrier's trim:
1448        // a slot narrower than 2|d| that runs out through this face leaves a
1449        // notch its own skin has to close, because the dilation fills the slot.
1450        // The source face keeps its notch; only the carrier is bridged.
1451        if distance < 0.0 && !shadowed_supports.is_empty() {
1452            let report = close_vacated_rims(
1453                &mut carrier,
1454                source_faces
1455                    .iter()
1456                    .find(|face| face.id == *face_id)
1457                    .copied()
1458                    .unwrap_or(face),
1459                &source_faces,
1460                shadowed_supports,
1461            )?;
1462            if report.closed > 0 {
1463                os_debug!(
1464                    "carrier for src face {face_id}: {} vacated rim run(s) bridged",
1465                    report.closed
1466                );
1467            }
1468            for declined in &report.declined {
1469                os_debug!("carrier for src face {face_id}: vacated rim left alone — {declined}");
1470                vacated_notes.push(format!("source face {face_id}: {declined}"));
1471            }
1472        }
1473        if carved.as_ref().is_some_and(|carved| !carved.other_pieces.is_empty()) {
1474            band_pieces.insert(carriers.len());
1475        }
1476        carriers.push(Carrier {
1477            solid: carrier,
1478            source_face_id: *face_id,
1479            kind: OffsetFaceRole::Offset,
1480        });
1481        // A BAND carve's other kept pieces (whole body only): a carrier each,
1482        // over its own carved source, the selection reading every one against
1483        // the whole source.
1484        for piece in carved.iter().flat_map(|carved| &carved.other_pieces) {
1485            let (piece_carrier, piece_lane) = carrier_solid_sided_lane(&piece.solid, *face_id, distance, &extension)?;
1486            os_debug!("carrier for src face {face_id}: band piece lane {piece_lane:?} ({:.1}% kept)", piece.kept_fraction * 100.0);
1487            band_pieces.insert(carriers.len());
1488            carriers.push(Carrier {
1489                solid: piece_carrier,
1490                source_face_id: *face_id,
1491                kind: OffsetFaceRole::Offset,
1492            });
1493        }
1494    }
1495    profile::lap(&mut clock, profile::CARRIER_TRIM);
1496    // APEX-CAP carriers: a retained face whose DEGENERATE edge (an apex
1497    // point, e.g. a conic crater's tip) offsets into a RING is an EXTERIOR
1498    // cone offset — the parallel surface truncates at the ring and the exact
1499    // rolling-ball offset closes it with a SPHERE of radius |distance| about
1500    // the apex. Emit that sphere as an extra carrier: the ring imprint
1501    // (sphere × offset frustum) splits it, the on-skin filter keeps exactly
1502    // the cap sector (its points are |d| from the apex and ≥|d| from the
1503    // rest of the face), and the ring becomes two-use.
1504    let mut apex_cap_sources = HashSet::default();
1505    let mut apex_cap_pairs: Vec<(usize, usize)> = Vec::new();
1506    {
1507        let retained_count = carriers.len();
1508        for index in 0..retained_count {
1509            // A CARVED support's trim is the carved one. Its coedges name edges
1510            // that live only in the carved clone, so the `source.edges` lookup
1511            // below finds nothing and the apex-cap lane skips the face — which
1512            // is right: the carve already ended that carrier at the offset's own
1513            // pinch, and there is no apex ring left to cap.
1514            let carved_face = carved_supports.get(&carriers[index].source_face_id);
1515            let source_face = carved_face
1516                .or_else(|| source_by_id_lookup(&source_faces, carriers[index].source_face_id));
1517            let Some(source_face) = source_face else {
1518                continue;
1519            };
1520            let carrier_surface = carriers[index].solid.shells[0].faces[0].surface.clone();
1521            for coedge in source_face
1522                .loops
1523                .iter()
1524                .flat_map(|loop_record| &loop_record.coedges)
1525            {
1526                let Some(edge) = source
1527                    .edges
1528                    .iter()
1529                    .find(|edge| edge.id == coedge.edge_id)
1530                else {
1531                    continue;
1532                };
1533                if !edge.degenerate {
1534                    continue;
1535                }
1536                // Image of the degenerate edge on the offset surface.
1537                let [p0, p1] = coedge.pcurve.domain().or_refuse(KernelStage::Sew, "domain")?;
1538                let mut ring = Vec::new();
1539                for sample in 0..=8 {
1540                    let uv = coedge
1541                        .pcurve
1542                        .evaluate(p0 + (p1 - p0) * sample as f64 / 8.0).or_refuse(KernelStage::Sew, "evaluate")?;
1543                    ring.push(carrier_surface.evaluate(uv.x, uv.y).or_refuse(KernelStage::Sew, "evaluate")?);
1544                }
1545                let spread = ring
1546                    .iter()
1547                    .map(|point| point.sub(ring[0]).length())
1548                    .fold(0.0f64, f64::max);
1549                if spread <= distance.abs() * 1e-2 {
1550                    continue;
1551                }
1552                let apex = source
1553                    .vertices
1554                    .iter()
1555                    .find(|vertex| vertex.id == edge.start_vertex_id)
1556                    .map(|vertex| vertex.point)
1557                    .ok_or_else(|| "offset_shell: apex vertex missing".to_string()).or_refuse(KernelStage::Sew, "offset_shell_apex_vertex_missing")?;
1558                let centroid = ring
1559                    .iter()
1560                    .fold(Vec3::default(), |sum, point| sum.add(*point))
1561                    .scale(1.0 / ring.len() as f64);
1562                let axis = apex.sub(centroid);
1563                let axis = if axis.length() > 1e-9 {
1564                    axis.normalized().or_refuse(KernelStage::Sew, "normalized")?
1565                } else {
1566                    Vec3::new(0.0, 0.0, 1.0)
1567                };
1568                os_debug!(
1569                    "apex-cap carrier for src face {} at ({:.3},{:.3},{:.3}) r={:.3}",
1570                    carriers[index].source_face_id,
1571                    apex.x,
1572                    apex.y,
1573                    apex.z,
1574                    distance.abs(),
1575                );
1576                apex_cap_sources.insert(index);
1577                apex_cap_sources.insert(carriers.len());
1578                apex_cap_pairs.push((index, carriers.len()));
1579                carriers.push(Carrier {
1580                    solid: crate::make_sphere_brep(apex, distance.abs(), axis).or_refuse(KernelStage::Sew, "make_sphere_brep")?,
1581                    source_face_id: carriers[index].source_face_id,
1582                    kind: OffsetFaceRole::Offset,
1583                });
1584            }
1585        }
1586    }
1587    // Lane O item 705: the ROUND carriers about tangent opening rims, emitted
1588    // as the apex caps are (an extra Offset carrier of the neighbour face) and
1589    // handled by the same exemptions and coincident-edge splits for now.
1590    if !tangent_rim_rounds.is_empty() {
1591        let tolerance = 1e-7f64.max(crate::solid_scale(source) * 1e-9);
1592        for (neighbour_id, opening_id, edge_id) in &tangent_rim_rounds {
1593            let Some(neighbour_index) = carriers.iter().position(|carrier| carrier.source_face_id == *neighbour_id && matches!(carrier.kind, OffsetFaceRole::Offset)) else {
1594                continue;
1595            };
1596            let Some(edge) = source.edges.iter().find(|edge| edge.id == *edge_id) else { continue };
1597            let Some(opening_face) = source_by_id_lookup(&source_faces, *opening_id) else { continue };
1598            match super::rim_round::circular_rim_round(edge, opening_face, distance, tolerance)? {
1599                Some(round) => {
1600                    os_debug!("tangent rim round: torus about edge {edge_id} (neighbour {neighbour_id}, opening {opening_id}) as carrier {}", carriers.len());
1601                    apex_cap_sources.insert(neighbour_index);
1602                    apex_cap_sources.insert(carriers.len());
1603                    apex_cap_pairs.push((neighbour_index, carriers.len()));
1604                    carriers.push(Carrier { solid: round, source_face_id: *neighbour_id, kind: OffsetFaceRole::Offset });
1605                }
1606                None => {
1607                    return Err(KernelRefusal::unsupported(KernelStage::Refine, "offset_shell_tangent_rim_round", format!(
1608                        "offset_shell: the round about the tangent rim (edge {edge_id}) between source face {neighbour_id} and \
1609                         curved opening face {opening_id} is built only for a circular rim inside its own circle"
1610                    )));
1611                }
1612            }
1613        }
1614    }
1615    // A collapsed round's END on a planar opening: the tube about it
1616    // (`rim_round::planar_rim_tube`), riding the round's id as a synthetic
1617    // carrier the way an apex cap rides its cone's.
1618    if distance > 0.0 && super::rim_round::collapsed_rim_tube_enabled() {
1619        let tolerance = 1e-7f64.max(crate::solid_scale(source) * 1e-9);
1620        // A tube a previous pass read SHADOWED is omitted with its round, as
1621        // every shadowed support is: building it again would read shadowed
1622        // again and ask for the same re-run.
1623        // A SURVIVING round (`BREP_OFFSET_SURVIVING_RIM_TUBE`) takes its tube
1624        // too: its offset ends `distance` under the rim, and the quarter tube
1625        // runs from there to the mouth.
1626        let surviving = retained
1627            .iter()
1628            .filter(|id| super::rim_round::surviving_rim_tube_enabled() && !collapsed_supports.contains(id))
1629            .map(|id| (*id, true));
1630        let rounds = collapsed_supports.iter().map(|id| (*id, false)).chain(surviving).collect::<Vec<_>>();
1631        for (collapsed_id, survives) in rounds.iter().filter(|(id, _)| !shadowed_supports.contains(id)) {
1632            let Some(face) = source_by_id_lookup(&source_faces, *collapsed_id) else { continue };
1633            for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
1634                let Some((mate, mate_use)) = junction_mate(&source_faces, face, coedge.edge_id) else { continue };
1635                // Planarity is read from the geometry in `planar_rim_tube`
1636                // (a plane may arrive degree-elevated or revolved).
1637                if !opening_set.contains(&mate.id)
1638                    || !uses_are_tangent(face, coedge, mate, mate_use)?
1639                {
1640                    continue;
1641                }
1642                let Some(edge) = source.edges.iter().find(|edge| edge.id == coedge.edge_id) else { continue };
1643                // A circle's tube ends ON the plane (its mouth an orphan rim);
1644                // a line's runs past it (cut by the wall like any skin).
1645                let (tube, on_plane) = match super::rim_round::planar_rim_tube(edge, mate, distance, tolerance, *survives)? {
1646                    Some(tube) => (Some(tube), true),
1647                    None if super::rim_round::surviving_rim_tube_enabled() => {
1648                        (super::rim_round::planar_line_rim_tube(edge, mate, distance, tolerance, *survives)?, false)
1649                    }
1650                    None => (None, false),
1651                };
1652                if let Some(tube) = tube {
1653                    os_debug!(
1654                        "rim tube: about edge {} (face {collapsed_id}, {}, opening {}) as carrier {}",
1655                        edge.id,
1656                        if *survives { "surviving" } else { "collapsed" },
1657                        mate.id,
1658                        carriers.len()
1659                    );
1660                    if on_plane {
1661                        rim_tubes.insert(carriers.len(), mate.id);
1662                    }
1663                    if *survives {
1664                        surviving_tubes.insert(carriers.len());
1665                    }
1666                    carriers.push(Carrier { solid: tube, source_face_id: *collapsed_id, kind: OffsetFaceRole::Offset });
1667                }
1668            }
1669        }
1670    }
1671    profile::lap(&mut clock, profile::APEX_CAPS);
1672    // A fold the carve's probe did not see (`outward_fold_the_carve_missed`):
1673    // a band too thin for its grid is built whole, and the torus wedge grown by
1674    // 1.001 then held the reflected lemon beyond its axis. Asked of every
1675    // retained face the carve neither carved nor omitted, on every outward
1676    // shell: a ruled wall is what first let the pipeline CLOSE such a shape,
1677    // but the geometry is the trigger. Refused by name, the tangent onset
1678    // included; a partial revolve of that kind is the revolved-wedge lane's
1679    // question, and that lane runs in front of this pipeline.
1680    if distance < 0.0 {
1681        for face_id in &retained {
1682            if carved_supports.contains_key(face_id)
1683                || !carriers.iter().any(|carrier| carrier.source_face_id == *face_id)
1684            {
1685                continue;
1686            }
1687            let face = source_by_id_lookup(&source_faces, *face_id).unwrap();
1688            if let Some(fold) = profile::detail("outward_fold_the_carve_missed", || outward_fold_the_carve_missed(face, distance))? {
1689                return Err(KernelRefusal::unsupported(KernelStage::Refine, "offset_shell_outward_fold_band", format!(
1690                    "offset_shell: the outward offset of source face {face_id} folds where the carve \
1691                     saw no fold (area factor {:.3e} at u={:.6}, v={:.6}); a fold band that thin is \
1692                     not built",
1693                    fold.factor, fold.u, fold.v
1694                )));
1695            }
1696        }
1697    }
1698    profile::lap(&mut clock, profile::CARRIER_REGULARITY);
1699    // Wall carriers built as a RULED opening face extended along itself, by
1700    // carrier index: the in-front guard reads their sides off the surface
1701    // normal where it would read a plane's.
1702    let mut ruled_walls = HashSet::default();
1703    // Inward walls at reflex rims need construction area beyond the source
1704    // opening too. Track them for source imprints and material-side selection.
1705    let mut inward_extended_walls = HashSet::default();
1706    let mut reflex_wall_neighbors = HashMap::default();
1707    // OUTWARD through a CURVED opening. A ruled one — the cone a revolved
1708    // straight profile edge sweeps, a cylinder — has its wall built as the
1709    // opening face held in place and EXTENDED along itself, exactly as a plane
1710    // is padded (`extended_ruled_wall`); the pad is the plane's, read off the
1711    // same convex junctions. Built first, so the planar walls know which
1712    // neighbours are ruled walls.
1713    //
1714    // Any other curved opening is refused by name. Its wall used to be the
1715    // unpadded source face, which never reaches the grown offset: on a torus
1716    // wedge whose chord revolves to a cone, the pair offset x cone cut 0
1717    // pieces, the cone's one fragment was dropped as a void cross-section, and
1718    // the result read "completion produced non-integral genus" with 12 open
1719    // edges. No outward shell in the kernel suites or the case corpus closed
1720    // through that wall (census, 2026-09-17).
1721    let mut ruled_built = HashMap::<u64, BrepSolid>::default();
1722    if distance < 0.0 {
1723        for face_id in opening_face_ids {
1724            let source_face = source_by_id_lookup(&source_faces, *face_id).unwrap();
1725            if source_face.surface.is_affine().or_refuse(KernelStage::Sew, "is_affine")? {
1726                continue;
1727            }
1728            if !ruled_opening(source_face)? {
1729                return Err(KernelRefusal::unsupported(KernelStage::Refine, "offset_shell_curved_opening", format!(
1730                    "offset_shell: opening face {face_id} is curved and not a ruled surface; an \
1731                     outward wall is built only on a planar or ruled opening"
1732                )));
1733            }
1734            let pad = outward_wall_pad(
1735                source,
1736                source_face,
1737                &source_faces,
1738                &opening_set,
1739                distance.abs(),
1740            )?;
1741            let tolerance = 1e-7f64.max(crate::solid_scale(source) * 1e-9);
1742            match extended_ruled_wall(source, source_face, pad, tolerance)? {
1743                Ok(wall) => {
1744                    os_debug!(
1745                        "wall for opening face {face_id}: ruled, pad {pad:.4}, sides reach {:.4?}",
1746                        wall.reached
1747                    );
1748                    ruled_built.insert(*face_id, wall.solid);
1749                }
1750                Err(reason) => {
1751                    return Err(KernelRefusal::unsupported(KernelStage::Refine, "offset_shell_ruled_wall", format!(
1752                        "offset_shell: the outward wall of ruled opening face {face_id} cannot be \
1753                         built: {reason}"
1754                    )));
1755                }
1756            }
1757        }
1758    }
1759    let ruled_openings = ruled_built
1760        .keys()
1761        .filter_map(|id| source_by_id_lookup(&source_faces, *id))
1762        .collect::<Vec<_>>();
1763    for face_id in opening_face_ids {
1764        let source_face = source_faces
1765            .iter()
1766            .find(|face| face.id == *face_id)
1767            .unwrap();
1768        if let Some(wall) = ruled_built.remove(face_id) {
1769            ruled_walls.insert(carriers.len());
1770            carriers.push(Carrier {
1771                solid: wall,
1772                source_face_id: *face_id,
1773                kind: OffsetFaceRole::Wall,
1774            });
1775            continue;
1776        }
1777        if distance > 0.0
1778            && source_face.surface.is_affine().or_refuse(KernelStage::Refine, "is_affine")?
1779        {
1780            if let Some((pad, neighbors)) =
1781                inward_wall_pad(source, source_face, &source_faces, &opening_set, distance)?
1782            {
1783                // Scaling a notched/free-form outline can still clip the new
1784                // rim. Use the whole plane rectangle; source and offset
1785                // imprints below recover both exact boundaries of the wall.
1786                let padded = carrier_solid(source, *face_id, 0.0, pad)?;
1787                let wall = full_rectangle_face(&padded, &padded.shells[0].faces[0])?;
1788                inward_extended_walls.insert(carriers.len());
1789                reflex_wall_neighbors.insert(carriers.len(), neighbors);
1790                carriers.push(Carrier {
1791                    solid: wall,
1792                    source_face_id: *face_id,
1793                    kind: OffsetFaceRole::Wall,
1794                });
1795                continue;
1796            }
1797        }
1798        carriers.push(Carrier {
1799            solid: if distance < 0.0 && source_face.surface.is_affine().or_refuse(KernelStage::Sew, "is_affine")? {
1800                let pad = outward_wall_pad(
1801                    source,
1802                    source_face,
1803                    &source_faces,
1804                    &opening_set,
1805                    distance.abs(),
1806                )?;
1807                // A plane meeting a RULED opening is padded past the grown
1808                // outline, not onto it. Padded by exactly the pad, its trim's
1809                // arc lands ON the grown offset's section wherever the join is
1810                // perpendicular, and the ruled wall's section then ENDS on that
1811                // coincident pair: on the torus wedge the cap shredded into 60
1812                // slivers along the grown circle. The clearance is counted in
1813                // the band that decides whether the strip beyond the grown
1814                // outline is wall or void, so the strip always resolves as its
1815                // own fragment and is dropped as void.
1816                let uniform_pad = pad;
1817                let pad = if ruled_openings
1818                    .iter()
1819                    .any(|ruled| source_faces_adjacent(source_face, ruled))
1820                {
1821                    pad + RULED_NEIGHBOUR_CLEARANCE_BANDS
1822                        * offset_skin_band(crate::solid_scale(source), distance)
1823                } else if outline_has_free_element(source, source_face)? {
1824                    // A free-form outline's wall is a FIT: without the same
1825                    // clearance its outline sits within the fit tolerance of
1826                    // the carriers' own sections on the plane, and the
1827                    // near-coincident curves shred the wall's imprint (26 to
1828                    // 121 fragments on the free-form D band, 2026-09-26). With
1829                    // it, the surplus ring is cut away cleanly.
1830                    pad + RULED_NEIGHBOUR_CLEARANCE_BANDS * offset_skin_band(crate::solid_scale(source), distance)
1831                } else {
1832                    pad
1833                };
1834                os_debug!("wall for opening face {face_id}: outward pad {pad:.4}");
1835                // The wall is the opening's outline OFFSET by the pad in its
1836                // own plane (`outline_offset.rs`). The pad used to SCALE that
1837                // outline about the patch centre, which is the offset only for
1838                // a rectangle filling its patch or a circle centred on it: an
1839                // L-shaped opening's notch edges pass through the centre and
1840                // did not move at all, so the notch faces' grown offsets
1841                // crossed the plane outside the wall ("non-integral genus",
1842                // `l-step-open-bottom` at d = −1.5 in the membrane census).
1843                //
1844                // An outline this module does not offset keeps the scaled wall,
1845                // but only when that wall still COVERS the offset outline along
1846                // every edge a retained face meets — which is what the sections
1847                // have to land inside. Otherwise the shell refuses by name
1848                // rather than assembling an open rim.
1849                let mut scaled = carrier_solid(source, *face_id, 0.0, pad)?;
1850                drop_wall_interior_loops(&mut scaled)?;
1851                // Each outline edge padded for its own neighbour, plus the same
1852                // clearance the uniform pad carries (`outward_wall_pads_per_edge`).
1853                let per_edge = if per_edge_opening_pads_on() {
1854                    Some(outward_wall_pads_per_edge(source, source_face, &source_faces, &opening_set, distance.abs())?)
1855                } else {
1856                    None
1857                };
1858                // Where the pads differ, every edge also takes the clearance a
1859                // ruled or free-form neighbour's wall takes: an edge padded by
1860                // exactly d beside one padded more lands its wall boundary ON
1861                // the neighbour's offset section, and the imprint drops it as
1862                // boundary (non-integral genus at the corner they share).
1863                let clearance = match &per_edge {
1864                    Some(pads) if pads.values().any(|value| (value - uniform_pad).abs() > 1e-12 * uniform_pad.max(1.0)) => {
1865                        (pad - uniform_pad).max(
1866                            RULED_NEIGHBOUR_CLEARANCE_BANDS * offset_skin_band(crate::solid_scale(source), distance),
1867                        )
1868                    }
1869                    _ => pad - uniform_pad,
1870                };
1871                // An outline the per-edge offset declines (a tangent junction
1872                // between edges padded differently) takes the uniform pad.
1873                let outline_wall = || match &per_edge {
1874                    Some(pads) => match offset_outline_wall_per_edge(source, source_face, &|edge_id| {
1875                        pads.get(&edge_id).copied().unwrap_or(uniform_pad) + clearance
1876                    })? {
1877                        Ok(wall) => Ok(Ok(wall)),
1878                        Err(reason) => {
1879                            os_debug!("per-edge outline of opening face {face_id} declined ({reason}); uniform pad");
1880                            offset_outline_wall(source, source_face, pad)
1881                        }
1882                    },
1883                    None => offset_outline_wall(source, source_face, pad),
1884                };
1885                let mut wall = match profile::detail("offset_outline_wall", outline_wall)? {
1886                    Ok(outline) => {
1887                        // Where the scaled wall already trims the offset
1888                        // outline's own region — a rectangle filling its patch,
1889                        // a circle centred on it — it is kept, so no shell that
1890                        // was right before is rebuilt on a different patch.
1891                        let same = profile::detail("walls_trim_the_same_region", || walls_trim_the_same_region(
1892                            &outline,
1893                            &scaled,
1894                            1e-9f64.max(crate::solid_scale(source) * 1e-11),
1895                        ))?;
1896                        if same {
1897                            os_debug!("wall for opening face {face_id}: scaled, which IS its outline offset");
1898                            scaled
1899                        } else {
1900                            os_debug!("wall for opening face {face_id}: outline offset by {pad:.4}");
1901                            outline
1902                        }
1903                    }
1904                    Err(reason) => {
1905                        let carrier_surfaces = carriers
1906                            .iter()
1907                            .filter(|carrier| matches!(carrier.kind, OffsetFaceRole::Offset))
1908                            .map(|carrier| (carrier.source_face_id, &carrier.solid.shells[0].faces[0].surface))
1909                            .collect::<Vec<_>>();
1910                        if let Err(uncovered) = scaled_wall_covers_offset(
1911                            source,
1912                            source_face,
1913                            &scaled,
1914                            pad,
1915                            &source_faces,
1916                            &opening_set,
1917                            &carrier_surfaces,
1918                        )? {
1919                            return Err(KernelRefusal::unsupported(KernelStage::Refine, "offset_shell_opening_wall_coverage", format!(
1920                                "offset_shell: opening face {face_id}'s outline is not offset \
1921                                 ({reason}), and its scaled outward wall does not contain every \
1922                                 retained neighbour's grown offset section (a point of one lies \
1923                                 {uncovered:.3e} outside)"
1924                            )));
1925                        }
1926                        os_debug!(
1927                            "wall for opening face {face_id}: scaled, which covers its offset ({reason})"
1928                        );
1929                        scaled
1930                    }
1931                };
1932                // The pad extends the wall by STRETCHING the plane's 2x2 net
1933                // while the trim pcurves are cloned in UV, so every loop
1934                // scales about the patch centre by (w+2|d|)/w. For the OUTER
1935                // loop of a full-domain rectangle that lands exactly on the
1936                // grown outline — the intended wall extent. But an INTERIOR
1937                // loop (a carve outline: a bore, gouge or crater rim in the
1938                // opening face) is scaled OUTWARD too, and the enlarged hole
1939                // then swallows both circles the wall must be cut by (the
1940                // source carve rim from the wall x source imprint and the
1941                // shrunk rim from the wall x offset-carrier imprint) — the
1942                // imprints clip to nothing and the rims dangle one-use. Drop
1943                // interior loops instead: the wall covers the carve mouth,
1944                // the imprints cut the true rims, and selection (void-wall
1945                // guard + on-skin filter) drops the fragments over the void.
1946                drop_wall_interior_loops(&mut wall)?;
1947                wall
1948            } else {
1949                standalone_face(source, *face_id)?
1950            },
1951            source_face_id: *face_id,
1952            kind: OffsetFaceRole::Wall,
1953        });
1954    }
1955    if carriers.len() >= SOURCE_OPERAND as usize {
1956        return Err(KernelRefusal::unsupported(KernelStage::Collect, "offset_shell_carrier_count", "offset_shell: too many carrier faces for current ABI"));
1957    }
1958    profile::lap(&mut clock, profile::WALLS);
1959    // The characteristic length every tolerance below is derived from.  This
1960    // was `max ‖vertex‖` — the distance from the WORLD ORIGIN — until audit
1961    // slice 0: that form made every band widen as the part was moved away from
1962    // the origin while ignoring the part's actual size, so the same shell
1963    // solved to different tolerances depending only on where it was modelled.
1964    // `solid_scale` is the bbox diagonal, floored at 1.0 exactly as the old
1965    // fold was, so this changes ONE thing: placement-dependence.
1966    let scale = crate::solid_scale(source);
1967    crate::report_scale_migration("offset_shell", scale, || {
1968        source
1969            .vertices
1970            .iter()
1971            .map(|vertex| vertex.point.length())
1972            .fold(1.0, f64::max)
1973    });
1974    let smooth = synchronize_smooth_offset_boundaries(&mut carriers, &source_faces, scale)?;
1975    // Reflex-rim rebuilds run on BOTH attempts: the fallback for a broken
1976    // extension is an honest refusal, but the fallback for a skipped reflex
1977    // rebuild is a silently WRONG (membrane-capped) shell.
1978    let reflex_rebuilt = rebuild_reflex_rim_carriers(
1979        &mut carriers,
1980        source,
1981        &source_faces,
1982        &smooth.pairs,
1983        scale,
1984        distance,
1985    )?;
1986    *reflex_rebuilds = reflex_rebuilt.len();
1987    if extend_oblique_carriers {
1988        let oblique_extended = extend_offset_carriers_past_open_hole_rims(
1989            &mut carriers,
1990            source,
1991            &source_faces,
1992            &opening_set,
1993            &smooth.pairs,
1994            scale,
1995        )?;
1996        let mut already_extended = oblique_extended.clone();
1997        already_extended.extend(reflex_rebuilt.iter().copied());
1998        let fallshort_extended = extend_fallshort_curved_carriers(
1999            &mut carriers,
2000            source,
2001            &source_faces,
2002            &opening_set,
2003            &smooth.pairs,
2004            &already_extended,
2005            scale,
2006            distance,
2007        )?;
2008        *extension_fired = !oblique_extended.is_empty() || fallshort_extended > 0;
2009        os_debug!(
2010            "extended {} oblique + {fallshort_extended} fall-short carriers past their opening planes",
2011            oblique_extended.len(),
2012        );
2013    }
2014    profile::lap(&mut clock, profile::EXTENSION);
2015    let tolerance = 1e-7f64.max(scale * 1e-9);
2016    let pair_tolerance = (scale * 1e-8).max(2e-6);
2017    let reach = distance.abs() * 4.0 + pair_tolerance;
2018    // Only after the cascade has omitted a shadowed carrier: until then that
2019    // carrier still cuts both coplanar copies at the same points. A shell only:
2020    // under `offset_solid` (the dumbbell's run-on body shrunk with rounded
2021    // joins) it turned a refusal into a two-shell body 2.16 off its form.
2022    if abut_coplanar_carriers_on() && body == Body::Shell && !shadowed_supports.is_empty() {
2023        let abutted = abut_coplanar_offset_carriers(&mut carriers, tolerance.max(scale * 1e-9))?;
2024        if abutted > 0 {
2025            os_debug!("abutted {abutted} pair(s) of overlapping coplanar offset carriers");
2026        }
2027    }
2028    let carrier_samples = carriers
2029        .iter()
2030        .map(|carrier| carrier_extent_points(&carrier.solid))
2031        .collect::<Result<Vec<_>, _>>()?;
2032    let carrier_bounds = carrier_samples
2033        .iter()
2034        .map(|samples| Bounds::from_nonempty_points(samples))
2035        .collect::<Option<Vec<_>>>()
2036        .ok_or_else(|| "offset_shell: carrier has no boundary samples".to_string()).or_refuse(KernelStage::Sew, "offset_shell_carrier_has_no_boundary_samples")?;
2037    let source_by_id = source_faces
2038        .iter()
2039        .map(|face| (face.id, *face))
2040        .collect::<HashMap<_, _>>();
2041    let source_samples = source_faces
2042        .iter()
2043        .map(|face| {
2044            let standalone = standalone_face(source, face.id)?;
2045            Ok((face.id, edge_sample_points(&standalone)?))
2046        })
2047        .collect::<Result<HashMap<_, _>, KernelRefusal>>()?;
2048    if debug_enabled() {
2049        for (index, carrier) in carriers.iter().enumerate() {
2050            let face = &carrier.solid.shells[0].faces[0];
2051            let samples = &carrier_samples[index];
2052            let bounds =
2053                samples
2054                    .iter()
2055                    .fold((Vec3::default(), Vec3::default()), |(low, high), point| {
2056                        (
2057                            Vec3 {
2058                                x: low.x.min(point.x),
2059                                y: low.y.min(point.y),
2060                                z: low.z.min(point.z),
2061                            },
2062                            Vec3 {
2063                                x: high.x.max(point.x),
2064                                y: high.y.max(point.y),
2065                                z: high.z.max(point.z),
2066                            },
2067                        )
2068                    });
2069            let surface = &face.surface;
2070            let rational = surface
2071                .control_points
2072                .iter()
2073                .flatten()
2074                .any(|point| (point.w - 1.0).abs() > 1e-12);
2075            os_debug!(
2076                "carrier[{index}] kind={:?} source_face={} loops={} deg=({},{}) net={}x{} rational={rational} bounds=({:.3},{:.3},{:.3})..({:.3},{:.3},{:.3})",
2077                carrier.kind, carrier.source_face_id, face.loops.len(),
2078                surface.degree_u, surface.degree_v,
2079                surface.control_points.len(),
2080                surface.control_points.first().map(|row| row.len()).unwrap_or(0),
2081                bounds.0.x, bounds.0.y, bounds.0.z, bounds.1.x, bounds.1.y, bounds.1.z,
2082            );
2083        }
2084        for (index, carrier) in carriers.iter().enumerate() {
2085            if !matches!(carrier.kind, OffsetFaceRole::Offset) {
2086                continue;
2087            }
2088            let source_face = source_by_id[&carrier.source_face_id];
2089            let carrier_surface = &carrier.solid.shells[0].faces[0].surface;
2090            let (ku, kv) = (
2091                crate::KnotVector::new(
2092                    source_face.surface.knots_u.clone(),
2093                    source_face.surface.degree_u,
2094                ),
2095                crate::KnotVector::new(
2096                    source_face.surface.knots_v.clone(),
2097                    source_face.surface.degree_v,
2098                ),
2099            );
2100            if let (Ok(ku), Ok(kv)) = (ku, kv) {
2101                let [u0, u1] = ku.domain();
2102                let [v0, v1] = kv.domain();
2103                let mut worst = 0.0f64;
2104                let mut worst_at = (0.0f64, 0.0f64);
2105                for iu in 0..=24 {
2106                    for iv in 0..=24 {
2107                        let u = u0 + (u1 - u0) * iu as f64 / 24.0;
2108                        let v = v0 + (v1 - v0) * iv as f64 / 24.0;
2109                        let expected = face_offsets(source_face)
2110                            .at(u, v, -distance)
2111                            .map(|sample| sample.point);
2112                        let actual = carrier_surface.evaluate(u, v);
2113                        if let (Ok(expected), Ok(actual)) = (expected, actual) {
2114                            let error = expected.sub(actual).length();
2115                            if error > worst {
2116                                worst = error;
2117                                worst_at = (u, v);
2118                            }
2119                        }
2120                    }
2121                }
2122                let mut normal_swing = 0.0f64;
2123                let mut previous: Option<Vec3> = None;
2124                for iu in 0..=48 {
2125                    let u = u0 + (u1 - u0) * iu as f64 / 48.0;
2126                    let v = (v0 + v1) / 2.0;
2127                    if let Ok(normal) = face_normal(source_face, u, v) {
2128                        if let Some(previous) = previous {
2129                            normal_swing = normal_swing.max(previous.sub(normal).length());
2130                        }
2131                        previous = Some(normal);
2132                    }
2133                }
2134                let weights = source_face
2135                    .surface
2136                    .control_points
2137                    .iter()
2138                    .flatten()
2139                    .map(|point| point.w)
2140                    .fold((f64::MAX, f64::MIN), |(low, high), w| {
2141                        (low.min(w), high.max(w))
2142                    });
2143                os_debug!(
2144                    "carrier[{index}] offset fit error max={worst:.6} at=({:.4},{:.4}) domain_u=({u0:.4},{u1:.4}) normal_step_max={normal_swing:.4} src_net={}x{} src_deg=({},{}) src_w=({:.4},{:.4}) knots_u={:?}",
2145                    worst_at.0, worst_at.1,
2146                    source_face.surface.control_points.len(),
2147                    source_face.surface.control_points.first().map(|row| row.len()).unwrap_or(0),
2148                    source_face.surface.degree_u, source_face.surface.degree_v,
2149                    weights.0, weights.1,
2150                    &source_face.surface.knots_u,
2151                );
2152            }
2153        }
2154        os_debug!("smooth pairs: {:?}", smooth.pairs);
2155    }
2156    let mut imprint = empty_imprint();
2157    let mut next_piece_id = 1;
2158    let mut next_vertex_id = 1;
2159    // Lane P3b row 2 (2026-10-26): where the IMPRINT phase spends its time
2160    // outside `build_imprints`, one `offset_shell.imprint_split` line under
2161    // BREP_PROFILE: the carrier-pair builds and merges, the wall x source
2162    // builds, their standalone face copies and merges, the apex ring splits,
2163    // the smooth-split sync and the boundary-coincidence filter.
2164    let split_profile = crate::imprint::profile_enabled();
2165    let mut split_ms = [0.0f64; 9];
2166    let mut split_clock = split_profile.then(web_time::Instant::now);
2167    let mut split_lap = |slot: usize, clock: &mut Option<web_time::Instant>| {
2168        if let Some(started) = clock {
2169            let now = web_time::Instant::now();
2170            split_ms[slot] += (now - *started).as_secs_f64() * 1e3;
2171            *started = now;
2172        }
2173    };
2174    // The pair skip rules, one closure for both imprint paths below (the
2175    // per-pair calls and row 6's one-call composite).
2176    // TANGENT RIM CUTS, planned before the imprint (`tangent_rim_cuts.rs`).
2177    let tangent_rim_cuts = if super::tangent_rim_cuts::tangent_rim_cuts_enabled() {
2178        super::tangent_rim_cuts::plan_tangent_rim_cuts(&carriers, &source_faces, &smooth.pairs, tolerance, scale)?
2179    } else {
2180        Vec::new()
2181    };
2182    let pair_admitted = |first: usize, second: usize| -> bool {
2183            let first_source = source_by_id[&carriers[first].source_face_id];
2184            let second_source = source_by_id[&carriers[second].source_face_id];
2185            if matches!(carriers[first].kind, OffsetFaceRole::Wall)
2186                && matches!(carriers[second].kind, OffsetFaceRole::Wall)
2187            {
2188                // Unextended inward walls are the opening faces themselves:
2189                // they never overlap; adjacent ones only touch along their
2190                // shared edge, so there is nothing to imprint. OUTWARD walls
2191                // are the opening planes EXTENDED by |distance|: the walls of
2192                // two ADJACENT openings cross along the line of their shared
2193                // source edge, and each wall ring must stop there (the sheet
2194                // past that line lies in front of the other opening). Without
2195                // the cut the wall × source chain below stays open on the
2196                // shared-edge side (its neighbour there is an opening, not a
2197                // retained face), the wall never fragments into its ring, and
2198                // every source rim along both openings dangles one-use.
2199                // Extended inward walls need those mutual cuts as well.
2200                if (distance > 0.0
2201                    && !inward_extended_walls.contains(&first)
2202                    && !inward_extended_walls.contains(&second))
2203                    || !source_faces_adjacent(first_source, second_source)
2204                {
2205                    return false;
2206                }
2207            }
2208            if smooth.pairs.contains(&(first, second)) {
2209                os_debug!("pair ({first},{second}) skipped: smooth");
2210                return false;
2211            }
2212            if !carrier_bounds[first].intersects_upper(carrier_bounds[second], pair_tolerance) {
2213                os_debug!("pair ({first},{second}) skipped: bounds");
2214                return false;
2215            }
2216            if !source_faces_adjacent(first_source, second_source)
2217                && sample_separation(
2218                    &source_samples[&first_source.id],
2219                    &source_samples[&second_source.id],
2220                ) > reach
2221            {
2222                os_debug!("pair ({first},{second}) skipped: separation");
2223                return false;
2224            }
2225            true
2226    };
2227    // The wall x source pairs: an extended opening wall (outward, or inward
2228    // at a reflex rim) against each retained source face adjacent to its
2229    // opening (see the note at the per-pair loop below).
2230    let mut wall_source_pairs: Vec<(usize, u64)> = Vec::new();
2231    if body == Body::Shell && (distance < 0.0 || !inward_extended_walls.is_empty()) {
2232        for index in 0..carriers.len() {
2233            if !matches!(carriers[index].kind, OffsetFaceRole::Wall) {
2234                continue;
2235            }
2236            if distance > 0.0 && !inward_extended_walls.contains(&index) {
2237                continue;
2238            }
2239            let opening = source_by_id[&carriers[index].source_face_id];
2240            for retained_id in &retained {
2241                if source_faces_adjacent(opening, source_by_id[retained_id]) {
2242                    wall_source_pairs.push((index, *retained_id));
2243                }
2244            }
2245        }
2246    }
2247    let one_call = one_call_imprint_enabled();
2248    let mut one_call_done = false;
2249    if one_call {
2250        // ONE-CALL IMPRINT (`BREP_OFFSET_ONE_CALL_IMPRINT`, lane P3b row 6):
2251        // every carrier and every retained source face a wall is cut against
2252        // go into one open sheet solid (ids renumbered per member), one
2253        // `build_imprints` processes exactly the admitted pairs, and its
2254        // post-passes run once over the whole piece set. The record comes
2255        // back in the shell's operand space. A failure of the single call
2256        // falls back to the per-pair path below, which tolerates a failed
2257        // pair on its own.
2258        let mut members: Vec<(u8, &BrepSolid)> = carriers.iter().enumerate().map(|(index, carrier)| (index as u8, &carrier.solid)).collect();
2259        let mut source_members: Vec<(u64, BrepSolid)> = Vec::new();
2260        for (_, retained_id) in &wall_source_pairs {
2261            if !source_members.iter().any(|(id, _)| id == retained_id) {
2262                source_members.push((*retained_id, standalone_face(source, *retained_id)?));
2263            }
2264        }
2265        for (_, solid) in &source_members {
2266            members.push((SOURCE_OPERAND, solid));
2267        }
2268        let composite = compose_imprint_operands(&members);
2269        let mut admitted: HashSet<(usize, usize)> = HashSet::default();
2270        for first in 0..carriers.len() {
2271            for second in first + 1..carriers.len() {
2272                if pair_admitted(first, second) {
2273                    admitted.insert((composite.face_index[first], composite.face_index[second]));
2274                }
2275            }
2276        }
2277        for (index, retained_id) in &wall_source_pairs {
2278            let member = carriers.len() + source_members.iter().position(|(id, _)| id == retained_id).unwrap();
2279            let (a, b) = (composite.face_index[*index], composite.face_index[member]);
2280            admitted.insert((a.min(b), a.max(b)));
2281        }
2282        split_lap(0, &mut split_clock);
2283        match crate::imprint::build_carrier_imprints_within(
2284            &composite.solid,
2285            &|first, second| admitted.contains(&(first, second)),
2286            &ImprintOptions {
2287                tolerance,
2288                maximum_fit_points: 96,
2289                local_fit: false,
2290                fit_chunk_points: None,
2291                maximum_ssi_step: Some((scale * 0.0005).max(tolerance * 100.0)),
2292                span_budget: None,
2293                hermite_sections: false,
2294                tangent_curve_lane: false,
2295                exact_iso_pcurves: offset_exact_iso_pcurves_on(),
2296                march_starts: false,
2297                two_radius_junctions: false,
2298                tangent_curve_imprint: false,
2299            },
2300            !shielded_cusps.is_empty(),
2301        ) {
2302            Ok(record) => {
2303                split_lap(1, &mut split_clock);
2304                imprint = translate_composite_imprint(record, &composite, tolerance, scale)?;
2305                next_piece_id = imprint.pieces.iter().map(|piece| piece.id).max().unwrap_or(0) + 1;
2306                next_vertex_id = imprint.vertices.iter().map(|vertex| vertex.id).max().unwrap_or(0) + 1;
2307                one_call_done = true;
2308                ONE_CALL_RUNS.with(|count| count.set(count.get() + 1));
2309                split_lap(2, &mut split_clock);
2310                os_debug!(
2311                    "one-call imprint: {} members, {} admitted pairs, {} pieces",
2312                    members.len(),
2313                    admitted.len(),
2314                    imprint.pieces.len(),
2315                );
2316            }
2317            Err(error) => {
2318                os_debug!("one-call imprint failed, per-pair path: {error}");
2319            }
2320        }
2321    }
2322    for first in 0..carriers.len() {
2323        for second in first + 1..carriers.len() {
2324            if one_call_done {
2325                break;
2326            }
2327            if !pair_admitted(first, second) {
2328                continue;
2329            }
2330            split_lap(0, &mut split_clock);
2331            let pair = match crate::imprint::build_carrier_imprints(
2332                &carriers[first].solid,
2333                &carriers[second].solid,
2334                &ImprintOptions {
2335                    tolerance,
2336                    maximum_fit_points: 96,
2337                    // The GLOBAL interpolation lane. `local_fit: true` until
2338                    // 2026-09-13, which cost three orders on every smooth
2339                    // section: measured on the apex cone's base circle, the
2340                    // local lane needs 3,070 control points to reach 2.0e-5
2341                    // where the global one reaches 1.4e-8 with 384. What the
2342                    // local lane is for — a rim through a corner, where its
2343                    // monotonicity limiter holds a kink the global cubic rings
2344                    // across, 4.9x measured — is now the fit's own fallback:
2345                    // `fit_polyline` re-runs the other lane whenever the asked
2346                    // one cannot meet the tolerance and returns the better
2347                    // MEASURED curve, so this flag chooses which ladder is
2348                    // paid for first, never which curve is delivered.
2349                    local_fit: false,
2350                    fit_chunk_points: None,
2351                    // Offset carriers can meet in short, tightly curved
2352                    // branches. The general SSI default (diagonal / 15) is
2353                    // too coarse here and lets independently fitted branches
2354                    // miss a shared junction when thickness crosses one of
2355                    // those branches.
2356                    maximum_ssi_step: Some((scale * 0.0005).max(tolerance * 100.0)),
2357                    span_budget: None,
2358                    hermite_sections: false,
2359                    tangent_curve_lane: false,
2360                    exact_iso_pcurves: offset_exact_iso_pcurves_on(),
2361                    march_starts: false,
2362                    two_radius_junctions: false,
2363                    tangent_curve_imprint: false,
2364                },
2365                !shielded_cusps.is_empty(),
2366            ) {
2367                Ok(pair) => pair,
2368                // A failed pair imprint (e.g. the marching SSI exhausting its
2369                // step budget on a long closed sphere/plane intersection) is
2370                // not fatal to the shell: the affected rim simply stays
2371                // unsplit and the rim-weld passes below get to close it. The
2372                // final watertightness gate still refuses anything the welds
2373                // cannot reach, so tolerating the miss only enlarges the
2374                // honest success set.
2375                Err(error) => {
2376                    os_debug!("pair ({first},{second}) imprint failed: {error}");
2377                    continue;
2378                }
2379            };
2380            split_lap(1, &mut split_clock);
2381            let pieces_before = imprint.pieces.len();
2382            merge_pair_imprint(
2383                &mut imprint,
2384                pair,
2385                first as u8,
2386                second as u8,
2387                &mut next_piece_id,
2388                &mut next_vertex_id,
2389                tolerance,
2390                scale,
2391            );
2392            split_lap(2, &mut split_clock);
2393            os_debug!(
2394                "pair ({first},{second}) src=({},{}) pieces+={}",
2395                carriers[first].source_face_id,
2396                carriers[second].source_face_id,
2397                imprint.pieces.len() - pieces_before,
2398            );
2399        }
2400    }
2401    if body == Body::Shell && (distance < 0.0 || !inward_extended_walls.is_empty()) {
2402        // An extended opening-wall carrier (outward, or inward at a reflex
2403        // rim) no longer carries the source outline. OUTWARD it has the GROWN
2404        // outline. Its inner boundary — where the wall ring stops at the
2405        // source solid — is the source outline, and the retained SOURCE faces
2406        // are not carriers, so no carrier×carrier pair ever imprints it.
2407        // Un-cut, the wall stays one whole-plane fragment covering the
2408        // opening void, and the source faces' rim edges dangle one-use.
2409        // Imprint each wall carrier against the retained source faces that
2410        // share an edge with its opening: the wall then fragments into the
2411        // ring (kept) and the opening hole (dropped by the void guard).
2412        for index in 0..carriers.len() {
2413            if one_call_done {
2414                break;
2415            }
2416            if !matches!(carriers[index].kind, OffsetFaceRole::Wall) {
2417                continue;
2418            }
2419            if distance > 0.0 && !inward_extended_walls.contains(&index) {
2420                continue;
2421            }
2422            let opening = source_by_id[&carriers[index].source_face_id];
2423            for retained_id in &retained {
2424                let retained_face = source_by_id[retained_id];
2425                if !source_faces_adjacent(opening, retained_face) {
2426                    continue;
2427                }
2428                split_lap(0, &mut split_clock);
2429                let neighbor = standalone_face(source, *retained_id)?;
2430                split_lap(3, &mut split_clock);
2431                let pair = match build_imprints(
2432                    &carriers[index].solid,
2433                    &neighbor,
2434                    &ImprintOptions {
2435                        tolerance,
2436                        maximum_fit_points: 96,
2437                        // The global lane, as above.
2438                        local_fit: false,
2439                        fit_chunk_points: None,
2440                        maximum_ssi_step: Some((scale * 0.0005).max(tolerance * 100.0)),
2441                        span_budget: None,
2442                        hermite_sections: false,
2443                        tangent_curve_lane: false,
2444                        exact_iso_pcurves: offset_exact_iso_pcurves_on(),
2445                        march_starts: false,
2446                        two_radius_junctions: false,
2447                        tangent_curve_imprint: false,
2448                    },
2449                ) {
2450                    Ok(pair) => pair,
2451                    Err(error) => {
2452                        os_debug!(
2453                            "wall×source pair ({index},{retained_id}) imprint failed: {error}"
2454                        );
2455                        continue;
2456                    }
2457                };
2458                split_lap(4, &mut split_clock);
2459                let pieces_before = imprint.pieces.len();
2460                merge_pair_imprint(
2461                    &mut imprint,
2462                    pair,
2463                    index as u8,
2464                    SOURCE_OPERAND,
2465                    &mut next_piece_id,
2466                    &mut next_vertex_id,
2467                    tolerance,
2468                    scale,
2469                );
2470                split_lap(5, &mut split_clock);
2471                os_debug!(
2472                    "wall×source pair ({index},{retained_id}) pieces+={}",
2473                    imprint.pieces.len() - pieces_before,
2474                );
2475            }
2476        }
2477    }
2478    // APEX-CAP ring splits: the cap × cone section lies ON the cone
2479    // carrier's promoted ring edge (an overlap, not a crossing), so
2480    // `build_imprints` mints no edge splits for the cone side. Without them
2481    // the cone keeps ONE closed ring edge while the cap carries the section
2482    // as arcs — mismatched segmentation, both sides one-use. Record the arc
2483    // junctions as splits on the cone's coincident edge.
2484    for (cone_index, cap_index) in &apex_cap_pairs {
2485        let cap_face_id = carriers[*cap_index].solid.shells[0].faces[0].id;
2486        let piece_ids = imprint
2487            .by_face
2488            .iter()
2489            .find(|entry| entry.operand == *cap_index as u8 && entry.face_id == cap_face_id)
2490            .map(|entry| entry.piece_ids.clone())
2491            .unwrap_or_default();
2492        let coincidence_band = 2e-5f64.max(scale * 1e-7);
2493        for piece_id in piece_ids {
2494            let Some((curve, t0, t1)) = imprint
2495                .pieces
2496                .iter()
2497                .find(|piece| piece.id == piece_id)
2498                .map(|piece| (piece.curve.clone(), piece.t0, piece.t1))
2499            else {
2500                continue;
2501            };
2502            for endpoint in [curve.evaluate(t0).or_refuse(KernelStage::Sew, "evaluate")?, curve.evaluate(t1).or_refuse(KernelStage::Sew, "evaluate")?] {
2503                for edge in &carriers[*cone_index].solid.edges {
2504                    if edge.degenerate {
2505                        continue;
2506                    }
2507                    let projection = crate::project_point_to_curve(&edge.curve, endpoint).or_refuse(KernelStage::Sew, "project_point_to_curve")?;
2508                    if projection.distance > coincidence_band
2509                        || projection.u < edge.t0 + 1e-9
2510                        || projection.u > edge.t1 - 1e-9
2511                    {
2512                        continue;
2513                    }
2514                    let parameter = projection.u;
2515                    if let Some(existing) = imprint.edge_splits.iter_mut().find(|split| {
2516                        split.operand == *cone_index as u8 && split.edge_id == edge.id
2517                    }) {
2518                        if !existing
2519                            .parameters
2520                            .iter()
2521                            .any(|value| (*value - parameter).abs() <= 1e-8)
2522                        {
2523                            existing.parameters.push(parameter);
2524                        }
2525                    } else {
2526                        imprint.edge_splits.push(EdgeSplitRecord {
2527                            operand: *cone_index as u8,
2528                            edge_id: edge.id,
2529                            parameters: vec![parameter],
2530                        });
2531                    }
2532                    os_debug!(
2533                        "apex-cap ring split: cone carrier {cone_index} edge {} at t={parameter:.6}",
2534                        edge.id,
2535                    );
2536                }
2537            }
2538        }
2539    }
2540    if debug_enabled() {
2541        for piece in &imprint.pieces {
2542            let start = piece.curve.evaluate(piece.t0);
2543            let mid = piece.curve.evaluate((piece.t0 + piece.t1) * 0.5);
2544            let end = piece.curve.evaluate(piece.t1);
2545            if let (Ok(start), Ok(mid), Ok(end)) = (start, mid, end) {
2546                os_debug!(
2547                    "piece[{}] ({:.4},{:.4},{:.4})..({:.4},{:.4},{:.4})..({:.4},{:.4},{:.4}) on {:?}",
2548                    piece.id,
2549                    start.x,
2550                    start.y,
2551                    start.z,
2552                    mid.x,
2553                    mid.y,
2554                    mid.z,
2555                    end.x,
2556                    end.y,
2557                    end.z,
2558                    piece.support_faces,
2559                );
2560                for pcurve in &piece.pcurves {
2561                    let uv = |t: f64| pcurve.pcurve.evaluate(t).map(|p| (p.x, p.y)).unwrap_or((f64::NAN, f64::NAN));
2562                    let [a, b] = pcurve.pcurve.domain().unwrap_or([0.0, 1.0]);
2563                    os_debug!(
2564                        "  pcurve operand={} face={} uv {:?}..{:?}..{:?}",
2565                        pcurve.operand, pcurve.face_id, uv(a), uv(0.5 * (a + b)), uv(b),
2566                    );
2567                }
2568            }
2569        }
2570    }
2571    os_debug!("tangent rim cuts imprinted: {}", tangent_rim_cuts.len());
2572    super::tangent_rim_cuts::drop_marched_rim_noise(&mut imprint, &tangent_rim_cuts, distance)?;
2573    let rim_cut_pieces = super::tangent_rim_cuts::imprint_tangent_rim_cuts(
2574        &mut imprint,
2575        &carriers,
2576        tangent_rim_cuts,
2577        &mut next_piece_id,
2578        &mut next_vertex_id,
2579        distance,
2580        tolerance,
2581        scale,
2582    )?;
2583    split_lap(6, &mut split_clock);
2584    synchronize_smooth_edge_splits(&mut imprint, &smooth.edge_pairs);
2585    split_lap(7, &mut split_clock);
2586    // This decides whether an imprint is genuinely the carrier's existing
2587    // trim, not whether independently fitted curves can later be sewn. The
2588    // looser assembly tolerance can erase a short separating branch while it
2589    // is still departing a boundary.
2590    let boundary_coincidence_tolerance = 2e-5f64.max(scale * 1e-7);
2591    let piece_geometry = imprint
2592        .pieces
2593        .iter()
2594        .map(|piece| {
2595            (
2596                piece.id,
2597                FragmentEdgeGeometry {
2598                    curve: piece.curve.clone(),
2599                    t0: piece.t0,
2600                    t1: piece.t1,
2601                },
2602            )
2603        })
2604        .collect::<HashMap<_, _>>();
2605    // A rim tube ends ON its opening's plane: its mouth reaches that
2606    // opening's wall as an orphan rim, welded into the cap like any skin's.
2607    // That wall's own copy of the section would cut the mouth a second time;
2608    // a section with any OTHER wall (a second opening the tube crosses) is a
2609    // true trim and stays.
2610    if !rim_tubes.is_empty() {
2611        for entry in imprint.by_face.iter_mut() {
2612            let Some(wall) = carriers.get(entry.operand as usize) else { continue };
2613            if !matches!(wall.kind, OffsetFaceRole::Wall) {
2614                continue;
2615            }
2616            let wall_opening = wall.source_face_id;
2617            entry.piece_ids.retain(|piece_id| {
2618                !imprint.pieces.iter().any(|piece| {
2619                    piece.id == *piece_id
2620                        && piece
2621                            .support_faces
2622                            .iter()
2623                            .any(|face| rim_tubes.get(&(face.operand as usize)) == Some(&wall_opening))
2624                })
2625            });
2626        }
2627    }
2628    for (index, carrier) in carriers.iter().enumerate() {
2629        if !matches!(carrier.kind, OffsetFaceRole::Offset) {
2630            continue;
2631        }
2632        // A rebuilt carrier keeps the edge records of the trim it replaced
2633        // (`full_rectangle_face` appends its rectangle to a copy). A tangent
2634        // rim cut restores exactly such a rim, so it is read against the
2635        // edges the trim USES; every other piece keeps the reading it had.
2636        let used_edges = carrier.solid.shells[0].faces[0]
2637            .loops
2638            .iter()
2639            .flat_map(|loop_record| &loop_record.coedges)
2640            .map(|coedge| coedge.edge_id)
2641            .collect::<HashSet<_>>();
2642        let boundaries = carrier
2643            .solid
2644            .edges
2645            .iter()
2646            .map(|edge| (used_edges.contains(&edge.id), FragmentEdgeGeometry {
2647                curve: edge.curve.clone(),
2648                t0: edge.t0,
2649                t1: edge.t1,
2650            }))
2651            .collect::<Vec<_>>();
2652        if let Some(by_face) = imprint
2653            .by_face
2654            .iter_mut()
2655            .find(|entry| entry.operand == index as u8)
2656        {
2657            let before = by_face.piece_ids.clone();
2658            by_face.piece_ids.retain(|piece_id| {
2659                let piece = &piece_geometry[piece_id];
2660                let rim_cut = rim_cut_pieces.contains(piece_id);
2661                !boundaries.iter().any(|(used, boundary)| {
2662                    (*used || !rim_cut)
2663                        && fragment_edge_lies_on(piece, boundary, boundary_coincidence_tolerance)
2664                            .unwrap_or(false)
2665                })
2666            });
2667            // Separate retained planes can imprint overlapping portions of the
2668            // same line on this carrier. Arrange that cut once: duplicate
2669            // segments otherwise erase the region between a blend section
2670            // and the line. Preserve each piece on its other carrier.
2671            let candidates = by_face.piece_ids.clone();
2672            by_face.piece_ids.retain(|id| {
2673                let edge = &piece_geometry[id];
2674                if edge.curve.degree != 1 || edge.curve.control_points.len() != 2 {
2675                    return true;
2676                }
2677                !candidates.iter().any(|other_id| {
2678                    if id == other_id { return false; }
2679                    let other = &piece_geometry[other_id];
2680                    if other.curve.degree != 1 || other.curve.control_points.len() != 2 {
2681                        return false;
2682                    }
2683                    fragment_edge_lies_on(edge, other, tolerance).unwrap_or(false)
2684                        && (other_id < id
2685                            || !fragment_edge_lies_on(other, edge, tolerance).unwrap_or(false))
2686                })
2687            });
2688            if debug_enabled() && before.len() != by_face.piece_ids.len() {
2689                os_debug!(
2690                    "carrier[{index}] dropped boundary-coincident pieces: {:?} -> {:?}",
2691                    before,
2692                    by_face.piece_ids,
2693                );
2694            }
2695        }
2696    }
2697
2698    if debug_enabled() {
2699        for entry in &imprint.by_face {
2700            os_debug!(
2701                "by_face operand={} face={} pieces={:?}",
2702                entry.operand,
2703                entry.face_id,
2704                entry.piece_ids,
2705            );
2706        }
2707    }
2708    split_lap(8, &mut split_clock);
2709    if split_profile {
2710        profile_line!(
2711            "offset_shell.imprint_split skips={:.3} pair_build={:.3} pair_merge={:.3} standalone={:.3} wall_build={:.3} wall_merge={:.3} ring={:.3} smooth={:.3} filter={:.3}",
2712            split_ms[0], split_ms[1], split_ms[2], split_ms[3], split_ms[4], split_ms[5], split_ms[6], split_ms[7], split_ms[8],
2713        );
2714    }
2715    profile::lap(&mut clock, profile::IMPRINT);
2716    let mut split_carriers = Vec::new();
2717    let mut fragments_by_carrier = Vec::new();
2718    for (index, carrier) in carriers.iter().enumerate() {
2719        // Offset carriers keep their boundary un-split (their trims never
2720        // coincide with imprints — the boundary-coincidence filter drops such
2721        // pieces instead). An apex-cap ring breaks that assumption: the
2722        // frustum's ring is its TRIM boundary while the cap crosses it as TWO
2723        // imprint arcs — without splitting, the two sides segment differently
2724        // and both stay one-use. Split exactly the cap-affected carriers.
2725        let split = if matches!(carrier.kind, OffsetFaceRole::Offset)
2726            && !apex_cap_sources.contains(&index)
2727        {
2728            carrier.solid.clone()
2729        } else {
2730            apply_edge_splits(&carrier.solid, index as u8, &imprint)?
2731        };
2732        let fragment_clock = web_time::Instant::now();
2733        let fragments = fragment_solid(&split, index as u8, &imprint)?;
2734        os_debug!(
2735            "carrier[{index}] kind={:?} src={} fragments={} ({:.3} ms)",
2736            carrier.kind,
2737            carrier.source_face_id,
2738            fragments.len(),
2739            fragment_clock.elapsed().as_secs_f64() * 1e3,
2740        );
2741        if debug_enabled() {
2742            for (fragment_index, fragment) in fragments.iter().enumerate() {
2743                let mut boundary_count = 0usize;
2744                let mut imprint_pieces = Vec::new();
2745                let mut derived_count = 0usize;
2746                for coedge in fragment
2747                    .loops
2748                    .iter()
2749                    .flat_map(|loop_record| &loop_record.coedges)
2750                {
2751                    match &coedge.source {
2752                        FragmentEdgeSource::Boundary { .. }
2753                        | FragmentEdgeSource::SharedBoundary { .. } => boundary_count += 1,
2754                        FragmentEdgeSource::Imprint { piece_id } => imprint_pieces.push(*piece_id),
2755                        FragmentEdgeSource::Derived { .. } => derived_count += 1,
2756                    }
2757                }
2758                os_debug!(
2759                    "  frag[{index}.{fragment_index}] test=({:.3},{:.3},{:.3}) uv=({:.3},{:.3}) boundary={boundary_count} derived={derived_count} pieces={imprint_pieces:?}",
2760                    fragment.test_point.x, fragment.test_point.y, fragment.test_point.z,
2761                    fragment.test_uv.x, fragment.test_uv.y,
2762                );
2763            }
2764        }
2765        split_carriers.push(split);
2766        fragments_by_carrier.push(fragments);
2767    }
2768    profile::lap(&mut clock, profile::FRAGMENT);
2769    let mut assembly_sources = [(SOURCE_OPERAND, source)]
2770        .into_iter()
2771        .collect::<HashMap<_, _>>();
2772    for (index, carrier) in split_carriers.iter().enumerate() {
2773        assembly_sources.insert(index as u8, carrier);
2774    }
2775
2776    let source_edge_by_id = source
2777        .edges
2778        .iter()
2779        .map(|edge| (edge.id, edge))
2780        .collect::<HashMap<_, _>>();
2781    let retained_faces_with_edges = retained
2782        .iter()
2783        .map(|face_id| {
2784            let face = source_by_id[face_id];
2785            let edges = face
2786                .loops
2787                .iter()
2788                .flat_map(|loop_record| &loop_record.coedges)
2789                .filter_map(|coedge| source_edge_by_id.get(&coedge.edge_id).copied())
2790                .collect::<Vec<_>>();
2791            (face, edges)
2792        })
2793        .collect::<Vec<_>>();
2794    let mut offset_skin_tolerance = offset_skin_band(scale, distance);
2795    // `BREP_OFFSET_THIN_SKIN_PAD`: the band's 2e-3 floor is a fixed length;
2796    // on a shell thinner than it (box-paper-thin, d = 1e-3) no point was ever
2797    // shadowed (`separation < d - 2e-3` cannot hold), so the opening's 1e-3
2798    // corner squares, holding no wall seed, read as the void and were left
2799    // out of the rim. A thin shell's band is held to a quarter of it.
2800    if thin_skin_pad_enabled() && distance > 0.0 {
2801        offset_skin_tolerance = offset_skin_tolerance.min(0.25 * distance.abs());
2802    }
2803    // OUTWARD shells: a wall fragment lying IN FRONT of another opening —
2804    // past that opening's plane on its void side, within the extent of its
2805    // (extended) wall carrier — is not material: an opening removes
2806    // everything in front of it. Such a fragment is the sheet of this wall
2807    // between the source outline and the grown outline on the far side of an
2808    // ADJACENT opening's shared edge (the x∈[−1,0] strip of an opened −Z
2809    // face's wall, in front of the opened −X face). It sits within |distance|
2810    // of a retained face's corner edge, so the void-cross-section guard reads
2811    // it as wall thickness; only the other opening's plane tells it apart.
2812    //
2813    // A RULED opening's wall is curved, so it has no one plane: its front is
2814    // read at the point's foot on the wall carrier, along the carrier's normal
2815    // turned to the opening face's outward side. On the torus wedge that is
2816    // what drops the start and end caps' strips beyond the extended chord,
2817    // which lie within |distance| of the torus and in front of the cone.
2818    let mut opening_planes: Vec<(usize, Vec3, Vec3)> = Vec::new();
2819    let mut opening_ruled: Vec<(usize, f64)> = Vec::new();
2820    if distance < 0.0 {
2821        for (index, carrier) in carriers.iter().enumerate() {
2822            if !matches!(carrier.kind, OffsetFaceRole::Wall) {
2823                continue;
2824            }
2825            let opening = source_by_id[&carrier.source_face_id];
2826            let [u0, u1] = opening.surface.domain_u().or_refuse(KernelStage::Sew, "domain_u")?;
2827            let [v0, v1] = opening.surface.domain_v().or_refuse(KernelStage::Sew, "domain_v")?;
2828            let (u, v) = ((u0 + u1) * 0.5, (v0 + v1) * 0.5);
2829            if ruled_walls.contains(&index) {
2830                let wall = &split_carriers[index].shells[0].faces[0];
2831                let probe = project_point_to_surface(&wall.surface, opening.surface.evaluate(u, v).or_refuse(KernelStage::Sew, "evaluate")?).or_refuse(KernelStage::Sew, "project_point_to_surface")?;
2832                let side = face_normal(wall, probe.u, probe.v)?.dot(face_normal(opening, u, v)?);
2833                opening_ruled.push((index, if side < 0.0 { -1.0 } else { 1.0 }));
2834                continue;
2835            }
2836            if !opening.surface.is_affine().or_refuse(KernelStage::Sew, "is_affine")? {
2837                continue;
2838            }
2839            opening_planes.push((
2840                index,
2841                opening.surface.evaluate(u, v).or_refuse(KernelStage::Sew, "evaluate")?,
2842                face_normal(opening, u, v)?,
2843            ));
2844        }
2845    }
2846    let in_front_of_other_opening = |wall_index: usize, point: Vec3| -> Result<bool, KernelRefusal> {
2847        let band = 2e-3f64.max(scale * 5e-5);
2848        for (index, plane_point, outward) in &opening_planes {
2849            if *index == wall_index || point.sub(*plane_point).dot(*outward) <= band {
2850                continue;
2851            }
2852            let face = &split_carriers[*index].shells[0].faces[0];
2853            let projection = project_point_to_surface(&face.surface, point).or_refuse(KernelStage::Sew, "project_point_to_surface")?;
2854            let uv = Vec2 {
2855                x: projection.u,
2856                y: projection.v,
2857            };
2858            if parameter_point_in_face(face, uv, 1e-8).or_refuse(KernelStage::Sew, "parameter_point_in_face")? != PolygonClass::Outside {
2859                return Ok(true);
2860            }
2861        }
2862        for (index, side) in &opening_ruled {
2863            if *index == wall_index {
2864                continue;
2865            }
2866            let face = &split_carriers[*index].shells[0].faces[0];
2867            let projection = project_point_to_surface(&face.surface, point).or_refuse(KernelStage::Sew, "project_point_to_surface")?;
2868            let outward = face_normal(face, projection.u, projection.v)?.scale(*side);
2869            if point.sub(projection.point).dot(outward) <= band {
2870                continue;
2871            }
2872            let uv = Vec2 {
2873                x: projection.u,
2874                y: projection.v,
2875            };
2876            if parameter_point_in_face(face, uv, 1e-8).or_refuse(KernelStage::Sew, "parameter_point_in_face")? != PolygonClass::Outside {
2877                return Ok(true);
2878            }
2879        }
2880        Ok(false)
2881    };
2882
2883    let mut chosen_offsets = Vec::new();
2884    let mut chosen_walls = Vec::new();
2885    let mut newly_shadowed = HashSet::<u64>::default();
2886    for (index, carrier) in carriers.iter().enumerate() {
2887        let raw_seeds = source_seeds(source, carrier.source_face_id)?;
2888        let mut seeds = Vec::with_capacity(raw_seeds.len());
2889        for raw_seed in raw_seeds {
2890            let seed = if matches!(carrier.kind, OffsetFaceRole::Offset) {
2891                offset_seed(
2892                    source_by_id[&carrier.source_face_id],
2893                    raw_seed,
2894                    &split_carriers[index].shells[0].faces[0].surface,
2895                    distance,
2896                    2e-3f64.max(scale * 5e-5),
2897                )?
2898                .unwrap_or(raw_seed)
2899            } else if inward_extended_walls.contains(&index) {
2900                offset_seed(
2901                    source_by_id[&carrier.source_face_id],
2902                    raw_seed,
2903                    &split_carriers[index].shells[0].faces[0].surface,
2904                    0.0,
2905                    2e-3f64.max(scale * 5e-5),
2906                )?
2907                .unwrap_or(raw_seed)
2908            } else {
2909                raw_seed
2910            };
2911            if seed.sub(raw_seed).length() > 1e-9 {
2912                os_debug!(
2913                    "  seed[{index}] moved from ({:.4},{:.4}) to the offset image ({:.4},{:.4})",
2914                    raw_seed.x,
2915                    raw_seed.y,
2916                    seed.x,
2917                    seed.y
2918                );
2919            }
2920            seeds.push(seed);
2921        }
2922        let seed = seeds[0];
2923        if matches!(carrier.kind, OffsetFaceRole::Offset) {
2924            // Fragments whose test point sits at the full offset distance
2925            // from every retained source face are the true offset-skin
2926            // regions. Fragments closer to some other face are shadowed
2927            // pockets/strips that another carrier owns.
2928            // A fragment whose offset lies ON another retained face's offset
2929            // (material exactly twice the shell distance thick: a slot, fin or
2930            // floor at t = 2d) reads as SHADOWED by that face. One hair
2931            // thinner, the same fragment reads shadowed on its own and is
2932            // dropped by the on-skin filter, or omits its carrier by the
2933            // skinless rule below, so the answer is the limit of that
2934            // construction: the census's L∞ forms are continuous across the
2935            // onset. Without this the fragment read On, was selected, and the
2936            // shell refused as "a cavity pinched to zero thickness". The
2937            // coincidence test is `coincident_offset_face`'s (the other face's
2938            // distance within `offset_skin_tolerance` of |d|, its foot on the
2939            // opposite side of the point from this face's own), taken only on
2940            // the THIN side of the onset.
2941            let mut readings = Vec::with_capacity(fragments_by_carrier[index].len());
2942            // The construction band allows a carrier's own fit residual. It
2943            // must not also preserve pockets buried by neighboring offsets:
2944            // that coverage is what justified admitting a finite cusp. Keep
2945            // the own-face reading unchanged, and measure other faces at the
2946            // fit tolerance for this construction.
2947            let cusp_neighbors = if shielded_cusps.is_empty() {
2948                Vec::new()
2949            } else {
2950                retained_faces_with_edges.iter()
2951                    .filter(|(face, _)| face.id != carrier.source_face_id)
2952                    .cloned().collect::<Vec<_>>()
2953            };
2954            for fragment in &fragments_by_carrier[index] {
2955                let reading = offset_skin_reading(
2956                    fragment.test_point,
2957                    &retained_faces_with_edges,
2958                    distance,
2959                    offset_skin_tolerance,
2960                );
2961                let reading = if matches!(&reading, SkinReading::On) && !cusp_neighbors.is_empty() {
2962                    offset_skin_reading(
2963                        fragment.test_point,
2964                        &cusp_neighbors,
2965                        distance,
2966                        4.0 * KernelTolerances::for_solid(source, 1e-7).intersection_fit,
2967                    )
2968                } else {
2969                    reading
2970                };
2971                let reading = match reading {
2972                    SkinReading::On => match coincident_offset_face(
2973                        fragment.test_point,
2974                        carrier.source_face_id,
2975                        &retained_faces_with_edges,
2976                        distance,
2977                        offset_skin_tolerance,
2978                    )? {
2979                        // ONE-SIDED and tight: only material no thicker than
2980                        // 2|d| (to 10× the model tolerance) takes the thin
2981                        // construction, which is exact there. A wall inside
2982                        // the skin band but genuinely thicker than 2|d| keeps
2983                        // its sliver cavity's named refusal below; taking the
2984                        // thin construction there would fill a real cavity.
2985                        Some((face, separation)) if separation <= distance.abs() + tolerance * 10.0 => {
2986                            // A coincidence the fragment's other interior
2987                            // points do not share is a tangent TOUCH: the
2988                            // cavity pinches to a line there, and dropping the
2989                            // fragment as a sheet would discard real skin.
2990                            if tangent_touch_on() {
2991                                if let Some((farther, far)) = tangent_touch(
2992                                    fragment,
2993                                    face,
2994                                    &retained_faces_with_edges,
2995                                    distance,
2996                                    offset_skin_tolerance,
2997                                )? {
2998                                    return Err(KernelRefusal::unsupported(KernelStage::Select, refusals::TANGENT_OFFSETS, format!(
2999                                        "offset_shell: the offsets of source faces {} and {face} touch tangentially near \
3000                                         ({:.4}, {:.4}, {:.4}) — the material between those faces is exactly twice the \
3001                                         shell distance thick along that touch (separation {separation:.6} against {:.6}) \
3002                                         and thicker beside it (the offset reads {far:.4} from face {face} at ({:.4}, {:.4}, {:.4})), so the cavity would \
3003                                         pinch to a line there; a cavity pinched to a line is not supported — use a \
3004                                         shell distance a little below {:.4}",
3005                                        carrier.source_face_id,
3006                                        fragment.test_point.x,
3007                                        fragment.test_point.y,
3008                                        fragment.test_point.z,
3009                                        distance.abs(),
3010                                        farther.x,
3011                                        farther.y,
3012                                        farther.z,
3013                                        distance.abs(),
3014                                    )));
3015                                }
3016                            }
3017                            SkinReading::Shadowed { face, separation }
3018                        }
3019                        _ => SkinReading::On,
3020                    },
3021                    other => other,
3022                };
3023                // One test point cannot speak for a skin that bounds a cavity
3024                // the solid demonstrably has: see `cavity_witness`.
3025                let reading = match reading {
3026                    SkinReading::Shadowed { .. } if cavity_bounds.contains(&carrier.source_face_id) => SkinReading::On,
3027                    other => other,
3028                };
3029                readings.push(reading);
3030            }
3031            for (fragment, reading) in fragments_by_carrier[index].iter().zip(&readings) {
3032                if let SkinReading::Unmeasured { face, reason } = reading {
3033                    return Err(unmeasured_skin_refusal(fragment.test_point, *face, reason));
3034                }
3035            }
3036            if mixed_fragment_report_on() {
3037                let mut omitted = shadowed_supports.iter().copied().collect::<Vec<_>>();
3038                omitted.sort_unstable();
3039                for (fragment_index, (fragment, reading)) in fragments_by_carrier[index].iter().zip(&readings).enumerate() {
3040                    let Some(mixed) = mixed_fragment_reading(fragment, source, &retained_faces_with_edges, distance, offset_skin_tolerance)? else { continue };
3041                    if mixed.mixed() {
3042                        eprintln!(
3043                            "MIXED-FRAGMENT d={distance} omitted={omitted:?} src={} fragment={fragment_index} skin={} shadowed={} of {} shadowing={:?} test_reading={} test=({:.4},{:.4},{:.4})",
3044                            carrier.source_face_id, mixed.skin, mixed.shadowed, mixed.inside, mixed.shadowing,
3045                            match reading { SkinReading::On => "On", SkinReading::Shadowed { .. } => "Shadowed", SkinReading::Unmeasured { .. } => "Unmeasured" },
3046                            fragment.test_point.x, fragment.test_point.y, fragment.test_point.z,
3047                        );
3048                    }
3049                }
3050            }
3051            // EVERY fragment measured nearer than the distance to some other
3052            // retained face: this support's offset is SHADOWED over its whole
3053            // extended carrier — the side walls of a slot narrower than 2|d|
3054            // grown outward, a pocket floor within 2d of the face under it.
3055            // It owns no skin. It used to switch the filter off and keep its
3056            // seeded fragment anyway, which built a closed, validating shell
3057            // with an inverted box inside it (+90 on a width-2 slot grown by
3058            // 1.5, with the 90 of material at its centre missing). Dropping
3059            // only its fragments is not enough: its carrier has already cut
3060            // its neighbours, and the top skin over that slot keeps a hole
3061            // nothing fills. So the pass is re-run with the support omitted
3062            // before the imprint, like a collapsed one. An apex-cap sphere
3063            // shares its cone's source id and is not judged here.
3064            //
3065            // Only the FIRST pass omits. A test point speaks for its fragment
3066            // because every other carrier's imprint bounds it; omitting a
3067            // carrier removes cuts, merges fragments and moves test points,
3068            // but changes no distance, so a support that reads shadowed only
3069            // AFTER an omission is reading a test point that no longer stands
3070            // for its fragment. Measured on two bosses 1 apart grown outward
3071            // by 1.5: once the facing boss walls were omitted, the plate's
3072            // grown top — one uncut fragment, mostly skin — read shadowed at
3073            // its single test point.
3074            //
3075            // "Every fragment" counts a fragment the selection would drop by
3076            // CLASS as not skin, as the selection does: the extended carrier's
3077            // surplus past a slot's end reads at least the distance from every
3078            // face, lies inside the source, and on a slot 1 wide grown outward
3079            // left the slot floor unjudged until the side walls were gone.
3080            // ADRIFT: a fragment whose test point is farther from its OWN face
3081            // than the distance, in the mitered metric, is not that face's skin
3082            // — it is inside the cavity, past where its neighbours' offsets cut
3083            // it. A rib, a pin or a divider thinner than 2d shelled inward
3084            // keeps such fragments, and the assembly then fails on them.
3085            let adrift = fragments_by_carrier[index]
3086                .iter()
3087                .map(|fragment| {
3088                    point_adrift_of_its_own_offset(
3089                        fragment.test_point,
3090                        carrier.source_face_id,
3091                        &retained_faces_with_edges,
3092                        distance,
3093                        offset_skin_tolerance,
3094                    )
3095                })
3096                .collect::<Vec<_>>();
3097            let mut skinless = readings
3098                .iter()
3099                .any(|reading| matches!(reading, SkinReading::Shadowed { .. }))
3100                || adrift.iter().any(|flag| *flag);
3101            for (fragment, reading) in fragments_by_carrier[index].iter().zip(&readings) {
3102                if !skinless {
3103                    break;
3104                }
3105                if matches!(reading, SkinReading::On)
3106                    && !adrift[fragments_by_carrier[index]
3107                        .iter()
3108                        .position(|other| std::ptr::eq(other, fragment))
3109                        .unwrap_or(0)]
3110                {
3111                    let class = classify_point(fragment.test_point, source, tolerance * 10.0).or_refuse(KernelStage::Sew, "classify_point")?.class;
3112                    skinless = (distance > 0.0 && class == PointClass::Out)
3113                        || (distance < 0.0 && class == PointClass::In);
3114                }
3115            }
3116            #[cfg(not(test))]
3117            let forced_shadow = false;
3118            let skinless = skinless || forced_shadow;
3119            if skinless && !apex_cap_sources.contains(&index) {
3120                if body == Body::Shell && distance > 0.0 && cascade_omission_enabled() && !forced_shadow {
3121                    let held = fragments_holding_true_skin(
3122                        source_by_id[&carrier.source_face_id],
3123                        source,
3124                        &fragments_by_carrier[index],
3125                        &retained_faces_with_edges,
3126                        distance,
3127                        offset_skin_tolerance,
3128                    )?;
3129                    if !held.is_empty() {
3130                        os_debug!("  select[{index}] src={}: {} fragment(s) hold true skin", carrier.source_face_id, held.len());
3131                        chosen_offsets.extend(held);
3132                        continue;
3133                    }
3134                }
3135                if !shadowed_supports.is_empty() && !(body == Body::Shell && distance > 0.0 && cascade_omission_enabled()) {
3136                    let mut omitted = shadowed_supports.iter().copied().collect::<Vec<_>>();
3137                    omitted.sort_unstable();
3138                    return Err(KernelRefusal::unsupported(KernelStage::Select, "offset_shell_shadow_cascade", format!(
3139                        "offset_shell: omitting the shadowed offsets of source faces {omitted:?} \
3140                         leaves the offset of source face {} shadowed at every one of its {} \
3141                         fragment test points, which no longer stand for their fragments once \
3142                         those carriers stop cutting it",
3143                        carrier.source_face_id,
3144                        readings.len()
3145                    )));
3146                }
3147                if surviving_tubes.contains(&index) {
3148                    os_debug!("  select[{index}] src={}: a surviving round's rim tube reads shadowed; only the tube is dropped", carrier.source_face_id);
3149                    continue;
3150                }
3151                // A band piece buried whole is that piece's answer, not its
3152                // face's: its siblings may still bound material. Its carrier
3153                // stays in the imprint, so the cuts it makes are unchanged.
3154                if band_pieces.contains(&index)
3155                    && carriers.iter().enumerate().any(|(other, sibling)| {
3156                        other != index && sibling.source_face_id == carrier.source_face_id && band_pieces.contains(&other)
3157                    })
3158                {
3159                    os_debug!("  select[{index}] src={}: a band piece reads shadowed; only the piece is dropped", carrier.source_face_id);
3160                    continue;
3161                }
3162                os_debug!(
3163                    "  select[{index}] src={} SHADOWED over all {} fragment(s): {:?}",
3164                    carrier.source_face_id,
3165                    readings.len(),
3166                    readings
3167                );
3168                newly_shadowed.insert(carrier.source_face_id);
3169                continue;
3170            }
3171            // Partly shadowed: keep a bounded sample of the shadowed test
3172            // points, so a refusal can say where two offsets cross.
3173            for (fragment, reading) in fragments_by_carrier[index].iter().zip(&readings) {
3174                if shadowed_points.len() >= MAXIMUM_CROSSING_READS {
3175                    break;
3176                }
3177                if matches!(reading, SkinReading::Shadowed { .. }) {
3178                    shadowed_points.push((fragment.test_point, carrier.source_face_id));
3179                }
3180            }
3181            let mut on_skin = readings
3182                .iter()
3183                .zip(&adrift)
3184                .map(|(reading, adrift)| matches!(reading, SkinReading::On) && !adrift)
3185                .collect::<Vec<_>>();
3186            if open_section_reach {
3187                if let Some(ends) = open_profile_end_neighbours(index, &carriers, &source_faces)? {
3188                    // A continued variable profile can approach its original
3189                    // end cap inside the distance band. Its sharp boundary is
3190                    // the section with the OFFSET end plane, not that old cap.
3191                    for (keep, fragment) in on_skin.iter_mut().zip(&fragments_by_carrier[index]) {
3192                        *keep = !outside_continued_neighbours(fragment.test_point, &ends, &carriers, tolerance)?;
3193                    }
3194                    os_debug!("  select[{index}] open profile kept {} central regions", on_skin.iter().filter(|keep| **keep).count());
3195                }
3196            }
3197            // A synthetic apex sphere has no source-face seed of its own to
3198            // fall back to. When its whole cap is hidden by retained offsets,
3199            // keep its cuts but contribute no skin. Otherwise the fallback
3200            // selects the uncut sphere as a stray patch inside the material.
3201            // The parent cone remains subject to the ordinary selection.
3202            let skin_filter_active = on_skin.iter().any(|flag| *flag)
3203                || apex_cap_pairs.iter().any(|(_, cap)| *cap == index);
3204            let opening_limits = if inward_extended_walls.is_empty() {
3205                Vec::new()
3206            } else {
3207                let openings = inward_extended_walls
3208                    .iter()
3209                    .map(|index| source_by_id[&carriers[*index].source_face_id])
3210                    .collect::<Vec<_>>();
3211                opening_trim_halfspaces(source_by_id[&carrier.source_face_id], &openings, tolerance)?
3212            };
3213            let mut classified = Vec::new();
3214            let mut viable = Vec::new();
3215            for (fragment_index, fragment) in fragments_by_carrier[index].iter().enumerate() {
3216                let class = classify_point(fragment.test_point, source, tolerance * 10.0).or_refuse(KernelStage::Sew, "classify_point")?.class;
3217                let excluded_by_class = (distance > 0.0 && class == PointClass::Out)
3218                    || (distance < 0.0 && class == PointClass::In);
3219                let contact = if excluded_by_class {
3220                    false
3221                } else {
3222                    distance > 0.0
3223                        && fragment_has_sustained_source_contact(
3224                            fragment,
3225                            &source_faces,
3226                            &assembly_sources,
3227                            &imprint,
3228                            2e-3f64.max(scale * 5e-5),
3229                        )?
3230                };
3231                os_debug!(
3232                    "  select[{index}.{fragment_index}] class={class:?} contact={contact} on_skin={} reading={:?} adrift={} seed_in={:?} uv=({:.3},{:.3}) at ({:.4},{:.4},{:.4})",
3233                    on_skin[fragment_index],
3234                    readings[fragment_index],
3235                    adrift[fragment_index],
3236                    parameter_point_in_face(&fragment_as_trim(fragment), seed, 1e-8),
3237                    fragment.test_uv.x, fragment.test_uv.y,
3238                    fragment.test_point.x, fragment.test_point.y, fragment.test_point.z,
3239                );
3240                let past_opening = opening_limits.iter().any(|(origin, normal)| {
3241                    fragment.test_point.sub(*origin).dot(*normal) < -tolerance * 10.0
3242                });
3243                if excluded_by_class
3244                    || past_opening
3245                    || (skin_filter_active && !on_skin[fragment_index])
3246                {
3247                    continue;
3248                }
3249                classified.push(fragment.clone());
3250                if contact {
3251                    continue;
3252                }
3253                viable.push(fragment.clone());
3254            }
3255            // One skin per REGION of the source face (see `source_seeds`):
3256            // every region of a pinched face is offset like a face of its
3257            // own, and the selection below answers each region's seed. An
3258            // ordinary face has the one seed and the one answer it always had.
3259            let mut region_skins = Vec::new();
3260            let continued_neighbours = if distance > 0.0 {
3261                continued_sphere_neighbours(index, &carriers, &source_faces, scale)?
3262            } else { None };
3263            if let Some(neighbours) = &continued_neighbours {
3264                for fragment in &classified {
3265                    if outside_continued_neighbours(fragment.test_point, neighbours, &carriers, tolerance)? {
3266                        region_skins.push(fragment.clone());
3267                    }
3268                }
3269                os_debug!("  select[{index}] continued sphere kept {} regions", region_skins.len());
3270            }
3271            for &seed in seeds.iter().filter(|_| continued_neighbours.is_none()) {
3272                os_debug!("  select[{index}] seed=({:.4},{:.4})", seed.x, seed.y);
3273                let seeded = viable
3274                    .iter()
3275                    .filter(|fragment| {
3276                        parameter_point_in_face(&fragment_as_trim(fragment), seed, 1e-8)
3277                            .is_ok_and(|class| class != PolygonClass::Outside)
3278                    })
3279                    .cloned()
3280                    .collect::<Vec<_>>();
3281                let seeded_classified = classified
3282                    .iter()
3283                    .filter(|fragment| {
3284                        parameter_point_in_face(&fragment_as_trim(fragment), seed, 1e-8)
3285                            .is_ok_and(|class| class != PolygonClass::Outside)
3286                    })
3287                    .cloned()
3288                    .collect::<Vec<_>>();
3289                let selected = if viable.is_empty() {
3290                    if !skin_filter_active {
3291                        // NOTHING on this carrier reads on-skin: every classified
3292                        // fragment's test point is measurably CLOSER than the
3293                        // offset distance to some retained face — a buried strip
3294                        // another carrier owns. Forcing the largest one in anyway
3295                        // plants a wrong skin patch that collides with the
3296                        // completion phase's reconstruction (3-use edges).
3297                        // Contribute nothing: `complete_opening_boundary_cycles`
3298                        // rebuilds the true skin from the carrier surface, and the
3299                        // watertight gate still refuses if it cannot.
3300                        None
3301                    } else {
3302                        // ON ITS OWN OFFSET (`BREP_OFFSET_STAND_IN_ON_OWN_OFFSET`):
3303                        // the stand-in is drawn only from the pieces whose test
3304                        // point lies the distance from the carrier's OWN trimmed
3305                        // face, the one holding the seed first. A cylinder kept
3306                        // as one face is offset on its full turn, and the part
3307                        // of that turn buried in the neighbouring wall comes
3308                        // out as a larger piece than the face's own image (a
3309                        // boss whose axis sits inside the wall: 2.4 from the
3310                        // cylinder against 0.1); chosen by area it closed the
3311                        // shell around a skin inside the material.
3312                        let mut pool = classified.clone();
3313                        let mut seeded_own = None;
3314                        if stand_in_on_own_offset_on() {
3315                            let own = classified
3316                                .iter()
3317                                .filter(|fragment| {
3318                                    own_offset_departure(fragment.test_point, carrier.source_face_id, &retained_faces_with_edges, distance)
3319                                        .is_some_and(|departure| departure.abs() <= offset_skin_tolerance)
3320                                })
3321                                .cloned()
3322                                .collect::<Vec<_>>();
3323                            if !own.is_empty() {
3324                                let mut seeded = own
3325                                    .iter()
3326                                    .filter(|fragment| {
3327                                        parameter_point_in_face(&fragment_as_trim(fragment), seed, 1e-8)
3328                                            .is_ok_and(|class| class != PolygonClass::Outside)
3329                                    })
3330                                    .cloned()
3331                                    .collect::<Vec<_>>();
3332                                seeded.sort_by(|a, b| a.test_uv.sub(seed).length().total_cmp(&b.test_uv.sub(seed).length()));
3333                                seeded_own = seeded.into_iter().next();
3334                                pool = own;
3335                            }
3336                        }
3337                        let mut by_area = pool
3338                            .iter()
3339                            .cloned()
3340                            .map(|fragment| {
3341                                let area = parameter_space_area(&fragment_as_trim(&fragment)).or_refuse(KernelStage::Sew, "parameter_space_area")?.abs();
3342                                Ok((fragment, area))
3343                            })
3344                            .collect::<Result<Vec<_>, KernelRefusal>>()?;
3345                        by_area.sort_by(|a, b| b.1.total_cmp(&a.1));
3346                        seeded_own.or_else(|| by_area.into_iter().next().map(|entry| entry.0))
3347                    }
3348                } else if !seeded_classified.is_empty() {
3349                    let mut candidates = seeded_classified;
3350                    candidates.sort_by(|a, b| {
3351                        a.test_uv
3352                            .sub(seed)
3353                            .length()
3354                            .total_cmp(&b.test_uv.sub(seed).length())
3355                    });
3356                    candidates.into_iter().next()
3357                } else if viable.len() > 2 {
3358                    let mut by_area = viable
3359                        .iter()
3360                        .cloned()
3361                        .map(|fragment| {
3362                            let area = parameter_space_area(&fragment_as_trim(&fragment)).or_refuse(KernelStage::Sew, "parameter_space_area")?.abs();
3363                            Ok((fragment, area))
3364                        })
3365                        .collect::<Result<Vec<_>, KernelRefusal>>()?;
3366                    by_area.sort_by(|a, b| b.1.total_cmp(&a.1));
3367                    by_area.into_iter().next().map(|entry| entry.0)
3368                } else {
3369                    let mut candidates = if seeded.is_empty() { viable.clone() } else { seeded };
3370                    candidates.sort_by(|a, b| {
3371                        a.test_uv
3372                            .sub(seed)
3373                            .length()
3374                            .total_cmp(&b.test_uv.sub(seed).length())
3375                    });
3376                    candidates.into_iter().next()
3377                };
3378                let mut drop_debris = false;
3379                if let Some(fragment) = &selected {
3380                    os_debug!(
3381                        "  select[{index}] src={} chosen test point departs its own face's offset \
3382                         distance by {:?}",
3383                        carrier.source_face_id,
3384                        own_offset_departure(
3385                            fragment.test_point,
3386                            carrier.source_face_id,
3387                            &retained_faces_with_edges,
3388                            distance
3389                        )
3390                    );
3391                    os_debug!(
3392                        "  select[{index}] src={} chosen test point departs in the MITER metric by {:?}",
3393                        carrier.source_face_id,
3394                        own_miter_departure(
3395                            fragment.test_point,
3396                            carrier.source_face_id,
3397                            &retained_faces_with_edges,
3398                            distance
3399                        )
3400                    );
3401                    let coincidence = coincident_offset_face(
3402                        fragment.test_point,
3403                        carrier.source_face_id,
3404                        &retained_faces_with_edges,
3405                        distance,
3406                        offset_skin_tolerance,
3407                    )?;
3408                    let coincidence = match coincidence {
3409                        Some((other, separation))
3410                            if coincide_debris_on()
3411                                && fragment_is_band_debris(fragment, offset_skin_tolerance)? =>
3412                        {
3413                            os_debug!(
3414                                "  select[{index}] src={} drops corner debris coincident with {other} \
3415                                 (separation {separation}) at {:?}",
3416                                carrier.source_face_id,
3417                                fragment.test_point
3418                            );
3419                            drop_debris = true;
3420                            None
3421                        }
3422                        reading => reading,
3423                    };
3424                    if let Some((other, separation)) = coincidence {
3425                        return Err(KernelRefusal::unsupported(KernelStage::Select, "offset_shell_coincident_offsets", format!(
3426                            "offset_shell: the offsets of source faces {} and {other} coincide near \
3427                             ({:.4}, {:.4}, {:.4}) — the material between those faces is twice the \
3428                             shell distance thick (separation {separation:.6} against {:.6}, band \
3429                             {offset_skin_tolerance:.1e}), so the cavity between them has no \
3430                             thickness there; a cavity pinched to zero thickness is not supported",
3431                            carrier.source_face_id,
3432                            fragment.test_point.x,
3433                            fragment.test_point.y,
3434                            fragment.test_point.z,
3435                            distance.abs(),
3436                        )));
3437                    }
3438                }
3439                let selected = if drop_debris { None } else { selected };
3440                if let Some(fragment) = selected {
3441                    // A pinched face's seeds each find their own region; a
3442                    // fallback that ignores the seed can answer the same
3443                    // fragment twice, and one skin must enter once.
3444                    if !region_skins
3445                        .iter()
3446                        .any(|other: &FaceFragmentRecord| {
3447                            other.test_point.sub(fragment.test_point).length() <= 1e-12
3448                        })
3449                    {
3450                        region_skins.push(fragment);
3451                    }
3452                }
3453            }
3454            // EVERY SKIN PIECE (`BREP_OFFSET_EVERY_SKIN_PIECE`, default on):
3455            // one source region's offset skin can come out in several pieces
3456            // when another offset cuts it (the drilled block's bore skin,
3457            // radius 4, runs into the wall skin x = 19 and parts it at
3458            // y = 10 ± √15/2) or the carrier's seam parts it (the bore skin
3459            // itself, at its seam). The seed answers one piece; every
3460            // classified fragment already reads on the skin, inside the source
3461            // and short of the openings, so all of them are the skin, as for
3462            // the extended walls below. Left out, the pieces the seed missed
3463            // left their outlines one-use (shell/hole-skin-merging-wall).
3464            // Only where the seed could not choose: an inward shell whose every
3465            // on-skin fragment touches the source (`viable` empty), so the
3466            // largest stood in for the region; an outward shell's fragments and
3467            // a seeded choice keep the seed's answer. And only a piece whose
3468            // test point lies the distance from its OWN trimmed face: "on the
3469            // skin" says no retained face is nearer, which a point inside the
3470            // offset body also reads (the cylinder's offset past a reflex
3471            // junction, inside the box's offset wall: 0.139 from the trimmed
3472            // cylinder against 0.1, reflex_junction_under_a_filleted_top).
3473            if every_skin_piece_enabled()
3474                && distance > 0.0
3475                && (viable.is_empty() || every_seeded_piece)
3476                && skin_filter_active
3477                && inward_extended_walls.is_empty()
3478                && classified.len() > region_skins.len()
3479            {
3480                for fragment in &classified {
3481                    if region_skins.iter().any(|other: &FaceFragmentRecord| other.test_point.sub(fragment.test_point).length() <= 1e-12) {
3482                        continue;
3483                    }
3484                    let departure = own_offset_departure(fragment.test_point, carrier.source_face_id, &retained_faces_with_edges, distance);
3485                    os_debug!("  select[{index}] every skin piece: test point ({:.4},{:.4},{:.4}) departs its own face's offset by {departure:?}", fragment.test_point.x, fragment.test_point.y, fragment.test_point.z);
3486                    if departure.is_some_and(|departure| departure.abs() <= offset_skin_tolerance) {
3487                        region_skins.push(fragment.clone());
3488                    }
3489                }
3490            }
3491            if !inward_extended_walls.is_empty() && skin_filter_active {
3492                // The extended opening cuts beyond the source footprint.
3493                // Other finite carriers can subdivide a connected offset
3494                // region there (the box/revolve report splits both box caps
3495                // at x=1). A single source seed keeps only one of those cells.
3496                // Keep every cell already proved inside the source and on
3497                // the offset skin, then merge their shared boundaries.
3498                region_skins = classified;
3499            }
3500            chosen_offsets.extend(region_skins);
3501        } else if body == Body::Whole {
3502            // A HELD face of the offset body: its carrier is the face at
3503            // distance zero, cut by the neighbouring offset skins; the body
3504            // keeps the region the face's own seed lies in, whole. There is
3505            // no source rim to stop at and no void in front of it.
3506            for (fragment_index, fragment) in fragments_by_carrier[index].iter().enumerate() {
3507                if seeds.iter().any(|seed| {
3508                    parameter_point_in_face(&fragment_as_trim(fragment), *seed, 1e-8)
3509                        .is_ok_and(|class| class != PolygonClass::Outside)
3510                }) {
3511                    os_debug!("  held[{index}.{fragment_index}] kept: contains the face's seed");
3512                    chosen_walls.push(fragment.clone());
3513                }
3514            }
3515        } else {
3516            // Keep arrangement order stable. Besides making the result
3517            // reproducible, this matches the reference kernel's Set insertion
3518            // order when the final manifold-wall guard admits fragments.
3519            let opening = source_by_id[&carrier.source_face_id];
3520            let wall_seeds = opening_wall_seeds(
3521                opening,
3522                &split_carriers[index].shells[0].faces[0],
3523                source,
3524                &opening_set,
3525                distance,
3526            )?;
3527            // The wall-seed exemptions below rest on "the coplanar-rim weld
3528            // cuts the void hole later" — which only ever happens on PLANAR
3529            // opening carriers. A curved carrier (e.g. the sphere face used
3530            // directly as the opening) keeps its un-split fragment forever:
3531            // exempting it would seal the opening with the source face itself
3532            // and fabricate a closed hollow solid. Curved carriers therefore
3533            // get the strict void guard.
3534            let carrier_planar =
3535                surface_is_planar(&split_carriers[index].shells[0].faces[0].surface, tolerance)
3536                    .unwrap_or(false);
3537            let extended_inward = inward_extended_walls.contains(&index);
3538            let outside_source = |point| -> Result<bool, KernelRefusal> {
3539                Ok(extended_inward
3540                    && classify_point(point, source, tolerance * 10.0)
3541                        .or_refuse(KernelStage::Select, "classify_point")?.class == PointClass::Out)
3542            };
3543            let wall_on_skin = |point| {
3544                if extended_inward {
3545                    let inside_source = classify_point(point, source, tolerance * 10.0)
3546                        .or_refuse(KernelStage::Select, "classify_point")?.class == PointClass::In;
3547                    point_on_inward_opening_skin(
3548                        point,
3549                        &retained_faces_with_edges,
3550                        &reflex_wall_neighbors[&index],
3551                        inside_source,
3552                        distance,
3553                        offset_skin_tolerance,
3554                    )
3555                } else {
3556                    point_on_offset_skin(
3557                        point,
3558                        &retained_faces_with_edges,
3559                        distance,
3560                        offset_skin_tolerance,
3561                    )
3562                }
3563            };
3564            let mut selected_indices = Vec::new();
3565            for (fragment_index, fragment) in fragments_by_carrier[index].iter().enumerate() {
3566                if outside_source(fragment.test_point)? {
3567                    continue;
3568                }
3569                if parameter_point_in_face(&fragment_as_trim(fragment), seed, 1e-8).or_refuse(KernelStage::Sew, "parameter_point_in_face")?
3570                    == PolygonClass::Outside
3571                {
3572                    if in_front_of_other_opening(index, fragment.test_point)? {
3573                        os_debug!(
3574                            "  wall[{index}.{fragment_index}] skipped: in front of another \
3575                             opening at ({:.3},{:.3},{:.3})",
3576                            fragment.test_point.x,
3577                            fragment.test_point.y,
3578                            fragment.test_point.z,
3579                        );
3580                        continue;
3581                    }
3582                    // Wall = the material cross-section exposed at the
3583                    // opening: every point of a genuine wall fragment lies
3584                    // WITHIN the offset distance of some retained face (it is
3585                    // the thickness between that face and its offset skin). A
3586                    // fragment at ≥ distance from EVERY retained face — and
3587                    // containing no expected wall seed (an un-split cap
3588                    // fragment can span both the void AND the wall annulus;
3589                    // the coplanar-rim weld cuts its hole later) — is the
3590                    // core's own cross-section: a HOLE in the opening (e.g.
3591                    // the corner void where a carve's offset circle passes
3592                    // just inside the opening's corner). Welding it shut
3593                    // would fabricate a wall over the void.
3594                    if wall_on_skin(fragment.test_point)? && !(carrier_planar
3595                        && !extended_inward
3596                        && wall_seeds.iter().any(|wall_seed| {
3597                            parameter_point_in_face(&fragment_as_trim(fragment), *wall_seed, 1e-8)
3598                                .is_ok_and(|class| class != PolygonClass::Outside)
3599                        }))
3600                    {
3601                        os_debug!(
3602                            "  wall[{index}.{fragment_index}] skipped: void cross-section at \
3603                             ({:.3},{:.3},{:.3})",
3604                            fragment.test_point.x,
3605                            fragment.test_point.y,
3606                            fragment.test_point.z,
3607                        );
3608                        continue;
3609                    }
3610                    // A SURPLUS fragment beyond a sharp convex corner: it
3611                    // touches the wall's own outline, no edge of it was cut by
3612                    // the SOURCE (the rim every genuine wall region borders),
3613                    // and it holds no wall seed. The void test above reads it
3614                    // as material, because it measures a planar neighbour in the
3615                    // MITER metric (its extended plane, 0.277 from this region
3616                    // on the free-form D turning 83.7° at d = 0.3). The
3617                    // opening wall's clearance cuts such a region off between
3618                    // the carriers' tails past the mitre, and kept, it
3619                    // assembled as "non-integral genus" (8 of the D band's 42
3620                    // cells, 2026-09-26).
3621                    if distance < 0.0
3622                        && wall_surplus_beyond_the_sections(fragment, index as u8, |piece_id| {
3623                            imprint.pieces.iter().find(|piece| piece.id == piece_id).is_some_and(|piece| {
3624                                piece.support_faces.iter().any(|key| key.operand == SOURCE_OPERAND)
3625                            })
3626                        })
3627                        && !wall_seeds.iter().any(|wall_seed| {
3628                            parameter_point_in_face(&fragment_as_trim(fragment), *wall_seed, 1e-8)
3629                                .is_ok_and(|class| class != PolygonClass::Outside)
3630                        })
3631                    {
3632                        os_debug!(
3633                            "  wall[{index}.{fragment_index}] skipped: surplus beyond the sections at \
3634                             ({:.3},{:.3},{:.3}), touching the wall outline and no source rim",
3635                            fragment.test_point.x,
3636                            fragment.test_point.y,
3637                            fragment.test_point.z,
3638                        );
3639                        continue;
3640                    }
3641                    selected_indices.push(fragment_index);
3642                }
3643            }
3644            for wall_seed in wall_seeds {
3645                let fragments = &fragments_by_carrier[index];
3646                let nearest_containing = fragments
3647                    .iter()
3648                    .enumerate()
3649                    .filter(|(_, fragment)| {
3650                        parameter_point_in_face(&fragment_as_trim(fragment), wall_seed, 1e-8)
3651                            .is_ok_and(|class| class != PolygonClass::Outside)
3652                    })
3653                    .min_by(|(_, first), (_, second)| {
3654                        first
3655                            .test_uv
3656                            .sub(wall_seed)
3657                            .length()
3658                            .total_cmp(&second.test_uv.sub(wall_seed).length())
3659                    })
3660                    .map(|(fragment_index, _)| fragment_index);
3661                // Arrangement fitting can leave the seed just outside every
3662                // fragment by a small amount. Match the reference kernel's
3663                // geometric fallback instead of silently omitting the wall
3664                // fragment and leaving the assembled shell open.
3665                let nearest = if nearest_containing.is_some() {
3666                    nearest_containing
3667                } else {
3668                    let seed_point = split_carriers[index].shells[0].faces[0]
3669                        .surface
3670                        .evaluate(wall_seed.x, wall_seed.y).or_refuse(KernelStage::Sew, "evaluate")?;
3671                    fragments
3672                        .iter()
3673                        .enumerate()
3674                        .min_by(|(_, first), (_, second)| {
3675                            first
3676                                .test_point
3677                                .sub(seed_point)
3678                                .length()
3679                                .total_cmp(&second.test_point.sub(seed_point).length())
3680                        })
3681                        .map(|(fragment_index, _)| fragment_index)
3682                };
3683                if let Some(fragment_index) = nearest {
3684                    let candidate = &fragments_by_carrier[index][fragment_index];
3685                    if outside_source(candidate.test_point)?
3686                        || in_front_of_other_opening(index, candidate.test_point)?
3687                    {
3688                        continue;
3689                    }
3690                    // Void-cross-section guard. On a PLANAR carrier it applies
3691                    // to the GEOMETRIC FALLBACK only: a fragment that
3692                    // genuinely contains this wall seed is wall content by
3693                    // construction (even when un-split it also spans void —
3694                    // the rim weld cuts the hole later), but a merely-nearest
3695                    // fragment must not resurrect a hole in the opening. On a
3696                    // CURVED carrier no later weld cuts the hole, so even a
3697                    // seed-containing fragment gets the strict guard.
3698                    // Extended inward walls are cut by the source as well:
3699                    // a seed must not resurrect the opposite side of a
3700                    // reflex rim merely because its unsigned distance is small.
3701                    if (nearest_containing.is_none() || !carrier_planar || extended_inward)
3702                        && wall_on_skin(candidate.test_point)?
3703                    {
3704                        os_debug!(
3705                            "  wall[{index}.{fragment_index}] seed-hit skipped: void \
3706                             cross-section (planar={carrier_planar}) at ({:.3},{:.3},{:.3})",
3707                            candidate.test_point.x,
3708                            candidate.test_point.y,
3709                            candidate.test_point.z,
3710                        );
3711                        continue;
3712                    }
3713                    let existing = chosen_offsets.iter().cloned().chain(
3714                        selected_indices
3715                            .iter()
3716                            .map(|selected| fragments_by_carrier[index][*selected].clone()),
3717                    );
3718                    if !selected_indices.contains(&fragment_index)
3719                        && !would_overuse_existing_boundary(
3720                            candidate,
3721                            existing,
3722                            &assembly_sources,
3723                            &imprint,
3724                            2e-3,
3725                        )?
3726                    {
3727                        selected_indices.push(fragment_index);
3728                    }
3729                }
3730            }
3731            for fragment_index in selected_indices.iter().copied() {
3732                let mut fragment = fragments_by_carrier[index][fragment_index].clone();
3733                // An OUTWARD wall is the grown body's section less the source:
3734                // none of it lies inside the source. A kept fragment that does
3735                // is the opening's plane carried past a reflex outline edge
3736                // (an L-block opened at its step: the plane beyond the step
3737                // runs inside the block's leg), and the fragments around it
3738                // were cut only where the source meets the plane, so the
3739                // selection cannot tell wall from material there. The boolean
3740                // lane builds that shell exactly; refuse by name to reach it.
3741                if distance < 0.0
3742                    && !extended_inward
3743                    && wall_inside_source_lane_on()
3744                    && classify_point(fragment.test_point, source, tolerance * 10.0)
3745                        .or_refuse(KernelStage::Select, "classify_point")?.class == PointClass::In
3746                {
3747                    return Err(KernelRefusal::unsupported(
3748                        KernelStage::Select,
3749                        "offset_shell_wall_inside_source",
3750                        format!(
3751                            "offset_shell: opening face {}'s outward wall keeps a fragment inside the \
3752                             source at ({:.3},{:.3},{:.3})",
3753                            carrier.source_face_id, fragment.test_point.x, fragment.test_point.y, fragment.test_point.z,
3754                        ),
3755                    ));
3756                }
3757                // Past a reflex rim the wall closes the cavity on the other
3758                // side of the opening plane, so its normal reverses too.
3759                if extended_inward
3760                    && classify_point(fragment.test_point, source, tolerance * 10.0)
3761                        .or_refuse(KernelStage::Select, "classify_point")?.class == PointClass::In
3762                {
3763                    flip_fragment(&mut fragment)?;
3764                }
3765                chosen_walls.push(fragment);
3766            }
3767        }
3768    }
3769    if debug_enabled() {
3770        for fragment in &chosen_offsets {
3771            os_debug!(
3772                "chosen offset: operand={} src={} test=({:.3},{:.3},{:.3})",
3773                fragment.operand,
3774                carriers[fragment.operand as usize].source_face_id,
3775                fragment.test_point.x,
3776                fragment.test_point.y,
3777                fragment.test_point.z,
3778            );
3779            for (loop_index, loop_record) in fragment.loops.iter().enumerate() {
3780                for coedge in &loop_record.coedges {
3781                    let surface = &fragment.surface;
3782                    let [c0, c1] = coedge.pcurve.domain().unwrap_or([0.0, 0.0]);
3783                    let uv0 = coedge.pcurve.evaluate(c0);
3784                    let uv1 = coedge.pcurve.evaluate(c1);
3785                    if let (Ok(uv0), Ok(uv1)) = (uv0, uv1) {
3786                        let p0 = surface.evaluate(uv0.x, uv0.y);
3787                        let p1 = surface.evaluate(uv1.x, uv1.y);
3788                        if let (Ok(p0), Ok(p1)) = (p0, p1) {
3789                            let kind = match &coedge.source {
3790                                FragmentEdgeSource::Boundary { edge_id, .. } => {
3791                                    format!("bnd:{edge_id}")
3792                                }
3793                                FragmentEdgeSource::SharedBoundary { edge_id, .. } => {
3794                                    format!("sbnd:{edge_id}")
3795                                }
3796                                FragmentEdgeSource::Imprint { piece_id } => {
3797                                    format!("imp:{piece_id}")
3798                                }
3799                                FragmentEdgeSource::Derived { .. } => "derived".to_string(),
3800                            };
3801                            os_debug!(
3802                                "    loop{loop_index} {kind} ({:.4},{:.4},{:.4})..({:.4},{:.4},{:.4})",
3803                                p0.x, p0.y, p0.z, p1.x, p1.y, p1.z,
3804                            );
3805                        }
3806                    }
3807                }
3808            }
3809        }
3810        for fragment in &chosen_walls {
3811            os_debug!(
3812                "chosen wall: operand={} src={} test=({:.3},{:.3},{:.3})",
3813                fragment.operand,
3814                carriers[fragment.operand as usize].source_face_id,
3815                fragment.test_point.x,
3816                fragment.test_point.y,
3817                fragment.test_point.z,
3818            );
3819        }
3820    }
3821    // A re-run must omit something this pass did not, or it replays this pass
3822    // exactly and recurses until the stack overflows: only supports not
3823    // already omitted count. A carrier riding an omitted support's id (a
3824    // synthetic carrier the omission did not remove) reading shadowed is
3825    // refused by name instead.
3826    let already_omitted = newly_shadowed.iter().filter(|id| shadowed_supports.contains(id)).copied().collect::<Vec<_>>();
3827    newly_shadowed.retain(|id| !shadowed_supports.contains(id));
3828    if newly_shadowed.is_empty() && !already_omitted.is_empty() {
3829        let mut faces = already_omitted;
3830        faces.sort_unstable();
3831        return Err(KernelRefusal::unsupported(KernelStage::Select, refusals::SHADOW_RETRY_STALLED, format!(
3832            "offset_shell: a carrier built for the already omitted source face(s) {faces:?} reads shadowed \
3833             over its whole extent, so omitting it again cannot change the construction"
3834        )));
3835    }
3836    if !newly_shadowed.is_empty() {
3837        let mut omitted = shadowed_supports.clone();
3838        omitted.extend(newly_shadowed.iter().copied());
3839        os_debug!(
3840            "re-running without shadowed offset supports {:?} (omitted before: {:?})",
3841            newly_shadowed,
3842            shadowed_supports
3843        );
3844        // What this pass sampled belongs to carriers the next pass may not
3845        // build.
3846        shadowed_points.clear();
3847        profile::lap(&mut clock, profile::SELECT);
3848        let cascaded = !shadowed_supports.is_empty();
3849        let rebuilt = offset_shell_impl(
3850            source,
3851            opening_face_ids,
3852            distance,
3853            body,
3854            extend_oblique_carriers,
3855            extension_fired,
3856            reflex_rebuilds,
3857            &omitted,
3858            cavity_bounds,
3859            every_seeded_piece,
3860            shadowed_points,
3861            omitted_supports,
3862            vacated_notes,
3863        );
3864        let rebuilt = rebuilt?;
3865        if cascaded {
3866            refuse_a_cascade_that_kept_the_cavity(source, opening_face_ids, distance, &rebuilt.solid)?;
3867        }
3868        return Ok(rebuilt);
3869    }
3870    if chosen_offsets.is_empty() && !shadowed_supports.is_empty() {
3871        if matches!(body, Body::Shell) {
3872            if let Some(witness) = cavity_witness(source, opening_face_ids, distance)? {
3873                if !witness.bounds.is_subset(cavity_bounds) {
3874                    let mut bounds = cavity_bounds.clone();
3875                    bounds.extend(witness.bounds.iter().copied());
3876                    os_debug!(
3877                        "every skin read shadowed, but ({:.4}, {:.4}, {:.4}) lies {:.6} from every retained face: re-running with faces {:?} kept",
3878                        witness.point.x, witness.point.y, witness.point.z, witness.clearance, bounds
3879                    );
3880                    shadowed_points.clear();
3881                    profile::lap(&mut clock, profile::SELECT);
3882                    return offset_shell_impl(
3883                        source,
3884                        opening_face_ids,
3885                        distance,
3886                        body,
3887                        extend_oblique_carriers,
3888                        extension_fired,
3889                        reflex_rebuilds,
3890                        &HashSet::default(),
3891                        &bounds,
3892                        every_seeded_piece,
3893                        shadowed_points,
3894                        omitted_supports,
3895                        vacated_notes,
3896                    );
3897                }
3898                return Err(KernelRefusal::unsupported(KernelStage::Select, "offset_shell_cavity_unbuilt", format!(
3899                    "offset_shell: a cavity remains at this distance (the point ({:.4}, {:.4}, {:.4}) is {:.4} from \
3900                     every retained face, past the shell distance {distance}), but every offset skin around it \
3901                     reads as covered by another face, so it could not be built; returning the solid unchanged \
3902                     would be wrong — use a smaller shell distance",
3903                    witness.point.x, witness.point.y, witness.point.z, witness.clearance
3904                )));
3905            }
3906            if let Some(unchanged) = empty_cavity_shell(source, opening_face_ids, distance)? {
3907                return Ok(unchanged);
3908            }
3909        }
3910        let mut omitted = shadowed_supports.iter().copied().collect::<Vec<_>>();
3911        omitted.sort_unstable();
3912        return Err(KernelRefusal::unsupported(KernelStage::Select, "offset_shell_all_shadowed", format!(
3913            "offset_shell: no retained face keeps any offset skin once the shadowed offsets of \
3914             source faces {omitted:?} are omitted — the solid is nowhere thicker than twice the \
3915             shell distance, so there is no cavity to shell"
3916        )));
3917    }
3918    if chosen_offsets.is_empty() {
3919        // NO SKIN, NONE SHADOWED (`BREP_OFFSET_SHELL_EMPTY_CAVITY`, default on; `=0` restores): every offset
3920        // skin lies wholly outside the solid, so none was selected, though no support read
3921        // shadowed (a cone r 3 h 4 open at its base at wall 2.5: its offset cone's own apex falls
3922        // below the opening plane). That is the empty cavity the shadowed branch above answers
3923        // with the solid unchanged; it is answered the same way, on the same two readings: no
3924        // witness of a cavity, and no point of the solid farther than the wall from every
3925        // retained face.
3926        if matches!(body, Body::Shell) && empty_cavity_any_enabled() && cavity_witness(source, opening_face_ids, distance)?.is_none() {
3927            if let Some(unchanged) = empty_cavity_shell(source, opening_face_ids, distance)? {
3928                os_debug!("no offset skin was selected and no cavity remains: the solid is its own shell");
3929                return Ok(unchanged);
3930            }
3931        }
3932        return Err(KernelRefusal::internal(KernelStage::Select, "offset_shell_no_boundary", "offset_shell: carrier intersections produced no offset boundary"));
3933    }
3934    // Opening-wall fragments can overlap at dense carrier junctions. The
3935    // seed-time guard above handles geometric containment; this final pass
3936    // mirrors the topology-level rule and counts exact fragment edge sources.
3937    let mut boundary_use_count = HashMap::<[i64; 9], usize>::default();
3938    for fragment in &chosen_offsets {
3939        for coedge in fragment
3940            .loops
3941            .iter()
3942            .flat_map(|loop_record| &loop_record.coedges)
3943        {
3944            let key = fragment_edge_segment_key(&coedge.source, &assembly_sources, &imprint)?;
3945            *boundary_use_count.entry(key).or_default() += 1;
3946        }
3947    }
3948    let mut manifold_walls = Vec::new();
3949    for fragment in chosen_walls {
3950        let keys = fragment
3951            .loops
3952            .iter()
3953            .flat_map(|loop_record| &loop_record.coedges)
3954            .map(|coedge| fragment_edge_segment_key(&coedge.source, &assembly_sources, &imprint))
3955            .collect::<Result<Vec<_>, _>>()?;
3956        if !keys
3957            .iter()
3958            .any(|key| boundary_use_count.get(key).copied().unwrap_or(0) >= 2)
3959        {
3960            for key in keys {
3961                *boundary_use_count.entry(key).or_default() += 1;
3962            }
3963            manifold_walls.push(fragment);
3964        }
3965    }
3966    os_debug!(
3967        "manifold walls kept: {} operands={:?}",
3968        manifold_walls.len(),
3969        manifold_walls
3970            .iter()
3971            .map(|fragment| fragment.operand)
3972            .collect::<Vec<_>>(),
3973    );
3974    let mut chosen_walls = manifold_walls;
3975    // A part of the selected cavity skin with no path to an opening wall is a
3976    // SEALED hollow; named only if the assembly then refuses.
3977    let sealed = if sealed_hollow_on() && body == Body::Shell {
3978        sealed_skins(&chosen_offsets, &chosen_walls, &assembly_sources, &imprint, |fragment| {
3979            carriers[fragment.operand as usize].source_face_id
3980        })?
3981    } else {
3982        Vec::new()
3983    };
3984    // EVERY SKIN SEALED (`BREP_OFFSET_SHELL_SEALED_OPENINGS_WHOLE`, default on; `=0` restores): no selected
3985    // skin reaches an opening, so the cavity is a closed void below them and each opening face
3986    // stays as it is. Its wall fragments were cut by the skins' carriers PAST the cavity's own
3987    // end (the 8 x 8 pyramid cut at 4, shelled open at its top at 1.9: the sides' offsets cross
3988    // at z 3.75 and their mirrored continuations cut the opening in a square 0.25 across, which
3989    // the wall selection dropped as the cavity's mouth and nothing filled). The opening faces
3990    // are kept whole from the source instead of as wall fragments.
3991    // A skin with an edge cut by an opening's wall carrier reaches that opening, whatever the
3992    // fragment connectivity reads (a pinched lemon shelled through both caps reads sealed by it).
3993    let reaches_an_opening = || {
3994        chosen_offsets.iter().flat_map(|fragment| fragment.loops.iter().flat_map(|loop_record| &loop_record.coedges)).any(|coedge| {
3995            let FragmentEdgeSource::Imprint { piece_id } = &coedge.source else { return false };
3996            imprint.pieces.iter().find(|piece| piece.id == *piece_id).is_some_and(|piece| {
3997                piece.support_faces.iter().any(|key| carriers.get(key.operand as usize).is_some_and(|carrier| carrier.kind == OffsetFaceRole::Wall))
3998            })
3999        })
4000    };
4001    // ... or whose edge lies on an opening face (a carrier reaching its opening plane meets it
4002    // along its own boundary, not an imprint).
4003    let touches_an_opening = || -> Result<bool, KernelRefusal> {
4004        let openings = source.shells.iter().flat_map(|shell| &shell.faces).filter(|face| opening_face_ids.contains(&face.id)).collect::<Vec<_>>();
4005        let band = 1e-7 * crate::solid_scale(source).max(1.0);
4006        for (_, middle) in sealed.iter().flat_map(|skin| &skin.edge_middles) {
4007            for face in &openings {
4008                let Ok(foot) = crate::project_point_to_surface(&face.surface, *middle) else { continue };
4009                if foot.distance <= band
4010                    && parameter_point_in_face(face, Vec2 { x: foot.u, y: foot.v }, 1e-9).or_refuse(KernelStage::Select, "parameter_point_in_face")? != PolygonClass::Outside
4011                {
4012                    return Ok(true);
4013                }
4014            }
4015        }
4016        Ok(false)
4017    };
4018    let all_sealed = sealed_openings_whole_on()
4019        && !chosen_offsets.is_empty()
4020        && sealed.iter().map(|skin| skin.fragments).sum::<usize>() == chosen_offsets.len()
4021        && !reaches_an_opening()
4022        && !touches_an_opening()?;
4023    if all_sealed {
4024        os_debug!("every selected skin is sealed: the openings stay whole");
4025        chosen_walls.clear();
4026    }
4027    if !sealed.is_empty() {
4028        os_debug!(
4029            "sealed skins: {:?}",
4030            sealed.iter().map(|skin| (&skin.sources, skin.centre, skin.edge_middles.len())).collect::<Vec<_>>()
4031        );
4032    }
4033
4034    profile::lap(&mut clock, profile::SELECT);
4035    let stage_clock = web_time::Instant::now();
4036    // The offset BODY has no source face in it: it is the skins (and the held
4037    // faces) alone, oriented as the source is, so nothing is flipped either.
4038    let source_fragments = if body == Body::Whole {
4039        Vec::new()
4040    } else {
4041        fragment_solid(source, SOURCE_OPERAND, &empty_imprint())?
4042    };
4043    os_debug!("stage: source fragments {:.3}s", stage_clock.elapsed().as_secs_f64());
4044    let mut selected = source_fragments
4045        .into_iter()
4046        .filter(|fragment| retained.contains(&fragment.source_face_id) || (all_sealed && opening_face_ids.contains(&fragment.source_face_id)))
4047        .collect::<Vec<_>>();
4048    let mut face_images = selected
4049        .iter()
4050        .map(|fragment| OffsetShellFaceImageRecord {
4051            role: OffsetFaceRole::Source,
4052            source_face_id: fragment.source_face_id,
4053        })
4054        .collect::<Vec<_>>();
4055    if distance < 0.0 {
4056        for fragment in &mut selected {
4057            flip_fragment(fragment)?;
4058        }
4059    }
4060    if distance > 0.0 && body == Body::Shell {
4061        for fragment in &mut chosen_offsets {
4062            flip_fragment(fragment)?;
4063        }
4064    }
4065    face_images.extend(
4066        chosen_offsets
4067            .iter()
4068            .map(|fragment| OffsetShellFaceImageRecord {
4069                role: OffsetFaceRole::Offset,
4070                source_face_id: carriers[fragment.operand as usize].source_face_id,
4071            }),
4072    );
4073    face_images.extend(
4074        chosen_walls
4075            .iter()
4076            .map(|fragment| OffsetShellFaceImageRecord {
4077                role: OffsetFaceRole::Wall,
4078                source_face_id: carriers[fragment.operand as usize].source_face_id,
4079            }),
4080    );
4081    selected.extend(chosen_offsets);
4082    selected.extend(chosen_walls);
4083    // `BREP_OFFSET_THIN_SKIN_PAD`: the same fixed 2e-3 floor as the skin band
4084    // welded the 1e-3 rim of box-paper-thin into points (every rim edge
4085    // degenerate, the rim eight one-face shells, the volume short by the
4086    // rim's 0.072); a thin inward shell's weld is held to a quarter of it.
4087    let mut assembly_weld = 2e-3f64.max(scale * 5e-5);
4088    if thin_skin_pad_enabled() && distance > 0.0 {
4089        assembly_weld = assembly_weld.min(0.25 * distance.abs());
4090    }
4091    let mut solid = profile::detail("assemble_open_fragments", || assemble_open_fragments(
4092        selected,
4093        &assembly_sources,
4094        &imprint,
4095        assembly_weld,
4096    ))?;
4097    os_debug!("stage: assembled open fragments {:.3}s", stage_clock.elapsed().as_secs_f64());
4098    profile::detail("orient_open_solid_faces", || orient_open_solid_faces(&mut solid))?;
4099    os_debug!("stage: oriented {:.3}s", stage_clock.elapsed().as_secs_f64());
4100    let connector_images = profile::detail("complete_sharp_offset_connectors", || complete_sharp_offset_connectors(
4101        &mut solid,
4102        source,
4103        &face_images,
4104        distance,
4105        2e-3f64.max(scale * 5e-5),
4106    ))?;
4107    os_debug!(
4108        "sharp connector completion added {} faces ({:.3}s)",
4109        connector_images.len(),
4110        stage_clock.elapsed().as_secs_f64()
4111    );
4112    if !connector_images.is_empty() {
4113        // Wall fragments were arranged before the sharp seam was closed, so
4114        // their prospective inner boundary was an open chain. Rebuild the
4115        // wall from the now-closed source/offset cycles instead of retaining
4116        // that pre-connector fragment.
4117        for shell in &mut solid.shells {
4118            shell.faces.retain(|face| {
4119                !matches!(
4120                    face_images
4121                        .get(face.id.saturating_sub(1) as usize)
4122                        .map(|image| image.role),
4123                    Some(OffsetFaceRole::Wall)
4124                )
4125            });
4126        }
4127        solid.shells.retain(|shell| !shell.faces.is_empty());
4128    }
4129    face_images.extend(connector_images);
4130    profile::detail("orient_open_solid_faces", || orient_open_solid_faces(&mut solid))?;
4131    // Weld curved-face offset rims that the wall fragmentation left orphaned
4132    // into their coplanar opening cap (cylinder / straight-hole shells). This
4133    // is the seam-rim consistency step the offset pipeline previously lacked.
4134    let welded_rims = profile::detail("weld_coplanar_orphan_rims", || weld_coplanar_orphan_rims(&mut solid, 2e-3f64.max(scale * 5e-5)))?;
4135    os_debug!("welded {welded_rims} coplanar orphan rims into opening caps");
4136    // A rim that is not a circle: a free-form or non-iso rim whose offset image
4137    // falls short of the opening. It runs after every earlier weld because it
4138    // only ever sees rims none of them closed.
4139    let rim_band = profile::detail("weld_free_form_rim_bands", || weld_free_form_rim_bands(
4140        &mut solid,
4141        &mut face_images,
4142        &carriers,
4143        source,
4144        2e-3f64.max(scale * 5e-5),
4145    ))?;
4146    let rim_bands = rim_band.welded;
4147    os_debug!("welded {rim_bands} free-form rim bands");
4148    // Weld leftover coaxial coplanar rim PAIRS (a through-hole's exposed wall
4149    // thickness at each opening) into new planar annulus faces.
4150    let pair_rims =
4151        profile::detail("weld_coplanar_rim_pair_annuli", || weld_coplanar_rim_pair_annuli(&mut solid, &mut face_images, 2e-3f64.max(scale * 5e-5)))?;
4152    os_debug!("welded {pair_rims} coplanar rim pairs into annulus walls");
4153    if debug_enabled() {
4154        for (shell_index, shell) in solid.shells.iter().enumerate() {
4155            for face in &shell.faces {
4156                os_debug!(
4157                    "POSTWELD shell {} face {} same_sense={} loops={}",
4158                    shell_index,
4159                    face.id,
4160                    face.same_sense,
4161                    face.loops.len()
4162                );
4163                for (loop_index, loop_record) in face.loops.iter().enumerate() {
4164                    let walk = loop_record
4165                        .coedges
4166                        .iter()
4167                        .map(|coedge| {
4168                            let spin = (|| -> Result<f64, KernelRefusal> {
4169                                let [d0, d1] = coedge.pcurve.domain().or_refuse(KernelStage::Sew, "domain")?;
4170                                let a = coedge.pcurve.evaluate(d0 + (d1 - d0) * 0.45).or_refuse(KernelStage::Sew, "evaluate")?;
4171                                let b = coedge.pcurve.evaluate(d0 + (d1 - d0) * 0.55).or_refuse(KernelStage::Sew, "evaluate")?;
4172                                let pa = face.surface.evaluate(a.x, a.y).or_refuse(KernelStage::Sew, "evaluate")?;
4173                                let pb = face.surface.evaluate(b.x, b.y).or_refuse(KernelStage::Sew, "evaluate")?;
4174                                Ok(pa.cross(pb).z)
4175                            })()
4176                            .unwrap_or(f64::NAN);
4177                            format!(
4178                                "{}{}(spin{:+.0})",
4179                                if coedge.forward { "+" } else { "-" },
4180                                coedge.edge_id,
4181                                spin.signum()
4182                            )
4183                        })
4184                        .collect::<Vec<_>>();
4185                    os_debug!("    loop {} {:?}", loop_index, walk);
4186                }
4187            }
4188        }
4189    }
4190    let completion_carriers = carriers.iter().collect::<Vec<_>>();
4191    let completion_tolerance = 2e-3f64.max(scale * 5e-5);
4192    // Unify geometric duplicate arc records BEFORE completion: a ring that is
4193    // already covered by both its faces (frustum + apex cap) must not read as
4194    // an open boundary, or completion papers over it with duplicate faces.
4195    let duplicate_welds = profile::detail("weld_duplicate_one_use_arcs", || weld_duplicate_one_use_arcs(&mut solid, completion_tolerance))?;
4196    os_debug!("welded {duplicate_welds} duplicate one-use boundary arcs");
4197    if debug_enabled() {
4198        let mut use_counts = HashMap::<u64, usize>::default();
4199        for coedge in solid
4200            .shells
4201            .iter()
4202            .flat_map(|shell| &shell.faces)
4203            .flat_map(|face| &face.loops)
4204            .flat_map(|loop_record| &loop_record.coedges)
4205        {
4206            *use_counts.entry(coedge.edge_id).or_default() += 1;
4207        }
4208        let open = use_counts.values().filter(|count| **count == 1).count();
4209        os_debug!(
4210            "assembled: faces={} open_edges={open}",
4211            solid
4212                .shells
4213                .iter()
4214                .map(|shell| shell.faces.len())
4215                .sum::<usize>()
4216        );
4217    }
4218    let completed_images = profile::detail("complete_opening_boundary_cycles", || complete_opening_boundary_cycles(
4219        &mut solid,
4220        &completion_carriers,
4221        &face_images,
4222        completion_tolerance,
4223    ))?;
4224    os_debug!("completion added {} faces", completed_images.len());
4225    face_images.extend(completed_images);
4226    let solid = profile::detail("merge_same_surface_faces_open", || merge_same_surface_faces_open(&solid, (1e-7f64).max(scale * 1e-9)))?;
4227    let assembly_tolerance = 2e-3f64.max(scale * 5e-5);
4228    // No faceted fallback here: an offset shell must be made of real analytic
4229    // surfaces. Failing loudly beats silently returning a tessellated BREP
4230    // with destroyed face provenance.
4231    // A shell the rim band lane recognized but could not close fails here as it
4232    // always did; the refusal now carries the lane's reason.
4233    let finalized = profile::detail("finalize_assembled_solid", || finalize_assembled_solid(solid, assembly_tolerance)).map_err(|error| {
4234        match &rim_band.decline {
4235            Some(reason) => error.with_message(|message| format!("{message}; offset_shell: {reason}")),
4236            None => error,
4237        }
4238    });
4239    let mut solid = match finalized {
4240        Ok(solid) => solid,
4241        Err(error) => {
4242            os_debug!("finalize_assembled_solid: {}", error.message);
4243            if !every_seeded_piece && body == Body::Shell && distance > 0.0 && every_seeded_skin_piece_enabled() {
4244                let retried = offset_shell_impl(
4245                    source,
4246                    opening_face_ids,
4247                    distance,
4248                    body,
4249                    extend_oblique_carriers,
4250                    extension_fired,
4251                    reflex_rebuilds,
4252                    shadowed_supports,
4253                    cavity_bounds,
4254                    true,
4255                    shadowed_points,
4256                    omitted_supports,
4257                    vacated_notes,
4258                );
4259                if retried.is_ok() {
4260                    return retried;
4261                }
4262            }
4263            if let Some((index, own, other, thickness)) = sealing_distance(
4264                &sealed,
4265                source,
4266                &retained_faces_with_edges,
4267                distance,
4268                offset_skin_tolerance,
4269            )? {
4270                let skin = &sealed[index];
4271                let bounding = skin.sources.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
4272                return Err(KernelRefusal::unsupported(KernelStage::Sew, refusals::SEALED_HOLLOW, format!(
4273                    "offset_shell: at this distance the cavity splits — a hollow bounded by the offsets of \
4274                     source faces {bounding} near ({:.4}, {:.4}, {:.4}) is sealed off from the opening, and a \
4275                     sealed hollow could not be assembled here. It is closed off where the offsets of source \
4276                     faces {own} and {other} cross, which they do from {:.4} up ({thickness:.4} of material \
4277                     between them); below {:.4} it opens into the rest of the cavity, so use a shell distance \
4278                     below that",
4279                    skin.centre.x,
4280                    skin.centre.y,
4281                    skin.centre.z,
4282                    0.5 * thickness,
4283                    0.5 * thickness,
4284                )));
4285            }
4286            return Err(error);
4287        }
4288    };
4289    profile::detail("reconstruct_analytic_shell", || crate::offset_retrim::reconstruct_analytic_shell(&mut solid))?;
4290    if exact_planar_pcurves_on() {
4291        // Only the faces the offset BUILT: a retained source face keeps the
4292        // source's own trims, so the shell and its source still agree there
4293        // (a cavity read as source less shell cancels what they share).
4294        let built = solid
4295            .shells
4296            .iter()
4297            .flat_map(|shell| &shell.faces)
4298            .filter(|face| face_images.get(face.id.saturating_sub(1) as usize).is_some_and(|image| !matches!(image.role, OffsetFaceRole::Source)))
4299            .map(|face| face.id)
4300            .collect::<HashSet<u64>>();
4301        let replaced = exact_planar_pcurves(&mut solid, &built, (1e-7f64).max(scale * 1e-8))?;
4302        os_debug!("exact planar pcurves: {replaced} coedge(s) re-derived from their edges");
4303    }
4304    if rim_bands + pair_rims > 0 || !inward_extended_walls.is_empty() {
4305        // Rim welds and extended reflex walls join independently-oriented skins;
4306        // put the whole finalized manifold on one normal convention so the
4307        // shell reports its exact wall volume (coplanar-only shells keep
4308        // their assembled sense).
4309        profile::detail("coheres_face_normals", || coheres_face_normals(&mut solid))?;
4310    }
4311    let solid = solid;
4312    profile::lap(&mut clock, profile::ASSEMBLY);
4313    face_images = solid
4314        .shells
4315        .iter()
4316        .flat_map(|shell| &shell.faces)
4317        .map(|face| {
4318            face_images
4319                .get(face.id.saturating_sub(1) as usize)
4320                .cloned()
4321                .ok_or_else(|| "offset_shell: merged face lost provenance".to_string())
4322        })
4323        .collect::<Result<Vec<_>, _>>().or_refuse(KernelStage::Sew, "offset_shell_merged_face_lost_provenance")?;
4324    // A bore's end ring carries the bore wall's provenance whichever
4325    // construction built it (the opening's fragmentation or the rim-pair
4326    // weld), so its name does not depend on the path the rims took.
4327    let bore_rings = claim_bore_end_rings(&solid, &mut face_images)?;
4328    os_debug!("{bore_rings} bore end rings took the bore wall's provenance");
4329    // Honesty gate: a real rim left one-use is a hole in the shell that the
4330    // degenerate marking hides from `validate()` (degenerate edges are allowed
4331    // to be face-local). Refuse such a result instead of shipping a
4332    // non-watertight solid as valid. A rim is a CLOSED edge whose interior
4333    // sweeps measurably away from its seam vertex — a genuine circle, not a
4334    // legitimate pole point placeholder (which stays one-use by design).
4335    let mut rim_use_counts = HashMap::<u64, usize>::default();
4336    for coedge in solid
4337        .shells
4338        .iter()
4339        .flat_map(|shell| &shell.faces)
4340        .flat_map(|face| &face.loops)
4341        .flat_map(|loop_record| &loop_record.coedges)
4342    {
4343        *rim_use_counts.entry(coedge.edge_id).or_default() += 1;
4344    }
4345    if debug_enabled() {
4346        for (shell_index, shell) in solid.shells.iter().enumerate() {
4347            for face in &shell.faces {
4348                let role = face_images
4349                    .get(face.id.saturating_sub(1) as usize)
4350                    .map(|image| image.role);
4351                let c = face.surface.evaluate(0.5, 0.5).unwrap_or_default();
4352                os_debug!(
4353                    "DUMPFACE shell {} face {} affine={} role={:?} loops={} center=({:.3},{:.3},{:.3})",
4354                    shell_index, face.id, face.surface.is_affine().unwrap_or(false), role,
4355                    face.loops.len(), c.x, c.y, c.z
4356                );
4357                for (li, lp) in face.loops.iter().enumerate() {
4358                    let ids = lp.coedges.iter().map(|c| c.edge_id).collect::<Vec<_>>();
4359                    os_debug!("    loop {} edges {:?}", li, ids);
4360                }
4361            }
4362        }
4363        for edge in &solid.edges {
4364            let uses = rim_use_counts.get(&edge.id).copied().unwrap_or(0);
4365            let s = edge.curve.evaluate(edge.t0).or_refuse(KernelStage::Sew, "evaluate")?;
4366            let m = edge.curve.evaluate((edge.t0 + edge.t1) * 0.5).or_refuse(KernelStage::Sew, "evaluate")?;
4367            let q = edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * 0.25).or_refuse(KernelStage::Sew, "evaluate")?;
4368            os_debug!(
4369                "DUMPEDGE edge {} uses={} closed={} deg={} cpts={} cdeg={} knots={:?} start=({:.3},{:.3},{:.3}) q=({:.3},{:.3},{:.3}) mid=({:.3},{:.3},{:.3})",
4370                edge.id, uses, edge.start_vertex_id == edge.end_vertex_id, edge.degenerate,
4371                edge.curve.control_points.len(), edge.curve.degree, edge.curve.knots,
4372                s.x, s.y, s.z, q.x, q.y, q.z, m.x, m.y, m.z
4373            );
4374        }
4375    }
4376    for edge in &solid.edges {
4377        if rim_use_counts.get(&edge.id).copied().unwrap_or(0) != 1
4378            || edge.start_vertex_id != edge.end_vertex_id
4379        {
4380            continue;
4381        }
4382        let anchor = edge.curve.evaluate(edge.t0).or_refuse(KernelStage::Sew, "evaluate")?;
4383        let sweep_threshold = 1e-4f64.max(scale * 1e-6);
4384        let sweeps = [0.25, 0.5, 0.75].into_iter().any(|fraction| {
4385            edge.curve
4386                .evaluate(edge.t0 + (edge.t1 - edge.t0) * fraction)
4387                .map(|point| point.sub(anchor).length() > sweep_threshold)
4388                .unwrap_or(false)
4389        });
4390        if sweeps {
4391            if debug_enabled() {
4392                let rim_mid = edge.curve.evaluate((edge.t0 + edge.t1) * 0.5).or_refuse(KernelStage::Sew, "evaluate")?;
4393                os_debug!(
4394                    "PROBE orphan rim edge {} anchor=({:.4},{:.4},{:.4}) mid=({:.4},{:.4},{:.4})",
4395                    edge.id,
4396                    anchor.x,
4397                    anchor.y,
4398                    anchor.z,
4399                    rim_mid.x,
4400                    rim_mid.y,
4401                    rim_mid.z
4402                );
4403                for (shell_index, shell) in solid.shells.iter().enumerate() {
4404                    for face in &shell.faces {
4405                        let uses_rim = face
4406                            .loops
4407                            .iter()
4408                            .flat_map(|l| &l.coedges)
4409                            .any(|c| c.edge_id == edge.id);
4410                        let affine = face.surface.is_affine().unwrap_or(false);
4411                        let on = edge_on_surface(edge, &face.surface, 2e-3f64.max(scale * 5e-5))
4412                            .unwrap_or(false);
4413                        let proj = project_point_to_surface(&face.surface, rim_mid).or_refuse(KernelStage::Sew, "project_point_to_surface")?;
4414                        let contains = if on {
4415                            parameter_point_in_face(
4416                                face,
4417                                Vec2 {
4418                                    x: proj.u,
4419                                    y: proj.v,
4420                                },
4421                                2e-3f64.max(scale * 5e-5),
4422                            ).or_refuse(KernelStage::Sew, "parameter_point_in_face")? != PolygonClass::Outside
4423                        } else {
4424                            false
4425                        };
4426                        if on || uses_rim {
4427                            os_debug!(
4428                                "  face {} shell {} affine={} uses_rim={} on_surf={} proj_dist={:.5} contains={}",
4429                                face.id, shell_index, affine, uses_rim, on, proj.distance, contains
4430                            );
4431                        }
4432                    }
4433                }
4434            }
4435            // The pieces a single seed missed leave their outlines one-use
4436            // here as at the assembly's own exit: the same retry answers it.
4437            if !every_seeded_piece && body == Body::Shell && distance > 0.0 && every_seeded_skin_piece_enabled() {
4438                let retried = offset_shell_impl(
4439                    source,
4440                    opening_face_ids,
4441                    distance,
4442                    body,
4443                    extend_oblique_carriers,
4444                    extension_fired,
4445                    reflex_rebuilds,
4446                    shadowed_supports,
4447                    cavity_bounds,
4448                    true,
4449                    shadowed_points,
4450                    omitted_supports,
4451                    vacated_notes,
4452                );
4453                if retried.is_ok() {
4454                    return retried;
4455                }
4456            }
4457            return Err(refusals::unwelded_curved_rim(edge.id, anchor).into());
4458        }
4459    }
4460    // The shell's single exit. An offset skin that crosses another wall, or
4461    // folds through itself where the source turned tighter than the distance,
4462    // leaves a body that validates and measures — so it is asked here, and
4463    // repaired or refused by name rather than returned.
4464    let mut solid = solid;
4465    // Face-local rim construction and planar merging can reuse wire IDs.
4466    // Reserve every existing ID, then replace only duplicates so the completed
4467    // body can cross the arena/buffer ingestion boundary. These IDs have no
4468    // external references; face/edge identities and provenance stay intact.
4469    let mut loop_ids = HashSet::default();
4470    let mut coedge_ids = HashSet::default();
4471    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
4472        for wire in &face.loops {
4473            loop_ids.insert(wire.id);
4474            coedge_ids.extend(wire.coedges.iter().map(|coedge| coedge.id));
4475        }
4476    }
4477    let mut seen_loops = HashSet::default();
4478    let mut seen_coedges = HashSet::default();
4479    let mut next_loop = 1;
4480    let mut next_coedge = 1;
4481    for face in solid.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
4482        for wire in &mut face.loops {
4483            if !seen_loops.insert(wire.id) {
4484                while !loop_ids.insert(next_loop) { next_loop += 1; }
4485                wire.id = next_loop;
4486            }
4487            for coedge in &mut wire.coedges {
4488                if !seen_coedges.insert(coedge.id) {
4489                    while !coedge_ids.insert(next_coedge) { next_coedge += 1; }
4490                    coedge.id = next_coedge;
4491                }
4492            }
4493        }
4494    }
4495    let solid = profile::detail("accept_offset_result", || super::acceptance::accept_offset_result(solid))?;
4496    profile::lap(&mut clock, profile::ACCEPTANCE);
4497    Ok(OffsetShellResultRecord { solid, face_images })
4498}
4499
4500/// Run offset shell with stable counters and validation diagnostics suitable
4501/// for automated regressions and UI presentation.
4502pub fn offset_shell_with_diagnostics(
4503    source: &BrepSolid,
4504    opening_face_ids: &[u64],
4505    distance: f64,
4506    tolerances: Option<KernelTolerances>,
4507) -> Result<KernelOutcome<OffsetShellResultRecord>, KernelRefusal> {
4508    if let Some(scaled) = crate::rescale::ScaledOffset::of(source, distance, "offset_shell")? {
4509        let mut outcome = offset_shell_with_diagnostics(&scaled.source, opening_face_ids, scaled.distance, tolerances)
4510            .map_err(|error| scaled.refusal(error))?;
4511        outcome.value.solid = scaled.back(&outcome.value.solid, "offset_shell")?;
4512        outcome.diagnostics.count_n("working_scale.fired", 1);
4513        outcome.diagnostics.measure_max("working_scale.factor", scaled.factor);
4514        return Ok(outcome);
4515    }
4516    let policy = tolerances.unwrap_or_else(|| KernelTolerances::for_solid(source, 1e-7));
4517    policy.check().or_refuse(KernelStage::Sew, "check")?;
4518    let mut diagnostics = KernelDiagnostics::default();
4519    diagnostics.count_n(
4520        "collect.source_faces",
4521        source
4522            .shells
4523            .iter()
4524            .map(|shell| shell.faces.len() as u64)
4525            .sum(),
4526    );
4527    diagnostics.count_n("collect.opening_faces", opening_face_ids.len() as u64);
4528    diagnostics.measure_max("offset.distance", distance.abs());
4529    diagnostics.measure_max("tolerance.model", policy.model);
4530    // Tally every pcurve fit the shell makes (its own re-trims and any boolean
4531    // it runs) so `pcurve.unmet_floor` reports a trim that stopped at the
4532    // sample ceiling instead of passing it off as one that met the floor.
4533    let fit_scope = crate::PcurveFitScope::open();
4534    // Same for the polyline fits of its carrier×carrier sections, which is
4535    // where a marched rim's accuracy is decided (`geometry/fit.rs`).
4536    let polyline_scope = crate::PolylineFitScope::open();
4537    let result = offset_shell(source, opening_face_ids, distance)?;
4538    fit_scope.close().report_into(&mut diagnostics);
4539    polyline_scope.close().report_into(&mut diagnostics);
4540    // The phase split of the run that just finished (`profile.rs`), in the
4541    // boolean's `timing.<phase>_ms` shape so one reader serves both.
4542    let timings = profile::snapshot();
4543    diagnostics.count_n("shell.attempts", timings.attempts);
4544    for (phase, count) in &timings.carriers {
4545        diagnostics.count_n(format!("shell.{phase}"), *count);
4546    }
4547    for (phase, ms) in &timings.ms {
4548        diagnostics.measure_max(format!("timing.{phase}_ms"), *ms);
4549    }
4550    diagnostics.count_n(
4551        "sew.output_faces",
4552        result
4553            .solid
4554            .shells
4555            .iter()
4556            .map(|shell| shell.faces.len() as u64)
4557            .sum(),
4558    );
4559    diagnostics.count_n("sew.face_images", result.face_images.len() as u64);
4560    let validation = result.solid.validate_detailed(&policy);
4561    diagnostics.measure_max("validate.max_pcurve_error", validation.max_pcurve_error);
4562    diagnostics.count_n("validate.issues", validation.issues.len() as u64);
4563    diagnostics.count_n(
4564        "validate.wire_warnings",
4565        validation.wire_warnings.len() as u64,
4566    );
4567    for warning in validation.wire_warnings {
4568        diagnostics.event(
4569            DiagnosticSeverity::Warning,
4570            KernelStage::Validate,
4571            "validate.uv_wire",
4572            warning.message,
4573        );
4574    }
4575    if !validation.issues.is_empty() {
4576        for issue in &validation.issues {
4577            diagnostics.event(
4578                DiagnosticSeverity::Error,
4579                KernelStage::Validate,
4580                "validate.brep",
4581                issue.message.clone(),
4582            );
4583        }
4584        return Err(KernelRefusal::internal(KernelStage::Validate, "offset_shell_diagnostic_result", format!(
4585            "offset_shell: invalid diagnostic result: {:?}",
4586            validation.issues
4587        )));
4588    }
4589    Ok(KernelOutcome {
4590        value: result,
4591        diagnostics,
4592    })
4593}
4594
4595/// Whether a wall fragment lies wholly in the wall's surplus: it has an edge on
4596/// the wall carrier's own outline (`Boundary` of operand `wall_operand`) and no
4597/// edge imprinted by the SOURCE solid, whose rim every genuine opening-wall
4598/// region borders. `cut_by_source` answers whether an imprint piece has the
4599/// source among its two support faces.
4600pub fn wall_surplus_beyond_the_sections(
4601    fragment: &FaceFragmentRecord,
4602    wall_operand: u8,
4603    cut_by_source: impl Fn(u64) -> bool,
4604) -> bool {
4605    let mut on_outline = false;
4606    for coedge in fragment.loops.iter().flat_map(|record| &record.coedges) {
4607        match &coedge.source {
4608            FragmentEdgeSource::Boundary { operand, .. } if *operand == wall_operand => on_outline = true,
4609            FragmentEdgeSource::Boundary { operand, .. } | FragmentEdgeSource::SharedBoundary { operand, .. }
4610                if *operand == SOURCE_OPERAND =>
4611            {
4612                return false;
4613            }
4614            FragmentEdgeSource::Imprint { piece_id } => {
4615                if cut_by_source(*piece_id) {
4616                    return false;
4617                }
4618            }
4619            _ => {}
4620        }
4621    }
4622    on_outline
4623}
4624
4625
4626/// `BREP_OFFSET_SHELL_CASCADE_OMISSION` (default on; `=0` restores): an inward
4627/// shell judges a carrier that reads shadowed at every fragment's test point
4628/// by its true skin instead ([`fragments_holding_true_skin`]). One test point
4629/// cannot speak for a fragment that is partly skin: a reported cylinder boss model's
4630/// root fillets bound the cavity's bulge toward the boss mouth at every
4631/// distance past the boss limit (checked with
4632/// `scripts/offset_cavity_volume.py`), and were dropped as shadowed. A carrier
4633/// holding no skin at all may then be omitted even after an earlier omission.
4634/// `BREP_OFFSET_ABUT_COPLANAR_CARRIERS` (default on; `=0` restores): see
4635/// [`abut_coplanar_offset_carriers`].
4636fn abut_coplanar_carriers_on() -> bool {
4637    switch!("BREP_OFFSET_ABUT_COPLANAR_CARRIERS", true)
4638}
4639
4640/// Two retained planar faces on ONE plane with the same outward sense (the
4641/// matching side walls of two pockets) have offsets on one plane too, and each
4642/// carrier is continued past its trim to its mitre — so across the material
4643/// between them (a divider thinner than 2d) the two carriers OVERLAP. Every
4644/// carrier crossing that plane then imprints two partly overlapping copies of
4645/// one cut, which the arrangement cannot use: the frame's offset over two
4646/// pockets lost all its cuts once the divider's own (shadowed) offsets stopped
4647/// splitting them, and the shell refused.
4648///
4649/// Such a pair is cut back to abut at the middle of its overlap, each keeping
4650/// its own side: the union of the two, the plane the cavity is bounded by, is
4651/// unchanged, and each keeps its own source face. Planar degree-(1, 1)
4652/// carriers whose trim is a parameter rectangle, overlapping along one
4653/// direction and matching along the other; any other pair is left as it was.
4654/// Run only in a pass after the cascade omitted a shadowed carrier: until then
4655/// that carrier cuts both copies at the same points and the overlap is
4656/// harmless (the outward divider builds exactly in its first pass, and cut
4657/// back there it gained a 342-area membrane). Returns how many pairs were cut
4658/// back.
4659fn abut_coplanar_offset_carriers(carriers: &mut [Carrier], tolerance: f64) -> Result<usize, KernelRefusal> {
4660    struct Plate {
4661        index: usize,
4662        origin: Vec3,
4663        axes: [Vec3; 2],
4664        lengths: [f64; 2],
4665        normal: Vec3,
4666        height: f64,
4667    }
4668    let plate = |index: usize, carrier: &Carrier| -> Result<Option<Plate>, KernelRefusal> {
4669        if !matches!(carrier.kind, OffsetFaceRole::Offset) {
4670            return Ok(None);
4671        }
4672        let face = &carrier.solid.shells[0].faces[0];
4673        let surface = &face.surface;
4674        if surface.degree_u != 1 || surface.degree_v != 1 || surface.control_points.len() != 2 || surface.control_points[0].len() != 2 {
4675            return Ok(None);
4676        }
4677        if surface.control_points.iter().flatten().any(|point| (point.w - 1.0).abs() > 1e-12) || face.loops.len() != 1 {
4678            return Ok(None);
4679        }
4680        let [u0, u1] = surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
4681        let [v0, v1] = surface.domain_v().or_refuse(KernelStage::Refine, "domain_v")?;
4682        // A rectangular trim: four straight pcurves, each running along u or
4683        // along v, whose box lies inside the domain.
4684        if face.loops[0].coedges.len() != 4 {
4685            return Ok(None);
4686        }
4687        let mut uv_box = [f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY];
4688        for coedge in &face.loops[0].coedges {
4689            if coedge.pcurve.degree != 1 || coedge.pcurve.control_points.len() != 2 {
4690                return Ok(None);
4691            }
4692            let (Ok(a), Ok(b)) = (coedge.pcurve.control_points[0].point(), coedge.pcurve.control_points[1].point()) else { return Ok(None) };
4693            let (du, dv) = ((b.x - a.x).abs(), (b.y - a.y).abs());
4694            if du.min(dv) > 1e-12 * du.max(dv) {
4695                return Ok(None);
4696            }
4697            let [a, b] = coedge.pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
4698            for t in [a, b] {
4699                let uv = coedge.pcurve.evaluate(t).or_refuse(KernelStage::Refine, "evaluate")?;
4700                uv_box = [uv_box[0].min(uv.x), uv_box[1].max(uv.x), uv_box[2].min(uv.y), uv_box[3].max(uv.y)];
4701            }
4702        }
4703        let span = (u1 - u0).abs().max(v1 - v0).max(1.0);
4704        let [bu0, bu1, bv0, bv1] = uv_box;
4705        let box_area = (bu1 - bu0) * (bv1 - bv0);
4706        if bu0 < u0 - 1e-9 * span || bu1 > u1 + 1e-9 * span || bv0 < v0 - 1e-9 * span || bv1 > v1 + 1e-9 * span
4707            || !(box_area > 0.0)
4708            || (parameter_space_area(face).or_refuse(KernelStage::Refine, "parameter_space_area")?.abs() - box_area).abs() > 1e-9 * box_area
4709        {
4710            return Ok(None);
4711        }
4712        let origin = surface.evaluate(bu0, bv0).or_refuse(KernelStage::Refine, "evaluate")?;
4713        let along_u = surface.evaluate(bu1, bv0).or_refuse(KernelStage::Refine, "evaluate")?.sub(origin);
4714        let along_v = surface.evaluate(bu0, bv1).or_refuse(KernelStage::Refine, "evaluate")?.sub(origin);
4715        let lengths = [along_u.length(), along_v.length()];
4716        if lengths[0] <= tolerance || lengths[1] <= tolerance {
4717            return Ok(None);
4718        }
4719        let axes = [along_u.scale(1.0 / lengths[0]), along_v.scale(1.0 / lengths[1])];
4720        if axes[0].dot(axes[1]).abs() > 1e-9 {
4721            return Ok(None);
4722        }
4723        // A rectangle, not a bilinear quadrilateral: the fourth corner closes it.
4724        let far = surface.evaluate(bu1, bv1).or_refuse(KernelStage::Refine, "evaluate")?;
4725        if far.sub(origin.add(along_u).add(along_v)).length() > tolerance {
4726            return Ok(None);
4727        }
4728        let sense = if face.same_sense { 1.0 } else { -1.0 };
4729        let normal = axes[0].cross(axes[1]).scale(sense);
4730        Ok(Some(Plate { index, origin, axes, lengths, normal, height: normal.dot(origin) }))
4731    };
4732    let mut abutted = 0usize;
4733    'pairs: loop {
4734        let plates = carriers
4735            .iter()
4736            .enumerate()
4737            .map(|(index, carrier)| plate(index, carrier))
4738            .collect::<Result<Vec<_>, _>>()?
4739            .into_iter()
4740            .flatten()
4741            .collect::<Vec<_>>();
4742        for (i, first) in plates.iter().enumerate() {
4743            for second in &plates[i + 1..] {
4744                if first.normal.dot(second.normal) < 1.0 - 1e-12 || (first.height - second.height).abs() > tolerance {
4745                    continue;
4746                }
4747                // ONE plane: every corner of the second on the first's plane, so a
4748                // slightly tilted pair (equal near one point) is not cut back.
4749                let on_plane = |point: Vec3| (first.normal.dot(point) - first.height).abs() <= tolerance;
4750                let second_far = second.origin.add(second.axes[0].scale(second.lengths[0]));
4751                let second_up = second.origin.add(second.axes[1].scale(second.lengths[1]));
4752                if !on_plane(second.origin) || !on_plane(second_far) || !on_plane(second_up)
4753                    || !on_plane(second_far.add(second.axes[1].scale(second.lengths[1])))
4754                    || !on_plane(first.origin.add(first.axes[0].scale(first.lengths[0])).add(first.axes[1].scale(first.lengths[1])))
4755                {
4756                    continue;
4757                }
4758                // The second's extent in the first's frame, along each axis.
4759                let corners = [
4760                    second.origin,
4761                    second.origin.add(second.axes[0].scale(second.lengths[0])),
4762                    second.origin.add(second.axes[1].scale(second.lengths[1])),
4763                    second.origin.add(second.axes[0].scale(second.lengths[0])).add(second.axes[1].scale(second.lengths[1])),
4764                ];
4765                let range = |axis: usize| {
4766                    corners.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), corner| {
4767                        let at = corner.sub(first.origin).dot(first.axes[axis]);
4768                        (low.min(at), high.max(at))
4769                    })
4770                };
4771                let ranges = [range(0), range(1)];
4772                // The second must be a rectangle aligned with the first.
4773                if second.axes.iter().any(|axis| axis.dot(first.axes[0]).abs().min(axis.dot(first.axes[1]).abs()) > 1e-9) {
4774                    continue;
4775                }
4776                for (along, across) in [(0usize, 1usize), (1, 0)] {
4777                    let (low, high) = ranges[along];
4778                    let (across_low, across_high) = ranges[across];
4779                    if (across_low).abs() > tolerance || (across_high - first.lengths[across]).abs() > tolerance {
4780                        continue;
4781                    }
4782                    let overlap = (high.min(first.lengths[along]), low.max(0.0));
4783                    if overlap.0 - overlap.1 <= tolerance {
4784                        continue;
4785                    }
4786                    let first_holds = low >= -tolerance && high <= first.lengths[along] + tolerance;
4787                    let second_holds = low <= tolerance && high >= first.lengths[along] - tolerance;
4788                    if first_holds || second_holds {
4789                        continue;
4790                    }
4791                    let cut = 0.5 * (overlap.0 + overlap.1);
4792                    let point = first.origin.add(first.axes[along].scale(cut));
4793                    let first_low_side = 0.5 * first.lengths[along] < cut;
4794                    clip_plate(&mut carriers[first.index], point, first.axes[along], first_low_side)?;
4795                    clip_plate(&mut carriers[second.index], point, first.axes[along], !first_low_side)?;
4796                    abutted += 1;
4797                    continue 'pairs;
4798                }
4799            }
4800        }
4801        break;
4802    }
4803    Ok(abutted)
4804}
4805
4806/// Cut a planar degree-(1, 1) carrier back at the plane through `point`
4807/// normal to `axis`, keeping the side below it (`keep_low`) or above it, and
4808/// rebuild its trim as the new parameter rectangle.
4809fn clip_plate(carrier: &mut Carrier, point: Vec3, axis: Vec3, keep_low: bool) -> Result<(), KernelRefusal> {
4810    let face = carrier.solid.shells[0].faces[0].clone();
4811    let surface = &face.surface;
4812    let mut uv_box = [f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY];
4813    for coedge in &face.loops[0].coedges {
4814        let [a, b] = coedge.pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
4815        for t in [a, b] {
4816            let uv = coedge.pcurve.evaluate(t).or_refuse(KernelStage::Refine, "evaluate")?;
4817            uv_box = [uv_box[0].min(uv.x), uv_box[1].max(uv.x), uv_box[2].min(uv.y), uv_box[3].max(uv.y)];
4818        }
4819    }
4820    let [u0, u1, v0, v1] = uv_box;
4821    let origin = surface.evaluate(u0, v0).or_refuse(KernelStage::Refine, "evaluate")?;
4822    let du = surface.evaluate(u1, v0).or_refuse(KernelStage::Refine, "evaluate")?.sub(origin);
4823    let dv = surface.evaluate(u0, v1).or_refuse(KernelStage::Refine, "evaluate")?.sub(origin);
4824    let level = point.sub(origin).dot(axis);
4825    let (mut ru, mut rv) = ([u0, u1], [v0, v1]);
4826    // Which parameter runs along the axis, and where it reaches the cut.
4827    if du.dot(axis).abs() > dv.dot(axis).abs() {
4828        let at = u0 + (u1 - u0) * level / du.dot(axis);
4829        let low_end_is_u0 = du.dot(axis) > 0.0;
4830        if keep_low == low_end_is_u0 { ru[1] = at } else { ru[0] = at }
4831        if ru[0] > ru[1] { ru.swap(0, 1) }
4832    } else {
4833        let at = v0 + (v1 - v0) * level / dv.dot(axis);
4834        let low_end_is_v0 = dv.dot(axis) > 0.0;
4835        if keep_low == low_end_is_v0 { rv[1] = at } else { rv[0] = at }
4836        if rv[0] > rv[1] { rv.swap(0, 1) }
4837    }
4838    let corner = |u: f64, v: f64| -> Result<crate::Vec4, KernelRefusal> {
4839        Ok(crate::Vec4::from_point(surface.evaluate(u, v).or_refuse(KernelStage::Refine, "evaluate")?, 1.0))
4840    };
4841    let clipped = crate::NurbsSurface::new(
4842        1,
4843        1,
4844        vec![ru[0], ru[0], ru[1], ru[1]],
4845        vec![rv[0], rv[0], rv[1], rv[1]],
4846        vec![vec![corner(ru[0], rv[0])?, corner(ru[0], rv[1])?], vec![corner(ru[1], rv[0])?, corner(ru[1], rv[1])?]],
4847    )
4848    .or_refuse(KernelStage::Refine, "new")?;
4849    let mut rebuilt = face;
4850    rebuilt.surface = clipped;
4851    carrier.solid = full_rectangle_face(&carrier.solid, &rebuilt)?;
4852    Ok(())
4853}
4854
4855/// `BREP_OFFSET_PER_EDGE_OPENING_PADS` (default on; `=0` restores): a planar outward
4856/// opening wall's outline is offset per edge, each by its own junction's pad
4857/// (`outward_wall_pads_per_edge`), not all by the worst one's.
4858fn per_edge_opening_pads_on() -> bool {
4859    switch!("BREP_OFFSET_PER_EDGE_OPENING_PADS", true)
4860}
4861
4862/// `BREP_OFFSET_NONUNIFORM_SLID_TRIM` (default on; `=0` restores): an outward planar
4863/// carrier whose extension is NOT uniform also takes its full rectangle when
4864/// its slid trim falls short of its narrowest pad.
4865fn nonuniform_slid_trim_on() -> bool {
4866    switch!("BREP_OFFSET_NONUNIFORM_SLID_TRIM", true)
4867}
4868
4869fn cascade_omission_enabled() -> bool {
4870    switch!("BREP_OFFSET_SHELL_CASCADE_OMISSION", true)
4871}
4872
4873/// A cascade of omissions must leave the deepest point of the true cavity
4874/// hollow: a carrier omitted on a test point that did not stand for its
4875/// fragment would show as material there.
4876fn refuse_a_cascade_that_kept_the_cavity(
4877    source: &BrepSolid,
4878    opening_face_ids: &[u64],
4879    distance: f64,
4880    result: &BrepSolid,
4881) -> Result<(), KernelRefusal> {
4882    let Some(witness) = cavity_witness(source, opening_face_ids, distance)? else {
4883        return Ok(());
4884    };
4885    let scale = crate::solid_scale(source).max(1.0);
4886    let class = classify_point(witness.point, result, 1e-8 * scale).or_refuse(KernelStage::Select, "classify_point")?.class;
4887    if class == PointClass::In {
4888        return Err(KernelRefusal::unsupported(KernelStage::Select, "offset_shell_shadow_cascade", format!(
4889            "offset_shell: omitting offsets that read shadowed only after earlier omissions leaves material at \
4890             ({:.4}, {:.4}, {:.4}), which is {:.4} from every retained face, past the shell distance {distance}; \
4891             the cavity there could not be built — use a smaller shell distance",
4892            witness.point.x, witness.point.y, witness.point.z, witness.clearance
4893        )));
4894    }
4895    Ok(())
4896}
4897
4898/// `BREP_OFFSET_SHELL_CAVITY_WITNESS` (default on; `=0` restores): [`cavity_witness`].
4899fn retained_faces_of<'a>(retained: &[(&'a FaceRecord, Vec<&'a EdgeRecord>)]) -> Vec<&'a FaceRecord> {
4900    retained.iter().map(|(face, _)| *face).collect()
4901}
4902
4903fn sealed_openings_whole_on() -> bool {
4904    switch!("BREP_OFFSET_SHELL_SEALED_OPENINGS_WHOLE", true)
4905}
4906
4907fn empty_cavity_any_enabled() -> bool {
4908    switch!("BREP_OFFSET_SHELL_EMPTY_CAVITY", true)
4909}
4910
4911fn cavity_witness_enabled() -> bool {
4912    switch!("BREP_OFFSET_SHELL_CAVITY_WITNESS", true)
4913}
4914
4915/// A point of the solid farther than the shell distance from every retained
4916/// face, and the faces nearest it, whose skins bound that cavity.
4917#[derive(Debug)]
4918pub struct CavityWitness {
4919    pub(super) point: Vec3,
4920    pub clearance: f64,
4921    pub bounds: HashSet<u64>,
4922}
4923
4924/// Looks for the cavity the shadow reading says is not there. A fragment's
4925/// single test point can read shadowed while most of the fragment is real skin
4926/// (a reported cylinder boss model at 4.8: the r 0.2 bore of a cylinder r 5, one uncut
4927/// fragment whose test point lies 4.72 from a boss wall), and a cavity that
4928/// thin falls between the 12³ cells of [`empty_cavity_shell`], which then
4929/// returned the source as a success.
4930///
4931/// Distance to the retained faces is 1-Lipschitz, so any cavity's maximum is
4932/// climbed to from the samples that read highest: the best cell centres start
4933/// a pattern search that stays inside the solid. It is a search, not a proof;
4934/// what it cannot miss is a cavity whose ridge those starts climb.
4935pub fn cavity_witness(
4936    source: &BrepSolid,
4937    opening_face_ids: &[u64],
4938    distance: f64,
4939) -> Result<Option<CavityWitness>, KernelRefusal> {
4940    if !cavity_witness_enabled() || distance <= 0.0 || opening_face_ids.is_empty() {
4941        return Ok(None);
4942    }
4943    let faces = source.shells.iter().flat_map(|shell| &shell.faces).collect::<Vec<_>>();
4944    let retained = faces.iter().filter(|face| !opening_face_ids.contains(&face.id)).copied().collect::<Vec<_>>();
4945    if retained.is_empty() {
4946        return Ok(None);
4947    }
4948    // Each face's own edges: a foot off the trim falls back on the edges it is
4949    // given, and the whole solid's would read a wall as near as any rim.
4950    let edge_by_id = source.edges.iter().map(|edge| (edge.id, edge)).collect::<HashMap<_, _>>();
4951    let retained = retained
4952        .into_iter()
4953        .map(|face| {
4954            let edges = face
4955                .loops
4956                .iter()
4957                .flat_map(|loop_record| &loop_record.coedges)
4958                .filter_map(|coedge| edge_by_id.get(&coedge.edge_id).copied())
4959                .collect::<Vec<_>>();
4960            (face, edges)
4961        })
4962        .collect::<Vec<_>>();
4963    let Some((low, high)) = control_hull(source, &faces) else { return Ok(None) };
4964    let scale = crate::solid_scale(source).max(1.0);
4965    let classify_tolerance = 1e-8 * scale;
4966    let margin = 1e-6 * scale;
4967    let readings = |point: Vec3| -> Result<Vec<(u64, f64)>, KernelRefusal> {
4968        retained
4969            .iter()
4970            .map(|(face, edges)| {
4971                // `BREP_OFFSET_RULED_MITER`: a ruled face reads the mitered metric the skin test
4972                // reads it by, or the witness finds a cavity past a rim the skins never reach.
4973                let ruled = if super::carriers::ruled_miter_on() { super::carriers::ruled_miter_distance(face, edges, point, &retained_faces_of(&retained))? } else { None };
4974                Ok((face.id, match ruled {
4975                    Some(mitered) => mitered,
4976                    None => distance_to_trimmed_face(face, edges, point)?,
4977                }))
4978            })
4979            .collect()
4980    };
4981    let clearance = |values: &[(u64, f64)]| values.iter().map(|(_, value)| *value).fold(f64::INFINITY, f64::min);
4982    let inside = |point: Vec3| -> Result<bool, KernelRefusal> {
4983        Ok(classify_point(point, source, classify_tolerance).or_refuse(KernelStage::Select, "classify_point")?.class == PointClass::In)
4984    };
4985    const CELLS: usize = 12;
4986    const STARTS: usize = 24;
4987    const MOVES: usize = 160;
4988    let span = high.sub(low);
4989    let mut starts = Vec::new();
4990    for i in 0..CELLS {
4991        for j in 0..CELLS {
4992            for k in 0..CELLS {
4993                let at = |index: usize| (index as f64 + 0.5) / CELLS as f64;
4994                let point = Vec3::new(low.x + span.x * at(i), low.y + span.y * at(j), low.z + span.z * at(k));
4995                if inside(point)? {
4996                    starts.push((clearance(&readings(point)?), point));
4997                }
4998            }
4999        }
5000    }
5001    starts.sort_by(|a, b| b.0.total_cmp(&a.0));
5002    starts.truncate(STARTS);
5003    const DIRECTIONS: [(f64, f64, f64); 14] = [
5004        (1.0, 0.0, 0.0), (-1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, -1.0),
5005        (1.0, 1.0, 1.0), (-1.0, -1.0, -1.0), (1.0, 1.0, -1.0), (-1.0, -1.0, 1.0),
5006        (1.0, -1.0, 1.0), (-1.0, 1.0, -1.0), (-1.0, 1.0, 1.0), (1.0, -1.0, -1.0),
5007    ];
5008    let first_step = span.x.max(span.y).max(span.z) / CELLS as f64;
5009    let mut footless = None;
5010    for (start_clearance, start) in starts {
5011        let (mut point, mut best, mut step) = (start, start_clearance, first_step);
5012        for _ in 0..MOVES {
5013            if step < 1e-6 * scale {
5014                break;
5015            }
5016            let mut moved = false;
5017            for (x, y, z) in DIRECTIONS {
5018                let length = (x * x + y * y + z * z).sqrt();
5019                let next = Vec3::new(point.x + step * x / length, point.y + step * y / length, point.z + step * z / length);
5020                let value = clearance(&readings(next)?);
5021                if value > best && inside(next)? {
5022                    (point, best, moved) = (next, value, true);
5023                    break;
5024                }
5025            }
5026            if !moved {
5027                step *= 0.5;
5028            }
5029        }
5030        if best > distance + margin {
5031            // The climb ends on the ridge, where every face around it ties.
5032            // Nudged off the ridge, still inside the cavity, each point has one
5033            // nearest face, which counts if its foot lands inside its trim (a
5034            // tie through a face's rim is that edge, not its offset). The faces
5035            // that wrap the cavity collect the votes; a fillet seen only
5036            // through the mouth of a boss does not.
5037            let nudge = 0.5 * (best - distance);
5038            let mut votes = HashMap::<u64, usize>::default();
5039            for (x, y, z) in DIRECTIONS {
5040                let length = (x * x + y * y + z * z).sqrt();
5041                let near = Vec3::new(point.x + nudge * x / length, point.y + nudge * y / length, point.z + nudge * z / length);
5042                let values = readings(near)?;
5043                let Some((id, _)) = values.iter().min_by(|a, b| a.1.total_cmp(&b.1)).copied() else { continue };
5044                let Some((face, _)) = retained.iter().find(|(face, _)| face.id == id) else { continue };
5045                if foot_inside_trim(face, near)? {
5046                    *votes.entry(id).or_default() += 1;
5047                }
5048            }
5049            let most = votes.values().copied().max().unwrap_or(0);
5050            let bounds = votes.iter().filter(|(_, count)| **count * 2 >= most).map(|(id, _)| *id).collect::<HashSet<_>>();
5051            let witness = CavityWitness { point, clearance: best, bounds };
5052            if !witness.bounds.is_empty() {
5053                return Ok(Some(witness));
5054            }
5055            footless = Some(witness);
5056        }
5057    }
5058    Ok(footless)
5059}
5060
5061/// The box of the solid's vertices and face control points; `None` when a
5062/// control point cannot be read.
5063fn control_hull(source: &BrepSolid, faces: &[&FaceRecord]) -> Option<(Vec3, Vec3)> {
5064    let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
5065    let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
5066    for vertex in &source.vertices {
5067        low = Vec3::new(low.x.min(vertex.point.x), low.y.min(vertex.point.y), low.z.min(vertex.point.z));
5068        high = Vec3::new(high.x.max(vertex.point.x), high.y.max(vertex.point.y), high.z.max(vertex.point.z));
5069    }
5070    for control in faces.iter().flat_map(|face| face.surface.control_points.iter().flatten()) {
5071        let point = control.point().ok()?;
5072        low = Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z));
5073        high = Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z));
5074    }
5075    Some((low, high))
5076}
5077
5078/// `BREP_OFFSET_SHELL_EMPTY_CAVITY` (default on; `=0` restores): [`empty_cavity_shell`].
5079pub(super) fn empty_cavity_enabled() -> bool {
5080    switch!("BREP_OFFSET_SHELL_EMPTY_CAVITY", true)
5081}
5082
5083
5084/// An INWARD shell whose every retained face's offset skin is shadowed: the
5085/// cavity, the points of the solid farther than `distance` from every retained
5086/// face, is empty, so the shell is the solid itself, every face its own
5087/// `Source` image (brep-bench shell/box-walls-meeting: the box 10 x 8 x 6
5088/// shelled by 4 open at its top, whose y walls' offsets meet in the plane
5089/// y = 4, was refused "no retained face keeps any offset skin ... there is no
5090/// cavity to shell"; the case reads the box, 480 and 376).
5091///
5092/// The shadow reading is checked before the solid is returned: on a 12³ grid
5093/// of cell centres over the solid's control hull, no point the solid
5094/// classifies Inside may lie farther than `distance` (plus 1e-9 of the
5095/// solid's size) from every retained face. A point that does means the
5096/// cavity is not empty, and the refusal stands.
5097fn empty_cavity_shell(
5098    source: &BrepSolid,
5099    opening_face_ids: &[u64],
5100    distance: f64,
5101) -> Result<Option<OffsetShellResultRecord>, KernelRefusal> {
5102    if !empty_cavity_enabled() || distance <= 0.0 || opening_face_ids.is_empty() {
5103        return Ok(None);
5104    }
5105    let faces = source.shells.iter().flat_map(|shell| &shell.faces).collect::<Vec<_>>();
5106    let retained = faces.iter().filter(|face| !opening_face_ids.contains(&face.id)).copied().collect::<Vec<_>>();
5107    if retained.is_empty() {
5108        return Ok(None);
5109    }
5110    let edges = source.edges.iter().collect::<Vec<_>>();
5111    let Some((low, high)) = control_hull(source, &faces) else { return Ok(None) };
5112    let scale = crate::solid_scale(source).max(1.0);
5113    let tolerance = 1e-9 * scale;
5114    const CELLS: usize = 12;
5115    let span = high.sub(low);
5116    let mut inside = 0usize;
5117    for i in 0..CELLS {
5118        for j in 0..CELLS {
5119            for k in 0..CELLS {
5120                let at = |index: usize| (index as f64 + 0.5) / CELLS as f64;
5121                let point = Vec3::new(low.x + span.x * at(i), low.y + span.y * at(j), low.z + span.z * at(k));
5122                let class = classify_point(point, source, tolerance * 10.0).or_refuse(KernelStage::Select, "classify_point")?.class;
5123                if class != PointClass::In {
5124                    continue;
5125                }
5126                inside += 1;
5127                let mut nearest = f64::INFINITY;
5128                for face in &retained {
5129                    nearest = nearest.min(distance_to_trimmed_face(face, &edges, point)?);
5130                    if nearest <= distance + tolerance {
5131                        break;
5132                    }
5133                }
5134                if nearest > distance + tolerance {
5135                    os_debug!(
5136                        "empty cavity declined: ({:.4}, {:.4}, {:.4}) lies {nearest:.6} from every retained face",
5137                        point.x, point.y, point.z
5138                    );
5139                    return Ok(None);
5140                }
5141            }
5142        }
5143    }
5144    if inside == 0 {
5145        return Ok(None);
5146    }
5147    os_debug!("empty cavity: every retained skin is shadowed and {inside} sampled interior points lie within the distance");
5148    let face_images = faces
5149        .iter()
5150        .map(|face| OffsetShellFaceImageRecord { role: OffsetFaceRole::Source, source_face_id: face.id })
5151        .collect();
5152    Ok(Some(OffsetShellResultRecord { solid: source.clone(), face_images }))
5153}
5154
5155/// `BREP_OFFSET_THIN_PAD_RECTANGLE` (default on; `=0` restores): a thin-skin
5156/// padded plane with a curved outline is trimmed by its padded rectangle, not
5157/// by its slid outline (see the carrier construction).
5158fn thin_pad_rectangle_enabled() -> bool {
5159    switch!("BREP_OFFSET_THIN_PAD_RECTANGLE", true)
5160}
5161
5162/// `BREP_OFFSET_THIN_SKIN_PAD` (default on; `=0` restores): [`thin_skin_pad`].
5163fn thin_skin_pad_enabled() -> bool {
5164    switch!("BREP_OFFSET_THIN_SKIN_PAD", true)
5165}
5166
5167
5168/// The pad of an INWARD planar carrier whose shell is thinner than the
5169/// fragmenter's graze band: `None` otherwise.
5170///
5171/// Cause (the 10 × 8 × 6 box shelled 0.001 open at its top, brep-bench
5172/// shell/box-paper-thin, read 0.1653 against 0.2959 with an open mesh): each
5173/// carrier is its source face moved 0.001, and its neighbours' skins cut it
5174/// 0.001 inside its rim, with both ends 0.001 from the carrier's corners. The
5175/// imprint's pcurves are right (v = 0.001), but `fragment_face_arranged` lets a
5176/// CUT endpoint join a boundary corner image within `arrangement_tolerance ·
5177/// 100` (1.2e-3 on a 10 × 8 chart) with no 3D check, so both ends moved onto
5178/// the corners, the cut lay on the rim and was dropped as its duplicate
5179/// ("drop cut chain 6 as duplicate of boundary chain 0"). Padded past its rims,
5180/// the carrier's corners are far from every section's ends; the surplus
5181/// strips beyond the sections are outside the source or shadowed by the
5182/// neighbours and are dropped by the ordinary selection.
5183///
5184/// Thin: `distance` under 2e-3 of the solid's size (the band is 1e-4 of a
5185/// chart's diagonal, a chart at most the solid's size). The pad is 4e-3 of
5186/// the size plus the distance.
5187///
5188/// The same switch holds the selection's skin band and the assembly's weld to
5189/// a quarter of an inward distance: both had a fixed 2e-3 floor, twice this
5190/// shell's thickness (see `offset_skin_tolerance` and `assembly_weld`).
5191fn thin_skin_pad(source: &BrepSolid, face: &FaceRecord, distance: f64) -> Result<Option<f64>, KernelRefusal> {
5192    if !thin_skin_pad_enabled() || distance <= 0.0 || !face.surface.is_affine().or_refuse(KernelStage::Refine, "is_affine")? {
5193        return Ok(None);
5194    }
5195    let size = crate::solid_scale(source).max(1e-9);
5196    if distance >= 2e-3 * size {
5197        return Ok(None);
5198    }
5199    Ok(Some(4e-3 * size + distance))
5200}