brepkit-operations 3.2.13

CAD modeling operations (booleans, fillets, extrusions) for brepkit
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
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::print_stderr,
    deprecated
)]

use std::collections::{HashMap, HashSet};

use brepkit_math::nurbs::surface::NurbsSurface;
use brepkit_math::vec::Point3;
use brepkit_topology::Topology;
use brepkit_topology::edge::EdgeId;
use brepkit_topology::face::{FaceId, FaceSurface};
use brepkit_topology::solid::SolidId;
use brepkit_topology::test_utils::make_unit_cube_manifold;
use brepkit_topology::validation::validate_shell_manifold;

use crate::test_helpers::assert_euler_genus0;

use super::*;

fn solid_edge_ids(topo: &Topology, solid_id: SolidId) -> Vec<EdgeId> {
    let solid = topo.solid(solid_id).expect("test solid");
    let shell = topo.shell(solid.outer_shell()).expect("test shell");
    let mut seen = HashSet::new();
    let mut edges = Vec::new();
    for &fid in shell.faces() {
        let face = topo.face(fid).expect("test face");
        let wire = topo.wire(face.outer_wire()).expect("test wire");
        for oe in wire.edges() {
            if seen.insert(oe.edge().index()) {
                edges.push(oe.edge());
            }
        }
    }
    edges
}

#[test]
fn fillet_single_edge() {
    let mut topo = Topology::new();
    let cube = make_unit_cube_manifold(&mut topo);

    let edges = solid_edge_ids(&topo, cube);
    let target = edges[0];

    let result = fillet(&mut topo, cube, &[target], 0.1).expect("fillet should succeed");

    let s = topo.solid(result).expect("result solid");
    let sh = topo.shell(s.outer_shell()).expect("shell");

    // 6 original + 1 fillet = 7 faces
    assert_eq!(
        sh.faces().len(),
        7,
        "expected 7 faces after single-edge fillet"
    );
}

#[test]
fn fillet_single_edge_euler() {
    let mut topo = Topology::new();
    let cube = make_unit_cube_manifold(&mut topo);
    let edges = solid_edge_ids(&topo, cube);
    let result = fillet(&mut topo, cube, &[edges[0]], 0.1).expect("fillet should succeed");
    assert_euler_genus0(&topo, result);
}

#[test]
fn fillet_result_is_manifold() {
    let mut topo = Topology::new();
    let cube = make_unit_cube_manifold(&mut topo);

    let edges = solid_edge_ids(&topo, cube);
    let result = fillet(&mut topo, cube, &[edges[0]], 0.1).expect("fillet should succeed");

    let s = topo.solid(result).expect("result solid");
    let sh = topo.shell(s.outer_shell()).expect("shell");
    validate_shell_manifold(sh, &topo).expect("fillet result should be manifold");
}

#[test]
fn fillet_zero_radius_error() {
    let mut topo = Topology::new();
    let cube = make_unit_cube_manifold(&mut topo);
    let edges = solid_edge_ids(&topo, cube);
    assert!(fillet(&mut topo, cube, &[edges[0]], 0.0).is_err());
}

#[test]
fn fillet_negative_radius_error() {
    let mut topo = Topology::new();
    let cube = make_unit_cube_manifold(&mut topo);
    let edges = solid_edge_ids(&topo, cube);
    assert!(fillet(&mut topo, cube, &[edges[0]], -0.1).is_err());
}

#[test]
fn fillet_no_edges_error() {
    let mut topo = Topology::new();
    let cube = make_unit_cube_manifold(&mut topo);
    assert!(fillet(&mut topo, cube, &[], 0.1).is_err());
}

#[test]
fn radius_law_constant() {
    let law = FilletRadiusLaw::Constant(0.5);
    assert!((law.evaluate(0.0) - 0.5).abs() < 1e-10);
    assert!((law.evaluate(0.5) - 0.5).abs() < 1e-10);
    assert!((law.evaluate(1.0) - 0.5).abs() < 1e-10);
}

#[test]
fn radius_law_linear() {
    let law = FilletRadiusLaw::Linear {
        start: 0.1,
        end: 0.5,
    };
    assert!((law.evaluate(0.0) - 0.1).abs() < 1e-10);
    assert!((law.evaluate(0.5) - 0.3).abs() < 1e-10);
    assert!((law.evaluate(1.0) - 0.5).abs() < 1e-10);
}

#[test]
fn radius_law_scurve() {
    let law = FilletRadiusLaw::SCurve {
        start: 0.1,
        end: 0.5,
    };
    // S-curve should match endpoints
    assert!((law.evaluate(0.0) - 0.1).abs() < 1e-10);
    assert!((law.evaluate(1.0) - 0.5).abs() < 1e-10);
    // Midpoint should be between start and end
    let mid = law.evaluate(0.5);
    assert!(mid > 0.1 && mid < 0.5);
}

#[test]
fn fillet_variable_constant_law() {
    let mut topo = Topology::new();
    let cube = make_unit_cube_manifold(&mut topo);

    let edges = solid_edge_ids(&topo, cube);
    let laws = vec![(edges[0], FilletRadiusLaw::Constant(0.1))];

    let result = fillet_variable(&mut topo, cube, &laws).expect("variable fillet should work");

    let s = topo.solid(result).expect("result solid");
    let sh = topo.shell(s.outer_shell()).expect("shell");
    assert_eq!(sh.faces().len(), 7, "should have 7 faces after fillet");
}

#[test]
fn fillet_variable_linear_law() {
    let mut topo = Topology::new();
    let cube = make_unit_cube_manifold(&mut topo);

    let edges = solid_edge_ids(&topo, cube);
    let laws = vec![(
        edges[0],
        FilletRadiusLaw::Linear {
            start: 0.05,
            end: 0.15,
        },
    )];

    let result = fillet_variable(&mut topo, cube, &laws).expect("variable fillet should work");

    let vol = crate::measure::solid_volume(&topo, result, 0.1).unwrap();
    assert!(vol > 0.5, "filleted cube should have volume, got {vol}");
}

#[test]
fn fillet_variable_removes_material_linear_law() {
    let mut topo = Topology::new();
    let solid = crate::primitives::make_box(&mut topo, 10.0, 10.0, 10.0).unwrap();
    let edges = solid_edge_ids(&topo, solid);
    let laws = vec![(
        edges[0],
        FilletRadiusLaw::Linear {
            start: 0.5,
            end: 1.5,
        },
    )];
    let result = fillet_variable(&mut topo, solid, &laws).expect("variable fillet");
    let vol = crate::measure::solid_volume(&topo, result, 0.05).unwrap();
    assert!(vol < 1000.0, "fillet must remove material, got {vol}");
    assert!(
        vol > 900.0,
        "single-edge fillet removes only a sliver, got {vol}"
    );

    let s = topo.solid(result).expect("result solid");
    let sh = topo.shell(s.outer_shell()).expect("shell");
    validate_shell_manifold(sh, &topo).expect("variable fillet result should be manifold");
    assert_euler_genus0(&topo, result);
}

