ogeom-offset 0.3.2

Offsetting, shelling, sweeping, lofting and draft
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
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
//! Pipes and lofts, against Pappus and the frustum formulae.
#![allow(clippy::unwrap_used, clippy::expect_used, reason = "test code")]

use ogeom_core::Tolerances;
use ogeom_geom::Curve3d as _;
use ogeom_math::{Circle, Frame, Point};
use ogeom_topo::{Filter, ShapeType, explore};

const T: Tolerances = Tolerances::millimetres();

fn fine() -> ogeom_mesh::Deflection {
    ogeom_mesh::Deflection {
        chord: 1e-4,
        ..ogeom_mesh::Deflection::default()
    }
}

fn volume(model: &ogeom_topo::Model, shape: &ogeom_topo::Shape) -> f64 {
    ogeom_algo::volume_properties(model, shape, fine(), T)
        .unwrap()
        .mass
}

#[test]
fn a_straight_pipe_is_a_cylinder() {
    let mut model = ogeom_topo::Model::new();
    let line = ogeom_geom::LineCurve::segment(Point::ORIGIN, Point::new(0.0, 0.0, 2.0), T).unwrap();
    let curve = ogeom_geom::Curve::Line(line);
    let domain = curve.domain();
    let spine = ogeom_algo::make_edge(&mut model, curve, domain, T)
        .unwrap()
        .shape;

    let result = ogeom_offset::make_pipe(&mut model, &spine, 0.3, T).unwrap();
    let expected = core::f64::consts::PI * 0.09 * 2.0;
    let measured = volume(&model, &result.shape);
    assert!(
        (measured - expected).abs() < 5e-4,
        "straight pipe volume {measured} against {expected}"
    );
    assert!(!result.history.generated(&spine).is_empty());
}

#[test]
fn a_quarter_arc_pipe_is_a_torus_segment() {
    let mut model = ogeom_topo::Model::new();
    let circle = Circle::new(Frame::WORLD, 2.0, T).unwrap();
    let curve = ogeom_geom::Curve::Circle(ogeom_geom::CircleCurve::new(circle));
    let spine = ogeom_algo::make_edge(&mut model, curve, (0.0, core::f64::consts::FRAC_PI_2), T)
        .unwrap()
        .shape;

    let result = ogeom_offset::make_pipe(&mut model, &spine, 0.3, T).unwrap();
    let diagnosis = ogeom_algo::check(&model, &result.shape, T).unwrap();
    assert!(diagnosis.is_valid(), "{:?}", diagnosis.problems);

    // Pappus: the tube's area rides the spine's length.
    let expected = core::f64::consts::PI * 0.09 * 2.0 * core::f64::consts::FRAC_PI_2;
    let measured = volume(&model, &result.shape);
    assert!(
        (measured - expected).abs() < 1e-3,
        "arc pipe volume {measured} against {expected}"
    );

    // Four faces: two half tubes and two meridian caps.
    let faces = ogeom_topo::explore(
        &model,
        &result.shape,
        Filter::OfType(ogeom_topo::ShapeType::Face),
    )
    .unwrap();
    assert_eq!(faces.len(), 4);
}

#[test]
fn a_closed_circular_pipe_is_the_whole_torus() {
    let mut model = ogeom_topo::Model::new();
    let circle = Circle::new(Frame::WORLD, 2.0, T).unwrap();
    let curve = ogeom_geom::Curve::Circle(ogeom_geom::CircleCurve::new(circle));
    let domain = curve.domain();
    let spine = ogeom_algo::make_edge(&mut model, curve, domain, T)
        .unwrap()
        .shape;

    let result = ogeom_offset::make_pipe(&mut model, &spine, 0.3, T).unwrap();
    let expected = 2.0 * core::f64::consts::PI * core::f64::consts::PI * 2.0 * 0.09;
    let measured = volume(&model, &result.shape);
    assert!(
        (measured - expected).abs() < 2e-3,
        "torus pipe volume {measured} against {expected}"
    );
}

#[test]
fn a_pipe_that_swallows_its_spine_is_refused() {
    let mut model = ogeom_topo::Model::new();
    let circle = Circle::new(Frame::WORLD, 0.5, T).unwrap();
    let curve = ogeom_geom::Curve::Circle(ogeom_geom::CircleCurve::new(circle));
    let domain = curve.domain();
    let spine = ogeom_algo::make_edge(&mut model, curve, domain, T)
        .unwrap()
        .shape;
    assert!(ogeom_offset::make_pipe(&mut model, &spine, 0.6, T).is_err());
}

fn square(model: &mut ogeom_topo::Model, half: f64, z: f64) -> ogeom_topo::Shape {
    let corners = [
        Point::new(-half, -half, z),
        Point::new(half, -half, z),
        Point::new(half, half, z),
        Point::new(-half, half, z),
    ];
    ogeom_algo::make_polygon(model, &corners, true, T)
        .unwrap()
        .shape
}

#[test]
fn a_polygonal_loft_is_the_frustum_pyramid() {
    let mut model = ogeom_topo::Model::new();
    let bottom = square(&mut model, 1.0, 0.0);
    let top = square(&mut model, 0.5, 2.0);

    let result = ogeom_offset::make_loft(&mut model, &bottom, &top, T).unwrap();
    let diagnosis = ogeom_algo::check(&model, &result.shape, T).unwrap();
    assert!(diagnosis.is_valid(), "{:?}", diagnosis.problems);

    // The pyramidal frustum: h/3 (A1 + A2 + sqrt(A1 A2)).
    let expected = 2.0 / 3.0 * (4.0 + 1.0 + 2.0);
    let measured = volume(&model, &result.shape);
    assert!(
        (measured - expected).abs() < 1e-9,
        "polygonal loft volume {measured} against {expected}"
    );
    assert!(!result.history.generated(&bottom).is_empty());
}

#[test]
fn a_circular_loft_is_the_cone_frustum() {
    let mut model = ogeom_topo::Model::new();
    let ring = |model: &mut ogeom_topo::Model, r: f64, z: f64| {
        let frame = Frame::new(
            Point::new(0.0, 0.0, z),
            ogeom_math::Direction::Z,
            ogeom_math::Direction::X,
            T,
        )
        .unwrap();
        let circle = Circle::new(frame, r, T).unwrap();
        let curve = ogeom_geom::Curve::Circle(ogeom_geom::CircleCurve::new(circle));
        let domain = curve.domain();
        let edge = ogeom_algo::make_edge(model, curve, domain, T)
            .unwrap()
            .shape;
        ogeom_algo::make_wire(model, std::slice::from_ref(&edge), T)
            .unwrap()
            .shape
    };
    let bottom = ring(&mut model, 1.0, 0.0);
    let top = ring(&mut model, 0.5, 2.0);

    let result = ogeom_offset::make_loft(&mut model, &bottom, &top, T).unwrap();
    let pi = core::f64::consts::PI;
    let expected = pi * 2.0 / 3.0 * 0.5_f64.mul_add(0.5, 1.0f64.mul_add(1.0, 1.0 * 0.5));
    let measured = volume(&model, &result.shape);
    assert!(
        (measured - expected).abs() < 1e-3,
        "circular loft volume {measured} against {expected}"
    );
}

#[test]
fn a_twisted_loft_s_walls_are_bilinear_and_measure_as_the_prismoid() {
    let mut model = ogeom_topo::Model::new();
    let bottom = square(&mut model, 1.0, 0.0);
    // The top square rotated 45 degrees and smaller: every wall is skew,
    // and each is the bilinear patch between its two segments.
    let corners = [
        Point::new(0.0, -0.7, 2.0),
        Point::new(0.7, 0.0, 2.0),
        Point::new(0.0, 0.7, 2.0),
        Point::new(-0.7, 0.0, 2.0),
    ];
    let top = ogeom_algo::make_polygon(&mut model, &corners, true, T)
        .unwrap()
        .shape;
    let result = ogeom_offset::make_loft(&mut model, &bottom, &top, T).unwrap();
    // A ruled solid's section area is quadratic in height, so the
    // prismoid formula is exact: h (A0 + 4 Amid + A1) / 6, the mid section
    // the polygon of the corresponding corners' midpoints.
    let low = [
        Point::new(-1.0, -1.0, 0.0),
        Point::new(1.0, -1.0, 0.0),
        Point::new(1.0, 1.0, 0.0),
        Point::new(-1.0, 1.0, 0.0),
    ];
    let shoelace = |c: &[Point]| -> f64 {
        (0..c.len())
            .map(|i| {
                let (a, b) = (c[i], c[(i + 1) % c.len()]);
                a.x * b.y - b.x * a.y
            })
            .sum::<f64>()
            .abs()
            / 2.0
    };
    let mid: Vec<Point> = low
        .iter()
        .zip(&corners)
        .map(|(a, b)| a.midpoint(*b))
        .collect();
    let (a0, a_mid, a1) = (shoelace(&low), shoelace(&mid), shoelace(&corners));
    let expected = 2.0 * (a0 + 4.0 * a_mid + a1) / 6.0;
    let measured = volume(&model, &result.shape);
    assert!(
        (measured - expected).abs() < expected * 5e-3,
        "twisted loft volume {measured} against the prismoid's {expected}"
    );
}

#[test]
fn a_skinned_loft_through_cone_sections_measures_as_the_frustum() {
    let mut model = ogeom_topo::Model::new();
    let ring = |model: &mut ogeom_topo::Model, r: f64, z: f64| {
        let frame = Frame::new(
            Point::new(0.0, 0.0, z),
            ogeom_math::Direction::Z,
            ogeom_math::Direction::X,
            T,
        )
        .unwrap();
        let circle = Circle::new(frame, r, T).unwrap();
        let curve = ogeom_geom::Curve::Circle(ogeom_geom::CircleCurve::new(circle));
        let domain = curve.domain();
        let edge = ogeom_algo::make_edge(model, curve, domain, T)
            .unwrap()
            .shape;
        ogeom_algo::make_wire(model, std::slice::from_ref(&edge), T)
            .unwrap()
            .shape
    };
    let sections = [
        ring(&mut model, 1.0, 0.0),
        ring(&mut model, 0.75, 1.0),
        ring(&mut model, 0.5, 2.0),
    ];
    let result = ogeom_offset::make_loft_skinned(&mut model, &sections, 1e-3, T).unwrap();
    let diagnosis = ogeom_algo::check(&model, &result.shape, T).unwrap();
    assert!(diagnosis.is_valid(), "{:?}", diagnosis.problems);

    // Linear radii through cone sections: the skin reproduces the frustum.
    let pi = core::f64::consts::PI;
    let expected = pi * 2.0 / 3.0 * (1.0 + 0.5 + 0.25);
    let measured = volume(&model, &result.shape);
    // A skin at its own stated error: the volume deficit is the fitted
    // sections riding just inside their circles.
    assert!(
        (measured - expected).abs() < 1e-2,
        "skinned frustum volume {measured} against {expected}"
    );
}

