BREP_kernel 0.5.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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
use super::*;

/// Extend a hole-wall offset carrier's trim past the opening planes it
/// pierces, so the arrangement — not a rim weld — closes the opening.
///
/// `offset_face_carrier` trims the offset carrier with the parametric IMAGE
/// of the source trim: every source rim point moves `distance` along the
/// local surface normal. When the hole wall meets the pierced face
/// perpendicularly, that image stays in the opening plane and the coplanar
/// rim welds close the shell. When the wall is OBLIQUE (tilted drill axis)
/// or CONICAL, the normal has a component along the opening normal and the
/// image rim leaves the plane — for a tilted cylinder it oscillates
/// sinusoidally about it (z = z₀ + d·n_z(θ)), for a cone it is a coaxial
/// circle shifted along the axis by d·sin(half-angle). The pair imprint
/// against the opening plane then only exists where the image OVERSHOOTS
/// the plane; on the fall-short side the offset skin ends mid-air inside
/// the material, the source rim and the image rim both stay one-use, and
/// the honesty gate refuses the shell.
///
/// The correct opening wall is the piece of the ORIGINAL pierced face's
/// plane between the source rim and the offset carrier's exact plane
/// section (Parasolid hollow semantics: the cavity is trimmed by the
/// opening surface). That is precisely what the arrangement already builds
/// on its own whenever the offset carrier REACHES through the plane — the
/// carrier × opening-plane imprint is the exact conic (analytic plane ×
/// quadric SSI), the carrier keeps its main fragment, and the wall
/// fragment on the opening plane is the flat annulus between the drilled
/// rim and that conic. So instead of welding the gap after assembly,
/// rebuild the qualifying carrier's trim as the full-period band of its
/// surface extended to the surface's own v-domain ends, which lie beyond
/// the opening planes (drill tools always overshoot the stock). Exactness
/// is free: the new rims are surface isolines and the conic trims come
/// from the analytic intersection.
///
/// Qualification is deliberately narrow so every landed lane keeps its
/// existing path (straight holes: coplanar rim-pair welds; frustum outer
/// walls: ruled band weld):
/// - the carrier face is a closed band: nothing but closed full-period
///   rims (exactly two), face-local seams, and degenerate placeholders;
/// - each rim edge is shared with a PLANAR opening face as an INNER
///   (hole) loop of that face — an outer-loop rim is the frustum lane,
///   where the opening face ends at the wall and the ruled band is the
///   landed closure;
/// - the rim's offset image genuinely leaves the opening plane (beyond
///   the weld tolerance band) — an in-plane image is the straight-hole
///   lane;
/// - both surface v-domain ends clear their opening planes on the far
///   side, so the extended band genuinely reaches through both openings
///   (when the surface itself stops short, nothing can close the shell
///   and the honest refusal stands).
pub(super) fn extend_offset_carriers_past_open_hole_rims(
    carriers: &mut [Carrier],
    source: &BrepSolid,
    source_faces: &[&FaceRecord],
    opening_set: &HashSet<u64>,
    smooth_pairs: &HashSet<(usize, usize)>,
    scale: f64,
) -> Result<HashSet<usize>, String> {
    let weld_band = 2e-3f64.max(scale * 5e-5);
    let source_edge_by_id = source
        .edges
        .iter()
        .map(|edge| (edge.id, edge))
        .collect::<HashMap<_, _>>();
    let mut extended = HashSet::default();
    'carrier: for index in 0..carriers.len() {
        if !matches!(carriers[index].kind, OffsetFaceRole::Offset) {
            continue;
        }
        // Smooth-synchronized carriers had boundary curves rewritten against
        // their tangent neighbours; leave them to that machinery.
        if smooth_pairs
            .iter()
            .any(|(first, second)| *first == index || *second == index)
        {
            continue;
        }
        let Some(source_face) = source_faces
            .iter()
            .find(|face| face.id == carriers[index].source_face_id)
        else {
            continue;
        };
        let mut local_uses = HashMap::<u64, usize>::default();
        for coedge in source_face
            .loops
            .iter()
            .flat_map(|loop_record| &loop_record.coedges)
        {
            *local_uses.entry(coedge.edge_id).or_default() += 1;
        }
        // A closed band trims to nothing but rims + face-local seams.
        let mut rims = Vec::new();
        for (loop_index, loop_record) in source_face.loops.iter().enumerate() {
            for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
                let Some(edge) = source_edge_by_id.get(&coedge.edge_id) else {
                    continue 'carrier;
                };
                if edge.degenerate {
                    continue;
                }
                match local_uses[&coedge.edge_id] {
                    2 => {}
                    1 if edge.start_vertex_id == edge.end_vertex_id => {
                        rims.push((loop_index, coedge_index, (*edge).clone()));
                    }
                    _ => continue 'carrier,
                }
            }
        }
        if rims.len() != 2 {
            continue;
        }
        let carrier_face = carriers[index].solid.shells[0].faces[0].clone();
        let surface = carrier_face.surface.clone();
        let [su0, su1] = surface.domain_u()?;
        let [sv0, sv1] = surface.domain_v()?;
        let v_mid = (sv0 + sv1) * 0.5;
        // The band must close in u (a periodic wall around the hole bore).
        if surface
            .evaluate(su0, v_mid)?
            .sub(surface.evaluate(su1, v_mid)?)
            .length()
            > weld_band
        {
            continue;
        }
        let mut rim_planes = Vec::new();
        for (loop_index, coedge_index, rim_edge) in &rims {
            let source_coedge = &source_face.loops[*loop_index].coedges[*coedge_index];
            // Full-period rim: its pcurve sweeps the whole u domain.
            let [p0, p1] = source_coedge.pcurve.domain()?;
            let mut u_low = f64::MAX;
            let mut u_high = f64::MIN;
            let mut v_mean = 0.0f64;
            for sample in 0..=32 {
                let uv = source_coedge
                    .pcurve
                    .evaluate(p0 + (p1 - p0) * sample as f64 / 32.0)?;
                u_low = u_low.min(uv.x);
                u_high = u_high.max(uv.x);
                v_mean += uv.y / 33.0;
            }
            let u_span = su1 - su0;
            if (u_low - su0).abs() > u_span * 1e-3 || (u_high - su1).abs() > u_span * 1e-3 {
                continue 'carrier;
            }
            // The rim must bound a PLANAR opening face as an INNER loop.
            let Some(opening) = source_faces.iter().find(|face| {
                opening_set.contains(&face.id)
                    && face
                        .loops
                        .iter()
                        .flat_map(|loop_record| &loop_record.coedges)
                        .any(|coedge| coedge.edge_id == rim_edge.id)
            }) else {
                continue 'carrier;
            };
            let Some((plane_point, plane_normal)) =
                planar_surface_frame(&opening.surface, weld_band)?
            else {
                continue 'carrier;
            };
            let mut rim_loop_area = None;
            let mut largest_other = 0.0f64;
            for loop_record in &opening.loops {
                let area = parameter_space_area(&FaceRecord {
                    id: 0,
                    surface: opening.surface.clone(),
                    same_sense: true,
                    loops: vec![loop_record.clone()],
                    name: None,
                })?
                .abs();
                if loop_record
                    .coedges
                    .iter()
                    .any(|coedge| coedge.edge_id == rim_edge.id)
                {
                    rim_loop_area = Some(area);
                } else {
                    largest_other = largest_other.max(area);
                }
            }
            let Some(rim_loop_area) = rim_loop_area else {
                continue 'carrier;
            };
            if rim_loop_area >= largest_other {
                continue 'carrier;
            }
            // The offset image of the rim must genuinely leave the plane
            // (the carrier mirrors the source loop/coedge structure 1:1).
            let image_coedge = &carrier_face.loops[*loop_index].coedges[*coedge_index];
            let Some(image_edge) = carriers[index]
                .solid
                .edges
                .iter()
                .find(|edge| edge.id == image_coedge.edge_id)
            else {
                continue 'carrier;
            };
            let mut off_plane = 0.0f64;
            for sample in 0..=32 {
                let point = image_edge.curve.evaluate(
                    image_edge.t0 + (image_edge.t1 - image_edge.t0) * sample as f64 / 32.0,
                )?;
                off_plane = off_plane.max(point.sub(plane_point).dot(plane_normal).abs());
            }
            if off_plane <= weld_band {
                continue 'carrier;
            }
            rim_planes.push((v_mean, plane_point, plane_normal));
        }
        // Pair each surface v-domain end with the opening plane of the rim
        // nearer to it, and require the extended isoline to clear that plane
        // on the far side (opposite the band interior).
        rim_planes.sort_by(|first, second| first.0.total_cmp(&second.0));
        let interior = surface.evaluate((su0 + su1) * 0.5, v_mid)?;
        for (v_end, (_, plane_point, plane_normal)) in [(sv0, rim_planes[0]), (sv1, rim_planes[1])]
        {
            let interior_sign = interior.sub(plane_point).dot(plane_normal).signum();
            let iso = surface.iso_curve_v(v_end)?;
            let [t0, t1] = iso.domain()?;
            for sample in 0..=32 {
                let point = iso.evaluate(t0 + (t1 - t0) * sample as f64 / 32.0)?;
                if point.sub(plane_point).dot(plane_normal) * interior_sign > -weld_band {
                    continue 'carrier;
                }
            }
        }
        // Rebuild the carrier as the full-domain band with exact isoline
        // rims — structurally the same face a freshly made cylinder/cone
        // side carries, which is the arrangement's best-tested input.
        let winding = parameter_space_area(&carrier_face)?;
        let bottom_rim = surface.iso_curve_v(sv0)?;
        let top_rim = surface.iso_curve_v(sv1)?;
        let seam = surface.iso_curve_u(su0)?;
        let [bottom_t0, bottom_t1] = bottom_rim.domain()?;
        let [top_t0, top_t1] = top_rim.domain()?;
        let corner_bottom = surface.evaluate(su0, sv0)?;
        let corner_top = surface.evaluate(su0, sv1)?;
        let flat = |u: f64, v: f64| Vec3::new(u, v, 0.0);
        let mut coedges = vec![
            CoedgeRecord {
                id: 1,
                edge_id: 1,
                forward: true,
                pcurve: crate::make_line(flat(su0, sv0), flat(su1, sv0))?,
            },
            CoedgeRecord {
                id: 2,
                edge_id: 3,
                forward: true,
                pcurve: crate::make_line(flat(su1, sv0), flat(su1, sv1))?,
            },
            CoedgeRecord {
                id: 3,
                edge_id: 2,
                forward: false,
                pcurve: crate::make_line(flat(su1, sv1), flat(su0, sv1))?,
            },
            CoedgeRecord {
                id: 4,
                edge_id: 3,
                forward: false,
                pcurve: crate::make_line(flat(su0, sv1), flat(su0, sv0))?,
            },
        ];
        if winding < 0.0 {
            coedges.reverse();
            for coedge in &mut coedges {
                coedge.forward = !coedge.forward;
                coedge.pcurve = coedge.pcurve.reversed()?;
            }
        }
        os_debug!(
            "carrier[{index}] src={} extended past opening planes: band v=({sv0:.4},{sv1:.4})",
            carriers[index].source_face_id,
        );
        carriers[index].solid = BrepSolid {
            id: carriers[index].solid.id,
            vertices: vec![
                VertexRecord {
                    id: 1,
                    point: corner_bottom,
                },
                VertexRecord {
                    id: 2,
                    point: corner_top,
                },
            ],
            edges: vec![
                EdgeRecord {
                    id: 1,
                    curve: bottom_rim,
                    t0: bottom_t0,
                    t1: bottom_t1,
                    start_vertex_id: 1,
                    end_vertex_id: 1,
                    degenerate: false,
                    name: None,
                },
                EdgeRecord {
                    id: 2,
                    curve: top_rim,
                    t0: top_t0,
                    t1: top_t1,
                    start_vertex_id: 2,
                    end_vertex_id: 2,
                    degenerate: false,
                    name: None,
                },
                EdgeRecord {
                    id: 3,
                    curve: seam,
                    t0: sv0,
                    t1: sv1,
                    start_vertex_id: 1,
                    end_vertex_id: 2,
                    degenerate: false,
                    name: None,
                },
            ],
            shells: vec![ShellRecord {
                id: 1,
                faces: vec![FaceRecord {
                    id: carrier_face.id,
                    surface,
                    same_sense: carrier_face.same_sense,
                    loops: vec![LoopRecord { id: 1, coedges }],
                    name: carrier_face.name.clone(),
                }],
            }],
            genus: 0,
        };
        extended.insert(index);
    }
    Ok(extended)
}

