BREP_kernel 0.4.0

A boundary representation (BREP) geometry kernel for building CAD applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
use super::*;

struct HealPlan {
    /// The two boundary-edge indices whose neighbours are the primary pair.
    primary: [usize; 2],
    /// The two lateral boundary-edge indices (end caps).
    lateral: [usize; 2],
    /// Triple point (recovered corner) for each lateral index.
    lateral_point: HashMap<usize, Vec3>,
}

/// Choose the unique opposite neighbour pair whose planes re-intersect through
/// the transition face's region.
fn plan_heal(planes: &[Plane; 4], f_center: Vec3, f_reach: f64) -> Result<HealPlan, String> {
    let mut candidates: Vec<HealPlan> = Vec::new();
    for start in 0..2usize {
        let primary = [start, start + 2];
        let lateral = [(start + 1) % 4, (start + 3) % 4];
        let Some(line) = intersect_planes(&planes[primary[0]], &planes[primary[1]]) else {
            continue;
        };
        let mut lateral_point = HashMap::default();
        let mut ok = true;
        for &lat in &lateral {
            match intersect_line_plane(&line, &planes[lat]) {
                Some(point) if point.sub(f_center).length() <= f_reach => {
                    lateral_point.insert(lat, point);
                }
                _ => {
                    ok = false;
                    break;
                }
            }
        }
        if !ok {
            continue;
        }
        candidates.push(HealPlan {
            primary,
            lateral,
            lateral_point,
        });
    }
    match candidates.len() {
        1 => Ok(candidates.pop().unwrap()),
        0 => Err(
            "delete_face_and_heal: the neighbours do not re-intersect cleanly \
                  (parallel planes, non-adjacent healing, or a multi-face gap) — refusing \
                  rather than emitting an invalid solid"
                .into(),
        ),
        _ => Err(
            "delete_face_and_heal: healing is ambiguous — both opposite neighbour \
                  pairs re-intersect through the deleted face"
                .into(),
        ),
    }
}

// `retrim_planar_face` moved to the shared re-trim home
// (`crate::offset_retrim`, offset-unification audit §10) — its body is
// unchanged and it is re-exported here so its nine direct-edit call sites keep
// the bare name they have always used.
pub(super) use crate::offset_retrim::retrim_planar_face;

/// Find, in a face's loops, the (loop index, coedge index) of the coedge that
/// references `edge_id`.
pub(super) fn locate_coedge(face: &FaceRecord, edge_id: u64) -> Option<(usize, usize)> {
    for (loop_index, loop_record) in face.loops.iter().enumerate() {
        for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
            if coedge.edge_id == edge_id {
                return Some((loop_index, coedge_index));
            }
        }
    }
    None
}

pub(super) fn coedge_from_vertex(coedge: &CoedgeRecord, edges: &HashMap<u64, EdgeRecord>) -> Option<u64> {
    let edge = edges.get(&coedge.edge_id)?;
    Some(if coedge.forward {
        edge.start_vertex_id
    } else {
        edge.end_vertex_id
    })
}

pub(super) fn coedge_to_vertex(coedge: &CoedgeRecord, edges: &HashMap<u64, EdgeRecord>) -> Option<u64> {
    let edge = edges.get(&coedge.edge_id)?;
    Some(if coedge.forward {
        edge.end_vertex_id
    } else {
        edge.start_vertex_id
    })
}