#[test]
fn fillet_has_positive_volume() {
    let mut topo = Topology::new();
    let cube = make_unit_cube_manifold(&mut topo);

    let edges = solid_edge_ids(&topo, cube);
    let result = fillet(&mut topo, cube, &[edges[0]], 0.1).expect("fillet should succeed");

    let vol = crate::measure::solid_volume(&topo, result, 0.1).unwrap();
    assert!(
        vol > 0.5,
        "filleted cube should have significant volume, got {vol}"
    );
}

#[test]
fn rolling_ball_fillet_single_edge() {
    let mut topo = Topology::new();
    let cube = make_unit_cube_manifold(&mut topo);

    let edges = solid_edge_ids(&topo, cube);
    let result = fillet_rolling_ball(&mut topo, cube, &[edges[0]], 0.1)
        .expect("rolling-ball fillet should succeed");

    let s = topo.solid(result).expect("result solid");
    let sh = topo.shell(s.outer_shell()).expect("shell");

    // 6 original faces + 1 NURBS fillet = 7 faces
    assert_eq!(
        sh.faces().len(),
        7,
        "expected 7 faces after single-edge rolling-ball fillet"
    );

    // Rolling-ball fillet on a box should still be genus-0 (χ=2).
    assert_euler_genus0(&topo, result);
}

#[test]
fn rolling_ball_rejects_closed_rim_so_dispatcher_falls_through() {
    // The degeneracy guard's whole purpose: a cylinder's closed circular rim
    // collapses its blend strip to zero area, and `try_fillet` relies on the
    // error to fall through to the walking engine. The guard clears healthy
    // faces via a cheap boundary-polygon area, so this pins that the shortcut
    // cannot accept a collapsed face and silently ship the corrupt solid.
    let mut topo = Topology::new();
    let cyl = crate::primitives::make_cylinder(&mut topo, 10.0, 20.0).expect("cylinder");
    let edges = solid_edge_ids(&topo, cyl);

    let err = fillet_rolling_ball(&mut topo, cyl, &edges, 0.5)
        .expect_err("rolling-ball must reject a closed circular rim");
    let reason = match &err {
        crate::OperationsError::InvalidInput { reason } => reason,
        other => unreachable!("expected InvalidInput from the degeneracy guard, got: {other:?}"),
    };
    assert!(
        reason.contains("degenerate face"),
        "expected the degeneracy guard to fire, got: {reason}"
    );
}

#[test]
fn rolling_ball_straight_edge_wall_is_exact_cylinder() {
    let mut topo = Topology::new();
    let cube = make_unit_cube_manifold(&mut topo);

    let edges = solid_edge_ids(&topo, cube);
    let result = fillet_rolling_ball(&mut topo, cube, &[edges[0]], 0.1)
        .expect("rolling-ball fillet should succeed");

    let s = topo.solid(result).expect("result solid");
    let sh = topo.shell(s.outer_shell()).expect("shell");

    // A straight edge between two planar faces rolls an EXACT quarter-cylinder,
    // so the blend wall must be a Cylinder, not a NURBS approximation of one.
    // Degrading it to NURBS costs downstream booleans their analytic path and
    // makes the wall tessellate far denser than its curvature warrants.
    let walls: Vec<_> = sh
        .faces()
        .iter()
        .filter(|&&fid| !topo.face(fid).expect("face").surface().is_planar())
        .collect();
    assert_eq!(walls.len(), 1, "one blend wall expected");
    let surface = topo.face(*walls[0]).expect("face").surface();
    assert!(
        matches!(surface, FaceSurface::Cylinder(cyl) if (cyl.radius() - 0.1).abs() < 1e-9),
        "straight-edge blend wall must be an exact r=0.1 Cylinder, got {:?}",
        surface.type_tag()
    );
}

#[test]
fn rolling_ball_fillet_surface_is_circular_arc() {
    let mut topo = Topology::new();
    let cube = make_unit_cube_manifold(&mut topo);

    let edges = solid_edge_ids(&topo, cube);
    let result = fillet_rolling_ball(&mut topo, cube, &[edges[0]], 0.2)
        .expect("rolling-ball fillet should succeed");

    let s = topo.solid(result).expect("result solid");
    let sh = topo.shell(s.outer_shell()).expect("shell");

    // Find the NURBS fillet face and verify it's a proper circular arc.
    for &fid in sh.faces() {
        let face = topo.face(fid).expect("face");
        if let FaceSurface::Nurbs(surface) = face.surface() {
            // The surface should be degree (2, 1) — circular arc × linear.
            assert_eq!(
                surface.degree_u(),
                2,
                "u (arc) direction should be degree 2"
            );
            assert_eq!(
                surface.degree_v(),
                1,
                "v (extrusion) direction should be degree 1"
            );

            // Evaluate at the midpoint (u=0.5, v=0.5) and check that
            // the point is at distance R from both adjacent faces.
            let mid_pt = surface.evaluate(0.5, 0.5);

            // For a unit cube, the fillet point should be inside the cube
            // (all coordinates between -0.1 and 1.1 for radius 0.2).
            assert!(
                mid_pt.x() > -0.5 && mid_pt.x() < 1.5,
                "fillet midpoint x should be near cube: {mid_pt:?}"
            );
        }
    }
}

#[test]
fn rolling_ball_fillet_positive_volume() {
    let mut topo = Topology::new();
    let cube = make_unit_cube_manifold(&mut topo);

    let edges = solid_edge_ids(&topo, cube);
    let result =
        fillet_rolling_ball(&mut topo, cube, &[edges[0]], 0.1).expect("fillet should succeed");

    let vol = crate::measure::solid_volume(&topo, result, 0.1).unwrap();
    assert!(
        vol > 0.5,
        "filleted cube should have significant volume, got {vol}"
    );
}

#[test]
fn rolling_ball_fillet_multiple_edges() {
    let mut topo = Topology::new();
    let cube = make_unit_cube_manifold(&mut topo);

    let edges = solid_edge_ids(&topo, cube);
    // edges[0] and edges[1] share a corner vertex.
    let result = fillet_rolling_ball(&mut topo, cube, &[edges[0], edges[1]], 0.1)
        .expect("multi-edge rolling-ball fillet should succeed");

    let s = topo.solid(result).expect("result solid");
    let sh = topo.shell(s.outer_shell()).expect("shell");

    // 6 trimmed planar + 2 NURBS fillet strips + 1 corner patch (the two
    // edges share a corner) = 9 faces.
    assert_eq!(
        sh.faces().len(),
        9,
        "expected 9 faces after two-edge shared-corner rolling-ball fillet"
    );
    validate_shell_manifold(sh, &topo).expect("two-edge fillet should be manifold");
}

