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                *lap_start = profile.enabled.then(Instant::now);
1004                return Ok(fragments);
1005            }
1006        }
1007        split_result = Some(outcome);
1008        *lap_start = profile.enabled.then(Instant::now);
1009    }
1010    let arranged = fragment_face_arranged(solid, operand, face, face_key, piece_ids, index, profile, lap_start);
1011    // A face no section touches that the arrangement answered with NOTHING is
1012    // not gone: it is one fragment, itself, and all it needs is a point of
1013    // its own material, found beside its trim (`trim_interior_probe`). The
1014    // arrangement keeps every face it does split (a pinched loop into two).
1015    if piece_ids.is_empty() && trim_probe_enabled() && matches!(&arranged, Ok(fragments) if fragments.is_empty()) {
1016        let u = KnotVector::new(face.surface.knots_u.clone(), face.surface.degree_u).or_refuse(KernelStage::Fragment, "new")?.domain();
1017        let v = KnotVector::new(face.surface.knots_v.clone(), face.surface.degree_v).or_refuse(KernelStage::Fragment, "new")?.domain();
1018        if let Some((uv, extra_test_points)) = trim_interior_probe(face, u, v)? {
1019            return Ok(vec![untouched_fragment(face, operand, uv, extra_test_points)?]);
1020        }
1021    }
1022    if let Some(split) = split_result {
1023        let verdict = match (&split, &arranged) {
1024            (Err(decline), _) => format!("declined {decline}"),
1025            (Ok(_), Err(refusal)) => format!("MISMATCH split built {} fragments, arrangement refused: {refusal}", split.as_ref().map_or(0, Vec::len)),
1026            (Ok(split), Ok(arranged)) => match fragments_agree(split, arranged) {
1027                Ok(agreement) => agreement.to_string(),
1028                Err(why) => format!("MISMATCH {why}"),
1029            },
1030        };
1031        loop_split_census(|| format!("operand {operand} face {} pieces {} loops {} {verdict}", face.id, piece_ids.len(), face.loops.len()));
1032    }
1033    arranged
1034}
1035
1036
1037#[allow(clippy::too_many_arguments)]
1038fn fragment_face_arranged(
1039    solid: &BrepSolid,
1040    operand: u8,
1041    face: &FaceRecord,
1042    face_key: FaceKey,
1043    piece_ids: &[u64],
1044    index: &FragmentIndex,
1045    profile: &mut FragmentProfile,
1046    lap_start: &mut Option<Instant>,
1047) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
1048
1049    let u_domain = KnotVector::new(face.surface.knots_u.clone(), face.surface.degree_u).or_refuse(KernelStage::Fragment, "new")?.domain();
1050    let v_domain = KnotVector::new(face.surface.knots_v.clone(), face.surface.degree_v).or_refuse(KernelStage::Fragment, "new")?.domain();
1051    let diagonal =
1052        ((u_domain[1] - u_domain[0]).powi(2) + (v_domain[1] - v_domain[0]).powi(2)).sqrt();
1053    let original_resolution = 1e-7f64.max(diagonal * 1e-6);
1054    let (strip_resolution, feature_strip, wedge_resolution, lens_face) = thin_boundary_resolution(solid, face, face_key, piece_ids, index, original_resolution);
1055    let (band_tolerance, band_sampling) = strip_resolution
1056        .unwrap_or((original_resolution, original_resolution));
1057    // A wedge narrows the arrangement and the sampling only; the bands a chain
1058    // end is matched in stay the face's own (a marched cut stops a few 1e-6
1059    // short of the boundary it ends on, and a dome's pole wedge that narrowed
1060    // them kept that end from its junction).
1061    let (arrangement_tolerance, sampling_bound) = match wedge_resolution {
1062        Some((arrangement, sampling)) => (band_tolerance.min(arrangement), band_sampling.min(sampling)),
1063        None => (band_tolerance, band_sampling),
1064    };
1065    // FEATURE SCALE B4 (`BREP_FEATURE_SCALE_FRAGMENT`): with a thin strip
1066    // between two cuts or a near touch on the face, a chain end is matched to another vertex's image only within
1067    // the strip's own sampling bound in the chart and 1e-7 in model space
1068    // (`strip_between` admits only strips over 8e-7 wide), not 100
1069    // resolutions and 1e-5: the hairline slot's two walls end 1e-6 apart on
1070    // the cube's top, and each wall's cut took the other's far end.
1071    // Only for a strip a feature-scale measure found: a cut-against-boundary
1072    // strip the fragmenter always measured kept its wide bands (narrowing them
1073    // too opened loops on revolve ∪ wedge fixtures with coincident side planes).
1074    // OPERAND SLIVERS (`BREP_FEATURE_SCALE_OPERAND_SLIVERS`): a face that meets
1075    // a sliver FeatureScale registered between the two operands matches its
1076    // chain ends in the strip's bands too. Two boxes whose +y faces stand 1e-5
1077    // apart: a side face's strip between its own edge and the other box's
1078    // edge (the cosurface exchange's cut) is exactly 1e-5 wide, the wide
1079    // bands (1e-5 in model space) took the strip's corners for one vertex, the
1080    // cut read as a duplicate of the bent boundary and was dropped, and the
1081    // slab lost its four side faces.
1082    let strip_snap = feature_strip
1083        || (strip_resolution.is_some()
1084            && !index.operand_sliver_regions.is_empty()
1085            && crate::spatial::Aabb::from_surface_controls(&face.surface)
1086                .is_ok_and(|face_box| index.operand_sliver_regions.iter().any(|region| face_box.intersects(*region, original_resolution))));
1087    let (image_band, image_band_3d) = if strip_snap {
1088        (sampling_bound, 1e-7)
1089    } else {
1090        (band_tolerance * 100.0, 1e-5)
1091    };
1092    let snap_threshold = 0.1 * diagonal;
1093    let junction_radius = (band_tolerance * 50.0).max(diagonal * 1.5e-3);
1094    // WRAPPED-BAND RE-BASE: a face on a closed direction whose material is the
1095    // wrapped COMPLEMENT of its trim hull (two full-wrap rims at the hull
1096    // edges, material crossing the seam between them — trial 35's torus face:
1097    // rims at v=0.25/1.0, material v∈[0,0.25]) cannot be arranged in the flat
1098    // domain rectangle: a cut through the band ends at v=0 while its junction
1099    // partner (the split rim vertex) sits at v=1, so every cut dangles, cycle
1100    // extraction fails, and the face is dropped wholesale (one-use cascade).
1101    // Re-base into the material-coherent frame [hull_high, hull_low+period]:
1102    // shift every chain point on the low side of the hull window (+period), so
1103    // rims and cuts junction in ONE unwrapped chart, and wrap region test
1104    // points back into the domain on exit. Detection mirrors the imprint's
1105    // restricted-carrier wrap guard: the hull-complement strip contains no
1106    // loop curves, so one sample at its middle decides materiality exactly.
1107    // Escape hatch: BREP_BAND_REBASE=0.
1108    let band_rebase: [Option<(f64, f64)>; 2] = {
1109        let mut rebase = [None, None];
1110        let closed = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
1111        if (closed.0 || closed.1) && std::env::var("BREP_BAND_REBASE").as_deref() != Ok("0") {
1112            // Per-coedge hulls on each axis, plus whether any ISO-RIM
1113            // (a coedge whose pcurve is near-constant on the axis) sits at a
1114            // domain edge — the discriminator for the wrapped-band class.
1115            // A seam-straddling boundary band (helmet Face_15, whose source
1116            // pcurves are already unwrapped past the domain) has no such rim
1117            // and its frame is already coherent; it must NOT be re-based.
1118            let mut coverage: [Vec<[f64; 2]>; 2] = [Vec::new(), Vec::new()];
1119            let mut edge_rim = [false, false];
1120            let mut hull = [
1121                [f64::INFINITY, f64::NEG_INFINITY],
1122                [f64::INFINITY, f64::NEG_INFINITY],
1123            ];
1124            for coedge in face
1125                .loops
1126                .iter()
1127                .flat_map(|loop_record| &loop_record.coedges)
1128            {
1129                let mut extent = [
1130                    [f64::INFINITY, f64::NEG_INFINITY],
1131                    [f64::INFINITY, f64::NEG_INFINITY],
1132                ];
1133                for control in &coedge.pcurve.control_points {
1134                    if control.w.abs() <= 1e-300 {
1135                        continue;
1136                    }
1137                    let point = [control.x / control.w, control.y / control.w];
1138                    for axis in 0..2 {
1139                        extent[axis][0] = extent[axis][0].min(point[axis]);
1140                        extent[axis][1] = extent[axis][1].max(point[axis]);
1141                        hull[axis][0] = hull[axis][0].min(point[axis]);
1142                        hull[axis][1] = hull[axis][1].max(point[axis]);
1143                    }
1144                }
1145                for axis in 0..2 {
1146                    if !extent[axis][0].is_finite() {
1147                        continue;
1148                    }
1149                    let domain = if axis == 0 { u_domain } else { v_domain };
1150                    let span = domain[1] - domain[0];
1151                    coverage[axis].push(extent[axis]);
1152                    let flat = extent[axis][1] - extent[axis][0] <= 1e-3 * span;
1153                    let at_edge = (extent[axis][0] - domain[0]).abs() <= 1e-6 * span
1154                        || (extent[axis][1] - domain[1]).abs() <= 1e-6 * span;
1155                    if flat && at_edge {
1156                        edge_rim[axis] = true;
1157                    }
1158                }
1159            }
1160            for axis in 0..2 {
1161                if !(if axis == 0 { closed.0 } else { closed.1 }) || !edge_rim[axis] {
1162                    continue;
1163                }
1164                let domain = if axis == 0 { u_domain } else { v_domain };
1165                let span = domain[1] - domain[0];
1166                // Merge the coverage intervals (clamped into the domain) and
1167                // find the largest uncovered gap. The gap contains no boundary
1168                // curve, so it is uniformly material or uniformly void — one
1169                // sample at its middle decides exactly. A strictly INTERIOR
1170                // void gap means the material wraps through the domain edge.
1171                let mut intervals: Vec<[f64; 2]> = coverage[axis]
1172                    .iter()
1173                    .map(|window| {
1174                        [window[0].max(domain[0]), window[1].min(domain[1])]
1175                    })
1176                    .filter(|window| window[1] >= window[0])
1177                    .collect();
1178                intervals.sort_by(|a, b| a[0].total_cmp(&b[0]));
1179                let mut gaps: Vec<[f64; 2]> = Vec::new();
1180                let mut reach = domain[0];
1181                for window in &intervals {
1182                    if window[0] > reach {
1183                        gaps.push([reach, window[0]]);
1184                    }
1185                    reach = reach.max(window[1]);
1186                }
1187                if reach < domain[1] {
1188                    gaps.push([reach, domain[1]]);
1189                }
1190                let other_mid = (hull[1 - axis][0].max(if axis == 0 {
1191                    v_domain[0]
1192                } else {
1193                    u_domain[0]
1194                }) + hull[1 - axis][1].min(if axis == 0 {
1195                    v_domain[1]
1196                } else {
1197                    u_domain[1]
1198                })) / 2.0;
1199                let mut void: Option<[f64; 2]> = None;
1200                for gap in gaps {
1201                    if gap[1] - gap[0] <= 1e-6 * span {
1202                        continue;
1203                    }
1204                    let mid = (gap[0] + gap[1]) / 2.0;
1205                    let sample = if axis == 0 {
1206                        Vec2 {
1207                            x: mid,
1208                            y: other_mid,
1209                        }
1210                    } else {
1211                        Vec2 {
1212                            x: other_mid,
1213                            y: mid,
1214                        }
1215                    };
1216                    if parameter_point_in_face(face, sample, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")? != PolygonClass::Inside
1217                        && void
1218                            .map(|best| gap[1] - gap[0] > best[1] - best[0])
1219                            .unwrap_or(true)
1220                    {
1221                        void = Some(gap);
1222                    }
1223                }
1224                if let Some([g0, g1]) = void {
1225                    // The material+boundary arc wraps the domain edge exactly
1226                    // when boundary coverage touches BOTH edge representations
1227                    // (the on-seam rim at one, the material-side chains at the
1228                    // other) with the void between them. An ordinary band
1229                    // (material inside the rims) touches only one edge and
1230                    // must keep the flat frame.
1231                    let touches_low = intervals
1232                        .iter()
1233                        .any(|window| window[0] <= domain[0] + 1e-6 * span);
1234                    let touches_high = intervals
1235                        .iter()
1236                        .any(|window| window[1] >= domain[1] - 1e-6 * span);
1237                    if touches_low && touches_high {
1238                        // Shift everything on the low side of the void up one
1239                        // period so the band is contiguous in the arrangement
1240                        // frame.
1241                        rebase[axis] = Some(((g0 + g1) / 2.0, span));
1242                    }
1243                }
1244            }
1245        }
1246        rebase
1247    };
1248    let rebase_point = |mut point: Vec2| -> Vec2 {
1249        if let Some((cutoff, period)) = band_rebase[0] {
1250            if point.x < cutoff {
1251                point.x += period;
1252            }
1253        }
1254        if let Some((cutoff, period)) = band_rebase[1] {
1255            if point.y < cutoff {
1256                point.y += period;
1257            }
1258        }
1259        point
1260    };
1261    // Region test points computed in a re-based or unwrapped frame must be
1262    // folded back into the domain before trim classification / evaluation.
1263    // Wrapping is gated on the axis being CLOSED (a coherent flat face never
1264    // produces out-of-domain interior points, so this is a no-op there).
1265    let wrap_back = {
1266        let closed = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
1267        move |mut point: Vec2| -> Vec2 {
1268            if closed.0 {
1269                let span = u_domain[1] - u_domain[0];
1270                if point.x < u_domain[0] || point.x > u_domain[1] {
1271                    point.x = u_domain[0] + (point.x - u_domain[0]).rem_euclid(span);
1272                }
1273            }
1274            if closed.1 {
1275                let span = v_domain[1] - v_domain[0];
1276                if point.y < v_domain[0] || point.y > v_domain[1] {
1277                    point.y = v_domain[0] + (point.y - v_domain[0]).rem_euclid(span);
1278                }
1279            }
1280            point
1281        }
1282    };
1283    profile.setup += profile.lap(lap_start);
1284    let pieces_by_id = &index.pieces_by_id;
1285    let mut cut_hints = Vec::new();
1286    let mut active_pieces = Vec::new();
1287    let mut cut_keys = HashMap::default();
1288    for piece_id in piece_ids {
1289        let piece = pieces_by_id
1290            .get(piece_id)
1291            .ok_or_else(|| KernelRefusal::internal(KernelStage::Fragment, "fragment.face_split", "fragment_face: missing imprint piece"))?;
1292        let pcurve = pcurve_for(piece, face_key)?;
1293        let [start, end] = pcurve.domain().or_refuse(KernelStage::Fragment, "domain")?;
1294        let a = pcurve.evaluate(start).or_refuse(KernelStage::Fragment, "evaluate")?;
1295        let b = pcurve.evaluate(end).or_refuse(KernelStage::Fragment, "evaluate")?;
1296        let middle = pcurve.evaluate((start + end) / 2.0).or_refuse(KernelStage::Fragment, "evaluate")?;
1297        for point in [a, b] {
1298            cut_hints.push(Vec2 {
1299                x: point.x,
1300                y: point.y,
1301            });
1302        }
1303        let quantize = |point: Vec3| {
1304            (
1305                (point.x / arrangement_tolerance).round() as i64,
1306                (point.y / arrangement_tolerance).round() as i64,
1307            )
1308        };
1309        let mut endpoints = [quantize(a), quantize(b)];
1310        endpoints.sort();
1311        let key = (endpoints[0], quantize(middle), endpoints[1]);
1312        if cut_keys.insert(key, *piece_id).is_none() {
1313            active_pieces.push(*piece_id);
1314        }
1315    }
1316
1317    let mut segments = Vec::new();
1318    let mut chains = Vec::new();
1319    let mut vertex_images: std::collections::HashMap<String, Vec<Vec2>> =
1320        std::collections::HashMap::new();
1321    let mut endpoint_images: Vec<(Vec3, Vec2)> = Vec::new();
1322    // Each boundary image carries its 3D vertex point so the boundary-side
1323    // canonicalization can refuse to unify two DISTINCT boundary vertices.
1324    let mut boundary_images: Vec<(Vec2, Vec3)> = Vec::new();
1325    // BOUNDARY-VERTEX ANCHOR (t427 box-corner graze). The boundary-side snap
1326    // below (rule 3) merges a chain endpoint onto a same-side boundary image
1327    // within arr_tol*100 with NO 3D check. For a CUT/section terminus that is
1328    // the intended near-tangent graze bridge onto a trim edge. For a BOUNDARY
1329    // endpoint it is a bug: two genuinely-distinct same-operand boundary
1330    // vertices (t427: box corner v8 at v=68.4851 vs the edge-16 split A at
1331    // v=68.4783, 6.8e-3 apart on the u=max domain edge, 6.8e-3 apart in 3D ≫
1332    // the 1e-5 weld floor) get unified, which droops edge 21's pcurve and
1333    // mints a phantom corner lens bounded by derived edges → a one-use cluster
1334    // that only strands in UNION (where the unsectioned neighbour keeps the
1335    // whole edge 21). Anchor a boundary endpoint to a same-side image only when
1336    // they are the SAME physical vertex (3D-coincident within the weld floor).
1337    // Hatch BREP_BOUNDARY_VERTEX_ANCHOR=0 restores the pre-fix behaviour.
1338    let boundary_vertex_anchor_off =
1339        std::env::var("BREP_BOUNDARY_VERTEX_ANCHOR").as_deref() == Ok("0");
1340    let boundary_side = |point: Vec2| {
1341        let distances = [
1342            (point.x - u_domain[0]).abs(),
1343            (point.x - u_domain[1]).abs(),
1344            (point.y - v_domain[0]).abs(),
1345            (point.y - v_domain[1]).abs(),
1346        ];
1347        let index = distances
1348            .iter()
1349            .enumerate()
1350            .min_by(|a, b| a.1.total_cmp(b.1))
1351            .map(|entry| entry.0)
1352            .unwrap();
1353        (distances[index] <= arrangement_tolerance * 50.0).then_some(index)
1354    };
1355
1356    // RIM BRIDGE (`BREP_RIM_BRIDGE`, default on, `=0` off; the imprint mints the
1357    // bridge): a straight section a few `tol / |tan·n|` long between two
1358    // rim pierces, one end on a vertex of this face's rim (within the weld)
1359    // and the other a distinct vertex just inside it. The far end lies far closer to the rim in the chart
1360    // than in space, so rule 3 below (a cut end onto a same-side boundary
1361    // image, no 3-D check) would fold the bridge onto the rim vertex and the
1362    // sections meeting it would skip it. Its ends keep their own images.
1363    let bridge_keys: HashSet<String> = if rim_bridge_enabled() {
1364        let weld = crate::tolerance::assembler_weld(1e-7);
1365        // The face's own boundary vertices: a bridge has one end on its rim.
1366        let mut rim_points = Vec::new();
1367        for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
1368            if let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) {
1369                for vertex_id in [edge.start_vertex_id, edge.end_vertex_id] {
1370                    rim_points.push(vertex_point(solid, vertex_id)?);
1371                }
1372            }
1373        }
1374        let on_rim = |point: &Vec3| rim_points.iter().any(|rim| rim.sub(*point).length() <= weld);
1375        piece_ids
1376            .iter()
1377            .filter_map(|piece_id| pieces_by_id.get(piece_id))
1378            .filter(|piece| {
1379                piece.start_vertex_id != piece.end_vertex_id
1380                    && piece.curve.degree == 1
1381                    && piece.curve.control_points.len() == 2
1382                    && match (index.vertex_points.get(&piece.start_vertex_id), index.vertex_points.get(&piece.end_vertex_id)) {
1383                        (Some(a), Some(b)) => {
1384                            let gap = a.sub(*b).length();
1385                            gap > weld && gap <= 1e-3 && (on_rim(a) || on_rim(b))
1386                        }
1387                        _ => false,
1388                    }
1389            })
1390            .flat_map(|piece| [format!("i:{}", piece.start_vertex_id), format!("i:{}", piece.end_vertex_id)])
1391            .collect()
1392    } else {
1393        HashSet::default()
1394    };
1395    // Vertices where two or more cut pieces of this face meet: an interior
1396    // junction of the section, never a boundary vertex it merely nears.
1397    let junction_keys: HashSet<String> = if crate::switch!("BREP_NEAR_SEAM_CLOSED_RUN", true) {
1398        let mut seen: HashMap<u64, usize> = HashMap::default();
1399        for piece in active_pieces.iter().filter_map(|piece_id| pieces_by_id.get(piece_id)) {
1400            if piece.start_vertex_id != piece.end_vertex_id {
1401                *seen.entry(piece.start_vertex_id).or_default() += 1;
1402                *seen.entry(piece.end_vertex_id).or_default() += 1;
1403            }
1404        }
1405        seen.into_iter().filter(|(_, uses)| *uses >= 2).map(|(id, _)| format!("i:{id}")).collect()
1406    } else {
1407        HashSet::default()
1408    };
1409    let mut add_chain = |mut points: Vec<Vec2>,
1410                         source: ChainSource,
1411                         vertex_start_key: String,
1412                         vertex_start_point: Vec3,
1413                         vertex_end_key: String,
1414                         vertex_end_point: Vec3,
1415                         is_boundary: bool|
1416     -> Result<(), KernelRefusal> {
1417        for (at, key, point3) in [
1418            (0usize, vertex_start_key, vertex_start_point),
1419            (points.len() - 1, vertex_end_key, vertex_end_point),
1420        ] {
1421            let point = points[at];
1422            let bridged = bridge_keys.contains(&key);
1423            let junction = junction_keys.contains(&key);
1424            let images = vertex_images.entry(key).or_default();
1425            let canonical = images
1426                .iter()
1427                .copied()
1428                .find(|image| image.sub(point).length() <= snap_threshold)
1429                .or_else(|| {
1430                    endpoint_images
1431                        .iter()
1432                        .find(|(candidate3, candidate)| {
1433                            candidate3.sub(point3).length() <= image_band_3d
1434                                && candidate.sub(point).length() <= image_band
1435                        })
1436                        .map(|candidate| candidate.1)
1437                })
1438                .or_else(|| {
1439                    if bridged {
1440                        return None;
1441                    }
1442                    boundary_side(point).and_then(|side| {
1443                        boundary_images
1444                            .iter()
1445                            .find(|(candidate, candidate3)| {
1446                                boundary_side(*candidate) == Some(side)
1447                                    && candidate.sub(point).length()
1448                                        <= image_band
1449                                    // Boundary endpoints only merge to a same-side
1450                                    // image when 3D-coincident (same physical
1451                                    // vertex); cut endpoints keep the graze bridge.
1452                                    && (boundary_vertex_anchor_off
1453                                        || (!is_boundary && !junction)
1454                                        || candidate3.sub(point3).length() <= 1e-5)
1455                            })
1456                            .map(|(candidate, _)| *candidate)
1457                    })
1458                });
1459            if let Some(canonical) = canonical {
1460                points[at] = canonical;
1461                images.push(canonical);
1462            } else {
1463                images.push(point);
1464                endpoint_images.push((point3, point));
1465                if is_boundary && boundary_side(point).is_some() {
1466                    boundary_images.push((point, point3));
1467                }
1468            }
1469        }
1470        if points.len() > 2 {
1471            let start = points[0];
1472            let end = points[points.len() - 1];
1473            let thin = |radius: f64| {
1474                let mut kept = vec![start];
1475                kept.extend(points[1..points.len() - 1].iter().copied().filter(|point| {
1476                    point.sub(start).length() > radius && point.sub(end).length() > radius
1477                }));
1478                kept.push(end);
1479                kept
1480            };
1481            let mut kept = thin(junction_radius);
1482            // SMALL RING (`BREP_FRAGMENT_SMALL_RING`): a chain that lies wholly
1483            // inside the junction radius of its own ends (the 0.028 pinhole on a
1484            // plane charted over [0, 30]², radius 0.064) loses every interior
1485            // point: a closed one bounds nothing and two half-circles fold onto
1486            // one chord, so the region they ring is never carved. When the
1487            // thinning would leave the chain flatter than it is (its bulge off
1488            // the chord, or off its vertex when closed, past ten tolerances),
1489            // thin it at a tenth of that bulge instead.
1490            let closed = start.sub(end).length() <= arrangement_tolerance;
1491            if kept.len() < if closed { 4 } else { 3 } && small_ring_enabled() {
1492                let chord = end.sub(start);
1493                let span = chord.length();
1494                let bulge = points
1495                    .iter()
1496                    .map(|point| {
1497                        let offset = point.sub(start);
1498                        if closed || span <= arrangement_tolerance {
1499                            offset.length()
1500                        } else {
1501                            (offset.x * chord.y - offset.y * chord.x).abs() / span
1502                        }
1503                    })
1504                    .fold(0.0, f64::max);
1505                // On a lens's face the arcs bound a strip eight resolutions
1506                // wide, at least one of them bulging by four.
1507                if bulge > arrangement_tolerance * if lens_face { 4.0 } else { 10.0 } {
1508                    kept = thin(bulge * 0.1);
1509                }
1510            }
1511            points = kept;
1512        }
1513        let chain_index = chains.len();
1514        let chain_segments = points
1515            .windows(2)
1516            .map(|pair| (pair[0], pair[1]))
1517            .collect::<Vec<_>>();
1518        for (segment_index, pair) in points.windows(2).enumerate() {
1519            segments.push(Segment2 {
1520                a: pair[0],
1521                b: pair[1],
1522                tag: segment_tag(chain_index, segment_index),
1523            });
1524        }
1525        chains.push(Chain {
1526            source,
1527            count: points.len() - 1,
1528            start: points[0],
1529            end: points[points.len() - 1],
1530            segments: chain_segments,
1531        });
1532        Ok(())
1533    };
1534
1535    profile.hints += profile.lap(lap_start);
1536    // SEAM-IMAGE LOOPS: per-loop u-control-hulls, computed once for the
1537    // straddling-hole gate below (does any OTHER loop span the full closed-u
1538    // domain — the rectangle-with-seam outer that closes the strip walls).
1539    let loop_hull_u: Vec<[f64; 2]> = face
1540        .loops
1541        .iter()
1542        .map(|loop_record| {
1543            let mut hull = [f64::INFINITY, f64::NEG_INFINITY];
1544            for coedge in &loop_record.coedges {
1545                for control in &coedge.pcurve.control_points {
1546                    if control.w.abs() <= 1e-300 {
1547                        continue;
1548                    }
1549                    hull[0] = hull[0].min(control.x / control.w);
1550                    hull[1] = hull[1].max(control.x / control.w);
1551                }
1552            }
1553            hull
1554        })
1555        .collect();
1556    // Signed area of the face's full-u-span loop (the rectangle-with-seam
1557    // outer), recorded as it is processed: it defines the chart's material
1558    // orientation, so a HOLE is any loop winding OPPOSITE to it (the absolute
1559    // sign is chart-dependent — mirrored charts flip both).
1560    let mut full_span_loop_area: Option<f64> = None;
1561    // Post-rebase boundary polyline segments (incl. seam-image copies), kept
1562    // for the sag-refinement boundary-crossing parity guard on cut chains.
1563    let mut boundary_segments: Vec<(Vec2, Vec2)> = Vec::new();
1564    // The u and v extent of the boundary chains as the arrangement places
1565    // them — after the seam-hop unwrap and the band re-base, before any
1566    // seam-image copy — which is the period window the face's material lives
1567    // in. See the cut-chain period lift below.
1568    let mut band_hull = [[f64::INFINITY, f64::NEG_INFINITY]; 2];
1569    // BOUNDARY-VERTEX HINTS (2026-11-02): a curved boundary chord is refined
1570    // where ANOTHER boundary vertex of the face lies within its length, exactly
1571    // as `refine_near_hints` already refines it near a cut's endpoints.
1572    // `sample_boundary_chain` only keeps a chord within a ten-thousandth of the
1573    // domain diagonal of its pcurve, and that bound cannot see a second loop:
1574    // the plate's top face (diagonal 222) drew its r 10.7 blend-corner arc at
1575    // 16 chords sagging 0.0128, while the corner vertex of the hole the earlier
1576    // subtracts cut sits 0.011 inside that arc. The hole loop poked through the
1577    // outer loop's polyline, the arrangement cut the rim at the chord crossings
1578    // (0.04 from the true arc, on the far side of the hole vertex), and the
1579    // subtract refused with four one-use rim edges and a 0.0125 vertex gap. The
1580    // face's own vertices are hints, so a chord that a neighbouring vertex
1581    // approaches within its length is drawn sixteen times finer there (sag 5e-5
1582    // against the 0.011 clearance). A chord's own endpoints are not hints for
1583    // it (every chord ends at a vertex), and a straight pcurve has no chords to
1584    // refine. Escape hatch `BREP_BOUNDARY_VERTEX_HINTS=0|off`.
1585    let boundary_vertex_hints: Vec<Vec2> = if boundary_vertex_hints_enabled() {
1586        let mut hints = Vec::new();
1587        for loop_record in &face.loops {
1588            for coedge in &loop_record.coedges {
1589                let [start, end] = coedge.pcurve.domain().or_refuse(KernelStage::Fragment, "domain")?;
1590                for parameter in [start, end] {
1591                    let point = coedge.pcurve.evaluate(parameter).or_refuse(KernelStage::Fragment, "evaluate")?;
1592                    hints.push(Vec2 { x: point.x, y: point.y });
1593                }
1594            }
1595        }
1596        hints
1597    } else {
1598        Vec::new()
1599    };
1600    for (loop_index, loop_record) in face.loops.iter().enumerate() {
1601        // SEAM-HOP UNWRAP: a loop whose pcurves are drawn IN-DOMAIN but hop
1602        // the seam between consecutive coedges (t91's face 675: the boundary
1603        // jumps u=1→0 at v≈0.967 and back at v≈0.453) is incoherent in the
1604        // flat chart — its cut chains mint fine and then dangle against the
1605        // hopping boundary, cycle extraction fails, and the face drops
1606        // wholesale (the trial-35 zero-fragment signature, third variant).
1607        // Unwrap onto the covering plane with the SAME per-coedge offsets the
1608        // mass integrator / tessellator / seam-band classifier use
1609        // (`loop_seam_offsets`); a continuous loop gets all-zero offsets and
1610        // is untouched (helmet-class unwrapped sources, native seam-edge
1611        // loops, plain faces). Composes with the band re-base above: offsets
1612        // normalize the boundary FIRST, after which the re-base's
1613        // below-cutoff boundary shifts are no-ops and only its cut-chain
1614        // shifts still apply. Escape hatch: BREP_LOOP_UNWRAP=0.
1615        let closed = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
1616        let offsets = if (closed.0 || closed.1)
1617            && std::env::var("BREP_LOOP_UNWRAP").as_deref() != Ok("0")
1618        {
1619            crate::topology::loop_seam_offsets(
1620                &loop_record.coedges,
1621                closed.0,
1622                closed.1,
1623                u_domain[1] - u_domain[0],
1624                v_domain[1] - v_domain[0],
1625            ).or_refuse(KernelStage::Fragment, "csg.fragment.face_split")?
1626        } else {
1627            vec![[0.0, 0.0]; loop_record.coedges.len()]
1628        };
1629        let mut sampled: Vec<(usize, Vec<Vec2>, NurbsCurve, u64, u64)> =
1630            Vec::with_capacity(loop_record.coedges.len());
1631        for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
1632            let edge = edge_for(solid, coedge.edge_id)?;
1633            let (start_vertex, end_vertex) = if coedge.forward {
1634                (edge.start_vertex_id, edge.end_vertex_id)
1635            } else {
1636                (edge.end_vertex_id, edge.start_vertex_id)
1637            };
1638            let offset = offsets
1639                .get(coedge_index)
1640                .copied()
1641                .unwrap_or([0.0, 0.0]);
1642            // Adaptive samples are not uniformly spaced in parameter. Do not
1643            // feed them to refine_near_hints, which assumes uniform input.
1644            let boundary_points = if strip_resolution.is_some() || wedge_resolution.is_some() {
1645                let initial = sample_chain(&coedge.pcurve)?;
1646                sag_refine_chain(&coedge.pcurve, initial, sampling_bound)?.0
1647            } else {
1648                // A curved boundary is drawn within a ten-thousandth of the
1649                // domain's diagonal of itself (`sample_boundary_chain`), so a
1650                // narrow face's two rims cannot cross each other.
1651                let initial = sample_boundary_chain(&coedge.pcurve, (diagonal * 1e-4).max(sampling_bound), 1024)?;
1652                if boundary_vertex_hints.is_empty() || initial.len() < 3 {
1653                    refine_near_hints(&initial, &coedge.pcurve, &cut_hints)?
1654                } else {
1655                    let own = [initial[0], initial[initial.len() - 1]];
1656                    let hints: Vec<Vec2> = cut_hints
1657                        .iter()
1658                        .copied()
1659                        .chain(boundary_vertex_hints.iter().copied().filter(|hint| {
1660                            own.iter().all(|end| hint.sub(*end).length() > arrangement_tolerance)
1661                        }))
1662                        .collect();
1663                    refine_near_hints(&initial, &coedge.pcurve, &hints)?
1664                }
1665            };
1666            let points: Vec<Vec2> = boundary_points
1667                    .into_iter()
1668                    .map(|point| {
1669                        rebase_point(Vec2 {
1670                            x: point.x + offset[0],
1671                            y: point.y + offset[1],
1672                        })
1673                    })
1674                    .collect();
1675            let curve = trimmed_curve(&edge.curve, edge.t0, edge.t1)?;
1676            let curve = if coedge.forward {
1677                curve
1678            } else {
1679                curve.reversed().or_refuse(KernelStage::Fragment, "reversed")?
1680            };
1681            sampled.push((coedge_index, points, curve, start_vertex, end_vertex));
1682        }
1683        // SEAM-IMAGE for a STRADDLING HOLE loop: an inner (hole) loop whose
1684        // unwrapped chains poke past a closed-u domain wall exists at only ONE
1685        // period image in the arrangement strip, so the strip's OTHER side
1686        // never sees it — the seam-adjacent region there keeps a boundary
1687        // running straight through the hole opening (t181/00000312#p7: face
1688        // 519's decagon hole unwraps to u∈[−0.039,0.039]; the region left of
1689        // the seam used the FULL seam edge 475 while the right region split at
1690        // the hole crossings; the hole's far-half rim edges stranded one-use
1691        // and an 18mm derived chord bridged the gap). Insert a duplicate of
1692        // the loop's chains shifted one period toward the strip's other side,
1693        // so BOTH walls are split by the hole and the half-hole phantom
1694        // regions (rejected by the cross-frame containment) carve it out.
1695        // STRUCTURAL GATE (all required): u-closed face; ≥2 loops; the loop's
1696        // unwrapped span crosses a u-wall by > junction slack; loop width ≤
1697        // half the period (a compact hole, never a rim/horizon); winding
1698        // OPPOSITE to the full-span outer loop (hole orientation relative to
1699        // the chart — an outer loop copy would double-cover material); and
1700        // some OTHER loop's control hull spans the full u-domain (the
1701        // seam-carrying rectangle exists). Escape hatch:
1702        // BREP_SEAM_IMAGE_LOOPS=0.
1703        let image_shift: Option<f64> = {
1704            let span = u_domain[1] - u_domain[0];
1705            let slack = arrangement_tolerance * 50.0;
1706            if !closed.0
1707                || face.loops.len() < 2
1708                || span <= 0.0
1709                || std::env::var("BREP_SEAM_IMAGE_LOOPS").as_deref() == Ok("0")
1710            {
1711                None
1712            } else {
1713                let mut min_u = f64::INFINITY;
1714                let mut max_u = f64::NEG_INFINITY;
1715                let mut area = 0.0;
1716                let mut flat: Vec<Vec2> = sampled
1717                    .iter()
1718                    .flat_map(|(_, points, ..)| points.iter().copied())
1719                    .collect();
1720                if flat.len() < 3 {
1721                    flat.clear();
1722                }
1723                for (index, point) in flat.iter().enumerate() {
1724                    min_u = min_u.min(point.x);
1725                    max_u = max_u.max(point.x);
1726                    let next = flat[(index + 1) % flat.len()];
1727                    area += crate::polygon::area_term([point.x, point.y], [next.x, next.y]);
1728                }
1729                // Full-span discrimination must use the UNWRAPPED width: a
1730                // straddling hole's raw control hull spans the whole domain
1731                // (its halves are stored at both seam sides), but its
1732                // unwrapped chains are compact; only the true outer rectangle
1733                // stays period-wide after unwrapping.
1734                let spans_full_domain =
1735                    !flat.is_empty() && max_u - min_u >= span * (1.0 - 1e-6);
1736                if spans_full_domain && full_span_loop_area.is_none() {
1737                    full_span_loop_area = Some(area);
1738                }
1739                let straddles_low = min_u < u_domain[0] - slack;
1740                let straddles_high = max_u > u_domain[1] + slack;
1741                let compact = max_u - min_u <= 0.5 * span;
1742                let is_hole = full_span_loop_area
1743                    .map(|outer| !spans_full_domain && area * outer < 0.0)
1744                    .unwrap_or(false);
1745                let has_full_span_other = loop_hull_u.iter().enumerate().any(|(other, hull)| {
1746                    other != loop_index
1747                        && hull[0] <= u_domain[0] + 1e-6 * span
1748                        && hull[1] >= u_domain[1] - 1e-6 * span
1749                });
1750                if compact && is_hole && has_full_span_other && (straddles_low ^ straddles_high) {
1751                    if env_read!("BREP_DEBUG_FRAG")
1752                        .map(|value| value == face.id.to_string())
1753                        .unwrap_or(false)
1754                    {
1755                        eprintln!(
1756                            "  seam-image: face {} loop {loop_index} straddles u-wall (u=[{min_u:.6},{max_u:.6}]) — inserting {} period image",
1757                            face.id,
1758                            if straddles_low { "+1" } else { "-1" }
1759                        );
1760                    }
1761                    Some(if straddles_low { span } else { -span })
1762                } else {
1763                    None
1764                }
1765            }
1766        };
1767        for (coedge_index, points, curve, start_vertex, end_vertex) in sampled {
1768            let coedge = &loop_record.coedges[coedge_index];
1769            for point in &points {
1770                band_hull[0] = [band_hull[0][0].min(point.x), band_hull[0][1].max(point.x)];
1771                band_hull[1] = [band_hull[1][0].min(point.y), band_hull[1][1].max(point.y)];
1772            }
1773            boundary_segments.extend(points.windows(2).map(|pair| (pair[0], pair[1])));
1774            add_chain(
1775                points.clone(),
1776                ChainSource::Boundary {
1777                    coedge: coedge.clone(),
1778                    curve: curve.clone(),
1779                },
1780                format!("b:{operand}:{start_vertex}"),
1781                vertex_point(solid, start_vertex)?,
1782                format!("b:{operand}:{end_vertex}"),
1783                vertex_point(solid, end_vertex)?,
1784                true,
1785            )?;
1786            if let Some(shift) = image_shift {
1787                let shifted: Vec<Vec2> = points
1788                    .iter()
1789                    .map(|point| Vec2 {
1790                        x: point.x + shift,
1791                        y: point.y,
1792                    })
1793                    .collect();
1794                boundary_segments
1795                    .extend(shifted.windows(2).map(|pair| (pair[0], pair[1])));
1796                add_chain(
1797                    shifted,
1798                    ChainSource::Boundary {
1799                        coedge: coedge.clone(),
1800                        curve,
1801                    },
1802                    format!("b:{operand}:{start_vertex}"),
1803                    vertex_point(solid, start_vertex)?,
1804                    format!("b:{operand}:{end_vertex}"),
1805                    vertex_point(solid, end_vertex)?,
1806                    true,
1807                )?;
1808            }
1809        }
1810    }
1811    // CUT-CHAIN CLAMP BOUND: on a CLOSED direction the face's boundary band may
1812    // legitimately extend past the surface domain — a seam-straddling face is
1813    // arranged in UNWRAPPED coordinates (helmet Face_15's boundary chains run
1814    // u∈[-0.178, 0.295] on a [0,1]-domain surface). Clamping a cut pcurve to
1815    // the surface domain there tears it off the band: the branch-preserved
1816    // truncation bridge collapsed to a count=1 sliver hugging u=0 and the face
1817    // never split. Widen the clamp bound to domain ∪ trim-pcurve control hulls
1818    // (the hulls bound the boundary chains); a cut already inside the domain is
1819    // untouched, and OPEN directions keep the plain domain clamp. Escape hatch
1820    // BREP_FRAG_ENV_CLAMP=0.
1821    let (clamp_u, clamp_v) = {
1822        let mut clamp_u = u_domain;
1823        let mut clamp_v = v_domain;
1824        let (closed_u, closed_v) = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
1825        // NOTE (2026-09-16): this hatch's ONLY tamper guard,
1826        // `csg/fragment/tests.rs::seam_band_cut_chain_splits_periodic_face`, went
1827        // INERT when the march-window lift landed — that test now passes with this
1828        // hatch off, so nothing tamper-verifies this mechanism any more. Not that it
1829        // is untested: no other test NAMES this hatch.
1830        if (closed_u || closed_v) && std::env::var("BREP_FRAG_ENV_CLAMP").as_deref() != Ok("0") {
1831            for loop_record in &face.loops {
1832                for coedge in &loop_record.coedges {
1833                    for point in &coedge.pcurve.control_points {
1834                        if point.w.abs() <= 1e-300 {
1835                            continue;
1836                        }
1837                        if closed_u {
1838                            clamp_u[0] = clamp_u[0].min(point.x / point.w);
1839                            clamp_u[1] = clamp_u[1].max(point.x / point.w);
1840                        }
1841                        if closed_v {
1842                            clamp_v[0] = clamp_v[0].min(point.y / point.w);
1843                            clamp_v[1] = clamp_v[1].max(point.y / point.w);
1844                        }
1845                    }
1846                }
1847            }
1848        }
1849        (clamp_u, clamp_v)
1850    };
1851    profile.boundary += profile.lap(lap_start);
1852    for piece_id in active_pieces {
1853        let piece = pieces_by_id[&piece_id];
1854        let pcurve = pcurve_for(piece, face_key)?.clone();
1855        // SAG-BOUNDED CUT-CHAIN FIDELITY (t70 split-set asynchrony class).
1856        // `sample_chain`'s uniform sampling is knot-driven, so the SAME
1857        // imprint piece gets a 16-segment polyline on one support face and a
1858        // 92-segment one on the other (the counts follow each face's pcurve
1859        // knot structure, not the curvature). A coarse chord can then sag
1860        // MILLIMETRE-scale away from the true pcurve and invade a trim
1861        // region the true curve clears — t70: piece 55's chord on face
1862        // 1:405 sagged ~3e-3 into a hole corner the true pcurve misses by
1863        // 1.3e-3, so the arrangement carved phantom micro-junctions on that
1864        // face only, the two owners' split sets diverged (whole Imprint
1865        // edge vs a 4-piece Derived chain of the same locus), and every op
1866        // failed with one-use edges. Refining every cut chain until its
1867        // chords hug the true pcurve within the arrangement's own tolerance
1868        // makes both owners' polylines faithful to the ONE shared curve, so
1869        // their junction sets agree structurally (no proximity decisions
1870        // anywhere). Escape hatch: BREP_CHAIN_SAG_REFINE=0.
1871        let (mut points, original_flags) = sag_refine_chain(
1872            &pcurve,
1873            sample_chain(&pcurve)?,
1874            sampling_bound,
1875        )?;
1876        for point in &mut points {
1877            if point.x < clamp_u[0] {
1878                point.x = clamp_u[0] + arrangement_tolerance * 10.0;
1879            } else if point.x > clamp_u[1] {
1880                point.x = clamp_u[1] - arrangement_tolerance * 10.0;
1881            }
1882            if point.y < clamp_v[0] {
1883                point.y = clamp_v[0] + arrangement_tolerance * 10.0;
1884            } else if point.y > clamp_v[1] {
1885                point.y = clamp_v[1] - arrangement_tolerance * 10.0;
1886            }
1887        }
1888        let snap_endpoint_to_domain = |point: Vec2| {
1889            let candidates = [
1890                (
1891                    (point.x - u_domain[0]).abs(),
1892                    Vec2 {
1893                        x: u_domain[0],
1894                        y: point.y,
1895                    },
1896                ),
1897                (
1898                    (point.x - u_domain[1]).abs(),
1899                    Vec2 {
1900                        x: u_domain[1],
1901                        y: point.y,
1902                    },
1903                ),
1904                (
1905                    (point.y - v_domain[0]).abs(),
1906                    Vec2 {
1907                        x: point.x,
1908                        y: v_domain[0],
1909                    },
1910                ),
1911                (
1912                    (point.y - v_domain[1]).abs(),
1913                    Vec2 {
1914                        x: point.x,
1915                        y: v_domain[1],
1916                    },
1917                ),
1918            ];
1919            let nearest = candidates
1920                .into_iter()
1921                .min_by(|first, second| first.0.total_cmp(&second.0))
1922                .unwrap();
1923            if nearest.0 <= arrangement_tolerance * 50.0 {
1924                nearest.1
1925            } else {
1926                point
1927            }
1928        };
1929        let last = points.len() - 1;
1930        // A rim bridge's ends keep their own place (see RIM BRIDGE above): the
1931        // end inside the face is a distinct vertex a chart hair from the edge.
1932        // A cut's end at a vertex INSIDE the face a few 1e-5 of the period
1933        // from the seam (another body's seam vertex on a section that runs
1934        // along this face's seam) is inside the snap band, and snapping it
1935        // onto the domain edge moved that vertex to the seam: the section's
1936        // short piece then closed into a whole ring and the face never split.
1937        // With `BREP_NEAR_SEAM_CLOSED_RUN` an end snaps across a closed
1938        // direction (onto the seam) only when the edge's image is at least as
1939        // near the piece's own vertex as its place is. The end's own vertex is
1940        // the piece's vertex nearest its image (the piece's vertex order need
1941        // not follow its pcurve). A snap onto an OPEN domain edge is a rim, not
1942        // a seam, and always snaps: an offset's intersection vertex a few 1e-6
1943        // inside a quarter cylinder's rim is that rim's vertex, and keeping it
1944        // in place stranded the section's piece one-use beside the rim.
1945        let closed_axes = face.surface.closed_directions().unwrap_or((false, false));
1946        let keeps_vertex = |snapped: Vec2, original: Vec2, _vertex_id: u64| -> bool {
1947            let onto_seam = (closed_axes.0 && snapped.x != original.x) || (closed_axes.1 && snapped.y != original.y);
1948            if !crate::switch!("BREP_NEAR_SEAM_CLOSED_RUN", true) || !onto_seam {
1949                return true;
1950            }
1951            let (Ok(at), Ok(moved)) = (face.surface.evaluate(original.x, original.y), face.surface.evaluate(snapped.x, snapped.y)) else {
1952                return true;
1953            };
1954            let own = [piece.start_vertex_id, piece.end_vertex_id]
1955                .iter()
1956                .filter_map(|id| index.vertex_points.get(id))
1957                .min_by(|a, b| a.sub(at).length().total_cmp(&b.sub(at).length()));
1958            let keep = own.is_none_or(|vertex| moved.sub(*vertex).length() <= at.sub(*vertex).length());
1959            keep
1960        };
1961        // `BREP_FRAGMENT_EXACT_END_STAYS` (default on, `=0` restores): on a plane, a straight
1962        // cut's end is an exact vertex, not a marched end's slack. One that its
1963        // own vertex places a resolvable distance off the domain edge (more
1964        // than eight identity bands in model space) stays where it is: a box
1965        // turned a few 1e-6 rad has a corner edge piercing the other's face
1966        // 4e-6 inside its edge, and snapping that end onto the edge put the
1967        // vertex where the solid has none while its mates kept the true one.
1968        // A face read as one surface with a face of the other operand keeps the
1969        // snap: its pair's slivers are below resolution and its vertices are
1970        // read at the pair's band, not placed exactly.
1971        let straight_on_plane = exact_end_stays_on()
1972            && !index.cosurface_pairs.iter().any(|(first, _)| *first == face_key)
1973            && face.surface.is_affine().unwrap_or(false)
1974            && piece.curve.degree == 1
1975            && piece.curve.control_points.len() == 2;
1976        let exact_end_off_edge = |snapped: Vec2, original: Vec2, vertex_id: u64| -> bool {
1977            if !straight_on_plane || (snapped.x == original.x && snapped.y == original.y) {
1978                return false;
1979            }
1980            let (Some(vertex), Ok(moved)) = (index.vertex_points.get(&vertex_id), face.surface.evaluate(snapped.x, snapped.y)) else {
1981                return false;
1982            };
1983            let identity = crate::classification::surface_uv_band(&face.surface, original.x, original.y, 1e-7);
1984            let off = original.sub(snapped).length();
1985            off > identity * 8.0 && moved.sub(*vertex).length() > 8e-7
1986        };
1987        if !bridge_keys.contains(&format!("i:{}", piece.start_vertex_id)) {
1988            let snapped = snap_endpoint_to_domain(points[0]);
1989            if keeps_vertex(snapped, points[0], piece.start_vertex_id)
1990                && !exact_end_off_edge(snapped, points[0], piece.start_vertex_id)
1991            {
1992                points[0] = snapped;
1993            }
1994        }
1995        if !bridge_keys.contains(&format!("i:{}", piece.end_vertex_id)) {
1996            let snapped = snap_endpoint_to_domain(points[last]);
1997            if keeps_vertex(snapped, points[last], piece.end_vertex_id)
1998                && !exact_end_off_edge(snapped, points[last], piece.end_vertex_id)
1999            {
2000                points[last] = snapped;
2001            }
2002        }
2003        for point in &mut points {
2004            *point = rebase_point(*point);
2005        }
2006        // CUT-CHAIN PERIOD LIFT. A section's pcurve on a closed carrier is
2007        // drawn on the carrier's own period, but the boundary chains above can
2008        // sit a period away from it: an imported face whose seam edge is not
2009        // at the carrier's parameter origin carries rims split AT that origin,
2010        // so its loop hops the branch cut between coedges and the seam-hop
2011        // unwrap lays it out over [seam, seam + period] (the 2026-09-14 gear:
2012        // cone and fillet torus with seam edges at u = 1/2, boundary chains on
2013        // u ∈ [0.5, 1.5], section arcs on [0, 0.5] and [0.5, 1]). The arc a
2014        // period off never meets the band, the section never closes across the
2015        // face, the face stays one fragment and is kept or dropped whole — one
2016        // rim and the section ring then strand one-use. Every piece the imprint
2017        // attaches to a face has its midpoint inside that face's trim, so the
2018        // chain's image whose middle lies inside the band is the one the
2019        // arrangement must see; a whole-period shift is exact on a periodic
2020        // carrier. The chain is lifted only when its middle is OUTSIDE the band
2021        // and exactly one period image puts it inside, so a chain already
2022        // coherent with its band — every native face, every re-based band —
2023        // is untouched. The pcurve keeps the carrier's own period (the lift is
2024        // an arrangement coordinate, recorded on the chain for the partial-run
2025        // rescue). A lifted chain that still crosses a wall of the band crosses
2026        // the face's seam edge unsplit, and the face refuses by name. Escape
2027        // hatch `BREP_CUT_PERIOD_LIFT=0`.
2028        let mut lift = Vec2 { x: 0.0, y: 0.0 };
2029        if std::env::var("BREP_CUT_PERIOD_LIFT").as_deref() != Ok("0") {
2030            let closed = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
2031            for axis in 0..2 {
2032                let (is_closed, domain) = if axis == 0 { (closed.0, u_domain) } else { (closed.1, v_domain) };
2033                let [low, high] = band_hull[axis];
2034                let span = domain[1] - domain[0];
2035                if !is_closed || !(span > 0.0) || !(low < domain[0] || high > domain[1]) {
2036                    continue;
2037                }
2038                let coordinate = |point: &Vec2| if axis == 0 { point.x } else { point.y };
2039                let middle = coordinate(&points[points.len() / 2]);
2040                let inside = |value: f64| value > low && value < high;
2041                if inside(middle) {
2042                    continue;
2043                }
2044                let images: Vec<f64> = [-2.0, -1.0, 1.0, 2.0]
2045                    .into_iter()
2046                    .map(|periods| periods * span)
2047                    .filter(|shift| inside(middle + shift))
2048                    .collect();
2049                let [shift] = images[..] else {
2050                    continue;
2051                };
2052                let slack = arrangement_tolerance * 50.0;
2053                let (reach_low, reach_high) = points.iter().map(coordinate).fold(
2054                    (f64::INFINITY, f64::NEG_INFINITY),
2055                    |(lo, hi), value| (lo.min(value), hi.max(value)),
2056                );
2057                if reach_low + shift < low - slack || reach_high + shift > high + slack {
2058                    let [first, second] = piece.support_faces;
2059                    return Err(KernelRefusal::internal(
2060                        KernelStage::Fragment,
2061                        "fragment.face_split",
2062                        format!(
2063                            "fragment_face: section piece {piece_id} of faces {}:{} x {}:{} crosses \
2064                             the seam wall of face {}:{}'s unwrapped band ({} in [{low:.9}, {high:.9}], \
2065                             the section's period image [{:.9}, {:.9}]) without a vertex there",
2066                            first.operand,
2067                            first.face_id,
2068                            second.operand,
2069                            second.face_id,
2070                            operand,
2071                            face.id,
2072                            if axis == 0 { "u" } else { "v" },
2073                            reach_low + shift,
2074                            reach_high + shift,
2075                        ),
2076                    ));
2077                }
2078                for point in &mut points {
2079                    if axis == 0 {
2080                        point.x += shift;
2081                    } else {
2082                        point.y += shift;
2083                    }
2084                }
2085                if axis == 0 {
2086                    lift.x = shift;
2087                } else {
2088                    lift.y = shift;
2089                }
2090                if env_read!("BREP_DEBUG_FRAG")
2091                    .map(|value| value == face.id.to_string())
2092                    .unwrap_or(false)
2093                {
2094                    eprintln!(
2095                        "  period lift: face {} cut p{piece_id} {} {shift:+} into the band [{low:.6},{high:.6}]",
2096                        face.id,
2097                        if axis == 0 { "u" } else { "v" }
2098                    );
2099                }
2100            }
2101        }
2102        // Guard runs on the FINAL (clamped/snapped/rebased) coordinates — the
2103        // same frame the boundary chains were sampled into — so crossing
2104        // parity is measured exactly where the arrangement would see it.
2105        points = enforce_boundary_crossing_parity(
2106            points,
2107            &original_flags,
2108            &boundary_segments,
2109            arrangement_tolerance,
2110            env_read!("BREP_DEBUG_FRAG")
2111                .map(|value| value == face.id.to_string())
2112                .unwrap_or(false),
2113            face.id,
2114        );
2115        let start_point = index
2116            .vertex_points
2117            .get(&piece.start_vertex_id)
2118            .copied()
2119            .ok_or_else(|| KernelRefusal::internal(KernelStage::Fragment, "fragment.face_split", "fragment_face: missing imprint start vertex"))?;
2120        let end_point = index
2121            .vertex_points
2122            .get(&piece.end_vertex_id)
2123            .copied()
2124            .ok_or_else(|| KernelRefusal::internal(KernelStage::Fragment, "fragment.face_split", "fragment_face: missing imprint end vertex"))?;
2125        add_chain(
2126            points,
2127            ChainSource::Cut {
2128                piece_id,
2129                pcurve,
2130                lift,
2131                curve: trimmed_curve(&piece.curve, piece.t0, piece.t1)?,
2132                shared_ring: piece.shared_edge.filter(|_| {
2133                    piece
2134                        .curve
2135                        .evaluate(piece.t0)
2136                        .ok()
2137                        .zip(piece.curve.evaluate(piece.t1).ok())
2138                        .is_some_and(|(a, b)| a.sub(b).length() <= 1e-6)
2139                }),
2140            },
2141            format!("i:{}", piece.start_vertex_id),
2142            start_point,
2143            format!("i:{}", piece.end_vertex_id),
2144            end_point,
2145            false,
2146        )?;
2147    }
2148    drop(add_chain);
2149
2150    // POLE-GAP BRIDGE (single-loop periodic cap; corpus fixture 25 cube-pierce).
2151    // A face closed in one parameter direction can carry a DEGENERATE pole
2152    // iso-line — a whole domain-edge row of one parameter collapsing to a
2153    // single 3D point (the dome apex v2 at v=0 here). The imported trim
2154    // represents the pole with a partial arc plus a degenerate self-edge that
2155    // stop SHORT of the opposite seam foot, so the outer boundary is OPEN in
2156    // the flat UV chart at the pole: the two seam feet sit a FRACTION of a
2157    // period apart (never a whole period), so no covering-strip period-image
2158    // can ever join them — this case is structurally outside the seam-image
2159    // loops machinery above. When a section cut then splits the cap,
2160    // `arrange_segments` closes only the lens region that avoids the pole and
2161    // DROPS the seam-and-pole-spanning outside region: the cap fragments to 1
2162    // not 2, its section + outer-rim edges strand one-use (union/subtract fail
2163    // `S=1 genus=1`), while intersect keeps the lens and succeeds. Close the
2164    // boundary in-chart: pair the two dangling (odd-incidence) boundary
2165    // endpoints that are UV images of the SAME solid vertex (structural
2166    // identity via `vertex_images`, never proximity clustering), VERIFY the
2167    // straight UV connector between them is degenerate (every sample collapses
2168    // to one 3D point — a genuine pole, not a real seam that would cross
2169    // material), and add a bridge chain that REUSES an existing degenerate
2170    // pole edge as its source. The reused edge is 3D-zero-length, so the
2171    // minted coedge is s==e and exempt from the two-use rule — no new edge is
2172    // introduced (the zero-regression reuse pattern), and the outside fragment
2173    // reproduces the original cap loop's own pole/seam structure. A
2174    // cleanly-closing boundary has no odd node and is byte-identical untouched;
2175    // a genuine (non-degenerate) seam gap fails the degeneracy check and is
2176    // left alone (the safe direction). Escape hatch: BREP_POLE_GAP_BRIDGE=0.
2177    let pole_gap_closed = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
2178    if (pole_gap_closed.0 || pole_gap_closed.1)
2179        && std::env::var("BREP_POLE_GAP_BRIDGE").as_deref() != Ok("0")
2180    {
2181        // A degenerate pole iso-line only exists on a surface closed in the
2182        // seam direction; a non-periodic face never reaches this block and is
2183        // byte-identical untouched.
2184        //
2185        // `add_chain` canonicalizes shared endpoints to a bit-identical `Vec2`,
2186        // so a TIGHT epsilon groups exactly the coincident nodes and never
2187        // over-merges two distinct nearby vertices (which would corrupt the
2188        // incidence parity on a small face).
2189        let node_tol = arrangement_tolerance * 10.0;
2190        // Incidence over BOUNDARY chain endpoints only — the pole gap is a
2191        // property of the trim boundary, and cut chains anchor to it elsewhere.
2192        let mut nodes: Vec<(Vec2, usize)> = Vec::new();
2193        for chain in &chains {
2194            if !matches!(chain.source, ChainSource::Boundary { .. }) {
2195                continue;
2196            }
2197            for point in [chain.start, chain.end] {
2198                if let Some(entry) = nodes.iter_mut().find(|(q, _)| q.sub(point).length() <= node_tol)
2199                {
2200                    entry.1 += 1;
2201                } else {
2202                    nodes.push((point, 1));
2203                }
2204            }
2205        }
2206        // Odd incidence => the boundary is UV-open at that endpoint.
2207        let odd: Vec<Vec2> = nodes
2208            .iter()
2209            .filter(|(_, count)| count % 2 == 1)
2210            .map(|(point, _)| *point)
2211            .collect();
2212        // Each odd node's owning solid vertex: the canonical image lists in
2213        // `vertex_images` are keyed "b:{operand}:{vertex_id}".
2214        let vertex_of = |point: Vec2| -> Option<u64> {
2215            vertex_images.iter().find_map(|(key, images)| {
2216                images
2217                    .iter()
2218                    .any(|image| image.sub(point).length() <= node_tol)
2219                    .then(|| key.rsplit(':').next().and_then(|id| id.parse::<u64>().ok()))
2220                    .flatten()
2221            })
2222        };
2223        let mut by_vertex: HashMap<u64, Vec<Vec2>> = HashMap::default();
2224        for point in &odd {
2225            if let Some(vertex_id) = vertex_of(*point) {
2226                by_vertex.entry(vertex_id).or_default().push(*point);
2227            }
2228        }
2229        // Forward-evaluate only (the projector is a poisoned oracle; evaluate
2230        // is exact). A degenerate 3D curve collapses to a point over its span.
2231        let curve_degenerate = |curve: &NurbsCurve| -> bool {
2232            let Ok(domain) = curve.domain() else {
2233                return false;
2234            };
2235            let Ok(base) = curve.evaluate(domain[0]) else {
2236                return false;
2237            };
2238            [0.5, 1.0].iter().all(|fraction| {
2239                curve
2240                    .evaluate(domain[0] + (domain[1] - domain[0]) * fraction)
2241                    .map(|point| point.sub(base).length() <= 1e-5)
2242                    .unwrap_or(false)
2243            })
2244        };
2245        for (vertex_id, images) in by_vertex {
2246            // A pole slit unclosed in exactly one place has EXACTLY two dangling
2247            // images of its apex vertex; anything else is not this class.
2248            if images.len() != 2 {
2249                continue;
2250            }
2251            let (a, b) = (images[0], images[1]);
2252            // The straight UV connector must be a degenerate iso-line: every
2253            // sample collapses to one 3D point. This is the gate that keeps a
2254            // real seam (whose connector crosses material) from being bridged.
2255            let mut base: Option<Vec3> = None;
2256            let mut degenerate = true;
2257            for step in 0..=8 {
2258                let fraction = step as f64 / 8.0;
2259                let uv = a.add(b.sub(a).scale(fraction));
2260                match face.surface.evaluate(uv.x, uv.y) {
2261                    Ok(point) => match base {
2262                        None => base = Some(point),
2263                        Some(reference) => {
2264                            if point.sub(reference).length() > 1e-5 {
2265                                degenerate = false;
2266                                break;
2267                            }
2268                        }
2269                    },
2270                    Err(_) => {
2271                        degenerate = false;
2272                        break;
2273                    }
2274                }
2275            }
2276            if !degenerate {
2277                continue;
2278            }
2279            // Reuse an existing degenerate pole edge's source (its 3D curve is a
2280            // point, so the minted coedge is s==e and validation-exempt).
2281            let Some(source) = chains.iter().find_map(|chain| match &chain.source {
2282                ChainSource::Boundary { coedge, curve }
2283                    if chain.start.sub(chain.end).length() <= node_tol
2284                        && chain.count <= 1
2285                        && (chain.start.sub(a).length() <= node_tol
2286                            || chain.start.sub(b).length() <= node_tol)
2287                        && curve_degenerate(curve) =>
2288                {
2289                    Some(ChainSource::Boundary {
2290                        coedge: coedge.clone(),
2291                        curve: curve.clone(),
2292                    })
2293                }
2294                _ => None,
2295            }) else {
2296                continue;
2297            };
2298            let chain_index = chains.len();
2299            segments.push(Segment2 {
2300                a,
2301                b,
2302                tag: segment_tag(chain_index, 0),
2303            });
2304            chains.push(Chain {
2305                source,
2306                count: 1,
2307                start: a,
2308                end: b,
2309                segments: vec![(a, b)],
2310            });
2311            boundary_segments.push((a, b));
2312            if env_read!("BREP_DEBUG_FRAG")
2313                .map(|value| value == face.id.to_string())
2314                .unwrap_or(false)
2315            {
2316                eprintln!(
2317                    "  pole-gap bridge: face {} vertex {vertex_id} joins \
2318                     ({:.6},{:.6})->({:.6},{:.6}) along a degenerate iso-line",
2319                    face.id, a.x, a.y, b.x, b.y
2320                );
2321            }
2322        }
2323    }
2324
2325    // A cut chain that coincides with a boundary chain cannot split the
2326    // interior — the face's own edge already bounds it there. Worse, the
2327    // duplicate overlapping segments corrupt arrangement cycle extraction
2328    // and silently swallow every region that touches the overlap (seen when
2329    // endpoint polishing snaps a face/face intersection line onto a
2330    // near-coincident boundary edge of the same face). Drop such cuts
2331    // before arranging.
2332    let coincidence_tolerance = arrangement_tolerance * 50.0;
2333    let point_segment_distance = |point: Vec2, a: Vec2, b: Vec2| -> f64 {
2334        let segment = b.sub(a);
2335        let length_squared = segment.dot(segment);
2336        if length_squared <= 1e-30 {
2337            return point.sub(a).length();
2338        }
2339        let parameter = (point.sub(a).dot(segment) / length_squared).clamp(0.0, 1.0);
2340        point.sub(a.add(segment.scale(parameter))).length()
2341    };
2342    let near_chain = |point: Vec2, chain: &Chain, tolerance: f64| {
2343        chain
2344            .segments
2345            .iter()
2346            .any(|(a, b)| point_segment_distance(point, *a, *b) <= tolerance)
2347    };
2348    // A cut coincides with a boundary only if its INTERIOR follows the same
2349    // path, not merely its endpoints. A single-segment straight cut whose two
2350    // endpoints happen to land on a CURVED boundary edge's endpoints (a
2351    // cap∩cap intersection chord spanning a curved rim arc — the missing
2352    // cone-cap split behind the curved-primitive open-edge booleans) shares
2353    // only its endpoints and cuts clean across the interior; dropping it as a
2354    // duplicate loses the region it carves. So also require the segment
2355    // MIDPOINTS to lie near the boundary. The midpoint test runs at a looser
2356    // threshold than the endpoint match: a genuinely-coincident curved cut's
2357    // polyline midpoints carry their own chord sag (order 1× tolerance), which
2358    // must still count as near, while a chord spanning a curved arc departs by
2359    // the arc's sagitta (orders of magnitude larger) and is correctly kept. On
2360    // the box path both edges are straight, so two shared endpoints force the
2361    // midpoint onto the boundary and the drop is unchanged.
2362    let midpoint_tolerance = coincidence_tolerance * 8.0;
2363    // CORNER-CHORD VETO. The endpoint match above admits a cut whose endpoint
2364    // sits up to `coincidence_tolerance` (50x arr_tol) from the boundary
2365    // chain's endpoint. When a section threads through a MODEL CORNER where two
2366    // boundary edges (legs) meet at a shared vertex, the section arm on the
2367    // sliver face between them is the HYPOTENUSE of a tiny right triangle whose
2368    // short leg can be well under that slack (t634: the torus crosses a 3-face
2369    // corner of 00000327; on the sliver face the arm's start is 31x arr_tol
2370    // from the matched leg's start, and the hypotenuse midpoint is ~15x arr_tol
2371    // off the leg — both under the 50x/400x tolerances). The old test dropped
2372    // that arm as a "duplicate" of one leg, so the tiny corner region was never
2373    // carved on the sliver face while the mate operand kept the arm -> the
2374    // shared section edge went one-use (invalid genus). A genuine corner chord
2375    // is distinguishable STRUCTURALLY, not by tolerance: its endpoint coincides
2376    // (at NODE scale = the arrangement's own find_node snap) with a real,
2377    // DISTINCT boundary vertex — proof it terminates at a 0-cell of its own,
2378    // spanning two legs, rather than retracing this one edge. A true retrace
2379    // (box duplicate, cap-rim chord) has endpoints AT the matched chain's ends
2380    // (gap ~0), so the veto never triggers for it. Hatch restores the old drop.
2381    profile.cuts += profile.lap(lap_start);
2382    let corner_veto_enabled = std::env::var("BREP_DUP_DROP_CORNER_VETO")
2383        .map(|value| value != "0")
2384        .unwrap_or(true);
2385    let node_tolerance = arrangement_tolerance;
2386    let terminates_at_distinct_boundary_vertex = |cut_end: Vec2, matched_end: Vec2| -> bool {
2387        cut_end.sub(matched_end).length() > node_tolerance
2388            && chains.iter().any(|other| {
2389                matches!(other.source, ChainSource::Boundary { .. })
2390                    && (other.start.sub(cut_end).length() <= node_tolerance
2391                        || other.end.sub(cut_end).length() <= node_tolerance)
2392            })
2393    };
2394    let debug_drop = env_read!("BREP_DEBUG_FRAG")
2395        .map(|value| value == face.id.to_string())
2396        .unwrap_or(false);
2397    // MICRO-BOUNDARY SKIP (t316). A boundary chain SHORTER than the coincidence
2398    // tolerance cannot serve as a duplication reference: its two endpoints are
2399    // indistinguishable at this tolerance, so the orientation-agnostic endpoint
2400    // match collapses and a cut that merely touches ONE of its ends spuriously
2401    // "matches" BOTH. That wrongly drops a junction-bridge micro-cut spanning a
2402    // weld-scale vertex cluster (t316: cut p38, the ~0.004mm bridge from a
2403    // section terminus C to the plate-rim node C', gets dropped against e99 — a
2404    // ~0.008mm rim segment shorter than the 0.07mm coincidence tolerance —
2405    // stranding the whole b-poke bottom-cap sliver one-use). The genuine target
2406    // (the tangent-wall cap section, coincident with a full-length box edge ≫
2407    // tolerance) is untouched. Independent of the corner-chord veto below: this
2408    // guard disqualifies a sub-tolerance BOUNDARY as a reference, that one spares
2409    // a corner-spanning CUT. Hatch `BREP_DUP_CUT_MICRO_BOUNDARY=0` restores the
2410    // old, length-agnostic reference test.
2411    let micro_boundary_skip = std::env::var("BREP_DUP_CUT_MICRO_BOUNDARY").as_deref() != Ok("0");
2412    let boundary_extent = |boundary: &Chain| -> f64 {
2413        boundary
2414            .segments
2415            .iter()
2416            .map(|(a, b)| b.sub(*a).length())
2417            .sum()
2418    };
2419    // POLE-COLLAPSED ENDS. A pole is a whole row of the chart at one 3D
2420    // point, so two chain ends on its degenerate boundary chain are one point
2421    // however far apart their u reads, and near the pole a chart distance says
2422    // nothing about the 3D one. The revolve_pole union's G2 end cap (a 93 deg
2423    // sector with its apex on the axis) is cut by the wedge's two side planes
2424    // along its own radius edges: the sections are those edges' sub-arcs to
2425    // 1e-15, ending 3.2e-6 short of the apex. Their pcurves follow u = 1 and
2426    // u = 0 and then swing to one u = 0.443 at the pole; evaluated on the cap
2427    // a chain stands 7.4e-4 off its radius at v = 0.99976. The endpoint test
2428    // read a gap of 0.557 and kept both cuts, and the arrangement carved two
2429    // slivers, each bounded by a radius edge and its own weld copy. One was
2430    // kept in the union and the coplanar merge refused its genus; the
2431    // intersection refused with one-use edges. So when a chain end and a
2432    // boundary end both lie on one degenerate boundary chain they coincide,
2433    // and the cut is held to the boundary in 3D, section curve against edge
2434    // curve, within the coincidence tolerance carried along the boundary by
2435    // its own stretch (3D length over chart length). Escape hatch
2436    // `BREP_DUP_DROP_POLE=0`.
2437    let pole_ends = std::env::var("BREP_DUP_DROP_POLE").as_deref() != Ok("0");
2438    let degenerate_chains: Vec<usize> = chains
2439        .iter()
2440        .enumerate()
2441        .filter(|(_, chain)| match &chain.source {
2442            ChainSource::Boundary { coedge, .. } => solid
2443                .edges
2444                .iter()
2445                .any(|edge| edge.id == coedge.edge_id && edge.degenerate),
2446            ChainSource::Cut { .. } => false,
2447        })
2448        .map(|(index, _)| index)
2449        .collect();
2450    let on_one_pole = |a: Vec2, b: Vec2| -> bool {
2451        degenerate_chains.iter().any(|&pole| {
2452            near_chain(a, &chains[pole], coincidence_tolerance)
2453                && near_chain(b, &chains[pole], coincidence_tolerance)
2454        })
2455    };
2456    let coincident_in_space = |cut: &Chain, boundary: &Chain, weld_scale: bool| -> bool {
2457        let ChainSource::Boundary { curve, coedge } = &boundary.source else {
2458            return false;
2459        };
2460        let ChainSource::Cut { curve: section, piece_id, .. } = &cut.source else {
2461            return false;
2462        };
2463        let Ok([start, end]) = section.domain() else {
2464            return false;
2465        };
2466        let mut chart_length = 0.0;
2467        let mut space_length = 0.0;
2468        for (a, b) in &boundary.segments {
2469            let (Ok(pa), Ok(pb)) = (face.surface.evaluate(a.x, a.y), face.surface.evaluate(b.x, b.y)) else {
2470                return false;
2471            };
2472            chart_length += b.sub(*a).length();
2473            space_length += pb.sub(pa).length();
2474        }
2475        if chart_length <= 0.0 || space_length <= 0.0 {
2476            return false;
2477        }
2478        let copy_boundary = index.pieces_by_id.get(piece_id).is_some_and(|piece| {
2479            boundary_has_cosurface_partner(solid, face_key, coedge.edge_id, piece, index)
2480                || (cosurface_corner_copy_on()
2481                    && boundary_is_cosurface_corner(solid, face_key, coedge.edge_id, piece, index))
2482        });
2483        let bound = if weld_scale {
2484            if copy_boundary { crate::tolerance::WELD_FLOOR } else { 1e-7 }
2485        } else {
2486            coincidence_tolerance * space_length / chart_length
2487        };
2488        let stations = cut.segments.len().max(16);
2489        (0..=stations).all(|index| {
2490            section
2491                .evaluate(start + (end - start) * index as f64 / stations as f64)
2492                .ok()
2493                .and_then(|at| crate::project_point_to_curve(curve, at).ok())
2494                .is_some_and(|projection| projection.distance <= bound)
2495        })
2496    };
2497    // [`coincident_in_space`] at the weld band, and the reverse: every station
2498    // of the boundary's curve lies within the same band of the cut's, so the
2499    // two are one curve, not a cut that merely stays near part of the boundary.
2500    // Only where the boundary has the other operand's coincident copy beside it
2501    // (the weld band's own condition).
2502    let follows_copy_both_ways = |cut: &Chain, boundary: &Chain| -> bool {
2503        let (ChainSource::Boundary { curve, coedge }, ChainSource::Cut { curve: section, piece_id, .. }) = (&boundary.source, &cut.source) else {
2504            return false;
2505        };
2506        let copy = index.pieces_by_id.get(piece_id).is_some_and(|piece| {
2507            boundary_has_cosurface_partner(solid, face_key, coedge.edge_id, piece, index)
2508        });
2509        if !copy || !coincident_in_space(cut, boundary, true) {
2510            return false;
2511        }
2512        let Ok([start, end]) = curve.domain() else {
2513            return false;
2514        };
2515        let stations = boundary.segments.len().max(16);
2516        let mut distances = Vec::with_capacity(stations + 1);
2517        for station in 0..=stations {
2518            let Some(distance) = curve
2519                .evaluate(start + (end - start) * station as f64 / stations as f64)
2520                .ok()
2521                .and_then(|at| crate::project_point_to_curve(section, at).ok())
2522                .map(|projection| projection.distance)
2523            else {
2524                return false;
2525            };
2526            if distance > crate::tolerance::WELD_FLOOR {
2527                return false;
2528            }
2529            distances.push(distance);
2530        }
2531        // A copy offset to one side all along (two coaxial rims a weld floor
2532        // apart) bounds a real strip, however thin: it is a cut. The rim again
2533        // turned or moved by round-off crosses it, coming to it inside: there
2534        // the nearest station reads well under the farthest.
2535        let interior = &distances[stations / 20 + 1..stations - stations / 20];
2536        let (nearest, farthest) = interior
2537            .iter()
2538            .fold((f64::INFINITY, 0.0f64), |(low, high), &distance| (low.min(distance), high.max(distance)));
2539        farthest <= 1e-7 || nearest <= 0.1 * farthest
2540    };
2541    let mut dropped_chains = HashSet::default();
2542    for (index, chain) in chains.iter().enumerate() {
2543        if !matches!(chain.source, ChainSource::Cut { .. }) {
2544            continue;
2545        }
2546        let mut matched_boundary: Option<usize> = None;
2547        for (boundary_index, boundary) in chains.iter().enumerate() {
2548            if !matches!(boundary.source, ChainSource::Boundary { .. }) {
2549                continue;
2550            }
2551            // t316: a sub-tolerance micro-boundary cannot be a duplication
2552            // reference — its endpoints collapse at this tolerance, so a cut that
2553            // merely touches one end spuriously matches both. Skip it as a
2554            // candidate (never selectable as `matched_boundary`).
2555            if micro_boundary_skip && boundary_extent(boundary) <= coincidence_tolerance {
2556                continue;
2557            }
2558            let forward = boundary.start.sub(chain.start).length() <= coincidence_tolerance
2559                && boundary.end.sub(chain.end).length() <= coincidence_tolerance;
2560            let reversed = boundary.start.sub(chain.end).length() <= coincidence_tolerance
2561                && boundary.end.sub(chain.start).length() <= coincidence_tolerance;
2562            let same_end = |a: Vec2, b: Vec2| a.sub(b).length() <= coincidence_tolerance || on_one_pole(a, b);
2563            let (forward, reversed, at_pole) = if forward || reversed || !pole_ends || degenerate_chains.is_empty() {
2564                (forward, reversed, false)
2565            } else {
2566                let forward = same_end(boundary.start, chain.start) && same_end(boundary.end, chain.end);
2567                let reversed = same_end(boundary.start, chain.end) && same_end(boundary.end, chain.start);
2568                (forward, reversed, true)
2569            };
2570            if !(forward || reversed) {
2571                continue;
2572            }
2573            let interior_coincident = if at_pole {
2574                coincident_in_space(chain, boundary, false)
2575            } else {
2576                chain.segments.iter().all(|(a, b)| {
2577                    near_chain(*a, boundary, coincidence_tolerance)
2578                        && near_chain(*b, boundary, coincidence_tolerance)
2579                        && near_chain(a.add(*b).scale(0.5), boundary, midpoint_tolerance)
2580                })
2581            };
2582            // DUPLICATE CUT BY SPACE (`BREP_DUP_CUT_SPACE_NOMINATION`, default
2583            // on, `=0` restores): a cut whose ends match the boundary's and that follows it in
2584            // model space at every station ([`coincident_in_space`] at the weld
2585            // band, both ways: the boundary's stations lie on the cut too, and
2586            // only along a boundary with the other operand's coincident copy
2587            // beside it, and only a copy that comes to the boundary inside, not
2588            // one offset to one side all along) is nominated even where the
2589            // chart test above misses. That
2590            // test measures the cut's samples, on the true curve, against the
2591            // boundary's chords, whose sag can exceed its band, so it passed or
2592            // failed by where the cut happened to be sampled: spline-prisms
2593            // 5047's moved copy (b's rim 4.7e-6 off a's top rim, translated)
2594            // kept the rim as a cut and split the cap into slivers.
2595            let interior_coincident = interior_coincident
2596                || (dup_cut_space_nomination_enabled() && follows_copy_both_ways(chain, boundary));
2597            if !interior_coincident {
2598                continue;
2599            }
2600            // UV proximity only nominates a duplicate. A real cap lens can
2601            // be narrower than that chart-space search band while its two
2602            // arcs are distinct in 3D. Discard the cut only when the section
2603            // follows the boundary within model identity, not the repair band.
2604            // Endpoint anchoring can turn a very short cut and boundary into
2605            // the SAME chart segment even when their pre-anchor 3D curves
2606            // differ. Such identical constraints cannot enclose a region;
2607            // keeping both would corrupt arrangement cycle extraction.
2608            let identical_segment = chain.segments.len() == 1
2609                && boundary.segments.len() == 1
2610                && ((chain.start.sub(boundary.start).length() <= node_tolerance
2611                    && chain.end.sub(boundary.end).length() <= node_tolerance)
2612                    || (chain.start.sub(boundary.end).length() <= node_tolerance
2613                        && chain.end.sub(boundary.start).length() <= node_tolerance));
2614            if !identical_segment
2615                && std::env::var("BREP_DUP_CUT_GEOMETRY").as_deref() != Ok("0")
2616                && !coincident_in_space(chain, boundary, true)
2617            {
2618                continue;
2619            }
2620            if corner_veto_enabled {
2621                // Pair each cut endpoint with the boundary endpoint it matched.
2622                let (bnd_for_start, bnd_for_end) = if forward {
2623                    (boundary.start, boundary.end)
2624                } else {
2625                    (boundary.end, boundary.start)
2626                };
2627                if terminates_at_distinct_boundary_vertex(chain.start, bnd_for_start)
2628                    || terminates_at_distinct_boundary_vertex(chain.end, bnd_for_end)
2629                {
2630                    continue;
2631                }
2632            }
2633            matched_boundary = Some(boundary_index);
2634            break;
2635        }
2636        if let Some(boundary_index) = matched_boundary {
2637            if debug_drop {
2638                let boundary = &chains[boundary_index];
2639                eprintln!(
2640                    "  drop cut chain {} as duplicate of boundary chain {} (endpoint gaps {:.3e}/{:.3e})",
2641                    index,
2642                    boundary_index,
2643                    boundary.start.sub(chain.start).length(),
2644                    boundary.end.sub(chain.end).length(),
2645                );
2646            }
2647            dropped_chains.insert(index);
2648        }
2649    }
2650    if !dropped_chains.is_empty() {
2651        segments.retain(|segment| {
2652            tag_chain(&segment.tag)
2653                .map(|chain| !dropped_chains.contains(&(chain as usize)))
2654                .unwrap_or(true)
2655        });
2656    }
2657
2658    let debug = env_read!("BREP_DEBUG_FRAG")
2659        .map(|value| value == face.id.to_string())
2660        .unwrap_or(false);
2661    if debug {
2662        eprintln!(
2663            "fragment_face {}: domain u={:?} v={:?} arr_tol={:.3e} chains={} segments={}",
2664            face.id,
2665            u_domain,
2666            v_domain,
2667            arrangement_tolerance,
2668            chains.len(),
2669            segments.len()
2670        );
2671        for (index, chain) in chains.iter().enumerate() {
2672            let kind = match &chain.source {
2673                ChainSource::Boundary { coedge, .. } => format!("boundary e{}", coedge.edge_id),
2674                ChainSource::Cut { piece_id, .. } => format!("cut p{piece_id}"),
2675            };
2676            eprintln!(
2677                "  chain {index} {kind} count={} start=({:.9},{:.9}) end=({:.9},{:.9})",
2678                chain.count, chain.start.x, chain.start.y, chain.end.x, chain.end.y
2679            );
2680        }
2681    }
2682    // TRIPLE-POINT CUT-CHAIN BRIDGE (imported-geometry corner rescue).
2683    // Two SSI cut curves that meet at a triple point (two faces of one operand
2684    // both crossing a single face of the other) can be marched to endpoints that
2685    // DISAGREE by more than arr_tol when the operand's shared edge carries an
2686    // imported edge<->vertex gap — the imprint then mints TWO vertices for the
2687    // one corner, so the cut chain is BROKEN there. A broken cut cannot separate
2688    // the domain: the arrangement returns one region covering the whole face, the
2689    // face is classified by a single test point and wrongly dropped, and its
2690    // neighbours' shared SSI edges are stranded one-use (non-integral genus).
2691    // Reconnect a pair of cut-chain endpoints that BOTH dangle in the interior
2692    // (each neither on a domain boundary nor meeting any other chain endpoint)
2693    // and whose chains are EACH anchored at their other end, by snapping them to
2694    // their midpoint. Gated on the dangling-anchored-pair precondition, which
2695    // only a broken cut produces, so a face whose cuts already connect (every
2696    // currently-succeeding fragmentation) is never touched.
2697    if chains.iter().any(|c| matches!(c.source, ChainSource::Cut { .. })) {
2698        let endpoints: Vec<(usize, bool, Vec2)> = chains
2699            .iter()
2700            .enumerate()
2701            .flat_map(|(i, c)| [(i, false, c.start), (i, true, c.end)])
2702            .collect();
2703        let anchored = |chain: usize, point: Vec2| -> bool {
2704            boundary_side(point).is_some()
2705                || endpoints.iter().any(|(other_chain, _, other_point)| {
2706                    *other_chain != chain
2707                        && other_point.sub(point).length() <= junction_radius
2708                })
2709        };
2710        // Interior cut endpoints with an anchored far end are the loose ends of
2711        // an almost-through cut. Only these are bridge candidates.
2712        //
2713        // OVERSHOOT-STUB EXCLUSION (offset-shell triple junctions). A pairwise
2714        // section between offset carriers is clipped to the offset IMAGE of the
2715        // source trims, which can extend PAST the true junction with a third
2716        // carrier's section instead of stopping at it (O.S14: the plane×cylinder
2717        // line runs to the source cone∩cylinder circle image at y=100/13 while
2718        // the plane×cone section crosses it ~0.3 earlier at the real offset
2719        // junction). Such a chain is already CONNECTED into the cut graph:
2720        // arrange_segments splits both chains at the crossing node and its
2721        // degree-1 pruning drops the overshoot stub beyond it, and build_loop
2722        // emits the surviving partial runs as Derived sub-curves. The stub's
2723        // dangling endpoint is therefore NOT a broken-junction loose end —
2724        // bridging it would drag a chain end to a midpoint off the section
2725        // (a wrong patch) and the 3D gate would refuse a face the arrangement
2726        // handles exactly. Exclude an endpoint from bridge candidacy when its
2727        // chain intersects another CUT chain at a point interior to the chain
2728        // (beyond the junction radius of both its endpoints — an intersection
2729        // AT the far anchor is the ordinary shared-junction meeting and must
2730        // keep the endpoint eligible, which preserves the imported-geometry
2731        // broken-cut rescue: those chains stop SHORT of each other and have no
2732        // crossing at all).
2733        let cut_chain_has_interior_crossing = |i: usize| -> bool {
2734            let chain = &chains[i];
2735            chains.iter().enumerate().any(|(j, other)| {
2736                // A boundary-duplicate chain was dropped from the arrangement's
2737                // segment set; a crossing with it would not materialize a node.
2738                if j == i
2739                    || dropped_chains.contains(&j)
2740                    || !matches!(other.source, ChainSource::Cut { .. })
2741                {
2742                    return false;
2743                }
2744                chain.segments.iter().any(|&(a0, a1)| {
2745                    other.segments.iter().any(|&(b0, b1)| {
2746                        let Some([t, _]) = crate::arrangement::segment_intersection(
2747                            a0,
2748                            a1,
2749                            b0,
2750                            b1,
2751                            arrangement_tolerance,
2752                        ) else {
2753                            return false;
2754                        };
2755                        let crossing = a0.add(a1.sub(a0).scale(t));
2756                        crossing.sub(chain.start).length() > junction_radius
2757                            && crossing.sub(chain.end).length() > junction_radius
2758                    })
2759                })
2760            })
2761        };
2762        let boundary_anchor = bridge_boundary_t_junction_anchor_enabled();
2763        let lies_on_another_cut_run = |i: usize, point: Vec2| -> bool {
2764            bridge_t_junction_anchor_enabled()
2765                && chains.iter().enumerate().any(|(j, other)| {
2766                    j != i
2767                        && !dropped_chains.contains(&j)
2768                        && (boundary_anchor || matches!(other.source, ChainSource::Cut { .. }))
2769                        && other.segments.iter().any(|&(a, b)| {
2770                            let along = b.sub(a);
2771                            let span = along.dot(along);
2772                            let t = if span > 0.0 {
2773                                (point.sub(a).dot(along) / span).clamp(0.0, 1.0)
2774                            } else {
2775                                0.0
2776                            };
2777                            a.add(along.scale(t)).sub(point).length() <= arrangement_tolerance
2778                        })
2779                })
2780        };
2781        let mut loose: Vec<(usize, bool, Vec2)> = Vec::new();
2782        for (i, c) in chains.iter().enumerate() {
2783            if !matches!(c.source, ChainSource::Cut { .. }) {
2784                continue;
2785            }
2786            for (is_end, this, other) in [(false, c.start, c.end), (true, c.end, c.start)] {
2787                if !anchored(i, this) && anchored(i, other) {
2788                    if lies_on_another_cut_run(i, this) {
2789                        if debug {
2790                            eprintln!("  cut chain {i} end {} is a T-junction on another chain's run", if is_end { "end" } else { "start" });
2791                        }
2792                        continue;
2793                    }
2794                    if cut_chain_has_interior_crossing(i) {
2795                        if debug {
2796                            eprintln!(
2797                                "  cut chain {i} loose {} excluded from junction bridging — \
2798                                 the chain crosses another cut chain mid-run; arrangement \
2799                                 pruning owns the overshoot stub",
2800                                if is_end { "end" } else { "start" },
2801                            );
2802                        }
2803                        continue;
2804                    }
2805                    loose.push((i, is_end, this));
2806                }
2807            }
2808        }
2809        // A triple-point disagreement on imported geometry runs a few 1e-4 (the
2810        // edge<->vertex gap), well under a percent of the face diagonal; bound the
2811        // bridge span so two unrelated loose cuts across a face are never joined.
2812        let bridge_band = (diagonal * 0.02).max(junction_radius * 4.0);
2813        if debug && !loose.is_empty() {
2814            eprintln!("  junction_radius={junction_radius:.6} bridge_band={bridge_band:.6} loose={loose:?}");
2815        }
2816        let skip_crossing_pairs = bridge_skip_crossing_pairs_enabled();
2817        let chains_cross = |i: usize, j: usize| -> bool {
2818            chains[i].segments.iter().any(|&(a0, a1)| {
2819                chains[j].segments.iter().any(|&(b0, b1)| {
2820                    crate::arrangement::segment_intersection(a0, a1, b0, b1, arrangement_tolerance).is_some()
2821                })
2822            })
2823        };
2824        let mut pairs: Vec<(f64, usize, usize)> = Vec::new();
2825        for a in 0..loose.len() {
2826            for b in (a + 1)..loose.len() {
2827                if loose[a].0 == loose[b].0 {
2828                    continue; // never bridge a chain to itself
2829                }
2830                if skip_crossing_pairs && chains_cross(loose[a].0, loose[b].0) {
2831                    if debug {
2832                        eprintln!("  loose ends of chains {} and {} are not bridged: the chains cross", loose[a].0, loose[b].0);
2833                    }
2834                    continue;
2835                }
2836                let gap = loose[a].2.sub(loose[b].2).length();
2837                if gap <= bridge_band {
2838                    pairs.push((gap, a, b));
2839                }
2840            }
2841        }
2842        pairs.sort_by(|x, y| x.0.total_cmp(&y.0));
2843        // 3D-DISTANCE CORROBORATION (case 08:10-genus, secondary defect): the
2844        // 2% UV band is metric-blind — on a big-carrier face (full-sphere
2845        // domain [0,1]² spanning hundreds of mm) it silently bridged loose
2846        // ends 8-14 mm apart in 3D, manufacturing UV-closed but 3D-OPEN loops
2847        // ("loop open between coedges" at assembly). A legitimate bridge heals
2848        // a triple-point disagreement (imported edge<->vertex gap, a small
2849        // fraction of the face scale); an impossible one spans a real missing
2850        // piece. Corroborate every candidate pair in 3D: evaluate the surface
2851        // at both (wrapped-back) loose ends and REFUSE — loudly, as a
2852        // missing-piece error — when their 3D gap exceeds 1% of the face's 3D
2853        // diameter (estimated over a coarse full-domain grid; on a small trim
2854        // of a big carrier this overstates the diameter, i.e. errs LENIENT —
2855        // the safe direction). Any probe evaluation failure falls back to the
2856        // old silent bridging (a diagnostic must not fail the operation).
2857        // Escape hatch: BREP_BRIDGE_3D_GATE=0 restores unconditional bridging.
2858        let bridge_3d_gate = std::env::var("BREP_BRIDGE_3D_GATE").as_deref() != Ok("0");
2859        let face_diameter3 = if bridge_3d_gate && !pairs.is_empty() {
2860            let mut samples: Vec<Vec3> = Vec::new();
2861            'grid: for i in 0..3 {
2862                for j in 0..3 {
2863                    let u = u_domain[0] + (u_domain[1] - u_domain[0]) * i as f64 / 2.0;
2864                    let v = v_domain[0] + (v_domain[1] - v_domain[0]) * j as f64 / 2.0;
2865                    match face.surface.evaluate(u, v) {
2866                        Ok(point) => samples.push(point),
2867                        Err(_) => {
2868                            samples.clear();
2869                            break 'grid;
2870                        }
2871                    }
2872                }
2873            }
2874            let mut diameter = 0.0f64;
2875            for (index, a) in samples.iter().enumerate() {
2876                for b in samples.iter().skip(index + 1) {
2877                    diameter = diameter.max(a.sub(*b).length());
2878                }
2879            }
2880            (diameter > 0.0).then_some(diameter)
2881        } else {
2882            None
2883        };
2884        let mut consumed = vec![false; loose.len()];
2885        let mut bridged = 0usize;
2886        for (gap, a, b) in pairs {
2887            if consumed[a] || consumed[b] {
2888                continue;
2889            }
2890            consumed[a] = true;
2891            consumed[b] = true;
2892            let (chain_a, _, point_a) = loose[a];
2893            let (chain_b, _, point_b) = loose[b];
2894            if let Some(diameter) = face_diameter3 {
2895                let wrapped_a = wrap_back(point_a);
2896                let wrapped_b = wrap_back(point_b);
2897                if let (Ok(position_a), Ok(position_b)) = (
2898                    face.surface.evaluate(wrapped_a.x, wrapped_a.y),
2899                    face.surface.evaluate(wrapped_b.x, wrapped_b.y),
2900                ) {
2901                    let gap3 = position_a.sub(position_b).length();
2902                    let limit = 0.01 * diameter;
2903                    if gap3 > limit {
2904                        return Err(KernelRefusal::internal(KernelStage::Fragment, "fragment.face_split", format!(
2905                            "fragment_face {}: cut junction bridge refused — 3D gap \
2906                             {gap3:.4} exceeds {limit:.4} (1% of face diameter \
2907                             {diameter:.4}) across uv gap {gap:.6}; a section piece \
2908                             is missing between chains {chain_a} and {chain_b}",
2909                            face.id
2910                        )));
2911                    }
2912                }
2913            }
2914            let midpoint = point_a.add(point_b).scale(0.5);
2915            if debug {
2916                eprintln!(
2917                    "  bridging chain {chain_a} at ({:.9},{:.9}) and chain {chain_b} at ({:.9},{:.9}), uv gap {gap:.6}",
2918                    point_a.x, point_a.y, point_b.x, point_b.y
2919                );
2920            }
2921            for (chain, old) in [(chain_a, point_a), (chain_b, point_b)] {
2922                if chains[chain].start.sub(old).length() <= 1e-15 {
2923                    chains[chain].start = midpoint;
2924                }
2925                if chains[chain].end.sub(old).length() <= 1e-15 {
2926                    chains[chain].end = midpoint;
2927                }
2928                for seg in &mut chains[chain].segments {
2929                    if seg.0.sub(old).length() <= 1e-15 {
2930                        seg.0 = midpoint;
2931                    }
2932                    if seg.1.sub(old).length() <= 1e-15 {
2933                        seg.1 = midpoint;
2934                    }
2935                }
2936                for segment in segments.iter_mut() {
2937                    if tag_chain(&segment.tag) != Some(chain as u64) {
2938                        continue;
2939                    }
2940                    if segment.a.sub(old).length() <= 1e-15 {
2941                        segment.a = midpoint;
2942                    }
2943                    if segment.b.sub(old).length() <= 1e-15 {
2944                        segment.b = midpoint;
2945                    }
2946                }
2947            }
2948            bridged += 1;
2949        }
2950        if debug && bridged > 0 {
2951            eprintln!("  bridged {bridged} broken cut junction(s)");
2952        }
2953    }
2954    // GRAZE-BAND COMMON-BLOCK — near-tangent hook absorption (member t548,
2955    // fixture 28). fragment_face runs on the ALREADY edge-split solid, so
2956    // every imprint-minted section×boundary crossing is already a chain endpoint
2957    // by construction. A near-tangent SSI section ending at a shared junction
2958    // vertex can HOOK in its last span: its sampled pcurve overshoots and crosses
2959    // the boundary edge a graze before reaching the shared endpoint (the crossing
2960    // add_edge_split already REFUSED as sub-weld, so the imprint minted only the
2961    // shared vertex). arrange_segments, seeing the linearised hook, re-invents that
2962    // crossing as a distinct INTERIOR point Q, splits the boundary there, and
2963    // spawns a sub-band micro-stub that strands one-use at assembly (t548's
2964    // A→B→C needle). Absorb it deterministically: when a Cut chain and a Boundary
2965    // chain SHARE an endpoint node P, and the cut's polyline crosses that boundary
2966    // at an interior point Q within a MEASURED band of P (3D via surface.evaluate;
2967    // ceiling = the residual-merge sep_cap family, never grown, never the poisoned
2968    // projector), CLIP the cut's hooked tail — drop the samples between the
2969    // crossing and P and run straight into P. The cut's SOURCE curve is untouched,
2970    // so the complete-run path in build_loop still emits the full section edge to
2971    // P; only the spurious arrangement self-crossing is removed. This is the
2972    // arrangement sibling of BREP_SAG_CROSSING_GUARD ("sag refinement may REMOVE a
2973    // crossing but never ADD one"): the arrangement may not invent a boundary
2974    // crossing the imprint did not mint. The structural gate (shared endpoint +
2975    // strictly-interior sub-band crossing) keeps it off legitimate transversals —
2976    // an interior crossing BEYOND the band bails the chain untouched. Generalising
2977    // that gate to Cut×Cut pairs over a measured junction blob was tried and
2978    // falsified as a structural no-op: a crossing in the junction-ADJACENT first
2979    // segment leaves keep_lo=1 reconnecting an identical polyline, and two arms
2980    // that DIVERGE from a shared junction cannot be uncrossed by clipping — this
2981    // absorbs a multi-segment overshoot-and-return hook only. Escape hatch
2982    // BREP_GRAZE_HOOK_CLIP=0.
2983    if std::env::var("BREP_GRAZE_HOOK_CLIP").as_deref() != Ok("0") {
2984        let raw_extent = if solid.vertices.is_empty() {
2985            0.0
2986        } else {
2987            let mut lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
2988            let mut hi = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
2989            for v in &solid.vertices {
2990                lo.x = lo.x.min(v.point.x);
2991                lo.y = lo.y.min(v.point.y);
2992                lo.z = lo.z.min(v.point.z);
2993                hi.x = hi.x.max(v.point.x);
2994                hi.y = hi.y.max(v.point.y);
2995                hi.z = hi.z.max(v.point.z);
2996            }
2997            hi.sub(lo).length()
2998        };
2999        // Mirror imprint::residual_merge_bands' sep_cap (the measured junction-radius
3000        // family, 1.5e-3·extent, floored by the achieved weld band) — the largest
3001        // near-tangent hook a shared-junction section can plausibly span.
3002        let band = 2.0 * 1e-5 * raw_extent.max(1.0);
3003        let sep_cap = (1.5e-3 * raw_extent).max(band);
3004        let graze_debug = debug || std::env::var("BREP_DEBUG_GRAZE").as_deref() == Ok("1");
3005
3006        let mut plans: Vec<(usize, Vec<(Vec2, Vec2)>, f64)> = Vec::new();
3007        for ci in 0..chains.len() {
3008            if !matches!(chains[ci].source, ChainSource::Cut { .. }) {
3009                continue;
3010            }
3011            // A chain already dropped as a boundary duplicate has had its flat
3012            // `segments` removed; never re-materialise it below.
3013            if dropped_chains.contains(&ci) {
3014                continue;
3015            }
3016            if chains[ci].segments.is_empty() {
3017                continue;
3018            }
3019            let mut lo_cut: Option<usize> = None; // clip a start hook after this seg
3020            let mut hi_cut: Option<usize> = None; // clip an end hook from this seg on
3021            let mut measured = 0.0f64;
3022            let mut bail = false;
3023            for &at_end in &[false, true] {
3024                let p = if at_end {
3025                    chains[ci].end
3026                } else {
3027                    chains[ci].start
3028                };
3029                let Ok(p3) = face.surface.evaluate(p.x, p.y) else {
3030                    continue;
3031                };
3032                for bi in 0..chains.len() {
3033                    if bi == ci || !matches!(chains[bi].source, ChainSource::Boundary { .. }) {
3034                        continue;
3035                    }
3036                    let shares = chains[bi].start.sub(p).length() <= node_tolerance
3037                        || chains[bi].end.sub(p).length() <= node_tolerance;
3038                    if !shares {
3039                        continue;
3040                    }
3041                    for si in 0..chains[ci].segments.len() {
3042                        let (sa, sb) = chains[ci].segments[si];
3043                        for &(ba, bb) in &chains[bi].segments {
3044                            let Some([t1, t2]) = crate::arrangement::segment_intersection(
3045                                sa,
3046                                sb,
3047                                ba,
3048                                bb,
3049                                arrangement_tolerance,
3050                            ) else {
3051                                continue;
3052                            };
3053                            // Strictly interior on BOTH segments: not the shared-node
3054                            // touch (t≈0/1) and not a boundary-endpoint (imprint-minted)
3055                            // crossing (t2≈0/1) — an arrangement-invented self-crossing.
3056                            if !(t1 > 1e-3 && t1 < 1.0 - 1e-3 && t2 > 1e-3 && t2 < 1.0 - 1e-3) {
3057                                continue;
3058                            }
3059                            let q = Vec2 {
3060                                x: sa.x + (sb.x - sa.x) * t1,
3061                                y: sa.y + (sb.y - sa.y) * t1,
3062                            };
3063                            let Ok(q3) = face.surface.evaluate(q.x, q.y) else {
3064                                continue;
3065                            };
3066                            let dist = q3.sub(p3).length();
3067                            if dist > sep_cap {
3068                                // A genuine transversal far from the shared vertex —
3069                                // preserve current behaviour, touch nothing.
3070                                bail = true;
3071                                break;
3072                            }
3073                            measured = measured.max(dist);
3074                            if at_end {
3075                                hi_cut = Some(hi_cut.map_or(si, |m| m.min(si)));
3076                            } else {
3077                                lo_cut = Some(lo_cut.map_or(si, |m| m.max(si)));
3078                            }
3079                        }
3080                        if bail {
3081                            break;
3082                        }
3083                    }
3084                    if bail {
3085                        break;
3086                    }
3087                }
3088                if bail {
3089                    break;
3090                }
3091            }
3092            if bail || (lo_cut.is_none() && hi_cut.is_none()) {
3093                continue;
3094            }
3095            let segs = &chains[ci].segments;
3096            let keep_lo = lo_cut.map(|m| m + 1).unwrap_or(0);
3097            let keep_hi = hi_cut.unwrap_or(segs.len());
3098            if keep_lo >= keep_hi {
3099                continue;
3100            }
3101            let mut points: Vec<Vec2> = Vec::with_capacity(keep_hi - keep_lo + 3);
3102            if lo_cut.is_some() {
3103                points.push(chains[ci].start);
3104            }
3105            points.push(segs[keep_lo].0);
3106            for si in keep_lo..keep_hi {
3107                points.push(segs[si].1);
3108            }
3109            if hi_cut.is_some() {
3110                points.push(chains[ci].end);
3111            }
3112            let new_segments: Vec<(Vec2, Vec2)> = points
3113                .windows(2)
3114                .filter(|w| w[0].sub(w[1]).length() > 0.0)
3115                .map(|w| (w[0], w[1]))
3116                .collect();
3117            if new_segments.is_empty() {
3118                continue;
3119            }
3120            if graze_debug {
3121                eprintln!(
3122                    "graze-hook-clip: face {} cut chain {} measured_band={:.3e} sep_cap={:.3e} \
3123                     segs {} -> {} (lo_cut={:?} hi_cut={:?})",
3124                    face.id,
3125                    ci,
3126                    measured,
3127                    sep_cap,
3128                    chains[ci].segments.len(),
3129                    new_segments.len(),
3130                    lo_cut,
3131                    hi_cut
3132                );
3133            }
3134            plans.push((ci, new_segments, measured));
3135        }
3136        for (ci, new_segments, _) in plans {
3137            chains[ci].count = new_segments.len();
3138            chains[ci].segments = new_segments.clone();
3139            segments.retain(|s| tag_chain(&s.tag) != Some(ci as u64));
3140            for (segment_index, (a, b)) in new_segments.into_iter().enumerate() {
3141                segments.push(Segment2 {
3142                    a,
3143                    b,
3144                    tag: segment_tag(ci, segment_index),
3145                });
3146            }
3147        }
3148    }
3149    profile.dedup_bridge += profile.lap(lap_start);
3150    profile.arranged_faces += 1;
3151    // LENS PAIRS APART (`BREP_LENS_PAIR_APART`, default on, `=0` restores;
3152    // `BREP_LENS_PAIR_APART_CHECK` reports the pairs and keeps the plain
3153    // arrangement): on a lens's face, two open chains sharing both ends and
3154    // parting on one side between them (a cap's rim and the other prism's
3155    // section a hair inside it, both sampled at one set of stations) are
3156    // arranged apart in the zone beside each end where their polylines run
3157    // within four tolerances of each other, meeting there only at the end. Near each end the two run
3158    // within the arrangement's tolerance, and the plain arrangement made a
3159    // node of two samples there, or of two chords crossing at a grazing
3160    // angle, a chord away from the true crossing: the runs ended there and
3161    // the loop's vertex stood 0.025 off its edge.
3162    let lens_apart_on = lens_face && crate::switch!("BREP_LENS_PAIR_APART", true);
3163    let lens_apart_check = lens_face && crate::switch!("BREP_LENS_PAIR_APART_CHECK", false);
3164    let lens_pairs: Vec<crate::LensPair> = if lens_apart_on || lens_apart_check {
3165        let shapes: Vec<(Vec2, Vec2, &[(Vec2, Vec2)])> = chains.iter().map(|chain| (chain.start, chain.end, chain.segments.as_slice())).collect();
3166        let pairs = lens_pairs(&shapes, arrangement_tolerance);
3167        if lens_apart_check && !pairs.is_empty() {
3168            let shown: Vec<(u64, u64, f64, f64)> = pairs.iter().map(|pair| (pair.first, pair.second, pair.ends[0].2, pair.ends[1].2)).collect();
3169            eprintln!("lens pairs apart: face {} pairs (first, second, start zone, end zone) {shown:?}", face.id);
3170        }
3171        pairs
3172    } else {
3173        Vec::new()
3174    };
3175    let regions = if lens_apart_on && !lens_pairs.is_empty() {
3176        let chain_of: Vec<u64> = segments.iter().map(|segment| tag_chain(&segment.tag).unwrap_or(u64::MAX)).collect();
3177        let apart = crate::LensApart { chain_of: &chain_of, pairs: &lens_pairs };
3178        crate::arrange_segments_lens_apart(&segments, arrangement_tolerance, &apart).or_refuse(KernelStage::Fragment, "arrange_segments")?
3179    } else {
3180        arrange_segments(&segments, arrangement_tolerance).or_refuse(KernelStage::Fragment, "arrange_segments")?
3181    };
3182    profile.arrange += profile.lap(lap_start);
3183    profile.region_faces += 1;
3184    // Orient every rebuilt loop the way the SOURCE face's own loops are
3185    // oriented, rather than assuming `same_sense` predicts it. The two agree on
3186    // every face whose chart is right-handed against its normal, so this is a
3187    // no-op there; it differs only on a face the old assumption got wrong, and
3188    // getting it wrong reverses that face's whole fragment. Falls back to the
3189    // old rule whenever the source winding cannot be read (see the helper).
3190    // Escape hatch for A/B against the old behaviour.
3191    let source_winding = if std::env::var("BREP_FRAGMENT_SOURCE_WINDING").as_deref() == Ok("0") {
3192        None
3193    } else {
3194        source_loop_winding_negative(face)?
3195    };
3196    let reverse_loops = source_winding.unwrap_or(!face.same_sense);
3197    if debug && reverse_loops != !face.same_sense {
3198        eprintln!(
3199            "  face {}: source loop winds {} against same_sense={} — orienting fragments to the source",
3200            face.id,
3201            if reverse_loops { "CW" } else { "CCW" },
3202            face.same_sense
3203        );
3204    }
3205    // Section pieces the arrangement bounded no region with: a piece that ends
3206    // inside the face (the ruling along which a cylinder merely touches this
3207    // wall) splits nothing, and the region's points are found from the region's
3208    // boundary alone, so one can land on the piece itself, where the face
3209    // touches the other body and reads as lying ON it.
3210    let stray_pieces: Vec<Vec<Vec2>> = if stray_piece_clearance_enabled() {
3211        let used: HashSet<u64> = regions
3212            .iter()
3213            .flat_map(|region| region.outer.iter().chain(region.holes.iter().flatten()))
3214            .filter_map(|usage| tag_chain(&usage.piece.parent.tag))
3215            .collect();
3216        chains
3217            .iter()
3218            .enumerate()
3219            .filter(|(index, chain)| matches!(chain.source, ChainSource::Cut { .. }) && !chain.segments.is_empty() && !used.contains(&(*index as u64)))
3220            .map(|(_, chain)| {
3221                // There and back: a closed path of no area, read as a hole's boundary.
3222                let mut path: Vec<Vec2> = chain.segments.iter().map(|segment| segment.0).collect();
3223                path.push(chain.segments[chain.segments.len() - 1].1);
3224                let back: Vec<Vec2> = path[1..path.len() - 1].iter().rev().copied().collect();
3225                path.extend(back);
3226                path
3227            })
3228            .collect()
3229    } else {
3230        Vec::new()
3231    };
3232    let mut fragments = Vec::new();
3233    for mut region in regions {
3234        super::loops::detach_touched_closed_boundaries(&mut region, &chains, arrangement_tolerance)?;
3235        let order = FragmentOrder {
3236            area: region.outer_area,
3237            key: super::loops::region_topology_key(&region.outer, &region.holes),
3238        };
3239        let mut region_lap = profile.enabled.then(Instant::now);
3240        let arranged: Vec<Vec2> = if stray_pieces.is_empty() {
3241            interior_points(&region.outer, &region.holes, region.area, 3)
3242        } else {
3243            super::loops::interior_points_clear_of(&region.outer, &region.holes, &stray_pieces, region.area, 3)
3244        };
3245        let interior_ms = profile.lap(&mut region_lap).as_secs_f64() * 1000.0;
3246        let candidates: Vec<Vec2> = arranged.iter().copied().map(wrap_back).collect();
3247        let Some(&test_uv) = candidates.first() else {
3248            if debug {
3249                eprintln!("  region area={:.6e}: no interior point", region.area);
3250            }
3251            continue;
3252        };
3253        let mut containment = parameter_point_in_face(face, test_uv, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")?;
3254        // TRIM-FRAME CONTAINMENT. A face whose own pcurves run past its
3255        // carrier's domain (helmet Face_15: its trim spans u in
3256        // [-0.178, 0.298] on a carrier closed in u, drawn without a hop) is
3257        // arranged in that frame, and the region's point is on the face there.
3258        // Its wrapped image (u = 0.970 for -0.030) lies on no trim polygon,
3259        // and containment has no period image to try for a trim that never
3260        // hops the seam, so it reads Outside and the region was dropped: the
3261        // face's y >= 0 piece in `20_helmet_merge_stage` b - a, whose section
3262        // edges then stood one-use. With no band re-base the arrangement's
3263        // frame is the trim's own, so the region's point is asked there as
3264        // well. Escape hatch `BREP_REGION_TRIM_FRAME=0`.
3265        if containment != PolygonClass::Inside
3266            && band_rebase == [None, None]
3267            && (arranged[0].x != test_uv.x || arranged[0].y != test_uv.y)
3268            && std::env::var("BREP_REGION_TRIM_FRAME").as_deref() != Ok("0")
3269        {
3270            containment = parameter_point_in_face(face, arranged[0], 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")?;
3271            if debug {
3272                eprintln!(
3273                    "  region area={:.6e} test=({:.9},{:.9}) asked in the trim's frame at ({:.9},{:.9}): {:?}",
3274                    region.area, test_uv.x, test_uv.y, arranged[0].x, arranged[0].y,
3275                    containment == PolygonClass::Inside
3276                );
3277            }
3278        }
3279        if containment != PolygonClass::Inside {
3280            if debug {
3281                eprintln!(
3282                    "  region area={:.6e} test=({:.9},{:.9}): outside trimmed face",
3283                    region.area, test_uv.x, test_uv.y
3284                );
3285            }
3286            continue;
3287        }
3288        if debug {
3289            eprintln!(
3290                "  region area={:.6e} test=({:.9},{:.9}): KEPT",
3291                region.area, test_uv.x, test_uv.y
3292            );
3293        }
3294        let containment_ms = profile.lap(&mut region_lap).as_secs_f64() * 1000.0;
3295        let Some(outer_loop) = build_loop(
3296            &region.outer,
3297            reverse_loops,
3298            &chains,
3299            arrangement_tolerance,
3300            &face.surface,
3301        )?
3302        else {
3303            // Spurious zero-area antenna region (e.g. a seam-grazing fold on a
3304            // periodic band); it bounds no material, so drop it.
3305            if debug {
3306                eprintln!("  region area={:.6e}: dropped (degenerate antenna)", region.area);
3307            }
3308            continue;
3309        };
3310        let mut loops = vec![outer_loop];
3311        for hole in &region.holes {
3312            // Holes take the SAME flag as the outer loop: the arrangement
3313            // hands them back already wound against it, so reversing both
3314            // together keeps them opposite.
3315            if let Some(hole_loop) = build_loop(
3316                hole,
3317                reverse_loops,
3318                &chains,
3319                arrangement_tolerance,
3320                &face.surface,
3321            )? {
3322                loops.push(hole_loop);
3323            }
3324        }
3325        for loop_record in &mut loops {
3326            for coedge in &mut loop_record.coedges {
3327                if let FragmentEdgeSource::Boundary {
3328                    operand: source_operand,
3329                    ..
3330                } = &mut coedge.source
3331                {
3332                    *source_operand = operand;
3333                }
3334            }
3335        }
3336        let mut extra_test_points = Vec::new();
3337        for &candidate in candidates.iter().skip(1) {
3338            if parameter_point_in_face(face, candidate, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")? == PolygonClass::Inside {
3339                extra_test_points.push(face.surface.evaluate(candidate.x, candidate.y).or_refuse(KernelStage::Fragment, "evaluate")?);
3340            }
3341        }
3342        if profile.enabled {
3343            crate::imprint::profile_emit(format_args!("fragment.region face={} edges={} holes={} interior={interior_ms:.3} containment={containment_ms:.3} loops={:.3}",
3344                face.id, region.outer.len(), region.holes.len(), profile.lap(&mut region_lap).as_secs_f64() * 1000.0));
3345        }
3346        fragments.push(FaceFragmentRecord {
3347            operand,
3348            source_face_id: face.id,
3349            surface: face.surface.clone(),
3350            same_sense: face.same_sense,
3351            loops,
3352            test_point: face.surface.evaluate(test_uv.x, test_uv.y).or_refuse(KernelStage::Fragment, "evaluate")?,
3353            test_uv,
3354            extra_test_points,
3355            order: Some(order),
3356        });
3357    }
3358
3359    // Rescue an UNCUT face the flat 2D arrangement failed to reconstruct.
3360    // A seam-closed multi-loop face (a band on a surface of revolution, whose
3361    // param-space loops only close across the u/v seam, or a holed face whose
3362    // domain centre lands in the hole so the fast path above declined it)
3363    // collapses to zero-area lines in the [0,1]^2 arrangement and yields NO
3364    // region -> the face is dropped entirely, stranding its neighbours' shared
3365    // edges as one-use and knocking the assembly's genus off an integer. Since
3366    // the face is uncut, its loops already describe the exact trimmed boundary,
3367    // so pass the unchanged face through — we only need a valid interior test
3368    // point, found by gridding the ACTUAL knot domain. Gated on
3369    // `fragments.is_empty()`, this never touches a face the arrangement handled.
3370    profile.regions += profile.lap(lap_start);
3371    if fragments.is_empty() && piece_ids.is_empty() {
3372        const GRID: usize = 12;
3373        let mut test_uv: Option<Vec2> = None;
3374        let mut extra_test_points: Vec<Vec3> = Vec::new();
3375        'search: for iu in 1..GRID {
3376            for iv in 1..GRID {
3377                let candidate = Vec2 {
3378                    x: u_domain[0] + (u_domain[1] - u_domain[0]) * iu as f64 / GRID as f64,
3379                    y: v_domain[0] + (v_domain[1] - v_domain[0]) * iv as f64 / GRID as f64,
3380                };
3381                if parameter_point_in_face(face, candidate, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")? == PolygonClass::Inside {
3382                    if test_uv.is_none() {
3383                        test_uv = Some(candidate);
3384                    } else {
3385                        extra_test_points.push(face.surface.evaluate(candidate.x, candidate.y).or_refuse(KernelStage::Fragment, "evaluate")?);
3386                        if extra_test_points.len() >= 2 {
3387                            break 'search;
3388                        }
3389                    }
3390                }
3391            }
3392        }
3393        // SEAM-STRADDLING BAND fallback (a SINGLY-periodic surface of
3394        // revolution whose trim loop closes only ACROSS the u/v seam — e.g. a
3395        // rounded imported cap grazed near-tangent, so it stays uncut). The
3396        // even-odd `parameter_point_in_face` reads Outside EVERYWHERE on such a
3397        // loop (the seam hop makes the [0,1]^2 polygon non-simple), so the knot
3398        // grid above finds nothing and the face would still drop. `seam_band_
3399        // point_in_face` only covers the DOUBLY-periodic (torus) case, so the
3400        // singly-periodic band has no seam-aware classifier. Unwrap the loop
3401        // onto the surface's covering plane (`loop_seam_offsets`, the same fold
3402        // the mass integrator and tessellator use), where it IS a simple
3403        // polygon, grid that unwrapped bbox with the plain even-odd test, and
3404        // map an interior hit back into the domain. Runs ONLY when the grid
3405        // already failed AND the offsets show the loop truly straddled a seam
3406        // (a full-wrap rim yields all-zero offsets and is left untouched), so it
3407        // never changes a face any earlier path handled.
3408        if test_uv.is_none() {
3409            let (closed_u, closed_v) = face.surface.closed_directions().or_refuse(KernelStage::Fragment, "closed_directions")?;
3410            if closed_u || closed_v {
3411                let u_period = u_domain[1] - u_domain[0];
3412                let v_period = v_domain[1] - v_domain[0];
3413                let mut loop_polygons: Vec<Vec<Vec2>> = Vec::new();
3414                let mut straddled = false;
3415                let (mut umin, mut umax, mut vmin, mut vmax) = (
3416                    f64::INFINITY,
3417                    f64::NEG_INFINITY,
3418                    f64::INFINITY,
3419                    f64::NEG_INFINITY,
3420                );
3421                for loop_record in &face.loops {
3422                    let offsets = crate::topology::loop_seam_offsets(
3423                        &loop_record.coedges,
3424                        closed_u,
3425                        closed_v,
3426                        u_period,
3427                        v_period,
3428                    ).or_refuse(KernelStage::Fragment, "csg.fragment.face_split")?;
3429                    if offsets.iter().any(|o| o[0] != 0.0 || o[1] != 0.0) {
3430                        straddled = true;
3431                    }
3432                    let mut polygon = Vec::new();
3433                    for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
3434                        let [d0, d1] = coedge.pcurve.domain().or_refuse(KernelStage::Fragment, "domain")?;
3435                        let samples = 32usize;
3436                        for k in 0..samples {
3437                            let t = d0 + (d1 - d0) * k as f64 / samples as f64;
3438                            let p = coedge.pcurve.evaluate(t).or_refuse(KernelStage::Fragment, "evaluate")?;
3439                            let uv = Vec2 {
3440                                x: p.x + offsets[coedge_index][0],
3441                                y: p.y + offsets[coedge_index][1],
3442                            };
3443                            umin = umin.min(uv.x);
3444                            umax = umax.max(uv.x);
3445                            vmin = vmin.min(uv.y);
3446                            vmax = vmax.max(uv.y);
3447                            polygon.push(uv);
3448                        }
3449                    }
3450                    loop_polygons.push(polygon);
3451                }
3452                if straddled && umax > umin && vmax > vmin {
3453                    let wrap = |value: f64, lo: f64, span: f64| {
3454                        if span > 0.0 {
3455                            lo + (value - lo).rem_euclid(span)
3456                        } else {
3457                            value
3458                        }
3459                    };
3460                    'seam: for iu in 1..GRID {
3461                        for iv in 1..GRID {
3462                            let cu = umin + (umax - umin) * iu as f64 / GRID as f64;
3463                            let cv = vmin + (vmax - vmin) * iv as f64 / GRID as f64;
3464                            let candidate = Vec2 { x: cu, y: cv };
3465                            // Even-odd fill across ALL unwrapped loops: interior
3466                            // of the trimmed region is where the winding is odd
3467                            // (outer loop minus any hole loops), independent of
3468                            // which loop is the outer one.
3469                            let winding = loop_polygons
3470                                .iter()
3471                                .filter(|polygon| point_in_polygon(candidate, polygon))
3472                                .count();
3473                            if winding % 2 == 0 {
3474                                continue;
3475                            }
3476                            let mapped = Vec2 {
3477                                x: if closed_u {
3478                                    wrap(cu, u_domain[0], u_period)
3479                                } else {
3480                                    cu
3481                                },
3482                                y: if closed_v {
3483                                    wrap(cv, v_domain[0], v_period)
3484                                } else {
3485                                    cv
3486                                },
3487                            };
3488                            if test_uv.is_none() {
3489                                test_uv = Some(mapped);
3490                            } else {
3491                                extra_test_points
3492                                    .push(face.surface.evaluate(mapped.x, mapped.y).or_refuse(KernelStage::Fragment, "evaluate")?);
3493                                if extra_test_points.len() >= 2 {
3494                                    break 'seam;
3495                                }
3496                            }
3497                        }
3498                    }
3499                }
3500            }
3501        }
3502        if let Some(uv) = test_uv {
3503            fragments.push(FaceFragmentRecord {
3504                operand,
3505                source_face_id: face.id,
3506                surface: face.surface.clone(),
3507                same_sense: face.same_sense,
3508                loops: face
3509                    .loops
3510                    .iter()
3511                    .map(|loop_record| FragmentLoop {
3512                        coedges: loop_record
3513                            .coedges
3514                            .iter()
3515                            .map(|coedge| FragmentCoedge {
3516                                source: FragmentEdgeSource::Boundary {
3517                                    operand,
3518                                    edge_id: coedge.edge_id,
3519                                },
3520                                forward: coedge.forward,
3521                                pcurve: coedge.pcurve.clone(),
3522                            })
3523                            .collect(),
3524                    })
3525                    .collect(),
3526                test_point: face.surface.evaluate(uv.x, uv.y).or_refuse(KernelStage::Fragment, "evaluate")?,
3527                test_uv: uv,
3528                extra_test_points,
3529                order: None,
3530            });
3531        }
3532    }
3533    profile.rescue += profile.lap(lap_start);
3534    Ok(fragments)
3535}
3536
3537pub fn fragment_solid(
3538    solid: &BrepSolid,
3539    operand: u8,
3540    imprint: &ImprintResultRecord,
3541) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
3542    fragment_solid_against(solid, operand, imprint, None)
3543}
3544
3545/// A positive rational carrier is enclosed by its control hull. Unknown or
3546/// non-finite weights/points cannot certify separation and keep the full path.
3547pub fn bounded_carriers(solid: &BrepSolid) -> bool {
3548    solid.shells.iter().flat_map(|s| &s.faces).all(|face| bounded_carrier(face))
3549}
3550
3551fn bounded_carrier(face: &FaceRecord) -> bool {
3552    let (Ok(u), Ok(v)) = (face.surface.domain_u(), face.surface.domain_v()) else { return false };
3553    let positive_finite = |p: &crate::Vec4| {
3554        p.w > 0.0 && p.w.is_finite() && p.point().is_ok_and(|v|
3555            v.x.is_finite() && v.y.is_finite() && v.z.is_finite())
3556    };
3557    // Extended trims may live outside the carrier hull. Positive pcurve
3558    // controls within both knot domains certify the whole trim stays inside;
3559    // otherwise retain the existing extension/seam handling, without epsilon.
3560    // ROUNDING SLACK (`BREP_FRAGMENT_SCOPE_ULPS`, default on; `=0` restores the exact test): a trim that runs ALONG a domain
3561    // border carries controls a few ulps past it (a hole wall's seam at u = -7.8e-16 or
3562    // 1.0000000000000009, a bore's floor at 1.5200000000000002 of 1.52), and the exact test then
3563    // called every such carrier unbounded: on a part of countersunk seats and blind bores no face
3564    // was ever separated and each of 88 booleans arranged all ~500 faces to cut 6. A control within
3565    // `SCOPE_ULPS` ulps of the border moves the trim off the hull by that many ulps of the
3566    // carrier's size, orders below the separation band every caller adds.
3567    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 };
3568    let (su, sv) = (slack(u), slack(v));
3569    face.surface.control_points.iter().flatten().all(positive_finite)
3570        && face.loops.iter().flat_map(|lp| &lp.coedges).all(|coedge| {
3571            coedge.pcurve.control_points.iter().all(|p| {
3572                positive_finite(p) && p.point().is_ok_and(|p|
3573                    p.x >= u[0] - su && p.x <= u[1] + su && p.y >= v[0] - sv && p.y <= v[1] + sv)
3574            })
3575        })
3576}
3577
3578/// The rounding slack of `bounded_carrier`'s trim test, in ulps of the domain.
3579const SCOPE_ULPS: f64 = 64.0;
3580
3581fn scope_ulps_on() -> bool {
3582    crate::switch!("BREP_FRAGMENT_SCOPE_ULPS", true)
3583}
3584
3585/// Exact control-hull separation, including the extended-trim guard.
3586pub fn face_separated(face: &FaceRecord, bounds: crate::Aabb, band: f64) -> bool {
3587    bounded_carrier(face) && crate::Aabb::from_surface_controls(&face.surface)
3588        .is_ok_and(|own| !own.intersects(bounds, band))
3589}
3590
3591/// A boundary witness suffices when the ENTIRE carrier is separated from the
3592/// other operand: every point of the face has the same Outside classification.
3593/// Keep the authored loops exactly; no interior-point search or arrangement
3594/// is needed to decide material against an operand outside this carrier box.
3595/// TRIM-SIDE PROBE for a face no section touches whose arrangement came back
3596/// EMPTY (hosted report 2026-11-02 "boolean fails", the shelf pin): the
3597/// bracket union's cylinder carried its cone on a 0.01-wide cap ring (the
3598/// cone's base rim 0.01 inside the cylinder's cap), no section on it. Its
3599/// domain centre is its hole, so it went to the arrangement for a test
3600/// point, which sampled a circle at 32 chords: the inner rim's chords sagged
3601/// 0.0115 into the hole, the only region's test point sat there, "outside
3602/// trimmed face", and the face was dropped without a word (open edges at
3603/// assembly, or a body that validated at the wrong volume). A face without
3604/// a cut that the arrangement does not split is one fragment, itself; all
3605/// it needs is a point of its own material, and that lies beside its trim: a
3606/// station on each loop's pcurve, stepped off along the pcurve's normal on
3607/// both sides over a ladder of distances, the first one the trim owns. The
3608/// arrangement's own answers stand where it gives any (a pinched loop it
3609/// splits in two). Escape hatch `BREP_FRAGMENT_TRIM_PROBE=0|off` leaves the
3610/// empty answer as it was.
3611fn trim_probe_enabled() -> bool {
3612    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3613    *ON.get_or_init(|| !matches!(std::env::var("BREP_FRAGMENT_TRIM_PROBE").as_deref(), Ok("0") | Ok("off")))
3614}
3615
3616/// The face itself as its one fragment, with the test point `uv`.
3617fn untouched_fragment(
3618    face: &FaceRecord,
3619    operand: u8,
3620    uv: Vec2,
3621    extra_test_points: Vec<Vec3>,
3622) -> Result<FaceFragmentRecord, KernelRefusal> {
3623    Ok(FaceFragmentRecord {
3624        operand,
3625        source_face_id: face.id,
3626        surface: face.surface.clone(),
3627        same_sense: face.same_sense,
3628        loops: face
3629            .loops
3630            .iter()
3631            .map(|loop_record| FragmentLoop {
3632                coedges: loop_record
3633                    .coedges
3634                    .iter()
3635                    .map(|coedge| FragmentCoedge {
3636                        source: FragmentEdgeSource::Boundary {
3637                            operand,
3638                            edge_id: coedge.edge_id,
3639                        },
3640                        forward: coedge.forward,
3641                        pcurve: coedge.pcurve.clone(),
3642                    })
3643                    .collect(),
3644            })
3645            .collect(),
3646        test_point: face.surface.evaluate(uv.x, uv.y).or_refuse(KernelStage::Fragment, "evaluate")?,
3647        test_uv: uv,
3648        extra_test_points,
3649        order: None,
3650    })
3651}
3652
3653/// A point of `face`'s material beside its trim, with up to two more as
3654/// extra test points, or `None` when no station of the ladder is owned.
3655/// Keep a region's test points clear of the section pieces that end inside it
3656/// (`BREP_FRAGMENT_STRAY_PIECE_CLEARANCE`, default on; `=0` reads the region's
3657/// boundary alone).
3658fn stray_piece_clearance_enabled() -> bool {
3659    switch!("BREP_FRAGMENT_STRAY_PIECE_CLEARANCE", true)
3660}
3661
3662fn trim_interior_probe(
3663    face: &FaceRecord,
3664    u: [f64; 2],
3665    v: [f64; 2],
3666) -> Result<Option<(Vec2, Vec<Vec3>)>, KernelRefusal> {
3667    let diagonal = ((u[1] - u[0]).powi(2) + (v[1] - v[0]).powi(2)).sqrt();
3668    if !(diagonal > 0.0) {
3669        return Ok(None);
3670    }
3671    let mut found: Vec<Vec2> = Vec::new();
3672    'loops: for loop_record in &face.loops {
3673        for coedge in &loop_record.coedges {
3674            let [a, b] = coedge.pcurve.domain().or_refuse(KernelStage::Fragment, "domain")?;
3675            if !(b > a) {
3676                continue;
3677            }
3678            for fraction in [0.5, 0.25, 0.75] {
3679                let t = a + (b - a) * fraction;
3680                let derivatives = coedge.pcurve.derivatives(t, 1).or_refuse(KernelStage::Fragment, "derivatives")?;
3681                let (at, tangent) = (derivatives[0], derivatives[1]);
3682                let speed = (tangent.x * tangent.x + tangent.y * tangent.y).sqrt();
3683                if !(speed > 0.0) || !speed.is_finite() {
3684                    continue;
3685                }
3686                let normal = Vec2 { x: -tangent.y / speed, y: tangent.x / speed };
3687                for scale in [1e-2, 1e-3, 1e-4, 1e-5, 1e-6] {
3688                    let step = diagonal * scale;
3689                    for sign in [1.0, -1.0] {
3690                        let candidate = Vec2 { x: at.x + normal.x * step * sign, y: at.y + normal.y * step * sign };
3691                        if candidate.x < u[0] || candidate.x > u[1] || candidate.y < v[0] || candidate.y > v[1] {
3692                            continue;
3693                        }
3694                        if parameter_point_in_face(face, candidate, 1e-9).or_refuse(KernelStage::Fragment, "parameter_point_in_face")? == PolygonClass::Inside {
3695                            found.push(candidate);
3696                            if found.len() >= 3 {
3697                                break 'loops;
3698                            }
3699                            continue 'loops;
3700                        }
3701                    }
3702                }
3703            }
3704        }
3705    }
3706    let Some(uv) = found.first().copied() else {
3707        return Ok(None);
3708    };
3709    let mut extra_test_points = Vec::new();
3710    for candidate in found.iter().skip(1) {
3711        extra_test_points.push(face.surface.evaluate(candidate.x, candidate.y).or_refuse(KernelStage::Fragment, "evaluate")?);
3712    }
3713    Ok(Some((uv, extra_test_points)))
3714}
3715
3716fn separated_fragment(face: &FaceRecord, operand: u8) -> Option<FaceFragmentRecord> {
3717    let coedge = face.loops.first()?.coedges.first()?;
3718    let [a, b] = coedge.pcurve.domain().ok()?;
3719    let point = coedge.pcurve.evaluate(a + (b - a) * 0.5).ok()?;
3720    let uv = Vec2 { x: point.x, y: point.y };
3721    let test_point = face.surface.evaluate(uv.x, uv.y).ok()?;
3722    Some(FaceFragmentRecord {
3723        operand, source_face_id: face.id, surface: face.surface.clone(),
3724        same_sense: face.same_sense,
3725        loops: face.loops.iter().map(|lp| FragmentLoop {
3726            coedges: lp.coedges.iter().map(|coedge| FragmentCoedge {
3727                source: FragmentEdgeSource::Boundary { operand, edge_id: coedge.edge_id },
3728                forward: coedge.forward, pcurve: coedge.pcurve.clone(),
3729            }).collect(),
3730        }).collect(),
3731        test_point, test_uv: uv, extra_test_points: Vec::new(), order: None,
3732    })
3733}
3734
3735pub fn fragment_solid_against(
3736    solid: &BrepSolid,
3737    operand: u8,
3738    imprint: &ImprintResultRecord,
3739    other: Option<(crate::Aabb, f64)>,
3740) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
3741    let mut profile = FragmentProfile::new();
3742    if profile.enabled {
3743        crate::classification::containment_profile_begin();
3744    }
3745    let result = fragment_solid_profiled(solid, operand, imprint, other, &mut profile);
3746    profile.report(operand);
3747    if profile.enabled {
3748        crate::classification::containment_profile_report("fragment");
3749    }
3750    result
3751}
3752
3753pub fn fragment_solid_profiled(
3754    solid: &BrepSolid,
3755    operand: u8,
3756    imprint: &ImprintResultRecord,
3757    other: Option<(crate::Aabb, f64)>,
3758    profile: &mut FragmentProfile,
3759) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
3760    let index = FragmentIndex::build(imprint);
3761    let mut fragments = Vec::new();
3762    for face in solid.shells.iter().flat_map(|shell| shell.faces.iter()) {
3763        let far = other.is_some_and(|(bounds, band)| face_separated(face, bounds, band));
3764        if !far { profile.box_candidates += 1; }
3765        let has_pieces = index.by_face.get(&(operand, face.id)).is_some_and(|ids| !ids.is_empty());
3766        let cosurface = index.cosurface_pairs.iter().any(|(key, _)| key.operand == operand && key.face_id == face.id);
3767        if far && !has_pieces && !cosurface && std::env::var("BREP_FRAGMENT_SCOPE").as_deref() != Ok("0") {
3768            if let Some(fragment) = separated_fragment(face, operand) {
3769                profile.separated_faces += 1;
3770                profile.face_done(face.id, None);
3771                fragments.push(fragment);
3772                continue;
3773            }
3774        }
3775        let before = (profile.arranged_faces, profile.region_faces);
3776        fragments.extend(fragment_face_indexed(solid, operand, face, &index, profile)?);
3777        if far {
3778            profile.far_arranged += profile.arranged_faces - before.0;
3779            profile.far_regions += profile.region_faces - before.1;
3780        }
3781    }
3782    Ok(fragments)
3783}
3784
3785
3786/// `BREP_RIM_BRIDGE` (default on, `=0` off): the fragment side of the imprint's rim
3787/// bridge (see RIM BRIDGE in `fragment_face_arranged`).
3788fn rim_bridge_enabled() -> bool {
3789    crate::switch!("BREP_RIM_BRIDGE", true)
3790}
3791
3792/// The lens pairs among `chains` (start, end, segments) that an arrangement
3793/// at `tolerance` keeps apart in their end zones (`BREP_LENS_PAIR_APART`):
3794/// two open chains sharing both ends (within ten tolerances), every sample of
3795/// each farther than the tolerance from the other standing on one side of it,
3796/// and the samples within the tolerance only running unbroken from the two
3797/// ends. Each end's zone runs out to the first sample of either chain
3798/// standing farther than four tolerances from the other.
3799pub(crate) fn lens_pairs(chains: &[(Vec2, Vec2, &[(Vec2, Vec2)])], tolerance: f64) -> Vec<crate::LensPair> {
3800    let (meet, zone_band) = (10.0 * tolerance, 4.0 * tolerance);
3801    // The distance from `point` to a polyline, signed by the side of the
3802    // nearest segment it stands on.
3803    let signed_to = |point: Vec2, segments: &[(Vec2, Vec2)]| -> (f64, f64) {
3804        let mut best = (f64::INFINITY, 0.0);
3805        for (a, b) in segments {
3806            let span = b.sub(*a);
3807            let squared = span.dot(span);
3808            let t = if squared > 0.0 { (point.sub(*a).dot(span) / squared).clamp(0.0, 1.0) } else { 0.0 };
3809            let foot = Vec2 { x: a.x + span.x * t, y: a.y + span.y * t };
3810            let distance = point.sub(foot).length();
3811            if distance < best.0 {
3812                let side = span.x * (point.y - a.y) - span.y * (point.x - a.x);
3813                best = (distance, side.signum());
3814            }
3815        }
3816        best
3817    };
3818    let points_of = |segments: &[(Vec2, Vec2)]| -> Vec<Vec2> { segments.iter().map(|(a, _)| *a).chain(segments.last().map(|(_, b)| *b)).collect() };
3819    // How far from its first point a polyline (read from one end) runs until
3820    // a sample stands farther than the zone band from the other.
3821    let zone_from = |points: &[Vec2], other: &[(Vec2, Vec2)]| -> Option<f64> {
3822        let end = points[0];
3823        points.iter().skip(1).find(|point| signed_to(**point, other).0 > zone_band).map(|point| point.sub(end).length())
3824    };
3825    let one_side = |segments: &[(Vec2, Vec2)], other: &[(Vec2, Vec2)]| -> bool {
3826        let readings: Vec<(f64, f64)> = points_of(segments).iter().map(|point| signed_to(*point, other)).collect();
3827        let close = |reading: &(f64, f64)| reading.0 <= tolerance;
3828        let head = readings.iter().take_while(|reading| close(reading)).count();
3829        let tail = readings.iter().rev().take_while(|reading| close(reading)).count();
3830        if head + tail >= readings.len() {
3831            return false;
3832        }
3833        let middle = &readings[head..readings.len() - tail];
3834        let sign = middle[0].1;
3835        sign != 0.0 && middle.iter().all(|reading| !close(reading) && reading.1 == sign)
3836    };
3837    let mut pairs = Vec::new();
3838    for i in 0..chains.len() {
3839        for j in (i + 1)..chains.len() {
3840            let ((a_start, a_end, a), (b_start, b_end, b)) = (chains[i], chains[j]);
3841            if a.len() < 2 || b.len() < 2 {
3842                continue;
3843            }
3844            let open = |start: Vec2, end: Vec2| start.sub(end).length() > meet;
3845            let same = a_start.sub(b_start).length() <= meet && a_end.sub(b_end).length() <= meet;
3846            let reversed = a_start.sub(b_end).length() <= meet && a_end.sub(b_start).length() <= meet;
3847            if !(open(a_start, a_end) && open(b_start, b_end) && (same || reversed)) {
3848                continue;
3849            }
3850            // A side change anywhere is a crossing of the chains themselves
3851            // (two exact polylines 3e-7 apart crossing twice beside an end),
3852            // and a contact inside the tolerance away from the ends is one
3853            // the samples cannot tell from a crossing: either way the pair is
3854            // arranged plainly.
3855            if !(one_side(a, b) && one_side(b, a)) {
3856                continue;
3857            }
3858            let (a_points, b_points) = (points_of(a), points_of(b));
3859            let reversed_points = |points: &[Vec2]| -> Vec<Vec2> { points.iter().rev().copied().collect() };
3860            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()) };
3861            let zone = |a_points: &[Vec2], b_points: &[Vec2]| -> Option<f64> { Some(zone_from(a_points, b)?.max(zone_from(b_points, a)?)) };
3862            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 };
3863            pairs.push(crate::LensPair { first: i as u64, second: j as u64, ends: [(a_start, meet, start_zone), (a_end, meet, end_zone)] });
3864        }
3865    }
3866    pairs
3867}