springrep 1.0.0

An exact boundary-representation geometry kernel, in safe Rust
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
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
//! STEP B-rep topology into a kernel solid: vertices and edges shared across faces, each face's
//! loops given pcurves that close in its parameter plane, with the seams and poles the kernel's
//! representation needs (doc/design.md, "Representation").
//!
//! A solid is read in three passes: the file's topology into [`Raw`], [`super::heal`] where the
//! file's geometry disagrees with itself by more than the kernel tolerance, then the arena.

use std::collections::HashMap;

use super::geometry::Geometry;
use super::heal;
use super::part21::Param;
use crate::{
    Error, Result, check,
    geom::{Circle, Curve, Line, Surface},
    math::{Frame, Point3, Vec2},
    tol,
    topo::{Brep, CoedgeSpec, EdgeId, FaceId, PCurve, ShellId, SolidId, VertexId, project_on},
};

fn bad<T>(id: u64, what: &str) -> Result<T> {
    Err(Error::InvalidInput(format!("STEP #{id}: {what}")))
}

fn unsupported<T>(id: u64, what: &str) -> Result<T> {
    Err(Error::Unsupported(format!("STEP #{id}: {what}")))
}

/// A face's use of an edge, in the kernel edge's direction or against it.
#[derive(Clone, Copy, Debug)]
pub(super) struct Use {
    pub edge: usize,
    pub reversed: bool,
}

/// An edge as the file gives it, turned to run along its curve: from `start` to `end`.
#[derive(Clone, Debug)]
pub(super) struct RawEdge {
    pub id: u64,
    pub curve: Curve,
    pub start: usize,
    pub end: usize,
    /// The faces that use it, once per use.
    pub faces: Vec<usize>,
}

#[derive(Clone, Debug)]
pub(super) struct RawFace {
    pub id: u64,
    pub name: String,
    pub surface: Surface,
    pub reversed: bool,
    /// Each bound: whether the file calls it the outer one, and its uses in loop order.
    pub bounds: Vec<(bool, Vec<Use>)>,
    /// The points its `VERTEX_LOOP`s hold inside it, where something touches it there.
    pub points: Vec<usize>,
}

/// One solid's topology and geometry as read, before any pcurve.
#[derive(Clone, Debug, Default)]
pub(super) struct Raw {
    pub points: Vec<Point3>,
    /// Each point's `VERTEX_POINT` instance.
    pub vertex_ids: Vec<u64>,
    pub edges: Vec<RawEdge>,
    pub faces: Vec<RawFace>,
    pub shells: Vec<Vec<usize>>,
}

/// The parameter of the point of `c` nearest `p`; a periodic curve's within its first period.
pub(super) fn param_of(c: &Curve, p: Point3) -> f64 {
    let (d0, d1) = c.domain();
    match c.period() {
        // A search over one period can stall at its ends, so a periodic curve is searched over
        // two periods half a period apart: the nearest point is inside at least one of them.
        Some(per) => {
            let t = [d0, d0 + 0.5 * per]
                .map(|a| c.project(p, a, a + per))
                .into_iter()
                .min_by(|&a, &b| c.eval(a).dist(p).total_cmp(&c.eval(b).dist(p)))
                .unwrap_or(d0);
            d0 + (t - d0).rem_euclid(per)
        }
        None if d0.is_finite() => c.project(p, d0, d1),
        None => c.project(p, -1e12, 1e12),
    }
}

/// The parameter range of an edge of `c` from `ps` to `pe`; `closed` when both are one vertex.
pub(super) fn edge_range(c: &Curve, ps: Point3, pe: Point3, closed: bool) -> Option<(f64, f64)> {
    let (d0, d1) = c.domain();
    let t0 = param_of(c, ps);
    let mut t1 = param_of(c, pe);
    match c.period() {
        Some(p) if closed => t1 = t0 + p,
        Some(p) => {
            t1 = t0 + (t1 - t0).rem_euclid(p);
            // A vertex at the join of the period projects to either end of it.
            if (t1 - t0).abs() <= tol::param(c.d1(t0).1.norm()) {
                t1 = t0 + p;
            }
        }
        None if closed => return None,
        None => {}
    }
    let snap = |t: f64| {
        if c.period().is_some() || !d0.is_finite() {
            return t;
        }
        let near = tol::param(c.d1(t).1.norm());
        if (t - d0).abs() <= near {
            d0
        } else if (t - d1).abs() <= near {
            d1
        } else {
            t
        }
    };
    let (t0, t1) = (snap(t0), snap(t1));
    (t1 > t0).then_some((t0, t1))
}

/// `raw` without the edges split in two after they were read, which no face uses any more.
fn without_split(mut raw: Raw, splits: &HashMap<usize, [usize; 2]>) -> Raw {
    if splits.is_empty() {
        return raw;
    }
    let mut index = vec![usize::MAX; raw.edges.len()];
    let mut kept = Vec::with_capacity(raw.edges.len());
    for (i, e) in raw.edges.drain(..).enumerate() {
        if !splits.contains_key(&i) {
            index[i] = kept.len();
            kept.push(e);
        }
    }
    raw.edges = kept;
    for f in &mut raw.faces {
        for (_, uses) in &mut f.bounds {
            for u in uses {
                u.edge = index[u.edge];
            }
        }
    }
    raw
}

/// `raw` with its coincident vertices made one, and then its coincident edges. A solid that
/// touches itself is written, as STEP's manifold solids require, with each side of the contact
/// given its own vertices and edges; two vertices of one valid solid are never that close, so
/// coincident ones are such a contact, and joining them gives it back.
fn join_contacts(mut raw: Raw) -> Raw {
    let n = raw.points.len();
    let mut parent: Vec<usize> = (0..n).collect();
    fn root(p: &mut [usize], mut i: usize) -> usize {
        while p[i] != i {
            p[i] = p[p[i]];
            i = p[i];
        }
        i
    }
    let mut order: Vec<usize> = (0..n).collect();
    order.sort_by(|&a, &b| raw.points[a].x.total_cmp(&raw.points[b].x));
    let mut joined = false;
    for (k, &i) in order.iter().enumerate() {
        for &j in &order[k + 1..] {
            if raw.points[j].x - raw.points[i].x > tol::LINEAR {
                break;
            }
            if raw.points[i].dist(raw.points[j]) <= tol::LINEAR {
                let (a, b) = (root(&mut parent, i), root(&mut parent, j));
                if a != b {
                    parent[a.max(b)] = a.min(b);
                    joined = true;
                }
            }
        }
    }
    if joined {
        // The points kept, renumbered in order.
        let mut index = vec![usize::MAX; n];
        let (mut points, mut ids) = (Vec::new(), Vec::new());
        for (i, slot) in index.iter_mut().enumerate() {
            if root(&mut parent, i) == i {
                *slot = points.len();
                points.push(raw.points[i]);
                ids.push(raw.vertex_ids[i]);
            }
        }
        let at: Vec<usize> = (0..n).map(|i| index[root(&mut parent, i)]).collect();
        raw.points = points;
        raw.vertex_ids = ids;
        for e in &mut raw.edges {
            e.start = at[e.start];
            e.end = at[e.end];
        }
        for f in &mut raw.faces {
            for v in &mut f.points {
                *v = at[*v];
            }
        }
    }
    // Edges between the same vertices that lie along each other: each later one is the first,
    // its uses turned where it runs the other way.
    let mut ends: HashMap<(usize, usize), Vec<usize>> = HashMap::new();
    for (i, e) in raw.edges.iter().enumerate() {
        ends.entry((e.start.min(e.end), e.start.max(e.end)))
            .or_default()
            .push(i);
    }
    let m = raw.edges.len();
    let mut into: Vec<(usize, bool)> = (0..m).map(|i| (i, false)).collect();
    let mut any = false;
    for group in ends.values().filter(|g| g.len() > 1) {
        for (k, &i) in group.iter().enumerate() {
            if into[i].0 != i {
                continue;
            }
            let a = &raw.edges[i];
            let (pa, pz) = (raw.points[a.start], raw.points[a.end]);
            let Some((t0, t1)) = edge_range(&a.curve, pa, pz, a.start == a.end) else {
                continue;
            };
            let (q, d) = a.curve.d1(0.5 * (t0 + t1));
            for &j in &group[k + 1..] {
                let b = &raw.edges[j];
                if into[j].0 != j {
                    continue;
                }
                // On `b`'s curve within its range: two arcs of one circle share their ends too.
                let (pb, pe) = (raw.points[b.start], raw.points[b.end]);
                let Some((u0, u1)) = edge_range(&b.curve, pb, pe, b.start == b.end) else {
                    continue;
                };
                let mut t = param_of(&b.curve, q);
                if let Some(p) = b.curve.period() {
                    t = u0 + (t - u0).rem_euclid(p);
                }
                let (r, dr) = b.curve.d1(t);
                if (u0..=u1).contains(&t) && r.dist(q) <= tol::LINEAR {
                    into[j] = (i, d.dot(dr) < 0.0);
                    any = true;
                }
            }
        }
    }
    if !any {
        return raw;
    }
    let mut kept = vec![usize::MAX; m];
    let mut edges = Vec::new();
    for i in 0..m {
        if into[i].0 == i {
            kept[i] = edges.len();
            edges.push(raw.edges[i].clone());
        }
    }
    for (i, &(to, _)) in into.iter().enumerate() {
        if to != i {
            let faces = raw.edges[i].faces.clone();
            edges[kept[to]].faces.extend(faces);
        }
    }
    raw.edges = edges;
    for f in &mut raw.faces {
        for (_, uses) in &mut f.bounds {
            for u in uses {
                let (to, flip) = into[u.edge];
                u.edge = kept[to];
                u.reversed ^= flip;
            }
        }
    }
    raw
}