/// Fall-short curved carriers: the sibling disease to the oblique-bore lane
/// above, on the OTHER side of the opening. When a retained CURVED face meets
/// an opening face and its centre of curvature lies BEYOND the opening
/// surface, the offset image of the shared rim moves INTO the material —
/// radial offsetting scales the trim away from the plane. E.g. a sphere gouge
/// whose centre sits outside the box: cavity radius r offsets to r+d, and a
/// rim point p on the opening plane maps to c + (r+d)/r·(p−c), strictly on
/// the material side whenever c is beyond the plane. The trimmed carrier then
/// NEVER reaches the opening surface, the carrier × opening-wall SSI finds
/// nothing (correctly — the trimmed patches are disjoint), the offset skin
/// ends mid-air, and the honesty gate refuses the shell.
///
/// The cure is the oblique lane's cure: rebuild the qualifying carrier's trim
/// so the surface reaches THROUGH the opening plane and let the arrangement
/// cut it back with the exact plane × quadric section. Here the trim becomes
/// the surface's FULL domain (a gouge rim is a partial arc chain against the
/// opening's outer loop — there is no band structure to preserve); a pole at
/// a v-domain end collapses to a degenerate edge exactly like a freshly made
/// sphere face, the arrangement's best-tested input.
///
/// Qualification (narrow, so every landed lane keeps its path):
/// - Offset carrier, curved, not smooth-paired, not rebuilt by the oblique
///   lane above;
/// - the source face shares a non-degenerate edge with a PLANAR opening face;
/// - that rim's offset image falls ENTIRELY on the material side of the
///   opening plane (beyond the weld band) — an image that reaches or crosses
///   the plane is the arrangement's ordinary imprint case (it needs no help);
/// - the surface's full domain genuinely crosses the opening plane on the
///   outside — a surface that stops at the opening (cone base, frustum caps)
///   keeps its ruled-weld lane;
/// - the surface closes in u, so the full-domain face is seam-gluable.
pub(super) fn extend_fallshort_curved_carriers(
    carriers: &mut [Carrier],
    source: &BrepSolid,
    source_faces: &[&FaceRecord],
    opening_set: &HashSet<u64>,
    smooth_pairs: &HashSet<(usize, usize)>,
    already_extended: &HashSet<usize>,
    scale: f64,
    distance: f64,
) -> Result<usize, String> {
    let weld_band = 2e-3f64.max(scale * 5e-5);
    let source_edge_by_id = source
        .edges
        .iter()
        .map(|edge| (edge.id, edge))
        .collect::<HashMap<_, _>>();
    let mut extended = 0usize;
    'carrier: for index in 0..carriers.len() {
        if !matches!(carriers[index].kind, OffsetFaceRole::Offset)
            || already_extended.contains(&index)
        {
            continue;
        }
        if smooth_pairs
            .iter()
            .any(|(first, second)| *first == index || *second == index)
        {
            continue;
        }
        let Some(source_face) = source_faces
            .iter()
            .find(|face| face.id == carriers[index].source_face_id)
        else {
            continue;
        };
        // Affine carriers translate along their normal: the shared rim's
        // image stays on the opening surface by construction.
        if source_face.surface.is_affine()? {
            continue;
        }
        let carrier_face = carriers[index].solid.shells[0].faces[0].clone();
        let surface = carrier_face.surface.clone();
        let [su0, su1] = surface.domain_u()?;
        let [sv0, sv1] = surface.domain_v()?;
        let v_mid = (sv0 + sv1) * 0.5;
        // The full-domain rebuild needs a seam-gluable (u-closed) surface.
        if surface
            .evaluate(su0, v_mid)?
            .sub(surface.evaluate(su1, v_mid)?)
            .length()
            > weld_band
        {
            continue;
        }
        let mut qualifies = false;
        'rims: for (loop_index, loop_record) in source_face.loops.iter().enumerate() {
            for (coedge_index, coedge) in loop_record.coedges.iter().enumerate() {
                let Some(edge) = source_edge_by_id.get(&coedge.edge_id) else {
                    continue;
                };
                if edge.degenerate {
                    continue;
                }
                let Some(opening) = source_faces.iter().find(|face| {
                    opening_set.contains(&face.id)
                        && face
                            .loops
                            .iter()
                            .flat_map(|loop_record| &loop_record.coedges)
                            .any(|other| other.edge_id == coedge.edge_id)
                }) else {
                    continue;
                };
                let Some((plane_point, mut plane_normal)) =
                    planar_surface_frame(&opening.surface, weld_band)?
                else {
                    continue;
                };
                // Orient the plane normal OUTWARD (off the material) via the
                // opening face's own oriented normal. A revolved cap's
                // parameterization can be degenerate at some boundary uv
                // (partials vanish on the axis) — probe coedge midpoints
                // until one yields a normal; none at all disqualifies the rim
                // rather than failing the whole shell.
                let Some(outward) = opening
                    .loops
                    .iter()
                    .flat_map(|loop_record| &loop_record.coedges)
                    .find_map(|opening_coedge| {
                        let [p0, p1] = opening_coedge.pcurve.domain().ok()?;
                        let opening_uv =
                            opening_coedge.pcurve.evaluate((p0 + p1) * 0.5).ok()?;
                        face_normal(opening, opening_uv.x, opening_uv.y).ok()
                    })
                else {
                    continue;
                };
                if plane_normal.dot(outward) < 0.0 {
                    plane_normal = plane_normal.scale(-1.0);
                }
                // A CLOSED full rim on the opening's OUTER loop is the ruled
                // weld's territory (a dome/frustum lateral ending at its cap:
                // the exact band between the coaxial rims is the landed
                // closure). A closed rim qualifies here only as an INNER
                // (hole) loop — a pocket carved interior to the opening face.
                // Open arc chains (a gouge across the face's outer boundary)
                // always qualify: no band structure exists for them.
                if edge.start_vertex_id == edge.end_vertex_id {
                    let mut rim_loop_area = None;
                    let mut largest_other = 0.0f64;
                    for loop_record in &opening.loops {
                        let area = parameter_space_area(&FaceRecord {
                            id: 0,
                            surface: opening.surface.clone(),
                            same_sense: true,
                            loops: vec![loop_record.clone()],
                            name: None,
                        })?
                        .abs();
                        if loop_record
                            .coedges
                            .iter()
                            .any(|other| other.edge_id == coedge.edge_id)
                        {
                            rim_loop_area = Some(area);
                        } else {
                            largest_other = largest_other.max(area);
                        }
                    }
                    let Some(rim_loop_area) = rim_loop_area else {
                        continue;
                    };
                    if rim_loop_area >= largest_other {
                        continue;
                    }
                }
                // Fall-short: the rim's offset image sits strictly on the
                // material side (the carrier mirrors the source loop/coedge
                // structure 1:1 — a missing mirror means another lane already
                // reshaped this carrier).
                let Some(image_coedge) = carrier_face
                    .loops
                    .get(loop_index)
                    .and_then(|loop_record| loop_record.coedges.get(coedge_index))
                else {
                    continue 'carrier;
                };
                let Some(image_edge) = carriers[index]
                    .solid
                    .edges
                    .iter()
                    .find(|edge| edge.id == image_coedge.edge_id)
                else {
                    continue 'carrier;
                };
                let mut falls_short = true;
                for sample in 0..=16 {
                    let point = image_edge.curve.evaluate(
                        image_edge.t0 + (image_edge.t1 - image_edge.t0) * sample as f64 / 16.0,
                    )?;
                    if point.sub(plane_point).dot(plane_normal) > -weld_band {
                        falls_short = false;
                        break;
                    }
                }
                if !falls_short {
                    continue;
                }
                // The full domain must genuinely cross the opening plane —
                // otherwise extension cannot reach it either and the honest
                // refusal stands.
                let mut crosses = false;
                'grid: for iu in 0..=16 {
                    for iv in 0..=16 {
                        let point = surface.evaluate(
                            su0 + (su1 - su0) * iu as f64 / 16.0,
                            sv0 + (sv1 - sv0) * iv as f64 / 16.0,
                        )?;
                        if point.sub(plane_point).dot(plane_normal) > weld_band {
                            crosses = true;
                            break 'grid;
                        }
                    }
                }
                if crosses {
                    qualifies = true;
                    break 'rims;
                }
            }
        }
        if !qualifies {
            continue;
        }
        if rebuild_carrier_full_domain(
            &mut carriers[index],
            source_face,
            weld_band,
            distance,
            index,
            "a fall-short opening rim",
        )? {
            extended += 1;
        }
    }
    Ok(extended)
}

