Skip to main content

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