/// The vertex a use starts at.
fn use_start(raw: &Raw, u: &Use) -> usize {
    let e = &raw.edges[u.edge];
    if u.reversed { e.end } else { e.start }
}

/// Reads one solid's topology, sharing vertices and edges between its faces.
struct Reader<'g, 'a> {
    geo: &'g mut Geometry<'a>,
    raw: Raw,
    vertices: HashMap<u64, usize>,
    /// Each edge's index and whether it runs against the STEP edge's direction.
    edges: HashMap<u64, (usize, bool)>,
    /// A `POLY_LOOP`'s corners, by their coordinates, and its sides, by their two corners.
    corners: HashMap<[u64; 3], usize>,
    sides: HashMap<(usize, usize), usize>,
    /// Edges split in two after they were read, to give a seam a vertex: each one's two halves.
    splits: HashMap<usize, [usize; 2]>,
}

/// One bound of a face as the file gives it.
enum Bound {
    /// Whether the file calls it the outer bound, and its uses in loop order.
    Edges(bool, Vec<Use>),
    /// A `VERTEX_LOOP`: the face closes on this one vertex, the apex of a cone or the pole of a
    /// sphere, or, anywhere else, holds it as a point where something touches the face.
    Vertex(usize),
}

impl<'g, 'a> Reader<'g, 'a> {
    fn params(&self, id: u64, kinds: &[&str]) -> Result<(&'a str, &'a [Param])> {
        let Some(e) = self.geo.file.get(id) else {
            return bad(id, "missing instance");
        };
        for (k, p) in &e.parts {
            if kinds.contains(&k.as_str()) {
                return Ok((k.as_str(), p.as_slice()));
            }
        }
        unsupported(
            id,
            &format!("{} where {} was expected", e.kind(), kinds.join(" or ")),
        )
    }

    fn vertex(&mut self, id: u64) -> Result<usize> {
        if let Some(&v) = self.vertices.get(&id) {
            return Ok(v);
        }
        let (_, a) = self.params(id, &["VERTEX_POINT"])?;
        let p = self.geo.point(self.geo.reference(id, a.get(1))?)?;
        self.raw.points.push(p);
        self.raw.vertex_ids.push(id);
        let v = self.raw.points.len() - 1;
        self.vertices.insert(id, v);
        Ok(v)
    }

    fn edge(&mut self, id: u64) -> Result<(usize, bool)> {
        if let Some(&e) = self.edges.get(&id) {
            return Ok(e);
        }
        let (_, a) = self.params(id, &["EDGE_CURVE"])?;
        let vs = self.vertex(self.geo.reference(id, a.get(1))?)?;
        let ve = self.vertex(self.geo.reference(id, a.get(2))?)?;
        let curve = self.geo.curve(self.geo.reference(id, a.get(3))?)?;
        let flip = a.get(4).and_then(Param::as_bool) == Some(false);
        let (start, end) = if flip { (ve, vs) } else { (vs, ve) };
        self.raw.edges.push(RawEdge {
            id,
            curve,
            start,
            end,
            faces: Vec::new(),
        });
        let e = (self.raw.edges.len() - 1, flip);
        self.edges.insert(id, e);
        Ok(e)
    }

    /// The vertex at a `POLY_LOOP` corner; corners at one place are one vertex.
    fn corner(&mut self, id: u64) -> Result<usize> {
        let p = self.geo.point(id)?;
        let key = [p.x.to_bits(), p.y.to_bits(), p.z.to_bits()];
        if let Some(&v) = self.corners.get(&key) {
            return Ok(v);
        }
        self.raw.points.push(p);
        self.raw.vertex_ids.push(id);
        let v = self.raw.points.len() - 1;
        self.corners.insert(key, v);
        Ok(v)
    }

    /// The uses of a `POLY_LOOP`'s straight sides, each side shared with the face across it.
    fn poly_loop(&mut self, lp: u64, la: &[Param], forward: bool) -> Result<Vec<Use>> {
        let mut corners = Vec::new();
        for p in la.get(1).and_then(Param::as_list).unwrap_or(&[]) {
            corners.push(self.corner(self.geo.reference(lp, Some(p))?)?);
        }
        corners.dedup();
        while corners.len() > 1 && corners.first() == corners.last() {
            corners.pop();
        }
        if corners.len() < 3 {
            return bad(lp, "a polygon needs three distinct corners");
        }
        let mut uses = Vec::new();
        for k in 0..corners.len() {
            let (a, b) = (corners[k], corners[(k + 1) % corners.len()]);
            let edge = match self.sides.get(&(a.min(b), a.max(b))) {
                Some(&e) => e,
                None => {
                    let (pa, pb) = (self.raw.points[a], self.raw.points[b]);
                    let Some(dir) = (pb - pa).unit() else {
                        return bad(lp, "a polygon side has no length");
                    };
                    self.raw.edges.push(RawEdge {
                        id: lp,
                        curve: Curve::Line(Line { origin: pa, dir }),
                        start: a,
                        end: b,
                        faces: Vec::new(),
                    });
                    let e = self.raw.edges.len() - 1;
                    self.sides.insert((a.min(b), a.max(b)), e);
                    e
                }
            };
            let along = self.raw.edges[edge].start == a;
            uses.push(Use {
                edge,
                reversed: along != forward,
            });
        }
        if !forward {
            uses.reverse();
        }
        Ok(uses)
    }

    /// The edge uses of one `FACE_BOUND`, in the kernel's direction for the face.
    fn bound(&mut self, id: u64, flip_face: bool) -> Result<Bound> {
        let (kind, a) = self.params(id, &["FACE_OUTER_BOUND", "FACE_BOUND"])?;
        let outer = kind == "FACE_OUTER_BOUND";
        let lp = self.geo.reference(id, a.get(1))?;
        let orient = a.get(2).and_then(Param::as_bool) != Some(false);
        let (lk, la) = self.params(lp, &["EDGE_LOOP", "VERTEX_LOOP", "POLY_LOOP"])?;
        match lk {
            "VERTEX_LOOP" => {
                return Ok(Bound::Vertex(
                    self.vertex(self.geo.reference(lp, la.get(1))?)?,
                ));
            }
            "POLY_LOOP" => {
                return Ok(Bound::Edges(
                    outer,
                    self.poly_loop(lp, la, orient != flip_face)?,
                ));
            }
            _ => {}
        }
        let mut uses = Vec::new();
        for oe in la.get(1).and_then(Param::as_list).unwrap_or(&[]) {
            let oe = self.geo.reference(lp, Some(oe))?;
            let (_, p) = self.params(oe, &["ORIENTED_EDGE"])?;
            let (edge, flip) = self.edge(self.geo.reference(oe, p.get(3))?)?;
            let along = p.get(4).and_then(Param::as_bool) != Some(false);
            uses.push(Use {
                edge,
                reversed: ((along == orient) ^ flip_face) == flip,
            });
        }
        if !orient ^ flip_face {
            uses.reverse();
        }
        if uses.is_empty() {
            return bad(lp, "empty loop");
        }
        Ok(Bound::Edges(outer, self.expand(&uses)))
    }

    /// A seam from `from` to `apex` along `surface`, for a face that closes on its apex: a
    /// generator of a cone, a meridian of a sphere.
    fn seam(&mut self, id: u64, surface: &Surface, from: usize, apex: usize) -> Result<usize> {
        let (p, q) = (self.raw.points[from], self.raw.points[apex]);
        let curve = match surface {
            Surface::Cone(_) => match (q - p).unit() {
                Some(dir) => Curve::Line(Line { origin: p, dir }),
                None => return bad(id, "the vertex loop sits on its face's other bound"),
            },
            Surface::Sphere(s) => {
                let c = s.frame.origin;
                let x = p - c;
                let y = (q - c) - x.unit_or_zero() * (q - c).dot(x.unit_or_zero());
                match Frame::new(c, x.cross(y), x) {
                    Ok(frame) => Curve::Circle(Circle {
                        frame,
                        radius: s.radius,
                    }),
                    Err(_) => return bad(id, "the vertex loop is not at a pole of its sphere"),
                }
            }
            other => {
                return unsupported(id, &format!("VERTEX_LOOP bound on a {} face", other.kind()));
            }
        };
        self.raw.edges.push(RawEdge {
            id,
            curve,
            start: from,
            end: apex,
            faces: Vec::new(),
        });
        Ok(self.raw.edges.len() - 1)
    }

    /// `uses` with each use of a split edge as the uses of its halves.
    fn expand(&self, uses: &[Use]) -> Vec<Use> {
        let mut out = Vec::with_capacity(uses.len());
        for &u in uses {
            match self.splits.get(&u.edge) {
                Some(&[a, b]) => {
                    let halves = [Use { edge: a, ..u }, Use { edge: b, ..u }];
                    let ordered = if u.reversed {
                        [halves[1], halves[0]]
                    } else {
                        halves
                    };
                    out.extend(self.expand(&ordered));
                }
                None => out.push(u),
            }
        }
        out
    }