/// Rebuild an offset carrier as its surface's FULL-DOMAIN face: seam edge
/// used twice, v-domain ends as closed rims — or degenerate point edges when
/// the iso curve collapses (poles), matching a freshly made sphere face. Any
/// interior loops (holes) in the source trim disappear with the rebuild — the
/// surplus sheet is cut back by the imprint pairs + fragment classification.
/// Returns false (carrier untouched) when the surface is not u-closed.
fn rebuild_carrier_full_domain(
    carrier: &mut Carrier,
    source_face: &FaceRecord,
    weld_band: f64,
    distance: f64,
    index: usize,
    reason: &str,
) -> Result<bool, String> {
    let carrier_face = carrier.solid.shells[0].faces[0].clone();
    let mut surface = carrier_face.surface.clone();
    let [mut su0, mut su1] = surface.domain_u()?;
    let [mut sv0, mut sv1] = surface.domain_v()?;
    let v_mid = (sv0 + sv1) * 0.5;
    // The full-domain rebuild needs a seam-gluable (u-closed) surface.
    if surface
        .evaluate(su0, v_mid)?
        .sub(surface.evaluate(su1, v_mid)?)
        .length()
        > weld_band
    {
        return Ok(false);
    }
    // A SPHERE source gets its carrier rebuilt on the EXACT full offset
    // sphere. App-built sphere nets are v-clipped short of a pole, so
    // "full domain" of the fitted offset surface still misses a polar
    // cap; when the offset sphere pokes through the opening plane near
    // that pole (the missing-cap band is only a few degrees wide), the
    // rim arcs the shell needs run through the missing cap, the imprint
    // clips them away, and the loop on this carrier can never close.
    // The analytic rebuild also replaces the Greville fit's pole rows
    // (fit error grows unbounded at a degenerate row) with exact ones.
    if let Some(crate::AnalyticSurface::Sphere { frame, radius }) =
        crate::analytic_surface::recognize(&source_face.surface)
    {
        let mid = surface.evaluate((su0 + su1) * 0.5, (sv0 + sv1) * 0.5)?;
        let measured = mid.sub(frame.origin).length();
        let grown = radius + distance.abs();
        let shrunk = (radius - distance.abs()).abs();
        // The fitted carrier disambiguates cavity (grown) vs boss
        // (shrunk); the analytic radius itself stays exact.
        let target = if (measured - grown).abs() <= (measured - shrunk).abs() {
            grown
        } else {
            shrunk
        };
        if (measured - target).abs() <= weld_band.max(distance.abs() * 0.5) && target > weld_band {
            let full = crate::make_sphere_surface(frame.origin, target, frame.axis)?;
            let [fu0, fu1] = full.domain_u()?;
            let [fv0, fv1] = full.domain_v()?;
            let old_normal = surface.normal((su0 + su1) * 0.5, (sv0 + sv1) * 0.5)?;
            let radial = mid.sub(frame.origin).normalized()?;
            let sample = full.evaluate((fu0 + fu1) * 0.5, (fv0 + fv1) * 0.5)?;
            let new_normal = full.normal((fu0 + fu1) * 0.5, (fv0 + fv1) * 0.5)?;
            let new_radial = sample.sub(frame.origin).normalized()?;
            // The rebuilt net must agree with the fitted carrier on which
            // side the surface normal faces; a mismatch would silently
            // invert the face, so refuse the rebuild instead (the honest
            // refusal downstream is strictly better than a wrong solid).
            if (old_normal.dot(radial) > 0.0) == (new_normal.dot(new_radial) > 0.0) {
                os_debug!("carrier[{index}] rebuilt on the exact full offset sphere r={target:.6}");
                surface = full;
                (su0, su1, sv0, sv1) = (fu0, fu1, fv0, fv1);
            } else {
                os_debug!("carrier[{index}] sphere rebuild skipped: orientation mismatch");
            }
        } else {
            os_debug!(
                "carrier[{index}] sphere rebuild skipped: measured radius {measured:.6} \
                 matches neither grown nor shrunk offset of {radius:.6}"
            );
        }
    }
    let winding = parameter_space_area(&carrier_face)?;
    let pole_point = |iso: &crate::NurbsCurve| -> Result<Option<Vec3>, String> {
        let [t0, t1] = iso.domain()?;
        let anchor = iso.evaluate(t0)?;
        let mut deviation = 0.0f64;
        for sample in 1..=8 {
            let point = iso.evaluate(t0 + (t1 - t0) * sample as f64 / 8.0)?;
            deviation = deviation.max(point.sub(anchor).length());
        }
        os_debug!("  pole probe: max deviation {deviation:.6}");
        Ok((deviation <= weld_band).then_some(anchor))
    };
    let bottom_iso = surface.iso_curve_v(sv0)?;
    let top_iso = surface.iso_curve_v(sv1)?;
    let bottom_pole = pole_point(&bottom_iso)?;
    let top_pole = pole_point(&top_iso)?;
    let corner_bottom = surface.evaluate(su0, sv0)?;
    let corner_top = surface.evaluate(su0, sv1)?;
    let seam = surface.iso_curve_u(su0)?;
    let v_end_edge = |id: u64,
                      iso: crate::NurbsCurve,
                      pole: Option<Vec3>,
                      vertex: u64|
     -> Result<EdgeRecord, String> {
        Ok(match pole {
            Some(point) => EdgeRecord {
                id,
                curve: crate::make_line(point, point)?,
                t0: 0.0,
                t1: 1.0,
                start_vertex_id: vertex,
                end_vertex_id: vertex,
                degenerate: true,
                name: None,
            },
            None => {
                let [t0, t1] = iso.domain()?;
                EdgeRecord {
                    id,
                    curve: iso,
                    t0,
                    t1,
                    start_vertex_id: vertex,
                    end_vertex_id: vertex,
                    degenerate: false,
                    name: None,
                }
            }
        })
    };
    let flat = |u: f64, v: f64| Vec3::new(u, v, 0.0);
    let mut coedges = vec![
        CoedgeRecord {
            id: 1,
            edge_id: 1,
            forward: true,
            pcurve: crate::make_line(flat(su0, sv0), flat(su1, sv0))?,
        },
        CoedgeRecord {
            id: 2,
            edge_id: 3,
            forward: true,
            pcurve: crate::make_line(flat(su1, sv0), flat(su1, sv1))?,
        },
        CoedgeRecord {
            id: 3,
            edge_id: 2,
            forward: false,
            pcurve: crate::make_line(flat(su1, sv1), flat(su0, sv1))?,
        },
        CoedgeRecord {
            id: 4,
            edge_id: 3,
            forward: false,
            pcurve: crate::make_line(flat(su0, sv1), flat(su0, sv0))?,
        },
    ];
    if winding < 0.0 {
        coedges.reverse();
        for coedge in &mut coedges {
            coedge.forward = !coedge.forward;
            coedge.pcurve = coedge.pcurve.reversed()?;
        }
    }
    os_debug!(
        "carrier[{index}] src={} extended to full domain past {reason} \
         (poles: bottom={} top={})",
        carrier.source_face_id,
        bottom_pole.is_some(),
        top_pole.is_some(),
    );
    carrier.solid = BrepSolid {
        id: carrier.solid.id,
        vertices: vec![
            VertexRecord {
                id: 1,
                point: corner_bottom,
            },
            VertexRecord {
                id: 2,
                point: corner_top,
            },
        ],
        edges: vec![
            v_end_edge(1, bottom_iso, bottom_pole, 1)?,
            v_end_edge(2, top_iso, top_pole, 2)?,
            EdgeRecord {
                id: 3,
                curve: seam,
                t0: sv0,
                t1: sv1,
                start_vertex_id: 1,
                end_vertex_id: 2,
                degenerate: false,
                name: None,
            },
        ],
        shells: vec![ShellRecord {
            id: 1,
            faces: vec![FaceRecord {
                id: carrier_face.id,
                surface,
                same_sense: carrier_face.same_sense,
                loops: vec![LoopRecord { id: 1, coedges }],
                name: carrier_face.name.clone(),
            }],
        }],
        genus: 0,
    };
    Ok(true)
}

