brepkit-operations 3.0.0

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
#![allow(clippy::unwrap_used)]

use std::collections::HashMap;

use brepkit_math::nurbs::curve::NurbsCurve;
use brepkit_math::tolerance::Tolerance;
use brepkit_math::vec::Point3;
use brepkit_topology::Topology;
use brepkit_topology::face::FaceSurface;
use brepkit_topology::test_utils::make_unit_square_face;

use super::*;

/// Helper: create a straight-line NURBS path from origin along +Z by `length`.
fn straight_z_path(length: f64) -> NurbsCurve {
    NurbsCurve::new(
        1,
        vec![0.0, 0.0, 1.0, 1.0],
        vec![Point3::new(0.0, 0.0, 0.0), Point3::new(0.0, 0.0, length)],
        vec![1.0, 1.0],
    )
    .unwrap()
}

/// Helper: create a quarter-circle NURBS path in the XZ plane.
fn quarter_circle_xz_path(radius: f64) -> NurbsCurve {
    let w = std::f64::consts::FRAC_1_SQRT_2;
    NurbsCurve::new(
        2,
        vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
        vec![
            Point3::new(0.0, 0.0, 0.0),
            Point3::new(radius, 0.0, 0.0),
            Point3::new(radius, 0.0, radius),
        ],
        vec![1.0, w, 1.0],
    )
    .unwrap()
}

/// Helper: a `size`×`size` square profile face centered at the origin in
/// the XY plane (normal +Z).
fn make_square(topo: &mut Topology, size: f64) -> FaceId {
    let hs = size / 2.0;
    let t = 1e-7;
    let v0 = topo.add_vertex(Vertex::new(Point3::new(-hs, -hs, 0.0), t));
    let v1 = topo.add_vertex(Vertex::new(Point3::new(hs, -hs, 0.0), t));
    let v2 = topo.add_vertex(Vertex::new(Point3::new(hs, hs, 0.0), t));
    let v3 = topo.add_vertex(Vertex::new(Point3::new(-hs, hs, 0.0), t));
    let e0 = topo.add_edge(Edge::new(v0, v1, EdgeCurve::Line));
    let e1 = topo.add_edge(Edge::new(v1, v2, EdgeCurve::Line));
    let e2 = topo.add_edge(Edge::new(v2, v3, EdgeCurve::Line));
    let e3 = topo.add_edge(Edge::new(v3, v0, EdgeCurve::Line));
    let wire = Wire::new(
        vec![
            OrientedEdge::new(e0, true),
            OrientedEdge::new(e1, true),
            OrientedEdge::new(e2, true),
            OrientedEdge::new(e3, true),
        ],
        true,
    )
    .unwrap();
    let wid = topo.add_wire(wire);
    topo.add_face(Face::new(
        wid,
        vec![],
        FaceSurface::Plane {
            normal: Vec3::new(0.0, 0.0, 1.0),
            d: 0.0,
        },
    ))
}

#[test]
fn multi_section_sweep_line_spine_tapered_volume() {
    let mut topo = Topology::new();
    let big = make_square(&mut topo, 10.0);
    let small = make_square(&mut topo, 6.0);
    let spine = straight_z_path(20.0);

    let solid = multi_section_sweep(&mut topo, &spine, &[(big, 0.0), (small, 1.0)], true).unwrap();
    let vol = crate::measure::solid_volume(&topo, solid, 0.1).unwrap();

    // Frustum between a 10×10 and 6×6 square over height 20 lies strictly
    // between the two straight-prism volumes (6²·20 = 720 and 10²·20 = 2000).
    assert!(
        vol > 720.0 && vol < 2000.0,
        "expected tapered volume, got {vol}"
    );
}

#[test]
fn multi_section_sweep_curved_spine_positive_volume() {
    let mut topo = Topology::new();
    // Three sections so the loft follows the quarter-circle spine; the RMF
    // keeps each profile perpendicular and twist-free.
    let a = make_square(&mut topo, 4.0);
    let b = make_square(&mut topo, 4.0);
    let c = make_square(&mut topo, 4.0);
    let spine = quarter_circle_xz_path(20.0);

    let solid =
        multi_section_sweep(&mut topo, &spine, &[(a, 0.0), (b, 0.5), (c, 1.0)], true).unwrap();
    let vol = crate::measure::solid_volume(&topo, solid, 0.1).unwrap();
    assert!(
        vol > 0.0,
        "curved-spine multi-section sweep volume, got {vol}"
    );
}

#[test]
fn multi_section_sweep_rejects_single_section() {
    let mut topo = Topology::new();
    let only = make_square(&mut topo, 4.0);
    let spine = straight_z_path(10.0);
    assert!(multi_section_sweep(&mut topo, &spine, &[(only, 0.0)], true).is_err());
}

#[test]
fn multi_section_sweep_rejects_out_of_range_param() {
    let mut topo = Topology::new();
    let a = make_square(&mut topo, 4.0);
    let b = make_square(&mut topo, 4.0);
    let spine = straight_z_path(10.0);
    assert!(multi_section_sweep(&mut topo, &spine, &[(a, 0.0), (b, 1.5)], true).is_err());
}

#[test]
fn multi_section_sweep_unsorted_params_match_sorted() {
    // Placement sorts by parameter, so input order must not change the result.
    let mut t1 = Topology::new();
    let (a1, b1) = (make_square(&mut t1, 10.0), make_square(&mut t1, 4.0));
    let s1 = multi_section_sweep(
        &mut t1,
        &straight_z_path(20.0),
        &[(a1, 0.0), (b1, 1.0)],
        true,
    )
    .unwrap();
    let v_sorted = crate::measure::solid_volume(&t1, s1, 0.1).unwrap();

    let mut t2 = Topology::new();
    let (a2, b2) = (make_square(&mut t2, 10.0), make_square(&mut t2, 4.0));
    let s2 = multi_section_sweep(
        &mut t2,
        &straight_z_path(20.0),
        &[(b2, 1.0), (a2, 0.0)],
        true,
    )
    .unwrap();
    let v_unsorted = crate::measure::solid_volume(&t2, s2, 0.1).unwrap();

    assert!(
        (v_sorted - v_unsorted).abs() < 1e-6,
        "{v_sorted} vs {v_unsorted}"
    );
}