    /// Splits edge `e` at its parameter `t` into two edges meeting at a new vertex there, and
    /// gives every face read so far, and `bounds`, the halves in its place. Returns the vertex.
    fn split_edge(&mut self, e: usize, t: f64, bounds: &mut [(bool, Vec<Use>)]) -> usize {
        let edge = self.raw.edges[e].clone();
        let p = edge.curve.eval(t);
        self.raw.points.push(p);
        self.raw.vertex_ids.push(edge.id);
        let v = self.raw.points.len() - 1;
        self.raw.edges.push(RawEdge {
            end: v,
            ..edge.clone()
        });
        self.raw.edges.push(RawEdge { start: v, ..edge });
        let n = self.raw.edges.len();
        self.splits.insert(e, [n - 2, n - 1]);
        for f in 0..self.raw.faces.len() {
            for b in 0..self.raw.faces[f].bounds.len() {
                let uses = self.expand(&self.raw.faces[f].bounds[b].1);
                self.raw.faces[f].bounds[b].1 = uses;
            }
        }
        for (_, uses) in bounds.iter_mut() {
            *uses = self.expand(uses);
        }
        v
    }

    /// Where `uses` cross the angle `at` about `frame`'s axis, as an edge and its parameter.
    fn crossing(&self, frame: &Frame, uses: &[Use], at: f64) -> Option<(usize, f64)> {
        let off = |p: Point3| {
            let l = frame.to_local(p);
            (l.y.atan2(l.x) - at + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU)
                - std::f64::consts::PI
        };
        for u in uses {
            let e = &self.raw.edges[u.edge];
            let (ps, pe) = (self.raw.points[e.start], self.raw.points[e.end]);
            let (t0, t1) = edge_range(&e.curve, ps, pe, e.start == e.end)?;
            let n = 64;
            for k in 0..n {
                let (mut lo, mut hi) = (
                    t0 + (t1 - t0) * k as f64 / n as f64,
                    t0 + (t1 - t0) * (k + 1) as f64 / n as f64,
                );
                let (dl, dh) = (off(e.curve.eval(lo)), off(e.curve.eval(hi)));
                // A sign change away from the wrap at half a turn.
                if dl.signum() == dh.signum() || dl.abs().max(dh.abs()) > 1.0 {
                    continue;
                }
                for _ in 0..100 {
                    let mid = 0.5 * (lo + hi);
                    if off(e.curve.eval(mid)).signum() == dl.signum() {
                        lo = mid;
                    } else {
                        hi = mid;
                    }
                }
                return Some((u.edge, 0.5 * (lo + hi)));
            }
        }
        None
    }

    /// The angle `uses` sweep about `frame`'s axis, from samples along each edge in its use's
    /// direction; `None` where an edge's span between its vertices cannot be found, or where the
    /// loop passes over the axis, as a seam through a pole does, and its angle jumps.
    fn swept(&self, frame: &Frame, uses: &[Use]) -> Option<f64> {
        let angle = |p: Point3| {
            let l = frame.to_local(p);
            l.y.atan2(l.x)
        };
        let mut total = 0.0;
        for u in uses {
            let e = &self.raw.edges[u.edge];
            let (ps, pe) = (self.raw.points[e.start], self.raw.points[e.end]);
            let (t0, t1) = edge_range(&e.curve, ps, pe, e.start == e.end)?;
            let n = 64;
            let mut ts: Vec<f64> = (0..=n)
                .map(|k| t0 + (t1 - t0) * k as f64 / n as f64)
                .collect();
            if u.reversed {
                ts.reverse();
            }
            for w in ts.windows(2) {
                let d = angle(e.curve.eval(w[1])) - angle(e.curve.eval(w[0]));
                let d = (d + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU)
                    - std::f64::consts::PI;
                if d.abs() > 1.0 {
                    return None;
                }
                total += d;
            }
        }
        Some(total)
    }

    /// A face of revolution (cylinder, cone, sphere, torus) with two loops that each go once round
    /// its axis, the ways opposite, and no seam: those two become one loop, the first, a seam
    /// along the surface to a vertex of the second at the same angle, the second, and the seam
    /// back. Its pcurves then close in the parameter plane, as the kernel's faces do. Other loops,
    /// holes through the band, stay. `reversed` is the face's orientation against its surface's.
    /// `None` when the face is not such a band, or no vertex of the second lies on the seam's line.
    fn seamed_band(
        &mut self,
        id: u64,
        surface: &Surface,
        reversed: bool,
        bounds: &mut Vec<(bool, Vec<Use>)>,
    ) -> Option<()> {
        let frame = match surface {
            Surface::Cylinder(c) => c.frame,
            Surface::Cone(c) => c.frame,
            Surface::Sphere(s) => s.frame,
            Surface::Torus(t) => t.frame,
            _ => return None,
        };
        let full = |w: f64| (w.abs() - std::f64::consts::TAU).abs() < 0.1;
        let mut winding = Vec::new();
        for (k, (_, uses)) in bounds.iter().enumerate() {
            let w = self.swept(&frame, uses)?;
            if full(w) {
                winding.push((k, w));
            }
        }
        let &[(ka, wa), (kb, wb)] = winding.as_slice() else {
            return None;
        };
        if wa * wb >= 0.0 {
            return None;
        }
        let (a, b) = (&bounds[ka].1, &bounds[kb].1);
        // A vertex of each loop on one line of the surface: a cylinder's lines run along its
        // axis, a cone's through its apex.
        let on_line = |p: Point3, q: Point3| {
            let (lp, lq) = (frame.to_local(p), frame.to_local(q));
            let radial = |l: Point3| (l.x * l.x + l.y * l.y).sqrt();
            let (rp, rq) = (radial(lp), radial(lq));
            if rp <= tol::LINEAR || rq <= tol::LINEAR {
                return false;
            }
            let (ux, uy) = (lp.x / rp, lp.y / rp);
            (lq.x - ux * rq).hypot(lq.y - uy * rq) <= tol::LINEAR
        };
        let aligned = (0..a.len())
            .flat_map(|i| (0..b.len()).map(move |j| (i, j)))
            .find(|&(i, j)| {
                let at = |u: &Use| self.raw.points[use_start(&self.raw, u)];
                on_line(at(&a[i]), at(&b[j]))
            });
        let (a, b, ia, ib) = match aligned {
            Some((i, j)) => (a.clone(), b.clone(), i, j),
            None => {
                // No vertex of the second loop at the first's angle: split the second's edge
                // there, in every face that uses it.
                let va = use_start(&self.raw, &a[0]);
                let la = frame.to_local(self.raw.points[va]);
                let (e, t) = self.crossing(&frame, b, la.y.atan2(la.x))?;
                let v = self.split_edge(e, t, bounds);
                let (a, b) = (bounds[ka].1.clone(), bounds[kb].1.clone());
                let ia = a.iter().position(|u| use_start(&self.raw, u) == va)?;
                let ib = b.iter().position(|u| use_start(&self.raw, u) == v)?;
                (a, b, ia, ib)
            }
        };
        let (va, vb) = (use_start(&self.raw, &a[ia]), use_start(&self.raw, &b[ib]));
        let (pa, pb) = (self.raw.points[va], self.raw.points[vb]);
        // The seam's line at the vertices' angle about the axis.
        let la = frame.to_local(pa);
        let radial = (frame.x * la.x + frame.y * la.y).unit()?;
        let meridian = |centre: Point3, radius: f64, toward_v: bool| {
            // A circle whose parameter is the surface's v there, or runs against it.
            let normal = radial.cross(frame.z) * if toward_v { 1.0 } else { -1.0 };
            Frame::new(centre, normal, radial)
                .ok()
                .map(|frame| Curve::Circle(Circle { frame, radius }))
        };
        let curve = match surface {
            Surface::Cylinder(_) | Surface::Cone(_) => Curve::Line(Line {
                origin: pa,
                dir: (pb - pa).unit()?,
            }),
            // A latitude band: the meridian between the two loops, which v crosses one way.
            Surface::Sphere(s) => {
                let v = |p: Point3| {
                    frame
                        .to_local(p)
                        .z
                        .atan2(frame.to_local(p).x.hypot(frame.to_local(p).y))
                };
                meridian(s.frame.origin, s.radius, v(pb) > v(pa))?
            }
            // A ring of the tube: the first loop's material lies on its left, seen from outside,
            // which is the way v grows from it when it runs the way u grows on a face along its
            // surface's normal.
            Surface::Torus(t) => {
                let toward_v = (wa > 0.0) != reversed;
                meridian(frame.origin + radial * t.major, t.minor, toward_v)?
            }
            _ => return None,
        };
        self.raw.edges.push(RawEdge {
            id,
            curve,
            start: va,
            end: vb,
            faces: Vec::new(),
        });
        let seam = self.raw.edges.len() - 1;
        let mut out: Vec<Use> = a[ia..].iter().chain(&a[..ia]).copied().collect();
        out.push(Use {
            edge: seam,
            reversed: false,
        });
        out.extend(b[ib..].iter().chain(&b[..ib]).copied());
        out.push(Use {
            edge: seam,
            reversed: true,
        });
        bounds.remove(ka.max(kb));
        bounds.remove(ka.min(kb));
        bounds.insert(0, (true, out));
        Some(())
    }