/// REFLEX-RIM lane: an offset carrier whose (curved, u-closed) source face
/// joins a RETAINED neighbour at a reflex edge cannot keep its source-sized
/// trim — the true offset∩offset junction lies PAST the cloned rim (miter
/// overshoot), and when the rim is an interior loop (a boss piercing the
/// face: cylinder through a cone) or a mid-surface arc, no amount of trim
/// stretching re-covers it (a hole excludes the junction band in uv
/// outright). Rebuild such carriers as full-domain faces: the imprint pairs
/// then carve the true junction into BOTH sheets as one shared cut and the
/// surplus is dropped by fragment classification. Runs on BOTH attempts (not
/// gated behind the extension retry): without it these shells close WRONGLY
/// (membrane caps over each rim copy), which is worse than any refusal.
pub(super) fn rebuild_reflex_rim_carriers(
    carriers: &mut [Carrier],
    source: &BrepSolid,
    source_faces: &[&FaceRecord],
    smooth_pairs: &HashSet<(usize, usize)>,
    scale: f64,
    distance: f64,
) -> Result<HashSet<usize>, String> {
    let weld_band = 2e-3f64.max(scale * 5e-5);
    let mut rebuilt = HashSet::default();
    for index in 0..carriers.len() {
        if !matches!(carriers[index].kind, OffsetFaceRole::Offset) {
            continue;
        }
        if smooth_pairs
            .iter()
            .any(|(first, second)| *first == index || *second == index)
        {
            continue;
        }
        let Some(source_face) = source_faces
            .iter()
            .find(|face| face.id == carriers[index].source_face_id)
        else {
            continue;
        };
        if source_face.surface.is_affine()? {
            continue;
        }
        if face_reflex_miter_tan(source, source_face)?.is_none() {
            continue;
        }
        if rebuild_carrier_full_domain(
            &mut carriers[index],
            source_face,
            weld_band,
            distance,
            index,
            "a reflex junction rim",
        )? {
            rebuilt.insert(index);
        }
    }
    Ok(rebuilt)
}