#[test]
fn profile_to_frame_matrix_is_proper_rotation() {
    // The placement must be a proper rotation (det +1), never a reflection,
    // or asymmetric profiles would be mirrored.
    let mut topo = Topology::new();
    let face = make_square(&mut topo, 4.0);
    let tangent = Vec3::new(1.0, 1.0, 1.0).normalize().unwrap();
    let up = orthogonalize(Vec3::new(0.0, 0.0, 1.0), tangent);
    let frame = Frame {
        origin: Point3::new(5.0, 6.0, 7.0),
        tangent,
        up,
        right: tangent.cross(up),
    };
    let m = profile_to_frame_matrix(&topo, face, &frame).unwrap();
    let r = &m.0;
    let det = r[0][0] * (r[1][1] * r[2][2] - r[1][2] * r[2][1])
        - r[0][1] * (r[1][0] * r[2][2] - r[1][2] * r[2][0])
        + r[0][2] * (r[1][0] * r[2][1] - r[1][1] * r[2][0]);
    assert!(
        (det - 1.0).abs() < 1e-9,
        "rotation det should be +1, got {det}"
    );
}

/// Helper: a `2*hx`×`2*hy` rectangle profile at the origin in the XY plane.
fn make_rect(topo: &mut Topology, hx: f64, hy: f64) -> FaceId {
    let t = 1e-7;
    let v0 = topo.add_vertex(Vertex::new(Point3::new(-hx, -hy, 0.0), t));
    let v1 = topo.add_vertex(Vertex::new(Point3::new(hx, -hy, 0.0), t));
    let v2 = topo.add_vertex(Vertex::new(Point3::new(hx, hy, 0.0), t));
    let v3 = topo.add_vertex(Vertex::new(Point3::new(-hx, hy, 0.0), t));
    let e0 = topo.add_edge(Edge::new(v0, v1, EdgeCurve::Line));
    let e1 = topo.add_edge(Edge::new(v1, v2, EdgeCurve::Line));
    let e2 = topo.add_edge(Edge::new(v2, v3, EdgeCurve::Line));
    let e3 = topo.add_edge(Edge::new(v3, v0, EdgeCurve::Line));
    let wire = Wire::new(
        vec![
            OrientedEdge::new(e0, true),
            OrientedEdge::new(e1, true),
            OrientedEdge::new(e2, true),
            OrientedEdge::new(e3, true),
        ],
        true,
    )
    .unwrap();
    let wid = topo.add_wire(wire);
    topo.add_face(Face::new(
        wid,
        vec![],
        FaceSurface::Plane {
            normal: Vec3::new(0.0, 0.0, 1.0),
            d: 0.0,
        },
    ))
}

/// Helper: a degree-1 guide curve from `(x0,y0,0)` to `(x1,y1,10)`.
fn guide_line(x0: f64, y0: f64, x1: f64, y1: f64) -> NurbsCurve {
    NurbsCurve::new(
        1,
        vec![0.0, 0.0, 1.0, 1.0],
        vec![Point3::new(x0, y0, 0.0), Point3::new(x1, y1, 10.0)],
        vec![1.0, 1.0],
    )
    .unwrap()
}

#[test]
fn sweep_guided_produces_valid_solid() {
    let mut topo = Topology::new();
    let profile = make_square(&mut topo, 4.0);
    let spine = straight_z_path(10.0);
    let aux = guide_line(10.0, 0.0, 10.0, 0.0);
    let solid = sweep_guided(&mut topo, profile, &spine, aux).unwrap();
    let vol = crate::measure::solid_volume(&topo, solid, 0.1).unwrap();
    assert!(vol > 0.0, "guided sweep volume, got {vol}");
}

#[test]
fn sweep_guided_rotating_aux_rolls_profile() {
    // A wide rectangle swept straight stays flat in Y. A guide that rotates
    // from +X to +Y over the sweep rolls the rectangle 90°, sweeping its
    // wide axis into Y — so the Y-extent grows far beyond the flat case.
    let mut t_plain = Topology::new();
    let p_plain = make_rect(&mut t_plain, 8.0, 1.0);
    let s_plain = sweep_with_options(
        &mut t_plain,
        p_plain,
        &straight_z_path(10.0),
        &SweepOptions::default(),
    )
    .unwrap();
    let bb_plain = crate::measure::solid_bounding_box(&t_plain, s_plain).unwrap();
    let y_plain = bb_plain.max.y() - bb_plain.min.y();

    let mut t_guided = Topology::new();
    let p_guided = make_rect(&mut t_guided, 8.0, 1.0);
    let aux = guide_line(30.0, 0.0, 0.0, 30.0);
    let s_guided = sweep_guided(&mut t_guided, p_guided, &straight_z_path(10.0), aux).unwrap();
    let bb_guided = crate::measure::solid_bounding_box(&t_guided, s_guided).unwrap();
    let y_guided = bb_guided.max.y() - bb_guided.min.y();

    assert!(
        y_plain < 4.0,
        "plain sweep keeps the rectangle flat in Y, got {y_plain}"
    );
    assert!(
        y_guided > 8.0,
        "the rotating guide should roll the wide axis into Y, got {y_guided}"
    );
}

#[test]
fn sweep_guided_handles_guide_meeting_spine() {
    // The guide starts coincident with the spine (up undefined at t=0) then
    // diverges — frame continuity must still yield a valid finite solid.
    let mut topo = Topology::new();
    let profile = make_square(&mut topo, 3.0);
    let spine = straight_z_path(10.0);
    let aux = guide_line(0.0, 0.0, 10.0, 0.0);
    let solid = sweep_guided(&mut topo, profile, &spine, aux).unwrap();
    let vol = crate::measure::solid_volume(&topo, solid, 0.1).unwrap();
    assert!(
        vol > 0.0 && vol.is_finite(),
        "guide-meets-spine should still yield a valid solid, got {vol}"
    );
}

#[test]
fn sweep_circle_along_straight_line_is_exact_cylinder() {
    // gh #965: sweeping a circle along a straight spine must produce an exact
    // cylinder (π·r²·L), not an inscribed polygonal prism (~2% low). The
    // straight-sweep fast path delegates to extrude, which builds a true
    // cylinder side face.
    use brepkit_math::vec::Vec3;
    use brepkit_topology::builder::make_circle_edge;
    use brepkit_topology::face::Face;
    use brepkit_topology::wire::{OrientedEdge, Wire};

    let tol = 1e-7;
    let mut topo = Topology::new();
    let circle = make_circle_edge(
        &mut topo,
        Point3::new(0.0, 0.0, 0.0),
        Vec3::new(0.0, 0.0, 1.0),
        2.0,
        tol,
    )
    .unwrap();
    let wid = topo.add_wire(Wire::new(vec![OrientedEdge::new(circle, true)], true).unwrap());
    let profile = topo.add_face(Face::new(
        wid,
        vec![],
        FaceSurface::Plane {
            normal: Vec3::new(0.0, 0.0, 1.0),
            d: 0.0,
        },
    ));
    let path = straight_z_path(20.0);

    let solid = sweep(&mut topo, profile, &path).unwrap();

    let vol = crate::measure::solid_volume(&topo, solid, 0.01).unwrap();
    let expected = std::f64::consts::PI * 4.0 * 20.0;
    assert!(
        (vol - expected).abs() / expected < 1e-6,
        "expected exact cylinder volume {expected}, got {vol}"
    );
    assert!(
        crate::validate::validate_solid(&topo, solid)
            .unwrap()
            .is_valid()
    );
}