/// Regression for #841: filleting two edges that share a corner vertex in a
/// single rolling-ball pass must produce a watertight (closed, euler-2) solid.
/// Previously the corner gap was left open (4 free edges, euler=1) because the
/// strips were set back but no corner patch closed the junction and the side
/// faces collapsed the unfilleted edge onto the far corner.
#[test]
fn rolling_ball_two_edges_shared_corner_watertight() {
    // Collect every pair of box edges that share a vertex, then fillet a sample.
    let mut topo = Topology::new();
    let cube = crate::primitives::make_box(&mut topo, 10.0, 10.0, 10.0).unwrap();
    let all_edges = solid_edge_ids(&topo, cube);

    // Find pairs of edges that share a vertex (a corner).
    let mut shared_pairs: Vec<(usize, usize)> = Vec::new();
    for i in 0..all_edges.len() {
        for j in (i + 1)..all_edges.len() {
            let ei = topo.edge(all_edges[i]).unwrap();
            let ej = topo.edge(all_edges[j]).unwrap();
            let shares = ei.start() == ej.start()
                || ei.start() == ej.end()
                || ei.end() == ej.start()
                || ei.end() == ej.end();
            if shares {
                shared_pairs.push((i, j));
            }
        }
    }
    assert!(
        !shared_pairs.is_empty(),
        "box should have corner-sharing edge pairs"
    );

    // Verify the first several corner-sharing pairs (iteration order); capped to
    // keep the test fast while still exercising multiple corners.
    for &(i, j) in shared_pairs.iter().take(6) {
        let mut t = Topology::new();
        let box_id = crate::primitives::make_box(&mut t, 10.0, 10.0, 10.0).unwrap();
        let edges = solid_edge_ids(&t, box_id);
        let result = fillet_rolling_ball(&mut t, box_id, &[edges[i], edges[j]], 1.0)
            .expect("fillet of shared-corner edges should succeed");

        let s = t.solid(result).expect("result solid");
        let sh = t.shell(s.outer_shell()).expect("shell");
        assert!(
            brepkit_topology::validation::validate_shell_closed(sh, &t).is_ok(),
            "shared-corner pair {i},{j} should be watertight"
        );
        assert!(
            validate_shell_manifold(sh, &t).is_ok(),
            "shared-corner pair {i},{j} should be manifold"
        );
        assert_euler_genus0(&t, result);

        let vol = crate::measure::solid_volume(&t, result, 0.01).unwrap();
        assert!(
            (985.0..1000.0).contains(&vol),
            "shared-corner pair {i},{j}: volume {vol} outside sane range"
        );
    }
}

/// A box edge pair that does NOT share a corner must remain watertight too
/// (the corner patch must not fire spuriously).
#[test]
fn rolling_ball_two_edges_no_shared_corner_watertight() {
    let mut topo = Topology::new();
    let cube = crate::primitives::make_box(&mut topo, 10.0, 10.0, 10.0).unwrap();
    let edges = solid_edge_ids(&topo, cube);

    // Find a pair with no shared vertex.
    let mut pair = None;
    'outer: for i in 0..edges.len() {
        for j in (i + 1)..edges.len() {
            let ei = topo.edge(edges[i]).unwrap();
            let ej = topo.edge(edges[j]).unwrap();
            let shares = ei.start() == ej.start()
                || ei.start() == ej.end()
                || ei.end() == ej.start()
                || ei.end() == ej.end();
            if !shares {
                pair = Some((i, j));
                break 'outer;
            }
        }
    }
    let (i, j) = pair.expect("box should have a non-corner-sharing edge pair");

    let result = fillet_rolling_ball(&mut topo, cube, &[edges[i], edges[j]], 1.0)
        .expect("non-shared-corner fillet should succeed");
    let s = topo.solid(result).expect("result solid");
    let sh = topo.shell(s.outer_shell()).expect("shell");
    // 6 trimmed planar + 2 fillet strips = 8 faces, no corner patch.
    assert_eq!(sh.faces().len(), 8, "non-shared pair should add no patch");
    brepkit_topology::validation::validate_shell_closed(sh, &topo)
        .expect("non-shared-corner fillet should be watertight");
    assert_euler_genus0(&topo, result);
}

#[test]
fn rolling_ball_fillet_error_cases() {
    let mut topo = Topology::new();
    let cube = make_unit_cube_manifold(&mut topo);
    let edges = solid_edge_ids(&topo, cube);

    assert!(fillet_rolling_ball(&mut topo, cube, &[edges[0]], 0.0).is_err());
    assert!(fillet_rolling_ball(&mut topo, cube, &[edges[0]], -0.1).is_err());
    assert!(fillet_rolling_ball(&mut topo, cube, &[], 0.1).is_err());
}

#[test]
fn vertex_blend_all_edges_box() {
    // Fillet all 12 edges of a unit cube → 8 vertex blend patches should
    // close the corners, giving a watertight mesh.
    let mut topo = Topology::new();
    let cube = make_unit_cube_manifold(&mut topo);
    let edges = solid_edge_ids(&topo, cube);
    assert_eq!(edges.len(), 12, "unit cube should have 12 edges");

    let result =
        fillet_rolling_ball(&mut topo, cube, &edges, 0.1).expect("all-edges fillet should succeed");

    let s = topo.solid(result).expect("result solid");
    let sh = topo.shell(s.outer_shell()).expect("shell");

    // 6 trimmed planar faces + 12 NURBS fillet strips + 8 vertex blend triangles = 26
    assert_eq!(
        sh.faces().len(),
        26,
        "expected 26 faces (6 planar + 12 fillet + 8 blend)"
    );
}

#[test]
fn vertex_blend_all_edges_box_volume() {
    // Fillet all 12 edges of a 10×10×10 box at r=1.0. The result must be a
    // closed, manifold, genus-0 solid (26 faces) whose volume reflects only
    // the fillet-arc and corner-blend material removal — not gross corner
    // excision. Analytic expectation ≈ 975.6:
    //   1000 − 12·(1−π/4)·1²·8 (edge slivers ≈ 20.6)
    //        − 8·(1−π/6)·1³    (corner blends ≈ 3.8).
    let mut topo = Topology::new();
    let cube = crate::primitives::make_box(&mut topo, 10.0, 10.0, 10.0).unwrap();
    let edges = solid_edge_ids(&topo, cube);
    assert_eq!(edges.len(), 12, "box should have 12 edges");

    let result =
        fillet_rolling_ball(&mut topo, cube, &edges, 1.0).expect("all-edges fillet should succeed");

    let s = topo.solid(result).expect("result solid");
    let sh = topo.shell(s.outer_shell()).expect("shell");
    validate_shell_manifold(sh, &topo).expect("filleted box should be manifold");
    assert_euler_genus0(&topo, result);

    assert_eq!(
        sh.faces().len(),
        26,
        "expected 26 faces (6 planar + 12 fillet + 8 blend)"
    );

    let vol = crate::measure::solid_volume(&topo, result, 0.01).unwrap();
    assert!(
        vol > 974.0 && vol < 978.0,
        "filleted box volume should be ≈975.6 (in 974..978), got {vol}"
    );
}

#[test]
fn vertex_blend_tessellates_successfully() {
    // Verify the fully-filleted box can be tessellated without error.
    // Watertight stitching at NURBS-to-planar seams is a tessellation-level
    // concern tracked separately.
    let mut topo = Topology::new();
    let cube = make_unit_cube_manifold(&mut topo);
    let edges = solid_edge_ids(&topo, cube);

    let result =
        fillet_rolling_ball(&mut topo, cube, &edges, 0.1).expect("all-edges fillet should succeed");

    let mesh = crate::tessellate::tessellate_solid(&topo, result, 0.05).unwrap();
    // Should produce a non-trivial mesh.
    assert!(mesh.positions.len() > 20, "should have many vertices");
    assert!(mesh.indices.len() > 60, "should have many triangles");
}