#[test]
fn a_pipe_along_a_free_form_spine_holds_pappus() {
    let mut model = ogeom_topo::Model::new();
    // A gentle S in the xz plane.
    let spine_curve = ogeom_geom::Curve::BSpline(
        ogeom_geom::BSplineCurve::new(
            ogeom_math::KnotVector::new(vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], 3).unwrap(),
            vec![
                Point::new(0.0, 0.0, 0.0),
                Point::new(2.0, 0.0, 1.0),
                Point::new(4.0, 0.0, -1.0),
                Point::new(6.0, 0.0, 0.0),
            ],
            T,
        )
        .unwrap(),
    );
    let domain = ogeom_geom::Curve3d::domain(&spine_curve);
    let spine = ogeom_algo::make_edge(&mut model, spine_curve.clone(), domain, T)
        .unwrap()
        .shape;
    let r = 0.2;
    let result = ogeom_offset::make_pipe_skinned(&mut model, &spine, r, 1e-4, T).unwrap();
    let diagnosis = ogeom_algo::check(&model, &result.shape, T).unwrap();
    assert!(diagnosis.is_valid(), "{:?}", diagnosis.problems);

    // Pappus for a rotation-minimizing tube: area times spine length, to
    // second order in curvature times radius.
    let length = ogeom_algo::curve_length(&spine_curve, domain, T).unwrap();
    let pi = core::f64::consts::PI;
    let expected = pi * r * r * length;
    let measured = volume(&model, &result.shape);
    assert!(
        (measured - expected).abs() < expected * 0.01,
        "free-form pipe volume {measured} against {expected}"
    );
    assert!(!result.history.generated(&spine).is_empty());
}

/// A square profile face of side `side`, square to `tangent` at `centre`.
fn square_profile(
    model: &mut ogeom_topo::Model,
    centre: ogeom_math::Point,
    tangent: ogeom_math::Vector,
    side: f64,
) -> ogeom_topo::Shape {
    use ogeom_math::Direction;
    let normal = Direction::new(tangent, T).unwrap();
    let plane = ogeom_math::Plane::through(centre, normal);
    let frame = plane.frame();
    let h = side / 2.0;
    let corners: Vec<ogeom_math::Point> = [(-h, -h), (h, -h), (h, h), (-h, h)]
        .iter()
        .map(|(a, b)| centre + frame.x().vector() * *a + frame.y().vector() * *b)
        .collect();
    let wire = ogeom_algo::make_polygon(model, &corners, true, T)
        .unwrap()
        .shape;
    let surface: ogeom_geom::SurfaceGeometry =
        ogeom_geom::PlaneSurface::over(plane, (-side * 2.0, side * 2.0), (-side * 2.0, side * 2.0))
            .unwrap()
            .into();
    ogeom_algo::make_face(model, surface, std::slice::from_ref(&wire), T)
        .unwrap()
        .shape
}

/// The quarter arc of radius `r` about the origin in the xy plane, starting
/// at `(r, 0, 0)` heading `+y`.
fn quarter_arc(model: &mut ogeom_topo::Model, r: f64) -> ogeom_topo::Shape {
    let circle = ogeom_math::Circle::new(Frame::WORLD, r, T).unwrap();
    let curve: ogeom_geom::Curve = ogeom_geom::CircleCurve::new(circle).into();
    ogeom_algo::make_edge(model, curve, (0.0, core::f64::consts::FRAC_PI_2), T)
        .unwrap()
        .shape
}

#[test]
fn a_square_face_along_an_arc_sweeps_the_volume_pappus_names() {
    let mut model = ogeom_topo::Model::new();
    let r = 20.0;
    let spine = quarter_arc(&mut model, r);
    let start = Point::new(r, 0.0, 0.0);
    let profile = square_profile(&mut model, start, ogeom_math::Vector::Y, 4.0);

    let result =
        ogeom_offset::make_pipe_shell(&mut model, &profile, &spine, false, 1e-3, T).unwrap();
    let diagnosis = ogeom_algo::check(&model, &result.shape, T).unwrap();
    assert!(diagnosis.is_valid(), "{:?}", diagnosis.problems);

    // Pappus: the centroid rides the spine, so the volume is area times the
    // arc's own length.
    let expected = 16.0 * (core::f64::consts::FRAC_PI_2 * r);
    let measured = ogeom_algo::volume_properties(
        &model,
        &result.shape,
        ogeom_mesh::Deflection::with_chord(1e-3).unwrap(),
        T,
    )
    .unwrap()
    .mass;
    assert!(
        (measured - expected).abs() / expected < 0.01,
        "pipe shell volume {measured} against {expected}"
    );
    assert!(!result.history.generated(&spine).is_empty());
    assert!(!result.history.generated(&profile).is_empty());
}

#[test]
fn a_triangle_along_a_helix_makes_a_thread() {
    use ogeom_geom::Curve3d as _;
    let mut model = ogeom_topo::Model::new();
    let helix = ogeom_geom::HelixCurve::new(Frame::WORLD, 5.0, 4.0, 2.0).unwrap();
    let curve: ogeom_geom::Curve = helix.into();
    let domain = curve.domain();
    let length = {
        // Chord-sum over a fine sampling: the closed form is the hypotenuse
        // law, but measuring it keeps the test honest about the curve.
        let mut sum = 0.0;
        let mut last = curve.point_at(domain.0, T).unwrap();
        for i in 1..=512 {
            let t = domain.0 + (domain.1 - domain.0) * f64::from(i) / 512.0;
            let p = curve.point_at(t, T).unwrap();
            sum += last.distance(p);
            last = p;
        }
        sum
    };
    let start = curve.point_at(domain.0, T).unwrap();
    let tangent = curve.d1_at(domain.0, T).unwrap();
    let spine = ogeom_algo::make_edge(&mut model, curve, domain, T)
        .unwrap()
        .shape;

    // A triangular wire centred on the spine, square to it: the thread form.
    let normal = ogeom_math::Direction::new(tangent, T).unwrap();
    let plane = ogeom_math::Plane::through(start, normal);
    let frame = plane.frame();
    let corners: Vec<Point> = [(0.6, 0.0), (-0.3, 0.45), (-0.3, -0.45)]
        .iter()
        .map(|(a, b)| start + frame.x().vector() * *a + frame.y().vector() * *b)
        .collect();
    let profile = ogeom_algo::make_polygon(&mut model, &corners, true, T)
        .unwrap()
        .shape;

    let result =
        ogeom_offset::make_pipe_shell(&mut model, &profile, &spine, true, 1e-3, T).unwrap();
    let diagnosis = ogeom_algo::check(&model, &result.shape, T).unwrap();
    assert!(diagnosis.is_valid(), "{:?}", diagnosis.problems);

    // The triangle's area times the helix length brackets the thread: the
    // Frenet frames turn the profile with the spine, and the centroid rides
    // it, so the volume sits near the Pappus figure.
    let area = 0.9 * 0.45; // base 0.9, height 0.9, halved
    let expected = area * length;
    // Coarse deflection on purpose: a hundred-station helical skin at a
    // fine chord costs minutes and the claim here is a ten-percent band.
    let measured =
        ogeom_algo::volume_properties(&model, &result.shape, ogeom_mesh::Deflection::default(), T)
            .unwrap()
            .mass;
    assert!(
        (measured - expected).abs() / expected < 0.1,
        "thread volume {measured} against {expected}"
    );
}

#[test]
fn a_profile_with_a_hole_sweeps_the_hole() {
    let mut model = ogeom_topo::Model::new();
    let r = 20.0;
    let spine = quarter_arc(&mut model, r);
    let start = Point::new(r, 0.0, 0.0);

    // A square face with a round hole: the hole must ride the sweep.
    let normal = ogeom_math::Direction::new(ogeom_math::Vector::Y, T).unwrap();
    let plane = ogeom_math::Plane::through(start, normal);
    let frame = plane.frame();
    let h = 2.0;
    let corners: Vec<Point> = [(-h, -h), (h, -h), (h, h), (-h, h)]
        .iter()
        .map(|(a, b)| start + frame.x().vector() * *a + frame.y().vector() * *b)
        .collect();
    let outer = ogeom_algo::make_polygon(&mut model, &corners, true, T)
        .unwrap()
        .shape;
    let hole_circle =
        ogeom_math::Circle::new(ogeom_math::Frame::about(start, normal), 1.0, T).unwrap();
    let hole_curve: ogeom_geom::Curve = ogeom_geom::CircleCurve::new(hole_circle).into();
    let hole_domain = ogeom_geom::Curve3d::domain(&hole_curve);
    let hole_edge = ogeom_algo::make_edge(&mut model, hole_curve, hole_domain, T)
        .unwrap()
        .shape;
    let hole = ogeom_algo::make_wire(&mut model, std::slice::from_ref(&hole_edge), T)
        .unwrap()
        .shape;
    let surface: ogeom_geom::SurfaceGeometry =
        ogeom_geom::PlaneSurface::over(plane, (-8.0, 8.0), (-8.0, 8.0))
            .unwrap()
            .into();
    let profile = ogeom_algo::make_face(&mut model, surface, &[outer, hole], T)
        .unwrap()
        .shape;

    let result =
        ogeom_offset::make_pipe_shell(&mut model, &profile, &spine, false, 1e-3, T).unwrap();
    let diagnosis = ogeom_algo::check(&model, &result.shape, T).unwrap();
    assert!(diagnosis.is_valid(), "{:?}", diagnosis.problems);

    let pi = core::f64::consts::PI;
    let expected = (16.0 - pi) * (core::f64::consts::FRAC_PI_2 * r);
    let measured = ogeom_algo::volume_properties(
        &model,
        &result.shape,
        ogeom_mesh::Deflection::with_chord(1e-3).unwrap(),
        T,
    )
    .unwrap()
    .mass;
    assert!(
        (measured - expected).abs() / expected < 0.01,
        "holed pipe shell volume {measured} against {expected}"
    );
}