/// One sampled station of the junction between `face` and `mate` along
/// their shared edge: both faces' outward normals read at the SAME 3D
/// point, and `face`'s coedge-oriented tangent there.
pub(super) struct JunctionStation {
    pub normal: Vec3,
    pub mate_normal: Vec3,
    pub tangent: Vec3,
}

impl JunctionStation {
    /// Convex when the material dihedral is below π (a box's every edge),
    /// reflex above it (a pocket's internal corner). Sign convention
    /// verified on a box: all edges convex → cross·tangent > 0 with the
    /// coedge-oriented tangent.
    pub fn is_convex(&self) -> bool {
        self.normal.cross(self.mate_normal).dot(self.tangent) > 0.0
    }

    /// tan(θn/2), θn the angle between the two outward normals: the arc
    /// overshoot, per unit offset distance, at which the two faces' offsets
    /// meet past the source rim (1 for a perpendicular join, unbounded as
    /// the join becomes tangential).
    pub fn miter_tan(&self) -> f64 {
        let cos_normals = self.normal.dot(self.mate_normal).clamp(-1.0, 1.0);
        (cos_normals.acos() * 0.5).tan()
    }
}

/// Sample the sharp junction between `face` and `mate` along their shared
/// `edge` at five stations. Smooth stations — the same band
/// `uses_are_tangent` accepts for boundary synchronization — are left out:
/// a tangent join has no miter at all. The crossing angle varies along a
/// curved junction (a cylinder piercing a cone runs from steep to shallow
/// around the quartic rim), which is why callers keep the worst station.
pub(super) fn junction_stations(
    face: &FaceRecord,
    coedge: &CoedgeRecord,
    edge: &EdgeRecord,
    mate: &FaceRecord,
) -> Result<Vec<JunctionStation>, String> {
    let mut stations = Vec::new();
    for fraction in [0.1f64, 0.3, 0.5, 0.7, 0.9] {
        let t_sample = edge.t0 + (edge.t1 - edge.t0) * fraction;
        let step = ((edge.t1 - edge.t0) * 1e-3).max(1e-9);
        let before = edge.curve.evaluate(t_sample - step)?;
        let after = edge.curve.evaluate(t_sample + step)?;
        let mut tangent = after.sub(before);
        if tangent.length() <= 1e-12 {
            continue;
        }
        if !coedge.forward {
            tangent = tangent.scale(-1.0);
        }
        // Both normals are taken at the SAME 3D station, located on
        // each face by projection. Reading the two pcurves at equal
        // fractions assumed they share the edge's parameterization,
        // which a blend's end arc on a sphere does not: the normals
        // were then compared at different points of a TANGENT arc,
        // read as a sharp crossing, and the sign came out reflex for
        // two of a corner's three fillets — full-domain rebuilding
        // the corner sphere into a carrier nothing could trim.
        let station = edge.curve.evaluate(t_sample)?;
        let uv_this = {
            let projection = project_point_to_surface(&face.surface, station)?;
            Vec2 {
                x: projection.u,
                y: projection.v,
            }
        };
        let uv_mate = {
            let projection = project_point_to_surface(&mate.surface, station)?;
            Vec2 {
                x: projection.u,
                y: projection.v,
            }
        };
        let normal = face_normal(face, uv_this.x, uv_this.y)?;
        let mate_normal = face_normal(mate, uv_mate.x, uv_mate.y)?;
        let cross = normal.cross(mate_normal);
        if cross.length() <= 1e-6 || normal.dot(mate_normal) >= SMOOTH_JUNCTION_COS {
            continue;
        }
        stations.push(JunctionStation {
            normal,
            mate_normal,
            tangent,
        });
    }
    Ok(stations)
}