#[test]
fn sweep_square_along_line() {
    // A straight perpendicular sweep is a prism: a unit square swept along a
    // length-2 line is a 1×1×2 box — 6 planar faces, volume 2 — built exactly
    // via the extrude fast path (not a faceted multi-ring solid).
    let mut topo = Topology::new();
    let face = make_unit_square_face(&mut topo);
    let path = straight_z_path(2.0);

    let solid = sweep(&mut topo, face, &path).unwrap();

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

    assert_eq!(shell.faces().len(), 6, "a straight square sweep is a box");

    for &fid in shell.faces() {
        let f = topo.face(fid).unwrap();
        assert!(
            matches!(f.surface(), FaceSurface::Plane { .. }),
            "all box faces should be planar"
        );
    }

    let vol = crate::measure::solid_volume(&topo, solid, 0.01).unwrap();
    assert!(
        (vol - 2.0).abs() < 1e-9,
        "expected box volume 2.0, got {vol}"
    );
}

#[test]
fn sweep_square_along_quarter_circle() {
    let mut topo = Topology::new();
    let face = make_unit_square_face(&mut topo);
    let path = quarter_circle_xz_path(5.0);

    let solid = sweep(&mut topo, face, &path).unwrap();

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

    // 6 segments (max(3*2, 4)) × 4 edges + 2 caps = 26 faces.
    let num_segs = (path.control_points().len() * 2).max(4);
    let expected_faces = num_segs * 4 + 2;
    assert_eq!(shell.faces().len(), expected_faces);

    // Verify manifold: every edge shared by exactly 2 faces.
    let mut edge_counts: HashMap<usize, usize> = HashMap::new();
    for &fid in shell.faces() {
        let f = topo.face(fid).unwrap();
        let wire = topo.wire(f.outer_wire()).unwrap();
        for oe in wire.edges() {
            *edge_counts.entry(oe.edge().index()).or_insert(0) += 1;
        }
    }
    for (&edge_idx, &count) in &edge_counts {
        assert_eq!(
            count, 2,
            "edge {edge_idx} shared by {count} faces, expected 2"
        );
    }
}

#[test]
fn sweep_insufficient_control_points_error() {
    let mut topo = Topology::new();
    let face = make_unit_square_face(&mut topo);

    // A path with only 1 control point is invalid.
    let path = NurbsCurve::new(
        0,
        vec![0.0, 1.0],
        vec![Point3::new(0.0, 0.0, 0.0)],
        vec![1.0],
    )
    .unwrap();

    let result = sweep(&mut topo, face, &path);
    assert!(result.is_err());
}

#[test]
fn sweep_zero_path_error() {
    let mut topo = Topology::new();
    let face = make_unit_square_face(&mut topo);

    // A path where start == end (zero length).
    let path = NurbsCurve::new(
        1,
        vec![0.0, 0.0, 1.0, 1.0],
        vec![Point3::new(1.0, 2.0, 3.0), Point3::new(1.0, 2.0, 3.0)],
        vec![1.0, 1.0],
    )
    .unwrap();

    let result = sweep(&mut topo, face, &path);
    assert!(result.is_err());
}

#[test]
fn sweep_and_tessellate_roundtrip() {
    use crate::tessellate::tessellate;

    let mut topo = Topology::new();
    let face = make_unit_square_face(&mut topo);
    let path = quarter_circle_xz_path(5.0);

    let solid = sweep(&mut topo, face, &path).unwrap();

    let solid_data = topo.solid(solid).unwrap();
    let shell = topo.shell(solid_data.outer_shell()).unwrap();
    let tol = Tolerance::new();

    for &fid in shell.faces() {
        let mesh = tessellate(&topo, fid, 0.25).unwrap();
        assert!(!mesh.positions.is_empty());
        assert!(!mesh.indices.is_empty());
        assert_eq!(mesh.positions.len(), mesh.normals.len());

        for normal in &mesh.normals {
            let len = normal.length();
            assert!(
                tol.approx_eq(len, 1.0) || tol.approx_eq(len, 0.0),
                "normal length should be ~1.0, got {len}"
            );
        }
    }
}

#[test]
fn sweep_with_default_options_matches_basic() {
    let mut topo = Topology::new();
    let face = crate::primitives::make_box(&mut topo, 0.5, 0.5, 0.01).unwrap();
    let solid = topo.solid(face).unwrap();
    let shell = topo.shell(solid.outer_shell()).unwrap();
    let profile = shell.faces()[0];

    let path = NurbsCurve::new(
        1,
        vec![0.0, 0.0, 1.0, 1.0],
        vec![Point3::new(0.0, 0.0, 0.0), Point3::new(0.0, 0.0, 5.0)],
        vec![1.0, 1.0],
    )
    .unwrap();

    let options = SweepOptions::default();
    let result = sweep_with_options(&mut topo, profile, &path, &options);
    assert!(result.is_ok());
}

#[test]
fn sweep_with_linear_scale() {
    let mut topo = Topology::new();
    let profile = make_unit_square_face(&mut topo);

    let path = NurbsCurve::new(
        1,
        vec![0.0, 0.0, 1.0, 1.0],
        vec![Point3::new(0.0, 0.0, 0.0), Point3::new(0.0, 0.0, 5.0)],
        vec![1.0, 1.0],
    )
    .unwrap();

    let options = SweepOptions {
        scale_law: Some(Box::new(|t| 0.5f64.mul_add(-t, 1.0))), // taper from 1.0 to 0.5
        segments: 8,
        ..Default::default()
    };

    let result = sweep_with_options(&mut topo, profile, &path, &options).unwrap();

    let vol = crate::measure::solid_volume(&topo, result, 0.5).unwrap();
    assert!(vol > 0.0, "tapered sweep should have positive volume");
}

#[test]
fn sweep_fixed_contact_mode() {
    let mut topo = Topology::new();
    let profile = make_unit_square_face(&mut topo);

    let path = NurbsCurve::new(
        1,
        vec![0.0, 0.0, 1.0, 1.0],
        vec![Point3::new(0.0, 0.0, 0.0), Point3::new(0.0, 0.0, 5.0)],
        vec![1.0, 1.0],
    )
    .unwrap();

    let options = SweepOptions {
        contact_mode: SweepContactMode::Fixed,
        ..Default::default()
    };

    let result = sweep_with_options(&mut topo, profile, &path, &options);
    assert!(result.is_ok());
}