#[test]
fn vertex_blend_positive_volume() {
    let mut topo = Topology::new();
    let cube = make_unit_cube_manifold(&mut topo);
    let edges = solid_edge_ids(&topo, cube);

    let result =
        fillet_rolling_ball(&mut topo, cube, &edges, 0.1).expect("all-edges fillet should succeed");

    let vol = crate::measure::solid_volume(&topo, result, 0.005).unwrap();
    // Analytic rounded-cube volume for s=1, r=0.1 (Minkowski sum of the inner
    // (s−2r)³ box with a ball of radius r):
    //   (0.8)³ + 6·(0.8)²·0.1 + 12·0.8·(π/4)·0.1² + (4/3)π·0.1³ ≈ 0.9756.
    assert!(
        vol > 0.970 && vol < 0.980,
        "filleted unit-cube volume should be ≈0.9756 (in 0.970..0.980), got {vol}"
    );
}

#[test]
fn vertex_blend_box_primitive() {
    // Test with make_box (2×3×4) to verify non-unit dimensions work.
    let mut topo = Topology::new();
    let solid = crate::primitives::make_box(&mut topo, 2.0, 3.0, 4.0).unwrap();
    let edges = solid_edge_ids(&topo, solid);
    assert_eq!(edges.len(), 12);

    let result = fillet_rolling_ball(&mut topo, solid, &edges, 0.2)
        .expect("box primitive all-edges fillet should succeed");

    let s = topo.solid(result).expect("result solid");
    let sh = topo.shell(s.outer_shell()).expect("shell");
    assert_eq!(sh.faces().len(), 26);
}

#[test]
fn vertex_blend_three_edges_at_corner() {
    // Fillet just the 3 edges meeting at one corner vertex to test minimal
    // vertex blend (produces one blend triangle).
    let mut topo = Topology::new();
    let cube = make_unit_cube_manifold(&mut topo);
    let all_edges = solid_edge_ids(&topo, cube);

    // Find 3 edges sharing a common vertex.
    let mut vertex_to_edges: HashMap<usize, Vec<EdgeId>> = HashMap::new();
    for &eid in &all_edges {
        let e = topo.edge(eid).unwrap();
        vertex_to_edges
            .entry(e.start().index())
            .or_default()
            .push(eid);
        vertex_to_edges
            .entry(e.end().index())
            .or_default()
            .push(eid);
    }

    let (&_vi, corner_edges) = vertex_to_edges
        .iter()
        .find(|(_, edges)| edges.len() >= 3)
        .expect("box should have vertices with 3 edges");

    let targets: Vec<EdgeId> = corner_edges.iter().take(3).copied().collect();

    let result = fillet_rolling_ball(&mut topo, cube, &targets, 0.1)
        .expect("3-edge corner fillet should succeed");

    let s = topo.solid(result).expect("result solid");
    let sh = topo.shell(s.outer_shell()).expect("shell");

    // 6 original faces + 3 NURBS fillets + at least 1 vertex blend triangle
    assert!(
        sh.faces().len() >= 10,
        "expected at least 10 faces (6 + 3 + 1 blend), got {}",
        sh.faces().len()
    );
}

#[test]
fn vertex_blend_is_curved_not_flat() {
    // Fillet all 12 edges of a unit cube. Verify that vertex blend
    // NURBS patches approximate a spherical cap on the correct
    // fillet sphere: center at (corner - R*(1,1,1)/|...|), radius R.
    let r = 0.1_f64;
    let mut topo = Topology::new();
    let cube = make_unit_cube_manifold(&mut topo);
    let edges = solid_edge_ids(&topo, cube);

    let result =
        fillet_rolling_ball(&mut topo, cube, &edges, r).expect("all-edges fillet should succeed");

    let solid = topo.solid(result).unwrap();
    let shell = topo.shell(solid.outer_shell()).unwrap();

    // For each blend face, check that interior surface points lie
    // approximately on a sphere of radius R centered inside the solid.
    let mut blend_face_count = 0;
    let mut max_sphere_err = 0.0_f64;

    for &fid in shell.faces() {
        let face = topo.face(fid).unwrap();
        if !matches!(face.surface(), FaceSurface::Nurbs(_)) {
            continue;
        }
        let wire = topo.wire(face.outer_wire()).unwrap();
        let wire_verts: Vec<Point3> = wire
            .edges()
            .iter()
            .map(|oe| {
                let v = topo.vertex(topo.edge(oe.edge()).unwrap().start()).unwrap();
                v.point()
            })
            .collect();
        if wire_verts.len() != 3 {
            continue;
        }
        blend_face_count += 1;

        // The sphere center is at the original cube corner offset
        // inward by R along each face normal. For a 90° corner with
        // axis-aligned face normals, this is corner ± R on each axis.
        // Find the nearest cube corner by rounding each boundary vertex
        // coordinate to 0 or 1.
        let avg = Point3::new(
            (wire_verts[0].x() + wire_verts[1].x() + wire_verts[2].x()) / 3.0,
            (wire_verts[0].y() + wire_verts[1].y() + wire_verts[2].y()) / 3.0,
            (wire_verts[0].z() + wire_verts[1].z() + wire_verts[2].z()) / 3.0,
        );
        let corner = Point3::new(
            if avg.x() > 0.5 { 1.0 } else { 0.0 },
            if avg.y() > 0.5 { 1.0 } else { 0.0 },
            if avg.z() > 0.5 { 1.0 } else { 0.0 },
        );
        let sphere_center = Point3::new(
            corner.x() + if corner.x() > 0.5 { -r } else { r },
            corner.y() + if corner.y() > 0.5 { -r } else { r },
            corner.z() + if corner.z() > 0.5 { -r } else { r },
        );

        // The boundary points are at distance √2·R from the sphere center
        // (they're on face planes, not on the fillet sphere itself).
        // The rational Bézier patch should lie on a sphere of that radius.
        let r_blend = (wire_verts[0] - sphere_center).length();

        // Evaluate interior points and check distance from sphere.
        if let FaceSurface::Nurbs(srf) = face.surface() {
            for u in [0.25, 0.5, 0.75] {
                for v in [0.25, 0.5, 0.75] {
                    let pt = srf.evaluate(u, v);
                    let dist = (pt - sphere_center).length();
                    let err = (dist - r_blend).abs();
                    max_sphere_err = max_sphere_err.max(err);
                }
            }
        }
    }

    assert!(
        blend_face_count >= 8,
        "expected 8 vertex blend faces, found {blend_face_count}"
    );
    // A degree (2,2) rational patch can't exactly represent a sphere —
    // the triangular degenerate topology introduces approximation error.
    // Allow up to 6% of the fillet radius (increased from 5% after fillet
    // contact direction fix which slightly shifts vertex blend sampling).
    assert!(
        max_sphere_err < r * 0.06,
        "blend surface deviates from sphere by {max_sphere_err:.6} (limit {:.6})",
        r * 0.06,
    );
}