    /// A sphere or cone face with one loop that goes once round its axis and no seam: a cap over
    /// the pole on the loop's left seen from outside, or over the cone's apex, the only side that
    /// closes. As a vertex loop there would, it gives the loop a seam up to the pole and back. A
    /// loop through a pole of a sphere's frame, such as a hemisphere's great circle, is a latitude
    /// of the frame about its circle's normal, which then becomes the surface's frame. Other loops,
    /// holes through the cap, stay. False when the face is not such a cap.
    fn capped(
        &mut self,
        id: u64,
        surface: &mut Surface,
        reversed: bool,
        bounds: &mut [(bool, Vec<Use>)],
    ) -> Result<bool> {
        let (base, sphere) = match &*surface {
            Surface::Sphere(s) => (s.frame, true),
            Surface::Cone(c) if c.half_angle.abs() > tol::ANGULAR => (c.frame, false),
            _ => return Ok(false),
        };
        let mut found = None;
        for (k, (_, uses)) in bounds.iter().enumerate() {
            // A loop through the apex, or a pole, already closes on it by its own seam.
            let at_pole = uses.iter().any(|u| {
                let l = base.to_local(self.raw.points[use_start(&self.raw, u)]);
                l.x.hypot(l.y) <= tol::LINEAR
            });
            let frame = match uses.as_slice() {
                _ if !at_pole => base,
                [u] if sphere => match &self.raw.edges[u.edge].curve {
                    Curve::Circle(c) => match Frame::new(base.origin, c.frame.z, c.frame.x) {
                        Ok(f) => f,
                        Err(_) => continue,
                    },
                    _ => continue,
                },
                _ => continue,
            };
            let Some(w) = self.swept(&frame, uses) else {
                continue;
            };
            if (w.abs() - std::f64::consts::TAU).abs() < 0.1 {
                if found.is_some() {
                    return Ok(false);
                }
                found = Some((k, frame, w));
            }
        }
        let Some((k, frame, w)) = found else {
            return Ok(false);
        };
        let uses = &bounds[k].1;
        let pole = match surface {
            Surface::Sphere(s) => {
                s.frame = frame;
                // Along the outward normal, a loop running the way u grows has +z on its left.
                let up = (w > 0.0) != reversed;
                frame.origin + frame.z * if up { s.radius } else { -s.radius }
            }
            Surface::Cone(c) => c.frame.origin - c.frame.z * (c.radius / c.half_angle.tan()),
            _ => return Ok(false),
        };
        self.raw.points.push(pole);
        self.raw.vertex_ids.push(id);
        let apex = self.raw.points.len() - 1;
        let from = use_start(&self.raw, &uses[0]);
        let seam = self.seam(id, surface, from, apex)?;
        for reversed in [false, true] {
            bounds[k].1.push(Use {
                edge: seam,
                reversed,
            });
        }
        Ok(true)
    }

    fn face(&mut self, id: u64, flip_face: bool) -> Result<usize> {
        let (_, a) = self.params(id, &["ADVANCED_FACE", "FACE_SURFACE"])?;
        let name = a.first().and_then(Param::as_str).unwrap_or("").to_string();
        let mut surface = self.geo.surface(self.geo.reference(id, a.get(2))?)?;
        let same_sense = a.get(3).and_then(Param::as_bool) != Some(false);
        let mut bounds = Vec::new();
        let mut apexes = Vec::new();
        for bd in a.get(1).and_then(Param::as_list).unwrap_or(&[]) {
            match self.bound(self.geo.reference(id, Some(bd))?, flip_face)? {
                Bound::Edges(outer, uses) => bounds.push((outer, uses)),
                Bound::Vertex(v) => apexes.push(v),
            }
        }
        let (mut apexes, points): (Vec<usize>, Vec<usize>) = apexes
            .into_iter()
            .partition(|&v| closes_at(&surface, self.raw.points[v]));
        for &v in &points {
            let p = self.raw.points[v];
            let uv = surface.project(p);
            if surface.eval(uv.x, uv.y).dist(p) > tol::LINEAR {
                return bad(id, "a VERTEX_LOOP off its face's surface");
            }
        }
        // A whole sphere, bounded only by a vertex loop at one pole: the kernel's seam, a
        // meridian from the other pole to it, used both ways.
        if let ([apex], 0, Surface::Sphere(sp)) = (apexes.as_slice(), bounds.len(), &surface) {
            let (c, p) = (sp.frame.origin, self.raw.points[*apex]);
            let other = c * 2.0 - p;
            self.raw.points.push(other);
            self.raw.vertex_ids.push(id);
            let from = self.raw.points.len() - 1;
            let x = (other - c).unit_or_zero();
            let Ok(frame) = Frame::new(c, x.cross(sp.frame.x), x) else {
                return bad(id, "the vertex loop is not at a pole of its sphere");
            };
            self.raw.edges.push(RawEdge {
                id,
                curve: Curve::Circle(Circle {
                    frame,
                    radius: sp.radius,
                }),
                start: from,
                end: *apex,
                faces: Vec::new(),
            });
            let seam = self.raw.edges.len() - 1;
            bounds.push((
                true,
                vec![
                    Use {
                        edge: seam,
                        reversed: false,
                    },
                    Use {
                        edge: seam,
                        reversed: true,
                    },
                ],
            ));
            apexes.clear();
        }
        // A face that closes on a vertex is, in the kernel, its other bound followed by a seam
        // up to the vertex and back, the pole between the seam's two uses.
        match (apexes.as_slice(), bounds.len()) {
            ([], _) => {}
            (&[apex], 1) => {
                let uses = &bounds[0].1;
                let first = uses[0];
                let e = &self.raw.edges[first.edge];
                let from = if first.reversed { e.end } else { e.start };
                let seam = self.seam(id, &surface, from, apex)?;
                bounds[0].1.push(Use {
                    edge: seam,
                    reversed: false,
                });
                bounds[0].1.push(Use {
                    edge: seam,
                    reversed: true,
                });
            }
            _ => {
                return unsupported(
                    id,
                    "a vertex loop other than one face's apex beside one other bound",
                );
            }
        }
        if bounds.is_empty() {
            return unsupported(id, "face without bounds");
        }
        let reversed = !same_sense ^ flip_face;
        if self
            .seamed_band(id, &surface, reversed, &mut bounds)
            .is_none()
            && apexes.is_empty()
        {
            self.capped(id, &mut surface, reversed, &mut bounds)?;
        }
        let f = self.raw.faces.len();
        for (_, uses) in &bounds {
            for u in uses {
                self.raw.edges[u.edge].faces.push(f);
            }
        }
        self.raw.faces.push(RawFace {
            id,
            name,
            surface,
            reversed: !same_sense ^ flip_face,
            bounds,
            points,
        });
        Ok(f)
    }

    fn solid(&mut self, id: u64) -> Result<()> {
        let Some(e) = self.geo.file.get(id) else {
            return bad(id, "missing instance");
        };
        let (kind, a) = (&e.parts[0].0, &e.parts[0].1);
        let mut shells: Vec<u64> = Vec::new();
        match kind.as_str() {
            "MANIFOLD_SOLID_BREP" | "FACETED_BREP" => {
                shells.push(self.geo.reference(id, a.get(1))?)
            }
            "BREP_WITH_VOIDS" => {
                shells.push(self.geo.reference(id, a.get(1))?);
                for v in a.get(2).and_then(Param::as_list).unwrap_or(&[]) {
                    shells.push(self.geo.reference(id, Some(v))?);
                }
            }
            other => return unsupported(id, &format!("solid {other}")),
        }
        for mut sh in shells {
            let mut flip = false;
            if let Some(p) = self
                .geo
                .file
                .get(sh)
                .and_then(|e| e.part("ORIENTED_CLOSED_SHELL"))
            {
                flip = p.get(3).and_then(Param::as_bool) == Some(false);
                sh = self.geo.reference(sh, p.get(2))?;
            }
            let (_, p) = self.params(sh, &["CLOSED_SHELL"])?;
            let mut faces = Vec::new();
            for f in p.get(1).and_then(Param::as_list).unwrap_or(&[]) {
                faces.push(self.face(self.geo.reference(sh, Some(f))?, flip)?);
            }
            self.raw.shells.push(faces);
        }
        Ok(())
    }
}

/// One coedge's samples in the parameter plane, in its own direction.
#[derive(Clone, Debug)]
struct Track {
    ts: Vec<f64>,
    uvs: Vec<Vec2>,
}

/// Builds the arena of a read (and, where needed, healed) solid.
struct Builder {
    b: Brep,
    vertices: Vec<VertexId>,
    edges: Vec<EdgeId>,
}

impl Builder {
    fn new(raw: &Raw, ranges: &[(f64, f64)]) -> Builder {
        let mut b = Brep::new();
        let vertices: Vec<VertexId> = raw.points.iter().map(|&p| b.add_vertex(p)).collect();
        let edges = raw
            .edges
            .iter()
            .zip(ranges)
            .map(|(e, &r)| b.add_edge(e.curve.clone(), r, vertices[e.start], vertices[e.end]))
            .collect();
        Builder { b, vertices, edges }
    }