#[test]
fn sweep_constant_normal_mode() {
    let mut topo = Topology::new();
    let profile = make_unit_square_face(&mut topo);

    let path = NurbsCurve::new(
        1,
        vec![0.0, 0.0, 1.0, 1.0],
        vec![Point3::new(0.0, 0.0, 0.0), Point3::new(0.0, 0.0, 5.0)],
        vec![1.0, 1.0],
    )
    .unwrap();

    let options = SweepOptions {
        contact_mode: SweepContactMode::ConstantNormal(Vec3::new(0.0, 1.0, 0.0)),
        ..Default::default()
    };

    let result = sweep_with_options(&mut topo, profile, &path, &options);
    assert!(result.is_ok());
}

// ── Smooth sweep tests ──────────────────────────

#[test]
fn sweep_smooth_produces_nurbs_sides() {
    let mut topo = Topology::new();
    let profile = make_unit_square_face(&mut topo);
    let path = straight_z_path(2.0);

    let solid = sweep_smooth(&mut topo, profile, &path).unwrap();

    let s = topo.solid(solid).unwrap();
    let sh = topo.shell(s.outer_shell()).unwrap();

    // Should have N NURBS sides + 2 planar caps.
    let nurbs_count = sh
        .faces()
        .iter()
        .filter(|&&fid| matches!(topo.face(fid).unwrap().surface(), FaceSurface::Nurbs(_)))
        .count();

    assert!(
        nurbs_count > 0,
        "smooth sweep should produce NURBS side faces"
    );

    // Fewer faces than the basic sweep (N sides vs N*segments sides).
    let profile_edge_count = 4; // square has 4 edges
    let expected_face_count = profile_edge_count + 2; // N sides + 2 caps
    assert_eq!(
        sh.faces().len(),
        expected_face_count,
        "smooth sweep should have {expected_face_count} faces, got {}",
        sh.faces().len()
    );
}

#[test]
fn sweep_smooth_positive_volume() {
    let mut topo = Topology::new();
    let profile = make_unit_square_face(&mut topo);
    let path = straight_z_path(3.0);

    let solid = sweep_smooth(&mut topo, profile, &path).unwrap();

    let vol = crate::measure::solid_volume(&topo, solid, 0.1).unwrap();
    assert!(
        vol > 0.0,
        "smooth sweep should have positive volume, got {vol}"
    );
}

#[test]
fn sweep_smooth_curved_path() {
    let mut topo = Topology::new();
    let profile = make_unit_square_face(&mut topo);
    let path = quarter_circle_xz_path(5.0);

    let solid = sweep_smooth(&mut topo, profile, &path).unwrap();

    let s = topo.solid(solid).unwrap();
    let sh = topo.shell(s.outer_shell()).unwrap();

    assert_eq!(
        sh.faces().len(),
        6,
        "smooth curved sweep should have 6 faces"
    );

    // A unit square swept along a quarter circle of radius 5: the swept volume
    // is ~ profile area (1) × arc length (π/2 × 5 ≈ 7.85). Before profile
    // auto-orientation the XY-plane profile was edge-on to the +X start tangent
    // and collapsed to a ~zero-volume ribbon that still satisfied `vol > 0`.
    let vol = crate::measure::solid_volume(&topo, solid, 0.1).unwrap();
    assert!(
        vol > 7.0 && vol < 8.5,
        "curved smooth sweep volume should be ~7.85, got {vol}"
    );
}

/// Helper: create a closed circular NURBS path (full circle in XZ plane).
///
/// Uses the XZ plane so that a profile in XY sweeps with full 3D extent
/// (the path tangent at t=0 is +Z, giving the profile extent in both
/// right(Y) and up(X) directions relative to the frame).
fn closed_circle_path(radius: f64) -> NurbsCurve {
    // Full circle as a rational quadratic NURBS with 9 control points.
    let w = std::f64::consts::FRAC_1_SQRT_2;
    let r = radius;
    NurbsCurve::new(
        2,
        vec![
            0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0,
        ],
        vec![
            Point3::new(r, 0.0, 0.0),
            Point3::new(r, 0.0, r),
            Point3::new(0.0, 0.0, r),
            Point3::new(-r, 0.0, r),
            Point3::new(-r, 0.0, 0.0),
            Point3::new(-r, 0.0, -r),
            Point3::new(0.0, 0.0, -r),
            Point3::new(r, 0.0, -r),
            Point3::new(r, 0.0, 0.0),
        ],
        vec![1.0, w, 1.0, w, 1.0, w, 1.0, w, 1.0],
    )
    .unwrap()
}

#[test]
fn sweep_closed_circular_path() {
    // Sweeping a small square profile around a closed circle should
    // produce a torus-like solid with no cap faces.
    let mut topo = Topology::new();
    let profile = make_unit_square_face(&mut topo);
    let path = closed_circle_path(5.0);

    let solid = sweep(&mut topo, profile, &path).unwrap();

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

    // Closed sweep: no caps, only side faces.
    let num_segs = (path.control_points().len() * 2).max(4);
    let expected_faces = num_segs * 4; // 4 edges per profile × num_segments
    assert_eq!(
        shell.faces().len(),
        expected_faces,
        "closed sweep should have {expected_faces} side faces (no caps)"
    );

    // Verify manifold: every edge shared by exactly 2 faces.
    let mut edge_counts: HashMap<usize, usize> = HashMap::new();
    for &fid in shell.faces() {
        let f = topo.face(fid).unwrap();
        let wire = topo.wire(f.outer_wire()).unwrap();
        for oe in wire.edges() {
            *edge_counts.entry(oe.edge().index()).or_insert(0) += 1;
        }
    }
    for (&edge_idx, &count) in &edge_counts {
        assert_eq!(
            count, 2,
            "edge {edge_idx} shared by {count} faces, expected 2 (manifold)"
        );
    }

    // Should have positive volume.
    let vol = crate::measure::solid_volume(&topo, solid, 0.1).unwrap();
    assert!(
        vol > 0.0,
        "closed sweep should have positive volume, got {vol}"
    );
}