/// The face that shares `edge_id` with `face`, with its use of that edge.
pub(super) fn junction_mate<'a>(
    faces: &[&'a FaceRecord],
    face: &FaceRecord,
    edge_id: u64,
) -> Option<(&'a FaceRecord, &'a CoedgeRecord)> {
    faces.iter().find_map(|other| {
        if other.id == face.id {
            return None;
        }
        other
            .loops
            .iter()
            .flat_map(|loop_record| &loop_record.coedges)
            .find(|other_coedge| other_coedge.edge_id == edge_id)
            .map(|other_coedge| (*other, other_coedge))
    })
}

/// When `face` meets a neighbour at a REFLEX (concave) edge — the material
/// dihedral exceeds π (a pocket's internal corner: material wraps 270° around
/// the edge) — returns the WORST miter factor tan(θn/2) over samples along
/// its reflex edges, where θn is the angle between the two faces' outward
/// normals. At such an edge this face's offset skin must GROW past the source
/// footprint to reach the neighbour's offset: the offsets meet at arc
/// overshoot d·tan(θn/2) past the source rim (d for a perpendicular join,
/// unbounded as the join becomes tangential), so a flat d-sized extension
/// only covers joins at 90° or steeper. A smooth/tangent join (|n1×n2| ≈ 0)
/// is neither reflex nor convex. `None` = no reflex edge.
pub(super) fn face_reflex_miter_tan(source: &BrepSolid, face: &FaceRecord) -> Result<Option<f64>, String> {
    let edge_by_id = source
        .edges
        .iter()
        .map(|edge| (edge.id, edge))
        .collect::<HashMap<_, _>>();
    let faces = source
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .collect::<Vec<_>>();
    let mut worst: Option<f64> = None;
    for loop_record in &face.loops {
        for coedge in &loop_record.coedges {
            let Some(edge) = edge_by_id.get(&coedge.edge_id) else {
                continue;
            };
            if edge.degenerate {
                continue;
            }
            let Some((mate, _)) = junction_mate(&faces, face, coedge.edge_id) else {
                continue;
            };
            for station in junction_stations(face, coedge, edge, mate)? {
                if !station.is_convex() {
                    worst = Some(worst.unwrap_or(0.0).max(station.miter_tan()));
                }
            }
        }
    }
    Ok(worst)
}