/// Golovanov §6.12 — delete a transition face and heal the hole by extending
/// and re-intersecting its immediate neighbours. See the module docs for the
/// covered vs deferred cases. Returns a fresh solid that is guaranteed to
/// `validate()`, or a clear `Err` describing why the heal was refused.
pub fn delete_face_and_heal(solid: &BrepSolid, face_id: u64) -> Result<BrepSolid, String> {
    let mut solid = solid.clone();
    let scale = solid_model_scale(&solid);
    let tolerance = (scale * 1e-7).max(1e-9);

    let (shell_index, face_index) = find_face(&solid, face_id)
        .ok_or_else(|| format!("delete_face_and_heal: no face with id {face_id}"))?;

    // --- Read the transition face's boundary (immutable snapshot) ---------
    let boundary: Vec<(u64, bool)> = {
        let face = &solid.shells[shell_index].faces[face_index];
        if face.loops.len() != 1 {
            return Err(format!(
                "delete_face_and_heal: face {face_id} has {} loops; only a simple \
                 single-loop transition face is supported",
                face.loops.len()
            ));
        }
        face.loops[0]
            .coedges
            .iter()
            .map(|coedge| (coedge.edge_id, coedge.forward))
            .collect()
    };
    if boundary.len() != 4 {
        return Err(format!(
            "delete_face_and_heal: face {face_id} has {} boundary edges; only 4-sided \
             transition faces (a single chamfer/fillet edge) are supported \
             (deferred: multi-face gaps)",
            boundary.len()
        ));
    }
    let boundary_edge_ids: HashSet<u64> = boundary.iter().map(|(edge_id, _)| *edge_id).collect();
    if boundary_edge_ids.len() == 3 {
        // A CLOSED transition strip (a fillet/chamfer around a full rim):
        // loop = [seam+, rim_a, seam-, rim_b] — the seam doubled, two closed
        // rims. Heals by re-intersecting the two neighbours analytically.
        return heal_closed_transition(&solid, shell_index, face_index, &boundary);
    }
    if boundary_edge_ids.len() != 4 {
        return Err(
            "delete_face_and_heal: transition face uses an edge more than once \
                    (deferred: periodic/closed transition)"
                .into(),
        );
    }

    // Neighbour faces (one per boundary edge, in loop order).
    let mut neighbour_ids = [0u64; 4];
    for (index, (edge_id, _)) in boundary.iter().enumerate() {
        neighbour_ids[index] = other_face_of_edge(&solid, *edge_id, face_id)?;
    }
    let unique: HashSet<u64> = neighbour_ids.iter().copied().collect();
    if unique.len() != 4 {
        return Err(
            "delete_face_and_heal: the transition face touches a neighbour more \
                    than once (deferred: periodic/closed transition)"
                .into(),
        );
    }

    // Carriers of the neighbours: all-planar takes the closed-form planar
    // path below; any curved analytic neighbour routes to the mixed
    // open-chain heal (plane × cylinder/ruled-revolution re-intersection).
    let neighbour_planes: [Plane; 4] = {
        let mut planes: Vec<Option<Plane>> = Vec::with_capacity(4);
        for &neighbour_id in &neighbour_ids {
            let (ns, nf) = find_face(&solid, neighbour_id)
                .ok_or_else(|| format!("delete_face_and_heal: missing neighbour {neighbour_id}"))?;
            planes.push(
                plane_of_surface(
                    &solid.shells[ns].faces[nf].surface,
                    (scale * 1e-6).max(1e-7),
                    "delete_face_and_heal",
                )
                .ok(),
            );
        }
        if planes.iter().any(Option::is_none) {
            return heal_open_transition_mixed(
                &solid,
                shell_index,
                face_index,
                &boundary,
                &neighbour_ids,
            );
        }
        [
            planes[0].unwrap(),
            planes[1].unwrap(),
            planes[2].unwrap(),
            planes[3].unwrap(),
        ]
    };

    // Transition-face region gate (centre + reach), from its loop vertices.
    let transition_vertices: Vec<u64> = boundary
        .iter()
        .map(|(edge_id, forward)| {
            let edge = solid
                .edges
                .iter()
                .find(|edge| edge.id == *edge_id)
                .ok_or_else(|| format!("delete_face_and_heal: missing edge {edge_id}"))?;
            Ok(if *forward {
                edge.start_vertex_id
            } else {
                edge.end_vertex_id
            })
        })
        .collect::<Result<Vec<u64>, String>>()?;
    if transition_vertices.iter().collect::<HashSet<_>>().len() != 4 {
        return Err(
            "delete_face_and_heal: transition face has repeated corner vertices \
                    (deferred: degenerate transition)"
                .into(),
        );
    }
    let mut f_center = Vec3::default();
    for &vertex_id in &transition_vertices {
        f_center = f_center.add(edge_point(&solid, vertex_id)?);
    }
    f_center = f_center.scale(0.25);
    let mut f_reach = 0.0f64;
    for &vertex_id in &transition_vertices {
        f_reach = f_reach.max(edge_point(&solid, vertex_id)?.sub(f_center).length());
    }
    let f_reach = f_reach * 3.0 + tolerance;

    let plan = plan_heal(&neighbour_planes, f_center, f_reach)?;

    // --- New recovered corners (triple points) and the new sharp edge ------
    let mut next_id = max_topology_id(&solid) + 1;
    let mut alloc = || {
        let value = next_id;
        next_id += 1;
        value
    };

    let lateral_a = plan.lateral[0];
    let lateral_b = plan.lateral[1];
    let point_a = plan.lateral_point[&lateral_a];
    let point_b = plan.lateral_point[&lateral_b];
    if point_a.sub(point_b).length() <= tolerance {
        return Err(
            "delete_face_and_heal: recovered corners coincide — the neighbours \
                    do not bound a clean edge"
                .into(),
        );
    }
    let vertex_a = alloc();
    let vertex_b = alloc();
    let mut lateral_vertex: HashMap<usize, u64> = HashMap::default();
    lateral_vertex.insert(lateral_a, vertex_a);
    lateral_vertex.insert(lateral_b, vertex_b);

    // The new sharp edge S (start = corner A, end = corner B).
    let sharp_edge_id = alloc();
    let sharp_edge = EdgeRecord {
        id: sharp_edge_id,
        curve: make_line(point_a, point_b)?,
        t0: 0.0,
        t1: 1.0,
        start_vertex_id: vertex_a,
        end_vertex_id: vertex_b,
        degenerate: false,
        name: None,
    };

    // --- Collapse each transition corner onto its recovered corner ---------
    // Corner vertex `transition_vertices[i]` sits between neighbour[(i+3)%4]
    // and neighbour[i]; exactly one of those two is a lateral face, and the
    // corner collapses onto that lateral's recovered corner.
    let lateral_set: HashSet<usize> = plan.lateral.iter().copied().collect();
    let mut collapse: HashMap<u64, u64> = HashMap::default();
    for index in 0..4usize {
        let previous = (index + 3) % 4;
        let lateral_index = if lateral_set.contains(&previous) {
            previous
        } else if lateral_set.contains(&index) {
            index
        } else {
            return Err(
                "delete_face_and_heal: transition corner is not flanked by a \
                        lateral face (unexpected neighbour ordering)"
                    .into(),
            );
        };
        let target = lateral_vertex[&lateral_index];
        collapse.insert(transition_vertices[index], target);
    }
    let new_vertex_points: HashMap<u64, Vec3> = [(vertex_a, point_a), (vertex_b, point_b)]
        .into_iter()
        .collect();

    // Relocate every non-transition edge that ends on a collapsed corner.
    for edge in &mut solid.edges {
        if boundary_edge_ids.contains(&edge.id) {
            continue;
        }
        let start_target = collapse.get(&edge.start_vertex_id).copied();
        let end_target = collapse.get(&edge.end_vertex_id).copied();
        if start_target.is_none() && end_target.is_none() {
            continue;
        }
        if edge.curve.degree != 1 || edge.curve.control_points.len() != 2 {
            return Err(
                "delete_face_and_heal: a side edge meeting the transition face is \
                        not a straight line (deferred: curved neighbour edges)"
                    .into(),
            );
        }
        let mut start_point = edge.curve.control_points[0].point()?;
        let mut end_point = edge.curve.control_points[1].point()?;
        if let Some(target) = start_target {
            edge.start_vertex_id = target;
            start_point = new_vertex_points[&target];
        }
        if let Some(target) = end_target {
            edge.end_vertex_id = target;
            end_point = new_vertex_points[&target];
        }
        if start_point.sub(end_point).length() <= tolerance {
            return Err(
                "delete_face_and_heal: healing would collapse a side edge to zero \
                        length (deferred: degenerate transition)"
                    .into(),
            );
        }
        edge.curve = make_line(start_point, end_point)?;
        edge.t0 = 0.0;
        edge.t1 = 1.0;
    }

    // Index the (now relocated) edges for loop rewrites and pcurve rebuilds.
    let mut edges_by_id: HashMap<u64, EdgeRecord> = solid
        .edges
        .iter()
        .map(|edge| (edge.id, edge.clone()))
        .collect();
    edges_by_id.insert(sharp_edge_id, sharp_edge.clone());

    // --- Rewrite neighbour loops ------------------------------------------
    // Primary faces: replace their support coedge (on the deleted face's edge)
    // with a coedge on the new sharp edge S.
    for &primary_index in &plan.primary {
        let primary_edge = boundary[primary_index].0;
        let neighbour_id = neighbour_ids[primary_index];
        let (ns, nf) = find_face(&solid, neighbour_id)
            .ok_or_else(|| format!("delete_face_and_heal: missing neighbour {neighbour_id}"))?;
        let face = &mut solid.shells[ns].faces[nf];
        let (loop_index, coedge_index) = locate_coedge(face, primary_edge).ok_or_else(|| {
            format!(
                "delete_face_and_heal: neighbour {neighbour_id} does not use edge {primary_edge}"
            )
        })?;
        let coedges = &face.loops[loop_index].coedges;
        let count = coedges.len();
        let previous = &coedges[(coedge_index + count - 1) % count];
        let next = &coedges[(coedge_index + 1) % count];
        let required_from = coedge_to_vertex(previous, &edges_by_id).ok_or_else(|| {
            "delete_face_and_heal: could not resolve loop connectivity".to_string()
        })?;
        let required_to = coedge_from_vertex(next, &edges_by_id).ok_or_else(|| {
            "delete_face_and_heal: could not resolve loop connectivity".to_string()
        })?;
        let forward = if required_from == vertex_a && required_to == vertex_b {
            true
        } else if required_from == vertex_b && required_to == vertex_a {
            false
        } else {
            return Err(
                "delete_face_and_heal: new edge does not close the primary loop \
                        (unexpected connectivity)"
                    .into(),
            );
        };
        let new_coedge = CoedgeRecord {
            id: alloc(),
            edge_id: sharp_edge_id,
            forward,
            // Placeholder; retrim_planar_face recomputes every pcurve below.
            pcurve: make_line(Vec3::default(), Vec3::new(1.0, 0.0, 0.0))?,
        };
        face.loops[loop_index].coedges[coedge_index] = new_coedge;
    }

    // Lateral (cap) faces: drop the cap coedge; its two neighbours already
    // meet at the recovered corner.
    for &lateral_index in &plan.lateral {
        let lateral_edge = boundary[lateral_index].0;
        let neighbour_id = neighbour_ids[lateral_index];
        let (ns, nf) = find_face(&solid, neighbour_id)
            .ok_or_else(|| format!("delete_face_and_heal: missing neighbour {neighbour_id}"))?;
        let face = &mut solid.shells[ns].faces[nf];
        let (loop_index, coedge_index) = locate_coedge(face, lateral_edge).ok_or_else(|| {
            format!(
                "delete_face_and_heal: neighbour {neighbour_id} does not use edge {lateral_edge}"
            )
        })?;
        face.loops[loop_index].coedges.remove(coedge_index);
        if face.loops[loop_index].coedges.is_empty() {
            return Err("delete_face_and_heal: healing emptied a lateral face loop".into());
        }
    }

    // --- Prune the deleted face, its edges, and its corner vertices --------
    solid.shells[shell_index]
        .faces
        .retain(|face| face.id != face_id);
    solid
        .edges
        .retain(|edge| !boundary_edge_ids.contains(&edge.id));
    let removed_vertices: HashSet<u64> = transition_vertices.iter().copied().collect();
    solid.edges.push(sharp_edge);
    solid
        .vertices
        .retain(|vertex| !removed_vertices.contains(&vertex.id));
    solid.vertices.push(VertexRecord {
        id: vertex_a,
        point: point_a,
    });
    solid.vertices.push(VertexRecord {
        id: vertex_b,
        point: point_b,
    });

    // --- Re-trim every affected neighbour on its (extended) carrier --------
    let final_edges: HashMap<u64, EdgeRecord> = solid
        .edges
        .iter()
        .map(|edge| (edge.id, edge.clone()))
        .collect();
    for (index, &neighbour_id) in neighbour_ids.iter().enumerate() {
        let plane = neighbour_planes[index];
        let (ns, nf) = find_face(&solid, neighbour_id)
            .ok_or_else(|| format!("delete_face_and_heal: missing neighbour {neighbour_id}"))?;
        retrim_planar_face(
            &mut solid.shells[ns].faces[nf],
            &plane,
            &final_edges,
            scale,
            "delete_face_and_heal",
        )?;
    }

    // Genus is preserved by removing a genus-neutral transition face; the
    // Euler check inside validate() confirms it.
    let issues = solid.validate();
    if !issues.is_empty() {
        return Err(format!(
            "delete_face_and_heal: healed solid failed validation: {issues:?}"
        ));
    }
    Ok(solid)
}