/// Helper: create a square face with a smaller square hole (inner wire).
fn make_square_face_with_hole(topo: &mut Topology) -> FaceId {
    use brepkit_topology::edge::{Edge, EdgeCurve};
    use brepkit_topology::face::{Face, FaceSurface};
    use brepkit_topology::vertex::Vertex;
    use brepkit_topology::wire::{OrientedEdge, Wire};

    let lin = Tolerance::new().linear;

    // Outer square: 2x2 centered at origin in XY plane
    let ov0 = topo.add_vertex(Vertex::new(Point3::new(-1.0, -1.0, 0.0), lin));
    let ov1 = topo.add_vertex(Vertex::new(Point3::new(1.0, -1.0, 0.0), lin));
    let ov2 = topo.add_vertex(Vertex::new(Point3::new(1.0, 1.0, 0.0), lin));
    let ov3 = topo.add_vertex(Vertex::new(Point3::new(-1.0, 1.0, 0.0), lin));

    let oe0 = topo.add_edge(Edge::new(ov0, ov1, EdgeCurve::Line));
    let oe1 = topo.add_edge(Edge::new(ov1, ov2, EdgeCurve::Line));
    let oe2 = topo.add_edge(Edge::new(ov2, ov3, EdgeCurve::Line));
    let oe3 = topo.add_edge(Edge::new(ov3, ov0, EdgeCurve::Line));

    let outer_wire = topo.add_wire(
        Wire::new(
            vec![
                OrientedEdge::new(oe0, true),
                OrientedEdge::new(oe1, true),
                OrientedEdge::new(oe2, true),
                OrientedEdge::new(oe3, true),
            ],
            true,
        )
        .unwrap(),
    );

    // Inner square: 0.5x0.5 centered at origin (hole)
    let iv0 = topo.add_vertex(Vertex::new(Point3::new(-0.25, -0.25, 0.0), lin));
    let iv1 = topo.add_vertex(Vertex::new(Point3::new(0.25, -0.25, 0.0), lin));
    let iv2 = topo.add_vertex(Vertex::new(Point3::new(0.25, 0.25, 0.0), lin));
    let iv3 = topo.add_vertex(Vertex::new(Point3::new(-0.25, 0.25, 0.0), lin));

    let ie0 = topo.add_edge(Edge::new(iv0, iv1, EdgeCurve::Line));
    let ie1 = topo.add_edge(Edge::new(iv1, iv2, EdgeCurve::Line));
    let ie2 = topo.add_edge(Edge::new(iv2, iv3, EdgeCurve::Line));
    let ie3 = topo.add_edge(Edge::new(iv3, iv0, EdgeCurve::Line));

    let inner_wire = topo.add_wire(
        Wire::new(
            vec![
                OrientedEdge::new(ie0, true),
                OrientedEdge::new(ie1, true),
                OrientedEdge::new(ie2, true),
                OrientedEdge::new(ie3, true),
            ],
            true,
        )
        .unwrap(),
    );

    topo.add_face(Face::new(
        outer_wire,
        vec![inner_wire],
        FaceSurface::Plane {
            normal: Vec3::new(0.0, 0.0, 1.0),
            d: 0.0,
        },
    ))
}

#[test]
fn sweep_closed_path_with_inner_hole() {
    // Sweeping a profile with inner holes along a closed path should not panic.
    let mut topo = Topology::new();
    let profile = make_square_face_with_hole(&mut topo);
    let path = closed_circle_path(5.0);

    let solid = sweep(&mut topo, profile, &path).unwrap();

    let vol = crate::measure::solid_volume(&topo, solid, 0.1).unwrap();
    assert!(
        vol > 0.0,
        "closed sweep with inner hole should have positive volume, got {vol}"
    );
}

#[test]
fn sweep_smooth_closed_path() {
    // sweep_smooth delegates to sweep for closed paths.
    let mut topo = Topology::new();
    let profile = make_unit_square_face(&mut topo);
    let path = closed_circle_path(5.0);

    let solid = sweep_smooth(&mut topo, profile, &path).unwrap();

    let vol = crate::measure::solid_volume(&topo, solid, 0.1).unwrap();
    assert!(
        vol > 0.0,
        "smooth closed sweep should have positive volume, got {vol}"
    );
}

#[test]
fn sweep_cw_profile_produces_correct_solid() {
    let path = straight_z_path(3.0);
    crate::test_helpers::assert_cw_profile_produces_valid_solid(
        |topo, face| sweep(topo, face, &path).unwrap(),
        3.0,
        0.05,
    );
}

/// Translation invariance for CW-wound sweep.
#[test]
fn sweep_cw_profile_translation_invariant() {
    use brepkit_topology::test_utils::make_cw_unit_square_face;

    let mut topo1 = Topology::new();
    let face1 = make_cw_unit_square_face(&mut topo1);
    let path1 = straight_z_path(3.0);
    let solid1 = sweep(&mut topo1, face1, &path1).unwrap();
    let vol1 = crate::measure::solid_volume(&topo1, solid1, 0.1).unwrap();

    let mut topo2 = Topology::new();
    let face2 = make_cw_unit_square_face(&mut topo2);
    let path2 = straight_z_path(3.0);
    let solid2 = sweep(&mut topo2, face2, &path2).unwrap();
    crate::transform::transform_solid(
        &mut topo2,
        solid2,
        &brepkit_math::mat::Mat4::translation(1000.0, 1000.0, 1000.0),
    )
    .unwrap();
    let vol2 = crate::measure::solid_volume(&topo2, solid2, 0.1).unwrap();

    let rel_err = (vol1 - vol2).abs() / vol1.max(1e-12);
    assert!(
        rel_err < 0.01,
        "CW sweep volumes should match: origin={vol1}, translated={vol2}, \
             rel_err={rel_err:.2e}"
    );
}

/// Sweep a CW-wound profile along a NON-PARALLEL axis (X path, XY profile).
/// This exercises the `input_normal` negation fix — without it, the
/// `orthogonalize(input_normal, path_tangent)` up-hint is wrong and
/// the profile is flipped upside-down.
#[test]
fn sweep_cw_profile_nonparallel_axis() {
    use brepkit_topology::edge::{Edge, EdgeCurve};
    use brepkit_topology::face::Face;
    use brepkit_topology::vertex::Vertex;
    use brepkit_topology::wire::{OrientedEdge, Wire};

    let mut topo = Topology::new();
    let tol_val = 1e-7;

    // CW rectangle 1×2 on XY plane: (0,0)→(0,2)→(1,2)→(1,0)
    let v0 = topo.add_vertex(Vertex::new(Point3::new(0.0, 0.0, 0.0), tol_val));
    let v1 = topo.add_vertex(Vertex::new(Point3::new(0.0, 2.0, 0.0), tol_val));
    let v2 = topo.add_vertex(Vertex::new(Point3::new(1.0, 2.0, 0.0), tol_val));
    let v3 = topo.add_vertex(Vertex::new(Point3::new(1.0, 0.0, 0.0), tol_val));

    let e0 = topo.add_edge(Edge::new(v0, v1, EdgeCurve::Line));
    let e1 = topo.add_edge(Edge::new(v1, v2, EdgeCurve::Line));
    let e2 = topo.add_edge(Edge::new(v2, v3, EdgeCurve::Line));
    let e3 = topo.add_edge(Edge::new(v3, v0, EdgeCurve::Line));

    let wire = Wire::new(
        vec![
            OrientedEdge::new(e0, true),
            OrientedEdge::new(e1, true),
            OrientedEdge::new(e2, true),
            OrientedEdge::new(e3, true),
        ],
        true,
    )
    .unwrap();
    let wid = topo.add_wire(wire);

    // CW winding → Newell normal = -Z
    let face = topo.add_face(Face::new(
        wid,
        vec![],
        FaceSurface::Plane {
            normal: Vec3::new(0.0, 0.0, -1.0),
            d: 0.0,
        },
    ));

    // Sweep along +Z (profile normal is perpendicular to path → up-hint matters)
    let path = straight_z_path(5.0);
    let solid = sweep(&mut topo, face, &path).unwrap();

    // Expected: 1×2×5 = 10.0
    let vol = crate::measure::solid_volume(&topo, solid, 0.1).unwrap();
    assert!(
        (vol - 10.0).abs() < 0.5,
        "CW 1×2 rectangle swept along Z should produce volume ~10.0, got {vol}"
    );
}