#[test]
fn vertex_blend_sphere_center_inside_solid() {
    // Verify the blend surface midpoints are close to the solid
    // boundary. The (2,2) rational patch is an approximation of the
    // spherical cap, so allow up to R/2 overshoot past face planes.
    let r = 0.1_f64;
    let margin = r;
    let mut topo = Topology::new();
    let cube = make_unit_cube_manifold(&mut topo);
    let edges = solid_edge_ids(&topo, cube);

    let result =
        fillet_rolling_ball(&mut topo, cube, &edges, r).expect("all-edges fillet should succeed");

    let solid = topo.solid(result).unwrap();
    let shell = topo.shell(solid.outer_shell()).unwrap();

    for &fid in shell.faces() {
        let face = topo.face(fid).unwrap();
        if let FaceSurface::Nurbs(srf) = face.surface() {
            let wire = topo.wire(face.outer_wire()).unwrap();
            if wire.edges().len() != 3 {
                continue;
            }

            // Sample interior surface points — they should be
            // within the unit cube bounds (with some tolerance for
            // the quadratic patch approximation error).
            for u in [0.25, 0.5, 0.75] {
                for v in [0.25, 0.5] {
                    let pt = srf.evaluate(u, v);
                    assert!(
                        pt.x() > -margin
                            && pt.x() < 1.0 + margin
                            && pt.y() > -margin
                            && pt.y() < 1.0 + margin
                            && pt.z() > -margin
                            && pt.z() < 1.0 + margin,
                        "blend point ({:.4},{:.4},{:.4}) too far outside unit cube",
                        pt.x(),
                        pt.y(),
                        pt.z(),
                    );
                }
            }
        }
    }
}

/// Fillet on a boolean result: fuse(box, cylinder) → fillet should work
/// on edges shared between two planar faces.
#[test]
fn fillet_on_boolean_result() {
    let mut topo = Topology::new();
    let base = crate::primitives::make_box(&mut topo, 80.0, 60.0, 10.0).unwrap();
    let boss = crate::primitives::make_cylinder(&mut topo, 15.0, 30.0).unwrap();
    let mat = brepkit_math::mat::Mat4::translation(40.0, 30.0, 10.0);
    crate::transform::transform_solid(&mut topo, boss, &mat).unwrap();

    let fused =
        crate::boolean::boolean(&mut topo, crate::boolean::BooleanOp::Fuse, base, boss).unwrap();

    let solid = topo.solid(fused).unwrap();
    let shell = topo.shell(solid.outer_shell()).unwrap();

    // Build edge-to-face map from all wires (outer + inner).
    let mut edge_to_face_ids: HashMap<usize, Vec<FaceId>> = HashMap::new();
    for &fid in shell.faces() {
        let face = topo.face(fid).unwrap();
        let wire = topo.wire(face.outer_wire()).unwrap();
        for oe in wire.edges() {
            edge_to_face_ids
                .entry(oe.edge().index())
                .or_default()
                .push(fid);
        }
        for &iwid in face.inner_wires() {
            let iw = topo.wire(iwid).unwrap();
            for oe in iw.edges() {
                edge_to_face_ids
                    .entry(oe.edge().index())
                    .or_default()
                    .push(fid);
            }
        }
    }

    // Allow a small number of seam edges from cylindrical band discretization.
    let bad_count = edge_to_face_ids.values().filter(|f| f.len() != 2).count();
    assert!(
        bad_count <= 4,
        "too many non-manifold edges: {bad_count} (expected <= 4 seam edges)",
    );

    // Fillet only manifold edges where BOTH adjacent faces are planar.
    let is_planar = |fid: FaceId| -> bool {
        matches!(topo.face(fid).unwrap().surface(), FaceSurface::Plane { .. })
    };
    let mut planar_edges = Vec::new();
    for (&eidx, face_ids) in &edge_to_face_ids {
        if face_ids.len() == 2 && is_planar(face_ids[0]) && is_planar(face_ids[1]) {
            let face = topo.face(face_ids[0]).unwrap();
            let wire = topo.wire(face.outer_wire()).unwrap();
            for oe in wire.edges() {
                if oe.edge().index() == eidx {
                    planar_edges.push(oe.edge());
                    break;
                }
            }
        }
    }
    planar_edges.sort_unstable_by_key(|e| e.index());
    planar_edges.dedup_by_key(|e| e.index());

    assert!(
        !planar_edges.is_empty(),
        "should have planar-planar edges to fillet"
    );
    let result = fillet(&mut topo, fused, &planar_edges, 1.0);
    assert!(
        result.is_ok(),
        "fillet on planar edges of boolean result should succeed: {:?}",
        result.err()
    );
}

#[test]
fn fillet_radius_too_large_rejected() {
    let mut topo = Topology::new();
    let solid = crate::primitives::make_box(&mut topo, 2.0, 2.0, 2.0).unwrap();
    let edges = solid_edge_ids(&topo, solid);
    // Unit cube has edge length 2.0 — a radius of 3.0 exceeds adjacent edges.
    let result = fillet_rolling_ball(&mut topo, solid, &edges[..1], 3.0);
    assert!(result.is_err(), "should reject radius exceeding face size");
    let msg = format!("{}", result.unwrap_err());
    assert!(
        msg.contains("exceeds"),
        "error should mention exceeds: {msg}"
    );
}

#[test]
fn fillet_radius_exceeds_cylinder_curvature_rejected() {
    // A cylinder of radius 1.0 cannot be filleted with radius >= 1.0:
    // the offset surface would degenerate to a line.
    let mut topo = Topology::new();
    let solid = crate::primitives::make_cylinder(&mut topo, 1.0, 4.0).unwrap();
    let plane_cyl_edge = {
        let s = topo.solid(solid).unwrap();
        let sh = topo.shell(s.outer_shell()).unwrap();
        let mut edge_faces: HashMap<usize, Vec<FaceId>> = HashMap::new();
        for &fid in sh.faces() {
            let wire = topo.wire(topo.face(fid).unwrap().outer_wire()).unwrap();
            for oe in wire.edges() {
                edge_faces.entry(oe.edge().index()).or_default().push(fid);
            }
        }
        let mut found = None;
        'outer: for (&eidx, fids) in &edge_faces {
            if fids.len() == 2 {
                let s1 = topo.face(fids[0]).unwrap().surface().clone();
                let s2 = topo.face(fids[1]).unwrap().surface().clone();
                let has_plane = matches!(s1, FaceSurface::Plane { .. })
                    || matches!(s2, FaceSurface::Plane { .. });
                let has_cyl = matches!(s1, FaceSurface::Cylinder(_))
                    || matches!(s2, FaceSurface::Cylinder(_));
                if has_plane && has_cyl {
                    for &fid in sh.faces() {
                        let wire = topo.wire(topo.face(fid).unwrap().outer_wire()).unwrap();
                        for oe in wire.edges() {
                            if oe.edge().index() == eidx {
                                found = Some(oe.edge());
                                break 'outer;
                            }
                        }
                    }
                }
            }
        }
        found.expect("cylinder must have a plane-cylinder edge")
    };

    // radius == cylinder radius → curvature radius exactly met → reject.
    let result = fillet_rolling_ball(&mut topo, solid, &[plane_cyl_edge], 1.0);
    assert!(
        result.is_err(),
        "radius == cylinder radius should be rejected"
    );
    let msg = format!("{}", result.unwrap_err());
    assert!(
        msg.contains("curvature"),
        "error should mention curvature: {msg}"
    );

    // radius > cylinder radius → also rejected.
    let result2 = fillet_rolling_ball(&mut topo, solid, &[plane_cyl_edge], 1.5);
    assert!(
        result2.is_err(),
        "radius > cylinder radius should be rejected"
    );

    // radius < cylinder radius → passes curvature check (may succeed or fail
    // for other fillet reasons, but must not fail on curvature).
    let result3 = fillet_rolling_ball(&mut topo, solid, &[plane_cyl_edge], 0.3);
    if let Err(ref e) = result3 {
        let msg = format!("{e}");
        assert!(
            !msg.contains("curvature"),
            "small radius should not fail curvature check: {msg}"
        );
    }
}

