Skip to main content

brep_kernel/healing/
accept.rs

1//! Is a constructed result SOUND enough to return — and if not, can it be
2//! repaired rather than refused?
3//!
4//! `validate()` is an incidence test and says nothing about a body passing
5//! through itself. [`crate::solid_self_intersections`] does, in two forms: two
6//! faces CROSSING, and one face FOLDING through itself. Neither changes the
7//! volume in a way a closed-form oracle can see — a shape can enclose exactly
8//! the right amount of space while passing through itself — so a lane that
9//! returns one reports success for a different result. That is the failure
10//! mode this module exists to stop.
11//!
12//! ## Repair first, refuse second
13//!
14//! A self-intersection is not automatically a dead end. Where two faces of one
15//! body cross along a curve and the material beyond that curve is a sliver,
16//! the answer is to SPLIT both faces along their carriers' exact intersection
17//! and drop the pieces that should not be there —
18//! [`resolve_face_crossing`]. Only when that cannot be bounded does the lane
19//! refuse.
20//!
21//! The drop is closed under one rule — a face left holding a boundary no other
22//! face answers for bordered the dropped material — and that rule has two
23//! answers. DROPPING the face is right when the unanswered boundary is the
24//! whole of what it contributed: a tail beside a tail. RE-TRIMMING it — taking
25//! the unanswered coedges off and re-linking what is left into closed loops —
26//! is right when the body keeps the face and only part of its boundary went,
27//! which is the only way a BREAKOUT closes. A bore carried out through a side
28//! wall leaves the mouth flat holding the stretch of a corner edge that now
29//! runs INSIDE the bore and the arc of its own mouth ring that now runs
30//! OUTSIDE the body; dropping the flat is absurd, and taking those two coedges
31//! off it merges its mouth loop into its outer loop, which is the topology a
32//! breakout has. The enumeration runs under the dropping closure first and
33//! reaches the re-trimming one only where that resolved nothing at all, so the
34//! second can turn a refusal into a repair and can never change a repair this
35//! module already made.
36//!
37//! A FOLD is different and is refused outright here. A face folded through
38//! itself is a TRIM that was never constructed: the answer is to carve the
39//! folded part of the trim away at the point the carrier is built
40//! (`offset/carve.rs`), not to repair the finished body. Refusing it by name
41//! is what sends the caller to the lane that can fix it.
42//!
43//! ## A hole that left its face
44//!
45//! The scan reads the body as a SURFACE: it convicts two faces that cross and
46//! one face that folds. Neither describes a face whose HOLE loop has wandered
47//! off the face it is a hole in — the trim is nonsense but nothing crosses,
48//! because the wall the hole opens into has gone with it. A direct edit that
49//! carries a bore clean off the body builds exactly that: `validate()` is an
50//! incidence test and passes, the scan finds no pair to convict, and the
51//! divergence-theorem volume of a cylinder is blind to where its axis sits, so
52//! the wrong body measures right to the last bit. [`refuse_holes_leaving_their_faces`]
53//! is the floor for it, and it runs LAST — after the repair, on whatever body
54//! the repair left — so a crossing the repair can take is still taken.
55//!
56//! ## And a hole that left its face ONTO A NEIGHBOUR
57//!
58//! That floor convicts two different things, and only one of them has no right
59//! answer. A bore dragged CLEAN OFF the body has none: the carrier misses the
60//! solid, and there is nothing to cut at any extent. A bore dragged so that its
61//! exit mouth crosses the edge between the face it opened through and the face
62//! next door has one, and it is the body the crossing repair already builds for
63//! a bore carried out through a side wall — the moved carrier and the
64//! neighbour split along their exact section, the overshoot dropped, and the
65//! faces left holding an unanswered boundary RE-TRIMMED, which merges the mouth
66//! into the outer loops of the two faces it now opens through.
67//!
68//! [`accept_or_break_out`] tries that before refusing, and the two cases are
69//! told apart by GEOMETRY rather than by a threshold: the convicted hole loop
70//! is traced in its own face's parameter plane and asked which of that face's
71//! outer coedges it crosses ([`breakout_pair`]). A hole that has broken out
72//! onto a neighbour crosses one, and the face across that edge is the one to
73//! re-trim against. A hole that has left the body altogether crosses none, and
74//! there is no second face for the repair to be about — so the runaway refuses
75//! before a single face is split, and it refuses with the floor's own words
76//! plus the repair's reason for declining.
77//!
78//! The extent is DERIVED and not invented, which is what makes this the same
79//! repair rather than a new operation with a new input. The tool is the moved
80//! carrier trimmed against the body, and where the carrier meets the body is
81//! what the imprint computes. Measured on the 2026-09-21 exit-hole report: the
82//! body this builds removes 4195.389267765 from the filled wedge, against
83//! 4195.389268713 for the same wedge with the INFINITE moved carrier
84//! subtracted through the boolean and 4195.389267095 for a slice integration
85//! that never enters the kernel — three roads, 1.6e-9 apart.
86//!
87//! ## The order
88//!
89//! Three separate slices built [`accept_sound`]'s sequence on 2026-09-21 and
90//! none of them saw the whole of it, so here it is end to end:
91//!
92//! 1. SCAN once. One tessellation, one BVH sweep; every verdict below is read
93//!    off that single reading.
94//! 2. NOT FLAGGED — [`accept_or_break_out`]: the hole-containment floor runs on
95//!    the body as built, and the body is returned when it says nothing. When it
96//!    convicts, the BREAKOUT is tried before the refusal — the same split and
97//!    re-trim step 4 runs, on a pair the floor names instead of one the scan
98//!    confirmed — and only a breakout that cannot be built refuses. This is the
99//!    ONLY path a bore carried clear of its faces reaches, because a bore that
100//!    has left the solid crosses nothing.
101//! 3. FLAGGED — the body is dumped under `BREP_HEAL_DUMP`, and a FOLD refuses
102//!    here and now: a fold is a trim that was never constructed, not material
103//!    to drop.
104//! 4. A CROSSING goes to [`resolve_face_crossing`], which returns the body
105//!    UNCHANGED when nothing is confirmed, refuses a fold and refuses more than
106//!    one crossing pair, and otherwise imprints the two carriers' section onto
107//!    both faces and enumerates every way of dropping the resulting pieces —
108//!    closed under `Drop` first, and under `Retrim` only where that resolved
109//!    nothing at all.
110//! 5. The repaired body is SCANNED AGAIN, and a repair that still
111//!    self-intersects refuses, naming the original crossing.
112//! 6. [`accept_or_break_out`] AGAIN, on the repaired body, so a re-trim that
113//!    left a hole off its face is broken out in turn or refused, rather than
114//!    shipped.
115//!
116//! Steps 4 and 6 bound each other, and the boundary is not a gap. The crossing
117//! repair needs a section to split along, and a section exists exactly while
118//! the moved carrier still MEETS the body; the containment floor decides what
119//! is left. Measured on the 2026-09-21 runaway-bore report, the crossing
120//! regime ends and the carrier's clearance turns positive in the SAME step of
121//! a swept drag, and 13.90 mm past that the repair is handed a body with
122//! nothing to imprint and hands it straight back.
123//!
124//! What step 2's breakout adds is the OTHER side of that boundary: the window
125//! where the mouth has crossed its face's edge but the wall's overshoot is
126//! still a sliver the tessellation cannot resolve, so the scan confirms
127//! nothing and step 4 is never entered. On the reported document that window
128//! is `s = 0.99 … 1.03` of the drag, and the scan takes over at `s = 1.04`.
129//! The two routes reach the same [`split_and_drop`] and the repair is one
130//! repair.
131//!
132//! ## Cost
133//!
134//! One tessellation and one BVH sweep per accepted result, and only on the
135//! success path. Both verdicts come off that one scan. The containment floor
136//! traces the loops of PLANAR faces that have more than one, in their own
137//! parameters; a face with a single loop costs nothing.
138//!
139//! That note used to stop at that sentence, and stopping there was
140//! misleading: the floor's cost was never in how MANY faces qualify but in
141//! how LARGE one qualifying face's loops can be. A loop is traced at 32
142//! stations per KNOT SPAN, so a box's face gives four points and an imported
143//! 100-tooth gear's flat gives 1.1 MILLION; testing every hole point against
144//! every one of those is a PRODUCT, and three such faces out of 1004 cost 24
145//! s of a 30 s replay. The trace is unchanged — decimating it would weaken
146//! the predicate — and the product is what went instead: the outer loop is
147//! indexed once into bands of its own `v` ([`BoundaryBands`]) and each hole
148//! point reads only the band it falls in, for the same answer at `hole
149//! points × segments per band`.
150
151use crate::{KernelRefusal, KernelStage, OrRefuse, SoundnessDefect};
152use crate::topology::{BrepSolid, LoopRecord};
153use crate::{solid_self_intersections, SelfIntersectionOptions, SelfIntersectionReport};
154
155/// Scan a finished result and either accept it, repair it, or refuse it by
156/// name.
157///
158/// `entry` is the lane's own name, so the refusal reads as that lane's
159/// refusal rather than as a soundness module's.
160pub fn accept_sound(solid: BrepSolid, entry: &str) -> Result<BrepSolid, KernelRefusal> {
161    let report = scan(&solid, entry)?;
162    if !report.is_flagged() {
163        return accept_or_break_out(solid, entry);
164    }
165    dump_flagged(&solid, entry);
166    if let Some(refusal) = fold_refusal(&report, entry) {
167        return Err(refusal);
168    }
169    // Two faces crossing: try to split and trim before refusing.
170    let repaired = match resolve_face_crossing(&solid) {
171        Ok(repaired) => repaired,
172        // The crossing lane declined. Where the containment floor ALSO convicts
173        // a hole loop that has left its face, this body may be a BREAKOUT the
174        // other route can take — a mouth that has migrated onto a neighbouring
175        // face crosses that neighbour, so the scan flags it, and the pair the
176        // scan picked is not always the pair the re-trim needs.
177        //
178        // Guarded three ways, because a second chance is exactly how a body
179        // that should refuse gets talked into building. The floor's conviction
180        // is the ticket — a body that merely self-intersects never reaches
181        // here. The success path above is untouched, so a body that repairs
182        // today repairs identically. And the result goes through the same
183        // re-scan and the same floor below as any other repair.
184        Err(reason) if first_hole_breach(&solid).is_some() => {
185            match break_out_until_contained(solid.clone(), entry) {
186                Ok(repaired) => repaired,
187                Err(second) => {
188                    return Err(crossing_refusal(
189                        &report,
190                        entry,
191                        &format!(
192                            "{reason}. The breakout route was offered it too and declined: \
193                             {second}"
194                        ),
195                    ))
196                }
197            }
198        }
199        Err(reason) => return Err(crossing_refusal(&report, entry, &reason.message)),
200    };
201    let after = scan(&repaired, entry)?;
202    if after.is_flagged() {
203        return Err(crossing_refusal(
204            &report,
205            entry,
206            &format!(
207                "the repair ran and the result still self-intersects — {}",
208                after.summary().unwrap_or_else(|| "no summary".into())
209            ),
210        ));
211    }
212    accept_or_break_out(repaired, entry)
213}
214
215/// How many hole-containment breaches one acceptance may break out, before it
216/// stops and refuses.
217///
218/// A bore has TWO mouths, and a motion big enough to walk one onto the next
219/// face can walk the other too — so one is not enough, and the whole point of a
220/// bound is that a repair which does not actually reduce the breaches cannot
221/// spin. Four leaves room for a two-mouth migration and a re-trim that opens
222/// one more, and stops well short of a body being talked into building by
223/// attrition.
224const MAX_BREAKOUT_ROUNDS: usize = 4;
225
226/// The containment floor, with the BREAKOUT tried before the refusal.
227///
228/// A hole loop that has left its face is not one case but two, and they are
229/// told apart by where it went. A hole that has left ONTO ANOTHER FACE has a
230/// right answer the kernel can build — the moved carrier re-trimmed against the
231/// face it now opens through — and this builds it when the mouth STRADDLES its
232/// face's boundary, which is the reported case. A hole that has left the body
233/// has no such answer, and this refuses exactly as the floor always did, with
234/// the repair's own reason for declining carried after the floor's so the
235/// refusal says which of the two it was.
236///
237/// **A mouth that has migrated WHOLLY off its face is built by the CROSSING
238/// LANE, not by this route.** Until 2026-09-22 it was built by neither: the
239/// departed face kept a hole loop the imprint never cut and the drop
240/// enumeration had no move for retiring one, so every candidate face this
241/// route offered the carrier to declined. The drop closures have that move now
242/// — [`fragment_is_detached`] and [`holds_only_stale_loops`] — and a turned
243/// bore whose exit migrates onto the next face is repaired to its closed form
244/// through [`resolve_face_crossing`], which `accept_sound` reaches first.
245///
246/// What is left for this route to decide is the mouth that has arrived on
247/// NOTHING: a carrier clear of the body cuts no face of it, every candidate
248/// declines, and the refusal names each face it tried and the distance it
249/// tried it at. That is measured, not assumed, by
250/// `a_mouth_that_has_left_the_body_reaches_the_migration_route_and_is_refused_by_name`.
251fn accept_or_break_out(solid: BrepSolid, entry: &str) -> Result<BrepSolid, KernelRefusal> {
252    if refuse_holes_leaving_their_faces(&solid, entry).is_ok() {
253        return Ok(solid);
254    }
255    break_out_until_contained(solid, entry)
256}
257
258/// Break out every hole the containment floor convicts, one at a time, and hand
259/// back a body that BOTH scans clean and passes the floor.
260///
261/// The rounds are what a two-mouth migration needs: repairing one mouth leaves
262/// the other still off its face, and — while it is — the body legitimately
263/// still passes through itself, because the second mouth's wall is still
264/// standing where the material is not. So an intermediate round is allowed to
265/// be flagged; the END of it is not. Nothing is returned that would not have
266/// been accepted had it been built that way in the first place.
267fn break_out_until_contained(solid: BrepSolid, entry: &str) -> Result<BrepSolid, KernelRefusal> {
268    let mut current = solid;
269    for _ in 0..MAX_BREAKOUT_ROUNDS {
270        let Some(breach) = first_hole_breach(&current) else {
271            // Contained. It still has to be SOUND to be returned.
272            let report = scan(&current, entry)?;
273            if report.is_flagged() {
274                return Err(KernelRefusal::unsound(
275                    KernelStage::Validate,
276                    SoundnessDefect::Crossing,
277                    crossing_faces(&report),
278                    format!(
279                        "{entry}: the breakout repair built a body and it SELF-INTERSECTS — {}",
280                        report.summary().unwrap_or_else(|| "no summary".into()),
281                    ),
282                ));
283            }
284            return Ok(current);
285        };
286        // The floor's refusal is the primary one; the breakout's decline is
287        // context appended to it, and the class stays the floor's.
288        let floor = hole_breach_refusal(&current, &breach, entry);
289        current = repair_hole_breakout(&current, &breach).map_err(|reason| {
290            floor.with_message(|floor| {
291                format!("{floor}. The breakout repair was offered this body and declined it: {reason}")
292            })
293        })?;
294    }
295    let breach = first_hole_breach(&current).expect("the loop only falls through on a breach");
296    Err(
297        hole_breach_refusal(&current, &breach, entry).with_message(|floor| {
298            format!(
299                "{floor}. {MAX_BREAKOUT_ROUNDS} breakouts were built and a hole is still off its face, so \
300                 this stops rather than repairing a body into one nobody asked for"
301            )
302        }),
303    )
304}
305
306/// [`accept_sound`] for a lane whose INPUTS may themselves self-intersect.
307///
308/// A boolean of two bodies that already pass through themselves is entitled to
309/// return a result that does: the defect came in with the operand and refusing
310/// it here would blame the wrong operation. What must never pass is a crossing
311/// the operation ITSELF introduced, so the inputs are scanned only when the
312/// output is flagged — the common case pays for one scan, not three.
313pub fn accept_sound_against(
314    inputs: &[&BrepSolid],
315    solid: BrepSolid,
316    entry: &str,
317) -> Result<BrepSolid, KernelRefusal> {
318    let report = scan(&solid, entry)?;
319    if !report.is_flagged() {
320        return Ok(solid);
321    }
322    for input in inputs {
323        let before = scan(input, entry)?;
324        if before.is_flagged() {
325            // Said plainly rather than silently: the operand arrived broken.
326            return Ok(solid);
327        }
328    }
329    accept_sound(solid, entry)
330}
331
332/// The scan, with a read failure reported as a refusal rather than swallowed:
333/// a result that could not be scanned is not a result that scanned clean.
334fn scan(solid: &BrepSolid, entry: &str) -> Result<SelfIntersectionReport, KernelRefusal> {
335    let options = SelfIntersectionOptions::for_solid(solid);
336    solid_self_intersections(solid, options).map_err(|message| {
337        KernelRefusal::internal(
338            KernelStage::Validate,
339            "soundness_scan",
340            format!("{entry}: the soundness scan could not run: {message}"),
341        )
342    })
343}
344
345/// The faces the scan's confirmed crossings name, each once, in report order.
346fn crossing_faces(report: &SelfIntersectionReport) -> Vec<u64> {
347    let mut faces = Vec::new();
348    for crossing in &report.confirmed {
349        for face in [crossing.face_a, crossing.face_b] {
350            if !faces.contains(&face) {
351                faces.push(face);
352            }
353        }
354    }
355    faces
356}
357
358/// The refusal for a face folded through itself — named, with both feet, the
359/// point and the margins, and pointing at the lane that owns the fix.
360fn fold_refusal(report: &SelfIntersectionReport, entry: &str) -> Option<KernelRefusal> {
361    let fold = report.folds.first()?;
362    let faces = report.folds.iter().map(|fold| fold.face).collect();
363    let message = format!(
364        "{entry}: the result's face {}{} FOLDS THROUGH ITSELF in 3D — its surface carries \
365         ({:.6}, {:.6}) and ({:.6}, {:.6}), {:.3e} apart in its own domain and both inside \
366         its trim, to the same point ({:.4}, {:.4}, {:.4}) (residual {:.3e}, branches {:.1} \
367         degrees apart){}. The face is wrong in AREA where its volume is not, so nothing that \
368         measures volume notices and `validate()` cannot see it at all. A fold is a trim that \
369         was never constructed: the folded part of the parameter region has to be carved away \
370         where the carrier is built, not repaired out of the finished body.",
371        fold.face,
372        fold.face_name
373            .as_ref()
374            .map(|name| format!(" '{name}'"))
375            .unwrap_or_default(),
376        fold.uv_a[0],
377        fold.uv_a[1],
378        fold.uv_b[0],
379        fold.uv_b[1],
380        fold.uv_separation,
381        fold.point.x,
382        fold.point.y,
383        fold.point.z,
384        fold.residual,
385        fold.normal_angle.to_degrees(),
386        if report.folds.len() > 1 {
387            format!(" ({} folded faces in all)", report.folds.len())
388        } else {
389            String::new()
390        },
391    );
392    Some(KernelRefusal::unsound(
393        KernelStage::Validate,
394        SoundnessDefect::Fold,
395        faces,
396        message,
397    ))
398}
399
400/// The refusal for two faces crossing, naming every pair and why the repair
401/// did not take it.
402fn crossing_refusal(report: &SelfIntersectionReport, entry: &str, reason: &str) -> KernelRefusal {
403    let pairs = report
404        .confirmed
405        .iter()
406        .map(|crossing| {
407            format!(
408                "faces {} and {} near ({:.4}, {:.4}, {:.4}) (straddle {:.3e} against a band of {:.1e})",
409                crossing.face_a,
410                crossing.face_b,
411                crossing.point.x,
412                crossing.point.y,
413                crossing.point.z,
414                crossing.straddle,
415                report.options.straddle_band
416            )
417        })
418        .collect::<Vec<_>>()
419        .join("; ");
420    KernelRefusal::unsound(
421        KernelStage::Validate,
422        SoundnessDefect::Crossing,
423        crossing_faces(report),
424        format!(
425            "{entry}: the result SELF-INTERSECTS — {pairs}. The enclosed space can still measure \
426             right, so neither a volume oracle nor `validate()` would have caught this. The repair \
427             that splits both faces along their carriers' intersection and drops the enclosed \
428             material did not take it: {reason}"
429        ),
430    )
431}
432
433// ---------------------------------------------------------------------------
434// The hole-containment floor
435// ---------------------------------------------------------------------------
436
437/// Stations per curved pcurve span when a loop is traced in its face's own
438/// parameters. A straight pcurve contributes its start point only — the next
439/// coedge begins where it ends.
440const LOOP_SAMPLES_PER_SPAN: usize = 32;
441
442/// A loop of a face as a closed polyline in that face's own parameter plane,
443/// traced coedge by coedge along each pcurve (already oriented to its coedge).
444fn loop_parameter_polyline(loop_record: &LoopRecord) -> Result<Vec<(f64, f64)>, KernelRefusal> {
445    pcurve_polyline(loop_record.coedges.iter().map(|coedge| &coedge.pcurve))
446}
447
448/// The same walk for a FRAGMENT's loop, which carries the same pcurves under a
449/// different record. One sampler, so a loop traced during the repair and the
450/// same loop traced by the containment floor are the same polyline.
451fn fragment_loop_polyline(
452    fragment_loop: &crate::fragment::FragmentLoop,
453) -> Result<Vec<(f64, f64)>, KernelRefusal> {
454    pcurve_polyline(fragment_loop.coedges.iter().map(|coedge| &coedge.pcurve))
455}
456
457fn pcurve_polyline<'a>(
458    pcurves: impl Iterator<Item = &'a crate::NurbsCurve>,
459) -> Result<Vec<(f64, f64)>, KernelRefusal> {
460    let mut points = Vec::new();
461    for pcurve in pcurves {
462        let [d0, d1] = pcurve.domain().or_refuse(KernelStage::Validate, "domain")?;
463        let steps = if pcurve.degree <= 1 && pcurve.control_points.len() == 2 {
464            1
465        } else {
466            let mut spans = 0usize;
467            for window in pcurve.knots.windows(2) {
468                if window[1] > window[0] {
469                    spans += 1;
470                }
471            }
472            spans.max(1) * LOOP_SAMPLES_PER_SPAN
473        };
474        for step in 0..steps {
475            let uv = pcurve.evaluate(d0 + (d1 - d0) * (step as f64 / steps as f64)).or_refuse(KernelStage::Validate, "evaluate")?;
476            points.push((uv.x, uv.y));
477        }
478    }
479    Ok(points)
480}
481
482fn polyline_area(points: &[(f64, f64)]) -> f64 {
483    let mut twice = 0.0;
484    for index in 0..points.len() {
485        let (x0, y0) = points[index];
486        let (x1, y1) = points[(index + 1) % points.len()];
487        twice += x0 * y1 - x1 * y0;
488    }
489    0.5 * twice
490}
491
492/// The outer loop's segments, bucketed by the band of `v` each one spans.
493///
494/// The floor asks a hole point two questions — even-odd parity against the
495/// outer loop, and whether the point sits within `tolerance` of it — and both
496/// read ONLY the segments whose own `v` range reaches the point's `v`. A
497/// segment that does not reach it has both endpoints on the same side of the
498/// horizontal ray, so it cannot toggle the parity; and every point of it is
499/// further away than `tolerance` in `v` alone, so it cannot be the witness
500/// that the point is on the boundary. Answering out of the band is therefore
501/// the SAME answer as walking the whole loop, not an approximation of it: the
502/// set of segments that can toggle is identical, parity is an XOR and does not
503/// care in what order they come, and the nearest segment — if there is one
504/// within `tolerance` at all — is among those searched.
505///
506/// What changes is the COST. The brute-force walk is `hole points × outer
507/// points`, which on an imported 100-tooth gear's flat is 1.1 million outer
508/// stations against 11 904 hole stations — 1.3e10 pairs on ONE face, 24 s of a
509/// 30 s replay. Through the bands it is `hole points × segments per band`,
510/// plus one linear pass to build.
511///
512/// Laid out CSR — one offsets array and one flat segment array — because a
513/// loop of a million points would otherwise want a million `Vec` headers.
514struct BoundaryBands<'a> {
515    points: &'a [(f64, f64)],
516    /// The bottom of the first band: the loop's lowest `v`.
517    v_lo: f64,
518    /// Bands per unit of `v`. Zero when the loop has no `v` extent to divide,
519    /// in which case there is one band and everything lands in it.
520    bands_per_v: f64,
521    /// `starts[band] .. starts[band + 1]` indexes `segments`.
522    starts: Vec<u32>,
523    /// Segment `i` is `points[i] -> points[(i + 1) % len]`, the closing
524    /// segment included.
525    segments: Vec<u32>,
526}
527
528impl<'a> BoundaryBands<'a> {
529    fn build(points: &'a [(f64, f64)]) -> Self {
530        let count = points.len();
531        debug_assert!(count < u32::MAX as usize, "segment indices are u32");
532        let (mut v_lo, mut v_hi) = (f64::INFINITY, f64::NEG_INFINITY);
533        let mut variation = 0.0;
534        for index in 0..count {
535            let (_, y0) = points[index];
536            let (_, y1) = points[(index + 1) % count];
537            v_lo = v_lo.min(y0);
538            v_hi = v_hi.max(y0);
539            variation += (y1 - y0).abs();
540        }
541        // One band per `variation / count` of `v`. That width is what makes the
542        // index linear in the loop whatever the loop's shape: a segment lands
543        // in `its own v extent / band width + 2` bands, and those sum to about
544        // `3 × count` however the vertical variation is distributed — a gear
545        // tooth's thousands of short segments and a box's four long ones alike.
546        let span = v_hi - v_lo;
547        let bands = if span.is_finite() && span > 0.0 && variation > 0.0 {
548            let wanted = span * count as f64 / variation;
549            if wanted.is_finite() && wanted >= 1.0 {
550                (wanted as usize).min(count.max(1))
551            } else {
552                1
553            }
554        } else {
555            1
556        };
557        let bands_per_v = if bands > 1 { bands as f64 / span } else { 0.0 };
558        let band_of = |v: f64| -> usize {
559            if bands_per_v == 0.0 {
560                return 0;
561            }
562            let raw = (v - v_lo) * bands_per_v;
563            // Written so a NaN takes the first branch rather than falling
564            // through to an `as usize` cast of it.
565            if !(raw > 0.0) {
566                0
567            } else if raw >= (bands - 1) as f64 {
568                bands - 1
569            } else {
570                raw as usize
571            }
572        };
573        let mut starts = vec![0u32; bands + 1];
574        for index in 0..count {
575            let (_, y0) = points[index];
576            let (_, y1) = points[(index + 1) % count];
577            let (lo, hi) = (band_of(y0.min(y1)), band_of(y0.max(y1)));
578            for start in starts[lo + 1..=hi + 1].iter_mut() {
579                *start += 1;
580            }
581        }
582        for band in 1..=bands {
583            starts[band] += starts[band - 1];
584        }
585        let mut cursor = starts.clone();
586        let mut segments = vec![0u32; starts[bands] as usize];
587        for index in 0..count {
588            let (_, y0) = points[index];
589            let (_, y1) = points[(index + 1) % count];
590            let (lo, hi) = (band_of(y0.min(y1)), band_of(y0.max(y1)));
591            for band in lo..=hi {
592                segments[cursor[band] as usize] = index as u32;
593                cursor[band] += 1;
594            }
595        }
596        Self {
597            points,
598            v_lo,
599            bands_per_v,
600            starts,
601            segments,
602        }
603    }
604
605    fn band_count(&self) -> usize {
606        self.starts.len() - 1
607    }
608
609    /// The band `v` falls in, clamped. A `v` outside the loop's own extent
610    /// clamps to an end band, whose segments then fail the tests on their own
611    /// terms — nothing straddles a ray the whole loop sits above or below.
612    fn band_of(&self, v: f64) -> usize {
613        if self.bands_per_v == 0.0 {
614            return 0;
615        }
616        let bands = self.band_count();
617        let raw = (v - self.v_lo) * self.bands_per_v;
618        if !(raw > 0.0) {
619            0
620        } else if raw >= (bands - 1) as f64 {
621            bands - 1
622        } else {
623            raw as usize
624        }
625    }
626
627    fn segment(&self, index: u32) -> ((f64, f64), (f64, f64)) {
628        let index = index as usize;
629        (
630            self.points[index],
631            self.points[(index + 1) % self.points.len()],
632        )
633    }
634
635    /// Even-odd parity: is `(u, v)` inside the closed loop?
636    fn contains(&self, point: (f64, f64)) -> bool {
637        let (u, v) = point;
638        let band = self.band_of(v);
639        let mut inside = false;
640        for &index in &self.segments[self.starts[band] as usize..self.starts[band + 1] as usize] {
641            let ((x0, y0), (x1, y1)) = self.segment(index);
642            if (y0 > v) != (y1 > v) && u < x0 + (v - y0) * (x1 - x0) / (y1 - y0) {
643                inside = !inside;
644            }
645        }
646        inside
647    }
648
649    /// Does `(u, v)` sit within `tolerance` of the loop — is it ON the
650    /// boundary rather than off the face?
651    ///
652    /// The bands searched are widened by one on each side of the `tolerance`
653    /// band, so the margin against a segment being excluded by a rounding of
654    /// its own `v` extent is a whole band rather than an ulp.
655    fn within(&self, point: (f64, f64), tolerance: f64) -> bool {
656        let (u, v) = point;
657        let lo = self.band_of(v - tolerance).saturating_sub(1);
658        let hi = (self.band_of(v + tolerance) + 1).min(self.band_count() - 1);
659        for band in lo..=hi {
660            for &index in &self.segments[self.starts[band] as usize..self.starts[band + 1] as usize]
661            {
662                let ((x0, y0), (x1, y1)) = self.segment(index);
663                let (dx, dy) = (x1 - x0, y1 - y0);
664                let length_squared = dx * dx + dy * dy;
665                let t = if length_squared > 0.0 {
666                    (((u - x0) * dx + (v - y0) * dy) / length_squared).clamp(0.0, 1.0)
667                } else {
668                    0.0
669                };
670                let (px, py) = (x0 + t * dx, y0 + t * dy);
671                if ((u - px).powi(2) + (v - py).powi(2)).sqrt() <= tolerance {
672                    return true;
673                }
674            }
675        }
676        false
677    }
678
679    /// The point of the loop nearest to `(u, v)` in the parameter plane, and
680    /// how far it is.
681    ///
682    /// Searched outward from the point's own band a ring at a time, stopping
683    /// when the next ring's `v` alone is further than the best found: every
684    /// segment in band `b` has every point of it within that band's `v`
685    /// range, so a band `r` away from the query's cannot hold a closer point
686    /// than `(r - 1)` band heights. A query beyond the loop's `v` extent
687    /// clamps to an end band and the same bound holds, larger. Called only
688    /// for a station that has already FAILED parity and the parameter band,
689    /// so its cost is paid once per conviction, not once per station.
690    fn nearest(&self, point: (f64, f64)) -> ((f64, f64), f64) {
691        let (u, v) = point;
692        let bands = self.band_count();
693        let centre = self.band_of(v);
694        let band_height = if self.bands_per_v > 0.0 { 1.0 / self.bands_per_v } else { f64::INFINITY };
695        let mut best = f64::INFINITY;
696        let mut best_point = self.points[0];
697        let search = |band: usize, best: &mut f64, best_point: &mut (f64, f64)| {
698            for &index in &self.segments[self.starts[band] as usize..self.starts[band + 1] as usize] {
699                let ((x0, y0), (x1, y1)) = self.segment(index);
700                let (dx, dy) = (x1 - x0, y1 - y0);
701                let length_squared = dx * dx + dy * dy;
702                let t = if length_squared > 0.0 {
703                    (((u - x0) * dx + (v - y0) * dy) / length_squared).clamp(0.0, 1.0)
704                } else {
705                    0.0
706                };
707                let candidate = (x0 + t * dx, y0 + t * dy);
708                let distance = ((u - candidate.0).powi(2) + (v - candidate.1).powi(2)).sqrt();
709                if distance < *best {
710                    *best = distance;
711                    *best_point = candidate;
712                }
713            }
714        };
715        for ring in 0..bands {
716            if ring > 1 && (ring - 1) as f64 * band_height > best {
717                break;
718            }
719            let below = centre.checked_sub(ring);
720            let above = if centre + ring < bands { Some(centre + ring) } else { None };
721            if below.is_none() && above.is_none() {
722                break;
723            }
724            if let Some(band) = below {
725                search(band, &mut best, &mut best_point);
726            }
727            if let Some(band) = above {
728                if ring > 0 {
729                    search(band, &mut best, &mut best_point);
730                }
731            }
732        }
733        (best_point, best)
734    }
735}
736
737/// THE HOLE-CONTAINMENT FLOOR: a face whose hole loop has left that face's
738/// own outer loop is refused, naming the hole — on EVERY carrier, planar or
739/// not.
740///
741/// A hole is a hole IN something. Carry a bore's mouth off the flat it opens
742/// through — a direct edit dragging the wall clear of the body — and what the
743/// fixed-topology road emits is the mouth loop hanging in the plane beside the
744/// face it is supposed to perforate, with the wall it bounds somewhere else
745/// entirely. Every other floor is blind to it: `validate()` tests INCIDENCE and
746/// the incidences are all intact; the scan needs two faces to CROSS and the
747/// runaway bore crosses nothing; and the divergence-theorem volume of a
748/// cylinder does not depend on where its axis sits, so the body can measure to
749/// the last bit of the right answer while being the wrong body. The correct
750/// result needs the hole to break through a neighbouring face — a topology
751/// change the direct edits do not make — so this refuses instead of shipping it.
752///
753/// Decided in the face's own parameter plane by parity against the outer loop
754/// (the one enclosing the largest parameter area). A point that fails parity
755/// but sits within `tolerance` of the outer loop is treated as ON it, so a
756/// mouth tangent to its face's own boundary is not convicted by sampling
757/// noise. The predicate is only as fine as the sampling: a curved hole poking
758/// out by less than its sampled chord sag can still pass.
759///
760/// On a PLANE the parameter plane is affine to space and the pcurves are exact
761/// images, so the band is the parameter band alone. On every other carrier the
762/// pcurves are FITTED, to [`crate::PCURVE_REFINEMENT_TOLERANCE`] in space, and
763/// a fit's noise can put a station of a legitimately tangent mouth a few
764/// parameter ulps outside its face. So a station that fails both tests on a
765/// non-affine face is convicted only if it is also further than
766/// [`CURVED_BREACH_ACQUITTAL`] IN SPACE from the nearest point of the outer
767/// loop — the same trace read back through the surface. That distance is the
768/// smallest curved breach the floor can see; it is a floor on the fit, not on
769/// the sampling. Until 2026-09-30 every non-planar face was skipped outright,
770/// so a mouth carried off a cylinder wall or a torus by a motion that pierced
771/// nothing the scan could resolve shipped as a wrong body.
772///
773/// A closed carrier is read in two shapes. Where NO loop winds the period
774/// (the nested case — a bored post's wall, whose outer loop holds the seam
775/// twice), the outer loop is the one enclosing the largest parameter area and
776/// the holes must lie inside it; a hole station is folded by whole periods
777/// into the outer loop's window only where that loop carries no seam coedge,
778/// so a hole traced across a seam that IS an edge of the outer loop (a hole
779/// with an edge of its own face running through it — the builders split the
780/// seam where a mouth reaches it) is a wrong body and is convicted. Where some
781/// loop DOES wind (the banded case — a refitted full cylinder is bounded by
782/// two rings and no seam, a dome cut off a sphere by one), the face has no
783/// outer loop and a hole must lie on every ring's material side, decided
784/// along the open direction with the ring's winding sign and the face's own
785/// orientation convention ([`banded_hole_breach`]). A band whose rings wind a
786/// carrier closed BOTH ways selects its intended region by the same orientation
787/// convention, using the next transverse boundary modulo that period. A loop
788/// winding both ways remains outside this arm. A breach the banded arm convicts is refused, not
789/// broken out: the breakout route reads a nested outer loop.
790///
791/// Both questions go through [`BoundaryBands`], which is an INDEX over the
792/// outer loop and not a coarser reading of it: the answers are the ones a walk
793/// of the whole traced polyline gives, off the whole traced polyline, at a
794/// cost that is no longer the product of the two loops' lengths.
795///
796/// This runs at the END of [`accept_sound`], on the body the repair left, so a
797/// crossing the repair can take is still taken — the reason an earlier
798/// primitive-level copy of this floor was removed.
799fn refuse_holes_leaving_their_faces(solid: &BrepSolid, entry: &str) -> Result<(), KernelRefusal> {
800    match first_hole_breach(solid) {
801        Some(breach) => Err(hole_breach_refusal(solid, &breach, entry)),
802        None => Ok(()),
803    }
804}
805
806/// A hole loop the floor has convicted: WHICH face, which loop of it, and the
807/// sample that fell outside, in that face's own parameters.
808///
809/// The floor's verdict is a yes or no; this is the same verdict with the
810/// witness kept, so a lane that can BUILD the right body has something to
811/// build it from. Nothing about the predicate changes by recording it.
812struct HoleBreach {
813    face: u64,
814    loop_index: usize,
815    loop_id: u64,
816    at: (f64, f64),
817    /// Convicted by the banded arm — the face has rings and no outer loop, so
818    /// the breakout route, which reads a nested outer loop, has nothing to
819    /// read and declines by name.
820    banded: bool,
821}
822
823/// THE FLOOR'S PREDICATE, verbatim — the first hole loop on any face that has
824/// left that face's own outer loop, or `None`.
825///
826/// This is the whole of the decision [`refuse_holes_leaving_their_faces`] used
827/// to make inline; the refusal is now written by [`hole_breach_refusal`] off
828/// what this returns. Same loops, same trace, same bands, same tolerance, same
829/// first-hit order.
830fn first_hole_breach(solid: &BrepSolid) -> Option<HoleBreach> {
831    for shell in &solid.shells {
832        for face in &shell.faces {
833            if face.loops.len() < 2 {
834                continue;
835            }
836            // Exact pcurves on an affine carrier; fitted ones everywhere else,
837            // which earn the acquittal in space.
838            let fitted = !face.surface.is_affine().unwrap_or(false);
839            let closed = face.surface.closed_directions().unwrap_or((false, false));
840            let period = (
841                face.surface.domain_u().map(|[a, b]| b - a).unwrap_or(0.0),
842                face.surface.domain_v().map(|[a, b]| b - a).unwrap_or(0.0),
843            );
844            let windings: Vec<(i32, i32)> = face
845                .loops
846                .iter()
847                .map(|record| loop_winding(record, closed, period))
848                .collect();
849            let polylines = face
850                .loops
851                .iter()
852                .map(loop_parameter_polyline)
853                .collect::<Result<Vec<_>, KernelRefusal>>()
854                // A loop this cannot be traced from is not a loop this can
855                // convict: the acceptance's own floors already ran.
856                .unwrap_or_default();
857            if polylines.len() != face.loops.len() || polylines.iter().any(Vec::is_empty) {
858                continue;
859            }
860            let breach = if windings.iter().all(|&winding| winding == (0, 0)) {
861                let spherical = matches!(face.surface.analytic(), Some(crate::AnalyticSurface::Sphere { .. }));
862                if spherical && !sphere_has_parameter_outer(solid, face, &polylines) {
863                    spherical_hole_breach(solid, face)
864                } else {
865                    nested_hole_breach(face, &polylines, fitted, closed, period)
866                }
867            } else {
868                banded_hole_breach(face, &polylines, &windings, fitted, closed, period)
869            };
870            if breach.is_some() {
871                return breach;
872            }
873        }
874    }
875    None
876}
877
878/// A bounded spherical patch can use the existing indexed nested floor.
879/// Its largest UV loop must be a real, correctly oriented material outer
880/// boundary, with the other real loops oriented as holes. A full-domain
881/// rectangle made only of seams and collapsed poles is not such a boundary.
882fn sphere_has_parameter_outer(
883    solid: &BrepSolid,
884    face: &crate::FaceRecord,
885    polylines: &[Vec<(f64, f64)>],
886) -> bool {
887    let areas: Vec<_> = polylines.iter().map(|points| polyline_area(points)).collect();
888    let Some(outer) = (0..areas.len()).max_by(|&a, &b| areas[a].abs().total_cmp(&areas[b].abs())) else {
889        return false;
890    };
891    let orientation = if face.same_sense { 1.0 } else { -1.0 };
892    if areas[outer] * orientation <= 0.0 { return false; }
893    let real = |index: usize| face.loops[index].coedges.iter().any(|coedge| {
894        face.loops.iter().flat_map(|rim| &rim.coedges)
895            .filter(|other| other.edge_id == coedge.edge_id).count() == 1
896            && !solid.edges.iter().any(|edge| edge.id == coedge.edge_id && edge.degenerate)
897    });
898    real(outer) && (0..areas.len()).all(|i| i == outer || !real(i) || areas[i] * orientation <= 0.0)
899}
900
901/// A sphere has no distinguished outer boundary: two disjoint negatively
902/// oriented trims can both be holes in the remaining sphere. Choosing the
903/// largest UV polygon as an outer loop falsely rejects that topology, and
904/// even mistakes an imported retraced pole cut for a runaway hole. Ask the
905/// same spherical material-side classifier used by containment and meshing:
906/// each real boundary must lie in the region left by the other loops.
907fn spherical_hole_breach(solid: &BrepSolid, face: &crate::FaceRecord) -> Option<HoleBreach> {
908    let mut uses = std::collections::HashMap::new();
909    for coedge in face.loops.iter().flat_map(|rim| &rim.coedges) {
910        *uses.entry(coedge.edge_id).or_insert(0usize) += 1;
911    }
912    for (index, rim) in face.loops.iter().enumerate() {
913        let mut other = face.clone();
914        other.loops.remove(index);
915        // A loop containing only domain seams and collapsed poles carries
916        // no material boundary. Keep mixed loops intact: the sampler reads
917        // each coedge's endpoint from the next coedge's start. Removing a
918        // paired seam joining two rims would bridge those rims with fake
919        // chords; the spherical classifier cancels the seam itself.
920        other.loops.retain(|boundary| {
921            boundary.coedges.iter().any(|coedge| {
922                uses[&coedge.edge_id] == 1
923                    && !solid.edges.iter().any(|edge| {
924                        edge.id == coedge.edge_id && edge.degenerate
925                    })
926            })
927        });
928        if other.loops.is_empty() {
929            continue;
930        }
931        let [u0, u1] = face.surface.domain_u().ok()?;
932        for coedge in &rim.coedges {
933            // A seam traversed twice and a collapsed pole have no spherical
934            // area. Their UV trace is not a boundary of the retained region.
935            if uses[&coedge.edge_id] > 1
936                || solid
937                    .edges
938                    .iter()
939                    .any(|edge| edge.id == coedge.edge_id && edge.degenerate)
940            {
941                continue;
942            }
943            let boundary = LoopRecord {
944                id: rim.id,
945                coedges: vec![coedge.clone()],
946            };
947            let Ok(mut points) = loop_parameter_polyline(&boundary) else {
948                continue;
949            };
950            // Straight UV edges contribute only their start in the ordinary
951            // polygon sampler. Include an interior witness here: two holes
952            // can share horizontal boundary levels while their vertical sides
953            // run through the other hole's interior.
954            if coedge.pcurve.degree == 1 && coedge.pcurve.control_points.len() == 2 {
955                let [a, b] = coedge.pcurve.domain().ok()?;
956                let midpoint = coedge.pcurve.evaluate((a + b) * 0.5).ok()?;
957                points.push((midpoint.x, midpoint.y));
958            }
959            for (u, v) in points {
960                if crate::parameter_point_in_face(
961                    &other,
962                    crate::Vec2 {
963                        x: u0 + (u - u0).rem_euclid(u1 - u0),
964                        y: v,
965                    },
966                    1e-6,
967                )
968                .ok()
969                    != Some(crate::PolygonClass::Outside)
970                {
971                    continue;
972                }
973                return Some(HoleBreach {
974                    face: face.id,
975                    loop_index: index,
976                    loop_id: rim.id,
977                    at: (u, v),
978                    banded: true,
979                });
980            }
981        }
982    }
983    None
984}
985
986/// How many times a loop goes round each CLOSED direction of its carrier, read
987/// off its coedges' pcurve ENDPOINTS rather than its traced stations: a ring
988/// the refit writes as one straight pcurve across the whole period traces to a
989/// single station, and the trace cannot see it go round. An open direction
990/// winds nothing.
991fn loop_winding(loop_record: &LoopRecord, closed: (bool, bool), period: (f64, f64)) -> (i32, i32) {
992    let (mut du, mut dv) = (0.0, 0.0);
993    for coedge in &loop_record.coedges {
994        let Ok([d0, d1]) = coedge.pcurve.domain() else { return (0, 0) };
995        let (Ok(start), Ok(end)) = (coedge.pcurve.evaluate(d0), coedge.pcurve.evaluate(d1)) else {
996            return (0, 0);
997        };
998        du += end.x - start.x;
999        dv += end.y - start.y;
1000    }
1001    let wind = |closed: bool, net: f64, period: f64| {
1002        if closed && period > 0.0 && net.is_finite() {
1003            (net / period).round() as i32
1004        } else {
1005            0
1006        }
1007    };
1008    (wind(closed.0, du, period.0), wind(closed.1, dv, period.1))
1009}
1010
1011/// Does this loop hold the same edge twice — a SEAM of a closed carrier, both
1012/// sides of it on this one face?
1013fn has_seam_pair(loop_record: &LoopRecord) -> bool {
1014    loop_record.coedges.iter().enumerate().any(|(index, coedge)| {
1015        loop_record.coedges[index + 1..]
1016            .iter()
1017            .any(|other| other.edge_id == coedge.edge_id)
1018    })
1019}
1020
1021/// THE NESTED CASE: no loop winds the carrier, so the loop enclosing the
1022/// largest parameter area is the face's outer boundary and every other loop is
1023/// a hole that must lie inside it. This is the floor exactly as the planar arm
1024/// always ran it, with two additions for a closed carrier: a hole station is
1025/// FOLDED by whole periods into the outer loop's own window where the outer
1026/// loop carries no seam coedge (a fitted pcurve unwraps across the seam on its
1027/// own terms, and a partial patch's outer loop and its hole need not have
1028/// unwrapped the same way), and never folded where it does — then the seam is
1029/// an edge of the outer loop and a hole across it is a wrong body.
1030fn nested_hole_breach(
1031    face: &crate::FaceRecord,
1032    polylines: &[Vec<(f64, f64)>],
1033    fitted: bool,
1034    closed: (bool, bool),
1035    period: (f64, f64),
1036) -> Option<HoleBreach> {
1037    let outer_index = (0..polylines.len())
1038        .max_by(|&a, &b| {
1039            polyline_area(&polylines[a])
1040                .abs()
1041                .total_cmp(&polyline_area(&polylines[b]).abs())
1042        })
1043        .unwrap_or(0);
1044    let outer = &polylines[outer_index];
1045    // Every hole point is asked the same two questions against this one
1046    // loop, so the loop is indexed ONCE and each question then reads the band
1047    // it falls in rather than the whole polyline. The answers are the ones
1048    // the whole-polyline walk gives; see [`BoundaryBands`].
1049    let bands = BoundaryBands::build(outer);
1050    let tolerance = boundary_tolerance(outer);
1051    let seamed = has_seam_pair(&face.loops[outer_index]);
1052    let (mut lo, mut hi) = ((f64::MAX, f64::MAX), (f64::MIN, f64::MIN));
1053    for &(u, v) in outer {
1054        lo = (lo.0.min(u), lo.1.min(v));
1055        hi = (hi.0.max(u), hi.1.max(v));
1056    }
1057    let centre = (0.5 * (lo.0 + hi.0), 0.5 * (lo.1 + hi.1));
1058    let fold_u = closed.0 && !seamed && period.0 > 0.0;
1059    let fold_v = closed.1 && !seamed && period.1 > 0.0;
1060    let fold = |(u, v): (f64, f64)| {
1061        (
1062            if fold_u { u + period.0 * ((centre.0 - u) / period.0).round() } else { u },
1063            if fold_v { v + period.1 * ((centre.1 - v) / period.1).round() } else { v },
1064        )
1065    };
1066    for (index, hole) in polylines.iter().enumerate() {
1067        if index == outer_index {
1068            continue;
1069        }
1070        let Some(at) = hole.iter().map(|&point| fold(point)).find(|&point| {
1071            !bands.contains(point)
1072                && !bands.within(point, tolerance)
1073                && !(fitted && acquitted_in_space(&face.surface, point, bands.nearest(point).0))
1074        }) else {
1075            continue;
1076        };
1077        return Some(HoleBreach {
1078            face: face.id,
1079            loop_index: index,
1080            loop_id: face.loops[index].id,
1081            at,
1082            banded: false,
1083        });
1084    }
1085    None
1086}
1087
1088/// A ring's segments in the parameter plane, one coedge after another with
1089/// every end point included, closed by the whole periods the ring winds — so
1090/// the segment that closes it is the short one back to the start's image, not
1091/// a jump across the domain.
1092struct Ring {
1093    segments: Vec<((f64, f64), (f64, f64))>,
1094    /// Is the face's material on the ring's POSITIVE side along the transverse
1095    /// direction?
1096    material_positive: bool,
1097    positive_winding: bool,
1098}
1099
1100/// THE BANDED CASE: some loop winds the carrier's closed direction, so the
1101/// face has no outer loop in the parameter plane — it is a band between RINGS
1102/// (a refitted full cylinder is bounded by two, a dome cut off a sphere by
1103/// one), and its holes are the loops that do not wind. A hole is in the face
1104/// when it is on every ring's MATERIAL side, decided by a ray along the open
1105/// direction: the ring's winding sign says which side its material is on once
1106/// the face's own orientation convention is read off a hole (a hole loop runs
1107/// with the material on its left when its parameter area is negative — the
1108/// mirror of the outer loop it is a hole in — and on its right otherwise).
1109/// Stations and rings are compared modulo the period, so a ring or a hole
1110/// unwrapped across the seam reads the same as one that was not.
1111///
1112/// Every winding loop must go round exactly once along the same closed axis.
1113/// If the transverse direction is also closed, oriented crossings select the
1114/// material region (including the complementary band); ring windings must
1115/// cancel. Loops winding both axes remain outside this arm.
1116fn banded_hole_breach(
1117    face: &crate::FaceRecord,
1118    polylines: &[Vec<(f64, f64)>],
1119    windings: &[(i32, i32)],
1120    fitted: bool,
1121    closed: (bool, bool),
1122    period: (f64, f64),
1123) -> Option<HoleBreach> {
1124    let rings_wind = |axis: usize| {
1125        windings
1126            .iter()
1127            .filter(|&&winding| winding != (0, 0))
1128            .all(|&(u, v)| {
1129                if axis == 0 {
1130                    u.abs() == 1 && v == 0
1131                } else {
1132                    v.abs() == 1 && u == 0
1133                }
1134            })
1135    };
1136    // `along` is the closed direction the rings wind; `open` names the
1137    // transverse axis (which can itself be periodic).
1138    let along = if rings_wind(0) && closed.0 && period.0 > 0.0 {
1139        0
1140    } else if rings_wind(1) && closed.1 && period.1 > 0.0 {
1141        1
1142    } else {
1143        return None;
1144    };
1145    let open = 1 - along;
1146    let axis = |point: (f64, f64), which: usize| if which == 0 { point.0 } else { point.1 };
1147    let period_along = axis(period, along);
1148    let transverse_period = if if open == 0 { closed.0 } else { closed.1 } {
1149        let p = axis(period, open);
1150        // Boundaries of a region on a torus must cancel in homology. A
1151        // nonseparating single ring does not define a material band.
1152        if p <= 0.0
1153            || windings
1154                .iter()
1155                .map(|&w| if along == 0 { w.0 } else { w.1 })
1156                .sum::<i32>()
1157                != 0
1158        {
1159            return None;
1160        }
1161        Some(p)
1162    } else {
1163        None
1164    };
1165    let domain_start = if along == 0 {
1166        face.surface.domain_u().ok()?[0]
1167    } else {
1168        face.surface.domain_v().ok()?[0]
1169    };
1170
1171    // The orientation convention, read off the first hole with an area.
1172    let left = polylines
1173        .iter()
1174        .zip(windings)
1175        .filter(|(_, &winding)| winding == (0, 0))
1176        .map(|(hole, _)| {
1177            // Area is translation invariant. Subtract a local origin before
1178            // multiplying: period translations must not cancel a small
1179            // hole's area to zero or invert its orientation convention.
1180            let origin = hole[0];
1181            let local: Vec<_> = hole.iter()
1182                .map(|&(u, v)| (u - origin.0, v - origin.1))
1183                .collect();
1184            polyline_area(&local)
1185        })
1186        .find(|area| *area != 0.0)?
1187        < 0.0;
1188
1189    let mut rings: Vec<Ring> = Vec::new();
1190    let mut extent = 0.0f64;
1191    for (index, record) in face.loops.iter().enumerate() {
1192        let winding = windings[index];
1193        if winding == (0, 0) {
1194            continue;
1195        }
1196        let mut points: Vec<(f64, f64)> = Vec::new();
1197        for coedge in &record.coedges {
1198            points.extend(coedge_parameter_polyline(coedge).ok()?);
1199        }
1200        let first = *points.first()?;
1201        points.push((
1202            first.0 + winding.0 as f64 * period.0,
1203            first.1 + winding.1 as f64 * period.1,
1204        ));
1205        for window in points.windows(2) {
1206            extent = extent
1207                .max(axis(window[0], open) - axis(window[1], open))
1208                .max(axis(window[1], open) - axis(window[0], open));
1209        }
1210        let segments = points
1211            .windows(2)
1212            .map(|window| (window[0], window[1]))
1213            .collect();
1214        // Material on the LEFT of a ring winding +u lies at +v; on the left of
1215        // one winding +v it lies at −u.
1216        let positive_winding = axis((winding.0 as f64, winding.1 as f64), along) > 0.0;
1217        let material_positive = if along == 0 {
1218            positive_winding == left
1219        } else {
1220            positive_winding != left
1221        };
1222        rings.push(Ring {
1223            segments,
1224            material_positive,
1225            positive_winding,
1226        });
1227    }
1228    let tolerance = (extent.max(period_along) * 1e-9).max(1e-12);
1229
1230    for (index, hole) in polylines.iter().enumerate() {
1231        if windings[index] != (0, 0) {
1232            continue;
1233        }
1234        for &station in hole {
1235            // Reduced into one period along the rings.
1236            let station = {
1237                let s = axis(station, along);
1238                let reduced = domain_start + (s - domain_start).rem_euclid(period_along);
1239                if along == 0 {
1240                    (reduced, station.1)
1241                } else {
1242                    (station.0, reduced)
1243                }
1244            };
1245            let held = if let Some(transverse) = transverse_period {
1246                periodic_band_holds(&rings, station, along, period_along, transverse)?
1247            } else {
1248                rings
1249                    .iter()
1250                    .all(|ring| ring_holds(ring, station, along, period_along))
1251            };
1252            if held {
1253                continue;
1254            }
1255            let (nearest, distance) =
1256                rings_nearest(&rings, station, along, period_along, transverse_period);
1257            if distance <= tolerance {
1258                continue;
1259            }
1260            if fitted && acquitted_in_space(&face.surface, station, nearest) {
1261                continue;
1262            }
1263            return Some(HoleBreach {
1264                face: face.id,
1265                loop_index: index,
1266                loop_id: face.loops[index].id,
1267                at: station,
1268                banded: true,
1269            });
1270        }
1271    }
1272    None
1273}
1274
1275/// Images relative to the segment midpoint nearest the query, rather than
1276/// the domain origin. Ordinary traced ring segments span at most a period
1277/// and a bit; two images either way cover those even after arbitrary whole
1278/// period translations. This is not a bound for multiply traversed segments.
1279const RING_IMAGES: [i32; 5] = [-2, -1, 0, 1, 2];
1280
1281/// Is `station` on this ring's material side? A ray from the station along
1282/// the OPEN direction, positive way, crosses the ring an odd number of times
1283/// exactly when the ring lies on the positive side of the station — and then
1284/// the station is on the ring's NEGATIVE side, which is the material side
1285/// exactly when the ring's material is not on its positive side.
1286fn ring_holds(ring: &Ring, station: (f64, f64), along: usize, period: f64) -> bool {
1287    let (s_along, s_open) = if along == 0 {
1288        (station.0, station.1)
1289    } else {
1290        (station.1, station.0)
1291    };
1292    let mut crossings = 0usize;
1293    for &(a, b) in &ring.segments {
1294        let (a_along, a_open) = if along == 0 { (a.0, a.1) } else { (a.1, a.0) };
1295        let (b_along, b_open) = if along == 0 { (b.0, b.1) } else { (b.1, b.0) };
1296        for image in RING_IMAGES {
1297            let shift =
1298                (((s_along - 0.5 * (a_along + b_along)) / period).round() + image as f64) * period;
1299            let (a_s, b_s) = (a_along + shift, b_along + shift);
1300            if (a_s > s_along) != (b_s > s_along) {
1301                let at = a_open + (s_along - a_s) * (b_open - a_open) / (b_s - a_s);
1302                if at > s_open {
1303                    crossings += 1;
1304                }
1305            }
1306        }
1307    }
1308    let ring_is_positive = crossings % 2 == 1;
1309    ring_is_positive != ring.material_positive
1310}
1311
1312/// On a doubly periodic chart there is no outside at infinity. The first
1313/// transverse boundary ahead of a station decides its material side. Its
1314/// orientation comes from the same hole-area convention as the open band;
1315/// reversing all loops therefore preserves the region, while reversing just
1316/// the rings chooses its complement. Signed events cancel tangent contacts.
1317fn periodic_band_holds(
1318    rings: &[Ring],
1319    station: (f64, f64),
1320    along: usize,
1321    period: f64,
1322    transverse: f64,
1323) -> Option<bool> {
1324    let (s, t) = if along == 0 {
1325        station
1326    } else {
1327        (station.1, station.0)
1328    };
1329    let mut events = Vec::new();
1330    for ring in rings {
1331        for &(a, b) in &ring.segments {
1332            let (a_s, a_t) = if along == 0 { a } else { (a.1, a.0) };
1333            let (b_s, b_t) = if along == 0 { b } else { (b.1, b.0) };
1334            let centre = ((s - 0.5 * (a_s + b_s)) / period).round();
1335            for image in RING_IMAGES {
1336                let shift = (centre + image as f64) * period;
1337                let (a_image, b_image) = (a_s + shift, b_s + shift);
1338                if (a_image > s) != (b_image > s) {
1339                    // Both segments incident to a tangent vertex must emit
1340                    // the stored vertex value. Re-interpolating an endpoint
1341                    // can move one event by ulps, splitting an exact signed
1342                    // cancellation and falsely rejecting a remote station.
1343                    // Compare in the same shifted chart as the crossing test;
1344                    // no event-distance tolerance or physical band changes.
1345                    let at = if s == a_image {
1346                        a_t
1347                    } else if s == b_image {
1348                        b_t
1349                    } else {
1350                        a_t + (s - a_s - shift) * (b_t - a_t) / (b_s - a_s)
1351                    };
1352                    let positive = if (b_s > a_s) == ring.positive_winding {
1353                        ring.material_positive
1354                    } else {
1355                        !ring.material_positive
1356                    };
1357                    events.push((
1358                        (at - t).rem_euclid(transverse),
1359                        if positive { 1i32 } else { -1 },
1360                    ));
1361                }
1362            }
1363        }
1364    }
1365    events.sort_by(|a, b| a.0.total_cmp(&b.0));
1366    let mut i = 0;
1367    while i < events.len() {
1368        let distance = events[i].0;
1369        let mut sign = 0;
1370        while i < events.len() && events[i].0 == distance {
1371            sign += events[i].1;
1372            i += 1;
1373        }
1374        if sign != 0 {
1375            return Some(sign < 0);
1376        }
1377    }
1378    None
1379}
1380
1381/// The nearest point of any ring to `station`, over the rings' period images,
1382/// and its distance in the parameter plane.
1383fn rings_nearest(
1384    rings: &[Ring],
1385    station: (f64, f64),
1386    along: usize,
1387    period: f64,
1388    transverse: Option<f64>,
1389) -> ((f64, f64), f64) {
1390    let (u, v) = station;
1391    let mut best = (station, f64::INFINITY);
1392    for ring in rings {
1393        for &(a, b) in &ring.segments {
1394            for image in RING_IMAGES {
1395                let midpoint = (0.5 * (a.0 + b.0), 0.5 * (a.1 + b.1));
1396                let (s, m) = if along == 0 {
1397                    (u, midpoint.0)
1398                } else {
1399                    (v, midpoint.1)
1400                };
1401                let along_shift = (((s - m) / period).round() + image as f64) * period;
1402                for across_image in if transverse.is_some() {
1403                    &RING_IMAGES[..]
1404                } else {
1405                    &RING_IMAGES[2..3]
1406                } {
1407                    let across_shift = transverse
1408                        .map(|p| {
1409                            let (s, m) = if along == 0 {
1410                                (v, midpoint.1)
1411                            } else {
1412                                (u, midpoint.0)
1413                            };
1414                            (((s - m) / p).round() + *across_image as f64) * p
1415                        })
1416                        .unwrap_or(0.0);
1417                    let shift = if along == 0 {
1418                        (along_shift, across_shift)
1419                    } else {
1420                        (across_shift, along_shift)
1421                    };
1422                    let (x0, y0) = (a.0 + shift.0, a.1 + shift.1);
1423                    let (x1, y1) = (b.0 + shift.0, b.1 + shift.1);
1424                    let (dx, dy) = (x1 - x0, y1 - y0);
1425                    let length_squared = dx * dx + dy * dy;
1426                    let t = if length_squared > 0.0 {
1427                        (((u - x0) * dx + (v - y0) * dy) / length_squared).clamp(0.0, 1.0)
1428                    } else {
1429                        0.0
1430                    };
1431                    let candidate = (x0 + t * dx, y0 + t * dy);
1432                    let distance = ((u - candidate.0).powi(2) + (v - candidate.1).powi(2)).sqrt();
1433                    if distance < best.1 {
1434                        best = (candidate, distance);
1435                    }
1436                }
1437            }
1438        }
1439    }
1440    best
1441}
1442
1443/// The "on the boundary" band, measured against the outer loop's own parameter
1444/// extent so it means the same thing on a 1 mm face and on a 1 m one.
1445fn boundary_tolerance(outer: &[(f64, f64)]) -> f64 {
1446    let (mut lo, mut hi) = ((f64::MAX, f64::MAX), (f64::MIN, f64::MIN));
1447    for &(u, v) in outer {
1448        lo = (lo.0.min(u), lo.1.min(v));
1449        hi = (hi.0.max(u), hi.1.max(v));
1450    }
1451    let extent = (hi.0 - lo.0).max(hi.1 - lo.1);
1452    (extent * 1e-9).max(1e-12)
1453}
1454
1455/// How far IN SPACE a station of a fitted hole loop may sit outside its face's
1456/// outer loop and still be read as ON it: ten times the floor the pcurve fit
1457/// refines to ([`crate::PCURVE_REFINEMENT_TOLERANCE`], 1e-7). A tangent mouth's
1458/// fit noise is under the floor; a breach the floor is for is a mouth carried
1459/// out by a motion, orders above it.
1460const CURVED_BREACH_ACQUITTAL: f64 = 10.0 * crate::PCURVE_REFINEMENT_TOLERANCE;
1461
1462/// Is a station that failed parity and the parameter band still within
1463/// [`CURVED_BREACH_ACQUITTAL`] of the face's boundary IN SPACE? Read through
1464/// the face's own surface at the station and at the boundary's nearest
1465/// parameter point (`nearest`), so a fitted pcurve's parameter noise is
1466/// judged by what it amounts to on the carrier. A surface that cannot be
1467/// evaluated acquits nothing.
1468fn acquitted_in_space(
1469    surface: &crate::NurbsSurface,
1470    point: (f64, f64),
1471    nearest: (f64, f64),
1472) -> bool {
1473    // EXTENDED, not clamped: a station past the end of an open direction is
1474    // read where the carrier's own ruled extension puts it, and one past a
1475    // seam where the period wraps it. `evaluate` clamps a parameter into the
1476    // domain, which would put every overshoot back ON the rim and acquit it.
1477    match (
1478        surface.evaluate_extended(point.0, point.1),
1479        surface.evaluate_extended(nearest.0, nearest.1),
1480    ) {
1481        (Ok(here), Ok(there)) => here.sub(there).length() <= CURVED_BREACH_ACQUITTAL,
1482        _ => false,
1483    }
1484}
1485
1486/// The floor's refusal, written off the breach it convicted.
1487fn hole_breach_refusal(solid: &BrepSolid, breach: &HoleBreach, entry: &str) -> KernelRefusal {
1488    let face = solid
1489        .shells
1490        .iter()
1491        .flat_map(|shell| &shell.faces)
1492        .find(|face| face.id == breach.face);
1493    let label = match face.and_then(|face| face.name.as_deref()) {
1494        Some(name) => format!("`{name}` (face {})", breach.face),
1495        None => format!("face {}", breach.face),
1496    };
1497    let (u, v) = breach.at;
1498    let where_in_space = face
1499        .and_then(|face| face.surface.evaluate_extended(u, v).ok())
1500        .map(|point| format!(" — ({:.4}, {:.4}, {:.4}) in space", point.x, point.y, point.z))
1501        .unwrap_or_default();
1502    KernelRefusal::unsound(
1503        KernelStage::Validate,
1504        SoundnessDefect::HoleBreach,
1505        vec![breach.face],
1506        format!(
1507            "{entry}: hole loop {} of {label} has LEFT that face — it runs outside the \
1508             face's own outer boundary, at ({u:.6}, {v:.6}) in the face's parameters{}. \
1509             A hole is a hole IN a face; this one bounds a wall that no longer opens \
1510             through it, so the right body needs the hole to break through a \
1511             neighbouring face, a topology change this operation does not make. \
1512             `validate()` cannot see it (every incidence is intact), the \
1513             self-intersection scan cannot (nothing crosses), and the volume need not \
1514             change at all — refusing rather than returning the wrong body",
1515            breach.loop_id, where_in_space,
1516        ),
1517    )
1518}
1519
1520// ---------------------------------------------------------------------------
1521// The breakout route: a hole that has left its face onto a NAMED neighbour
1522// ---------------------------------------------------------------------------
1523
1524/// The faces a breakout is between: the WALL the convicted hole loop bounds,
1525/// and the ONE neighbour of the breached face the hole has run out onto.
1526struct BreakoutPair {
1527    wall: u64,
1528    neighbour: u64,
1529}
1530
1531/// WHICH neighbour the runaway hole has gone onto — read in the breached
1532/// face's own parameter plane, where the question is a segment crossing and
1533/// not a guess.
1534///
1535/// The hole loop bounds a wall (for a bore, the bore's own cylindrical face):
1536/// exactly one other face answers for its edges, and that is the face whose
1537/// carrier has to be re-trimmed. The hole has left through some stretch of the
1538/// breached face's OUTER loop, and each outer coedge is shared with exactly one
1539/// neighbouring face, so the coedges the hole polyline crosses name the faces
1540/// it has gone out onto.
1541///
1542/// This refuses rather than choosing whenever the answer is not a single pair:
1543/// a hole bounding more than one face, a hole that crosses no outer coedge at
1544/// all (it has left the face's own parameter patch entirely — the runaway), and
1545/// a hole crossing into MORE THAN ONE neighbour, which is a breakout over a
1546/// corner and needs both re-trims resolved together rather than one at a time.
1547fn breakout_pair(solid: &BrepSolid, breach: &HoleBreach) -> Result<BreakoutPair, KernelRefusal> {
1548    let wall = breakout_wall(solid, breach)?;
1549    match breakout_neighbours_crossed(solid, breach, wall)?[..] {
1550        [neighbour] => Ok(BreakoutPair { wall, neighbour }),
1551        [] => Err(KernelRefusal::unsupported(KernelStage::Validate, NOT_A_STRADDLE_WHAT, NOT_A_STRADDLE)),
1552        ref many => Err(KernelRefusal::unsupported(KernelStage::Validate, "breakout.pair", format!(
1553            "the runaway hole crosses into {} neighbouring faces at once ({many:?}) — a \
1554             breakout over a corner, where the two re-trims bound each other and resolving one \
1555             at a time is a different problem from resolving both",
1556            many.len(),
1557        ))),
1558    }
1559}
1560
1561/// The marker [`breakout_pair`] returns when the hole does not STRADDLE its
1562/// face's boundary. It has either migrated wholly onto another face or left the
1563/// body; [`repair_hole_breakout`] tells those apart, by trying.
1564const NOT_A_STRADDLE: &str = "the hole does not straddle its own face's boundary";
1565
1566/// The slug [`breakout_pair`] mints [`NOT_A_STRADDLE`] under
1567/// (`UnsupportedGeometry`), shared with [`is_not_a_straddle`].
1568const NOT_A_STRADDLE_WHAT: &str = "breakout.not_a_straddle";
1569
1570/// Is this [`breakout_pair`]'s non-straddle answer? Read off the class and
1571/// slug, so the route's decision does not follow the sentence.
1572fn is_not_a_straddle(refusal: &KernelRefusal) -> bool {
1573    matches!(
1574        &refusal.class,
1575        crate::RefusalClass::UnsupportedGeometry { what } if what == NOT_A_STRADDLE_WHAT
1576    )
1577}
1578
1579/// The face the convicted hole loop BOUNDS — the moved carrier, for a bore the
1580/// bore's own wall. Exactly one other face may answer for its edges.
1581fn breakout_wall(solid: &BrepSolid, breach: &HoleBreach) -> Result<u64, KernelRefusal> {
1582    let face = face_by_id(solid, breach.face)?;
1583    let mut walls: Vec<u64> = Vec::new();
1584    for coedge in &face.loops[breach.loop_index].coedges {
1585        for other in solid.shells.iter().flat_map(|shell| &shell.faces) {
1586            if other.id == face.id {
1587                continue;
1588            }
1589            if other
1590                .loops
1591                .iter()
1592                .any(|wire| wire.coedges.iter().any(|use_| use_.edge_id == coedge.edge_id))
1593                && !walls.contains(&other.id)
1594            {
1595                walls.push(other.id);
1596            }
1597        }
1598    }
1599    match walls[..] {
1600        [wall] => Ok(wall),
1601        _ => Err(KernelRefusal::unsupported(KernelStage::Validate, "breakout.wall_count", format!(
1602            "the runaway hole loop bounds {} face(s) ({walls:?}); this route re-trims ONE moved \
1603             carrier against the body and cannot decide which of several is the one that moved",
1604            walls.len(),
1605        ))),
1606    }
1607}
1608
1609fn face_by_id<'a>(
1610    solid: &'a BrepSolid,
1611    id: u64,
1612) -> Result<&'a crate::FaceRecord, KernelRefusal> {
1613    solid
1614        .shells
1615        .iter()
1616        .flat_map(|shell| &shell.faces)
1617        .find(|face| face.id == id)
1618        .ok_or_else(|| {
1619            KernelRefusal::internal(KernelStage::Validate, "face_by_id", format!("face {id} is not on the body"))
1620        })
1621}
1622
1623/// The neighbours the hole has run out ONTO, read as segment crossings in the
1624/// breached face's own parameter plane.
1625///
1626/// This answers the STRADDLE: part of the mouth still inside the face it was
1627/// recorded on, part outside. It returns nothing for a mouth that has migrated
1628/// wholly onto another face — such a loop is entirely outside the outer loop
1629/// and crosses none of its coedges — and nothing for one that has left the body
1630/// altogether. Those two are told apart downstream, by geometry, in
1631/// [`repair_hole_breakout`].
1632fn breakout_neighbours_crossed(
1633    solid: &BrepSolid,
1634    breach: &HoleBreach,
1635    wall: u64,
1636) -> Result<Vec<u64>, KernelRefusal> {
1637    let face = face_by_id(solid, breach.face)?;
1638    let polylines = face
1639        .loops
1640        .iter()
1641        .map(loop_parameter_polyline)
1642        .collect::<Result<Vec<_>, KernelRefusal>>()
1643        .map_err(|error| {
1644            error.with_message(|error| format!("the breached face's loops could not be traced: {error}"))
1645        })?;
1646    let outer_index = (0..polylines.len())
1647        .max_by(|&a, &b| {
1648            polyline_area(&polylines[a])
1649                .abs()
1650                .total_cmp(&polyline_area(&polylines[b]).abs())
1651        })
1652        .unwrap_or(0);
1653    if outer_index == breach.loop_index {
1654        return Err(KernelRefusal::internal(KernelStage::Validate, "breakout.outer_loop", "the convicted loop is the face's own outer loop"));
1655    }
1656    let hole = &polylines[breach.loop_index];
1657
1658    let mut neighbours: Vec<u64> = Vec::new();
1659    for coedge in &face.loops[outer_index].coedges {
1660        let side = coedge_parameter_polyline(coedge)
1661            .map_err(|error| error.with_message(|error| format!("an outer coedge could not be traced: {error}")))?;
1662        if !polylines_cross(hole, &side) {
1663            continue;
1664        }
1665        for other in solid.shells.iter().flat_map(|shell| &shell.faces) {
1666            if other.id == face.id || other.id == wall {
1667                continue;
1668            }
1669            if other
1670                .loops
1671                .iter()
1672                .any(|wire| wire.coedges.iter().any(|use_| use_.edge_id == coedge.edge_id))
1673                && !neighbours.contains(&other.id)
1674            {
1675                neighbours.push(other.id);
1676            }
1677        }
1678    }
1679    Ok(neighbours)
1680}
1681
1682/// Every face across the breached face's OUTER boundary — the faces a mouth
1683/// leaving that face can have arrived on.
1684///
1685/// A migration is a mouth that has walked off one face and onto the next. The
1686/// next one is over an edge, so this is the candidate set, and it is small: the
1687/// outer loop's own neighbours, the wall excepted. A carrier that has reached
1688/// something further away than that is not a case this route claims, and it
1689/// says so rather than widening until it finds a face it can cut.
1690fn faces_over_the_outer_boundary(
1691    solid: &BrepSolid,
1692    breach: &HoleBreach,
1693    wall: u64,
1694) -> Result<Vec<u64>, KernelRefusal> {
1695    let face = face_by_id(solid, breach.face)?;
1696    let polylines = face
1697        .loops
1698        .iter()
1699        .map(loop_parameter_polyline)
1700        .collect::<Result<Vec<_>, KernelRefusal>>()
1701        .unwrap_or_default();
1702    let outer_index = (0..polylines.len())
1703        .max_by(|&a, &b| {
1704            polyline_area(&polylines[a])
1705                .abs()
1706                .total_cmp(&polyline_area(&polylines[b]).abs())
1707        })
1708        .unwrap_or(0);
1709    let mut over: Vec<u64> = Vec::new();
1710    for coedge in &face.loops[outer_index].coedges {
1711        for other in solid.shells.iter().flat_map(|shell| &shell.faces) {
1712            if other.id == face.id || other.id == wall {
1713                continue;
1714            }
1715            if other
1716                .loops
1717                .iter()
1718                .any(|wire| wire.coedges.iter().any(|use_| use_.edge_id == coedge.edge_id))
1719                && !over.contains(&other.id)
1720            {
1721                over.push(other.id);
1722            }
1723        }
1724    }
1725    Ok(over)
1726}
1727
1728/// One coedge as a polyline in its face's parameters, END POINT INCLUDED, so
1729/// the segments it yields are the whole of that coedge.
1730///
1731/// [`loop_parameter_polyline`] deliberately leaves each coedge's end point to
1732/// the next coedge's start; a single coedge asked about on its own has no next.
1733fn coedge_parameter_polyline(
1734    coedge: &crate::topology::CoedgeRecord,
1735) -> Result<Vec<(f64, f64)>, KernelRefusal> {
1736    let pcurve = &coedge.pcurve;
1737    let [d0, d1] = pcurve.domain().or_refuse(KernelStage::Validate, "domain")?;
1738    let steps = if pcurve.degree <= 1 && pcurve.control_points.len() == 2 {
1739        1
1740    } else {
1741        let mut spans = 0usize;
1742        for window in pcurve.knots.windows(2) {
1743            if window[1] > window[0] {
1744                spans += 1;
1745            }
1746        }
1747        spans.max(1) * LOOP_SAMPLES_PER_SPAN
1748    };
1749    let mut points = Vec::with_capacity(steps + 1);
1750    for step in 0..=steps {
1751        let uv = pcurve.evaluate(d0 + (d1 - d0) * (step as f64 / steps as f64)).or_refuse(KernelStage::Validate, "evaluate")?;
1752        points.push((uv.x, uv.y));
1753    }
1754    Ok(points)
1755}
1756
1757/// Does the CLOSED polyline `loop_points` cross the OPEN polyline `side`?
1758/// Proper segment intersection, in the face's own parameters.
1759fn polylines_cross(loop_points: &[(f64, f64)], side: &[(f64, f64)]) -> bool {
1760    for index in 0..loop_points.len() {
1761        let a = loop_points[index];
1762        let b = loop_points[(index + 1) % loop_points.len()];
1763        for window in side.windows(2) {
1764            if segments_cross(a, b, window[0], window[1]) {
1765                return true;
1766            }
1767        }
1768    }
1769    false
1770}
1771
1772fn segments_cross(a: (f64, f64), b: (f64, f64), c: (f64, f64), d: (f64, f64)) -> bool {
1773    let orient = |p: (f64, f64), q: (f64, f64), r: (f64, f64)| {
1774        (q.0 - p.0) * (r.1 - p.1) - (q.1 - p.1) * (r.0 - p.0)
1775    };
1776    let (d1, d2) = (orient(c, d, a), orient(c, d, b));
1777    let (d3, d4) = (orient(a, b, c), orient(a, b, d));
1778    ((d1 > 0.0) != (d2 > 0.0)) && ((d3 > 0.0) != (d4 > 0.0))
1779}
1780
1781/// THE BREAKOUT, reached from the containment floor instead of from the scan.
1782///
1783/// The floor convicts a hole loop that has left the face it is recorded on,
1784/// planar or curved. Where that hole has left ONTO a named neighbour — the case the operator
1785/// reported, an exit hole dragged across the edge between two faces — the right
1786/// body is the one the self-crossing repair already builds for a bore carried
1787/// out through a side wall: the moved carrier and the neighbour split along
1788/// their exact section, the pieces that ended up on the wrong side dropped, and
1789/// the faces left holding an unanswered boundary RE-TRIMMED, which merges the
1790/// mouth into the outer loops of the faces it now opens through.
1791///
1792/// What makes it the SAME repair and not a second one is that the extent is
1793/// still derived and not invented: the tool is the moved carrier trimmed
1794/// against the body, and where it meets the body is what the imprint computes.
1795/// The route in is what changes — the scan needs a mesh crossing it can
1796/// confirm, and at the near edge of a breakout the crossing is a sliver the
1797/// tessellation does not resolve, so the floor sees it first.
1798///
1799/// The genuine runaway is excluded by GEOMETRY and not by a threshold. A bore
1800/// carried clean off the body crosses no boundary of the face it left, so
1801/// [`breakout_pair`] finds no neighbour and this refuses before a single face
1802/// is split; and even given a pair, the imprint of a carrier that misses the
1803/// body cuts neither trim and [`split_and_drop`] declines on its own terms.
1804fn repair_hole_breakout(solid: &BrepSolid, breach: &HoleBreach) -> Result<BrepSolid, KernelRefusal> {
1805    let origin = || RepairOrigin::Breakout {
1806        face: breach.face,
1807        loop_id: breach.loop_id,
1808    };
1809    if breach.banded {
1810        return Err(KernelRefusal::unsupported(
1811            KernelStage::Validate,
1812            "breakout.band_face",
1813            format!(
1814                "face {} is a band bounded by rings that wind its carrier's period, with no outer \
1815                 loop in its parameter plane; this route re-trims a hole against the outer loop \
1816                 it straddles and does not re-trim a band",
1817                breach.face,
1818            ),
1819        ));
1820    }
1821    // THE STRADDLE: part of the mouth still inside the face it was recorded on,
1822    // part outside. Which neighbour is read off the crossing, exactly.
1823    match breakout_pair(solid, breach) {
1824        Ok(BreakoutPair { wall, neighbour }) => {
1825            return split_and_drop(solid, wall, neighbour, origin())
1826        }
1827        // Every refusal but the non-straddle is this route's own, classed as it
1828        // always was here; the non-straddle is read off its slug, not its text.
1829        Err(reason) if !is_not_a_straddle(&reason) => {
1830            return Err(KernelRefusal::unsupported(
1831                KernelStage::Validate,
1832                "breakout.pair",
1833                reason.message,
1834            ))
1835        }
1836        Err(_) => {}
1837    }
1838
1839    // THE MIGRATION, or the RUNAWAY. The mouth is wholly outside the face it
1840    // was recorded on, so nothing in that face's own parameter plane can say
1841    // where it went — a mouth that has walked onto the next face and a mouth
1842    // that has left the solid look the same from there.
1843    //
1844    // They do not look the same to the IMPRINT. The question that separates
1845    // them is whether the moved carrier still meets a face of the body, and
1846    // `split_and_drop` answers exactly that: handed a face the carrier misses
1847    // it declines with "the carriers' intersection reaches ... neither", before
1848    // anything is dropped. So the candidates are tried, and the answer is
1849    // decided BY THE RESULT — the same principle the drop enumeration inside
1850    // already runs on, and a discriminator that cannot drift, because a carrier
1851    // clear of the body cuts nothing anywhere.
1852    //
1853    // More than one candidate building is not an answer: the mouth would be on
1854    // two faces at once with no reason to prefer either, and choosing would be
1855    // the guess this module exists not to make.
1856    let wall = breakout_wall(solid, breach).map_err(|refusal| {
1857        KernelRefusal::internal(KernelStage::Validate, "breakout.wall", refusal.message)
1858    })?;
1859    let mut candidates = faces_over_the_outer_boundary(solid, breach, wall)
1860        .map_err(|refusal| {
1861            KernelRefusal::internal(KernelStage::Validate, "breakout.candidates", refusal.message)
1862        })?;
1863    if candidates.is_empty() {
1864        return Err(KernelRefusal::unsupported(
1865            KernelStage::Validate,
1866            "breakout.runaway",
1867            RUNAWAY,
1868        ));
1869    }
1870
1871    // WHICH face the mouth moved onto, when its own face's parameter plane can
1872    // no longer say. The carrier is a whole surface and generally meets the
1873    // body in more than one place — a through bore leaves by one face and
1874    // enters by another, and both are faces this carrier can be re-trimmed
1875    // against — so "some face it cuts" is not the answer. The answer is the
1876    // face the MIGRATED MOUTH IS AT: the candidates are ordered by the least
1877    // 3D distance from the convicted hole loop to the face's own trim, and the
1878    // nearest one that the repair can actually build is taken.
1879    //
1880    // A TIE is refused rather than broken. Two faces the same distance from the
1881    // mouth means the mouth sits on the edge between them, which is a corner
1882    // breakout — the case whose two re-trims bound each other.
1883    let mouth = hole_loop_in_space(solid, breach).map_err(|refusal| {
1884        KernelRefusal::internal(KernelStage::Validate, "breakout.mouth", refusal.message)
1885    })?;
1886    let scale = crate::solid_scale(solid);
1887    let mut ranked: Vec<(f64, u64)> = Vec::new();
1888    for candidate in candidates.drain(..) {
1889        ranked.push((
1890            distance_to_face(solid, candidate, &mouth)
1891                .map_err(|refusal| {
1892                    KernelRefusal::internal(KernelStage::Validate, "breakout.distance", refusal.message)
1893                })?,
1894            candidate,
1895        ));
1896    }
1897    ranked.sort_by(|a, b| a.0.total_cmp(&b.0));
1898    if ranked.len() > 1 && (ranked[1].0 - ranked[0].0).abs() <= scale * 1e-9 {
1899        return Err(KernelRefusal::ill_posed(
1900            KernelStage::Validate,
1901            "breakout.corner_tie",
1902            format!(
1903                "the migrated mouth is the same distance ({:.6}) from faces {} and {}, so the body \
1904                 does not say which of them it moved onto — a breakout over the corner between \
1905                 them, where the two re-trims bound each other",
1906                ranked[0].0, ranked[0].1, ranked[1].1,
1907            ),
1908        ));
1909    }
1910
1911    let carried = take_crossing_repairs();
1912    let mut declined: Vec<String> = Vec::new();
1913    for (distance, candidate) in ranked {
1914        match split_and_drop(solid, wall, candidate, origin()) {
1915            Ok(body) => {
1916                // The trial that built pushed a record; the ones that declined
1917                // pushed none. Keep that one and put the caller's ledger back.
1918                let mine = take_crossing_repairs();
1919                restore_repairs(carried.into_iter().chain(mine).collect());
1920                return Ok(body);
1921            }
1922            Err(reason) => {
1923                declined.push(format!("face {candidate} at {distance:.6}: {reason}"))
1924            }
1925        }
1926    }
1927    restore_repairs(carried);
1928    Err(KernelRefusal::unsupported(
1929        KernelStage::Validate,
1930        "breakout.runaway",
1931        format!(
1932            "{RUNAWAY} — the moved carrier was offered every face across that boundary, nearest \
1933             first, and cut none of them ({})",
1934            declined.join(" | ")
1935        ),
1936    ))
1937}
1938
1939/// The convicted hole loop as 3D points: its pcurves are in the breached face's
1940/// own parameters, so they are read back through that face's surface — the same
1941/// road the floor takes, and the reason the floor was never wrong about where a
1942/// loop is.
1943fn hole_loop_in_space(solid: &BrepSolid, breach: &HoleBreach) -> Result<Vec<crate::Vec3>, KernelRefusal> {
1944    let face = face_by_id(solid, breach.face)?;
1945    let uv = loop_parameter_polyline(&face.loops[breach.loop_index])?;
1946    uv.into_iter()
1947        .map(|(u, v)| face.surface.evaluate(u, v))
1948        .collect::<Result<Vec<_>, _>>()
1949        .map_err(|error| format!("the convicted hole loop could not be read in space: {error}"))
1950        .or_refuse(KernelStage::Validate, "evaluate")
1951}
1952
1953/// The least distance from a set of points to a face's own TRIM — sampled, in
1954/// the face's parameters, so a point beside a face's carrier but off the end of
1955/// the face does not read as being on it.
1956fn distance_to_face(
1957    solid: &BrepSolid,
1958    face_id: u64,
1959    points: &[crate::Vec3],
1960) -> Result<f64, KernelRefusal> {
1961    const STATIONS: usize = 32;
1962    let face = face_by_id(solid, face_id)?;
1963    let polylines = face
1964        .loops
1965        .iter()
1966        .map(loop_parameter_polyline)
1967        .collect::<Result<Vec<_>, KernelRefusal>>()?;
1968    let outer_index = (0..polylines.len())
1969        .max_by(|&a, &b| {
1970            polyline_area(&polylines[a])
1971                .abs()
1972                .total_cmp(&polyline_area(&polylines[b]).abs())
1973        })
1974        .unwrap_or(0);
1975    let bands = BoundaryBands::build(&polylines[outer_index]);
1976    let (mut lo, mut hi) = ((f64::MAX, f64::MAX), (f64::MIN, f64::MIN));
1977    for &(u, v) in &polylines[outer_index] {
1978        lo = (lo.0.min(u), lo.1.min(v));
1979        hi = (hi.0.max(u), hi.1.max(v));
1980    }
1981    let mut best = f64::INFINITY;
1982    for iu in 0..=STATIONS {
1983        for iv in 0..=STATIONS {
1984            let u = lo.0 + (hi.0 - lo.0) * iu as f64 / STATIONS as f64;
1985            let v = lo.1 + (hi.1 - lo.1) * iv as f64 / STATIONS as f64;
1986            if !bands.contains((u, v)) {
1987                continue;
1988            }
1989            if polylines
1990                .iter()
1991                .enumerate()
1992                .any(|(index, hole)| index != outer_index && inside_polyline((u, v), hole))
1993            {
1994                continue;
1995            }
1996            let Ok(point) = face.surface.evaluate(u, v) else {
1997                continue;
1998            };
1999            for probe in points {
2000                best = best.min(probe.sub(point).length());
2001            }
2002        }
2003    }
2004    Ok(best)
2005}
2006
2007/// Even-odd parity against a closed polyline, for the hole loops the band index
2008/// is not built over.
2009fn inside_polyline(point: (f64, f64), polygon: &[(f64, f64)]) -> bool {
2010    let (u, v) = point;
2011    let mut parity = false;
2012    for index in 0..polygon.len() {
2013        let (ax, ay) = polygon[index];
2014        let (bx, by) = polygon[(index + 1) % polygon.len()];
2015        if (ay > v) != (by > v) {
2016            let x = ax + (v - ay) / (by - ay) * (bx - ax);
2017            if x > u {
2018                parity = !parity;
2019            }
2020        }
2021    }
2022    parity
2023}
2024
2025/// The sentence a hole that has left the BODY earns, as opposed to one that has
2026/// moved onto another face. It is the one thing standing between the operator
2027/// and a silently ruined model, so it is a constant and not a phrasing.
2028const RUNAWAY: &str = "the runaway hole has left the face it was recorded on without arriving \
2029     on another: the moved carrier meets no face of the body, so there is nothing for it to be \
2030     re-trimmed against and no cut to perform at any extent";
2031
2032/// [`resolve_face_crossing`] for a pair this module has named itself rather
2033/// than read off the scan.
2034///
2035/// The scan is one way to find two faces of one body that have to be split
2036/// along their section, and the containment floor is another. Both hand the
2037/// same pair to the same repair.
2038pub fn resolve_face_crossing_between(
2039    solid: &BrepSolid,
2040    face_a: u64,
2041    face_b: u64,
2042) -> Result<BrepSolid, KernelRefusal> {
2043    let report = scan(solid, "resolve_face_crossing_between")?;
2044    split_and_drop(solid, face_a, face_b, RepairOrigin::Scan(&report))
2045}
2046
2047// ---------------------------------------------------------------------------
2048// The repair
2049// ---------------------------------------------------------------------------
2050
2051/// WHAT FOUND the pair this repair is about to split.
2052///
2053/// Two floors reach the same repair. The scan finds two faces whose meshes
2054/// cross and can say where and by how much; the hole-containment floor finds a
2055/// hole loop that has left its face and can say which loop and which face. The
2056/// repair does the same work either way, and the ledger says which asked for
2057/// it rather than printing a crossing point that was never measured.
2058enum RepairOrigin<'a> {
2059    /// The self-intersection scan confirmed a crossing pair.
2060    Scan(&'a SelfIntersectionReport),
2061    /// The containment floor convicted a hole loop that has broken out onto a
2062    /// neighbouring face.
2063    Breakout { face: u64, loop_id: u64 },
2064}
2065
2066/// The operand tag this repair works under. The solid is its own and only
2067/// operand: what is being resolved is a body crossing ITSELF, so there is no
2068/// second operand to be the other side of.
2069const SELF_OPERAND: u8 = 0;
2070
2071/// How many pieces the crossing may cut the two faces into before this repair
2072/// declines. Every way of dropping some of them is REBUILT and re-checked, so
2073/// the enumeration has to stay small enough to run in full: at eight pieces
2074/// there are at most 225 candidate drops, nearly all of which the re-trim
2075/// closure ends before anything is assembled. The variable-radius fillet's
2076/// crossing cuts four pieces and the two-bore fixture's cuts six.
2077const MAXIMUM_CROSSING_PIECES: usize = 8;
2078
2079/// Split two faces of ONE body that cross each other along their carriers'
2080/// exact intersection, drop the material the crossing encloses, and re-sew.
2081///
2082/// This is the bounded half of the self-intersection answer. Where two walls of
2083/// one body overshoot past each other instead of meeting at an edge, the
2084/// crossing curve IS the edge they should have met at: imprinting it onto both
2085/// faces cuts each into the part that belongs and the tail that overshot, and
2086/// dropping both tails leaves a body sewn along that curve.
2087///
2088/// **What it refuses, and why each refusal is a bound rather than a shrug:**
2089///
2090/// * A FOLD inside one face. There is no second face to imprint against, and
2091///   the answer is a trim that was never constructed rather than material to
2092///   drop — `offset/carve.rs` owns it.
2093/// * More than one crossing pair. Each repair changes the faces the next one
2094///   would be measured against, so resolving them together is a different
2095///   problem from resolving one.
2096/// * A crossing whose carriers' intersection does not cut BOTH trims. Then the
2097///   mesh crossing is not a curve the faces share and there is nothing to split
2098///   along.
2099/// * More pieces than [`MAXIMUM_CROSSING_PIECES`], because every candidate drop
2100///   is rebuilt in full and the enumeration has to run to the end rather than
2101///   be sampled.
2102/// * Any split whose reassembly does not come back SOUND. Every way of dropping
2103///   some pieces of each face — keeping at least one of each — is enumerated,
2104///   closed under the re-trim, rebuilt and re-checked in full (`validate()`
2105///   clean, connected, and scanning clean), so the piece choice is decided by
2106///   the result rather than guessed from a normal. If none verifies, the solid
2107///   is returned untouched and the caller refuses: a repair that cannot prove
2108///   its own answer must not ship one.
2109/// * A split that MORE THAN ONE drop resolves. Two sound answers is not an
2110///   answer, and choosing between them would be the guess this repair exists
2111///   not to make.
2112///
2113/// **The re-trim is the other half of the split.** Dropping a tail also removes
2114/// that tail's boundary uses on the NEIGHBOURING faces it bordered, and a body
2115/// cannot close over an edge only one face answers for. So the drop is closed
2116/// under "a face left holding an unmatched boundary goes too" — which, since
2117/// the imprint already cut those neighbours where the crossing curve met their
2118/// edges, drops the part of each that the crossing cut off. The closure is
2119/// bounded by the faces the imprint TOUCHED: reaching any other face ends that
2120/// candidate. Nothing here edits a loop by hand; every piece it chooses between
2121/// came out of the imprint/fragment machinery.
2122///
2123/// **And the drop RETIRES what the old configuration left.** The touched bound
2124/// is about material the crossing encloses, and it does not reach the third
2125/// thing a moved carrier leaves on a body: a piece, or a whole loop, that the
2126/// NEW configuration has no room for — a bore's exit ring still recorded on the
2127/// top face after the exit has migrated onto the side. Neither is material this
2128/// drop ran past; both are held by nothing the drop keeps, and keeping either
2129/// cannot close. [`fragment_is_detached`] retires the one the fragmenter
2130/// returns as its own island and [`holds_only_stale_loops`] the one it returns
2131/// as a hole loop that has left its face, and the ledger says a repair retired
2132/// something rather than leaving it to be read off the cell counts.
2133///
2134/// **A census has two directions and only one was enforced.** An edge used ONCE
2135/// is a face left holding an unanswered boundary, above. An edge used THREE
2136/// times is three faces along one curve, which is not a body either, and the
2137/// assembly does not refuse it — it puts the third face on a shell of its own
2138/// and every floor in this repository then passes the result.
2139/// [`over_used_edge`] refuses that candidate where the third use still exists,
2140/// which is here. It is what stopped the turned-bore migration returning a body
2141/// 23% out on area.
2142pub fn resolve_face_crossing(solid: &BrepSolid) -> Result<BrepSolid, KernelRefusal> {
2143    let options = SelfIntersectionOptions::for_solid(solid);
2144    let report = solid_self_intersections(solid, options).map_err(|message| {
2145        KernelRefusal::internal(
2146            KernelStage::Validate,
2147            "soundness_scan",
2148            format!("the soundness scan could not run: {message}"),
2149        )
2150    })?;
2151    if let Some(fold) = report.folds.first() {
2152        return Err(KernelRefusal::unsound(
2153            KernelStage::Validate,
2154            SoundnessDefect::Fold,
2155            report.folds.iter().map(|fold| fold.face).collect(),
2156            format!(
2157                "face {} folds through ITSELF; a fold is a trim that was never constructed and \
2158                 belongs to the carrier carve, not to this repair",
2159                fold.face
2160            ),
2161        ));
2162    }
2163    if report.confirmed.is_empty() {
2164        return Ok(solid.clone());
2165    }
2166    if report.confirmed.len() > 1 {
2167        return Err(KernelRefusal::unsupported(
2168            KernelStage::Validate,
2169            "crossing.multiple_pairs",
2170            format!(
2171                "{} crossing face pairs; each repair changes the faces the next would be measured \
2172                 against, so this repair takes one pair at a time",
2173                report.confirmed.len()
2174            ),
2175        ));
2176    }
2177    let crossing = &report.confirmed[0];
2178    split_and_drop(solid, crossing.face_a, crossing.face_b, RepairOrigin::Scan(&report))
2179}
2180
2181/// One crossing pair, split and resolved. Separated from the scan so the
2182/// refusals above read as one list.
2183fn split_and_drop(
2184    solid: &BrepSolid,
2185    face_a: u64,
2186    face_b: u64,
2187    origin: RepairOrigin<'_>,
2188) -> Result<BrepSolid, KernelRefusal> {
2189    use crate::fragment::fragment_solid;
2190    use crate::imprint::{FaceKey, ImprintOptions};
2191    use crate::{apply_edge_splits, build_imprints};
2192
2193    let scale = crate::solid_scale(solid);
2194    let tolerance = (scale * 1e-7).max(1e-9);
2195    if trace_on() {
2196        eprintln!("HEAL split_and_drop: faces {face_a} | {face_b}, scale {scale:.6}");
2197        trace_solid("entry solid", solid);
2198    }
2199
2200    // Each face as its own one-face open body, which is what the imprint
2201    // driver pairs: it walks operand A's faces against operand B's, and a
2202    // solid paired with itself would pair every face with itself first.
2203    let open_a = one_face_body(solid, face_a)?;
2204    let open_b = one_face_body(solid, face_b)?;
2205    let mut request = ImprintOptions {
2206        tolerance,
2207        // The GLOBAL interpolation lane: the section the repair cuts along is
2208        // the faithful one. On the only row this repair takes
2209        // (`FilletFailureWith2RasiusValues`) the global lane's section lies
2210        // 1.6e-6 from its two carriers where the local lane's lies 7.8e-4, and
2211        // it moves every face the section bounds onto its closed form (`Pin_S`
2212        // 1.6e-4 -> 4.4e-7). The local lane was asked for until
2213        // `process_curve` split an edge a section ENDS on whatever the angle:
2214        // that section is tangent to the bore's mouth ring at both ends, the
2215        // global fit reproduces the tangency, and the old gates left the ring
2216        // whole, so the repair succeeded only on the local fit's 1.4-degree
2217        // end-tangent error. `BREP_HEAL_FIT_LANE` re-measures it.
2218        local_fit: false,
2219        // The station budget is the imprint's own (the ladder climbs it to
2220        // twice that). `96` was `offset_shell`'s: every section this repair
2221        // reaches is a sparse march (68 points on the fillet row, 7 and 8 on
2222        // `BadBoolean`) that saturates either budget, bit-identically.
2223        ..ImprintOptions::default()
2224    };
2225    measured_fit_request(&mut request);
2226    let mut imprint = build_imprints(&open_a, &open_b, &request).map_err(|error| {
2227        error.with_message(|error| format!("the two carriers could not be imprinted: {error}"))
2228    })?;
2229
2230    // Both faces belong to ONE body, so both sides of the imprint are rewritten
2231    // onto that body's operand. The face ids are the solid's own and cannot
2232    // collide, so this is a relabel and not a merge.
2233    for face in &mut imprint.by_face {
2234        face.operand = SELF_OPERAND;
2235    }
2236    for split in &mut imprint.edge_splits {
2237        split.operand = SELF_OPERAND;
2238    }
2239    for piece in &mut imprint.pieces {
2240        for support in &mut piece.support_faces {
2241            *support = FaceKey {
2242                operand: SELF_OPERAND,
2243                face_id: support.face_id,
2244            };
2245        }
2246        for pcurve in &mut piece.pcurves {
2247            pcurve.operand = SELF_OPERAND;
2248        }
2249    }
2250    for barrier in &mut imprint.barrier_edges {
2251        barrier.0 = SELF_OPERAND;
2252    }
2253
2254    if trace_on() {
2255        trace_imprint(&imprint);
2256    }
2257
2258    let cut_a = imprint
2259        .by_face
2260        .iter()
2261        .any(|face| face.face_id == face_a && !face.piece_ids.is_empty());
2262    let cut_b = imprint
2263        .by_face
2264        .iter()
2265        .any(|face| face.face_id == face_b && !face.piece_ids.is_empty());
2266    if !cut_a || !cut_b {
2267        return Err(KernelRefusal::unsupported(
2268            KernelStage::Fragment,
2269            "crossing.no_shared_curve",
2270            format!(
2271                "the carriers' intersection reaches {} of the two trims, so there is no shared \
2272                 curve to split along",
2273                match (cut_a, cut_b) {
2274                    (true, false) => format!("only face {face_a}"),
2275                    (false, true) => format!("only face {face_b}"),
2276                    _ => "neither".into(),
2277                }
2278            ),
2279        ));
2280    }
2281
2282    let split = apply_edge_splits(solid, SELF_OPERAND, &imprint).map_err(|error| {
2283        error.with_message(|error| format!("the imprinted edge splits could not be applied: {error}"))
2284    })?;
2285    let fragments = fragment_solid(&split, SELF_OPERAND, &imprint).map_err(|error| {
2286        error.with_message(|error| format!("the split faces could not be fragmented: {error}"))
2287    })?;
2288
2289    if trace_on() {
2290        trace_solid("split solid", &split);
2291        trace_fragments(&fragments);
2292    }
2293
2294    // The faces the imprint TOUCHED: the two that cross, plus every face whose
2295    // own loop carries an edge the imprint split. Those are exactly the faces
2296    // the dropped material can border — the crossing curve ends ON a boundary
2297    // edge of each crossing face, and that edge is shared with a neighbour — so
2298    // they are the only faces this repair may re-trim. Anything beyond them is
2299    // material this repair has not been shown to own, and reaching one ends the
2300    // candidate rather than widening the drop.
2301    let touched = touched_faces(solid, &imprint, face_a, face_b);
2302    // A POLE edge is legitimately used once — it is a collapsed boundary, not a
2303    // shared one — so it never means the face beside it bordered dropped
2304    // material. Left in the census it would drop the fragment holding it, and
2305    // the cascade would refuse a body the repair could have resolved.
2306    let degenerate: rustc_hash::FxHashSet<EdgeKey> = split
2307        .edges
2308        .iter()
2309        .filter(|edge| edge.degenerate)
2310        .map(|edge| EdgeKey::Boundary(SELF_OPERAND, edge.id))
2311        .collect();
2312
2313    let pieces_of = |face: u64| -> Vec<usize> {
2314        fragments
2315            .iter()
2316            .enumerate()
2317            .filter_map(|(index, fragment)| (fragment.source_face_id == face).then_some(index))
2318            .collect()
2319    };
2320    let pieces_a = pieces_of(face_a);
2321    let pieces_b = pieces_of(face_b);
2322    // How many pieces the section has to cut, and it is not the same question
2323    // on both roads.
2324    //
2325    // From the SCAN, two faces overshoot PAST each other and the crossing curve
2326    // is the edge they should have met at, so it runs across both trims and
2327    // each has a tail: both sides must come out in two or more pieces, and one
2328    // piece is a section that grazed a trim rather than cut it.
2329    //
2330    // From the containment floor, the shape is different and the difference is
2331    // the whole of a COMPLETED MIGRATION. When a bore's mouth has walked
2332    // entirely onto the next face, the moved carrier meets that face in a
2333    // CLOSED loop inside its trim — the new mouth — which cuts nothing off it;
2334    // the face comes back as one piece carrying a new hole, and the only tail
2335    // is the wall's. Demanding two pieces of both would refuse exactly the case
2336    // the operator asked for, so this road asks for two pieces on ONE side and
2337    // at least one on the other. Nothing about the enumeration changes: a face
2338    // with one piece has one drop set, the empty one.
2339    let (need_a, need_b) = match &origin {
2340        RepairOrigin::Scan(_) => (2, 2),
2341        RepairOrigin::Breakout { .. } => {
2342            if pieces_a.len().max(pieces_b.len()) >= 2 {
2343                (1, 1)
2344            } else {
2345                (2, 2)
2346            }
2347        }
2348    };
2349    if pieces_a.len() < need_a || pieces_b.len() < need_b {
2350        return Err(KernelRefusal::unsupported(
2351            KernelStage::Fragment,
2352            "crossing.one_sided_cut",
2353            format!(
2354                "the crossing cut face {face_a} into {} piece(s) and face {face_b} into {} — this \
2355                 repair resolves the case where the curve cuts BOTH trims, so one part of each is \
2356                 the tail that overshot",
2357                pieces_a.len(),
2358                pieces_b.len()
2359            ),
2360        ));
2361    }
2362    if pieces_a.len() + pieces_b.len() > MAXIMUM_CROSSING_PIECES {
2363        return Err(KernelRefusal::non_convergence(
2364            KernelStage::Fragment,
2365            "crossing.pieces",
2366            format!(
2367                "the crossing cut face {face_a} into {} piece(s) and face {face_b} into {}, which is \
2368                 {} pieces against this repair's budget of {MAXIMUM_CROSSING_PIECES} — every way to \
2369                 drop some of them is rebuilt and re-checked, so the enumeration is bounded rather \
2370                 than sampled",
2371                pieces_a.len(),
2372                pieces_b.len(),
2373                pieces_a.len() + pieces_b.len(),
2374            ),
2375        ));
2376    }
2377
2378    // WHICH pieces are the tails is decided by the RESULT, not by a normal.
2379    // Every way to drop some pieces of each crossing face (keeping at least one
2380    // of each) is closed under the re-trim below, rebuilt in full and
2381    // re-checked; the repair is the answer only when exactly ONE of them
2382    // verifies.
2383    //
2384    // The enumeration runs under TWO closures, and the second only where the
2385    // first found nothing at all. [`DropClosure::Drop`] drops a neighbour the
2386    // drop leaves holding an unmatched boundary — the rule this repair has
2387    // always used, and the one every body it already resolves is decided by.
2388    // [`DropClosure::Retrim`] RE-TRIMS that neighbour instead. Ordering them
2389    // this way makes the second closure strictly additive: a body the first
2390    // resolves never reaches it, so no answer this repair already returns can
2391    // change. The price is the enumeration twice over on a body that refuses.
2392    let plan = DropPlan {
2393        split: &split,
2394        fragments: &fragments,
2395        imprint: &imprint,
2396        touched: &touched,
2397        degenerate: &degenerate,
2398        pieces_a: &pieces_a,
2399        pieces_b: &pieces_b,
2400        face_a,
2401        face_b,
2402        scale,
2403    };
2404    let (mut verified, refusals) = plan.enumerate(DropClosure::Drop);
2405    if verified.is_empty() {
2406        verified = plan.enumerate(DropClosure::Retrim).0;
2407    }
2408
2409    if verified.len() > 1 {
2410        return Err(KernelRefusal::ill_posed(
2411            KernelStage::Select,
2412            "crossing.ambiguous_drop",
2413            format!(
2414                "{} different drops of the crossing pieces all rebuilt into a sound body, so the \
2415                 result does not decide which material the crossing encloses; this repair answers \
2416                 only where one does",
2417                verified.len()
2418            ),
2419        ));
2420    }
2421    let Some(Candidate {
2422        dropped,
2423        retired,
2424        retrimmed,
2425        solid: repaired,
2426    }) = verified.pop()
2427    else {
2428        // The first few reasons, not all of them: eight pieces is up to 225
2429        // candidates and a refusal nobody can read is a refusal nobody uses.
2430        let listed = refusals
2431            .iter()
2432            .take(4)
2433            .cloned()
2434            .collect::<Vec<_>>()
2435            .join(" | ");
2436        // The candidate reasons (an over-used edge, a closure that consumed
2437        // every face, a rebuild that declined) are CONTEXT inside this one
2438        // refusal, whose class is minted here: the body still crosses itself.
2439        return Err(KernelRefusal::unsound(
2440            KernelStage::Sew,
2441            SoundnessDefect::Crossing,
2442            vec![face_a, face_b],
2443            format!(
2444                "none of the {} ways of dropping the crossing pieces rebuilt into a sound body \
2445                 ({listed}{}); the worst crossing was {:.3e} past its band, so the overshoot is \
2446                 real and it is the SPLIT that did not resolve it",
2447                refusals.len(),
2448                if refusals.len() > 4 {
2449                    format!(" | and {} more", refusals.len() - 4)
2450                } else {
2451                    String::new()
2452                },
2453                match &origin {
2454                    RepairOrigin::Scan(report) => report
2455                        .confirmed
2456                        .first()
2457                        .map(|crossing| crossing.straddle)
2458                        .unwrap_or_default(),
2459                    RepairOrigin::Breakout { .. } => 0.0,
2460                }
2461            ),
2462        ));
2463    };
2464
2465    record_repair(
2466        &fragments,
2467        &dropped,
2468        &retired,
2469        &retrimmed,
2470        face_a,
2471        face_b,
2472        &origin,
2473    );
2474    Ok(repaired)
2475}
2476
2477/// One candidate answer: the fragments the drop removed, the ones it RETIRED
2478/// as detached, the faces it RE-TRIMMED rather than removed, and the body
2479/// those choices rebuilt into.
2480struct Candidate {
2481    dropped: Vec<usize>,
2482    retired: Vec<u64>,
2483    retrimmed: Vec<u64>,
2484    solid: BrepSolid,
2485}
2486
2487/// How a candidate drop closes over a neighbour it leaves holding a boundary
2488/// no other face answers for.
2489#[derive(Clone, Copy, Eq, PartialEq)]
2490enum DropClosure {
2491    /// DROP that neighbour too, iterated to a fixed point — [`close_drop_set`].
2492    Drop,
2493    /// RE-TRIM it — [`retrim_drop_set`]: take the unmatched coedges off it and
2494    /// re-link what remains into closed loops on the same carrier, with the
2495    /// same pcurves. The bound is the same one (a face the imprint never cut
2496    /// still ends the candidate); what changes is that a face it DID cut is
2497    /// re-trimmed rather than consumed.
2498    Retrim,
2499}
2500
2501/// One crossing pair's split and everything a candidate drop is measured
2502/// against. Bundled so the enumeration can run once per closure.
2503struct DropPlan<'a> {
2504    split: &'a BrepSolid,
2505    fragments: &'a [crate::fragment::FaceFragmentRecord],
2506    imprint: &'a crate::imprint::ImprintResultRecord,
2507    touched: &'a rustc_hash::FxHashSet<u64>,
2508    degenerate: &'a rustc_hash::FxHashSet<EdgeKey>,
2509    pieces_a: &'a [usize],
2510    pieces_b: &'a [usize],
2511    face_a: u64,
2512    face_b: u64,
2513    scale: f64,
2514}
2515
2516impl DropPlan<'_> {
2517    /// Every way of dropping some pieces of each crossing face, closed under
2518    /// `closure`, rebuilt in full and re-checked. The candidates that verified
2519    /// come back first, the reasons the rest did not second.
2520    fn enumerate(&self, closure: DropClosure) -> (Vec<Candidate>, Vec<String>) {
2521        let (face_a, face_b) = (self.face_a, self.face_b);
2522        let mut refusals: Vec<String> = Vec::new();
2523        let mut verified: Vec<Candidate> = Vec::new();
2524        let mut seen: Vec<(Vec<usize>, Vec<Vec<usize>>)> = Vec::new();
2525        for drop_a in proper_subsets(self.pieces_a) {
2526            for drop_b in proper_subsets(self.pieces_b) {
2527                let mut dropped: Vec<usize> =
2528                    drop_a.iter().chain(drop_b.iter()).copied().collect();
2529                if dropped.is_empty() {
2530                    continue;
2531                }
2532                let label = format!(
2533                    "dropping piece(s) {:?} of face {face_a} and {:?} of face {face_b}",
2534                    drop_a
2535                        .iter()
2536                        .map(|index| self
2537                            .pieces_a
2538                            .iter()
2539                            .position(|piece| piece == index)
2540                            .unwrap_or(0))
2541                        .collect::<Vec<_>>(),
2542                    drop_b
2543                        .iter()
2544                        .map(|index| self
2545                            .pieces_b
2546                            .iter()
2547                            .position(|piece| piece == index)
2548                            .unwrap_or(0))
2549                        .collect::<Vec<_>>(),
2550                );
2551                // The re-trim: a face that bordered dropped material is left
2552                // with a boundary use no other face answers, and a body cannot
2553                // close over one. Closing the drop under that rule is what
2554                // turns a two-face split into a re-trim of every face the
2555                // dropped material bordered.
2556                // The dropping closure leaves every fragment as it was, so it
2557                // borrows the list rather than copying it per candidate.
2558                let mut retired: Vec<u64> = Vec::new();
2559                let closed = match closure {
2560                    DropClosure::Drop => close_drop_set(
2561                        self.fragments,
2562                        &mut dropped,
2563                        &mut retired,
2564                        self.touched,
2565                        self.degenerate,
2566                    )
2567                    .map(|()| (None, Vec::new())),
2568                    DropClosure::Retrim => retrim_drop_set(
2569                        self.fragments,
2570                        &mut dropped,
2571                        &mut retired,
2572                        self.touched,
2573                        self.degenerate,
2574                    )
2575                    .map(|(working, retrimmed)| (Some(working), retrimmed)),
2576                };
2577                let (working, retrimmed) = match closed {
2578                    Ok(closed) => closed,
2579                    Err(reason) => {
2580                        if trace_on() {
2581                            println!("    candidate died at closure {label}: {reason}");
2582                        }
2583                        refusals.push(format!("{label}: {reason}"));
2584                        continue;
2585                    }
2586                };
2587                let working: &[crate::fragment::FaceFragmentRecord] =
2588                    working.as_deref().unwrap_or(self.fragments);
2589                dropped.sort_unstable();
2590                // Two seeds can close onto the same answer. The signature is
2591                // the drop AND what the re-trim left of each kept fragment, so
2592                // a second closure that re-trimmed differently is a different
2593                // candidate rather than a hidden duplicate.
2594                let signature = (
2595                    dropped.clone(),
2596                    working
2597                        .iter()
2598                        .enumerate()
2599                        .filter(|(index, _)| !dropped.contains(index))
2600                        .map(|(_, fragment)| {
2601                            fragment
2602                                .loops
2603                                .iter()
2604                                .map(|fragment_loop| fragment_loop.coedges.len())
2605                                .collect()
2606                        })
2607                        .collect(),
2608                );
2609                if seen.contains(&signature) {
2610                    continue;
2611                }
2612                seen.push(signature);
2613                if dropped.len() == working.len() {
2614                    refusals.push(format!("{label}: the re-trim consumed every face"));
2615                    continue;
2616                }
2617                // The census's OTHER direction — see [`over_used_edge`].
2618                if let Some((key, count)) = over_used_edge(working, &dropped, self.degenerate) {
2619                    refusals.push(format!(
2620                        "{label}: {} is held {count} times by the pieces this drop keeps, and a \
2621                         closed body holds every edge exactly twice",
2622                        match key {
2623                            EdgeKey::Boundary(_, edge) => format!("edge {edge}"),
2624                            EdgeKey::Imprint(piece) => format!("imprint piece {piece}"),
2625                        }
2626                    ));
2627                    if trace_on() {
2628                        println!(
2629                            "    candidate refused   {label}: {key:?} held {count} times"
2630                        );
2631                    }
2632                    continue;
2633                }
2634                let selected: Vec<_> = working
2635                    .iter()
2636                    .enumerate()
2637                    .filter(|(index, _)| !dropped.contains(index))
2638                    .map(|(_, fragment)| fragment.clone())
2639                    .collect();
2640                match rebuild(self.split, selected, self.imprint, self.scale) {
2641                    // `BREP_HEAL_TRACE=1` prints every candidate the
2642                    // enumeration considered, whether it verified, and what
2643                    // volume it produced. This is the instrument that found the
2644                    // 2026-09-22 stale-fragment defect: the `touched` bound
2645                    // kills most candidates before `verified.len() == 1` picks
2646                    // a survivor, and without the list there is no way to see
2647                    // that the survivor was not the right one.
2648                    Ok(solid) => {
2649                        if trace_on() {
2650                            println!(
2651                                "    CANDIDATE VERIFIED  {label}  volume {:.6}  dropped {:?}",
2652                                crate::solid_mass_properties(&solid)
2653                                    .map(|mass| mass.volume)
2654                                    .unwrap_or(f64::NAN),
2655                                dropped
2656                            );
2657                        }
2658                        verified.push(Candidate {
2659                            dropped,
2660                            retired,
2661                            retrimmed,
2662                            solid,
2663                        })
2664                    }
2665                    Err(reason) => {
2666                        if trace_on() {
2667                            println!("    candidate refused   {label}: {reason}");
2668                        }
2669                        refusals.push(format!("{label}: {reason}"))
2670                    }
2671                }
2672            }
2673        }
2674        (verified, refusals)
2675    }
2676}
2677
2678/// The faces this repair may re-trim: the two that cross, and every face whose
2679/// own loops use an edge the imprint split.
2680fn touched_faces(
2681    solid: &BrepSolid,
2682    imprint: &crate::imprint::ImprintResultRecord,
2683    face_a: u64,
2684    face_b: u64,
2685) -> rustc_hash::FxHashSet<u64> {
2686    use rustc_hash::FxHashSet as HashSet;
2687    let split_edges: HashSet<u64> = imprint
2688        .edge_splits
2689        .iter()
2690        .filter(|split| split.operand == SELF_OPERAND)
2691        .map(|split| split.edge_id)
2692        .collect();
2693    let mut touched: HashSet<u64> = [face_a, face_b].into_iter().collect();
2694    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
2695        let uses_split = face
2696            .loops
2697            .iter()
2698            .flat_map(|loop_record| &loop_record.coedges)
2699            .any(|coedge| split_edges.contains(&coedge.edge_id));
2700        if uses_split {
2701            touched.insert(face.id);
2702        }
2703    }
2704    touched
2705}
2706
2707/// Close a drop set under the rule a closed body cannot break: every edge is
2708/// used exactly twice. Dropping a tail takes its uses with it, so any face left
2709/// holding a boundary no other face answers bordered the dropped material and
2710/// has to be re-trimmed — which, since the imprint already cut it, means
2711/// dropping the part of it that the crossing cut off. Iterated to a fixed
2712/// point, and bounded by the touched set: reaching a face the imprint never cut
2713/// means the drop has left the material the crossing encloses, and the
2714/// candidate is refused rather than grown.
2715///
2716/// The one thing that bound does not own is a fragment joined to NOTHING the
2717/// drop keeps — see [`fragment_is_detached`]. That is not material the drop ran
2718/// past; it is what the old configuration left, and it is retired wherever it
2719/// came from.
2720fn close_drop_set(
2721    fragments: &[crate::fragment::FaceFragmentRecord],
2722    dropped: &mut Vec<usize>,
2723    retired: &mut Vec<u64>,
2724    touched: &rustc_hash::FxHashSet<u64>,
2725    degenerate: &rustc_hash::FxHashSet<EdgeKey>,
2726) -> Result<(), KernelRefusal> {
2727    use rustc_hash::FxHashMap as HashMap;
2728    loop {
2729        let mut uses: HashMap<EdgeKey, usize> = HashMap::default();
2730        for (index, fragment) in fragments.iter().enumerate() {
2731            if dropped.contains(&index) {
2732                continue;
2733            }
2734            for key in fragment
2735                .loops
2736                .iter()
2737                .flat_map(|fragment_loop| &fragment_loop.coedges)
2738                .filter_map(|coedge| edge_key(&coedge.source))
2739            {
2740                *uses.entry(key).or_default() += 1;
2741            }
2742        }
2743        let mut grew = false;
2744        for (index, fragment) in fragments.iter().enumerate() {
2745            if dropped.contains(&index) {
2746                continue;
2747            }
2748            // RETIRED, not re-trimmed: a fragment holding no edge that any
2749            // other kept fragment holds is attached to nothing this drop keeps.
2750            // The [`touched`] bound does not apply to it, because that bound
2751            // asks whether the drop has run past the material the crossing
2752            // encloses — and a piece joined to the body by nothing is not
2753            // material this drop reached, it is material the OLD configuration
2754            // left behind. Retiring it cannot cascade: the only uses it removes
2755            // are uses nothing else holds. See [`fragment_is_detached`].
2756            if fragment_is_detached(fragment, &uses, degenerate) {
2757                dropped.push(index);
2758                retired.push(fragment.source_face_id);
2759                grew = true;
2760                continue;
2761            }
2762            let unmatched = fragment
2763                .loops
2764                .iter()
2765                .flat_map(|fragment_loop| &fragment_loop.coedges)
2766                .filter_map(|coedge| edge_key(&coedge.source))
2767                .filter(|key| !degenerate.contains(key))
2768                .any(|key| uses.get(&key) == Some(&1));
2769            if !unmatched {
2770                continue;
2771            }
2772            if !touched.contains(&fragment.source_face_id) {
2773                return Err(KernelRefusal::internal(KernelStage::Validate, "retrim.uncut_face", format!(
2774                    "the re-trim reached face {}, which the imprint never cut — the drop has run \
2775                     past the material the crossing encloses",
2776                    fragment.source_face_id
2777                )));
2778            }
2779            dropped.push(index);
2780            grew = true;
2781        }
2782        if !grew {
2783            return Ok(());
2784        }
2785    }
2786}
2787
2788/// [`close_drop_set`]'s other closure: a face left holding a boundary no other
2789/// face answers for is RE-TRIMMED rather than dropped.
2790///
2791/// Dropping it is the right answer when the unanswered boundary is the whole
2792/// of what that face contributed to the dropped material — a tail beside a
2793/// tail. It is the WRONG answer when the face is one the body keeps and only
2794/// part of its boundary went: a bore carried out through a side wall leaves
2795/// the mouth flat holding the stretch of its own corner edge that now runs
2796/// inside the bore, and the arc of the mouth ring that now runs outside the
2797/// body, and neither is material to drop — they are two coedges to take OFF a
2798/// face that otherwise stays exactly as it is. Taking them off merges that
2799/// face's mouth loop into its outer one, which is precisely the topology a
2800/// breakout has and a drop-only closure cannot reach.
2801///
2802/// The bound is [`close_drop_set`]'s: a face the imprint never cut still ends
2803/// the candidate rather than widening the re-trim, with the two exceptions that
2804/// are not re-trims at all — a fragment attached to nothing
2805/// ([`fragment_is_detached`]) and a whole loop that has left its face
2806/// ([`holds_only_stale_loops`]), both of which are retired. What comes back
2807/// is the fragment list to rebuild from — the untouched fragments as they were,
2808/// the re-trimmed ones with their loops re-linked — and the ids of the faces
2809/// that were re-trimmed, for the ledger. A fragment left with no coedge at all
2810/// joins `dropped`.
2811fn retrim_drop_set(
2812    fragments: &[crate::fragment::FaceFragmentRecord],
2813    dropped: &mut Vec<usize>,
2814    retired: &mut Vec<u64>,
2815    touched: &rustc_hash::FxHashSet<u64>,
2816    degenerate: &rustc_hash::FxHashSet<EdgeKey>,
2817) -> Result<(Vec<crate::fragment::FaceFragmentRecord>, Vec<u64>), KernelRefusal> {
2818    use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
2819
2820    let mut working = fragments.to_vec();
2821    let mut retrimmed: Vec<u64> = Vec::new();
2822    loop {
2823        let mut uses: HashMap<EdgeKey, usize> = HashMap::default();
2824        for (index, fragment) in working.iter().enumerate() {
2825            if dropped.contains(&index) {
2826                continue;
2827            }
2828            for key in fragment
2829                .loops
2830                .iter()
2831                .flat_map(|fragment_loop| &fragment_loop.coedges)
2832                .filter_map(|coedge| edge_key(&coedge.source))
2833            {
2834                *uses.entry(key).or_default() += 1;
2835            }
2836        }
2837        // RETIRED FIRST, and before the early return below, because a
2838        // detached fragment does not have to hold an UNMATCHED edge to be
2839        // detached — one whose loop walks its own seam twice holds that seam
2840        // twice itself, and the census reads two. See [`fragment_is_detached`].
2841        let mut grew = false;
2842        for index in 0..working.len() {
2843            if dropped.contains(&index) {
2844                continue;
2845            }
2846            if fragment_is_detached(&working[index], &uses, degenerate) {
2847                dropped.push(index);
2848                retired.push(working[index].source_face_id);
2849                grew = true;
2850            }
2851        }
2852        if grew {
2853            // The census is stale the moment anything is retired.
2854            continue;
2855        }
2856        // A POLE edge is legitimately used once, as in [`close_drop_set`].
2857        let unmatched: HashSet<EdgeKey> = uses
2858            .iter()
2859            .filter(|(key, count)| **count == 1 && !degenerate.contains(key))
2860            .map(|(key, _)| *key)
2861            .collect();
2862        if unmatched.is_empty() {
2863            return Ok((working, retrimmed));
2864        }
2865        for index in 0..working.len() {
2866            if dropped.contains(&index) {
2867                continue;
2868            }
2869            let holds = working[index]
2870                .loops
2871                .iter()
2872                .flat_map(|fragment_loop| &fragment_loop.coedges)
2873                .filter_map(|coedge| edge_key(&coedge.source))
2874                .any(|key| unmatched.contains(&key));
2875            if !holds {
2876                continue;
2877            }
2878            // A STALE LOOP is the other way the old configuration leaves
2879            // something behind, and the [`touched`] bound does not own it —
2880            // see [`holds_only_stale_loops`].
2881            let stale = holds_only_stale_loops(&working[index], &unmatched, degenerate);
2882            if !touched.contains(&working[index].source_face_id) && !stale {
2883                return Err(KernelRefusal::internal(KernelStage::Validate, "retrim.uncut_face", format!(
2884                    "the re-trim reached face {}, which the imprint never cut — the drop has run \
2885                     past the material the crossing encloses",
2886                    working[index].source_face_id
2887                )));
2888            }
2889            let face = working[index].source_face_id;
2890            match retrim_fragment(&working[index], &unmatched)? {
2891                Some(next) => {
2892                    working[index] = next;
2893                    if stale {
2894                        retired.push(face);
2895                    } else if !retrimmed.contains(&face) {
2896                        retrimmed.push(face);
2897                    }
2898                }
2899                None => dropped.push(index),
2900            }
2901            grew = true;
2902        }
2903        if !grew {
2904            return Ok((working, retrimmed));
2905        }
2906    }
2907}
2908
2909/// Re-trim ONE fragment: take off every coedge in `remove` and re-link what is
2910/// left into closed loops.
2911///
2912/// The link is made in the face's OWN parameter domain, which is where a trim
2913/// loop is closed and the only frame that tells the two sides of a seam apart —
2914/// a cylinder's seam is one curve in 3D and two coedges a period apart here.
2915/// Nothing is fitted or re-parameterised: each surviving coedge keeps its
2916/// source, its sense and its pcurve, and only the ORDER and the grouping into
2917/// loops are rebuilt. A chain that does not close is a re-trim this repair
2918/// cannot prove, and it refuses rather than emitting an open face.
2919///
2920/// The loops come back in the order of their first surviving coedge, so a face
2921/// whose outer loop has just absorbed an inner one is still outer-loop-first.
2922/// `Ok(None)` when nothing at all is left to keep.
2923fn retrim_fragment(
2924    fragment: &crate::fragment::FaceFragmentRecord,
2925    remove: &rustc_hash::FxHashSet<EdgeKey>,
2926) -> Result<Option<crate::fragment::FaceFragmentRecord>, KernelRefusal> {
2927    use crate::fragment::{FaceFragmentRecord, FragmentCoedge, FragmentLoop};
2928
2929    let kept: Vec<FragmentCoedge> = fragment
2930        .loops
2931        .iter()
2932        .flat_map(|fragment_loop| &fragment_loop.coedges)
2933        .filter(|coedge| !edge_key(&coedge.source).is_some_and(|key| remove.contains(&key)))
2934        .cloned()
2935        .collect();
2936    if kept.is_empty() {
2937        return Ok(None);
2938    }
2939    let ends = kept
2940        .iter()
2941        .map(|coedge| {
2942            let [t0, t1] = coedge.pcurve.domain()?;
2943            Ok((coedge.pcurve.evaluate(t0)?, coedge.pcurve.evaluate(t1)?))
2944        })
2945        .collect::<Result<Vec<_>, String>>().or_refuse(KernelStage::Validate, "collect")?;
2946    // The domain's own diagonal sets the band a junction is matched in: a
2947    // plane's parameters are millimetres and a cylinder's are radians against
2948    // millimetres, so one fixed number would mean two different things on the
2949    // two carriers. The ends being matched were cut from ONE curve by the
2950    // imprint's own split, so they agree to the fit's precision and the band
2951    // only has to be small against the face.
2952    let [u0, u1] = fragment.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
2953    let [v0, v1] = fragment.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
2954    let tolerance = 1e-4 * (u1 - u0).hypot(v1 - v0);
2955    let mut used = vec![false; kept.len()];
2956    let mut loops: Vec<FragmentLoop> = Vec::new();
2957    for seed in 0..kept.len() {
2958        if used[seed] {
2959            continue;
2960        }
2961        used[seed] = true;
2962        let mut chain = vec![seed];
2963        let start = ends[seed].0;
2964        let mut cursor = ends[seed].1;
2965        while cursor.sub(start).length() > tolerance {
2966            let next = (0..kept.len())
2967                .filter(|index| !used[*index])
2968                .map(|index| (index, ends[index].0.sub(cursor).length()))
2969                .filter(|(_, gap)| *gap <= tolerance)
2970                .min_by(|left, right| left.1.total_cmp(&right.1))
2971                .map(|(index, _)| index);
2972            let Some(next) = next else {
2973                return Err(KernelRefusal::internal(KernelStage::Validate, "retrim.open_chain", format!(
2974                    "face {}'s re-trim left a chain open at ({:.6}, {:.6}) in its own parameter \
2975                     domain — what the drop took off it does not close into a loop",
2976                    fragment.source_face_id, cursor.x, cursor.y
2977                )));
2978            };
2979            used[next] = true;
2980            chain.push(next);
2981            cursor = ends[next].1;
2982        }
2983        loops.push(FragmentLoop {
2984            coedges: chain.into_iter().map(|index| kept[index].clone()).collect(),
2985        });
2986    }
2987    Ok(Some(FaceFragmentRecord {
2988        loops,
2989        ..fragment.clone()
2990    }))
2991}
2992
2993/// Is this fragment attached to NOTHING else the drop keeps?
2994///
2995/// The census `uses` counts every non-dropped fragment's edge keys, this one's
2996/// included. So a fragment is detached exactly when, for every non-degenerate
2997/// key it holds, the census count equals ITS OWN count of that key: nobody else
2998/// is holding any edge of it.
2999///
3000/// It is stated that way rather than as "every key it holds is used once"
3001/// because a fragment may legitimately hold one key TWICE on its own — a
3002/// cylinder band walks its seam up one side and down the other — and such a
3003/// fragment is still detached when the seam's only two uses are both its.
3004///
3005/// **What a detached fragment IS.** It is a piece of the old configuration that
3006/// the new one has no room for: on the turned-bore migration, the top face's
3007/// hole loop is the exit ring the bore no longer opens through, sitting out at
3008/// x = 44.6 where the top face's own square ends at 20. The fragmenter returns
3009/// it as its own island because the ring is disjoint from the square, and the
3010/// only other face holding that ring is the wall's overshoot tail. Drop the
3011/// tail and the island is joined to nothing.
3012///
3013/// **Why retiring it is bounded.** Keeping it can never produce a closed body:
3014/// every edge it holds is answered for only by itself, so the assembly is open
3015/// there however the rest of the drop goes. And retiring it removes only uses
3016/// nothing else holds, so it cannot leave a third face unmatched — it does not
3017/// cascade, and no candidate the enumeration would otherwise verify is lost.
3018fn fragment_is_detached(
3019    fragment: &crate::fragment::FaceFragmentRecord,
3020    uses: &rustc_hash::FxHashMap<EdgeKey, usize>,
3021    degenerate: &rustc_hash::FxHashSet<EdgeKey>,
3022) -> bool {
3023    use rustc_hash::FxHashMap as HashMap;
3024    let mut own: HashMap<EdgeKey, usize> = HashMap::default();
3025    for key in fragment
3026        .loops
3027        .iter()
3028        .flat_map(|fragment_loop| &fragment_loop.coedges)
3029        .filter_map(|coedge| edge_key(&coedge.source))
3030        .filter(|key| !degenerate.contains(key))
3031    {
3032        *own.entry(key).or_default() += 1;
3033    }
3034    // A fragment carrying no identified edge at all is NOT called detached:
3035    // its boundary is all DERIVED, which `edge_key` deliberately does not
3036    // count, and the rebuild's own closure is what answers for those.
3037    !own.is_empty()
3038        && own
3039            .iter()
3040            .all(|(key, count)| uses.get(key).copied().unwrap_or(0) == *count)
3041}
3042
3043/// The OTHER way the old configuration leaves something behind: a WHOLE LOOP
3044/// of a face that nothing else answers for AND THAT HAS LEFT THAT FACE.
3045///
3046/// [`fragment_is_detached`] catches the leftover when the fragmenter returns it
3047/// as its own island — which it does when the stale ring is far enough from the
3048/// face's own trim to be plainly disjoint. When it is nearer, the same ring
3049/// comes back as a HOLE LOOP of the face it left: the turned bore's exit ring
3050/// at 40 degrees sits at `x = 22.9 - 30.7` against a top face that ends at 20,
3051/// and the top face is ONE fragment carrying it. There is no island to retire,
3052/// and taking the loop off is a RE-TRIM of a face the imprint never cut.
3053///
3054/// That is the move the earlier records named as missing — *"the departed face
3055/// keeps a hole loop the imprint never cut, and the drop enumeration has no
3056/// move for retiring one"*. This is the move, and it is bounded FOUR ways:
3057///
3058/// * **Unanswered for.** Every non-degenerate edge of the loop is used once,
3059///   by this fragment alone, so no other face the drop keeps is standing on it
3060///   and removing it takes nothing from anyone. A loop only PART of which is
3061///   unanswered for is a genuine re-trim of a neighbour that bordered the
3062///   dropped material, and the [`touched`] bound still owns that case.
3063/// * **It has LEFT the face**, by the containment floor's own test: every
3064///   sample of it lies outside the face's outer loop in that face's own
3065///   parameter plane. This is the condition that matters, and it was added
3066///   after measuring what happens without it. Unanswered-for alone is
3067///   SYMMETRIC — at 40 degrees it licensed retiring the bore's ENTRY mouth
3068///   just as readily as its departed exit ring, so the enumeration verified
3069///   two bodies and refused the pair as ambiguous. A loop still inside its own
3070///   face is trimming material and is not a leftover, whoever is holding it.
3071/// * **A loop survives.** This never empties a face; a fragment with nothing
3072///   left at all is the detached case above.
3073/// * **A PLANE only**, as the containment floor restricts itself, because on a
3074///   periodic surface "outside the outer loop" in the parameter plane is a
3075///   statement about the seam rather than about the trim.
3076///
3077/// And the body still has to rebuild, `validate()`, connect, scan clean and
3078/// pass the containment floor afterwards, exactly as before.
3079fn holds_only_stale_loops(
3080    fragment: &crate::fragment::FaceFragmentRecord,
3081    unmatched: &rustc_hash::FxHashSet<EdgeKey>,
3082    degenerate: &rustc_hash::FxHashSet<EdgeKey>,
3083) -> bool {
3084    if !matches!(
3085        fragment.surface.analytic(),
3086        Some(crate::AnalyticSurface::Plane { .. })
3087    ) {
3088        return false;
3089    }
3090    let mut stale: Vec<usize> = Vec::new();
3091    let mut surviving = 0usize;
3092    for (index, fragment_loop) in fragment.loops.iter().enumerate() {
3093        let keys: Vec<EdgeKey> = fragment_loop
3094            .coedges
3095            .iter()
3096            .filter_map(|coedge| edge_key(&coedge.source))
3097            .filter(|key| !degenerate.contains(key))
3098            .collect();
3099        if !keys.is_empty() && keys.iter().all(|key| unmatched.contains(key)) {
3100            stale.push(index);
3101            continue;
3102        }
3103        if keys.iter().any(|key| unmatched.contains(key)) {
3104            return false;
3105        }
3106        surviving += 1;
3107    }
3108    if stale.is_empty() || surviving == 0 {
3109        return false;
3110    }
3111    let Ok(polylines) = fragment
3112        .loops
3113        .iter()
3114        .map(fragment_loop_polyline)
3115        .collect::<Result<Vec<_>, KernelRefusal>>()
3116    else {
3117        return false;
3118    };
3119    if polylines.iter().any(Vec::is_empty) {
3120        return false;
3121    }
3122    let outer_index = (0..polylines.len())
3123        .max_by(|&a, &b| {
3124            polyline_area(&polylines[a])
3125                .abs()
3126                .total_cmp(&polyline_area(&polylines[b]).abs())
3127        })
3128        .unwrap_or(0);
3129    // The face's own outer loop being the stale one is not a leftover to
3130    // retire; it is the whole face going, which is the detached case.
3131    if stale.contains(&outer_index) {
3132        return false;
3133    }
3134    let outer = &polylines[outer_index];
3135    let bands = BoundaryBands::build(outer);
3136    let tolerance = boundary_tolerance(outer);
3137    stale.iter().all(|index| {
3138        polylines[*index]
3139            .iter()
3140            .all(|&point| !bands.contains(point) && !bands.within(point, tolerance))
3141    })
3142}
3143
3144/// The other half of the census rule, and the one that had no enforcement.
3145///
3146/// A closed body uses every non-degenerate edge EXACTLY TWICE. The drop
3147/// closures above are the "fewer than twice" half — a face left holding a
3148/// boundary nobody answers is dropped or re-trimmed. Nothing checked the other
3149/// direction, and the direction matters here: an imprint piece is cut into BOTH
3150/// crossing faces, so before any drop it is held four times, once by each of
3151/// the four pieces. A drop that takes one piece away leaves it held three
3152/// times — three faces along one curve, which is not a body.
3153///
3154/// That is the candidate the turned-bore migration used to return: dropping the
3155/// exit mouth's disc alone leaves the wall's kept part, the wall's overshoot
3156/// tail and the mouth flat's remainder all on the mouth ring. Refusing it is
3157/// what leaves the one drop that is right.
3158///
3159/// **And nothing downstream catches it**, which is why the check belongs here
3160/// and not there. `assemble_open_fragments` resolves the third use by putting
3161/// the overshoot on a shell of its OWN: the body comes back with every edge
3162/// used exactly twice, `validate()` clean, `solid_connectivity` calling it
3163/// connected (the sheets share edges with the main shell), the scan clean and
3164/// the containment floor acquitting it — a three-shell solid whose first shell
3165/// is the right answer and whose other two are sheets stapled to it. Measured
3166/// on the turned bore at 60 degrees: shell 1 is the 7 correct faces at
3167/// 7673.516114379 against a closed form of 7673.516114438, shell 2 is the
3168/// overshoot alone at -536.326313 and shell 3 the departed ring at -6.7e-14.
3169///
3170/// Returns the offending key and its count, smallest key first so the refusal
3171/// reads the same on every run.
3172fn over_used_edge(
3173    fragments: &[crate::fragment::FaceFragmentRecord],
3174    dropped: &[usize],
3175    degenerate: &rustc_hash::FxHashSet<EdgeKey>,
3176) -> Option<(EdgeKey, usize)> {
3177    use rustc_hash::FxHashMap as HashMap;
3178    let mut uses: HashMap<EdgeKey, usize> = HashMap::default();
3179    for (index, fragment) in fragments.iter().enumerate() {
3180        if dropped.contains(&index) {
3181            continue;
3182        }
3183        for key in fragment
3184            .loops
3185            .iter()
3186            .flat_map(|fragment_loop| &fragment_loop.coedges)
3187            .filter_map(|coedge| edge_key(&coedge.source))
3188            .filter(|key| !degenerate.contains(key))
3189        {
3190            *uses.entry(key).or_default() += 1;
3191        }
3192    }
3193    let mut over: Vec<(EdgeKey, usize)> = uses
3194        .into_iter()
3195        .filter(|(_, count)| *count > 2)
3196        .collect();
3197    over.sort_unstable();
3198    over.into_iter().next()
3199}
3200
3201/// The identity of a fragment coedge's edge, for the use census. A DERIVED
3202/// coedge carries a freshly minted curve rather than an identity, so it is not
3203/// counted — the rebuild's own closure check is what answers for those.
3204fn edge_key(source: &crate::fragment::FragmentEdgeSource) -> Option<EdgeKey> {
3205    use crate::fragment::FragmentEdgeSource;
3206    match source {
3207        FragmentEdgeSource::Boundary { operand, edge_id }
3208        | FragmentEdgeSource::SharedBoundary { operand, edge_id } => {
3209            Some(EdgeKey::Boundary(*operand, *edge_id))
3210        }
3211        FragmentEdgeSource::Imprint { piece_id } => Some(EdgeKey::Imprint(*piece_id)),
3212        FragmentEdgeSource::Derived { .. } => None,
3213    }
3214}
3215
3216#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
3217enum EdgeKey {
3218    Boundary(u8, u64),
3219    Imprint(u64),
3220}
3221
3222/// Every subset of `pieces` that leaves at least one behind, the empty one
3223/// included — the ways one face's pieces can be dropped.
3224fn proper_subsets(pieces: &[usize]) -> Vec<Vec<usize>> {
3225    let mut subsets = Vec::new();
3226    for mask in 0..(1u32 << pieces.len()) {
3227        if mask == (1u32 << pieces.len()) - 1 {
3228            // Dropping every piece of a crossing face is not a re-trim of it.
3229            continue;
3230        }
3231        subsets.push(
3232            pieces
3233                .iter()
3234                .enumerate()
3235                .filter(|(bit, _)| mask & (1 << bit) != 0)
3236                .map(|(_, piece)| *piece)
3237                .collect(),
3238        );
3239    }
3240    subsets
3241}
3242
3243/// Reassemble one choice of kept fragments and prove it sound, or say why not.
3244fn rebuild(
3245    split: &BrepSolid,
3246    selected: Vec<crate::fragment::FaceFragmentRecord>,
3247    imprint: &crate::imprint::ImprintResultRecord,
3248    scale: f64,
3249) -> Result<BrepSolid, KernelRefusal> {
3250    use crate::boolean::{assemble_open_fragments, finalize_assembled_solid};
3251    use rustc_hash::FxHashMap as HashMap;
3252
3253    let mut sources: HashMap<u8, &BrepSolid> = HashMap::default();
3254    sources.insert(SELF_OPERAND, split);
3255    let assembly_tolerance = 2e-3f64.max(scale * 5e-5);
3256    let solid = assemble_open_fragments(selected, &sources, imprint, assembly_tolerance)
3257        .map_err(|error| error.with_message(|error| format!("the kept pieces did not assemble: {error}")))?;
3258    let solid = finalize_assembled_solid(solid, assembly_tolerance)
3259        .map_err(|error| error.with_message(|error| format!("the assembly did not finalize: {error}")))?;
3260
3261    let issues = solid.validate();
3262    if !issues.is_empty() {
3263        return Err(KernelRefusal::internal(KernelStage::Validate, "rebuild.validate", format!(
3264            "the rebuilt body fails validate(): {}",
3265            issues[0].message
3266        )));
3267    }
3268    if crate::solid_connectivity(&solid).is_disconnected() {
3269        return Err(KernelRefusal::internal(KernelStage::Validate, "rebuild.connected", "the rebuilt body is not connected"));
3270    }
3271    let options = SelfIntersectionOptions::for_solid(&solid);
3272    let report = solid_self_intersections(&solid, options)
3273        .map_err(|message| format!("the rebuilt body could not be scanned: {message}"))
3274        .or_refuse(KernelStage::Validate, "solid_self_intersections")?;
3275    if report.is_flagged() {
3276        return Err(KernelRefusal::internal(KernelStage::Validate, "rebuild.self_intersects", format!(
3277            "the rebuilt body still self-intersects: {}",
3278            report.summary().unwrap_or_else(|| "no summary".into())
3279        )));
3280    }
3281    Ok(solid)
3282}
3283
3284/// One face of a body as its own open body, carrying the edges and vertices
3285/// that face uses and nothing else.
3286fn one_face_body(solid: &BrepSolid, face_id: u64) -> Result<BrepSolid, KernelRefusal> {
3287    use crate::topology::ShellRecord;
3288    use rustc_hash::FxHashSet as HashSet;
3289
3290    let face = solid
3291        .shells
3292        .iter()
3293        .flat_map(|shell| &shell.faces)
3294        .find(|face| face.id == face_id)
3295        .ok_or_else(|| {
3296            // The class its one caller gave it before this helper was typed.
3297            KernelRefusal::internal(KernelStage::Fragment, "one_face_body", format!("face {face_id} is not in this body"))
3298        })?
3299        .clone();
3300    let used: HashSet<u64> = face
3301        .loops
3302        .iter()
3303        .flat_map(|loop_record| &loop_record.coedges)
3304        .map(|coedge| coedge.edge_id)
3305        .collect();
3306    let edges: Vec<_> = solid
3307        .edges
3308        .iter()
3309        .filter(|edge| used.contains(&edge.id))
3310        .cloned()
3311        .collect();
3312    let vertices: HashSet<u64> = edges
3313        .iter()
3314        .flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id])
3315        .collect();
3316    Ok(BrepSolid {
3317        mass_properties_cache: Default::default(),
3318        id: solid.id,
3319        genus: 0,
3320        vertices: solid
3321            .vertices
3322            .iter()
3323            .filter(|vertex| vertices.contains(&vertex.id))
3324            .cloned()
3325            .collect(),
3326        edges,
3327        shells: vec![ShellRecord {
3328            id: 1,
3329            faces: vec![face],
3330        }],
3331    })
3332}
3333
3334// ---------------------------------------------------------------------------
3335// The ledger: a repaired result is reported as repaired
3336// ---------------------------------------------------------------------------
3337
3338/// One self-crossing this module REPAIRED rather than refused.
3339///
3340/// A repair changes the answer a lane returns, so it is never silent: the
3341/// feature that ran it carries this in its own result
3342/// (`FeatureResult::notes`), and the case gate records it per case. The
3343/// ledger is the carrier between the two — [`accept_sound`] is called from
3344/// lanes with no diagnostics record to write into, and threading one through
3345/// every lane exit would be a wider change than the repair itself. Same shape
3346/// as the boolean's `CONFORMANCE_REPAIRS` counter and the pcurve fit ledger.
3347#[derive(Clone, Debug)]
3348pub struct CrossingRepairRecord {
3349    /// The two faces that crossed.
3350    pub faces: (u64, u64),
3351    /// The crossing point the scan confirmed.
3352    pub point: crate::Vec3,
3353    /// How far past its band the crossing straddled.
3354    pub straddle: f64,
3355    /// Source faces whose pieces were dropped, with how many pieces of each.
3356    pub dropped: Vec<(u64, usize)>,
3357    /// Source faces the repair RETIRED a leftover from, with how many: a
3358    /// piece the drop left joined to nothing, or a whole loop of a face that
3359    /// nothing else answers for. Either way it is what the OLD configuration
3360    /// left on the body, and the ledger is the only place that says a repair
3361    /// took one off — "a piece was dropped" and "a leftover was retired" are
3362    /// different events.
3363    pub retired: Vec<(u64, usize)>,
3364    /// The faces the drop RE-TRIMMED: neighbours of the dropped material,
3365    /// which are neither of the crossing pair.
3366    pub retrimmed: Vec<u64>,
3367    /// Set when the repair was reached from the HOLE-CONTAINMENT FLOOR rather
3368    /// than from the scan: the face whose hole loop had left it, and that
3369    /// loop. `point` and `straddle` are then unmeasured and read zero, because
3370    /// no crossing was confirmed — the floor convicts a containment, not a
3371    /// crossing.
3372    pub breakout: Option<(u64, u64)>,
3373}
3374
3375impl std::fmt::Display for CrossingRepairRecord {
3376    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3377        if let Some((face, loop_id)) = self.breakout {
3378            return write!(
3379                formatter,
3380                "repaired a BREAKOUT: hole loop {loop_id} of face {face} had left that face \
3381                 onto face {}, so face {} — the wall it bounds — and face {} were split along \
3382                 their carriers' intersection; dropped {} and re-trimmed {}{}",
3383                self.faces.1,
3384                self.faces.0,
3385                self.faces.1,
3386                self.pieces_dropped(),
3387                self.faces_retrimmed(),
3388                self.pieces_retired(),
3389            );
3390        }
3391        write!(
3392            formatter,
3393            "repaired a self-crossing: faces {} and {} crossed near ({:.4}, {:.4}, {:.4}) \
3394             (straddle {:.3e}); split along their carriers' intersection, dropped {} \
3395             and re-trimmed {}{}",
3396            self.faces.0,
3397            self.faces.1,
3398            self.point.x,
3399            self.point.y,
3400            self.point.z,
3401            self.straddle,
3402            self.pieces_dropped(),
3403            self.faces_retrimmed(),
3404            self.pieces_retired(),
3405        )
3406    }
3407}
3408
3409impl CrossingRepairRecord {
3410    fn pieces_dropped(&self) -> String {
3411        self.dropped
3412            .iter()
3413            .map(|(face, count)| format!("{count} piece(s) of face {face}"))
3414            .collect::<Vec<_>>()
3415            .join(", ")
3416    }
3417
3418    fn faces_retrimmed(&self) -> String {
3419        if self.retrimmed.is_empty() {
3420            "no neighbouring face".to_string()
3421        } else {
3422            format!(
3423                "face(s) {}",
3424                self.retrimmed
3425                    .iter()
3426                    .map(|face| face.to_string())
3427                    .collect::<Vec<_>>()
3428                    .join(", ")
3429            )
3430        }
3431    }
3432
3433    /// The clause that says the OLD configuration's leftovers were taken off
3434    /// the body. Empty when nothing was retired, so every message this ledger
3435    /// already printed is unchanged; a repair that retires something says so
3436    /// and names the face, which is the only way the case gate's result line
3437    /// tells a repaired migration from the one it used to return.
3438    fn pieces_retired(&self) -> String {
3439        if self.retired.is_empty() {
3440            return String::new();
3441        }
3442        format!(
3443            ", and RETIRED {} the old configuration left, held by nothing else this repair keeps",
3444            self.retired
3445                .iter()
3446                .map(|(face, count)| format!("{count} leftover(s) of face {face}"))
3447                .collect::<Vec<_>>()
3448                .join(", ")
3449        )
3450    }
3451}
3452
3453thread_local! {
3454    static CROSSING_REPAIRS: std::cell::RefCell<Vec<CrossingRepairRecord>> =
3455        const { std::cell::RefCell::new(Vec::new()) };
3456}
3457
3458/// Take every repair made on this thread since the last call, leaving the
3459/// ledger empty. The history loop drains it after each feature so the repair
3460/// is reported against the feature that made it.
3461pub fn take_crossing_repairs() -> Vec<CrossingRepairRecord> {
3462    CROSSING_REPAIRS.with(|repairs| std::mem::take(&mut *repairs.borrow_mut()))
3463}
3464
3465/// Put a ledger back, replacing whatever is there.
3466///
3467/// The migration route TRIES candidate faces, and a trial that builds records
3468/// itself on the way past. Only the candidate whose body is returned may keep
3469/// its record, and a caller's own entries must survive the trials, so the
3470/// ledger is taken before and written back after. Nothing else may use this:
3471/// a repair reports itself once, where it happened.
3472fn restore_repairs(records: Vec<CrossingRepairRecord>) {
3473    CROSSING_REPAIRS.with(|repairs| *repairs.borrow_mut() = records);
3474}
3475
3476fn record_repair(
3477    fragments: &[crate::fragment::FaceFragmentRecord],
3478    dropped: &[usize],
3479    retired: &[u64],
3480    retrimmed_faces: &[u64],
3481    face_a: u64,
3482    face_b: u64,
3483    origin: &RepairOrigin<'_>,
3484) {
3485    let tally = |faces: &[u64]| {
3486        let mut by_face: Vec<(u64, usize)> = Vec::new();
3487        for face in faces {
3488            match by_face.iter_mut().find(|(existing, _)| existing == face) {
3489                Some((_, count)) => *count += 1,
3490                None => by_face.push((*face, 1)),
3491            }
3492        }
3493        by_face.sort_unstable();
3494        by_face
3495    };
3496    let by_face = tally(
3497        &dropped
3498            .iter()
3499            .map(|index| fragments[*index].source_face_id)
3500            .collect::<Vec<_>>(),
3501    );
3502    let retired = tally(retired);
3503    // A face that lost ONLY a detached piece was not re-trimmed — nothing of
3504    // it was re-cut, a leftover of the old configuration was taken off the
3505    // body — so it is reported under `retired` and not counted here twice.
3506    let mut retrimmed: Vec<u64> = by_face
3507        .iter()
3508        .filter(|(face, count)| {
3509            retired
3510                .iter()
3511                .find(|(retired_face, _)| retired_face == face)
3512                .map(|(_, retired_count)| retired_count < count)
3513                .unwrap_or(true)
3514        })
3515        .map(|(face, _)| *face)
3516        .chain(retrimmed_faces.iter().copied())
3517        .filter(|face| *face != face_a && *face != face_b)
3518        .collect();
3519    retrimmed.sort_unstable();
3520    retrimmed.dedup();
3521    let crossing = match origin {
3522        RepairOrigin::Scan(report) => report.confirmed.first(),
3523        RepairOrigin::Breakout { .. } => None,
3524    };
3525    let record = CrossingRepairRecord {
3526        faces: (face_a, face_b),
3527        point: crossing.map(|crossing| crossing.point).unwrap_or_default(),
3528        straddle: crossing.map(|crossing| crossing.straddle).unwrap_or_default(),
3529        dropped: by_face,
3530        retired,
3531        retrimmed,
3532        breakout: match origin {
3533            RepairOrigin::Scan(_) => None,
3534            RepairOrigin::Breakout { face, loop_id } => Some((*face, *loop_id)),
3535        },
3536    };
3537    if trace_on() {
3538        eprintln!("HEAL {record}");
3539    }
3540    CROSSING_REPAIRS.with(|repairs| repairs.borrow_mut().push(record));
3541}
3542
3543/// Write the flagged body out before the repair touches it, when
3544/// `BREP_HEAL_DUMP` names a directory. A crossing is measured off the body that
3545/// carries it — per-face areas, a mesh-arbitrated genus, the volume the repair
3546/// changes — and replaying a whole document to reach it again costs more than
3547/// the file does. Diagnostics only: the lane still repairs or refuses exactly
3548/// as it would have.
3549fn dump_flagged(solid: &BrepSolid, entry: &str) {
3550    let Ok(directory) = std::env::var("BREP_HEAL_DUMP") else {
3551        return;
3552    };
3553    if directory.is_empty() {
3554        return;
3555    }
3556    let name: String = entry
3557        .chars()
3558        .map(|character| if character.is_alphanumeric() { character } else { '_' })
3559        .collect();
3560    let path = std::path::Path::new(&directory).join(format!("flagged-{name}.json"));
3561    match serde_json::to_string(solid) {
3562        Ok(text) => {
3563            if let Err(error) = std::fs::write(&path, text) {
3564                eprintln!("HEAL dump {}: {error}", path.display());
3565            } else {
3566                eprintln!("HEAL dumped the flagged body to {}", path.display());
3567            }
3568        }
3569        Err(error) => eprintln!("HEAL dump: {error}"),
3570    }
3571}
3572
3573// ---------------------------------------------------------------------------
3574// Trace instrument (BREP_HEAL_TRACE=1)
3575// ---------------------------------------------------------------------------
3576
3577fn trace_on() -> bool {
3578    std::env::var("BREP_HEAL_TRACE").is_ok_and(|value| !value.is_empty() && value != "0")
3579}
3580
3581/// Measurement hatch for the section fit the repair's imprint asks for:
3582/// `BREP_HEAL_FIT_LANE=local|global` picks the lane its ladder starts in and
3583/// `BREP_HEAL_FIT_POINTS=<n>` its station budget. Both unset is the request as
3584/// built, so every lane and budget can be read off ONE binary against the
3585/// shipped one (`crossing_repair_probe body` with `BREP_DEBUG_POLYLINE_FIT=1`).
3586fn measured_fit_request(request: &mut crate::imprint::ImprintOptions) {
3587    match std::env::var("BREP_HEAL_FIT_LANE").as_deref() {
3588        Ok("local") => request.local_fit = true,
3589        Ok("global") => request.local_fit = false,
3590        _ => {}
3591    }
3592    if let Some(points) = std::env::var("BREP_HEAL_FIT_POINTS")
3593        .ok()
3594        .and_then(|value| value.parse::<usize>().ok())
3595        .filter(|points| *points >= 2)
3596    {
3597        request.maximum_fit_points = points;
3598    }
3599    if trace_on() {
3600        eprintln!(
3601            "HEAL imprint request: {} lane, {} stations, tolerance {:.3e}",
3602            if request.local_fit { "local" } else { "global" },
3603            request.maximum_fit_points,
3604            request.tolerance
3605        );
3606    }
3607}
3608
3609fn trace_solid(label: &str, solid: &BrepSolid) {
3610    use rustc_hash::FxHashMap as HashMap;
3611    let point: HashMap<u64, crate::Vec3> = solid
3612        .vertices
3613        .iter()
3614        .map(|vertex| (vertex.id, vertex.point))
3615        .collect();
3616    eprintln!(
3617        "HEAL {label}: {}F {}E {}V shells={}",
3618        solid.shells.iter().map(|shell| shell.faces.len()).sum::<usize>(),
3619        solid.edges.len(),
3620        solid.vertices.len(),
3621        solid.shells.len()
3622    );
3623    let mut uses: HashMap<u64, usize> = HashMap::default();
3624    for shell in &solid.shells {
3625        for face in &shell.faces {
3626            for loop_record in &face.loops {
3627                for coedge in &loop_record.coedges {
3628                    *uses.entry(coedge.edge_id).or_default() += 1;
3629                }
3630            }
3631        }
3632    }
3633    for edge in &solid.edges {
3634        let start = point.get(&edge.start_vertex_id).copied().unwrap_or_default();
3635        let end = point.get(&edge.end_vertex_id).copied().unwrap_or_default();
3636        eprintln!(
3637            "HEAL   edge {:>3} uses={} v{}->v{} ({:.4},{:.4},{:.4})->({:.4},{:.4},{:.4}) deg={} '{}'",
3638            edge.id,
3639            uses.get(&edge.id).copied().unwrap_or(0),
3640            edge.start_vertex_id,
3641            edge.end_vertex_id,
3642            start.x, start.y, start.z, end.x, end.y, end.z,
3643            edge.degenerate,
3644            edge.name.as_deref().unwrap_or("")
3645        );
3646    }
3647    for shell in &solid.shells {
3648        for face in &shell.faces {
3649            eprintln!(
3650                "HEAL   face {:>3} loops={} '{}'",
3651                face.id,
3652                face.loops.len(),
3653                face.name.as_deref().unwrap_or("")
3654            );
3655            for (index, loop_record) in face.loops.iter().enumerate() {
3656                let text = loop_record
3657                    .coedges
3658                    .iter()
3659                    .map(|coedge| format!("{}{}", if coedge.forward { '+' } else { '-' }, coedge.edge_id))
3660                    .collect::<Vec<_>>()
3661                    .join(" ");
3662                eprintln!("HEAL     loop {index}: {text}");
3663            }
3664        }
3665    }
3666}
3667
3668fn trace_imprint(imprint: &crate::imprint::ImprintResultRecord) {
3669    eprintln!(
3670        "HEAL imprint: {} piece(s) {} edge_split(s) by_face={:?}",
3671        imprint.pieces.len(),
3672        imprint.edge_splits.len(),
3673        imprint
3674            .by_face
3675            .iter()
3676            .map(|face| (face.operand, face.face_id, face.piece_ids.clone()))
3677            .collect::<Vec<_>>()
3678    );
3679    for piece in &imprint.pieces {
3680        let start = piece.curve.evaluate(piece.t0).unwrap_or_default();
3681        let end = piece.curve.evaluate(piece.t1).unwrap_or_default();
3682        let middle = piece.curve.evaluate((piece.t0 + piece.t1) / 2.0).unwrap_or_default();
3683        eprintln!(
3684            "HEAL   piece {} v{}->v{} ({:.4},{:.4},{:.4}) .. ({:.4},{:.4},{:.4}) .. ({:.4},{:.4},{:.4}) supports={:?} shared={:?}",
3685            piece.id,
3686            piece.start_vertex_id,
3687            piece.end_vertex_id,
3688            start.x, start.y, start.z,
3689            middle.x, middle.y, middle.z,
3690            end.x, end.y, end.z,
3691            piece.support_faces.iter().map(|key| (key.operand, key.face_id)).collect::<Vec<_>>(),
3692            piece.shared_edge,
3693        );
3694    }
3695    for split in &imprint.edge_splits {
3696        eprintln!(
3697            "HEAL   edge_split operand={} edge={} at {:?}",
3698            split.operand, split.edge_id, split.parameters
3699        );
3700    }
3701    for vertex in &imprint.vertices {
3702        eprintln!(
3703            "HEAL   imprint vertex {} ({:.4},{:.4},{:.4})",
3704            vertex.id, vertex.point.x, vertex.point.y, vertex.point.z
3705        );
3706    }
3707}
3708
3709fn trace_fragments(fragments: &[crate::fragment::FaceFragmentRecord]) {
3710    use crate::fragment::FragmentEdgeSource;
3711    eprintln!("HEAL fragments: {}", fragments.len());
3712    for (index, fragment) in fragments.iter().enumerate() {
3713        eprintln!(
3714            "HEAL   fragment {index} face {} loops={} test=({:.4},{:.4},{:.4})",
3715            fragment.source_face_id,
3716            fragment.loops.len(),
3717            fragment.test_point.x,
3718            fragment.test_point.y,
3719            fragment.test_point.z
3720        );
3721        for (loop_index, fragment_loop) in fragment.loops.iter().enumerate() {
3722            let text = fragment_loop
3723                .coedges
3724                .iter()
3725                .map(|coedge| {
3726                    let tag = match &coedge.source {
3727                        FragmentEdgeSource::Boundary { operand, edge_id } => format!("b{operand}:{edge_id}"),
3728                        FragmentEdgeSource::SharedBoundary { operand, edge_id } => format!("s{operand}:{edge_id}"),
3729                        FragmentEdgeSource::Imprint { piece_id } => format!("p{piece_id}"),
3730                        FragmentEdgeSource::Derived { start, end, .. } => format!(
3731                            "d({:.3},{:.3},{:.3})->({:.3},{:.3},{:.3})",
3732                            start.x, start.y, start.z, end.x, end.y, end.z
3733                        ),
3734                    };
3735                    format!("{}{tag}", if coedge.forward { '+' } else { '-' })
3736                })
3737                .collect::<Vec<_>>()
3738                .join(" ");
3739            eprintln!("HEAL     loop {loop_index}: {text}");
3740        }
3741    }
3742}
3743
3744