// ── Miter sweep tests ──────────────────────────

/// Helper: create an L-shaped polyline path (two line segments with
/// a 90-degree turn).
fn l_shaped_path() -> NurbsCurve {
    // Degree-1 NURBS: (0,0,0)→(0,0,5)→(5,0,5). Path goes along +Z
    // then turns +X — perpendicular to the XY-plane unit square
    // profile so the swept cross-section has nonzero area.
    // Internal knot at t=0.5 creates a C0 kink.
    NurbsCurve::new(
        1,
        vec![0.0, 0.0, 0.5, 1.0, 1.0],
        vec![
            Point3::new(0.0, 0.0, 0.0),
            Point3::new(0.0, 0.0, 5.0),
            Point3::new(5.0, 0.0, 5.0),
        ],
        vec![1.0, 1.0, 1.0],
    )
    .unwrap()
}

#[test]
fn detect_kinks_l_shaped_path() {
    let path = l_shaped_path();
    let kinks = detect_kinks(&path);
    assert_eq!(kinks.len(), 1, "L-shaped path should have one kink");
    assert!((kinks[0] - 0.5).abs() < 1e-6, "kink should be at t=0.5");
}

#[test]
fn detect_kinks_no_kinks_for_smooth_path() {
    // A smooth cubic NURBS with no internal knot multiplicity.
    let path = quarter_circle_xz_path(5.0);
    let kinks = detect_kinks(&path);
    assert!(kinks.is_empty(), "smooth path should have no kinks");
}

#[test]
fn detect_kinks_straight_line_no_kinks() {
    let path = straight_z_path(5.0);
    let kinks = detect_kinks(&path);
    assert!(kinks.is_empty(), "straight line should have no kinks");
}

#[test]
fn detect_kinks_collinear_polyline_no_kinks() {
    // A polyline with 3 collinear points — no tangent change.
    let path = NurbsCurve::new(
        1,
        vec![0.0, 0.0, 0.5, 1.0, 1.0],
        vec![
            Point3::new(0.0, 0.0, 0.0),
            Point3::new(5.0, 0.0, 0.0),
            Point3::new(10.0, 0.0, 0.0),
        ],
        vec![1.0, 1.0, 1.0],
    )
    .unwrap();
    let kinks = detect_kinks(&path);
    assert!(kinks.is_empty(), "collinear polyline should have no kinks");
}

#[test]
fn sweep_miter_l_shaped_path() {
    let mut topo = Topology::new();
    let profile = make_unit_square_face(&mut topo);
    let path = l_shaped_path();

    let options = SweepOptions {
        corner_mode: SweepCornerMode::Miter,
        ..Default::default()
    };
    let solid = sweep_with_options(&mut topo, profile, &path, &options).unwrap();

    let vol = crate::measure::solid_volume(&topo, solid, 0.1).unwrap();
    assert!(
        vol > 0.0,
        "miter sweep should have positive volume, got {vol}"
    );

    // Verify manifold: every edge shared by exactly 2 faces.
    let solid_data = topo.solid(solid).unwrap();
    let shell = topo.shell(solid_data.outer_shell()).unwrap();

    let mut edge_counts: HashMap<usize, usize> = HashMap::new();
    for &fid in shell.faces() {
        let f = topo.face(fid).unwrap();
        let wire = topo.wire(f.outer_wire()).unwrap();
        for oe in wire.edges() {
            *edge_counts.entry(oe.edge().index()).or_insert(0) += 1;
        }
    }
    for (&edge_idx, &count) in &edge_counts {
        assert_eq!(
            count, 2,
            "edge {edge_idx} shared by {count} faces, expected 2 (manifold)"
        );
    }
}

#[test]
fn sweep_miter_l_shaped_volume_correct() {
    // L-shaped path: (0,0,0)→(0,0,5)→(5,0,5) with 1×1 square profile.
    // With miter, the volume is two rectangular prisms joined at a 45-degree
    // miter plane. Each leg has length ~5, profile area ~1, so total is
    // roughly 10 (minus/plus the miter overlap which approximately cancels).
    let mut topo = Topology::new();
    let profile = make_unit_square_face(&mut topo);
    let path = l_shaped_path();

    let options = SweepOptions {
        corner_mode: SweepCornerMode::Miter,
        ..Default::default()
    };
    let solid = sweep_with_options(&mut topo, profile, &path, &options).unwrap();

    let vol = crate::measure::solid_volume(&topo, solid, 0.1).unwrap();

    // The exact volume depends on the miter geometry, but should be
    // in a reasonable range for a 1×1 profile swept along two 5-unit legs.
    assert!(
        vol > 5.0 && vol < 15.0,
        "L-sweep volume should be roughly 10 (two 5-unit legs), got {vol}"
    );
}

#[test]
fn sweep_miter_u_shaped_path() {
    // U-shaped path: 3 segments with 2 kinks, in ZX plane so
    // the XY-plane profile has nonzero cross-section area.
    let path = NurbsCurve::new(
        1,
        vec![0.0, 0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0, 1.0],
        vec![
            Point3::new(0.0, 0.0, 0.0),
            Point3::new(0.0, 0.0, 5.0),
            Point3::new(5.0, 0.0, 5.0),
            Point3::new(5.0, 0.0, 0.0),
        ],
        vec![1.0, 1.0, 1.0, 1.0],
    )
    .unwrap();

    let mut topo = Topology::new();
    let profile = make_unit_square_face(&mut topo);

    let options = SweepOptions {
        corner_mode: SweepCornerMode::Miter,
        ..Default::default()
    };
    let solid = sweep_with_options(&mut topo, profile, &path, &options).unwrap();

    let vol = crate::measure::solid_volume(&topo, solid, 0.1).unwrap();
    assert!(
        vol > 0.0,
        "U-shaped miter sweep should have positive volume, got {vol}"
    );
}