/// Resolve the id of the face nearest a 3D point (used by the app: the picked
/// point lies on the selected face). Mirrors `resolve_edge_by_point`.
pub fn resolve_face_by_point(solid: &BrepSolid, point: Vec3) -> Result<u64, String> {
    let scale = solid_model_scale(&solid);
    let mut best: Option<(u64, f64)> = None;
    for shell in &solid.shells {
        for face in &shell.faces {
            let Ok(projection) = crate::project_point_to_surface(&face.surface, point) else {
                continue;
            };
            if best
                .map(|(_, known)| projection.distance < known)
                .unwrap_or(true)
            {
                best = Some((face.id, projection.distance));
            }
        }
    }
    match best {
        Some((face_id, distance)) if distance <= (scale * 1e-3).max(1e-4) => Ok(face_id),
        Some((_, distance)) => Err(format!(
            "delete_face_and_heal: no face within tolerance of the point (nearest {distance:.6})"
        )),
        None => Err("delete_face_and_heal: solid has no faces".into()),
    }
}

// ---------------------------------------------------------------------------
// Tests — the capability matrix `examples/delete_face_matrix_probe.rs` measures,
// pinned. The probe is the instrument; these are the assertions it justified.
//
// The three lanes `delete_face_and_heal` dispatches across are covered in
// `tests.rs` (all-planar), `closed_heal_tests.rs` (closed full rim) and
// `open_heal_tests.rs` (open mixed). What lives HERE is what those files left
// unpinned: the dispatch GATES that never reach a lane at all, the closed
// lane's carrier breadth, and the one measurement that decides whether the
// shared re-intersection seam can replace the planar closed form.
// ---------------------------------------------------------------------------
#[cfg(test)]
mod delete_face_tests {
    use super::*;
    use crate::{
        boolean_operation, chamfer_edge, fillet_edge, make_box_brep, make_cone_brep,
        make_cylinder_brep, make_sphere_brep, solid_mass_properties, BooleanOperation,
        BooleanOptions,
    };