/// The factor an OUTWARD pad of |d| grows by so a junction whose offsets
/// meet `worst_tan`·d past the source rim (the worst sampled tan(θn/2),
/// `None` when no such junction bounds the pad) lands strictly INSIDE the
/// padded trim: ×1.5 headroom, as the reflex lane's inward extension, and
/// the same ×12 cap (a near-tangential join would ask for an unbounded
/// trim). Joins at 90° or steeper keep the exact |d| pad — every
/// perpendicular lane (a box's grown corner, a bore through a face) closes
/// on the boundary-coincident cut that pad produces, and the 1e-6 band
/// keeps a numerically-perpendicular join on that lane.
pub(super) fn outward_miter_scale(worst_tan: Option<f64>) -> f64 {
    match worst_tan {
        Some(tan) if tan > 1.0 + 1e-6 => (tan * 1.5).min(12.0),
        _ => 1.0,
    }
}

/// OUTWARD (negative distance) per-side extension of a retained face's
/// carrier: `amount` (= |distance|) across every side of the trim's uv
/// bounding box, EXCEPT a side the face runs along SMOOTHLY into retained
/// neighbours. At a sharp convex junction the two outward offsets separate
/// and meet again past both source rims, so each trim must grow to reach
/// the other (a box's grown corner); across an opening the wall plane cuts
/// the surplus back. At a smooth junction (a plane into its fillet, a
/// fillet's end into the corner blend) the offsets stay joined edge-to-edge,
/// and boundary synchronization pairs the two carriers only when both images
/// of the shared edge coincide — a uniform pad slid the plane's tangent edge
/// 0.6 sideways, no pair was ever made, and the tangent SSI cut nothing.
///
/// A side is smooth when at least one coedge RUNS ALONG it (≥90% of its
/// samples on the side — an edge merely ending there does not count) and
/// every such coedge is a smooth junction with a retained face. Ruled
/// carriers only ever grow along their rulings, so for them this decides
/// the two v-ends; the u sides are read but unused.
///
/// `amount` only reaches the meeting line of a convex junction at 90° or
/// steeper: the two outward offsets meet d·tan(θn/2) past the rim, and a
/// frustum's ACUTE base (material dihedral 90° − α) needs d·tan(45° + α/2)
/// — the cone carrier padded by exactly d stopped 0.13 above the padded
/// base plane, the pair imprint was skipped on bounds, and the cone's
/// bottom rim dangled one-use (the user's 2026-09-07 outward document).
/// So a sharp side grows by `outward_miter_scale` of the worst CONVEX
/// miter among the coedges along it; a side no coedge runs along (a
/// circular outline crosses all four) takes the face-wide worst. Reflex
/// coedges contribute nothing: those offsets cross inside the trims.
pub(super) fn outward_carrier_extension(
    source: &BrepSolid,
    face: &FaceRecord,
    source_faces: &[&FaceRecord],
    opening_set: &HashSet<u64>,
    amount: f64,
) -> Result<crate::CarrierExtension, String> {
    let [u0, u1] = face.surface.domain_u()?;
    let [v0, v1] = face.surface.domain_v()?;
    let edge_by_id = source
        .edges
        .iter()
        .map(|edge| (edge.id, edge))
        .collect::<HashMap<_, _>>();
    let mut uses: Vec<(Vec<Vec2>, bool, Option<f64>)> = Vec::new();
    let mut low = Vec2 {
        x: f64::INFINITY,
        y: f64::INFINITY,
    };
    let mut high = Vec2 {
        x: f64::NEG_INFINITY,
        y: f64::NEG_INFINITY,
    };
    for coedge in face
        .loops
        .iter()
        .flat_map(|loop_record| &loop_record.coedges)
    {
        if edge_by_id
            .get(&coedge.edge_id)
            .is_some_and(|edge| edge.degenerate)
        {
            continue;
        }
        let [p0, p1] = coedge.pcurve.domain()?;
        let samples = (0..=24)
            .map(|sample| {
                coedge
                    .pcurve
                    .evaluate(p0 + (p1 - p0) * sample as f64 / 24.0)
                    .map(|uv| Vec2 { x: uv.x, y: uv.y })
            })
            .collect::<Result<Vec<_>, String>>()?;
        for uv in &samples {
            low.x = low.x.min(uv.x);
            low.y = low.y.min(uv.y);
            high.x = high.x.max(uv.x);
            high.y = high.y.max(uv.y);
        }
        let mate = junction_mate(source_faces, face, coedge.edge_id)
            .filter(|(mate, _)| !opening_set.contains(&mate.id));
        let (smooth, convex_tan) = match mate {
            Some((mate, mate_use)) => {
                let smooth = uses_are_tangent(face, coedge, mate, mate_use)?;
                let convex_tan = match edge_by_id.get(&coedge.edge_id) {
                    Some(edge) if !smooth => junction_stations(face, coedge, edge, mate)?
                        .iter()
                        .filter(|station| station.is_convex())
                        .map(JunctionStation::miter_tan)
                        .fold(None, |worst: Option<f64>, tan| {
                            Some(worst.unwrap_or(0.0).max(tan))
                        }),
                    _ => None,
                };
                (smooth, convex_tan)
            }
            None => (false, None),
        };
        uses.push((samples, smooth, convex_tan));
    }
    if uses.is_empty() || !low.x.is_finite() || !high.x.is_finite() {
        return Ok(crate::CarrierExtension::uniform(amount));
    }
    let worst_of = |first: Option<f64>, tan: Option<f64>| -> Option<f64> {
        match (first, tan) {
            (Some(a), Some(b)) => Some(a.max(b)),
            (a, b) => a.or(b),
        }
    };
    let face_worst = uses.iter().fold(None, |worst, (_, _, convex_tan)| {
        worst_of(worst, *convex_tan)
    });
    let side = |axis: fn(&Vec2) -> f64, value: f64, span: f64| -> f64 {
        let band = (span.abs() * 1e-5).max(1e-9);
        let mut along = 0usize;
        let mut smooth_along = 0usize;
        let mut worst_along: Option<f64> = None;
        for (samples, smooth, convex_tan) in &uses {
            let on = samples
                .iter()
                .filter(|uv| (axis(uv) - value).abs() <= band)
                .count();
            if on * 10 >= samples.len() * 9 {
                along += 1;
                if *smooth {
                    smooth_along += 1;
                }
                worst_along = worst_of(worst_along, *convex_tan);
            }
        }
        if along > 0 && along == smooth_along {
            return 0.0;
        }
        let worst = if along > 0 { worst_along } else { face_worst };
        amount * outward_miter_scale(worst)
    };
    Ok(crate::CarrierExtension {
        u_min: side(|uv| uv.x, low.x, u1 - u0),
        u_max: side(|uv| uv.x, high.x, u1 - u0),
        v_min: side(|uv| uv.y, low.y, v1 - v0),
        v_max: side(|uv| uv.y, high.y, v1 - v0),
    })
}