#[test]
fn sweep_miter_fallback_smooth_on_no_kinks() {
    // Smooth path has no kinks — miter mode should fall back to smooth.
    let mut topo = Topology::new();
    let profile = make_unit_square_face(&mut topo);
    let path = straight_z_path(5.0);

    let options = SweepOptions {
        corner_mode: SweepCornerMode::Miter,
        ..Default::default()
    };
    let solid = sweep_with_options(&mut topo, profile, &path, &options).unwrap();

    let vol = crate::measure::solid_volume(&topo, solid, 0.1).unwrap();
    assert!(
        (vol - 5.0).abs() < 1.0,
        "straight-path miter fallback should produce volume ~5.0, got {vol}"
    );
}

// ── densify_path_points (rectLipSweep non-square overshoot regression) ──

/// Sample a rounded-rectangle boundary the way `sweepAlongEdges` does: line
/// edges contribute only endpoints; corner arcs contribute interior samples.
/// This reproduces the under-sampled long-edge condition that made the global
/// interpolating path fit overshoot on non-square spines.
fn sparse_rounded_rect(half_x: f64, half_y: f64, r: f64) -> Vec<Point3> {
    let (cx, cy) = (half_x - r, half_y - r);
    let hp = std::f64::consts::FRAC_PI_2;
    let corners = [
        (cx, -cy, -hp, 0.0),
        (cx, cy, 0.0, hp),
        (-cx, cy, hp, std::f64::consts::PI),
        (-cx, -cy, std::f64::consts::PI, 3.0 * hp),
    ];
    let mut pts: Vec<Point3> = Vec::new();
    let push = |p: Point3, pts: &mut Vec<Point3>| {
        if pts.last().is_none_or(|l: &Point3| (*l - p).length() > 1e-7) {
            pts.push(p);
        }
    };
    for &(ccx, ccy, a0, a1) in &corners {
        for k in 0..=8 {
            let a = a0 + (a1 - a0) * f64::from(k) / 8.0;
            push(
                Point3::new(ccx + r * a.cos(), ccy + r * a.sin(), 0.0),
                &mut pts,
            );
        }
    }
    if let Some(first) = pts.first().copied() {
        push(first, &mut pts);
    }
    pts
}

fn path_x_extent(path: &NurbsCurve) -> (f64, f64) {
    let mut lo = f64::INFINITY;
    let mut hi = f64::NEG_INFINITY;
    for k in 0..=400 {
        let x = path.evaluate(f64::from(k) / 400.0).x();
        lo = lo.min(x);
        hi = hi.max(x);
    }
    (lo, hi)
}

#[test]
fn densify_fixes_nonsquare_spine_overshoot() {
    use brepkit_math::nurbs::fitting::interpolate;

    // 42 x 126 rounded rect → half 21 x 63, r 3.75. Long edges (~118mm) are
    // sampled only at endpoints, so the raw fit overshoots far past x = ±21.
    let pts = sparse_rounded_rect(21.0, 63.0, 3.75);

    let raw = interpolate(&pts, 3).unwrap();
    let (_, raw_hi) = path_x_extent(&raw);
    assert!(
        raw_hi > 50.0,
        "expected the un-densified fit to overshoot (got x_max {raw_hi}); \
         if this no longer overshoots the regression guard is moot"
    );

    let dense = densify_path_points(&pts);
    let fixed = interpolate(&dense, 3).unwrap();
    let (fixed_lo, fixed_hi) = path_x_extent(&fixed);
    assert!(
        fixed_hi < 22.0 && fixed_lo > -22.0,
        "densified fit must stay near the true ±21 bound, got x[{fixed_lo:.2},{fixed_hi:.2}]"
    );
}

#[test]
fn densify_leaves_uniform_polyline_unchanged() {
    // Evenly spaced points: no gap exceeds the median multiple, so no inserts.
    let pts: Vec<Point3> = (0..10)
        .map(|i| Point3::new(f64::from(i), 0.0, 0.0))
        .collect();
    assert_eq!(densify_path_points(&pts).len(), pts.len());
}

#[test]
fn densify_short_input_is_identity() {
    let pts = vec![Point3::new(0.0, 0.0, 0.0), Point3::new(10.0, 0.0, 0.0)];
    assert_eq!(densify_path_points(&pts), pts);
}

#[test]
fn sweep_planar_profile_caps_are_planar() {
    // Regression: a planar profile must still produce flat `Plane` caps. The
    // path is curved (but starts tangent +Z) so the general sweep runs — a
    // straight path short-circuits to extrude and skips the cap code under test.
    let mut topo = Topology::new();
    let profile = make_square(&mut topo, 2.0);
    let path = NurbsCurve::new(
        2,
        vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
        vec![
            Point3::new(0.0, 0.0, 0.0),
            Point3::new(0.0, 0.0, 3.0),
            Point3::new(2.0, 0.0, 5.0),
        ],
        vec![1.0, 1.0, 1.0],
    )
    .unwrap();
    let solid = sweep(&mut topo, profile, &path).unwrap();
    let sh = topo
        .shell(topo.solid(solid).unwrap().outer_shell())
        .unwrap();
    let planar = sh
        .faces()
        .iter()
        .filter(|&&fid| topo.face(fid).unwrap().surface().is_planar())
        .count();
    assert_eq!(planar, sh.faces().len(), "planar sweep stays all-planar");
}

#[test]
fn sweep_nonplanar_saddle_profile_is_valid_solid() {
    // A non-planar (saddle) profile swept along a straight path: previously
    // rejected by the planar-only gate, now closed with bilinear caps.
    let mut topo = Topology::new();
    let profile = crate::test_helpers::make_saddle_profile(&mut topo, 2.0);
    assert!(
        !topo.face(profile).unwrap().surface().is_planar(),
        "saddle profile must be a non-planar face"
    );
    let path = straight_z_path(6.0);
    let solid = sweep(&mut topo, profile, &path).unwrap();

    let sh = topo
        .shell(topo.solid(solid).unwrap().outer_shell())
        .unwrap();
    let nurbs_caps = sh
        .faces()
        .iter()
        .filter(|&&fid| matches!(topo.face(fid).unwrap().surface(), FaceSurface::Nurbs(_)))
        .count();
    assert_eq!(
        nurbs_caps, 2,
        "non-planar ring caps are bilinear NURBS fills"
    );

    assert!(
        crate::validate::validate_solid(&topo, solid)
            .unwrap()
            .is_valid(),
        "non-planar sweep must be a valid solid"
    );
    // ~4×4 cross-section over a length-6 path → ≈96; bilinear caps don't overfill.
    let vol = crate::measure::solid_volume(&topo, solid, 0.1).unwrap();
    assert!(
        vol > 85.0 && vol < 110.0,
        "non-planar sweep volume out of expected range, got {vol}"
    );
}

