Skip to main content

brep_boolean/csg/fragment/
face_split.rs

1use crate::{KernelRefusal, KernelStage, OrRefuse};
2use super::*;
3use super::types::{Chain, ChainSource};
4use super::sampling::{enforce_boundary_crossing_parity, refine_near_hints, sag_refine_chain, sample_boundary_chain, sample_chain, trimmed_curve};
5pub use super::loops::{build_loop, edge_for, interior_points, pcurve_for, point_in_polygon, segment_tag, tag_chain, vertex_point};
6pub use super::loop_split::{fragments_agree, loop_split_census, loop_split_face, loop_split_mode, LoopSplitMode};
7/// `BREP_BOUNDARY_VERTEX_HINTS=0|off` restores boundary sampling that is blind
8/// to the face's other loops (see the BOUNDARY-VERTEX HINTS note in
9/// `fragment_face`).
10fn boundary_vertex_hints_enabled() -> bool {
11    switch!("BREP_BOUNDARY_VERTEX_HINTS", true)
12}
13
14/// Imprint id-index shared across every face of one operand. Built ONCE in
15/// `fragment_solid`; without it each face rebuilt `pieces_by_id`/`vertex_by_id`
16/// over ALL pieces (O(F*(P + P*V))) and linear-scanned `by_face`. Lookup-only,
17/// so every face gets the identical pieces/points the scans returned.
18/// `BREP_FRAGMENT_SMALL_RING` (default on; `0`/`off` restores the old
19/// thinning): a chain smaller than the arrangement's junction radius keeps its
20/// shape (see SMALL RING in `fragment_face_arranged`) instead of collapsing
21/// onto its ends.
22pub fn small_ring_enabled() -> bool {
23    switch!("BREP_FRAGMENT_SMALL_RING", true)
24}
25
26/// `BREP_BRIDGE_T_JUNCTION_ANCHOR` (default on; `=0` restores): a cut end lying
27/// on the run of another cut chain is a T-junction the arrangement nodes
28/// exactly, not half of a broken cut, so it is no bridge candidate. Without
29/// this, two independent T-ends close together on one chain read as a broken
30/// junction and are welded to their midpoint, or refused as a missing piece.
31fn bridge_t_junction_anchor_enabled() -> bool {
32    switch!("BREP_BRIDGE_T_JUNCTION_ANCHOR", true)
33}
34
35/// `BREP_BRIDGE_BOUNDARY_T_JUNCTION_ANCHOR` (default on; `=0` restores): a cut end lying on
36/// the run of one of the face's own BOUNDARY chains is a T-junction with the
37/// trim, which the arrangement nodes like any cut meeting the boundary, so it is
38/// no bridge candidate either. Cause (a reported box and pin model at 2.51 and
39/// 2.52): on the wall offset x = d, the bore and floor sections end on the
40/// opening edge 0.25 apart. Their other ends lie within the junction radius of
41/// the front offset's section (d - 2.5 = 0.01 from them), which reads them as
42/// anchored, so the two ends on the opening edge read as a broken cut and were
43/// welded to their midpoint, deleting the short bore arc there.
44fn bridge_boundary_t_junction_anchor_enabled() -> bool {
45    switch!("BREP_BRIDGE_BOUNDARY_T_JUNCTION_ANCHOR", true)
46}
47
48/// `BREP_BRIDGE_SKIP_CROSSING_PAIRS` (default on; `=0` restores): two loose cut ends whose
49/// chains cross each other are not a broken cut. The crossing is their
50/// junction, which the arrangement nodes, and its degree-1 pruning drops both
51/// overshoot stubs, so the pair is never bridged. Cause (a reported
52/// box and pin model at 2.54): on the floor offset, the wall and bore sections cross
53/// 0.061 from the wall section's end, inside the junction radius 0.064, so the
54/// overshoot exclusion did not see it; their ends lay 0.066 apart, just past
55/// that radius, so both read as loose and were welded to their midpoint, which
56/// left the loops open.
57fn bridge_skip_crossing_pairs_enabled() -> bool {
58    switch!("BREP_BRIDGE_SKIP_CROSSING_PAIRS", true)
59}
60
61pub struct FragmentIndex<'a> {
62    pub by_face: HashMap<(u8, u64), &'a [u64]>,
63    pub pieces_by_id: HashMap<u64, &'a ImprintPieceRecord>,
64    pub(super) vertex_points: HashMap<u64, Vec3>,
65    pub(super) cosurface_pairs: HashSet<(FaceKey, FaceKey)>,
66    /// `BREP_FEATURE_SCALE_OPERAND_SLIVERS`: the operand slivers' regions.
67    pub(super) operand_sliver_regions: Vec<crate::spatial::Aabb>,
68}
69
70impl<'a> FragmentIndex<'a> {
71    pub fn build(imprint: &'a ImprintResultRecord) -> Self {
72        let mut by_face: HashMap<(u8, u64), &'a [u64]> = HashMap::default();
73        for entry in &imprint.by_face {
74            // `.entry().or_insert` keeps the FIRST entry, matching the previous
75            // `by_face.iter().find(...)` (keys are unique in practice anyway).
76            by_face
77                .entry((entry.operand, entry.face_id))
78                .or_insert_with(|| entry.piece_ids.as_slice());
79        }
80        FragmentIndex {
81            by_face,
82            cosurface_pairs: imprint.cosurface_pairs.iter()
83                .flat_map(|&(a,b)| [(a,b),(b,a)]).collect(),
84            operand_sliver_regions: imprint
85                .operand_sliver_regions
86                .iter()
87                .map(|(lo, hi)| crate::spatial::Aabb { minimum: Vec3::new(lo[0], lo[1], lo[2]), maximum: Vec3::new(hi[0], hi[1], hi[2]) })
88                .collect(),
89            pieces_by_id: imprint
90                .pieces
91                .iter()
92                .map(|piece| (piece.id, piece))
93                .collect(),
94            vertex_points: imprint
95                .vertices
96                .iter()
97                .map(|vertex| (vertex.id, vertex.point))
98                .collect(),
99        }
100    }
101}
102
103/// Back-compat entry point: builds the imprint index for this single face.
104/// `fragment_solid` builds it once and calls `fragment_face_indexed` directly.
105pub fn fragment_face(
106    solid: &BrepSolid,
107    operand: u8,
108    face: &FaceRecord,
109    imprint: &ImprintResultRecord,
110) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
111    let index = FragmentIndex::build(imprint);
112    let mut profile = FragmentProfile::new();
113    let fragments = fragment_face_indexed(solid, operand, face, &index, &mut profile)?;
114    profile.report(operand);
115    Ok(fragments)
116}
117
118/// The winding the SOURCE face's own outer loop uses in its (u,v) chart:
119/// `Some(true)` when it is negative (clockwise), `Some(false)` when positive,
120/// `None` when the sign cannot be trusted.
121///
122/// `build_loop` orients a rebuilt fragment loop against the arrangement, whose
123/// outer cycles are ALWAYS positive-area (`arrangement.rs`: a cycle goes to
124/// `positive` only when `area > tol²`, and negative cycles become holes), and
125/// reversed it only for `!same_sense` — *material runs counter-clockwise in
126/// (u,v) exactly when `same_sense`*.
127///
128/// That rule is CORRECT and is this kernel's stated invariant: it is what
129/// `validate_uv_wire` checks (`brep/topology/validate.rs`, "wire winding
130/// disagrees with face sense"), what `watertight_tessellation::periodic::trim`
131/// cites as the authority for the same question, and what nine sites in `src/`
132/// compare a winding against. It is also forced by the definitions — with
133/// `n_s = S_u × S_v` and `n_f = same_sense ? n_s : −n_s`, material-on-the-left
134/// projected into the chart with `n_s` up leaves no freedom.
135///
136/// So a face carrying a CW outer loop with `same_sense = true` is MALFORMED,
137/// not merely unusual. This function exists because one arrives anyway: nothing
138/// refuses it on the way in, and `validate_uv_wire`'s verdict is filed under
139/// `ValidationReport::wire_warnings`, which `validate()` does not return — so
140/// every `validate().is_empty()` in the kernel reads clean on it.
141///
142/// Reading the source winding here is DEFENCE IN DEPTH, not a blessing of the
143/// chart: it stops the boolean refusing on such a face and builds the correct
144/// body instead. It does not make the face correct, and the real defect is
145/// upstream in whatever produced it.
146///
147/// Measured on the 2026-09-21 through-tunnel body: five of the stretched
148/// wedge's six faces wind positive, `Box_PZ` winds −1.2334e3 with `same_sense =
149/// true` (the plain box's `Box_PZ` winds +1.2143e3; `TF3` is what flips it).
150/// Rebuilding `Box_PZ` against the arrangement's CCW convention flips every
151/// coedge on it, which is the six same-sense edges the boolean then refuses on.
152///
153/// Restricted to OPEN charts on purpose. On a closed/periodic chart a raw
154/// shoelace is meaningless without the seam unwrap the arrangement scan does,
155/// and that path already has its own material-orientation authority in
156/// `full_span_loop_area`; leaving periodic faces on the old rule keeps this
157/// change to the case it was measured on. `None` also covers a loop with too
158/// few samples or an area too small to carry a reliable sign — the caller then
159/// keeps today's `!same_sense`.
160fn source_loop_winding_negative(face: &FaceRecord) -> Result<Option<bool>, KernelRefusal> {
161    let closed = face
162        .surface
163        .closed_directions()
164        .or_refuse(KernelStage::Fragment, "closed_directions")?;
165    if closed.0 || closed.1 {
166        return Ok(None);
167    }
168    // The OUTER loop is the one bounding the most parameter area; holes wind
169    // against it. Reading `loops[0]` would trust a convention this function
170    // exists to stop trusting.
171    let mut best: Option<f64> = None;
172    for loop_record in &face.loops {
173        let mut points: Vec<Vec2> = Vec::new();
174        for coedge in &loop_record.coedges {
175            let [d0, d1] = coedge
176                .pcurve
177                .domain()
178                .or_refuse(KernelStage::Fragment, "domain")?;
179            const SAMPLES: usize = 24;
180            for step in 0..SAMPLES {
181                let fraction = step as f64 / SAMPLES as f64;
182                // `d0 -> d1` ALWAYS. A pcurve is stored in its coedge's own
183                // traversal direction -- `reverse_fragment` flips `forward` and
184                // calls `pcurve.reversed()` together, and the loop-polygon
185                // builder below walks every pcurve `d0 -> d1` regardless of
186                // `forward`. Consulting `forward` here would reverse those
187                // segments in place and trace a zig-zag: on the plain box's
188                // `Box_NZ` (60.715 x 20 in parameter space) that yields 607.15,
189                // exactly half the 1214.3 the loop actually bounds, and the
190                // sign of a self-intersecting polygon is not the loop's
191                // winding.
192                let t = d0 + (d1 - d0) * fraction;
193                let point = coedge
194                    .pcurve
195                    .evaluate(t)
196                    .or_refuse(KernelStage::Fragment, "evaluate")?;
197                points.push(Vec2 { x: point.x, y: point.y });
198            }
199        }
200        if points.len() < 3 {
201            continue;
202        }
203        let mut area = 0.0;
204        for (index, point) in points.iter().enumerate() {
205            let next = points[(index + 1) % points.len()];
206            area += 0.5 * (crate::polygon::area_term([point.x, point.y], [next.x, next.y]));
207        }
208        if best.map(|current: f64| area.abs() > current.abs()).unwrap_or(true) {
209            best = Some(area);
210        }
211    }
212    // Scale the "is this sign real" floor to the chart, so a millimetre-wide
213    // face is not judged by a millimetre-squared absolute.
214    let u_domain = KnotVector::new(face.surface.knots_u.clone(), face.surface.degree_u)
215        .or_refuse(KernelStage::Fragment, "new")?
216        .domain();
217    let v_domain = KnotVector::new(face.surface.knots_v.clone(), face.surface.degree_v)
218        .or_refuse(KernelStage::Fragment, "new")?
219        .domain();
220    let chart = (u_domain[1] - u_domain[0]) * (v_domain[1] - v_domain[0]);
221    let floor = (chart.abs() * 1e-9).max(f64::MIN_POSITIVE);
222    Ok(match best {
223        Some(area) if area.abs() > floor => Some(area < 0.0),
224        _ => None,
225    })
226}
227
228/// A cut against the other operand's coincident copy of an incident face
229/// inherits that already-established face identity. This permits bounded rim
230/// repair without treating an unrelated nearby curve as the same boundary.
231fn boundary_has_cosurface_partner(
232    solid: &BrepSolid,
233    face: FaceKey,
234    boundary_edge: u64,
235    piece: &ImprintPieceRecord,
236    index: &FragmentIndex,
237) -> bool {
238    piece.support_faces.iter().filter(|other| other.operand != face.operand).any(|other| {
239        solid.shells.iter().flat_map(|shell| &shell.faces).any(|neighbour| {
240            neighbour.id != face.face_id
241                && index.cosurface_pairs.contains(&(FaceKey { operand:face.operand, face_id:neighbour.id }, *other))
242                && neighbour.loops.iter().flat_map(|lp| &lp.coedges)
243                    .any(|coedge| coedge.edge_id == boundary_edge)
244        })
245    })
246}
247
248/// `BREP_COSURFACE_CORNER_COPY` (default on; `=0` restores the 1e-7 bound): a cut on a face that reads as one
249/// surface with the cut's other support face, lying along a boundary edge whose
250/// neighbouring face also reads as one surface with a face of the other operand
251/// that carries the cut too, is that operand's copy of the same corner edge: the two corners sit within the
252/// pairs' separations of one another, so the duplicate test measures it at the
253/// weld floor. Without it a copy a little more than the model tolerance off the
254/// boundary splits off a sub-resolution strip whose test point can read Out
255/// beside a side face that reads On.
256fn dup_cut_space_nomination_enabled() -> bool {
257    crate::switch!("BREP_DUP_CUT_SPACE_NOMINATION", true)
258}
259
260fn cosurface_corner_copy_on() -> bool {
261    crate::switch!("BREP_COSURFACE_CORNER_COPY", true)
262}
263
264fn boundary_is_cosurface_corner(
265    solid: &BrepSolid,
266    face: FaceKey,
267    boundary_edge: u64,
268    piece: &ImprintPieceRecord,
269    index: &FragmentIndex,
270) -> bool {
271    let Some(other) = piece.support_faces.iter().find(|other| other.operand != face.operand) else {
272        return false;
273    };
274    if !index.cosurface_pairs.contains(&(face, *other)) {
275        return false;
276    }
277    solid.shells.iter().flat_map(|shell| &shell.faces).any(|neighbour| {
278        neighbour.id != face.face_id
279            && neighbour.loops.iter().flat_map(|lp| &lp.coedges).any(|coedge| coedge.edge_id == boundary_edge)
280            && index.cosurface_pairs.iter().any(|(first, second)| {
281                // The partner must carry the cut itself: then the cut runs along
282                // its edge with the cut's other support, not merely near a face
283                // that happens to read as one surface with the neighbour.
284                first.operand == face.operand
285                    && first.face_id == neighbour.id
286                    && second.operand != face.operand
287                    && index.by_face.get(&(second.operand, second.face_id)).is_some_and(|ids| ids.contains(&piece.id))
288            })
289    })
290}
291
292/// Detect a distinct narrow strip before replacing its curves by chords.
293/// Search tolerance only nominates a nearby boundary; positive separation in
294/// model space and parallel interior tangents establish a resolvable strip.
295///
296/// FEATURE SCALE B4 (`BREP_FEATURE_SCALE_FRAGMENT`, default on, `=0` off): a
297/// strip between two CUTS is measured the same way. brep-bench
298/// tangent/hairline-slot: the saw's two walls cross the cube's top 1e-6
299/// apart, under the 1.4e-5 resolution of its 10-wide chart, so the
300/// arrangement read them as one line and the strip between them was never
301/// formed.
302fn thin_boundary_resolution(
303    solid: &BrepSolid,
304    face: &FaceRecord,
305    face_key: FaceKey,
306    piece_ids: &[u64],
307    index: &FragmentIndex,
308    search: f64,
309) -> (Option<(f64, f64)>, bool, Option<(f64, f64)>, bool) {
310    let mut resolution: Option<(f64, f64)> = None;
311    // The wedges' resolution, kept apart: it narrows the arrangement and the
312    // sampling but not the bands a chain end is matched in. Whether a lens
313    // asked for it ([`lens_enabled`]).
314    let mut wedged: Option<(f64, f64)> = None;
315    let mut lens_found = false;
316    let mut take_wedge = |found: Option<(f64, f64, bool)>| {
317        if let Some((arrangement, sampling, lens)) = found {
318            lens_found |= lens;
319            wedged = Some(match wedged {
320                Some((a, s)) => (a.min(arrangement), s.min(sampling)),
321                None => (arrangement, sampling),
322            });
323        }
324    };
325    // Whether a feature-scale measure (a near touch, or a strip between two
326    // cuts) found a strip: only then are the image bands narrowed.
327    let mut feature_found = false;
328    let mut take = |strip: Option<(f64, f64)>| {
329        if let Some((arrangement, sampling)) = strip {
330            resolution = Some(match resolution {
331                Some((a, s)) => (a.min(arrangement), s.min(sampling)),
332                None => (arrangement, sampling),
333            });
334        }
335    };
336    let cuts: Vec<&NurbsCurve> = piece_ids
337        .iter()
338        .filter_map(|piece_id| index.pieces_by_id.get(piece_id).and_then(|piece| pcurve_for(piece, face_key).ok()))
339        .collect();
340    for piece_id in piece_ids {
341        let Some(piece) = index.pieces_by_id.get(piece_id) else { continue };
342        let Ok(cut) = pcurve_for(piece, face_key) else { continue };
343        for boundary in face.loops.iter().flat_map(|lp| &lp.coedges) {
344            if boundary_has_cosurface_partner(solid, face_key, boundary.edge_id, piece, index) {
345                continue;
346            }
347            let strip = strip_between(face, &cut, &boundary.pcurve, search);
348            take(match strip {
349                None if crate::feature_scale::fragment_enabled() => {
350                    let touch = near_touch(face, &cut, &boundary.pcurve, search);
351                    if touch.is_some() && env_read!("BREP_DEBUG_FEATURE_SCALE").is_some() {
352                        eprintln!("feature_scale: face {} near touch cut p{piece_id} / boundary e{} -> {touch:?}", face.id, boundary.edge_id);
353                    }
354                    feature_found |= touch.is_some();
355                    touch
356                }
357                strip => strip,
358            });
359            if wedge_enabled() {
360                let found = wedge(face, &cut, &boundary.pcurve, search);
361                if found.is_some() && env_read!("BREP_DEBUG_FEATURE_SCALE").is_some() {
362                    eprintln!("feature_scale: face {} wedge cut p{piece_id} / boundary e{} -> {found:?}", face.id, boundary.edge_id);
363                }
364                take_wedge(found);
365            }
366            if end_gap_enabled() {
367                let gap = end_gap(face, &cut, &boundary.pcurve, search);
368                if gap.is_some() && env_read!("BREP_DEBUG_FEATURE_SCALE").is_some() {
369                    eprintln!("feature_scale: face {} end gap cut p{piece_id} / boundary e{} -> {gap:?}", face.id, boundary.edge_id);
370                }
371                feature_found |= gap.is_some();
372                take(gap);
373            }
374        }
375    }
376    if crate::feature_scale::fragment_enabled() {
377        for (i, cut) in cuts.iter().enumerate() {
378            for other in &cuts[i + 1..] {
379                let strip = strip_between(face, cut, other, search);
380                let found = strip.or_else(|| near_touch(face, cut, other, search));
381                if wedge_enabled() {
382                    let found = match (wedge(face, cut, other, search), wedge(face, other, cut, search)) {
383                        (Some(x), Some(y)) => Some((x.0.min(y.0), x.1.min(y.1), x.2 || y.2)),
384                        (x, y) => x.or(y),
385                    };
386                    if found.is_some() && env_read!("BREP_DEBUG_FEATURE_SCALE").is_some() {
387                        eprintln!("feature_scale: face {} wedge cut pair {i} -> {found:?}", face.id);
388                    }
389                    take_wedge(found);
390                }
391                if found.is_some() && env_read!("BREP_DEBUG_FEATURE_SCALE").is_some() {
392                    eprintln!("feature_scale: face {} cut pair {i} {} -> {} {found:?}", face.id, if strip.is_some() { "strip" } else { "near touch" }, i);
393                }
394                feature_found |= found.is_some();
395                take(found);
396            }
397        }
398    }
399    // A lens of the face's own boundary (`BREP_FEATURE_SCALE_LENS`): two
400    // coedges leaving both of their ends together, a cap 1.8e-6 deep between
401    // two crossing circles, which no cut touches. Only pairs whose ends meet
402    // are read.
403    if lens_enabled() {
404        let coedges: Vec<&NurbsCurve> = face.loops.iter().flat_map(|lp| &lp.coedges).map(|coedge| &coedge.pcurve).collect();
405        let ends = |curve: &NurbsCurve| -> Option<[Vec3; 2]> {
406            let [lo, hi] = curve.domain().ok()?;
407            Some([curve.evaluate(lo).ok()?, curve.evaluate(hi).ok()?])
408        };
409        let ends: Vec<Option<[Vec3; 2]>> = coedges.iter().map(|curve| ends(curve)).collect();
410        for i in 0..coedges.len() {
411            for j in (i + 1)..coedges.len() {
412                let (Some(a), Some(b)) = (ends[i], ends[j]) else { continue };
413                let near = |p: Vec3, q: Vec3| p.sub(q).length() <= search;
414                let shared = (near(a[0], b[0]) && near(a[1], b[1])) || (near(a[0], b[1]) && near(a[1], b[0]));
415                if !shared || near(a[0], a[1]) {
416                    continue;
417                }
418                let found = match (wedge(face, coedges[i], coedges[j], search), wedge(face, coedges[j], coedges[i], search)) {
419                    (Some(x), Some(y)) => Some((x.0.min(y.0), x.1.min(y.1), x.2 || y.2)),
420                    (x, y) => x.or(y),
421                };
422                let found = found.filter(|found| found.2);
423                if found.is_some() && env_read!("BREP_DEBUG_FEATURE_SCALE").is_some() {
424                    eprintln!("feature_scale: face {} boundary lens {i}/{j} -> {found:?}", face.id);
425                }
426                take_wedge(found);
427            }
428        }
429    }
430    (resolution, feature_found, wedged, lens_found)
431}
432
433/// FEATURE SCALE, wedge (`BREP_FEATURE_SCALE_WEDGE`, default on; `=0` leaves
434/// wedges to the bands as before): see [`wedge`].
435fn wedge_enabled() -> bool {
436    crate::switch!("BREP_FEATURE_SCALE_WEDGE", true)
437}
438
439/// The arrangement and sampling resolutions a WEDGE needs: `cut` and `other`
440/// leave one end point together at a small angle in the chart and part in
441/// space. Within `resolution / angle` of the shared point the two polylines
442/// stand inside the arrangement's band, and there their chords cross and
443/// re-cross on round-off: a tool's wall (|Su| 11, |Sv| 5e-3) held the cut of a
444/// sweep's side wall and its own split edge leaving one vertex 8e-5 apart in
445/// the chart over its whole height (10° in space); at the 1.4e-6 resolution
446/// the first 1e-2 of the cut read as crossing the edge, minting slivers of
447/// 1e-9 whose loops missed each other by 1e-5. The resolution asked for keeps
448/// that stretch within 1e-3 of the cut's chart length. `None` unless the two
449/// leave a common end (within `search` in the chart) at under 0.2 rad, part
450/// by more than 8e-7 in model space a tenth of the way along the cut, and need
451/// a resolution finer than `search` yet no finer than the identity band along
452/// the chart's stiffer direction (the isotropic band takes the softer one,
453/// which on such a chart is wider than the wedge): a narrower wedge, or a
454/// tangent departure, is left to the bands as before.
455fn wedge(face: &FaceRecord, cut: &NurbsCurve, other: &NurbsCurve, search: f64) -> Option<(f64, f64, bool)> {
456    let [lo, hi] = cut.domain().ok()?;
457    let [other_lo, other_hi] = other.domain().ok()?;
458    // The cut's length in the chart, along a 16-chord polyline; a closed cut
459    // (its ends together) has no wedge end.
460    let mut chart_length = 0.0;
461    let mut previous = cut.evaluate(lo).ok()?;
462    for step in 1..=16 {
463        let point = cut.evaluate(lo + (hi - lo) * step as f64 / 16.0).ok()?;
464        chart_length += point.sub(previous).length();
465        previous = point;
466    }
467    if !(chart_length > 0.0) || cut.evaluate(lo).ok()?.sub(cut.evaluate(hi).ok()?).length() <= search {
468        return None;
469    }
470    let mut found: Option<(f64, f64, bool)> = None;
471    for (end, inward) in [(lo, 1.0), (hi, -1.0)] {
472        let Ok(cut_sample) = cut.derivatives(end, 1) else { continue };
473        for (other_end, other_inward) in [(other_lo, 1.0), (other_hi, -1.0)] {
474            let Ok(other_sample) = other.derivatives(other_end, 1) else { continue };
475            if cut_sample[0].sub(other_sample[0]).length() > search {
476                continue;
477            }
478            let a = cut_sample[1].scale(inward);
479            let b = other_sample[1].scale(other_inward);
480            if !(a.length() * b.length() > 1e-30) {
481                continue;
482            }
483            // A narrow wedge only: at a wider angle the curves part within
484            // the band at once, and narrowing a face for an ordinary junction
485            // (a spout's cut leaving a dome's pole) changed answers that were
486            // right.
487            let angle = a.cross(b).length().atan2(a.dot(b));
488            if !(angle.is_finite()) || angle > 0.2 {
489                continue;
490            }
491            let resolution = angle * chart_length * 1e-3;
492            if resolution >= search {
493                continue;
494            }
495            // How far the two part in model space and in the chart, a tenth of
496            // the way along the cut and (`BREP_FEATURE_SCALE_LENS`) halfway:
497            // a LENS, the cut and the other leaving both of its ends together
498            // (a cap's rim and the crossing circle 1.8e-6 inside it), parts
499            // most at its middle, by less than 8e-7 at a tenth.
500            let parting = |fraction: f64| -> Option<(f64, f64)> {
501                let parameter = if inward > 0.0 { lo + fraction * (hi - lo) } else { hi - fraction * (hi - lo) };
502                let probe = cut.evaluate(parameter).ok()?;
503                let foot = project_point_to_curve(other, probe).ok()?;
504                let here = face.surface.evaluate(probe.x, probe.y).ok()?;
505                let there = face.surface.evaluate(foot.point.x, foot.point.y).ok()?;
506                Some((here.sub(there).length(), probe.sub(foot.point).length()))
507            };
508            let Some((space, _)) = parting(0.1) else { continue };
509            let Ok(probe) = cut.evaluate(if inward > 0.0 { lo + 0.1 * (hi - lo) } else { hi - 0.1 * (hi - lo) }) else { continue };
510            let Ok(derivatives) = face.surface.derivatives(probe.x, probe.y, 1) else { continue };
511            let stiff = derivatives[1][0].length().max(derivatives[0][1].length());
512            let identity = crate::tolerance::parametric_tolerance(1e-7, stiff);
513            // A lens leaves the other's far end too: the cut's other end lies
514            // on one of the other's ends.
515            let far_end = if inward > 0.0 { hi } else { lo };
516            let far_point = cut.evaluate(far_end).ok();
517            let far_partner = far_point.and_then(|far| {
518                [other_lo, other_hi]
519                    .iter()
520                    .filter_map(|&end| other.evaluate(end).ok())
521                    .filter(|point| point.sub(far).length() <= search)
522                    .min_by(|p, q| p.sub(far).length().total_cmp(&q.sub(far).length()))
523                    .map(|point| (far, point))
524            });
525            let two_ended = far_partner.is_some();
526            // How far apart the two stand in model space at their ends: a
527            // lens bulges, parting at its middle by more than twice either
528            // end's gap. Two straight runs leaving both ends within the search
529            // part halfway by the mean of their end gaps, a wedge however the
530            // chart reads (a box face turned 1e-4 degrees on itself).
531            let end_gaps = far_partner.and_then(|(far, partner)| {
532                let gap = |p: Vec3, q: Vec3| -> Option<f64> {
533                    Some(face.surface.evaluate(p.x, p.y).ok()?.sub(face.surface.evaluate(q.x, q.y).ok()?).length())
534                };
535                Some(gap(cut_sample[0], other_sample[0])?.max(gap(far, partner)?))
536            });
537            // Where the ordinary reading declines (parting under 8e-7 a tenth
538            // along, or a resolution under the identity band), a lens is read
539            // halfway instead.
540            let lens = if two_ended && lens_enabled() && (space <= 8e-7 || resolution < identity) {
541                parting(0.5).filter(|(space, _)| *space > 8e-7 && end_gaps.is_some_and(|ends| *space > 2.0 * ends))
542            } else {
543                None
544            };
545            if space <= 8e-7 && lens.is_none() {
546                continue;
547            }
548            // A lens is resolved no finer than the identity band, its chains
549            // sampled to an eighth of its parting.
550            let (resolution, sampling) = match lens {
551                Some((_, chart)) => (resolution.max(identity), Some(chart / 8.0)),
552                None if resolution < identity => continue,
553                None => (resolution, None),
554            };
555            // Never more than 64 times finer than the face's own resolution:
556            // the sampling follows the arrangement down, and a dome's pole
557            // wedge asking for 2e-9 ran its chains out of points. A lens's
558            // chains are as short as the lens, and it may go 1024 times finer
559            // (a plane cutting a lens 1.8e-6 deep, on a cap 40 wide).
560            let resolution = resolution.max(search / if lens.is_some() { 1024.0 } else { 64.0 });
561            // A lens is resolved only where it parts by eight resolutions in
562            // the chart; a narrower one is left to the bands as before.
563            if lens.is_some_and(|(_, chart)| chart < 8.0 * resolution) {
564                continue;
565            }
566            let wanted = (resolution, search.min(resolution * 16.0).min(sampling.unwrap_or(f64::INFINITY)), lens.is_some());
567            found = Some(match found {
568                Some((x, y, l)) => (x.min(wanted.0), y.min(wanted.1), l || wanted.2),
569                None => wanted,
570            });
571        }
572    }
573    found
574}
575
576/// FEATURE SCALE, lens (`BREP_FEATURE_SCALE_LENS`, default on, `=0` off): a
577/// [`wedge`] whose two curves share both ends, which the ordinary reading
578/// declines (parting under 8e-7 a tenth of the way along the cut, or asking a
579/// resolution under the identity band), is read again halfway, and one
580/// parting by eight resolutions there is resolved no finer than the identity
581/// band.
582fn lens_enabled() -> bool {
583    crate::switch!("BREP_FEATURE_SCALE_LENS", true)
584}
585
586/// `BREP_FRAGMENT_EXACT_END_STAYS` (default on; `=0` restores the snap): see the endpoint snap in
587/// [`fragment_face_arranged`].
588fn exact_end_stays_on() -> bool {
589    crate::switch!("BREP_FRAGMENT_EXACT_END_STAYS", true)
590}
591
592/// FEATURE SCALE, end gap (`BREP_FEATURE_SCALE_END_GAP`, default on, `=0` off): an
593/// open cut that ENDS near a boundary edge of the face without ending on it.
594/// `near_touch` declines every approach at a cut's end, because a marched cut
595/// stops a few 1e-6 short of the boundary it ends on and resolving to that
596/// slack kept its end from snapping to its junction. A section that ends at a
597/// genuine vertex a small but real distance off the boundary is another
598/// thing: a cube against a copy turned 0.01 deg has a section on the cube's
599/// side that ends where the turned top edge pierces it, 3.9e-4 below the
600/// side's own top edge, inside the chart's wide bands (1.4e-3 image band and
601/// 2.1e-2 junction radius on a 10-wide face), and the arrangement joined that
602/// end to the top edge: a vertex the solid does not have, and a valid shell
603/// 1.9e-5 out in volume. An end is a gap when it stands off the boundary by
604/// more than the weld floor in model space (so a marched cut's slack is not
605/// one) and within the wide bands in the chart; the face's resolutions are
606/// then taken to that gap, as for a near touch.
607pub fn end_gap_enabled() -> bool {
608    crate::switch!("BREP_FEATURE_SCALE_END_GAP", true)
609}
610
611fn end_gap(face: &FaceRecord, cut: &NurbsCurve, other: &NurbsCurve, search: f64) -> Option<(f64, f64)> {
612    // Planar faces whose cut and boundary are both straight: the regime the
613    // measure was read on. Curved faces and curved trims keep their bands
614    // (fillet corners, pole bridges and rim strips are tuned to them).
615    let straight = |curve: &NurbsCurve| curve.degree == 1 && curve.control_points.len() == 2;
616    if !face.surface.is_affine().ok()? || !straight(cut) || !straight(other) {
617        return None;
618    }
619    let [lo, hi] = cut.domain().ok()?;
620    let start = cut.evaluate(lo).ok()?;
621    let end = cut.evaluate(hi).ok()?;
622    if start.sub(end).length() <= search {
623        return None;
624    }
625    let u_domain = face.surface.domain_u().ok()?;
626    let v_domain = face.surface.domain_v().ok()?;
627    let diagonal = ((u_domain[1] - u_domain[0]).powi(2) + (v_domain[1] - v_domain[0]).powi(2)).sqrt();
628    let reach = (search * 100.0).max(diagonal * 1.5e-3);
629    let mut found: Option<(f64, f64)> = None;
630    for point in [start, end] {
631        let Ok(foot) = project_point_to_curve(other, point) else { continue };
632        if foot.distance > reach {
633            continue;
634        }
635        let (Ok(here), Ok(there)) = (face.surface.evaluate(point.x, point.y), face.surface.evaluate(foot.point.x, foot.point.y)) else {
636            continue;
637        };
638        if here.sub(there).length() <= crate::tolerance::WELD_FLOOR {
639            continue;
640        }
641        let identity = crate::classification::surface_uv_band(&face.surface, point.x, point.y, 1e-7);
642        if foot.distance <= identity * 8.0 {
643            continue;
644        }
645        let resolution = (search.min((foot.distance / 128.0).max(identity)), search.min(foot.distance / 8.0));
646        found = Some(match found {
647            Some((a, s)) => (a.min(resolution.0), s.min(resolution.1)),
648            None => resolution,
649        });
650    }
651    found
652}
653
654/// FEATURE SCALE B4, near touch (`BREP_FEATURE_SCALE_FRAGMENT`): the
655/// resolutions a cut needs where it comes closer to `other` than the
656/// arrangement resolves without meeting it. brep-bench
657/// tangent/bore-a-micron-from-the-wall: the bore's circle on each cap passes
658/// 1e-6 inside the rim circle at (5, 0), under the cap's 1.4e-5 resolution, so
659/// the two circles fused there and both cap loops opened. The gaps vary from
660/// 1e-6 to 2 around the circle, which `strip_between` reads as a tangency. The
661/// closest approach is found by 257 samples refined by golden section; it is
662/// a near touch when it lies within `8·search` in the chart yet more than 8e-7
663/// apart in model space and beyond the chart's identity band.
664fn near_touch(face: &FaceRecord, cut: &NurbsCurve, other: &NurbsCurve, search: f64) -> Option<(f64, f64)> {
665    // Curves lie in their control hulls: hulls farther apart than the reach
666    // cannot hold a near touch, and most pairs on a face are that far apart.
667    let hull = |curve: &NurbsCurve| crate::spatial::Aabb::from_curve_controls(curve).ok();
668    if !hull(cut)?.intersects(hull(other)?, search * 8.0) {
669        return None;
670    }
671    if !near_touch_held_enabled() {
672        return near_touch_search(face, cut, other, search, None);
673    }
674    let held = crate::projection::HeldCurve::new(other.clone());
675    let quick = NearTouchQuick { held: &held, spans: span_hulls(other) };
676    let found = near_touch_search(face, cut, other, search, Some(&quick));
677    if near_touch_held_check() {
678        let fresh = near_touch_search(face, cut, other, search, None);
679        let bits = |found: Option<(f64, f64)>| found.map(|(a, b)| (a.to_bits(), b.to_bits()));
680        assert_eq!(bits(found), bits(fresh), "near touch held check: held {found:?} vs fresh {fresh:?}");
681    }
682    found
683}
684
685/// `BREP_NEAR_TOUCH_HELD` (default on; =0 runs the full scan with fresh projections): [`near_touch`] projects onto `other`
686/// through a [`crate::projection::HeldCurve`] (its seed samples read once, not
687/// its content hashed into the seed cache on each of the search's ~420
688/// projections; the same answers bit for bit) and its closest-approach scan
689/// projects only the samples whose distance bound from `other`'s span hulls
690/// could reach the scan's minimum. The scan's pick, the first sample at the
691/// least distance, is the same. `BREP_NEAR_TOUCH_HELD_CHECK=1` (read only with
692/// the switch on, like every check mode of a default-off switch) searches both
693/// ways and stops on any difference.
694fn near_touch_held_enabled() -> bool {
695    crate::switch!("BREP_NEAR_TOUCH_HELD", true)
696}
697
698fn near_touch_held_check() -> bool {
699    crate::switch!("BREP_NEAR_TOUCH_HELD_CHECK", false)
700}
701
702/// What the quick search holds for `other`: the held curve and the boxes of
703/// its spans' control points.
704struct NearTouchQuick<'a> {
705    held: &'a crate::projection::HeldCurve,
706    spans: Option<Vec<crate::spatial::Aabb>>,
707}
708
709/// The box of each knot span's control points. A span of a curve with finite
710/// positive weights lies in the hull of its `degree + 1` controls, so every
711/// point of the curve lies in one of these boxes; `None` when a weight or a
712/// coordinate does not allow that.
713fn span_hulls(curve: &NurbsCurve) -> Option<Vec<crate::spatial::Aabb>> {
714    let degree = curve.degree;
715    let controls = &curve.control_points;
716    if controls.iter().any(|c| !(c.w.is_finite() && c.w > 0.0 && c.x.is_finite() && c.y.is_finite() && c.z.is_finite())) {
717        return None;
718    }
719    let mut boxes = Vec::new();
720    for index in degree..controls.len() {
721        if index + 1 >= curve.knots.len() || curve.knots[index] >= curve.knots[index + 1] {
722            continue;
723        }
724        let points = controls[index - degree..=index].iter().map(|c| c.point()).collect::<Result<Vec<_>, _>>().ok()?;
725        boxes.push(crate::spatial::Aabb::from_points(points));
726    }
727    (!boxes.is_empty()).then_some(boxes)
728}
729
730/// A lower bound of the distance from `point` to any point in `boxes`,
731/// cushioned for the rounding of the gap and of an evaluated curve point
732/// (relative 1e-9 plus 64 ulps of the coordinates' size); never above the
733/// true distance from `point` to the curve the boxes hold.
734fn distance_floor(point: Vec3, boxes: &[crate::spatial::Aabb]) -> f64 {
735    let single = crate::spatial::Aabb { minimum: point, maximum: point };
736    boxes
737        .iter()
738        .map(|bounds| {
739            let gap = single.separation(*bounds);
740            let cushion = 64.0 * f64::EPSILON * (point.length() + bounds.minimum.length() + bounds.maximum.length());
741            gap * (1.0 - 1e-9) - cushion
742        })
743        .fold(f64::INFINITY, f64::min)
744        .max(0.0)
745}
746
747fn near_touch_search(
748    face: &FaceRecord,
749    cut: &NurbsCurve,
750    other: &NurbsCurve,
751    search: f64,
752    quick: Option<&NearTouchQuick>,
753) -> Option<(f64, f64)> {
754    let project = |point: Vec3| match quick {
755        Some(quick) => quick.held.project(point),
756        None => project_point_to_curve(other, point),
757    };
758    let [lo, hi] = cut.domain().ok()?;
759    let [other_lo, other_hi] = other.domain().ok()?;
760    // A cut that ENDS on `other` has no near touch with it, and saying so
761    // takes two projections instead of the search's 417 (brep-bench
762    // boolean/cross-drilled-cube: the Steinmetz arcs of crossing bores meet
763    // at their ends, and this search was 70% of that case's time). The search
764    // below samples the cut's ends exactly, so its closest approach is no
765    // wider in the chart than this end's gap (under 1e-3 of the reach and
766    // the identity band, below any gap it takes as a near touch), and the refined approach then lies
767    // at an open cut's end (`at_end`) or within 8e-7 in model space: None
768    // either way. The gap must be tiny in the chart AND in space (at a pole
769    // the chart's points meet in space while far apart in the chart). A cut
770    // that stops short of a boundary (a marched cut, by a few 1e-6) keeps
771    // the search.
772    let ends_on_other = [lo, hi].into_iter().any(|t| {
773        let Ok(point) = cut.evaluate(t) else { return false };
774        let Ok(foot) = project(point) else { return false };
775        let identity = crate::classification::surface_uv_band(&face.surface, point.x, point.y, 1e-7);
776        if foot.distance > (search * 1e-3).min(identity) {
777            return false;
778        }
779        match (face.surface.evaluate(point.x, point.y), face.surface.evaluate(foot.point.x, foot.point.y)) {
780            (Ok(here), Ok(there)) => here.sub(there).length() <= 1e-9,
781            _ => false,
782        }
783    });
784    if ends_on_other {
785        return None;
786    }
787    let gap = |parameter: f64| -> Option<(f64, Vec3, Vec3, f64)> {
788        let point = cut.evaluate(parameter).ok()?;
789        let projected = project(point).ok()?;
790        Some((projected.distance, point, projected.point, projected.u))
791    };
792    // A closed curve's ends are a seam, not a junction; an open one's are
793    // where it meets the rest of the arrangement.
794    let closed = |curve: &NurbsCurve, a: f64, b: f64| -> bool {
795        match (curve.evaluate(a), curve.evaluate(b)) {
796            (Ok(start), Ok(end)) => start.sub(end).length() <= search,
797            _ => false,
798        }
799    };
800    let (cut_closed, other_closed) = (closed(cut, lo, hi), closed(other, other_lo, other_hi));
801    const SAMPLES: usize = 256;
802    let step = (hi - lo) / SAMPLES as f64;
803    let mut best: Option<(f64, f64)> = None;
804    match quick.and_then(|quick| quick.spans.as_deref()) {
805        None => {
806            for i in 0..=SAMPLES {
807                let parameter = lo + step * i as f64;
808                if let Some((distance, _, _, _)) = gap(parameter) {
809                    if best.is_none_or(|(_, d)| distance < d) {
810                        best = Some((parameter, distance));
811                    }
812                }
813            }
814        }
815        Some(spans) => {
816            // The same pick: the FIRST sample at the least distance. Samples
817            // are projected in order of their distance floor until the floor
818            // passes the least distance found, so every sample left unprojected
819            // is strictly farther than the pick and cannot tie with it.
820            let mut order = Vec::with_capacity(SAMPLES + 1);
821            for i in 0..=SAMPLES {
822                let parameter = lo + step * i as f64;
823                // A sample that does not evaluate is tried as the full scan tries it.
824                let floor = cut.evaluate(parameter).map_or(0.0, |point| distance_floor(point, spans));
825                order.push((floor, i));
826            }
827            order.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
828            let mut least: Option<(usize, f64)> = None;
829            for (floor, i) in order {
830                if least.is_some_and(|(_, d)| floor > d) {
831                    break;
832                }
833                if let Some((distance, _, _, _)) = gap(lo + step * i as f64) {
834                    if distance.is_nan() {
835                        return near_touch_search(face, cut, other, search, None);
836                    }
837                    if least.is_none_or(|(j, d)| distance < d || (distance == d && i < j)) {
838                        least = Some((i, distance));
839                    }
840                }
841            }
842            best = least.map(|(i, distance)| (lo + step * i as f64, distance));
843        }
844    }
845    let (centre, _) = best?;
846    let (mut a, mut b) = ((centre - step).max(lo), (centre + step).min(hi));
847    let ratio = 0.5 * (5f64.sqrt() - 1.0);
848    for _ in 0..80 {
849        let c = b - ratio * (b - a);
850        let d = a + ratio * (b - a);
851        if gap(c)?.0 < gap(d)?.0 { b = d } else { a = c }
852    }
853    let parameter = 0.5 * (a + b);
854    let (low_gap, point, foot, foot_parameter) = gap(parameter)?;
855    if low_gap > search * 8.0 {
856        return None;
857    }
858    // Only an approach in the middle of both curves is a near touch. A marched
859    // cut stops a few 1e-6 short of the boundary it ends on (its slack past the
860    // trim), and resolving the arrangement to that gap kept its end from
861    // snapping to its junction (r16: eleven boolean fixtures refused).
862    let at_end = |t: f64, a: f64, b: f64| (t - a).abs() <= 0.01 * (b - a) || (b - t).abs() <= 0.01 * (b - a);
863    if (!cut_closed && at_end(parameter, lo, hi)) || (!other_closed && at_end(foot_parameter, other_lo, other_hi)) {
864        return None;
865    }
866    let actual = face.surface.evaluate(point.x, point.y).ok()?;
867    let rim = face.surface.evaluate(foot.x, foot.y).ok()?;
868    if actual.sub(rim).length() <= 8e-7 {
869        return None;
870    }
871    let identity = crate::classification::surface_uv_band(&face.surface, point.x, point.y, 1e-7);
872    if low_gap <= identity * 8.0 {
873        return None;
874    }
875    Some((search.min((low_gap / 128.0).max(identity)), search.min(low_gap / 8.0)))
876}
877
878/// The arrangement and sampling resolutions a strip between `cut` and
879/// `other` (both pcurves on `face`) needs, or `None` when they do not bound a
880/// strip: some sample of `cut` farther than `8·search` from `other`, a
881/// tangent not parallel to it, a sample within 8e-7 of it in model space or
882/// within the chart's identity band, or gaps varying more than fourfold (a
883/// crossing or an isolated tangency).
884fn strip_between(face: &FaceRecord, cut: &NurbsCurve, other: &NurbsCurve, search: f64) -> Option<(f64, f64)> {
885    let [lo, hi] = cut.domain().ok()?;
886    let middle = cut.evaluate((lo + hi) * 0.5).ok()?;
887    let nearest = project_point_to_curve(other, middle).ok()?;
888    if nearest.distance > search * 8.0 { return None; }
889    let mut low_gap = f64::INFINITY;
890    let mut high_gap = 0.0f64;
891    let mut identity = 0.0f64;
892    for fraction in [0.125, 0.25, 0.5, 0.75, 0.875] {
893        let parameter = lo + (hi - lo) * fraction;
894        let cut_sample = cut.derivatives(parameter, 1).ok()?;
895        let point = cut_sample[0];
896        let projected = project_point_to_curve(other, point).ok()?;
897        if projected.distance > search * 8.0 { return None; }
898        let other_sample = other.derivatives(projected.u, 1).ok()?;
899        let a = cut_sample[1];
900        let b = other_sample[1];
901        let lengths = a.length() * b.length();
902        if lengths <= 1e-30 || a.dot(b).abs() < 0.995 * lengths { return None; }
903        let actual = face.surface.evaluate(point.x, point.y).ok()?;
904        let rim = face.surface.evaluate(projected.point.x, projected.point.y).ok()?;
905        if actual.sub(rim).length() <= 8e-7 { return None; }
906        let floor = crate::classification::surface_uv_band(
907            &face.surface, point.x, point.y, 1e-7,
908        );
909        if projected.distance <= floor * 8.0 { return None; }
910        low_gap = low_gap.min(projected.distance);
911        high_gap = high_gap.max(projected.distance);
912        identity = identity.max(floor);
913    }
914    // A crossing or isolated tangency does not describe a strip.
915    if high_gap > low_gap * 4.0 { return None; }
916    Some((search.min((low_gap / 128.0).max(identity)), search.min(low_gap / 8.0)))
917}
918
919fn fragment_face_indexed(
920    solid: &BrepSolid,
921    operand: u8,
922    face: &FaceRecord,
923    index: &FragmentIndex,
924    profile: &mut FragmentProfile,
925) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
926    let face_started = profile.enabled.then(Instant::now);
927    let mut lap_start = face_started;
928    let result = fragment_face_stages(solid, operand, face, index, profile, &mut lap_start);
929    profile.face_done(face.id, face_started);
930    result
931}
932
933fn fragment_face_stages(
934    solid: &BrepSolid,
935    operand: u8,
936    face: &FaceRecord,
937    index: &FragmentIndex,
938    profile: &mut FragmentProfile,
939    lap_start: &mut Option<Instant>,
940) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
941    let face_key = FaceKey {
942        operand,
943        face_id: face.id,
944    };
945    let piece_ids = index
946        .by_face
947        .get(&(operand, face.id))
948        .copied()
949        .unwrap_or(&[]);
950    if piece_ids.is_empty() {
951        profile.uncut_probe_faces += 1;
952        let u = KnotVector::new(face.surface.knots_u.clone(), face.surface.degree_u).or_refuse(KernelStage::Fragment, "new")?.domain();
953        let v = KnotVector::new(face.surface.knots_v.clone(), face.surface.degree_v).or_refuse(KernelStage::Fragment, "new")?.domain();
954        let uv = Vec2 {
955            x: (u[0] + u[1]) / 2.0,
956            y: (v[0] + v[1]) / 2.0,
957        };
958        let probe_started = profile.enabled.then(Instant::now);
959        let centre_inside = parameter_point_in_face(face, uv, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")? == PolygonClass::Inside;
960        if let Some(started) = probe_started { profile.uncut_probe += started.elapsed(); }
961        if !centre_inside {
962            // Trimmed faces need the arrangement path even without cuts to
963            // find a point in their actual outer loop.
964        } else {
965            let mut extra_test_points = Vec::new();
966            for (fu, fv) in [(0.35, 0.35), (0.65, 0.65)] {
967                let candidate = Vec2 {
968                    x: u[0] + (u[1] - u[0]) * fu,
969                    y: v[0] + (v[1] - v[0]) * fv,
970                };
971                let probe_started = profile.enabled.then(Instant::now);
972                let inside = parameter_point_in_face(face, candidate, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")? == PolygonClass::Inside;
973                if let Some(started) = probe_started { profile.uncut_probe += started.elapsed(); }
974                if inside {
975                    extra_test_points.push(face.surface.evaluate(candidate.x, candidate.y).or_refuse(KernelStage::Fragment, "evaluate")?);
976                }
977            }
978            let untouched = vec![untouched_fragment(face, operand, uv, extra_test_points)?];
979            profile.untouched += profile.lap(lap_start);
980            return Ok(untouched);
981        }
982    }
983    if !piece_ids.is_empty() {
984        profile.cut_faces += 1;
985    }
986    // LOOP SPLIT (`fragment/loop_split.rs`): a face whose pieces are simple is
987    // split loop by loop; `check` runs both paths and returns the
988    // arrangement's; `on` returns the split's where it applies.
989    let mode = loop_split_mode();
990    let mut split_result: Option<Result<Vec<FaceFragmentRecord>, super::loop_split::Decline>> = None;
991    if mode != LoopSplitMode::Off && !piece_ids.is_empty() {
992        let started = profile.enabled.then(Instant::now);
993        let outcome = loop_split_face(solid, operand, face, face_key, piece_ids, index)?;
994        if let Some(started) = started {
995            profile.loop_split += started.elapsed();
996        }
997        match &outcome {
998            Ok(_) => profile.loop_split_faces += 1,
999            Err(_) => profile.loop_split_declined += 1,
1000        }
1001        if mode == LoopSplitMode::On {
1002            if let Ok(fragments) = outcome {
1003                if std::env::var("BREP_DEBUG_FRAG_COUNT").is_ok() {
1004                    eprintln!("frag count: operand {operand} face {} pieces {:?} loop-split -> {} fragments", face.id, piece_ids, fragments.len());
1005                }
1006                *lap_start = profile.enabled.then(Instant::now);
1007                return Ok(fragments);
1008            }
1009        }
1010        split_result = Some(outcome);
1011        *lap_start = profile.enabled.then(Instant::now);
1012    }
1013    let arranged = fragment_face_arranged(solid, operand, face, face_key, piece_ids, index, profile, lap_start);
1014    // A face no section touches that the arrangement answered with NOTHING is
1015    // not gone: it is one fragment, itself, and all it needs is a point of
1016    // its own material, found beside its trim (`trim_interior_probe`). The
1017    // arrangement keeps every face it does split (a pinched loop into two).
1018    if piece_ids.is_empty() && trim_probe_enabled() && matches!(&arranged, Ok(fragments) if fragments.is_empty()) {
1019        let u = KnotVector::new(face.surface.knots_u.clone(), face.surface.degree_u).or_refuse(KernelStage::Fragment, "new")?.domain();
1020        let v = KnotVector::new(face.surface.knots_v.clone(), face.surface.degree_v).or_refuse(KernelStage::Fragment, "new")?.domain();
1021        if let Some((uv, extra_test_points)) = trim_interior_probe(face, u, v)? {
1022            return Ok(vec![untouched_fragment(face, operand, uv, extra_test_points)?]);
1023        }
1024    }
1025    if let Some(split) = &split_result {
1026        let verdict = match (split, &arranged) {
1027            (Err(decline), _) => format!("declined {decline}"),
1028            (Ok(_), Err(refusal)) => format!("MISMATCH split built {} fragments, arrangement refused: {refusal}", split.as_ref().map_or(0, Vec::len)),
1029            (Ok(split), Ok(arranged)) => match fragments_agree(split, arranged) {
1030                Ok(agreement) => agreement.to_string(),
1031                Err(why) => format!("MISMATCH {why}"),
1032            },
1033        };
1034        loop_split_census(|| format!("operand {operand} face {} pieces {} loops {} {verdict}", face.id, piece_ids.len(), face.loops.len()));
1035    }
1036    if std::env::var("BREP_DEBUG_FRAG_COUNT").is_ok() && !piece_ids.is_empty() {
1037        match (&split_result, &arranged) {
1038            (Some(Err(decline)), Ok(fragments)) => eprintln!("frag count: operand {operand} face {} pieces {:?} loop split declined ({decline}); arrangement -> {} fragments", face.id, piece_ids, fragments.len()),
1039            (_, Ok(fragments)) => eprintln!("frag count: operand {operand} face {} pieces {:?} arrangement -> {} fragments", face.id, piece_ids, fragments.len()),
1040            (_, Err(refusal)) => eprintln!("frag count: operand {operand} face {} arrangement refused: {refusal}", face.id),
1041        }
1042    }
1043    arranged
1044}
1045
1046
1047#[allow(clippy::too_many_arguments)]
1048fn fragment_face_arranged(
1049    solid: &BrepSolid,
1050    operand: u8,
1051    face: &FaceRecord,
1052    face_key: FaceKey,
1053    piece_ids: &[u64],
1054    index: &FragmentIndex,
1055    profile: &mut FragmentProfile,
1056    lap_start: &mut Option<Instant>,
1057) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
1058
1059    let u_domain = KnotVector::new(face.surface.knots_u.clone(), face.surface.degree_u).or_refuse(KernelStage::Fragment, "new")?.domain();
1060    let v_domain = KnotVector::new(face.surface.knots_v.clone(), face.surface.degree_v).or_refuse(KernelStage::Fragment, "new")?.domain();
1061    let diagonal =
1062        ((u_domain[1] - u_domain[0]).powi(2) + (v_domain[1] - v_domain[0]).powi(2)).sqrt();
1063    let original_resolution = 1e-7f64.max(diagonal * 1e-6);
1064    let (strip_resolution, feature_strip, wedge_resolution, lens_face) = thin_boundary_resolution(solid, face, face_key, piece_ids, index, original_resolution);
1065    let (band_tolerance, band_sampling) = strip_resolution
1066        .unwrap_or((original_resolution, original_resolution));
1067    // A wedge narrows the arrangement and the sampling only; the bands a chain
1068    // end is matched in stay the face's own (a marched cut stops a few 1e-6
1069    // short of the boundary it ends on, and a dome's pole wedge that narrowed
1070    // them kept that end from its junction).
1071    let (arrangement_tolerance, sampling_bound) = match wedge_resolution {
1072        Some((arrangement, sampling)) => (band_tolerance.min(arrangement), band_sampling.min(sampling)),
1073        None => (band_tolerance, band_sampling),
1074    };
1075    // FEATURE SCALE B4 (`BREP_FEATURE_SCALE_FRAGMENT`): with a thin strip
1076    // between two cuts or a near touch on the face, a chain end is matched to another vertex's image only within
1077    // the strip's own sampling bound in the chart and 1e-7 in model space
1078    // (`strip_between` admits only strips over 8e-7 wide), not 100
1079    // resolutions and 1e-5: the hairline slot's two walls end 1e-6 apart on
1080    // the cube's top, and each wall's cut took the other's far end.
1081    // Only for a strip a feature-scale measure found: a cut-against-boundary
1082    // strip the fragmenter always measured kept its wide bands (narrowing them
1083    // too opened loops on revolve ∪ wedge fixtures with coincident side planes).
1084    // OPERAND SLIVERS (`BREP_FEATURE_SCALE_OPERAND_SLIVERS`): a face that meets
1085    // a sliver FeatureScale registered between the two operands matches its
1086    // chain ends in the strip's bands too. Two boxes whose +y faces stand 1e-5
1087    // apart: a side face's strip between its own edge and the other box's
1088    // edge (the cosurface exchange's cut) is exactly 1e-5 wide, the wide
1089    // bands (1e-5 in model space) took the strip's corners for one vertex, the
1090    // cut read as a duplicate of the bent boundary and was dropped, and the
1091    // slab lost its four side faces.
1092    let strip_snap = feature_strip
1093        || (strip_resolution.is_some()
1094            && !index.operand_sliver_regions.is_empty()
1095            && crate::spatial::Aabb::from_surface_controls(&face.surface)
1096                .is_ok_and(|face_box| index.operand_sliver_regions.iter().any(|region| face_box.intersects(*region, original_resolution))));
1097    let (image_band, image_band_3d) = if strip_snap {
1098        (sampling_bound, 1e-7)
1099    } else {
1100        (band_tolerance * 100.0, 1e-5)
1101    };
1102    let snap_threshold = 0.1 * diagonal;
1103    let junction_radius = (band_tolerance * 50.0).max(diagonal * 1.5e-3);
1104    // WRAPPED-BAND RE-BASE: a face on a closed direction whose material is the
1105    // wrapped COMPLEMENT of its trim hull (two full-wrap rims at the hull
1106    // edges, material crossing the seam between them — trial 35's torus face:
1107    // rims at v=0.25/1.0, material v∈[0,0.25]) cannot be arranged in the flat
1108    // domain rectangle: a cut through the band ends at v=0 while its junction
1109    // partner (the split rim vertex) sits at v=1, so every cut dangles, cycle
1110    // extraction fails, and the face is dropped wholesale (one-use cascade).
1111    // Re-base into the material-coherent frame [hull_high, hull_low+period]:
1112    // shift every chain point on the low side of the hull window (+period), so
1113    // rims and cuts junction in ONE unwrapped chart, and wrap region test
1114    // points back into the domain on exit. Detection mirrors the imprint's
1115    // restricted-carrier wrap guard: the hull-complement strip contains no
1116    // loop curves, so one sample at its middle decides materiality exactly.
1117    // Escape hatch: BREP_BAND_REBASE=0.
1118    let band_rebase: [Option<(f64, f64)>; 2] = {
1119        let mut rebase = [None, None];
1120        let closed = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
1121        if (closed.0 || closed.1) && std::env::var("BREP_BAND_REBASE").as_deref() != Ok("0") {
1122            // Per-coedge hulls on each axis, plus whether any ISO-RIM
1123            // (a coedge whose pcurve is near-constant on the axis) sits at a
1124            // domain edge — the discriminator for the wrapped-band class.
1125            // A seam-straddling boundary band (helmet Face_15, whose source
1126            // pcurves are already unwrapped past the domain) has no such rim
1127            // and its frame is already coherent; it must NOT be re-based.
1128            let mut coverage: [Vec<[f64; 2]>; 2] = [Vec::new(), Vec::new()];
1129            let mut edge_rim = [false, false];
1130            let mut hull = [
1131                [f64::INFINITY, f64::NEG_INFINITY],
1132                [f64::INFINITY, f64::NEG_INFINITY],
1133            ];
1134            for coedge in face
1135                .loops
1136                .iter()
1137                .flat_map(|loop_record| &loop_record.coedges)
1138            {
1139                let mut extent = [
1140                    [f64::INFINITY, f64::NEG_INFINITY],
1141                    [f64::INFINITY, f64::NEG_INFINITY],
1142                ];
1143                for control in &coedge.pcurve.control_points {
1144                    if control.w.abs() <= 1e-300 {
1145                        continue;
1146                    }
1147                    let point = [control.x / control.w, control.y / control.w];
1148                    for axis in 0..2 {
1149                        extent[axis][0] = extent[axis][0].min(point[axis]);
1150                        extent[axis][1] = extent[axis][1].max(point[axis]);
1151                        hull[axis][0] = hull[axis][0].min(point[axis]);
1152                        hull[axis][1] = hull[axis][1].max(point[axis]);
1153                    }
1154                }
1155                for axis in 0..2 {
1156                    if !extent[axis][0].is_finite() {
1157                        continue;
1158                    }
1159                    let domain = if axis == 0 { u_domain } else { v_domain };
1160                    let span = domain[1] - domain[0];
1161                    coverage[axis].push(extent[axis]);
1162                    let flat = extent[axis][1] - extent[axis][0] <= 1e-3 * span;
1163                    let at_edge = (extent[axis][0] - domain[0]).abs() <= 1e-6 * span
1164                        || (extent[axis][1] - domain[1]).abs() <= 1e-6 * span;
1165                    if flat && at_edge {
1166                        edge_rim[axis] = true;
1167                    }
1168                }
1169            }
1170            for axis in 0..2 {
1171                if !(if axis == 0 { closed.0 } else { closed.1 }) || !edge_rim[axis] {
1172                    continue;
1173                }
1174                let domain = if axis == 0 { u_domain } else { v_domain };
1175                let span = domain[1] - domain[0];
1176                // Merge the coverage intervals (clamped into the domain) and
1177                // find the largest uncovered gap. The gap contains no boundary
1178                // curve, so it is uniformly material or uniformly void — one
1179                // sample at its middle decides exactly. A strictly INTERIOR
1180                // void gap means the material wraps through the domain edge.
1181                let mut intervals: Vec<[f64; 2]> = coverage[axis]
1182                    .iter()
1183                    .map(|window| {
1184                        [window[0].max(domain[0]), window[1].min(domain[1])]
1185                    })
1186                    .filter(|window| window[1] >= window[0])
1187                    .collect();
1188                intervals.sort_by(|a, b| a[0].total_cmp(&b[0]));
1189                let mut gaps: Vec<[f64; 2]> = Vec::new();
1190                let mut reach = domain[0];
1191                for window in &intervals {
1192                    if window[0] > reach {
1193                        gaps.push([reach, window[0]]);
1194                    }
1195                    reach = reach.max(window[1]);
1196                }
1197                if reach < domain[1] {
1198                    gaps.push([reach, domain[1]]);
1199                }
1200                let other_mid = (hull[1 - axis][0].max(if axis == 0 {
1201                    v_domain[0]
1202                } else {
1203                    u_domain[0]
1204                }) + hull[1 - axis][1].min(if axis == 0 {
1205                    v_domain[1]
1206                } else {
1207                    u_domain[1]
1208                })) / 2.0;
1209                let mut void: Option<[f64; 2]> = None;
1210                for gap in gaps {
1211                    if gap[1] - gap[0] <= 1e-6 * span {
1212                        continue;
1213                    }
1214                    let mid = (gap[0] + gap[1]) / 2.0;
1215                    let sample = if axis == 0 {
1216                        Vec2 {
1217                            x: mid,
1218                            y: other_mid,
1219                        }
1220                    } else {
1221                        Vec2 {
1222                            x: other_mid,
1223                            y: mid,
1224                        }
1225                    };
1226                    if parameter_point_in_face(face, sample, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")? != PolygonClass::Inside
1227                        && void
1228                            .map(|best| gap[1] - gap[0] > best[1] - best[0])
1229                            .unwrap_or(true)
1230                    {
1231                        void = Some(gap);
1232                    }
1233                }
1234                if let Some([g0, g1]) = void {
1235                    // The material+boundary arc wraps the domain edge exactly
1236                    // when boundary coverage touches BOTH edge representations
1237                    // (the on-seam rim at one, the material-side chains at the
1238                    // other) with the void between them. An ordinary band
1239                    // (material inside the rims) touches only one edge and
1240                    // must keep the flat frame.
1241                    let touches_low = intervals
1242                        .iter()
1243                        .any(|window| window[0] <= domain[0] + 1e-6 * span);
1244                    let touches_high = intervals
1245                        .iter()
1246                        .any(|window| window[1] >= domain[1] - 1e-6 * span);
1247                    if touches_low && touches_high {
1248                        // Shift everything on the low side of the void up one
1249                        // period so the band is contiguous in the arrangement
1250                        // frame.
1251                        rebase[axis] = Some(((g0 + g1) / 2.0, span));
1252                    }
1253                }
1254            }
1255        }
1256        rebase
1257    };
1258    let rebase_point = |mut point: Vec2| -> Vec2 {
1259        if let Some((cutoff, period)) = band_rebase[0] {
1260            if point.x < cutoff {
1261                point.x += period;
1262            }
1263        }
1264        if let Some((cutoff, period)) = band_rebase[1] {
1265            if point.y < cutoff {
1266                point.y += period;
1267            }
1268        }
1269        point
1270    };
1271    // Region test points computed in a re-based or unwrapped frame must be
1272    // folded back into the domain before trim classification / evaluation.
1273    // Wrapping is gated on the axis being CLOSED (a coherent flat face never
1274    // produces out-of-domain interior points, so this is a no-op there).
1275    let wrap_back = {
1276        let closed = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
1277        move |mut point: Vec2| -> Vec2 {
1278            if closed.0 {
1279                let span = u_domain[1] - u_domain[0];
1280                if point.x < u_domain[0] || point.x > u_domain[1] {
1281                    point.x = u_domain[0] + (point.x - u_domain[0]).rem_euclid(span);
1282                }
1283            }
1284            if closed.1 {
1285                let span = v_domain[1] - v_domain[0];
1286                if point.y < v_domain[0] || point.y > v_domain[1] {
1287                    point.y = v_domain[0] + (point.y - v_domain[0]).rem_euclid(span);
1288                }
1289            }
1290            point
1291        }
1292    };
1293    profile.setup += profile.lap(lap_start);
1294    let pieces_by_id = &index.pieces_by_id;
1295    let mut cut_hints = Vec::new();
1296    let mut active_pieces = Vec::new();
1297    let mut cut_keys = HashMap::default();
1298    for piece_id in piece_ids {
1299        let piece = pieces_by_id
1300            .get(piece_id)
1301            .ok_or_else(|| KernelRefusal::internal(KernelStage::Fragment, "fragment.face_split", "fragment_face: missing imprint piece"))?;
1302        let pcurve = pcurve_for(piece, face_key)?;
1303        let [start, end] = pcurve.domain().or_refuse(KernelStage::Fragment, "domain")?;
1304        let a = pcurve.evaluate(start).or_refuse(KernelStage::Fragment, "evaluate")?;
1305        let b = pcurve.evaluate(end).or_refuse(KernelStage::Fragment, "evaluate")?;
1306        let middle = pcurve.evaluate((start + end) / 2.0).or_refuse(KernelStage::Fragment, "evaluate")?;
1307        for point in [a, b] {
1308            cut_hints.push(Vec2 {
1309                x: point.x,
1310                y: point.y,
1311            });
1312        }
1313        let quantize = |point: Vec3| {
1314            (
1315                (point.x / arrangement_tolerance).round() as i64,
1316                (point.y / arrangement_tolerance).round() as i64,
1317            )
1318        };
1319        let mut endpoints = [quantize(a), quantize(b)];
1320        endpoints.sort();
1321        let key = (endpoints[0], quantize(middle), endpoints[1]);
1322        if cut_keys.insert(key, *piece_id).is_none() {
1323            active_pieces.push(*piece_id);
1324        }
1325    }
1326
1327    let mut segments = Vec::new();
1328    let mut chains = Vec::new();
1329    let mut vertex_images: std::collections::HashMap<String, Vec<Vec2>> =
1330        std::collections::HashMap::new();
1331    let mut endpoint_images: Vec<(Vec3, Vec2)> = Vec::new();
1332    // Each boundary image carries its 3D vertex point so the boundary-side
1333    // canonicalization can refuse to unify two DISTINCT boundary vertices.
1334    let mut boundary_images: Vec<(Vec2, Vec3)> = Vec::new();
1335    // BOUNDARY-VERTEX ANCHOR (t427 box-corner graze). The boundary-side snap
1336    // below (rule 3) merges a chain endpoint onto a same-side boundary image
1337    // within arr_tol*100 with NO 3D check. For a CUT/section terminus that is
1338    // the intended near-tangent graze bridge onto a trim edge. For a BOUNDARY
1339    // endpoint it is a bug: two genuinely-distinct same-operand boundary
1340    // vertices (t427: box corner v8 at v=68.4851 vs the edge-16 split A at
1341    // v=68.4783, 6.8e-3 apart on the u=max domain edge, 6.8e-3 apart in 3D ≫
1342    // the 1e-5 weld floor) get unified, which droops edge 21's pcurve and
1343    // mints a phantom corner lens bounded by derived edges → a one-use cluster
1344    // that only strands in UNION (where the unsectioned neighbour keeps the
1345    // whole edge 21). Anchor a boundary endpoint to a same-side image only when
1346    // they are the SAME physical vertex (3D-coincident within the weld floor).
1347    // Hatch BREP_BOUNDARY_VERTEX_ANCHOR=0 restores the pre-fix behaviour.
1348    let boundary_vertex_anchor_off =
1349        std::env::var("BREP_BOUNDARY_VERTEX_ANCHOR").as_deref() == Ok("0");
1350    let boundary_side = |point: Vec2| {
1351        let distances = [
1352            (point.x - u_domain[0]).abs(),
1353            (point.x - u_domain[1]).abs(),
1354            (point.y - v_domain[0]).abs(),
1355            (point.y - v_domain[1]).abs(),
1356        ];
1357        let index = distances
1358            .iter()
1359            .enumerate()
1360            .min_by(|a, b| a.1.total_cmp(b.1))
1361            .map(|entry| entry.0)
1362            .unwrap();
1363        (distances[index] <= arrangement_tolerance * 50.0).then_some(index)
1364    };
1365
1366    // RIM BRIDGE (`BREP_RIM_BRIDGE`, default on, `=0` off; the imprint mints the
1367    // bridge): a straight section a few `tol / |tan·n|` long between two
1368    // rim pierces, one end on a vertex of this face's rim (within the weld)
1369    // and the other a distinct vertex just inside it. The far end lies far closer to the rim in the chart
1370    // than in space, so rule 3 below (a cut end onto a same-side boundary
1371    // image, no 3-D check) would fold the bridge onto the rim vertex and the
1372    // sections meeting it would skip it. Its ends keep their own images.
1373    let bridge_keys: HashSet<String> = if rim_bridge_enabled() {
1374        let weld = crate::tolerance::assembler_weld(1e-7);
1375        // The face's own boundary vertices: a bridge has one end on its rim.
1376        let mut rim_points = Vec::new();
1377        for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
1378            if let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) {
1379                for vertex_id in [edge.start_vertex_id, edge.end_vertex_id] {
1380                    rim_points.push(vertex_point(solid, vertex_id)?);
1381                }
1382            }
1383        }
1384        let on_rim = |point: &Vec3| rim_points.iter().any(|rim| rim.sub(*point).length() <= weld);
1385        piece_ids
1386            .iter()
1387            .filter_map(|piece_id| pieces_by_id.get(piece_id))
1388            .filter(|piece| {
1389                piece.start_vertex_id != piece.end_vertex_id
1390                    && piece.curve.degree == 1
1391                    && piece.curve.control_points.len() == 2
1392                    && match (index.vertex_points.get(&piece.start_vertex_id), index.vertex_points.get(&piece.end_vertex_id)) {
1393                        (Some(a), Some(b)) => {
1394                            let gap = a.sub(*b).length();
1395                            gap > weld && gap <= 1e-3 && (on_rim(a) || on_rim(b))
1396                        }
1397                        _ => false,
1398                    }
1399            })
1400            .flat_map(|piece| [format!("i:{}", piece.start_vertex_id), format!("i:{}", piece.end_vertex_id)])
1401            .collect()
1402    } else {
1403        HashSet::default()
1404    };
1405    // Vertices where two or more cut pieces of this face meet: an interior
1406    // junction of the section, never a boundary vertex it merely nears.
1407    let junction_keys: HashSet<String> = if crate::switch!("BREP_NEAR_SEAM_CLOSED_RUN", true) {
1408        let mut seen: HashMap<u64, usize> = HashMap::default();
1409        for piece in active_pieces.iter().filter_map(|piece_id| pieces_by_id.get(piece_id)) {
1410            if piece.start_vertex_id != piece.end_vertex_id {
1411                *seen.entry(piece.start_vertex_id).or_default() += 1;
1412                *seen.entry(piece.end_vertex_id).or_default() += 1;
1413            }
1414        }
1415        seen.into_iter().filter(|(_, uses)| *uses >= 2).map(|(id, _)| format!("i:{id}")).collect()
1416    } else {
1417        HashSet::default()
1418    };
1419    let mut add_chain = |mut points: Vec<Vec2>,
1420                         source: ChainSource,
1421                         vertex_start_key: String,
1422                         vertex_start_point: Vec3,
1423                         vertex_end_key: String,
1424                         vertex_end_point: Vec3,
1425                         is_boundary: bool|
1426     -> Result<(), KernelRefusal> {
1427        for (at, key, point3) in [
1428            (0usize, vertex_start_key, vertex_start_point),
1429            (points.len() - 1, vertex_end_key, vertex_end_point),
1430        ] {
1431            let point = points[at];
1432            let bridged = bridge_keys.contains(&key);
1433            let junction = junction_keys.contains(&key);
1434            let images = vertex_images.entry(key).or_default();
1435            let canonical = images
1436                .iter()
1437                .copied()
1438                .find(|image| image.sub(point).length() <= snap_threshold)
1439                .or_else(|| {
1440                    endpoint_images
1441                        .iter()
1442                        .find(|(candidate3, candidate)| {
1443                            candidate3.sub(point3).length() <= image_band_3d
1444                                && candidate.sub(point).length() <= image_band
1445                        })
1446                        .map(|candidate| candidate.1)
1447                })
1448                .or_else(|| {
1449                    if bridged {
1450                        return None;
1451                    }
1452                    boundary_side(point).and_then(|side| {
1453                        boundary_images
1454                            .iter()
1455                            .find(|(candidate, candidate3)| {
1456                                boundary_side(*candidate) == Some(side)
1457                                    && candidate.sub(point).length()
1458                                        <= image_band
1459                                    // Boundary endpoints only merge to a same-side
1460                                    // image when 3D-coincident (same physical
1461                                    // vertex); cut endpoints keep the graze bridge.
1462                                    && (boundary_vertex_anchor_off
1463                                        || (!is_boundary && !junction)
1464                                        || candidate3.sub(point3).length() <= 1e-5)
1465                            })
1466                            .map(|(candidate, _)| *candidate)
1467                    })
1468                });
1469            if let Some(canonical) = canonical {
1470                points[at] = canonical;
1471                images.push(canonical);
1472            } else {
1473                images.push(point);
1474                endpoint_images.push((point3, point));
1475                if is_boundary && boundary_side(point).is_some() {
1476                    boundary_images.push((point, point3));
1477                }
1478            }
1479        }
1480        if points.len() > 2 {
1481            let start = points[0];
1482            let end = points[points.len() - 1];
1483            let thin = |radius: f64| {
1484                let mut kept = vec![start];
1485                kept.extend(points[1..points.len() - 1].iter().copied().filter(|point| {
1486                    point.sub(start).length() > radius && point.sub(end).length() > radius
1487                }));
1488                kept.push(end);
1489                kept
1490            };
1491            let mut kept = thin(junction_radius);
1492            // SMALL RING (`BREP_FRAGMENT_SMALL_RING`): a chain that lies wholly
1493            // inside the junction radius of its own ends (the 0.028 pinhole on a
1494            // plane charted over [0, 30]², radius 0.064) loses every interior
1495            // point: a closed one bounds nothing and two half-circles fold onto
1496            // one chord, so the region they ring is never carved. When the
1497            // thinning would leave the chain flatter than it is (its bulge off
1498            // the chord, or off its vertex when closed, past ten tolerances),
1499            // thin it at a tenth of that bulge instead.
1500            let closed = start.sub(end).length() <= arrangement_tolerance;
1501            if kept.len() < if closed { 4 } else { 3 } && small_ring_enabled() {
1502                let chord = end.sub(start);
1503                let span = chord.length();
1504                let bulge = points
1505                    .iter()
1506                    .map(|point| {
1507                        let offset = point.sub(start);
1508                        if closed || span <= arrangement_tolerance {
1509                            offset.length()
1510                        } else {
1511                            (offset.x * chord.y - offset.y * chord.x).abs() / span
1512                        }
1513                    })
1514                    .fold(0.0, f64::max);
1515                // On a lens's face the arcs bound a strip eight resolutions
1516                // wide, at least one of them bulging by four.
1517                if bulge > arrangement_tolerance * if lens_face { 4.0 } else { 10.0 } {
1518                    kept = thin(bulge * 0.1);
1519                }
1520            }
1521            points = kept;
1522        }
1523        let chain_index = chains.len();
1524        let chain_segments = points
1525            .windows(2)
1526            .map(|pair| (pair[0], pair[1]))
1527            .collect::<Vec<_>>();
1528        for (segment_index, pair) in points.windows(2).enumerate() {
1529            segments.push(Segment2 {
1530                a: pair[0],
1531                b: pair[1],
1532                tag: segment_tag(chain_index, segment_index),
1533            });
1534        }
1535        chains.push(Chain {
1536            source,
1537            count: points.len() - 1,
1538            start: points[0],
1539            end: points[points.len() - 1],
1540            segments: chain_segments,
1541        });
1542        Ok(())
1543    };
1544
1545    profile.hints += profile.lap(lap_start);
1546    // SEAM-IMAGE LOOPS: per-loop u-control-hulls, computed once for the
1547    // straddling-hole gate below (does any OTHER loop span the full closed-u
1548    // domain — the rectangle-with-seam outer that closes the strip walls).
1549    let loop_hull_u: Vec<[f64; 2]> = face
1550        .loops
1551        .iter()
1552        .map(|loop_record| {
1553            let mut hull = [f64::INFINITY, f64::NEG_INFINITY];
1554            for coedge in &loop_record.coedges {
1555                for control in &coedge.pcurve.control_points {
1556                    if control.w.abs() <= 1e-300 {
1557                        continue;
1558                    }
1559                    hull[0] = hull[0].min(control.x / control.w);
1560                    hull[1] = hull[1].max(control.x / control.w);
1561                }
1562            }
1563            hull
1564        })
1565        .collect();
1566    // Signed area of the face's full-u-span loop (the rectangle-with-seam
1567    // outer), recorded as it is processed: it defines the chart's material
1568    // orientation, so a HOLE is any loop winding OPPOSITE to it (the absolute
1569    // sign is chart-dependent — mirrored charts flip both).
1570    let mut full_span_loop_area: Option<f64> = None;
1571    // Post-rebase boundary polyline segments (incl. seam-image copies), kept
1572    // for the sag-refinement boundary-crossing parity guard on cut chains.
1573    let mut boundary_segments: Vec<(Vec2, Vec2)> = Vec::new();
1574    // The u and v extent of the boundary chains as the arrangement places
1575    // them — after the seam-hop unwrap and the band re-base, before any
1576    // seam-image copy — which is the period window the face's material lives
1577    // in. See the cut-chain period lift below.
1578    let mut band_hull = [[f64::INFINITY, f64::NEG_INFINITY]; 2];
1579    // BOUNDARY-VERTEX HINTS (2026-11-02): a curved boundary chord is refined
1580    // where ANOTHER boundary vertex of the face lies within its length, exactly
1581    // as `refine_near_hints` already refines it near a cut's endpoints.
1582    // `sample_boundary_chain` only keeps a chord within a ten-thousandth of the
1583    // domain diagonal of its pcurve, and that bound cannot see a second loop:
1584    // the plate's top face (diagonal 222) drew its r 10.7 blend-corner arc at
1585    // 16 chords sagging 0.0128, while the corner vertex of the hole the earlier
1586    // subtracts cut sits 0.011 inside that arc. The hole loop poked through the
1587    // outer loop's polyline, the arrangement cut the rim at the chord crossings
1588    // (0.04 from the true arc, on the far side of the hole vertex), and the
1589    // subtract refused with four one-use rim edges and a 0.0125 vertex gap. The
1590    // face's own vertices are hints, so a chord that a neighbouring vertex
1591    // approaches within its length is drawn sixteen times finer there (sag 5e-5
1592    // against the 0.011 clearance). A chord's own endpoints are not hints for
1593    // it (every chord ends at a vertex), and a straight pcurve has no chords to
1594    // refine. Escape hatch `BREP_BOUNDARY_VERTEX_HINTS=0|off`.
1595    let boundary_vertex_hints: Vec<Vec2> = if boundary_vertex_hints_enabled() {
1596        let mut hints = Vec::new();
1597        for loop_record in &face.loops {
1598            for coedge in &loop_record.coedges {
1599                let [start, end] = coedge.pcurve.domain().or_refuse(KernelStage::Fragment, "domain")?;
1600                for parameter in [start, end] {
1601                    let point = coedge.pcurve.evaluate(parameter).or_refuse(KernelStage::Fragment, "evaluate")?;
1602                    hints.push(Vec2 { x: point.x, y: point.y });
1603                }
1604            }
1605        }
1606        hints
1607    } else {
1608        Vec::new()
1609    };
1610    for (loop_index, loop_record) in face.loops.iter().enumerate() {
1611        // SEAM-HOP UNWRAP: a loop whose pcurves are drawn IN-DOMAIN but hop
1612        // the seam between consecutive coedges (t91's face 675: the boundary
1613        // jumps u=1→0 at v≈0.967 and back at v≈0.453) is incoherent in the
1614        // flat chart — its cut chains mint fine and then dangle against the
1615        // hopping boundary, cycle extraction fails, and the face drops
1616        // wholesale (the trial-35 zero-fragment signature, third variant).
1617        // Unwrap onto the covering plane with the SAME per-coedge offsets the
1618        // mass integrator / tessellator / seam-band classifier use
1619        // (`loop_seam_offsets`); a continuous loop gets all-zero offsets and
1620        // is untouched (helmet-class unwrapped sources, native seam-edge
1621        // loops, plain faces). Composes with the band re-base above: offsets
1622        // normalize the boundary FIRST, after which the re-base's
1623        // below-cutoff boundary shifts are no-ops and only its cut-chain
1624        // shifts still apply. Escape hatch: BREP_LOOP_UNWRAP=0.
1625        let closed = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
1626        let offsets = if (closed.0 || closed.1)
1627            && std::env::var("BREP_LOOP_UNWRAP").as_deref() != Ok("0")
1628        {
1629            crate::topology::loop_seam_offsets(
1630                &loop_record.coedges,
1631                closed.0,
1632                closed.1,
1633                u_domain[1] - u_domain[0],
1634                v_domain[1] - v_domain[0],
1635            ).or_refuse(KernelStage::Fragment, "csg.fragment.face_split")?
1636        } else {
1637            vec![[0.0, 0.0]; loop_record.coedges.len()]
1638        };
1639        let mut sampled: Vec<(usize, Vec<Vec2>, NurbsCurve, u64, u64)> =
1640            Vec::with_capacity(loop_record.coedges.len());
1641        for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
1642            let edge = edge_for(solid, coedge.edge_id)?;
1643            let (start_vertex, end_vertex) = if coedge.forward {
1644                (edge.start_vertex_id, edge.end_vertex_id)
1645            } else {
1646                (edge.end_vertex_id, edge.start_vertex_id)
1647            };
1648            let offset = offsets
1649                .get(coedge_index)
1650                .copied()
1651                .unwrap_or([0.0, 0.0]);
1652            // Adaptive samples are not uniformly spaced in parameter. Do not
1653            // feed them to refine_near_hints, which assumes uniform input.
1654            let boundary_points = if strip_resolution.is_some() || wedge_resolution.is_some() {
1655                let initial = sample_chain(&coedge.pcurve)?;
1656                sag_refine_chain(&coedge.pcurve, initial, sampling_bound)?.0
1657            } else {
1658                // A curved boundary is drawn within a ten-thousandth of the
1659                // domain's diagonal of itself (`sample_boundary_chain`), so a
1660                // narrow face's two rims cannot cross each other.
1661                let initial = sample_boundary_chain(&coedge.pcurve, (diagonal * 1e-4).max(sampling_bound), 1024)?;
1662                if boundary_vertex_hints.is_empty() || initial.len() < 3 {
1663                    refine_near_hints(&initial, &coedge.pcurve, &cut_hints)?
1664                } else {
1665                    let own = [initial[0], initial[initial.len() - 1]];
1666                    let hints: Vec<Vec2> = cut_hints
1667                        .iter()
1668                        .copied()
1669                        .chain(boundary_vertex_hints.iter().copied().filter(|hint| {
1670                            own.iter().all(|end| hint.sub(*end).length() > arrangement_tolerance)
1671                        }))
1672                        .collect();
1673                    refine_near_hints(&initial, &coedge.pcurve, &hints)?
1674                }
1675            };
1676            let points: Vec<Vec2> = boundary_points
1677                    .into_iter()
1678                    .map(|point| {
1679                        rebase_point(Vec2 {
1680                            x: point.x + offset[0],
1681                            y: point.y + offset[1],
1682                        })
1683                    })
1684                    .collect();
1685            let curve = trimmed_curve(&edge.curve, edge.t0, edge.t1)?;
1686            let curve = if coedge.forward {
1687                curve
1688            } else {
1689                curve.reversed().or_refuse(KernelStage::Fragment, "reversed")?
1690            };
1691            sampled.push((coedge_index, points, curve, start_vertex, end_vertex));
1692        }
1693        // SEAM-IMAGE for a STRADDLING HOLE loop: an inner (hole) loop whose
1694        // unwrapped chains poke past a closed-u domain wall exists at only ONE
1695        // period image in the arrangement strip, so the strip's OTHER side
1696        // never sees it — the seam-adjacent region there keeps a boundary
1697        // running straight through the hole opening (t181/00000312#p7: face
1698        // 519's decagon hole unwraps to u∈[−0.039,0.039]; the region left of
1699        // the seam used the FULL seam edge 475 while the right region split at
1700        // the hole crossings; the hole's far-half rim edges stranded one-use
1701        // and an 18mm derived chord bridged the gap). Insert a duplicate of
1702        // the loop's chains shifted one period toward the strip's other side,
1703        // so BOTH walls are split by the hole and the half-hole phantom
1704        // regions (rejected by the cross-frame containment) carve it out.
1705        // STRUCTURAL GATE (all required): u-closed face; ≥2 loops; the loop's
1706        // unwrapped span crosses a u-wall by > junction slack; loop width ≤
1707        // half the period (a compact hole, never a rim/horizon); winding
1708        // OPPOSITE to the full-span outer loop (hole orientation relative to
1709        // the chart — an outer loop copy would double-cover material); and
1710        // some OTHER loop's control hull spans the full u-domain (the
1711        // seam-carrying rectangle exists). Escape hatch:
1712        // BREP_SEAM_IMAGE_LOOPS=0.
1713        let image_shift: Option<f64> = {
1714            let span = u_domain[1] - u_domain[0];
1715            let slack = arrangement_tolerance * 50.0;
1716            if !closed.0
1717                || face.loops.len() < 2
1718                || span <= 0.0
1719                || std::env::var("BREP_SEAM_IMAGE_LOOPS").as_deref() == Ok("0")
1720            {
1721                None
1722            } else {
1723                let mut min_u = f64::INFINITY;
1724                let mut max_u = f64::NEG_INFINITY;
1725                let mut area = 0.0;
1726                let mut flat: Vec<Vec2> = sampled
1727                    .iter()
1728                    .flat_map(|(_, points, ..)| points.iter().copied())
1729                    .collect();
1730                if flat.len() < 3 {
1731                    flat.clear();
1732                }
1733                for (index, point) in flat.iter().enumerate() {
1734                    min_u = min_u.min(point.x);
1735                    max_u = max_u.max(point.x);
1736                    let next = flat[(index + 1) % flat.len()];
1737                    area += crate::polygon::area_term([point.x, point.y], [next.x, next.y]);
1738                }
1739                // Full-span discrimination must use the UNWRAPPED width: a
1740                // straddling hole's raw control hull spans the whole domain
1741                // (its halves are stored at both seam sides), but its
1742                // unwrapped chains are compact; only the true outer rectangle
1743                // stays period-wide after unwrapping.
1744                let spans_full_domain =
1745                    !flat.is_empty() && max_u - min_u >= span * (1.0 - 1e-6);
1746                if spans_full_domain && full_span_loop_area.is_none() {
1747                    full_span_loop_area = Some(area);
1748                }
1749                let straddles_low = min_u < u_domain[0] - slack;
1750                let straddles_high = max_u > u_domain[1] + slack;
1751                let compact = max_u - min_u <= 0.5 * span;
1752                let is_hole = full_span_loop_area
1753                    .map(|outer| !spans_full_domain && area * outer < 0.0)
1754                    .unwrap_or(false);
1755                let has_full_span_other = loop_hull_u.iter().enumerate().any(|(other, hull)| {
1756                    other != loop_index
1757                        && hull[0] <= u_domain[0] + 1e-6 * span
1758                        && hull[1] >= u_domain[1] - 1e-6 * span
1759                });
1760                if compact && is_hole && has_full_span_other && (straddles_low ^ straddles_high) {
1761                    if env_read!("BREP_DEBUG_FRAG")
1762                        .map(|value| value == face.id.to_string())
1763                        .unwrap_or(false)
1764                    {
1765                        eprintln!(
1766                            "  seam-image: face {} loop {loop_index} straddles u-wall (u=[{min_u:.6},{max_u:.6}]) — inserting {} period image",
1767                            face.id,
1768                            if straddles_low { "+1" } else { "-1" }
1769                        );
1770                    }
1771                    Some(if straddles_low { span } else { -span })
1772                } else {
1773                    None
1774                }
1775            }
1776        };
1777        for (coedge_index, points, curve, start_vertex, end_vertex) in sampled {
1778            let coedge = &loop_record.coedges[coedge_index];
1779            for point in &points {
1780                band_hull[0] = [band_hull[0][0].min(point.x), band_hull[0][1].max(point.x)];
1781                band_hull[1] = [band_hull[1][0].min(point.y), band_hull[1][1].max(point.y)];
1782            }
1783            boundary_segments.extend(points.windows(2).map(|pair| (pair[0], pair[1])));
1784            add_chain(
1785                points.clone(),
1786                ChainSource::Boundary {
1787                    coedge: coedge.clone(),
1788                    curve: curve.clone(),
1789                },
1790                format!("b:{operand}:{start_vertex}"),
1791                vertex_point(solid, start_vertex)?,
1792                format!("b:{operand}:{end_vertex}"),
1793                vertex_point(solid, end_vertex)?,
1794                true,
1795            )?;
1796            if let Some(shift) = image_shift {
1797                let shifted: Vec<Vec2> = points
1798                    .iter()
1799                    .map(|point| Vec2 {
1800                        x: point.x + shift,
1801                        y: point.y,
1802                    })
1803                    .collect();
1804                boundary_segments
1805                    .extend(shifted.windows(2).map(|pair| (pair[0], pair[1])));
1806                add_chain(
1807                    shifted,
1808                    ChainSource::Boundary {
1809                        coedge: coedge.clone(),
1810                        curve,
1811                    },
1812                    format!("b:{operand}:{start_vertex}"),
1813                    vertex_point(solid, start_vertex)?,
1814                    format!("b:{operand}:{end_vertex}"),
1815                    vertex_point(solid, end_vertex)?,
1816                    true,
1817                )?;
1818            }
1819        }
1820    }
1821    // CUT-CHAIN CLAMP BOUND: on a CLOSED direction the face's boundary band may
1822    // legitimately extend past the surface domain — a seam-straddling face is
1823    // arranged in UNWRAPPED coordinates (helmet Face_15's boundary chains run
1824    // u∈[-0.178, 0.295] on a [0,1]-domain surface). Clamping a cut pcurve to
1825    // the surface domain there tears it off the band: the branch-preserved
1826    // truncation bridge collapsed to a count=1 sliver hugging u=0 and the face
1827    // never split. Widen the clamp bound to domain ∪ trim-pcurve control hulls
1828    // (the hulls bound the boundary chains); a cut already inside the domain is
1829    // untouched, and OPEN directions keep the plain domain clamp. Escape hatch
1830    // BREP_FRAG_ENV_CLAMP=0.
1831    let (clamp_u, clamp_v) = {
1832        let mut clamp_u = u_domain;
1833        let mut clamp_v = v_domain;
1834        let (closed_u, closed_v) = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
1835        // NOTE (2026-09-16): this hatch's ONLY tamper guard,
1836        // `csg/fragment/tests.rs::seam_band_cut_chain_splits_periodic_face`, went
1837        // INERT when the march-window lift landed — that test now passes with this
1838        // hatch off, so nothing tamper-verifies this mechanism any more. Not that it
1839        // is untested: no other test NAMES this hatch.
1840        if (closed_u || closed_v) && std::env::var("BREP_FRAG_ENV_CLAMP").as_deref() != Ok("0") {
1841            for loop_record in &face.loops {
1842                for coedge in &loop_record.coedges {
1843                    for point in &coedge.pcurve.control_points {
1844                        if point.w.abs() <= 1e-300 {
1845                            continue;
1846                        }
1847                        if closed_u {
1848                            clamp_u[0] = clamp_u[0].min(point.x / point.w);
1849                            clamp_u[1] = clamp_u[1].max(point.x / point.w);
1850                        }
1851                        if closed_v {
1852                            clamp_v[0] = clamp_v[0].min(point.y / point.w);
1853                            clamp_v[1] = clamp_v[1].max(point.y / point.w);
1854                        }
1855                    }
1856                }
1857            }
1858        }
1859        (clamp_u, clamp_v)
1860    };
1861    profile.boundary += profile.lap(lap_start);
1862    for piece_id in active_pieces {
1863        let piece = pieces_by_id[&piece_id];
1864        let pcurve = pcurve_for(piece, face_key)?.clone();
1865        // SAG-BOUNDED CUT-CHAIN FIDELITY (t70 split-set asynchrony class).
1866        // `sample_chain`'s uniform sampling is knot-driven, so the SAME
1867        // imprint piece gets a 16-segment polyline on one support face and a
1868        // 92-segment one on the other (the counts follow each face's pcurve
1869        // knot structure, not the curvature). A coarse chord can then sag
1870        // MILLIMETRE-scale away from the true pcurve and invade a trim
1871        // region the true curve clears — t70: piece 55's chord on face
1872        // 1:405 sagged ~3e-3 into a hole corner the true pcurve misses by
1873        // 1.3e-3, so the arrangement carved phantom micro-junctions on that
1874        // face only, the two owners' split sets diverged (whole Imprint
1875        // edge vs a 4-piece Derived chain of the same locus), and every op
1876        // failed with one-use edges. Refining every cut chain until its
1877        // chords hug the true pcurve within the arrangement's own tolerance
1878        // makes both owners' polylines faithful to the ONE shared curve, so
1879        // their junction sets agree structurally (no proximity decisions
1880        // anywhere). Escape hatch: BREP_CHAIN_SAG_REFINE=0.
1881        let (mut points, original_flags) = sag_refine_chain(
1882            &pcurve,
1883            sample_chain(&pcurve)?,
1884            sampling_bound,
1885        )?;
1886        for point in &mut points {
1887            if point.x < clamp_u[0] {
1888                point.x = clamp_u[0] + arrangement_tolerance * 10.0;
1889            } else if point.x > clamp_u[1] {
1890                point.x = clamp_u[1] - arrangement_tolerance * 10.0;
1891            }
1892            if point.y < clamp_v[0] {
1893                point.y = clamp_v[0] + arrangement_tolerance * 10.0;
1894            } else if point.y > clamp_v[1] {
1895                point.y = clamp_v[1] - arrangement_tolerance * 10.0;
1896            }
1897        }
1898        let snap_endpoint_to_domain = |point: Vec2| {
1899            let candidates = [
1900                (
1901                    (point.x - u_domain[0]).abs(),
1902                    Vec2 {
1903                        x: u_domain[0],
1904                        y: point.y,
1905                    },
1906                ),
1907                (
1908                    (point.x - u_domain[1]).abs(),
1909                    Vec2 {
1910                        x: u_domain[1],
1911                        y: point.y,
1912                    },
1913                ),
1914                (
1915                    (point.y - v_domain[0]).abs(),
1916                    Vec2 {
1917                        x: point.x,
1918                        y: v_domain[0],
1919                    },
1920                ),
1921                (
1922                    (point.y - v_domain[1]).abs(),
1923                    Vec2 {
1924                        x: point.x,
1925                        y: v_domain[1],
1926                    },
1927                ),
1928            ];
1929            let nearest = candidates
1930                .into_iter()
1931                .min_by(|first, second| first.0.total_cmp(&second.0))
1932                .unwrap();
1933            if nearest.0 <= arrangement_tolerance * 50.0 {
1934                nearest.1
1935            } else {
1936                point
1937            }
1938        };
1939        let last = points.len() - 1;
1940        // A rim bridge's ends keep their own place (see RIM BRIDGE above): the
1941        // end inside the face is a distinct vertex a chart hair from the edge.
1942        // A cut's end at a vertex INSIDE the face a few 1e-5 of the period
1943        // from the seam (another body's seam vertex on a section that runs
1944        // along this face's seam) is inside the snap band, and snapping it
1945        // onto the domain edge moved that vertex to the seam: the section's
1946        // short piece then closed into a whole ring and the face never split.
1947        // With `BREP_NEAR_SEAM_CLOSED_RUN` an end snaps across a closed
1948        // direction (onto the seam) only when the edge's image is at least as
1949        // near the piece's own vertex as its place is. The end's own vertex is
1950        // the piece's vertex nearest its image (the piece's vertex order need
1951        // not follow its pcurve). A snap onto an OPEN domain edge is a rim, not
1952        // a seam, and always snaps: an offset's intersection vertex a few 1e-6
1953        // inside a quarter cylinder's rim is that rim's vertex, and keeping it
1954        // in place stranded the section's piece one-use beside the rim.
1955        let closed_axes = face.surface.closed_directions().unwrap_or((false, false));
1956        let keeps_vertex = |snapped: Vec2, original: Vec2, _vertex_id: u64| -> bool {
1957            let onto_seam = (closed_axes.0 && snapped.x != original.x) || (closed_axes.1 && snapped.y != original.y);
1958            if !crate::switch!("BREP_NEAR_SEAM_CLOSED_RUN", true) || !onto_seam {
1959                return true;
1960            }
1961            let (Ok(at), Ok(moved)) = (face.surface.evaluate(original.x, original.y), face.surface.evaluate(snapped.x, snapped.y)) else {
1962                return true;
1963            };
1964            let own = [piece.start_vertex_id, piece.end_vertex_id]
1965                .iter()
1966                .filter_map(|id| index.vertex_points.get(id))
1967                .min_by(|a, b| a.sub(at).length().total_cmp(&b.sub(at).length()));
1968            let keep = own.is_none_or(|vertex| moved.sub(*vertex).length() <= at.sub(*vertex).length());
1969            keep
1970        };
1971        // `BREP_FRAGMENT_EXACT_END_STAYS` (default on, `=0` restores): on a plane, a straight
1972        // cut's end is an exact vertex, not a marched end's slack. One that its
1973        // own vertex places a resolvable distance off the domain edge (more
1974        // than eight identity bands in model space) stays where it is: a box
1975        // turned a few 1e-6 rad has a corner edge piercing the other's face
1976        // 4e-6 inside its edge, and snapping that end onto the edge put the
1977        // vertex where the solid has none while its mates kept the true one.
1978        // A face read as one surface with a face of the other operand keeps the
1979        // snap: its pair's slivers are below resolution and its vertices are
1980        // read at the pair's band, not placed exactly.
1981        let straight_on_plane = exact_end_stays_on()
1982            && !index.cosurface_pairs.iter().any(|(first, _)| *first == face_key)
1983            && face.surface.is_affine().unwrap_or(false)
1984            && piece.curve.degree == 1
1985            && piece.curve.control_points.len() == 2;
1986        let exact_end_off_edge = |snapped: Vec2, original: Vec2, vertex_id: u64| -> bool {
1987            if !straight_on_plane || (snapped.x == original.x && snapped.y == original.y) {
1988                return false;
1989            }
1990            let (Some(vertex), Ok(moved)) = (index.vertex_points.get(&vertex_id), face.surface.evaluate(snapped.x, snapped.y)) else {
1991                return false;
1992            };
1993            let identity = crate::classification::surface_uv_band(&face.surface, original.x, original.y, 1e-7);
1994            let off = original.sub(snapped).length();
1995            off > identity * 8.0 && moved.sub(*vertex).length() > 8e-7
1996        };
1997        if !bridge_keys.contains(&format!("i:{}", piece.start_vertex_id)) {
1998            let snapped = snap_endpoint_to_domain(points[0]);
1999            if keeps_vertex(snapped, points[0], piece.start_vertex_id)
2000                && !exact_end_off_edge(snapped, points[0], piece.start_vertex_id)
2001            {
2002                points[0] = snapped;
2003            }
2004        }
2005        if !bridge_keys.contains(&format!("i:{}", piece.end_vertex_id)) {
2006            let snapped = snap_endpoint_to_domain(points[last]);
2007            if keeps_vertex(snapped, points[last], piece.end_vertex_id)
2008                && !exact_end_off_edge(snapped, points[last], piece.end_vertex_id)
2009            {
2010                points[last] = snapped;
2011            }
2012        }
2013        for point in &mut points {
2014            *point = rebase_point(*point);
2015        }
2016        // CUT-CHAIN PERIOD LIFT. A section's pcurve on a closed carrier is
2017        // drawn on the carrier's own period, but the boundary chains above can
2018        // sit a period away from it: an imported face whose seam edge is not
2019        // at the carrier's parameter origin carries rims split AT that origin,
2020        // so its loop hops the branch cut between coedges and the seam-hop
2021        // unwrap lays it out over [seam, seam + period] (the 2026-09-14 gear:
2022        // cone and fillet torus with seam edges at u = 1/2, boundary chains on
2023        // u ∈ [0.5, 1.5], section arcs on [0, 0.5] and [0.5, 1]). The arc a
2024        // period off never meets the band, the section never closes across the
2025        // face, the face stays one fragment and is kept or dropped whole — one
2026        // rim and the section ring then strand one-use. Every piece the imprint
2027        // attaches to a face has its midpoint inside that face's trim, so the
2028        // chain's image whose middle lies inside the band is the one the
2029        // arrangement must see; a whole-period shift is exact on a periodic
2030        // carrier. The chain is lifted only when its middle is OUTSIDE the band
2031        // and exactly one period image puts it inside, so a chain already
2032        // coherent with its band — every native face, every re-based band —
2033        // is untouched. The pcurve keeps the carrier's own period (the lift is
2034        // an arrangement coordinate, recorded on the chain for the partial-run
2035        // rescue). A lifted chain that still crosses a wall of the band crosses
2036        // the face's seam edge unsplit, and the face refuses by name. Escape
2037        // hatch `BREP_CUT_PERIOD_LIFT=0`.
2038        let mut lift = Vec2 { x: 0.0, y: 0.0 };
2039        if std::env::var("BREP_CUT_PERIOD_LIFT").as_deref() != Ok("0") {
2040            let closed = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
2041            for axis in 0..2 {
2042                let (is_closed, domain) = if axis == 0 { (closed.0, u_domain) } else { (closed.1, v_domain) };
2043                let [low, high] = band_hull[axis];
2044                let span = domain[1] - domain[0];
2045                if !is_closed || !(span > 0.0) || !(low < domain[0] || high > domain[1]) {
2046                    continue;
2047                }
2048                let coordinate = |point: &Vec2| if axis == 0 { point.x } else { point.y };
2049                let middle = coordinate(&points[points.len() / 2]);
2050                let inside = |value: f64| value > low && value < high;
2051                if inside(middle) {
2052                    continue;
2053                }
2054                let images: Vec<f64> = [-2.0, -1.0, 1.0, 2.0]
2055                    .into_iter()
2056                    .map(|periods| periods * span)
2057                    .filter(|shift| inside(middle + shift))
2058                    .collect();
2059                let [shift] = images[..] else {
2060                    continue;
2061                };
2062                let slack = arrangement_tolerance * 50.0;
2063                let (reach_low, reach_high) = points.iter().map(coordinate).fold(
2064                    (f64::INFINITY, f64::NEG_INFINITY),
2065                    |(lo, hi), value| (lo.min(value), hi.max(value)),
2066                );
2067                if reach_low + shift < low - slack || reach_high + shift > high + slack {
2068                    let [first, second] = piece.support_faces;
2069                    return Err(KernelRefusal::internal(
2070                        KernelStage::Fragment,
2071                        "fragment.face_split",
2072                        format!(
2073                            "fragment_face: section piece {piece_id} of faces {}:{} x {}:{} crosses \
2074                             the seam wall of face {}:{}'s unwrapped band ({} in [{low:.9}, {high:.9}], \
2075                             the section's period image [{:.9}, {:.9}]) without a vertex there",
2076                            first.operand,
2077                            first.face_id,
2078                            second.operand,
2079                            second.face_id,
2080                            operand,
2081                            face.id,
2082                            if axis == 0 { "u" } else { "v" },
2083                            reach_low + shift,
2084                            reach_high + shift,
2085                        ),
2086                    ));
2087                }
2088                for point in &mut points {
2089                    if axis == 0 {
2090                        point.x += shift;
2091                    } else {
2092                        point.y += shift;
2093                    }
2094                }
2095                if axis == 0 {
2096                    lift.x = shift;
2097                } else {
2098                    lift.y = shift;
2099                }
2100                if env_read!("BREP_DEBUG_FRAG")
2101                    .map(|value| value == face.id.to_string())
2102                    .unwrap_or(false)
2103                {
2104                    eprintln!(
2105                        "  period lift: face {} cut p{piece_id} {} {shift:+} into the band [{low:.6},{high:.6}]",
2106                        face.id,
2107                        if axis == 0 { "u" } else { "v" }
2108                    );
2109                }
2110            }
2111        }
2112        // Guard runs on the FINAL (clamped/snapped/rebased) coordinates — the
2113        // same frame the boundary chains were sampled into — so crossing
2114        // parity is measured exactly where the arrangement would see it.
2115        points = enforce_boundary_crossing_parity(
2116            points,
2117            &original_flags,
2118            &boundary_segments,
2119            arrangement_tolerance,
2120            env_read!("BREP_DEBUG_FRAG")
2121                .map(|value| value == face.id.to_string())
2122                .unwrap_or(false),
2123            face.id,
2124        );
2125        let start_point = index
2126            .vertex_points
2127            .get(&piece.start_vertex_id)
2128            .copied()
2129            .ok_or_else(|| KernelRefusal::internal(KernelStage::Fragment, "fragment.face_split", "fragment_face: missing imprint start vertex"))?;
2130        let end_point = index
2131            .vertex_points
2132            .get(&piece.end_vertex_id)
2133            .copied()
2134            .ok_or_else(|| KernelRefusal::internal(KernelStage::Fragment, "fragment.face_split", "fragment_face: missing imprint end vertex"))?;
2135        add_chain(
2136            points,
2137            ChainSource::Cut {
2138                piece_id,
2139                pcurve,
2140                lift,
2141                curve: trimmed_curve(&piece.curve, piece.t0, piece.t1)?,
2142                shared_ring: piece.shared_edge.filter(|_| {
2143                    piece
2144                        .curve
2145                        .evaluate(piece.t0)
2146                        .ok()
2147                        .zip(piece.curve.evaluate(piece.t1).ok())
2148                        .is_some_and(|(a, b)| a.sub(b).length() <= 1e-6)
2149                }),
2150            },
2151            format!("i:{}", piece.start_vertex_id),
2152            start_point,
2153            format!("i:{}", piece.end_vertex_id),
2154            end_point,
2155            false,
2156        )?;
2157    }
2158    drop(add_chain);
2159
2160    // POLE-GAP BRIDGE (single-loop periodic cap; corpus fixture 25 cube-pierce).
2161    // A face closed in one parameter direction can carry a DEGENERATE pole
2162    // iso-line — a whole domain-edge row of one parameter collapsing to a
2163    // single 3D point (the dome apex v2 at v=0 here). The imported trim
2164    // represents the pole with a partial arc plus a degenerate self-edge that
2165    // stop SHORT of the opposite seam foot, so the outer boundary is OPEN in
2166    // the flat UV chart at the pole: the two seam feet sit a FRACTION of a
2167    // period apart (never a whole period), so no covering-strip period-image
2168    // can ever join them — this case is structurally outside the seam-image
2169    // loops machinery above. When a section cut then splits the cap,
2170    // `arrange_segments` closes only the lens region that avoids the pole and
2171    // DROPS the seam-and-pole-spanning outside region: the cap fragments to 1
2172    // not 2, its section + outer-rim edges strand one-use (union/subtract fail
2173    // `S=1 genus=1`), while intersect keeps the lens and succeeds. Close the
2174    // boundary in-chart: pair the two dangling (odd-incidence) boundary
2175    // endpoints that are UV images of the SAME solid vertex (structural
2176    // identity via `vertex_images`, never proximity clustering), VERIFY the
2177    // straight UV connector between them is degenerate (every sample collapses
2178    // to one 3D point — a genuine pole, not a real seam that would cross
2179    // material), and add a bridge chain that REUSES an existing degenerate
2180    // pole edge as its source. The reused edge is 3D-zero-length, so the
2181    // minted coedge is s==e and exempt from the two-use rule — no new edge is
2182    // introduced (the zero-regression reuse pattern), and the outside fragment
2183    // reproduces the original cap loop's own pole/seam structure. A
2184    // cleanly-closing boundary has no odd node and is byte-identical untouched;
2185    // a genuine (non-degenerate) seam gap fails the degeneracy check and is
2186    // left alone (the safe direction). Escape hatch: BREP_POLE_GAP_BRIDGE=0.
2187    let pole_gap_closed = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
2188    if (pole_gap_closed.0 || pole_gap_closed.1)
2189        && std::env::var("BREP_POLE_GAP_BRIDGE").as_deref() != Ok("0")
2190    {
2191        // A degenerate pole iso-line only exists on a surface closed in the
2192        // seam direction; a non-periodic face never reaches this block and is
2193        // byte-identical untouched.
2194        //
2195        // `add_chain` canonicalizes shared endpoints to a bit-identical `Vec2`,
2196        // so a TIGHT epsilon groups exactly the coincident nodes and never
2197        // over-merges two distinct nearby vertices (which would corrupt the
2198        // incidence parity on a small face).
2199        let node_tol = arrangement_tolerance * 10.0;
2200        // Incidence over BOUNDARY chain endpoints only — the pole gap is a
2201        // property of the trim boundary, and cut chains anchor to it elsewhere.
2202        let mut nodes: Vec<(Vec2, usize)> = Vec::new();
2203        for chain in &chains {
2204            if !matches!(chain.source, ChainSource::Boundary { .. }) {
2205                continue;
2206            }
2207            for point in [chain.start, chain.end] {
2208                if let Some(entry) = nodes.iter_mut().find(|(q, _)| q.sub(point).length() <= node_tol)
2209                {
2210                    entry.1 += 1;
2211                } else {
2212                    nodes.push((point, 1));
2213                }
2214            }
2215        }
2216        // Odd incidence => the boundary is UV-open at that endpoint.
2217        let odd: Vec<Vec2> = nodes
2218            .iter()
2219            .filter(|(_, count)| count % 2 == 1)
2220            .map(|(point, _)| *point)
2221            .collect();
2222        // Each odd node's owning solid vertex: the canonical image lists in
2223        // `vertex_images` are keyed "b:{operand}:{vertex_id}".
2224        let vertex_of = |point: Vec2| -> Option<u64> {
2225            vertex_images.iter().find_map(|(key, images)| {
2226                images
2227                    .iter()
2228                    .any(|image| image.sub(point).length() <= node_tol)
2229                    .then(|| key.rsplit(':').next().and_then(|id| id.parse::<u64>().ok()))
2230                    .flatten()
2231            })
2232        };
2233        let mut by_vertex: HashMap<u64, Vec<Vec2>> = HashMap::default();
2234        for point in &odd {
2235            if let Some(vertex_id) = vertex_of(*point) {
2236                by_vertex.entry(vertex_id).or_default().push(*point);
2237            }
2238        }
2239        // Forward-evaluate only (the projector is a poisoned oracle; evaluate
2240        // is exact). A degenerate 3D curve collapses to a point over its span.
2241        let curve_degenerate = |curve: &NurbsCurve| -> bool {
2242            let Ok(domain) = curve.domain() else {
2243                return false;
2244            };
2245            let Ok(base) = curve.evaluate(domain[0]) else {
2246                return false;
2247            };
2248            [0.5, 1.0].iter().all(|fraction| {
2249                curve
2250                    .evaluate(domain[0] + (domain[1] - domain[0]) * fraction)
2251                    .map(|point| point.sub(base).length() <= 1e-5)
2252                    .unwrap_or(false)
2253            })
2254        };
2255        for (vertex_id, images) in by_vertex {
2256            // A pole slit unclosed in exactly one place has EXACTLY two dangling
2257            // images of its apex vertex; anything else is not this class.
2258            if images.len() != 2 {
2259                continue;
2260            }
2261            let (a, b) = (images[0], images[1]);
2262            // The straight UV connector must be a degenerate iso-line: every
2263            // sample collapses to one 3D point. This is the gate that keeps a
2264            // real seam (whose connector crosses material) from being bridged.
2265            let mut base: Option<Vec3> = None;
2266            let mut degenerate = true;
2267            for step in 0..=8 {
2268                let fraction = step as f64 / 8.0;
2269                let uv = a.add(b.sub(a).scale(fraction));
2270                match face.surface.evaluate(uv.x, uv.y) {
2271                    Ok(point) => match base {
2272                        None => base = Some(point),
2273                        Some(reference) => {
2274                            if point.sub(reference).length() > 1e-5 {
2275                                degenerate = false;
2276                                break;
2277                            }
2278                        }
2279                    },
2280                    Err(_) => {
2281                        degenerate = false;
2282                        break;
2283                    }
2284                }
2285            }
2286            if !degenerate {
2287                continue;
2288            }
2289            // Reuse an existing degenerate pole edge's source (its 3D curve is a
2290            // point, so the minted coedge is s==e and validation-exempt).
2291            let Some(source) = chains.iter().find_map(|chain| match &chain.source {
2292                ChainSource::Boundary { coedge, curve }
2293                    if chain.start.sub(chain.end).length() <= node_tol
2294                        && chain.count <= 1
2295                        && (chain.start.sub(a).length() <= node_tol
2296                            || chain.start.sub(b).length() <= node_tol)
2297                        && curve_degenerate(curve) =>
2298                {
2299                    Some(ChainSource::Boundary {
2300                        coedge: coedge.clone(),
2301                        curve: curve.clone(),
2302                    })
2303                }
2304                _ => None,
2305            }) else {
2306                continue;
2307            };
2308            let chain_index = chains.len();
2309            segments.push(Segment2 {
2310                a,
2311                b,
2312                tag: segment_tag(chain_index, 0),
2313            });
2314            chains.push(Chain {
2315                source,
2316                count: 1,
2317                start: a,
2318                end: b,
2319                segments: vec![(a, b)],
2320            });
2321            boundary_segments.push((a, b));
2322            if env_read!("BREP_DEBUG_FRAG")
2323                .map(|value| value == face.id.to_string())
2324                .unwrap_or(false)
2325            {
2326                eprintln!(
2327                    "  pole-gap bridge: face {} vertex {vertex_id} joins \
2328                     ({:.6},{:.6})->({:.6},{:.6}) along a degenerate iso-line",
2329                    face.id, a.x, a.y, b.x, b.y
2330                );
2331            }
2332        }
2333    }
2334
2335    // A cut chain that coincides with a boundary chain cannot split the
2336    // interior — the face's own edge already bounds it there. Worse, the
2337    // duplicate overlapping segments corrupt arrangement cycle extraction
2338    // and silently swallow every region that touches the overlap (seen when
2339    // endpoint polishing snaps a face/face intersection line onto a
2340    // near-coincident boundary edge of the same face). Drop such cuts
2341    // before arranging.
2342    let coincidence_tolerance = arrangement_tolerance * 50.0;
2343    let point_segment_distance = |point: Vec2, a: Vec2, b: Vec2| -> f64 {
2344        let segment = b.sub(a);
2345        let length_squared = segment.dot(segment);
2346        if length_squared <= 1e-30 {
2347            return point.sub(a).length();
2348        }
2349        let parameter = (point.sub(a).dot(segment) / length_squared).clamp(0.0, 1.0);
2350        point.sub(a.add(segment.scale(parameter))).length()
2351    };
2352    let near_chain = |point: Vec2, chain: &Chain, tolerance: f64| {
2353        chain
2354            .segments
2355            .iter()
2356            .any(|(a, b)| point_segment_distance(point, *a, *b) <= tolerance)
2357    };
2358    // A cut coincides with a boundary only if its INTERIOR follows the same
2359    // path, not merely its endpoints. A single-segment straight cut whose two
2360    // endpoints happen to land on a CURVED boundary edge's endpoints (a
2361    // cap∩cap intersection chord spanning a curved rim arc — the missing
2362    // cone-cap split behind the curved-primitive open-edge booleans) shares
2363    // only its endpoints and cuts clean across the interior; dropping it as a
2364    // duplicate loses the region it carves. So also require the segment
2365    // MIDPOINTS to lie near the boundary. The midpoint test runs at a looser
2366    // threshold than the endpoint match: a genuinely-coincident curved cut's
2367    // polyline midpoints carry their own chord sag (order 1× tolerance), which
2368    // must still count as near, while a chord spanning a curved arc departs by
2369    // the arc's sagitta (orders of magnitude larger) and is correctly kept. On
2370    // the box path both edges are straight, so two shared endpoints force the
2371    // midpoint onto the boundary and the drop is unchanged.
2372    let midpoint_tolerance = coincidence_tolerance * 8.0;
2373    // CORNER-CHORD VETO. The endpoint match above admits a cut whose endpoint
2374    // sits up to `coincidence_tolerance` (50x arr_tol) from the boundary
2375    // chain's endpoint. When a section threads through a MODEL CORNER where two
2376    // boundary edges (legs) meet at a shared vertex, the section arm on the
2377    // sliver face between them is the HYPOTENUSE of a tiny right triangle whose
2378    // short leg can be well under that slack (t634: the torus crosses a 3-face
2379    // corner of 00000327; on the sliver face the arm's start is 31x arr_tol
2380    // from the matched leg's start, and the hypotenuse midpoint is ~15x arr_tol
2381    // off the leg — both under the 50x/400x tolerances). The old test dropped
2382    // that arm as a "duplicate" of one leg, so the tiny corner region was never
2383    // carved on the sliver face while the mate operand kept the arm -> the
2384    // shared section edge went one-use (invalid genus). A genuine corner chord
2385    // is distinguishable STRUCTURALLY, not by tolerance: its endpoint coincides
2386    // (at NODE scale = the arrangement's own find_node snap) with a real,
2387    // DISTINCT boundary vertex — proof it terminates at a 0-cell of its own,
2388    // spanning two legs, rather than retracing this one edge. A true retrace
2389    // (box duplicate, cap-rim chord) has endpoints AT the matched chain's ends
2390    // (gap ~0), so the veto never triggers for it. Hatch restores the old drop.
2391    profile.cuts += profile.lap(lap_start);
2392    let corner_veto_enabled = std::env::var("BREP_DUP_DROP_CORNER_VETO")
2393        .map(|value| value != "0")
2394        .unwrap_or(true);
2395    let node_tolerance = arrangement_tolerance;
2396    let terminates_at_distinct_boundary_vertex = |cut_end: Vec2, matched_end: Vec2| -> bool {
2397        cut_end.sub(matched_end).length() > node_tolerance
2398            && chains.iter().any(|other| {
2399                matches!(other.source, ChainSource::Boundary { .. })
2400                    && (other.start.sub(cut_end).length() <= node_tolerance
2401                        || other.end.sub(cut_end).length() <= node_tolerance)
2402            })
2403    };
2404    let debug_drop = env_read!("BREP_DEBUG_FRAG")
2405        .map(|value| value == face.id.to_string())
2406        .unwrap_or(false);
2407    // MICRO-BOUNDARY SKIP (t316). A boundary chain SHORTER than the coincidence
2408    // tolerance cannot serve as a duplication reference: its two endpoints are
2409    // indistinguishable at this tolerance, so the orientation-agnostic endpoint
2410    // match collapses and a cut that merely touches ONE of its ends spuriously
2411    // "matches" BOTH. That wrongly drops a junction-bridge micro-cut spanning a
2412    // weld-scale vertex cluster (t316: cut p38, the ~0.004mm bridge from a
2413    // section terminus C to the plate-rim node C', gets dropped against e99 — a
2414    // ~0.008mm rim segment shorter than the 0.07mm coincidence tolerance —
2415    // stranding the whole b-poke bottom-cap sliver one-use). The genuine target
2416    // (the tangent-wall cap section, coincident with a full-length box edge ≫
2417    // tolerance) is untouched. Independent of the corner-chord veto below: this
2418    // guard disqualifies a sub-tolerance BOUNDARY as a reference, that one spares
2419    // a corner-spanning CUT. Hatch `BREP_DUP_CUT_MICRO_BOUNDARY=0` restores the
2420    // old, length-agnostic reference test.
2421    let micro_boundary_skip = std::env::var("BREP_DUP_CUT_MICRO_BOUNDARY").as_deref() != Ok("0");
2422    let boundary_extent = |boundary: &Chain| -> f64 {
2423        boundary
2424            .segments
2425            .iter()
2426            .map(|(a, b)| b.sub(*a).length())
2427            .sum()
2428    };
2429    // POLE-COLLAPSED ENDS. A pole is a whole row of the chart at one 3D
2430    // point, so two chain ends on its degenerate boundary chain are one point
2431    // however far apart their u reads, and near the pole a chart distance says
2432    // nothing about the 3D one. The revolve_pole union's G2 end cap (a 93 deg
2433    // sector with its apex on the axis) is cut by the wedge's two side planes
2434    // along its own radius edges: the sections are those edges' sub-arcs to
2435    // 1e-15, ending 3.2e-6 short of the apex. Their pcurves follow u = 1 and
2436    // u = 0 and then swing to one u = 0.443 at the pole; evaluated on the cap
2437    // a chain stands 7.4e-4 off its radius at v = 0.99976. The endpoint test
2438    // read a gap of 0.557 and kept both cuts, and the arrangement carved two
2439    // slivers, each bounded by a radius edge and its own weld copy. One was
2440    // kept in the union and the coplanar merge refused its genus; the
2441    // intersection refused with one-use edges. So when a chain end and a
2442    // boundary end both lie on one degenerate boundary chain they coincide,
2443    // and the cut is held to the boundary in 3D, section curve against edge
2444    // curve, within the coincidence tolerance carried along the boundary by
2445    // its own stretch (3D length over chart length). Escape hatch
2446    // `BREP_DUP_DROP_POLE=0`.
2447    let pole_ends = std::env::var("BREP_DUP_DROP_POLE").as_deref() != Ok("0");
2448    let degenerate_chains: Vec<usize> = chains
2449        .iter()
2450        .enumerate()
2451        .filter(|(_, chain)| match &chain.source {
2452            ChainSource::Boundary { coedge, .. } => solid
2453                .edges
2454                .iter()
2455                .any(|edge| edge.id == coedge.edge_id && edge.degenerate),
2456            ChainSource::Cut { .. } => false,
2457        })
2458        .map(|(index, _)| index)
2459        .collect();
2460    let on_one_pole = |a: Vec2, b: Vec2| -> bool {
2461        degenerate_chains.iter().any(|&pole| {
2462            near_chain(a, &chains[pole], coincidence_tolerance)
2463                && near_chain(b, &chains[pole], coincidence_tolerance)
2464        })
2465    };
2466    let coincident_in_space = |cut: &Chain, boundary: &Chain, weld_scale: bool| -> bool {
2467        let ChainSource::Boundary { curve, coedge } = &boundary.source else {
2468            return false;
2469        };
2470        let ChainSource::Cut { curve: section, piece_id, .. } = &cut.source else {
2471            return false;
2472        };
2473        let Ok([start, end]) = section.domain() else {
2474            return false;
2475        };
2476        let mut chart_length = 0.0;
2477        let mut space_length = 0.0;
2478        for (a, b) in &boundary.segments {
2479            let (Ok(pa), Ok(pb)) = (face.surface.evaluate(a.x, a.y), face.surface.evaluate(b.x, b.y)) else {
2480                return false;
2481            };
2482            chart_length += b.sub(*a).length();
2483            space_length += pb.sub(pa).length();
2484        }
2485        if chart_length <= 0.0 || space_length <= 0.0 {
2486            return false;
2487        }
2488        let copy_boundary = index.pieces_by_id.get(piece_id).is_some_and(|piece| {
2489            boundary_has_cosurface_partner(solid, face_key, coedge.edge_id, piece, index)
2490                || (cosurface_corner_copy_on()
2491                    && boundary_is_cosurface_corner(solid, face_key, coedge.edge_id, piece, index))
2492        });
2493        let bound = if weld_scale {
2494            if copy_boundary { crate::tolerance::WELD_FLOOR } else { 1e-7 }
2495        } else {
2496            coincidence_tolerance * space_length / chart_length
2497        };
2498        let stations = cut.segments.len().max(16);
2499        (0..=stations).all(|index| {
2500            section
2501                .evaluate(start + (end - start) * index as f64 / stations as f64)
2502                .ok()
2503                .and_then(|at| crate::project_point_to_curve(curve, at).ok())
2504                .is_some_and(|projection| projection.distance <= bound)
2505        })
2506    };
2507    // [`coincident_in_space`] at the weld band, and the reverse: every station
2508    // of the boundary's curve lies within the same band of the cut's, so the
2509    // two are one curve, not a cut that merely stays near part of the boundary.
2510    // Only where the boundary has the other operand's coincident copy beside it
2511    // (the weld band's own condition).
2512    let follows_copy_both_ways = |cut: &Chain, boundary: &Chain| -> bool {
2513        let (ChainSource::Boundary { curve, coedge }, ChainSource::Cut { curve: section, piece_id, .. }) = (&boundary.source, &cut.source) else {
2514            return false;
2515        };
2516        let copy = index.pieces_by_id.get(piece_id).is_some_and(|piece| {
2517            boundary_has_cosurface_partner(solid, face_key, coedge.edge_id, piece, index)
2518        });
2519        if !copy || !coincident_in_space(cut, boundary, true) {
2520            return false;
2521        }
2522        let Ok([start, end]) = curve.domain() else {
2523            return false;
2524        };
2525        let stations = boundary.segments.len().max(16);
2526        let mut distances = Vec::with_capacity(stations + 1);
2527        for station in 0..=stations {
2528            let Some(distance) = curve
2529                .evaluate(start + (end - start) * station as f64 / stations as f64)
2530                .ok()
2531                .and_then(|at| crate::project_point_to_curve(section, at).ok())
2532                .map(|projection| projection.distance)
2533            else {
2534                return false;
2535            };
2536            if distance > crate::tolerance::WELD_FLOOR {
2537                return false;
2538            }
2539            distances.push(distance);
2540        }
2541        // A copy offset to one side all along (two coaxial rims a weld floor
2542        // apart) bounds a real strip, however thin: it is a cut. The rim again
2543        // turned or moved by round-off crosses it, coming to it inside: there
2544        // the nearest station reads well under the farthest.
2545        let interior = &distances[stations / 20 + 1..stations - stations / 20];
2546        let (nearest, farthest) = interior
2547            .iter()
2548            .fold((f64::INFINITY, 0.0f64), |(low, high), &distance| (low.min(distance), high.max(distance)));
2549        farthest <= 1e-7 || nearest <= 0.1 * farthest
2550    };
2551    let mut dropped_chains = HashSet::default();
2552    for (index, chain) in chains.iter().enumerate() {
2553        if !matches!(chain.source, ChainSource::Cut { .. }) {
2554            continue;
2555        }
2556        let mut matched_boundary: Option<usize> = None;
2557        for (boundary_index, boundary) in chains.iter().enumerate() {
2558            if !matches!(boundary.source, ChainSource::Boundary { .. }) {
2559                continue;
2560            }
2561            // t316: a sub-tolerance micro-boundary cannot be a duplication
2562            // reference — its endpoints collapse at this tolerance, so a cut that
2563            // merely touches one end spuriously matches both. Skip it as a
2564            // candidate (never selectable as `matched_boundary`).
2565            if micro_boundary_skip && boundary_extent(boundary) <= coincidence_tolerance {
2566                continue;
2567            }
2568            let forward = boundary.start.sub(chain.start).length() <= coincidence_tolerance
2569                && boundary.end.sub(chain.end).length() <= coincidence_tolerance;
2570            let reversed = boundary.start.sub(chain.end).length() <= coincidence_tolerance
2571                && boundary.end.sub(chain.start).length() <= coincidence_tolerance;
2572            let same_end = |a: Vec2, b: Vec2| a.sub(b).length() <= coincidence_tolerance || on_one_pole(a, b);
2573            let (forward, reversed, at_pole) = if forward || reversed || !pole_ends || degenerate_chains.is_empty() {
2574                (forward, reversed, false)
2575            } else {
2576                let forward = same_end(boundary.start, chain.start) && same_end(boundary.end, chain.end);
2577                let reversed = same_end(boundary.start, chain.end) && same_end(boundary.end, chain.start);
2578                (forward, reversed, true)
2579            };
2580            if !(forward || reversed) {
2581                continue;
2582            }
2583            let interior_coincident = if at_pole {
2584                coincident_in_space(chain, boundary, false)
2585            } else {
2586                chain.segments.iter().all(|(a, b)| {
2587                    near_chain(*a, boundary, coincidence_tolerance)
2588                        && near_chain(*b, boundary, coincidence_tolerance)
2589                        && near_chain(a.add(*b).scale(0.5), boundary, midpoint_tolerance)
2590                })
2591            };
2592            // DUPLICATE CUT BY SPACE (`BREP_DUP_CUT_SPACE_NOMINATION`, default
2593            // on, `=0` restores): a cut whose ends match the boundary's and that follows it in
2594            // model space at every station ([`coincident_in_space`] at the weld
2595            // band, both ways: the boundary's stations lie on the cut too, and
2596            // only along a boundary with the other operand's coincident copy
2597            // beside it, and only a copy that comes to the boundary inside, not
2598            // one offset to one side all along) is nominated even where the
2599            // chart test above misses. That
2600            // test measures the cut's samples, on the true curve, against the
2601            // boundary's chords, whose sag can exceed its band, so it passed or
2602            // failed by where the cut happened to be sampled: spline-prisms
2603            // 5047's moved copy (b's rim 4.7e-6 off a's top rim, translated)
2604            // kept the rim as a cut and split the cap into slivers.
2605            let interior_coincident = interior_coincident
2606                || (dup_cut_space_nomination_enabled() && follows_copy_both_ways(chain, boundary));
2607            if !interior_coincident {
2608                continue;
2609            }
2610            // UV proximity only nominates a duplicate. A real cap lens can
2611            // be narrower than that chart-space search band while its two
2612            // arcs are distinct in 3D. Discard the cut only when the section
2613            // follows the boundary within model identity, not the repair band.
2614            // Endpoint anchoring can turn a very short cut and boundary into
2615            // the SAME chart segment even when their pre-anchor 3D curves
2616            // differ. Such identical constraints cannot enclose a region;
2617            // keeping both would corrupt arrangement cycle extraction.
2618            let identical_segment = chain.segments.len() == 1
2619                && boundary.segments.len() == 1
2620                && ((chain.start.sub(boundary.start).length() <= node_tolerance
2621                    && chain.end.sub(boundary.end).length() <= node_tolerance)
2622                    || (chain.start.sub(boundary.end).length() <= node_tolerance
2623                        && chain.end.sub(boundary.start).length() <= node_tolerance));
2624            if !identical_segment
2625                && std::env::var("BREP_DUP_CUT_GEOMETRY").as_deref() != Ok("0")
2626                && !coincident_in_space(chain, boundary, true)
2627            {
2628                continue;
2629            }
2630            if corner_veto_enabled {
2631                // Pair each cut endpoint with the boundary endpoint it matched.
2632                let (bnd_for_start, bnd_for_end) = if forward {
2633                    (boundary.start, boundary.end)
2634                } else {
2635                    (boundary.end, boundary.start)
2636                };
2637                if terminates_at_distinct_boundary_vertex(chain.start, bnd_for_start)
2638                    || terminates_at_distinct_boundary_vertex(chain.end, bnd_for_end)
2639                {
2640                    continue;
2641                }
2642            }
2643            matched_boundary = Some(boundary_index);
2644            break;
2645        }
2646        if let Some(boundary_index) = matched_boundary {
2647            if debug_drop {
2648                let boundary = &chains[boundary_index];
2649                eprintln!(
2650                    "  drop cut chain {} as duplicate of boundary chain {} (endpoint gaps {:.3e}/{:.3e})",
2651                    index,
2652                    boundary_index,
2653                    boundary.start.sub(chain.start).length(),
2654                    boundary.end.sub(chain.end).length(),
2655                );
2656            }
2657            dropped_chains.insert(index);
2658        }
2659    }
2660    if !dropped_chains.is_empty() {
2661        segments.retain(|segment| {
2662            tag_chain(&segment.tag)
2663                .map(|chain| !dropped_chains.contains(&(chain as usize)))
2664                .unwrap_or(true)
2665        });
2666    }
2667
2668    let debug = env_read!("BREP_DEBUG_FRAG")
2669        .map(|value| value == face.id.to_string())
2670        .unwrap_or(false);
2671    if debug {
2672        eprintln!(
2673            "fragment_face {}: domain u={:?} v={:?} arr_tol={:.3e} chains={} segments={}",
2674            face.id,
2675            u_domain,
2676            v_domain,
2677            arrangement_tolerance,
2678            chains.len(),
2679            segments.len()
2680        );
2681        for (index, chain) in chains.iter().enumerate() {
2682            let kind = match &chain.source {
2683                ChainSource::Boundary { coedge, .. } => format!("boundary e{}", coedge.edge_id),
2684                ChainSource::Cut { piece_id, .. } => format!("cut p{piece_id}"),
2685            };
2686            eprintln!(
2687                "  chain {index} {kind} count={} start=({:.9},{:.9}) end=({:.9},{:.9})",
2688                chain.count, chain.start.x, chain.start.y, chain.end.x, chain.end.y
2689            );
2690        }
2691    }
2692    // TRIPLE-POINT CUT-CHAIN BRIDGE (imported-geometry corner rescue).
2693    // Two SSI cut curves that meet at a triple point (two faces of one operand
2694    // both crossing a single face of the other) can be marched to endpoints that
2695    // DISAGREE by more than arr_tol when the operand's shared edge carries an
2696    // imported edge<->vertex gap — the imprint then mints TWO vertices for the
2697    // one corner, so the cut chain is BROKEN there. A broken cut cannot separate
2698    // the domain: the arrangement returns one region covering the whole face, the
2699    // face is classified by a single test point and wrongly dropped, and its
2700    // neighbours' shared SSI edges are stranded one-use (non-integral genus).
2701    // Reconnect a pair of cut-chain endpoints that BOTH dangle in the interior
2702    // (each neither on a domain boundary nor meeting any other chain endpoint)
2703    // and whose chains are EACH anchored at their other end, by snapping them to
2704    // their midpoint. Gated on the dangling-anchored-pair precondition, which
2705    // only a broken cut produces, so a face whose cuts already connect (every
2706    // currently-succeeding fragmentation) is never touched.
2707    if chains.iter().any(|c| matches!(c.source, ChainSource::Cut { .. })) {
2708        let endpoints: Vec<(usize, bool, Vec2)> = chains
2709            .iter()
2710            .enumerate()
2711            .flat_map(|(i, c)| [(i, false, c.start), (i, true, c.end)])
2712            .collect();
2713        let anchored = |chain: usize, point: Vec2| -> bool {
2714            boundary_side(point).is_some()
2715                || endpoints.iter().any(|(other_chain, _, other_point)| {
2716                    *other_chain != chain
2717                        && other_point.sub(point).length() <= junction_radius
2718                })
2719        };
2720        // Interior cut endpoints with an anchored far end are the loose ends of
2721        // an almost-through cut. Only these are bridge candidates.
2722        //
2723        // OVERSHOOT-STUB EXCLUSION (offset-shell triple junctions). A pairwise
2724        // section between offset carriers is clipped to the offset IMAGE of the
2725        // source trims, which can extend PAST the true junction with a third
2726        // carrier's section instead of stopping at it (O.S14: the plane×cylinder
2727        // line runs to the source cone∩cylinder circle image at y=100/13 while
2728        // the plane×cone section crosses it ~0.3 earlier at the real offset
2729        // junction). Such a chain is already CONNECTED into the cut graph:
2730        // arrange_segments splits both chains at the crossing node and its
2731        // degree-1 pruning drops the overshoot stub beyond it, and build_loop
2732        // emits the surviving partial runs as Derived sub-curves. The stub's
2733        // dangling endpoint is therefore NOT a broken-junction loose end —
2734        // bridging it would drag a chain end to a midpoint off the section
2735        // (a wrong patch) and the 3D gate would refuse a face the arrangement
2736        // handles exactly. Exclude an endpoint from bridge candidacy when its
2737        // chain intersects another CUT chain at a point interior to the chain
2738        // (beyond the junction radius of both its endpoints — an intersection
2739        // AT the far anchor is the ordinary shared-junction meeting and must
2740        // keep the endpoint eligible, which preserves the imported-geometry
2741        // broken-cut rescue: those chains stop SHORT of each other and have no
2742        // crossing at all).
2743        let cut_chain_has_interior_crossing = |i: usize| -> bool {
2744            let chain = &chains[i];
2745            chains.iter().enumerate().any(|(j, other)| {
2746                // A boundary-duplicate chain was dropped from the arrangement's
2747                // segment set; a crossing with it would not materialize a node.
2748                if j == i
2749                    || dropped_chains.contains(&j)
2750                    || !matches!(other.source, ChainSource::Cut { .. })
2751                {
2752                    return false;
2753                }
2754                chain.segments.iter().any(|&(a0, a1)| {
2755                    other.segments.iter().any(|&(b0, b1)| {
2756                        let Some([t, _]) = crate::arrangement::segment_intersection(
2757                            a0,
2758                            a1,
2759                            b0,
2760                            b1,
2761                            arrangement_tolerance,
2762                        ) else {
2763                            return false;
2764                        };
2765                        let crossing = a0.add(a1.sub(a0).scale(t));
2766                        crossing.sub(chain.start).length() > junction_radius
2767                            && crossing.sub(chain.end).length() > junction_radius
2768                    })
2769                })
2770            })
2771        };
2772        let boundary_anchor = bridge_boundary_t_junction_anchor_enabled();
2773        let lies_on_another_cut_run = |i: usize, point: Vec2| -> bool {
2774            bridge_t_junction_anchor_enabled()
2775                && chains.iter().enumerate().any(|(j, other)| {
2776                    j != i
2777                        && !dropped_chains.contains(&j)
2778                        && (boundary_anchor || matches!(other.source, ChainSource::Cut { .. }))
2779                        && other.segments.iter().any(|&(a, b)| {
2780                            let along = b.sub(a);
2781                            let span = along.dot(along);
2782                            let t = if span > 0.0 {
2783                                (point.sub(a).dot(along) / span).clamp(0.0, 1.0)
2784                            } else {
2785                                0.0
2786                            };
2787                            a.add(along.scale(t)).sub(point).length() <= arrangement_tolerance
2788                        })
2789                })
2790        };
2791        let mut loose: Vec<(usize, bool, Vec2)> = Vec::new();
2792        for (i, c) in chains.iter().enumerate() {
2793            if !matches!(c.source, ChainSource::Cut { .. }) {
2794                continue;
2795            }
2796            for (is_end, this, other) in [(false, c.start, c.end), (true, c.end, c.start)] {
2797                if !anchored(i, this) && anchored(i, other) {
2798                    if lies_on_another_cut_run(i, this) {
2799                        if debug {
2800                            eprintln!("  cut chain {i} end {} is a T-junction on another chain's run", if is_end { "end" } else { "start" });
2801                        }
2802                        continue;
2803                    }
2804                    if cut_chain_has_interior_crossing(i) {
2805                        if debug {
2806                            eprintln!(
2807                                "  cut chain {i} loose {} excluded from junction bridging — \
2808                                 the chain crosses another cut chain mid-run; arrangement \
2809                                 pruning owns the overshoot stub",
2810                                if is_end { "end" } else { "start" },
2811                            );
2812                        }
2813                        continue;
2814                    }
2815                    loose.push((i, is_end, this));
2816                }
2817            }
2818        }
2819        // A triple-point disagreement on imported geometry runs a few 1e-4 (the
2820        // edge<->vertex gap), well under a percent of the face diagonal; bound the
2821        // bridge span so two unrelated loose cuts across a face are never joined.
2822        let bridge_band = (diagonal * 0.02).max(junction_radius * 4.0);
2823        if debug && !loose.is_empty() {
2824            eprintln!("  junction_radius={junction_radius:.6} bridge_band={bridge_band:.6} loose={loose:?}");
2825        }
2826        let skip_crossing_pairs = bridge_skip_crossing_pairs_enabled();
2827        let chains_cross = |i: usize, j: usize| -> bool {
2828            chains[i].segments.iter().any(|&(a0, a1)| {
2829                chains[j].segments.iter().any(|&(b0, b1)| {
2830                    crate::arrangement::segment_intersection(a0, a1, b0, b1, arrangement_tolerance).is_some()
2831                })
2832            })
2833        };
2834        let mut pairs: Vec<(f64, usize, usize)> = Vec::new();
2835        for a in 0..loose.len() {
2836            for b in (a + 1)..loose.len() {
2837                if loose[a].0 == loose[b].0 {
2838                    continue; // never bridge a chain to itself
2839                }
2840                if skip_crossing_pairs && chains_cross(loose[a].0, loose[b].0) {
2841                    if debug {
2842                        eprintln!("  loose ends of chains {} and {} are not bridged: the chains cross", loose[a].0, loose[b].0);
2843                    }
2844                    continue;
2845                }
2846                let gap = loose[a].2.sub(loose[b].2).length();
2847                if gap <= bridge_band {
2848                    pairs.push((gap, a, b));
2849                }
2850            }
2851        }
2852        pairs.sort_by(|x, y| x.0.total_cmp(&y.0));
2853        // 3D-DISTANCE CORROBORATION (case 08:10-genus, secondary defect): the
2854        // 2% UV band is metric-blind — on a big-carrier face (full-sphere
2855        // domain [0,1]² spanning hundreds of mm) it silently bridged loose
2856        // ends 8-14 mm apart in 3D, manufacturing UV-closed but 3D-OPEN loops
2857        // ("loop open between coedges" at assembly). A legitimate bridge heals
2858        // a triple-point disagreement (imported edge<->vertex gap, a small
2859        // fraction of the face scale); an impossible one spans a real missing
2860        // piece. Corroborate every candidate pair in 3D: evaluate the surface
2861        // at both (wrapped-back) loose ends and REFUSE — loudly, as a
2862        // missing-piece error — when their 3D gap exceeds 1% of the face's 3D
2863        // diameter (estimated over a coarse full-domain grid; on a small trim
2864        // of a big carrier this overstates the diameter, i.e. errs LENIENT —
2865        // the safe direction). Any probe evaluation failure falls back to the
2866        // old silent bridging (a diagnostic must not fail the operation).
2867        // Escape hatch: BREP_BRIDGE_3D_GATE=0 restores unconditional bridging.
2868        let bridge_3d_gate = std::env::var("BREP_BRIDGE_3D_GATE").as_deref() != Ok("0");
2869        let face_diameter3 = if bridge_3d_gate && !pairs.is_empty() {
2870            let mut samples: Vec<Vec3> = Vec::new();
2871            'grid: for i in 0..3 {
2872                for j in 0..3 {
2873                    let u = u_domain[0] + (u_domain[1] - u_domain[0]) * i as f64 / 2.0;
2874                    let v = v_domain[0] + (v_domain[1] - v_domain[0]) * j as f64 / 2.0;
2875                    match face.surface.evaluate(u, v) {
2876                        Ok(point) => samples.push(point),
2877                        Err(_) => {
2878                            samples.clear();
2879                            break 'grid;
2880                        }
2881                    }
2882                }
2883            }
2884            let mut diameter = 0.0f64;
2885            for (index, a) in samples.iter().enumerate() {
2886                for b in samples.iter().skip(index + 1) {
2887                    diameter = diameter.max(a.sub(*b).length());
2888                }
2889            }
2890            (diameter > 0.0).then_some(diameter)
2891        } else {
2892            None
2893        };
2894        let mut consumed = vec![false; loose.len()];
2895        let mut bridged = 0usize;
2896        for (gap, a, b) in pairs {
2897            if consumed[a] || consumed[b] {
2898                continue;
2899            }
2900            consumed[a] = true;
2901            consumed[b] = true;
2902            let (chain_a, _, point_a) = loose[a];
2903            let (chain_b, _, point_b) = loose[b];
2904            if let Some(diameter) = face_diameter3 {
2905                let wrapped_a = wrap_back(point_a);
2906                let wrapped_b = wrap_back(point_b);
2907                if let (Ok(position_a), Ok(position_b)) = (
2908                    face.surface.evaluate(wrapped_a.x, wrapped_a.y),
2909                    face.surface.evaluate(wrapped_b.x, wrapped_b.y),
2910                ) {
2911                    let gap3 = position_a.sub(position_b).length();
2912                    let limit = 0.01 * diameter;
2913                    if gap3 > limit {
2914                        return Err(KernelRefusal::internal(KernelStage::Fragment, "fragment.face_split", format!(
2915                            "fragment_face {}: cut junction bridge refused — 3D gap \
2916                             {gap3:.4} exceeds {limit:.4} (1% of face diameter \
2917                             {diameter:.4}) across uv gap {gap:.6}; a section piece \
2918                             is missing between chains {chain_a} and {chain_b}",
2919                            face.id
2920                        )));
2921                    }
2922                }
2923            }
2924            let midpoint = point_a.add(point_b).scale(0.5);
2925            if debug {
2926                eprintln!(
2927                    "  bridging chain {chain_a} at ({:.9},{:.9}) and chain {chain_b} at ({:.9},{:.9}), uv gap {gap:.6}",
2928                    point_a.x, point_a.y, point_b.x, point_b.y
2929                );
2930            }
2931            for (chain, old) in [(chain_a, point_a), (chain_b, point_b)] {
2932                if chains[chain].start.sub(old).length() <= 1e-15 {
2933                    chains[chain].start = midpoint;
2934                }
2935                if chains[chain].end.sub(old).length() <= 1e-15 {
2936                    chains[chain].end = midpoint;
2937                }
2938                for seg in &mut chains[chain].segments {
2939                    if seg.0.sub(old).length() <= 1e-15 {
2940                        seg.0 = midpoint;
2941                    }
2942                    if seg.1.sub(old).length() <= 1e-15 {
2943                        seg.1 = midpoint;
2944                    }
2945                }
2946                for segment in segments.iter_mut() {
2947                    if tag_chain(&segment.tag) != Some(chain as u64) {
2948                        continue;
2949                    }
2950                    if segment.a.sub(old).length() <= 1e-15 {
2951                        segment.a = midpoint;
2952                    }
2953                    if segment.b.sub(old).length() <= 1e-15 {
2954                        segment.b = midpoint;
2955                    }
2956                }
2957            }
2958            bridged += 1;
2959        }
2960        if debug && bridged > 0 {
2961            eprintln!("  bridged {bridged} broken cut junction(s)");
2962        }
2963    }
2964    // GRAZE-BAND COMMON-BLOCK — near-tangent hook absorption (member t548,
2965    // fixture 28). fragment_face runs on the ALREADY edge-split solid, so
2966    // every imprint-minted section×boundary crossing is already a chain endpoint
2967    // by construction. A near-tangent SSI section ending at a shared junction
2968    // vertex can HOOK in its last span: its sampled pcurve overshoots and crosses
2969    // the boundary edge a graze before reaching the shared endpoint (the crossing
2970    // add_edge_split already REFUSED as sub-weld, so the imprint minted only the
2971    // shared vertex). arrange_segments, seeing the linearised hook, re-invents that
2972    // crossing as a distinct INTERIOR point Q, splits the boundary there, and
2973    // spawns a sub-band micro-stub that strands one-use at assembly (t548's
2974    // A→B→C needle). Absorb it deterministically: when a Cut chain and a Boundary
2975    // chain SHARE an endpoint node P, and the cut's polyline crosses that boundary
2976    // at an interior point Q within a MEASURED band of P (3D via surface.evaluate;
2977    // ceiling = the residual-merge sep_cap family, never grown, never the poisoned
2978    // projector), CLIP the cut's hooked tail — drop the samples between the
2979    // crossing and P and run straight into P. The cut's SOURCE curve is untouched,
2980    // so the complete-run path in build_loop still emits the full section edge to
2981    // P; only the spurious arrangement self-crossing is removed. This is the
2982    // arrangement sibling of BREP_SAG_CROSSING_GUARD ("sag refinement may REMOVE a
2983    // crossing but never ADD one"): the arrangement may not invent a boundary
2984    // crossing the imprint did not mint. The structural gate (shared endpoint +
2985    // strictly-interior sub-band crossing) keeps it off legitimate transversals —
2986    // an interior crossing BEYOND the band bails the chain untouched. Generalising
2987    // that gate to Cut×Cut pairs over a measured junction blob was tried and
2988    // falsified as a structural no-op: a crossing in the junction-ADJACENT first
2989    // segment leaves keep_lo=1 reconnecting an identical polyline, and two arms
2990    // that DIVERGE from a shared junction cannot be uncrossed by clipping — this
2991    // absorbs a multi-segment overshoot-and-return hook only. Escape hatch
2992    // BREP_GRAZE_HOOK_CLIP=0.
2993    if std::env::var("BREP_GRAZE_HOOK_CLIP").as_deref() != Ok("0") {
2994        let raw_extent = if solid.vertices.is_empty() {
2995            0.0
2996        } else {
2997            let mut lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
2998            let mut hi = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
2999            for v in &solid.vertices {
3000                lo.x = lo.x.min(v.point.x);
3001                lo.y = lo.y.min(v.point.y);
3002                lo.z = lo.z.min(v.point.z);
3003                hi.x = hi.x.max(v.point.x);
3004                hi.y = hi.y.max(v.point.y);
3005                hi.z = hi.z.max(v.point.z);
3006            }
3007            hi.sub(lo).length()
3008        };
3009        // Mirror imprint::residual_merge_bands' sep_cap (the measured junction-radius
3010        // family, 1.5e-3·extent, floored by the achieved weld band) — the largest
3011        // near-tangent hook a shared-junction section can plausibly span.
3012        let band = 2.0 * 1e-5 * raw_extent.max(1.0);
3013        let sep_cap = (1.5e-3 * raw_extent).max(band);
3014        let graze_debug = debug || std::env::var("BREP_DEBUG_GRAZE").as_deref() == Ok("1");
3015
3016        let mut plans: Vec<(usize, Vec<(Vec2, Vec2)>, f64)> = Vec::new();
3017        for ci in 0..chains.len() {
3018            if !matches!(chains[ci].source, ChainSource::Cut { .. }) {
3019                continue;
3020            }
3021            // A chain already dropped as a boundary duplicate has had its flat
3022            // `segments` removed; never re-materialise it below.
3023            if dropped_chains.contains(&ci) {
3024                continue;
3025            }
3026            if chains[ci].segments.is_empty() {
3027                continue;
3028            }
3029            let mut lo_cut: Option<usize> = None; // clip a start hook after this seg
3030            let mut hi_cut: Option<usize> = None; // clip an end hook from this seg on
3031            let mut measured = 0.0f64;
3032            let mut bail = false;
3033            for &at_end in &[false, true] {
3034                let p = if at_end {
3035                    chains[ci].end
3036                } else {
3037                    chains[ci].start
3038                };
3039                let Ok(p3) = face.surface.evaluate(p.x, p.y) else {
3040                    continue;
3041                };
3042                for bi in 0..chains.len() {
3043                    if bi == ci || !matches!(chains[bi].source, ChainSource::Boundary { .. }) {
3044                        continue;
3045                    }
3046                    let shares = chains[bi].start.sub(p).length() <= node_tolerance
3047                        || chains[bi].end.sub(p).length() <= node_tolerance;
3048                    if !shares {
3049                        continue;
3050                    }
3051                    for si in 0..chains[ci].segments.len() {
3052                        let (sa, sb) = chains[ci].segments[si];
3053                        for &(ba, bb) in &chains[bi].segments {
3054                            let Some([t1, t2]) = crate::arrangement::segment_intersection(
3055                                sa,
3056                                sb,
3057                                ba,
3058                                bb,
3059                                arrangement_tolerance,
3060                            ) else {
3061                                continue;
3062                            };
3063                            // Strictly interior on BOTH segments: not the shared-node
3064                            // touch (t≈0/1) and not a boundary-endpoint (imprint-minted)
3065                            // crossing (t2≈0/1) — an arrangement-invented self-crossing.
3066                            if !(t1 > 1e-3 && t1 < 1.0 - 1e-3 && t2 > 1e-3 && t2 < 1.0 - 1e-3) {
3067                                continue;
3068                            }
3069                            let q = Vec2 {
3070                                x: sa.x + (sb.x - sa.x) * t1,
3071                                y: sa.y + (sb.y - sa.y) * t1,
3072                            };
3073                            let Ok(q3) = face.surface.evaluate(q.x, q.y) else {
3074                                continue;
3075                            };
3076                            let dist = q3.sub(p3).length();
3077                            if dist > sep_cap {
3078                                // A genuine transversal far from the shared vertex —
3079                                // preserve current behaviour, touch nothing.
3080                                bail = true;
3081                                break;
3082                            }
3083                            measured = measured.max(dist);
3084                            if at_end {
3085                                hi_cut = Some(hi_cut.map_or(si, |m| m.min(si)));
3086                            } else {
3087                                lo_cut = Some(lo_cut.map_or(si, |m| m.max(si)));
3088                            }
3089                        }
3090                        if bail {
3091                            break;
3092                        }
3093                    }
3094                    if bail {
3095                        break;
3096                    }
3097                }
3098                if bail {
3099                    break;
3100                }
3101            }
3102            if bail || (lo_cut.is_none() && hi_cut.is_none()) {
3103                continue;
3104            }
3105            let segs = &chains[ci].segments;
3106            let keep_lo = lo_cut.map(|m| m + 1).unwrap_or(0);
3107            let keep_hi = hi_cut.unwrap_or(segs.len());
3108            if keep_lo >= keep_hi {
3109                continue;
3110            }
3111            let mut points: Vec<Vec2> = Vec::with_capacity(keep_hi - keep_lo + 3);
3112            if lo_cut.is_some() {
3113                points.push(chains[ci].start);
3114            }
3115            points.push(segs[keep_lo].0);
3116            for si in keep_lo..keep_hi {
3117                points.push(segs[si].1);
3118            }
3119            if hi_cut.is_some() {
3120                points.push(chains[ci].end);
3121            }
3122            let new_segments: Vec<(Vec2, Vec2)> = points
3123                .windows(2)
3124                .filter(|w| w[0].sub(w[1]).length() > 0.0)
3125                .map(|w| (w[0], w[1]))
3126                .collect();
3127            if new_segments.is_empty() {
3128                continue;
3129            }
3130            if graze_debug {
3131                eprintln!(
3132                    "graze-hook-clip: face {} cut chain {} measured_band={:.3e} sep_cap={:.3e} \
3133                     segs {} -> {} (lo_cut={:?} hi_cut={:?})",
3134                    face.id,
3135                    ci,
3136                    measured,
3137                    sep_cap,
3138                    chains[ci].segments.len(),
3139                    new_segments.len(),
3140                    lo_cut,
3141                    hi_cut
3142                );
3143            }
3144            plans.push((ci, new_segments, measured));
3145        }
3146        for (ci, new_segments, _) in plans {
3147            chains[ci].count = new_segments.len();
3148            chains[ci].segments = new_segments.clone();
3149            segments.retain(|s| tag_chain(&s.tag) != Some(ci as u64));
3150            for (segment_index, (a, b)) in new_segments.into_iter().enumerate() {
3151                segments.push(Segment2 {
3152                    a,
3153                    b,
3154                    tag: segment_tag(ci, segment_index),
3155                });
3156            }
3157        }
3158    }
3159    profile.dedup_bridge += profile.lap(lap_start);
3160    profile.arranged_faces += 1;
3161    // LENS PAIRS APART (`BREP_LENS_PAIR_APART`, default on, `=0` restores;
3162    // `BREP_LENS_PAIR_APART_CHECK` reports the pairs and keeps the plain
3163    // arrangement): on a lens's face, two open chains sharing both ends and
3164    // parting on one side between them (a cap's rim and the other prism's
3165    // section a hair inside it, both sampled at one set of stations) are
3166    // arranged apart in the zone beside each end where their polylines run
3167    // within four tolerances of each other, meeting there only at the end. Near each end the two run
3168    // within the arrangement's tolerance, and the plain arrangement made a
3169    // node of two samples there, or of two chords crossing at a grazing
3170    // angle, a chord away from the true crossing: the runs ended there and
3171    // the loop's vertex stood 0.025 off its edge.
3172    let lens_apart_on = lens_face && crate::switch!("BREP_LENS_PAIR_APART", true);
3173    let lens_apart_check = lens_face && crate::switch!("BREP_LENS_PAIR_APART_CHECK", false);
3174    let lens_pairs: Vec<crate::LensPair> = if lens_apart_on || lens_apart_check {
3175        let shapes: Vec<(Vec2, Vec2, &[(Vec2, Vec2)])> = chains.iter().map(|chain| (chain.start, chain.end, chain.segments.as_slice())).collect();
3176        let pairs = lens_pairs(&shapes, arrangement_tolerance);
3177        if lens_apart_check && !pairs.is_empty() {
3178            let shown: Vec<(u64, u64, f64, f64)> = pairs.iter().map(|pair| (pair.first, pair.second, pair.ends[0].2, pair.ends[1].2)).collect();
3179            eprintln!("lens pairs apart: face {} pairs (first, second, start zone, end zone) {shown:?}", face.id);
3180        }
3181        pairs
3182    } else {
3183        Vec::new()
3184    };
3185    let regions = if lens_apart_on && !lens_pairs.is_empty() {
3186        let chain_of: Vec<u64> = segments.iter().map(|segment| tag_chain(&segment.tag).unwrap_or(u64::MAX)).collect();
3187        let apart = crate::LensApart { chain_of: &chain_of, pairs: &lens_pairs };
3188        crate::arrange_segments_lens_apart(&segments, arrangement_tolerance, &apart).or_refuse(KernelStage::Fragment, "arrange_segments")?
3189    } else {
3190        arrange_segments(&segments, arrangement_tolerance).or_refuse(KernelStage::Fragment, "arrange_segments")?
3191    };
3192    profile.arrange += profile.lap(lap_start);
3193    profile.region_faces += 1;
3194    // Orient every rebuilt loop the way the SOURCE face's own loops are
3195    // oriented, rather than assuming `same_sense` predicts it. The two agree on
3196    // every face whose chart is right-handed against its normal, so this is a
3197    // no-op there; it differs only on a face the old assumption got wrong, and
3198    // getting it wrong reverses that face's whole fragment. Falls back to the
3199    // old rule whenever the source winding cannot be read (see the helper).
3200    // Escape hatch for A/B against the old behaviour.
3201    let source_winding = if std::env::var("BREP_FRAGMENT_SOURCE_WINDING").as_deref() == Ok("0") {
3202        None
3203    } else {
3204        source_loop_winding_negative(face)?
3205    };
3206    let reverse_loops = source_winding.unwrap_or(!face.same_sense);
3207    if debug && reverse_loops != !face.same_sense {
3208        eprintln!(
3209            "  face {}: source loop winds {} against same_sense={} — orienting fragments to the source",
3210            face.id,
3211            if reverse_loops { "CW" } else { "CCW" },
3212            face.same_sense
3213        );
3214    }
3215    // Section pieces the arrangement bounded no region with: a piece that ends
3216    // inside the face (the ruling along which a cylinder merely touches this
3217    // wall) splits nothing, and the region's points are found from the region's
3218    // boundary alone, so one can land on the piece itself, where the face
3219    // touches the other body and reads as lying ON it.
3220    let stray_pieces: Vec<Vec<Vec2>> = if stray_piece_clearance_enabled() {
3221        let used: HashSet<u64> = regions
3222            .iter()
3223            .flat_map(|region| region.outer.iter().chain(region.holes.iter().flatten()))
3224            .filter_map(|usage| tag_chain(&usage.piece.parent.tag))
3225            .collect();
3226        chains
3227            .iter()
3228            .enumerate()
3229            .filter(|(index, chain)| matches!(chain.source, ChainSource::Cut { .. }) && !chain.segments.is_empty() && !used.contains(&(*index as u64)))
3230            .map(|(_, chain)| {
3231                // There and back: a closed path of no area, read as a hole's boundary.
3232                let mut path: Vec<Vec2> = chain.segments.iter().map(|segment| segment.0).collect();
3233                path.push(chain.segments[chain.segments.len() - 1].1);
3234                let back: Vec<Vec2> = path[1..path.len() - 1].iter().rev().copied().collect();
3235                path.extend(back);
3236                path
3237            })
3238            .collect()
3239    } else {
3240        Vec::new()
3241    };
3242    let mut fragments = Vec::new();
3243    for mut region in regions {
3244        super::loops::detach_touched_closed_boundaries(&mut region, &chains, arrangement_tolerance)?;
3245        let order = FragmentOrder {
3246            area: region.outer_area,
3247            key: super::loops::region_topology_key(&region.outer, &region.holes),
3248        };
3249        let mut region_lap = profile.enabled.then(Instant::now);
3250        let arranged: Vec<Vec2> = if stray_pieces.is_empty() {
3251            interior_points(&region.outer, &region.holes, region.area, 3)
3252        } else {
3253            super::loops::interior_points_clear_of(&region.outer, &region.holes, &stray_pieces, region.area, 3)
3254        };
3255        let interior_ms = profile.lap(&mut region_lap).as_secs_f64() * 1000.0;
3256        let candidates: Vec<Vec2> = arranged.iter().copied().map(wrap_back).collect();
3257        let Some(&test_uv) = candidates.first() else {
3258            if debug {
3259                eprintln!("  region area={:.6e}: no interior point", region.area);
3260            }
3261            continue;
3262        };
3263        let mut containment = parameter_point_in_face(face, test_uv, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")?;
3264        // TRIM-FRAME CONTAINMENT. A face whose own pcurves run past its
3265        // carrier's domain (helmet Face_15: its trim spans u in
3266        // [-0.178, 0.298] on a carrier closed in u, drawn without a hop) is
3267        // arranged in that frame, and the region's point is on the face there.
3268        // Its wrapped image (u = 0.970 for -0.030) lies on no trim polygon,
3269        // and containment has no period image to try for a trim that never
3270        // hops the seam, so it reads Outside and the region was dropped: the
3271        // face's y >= 0 piece in `20_helmet_merge_stage` b - a, whose section
3272        // edges then stood one-use. With no band re-base the arrangement's
3273        // frame is the trim's own, so the region's point is asked there as
3274        // well. Escape hatch `BREP_REGION_TRIM_FRAME=0`.
3275        if containment != PolygonClass::Inside
3276            && band_rebase == [None, None]
3277            && (arranged[0].x != test_uv.x || arranged[0].y != test_uv.y)
3278            && std::env::var("BREP_REGION_TRIM_FRAME").as_deref() != Ok("0")
3279        {
3280            containment = parameter_point_in_face(face, arranged[0], 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")?;
3281            if debug {
3282                eprintln!(
3283                    "  region area={:.6e} test=({:.9},{:.9}) asked in the trim's frame at ({:.9},{:.9}): {:?}",
3284                    region.area, test_uv.x, test_uv.y, arranged[0].x, arranged[0].y,
3285                    containment == PolygonClass::Inside
3286                );
3287            }
3288        }
3289        if containment != PolygonClass::Inside {
3290            if debug {
3291                eprintln!(
3292                    "  region area={:.6e} test=({:.9},{:.9}): outside trimmed face",
3293                    region.area, test_uv.x, test_uv.y
3294                );
3295            }
3296            continue;
3297        }
3298        if debug {
3299            eprintln!(
3300                "  region area={:.6e} test=({:.9},{:.9}): KEPT",
3301                region.area, test_uv.x, test_uv.y
3302            );
3303        }
3304        let containment_ms = profile.lap(&mut region_lap).as_secs_f64() * 1000.0;
3305        let Some(outer_loop) = build_loop(
3306            &region.outer,
3307            reverse_loops,
3308            &chains,
3309            arrangement_tolerance,
3310            &face.surface,
3311        )?
3312        else {
3313            // Spurious zero-area antenna region (e.g. a seam-grazing fold on a
3314            // periodic band); it bounds no material, so drop it.
3315            if debug {
3316                eprintln!("  region area={:.6e}: dropped (degenerate antenna)", region.area);
3317            }
3318            continue;
3319        };
3320        let mut loops = vec![outer_loop];
3321        for hole in &region.holes {
3322            // Holes take the SAME flag as the outer loop: the arrangement
3323            // hands them back already wound against it, so reversing both
3324            // together keeps them opposite.
3325            if let Some(hole_loop) = build_loop(
3326                hole,
3327                reverse_loops,
3328                &chains,
3329                arrangement_tolerance,
3330                &face.surface,
3331            )? {
3332                loops.push(hole_loop);
3333            }
3334        }
3335        for loop_record in &mut loops {
3336            for coedge in &mut loop_record.coedges {
3337                if let FragmentEdgeSource::Boundary {
3338                    operand: source_operand,
3339                    ..
3340                } = &mut coedge.source
3341                {
3342                    *source_operand = operand;
3343                }
3344            }
3345        }
3346        let mut extra_test_points = Vec::new();
3347        for &candidate in candidates.iter().skip(1) {
3348            if parameter_point_in_face(face, candidate, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")? == PolygonClass::Inside {
3349                extra_test_points.push(face.surface.evaluate(candidate.x, candidate.y).or_refuse(KernelStage::Fragment, "evaluate")?);
3350            }
3351        }
3352        if profile.enabled {
3353            crate::imprint::profile_emit(format_args!("fragment.region face={} edges={} holes={} interior={interior_ms:.3} containment={containment_ms:.3} loops={:.3}",
3354                face.id, region.outer.len(), region.holes.len(), profile.lap(&mut region_lap).as_secs_f64() * 1000.0));
3355        }
3356        fragments.push(FaceFragmentRecord {
3357            operand,
3358            source_face_id: face.id,
3359            surface: face.surface.clone(),
3360            same_sense: face.same_sense,
3361            loops,
3362            test_point: face.surface.evaluate(test_uv.x, test_uv.y).or_refuse(KernelStage::Fragment, "evaluate")?,
3363            test_uv,
3364            extra_test_points,
3365            order: Some(order),
3366        });
3367    }
3368
3369    // Rescue an UNCUT face the flat 2D arrangement failed to reconstruct.
3370    // A seam-closed multi-loop face (a band on a surface of revolution, whose
3371    // param-space loops only close across the u/v seam, or a holed face whose
3372    // domain centre lands in the hole so the fast path above declined it)
3373    // collapses to zero-area lines in the [0,1]^2 arrangement and yields NO
3374    // region -> the face is dropped entirely, stranding its neighbours' shared
3375    // edges as one-use and knocking the assembly's genus off an integer. Since
3376    // the face is uncut, its loops already describe the exact trimmed boundary,
3377    // so pass the unchanged face through — we only need a valid interior test
3378    // point, found by gridding the ACTUAL knot domain. Gated on
3379    // `fragments.is_empty()`, this never touches a face the arrangement handled.
3380    profile.regions += profile.lap(lap_start);
3381    if fragments.is_empty() && piece_ids.is_empty() {
3382        const GRID: usize = 12;
3383        let mut test_uv: Option<Vec2> = None;
3384        let mut extra_test_points: Vec<Vec3> = Vec::new();
3385        'search: for iu in 1..GRID {
3386            for iv in 1..GRID {
3387                let candidate = Vec2 {
3388                    x: u_domain[0] + (u_domain[1] - u_domain[0]) * iu as f64 / GRID as f64,
3389                    y: v_domain[0] + (v_domain[1] - v_domain[0]) * iv as f64 / GRID as f64,
3390                };
3391                if parameter_point_in_face(face, candidate, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")? == PolygonClass::Inside {
3392                    if test_uv.is_none() {
3393                        test_uv = Some(candidate);
3394                    } else {
3395                        extra_test_points.push(face.surface.evaluate(candidate.x, candidate.y).or_refuse(KernelStage::Fragment, "evaluate")?);
3396                        if extra_test_points.len() >= 2 {
3397                            break 'search;
3398                        }
3399                    }
3400                }
3401            }
3402        }
3403        // SEAM-STRADDLING BAND fallback (a SINGLY-periodic surface of
3404        // revolution whose trim loop closes only ACROSS the u/v seam — e.g. a
3405        // rounded imported cap grazed near-tangent, so it stays uncut). The
3406        // even-odd `parameter_point_in_face` reads Outside EVERYWHERE on such a
3407        // loop (the seam hop makes the [0,1]^2 polygon non-simple), so the knot
3408        // grid above finds nothing and the face would still drop. `seam_band_
3409        // point_in_face` only covers the DOUBLY-periodic (torus) case, so the
3410        // singly-periodic band has no seam-aware classifier. Unwrap the loop
3411        // onto the surface's covering plane (`loop_seam_offsets`, the same fold
3412        // the mass integrator and tessellator use), where it IS a simple
3413        // polygon, grid that unwrapped bbox with the plain even-odd test, and
3414        // map an interior hit back into the domain. Runs ONLY when the grid
3415        // already failed AND the offsets show the loop truly straddled a seam
3416        // (a full-wrap rim yields all-zero offsets and is left untouched), so it
3417        // never changes a face any earlier path handled.
3418        if test_uv.is_none() {
3419            let (closed_u, closed_v) = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
3420            if closed_u || closed_v {
3421                let u_period = u_domain[1] - u_domain[0];
3422                let v_period = v_domain[1] - v_domain[0];
3423                let mut loop_polygons: Vec<Vec<Vec2>> = Vec::new();
3424                let mut straddled = false;
3425                let (mut umin, mut umax, mut vmin, mut vmax) = (
3426                    f64::INFINITY,
3427                    f64::NEG_INFINITY,
3428                    f64::INFINITY,
3429                    f64::NEG_INFINITY,
3430                );
3431                for loop_record in &face.loops {
3432                    let offsets = crate::topology::loop_seam_offsets(
3433                        &loop_record.coedges,
3434                        closed_u,
3435                        closed_v,
3436                        u_period,
3437                        v_period,
3438                    ).or_refuse(KernelStage::Fragment, "csg.fragment.face_split")?;
3439                    if offsets.iter().any(|o| o[0] != 0.0 || o[1] != 0.0) {
3440                        straddled = true;
3441                    }
3442                    let mut polygon = Vec::new();
3443                    for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
3444                        let [d0, d1] = coedge.pcurve.domain().or_refuse(KernelStage::Fragment, "domain")?;
3445                        let samples = 32usize;
3446                        for k in 0..samples {
3447                            let t = d0 + (d1 - d0) * k as f64 / samples as f64;
3448                            let p = coedge.pcurve.evaluate(t).or_refuse(KernelStage::Fragment, "evaluate")?;
3449                            let uv = Vec2 {
3450                                x: p.x + offsets[coedge_index][0],
3451                                y: p.y + offsets[coedge_index][1],
3452                            };
3453                            umin = umin.min(uv.x);
3454                            umax = umax.max(uv.x);
3455                            vmin = vmin.min(uv.y);
3456                            vmax = vmax.max(uv.y);
3457                            polygon.push(uv);
3458                        }
3459                    }
3460                    loop_polygons.push(polygon);
3461                }
3462                if straddled && umax > umin && vmax > vmin {
3463                    let wrap = |value: f64, lo: f64, span: f64| {
3464                        if span > 0.0 {
3465                            lo + (value - lo).rem_euclid(span)
3466                        } else {
3467                            value
3468                        }
3469                    };
3470                    'seam: for iu in 1..GRID {
3471                        for iv in 1..GRID {
3472                            let cu = umin + (umax - umin) * iu as f64 / GRID as f64;
3473                            let cv = vmin + (vmax - vmin) * iv as f64 / GRID as f64;
3474                            let candidate = Vec2 { x: cu, y: cv };
3475                            // Even-odd fill across ALL unwrapped loops: interior
3476                            // of the trimmed region is where the winding is odd
3477                            // (outer loop minus any hole loops), independent of
3478                            // which loop is the outer one.
3479                            let winding = loop_polygons
3480                                .iter()
3481                                .filter(|polygon| point_in_polygon(candidate, polygon))
3482                                .count();
3483                            if winding % 2 == 0 {
3484                                continue;
3485                            }
3486                            let mapped = Vec2 {
3487                                x: if closed_u {
3488                                    wrap(cu, u_domain[0], u_period)
3489                                } else {
3490                                    cu
3491                                },
3492                                y: if closed_v {
3493                                    wrap(cv, v_domain[0], v_period)
3494                                } else {
3495                                    cv
3496                                },
3497                            };
3498                            if test_uv.is_none() {
3499                                test_uv = Some(mapped);
3500                            } else {
3501                                extra_test_points
3502                                    .push(face.surface.evaluate(mapped.x, mapped.y).or_refuse(KernelStage::Fragment, "evaluate")?);
3503                                if extra_test_points.len() >= 2 {
3504                                    break 'seam;
3505                                }
3506                            }
3507                        }
3508                    }
3509                }
3510            }
3511        }
3512        if let Some(uv) = test_uv {
3513            fragments.push(FaceFragmentRecord {
3514                operand,
3515                source_face_id: face.id,
3516                surface: face.surface.clone(),
3517                same_sense: face.same_sense,
3518                loops: face
3519                    .loops
3520                    .iter()
3521                    .map(|loop_record| FragmentLoop {
3522                        coedges: loop_record
3523                            .coedges
3524                            .iter()
3525                            .map(|coedge| FragmentCoedge {
3526                                source: FragmentEdgeSource::Boundary {
3527                                    operand,
3528                                    edge_id: coedge.edge_id,
3529                                },
3530                                forward: coedge.forward,
3531                                pcurve: coedge.pcurve.clone(),
3532                            })
3533                            .collect(),
3534                    })
3535                    .collect(),
3536                test_point: face.surface.evaluate(uv.x, uv.y).or_refuse(KernelStage::Fragment, "evaluate")?,
3537                test_uv: uv,
3538                extra_test_points,
3539                order: None,
3540            });
3541        }
3542    }
3543    profile.rescue += profile.lap(lap_start);
3544    Ok(fragments)
3545}
3546
3547pub fn fragment_solid(
3548    solid: &BrepSolid,
3549    operand: u8,
3550    imprint: &ImprintResultRecord,
3551) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
3552    fragment_solid_against(solid, operand, imprint, None)
3553}
3554
3555/// A positive rational carrier is enclosed by its control hull. Unknown or
3556/// non-finite weights/points cannot certify separation and keep the full path.
3557pub fn bounded_carriers(solid: &BrepSolid) -> bool {
3558    solid.shells.iter().flat_map(|s| &s.faces).all(|face| bounded_carrier(face))
3559}
3560
3561fn bounded_carrier(face: &FaceRecord) -> bool {
3562    let (Ok(u), Ok(v)) = (face.surface.domain_u(), face.surface.domain_v()) else { return false };
3563    let positive_finite = |p: &crate::Vec4| {
3564        p.w > 0.0 && p.w.is_finite() && p.point().is_ok_and(|v|
3565            v.x.is_finite() && v.y.is_finite() && v.z.is_finite())
3566    };
3567    // Extended trims may live outside the carrier hull. Positive pcurve
3568    // controls within both knot domains certify the whole trim stays inside;
3569    // otherwise retain the existing extension/seam handling, without epsilon.
3570    // ROUNDING SLACK (`BREP_FRAGMENT_SCOPE_ULPS`, default on; `=0` restores the exact test): a trim that runs ALONG a domain
3571    // border carries controls a few ulps past it (a hole wall's seam at u = -7.8e-16 or
3572    // 1.0000000000000009, a bore's floor at 1.5200000000000002 of 1.52), and the exact test then
3573    // called every such carrier unbounded: on a part of countersunk seats and blind bores no face
3574    // was ever separated and each of 88 booleans arranged all ~500 faces to cut 6. A control within
3575    // `SCOPE_ULPS` ulps of the border moves the trim off the hull by that many ulps of the
3576    // carrier's size, orders below the separation band every caller adds.
3577    let slack = |d: [f64; 2]| if scope_ulps_on() { SCOPE_ULPS * f64::EPSILON * d[0].abs().max(d[1].abs()).max(d[1] - d[0]) } else { 0.0 };
3578    let (su, sv) = (slack(u), slack(v));
3579    face.surface.control_points.iter().flatten().all(positive_finite)
3580        && face.loops.iter().flat_map(|lp| &lp.coedges).all(|coedge| {
3581            coedge.pcurve.control_points.iter().all(|p| {
3582                positive_finite(p) && p.point().is_ok_and(|p|
3583                    p.x >= u[0] - su && p.x <= u[1] + su && p.y >= v[0] - sv && p.y <= v[1] + sv)
3584            })
3585        })
3586}
3587
3588/// The rounding slack of `bounded_carrier`'s trim test, in ulps of the domain.
3589const SCOPE_ULPS: f64 = 64.0;
3590
3591fn scope_ulps_on() -> bool {
3592    crate::switch!("BREP_FRAGMENT_SCOPE_ULPS", true)
3593}
3594
3595/// Exact control-hull separation, including the extended-trim guard.
3596pub fn face_separated(face: &FaceRecord, bounds: crate::Aabb, band: f64) -> bool {
3597    bounded_carrier(face) && crate::Aabb::from_surface_controls(&face.surface)
3598        .is_ok_and(|own| !own.intersects(bounds, band))
3599}
3600
3601/// A boundary witness suffices when the ENTIRE carrier is separated from the
3602/// other operand: every point of the face has the same Outside classification.
3603/// Keep the authored loops exactly; no interior-point search or arrangement
3604/// is needed to decide material against an operand outside this carrier box.
3605/// TRIM-SIDE PROBE for a face no section touches whose arrangement came back
3606/// EMPTY (hosted report 2026-11-02 "boolean fails", the shelf pin): the
3607/// bracket union's cylinder carried its cone on a 0.01-wide cap ring (the
3608/// cone's base rim 0.01 inside the cylinder's cap), no section on it. Its
3609/// domain centre is its hole, so it went to the arrangement for a test
3610/// point, which sampled a circle at 32 chords: the inner rim's chords sagged
3611/// 0.0115 into the hole, the only region's test point sat there, "outside
3612/// trimmed face", and the face was dropped without a word (open edges at
3613/// assembly, or a body that validated at the wrong volume). A face without
3614/// a cut that the arrangement does not split is one fragment, itself; all
3615/// it needs is a point of its own material, and that lies beside its trim: a
3616/// station on each loop's pcurve, stepped off along the pcurve's normal on
3617/// both sides over a ladder of distances, the first one the trim owns. The
3618/// arrangement's own answers stand where it gives any (a pinched loop it
3619/// splits in two). Escape hatch `BREP_FRAGMENT_TRIM_PROBE=0|off` leaves the
3620/// empty answer as it was.
3621fn trim_probe_enabled() -> bool {
3622    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3623    *ON.get_or_init(|| !matches!(std::env::var("BREP_FRAGMENT_TRIM_PROBE").as_deref(), Ok("0") | Ok("off")))
3624}
3625
3626/// The face itself as its one fragment, with the test point `uv`.
3627fn untouched_fragment(
3628    face: &FaceRecord,
3629    operand: u8,
3630    uv: Vec2,
3631    extra_test_points: Vec<Vec3>,
3632) -> Result<FaceFragmentRecord, KernelRefusal> {
3633    Ok(FaceFragmentRecord {
3634        operand,
3635        source_face_id: face.id,
3636        surface: face.surface.clone(),
3637        same_sense: face.same_sense,
3638        loops: face
3639            .loops
3640            .iter()
3641            .map(|loop_record| FragmentLoop {
3642                coedges: loop_record
3643                    .coedges
3644                    .iter()
3645                    .map(|coedge| FragmentCoedge {
3646                        source: FragmentEdgeSource::Boundary {
3647                            operand,
3648                            edge_id: coedge.edge_id,
3649                        },
3650                        forward: coedge.forward,
3651                        pcurve: coedge.pcurve.clone(),
3652                    })
3653                    .collect(),
3654            })
3655            .collect(),
3656        test_point: face.surface.evaluate(uv.x, uv.y).or_refuse(KernelStage::Fragment, "evaluate")?,
3657        test_uv: uv,
3658        extra_test_points,
3659        order: None,
3660    })
3661}
3662
3663/// A point of `face`'s material beside its trim, with up to two more as
3664/// extra test points, or `None` when no station of the ladder is owned.
3665/// Keep a region's test points clear of the section pieces that end inside it
3666/// (`BREP_FRAGMENT_STRAY_PIECE_CLEARANCE`, default on; `=0` reads the region's
3667/// boundary alone).
3668fn stray_piece_clearance_enabled() -> bool {
3669    switch!("BREP_FRAGMENT_STRAY_PIECE_CLEARANCE", true)
3670}
3671
3672fn trim_interior_probe(
3673    face: &FaceRecord,
3674    u: [f64; 2],
3675    v: [f64; 2],
3676) -> Result<Option<(Vec2, Vec<Vec3>)>, KernelRefusal> {
3677    let diagonal = ((u[1] - u[0]).powi(2) + (v[1] - v[0]).powi(2)).sqrt();
3678    if !(diagonal > 0.0) {
3679        return Ok(None);
3680    }
3681    let mut found: Vec<Vec2> = Vec::new();
3682    'loops: for loop_record in &face.loops {
3683        for coedge in &loop_record.coedges {
3684            let [a, b] = coedge.pcurve.domain().or_refuse(KernelStage::Fragment, "domain")?;
3685            if !(b > a) {
3686                continue;
3687            }
3688            for fraction in [0.5, 0.25, 0.75] {
3689                let t = a + (b - a) * fraction;
3690                let derivatives = coedge.pcurve.derivatives(t, 1).or_refuse(KernelStage::Fragment, "derivatives")?;
3691                let (at, tangent) = (derivatives[0], derivatives[1]);
3692                let speed = (tangent.x * tangent.x + tangent.y * tangent.y).sqrt();
3693                if !(speed > 0.0) || !speed.is_finite() {
3694                    continue;
3695                }
3696                let normal = Vec2 { x: -tangent.y / speed, y: tangent.x / speed };
3697                for scale in [1e-2, 1e-3, 1e-4, 1e-5, 1e-6] {
3698                    let step = diagonal * scale;
3699                    for sign in [1.0, -1.0] {
3700                        let candidate = Vec2 { x: at.x + normal.x * step * sign, y: at.y + normal.y * step * sign };
3701                        if candidate.x < u[0] || candidate.x > u[1] || candidate.y < v[0] || candidate.y > v[1] {
3702                            continue;
3703                        }
3704                        if parameter_point_in_face(face, candidate, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")? == PolygonClass::Inside {
3705                            found.push(candidate);
3706                            if found.len() >= 3 {
3707                                break 'loops;
3708                            }
3709                            continue 'loops;
3710                        }
3711                    }
3712                }
3713            }
3714        }
3715    }
3716    let Some(uv) = found.first().copied() else {
3717        return Ok(None);
3718    };
3719    let mut extra_test_points = Vec::new();
3720    for candidate in found.iter().skip(1) {
3721        extra_test_points.push(face.surface.evaluate(candidate.x, candidate.y).or_refuse(KernelStage::Fragment, "evaluate")?);
3722    }
3723    Ok(Some((uv, extra_test_points)))
3724}
3725
3726fn separated_fragment(face: &FaceRecord, operand: u8) -> Option<FaceFragmentRecord> {
3727    let coedge = face.loops.first()?.coedges.first()?;
3728    let [a, b] = coedge.pcurve.domain().ok()?;
3729    let point = coedge.pcurve.evaluate(a + (b - a) * 0.5).ok()?;
3730    let uv = Vec2 { x: point.x, y: point.y };
3731    let test_point = face.surface.evaluate(uv.x, uv.y).ok()?;
3732    Some(FaceFragmentRecord {
3733        operand, source_face_id: face.id, surface: face.surface.clone(),
3734        same_sense: face.same_sense,
3735        loops: face.loops.iter().map(|lp| FragmentLoop {
3736            coedges: lp.coedges.iter().map(|coedge| FragmentCoedge {
3737                source: FragmentEdgeSource::Boundary { operand, edge_id: coedge.edge_id },
3738                forward: coedge.forward, pcurve: coedge.pcurve.clone(),
3739            }).collect(),
3740        }).collect(),
3741        test_point, test_uv: uv, extra_test_points: Vec::new(), order: None,
3742    })
3743}
3744
3745pub fn fragment_solid_against(
3746    solid: &BrepSolid,
3747    operand: u8,
3748    imprint: &ImprintResultRecord,
3749    other: Option<(crate::Aabb, f64)>,
3750) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
3751    let mut profile = FragmentProfile::new();
3752    if profile.enabled {
3753        crate::classification::containment_profile_begin();
3754    }
3755    let result = fragment_solid_profiled(solid, operand, imprint, other, &mut profile);
3756    profile.report(operand);
3757    if profile.enabled {
3758        crate::classification::containment_profile_report("fragment");
3759    }
3760    result
3761}
3762
3763pub fn fragment_solid_profiled(
3764    solid: &BrepSolid,
3765    operand: u8,
3766    imprint: &ImprintResultRecord,
3767    other: Option<(crate::Aabb, f64)>,
3768    profile: &mut FragmentProfile,
3769) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
3770    let index = FragmentIndex::build(imprint);
3771    let mut fragments = Vec::new();
3772    for face in solid.shells.iter().flat_map(|shell| shell.faces.iter()) {
3773        let far = other.is_some_and(|(bounds, band)| face_separated(face, bounds, band));
3774        if !far { profile.box_candidates += 1; }
3775        let has_pieces = index.by_face.get(&(operand, face.id)).is_some_and(|ids| !ids.is_empty());
3776        let cosurface = index.cosurface_pairs.iter().any(|(key, _)| key.operand == operand && key.face_id == face.id);
3777        if far && !has_pieces && !cosurface && std::env::var("BREP_FRAGMENT_SCOPE").as_deref() != Ok("0") {
3778            if let Some(fragment) = separated_fragment(face, operand) {
3779                profile.separated_faces += 1;
3780                profile.face_done(face.id, None);
3781                fragments.push(fragment);
3782                continue;
3783            }
3784        }
3785        let before = (profile.arranged_faces, profile.region_faces);
3786        fragments.extend(fragment_face_indexed(solid, operand, face, &index, profile)?);
3787        if far {
3788            profile.far_arranged += profile.arranged_faces - before.0;
3789            profile.far_regions += profile.region_faces - before.1;
3790        }
3791    }
3792    Ok(fragments)
3793}
3794
3795
3796/// `BREP_RIM_BRIDGE` (default on, `=0` off): the fragment side of the imprint's rim
3797/// bridge (see RIM BRIDGE in `fragment_face_arranged`).
3798fn rim_bridge_enabled() -> bool {
3799    crate::switch!("BREP_RIM_BRIDGE", true)
3800}
3801
3802/// The lens pairs among `chains` (start, end, segments) that an arrangement
3803/// at `tolerance` keeps apart in their end zones (`BREP_LENS_PAIR_APART`):
3804/// two open chains sharing both ends (within ten tolerances), every sample of
3805/// each farther than the tolerance from the other standing on one side of it,
3806/// and the samples within the tolerance only running unbroken from the two
3807/// ends. Each end's zone runs out to the first sample of either chain
3808/// standing farther than four tolerances from the other.
3809pub(crate) fn lens_pairs(chains: &[(Vec2, Vec2, &[(Vec2, Vec2)])], tolerance: f64) -> Vec<crate::LensPair> {
3810    let (meet, zone_band) = (10.0 * tolerance, 4.0 * tolerance);
3811    // The distance from `point` to a polyline, signed by the side of the
3812    // nearest segment it stands on.
3813    let signed_to = |point: Vec2, segments: &[(Vec2, Vec2)]| -> (f64, f64) {
3814        let mut best = (f64::INFINITY, 0.0);
3815        for (a, b) in segments {
3816            let span = b.sub(*a);
3817            let squared = span.dot(span);
3818            let t = if squared > 0.0 { (point.sub(*a).dot(span) / squared).clamp(0.0, 1.0) } else { 0.0 };
3819            let foot = Vec2 { x: a.x + span.x * t, y: a.y + span.y * t };
3820            let distance = point.sub(foot).length();
3821            if distance < best.0 {
3822                let side = span.x * (point.y - a.y) - span.y * (point.x - a.x);
3823                best = (distance, side.signum());
3824            }
3825        }
3826        best
3827    };
3828    let points_of = |segments: &[(Vec2, Vec2)]| -> Vec<Vec2> { segments.iter().map(|(a, _)| *a).chain(segments.last().map(|(_, b)| *b)).collect() };
3829    // How far from its first point a polyline (read from one end) runs until
3830    // a sample stands farther than the zone band from the other.
3831    let zone_from = |points: &[Vec2], other: &[(Vec2, Vec2)]| -> Option<f64> {
3832        let end = points[0];
3833        points.iter().skip(1).find(|point| signed_to(**point, other).0 > zone_band).map(|point| point.sub(end).length())
3834    };
3835    let one_side = |segments: &[(Vec2, Vec2)], other: &[(Vec2, Vec2)]| -> bool {
3836        let readings: Vec<(f64, f64)> = points_of(segments).iter().map(|point| signed_to(*point, other)).collect();
3837        let close = |reading: &(f64, f64)| reading.0 <= tolerance;
3838        let head = readings.iter().take_while(|reading| close(reading)).count();
3839        let tail = readings.iter().rev().take_while(|reading| close(reading)).count();
3840        if head + tail >= readings.len() {
3841            return false;
3842        }
3843        let middle = &readings[head..readings.len() - tail];
3844        let sign = middle[0].1;
3845        sign != 0.0 && middle.iter().all(|reading| !close(reading) && reading.1 == sign)
3846    };
3847    let mut pairs = Vec::new();
3848    for i in 0..chains.len() {
3849        for j in (i + 1)..chains.len() {
3850            let ((a_start, a_end, a), (b_start, b_end, b)) = (chains[i], chains[j]);
3851            if a.len() < 2 || b.len() < 2 {
3852                continue;
3853            }
3854            let open = |start: Vec2, end: Vec2| start.sub(end).length() > meet;
3855            let same = a_start.sub(b_start).length() <= meet && a_end.sub(b_end).length() <= meet;
3856            let reversed = a_start.sub(b_end).length() <= meet && a_end.sub(b_start).length() <= meet;
3857            if !(open(a_start, a_end) && open(b_start, b_end) && (same || reversed)) {
3858                continue;
3859            }
3860            // A side change anywhere is a crossing of the chains themselves
3861            // (two exact polylines 3e-7 apart crossing twice beside an end),
3862            // and a contact inside the tolerance away from the ends is one
3863            // the samples cannot tell from a crossing: either way the pair is
3864            // arranged plainly.
3865            if !(one_side(a, b) && one_side(b, a)) {
3866                continue;
3867            }
3868            let (a_points, b_points) = (points_of(a), points_of(b));
3869            let reversed_points = |points: &[Vec2]| -> Vec<Vec2> { points.iter().rev().copied().collect() };
3870            let (b_from_a_start, b_from_a_end) = if same { (b_points.clone(), reversed_points(&b_points)) } else { (reversed_points(&b_points), b_points.clone()) };
3871            let zone = |a_points: &[Vec2], b_points: &[Vec2]| -> Option<f64> { Some(zone_from(a_points, b)?.max(zone_from(b_points, a)?)) };
3872            let (Some(start_zone), Some(end_zone)) = (zone(&a_points, &b_from_a_start), zone(&reversed_points(&a_points), &b_from_a_end)) else { continue };
3873            pairs.push(crate::LensPair { first: i as u64, second: j as u64, ends: [(a_start, meet, start_zone), (a_end, meet, end_zone)] });
3874        }
3875    }
3876    pairs
3877}