    /// The closed rim edge of a body of revolution at height `z`.
    fn closed_rim_at(solid: &BrepSolid, z: f64) -> u64 {
        solid
            .edges
            .iter()
            .find(|edge| {
                !edge.degenerate
                    && edge.start_vertex_id == edge.end_vertex_id
                    && edge
                        .curve
                        .evaluate(0.5 * (edge.t0 + edge.t1))
                        .map(|point| (point.z - z).abs() < 1e-6)
                        .unwrap_or(false)
            })
            .expect("closed rim")
            .id
    }

    fn named_face(solid: &BrepSolid, name: &str) -> u64 {
        solid
            .shells
            .iter()
            .flat_map(|shell| &shell.faces)
            .find(|face| face.name.as_deref() == Some(name))
            .expect("named blend face")
            .id
    }

    fn volume(solid: &BrepSolid) -> f64 {
        solid_mass_properties(solid)
            .expect("mass properties")
            .volume
    }

    /// Blend a closed rim, delete the blend, and require the ORIGINAL body
    /// back: same face count, same volume, clean `validate()`. The blend is
    /// the only thing that changed, so anything else that moves is a bug.
    fn round_trip(
        sharp: &BrepSolid,
        rim: u64,
        blend: fn(&BrepSolid, u64, f64, Option<&str>) -> Result<BrepSolid, String>,
        size: f64,
    ) -> BrepSolid {
        let faces_before: usize = sharp.shells.iter().map(|shell| shell.faces.len()).sum();
        let volume_before = volume(sharp);
        let blended = blend(sharp, rim, size, Some("B1")).expect("blend");
        assert!(blended.validate().is_empty(), "{:?}", blended.validate());
        let strip = named_face(&blended, "B1");

        let healed = delete_face_and_heal(&blended, strip).expect("heal");
        assert!(
            healed.validate().is_empty(),
            "healed solid must validate: {:?}",
            healed.validate()
        );
        assert_eq!(
            healed
                .shells
                .iter()
                .map(|shell| shell.faces.len())
                .sum::<usize>(),
            faces_before,
            "face count must return to the pre-blend count"
        );
        let volume_after = volume(&healed);
        assert!(
            (volume_after - volume_before).abs() <= 1e-6 * volume_before.abs(),
            "expected the pre-blend volume {volume_before}, got {volume_after}"
        );
        healed
    }

