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