#[test]
fn a_frenet_frame_on_a_straight_spine_is_refused_by_name() {
    let mut model = ogeom_topo::Model::new();
    let line =
        ogeom_geom::LineCurve::segment(Point::new(0.0, 0.0, 0.0), Point::new(0.0, 10.0, 0.0), T)
            .unwrap();
    let curve: ogeom_geom::Curve = line.into();
    let domain = ogeom_geom::Curve3d::domain(&curve);
    let spine = ogeom_algo::make_edge(&mut model, curve, domain, T)
        .unwrap()
        .shape;
    let profile = square_profile(
        &mut model,
        Point::new(0.0, 0.0, 0.0),
        ogeom_math::Vector::Y,
        2.0,
    );
    let err =
        ogeom_offset::make_pipe_shell(&mut model, &profile, &spine, true, 1e-3, T).unwrap_err();
    assert!(err.to_string().contains("Frenet"), "{err}");
}

#[test]
fn a_leaning_pipe_shell_profile_is_refused_by_name() {
    let mut model = ogeom_topo::Model::new();
    let spine = quarter_arc(&mut model, 20.0);
    // The profile's plane contains the start tangent instead of crossing it.
    let profile = square_profile(
        &mut model,
        Point::new(20.0, 0.0, 0.0),
        ogeom_math::Vector::Z,
        4.0,
    );
    let err =
        ogeom_offset::make_pipe_shell(&mut model, &profile, &spine, false, 1e-3, T).unwrap_err();
    assert!(err.to_string().contains("leans"), "{err}");
}

#[test]
fn a_closed_loft_through_four_sections_is_a_watertight_ring() {
    // Four circles stood around a ring, each square to the ring's own
    // tangent, lofted closed: one face bounding itself both ways round, no
    // caps anywhere.
    let mut model = ogeom_topo::Model::new();
    let ring_r = 10.0;
    let mut sections = Vec::new();
    for i in 0..16 {
        let angle = core::f64::consts::TAU / 16.0 * f64::from(i);
        let centre = Point::new(ring_r * angle.cos(), ring_r * angle.sin(), 0.0);
        let tangent = ogeom_math::Vector::new(-angle.sin(), angle.cos(), 0.0);
        let normal = ogeom_math::Direction::new(tangent, T).unwrap();
        // Alignment is the caller's authorship: every section shares its
        // local axes, so the loop does not twist.
        let frame = Frame::new(centre, normal, ogeom_math::Direction::Z, T).unwrap();
        let circle = Circle::new(frame, 1.0, T).unwrap();
        let curve: ogeom_geom::Curve = ogeom_geom::CircleCurve::new(circle).into();
        let domain = curve.domain();
        let edge = ogeom_algo::make_edge(&mut model, curve, domain, T)
            .unwrap()
            .shape;
        sections.push(
            ogeom_algo::make_wire(&mut model, std::slice::from_ref(&edge), T)
                .unwrap()
                .shape,
        );
    }
    let result = ogeom_offset::make_loft_skinned_closed(&mut model, &sections, 2e-2, T).unwrap();
    let diagnosis = ogeom_algo::check(&model, &result.shape, T).unwrap();
    assert!(diagnosis.is_valid(), "{:?}", diagnosis.problems);

    // One face, closed both ways round.
    assert_eq!(
        explore(&model, &result.shape, Filter::OfType(ShapeType::Face))
            .unwrap()
            .len(),
        1
    );
    // Sixteen sections make the loop dense enough for the closed C1 solve;
    // the volume then sits close to the torus the ring approximates.
    let expected = core::f64::consts::PI * (core::f64::consts::TAU * ring_r);
    let measured = ogeom_algo::volume_properties(
        &model,
        &result.shape,
        ogeom_mesh::Deflection::with_chord(1e-3).unwrap(),
        T,
    )
    .unwrap()
    .mass;
    assert!(
        (measured - expected).abs() / expected < 0.05,
        "closed loft volume {measured} against {expected}"
    );
    for section in &sections {
        assert!(!result.history.generated(section).is_empty());
    }
}

#[test]
fn a_rectangle_lofted_to_a_point_is_the_pyramid_the_closed_form_names() {
    let mut model = ogeom_topo::Model::new();
    let corners = [
        Point::new(0.0, 0.0, 0.0),
        Point::new(4.0, 0.0, 0.0),
        Point::new(4.0, 3.0, 0.0),
        Point::new(0.0, 3.0, 0.0),
    ];
    let base = ogeom_algo::make_polygon(&mut model, &corners, true, T)
        .unwrap()
        .shape;
    // A skew apex on purpose: pyramid walls are triangles wherever it sits.
    let apex = ogeom_algo::make_vertex(&mut model, Point::new(1.0, 1.0, 6.0)).shape;
    let result = ogeom_offset::make_loft(&mut model, &base, &apex, T).unwrap();
    let diagnosis = ogeom_algo::check(&model, &result.shape, T).unwrap();
    assert!(diagnosis.is_valid(), "{:?}", diagnosis.problems);

    let expected = 4.0 * 3.0 * 6.0 / 3.0;
    let measured =
        ogeom_algo::volume_properties(&model, &result.shape, ogeom_mesh::Deflection::default(), T)
            .unwrap()
            .mass;
    assert!(
        (measured - expected).abs() < 1e-6,
        "pyramid volume {measured} against {expected}"
    );
    assert!(!result.history.generated(&base).is_empty());
    assert!(!result.history.generated(&apex).is_empty());
}

#[test]
fn a_circle_lofted_to_a_point_on_its_axis_is_a_cone() {
    let mut model = ogeom_topo::Model::new();
    let circle = Circle::new(Frame::WORLD, 2.0, T).unwrap();
    let curve: ogeom_geom::Curve = ogeom_geom::CircleCurve::new(circle).into();
    let domain = curve.domain();
    let ring = ogeom_algo::make_edge(&mut model, curve, domain, T)
        .unwrap()
        .shape;
    let base = ogeom_algo::make_wire(&mut model, std::slice::from_ref(&ring), T)
        .unwrap()
        .shape;
    let apex = ogeom_algo::make_vertex(&mut model, Point::new(0.0, 0.0, 5.0)).shape;
    let result = ogeom_offset::make_loft(&mut model, &base, &apex, T).unwrap();
    let diagnosis = ogeom_algo::check(&model, &result.shape, T).unwrap();
    assert!(diagnosis.is_valid(), "{:?}", diagnosis.problems);

    let pi = core::f64::consts::PI;
    let expected = pi * 4.0 * 5.0 / 3.0;
    let measured = ogeom_algo::volume_properties(
        &model,
        &result.shape,
        ogeom_mesh::Deflection::with_chord(1e-4).unwrap(),
        T,
    )
    .unwrap()
    .mass;
    assert!(
        (measured - expected).abs() < 1e-3,
        "cone volume {measured} against {expected}"
    );

    // Off the axis the cone is oblique, which is the skinned machinery's.
    let mut second = ogeom_topo::Model::new();
    let circle = Circle::new(Frame::WORLD, 2.0, T).unwrap();
    let curve: ogeom_geom::Curve = ogeom_geom::CircleCurve::new(circle).into();
    let domain = curve.domain();
    let ring = ogeom_algo::make_edge(&mut second, curve, domain, T)
        .unwrap()
        .shape;
    let base = ogeom_algo::make_wire(&mut second, std::slice::from_ref(&ring), T)
        .unwrap()
        .shape;
    let leaning = ogeom_algo::make_vertex(&mut second, Point::new(1.0, 0.0, 5.0)).shape;
    assert!(ogeom_offset::make_loft(&mut second, &base, &leaning, T).is_err());
}

#[test]
fn an_alignment_hint_untwists_a_loft() {
    // Two squares whose traversals start a corner apart: left to their own
    // starts the skin shears, with the hints it is the prism it should be.
    let build = |model: &mut ogeom_topo::Model, rotate: usize, z: f64| -> ogeom_topo::Shape {
        let corners = [
            Point::new(0.0, 0.0, z),
            Point::new(2.0, 0.0, z),
            Point::new(2.0, 2.0, z),
            Point::new(0.0, 2.0, z),
        ];
        let rotated: Vec<Point> = (0..4).map(|i| corners[(i + rotate) % 4]).collect();
        ogeom_algo::make_polygon(model, &rotated, true, T)
            .unwrap()
            .shape
    };
    let mut model = ogeom_topo::Model::new();
    let bottom = build(&mut model, 0, 0.0);
    let top = build(&mut model, 1, 3.0);
    let hints = [Point::new(0.0, 0.0, 0.0), Point::new(0.0, 0.0, 3.0)];
    let aligned = ogeom_offset::make_loft_skinned_aligned(
        &mut model,
        &[bottom.clone(), top.clone()],
        &hints,
        5e-2,
        T,
    )
    .unwrap();
    let volume_of = |model: &ogeom_topo::Model, shape: &ogeom_topo::Shape| {
        ogeom_algo::volume_properties(
            model,
            shape,
            ogeom_mesh::Deflection::with_chord(1e-3).unwrap(),
            T,
        )
        .unwrap()
        .mass
    };
    let straight = volume_of(&model, &aligned.shape);
    assert!(
        (straight - 12.0).abs() / 12.0 < 0.05,
        "aligned loft volume {straight} against 12"
    );

    // Without the hints the rows pair a corner apart and the skin twists:
    // visibly less volume, which is the defect the hint exists to fix.
    let twisted = ogeom_offset::make_loft_skinned(&mut model, &[bottom, top], 5e-2, T).unwrap();
    let sheared = volume_of(&model, &twisted.shape);
    assert!(
        sheared < straight * 0.95,
        "the twist should cost volume: {sheared} vs {straight}"
    );
}

