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