#[test]
fn sweep_smooth_straight_path_exact_volume() {
    // Regression for the rail bug: sweep_smooth built per-face (duplicated)
    // straight rails and left the NURBS side faces with inward normals, giving a
    // non-manifold shell whose volume integrated to 1/3 of the true value. A
    // 2×2 square swept 6 along +Z is an exact 24-volume prism.
    let mut topo = Topology::new();
    let profile = make_square(&mut topo, 2.0);
    let solid = sweep_smooth(&mut topo, profile, &straight_z_path(6.0)).unwrap();

    assert!(
        crate::validate::validate_solid(&topo, solid)
            .unwrap()
            .is_valid(),
        "smooth sweep must be a valid (manifold) solid"
    );
    let vol = crate::measure::solid_volume(&topo, solid, 0.05).unwrap();
    assert!(
        (vol - 24.0).abs() / 24.0 < 0.01,
        "straight smooth-sweep prism volume should be 24, got {vol}"
    );
}

#[test]
fn sweep_smooth_gentle_curve_is_valid_with_sane_volume() {
    // A gently curved path (initial tangent +Z, bending toward +X): the shared
    // rails keep the shell manifold and the volume near the swept prism
    // (~profile area 4 × arc length ~6.3 ≈ 25), not 1/3 of it.
    let mut topo = Topology::new();
    let profile = make_square(&mut topo, 2.0);
    let path = NurbsCurve::new(
        2,
        vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0],
        vec![
            Point3::new(0.0, 0.0, 0.0),
            Point3::new(0.0, 0.0, 3.0),
            Point3::new(1.5, 0.0, 6.0),
        ],
        vec![1.0, 1.0, 1.0],
    )
    .unwrap();
    let solid = sweep_smooth(&mut topo, profile, &path).unwrap();

    assert!(
        crate::validate::validate_solid(&topo, solid)
            .unwrap()
            .is_valid(),
        "curved smooth sweep must be a valid solid"
    );
    let vol = crate::measure::solid_volume(&topo, solid, 0.05).unwrap();
    assert!(
        vol > 24.0 && vol < 26.0,
        "gently curved smooth-sweep volume should be ~25, got {vol}"
    );
}

#[test]
fn sweep_edge_on_profile_is_auto_oriented() {
    // An XY-plane square (normal +Z) swept along a +X path is "edge-on": its
    // plane contains the path tangent. Before profile auto-orientation this
    // collapsed to a flat, zero-volume ribbon; now the profile's 2D shape is
    // placed perpendicular to the path, giving a proper 1×1×5 prism (volume 5).
    let mut topo = Topology::new();
    let profile = make_square(&mut topo, 1.0);
    let path = NurbsCurve::new(
        1,
        vec![0.0, 0.0, 1.0, 1.0],
        vec![Point3::new(0.0, 0.0, 0.0), Point3::new(5.0, 0.0, 0.0)],
        vec![1.0, 1.0],
    )
    .unwrap();
    let solid = sweep(&mut topo, profile, &path).unwrap();
    assert!(
        crate::validate::validate_solid(&topo, solid)
            .unwrap()
            .is_valid(),
        "edge-on sweep must be a valid solid"
    );
    let vol = crate::measure::solid_volume(&topo, solid, 0.05).unwrap();
    assert!(
        (vol - 5.0).abs() / 5.0 < 0.02,
        "edge-on profile should sweep to a 1×1×5 prism (volume 5), got {vol}"
    );
}

#[test]
fn sweep_smooth_nonplanar_saddle_is_valid_solid() {
    // sweep_smooth previously gated non-planar profiles; with the rail fix,
    // auto-orientation, and boundary-fill caps it now sweeps them. A saddle
    // (~4×4) swept 6 along +Z is a prism of volume ~96 (the bilinear caps fill
    // the non-planar end rings).
    let mut topo = Topology::new();
    let profile = crate::test_helpers::make_saddle_profile(&mut topo, 2.0);
    assert!(!topo.face(profile).unwrap().surface().is_planar());
    let solid = sweep_smooth(&mut topo, profile, &straight_z_path(6.0)).unwrap();
    assert!(
        crate::validate::validate_solid(&topo, solid)
            .unwrap()
            .is_valid(),
        "non-planar smooth sweep must be a valid solid"
    );
    let vol = crate::measure::solid_volume(&topo, solid, 0.1).unwrap();
    assert!(
        (vol - 96.0).abs() / 96.0 < 0.05,
        "non-planar smooth sweep volume should be ~96, got {vol}"
    );
}

#[test]
fn sweep_with_options_nonplanar_saddle_is_valid_solid() {
    let mut topo = Topology::new();
    let profile = crate::test_helpers::make_saddle_profile(&mut topo, 2.0);
    let solid = sweep_with_options(
        &mut topo,
        profile,
        &straight_z_path(6.0),
        &SweepOptions::default(),
    )
    .unwrap();
    assert!(
        crate::validate::validate_solid(&topo, solid)
            .unwrap()
            .is_valid(),
        "non-planar sweep_with_options must be a valid solid"
    );
    let vol = crate::measure::solid_volume(&topo, solid, 0.1).unwrap();
    assert!(
        (vol - 96.0).abs() / 96.0 < 0.05,
        "non-planar sweep_with_options volume should be ~96, got {vol}"
    );
}

#[test]
fn multi_section_sweep_nonplanar_sections_is_valid_solid() {
    // multi_section places each section perpendicular to the spine and lofts
    // them; loft handles non-planar sections, so saddle sections now work
    // (previously gated by "multi-section sweep profiles must be planar").
    let mut topo = Topology::new();
    let a = crate::test_helpers::make_saddle_profile(&mut topo, 2.0);
    let b = crate::test_helpers::make_saddle_profile(&mut topo, 2.0);
    let solid = multi_section_sweep(
        &mut topo,
        &straight_z_path(6.0),
        &[(a, 0.0), (b, 1.0)],
        true,
    )
    .unwrap();
    assert!(
        crate::validate::validate_solid(&topo, solid)
            .unwrap()
            .is_valid(),
        "non-planar multi-section sweep must be a valid solid"
    );
    let vol = crate::measure::solid_volume(&topo, solid, 0.1).unwrap();
    assert!(
        vol > 80.0 && vol < 110.0,
        "non-planar multi-section sweep volume should be ~96, got {vol}"
    );
}