#[test]
fn a_ruled_loft_between_tilted_polygons_still_builds() {
    // Non-parallel sections were never the refusal; only skew walls are.
    // A top square turned about the x axis keeps every wall planar.
    let mut model = ogeom_topo::Model::new();
    let bottom = ogeom_algo::make_polygon(
        &mut model,
        &[
            Point::new(0.0, 0.0, 0.0),
            Point::new(2.0, 0.0, 0.0),
            Point::new(2.0, 2.0, 0.0),
            Point::new(0.0, 2.0, 0.0),
        ],
        true,
        T,
    )
    .unwrap()
    .shape;
    let angle = 25.0_f64.to_radians();
    let turn = |y: f64, z: f64| -> (f64, f64) {
        let (dy, dz) = (y - 1.0, z - 3.0);
        (
            angle.cos().mul_add(dy, -(angle.sin() * dz)) + 1.0,
            angle.sin().mul_add(dy, angle.cos() * dz) + 3.0,
        )
    };
    let corners: Vec<Point> = [(0.0_f64, 0.0_f64), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)]
        .iter()
        .map(|(x, y)| {
            let (ty, tz) = turn(*y, 3.0);
            Point::new(*x, ty, tz)
        })
        .collect();
    let top = ogeom_algo::make_polygon(&mut model, &corners, true, T)
        .unwrap()
        .shape;
    let result = ogeom_offset::make_loft(&mut model, &bottom, &top, T).unwrap();
    let diagnosis = ogeom_algo::check(&model, &result.shape, T).unwrap();
    assert!(diagnosis.is_valid(), "{:?}", diagnosis.problems);
    let measured =
        ogeom_algo::volume_properties(&model, &result.shape, ogeom_mesh::Deflection::default(), T)
            .unwrap()
            .mass;
    assert!(
        measured > 1.0,
        "the tilted loft encloses volume: {measured}"
    );
}

#[test]
fn a_pipe_shell_round_a_closed_circle_matches_the_torus() {
    // The case with an exact answer, which is what pins the holonomy
    // correction: a circular profile round a circular spine is a torus.
    let mut model = ogeom_topo::Model::new();
    let ring_r = 10.0;
    let circle = Circle::new(Frame::WORLD, ring_r, T).unwrap();
    let curve: ogeom_geom::Curve = ogeom_geom::CircleCurve::new(circle).into();
    let domain = curve.domain();
    let spine = ogeom_algo::make_edge(&mut model, curve, domain, T)
        .unwrap()
        .shape;

    let start = Point::new(ring_r, 0.0, 0.0);
    let normal = ogeom_math::Direction::new(ogeom_math::Vector::Y, T).unwrap();
    let section = Circle::new(
        Frame::new(start, normal, ogeom_math::Direction::Z, T).unwrap(),
        1.0,
        T,
    )
    .unwrap();
    let scurve: ogeom_geom::Curve = ogeom_geom::CircleCurve::new(section).into();
    let sdomain = scurve.domain();
    let sedge = ogeom_algo::make_edge(&mut model, scurve, sdomain, T)
        .unwrap()
        .shape;
    let profile = ogeom_algo::make_wire(&mut model, std::slice::from_ref(&sedge), T)
        .unwrap()
        .shape;

    let result =
        ogeom_offset::make_pipe_shell(&mut model, &profile, &spine, false, 5e-3, T).unwrap();
    let diagnosis = ogeom_algo::check(&model, &result.shape, T).unwrap();
    assert!(diagnosis.is_valid(), "{:?}", diagnosis.problems);

    let expected = 2.0 * core::f64::consts::PI * core::f64::consts::PI * ring_r;
    let measured = ogeom_algo::volume_properties(
        &model,
        &result.shape,
        ogeom_mesh::Deflection::with_chord(1e-3).unwrap(),
        T,
    )
    .unwrap()
    .mass;
    assert!(
        (measured - expected).abs() / expected < 0.01,
        "closed pipe shell volume {measured} against {expected}"
    );
    assert!(!result.history.generated(&spine).is_empty());
}

#[test]
fn a_round_profile_along_a_closed_square_spine_is_a_ring() {
    // The closed square spine, its corners rounded the way a real ring's
    // are: four straights and four quarter arcs, one G1 loop. The sharp
    // corner is refused by name (no skin can turn a section through a
    // finite angle over no arc), and the refusal test below pins that.
    let mut model = ogeom_topo::Model::new();
    let (half, r) = (8.0, 2.0);
    let flat = half - r;
    // Tangent points and corner arcs, walked counter-clockwise from the
    // middle of the +x side.
    let mut edges: Vec<ogeom_topo::Shape> = Vec::new();
    let mut vertices: Vec<(ogeom_topo::Shape, Point)> = Vec::new();
    let corner_centres = [
        Point::new(flat, flat, 0.0),
        Point::new(-flat, flat, 0.0),
        Point::new(-flat, -flat, 0.0),
        Point::new(flat, -flat, 0.0),
    ];
    // Each side's straight run, then the arc at its far corner.
    for (i, _) in corner_centres.iter().enumerate() {
        let angle = core::f64::consts::FRAC_PI_2 * f64::from(u8::try_from(i).unwrap());
        let (c, s_) = (angle.cos(), angle.sin());
        // Outward side direction and travel direction for side i.
        let out = ogeom_math::Vector::new(c, s_, 0.0);
        let along = ogeom_math::Vector::new(-s_, c, 0.0);
        let from = Point::new(0.0, 0.0, 0.0) + out * half - along * flat;
        let to = Point::new(0.0, 0.0, 0.0) + out * half + along * flat;
        vertices.push((ogeom_algo::make_vertex(&mut model, from).shape, from));
        vertices.push((ogeom_algo::make_vertex(&mut model, to).shape, to));
        let _ = &corner_centres[i];
    }
    for i in 0..4 {
        let (vf, pf) = vertices[2 * i].clone();
        let (vt, pt) = vertices[2 * i + 1].clone();
        let line = ogeom_geom::LineCurve::segment(pf, pt, T).unwrap();
        let curve: ogeom_geom::Curve = line.into();
        let domain = curve.domain();
        edges.push(
            ogeom_algo::make_edge_between(&mut model, curve, domain, &vf, &vt, T)
                .unwrap()
                .shape,
        );
        // The arc from this side's end to the next side's start, about the
        // shared corner centre.
        let (vn, _) = vertices[(2 * i + 2) % 8].clone();
        let centre = corner_centres[i];
        let frame = Frame::new(
            centre,
            ogeom_math::Direction::Z,
            ogeom_math::Direction::new(pt - centre, T).unwrap(),
            T,
        )
        .unwrap();
        let circle = Circle::new(frame, r, T).unwrap();
        let curve: ogeom_geom::Curve = ogeom_geom::CircleCurve::new(circle).into();
        edges.push(
            ogeom_algo::make_edge_between(
                &mut model,
                curve,
                (0.0, core::f64::consts::FRAC_PI_2),
                &vt,
                &vn,
                T,
            )
            .unwrap()
            .shape,
        );
    }
    let spine = ogeom_algo::make_wire(&mut model, &edges, T).unwrap().shape;

    // The profile at the first edge's own start, square to it.
    let start = vertices[0].1;
    let tangent = vertices[1].1 - vertices[0].1;
    let normal = ogeom_math::Direction::new(tangent, T).unwrap();
    let section = Circle::new(
        Frame::new(start, normal, ogeom_math::Direction::Z, T).unwrap(),
        1.0,
        T,
    )
    .unwrap();
    let scurve: ogeom_geom::Curve = ogeom_geom::CircleCurve::new(section).into();
    let sdomain = scurve.domain();
    let sedge = ogeom_algo::make_edge(&mut model, scurve, sdomain, T)
        .unwrap()
        .shape;
    let profile = ogeom_algo::make_wire(&mut model, std::slice::from_ref(&sedge), T)
        .unwrap()
        .shape;

    let result =
        ogeom_offset::make_pipe_shell(&mut model, &profile, &spine, false, 5e-2, T).unwrap();
    let diagnosis = ogeom_algo::check(&model, &result.shape, T).unwrap();
    assert!(diagnosis.is_valid(), "{:?}", diagnosis.problems);

    // One face bounding itself both ways round, and a volume in a coarse
    // band of Pappus: the corners are smoothed by the skin.
    assert_eq!(
        explore(&model, &result.shape, Filter::OfType(ShapeType::Face))
            .unwrap()
            .len(),
        1
    );
    // Pappus round the rounded square: perimeter = four flats and a full
    // circle of corner arcs.
    let perimeter = (2.0 * flat).mul_add(4.0, core::f64::consts::TAU * r);
    let expected = core::f64::consts::PI * perimeter;
    let measured = ogeom_algo::volume_properties(
        &model,
        &result.shape,
        ogeom_mesh::Deflection::with_chord(1e-3).unwrap(),
        T,
    )
    .unwrap()
    .mass;
    assert!(
        (measured - expected).abs() / expected < 0.02,
        "square ring volume {measured} against {expected}"
    );
}

#[test]
fn a_sharp_cornered_closed_spine_mitres_a_smooth_profile() {
    let mut model = ogeom_topo::Model::new();
    let corners = [
        Point::new(8.0, -8.0, 0.0),
        Point::new(8.0, 8.0, 0.0),
        Point::new(-8.0, 8.0, 0.0),
        Point::new(-8.0, -8.0, 0.0),
    ];
    let spine = ogeom_algo::make_polygon(&mut model, &corners, true, T)
        .unwrap()
        .shape;
    let start = corners[0];
    let normal = ogeom_math::Direction::new(corners[1] - corners[0], T).unwrap();
    let section = Circle::new(
        Frame::new(start, normal, ogeom_math::Direction::Z, T).unwrap(),
        1.0,
        T,
    )
    .unwrap();
    let scurve: ogeom_geom::Curve = ogeom_geom::CircleCurve::new(section).into();
    let sdomain = scurve.domain();
    let sedge = ogeom_algo::make_edge(&mut model, scurve, sdomain, T)
        .unwrap()
        .shape;
    let profile = ogeom_algo::make_wire(&mut model, std::slice::from_ref(&sedge), T)
        .unwrap()
        .shape;
    // The mitred ring, measured. A symmetric
    // profile's corner wedges cancel, so Pappus holds exactly: area times
    // the square's perimeter.
    let ring = ogeom_offset::make_pipe_shell(&mut model, &profile, &spine, false, 5e-2, T).unwrap();
    let measured = volume(&model, &ring.shape);
    let expected = core::f64::consts::PI * 64.0;
    assert!(
        (measured - expected).abs() < expected * 0.02,
        "mitred round ring volume {measured} against {expected}"
    );
}