#[test]
fn fillet_radius_just_fits() {
    let mut topo = Topology::new();
    let solid = crate::primitives::make_box(&mut topo, 4.0, 4.0, 4.0).unwrap();
    let edges = solid_edge_ids(&topo, solid);
    // Edge length is 4.0 — a radius of 1.0 should fit comfortably.
    let result = fillet_rolling_ball(&mut topo, solid, &edges[..1], 1.0);
    assert!(
        result.is_ok(),
        "small radius should succeed: {:?}",
        result.err()
    );
}

#[test]
fn fillet_plane_cylinder_edge() {
    // A cylinder's rim edges are CLOSED circles (start vertex == end vertex).
    // The rolling-ball engine is built around polygonal wires with distinct
    // corner vertices; a closed circular edge collapses its blend strip and the
    // adjacent disc cap to zero-area faces (the result is manifold but
    // geometrically degenerate — it silently drops the caps and shrinks the
    // wall, removing ~35% of the volume; see gh #967). The engine must reject
    // this rather than return the broken solid, so the dispatcher
    // (`wasm::try_fillet`) falls through to the walking blend engine
    // (`blend_ops::fillet_v2`), which rounds a closed rim correctly.
    let mut topo = Topology::new();
    let solid = crate::primitives::make_cylinder(&mut topo, 2.0, 4.0).unwrap();

    // Find edges that border both a planar face and a cylindrical face.
    let s = topo.solid(solid).unwrap();
    let sh = topo.shell(s.outer_shell()).unwrap();
    let mut plane_cyl_edges: Vec<EdgeId> = Vec::new();
    let mut edge_faces: HashMap<usize, Vec<FaceId>> = HashMap::new();

    for &fid in sh.faces() {
        let face = topo.face(fid).unwrap();
        let wire = topo.wire(face.outer_wire()).unwrap();
        for oe in wire.edges() {
            edge_faces.entry(oe.edge().index()).or_default().push(fid);
        }
    }

    for (&eidx, fids) in &edge_faces {
        if fids.len() == 2 {
            let s1 = topo.face(fids[0]).unwrap().surface().clone();
            let s2 = topo.face(fids[1]).unwrap().surface().clone();
            let has_plane =
                matches!(s1, FaceSurface::Plane { .. }) || matches!(s2, FaceSurface::Plane { .. });
            let has_cyl =
                matches!(s1, FaceSurface::Cylinder(_)) || matches!(s2, FaceSurface::Cylinder(_));
            if has_plane && has_cyl {
                // Recover the EdgeId from eidx — walk the shell to find it.
                for &fid in sh.faces() {
                    let face = topo.face(fid).unwrap();
                    let wire = topo.wire(face.outer_wire()).unwrap();
                    for oe in wire.edges() {
                        if oe.edge().index() == eidx {
                            plane_cyl_edges.push(oe.edge());
                        }
                    }
                }
                break; // Just need one edge for the test
            }
        }
    }

    assert!(
        !plane_cyl_edges.is_empty(),
        "cylinder should have plane-cylinder edges"
    );

    // Filleting the closed rim circle must be REJECTED (not return a degenerate
    // solid). The rejection lets the dispatcher fall through to the walking
    // engine, which rounds the rim into an exact quarter-torus (gh #967).
    let result = fillet_rolling_ball(&mut topo, solid, &plane_cyl_edges[..1], 0.3);
    assert!(
        result.is_err(),
        "rolling-ball fillet of a closed cylinder-rim edge must be rejected as \
         degenerate, not return a silently-broken solid"
    );
    let msg = format!("{}", result.err().unwrap());
    assert!(
        msg.contains("degenerate"),
        "expected a degenerate-face rejection, got: {msg}"
    );
}

#[test]
fn g1_propagate_box_no_expansion() {
    // On a box every edge meets its neighbors at 90°.
    // Seeding one edge should yield a set of size exactly 1 — no expansion.
    let mut topo = Topology::new();
    let solid = crate::primitives::make_box(&mut topo, 1.0, 1.0, 1.0).unwrap();
    let edges = solid_edge_ids(&topo, solid);
    let seed = &edges[..1];

    // expand_g1_chain is private; exercise it via the public wrapper.
    // We expect the wrapper to succeed and the fillet result to be valid
    // (same as seeding with the single edge directly).
    let result = fillet_rolling_ball_propagate_g1(&mut topo, solid, seed, 0.1);
    assert!(
        result.is_ok(),
        "propagate_g1 on a box edge should succeed: {:?}",
        result.err()
    );
    let result_solid = result.unwrap();
    let vol = crate::measure::solid_volume(&topo, result_solid, 0.01).unwrap();
    assert!(
        vol > 0.0 && vol < 1.0,
        "filleted box should have smaller volume than original: {vol}"
    );
}

#[test]
fn g1_propagate_collinear_long_box() {
    // Build a long box (4×1×1) and seed one of the long top edges.
    // A box's long edges are each a single edge, so propagation still
    // yields size 1 — but the wrapper should succeed and produce a valid solid.
    let mut topo = Topology::new();
    let solid = crate::primitives::make_box(&mut topo, 4.0, 1.0, 1.0).unwrap();

    // Pick the first edge that is parallel to the X axis (length ≈ 4.0).
    let edges = solid_edge_ids(&topo, solid);
    let long_edge = edges
        .iter()
        .find(|&&eid| {
            let e = topo.edge(eid).unwrap();
            let p0 = topo.vertex(e.start()).unwrap().point();
            let p1 = topo.vertex(e.end()).unwrap().point();
            let len = (p1 - p0).length();
            len > 3.5
        })
        .copied();
    let seed_edge = long_edge.expect("could not find a long edge on a 4×1×1 box");

    let result = fillet_rolling_ball_propagate_g1(&mut topo, solid, &[seed_edge], 0.1);
    assert!(
        result.is_ok(),
        "propagate_g1 on long-box edge should succeed: {:?}",
        result.err()
    );
    let result_solid = result.unwrap();
    let vol = crate::measure::solid_volume(&topo, result_solid, 0.01).unwrap();
    assert!(
        vol > 0.0 && vol < 4.0,
        "filleted long box volume should be positive and less than original: {vol}"
    );
}

#[test]
fn adjacent_fillet_overlap_all_edges_rejected() {
    // A 1×1×1 box with all 12 edges filleted at R=0.5 must fail:
    // at each 90° corner the setback from each end is R/tan(45°) = 0.5,
    // and 0.5 + 0.5 = 1.0 = edge length → strips exactly touch → reject.
    let mut topo = Topology::new();
    let solid = crate::primitives::make_box(&mut topo, 1.0, 1.0, 1.0).unwrap();
    let edges = solid_edge_ids(&topo, solid);
    let result = fillet_rolling_ball(&mut topo, solid, &edges, 0.5);
    assert!(
        result.is_err(),
        "all-edge fillet with R=0.5 on unit box should be rejected"
    );
    let msg = format!("{}", result.unwrap_err());
    assert!(
        msg.contains("adjacent fillet strips overlap"),
        "error should mention overlap: {msg}"
    );
}