    // --- closed lane: carrier breadth ------------------------------------

    /// A rim CHAMFER leaves a conical strip between the same two neighbours a
    /// rim fillet leaves a toroidal one between. `closed_heal_tests.rs` pins
    /// only the fillet; this pins that the strip's own carrier is irrelevant
    /// to the heal, which re-intersects the NEIGHBOURS.
    #[test]
    fn closed_heal_restores_the_cylinder_after_a_rim_chamfer() {
        let cylinder =
            make_cylinder_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), 4.0, 6.0).unwrap();
        let rim = closed_rim_at(&cylinder, 6.0);
        let healed = round_trip(&cylinder, rim, chamfer_edge, 1.0);
        // The re-sharpened rim is back at the top, radius 4.
        assert!(healed.edges.iter().any(|edge| {
            let Ok(point) = edge.curve.evaluate(0.5 * (edge.t0 + edge.t1)) else {
                return false;
            };
            (point.z - 6.0).abs() < 1e-6 && (point.x.hypot(point.y) - 4.0).abs() < 1e-6
        }));
    }

    /// A cone frustum's wall is a TAPERED ruled revolution — the closed form
    /// the rim rebind uses is `axial / height`, which is only the identity for
    /// a cylinder. Pins that the taper is carried.
    #[test]
    fn closed_heal_restores_the_cone_frustum_after_a_rim_fillet() {
        let cone =
            make_cone_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), 5.0, 2.5, 6.0).unwrap();
        let rim = closed_rim_at(&cone, 6.0);
        let healed = round_trip(&cone, rim, fillet_edge, 0.8);
        assert!(healed.edges.iter().any(|edge| {
            let Ok(point) = edge.curve.evaluate(0.5 * (edge.t0 + edge.t1)) else {
                return false;
            };
            (point.z - 6.0).abs() < 1e-6 && (point.x.hypot(point.y) - 2.5).abs() < 1e-6
        }));
    }

    /// An upper half-ball: a flat disk whose only neighbour is the spherical
    /// dome, meeting along the great-circle equator.
    fn upper_half_ball(radius: f64) -> BrepSolid {
        let sphere = make_sphere_brep(Vec3::default(), radius, Vec3::new(0.0, 0.0, 1.0)).unwrap();
        let box_up = make_box_brep(
            Vec3::new(-2.0 * radius, -2.0 * radius, 0.0),
            4.0 * radius,
            4.0 * radius,
            2.0 * radius,
        )
        .unwrap();
        let options = BooleanOptions {
            merge_coplanar_faces: true,
            ..BooleanOptions::default()
        };
        boolean_operation(&sphere, &box_up, BooleanOperation::Intersect, &options).unwrap()
    }

    /// A SPHERE neighbour. `intersect_analytic_pair` answers Sphere×Plane with
    /// the exact equator circle, but the rim rebind used to refuse anything
    /// that was not a `RuledRevolution` — the gate was narrower than the
    /// intersector behind it. Measured by the matrix probe as
    /// `ERR curved neighbour is not a ruled revolution` before this landed.
    #[test]
    fn closed_heal_rebinds_a_sphere_neighbour_after_a_rim_fillet() {
        let ball = upper_half_ball(5.0);
        let rim = closed_rim_at(&ball, 0.0);
        let healed = round_trip(&ball, rim, fillet_edge, 0.8);
        // The recovered rim is the great circle: radius 5 in the plane z = 0.
        assert!(healed.edges.iter().any(|edge| {
            let Ok(point) = edge.curve.evaluate(0.5 * (edge.t0 + edge.t1)) else {
                return false;
            };
            point.z.abs() < 1e-6 && (point.x.hypot(point.y) - 5.0).abs() < 1e-6
        }));
        // Every point of every edge still sits on the ball or its base plane —
        // the check that catches a seam meridian replaced by its chord.
        for edge in &healed.edges {
            if edge.degenerate {
                continue;
            }
            for step in 0..=8 {
                let t = edge.t0 + (edge.t1 - edge.t0) * f64::from(step) / 8.0;
                let point = edge.curve.evaluate(t).unwrap();
                let on_sphere = (point.length() - 5.0).abs() < 1e-6;
                let on_base = point.z.abs() < 1e-6 && point.length() <= 5.0 + 1e-6;
                assert!(
                    on_sphere || on_base,
                    "edge {} left both carriers at t={t}: {point:?}",
                    edge.id
                );
            }
        }
    }

    /// The same neighbour pair with a CONICAL strip instead of a toroidal one.
    #[test]
    fn closed_heal_rebinds_a_sphere_neighbour_after_a_rim_chamfer() {
        let ball = upper_half_ball(5.0);
        let rim = closed_rim_at(&ball, 0.0);
        round_trip(&ball, rim, chamfer_edge, 0.8);
    }

    /// A TORUS neighbour, the other carrier `intersect_plane_quadric` answers
    /// and the rim rebind used to refuse. Half a torus cut by the plane
    /// through its tube: `Plane × Torus` returns TWO closed circles (inner and
    /// outer rim), so this also pins that the heal picks the branch the strip
    /// surrounded rather than the first one offered.
    #[test]
    fn closed_heal_rebinds_a_torus_neighbour_after_a_rim_fillet() {
        let torus =
            crate::make_torus_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), 5.0, 2.0).unwrap();
        let box_up = make_box_brep(Vec3::new(-20.0, -20.0, 0.0), 40.0, 40.0, 20.0).unwrap();
        let options = BooleanOptions {
            merge_coplanar_faces: true,
            ..BooleanOptions::default()
        };
        let half =
            boolean_operation(&torus, &box_up, BooleanOperation::Intersect, &options).unwrap();
        // Half a torus: V = pi^2 * R * r^2.
        let expected = std::f64::consts::PI.powi(2) * 5.0 * 4.0;
        assert!((volume(&half) - expected).abs() <= 1e-6 * expected);
        let rim = closed_rim_at(&half, 0.0);
        let healed = round_trip(&half, rim, fillet_edge, 0.4);
        assert!((volume(&healed) - expected).abs() <= 1e-6 * expected);
    }

    // --- dispatch gates: the refusals that never reach a lane --------------

    #[test]
    fn refuses_a_face_that_does_not_exist() {
        let cube = make_box_brep(Vec3::default(), 1.0, 1.0, 1.0).unwrap();
        let error = delete_face_and_heal(&cube, 999_999).unwrap_err();
        assert!(
            error.contains("no face with id 999999"),
            "unexpected refusal: {error}"
        );
    }

    /// A drilled plate's top face has TWO loops (outer boundary + the hole).
    /// Healing a multi-loop face is a different problem from healing a
    /// transition strip; the gate must say so rather than heal the outer loop
    /// and leave the hole dangling.
    #[test]
    fn refuses_a_multi_loop_face_naming_the_loop_count() {
        let plate = make_box_brep(Vec3::default(), 20.0, 20.0, 4.0).unwrap();
        let drill = make_cylinder_brep(
            Vec3::new(10.0, 10.0, -1.0),
            Vec3::new(0.0, 0.0, 1.0),
            3.0,
            6.0,
        )
        .unwrap();
        let drilled = boolean_operation(
            &plate,
            &drill,
            BooleanOperation::Subtract,
            &BooleanOptions::default(),
        )
        .unwrap();
        let top = resolve_face_by_point(&drilled, Vec3::new(2.0, 2.0, 4.0)).unwrap();
        let error = delete_face_and_heal(&drilled, top).unwrap_err();
        assert!(
            error.contains("2 loops") && error.contains("single-loop"),
            "refusal must name the loop count: {error}"
        );
    }

    /// A 3-sided face is a CORNER transition: healing it recovers a vertex,
    /// not an edge, and that is a different algorithm (heal-tail plan §3.3,
    /// k = 3). The gate must name the side count so the refusal is actionable.
    #[test]
    fn refuses_a_face_that_is_not_four_sided() {
        let cube = make_box_brep(Vec3::default(), 10.0, 10.0, 10.0).unwrap();
        let profile = [
            make_line(Vec3::new(8.0, 0.0, 10.0), Vec3::new(0.0, 8.0, 10.0)).unwrap(),
            make_line(Vec3::new(0.0, 8.0, 10.0), Vec3::new(20.0, 20.0, 10.0)).unwrap(),
            make_line(Vec3::new(20.0, 20.0, 10.0), Vec3::new(8.0, 0.0, 10.0)).unwrap(),
        ];
        let cutter =
            crate::extrude_profile_brep(&profile, Vec3::new(0.0, 0.0, -1.0), 8.0).unwrap();
        let cut = boolean_operation(
            &cube,
            &cutter,
            BooleanOperation::Subtract,
            &BooleanOptions::default(),
        )
        .unwrap();
        let triangle = cut
            .shells
            .iter()
            .flat_map(|shell| &shell.faces)
            .find(|face| face.loops.len() == 1 && face.loops[0].coedges.len() == 3)
            .expect("3-sided cut face")
            .id;
        let error = delete_face_and_heal(&cut, triangle).unwrap_err();
        assert!(
            error.contains("3 boundary edges") && error.contains("4-sided"),
            "refusal must name the side count: {error}"
        );
    }

    // --- the shared re-intersection seam, measured -------------------------

    /// Can `offset_reintersect::reintersect_carriers` — the shared "these two
    /// carriers used to meet through a face that moved, where do they meet
    /// now" service — replace the all-planar closed form in `plan_heal`?
    ///
    /// MEASURED, not predicted: it ANSWERS — but only through the MARCHED
    /// lane, and that is the whole answer.
    ///
    /// `intersect_analytic_pair` declines Plane×Plane **by design**
    /// (`geometry/analytic_surface/intersect.rs:173-179`, with the reason in a
    /// comment there), so the shared seam falls straight through its exact
    /// lane for the commonest delete-face case there is and traces the line
    /// instead. What comes back is a `fit_polyline` of a traced polyline,
    /// residual-gated but an approximation; `plan_heal` returns the exact
    /// `intersect_planes` line. Swapping the seam in for the closed form would
    /// therefore replace an exact edge with a fitted one on every chamfered
    /// box in the corpus — strictly less exact, and not bit-identical.
    ///
    /// (A prediction this test refuted, recorded so it is not made twice: the
    /// march was expected to find NOTHING, on the grounds that it clamps to
    /// each surface's stored domain — `intersect/surface_surface_intersection.rs:111-117`
    /// — and a blend trims its neighbours back. It does clamp; but `chamfer_edge`
    /// leaves the neighbour CARRIERS at their original extents and only rewrites
    /// the trim loops, so the patches still overlap. Carrier coverage after a
    /// blend is a property of the blend, not something a general re-intersection
    /// may assume either way.)
    #[test]
    fn the_shared_reintersect_seam_declines_the_chamfered_cube_primaries() {
        let cube = make_box_brep(Vec3::default(), 1.0, 1.0, 1.0).unwrap();
        let edge = cube
            .edges
            .iter()
            .find(|edge| {
                edge.curve
                    .evaluate(0.5 * (edge.t0 + edge.t1))
                    .map(|point| (point.x - 1.0).abs() < 1e-9 && (point.z - 1.0).abs() < 1e-9)
                    .unwrap_or(false)
            })
            .expect("top-right cube edge")
            .id;
        let chamfered = chamfer_edge(&cube, edge, 0.2, Some("C1")).unwrap();
        let strip = named_face(&chamfered, "C1");

        // The two PRIMARY neighbours: the faces the chamfer's opposite
        // boundary edges border — the ones whose re-intersection is the
        // recovered sharp edge.
        let top = resolve_face_by_point(&chamfered, Vec3::new(0.4, 0.5, 1.0)).unwrap();
        let right = resolve_face_by_point(&chamfered, Vec3::new(1.0, 0.5, 0.4)).unwrap();
        assert_ne!(top, strip);
        assert_ne!(right, strip);
        let surface_of = |id: u64| {
            chamfered
                .shells
                .iter()
                .flat_map(|shell| &shell.faces)
                .find(|face| face.id == id)
                .map(|face| face.surface.clone())
                .expect("face")
        };

        // Seeded on the very boundary the heal is replacing — the strongest
        // seed set there is, so a refusal here is not a seeding accident.
        let mut seeds: Vec<Vec3> = Vec::new();
        for edge in &chamfered.edges {
            for step in 0..=4 {
                let t = edge.t0 + (edge.t1 - edge.t0) * f64::from(step) / 4.0;
                if let Ok(point) = edge.curve.evaluate(t) {
                    seeds.push(point);
                }
            }
        }
        let policy = MarchPolicy {
            tolerance: 1e-7,
            residual_tolerance: 1e-5,
            seeds,
        };
        let found = reintersect_carriers(&surface_of(top), &surface_of(right), &policy)
            .expect("the seam answers this pair");
        assert!(
            matches!(found.lane, RimLane::Marched),
            "plane x plane has no closed form, so the answer must come from the \
             marched lane; got the analytic one"
        );
        assert_eq!(found.sections.len(), 1, "one line, traced");
        // It is the right line, to within a fit residual — which is exactly the
        // exactness the closed form does not spend.
        let section = &found.sections[0];
        let [s0, s1] = section.curve.domain().unwrap();
        let mut worst = 0.0f64;
        for step in 0..=16 {
            let point = section
                .curve
                .evaluate(s0 + (s1 - s0) * f64::from(step) / 16.0)
                .unwrap();
            worst = worst.max((point.x - 1.0).abs().max((point.z - 1.0).abs()));
        }
        assert!(worst <= 1e-5, "the marched line drifts {worst} off x=1,z=1");

        // And the operation heals them anyway, through the closed form.
        let healed = delete_face_and_heal(&chamfered, strip).unwrap();
        assert!(healed.validate().is_empty());
        assert!((volume(&healed) - 1.0).abs() < 1e-9);
    }
}