#[test]
fn an_l_spine_mitres_its_corner_and_the_runs_share_the_ring() {
    // An open cornered spine: two straight legs at a right angle. Each leg
    // sweeps as its own ruled wall between end rings, the corner's twin
    // stations throw both boundary rings onto the bisector plane, and the
    // sew joins the runs along that one mitred ring. The mitre passes
    // through the centreline corner, so Pappus prices the whole elbow at
    // area times the legs' summed length, exactly.
    let mut model = ogeom_topo::Model::new();
    let a = Point::new(0.0, 0.0, 0.0);
    let b = Point::new(20.0, 0.0, 0.0);
    let c = Point::new(20.0, 20.0, 0.0);
    let va = ogeom_algo::make_vertex(&mut model, a).shape;
    let vb = ogeom_algo::make_vertex(&mut model, b).shape;
    let vc = ogeom_algo::make_vertex(&mut model, c).shape;
    let seg = |model: &mut ogeom_topo::Model,
               f: (&ogeom_topo::Shape, Point),
               t: (&ogeom_topo::Shape, Point)|
     -> ogeom_topo::Shape {
        let line = ogeom_geom::LineCurve::segment(f.1, t.1, T).unwrap();
        let curve = ogeom_geom::Curve::Line(line);
        let d = ogeom_geom::Curve3d::domain(&curve);
        ogeom_algo::make_edge_between(model, curve, d, f.0, t.0, T)
            .unwrap()
            .shape
    };
    let e1 = seg(&mut model, (&va, a), (&vb, b));
    let e2 = seg(&mut model, (&vb, b), (&vc, c));
    let spine = ogeom_algo::make_wire(&mut model, &[e1, e2], T)
        .unwrap()
        .shape;
    let profile = square_profile(&mut model, a, ogeom_math::Vector::X, 4.0);

    let result =
        ogeom_offset::make_pipe_shell(&mut model, &profile, &spine, false, 1e-3, T).unwrap();
    let diagnosis = ogeom_algo::check(&model, &result.shape, T).unwrap();
    assert!(diagnosis.is_valid(), "{:?}", diagnosis.problems);
    let measured = volume(&model, &result.shape);
    assert!(
        (measured - 640.0).abs() < 640.0 * 1e-3,
        "mitred elbow volume {measured} against 640"
    );
}

/// A quarter arc meeting a straight leg at a right angle, swept by a square:
/// the curved wall ends where its generators cross the straight leg's, not
/// on a mitre plane. The closed form is the plane slice's area times the
/// square's height: the quarter annulus, the leg's rectangle, less their
/// overlap under the outer arc, plus the inner corner the two extensions
/// fill between them.
#[test]
fn a_corner_against_a_curved_leg_meets_it_on_its_generators() {
    let mut model = ogeom_topo::Model::new();
    let r = 20.0;
    // A quarter arc ending at (0, 20), then a straight leg heading +x:
    // a genuine corner between a curved run and a straight one.
    let arc_curve: ogeom_geom::Curve =
        ogeom_geom::CircleCurve::new(ogeom_math::Circle::new(Frame::WORLD, r, T).unwrap()).into();
    let a = Point::new(r, 0.0, 0.0);
    let b = Point::new(0.0, r, 0.0);
    let c = Point::new(0.0, r + 20.0, 0.0);
    let va = ogeom_algo::make_vertex(&mut model, a).shape;
    let vb = ogeom_algo::make_vertex(&mut model, b).shape;
    let vc = ogeom_algo::make_vertex(&mut model, c).shape;
    let arc = ogeom_algo::make_edge_between(
        &mut model,
        arc_curve,
        (0.0, core::f64::consts::FRAC_PI_2),
        &va,
        &vb,
        T,
    )
    .unwrap()
    .shape;
    let line = ogeom_geom::LineCurve::segment(b, c, T).unwrap();
    // The arc leaves its end heading -x; the leg turns square up +y.
    let lcurve = ogeom_geom::Curve::Line(line);
    let ldomain = ogeom_geom::Curve3d::domain(&lcurve);
    let leg = ogeom_algo::make_edge_between(&mut model, lcurve, ldomain, &vb, &vc, T)
        .unwrap()
        .shape;
    let spine = ogeom_algo::make_wire(&mut model, &[arc, leg], T)
        .unwrap()
        .shape;
    let profile = square_profile(&mut model, a, ogeom_math::Vector::Y, 4.0);
    let result =
        ogeom_offset::make_pipe_shell(&mut model, &profile, &spine, false, 1e-3, T).unwrap();
    let diagnosis = ogeom_algo::check(&model, &result.shape, T).unwrap();
    assert!(diagnosis.is_valid(), "{:?}", diagnosis.problems);
    let (ro, ri, half) = (r + 2.0, r - 2.0, 2.0);
    let annulus = core::f64::consts::FRAC_PI_4 * (ro * ro - ri * ri);
    let leg = 2.0 * half * 20.0;
    // ∫₀^half (√(ro² − x²) − r) dx: the arc's material already inside the leg.
    let overlap =
        half * (ro * ro - half * half).sqrt() / 2.0 + ro * ro / 2.0 * (half / ro).asin() - r * half;
    // The inner corner between the arc's straight run-on and the leg's
    // run-back: a `half` by `half` square.
    let fill = half * half;
    let expected = (annulus + leg - overlap + fill) * 2.0 * half;
    let measured = volume(&model, &result.shape);
    assert!(
        (measured - expected).abs() < expected * 5e-3,
        "curved-leg corner volume {measured} against {expected}"
    );
}

/// A skinned loft ends at a point: circles narrowing to an apex, the apex
/// deliberately off every axis so no exact cone could stand in.
///
/// The reference is piecewise: Pappus's frustum from the two rings, plus the
/// cone from the top ring to the apex, whose shear off the axis changes
/// nothing, volume being shear-invariant. The skin smooths the crease where
/// the pieces meet, so the assertion carries the fit's honesty, not the
/// mesher's.
#[test]
fn a_skinned_loft_to_an_offset_point_measures_as_frustum_plus_cone() {
    let mut model = ogeom_topo::Model::new();
    let ring = |model: &mut ogeom_topo::Model, r: f64, z: f64| {
        let frame = Frame::new(
            Point::new(0.0, 0.0, z),
            ogeom_math::Direction::Z,
            ogeom_math::Direction::X,
            T,
        )
        .unwrap();
        let circle = Circle::new(frame, r, T).unwrap();
        let curve = ogeom_geom::Curve::Circle(ogeom_geom::CircleCurve::new(circle));
        let domain = curve.domain();
        let edge = ogeom_algo::make_edge(model, curve, domain, T)
            .unwrap()
            .shape;
        ogeom_algo::make_wire(model, std::slice::from_ref(&edge), T)
            .unwrap()
            .shape
    };
    let s0 = ring(&mut model, 10.0, 0.0);
    let s1 = ring(&mut model, 6.0, 6.0);
    let apex = ogeom_algo::make_vertex(&mut model, Point::new(2.0, 1.0, 15.0)).shape;
    let built = ogeom_offset::make_loft_skinned(&mut model, &[s0, s1, apex], 1e-2, T).unwrap();
    assert!(
        ogeom_algo::check(&model, &built.shape, T)
            .unwrap()
            .is_valid(),
        "the apex loft is a valid solid"
    );
    let frustum = core::f64::consts::PI * 6.0 / 3.0 * (100.0 + 60.0 + 36.0);
    let cone = core::f64::consts::PI * 36.0 * 9.0 / 3.0;
    let measured = volume(&model, &built.shape);
    let reference = frustum + cone;
    assert!(
        (measured - reference).abs() / reference < 0.01,
        "apex loft volume {measured} against {reference}"
    );
}

/// A wavy middle section skins: planarity is the caps' requirement, and only
/// the end sections carry caps.
#[test]
fn a_non_planar_middle_section_lofts() {
    let mut model = ogeom_topo::Model::new();
    let flat = |model: &mut ogeom_topo::Model, r: f64, z: f64| {
        let frame = Frame::new(
            Point::new(0.0, 0.0, z),
            ogeom_math::Direction::Z,
            ogeom_math::Direction::X,
            T,
        )
        .unwrap();
        let circle = Circle::new(frame, r, T).unwrap();
        let curve = ogeom_geom::Curve::Circle(ogeom_geom::CircleCurve::new(circle));
        let domain = curve.domain();
        let edge = ogeom_algo::make_edge(model, curve, domain, T)
            .unwrap()
            .shape;
        ogeom_algo::make_wire(model, std::slice::from_ref(&edge), T)
            .unwrap()
            .shape
    };
    // The middle ring waves out of plane: a trigonometric-spline circle
    // whose z oscillates, fitted closed.
    let wavy = {
        let n = 64_i32;
        let pts: Vec<Point> = (0..=n)
            .map(|i| {
                #[allow(clippy::cast_precision_loss)]
                let a = core::f64::consts::TAU * f64::from(i % n) / f64::from(n);
                Point::new(8.0 * a.cos(), 8.0 * a.sin(), 5.0 + 0.5 * (3.0 * a).sin())
            })
            .collect();
        let fitted = ogeom_geom::fit::fit_points_closed(&pts, 3, 1e-3, T).unwrap();
        let curve = ogeom_geom::Curve::BSpline(fitted.curve);
        let domain = curve.domain();
        let edge = ogeom_algo::make_edge(&mut model, curve, domain, T)
            .unwrap()
            .shape;
        ogeom_algo::make_wire(&mut model, std::slice::from_ref(&edge), T)
            .unwrap()
            .shape
    };
    let s0 = flat(&mut model, 10.0, 0.0);
    let s2 = flat(&mut model, 9.0, 10.0);
    let built = ogeom_offset::make_loft_skinned(&mut model, &[s0, wavy, s2], 5e-2, T).unwrap();
    assert!(
        ogeom_algo::check(&model, &built.shape, T)
            .unwrap()
            .is_valid(),
        "the wavy loft is a valid solid"
    );
    // Coarse expectation only: between the r=10 and r=9 caps through an
    // r=8 waist, the volume sits between the two bounding cylinders.
    let v = volume(&model, &built.shape);
    let lo = core::f64::consts::PI * 64.0 * 10.0;
    let hi = core::f64::consts::PI * 100.0 * 10.0;
    assert!(
        lo < v && v < hi,
        "wavy loft volume {v} outside ({lo}, {hi})"
    );
}