/// OUTWARD opening walls: how far the opening plane's uniform pad must
/// reach so the wall meets the offset of every retained neighbour where
/// that offset crosses the plane. The wall is the opening face's OWN plane
/// (not an offset), and a neighbour joined to it at material dihedral θ has
/// its outward offset cross the plane d/sin θ past the source rim — d for
/// a perpendicular join, d/cos α for a frustum narrowing toward the
/// opening: padded by exactly d the wall stopped 0.013 short of the offset
/// cone's section, the pair imprint cut nothing, and both the wall outline
/// and the cone carrier's top end dangled one-use (the user's 2026-09-07
/// outward document). Only CONVEX joins count — a reflex neighbour's
/// offset crosses the plane inside the opening's own footprint — and the
/// worst station goes through `outward_miter_scale`'s headroom and cap,
/// so perpendicular openings keep their exact d pad.
pub(super) fn outward_wall_pad(
    source: &BrepSolid,
    opening: &FaceRecord,
    source_faces: &[&FaceRecord],
    opening_set: &HashSet<u64>,
    amount: f64,
) -> Result<f64, String> {
    let edge_by_id = source
        .edges
        .iter()
        .map(|edge| (edge.id, edge))
        .collect::<HashMap<_, _>>();
    let mut worst: Option<f64> = None;
    for coedge in opening
        .loops
        .iter()
        .flat_map(|loop_record| &loop_record.coedges)
    {
        let Some(edge) = edge_by_id.get(&coedge.edge_id) else {
            continue;
        };
        if edge.degenerate {
            continue;
        }
        let Some((mate, _)) = junction_mate(source_faces, opening, coedge.edge_id)
            .filter(|(mate, _)| !opening_set.contains(&mate.id))
        else {
            continue;
        };
        for station in junction_stations(opening, coedge, edge, mate)? {
            if !station.is_convex() {
                continue;
            }
            let sin_dihedral = station.normal.cross(station.mate_normal).length();
            if sin_dihedral <= 1e-6 {
                continue;
            }
            worst = Some(worst.unwrap_or(0.0).max(1.0 / sin_dihedral));
        }
    }
    Ok(amount * outward_miter_scale(worst))
}

pub(super) fn source_by_id_lookup<'a>(
    source_faces: &[&'a FaceRecord],
    face_id: u64,
) -> Option<&'a FaceRecord> {
    source_faces.iter().find(|face| face.id == face_id).copied()
}

pub(super) fn sample_separation(first: &[Vec3], second: &[Vec3]) -> f64 {
    first
        .iter()
        .flat_map(|a| second.iter().map(move |b| a.sub(*b).length()))
        .fold(f64::INFINITY, f64::min)
}

pub(super) fn opening_wall_seeds(
    opening: &FaceRecord,
    carrier: &FaceRecord,
    source: &BrepSolid,
    opening_set: &HashSet<u64>,
    distance: f64,
) -> Result<Vec<Vec2>, String> {
    let source_faces = source
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .collect::<Vec<_>>();
    let mut seeds = Vec::new();
    for opening_use in opening
        .loops
        .iter()
        .flat_map(|loop_record| &loop_record.coedges)
    {
        let Some((neighbor, neighbor_use)) = source_faces.iter().find_map(|face| {
            if face.id == opening.id || opening_set.contains(&face.id) {
                return None;
            }
            face.loops
                .iter()
                .flat_map(|loop_record| &loop_record.coedges)
                .find(|coedge| coedge.edge_id == opening_use.edge_id)
                .map(|coedge| (*face, coedge))
        }) else {
            continue;
        };
        let [opening_start, opening_end] = opening_use.pcurve.domain()?;
        let opening_uv = opening_use
            .pcurve
            .evaluate((opening_start + opening_end) * 0.5)?;
        let original = opening.surface.evaluate(opening_uv.x, opening_uv.y)?;
        let [neighbor_start, neighbor_end] = neighbor_use.pcurve.domain()?;
        let neighbor_uv = neighbor_use
            .pcurve
            .evaluate((neighbor_start + neighbor_end) * 0.5)?;
        // The opening point stepped off along the NEIGHBOUR's offset direction:
        // the shared evaluator's normal, but anchored at a point on a different
        // face, so only the direction is borrowed.
        let expected = original.add(
            face_offsets(neighbor)
                .normal(neighbor_uv.x, neighbor_uv.y)?
                .scale(-distance),
        );
        let halfway = original.add(expected.sub(original).scale(0.5));
        let projection = project_point_to_surface(&carrier.surface, halfway)?;
        seeds.push(Vec2 {
            x: projection.u,
            y: projection.v,
        });
    }
    Ok(seeds)
}