    fn face(&mut self, f: &RawFace) -> Result<()> {
        let surface = &f.surface;
        let want = if f.reversed { -1.0 } else { 1.0 };
        let single = f.bounds.len() == 1;
        let mut tracks: Vec<(bool, &[Use], Vec<Track>)> = Vec::new();
        for (outer, uses) in &f.bounds {
            let sign = (*outer || single).then_some(want);
            let t = self
                .track_loop(surface, uses, sign)
                .or_else(|| self.track_loop(surface, uses, None));
            let Some(t) = t else {
                return Err(Error::InvalidInput(format!(
                    "STEP #{}: a loop of this {} face does not close in its parameters",
                    f.id,
                    surface.kind()
                )));
            };
            tracks.push((*outer, uses, t));
        }
        let areas: Vec<f64> = tracks.iter().map(|(_, _, t)| area2(t)).collect();
        let outer = (0..tracks.len())
            .filter(|&i| areas[i] * want > 0.0)
            .max_by(|&i, &j| {
                let key = |k: usize| (tracks[k].0, areas[k].abs());
                key(i)
                    .partial_cmp(&key(j))
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
            .unwrap_or(0);
        tracks.swap(0, outer);
        let (lo, hi) = uv_box(&tracks[0].2);
        for (_, _, t) in tracks.iter_mut().skip(1) {
            shift_into(surface, t, lo, hi);
        }
        let face = self.b.add_face(surface.clone(), f.reversed, []);
        for (_, uses, ts) in &tracks {
            let specs = self.specs(surface, uses, ts);
            self.b.add_loop(face, specs);
        }
        for &p in &f.points {
            let v = self.vertices[p];
            let mut at = [Track {
                ts: vec![0.0],
                uvs: vec![surface.project(self.b.vertex(v).point)],
            }];
            shift_into(surface, &mut at, lo, hi);
            let edge = self.b.add_degenerate_edge(v, (0.0, 1.0));
            let spec = CoedgeSpec {
                edge,
                reversed: false,
                pcurve: PCurve::Affine {
                    origin: at[0].uvs[0],
                    dir: Vec2::ZERO,
                },
            };
            self.b.add_loop(face, vec![spec]);
        }
        Ok(())
    }

    fn specs(&mut self, s: &Surface, uses: &[Use], tracks: &[Track]) -> Vec<CoedgeSpec> {
        let mut out = Vec::new();
        let n = uses.len();
        for k in 0..n {
            let (edge, reversed) = (self.edges[uses[k].edge], uses[k].reversed);
            let tr = &tracks[k];
            let pcurve = match (s, &self.b.edge(edge).curve) {
                (Surface::Plane(_), Some(Curve::Line(_))) => {
                    let (t0, t1) = (tr.ts[0], tr.ts[tr.ts.len() - 1]);
                    let (a, z) = (tr.uvs[0], tr.uvs[tr.uvs.len() - 1]);
                    let dir = (z - a) / (t1 - t0);
                    PCurve::Affine {
                        origin: a - dir * t0,
                        dir,
                    }
                }
                _ => PCurve::Projected { seed: tr.uvs[0] },
            };
            out.push(CoedgeSpec {
                edge,
                reversed,
                pcurve,
            });
            let end = tr.uvs[tr.uvs.len() - 1];
            let next = tracks[(k + 1) % n].uvs[0];
            if gap_is_pole(s, end, next) {
                let e = self.b.edge(edge);
                let v = if reversed { e.start } else { e.end };
                let d = self.b.add_degenerate_edge(v, (0.0, 1.0));
                out.push(CoedgeSpec {
                    edge: d,
                    reversed: false,
                    pcurve: PCurve::Affine {
                        origin: end,
                        dir: next - end,
                    },
                });
            }
        }
        out
    }

    /// The 3-D samples of a use of an edge, in its direction.
    fn samples(&self, u: Use) -> (Vec<f64>, Vec<Point3>) {
        let e = self.b.edge(self.edges[u.edge]);
        let c = e.curve.as_ref().expect("STEP edges have curves");
        let (t0, t1) = e.range;
        let mut cuts = vec![t0];
        cuts.extend(c.breakpoints(t0, t1));
        cuts.push(t1);
        let per = match c {
            Curve::Line(_) => 2,
            _ => (16 / (cuts.len() - 1)).max(4),
        };
        let mut ts = Vec::new();
        for w in cuts.windows(2) {
            for k in 0..per {
                ts.push(w[0] + (w[1] - w[0]) * k as f64 / per as f64);
            }
        }
        ts.push(t1);
        if u.reversed {
            ts.reverse();
        }
        let pts = ts.iter().map(|&t| c.eval(t)).collect();
        (ts, pts)
    }

    /// Each use's parameter-plane samples, continuous along the loop and closing back on its
    /// start; `None` if no choice of periods closes it. Where a loop leaves a pole the period it
    /// leaves in is free, and `sign`, when given, picks the choice that encloses area that way.
    fn track_loop(&self, s: &Surface, uses: &[Use], sign: Option<f64>) -> Option<Vec<Track>> {
        let samples: Vec<(Vec<f64>, Vec<Point3>)> = uses.iter().map(|&u| self.samples(u)).collect();
        let start = s.project(samples[0].1[0]);
        let mut acc = Vec::with_capacity(uses.len());
        self.track_from(s, uses, &samples, 0, start, sign, &mut acc)
            .then_some(acc)
    }

    #[allow(clippy::too_many_arguments)]
    fn track_from(
        &self,
        s: &Surface,
        uses: &[Use],
        samples: &[(Vec<f64>, Vec<Point3>)],
        k: usize,
        hint: Vec2,
        sign: Option<f64>,
        acc: &mut Vec<Track>,
    ) -> bool {
        if k == uses.len() {
            let (end, first) = (acc[k - 1].uvs[acc[k - 1].uvs.len() - 1], acc[0].uvs[0]);
            let closed = closes(s, end, first) || gap_is_pole(s, end, first);
            return closed && sign.is_none_or(|w| area2(acc) * w > 0.0);
        }
        let (ts, pts) = &samples[k];
        let first = s.project_near(pts[0], hint);
        let free = pole_free(s, first);
        let mut starts = vec![first];
        if free != (false, false) && pts.len() > 1 {
            // A use leaving a pole may leave at any angle: take the one its next point implies,
            // in each period near the hint.
            let inner = s.project_near(pts[1], hint);
            starts.clear();
            let shifts = |on: bool, p: Option<f64>| match p {
                Some(p) if on => vec![0.0, -p, p],
                _ => vec![0.0],
            };
            for du in shifts(free.0, s.u_period()) {
                for dv in shifts(free.1, s.v_period()) {
                    let mut c = first;
                    if free.0 {
                        c.x = inner.x + du;
                    }
                    if free.1 {
                        c.y = inner.y + dv;
                    }
                    starts.push(c);
                }
            }
            starts.sort_by(|a, b| a.dist(hint).total_cmp(&b.dist(hint)));
        }
        // A use running back over an earlier use of its edge is a slit, which a face may hold
        // where something touched it; a seam's second use runs a period away, so that is tried
        // first.
        for (slit, &st) in [false, true]
            .into_iter()
            .flat_map(|w| starts.iter().map(move |s| (w, s)))
        {
            let mut uvs = Vec::with_capacity(pts.len());
            uvs.push(st);
            for p in &pts[1..] {
                let prev = uvs[uvs.len() - 1];
                uvs.push(s.project_near(*p, prev));
            }
            let n = uvs.len();
            // At a pole the free parameter is the one the edge leaves it by, found as the
            // checker and every later reader of the pcurve finds it.
            let curve = self.b.edge(self.edges[uses[k].edge]).curve.as_ref();
            if let Some(c) = curve.filter(|_| n > 1) {
                if pole_free(s, uvs[0]) != (false, false) {
                    uvs[0] = project_on(s, c, ts[0], ts[1], st);
                }
                if pole_free(s, uvs[n - 1]) != (false, false) {
                    uvs[n - 1] = project_on(s, c, ts[n - 1], ts[n - 2], uvs[n - 2]);
                }
            }
            if coincides_with_twin(uses, acc, k, &uvs) != slit {
                continue;
            }
            let end = uvs[n - 1];
            acc.push(Track {
                ts: ts.clone(),
                uvs,
            });
            if self.track_from(s, uses, samples, k + 1, end, sign, acc) {
                return true;
            }
            acc.pop();
        }
        false
    }
}

/// Whether an earlier use of the same edge in this loop runs back over the same parameters: a slit,
/// where a seam's would run a period away.
fn coincides_with_twin(uses: &[Use], acc: &[Track], k: usize, uvs: &[Vec2]) -> bool {
    let n = uvs.len();
    (0..k).any(|j| {
        uses[j].edge == uses[k].edge && {
            let other = &acc[j].uvs;
            other.len() == n && other[n / 2].dist(uvs[n - 1 - n / 2]) < 1e-6
        }
    })
}

/// Whether the surface is singular at `uv`: `(u free, v free)` where moving in that parameter
/// does not move the point.
fn pole_free(s: &Surface, uv: Vec2) -> (bool, bool) {
    let (_, su, sv) = s.d1(uv.x, uv.y);
    (su.norm() <= tol::LINEAR, sv.norm() <= tol::LINEAR)
}

/// Whether `a` and `b` are the same point of the parameter plane, not a period apart.
fn closes(s: &Surface, a: Vec2, b: Vec2) -> bool {
    let near = |d: f64, p: Option<f64>| p.is_none_or(|p| d.abs() < 0.25 * p);
    near(a.x - b.x, s.u_period()) && near(a.y - b.y, s.v_period())
}

/// Whether the step from `a` to `b` is a pole's span: one point in space, apart in parameters.
fn gap_is_pole(s: &Surface, a: Vec2, b: Vec2) -> bool {
    let free = pole_free(s, a);
    if free == (false, false) {
        return false;
    }
    let (du, dv) = ((a.x - b.x).abs(), (a.y - b.y).abs());
    let (moved, held) = (1e-9, 1e-6);
    (free.0 && du > moved && dv <= held) || (free.1 && dv > moved && du <= held)
}

fn area2(tracks: &[Track]) -> f64 {
    let pts: Vec<Vec2> = tracks
        .iter()
        .flat_map(|t| t.uvs[..t.uvs.len() - 1].iter().copied())
        .collect();
    (0..pts.len())
        .map(|i| pts[i].cross(pts[(i + 1) % pts.len()]))
        .sum()
}

/// Whether a face on `s` bounded by a `VERTEX_LOOP` at `p` closes there: at a cone's apex or a
/// sphere's pole, where every parameter line meets.
fn closes_at(s: &Surface, p: Point3) -> bool {
    let near = |q: Point3| q.dist(p) <= tol::LINEAR;
    match s {
        Surface::Cone(c) => near(c.frame.origin - c.frame.z * (c.radius / c.half_angle.tan())),
        Surface::Sphere(sp) => {
            let (o, z) = (sp.frame.origin, sp.frame.z);
            near(o + z * sp.radius) || near(o - z * sp.radius)
        }
        _ => false,
    }
}

fn uv_box(tracks: &[Track]) -> (Vec2, Vec2) {
    let mut lo = Vec2::new(f64::INFINITY, f64::INFINITY);
    let mut hi = Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY);
    for p in tracks.iter().flat_map(|t| t.uvs.iter()) {
        lo = Vec2::new(lo.x.min(p.x), lo.y.min(p.y));
        hi = Vec2::new(hi.x.max(p.x), hi.y.max(p.y));
    }
    (lo, hi)
}

/// Moves a hole's samples by whole periods so its centre lies inside the outer loop's box.
fn shift_into(s: &Surface, tracks: &mut [Track], lo: Vec2, hi: Vec2) {
    let (a, b) = uv_box(tracks);
    let c = (a + b) * 0.5;
    let shift = |x: f64, lo: f64, hi: f64, p: Option<f64>| -> f64 {
        match p {
            Some(p) if x < lo || x > hi => ((0.5 * (lo + hi) - x) / p).round() * p,
            _ => 0.0,
        }
    };
    let d = Vec2::new(
        shift(c.x, lo.x, hi.x, s.u_period()),
        shift(c.y, lo.y, hi.y, s.v_period()),
    );
    if d.x != 0.0 || d.y != 0.0 {
        for t in tracks {
            for uv in &mut t.uvs {
                *uv = *uv + d;
            }
        }
    }
}

/// A solid read, its faces' STEP ids and names in order, and how far healing moved its geometry.
pub(super) type ReadSolid = (Brep, Vec<(u64, String)>, Option<heal::Healed>);

/// Builds the solid of a `MANIFOLD_SOLID_BREP` or `BREP_WITH_VOIDS`, healed where its geometry
/// disagrees with itself, and checked. Returns the solid, its faces' STEP ids and names in order,
/// and how far healing moved its geometry.
pub(super) fn solid(geo: &mut Geometry, id: u64) -> Result<ReadSolid> {
    if geo
        .file
        .get(id)
        .is_some_and(|e| e.part("TESSELLATED_SOLID").is_some())
    {
        return tessellated(geo, id).map(|b| {
            let names = vec![(0, String::new()); b.face_count()];
            (b, names, None)
        });
    }
    let mut rd = Reader {
        geo,
        raw: Raw::default(),
        vertices: HashMap::new(),
        edges: HashMap::new(),
        corners: HashMap::new(),
        sides: HashMap::new(),
        splits: HashMap::new(),
    };
    rd.solid(id)?;
    let uncertainty = rd.geo.uncertainty();
    let file = join_contacts(without_split(rd.raw, &rd.splits));
    let mut raw = file.clone();
    let names = || file.faces.iter().map(|f| (f.id, f.name.clone())).collect();
    let exact = heal::heal(&mut raw)
        .and_then(|(ranges, healed)| assemble(&raw, &ranges, None).map(|b| (b, healed)));
    let within = uncertainty.filter(|&u| u > tol::LINEAR);
    // Healing that moves geometry further than the file says its geometry meets has changed the
    // shape, not closed it: the file's geometry is kept instead where tolerances can hold it.
    let why = match exact {
        Ok((b, healed)) if within.is_none_or(|w| healed.as_ref().is_none_or(|h| h.moved <= w)) => {
            return Ok((b, names(), healed));
        }
        Ok((b, healed)) => Ok((b, healed)),
        Err(e) => Err(e),
    };
    // Geometry that cannot be made to meet within the kernel tolerance is kept as the file has
    // it, its edges and vertices given the tolerances it does meet within, whatever the file
    // states.
    let tolerant = |raw: &Raw| {
        let mut raw = raw.clone();
        heal::tolerate(&mut raw, within)
            .map_err(|t| format!("kept as the file has it, {t}"))
            .and_then(|t| {
                assemble(&raw, &t.ranges, Some(&t))
                    .map_err(|e| format!("kept as the file has it, with local tolerances: {e}"))
            })
    };
    match (tolerant(&file), why) {
        (Ok(b), _) => Ok((b, names(), None)),
        (Err(_), Ok((b, healed))) => Ok((b, names(), healed)),
        (Err(t), Err(e)) => {
            // Healed where it can be, and held by tolerances where it cannot.
            let mut loose = file.clone();
            let healed = heal::heal_loosely(&mut loose);
            let l = match (tolerant(&loose), healed.as_ref(), within) {
                (Ok(_), Some(h), Some(within)) if h.moved > within => format!(
                    "healing would move {} {:.1e} mm, more than the file's {within:.1e} mm",
                    h.what, h.moved
                ),
                (Ok(b), _, _) => return Ok((b, names(), healed)),
                (Err(l), _, _) => l,
            };
            Err(Error::InvalidInput(format!(
                "{e}; {t}; healed where it can be and {l}"
            )))
        }
    }
}

/// The checked arena of a solid read as `raw`, its edges over `ranges`, and its vertices and edges
/// given the local tolerances of `tolerated` where it is given.
fn assemble(raw: &Raw, ranges: &[(f64, f64)], tolerated: Option<&heal::Tolerated>) -> Result<Brep> {
    let mut b = build(raw, ranges, tolerated)?;
    // Some systems write a void's faces facing into it and turn its shell as well, which reads
    // inside out: a shell is the way the volume it encloses says, outer positive, void negative.
    let turned = check::turned_shells(&b);
    if !turned.is_empty() {
        b = build(&turned_round(raw, &turned), ranges, tolerated)?;
    }
    let issues = check::check_structure(&b);
    if !issues.is_empty() {
        return Err(Error::InvalidResult(
            issues.into_iter().map(|i| i.to_string()).collect(),
        ));
    }
    Ok(b)
}

/// `raw` with the faces of each of `turned`'s shells facing the other way.
fn turned_round(raw: &Raw, turned: &[(SolidId, ShellId, bool)]) -> Raw {
    let mut raw = raw.clone();
    for &(_, sh, _) in turned {
        for &f in &raw.shells[sh.index()].clone() {
            let face = &mut raw.faces[f];
            face.reversed = !face.reversed;
            for (_, uses) in &mut face.bounds {
                uses.reverse();
                for u in uses.iter_mut() {
                    u.reversed = !u.reversed;
                }
            }
        }
    }
    raw
}

/// The arena of a solid read as `raw`, as the file orients it, unchecked.
fn build(raw: &Raw, ranges: &[(f64, f64)], tolerated: Option<&heal::Tolerated>) -> Result<Brep> {
    let mut bld = Builder::new(raw, ranges);
    if let Some(t) = tolerated {
        for (v, &x) in t.vertices.iter().enumerate() {
            bld.b.set_vertex_tolerance(bld.vertices[v], x);
        }
        for (e, &x) in t.edges.iter().enumerate() {
            bld.b.set_edge_tolerance(bld.edges[e], x);
        }
    }
    for f in &raw.faces {
        bld.face(f)?;
    }
    let mut b = bld.b;
    let mut base = 0;
    let mut shells = Vec::new();
    for sh in &raw.shells {
        let ids: Vec<_> = b.face_ids().skip(base).take(sh.len()).collect();
        base += sh.len();
        shells.push(b.add_shell(ids));
    }
    b.add_solid(shells);
    // A solid that touches itself along an edge uses it four times; the file does not say which
    // faces pair across the material there, the faces round it do.
    b.pair_radial();
    Ok(b)
}

/// An AP242 `TESSELLATED_SOLID`: each triangle of its `TRIANGULATED_FACE`s a plane face, the
/// triangles sharing the edges between their corners. The triangles run counter-clockwise seen
/// from outside, as the schema has them.
fn tessellated(geo: &mut Geometry, id: u64) -> Result<Brep> {
    let unit = geo.length_unit();
    let Some(solid) = geo
        .file
        .get(id)
        .and_then(|e| e.part("TESSELLATED_SOLID"))
        .map(<[Param]>::to_vec)
    else {
        return bad(id, "expected a tessellated solid");
    };
    // Corners index their own face's list; one list's point is one vertex wherever it is used.
    let mut points: Vec<Point3> = Vec::new();
    let mut index: HashMap<(u64, usize), usize> = HashMap::new();
    let mut triangles: Vec<[usize; 3]> = Vec::new();
    for item in solid.get(1).and_then(Param::as_list).unwrap_or(&[]) {
        let fid = geo.reference(id, Some(item))?;
        let Some(face) = geo
            .file
            .get(fid)
            .and_then(|e| e.part("TRIANGULATED_FACE"))
            .map(<[Param]>::to_vec)
        else {
            return unsupported(fid, "a tessellated face other than a triangulated one");
        };
        let list = geo.reference(fid, face.get(1))?;
        let Some(coords) = geo
            .file
            .get(list)
            .and_then(|e| e.part("COORDINATES_LIST"))
            .map(<[Param]>::to_vec)
        else {
            return bad(list, "expected a coordinates list");
        };
        let mut xyz = Vec::new();
        for c in coords.get(2).and_then(Param::as_list).unwrap_or(&[]) {
            let v = geo.numbers(list, Some(c))?;
            if v.len() != 3 || v.iter().any(|x| !x.is_finite()) {
                return bad(list, "expected three finite coordinates");
            }
            xyz.push(Point3::new(v[0], v[1], v[2]) * unit);
        }
        // Triangle corners index the face's own points, which index the coordinates list.
        let own: Vec<usize> = face
            .get(5)
            .and_then(Param::as_list)
            .unwrap_or(&[])
            .iter()
            .map(|p| p.as_i64().map_or(0, |i| i as usize))
            .collect();
        let corner = |k: i64| -> Option<usize> {
            let k = usize::try_from(k).ok()?.checked_sub(1)?;
            let i = if own.is_empty() {
                k
            } else {
                own.get(k)?.checked_sub(1)?
            };
            (i < xyz.len()).then_some(i)
        };
        for tri in face.get(6).and_then(Param::as_list).unwrap_or(&[]) {
            let ks: Vec<i64> = tri
                .as_list()
                .unwrap_or(&[])
                .iter()
                .filter_map(Param::as_i64)
                .collect();
            let idx: Option<Vec<usize>> = ks.iter().map(|&k| corner(k)).collect();
            let Some(idx) = idx.filter(|v| v.len() == 3) else {
                return bad(fid, "a triangle needs three corners in its list");
            };
            let mut corners = [0; 3];
            for (corner, &i) in corners.iter_mut().zip(&idx) {
                *corner = *index.entry((list, i)).or_insert_with(|| {
                    points.push(xyz[i]);
                    points.len() - 1
                });
            }
            triangles.push(corners);
        }
    }
    if triangles.is_empty() {
        return bad(id, "a tessellated solid with no triangles");
    }
    crate::mesh::from_indexed(&points, &triangles)
}

/// Every face of the shells in `file`, each with its own vertices and edges, sewn into one solid:
/// vertices within `tolerance` of each other become one, edges that then share their ends and lie
/// together become one, faces are turned so each shared edge runs opposite ways in its two faces,
/// and the solid is healed onto its faces' surfaces as a read one is.
pub(super) fn sew(geo: &mut Geometry, tolerance: f64) -> Result<Brep> {
    let shells: Vec<u64> = geo
        .file
        .ids
        .iter()
        .zip(&geo.file.entities)
        .filter(|(_, e)| matches!(e.kind(), "OPEN_SHELL" | "CLOSED_SHELL"))
        .map(|(&id, _)| id)
        .collect();
    let mut rd = Reader {
        geo,
        raw: Raw::default(),
        vertices: HashMap::new(),
        edges: HashMap::new(),
        corners: HashMap::new(),
        sides: HashMap::new(),
        splits: HashMap::new(),
    };
    let mut faces = Vec::new();
    for sh in shells {
        let (_, p) = rd.params(sh, &["OPEN_SHELL", "CLOSED_SHELL"])?;
        for f in p.get(1).and_then(Param::as_list).unwrap_or(&[]) {
            faces.push(rd.face(rd.geo.reference(sh, Some(f))?, false)?);
        }
    }
    if faces.is_empty() {
        return Err(Error::InvalidInput(
            "STEP: the file holds no faces to sew".into(),
        ));
    }
    let mut raw = without_split(rd.raw, &rd.splits);
    // Points within the tolerance of each other are one, at their mean.
    let n = raw.points.len();
    let mut rep: Vec<usize> = (0..n).collect();
    fn root(rep: &mut [usize], i: usize) -> usize {
        let mut r = i;
        while rep[r] != r {
            r = rep[r];
        }
        rep[i] = r;
        r
    }
    for i in 0..n {
        for j in i + 1..n {
            if raw.points[i].dist(raw.points[j]) <= tolerance {
                let (a, b) = (root(&mut rep, i), root(&mut rep, j));
                if a != b {
                    rep[b] = a;
                }
            }
        }
    }
    let mut sum: HashMap<usize, (Point3, f64)> = HashMap::new();
    for i in 0..n {
        let r = root(&mut rep, i);
        let e = sum.entry(r).or_insert((Point3::ZERO, 0.0));
        e.0 += raw.points[i];
        e.1 += 1.0;
    }
    for i in 0..n {
        let r = root(&mut rep, i);
        let (s, k) = sum[&r];
        raw.points[i] = s * (1.0 / k);
    }
    // Edges that now run between one pair of points, and lie together along it, are one: the
    // first stands for the rest, and their uses are turned to its direction.
    let ends = |e: &RawEdge, rep: &mut [usize]| (root(rep, e.start), root(rep, e.end));
    let mut keep: Vec<usize> = (0..raw.edges.len()).collect();
    let mut turned = vec![false; raw.edges.len()];
    for i in 0..raw.edges.len() {
        if keep[i] != i {
            continue;
        }
        let (a, b) = ends(&raw.edges[i], &mut rep);
        let mid = |e: &RawEdge| {
            let (s, z) = (raw.points[e.start], raw.points[e.end]);
            let t = param_of(&e.curve, s.lerp(z, 0.5));
            e.curve.eval(t)
        };
        let mi = mid(&raw.edges[i]);
        for j in i + 1..raw.edges.len() {
            if keep[j] != j {
                continue;
            }
            let (c, d) = ends(&raw.edges[j], &mut rep);
            let same = (a, b) == (c, d);
            if !(same || (a, b) == (d, c)) || mid(&raw.edges[j]).dist(mi) > tolerance {
                continue;
            }
            keep[j] = i;
            turned[j] = !same;
        }
    }
    for f in &mut raw.faces {
        for (_, uses) in &mut f.bounds {
            for u in uses.iter_mut() {
                if keep[u.edge] != u.edge {
                    u.reversed ^= turned[u.edge];
                    u.edge = keep[u.edge];
                }
            }
        }
    }
    for e in &mut raw.edges {
        e.start = root(&mut rep, e.start);
        e.end = root(&mut rep, e.end);
    }
    // Each face's neighbours across its edges, and whether they agree: a shared edge runs one way
    // in one face and the other way in the other.
    let mut uses: HashMap<usize, Vec<(usize, bool)>> = HashMap::new();
    for (fi, f) in raw.faces.iter().enumerate() {
        for (_, us) in &f.bounds {
            for u in us {
                uses.entry(u.edge).or_default().push((fi, u.reversed));
            }
        }
    }
    let mut flip: Vec<Option<bool>> = vec![None; raw.faces.len()];
    for start in 0..raw.faces.len() {
        if flip[start].is_some() {
            continue;
        }
        flip[start] = Some(false);
        let mut stack = vec![start];
        while let Some(f) = stack.pop() {
            let mine = flip[f].unwrap_or(false);
            for (_, us) in &raw.faces[f].bounds {
                for u in us {
                    for &(g, rev) in uses.get(&u.edge).into_iter().flatten() {
                        if g == f || flip[g].is_some() {
                            continue;
                        }
                        // Agreeing faces use the edge opposite ways once both are turned as set.
                        let want = (u.reversed ^ mine) == rev;
                        flip[g] = Some(want);
                        stack.push(g);
                    }
                }
            }
        }
    }
    for (f, t) in raw.faces.iter_mut().zip(&flip) {
        if *t == Some(true) {
            f.reversed = !f.reversed;
            for (_, us) in &mut f.bounds {
                us.reverse();
                for u in us.iter_mut() {
                    u.reversed = !u.reversed;
                }
            }
        }
    }
    // Only the edges and points still used are kept, renumbered.
    let mut edge_at = vec![usize::MAX; raw.edges.len()];
    let mut edges = Vec::new();
    for (i, e) in raw.edges.drain(..).enumerate() {
        if keep[i] == i {
            edge_at[i] = edges.len();
            edges.push(e);
        }
    }
    raw.edges = edges;
    for f in &mut raw.faces {
        for (_, us) in &mut f.bounds {
            for u in us.iter_mut() {
                u.edge = edge_at[u.edge];
            }
        }
    }
    let mut point_at = vec![usize::MAX; raw.points.len()];
    let (mut points, mut ids) = (Vec::new(), Vec::new());
    for e in &mut raw.edges {
        for v in [&mut e.start, &mut e.end] {
            if point_at[*v] == usize::MAX {
                point_at[*v] = points.len();
                points.push(raw.points[*v]);
                ids.push(raw.vertex_ids[*v]);
            }
            *v = point_at[*v];
        }
    }
    for f in &mut raw.faces {
        for p in &mut f.points {
            *p = root(&mut rep, *p);
            if point_at[*p] == usize::MAX {
                point_at[*p] = points.len();
                points.push(raw.points[*p]);
                ids.push(raw.vertex_ids[*p]);
            }
            *p = point_at[*p];
        }
    }
    raw.points = points;
    raw.vertex_ids = ids;
    raw.edges.iter_mut().for_each(|e| e.faces.clear());
    for (fi, f) in raw.faces.iter().enumerate() {
        for (_, us) in &f.bounds {
            for u in us {
                raw.edges[u.edge].faces.push(fi);
            }
        }
    }
    raw.shells = vec![(0..raw.faces.len()).collect()];
    let (ranges, _) = heal::heal(&mut raw)?;
    assemble(&raw, &ranges, None)
}

/// `b` with each vertex at `points[v]`, each edge on `curves[e]` and each face on `surfaces[f]`,
/// its pcurves and parameter ranges found again as a file's are; `turned` runs every loop the
/// other way, for geometry that a mirror has turned inside out.
pub(crate) fn rebuilt(
    b: &Brep,
    points: Vec<Point3>,
    curves: Vec<Option<Curve>>,
    surfaces: Vec<Surface>,
    turned: bool,
) -> Result<Brep> {
    let mut raw = Raw {
        vertex_ids: (0..points.len() as u64).collect(),
        points,
        ..Raw::default()
    };
    let mut edge_at = vec![usize::MAX; curves.len()];
    for ((e, id), c) in b.edge_ids().enumerate().zip(curves) {
        if let Some(curve) = c {
            let x = b.edge(id);
            edge_at[e] = raw.edges.len();
            raw.edges.push(RawEdge {
                id: e as u64,
                curve,
                start: x.start.index(),
                end: x.end.index(),
                faces: Vec::new(),
            });
        }
    }
    let faces: Vec<FaceId> = b
        .face_ids()
        .filter(|&f| b.face(f).shell.is_some())
        .collect();
    for (&f, surface) in faces.iter().zip(surfaces) {
        let face = b.face(f);
        let mut bounds = Vec::new();
        for (k, &l) in face.loops.iter().enumerate() {
            let mut uses: Vec<Use> = b
                .lp(l)
                .coedges
                .iter()
                .map(|&c| b.coedge(c))
                .filter(|c| edge_at[c.edge.index()] != usize::MAX)
                .map(|c| Use {
                    edge: edge_at[c.edge.index()],
                    reversed: c.reversed ^ turned,
                })
                .collect();
            if turned {
                uses.reverse();
            }
            for u in &uses {
                raw.edges[u.edge].faces.push(raw.faces.len());
            }
            bounds.push((k == 0, uses));
        }
        raw.faces.push(RawFace {
            id: f.index() as u64,
            name: String::new(),
            surface,
            reversed: face.reversed ^ turned,
            bounds,
            points: Vec::new(),
        });
    }
    for sh in b.shell_ids() {
        let ids = &b.shell(sh).faces;
        raw.shells.push(
            ids.iter()
                .filter_map(|f| faces.iter().position(|g| g == f))
                .collect(),
        );
    }
    let (ranges, _) = heal::heal(&mut raw)?;
    let mut out = assemble(&raw, &ranges, None)?;
    for (g, &f) in out.face_ids().collect::<Vec<_>>().into_iter().zip(&faces) {
        out.set_face_names(g, b.face(f).names.clone());
    }
    Ok(out)
}

/// A solid as loose geometry and who uses what: the form a file gives one in, and the way to
/// build one whose faces are known by their surfaces and bounding edges alone.
#[derive(Clone, Debug, Default)]
pub(crate) struct Parts {
    pub points: Vec<Point3>,
    /// Each edge's curve and its ends, as indices into `points`.
    pub edges: Vec<(Curve, usize, usize)>,
    pub faces: Vec<PartFace>,
}

#[derive(Clone, Debug)]
pub(crate) struct PartFace {
    pub surface: Surface,
    pub reversed: bool,
    /// Each loop's uses of edges in order, the outer loop first: the edge, and whether the loop
    /// runs against it.
    pub loops: Vec<Vec<(usize, bool)>>,
    pub names: std::collections::BTreeSet<crate::topo::FaceName>,
    /// Which of the solid's shells it lies in, the outer one first.
    pub shell: usize,
}

/// The parts of `b`, one solid bounded by one outer shell and any voids. Degenerate edges, the
/// kernel's own, are left out.
pub(crate) fn parts_of(b: &Brep) -> Result<Parts> {
    let mut solids = b.solid_ids();
    let (Some(solid), None) = (solids.next(), solids.next()) else {
        return Err(Error::Unsupported("the parts of several solids".into()));
    };
    let solid = b.solid(solid);
    if solid.outer != 1 {
        return Err(Error::Unsupported(
            "the parts of a solid that touches itself".into(),
        ));
    }
    let mut parts = Parts {
        points: b.vertex_ids().map(|v| b.vertex(v).point).collect(),
        ..Parts::default()
    };
    let mut edge_at = vec![usize::MAX; b.edge_ids().count()];
    for e in b.edge_ids() {
        let x = b.edge(e);
        if let Some(curve) = &x.curve {
            edge_at[e.index()] = parts.edges.len();
            parts
                .edges
                .push((curve.clone(), x.start.index(), x.end.index()));
        }
    }
    for (shell, &sh) in solid.shells.iter().enumerate() {
        for &f in &b.shell(sh).faces {
            let face = b.face(f);
            let loops = face
                .loops
                .iter()
                .map(|&l| {
                    b.lp(l)
                        .coedges
                        .iter()
                        .map(|&c| b.coedge(c))
                        .filter(|c| edge_at[c.edge.index()] != usize::MAX)
                        .map(|c| (edge_at[c.edge.index()], c.reversed))
                        .collect()
                })
                .collect();
            parts.faces.push(PartFace {
                surface: face.surface.clone(),
                reversed: face.reversed,
                loops,
                names: face.names.clone(),
                shell,
            });
        }
    }
    Ok(parts)
}

/// The solid `parts` describe, its pcurves and parameter ranges found as a file's are. Points and
/// edges no face uses are left out.
pub(crate) fn solid_of(parts: &Parts) -> Result<Brep> {
    let mut raw = Raw::default();
    let mut edge_at = vec![usize::MAX; parts.edges.len()];
    let mut point_at = vec![usize::MAX; parts.points.len()];
    let mut order: Vec<usize> = (0..parts.faces.len()).collect();
    order.sort_by_key(|&f| parts.faces[f].shell);
    for (fi, &at) in order.iter().enumerate() {
        let f = &parts.faces[at];
        let mut bounds = Vec::new();
        for (k, l) in f.loops.iter().enumerate() {
            let mut uses = Vec::new();
            for &(e, reversed) in l {
                if edge_at[e] == usize::MAX {
                    let (curve, start, end) = &parts.edges[e];
                    let mut ends = [*start, *end];
                    for v in &mut ends {
                        if point_at[*v] == usize::MAX {
                            point_at[*v] = raw.points.len();
                            raw.vertex_ids.push(raw.points.len() as u64);
                            raw.points.push(parts.points[*v]);
                        }
                        *v = point_at[*v];
                    }
                    edge_at[e] = raw.edges.len();
                    raw.edges.push(RawEdge {
                        id: e as u64,
                        curve: curve.clone(),
                        start: ends[0],
                        end: ends[1],
                        faces: Vec::new(),
                    });
                }
                raw.edges[edge_at[e]].faces.push(fi);
                uses.push(Use {
                    edge: edge_at[e],
                    reversed,
                });
            }
            bounds.push((k == 0, uses));
        }
        raw.faces.push(RawFace {
            id: fi as u64,
            name: String::new(),
            surface: f.surface.clone(),
            reversed: f.reversed,
            bounds,
            points: Vec::new(),
        });
        if raw.shells.len() <= f.shell {
            raw.shells.resize(f.shell + 1, Vec::new());
        }
        raw.shells[f.shell].push(fi);
    }
    let (ranges, _) = heal::heal(&mut raw)?;
    let mut out = assemble(&raw, &ranges, None)?;
    for (g, &at) in out.face_ids().collect::<Vec<_>>().into_iter().zip(&order) {
        out.set_face_names(g, parts.faces[at].names.clone());
    }
    Ok(out)
}