/// A wavy *end* section is capped too: by a patch skinned from the rim
/// down to a point inside it, where a plane cannot stand on it.
///
/// The rim waves as `sin 3a`, whose mean is zero, so the volume the skinned
/// cap adds over the rim's mean plane cancels the volume it takes away, and
/// the solid measures as the frustum between the two rims' planes.
#[test]
fn a_non_planar_end_section_is_capped_by_a_skinned_patch() {
    let mut model = ogeom_topo::Model::new();
    let s0 = {
        let frame = Frame::new(
            Point::ORIGIN,
            ogeom_math::Direction::Z,
            ogeom_math::Direction::X,
            T,
        )
        .unwrap();
        let circle = Circle::new(frame, 10.0, T).unwrap();
        let curve = ogeom_geom::Curve::Circle(ogeom_geom::CircleCurve::new(circle));
        let domain = curve.domain();
        let edge = ogeom_algo::make_edge(&mut model, curve, domain, T)
            .unwrap()
            .shape;
        ogeom_algo::make_wire(&mut model, std::slice::from_ref(&edge), T)
            .unwrap()
            .shape
    };
    let wavy = {
        let n = 64_i32;
        let pts: Vec<Point> = (0..=n)
            .map(|i| {
                let a = core::f64::consts::TAU * f64::from(i % n) / f64::from(n);
                Point::new(8.0 * a.cos(), 8.0 * a.sin(), 5.0 + 0.5 * (3.0 * a).sin())
            })
            .collect();
        let fitted = ogeom_geom::fit::fit_points_closed(&pts, 3, 1e-3, T).unwrap();
        let curve = ogeom_geom::Curve::BSpline(fitted.curve);
        let domain = curve.domain();
        let edge = ogeom_algo::make_edge(&mut model, curve, domain, T)
            .unwrap()
            .shape;
        ogeom_algo::make_wire(&mut model, std::slice::from_ref(&edge), T)
            .unwrap()
            .shape
    };
    let built = ogeom_offset::make_loft_skinned(&mut model, &[s0, wavy], 5e-2, T).unwrap();
    let diagnosis = ogeom_algo::check(&model, &built.shape, T).unwrap();
    assert!(diagnosis.is_valid(), "{:?}", diagnosis.problems);
    let faces =
        ogeom_topo::explore_unique(&model, &built.shape, ogeom_topo::ShapeType::Face).unwrap();
    assert_eq!(faces.len(), 3, "a wall, a plane cap and a skinned cap");
    let mesh = ogeom_mesh::triangulate(&model, &built.shape, fine(), T).unwrap();
    assert!(mesh.is_closed(), "the skinned cap closes the solid");
    let v = volume(&model, &built.shape);
    let frustum = core::f64::consts::PI * 5.0 / 3.0 * (100.0 + 80.0 + 64.0);
    assert!(
        (v - frustum).abs() < frustum * 0.02,
        "loft with a wavy rim measures {v} against the frustum's {frustum}"
    );
}

/// A faceted profile round a closed circular spine: the square torus, whose
/// volume Pappus names exactly: side² × 2πR.
#[test]
fn a_square_profile_along_a_closed_circle_is_a_pappus_ring() {
    let mut model = ogeom_topo::Model::new();
    // The spine: a full circle of radius 20 in the XY plane.
    let frame = Frame::new(
        Point::new(0.0, 0.0, 0.0),
        ogeom_math::Direction::Z,
        ogeom_math::Direction::X,
        T,
    )
    .unwrap();
    let circle = Circle::new(frame, 20.0, T).unwrap();
    let curve = ogeom_geom::Curve::Circle(ogeom_geom::CircleCurve::new(circle));
    let domain = curve.domain();
    let spine_edge = ogeom_algo::make_edge(&mut model, curve, domain, T)
        .unwrap()
        .shape;
    let spine = ogeom_algo::make_wire(&mut model, std::slice::from_ref(&spine_edge), T)
        .unwrap()
        .shape;
    // The profile: a 4x4 square at the spine's start (20, 0, 0), square to
    // the spine's tangent (+Y), spanned by the plane normal X... the sweep
    // wants the profile square to the start tangent.
    let corners = [
        Point::new(18.0, 0.0, -2.0),
        Point::new(22.0, 0.0, -2.0),
        Point::new(22.0, 0.0, 2.0),
        Point::new(18.0, 0.0, 2.0),
    ];
    let profile = ogeom_algo::make_polygon(&mut model, &corners, true, T)
        .unwrap()
        .shape;
    let built =
        ogeom_offset::make_pipe_shell(&mut model, &profile, &spine, false, 5e-3, T).unwrap();
    assert!(
        ogeom_algo::check(&model, &built.shape, T)
            .unwrap()
            .is_valid(),
        "the square ring is a valid solid"
    );
    let expected = 16.0 * core::f64::consts::TAU * 20.0;
    let measured = volume(&model, &built.shape);
    assert!(
        (measured - expected).abs() / expected < 5e-3,
        "square ring volume {measured} against Pappus {expected}"
    );
}

/// A holed profile round a closed spine: the outer square ring less the
/// tunnel its hole sweeps: Pappus on both, subtracted.
#[test]
fn a_holed_profile_round_a_closed_spine_carries_its_tunnel() {
    let mut model = ogeom_topo::Model::new();
    let frame = Frame::new(
        Point::new(0.0, 0.0, 0.0),
        ogeom_math::Direction::Z,
        ogeom_math::Direction::X,
        T,
    )
    .unwrap();
    let circle = Circle::new(frame, 20.0, T).unwrap();
    let curve = ogeom_geom::Curve::Circle(ogeom_geom::CircleCurve::new(circle));
    let domain = curve.domain();
    let spine_edge = ogeom_algo::make_edge(&mut model, curve, domain, T)
        .unwrap()
        .shape;
    let spine = ogeom_algo::make_wire(&mut model, std::slice::from_ref(&spine_edge), T)
        .unwrap()
        .shape;
    // A 6x6 square with a 2x2 hole, centred at the spine's start.
    let outer = ogeom_algo::make_polygon(
        &mut model,
        &[
            Point::new(17.0, 0.0, -3.0),
            Point::new(23.0, 0.0, -3.0),
            Point::new(23.0, 0.0, 3.0),
            Point::new(17.0, 0.0, 3.0),
        ],
        true,
        T,
    )
    .unwrap()
    .shape;
    let hole = ogeom_algo::make_polygon(
        &mut model,
        &[
            Point::new(19.0, 0.0, -1.0),
            Point::new(21.0, 0.0, -1.0),
            Point::new(21.0, 0.0, 1.0),
            Point::new(19.0, 0.0, 1.0),
        ],
        true,
        T,
    )
    .unwrap()
    .shape;
    let plane = ogeom_math::Plane::through(Point::new(20.0, 0.0, 0.0), ogeom_math::Direction::Y);
    let surface: ogeom_geom::SurfaceGeometry =
        ogeom_geom::PlaneSurface::over(plane, (-10.0, 10.0), (-10.0, 10.0))
            .unwrap()
            .into();
    let profile = ogeom_algo::make_face(&mut model, surface, &[outer, hole], T)
        .unwrap()
        .shape;
    let built =
        ogeom_offset::make_pipe_shell(&mut model, &profile, &spine, false, 5e-3, T).unwrap();
    assert!(
        ogeom_algo::check(&model, &built.shape, T)
            .unwrap()
            .is_valid(),
        "the holed ring is a valid solid"
    );
    let expected = (36.0 - 4.0) * core::f64::consts::TAU * 20.0;
    let measured = volume(&model, &built.shape);
    assert!(
        (measured - expected).abs() / expected < 5e-3,
        "holed ring volume {measured} against Pappus {expected}"
    );
}

/// A faceted ring round a wavy *non-planar* closed spine: the geometry
/// that exposed two step-1 debts: rails must widen to their fits' honest
/// error before the sew can join them, and a ring strip's outward is away
/// from the spine's own line, not the loop's centroid. Volume is the
/// generalized Pappus, section area times the spine's arc length, held
/// loosely for the wave's second-order skew.
#[test]
fn a_faceted_ring_round_a_wavy_spine_closes_and_measures() {
    let mut model = ogeom_topo::Model::new();
    // A closed non-planar spine: a radius-20 circle with a gentle z-wave,
    // so the Frenet frame genuinely twists.
    let n = 96_i32;
    let pts: Vec<Point> = (0..=n)
        .map(|i| {
            let a = core::f64::consts::TAU * f64::from(i % n) / f64::from(n);
            Point::new(
                20.0 * a.cos(),
                20.0 * a.sin(),
                1.5 * (1.0 - (3.0 * a).cos()),
            )
        })
        .collect();
    let fitted = ogeom_geom::fit::fit_points_closed(&pts, 3, 1e-4, T).unwrap();
    let curve = ogeom_geom::Curve::BSpline(fitted.curve);
    let domain = curve.domain();
    let arc = {
        // The spine's own arc length, finely summed.
        let mut total = 0.0;
        let mut last = curve.point_at(domain.0, T).unwrap();
        for k in 1..=2048 {
            let t = domain.0 + (domain.1 - domain.0) * f64::from(k) / 2048.0;
            let p = curve.point_at(t, T).unwrap();
            total += last.distance(p);
            last = p;
        }
        total
    };
    // The profile stands square to the *fitted* tangent: the fit's own
    // start, not the ideal circle's.
    let (start, tangent) = {
        let p = curve.point_at(domain.0, T).unwrap();
        let d = curve.d1_at(domain.0, T).unwrap();
        (p, ogeom_math::Direction::new(d, T).unwrap())
    };
    let spine_edge = ogeom_algo::make_edge(&mut model, curve, domain, T)
        .unwrap()
        .shape;
    let spine = ogeom_algo::make_wire(&mut model, std::slice::from_ref(&spine_edge), T)
        .unwrap()
        .shape;
    let (ex, ey) = {
        let plane = ogeom_math::Plane::through(start, tangent);
        let f = plane.frame();
        (f.x().vector(), f.y().vector())
    };
    let corner = |a: f64, b: f64| start + ex * a + ey * b;
    let profile = ogeom_algo::make_polygon(
        &mut model,
        &[corner(-1.5, -1.0), corner(1.5, -1.0), corner(0.0, 1.6)],
        true,
        T,
    )
    .unwrap()
    .shape;
    // Both frame laws: the rotation-minimizing frame with its holonomy
    // paid off, and the Frenet frame, single-valued round the loop, its
    // corner loops each one rail shared by the two strips meeting there.
    let area = 0.5 * 3.0 * 2.6;
    let expected = area * arc;
    for frenet in [false, true] {
        let built =
            ogeom_offset::make_pipe_shell(&mut model, &profile, &spine, frenet, 5e-3, T).unwrap();
        assert!(
            ogeom_algo::check(&model, &built.shape, T)
                .unwrap()
                .is_valid(),
            "the wavy ring is a valid solid (frenet {frenet})"
        );
        let measured = volume(&model, &built.shape);
        assert!(
            (measured - expected).abs() / expected < 0.02,
            "wavy ring volume {measured} against A*L {expected} (frenet {frenet})"
        );
    }
}