#[test]
fn adjacent_fillet_overlap_fits_with_small_radius() {
    // The same box with R=0.4 must succeed: 0.4+0.4=0.8 < 1.0.
    // (We don't check the full solid validity here — that's covered by
    // vertex_blend_all_edges_box.  Just verify Phase 2d does not block it.)
    let mut topo = Topology::new();
    let solid = crate::primitives::make_box(&mut topo, 1.0, 1.0, 1.0).unwrap();
    let edges = solid_edge_ids(&topo, solid);
    let result = fillet_rolling_ball(&mut topo, solid, &edges, 0.4);
    assert!(
        result.is_ok(),
        "all-edge fillet with R=0.4 on unit box should be accepted by Phase 2d: {:?}",
        result.err()
    );
}

#[test]
fn adjacent_fillet_single_edge_no_phase2d_rejection() {
    // Filleting one edge of a box has no adjacent target edges — Phase 2d
    // never fires even for R close to the face size.
    let mut topo = Topology::new();
    let solid = crate::primitives::make_box(&mut topo, 1.0, 1.0, 1.0).unwrap();
    let edges = solid_edge_ids(&topo, solid);
    // Phase 2b caps R at the adjacent edge length (1.0). R=0.4 is well below that.
    let result = fillet_rolling_ball(&mut topo, solid, &edges[..1], 0.4);
    assert!(
        result.is_ok(),
        "single-edge fillet with R=0.4 should succeed: {:?}",
        result.err()
    );
}

#[test]
fn face_surface_normal_at_nurbs_via_projection() {
    // Directly test the NURBS branch of face_surface_normal_at.
    // Build a flat bilinear NURBS patch in the XY plane.  The outward
    // normal is (0, 0, 1) everywhere; point projection must return a
    // valid (u, v) that yields the correct normal.
    let srf = NurbsSurface::new(
        1,
        1,
        vec![0.0, 0.0, 1.0, 1.0],
        vec![0.0, 0.0, 1.0, 1.0],
        vec![
            vec![Point3::new(0.0, 0.0, 0.0), Point3::new(0.0, 1.0, 0.0)],
            vec![Point3::new(1.0, 0.0, 0.0), Point3::new(1.0, 1.0, 0.0)],
        ],
        vec![vec![1.0, 1.0], vec![1.0, 1.0]],
    )
    .expect("bilinear XY patch");

    let surface = FaceSurface::Nurbs(srf);

    // Test at a non-central point to ensure projection (not midpoint) is used.
    let n = face_surface_normal_at(&surface, Point3::new(0.2, 0.8, 0.0));
    let n = n.expect("NURBS normal should be Some for a surface point");

    // Flat XY patch has normal along ±Z.
    assert!(
        n.z().abs() > 0.9,
        "flat XY patch normal must be along Z, got: {n:?}"
    );
    // Result must be approximately unit length.
    assert!(
        (n.length() - 1.0).abs() < 0.01,
        "NURBS normal must be unit length, got: {}",
        n.length()
    );
}

#[test]
fn fillet_rolling_ball_second_pass_on_nurbs_solid() {
    // After a rolling-ball fillet the result solid contains a NURBS face.
    // A second fillet on a different manifold edge must succeed.  This
    // verifies that face_surfaces containing NURBS entries does not crash
    // fillet_rolling_ball even when the NURBS face is non-manifold in the
    // current implementation (so its normal branch is not reached yet).
    let mut topo = Topology::new();
    let solid = make_unit_cube_manifold(&mut topo);

    let edges1 = solid_edge_ids(&topo, solid);
    let result1 = fillet_rolling_ball(&mut topo, solid, &[edges1[0]], 0.1)
        .expect("first rolling-ball fillet should succeed");

    // Confirm a blend face was created (a cylinder here, NURBS for curved
    // neighbours).
    let has_nurbs = {
        let s = topo.solid(result1).unwrap();
        let sh = topo.shell(s.outer_shell()).unwrap();
        sh.faces()
            .iter()
            .any(|&fid| !topo.face(fid).unwrap().surface().is_planar())
    };
    assert!(has_nurbs, "first fillet must produce a blend face");

    // Second fillet on a different edge.
    let edges2 = solid_edge_ids(&topo, result1);
    let result2 = fillet_rolling_ball(&mut topo, result1, &[edges2[1]], 0.05);
    assert!(
        result2.is_ok(),
        "second fillet on NURBS-containing solid must succeed: {:?}",
        result2.err()
    );

    let vol = crate::measure::solid_volume(&topo, result2.unwrap(), 0.1).unwrap();
    assert!(
        vol > 0.5,
        "doubly-filleted solid must have positive volume, got {vol}"
    );
}

#[test]
fn fillet_on_fillet_box() {
    // Fillet all 12 edges of a box, then fillet the resulting NURBS edges.
    let mut topo = Topology::new();
    let solid = crate::primitives::make_box(&mut topo, 2.0, 2.0, 2.0).unwrap();
    let edges = solid_edge_ids(&topo, solid);

    let result1 = fillet_rolling_ball(&mut topo, solid, &edges, 0.1).unwrap();
    let vol1 = crate::measure::solid_volume(&topo, result1, 0.01).unwrap();
    assert!(vol1 > 0.0, "first fillet should produce positive volume");

    let edges2 = solid_edge_ids(&topo, result1);
    assert!(
        !edges2.is_empty(),
        "filleted solid must have edges for second fillet attempt"
    );

    // Try to fillet one of the new NURBS-NURBS edges with smaller radius.
    // This should not panic or error — it's the #39 test.
    let result2 = fillet_rolling_ball(&mut topo, result1, &edges2[..1], 0.05);
    match result2 {
        Ok(solid2) => {
            let vol2 = crate::measure::solid_volume(&topo, solid2, 0.01).unwrap();
            assert!(vol2 > 0.0, "second fillet should produce positive volume");
        }
        Err(e) => {
            // Graceful failure is acceptable — log the error for diagnostics
            eprintln!("second fillet failed gracefully: {e}");
        }
    }
}

#[test]
fn adjacent_fillet_overlap_curved_face_detected() {
    // Two small fillets on a cylinder face that would overlap.
    let mut topo = Topology::new();
    let cyl = crate::primitives::make_cylinder(&mut topo, 1.0, 2.0).unwrap();

    // Get edges - the cylinder has circle edges at top and bottom
    let edges = solid_edge_ids(&topo, cyl);

    // Try to fillet with a very large radius that should trigger overlap
    // on the curved cylinder face
    let result = fillet_rolling_ball(&mut topo, cyl, &edges, 0.9);
    // Should either succeed (if no overlap) or return an error (if overlap detected)
    // The key is: it should NOT panic
    match result {
        Ok(solid) => {
            let vol = crate::measure::solid_volume(&topo, solid, 0.01).unwrap();
            assert!(vol > 0.0);
        }
        Err(e) => {
            // A large radius on the closed cylinder rim is expected to fail.
            // Acceptable reasons: overlap / curvature bound, or the degenerate
            // closed-circular-edge rejection (the rim collapses the blend strip;
            // see gh #967). The key is that it must NOT panic.
            let msg = format!("{e}");
            assert!(
                msg.contains("overlap")
                    || msg.contains("curvature")
                    || msg.contains("exceeds")
                    || msg.contains("degenerate"),
                "expected overlap/curvature/degenerate error, got: {msg}"
            );
        }
    }
}

