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