#[test]
fn a_mitred_square_ring_measures_pappus_exactly() {
    // A 4x4 profile round a 30x30 square spine: the mitred ring is four
    // trimmed prisms meeting on their bisector planes, and its volume is
    // exactly area x perimeter: the outer box minus the inner box.
    let mut model = ogeom_topo::Model::new();
    let spine = ogeom_algo::make_polygon(
        &mut model,
        &[
            ogeom_math::Point::new(0.0, 0.0, 0.0),
            ogeom_math::Point::new(30.0, 0.0, 0.0),
            ogeom_math::Point::new(30.0, 30.0, 0.0),
            ogeom_math::Point::new(0.0, 30.0, 0.0),
        ],
        true,
        T,
    )
    .unwrap()
    .shape;
    let profile = square_profile(
        &mut model,
        ogeom_math::Point::new(0.0, 0.0, 0.0),
        ogeom_math::Vector::new(1.0, 0.0, 0.0),
        4.0,
    );
    let ring = ogeom_offset::make_pipe_shell(&mut model, &profile, &spine, false, 1e-4, T).unwrap();
    let measured = volume(&model, &ring.shape);
    let exact = 16.0 * 120.0;
    assert!(
        (measured - exact).abs() < exact * 1e-3,
        "mitred ring volume {measured} against {exact}"
    );
}

#[test]
fn a_cornered_ring_seamed_mid_leg_measures_pappus() {
    // The wire's seam stands halfway along a leg rather than on a corner:
    // the wrap's mitre plane is the leg's own cross-section, and the two
    // halves of that leg butt together on the seam's ring. Exactly the
    // corner-seamed ring's volume, with that leg in two pieces.
    let mut model = ogeom_topo::Model::new();
    let spine = ogeom_algo::make_polygon(
        &mut model,
        &[
            ogeom_math::Point::new(15.0, 0.0, 0.0),
            ogeom_math::Point::new(30.0, 0.0, 0.0),
            ogeom_math::Point::new(30.0, 30.0, 0.0),
            ogeom_math::Point::new(0.0, 30.0, 0.0),
            ogeom_math::Point::new(0.0, 0.0, 0.0),
        ],
        true,
        T,
    )
    .unwrap()
    .shape;
    let profile = square_profile(
        &mut model,
        ogeom_math::Point::new(15.0, 0.0, 0.0),
        ogeom_math::Vector::new(1.0, 0.0, 0.0),
        4.0,
    );
    let built =
        ogeom_offset::make_pipe_shell(&mut model, &profile, &spine, false, 1e-4, T).unwrap();
    assert!(
        ogeom_algo::check(&model, &built.shape, T)
            .unwrap()
            .is_valid(),
        "the mid-leg-seamed ring is a valid solid"
    );
    let measured = volume(&model, &built.shape);
    assert!(
        (measured - 1920.0).abs() < 1e-6,
        "mid-leg seam: {measured} against Pappus' 1920"
    );
    assert_eq!(
        ogeom_topo::explore_unique(&model, &built.shape, ogeom_topo::ShapeType::Face)
            .unwrap()
            .len(),
        20,
        "four legs of four walls, the seamed leg in two pieces"
    );
}

#[test]
fn a_skew_cornered_ring_closes_on_its_mitres() {
    // Corners with genuine out-of-plane turn. The frame reflected across
    // each mitre plane lands both sheared sections on one ring, the
    // loop's holonomy is spread along the legs as a twist (each straight
    // leg a ruled skin between its two end rings), and the ring closes as
    // a valid solid whose volume sits near area times perimeter, the
    // twist alone bending it away from Pappus.
    let mut model = ogeom_topo::Model::new();
    let pts = [
        ogeom_math::Point::new(0.0, 0.0, 0.0),
        ogeom_math::Point::new(20.0, 0.0, 4.0),
        ogeom_math::Point::new(30.0, 15.0, 0.0),
        ogeom_math::Point::new(20.0, 30.0, 4.0),
        ogeom_math::Point::new(0.0, 30.0, 0.0),
        ogeom_math::Point::new(-10.0, 15.0, 4.0),
    ];
    let spine = ogeom_algo::make_polygon(&mut model, &pts, true, T)
        .unwrap()
        .shape;
    let profile = square_profile(&mut model, pts[0], pts[1] - pts[0], 4.0);
    let built =
        ogeom_offset::make_pipe_shell(&mut model, &profile, &spine, false, 1e-3, T).unwrap();
    assert!(
        ogeom_algo::check(&model, &built.shape, T)
            .unwrap()
            .is_valid(),
        "the skew ring is a valid solid"
    );
    let perimeter: f64 = (0..pts.len())
        .map(|i| pts[i].distance(pts[(i + 1) % pts.len()]))
        .sum();
    let expected = 16.0 * perimeter;
    let measured = volume(&model, &built.shape);
    assert!(
        (measured - expected).abs() / expected < 0.03,
        "skew ring volume {measured} against A*L {expected}"
    );
}

#[test]
fn a_holed_profile_rounds_a_mitred_ring() {
    // A 6x6 profile with a 2x2 hole: the hole's walls sweep their own
    // shell, the void tunnel riding the same mitres. Exactly
    // (36 - 4) x perimeter.
    use ogeom_math::{Direction, Point, Vector};
    let mut model = ogeom_topo::Model::new();
    let spine = ogeom_algo::make_polygon(
        &mut model,
        &[
            Point::new(0.0, 0.0, 0.0),
            Point::new(30.0, 0.0, 0.0),
            Point::new(30.0, 30.0, 0.0),
            Point::new(0.0, 30.0, 0.0),
        ],
        true,
        T,
    )
    .unwrap()
    .shape;
    let plane = ogeom_math::Plane::through(Point::ORIGIN, Direction::new(Vector::X, T).unwrap());
    let frame = plane.frame();
    let ring_at = |model: &mut ogeom_topo::Model, half: f64| {
        let corners: Vec<Point> = [(-half, -half), (half, -half), (half, half), (-half, half)]
            .iter()
            .map(|(a, b)| Point::ORIGIN + frame.x().vector() * *a + frame.y().vector() * *b)
            .collect();
        ogeom_algo::make_polygon(model, &corners, true, T)
            .unwrap()
            .shape
    };
    let outer = ring_at(&mut model, 3.0);
    let hole = ring_at(&mut model, 1.0);
    let face = ogeom_algo::make_face(
        &mut model,
        ogeom_geom::PlaneSurface::over(plane, (-12.0, 12.0), (-12.0, 12.0))
            .unwrap()
            .into(),
        &[outer, hole],
        T,
    )
    .unwrap()
    .shape;
    let ring = ogeom_offset::make_pipe_shell(&mut model, &face, &spine, false, 1e-4, T).unwrap();
    let measured = volume(&model, &ring.shape);
    let exact = 32.0 * 120.0;
    assert!(
        (measured - exact).abs() < exact * 1e-3,
        "holed mitred ring volume {measured} against {exact}"
    );
}

/// A round profile of radius `radius` centred at `centre`, square to
/// `tangent`, as a one-edge wire.
fn circle_profile(
    model: &mut ogeom_topo::Model,
    centre: Point,
    tangent: ogeom_math::Vector,
    radius: f64,
) -> ogeom_topo::Shape {
    let normal = ogeom_math::Direction::new(tangent, T).unwrap();
    let section = Circle::new(
        Frame::new(centre, normal, ogeom_math::Direction::Z, T).unwrap(),
        radius,
        T,
    )
    .unwrap();
    let curve: ogeom_geom::Curve = ogeom_geom::CircleCurve::new(section).into();
    let domain = curve.domain();
    let edge = ogeom_algo::make_edge(model, curve, domain, T)
        .unwrap()
        .shape;
    ogeom_algo::make_wire(model, std::slice::from_ref(&edge), T)
        .unwrap()
        .shape
}

/// An arc of radius `r` about `centre` in the xy plane between the angles
/// `(t0, t1)`, on the vertices `va` at `t0` and `vb` at `t1`.
fn arc_between(
    model: &mut ogeom_topo::Model,
    centre: Point,
    r: f64,
    (t0, t1): (f64, f64),
    va: &ogeom_topo::Shape,
    vb: &ogeom_topo::Shape,
) -> ogeom_topo::Shape {
    let frame = Frame::new(
        centre,
        ogeom_math::Direction::Z,
        ogeom_math::Direction::X,
        T,
    )
    .unwrap();
    let curve: ogeom_geom::Curve =
        ogeom_geom::CircleCurve::new(ogeom_math::Circle::new(frame, r, T).unwrap()).into();
    ogeom_algo::make_edge_between(model, curve, (t0, t1), va, vb, T)
        .unwrap()
        .shape
}

/// Simpson's rule over `[a, b]` in `n` (even) steps.
fn simpson(a: f64, b: f64, n: usize, f: impl Fn(f64) -> f64) -> f64 {
    #[allow(clippy::cast_precision_loss)]
    let h = (b - a) / (n as f64);
    let mut sum = f(a) + f(b);
    for i in 1..n {
        #[allow(clippy::cast_precision_loss)]
        let x = a + h * (i as f64);
        sum += f(x) * if i % 2 == 1 { 4.0 } else { 2.0 };
    }
    sum * h / 3.0
}