#[test]
fn g1_chain_no_expansion_for_box() {
    // Box edges meet at 90 degrees — no G1 chains should be detected.
    // Filleting a single edge should succeed without expanding.
    let mut topo = Topology::new();
    let solid = crate::primitives::make_box(&mut topo, 2.0, 2.0, 2.0).unwrap();
    let edges = solid_edge_ids(&topo, solid);

    // Fillet a single edge with a small radius.
    let result = fillet_rolling_ball(&mut topo, solid, &edges[..1], 0.1);
    assert!(
        result.is_ok(),
        "single-edge fillet on box should succeed: {:?}",
        result.err()
    );

    let result_solid = result.unwrap();
    let vol = crate::measure::solid_volume(&topo, result_solid, 0.01).unwrap();
    // Original box volume: 8.0; fillet removes a small amount.
    assert!(
        vol > 7.0 && vol < 8.0,
        "filleted box volume should be slightly less than 8.0, got {vol}"
    );
}

#[test]
fn g1_chain_integrated_matches_explicit_wrapper() {
    // Since fillet_rolling_ball now does G1 expansion internally,
    // calling it directly on a seed should give the same result as
    // the explicit propagate_g1 wrapper.
    let mut topo1 = Topology::new();
    let solid1 = crate::primitives::make_box(&mut topo1, 1.0, 1.0, 1.0).unwrap();
    let edges1 = solid_edge_ids(&topo1, solid1);
    let result1 = fillet_rolling_ball(&mut topo1, solid1, &edges1[..1], 0.1);
    assert!(result1.is_ok(), "direct call should succeed");
    let vol1 = crate::measure::solid_volume(&topo1, result1.unwrap(), 0.01).unwrap();

    let mut topo2 = Topology::new();
    let solid2 = crate::primitives::make_box(&mut topo2, 1.0, 1.0, 1.0).unwrap();
    let edges2 = solid_edge_ids(&topo2, solid2);
    let result2 = fillet_rolling_ball_propagate_g1(&mut topo2, solid2, &edges2[..1], 0.1);
    assert!(result2.is_ok(), "wrapper call should succeed");
    let vol2 = crate::measure::solid_volume(&topo2, result2.unwrap(), 0.01).unwrap();

    // Both should produce the same volume (within tolerance).
    assert!(
        (vol1 - vol2).abs() < 0.01,
        "volumes should match: direct={vol1}, wrapper={vol2}"
    );
}

/// Dihedral angle (degrees) between the two faces of an edge, sampled at the
/// edge midpoint, using effective (reversal-adjusted) outward normals.
fn dihedral_deg(topo: &Topology, e: EdgeId, fs: &[FaceId]) -> f64 {
    let ed = topo.edge(e).unwrap();
    let a = topo.vertex(ed.start()).unwrap().point();
    let b = topo.vertex(ed.end()).unwrap().point();
    let mid = a + (b - a) * 0.5;
    let nrm = |fid: FaceId| {
        let face = topo.face(fid).unwrap();
        let n = match face.surface() {
            FaceSurface::Plane { normal, .. } => *normal,
            other => {
                let (u, v) = other.project_point(mid).unwrap_or((0.0, 0.0));
                other.normal(u, v)
            }
        };
        let n = if face.is_reversed() { -n } else { n };
        n.normalize().unwrap()
    };
    nrm(fs[0])
        .dot(nrm(fs[1]))
        .clamp(-1.0, 1.0)
        .acos()
        .to_degrees()
}

/// #834: round an edge whose neighbour is a previous fillet's NURBS blend face.
///
/// A single-edge rolling-ball fillet yields a watertight solid with a NURBS
/// blend face. Filleting a (non-tangent) edge bordering that blend face must
/// itself produce a valid, watertight manifold — the blend's accessible
/// non-degenerate edges are concave end-caps, so the fillet fills the seam.
#[test]
fn fillet_edge_adjacent_to_nurbs_blend_is_watertight() {
    use brepkit_topology::validation::validate_shell_closed;

    let mut topo = Topology::new();
    let cube = crate::primitives::make_box(&mut topo, 10.0, 10.0, 10.0).unwrap();
    let edges = solid_edge_ids(&topo, cube);

    // First fillet — one box edge → a watertight solid with a NURBS blend face.
    let first = fillet_rolling_ball(&mut topo, cube, &[edges[0]], 1.0).unwrap();
    {
        let sh = topo
            .shell(topo.solid(first).unwrap().outer_shell())
            .unwrap();
        validate_shell_closed(sh, &topo).expect("first fillet should be watertight");
    }
    let vol1 = crate::measure::solid_volume(&topo, first, 0.05).unwrap();

    // Collect NURBS blend faces and edge→faces adjacency.
    let blend_faces: HashSet<usize> = {
        let sh = topo
            .shell(topo.solid(first).unwrap().outer_shell())
            .unwrap();
        sh.faces()
            .iter()
            .filter(|&&f| !topo.face(f).unwrap().surface().is_planar())
            .map(|f| f.index())
            .collect()
    };
    assert!(
        !blend_faces.is_empty(),
        "first fillet must create a blend face"
    );

    let mut ef: HashMap<usize, Vec<FaceId>> = HashMap::new();
    {
        let sh = topo
            .shell(topo.solid(first).unwrap().outer_shell())
            .unwrap();
        for &fid in sh.faces() {
            for oe in topo
                .wire(topo.face(fid).unwrap().outer_wire())
                .unwrap()
                .edges()
            {
                ef.entry(oe.edge().index()).or_default().push(fid);
            }
        }
    }

    // A non-tangent edge bordering the NURBS blend face (the tangent contact
    // lines are G1/degenerate and are not fillettable).
    let target = solid_edge_ids(&topo, first)
        .into_iter()
        .find(|&e| {
            ef.get(&e.index()).is_some_and(|fs| {
                fs.len() == 2
                    && fs.iter().any(|f| blend_faces.contains(&f.index()))
                    && dihedral_deg(&topo, e, fs) > 5.0
            })
        })
        .expect("a non-tangent edge bordering the NURBS blend face");

    // Second fillet on that NURBS-blend-adjacent edge.
    let result = fillet_rolling_ball(&mut topo, first, &[target], 0.5).unwrap();
    let sh = topo
        .shell(topo.solid(result).unwrap().outer_shell())
        .unwrap();
    validate_shell_manifold(sh, &topo).expect("second fillet must be manifold");
    validate_shell_closed(sh, &topo)
        .expect("second fillet on a NURBS-blend-adjacent edge must be watertight");

    let vol2 = crate::measure::solid_volume(&topo, result, 0.05).unwrap();
    // Concave end-cap edge → the fillet fills; volume stays sane (between the
    // first fillet and the original box).
    assert!(
        vol2 > vol1 - 1e-6 && vol2 <= 1000.0 + 1e-6,
        "filled fillet volume out of range: first={vol1}, second={vol2}"
    );
}