/// The plane slice of a quarter-arc leg of radius `r` about the origin
/// meeting a straight leg up `+y` from `(0, r)`, for a profile of
/// half-width `w` across the turn: the quarter annulus, the leg's
/// rectangle of length `leg`, less their overlap under the outer arc,
/// plus the inner corner the two run-ons fill.
fn arc_then_leg_slice(r: f64, w: f64, leg: f64) -> f64 {
    let ro = r + w;
    let annulus = core::f64::consts::FRAC_PI_4 * (ro * ro - (r - w) * (r - w));
    let overlap = w * (ro * ro - w * w).sqrt() / 2.0 + ro * ro / 2.0 * (w / ro).asin() - r * w;
    annulus + 2.0 * w * leg - overlap + w * w
}

/// The round profile through the same corner: every slice of the tube is
/// the square's slice at that height's half-width, integrated.
#[test]
fn a_round_profile_meets_a_curved_leg_corner_on_its_generators() {
    let mut model = ogeom_topo::Model::new();
    let r = 20.0;
    let a = Point::new(r, 0.0, 0.0);
    let b = Point::new(0.0, r, 0.0);
    let c = Point::new(0.0, r + 20.0, 0.0);
    let va = ogeom_algo::make_vertex(&mut model, a).shape;
    let vb = ogeom_algo::make_vertex(&mut model, b).shape;
    let vc = ogeom_algo::make_vertex(&mut model, c).shape;
    let arc = arc_between(
        &mut model,
        Point::ORIGIN,
        r,
        (0.0, core::f64::consts::FRAC_PI_2),
        &va,
        &vb,
    );
    let lcurve = ogeom_geom::Curve::Line(ogeom_geom::LineCurve::segment(b, c, T).unwrap());
    let ldomain = ogeom_geom::Curve3d::domain(&lcurve);
    let leg = ogeom_algo::make_edge_between(&mut model, lcurve, ldomain, &vb, &vc, T)
        .unwrap()
        .shape;
    let spine = ogeom_algo::make_wire(&mut model, &[arc, leg], T)
        .unwrap()
        .shape;
    let profile = circle_profile(&mut model, a, ogeom_math::Vector::Y, 2.0);
    let result =
        ogeom_offset::make_pipe_shell(&mut model, &profile, &spine, false, 1e-3, T).unwrap();
    let diagnosis = ogeom_algo::check(&model, &result.shape, T).unwrap();
    assert!(diagnosis.is_valid(), "{:?}", diagnosis.problems);
    let expected = simpson(-2.0, 2.0, 4000, |z| {
        let w = (4.0 - z * z).max(0.0).sqrt();
        arc_then_leg_slice(r, w, 20.0)
    });
    let measured = volume(&model, &result.shape);
    assert!(
        (measured - expected).abs() < expected * 1e-2,
        "round curved-leg corner volume {measured} against {expected}"
    );
}

/// Two arcs meeting at a right angle: the corner turns from a bend one way
/// into a bend the other, and both legs' skins end on the crossing of
/// their generators. The slice is the union of the two quarter annuli and
/// the inner corner their run-ons fill, integrated by the width of that
/// union at each height.
#[test]
fn two_curved_legs_meet_at_a_corner_on_their_generators() {
    let mut model = ogeom_topo::Model::new();
    let r = 20.0;
    let a = Point::new(r, 0.0, 0.0);
    let b = Point::new(0.0, r, 0.0);
    let d = Point::new(r, 2.0 * r, 0.0);
    let centre2 = Point::new(r, r, 0.0);
    let va = ogeom_algo::make_vertex(&mut model, a).shape;
    let vb = ogeom_algo::make_vertex(&mut model, b).shape;
    let vd = ogeom_algo::make_vertex(&mut model, d).shape;
    let arc1 = arc_between(
        &mut model,
        Point::ORIGIN,
        r,
        (0.0, core::f64::consts::FRAC_PI_2),
        &va,
        &vb,
    );
    // About (r, r) from angle π at b back to π/2 at d: travelled against
    // its parameter, heading +y out of the corner.
    let arc2 = arc_between(
        &mut model,
        centre2,
        r,
        (core::f64::consts::FRAC_PI_2, core::f64::consts::PI),
        &vd,
        &vb,
    );
    let spine = ogeom_algo::make_wire(&mut model, &[arc1, arc2.reversed()], T)
        .unwrap()
        .shape;
    let profile = square_profile(&mut model, a, ogeom_math::Vector::Y, 4.0);
    let result =
        ogeom_offset::make_pipe_shell(&mut model, &profile, &spine, false, 1e-3, T).unwrap();
    let diagnosis = ogeom_algo::check(&model, &result.shape, T).unwrap();
    assert!(diagnosis.is_valid(), "{:?}", diagnosis.problems);
    // The union's width at height y: the first annulus's span (x ≥ 0), the
    // second's (x ≤ r), and the corner fill, merged.
    let w = 2.0;
    let width = |y: f64| -> f64 {
        let mut spans: Vec<(f64, f64)> = Vec::new();
        let (ro, ri) = (r + w, r - w);
        if (0.0..=ro).contains(&y) {
            let lo = (ri * ri - y * y).max(0.0).sqrt();
            let hi = (ro * ro - y * y).sqrt();
            spans.push((lo, hi));
        }
        let e = y - r;
        if (0.0..=ro).contains(&e) {
            let lo = r - (ro * ro - e * e).sqrt();
            let hi = r - (ri * ri - e * e).max(0.0).sqrt();
            spans.push((lo, hi));
        }
        if (r - w..=r).contains(&y) {
            spans.push((-w, 0.0));
        }
        spans.sort_by(|p, q| p.0.partial_cmp(&q.0).unwrap());
        let mut total = 0.0;
        let mut reach = f64::NEG_INFINITY;
        for (lo, hi) in spans {
            let lo = lo.max(reach);
            if hi > lo {
                total += hi - lo;
                reach = hi;
            }
        }
        total
    };
    let area = simpson(0.0, 2.0 * r + w, 40000, width);
    let expected = area * 2.0 * w;
    let measured = volume(&model, &result.shape);
    assert!(
        (measured - expected).abs() < expected * 5e-3,
        "arc-to-arc corner volume {measured} against {expected}"
    );
}

/// A D-shaped ring (a semicircle closed by its diameter) swept by a
/// square: both corners stand between the arc and the straight leg, one of
/// them the wrap. Each corner's slice is the arc's inner overlap with the
/// leg and the outer corner the run-ons fill.
#[test]
fn a_d_shaped_ring_corners_its_curved_leg_at_both_ends() {
    let mut model = ogeom_topo::Model::new();
    let r = 20.0;
    let a = Point::new(r, 0.0, 0.0);
    let b = Point::new(-r, 0.0, 0.0);
    let va = ogeom_algo::make_vertex(&mut model, a).shape;
    let vb = ogeom_algo::make_vertex(&mut model, b).shape;
    let arc = arc_between(
        &mut model,
        Point::ORIGIN,
        r,
        (0.0, core::f64::consts::PI),
        &va,
        &vb,
    );
    let lcurve = ogeom_geom::Curve::Line(ogeom_geom::LineCurve::segment(b, a, T).unwrap());
    let ldomain = ogeom_geom::Curve3d::domain(&lcurve);
    let leg = ogeom_algo::make_edge_between(&mut model, lcurve, ldomain, &vb, &va, T)
        .unwrap()
        .shape;
    let spine = ogeom_algo::make_wire(&mut model, &[arc, leg], T)
        .unwrap()
        .shape;
    let profile = square_profile(&mut model, a, ogeom_math::Vector::Y, 4.0);
    let result =
        ogeom_offset::make_pipe_shell(&mut model, &profile, &spine, false, 1e-3, T).unwrap();
    let diagnosis = ogeom_algo::check(&model, &result.shape, T).unwrap();
    assert!(diagnosis.is_valid(), "{:?}", diagnosis.problems);
    let w = 2.0;
    let (ro, ri) = (r + w, r - w);
    let annulus = core::f64::consts::FRAC_PI_2 * (ro * ro - ri * ri);
    let leg_area = 2.0 * w * 2.0 * r;
    // ∫₀^w (r − √(ri² − y²)) dy: the arc's material already inside the leg
    // at one corner.
    let overlap = r * w - (w * (ri * ri - w * w).sqrt() / 2.0 + ri * ri / 2.0 * (w / ri).asin());
    let expected = (annulus + leg_area - 2.0 * overlap + 2.0 * w * w) * 2.0 * w;
    let measured = volume(&model, &result.shape);
    assert!(
        (measured - expected).abs() < expected * 5e-3,
        "D ring volume {measured} against {expected}"
    );
}

/// A corner that turns a curved leg out of its own plane: the two legs'
/// generators for one profile point are skew and never meet, and the sweep
/// says so by name instead of sewing a gap.
#[test]
fn a_skew_corner_against_a_curved_leg_is_refused_by_name() {
    let mut model = ogeom_topo::Model::new();
    let r = 20.0;
    let a = Point::new(r, 0.0, 0.0);
    let b = Point::new(0.0, r, 0.0);
    let c = Point::new(0.0, r, 20.0);
    let va = ogeom_algo::make_vertex(&mut model, a).shape;
    let vb = ogeom_algo::make_vertex(&mut model, b).shape;
    let vc = ogeom_algo::make_vertex(&mut model, c).shape;
    let arc = arc_between(
        &mut model,
        Point::ORIGIN,
        r,
        (0.0, core::f64::consts::FRAC_PI_2),
        &va,
        &vb,
    );
    let lcurve = ogeom_geom::Curve::Line(ogeom_geom::LineCurve::segment(b, c, T).unwrap());
    let ldomain = ogeom_geom::Curve3d::domain(&lcurve);
    let leg = ogeom_algo::make_edge_between(&mut model, lcurve, ldomain, &vb, &vc, T)
        .unwrap()
        .shape;
    let spine = ogeom_algo::make_wire(&mut model, &[arc, leg], T)
        .unwrap()
        .shape;
    let profile = square_profile(&mut model, a, ogeom_math::Vector::Y, 4.0);
    let err =
        ogeom_offset::make_pipe_shell(&mut model, &profile, &spine, false, 1e-3, T).unwrap_err();
    assert!(
        err.to_string().contains("skew corner against a curved leg"),
        "{err}"
    );
}