delaunay 0.8.0

D-dimensional Delaunay triangulations and convex hulls in Rust, with exact predicates, deterministic degeneracy handling, explicit topology validation, and bistellar flips for finite point sets.
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
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(any(doc, doctest), doc = include_str!("../README.md"))]

//! ---
//! # Documentation map
//!
//! The README above is included verbatim and serves as the **user-facing introduction** to the
//! crate (overview, features, and quick-start examples).
//!
//! Everything below this line specifies the **semantic and correctness contract** of the
//! `delaunay` crate and is intended for users who need stronger guarantees, deeper understanding
//! of invariants, or who are extending the implementation.
//!
//! This crate’s documentation is intentionally layered by audience and intent:
//!
//! - **README.md** (included above):
//!   User-facing overview, feature list, and quick-start examples.
//!
//! - **Crate-level documentation (`lib.rs`)** (this document):
//!   The programming contract of the library: what invariants are enforced, when validation runs,
//!   and what errors mean.
//!
//!   In particular, this document covers:
//!   - The validation hierarchy and invariant stack (Levels 1–5)
//!   - Topological guarantees (`TopologyGuarantee`) and insertion-time validation policy (`ValidationPolicy`)
//!   - High-level error semantics and programming contract (transactional operations, duplicate rejection)
//!
//! - **docs/workflows.md**:
//!   Task-oriented, end-to-end usage recipes (Builder API, Edit API, validation,
//!   repairs, diagnostics, and statistics).
//!
//! - **docs/validation.md**:
//!   Formal definitions of validation Levels 1–5, their costs, and guidance on when
//!   each level should be applied.
//!
//! - **docs/diagnostics.md**:
//!   Opt-in diagnostic helpers, structured reports, debug switches, and guidance for
//!   producing useful failure reports without expanding the default API surface.
//!
//! - **docs/invariants.md**:
//!   Deeper theoretical discussion of topological and geometric invariants
//!   (PL-manifold conditions, ridge/vertex links, ordering heuristics, and
//!   convergence assumptions), plus algorithmic background and limitations.
//!
//! ## Which import do I need?
//!
//! The crate provides several focused prelude modules.  Pick the one that
//! matches your task:
//!
//! | Task | Import |
//! |---|---|
//! | Construct/configure a Delaunay triangulation | `use delaunay::prelude::construction::*` |
//! | Build/validate/repair generic triangulations | `use delaunay::prelude::triangulation::*` |
//! | Incremental insertion diagnostics and result types | `use delaunay::prelude::insertion::*` |
//! | Post-construction vertex deletion errors and keys | `use delaunay::prelude::deletion::*` |
//! | Read-only queries, traversal, ridge views, simplex barycenters, convex hull | `use delaunay::prelude::query::*` |
//! | Point location and conflict-region algorithms | `use delaunay::prelude::algorithms::*` |
//! | Geometry helpers, simplex realizations, coordinate ranges, predicates, points | `use delaunay::prelude::geometry::*` |
//! | Random points / triangulations for examples and tests | `use delaunay::prelude::generators::*` |
//! | Hilbert ordering and quantization utilities | `use delaunay::prelude::ordering::*` |
//! | Unified Pachner move workflow | `use delaunay::prelude::pachner::*` |
//! | Delaunay repair and flip-based Level 5 validation | `use delaunay::prelude::repair::*` |
//! | Delaunayize workflow (repair + flip) | `use delaunay::prelude::delaunayize::*` |
//! | Construction telemetry diagnostics | `use delaunay::prelude::diagnostics::*` |
//! | Export stable mesh and visualization primitives | `use delaunay::prelude::export::*` |
//! | Validation policies, errors, reports, PL-manifold link errors, and Level 5 diagnostics | `use delaunay::prelude::validation::*` |
//! | Topology validation, Euler characteristic, ridge queries | `use delaunay::prelude::topology::validation::*` |
//! | Topological spaces, topology traits, spherical point/metric backends, lifted toroidal IDs | `use delaunay::prelude::topology::spaces::*` |
//! | Low-level TDS simplices, facets, keys | `use delaunay::prelude::tds::*` |
//! | Collection types (`FastHashMap`, etc.) | `use delaunay::prelude::collections::*` |
//! | Broad convenience import for exploratory code | `use delaunay::prelude::*` |
//!
//! ## Public low-level namespace policy
//!
//! High-level Delaunay APIs are available directly from the crate root and
//! focused root modules: [`DelaunayTriangulation`], [`DelaunayTriangulationBuilder`],
//! [`construction`](crate::construction), [`flips`],
//! [`repair`], [`validation`], and
//! [`delaunayize`].  The nested `delaunay::delaunay::*`
//! facade is intentionally not part of the public API; use the crate root or a
//! focused prelude instead.
//!
//! ```compile_fail
//! use delaunay::delaunay::DelaunayTriangulation;
//! ```
//!
//! The low-level implementation namespace is private. The public low-level
//! surface is exposed through curated modules:
//! [`tds`](crate::tds), [`collections`],
//! [`algorithms`], and [`query`], plus the
//! matching focused preludes. These names describe the data structures and
//! workflows users compose without colliding with Rust's standard `core`
//! vocabulary.
//!
//! Prefer these curated modules and focused preludes in examples, doctests,
//! benchmarks, and downstream-style integration tests. High-level Delaunay
//! construction remains outside the low-level TDS/query surface.
//!
//! ## Examples (contract-oriented)
//!
//! ### Validation hierarchy (Levels 1–5)
//!
//! ```rust
//! use delaunay::prelude::construction::{
//!     DelaunayResult, DelaunayTriangulationBuilder, vertex,
//! };
//!
//! # fn main() -> DelaunayResult<()> {
//! let vertices = vec![
//!     vertex![0.0, 0.0, 0.0]?,
//!     vertex![1.0, 0.0, 0.0]?,
//!     vertex![0.0, 1.0, 0.0]?,
//!     vertex![0.0, 0.0, 1.0]?,
//! ];
//! let dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
//!
//! // Levels 1–2: Element Validity + Combinatorial Consistency
//! assert!(dt.validate_structure().is_ok());
//!
//! // Levels 1–3: + Intrinsic PL Topology
//! assert!(dt.as_triangulation().validate().is_ok());
//!
//! // Levels 1–4: elements + combinatorics + topology + realization validity
//! assert!(dt.as_triangulation().validate_realization().is_ok());
//!
//! // Level 5 only: Geometric Predicates (Delaunay today; assumes Levels 1–4)
//! assert!(dt.is_valid_delaunay().is_ok());
//!
//! // Levels 1–5: full cumulative validation
//! assert!(dt.validate().is_ok());
//! # Ok(())
//! # }
//! ```
//!
//! ### Topology guarantees and insertion-time validation (`TopologyGuarantee`, `ValidationPolicy`)
//!
//! ```rust
//! use delaunay::prelude::construction::{
//!     DelaunayResult, DelaunayTriangulationBuilder, TopologyGuarantee, vertex,
//! };
//! use delaunay::prelude::validation::ValidationPolicy;
//!
//! # fn main() -> DelaunayResult<()> {
//! let vertices = vec![
//!     vertex![0.0, 0.0, 0.0]?,
//!     vertex![1.0, 0.0, 0.0]?,
//!     vertex![0.0, 1.0, 0.0]?,
//!     vertex![0.0, 0.0, 1.0]?,
//! ];
//! let mut dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
//!
//! assert_eq!(dt.topology_guarantee(), TopologyGuarantee::PLManifold);
//! assert_eq!(dt.validation_policy(), ValidationPolicy::ExplicitOnly);
//!
//! dt.set_topology_guarantee(TopologyGuarantee::Pseudomanifold);
//! dt.set_validation_policy(ValidationPolicy::Always);
//!
//! assert_eq!(dt.topology_guarantee(), TopologyGuarantee::Pseudomanifold);
//! assert_eq!(dt.validation_policy(), ValidationPolicy::Always);
//! # Ok(())
//! # }
//! ```
//!
//! ### Transactional operations and duplicate rejection
//!
//! ```rust
//! use delaunay::prelude::construction::{
//!     DelaunayResult, DelaunayTriangulationBuilder, vertex,
//! };
//! use delaunay::prelude::insertion::InsertionError;
//!
//! # fn main() -> DelaunayResult<()> {
//! let vertices = vec![
//!     vertex![0.0, 0.0]?,
//!     vertex![1.0, 0.0]?,
//!     vertex![0.0, 1.0]?,
//! ];
//! let mut dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
//!
//! let before_vertices = dt.number_of_vertices();
//! let before_simplices = dt.number_of_simplices();
//!
//! // Duplicate coordinates are rejected.
//! let result = dt.insert_vertex(vertex![0.0, 0.0]?);
//! std::assert_matches!(result, Err(InsertionError::DuplicateCoordinates { .. }));
//!
//! // On error, the triangulation is unchanged.
//! assert_eq!(dt.number_of_vertices(), before_vertices);
//! assert_eq!(dt.number_of_simplices(), before_simplices);
//! # Ok(())
//! # }
//! ```
//!
//! # Triangulation invariants and validation hierarchy
//!
//! The crate is organized as a small **validation stack**, where each layer adds additional
//! invariants on top of the preceding one:
//!
//! - [`Vertex`](crate::tds::Vertex) and [`Simplex`](crate::tds::Simplex) provide
//!   **element validity** checks.
//!   Level 1 (elements) validation checks invariants such as:
//!   - **Vertex coordinates** – finite (no NaN/∞) and UUID is non-nil.
//!   - **Simplex shape** – exactly D+1 distinct vertex keys, valid UUID, and neighbor buffer length
//!     (if present) is D+1.
//!
//!   These checks are surfaced via [`Vertex::is_valid`](crate::tds::Vertex::is_valid),
//!   [`Vertex::vertex_report`](crate::tds::Vertex::vertex_report),
//!   [`Simplex::is_valid`](crate::tds::Simplex::is_valid), and
//!   [`Simplex::simplex_report`](crate::tds::Simplex::simplex_report), and are automatically run by
//!   [`Tds::validate`](crate::tds::Tds::validate) (Levels 1–2).
//!
//! - [`Tds`](crate::tds::Tds) (Triangulation Data Structure)
//!   stores the **combinatorial** representation.
//!   Level 2 (Combinatorial Consistency) validation checks invariants such as:
//!   - **Vertex mappings** – every vertex UUID has a corresponding key and vice versa.
//!   - **Simplex mappings** – every simplex UUID has a corresponding key and vice versa.
//!   - **No duplicate simplices** – no two maximal simplices share the same vertex set.
//!   - **Facet incidence** – each facet is one-sided or two-sided; topology
//!     metadata decides whether a one-sided facet is semantic boundary.
//!   - **Neighbor consistency** – neighbor relationships are mutual and reference a shared facet.
//!
//!   These checks are surfaced via [`Tds::is_valid`](crate::tds::Tds::is_valid)
//!   (structural only) and [`Tds::validate`](crate::tds::Tds::validate)
//!   (Levels 1–2, elements + combinatorics). For cumulative diagnostics across the full stack,
//!   use [`DelaunayTriangulation::validation_report`](crate::DelaunayTriangulation::validation_report).
//!
//! - [`Triangulation`] builds on the TDS and validates
//!   **intrinsic PL topology**.
//!   Level 3 (Intrinsic PL Topology) validation is performed by
//!   [`Triangulation::is_valid_topology`](crate::Triangulation::is_valid_topology) (Level 3 only) and
//!   [`Triangulation::validate`](crate::Triangulation::validate) (Levels 1–3), which:
//!   - Strengthens facet incidence to the **manifold facet property**:
//!     one-sided facets are valid only when the declared topology admits
//!     boundary; two-sided facets are interior.
//!   - Checks the **Euler characteristic** of the triangulation (using the topology module).
//!
//! - [`Triangulation`] also validates the **realization validity** of the abstract
//!   complex in the active ambient model. Level 4 validation is performed by
//!   [`Triangulation::is_valid_realization`](crate::Triangulation::is_valid_realization) (Level 4 only) and
//!   [`Triangulation::validate_realization`](crate::Triangulation::validate_realization) (Levels 1–4).
//!   Euclidean topology is checked directly in its ambient chart; toroidal
//!   topology is checked in periodic covering-space charts.
//!
//! - [`DelaunayTriangulation`] builds on `Triangulation` and validates the
//!   implemented **geometric predicate** family for Delaunay triangulations.
//!   Level 5 (Geometric Predicates) validation is performed by
//!   [`DelaunayTriangulation::is_valid_delaunay`](crate::DelaunayTriangulation::is_valid_delaunay) (Level 5 only) and
//!   [`DelaunayTriangulation::validate`](crate::DelaunayTriangulation::validate) (Levels 1–5).
//!   Batch construction normally runs final Delaunay validation before returning;
//!   [`ConstructionOptions::without_final_delaunay_enforcement`](crate::construction::ConstructionOptions::without_final_delaunay_enforcement)
//!   opts into returning after Levels 1–4 validation for exact degenerate or
//!   externally constrained connectivity.
//!   Incremental insertion can run global Level 5 checks according to
//!   [`DelaunayCheckPolicy`]. If robust
//!   fallback and repair cannot certify a checked result, the operation returns a
//!   typed error rather than silently accepting a known violation.
//!
//! ## Validation
//!
//! The crate exposes five validation levels
//! (Element Validity → Combinatorial Consistency → Intrinsic PL Topology →
//! Valid Realization → Geometric Predicates). The
//! canonical guide (when to use each level, complexity, examples, troubleshooting) lives in
//! `docs/validation.md`:
//! <https://github.com/acgetchell/delaunay/blob/main/docs/validation.md>
//!
//! In brief:
//! - Level 1 (elements / `Vertex` + `Simplex`): `Vertex::is_valid()` /
//!   `Simplex::is_valid()` for fast checks, or `vertex_report()` /
//!   `simplex_report()` for element-local diagnostics.
//! - Level 2 (Combinatorial Consistency / `Tds`): `dt.is_valid_structure()` for a quick check, or
//!   `dt.validate_structure()` for Levels 1–2.
//! - Level 3 (Intrinsic PL Topology / `Triangulation`):
//!   `dt.as_triangulation().is_valid_topology()` for topology-only checks, or
//!   `dt.as_triangulation().validate()` for Levels 1–3.
//! - Level 4 (Valid Realization / `Triangulation`): `dt.as_triangulation().validate_realization()`
//!   for cumulative realized-geometry checks, or `dt.as_triangulation().realization_report()` for layer-local diagnostics.
//! - Level 5 (Geometric Predicates / `DelaunayTriangulation`): `dt.is_valid_delaunay()` for the
//!   implemented Delaunay predicate family, or `dt.delaunay_report()` for layer-local diagnostics.
//! - Cumulative Delaunay validation: `dt.validate()` for Levels 1–5, or
//!   `dt.validation_report()` for full diagnostics.
//!
//! ### Automatic topology and changed-scope realization validation during insertion (`ValidationPolicy`)
//!
//! In addition to explicit validation calls, incremental construction (`new()` / `insert*()`) can run an
//! automatic **global Level 3 plus changed-scope Level 4** validation pass after insertion, controlled by
//! [`ValidationPolicy`](crate::prelude::validation::ValidationPolicy).
//!
//! The initial policy is derived from the active topology guarantee. The default
//! [`TopologyGuarantee::PLManifold`](crate::prelude::TopologyGuarantee::PLManifold)
//! uses [`ValidationPolicy::ExplicitOnly`]:
//! mandatory local topology and orientation/nondegeneracy realization checks still run during insertion, while automatic
//! global-topology/changed-scope realization validation is a caller-owned explicit checkpoint.
//!
//! This automatic pass runs Level 3 (`Triangulation::is_valid_topology()`), changed-simplex
//! Level 4 orientation/nondegeneracy checks, and changed-vs-current Level 4 pairwise checks. It does
//! **not** run Level 5 geometric-predicate validation, and old-vs-old Level 4 rescans remain an explicit
//! `Triangulation::validate_realization()` checkpoint.
//!
//! ```rust
//! use delaunay::prelude::construction::{
//!     DelaunayResult, DelaunayTriangulationBuilder, vertex,
//! };
//! use delaunay::prelude::validation::ValidationPolicy;
//!
//! # fn main() -> DelaunayResult<()> {
//! let vertices = vec![
//!     vertex![0.0, 0.0, 0.0]?,
//!     vertex![1.0, 0.0, 0.0]?,
//!     vertex![0.0, 1.0, 0.0]?,
//!     vertex![0.0, 0.0, 1.0]?,
//! ];
//! let mut dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
//!
//! // Caller-owned validation mode: keep mandatory topology checks, but run full
//! // Level 3 validation only through explicit validation calls.
//! dt.try_set_validation_policy(ValidationPolicy::ExplicitOnly)?;
//!
//! // Do incremental work...
//! dt.insert_vertex(vertex![0.2, 0.2, 0.2]?)?;
//!
//! // ...then explicitly validate the Intrinsic PL Topology layer when you need a certificate.
//! assert!(dt.as_triangulation().validate().is_ok());
//! # Ok(())
//! # }
//! ```
//!
//! ### Choosing Level 3 Intrinsic PL Topology guarantee (`TopologyGuarantee`)
//!
//! This section specifies *what* invariants are enforced. The formal topological
//! definitions and rationale live in `docs/invariants.md`.
//!
//! Level 3 Intrinsic PL Topology validation is parameterized by
//! [`TopologyGuarantee`](crate::prelude::construction::TopologyGuarantee). This is separate from
//! `ValidationPolicy`: it controls *what* invariants Level 3 enforces, not *when* automatic
//! validation runs.
//!
//! - [`TopologyGuarantee::PLManifold`](crate::prelude::construction::TopologyGuarantee::PLManifold)
//!   (default): enforces manifold facet degree, boundary closure, connectedness, Euler characteristic,
//!   and link-based manifold conditions. Ridge-link checks are applied incrementally during insertion,
//!   with vertex-link validation performed at construction completion.
//!
//!   The formal topological definitions, link conditions, and rationale for this validation strategy
//!   are documented in `docs/invariants.md`.
//! - [`TopologyGuarantee::PLManifoldStrict`]:
//!   vertex-link validation after every insertion (slowest, maximum safety).
//! - [`TopologyGuarantee::Pseudomanifold`]:
//!   skips vertex-link validation (may be faster), but bistellar flip convergence is not guaranteed and
//!   you may want to validate the Delaunay property explicitly for near-degenerate inputs.
//!
//! ```rust
//! use delaunay::prelude::construction::{
//!     DelaunayResult, DelaunayTriangulationBuilder, vertex,
//! };
//!
//! # fn main() -> DelaunayResult<()> {
//! let vertices = vec![
//!     vertex![0.0, 0.0, 0.0]?,
//!     vertex![1.0, 0.0, 0.0]?,
//!     vertex![0.0, 1.0, 0.0]?,
//!     vertex![0.0, 0.0, 1.0]?,
//! ];
//! let dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
//!
//! // For `TopologyGuarantee::PLManifold`, full certification includes a completion-time
//! // vertex-link validation pass.
//! assert!(dt.as_triangulation().validate_at_completion().is_ok());
//! # Ok(())
//! # }
//! ```
//!
//! ```rust
//! use delaunay::prelude::construction::{
//!     DelaunayResult, DelaunayTriangulationBuilder, vertex,
//! };
//!
//! # fn main() -> DelaunayResult<()> {
//! let vertices = vec![
//!     vertex![0.0, 0.0, 0.0]?,
//!     vertex![1.0, 0.0, 0.0]?,
//!     vertex![0.0, 1.0, 0.0]?,
//!     vertex![0.0, 0.0, 1.0]?,
//! ];
//! let dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
//!
//! // `validate()` returns the first violation; `validation_report()` is intended for
//! // debugging/telemetry where you want the full set of violated invariants.
//! assert!(dt.validation_report().is_ok());
//! # Ok(())
//! # }
//! ```
//!
//! ### Coordinate scalar policy
//!
//! The default supported coordinate input type is `f64`, matching the crate's
//! current linear algebra backend and geometric-primitive correctness
//! guarantees. Exact arithmetic is already used internally for robust predicate
//! fallbacks, and exact coordinate input may be supported explicitly in the
//! future.
//!
//! # Programming contract (high-level)
//!
//! - **Transactional mutations**: Construction and incremental operations are designed to be
//!   all-or-nothing. If an operation returns `Err(_)`, the triangulation is rolled back to its
//!   previous state.
//! - **Duplicate detection**: Near-duplicate coordinates are rejected using a scale-aware
//!   Euclidean tolerance based on nearby geometry and floating-point resolution, returning
//!   [`InsertionError::DuplicateCoordinates`].
//!   Duplicate UUIDs return
//!   [`InsertionError::DuplicateUuid`].
//! - **Explicit verification**: Use `dt.validate()` for cumulative verification (Levels 1–5), or
//!   `dt.is_valid_delaunay()` for Level 5 only.

// Forbid unsafe code throughout the entire crate
#![forbid(unsafe_code)]

/// Internal low-level triangulation data structures and algorithms.
///
/// This module backs the curated public low-level modules. It includes
/// [`Tds`](crate::tds::Tds), [`Simplex`](crate::tds::Simplex),
/// [`FacetView`](crate::tds::FacetView),
/// [`Vertex`](crate::tds::Vertex), the generic
/// [`Triangulation`] wrapper, and
/// algorithm building blocks used by the crate.
///
/// Public docs, examples, benchmarks, and downstream-style tests should prefer
/// the curated public modules and focused preludes:
///
/// - [`crate::tds`] / [`crate::prelude::tds`] for TDS simplices, facets, keys,
///   validation reports, and helpers.
/// - [`crate::collections`] / [`crate::prelude::collections`] for public
///   collection aliases and small buffers.
/// - [`crate::algorithms`] / [`crate::prelude::algorithms`] for point-location
///   and conflict-region algorithms.
/// - [`crate::query`] / [`crate::prelude::query`] for read-only traversal,
///   adjacency, convex hull, and set-comparison helpers.
///
/// High-level Delaunay construction and builder APIs live at the crate root
/// and under the focused Delaunay-facing preludes, not under `core`.
#[expect(
    clippy::redundant_pub_crate,
    reason = "`pub(crate)` keeps internal cross-module intent visible while `core` is private"
)]
mod core {
    /// Triangulation algorithms for construction, maintenance, and querying.
    pub mod algorithms {
        /// Flip-based algorithms (Delaunay repair, diagnostics, and related utilities).
        pub mod flips;
        /// Incremental cavity-based insertion.
        pub mod incremental_insertion;
        /// Point location algorithms (facet walking).
        pub mod locate;
        /// Bounded deterministic PL-manifold topology repair.
        pub(crate) mod pl_manifold_repair;
    }

    pub mod adjacency;
    pub mod facet_incidence;
    pub mod simplex;
    /// High-performance collection types optimized for computational geometry operations.
    ///
    /// This module provides centralized type aliases for performance-critical data structures
    /// used throughout the delaunay triangulation library. These aliases allow for easy
    /// future optimization and maintenance by providing a single location to change
    /// the underlying implementation.
    ///
    /// # Performance Rationale
    ///
    /// The type aliases in this module are optimized based on the specific usage patterns
    /// in computational geometry algorithms:
    ///
    /// ## Hash-based Collections
    ///
    /// - **FastHashMap/FastHashSet**: Uses `FastHasher`, a non-cryptographic hasher
    ///   that is 2-3x faster than `SipHash` for trusted data. Perfect for internal data
    ///   where collision resistance against adversarial input is not required.
    /// - **`SecureHashMap`/`SecureHashSet`**: Use Rust's randomized default
    ///   hasher for collections whose keys are derived from public coordinate
    ///   input or other caller-controlled values.
    ///
    /// ### ⚠️ Security Warning: `DoS` Resistance
    ///
    /// **The hasher used by `FastHashMap`/`FastHashSet` is NOT DoS-resistant.** It should only be
    /// used with trusted input data. Do not use `FastHashMap` or `FastHashSet` with
    /// attacker-controlled keys, as this could lead to hash collision attacks that
    /// degrade performance to O(n) worst-case behavior.
    ///
    /// **Safe usage patterns:**
    /// - Internal geometric computations with generated/computed keys
    /// - Trusted coordinate data from known sources
    /// - UUID-based keys generated by the library itself
    ///
    /// **Misuse patterns:**
    /// - Processing untrusted coordinate data from external sources
    /// - Using user-provided keys without validation
    /// - Network-facing applications with external input
    ///
    /// Use [`SecureHashMap`](crate::collections::SecureHashMap) or
    /// [`SecureHashSet`](crate::collections::SecureHashSet) when keys
    /// are derived from public input.
    ///
    /// ## Small Collections
    ///
    /// - **`SmallVec`**: Uses stack allocation for small collections, avoiding heap
    ///   allocations for the common case where collections remain small. This is
    ///   particularly effective for:
    ///   - Vertex neighbor lists (typically D+1 neighbors)
    ///   - Facet-to-simplex mappings (typically 1-2 simplices per facet)
    ///   - Temporary collections during geometric operations
    ///
    /// # Usage Patterns
    ///
    /// The size parameters for `SmallVec` are chosen based on empirical analysis of
    /// typical triangulation patterns:
    ///
    /// - **2 elements**: Facet incidence (one-sided = 1 simplex, two-sided = 2 simplices)
    /// - **4 elements**: Small temporary collections during geometric operations
    /// - **8 elements**: Vertex degrees and simplex neighbor counts in typical triangulations
    /// - **16 elements**: Larger temporary buffers for batch operations
    ///
    /// # Future Optimization
    ///
    /// This centralized approach allows for easy experimentation with different
    /// high-performance data structures:
    /// - Alternative hash functions (ahash, seahash)
    /// - Specialized geometric data structures
    /// - SIMD-optimized containers
    /// - Memory pool allocators
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::collections::{FastHashMap, SmallBuffer};
    ///
    /// // Use optimized HashMap for temporary mappings
    /// let mut temp_map: FastHashMap<u64, usize> = FastHashMap::default();
    /// temp_map.insert(7, 3);
    ///
    /// // Use stack-allocated buffer for small collections
    /// let mut small_list: SmallBuffer<i32, 8> = SmallBuffer::new();
    /// small_list.push(1);
    /// small_list.push(2);
    ///
    /// assert_eq!(temp_map.len(), 1);
    /// ```
    ///
    /// ## Key-based internal operations
    ///
    /// The crate uses stable keys (`VertexKey`, `SimplexKey`) internally for performance.
    /// This module provides optimized maps/sets keyed by those identifiers:
    ///
    /// ```rust
    /// use delaunay::prelude::collections::{SimplexKeySet, KeyBasedSimplexMap, VertexKeySet};
    ///
    /// let mut internal_simplices: SimplexKeySet = SimplexKeySet::default();
    /// let mut internal_vertices: VertexKeySet = VertexKeySet::default();
    /// let mut key_mappings: KeyBasedSimplexMap<String> = KeyBasedSimplexMap::default();
    /// ```
    pub mod collections {
        mod aliases;
        mod buffers;
        mod helpers;
        mod key_maps;
        mod secondary_maps;
        mod triangulation_maps;

        pub(crate) mod spatial_hash_grid;

        pub(crate) use aliases::StorageMap;
        pub use aliases::{
            Entry, FacetIndex, FastBuildHasher, FastHashMap, FastHashSet, FastHasher,
            MAX_PRACTICAL_DIMENSION_SIZE, SecureHashMap, SecureHashSet, SmallBuffer, Uuid,
        };

        pub use buffers::*;
        pub use helpers::*;
        pub use key_maps::*;
        pub use secondary_maps::*;
        pub use triangulation_maps::*;
    }
    /// Generic triangulation construction helpers.
    pub mod construction;
    pub mod edge;
    pub mod facet;
    /// Incremental insertion for generic triangulations.
    pub mod insertion;
    /// Semantic classification and telemetry for topological operations
    pub mod operations;
    /// Geometric orientation validation and canonicalization for generic triangulations.
    pub mod orientation;
    /// Read-only query and traversal helpers for generic triangulations.
    pub mod query;
    /// Realized Euclidean geometry validation for generic triangulations.
    pub mod realization;
    /// Local topology repair for generic triangulations.
    pub mod repair;
    /// Scoped rollback guards for internal topology mutation windows.
    pub(crate) mod rollback;
    /// Triangulation data structure internals.
    pub mod tds {
        mod equality;
        pub mod errors;
        pub(crate) mod incidence;
        mod keys;
        mod mutation;
        pub(crate) mod rollback;
        mod snapshot;
        mod storage;
        mod validation;

        pub use errors::*;
        pub use keys::{SimplexKey, VertexKey};
        pub(crate) use rollback::{
            TdsOwnerRollbackTransaction, TdsRollbackOwner, TdsRollbackTransaction,
        };
        pub use storage::{Tds, TopologyOwner, TopologyOwnerId};
    }
    /// Generic triangulation combining kernel + Tds.
    pub mod triangulation;
    /// Generic validation orchestration for triangulations.
    pub mod validation;

    /// General utility functions organized by functionality.
    pub mod util {
        pub(crate) mod canonical_points;
        pub mod deduplication;
        pub mod facet_keys;
        pub mod facet_utils;
        pub mod hashing;
        pub mod hilbert;
        pub mod jaccard;
        pub mod measurement;
        pub mod uuid;

        // Re-export utility internals within the private core namespace.
        pub use deduplication::*;
        pub use facet_keys::*;
        pub use facet_utils::*;
        pub use hashing::*;
        pub use hilbert::*;
        pub use jaccard::*;
        pub use measurement::*;
        pub use uuid::*;
    }

    pub mod vertex;

    /// Traits for Delaunay triangulation data structures.
    pub mod traits {
        pub mod data_type;
        pub mod facet_incidence_analysis;
        pub use data_type::*;
    }

    // Import concrete internal modules directly via `crate::core::<module>`.
    // Public low-level access is exposed through crate-root facades such as
    // `crate::tds`, `crate::collections`, `crate::algorithms`, and
    // `crate::query`.
}

#[cfg(feature = "bench")]
#[doc(hidden)]
pub mod bench_fixtures;

/// Contains geometric types including the `Point` struct and geometry predicates.
///
/// The geometry module provides coordinate abstractions through the
/// [`Coordinate`](crate::geometry::traits::coordinate::Coordinate) trait,
/// [`CoordinateRange`](crate::geometry::coordinate_range::CoordinateRange)
/// value type, and [`Point`](crate::geometry::point::Point) type. The default
/// supported coordinate input type is `f64`, matching the crate's current
/// linear algebra backend and geometric-primitive correctness guarantees;
/// exact coordinate input may be supported explicitly in the future.
pub mod geometry {
    /// Geometric algorithms for triangulations and spatial data structures
    pub mod algorithms {
        /// Convex hull operations on d-dimensional triangulations
        pub mod convex_hull;
        pub use convex_hull::*;
    }
    /// Validated coordinate-range types.
    pub mod coordinate_range;
    /// Pure labeled-simplex realization predicates used by Level 4 validation.
    pub mod realization;
    #[macro_use]
    pub mod matrix;
    /// Geometric kernel abstraction (CGAL-style).
    pub mod kernel;
    pub mod point;
    pub mod predicates;
    /// Geometric quality measures for d-dimensional simplices
    pub mod quality;
    /// Enhanced predicates with improved numerical robustness
    pub mod robust_predicates;
    /// Simulation of Simplicity (SoS) for deterministic degeneracy resolution
    pub mod sos;
    /// Geometric utility functions for d-dimensional geometry calculations
    pub mod util {
        pub mod circumsphere;
        pub mod conversions;
        pub mod measures;
        pub mod norms;
        pub mod point_generation;
        pub(crate) mod simplex_lp;
        pub mod triangulation_generation;

        // Re-export all public utility items for ergonomic `crate::geometry::util::*` access.
        pub use circumsphere::*;
        pub use conversions::*;
        pub use measures::*;
        pub use norms::*;
        pub use point_generation::*;
        pub use triangulation_generation::*;
    }
    /// Traits module containing coordinate abstractions and reusable trait definitions.
    ///
    /// This module contains the core `Coordinate` trait that abstracts coordinate
    /// operations, along with supporting traits for validation (`FiniteCheck`),
    /// equality comparison (`OrderedEq`), and hashing (`HashCoordinate`) of
    /// floating-point coordinate values.
    pub mod traits {
        pub mod coordinate;
        pub use coordinate::*;
    }
    pub use algorithms::*;
    pub use coordinate_range::*;
    pub use matrix::*;
    pub use point::*;
    pub use predicates::*;
    pub use quality::*;
    pub use realization::*;
    pub use traits::*;
    pub use util::*;
}

/// Fluent builder for Delaunay triangulations.
#[path = "delaunay/builder.rs"]
pub mod builder;
/// Batch construction options, errors, statistics, and policy helpers.
#[path = "delaunay/construction.rs"]
pub mod construction;
/// TDS-level implementation helpers for Delaunay's Level 5 Geometric Predicate scans.
#[path = "delaunay/property_validation.rs"]
mod delaunay_property_validation;
/// Read-only Delaunay query, traversal, and accessor methods.
#[path = "delaunay/query.rs"]
pub(crate) mod delaunay_query;
/// Delaunay-level rollback guards for mutation windows with auxiliary state.
#[path = "delaunay/rollback.rs"]
pub(crate) mod delaunay_rollback;
/// End-to-end "repair then delaunayize" workflow.
#[path = "delaunay/delaunayize.rs"]
pub mod delaunayize;
/// Post-construction vertex deletion operations.
#[path = "delaunay/deletion.rs"]
pub(crate) mod deletion;
/// Construction and performance diagnostics.
#[path = "delaunay/diagnostics.rs"]
pub mod diagnostics;
/// Triangulation editing operations (bistellar flips).
#[path = "delaunay/flips.rs"]
pub mod flips;
/// Post-construction vertex insertion operations.
#[path = "delaunay/insertion.rs"]
pub(crate) mod insertion;
#[path = "delaunay/locality.rs"]
pub(crate) mod locality;
/// Unified Pachner move workflow API for local topology editing.
#[path = "delaunay/pachner.rs"]
pub mod pachner;
/// Repair policies and outcomes for Delaunay triangulations.
#[path = "delaunay/repair.rs"]
pub mod repair;
/// Serialization support for Delaunay triangulations.
#[path = "delaunay/serialization.rs"]
pub(crate) mod serialization;
/// Prototype spherical Delaunay construction via the spherical topology backend.
#[path = "delaunay/spherical.rs"]
pub mod spherical;
/// Delaunay triangulation layer with incremental insertion.
#[path = "delaunay/triangulation.rs"]
pub(crate) mod triangulation;
/// Delaunay-level validation APIs, reports, and construction diagnostics.
#[path = "delaunay/validation.rs"]
pub mod validation;

/// I/O and downstream-facing export data models.
pub mod io {
    /// Generic simplicial-complex export data for notebooks and downstream tools.
    pub mod visualization;

    pub use visualization::*;
}

// Re-export commonly used Delaunay-facing types at the crate root.
pub use crate::builder::DelaunayTriangulationBuilder;
pub use crate::construction::{
    ConstructionOptions, ConstructionSkipSample, ConstructionSlowInsertionSample,
    ConstructionStatistics, DedupPolicy, DedupTolerance, DelaunayConstructionFailure,
    DelaunayConstructionRepairPhase, DelaunayConstructionRetryFailure, DelaunayError,
    DelaunayResult, DelaunayTriangulationConstructionError,
    DelaunayTriangulationConstructionErrorWithStatistics, InitialSimplexStrategy,
    InsertionOrderStrategy, RetryPolicy,
};
pub use crate::core::algorithms::incremental_insertion::{
    CavityFillingError, CavityRepairStage, DelaunayRepairErrorKind, DelaunayRepairFailureContext,
    HullExtensionReason, InitialSimplexConstructionError, InitialSimplexUnexpectedInsertionStage,
    InsertionError, InsertionErrorKind, InsertionErrorSourceKind,
    InsertionTopologyValidationContext, NeighborRebuildError, NeighborWiringError,
    SpatialIndexConstructionFailure, TdsConstructionFailure, TdsValidationFailure,
};
pub use crate::core::algorithms::pl_manifold_repair::{
    PlManifoldRepairError, PlManifoldRepairStage, PlManifoldRepairStats,
};
pub use crate::core::construction::{
    FinalDelaunayValidationContext, FinalTopologyValidationContext, TriangulationConstructionError,
};
pub use crate::core::insertion::DuplicateDetectionMetrics;
pub use crate::core::operations::{
    InsertionOutcome, InsertionResult, InsertionStatistics, RepairDecision, RepairSkipReason,
    SuspicionFlags, TopologicalOperation,
};
pub use crate::core::realization::{
    PeriodicDomainPeriodError, TriangulationRealizationIntersectionDetail,
    TriangulationRealizationSimplexDetail, TriangulationRealizationSimplexPairDetail,
    TriangulationRealizationValidationError, TriangulationRealizationValidationErrorKind,
    TriangulationRealizationValidationReport,
};
pub use crate::core::triangulation::Triangulation;
pub use crate::core::util::DeduplicationError;
pub use crate::core::validation::{
    OrientationWitness, TopologyGuarantee, TriangulationValidationError,
    ValidationConfigurationError, ValidationPolicy,
};
#[cfg(feature = "diagnostics")]
#[cfg_attr(docsrs, doc(cfg(feature = "diagnostics")))]
pub use crate::delaunay_property_validation::debug_print_first_delaunay_violation;
pub use crate::delaunay_property_validation::{
    DelaunayValidationError, DelaunayViolationDetail, DelaunayViolationReport,
    delaunay_violation_report, find_delaunay_violations,
};
pub use crate::delaunay_query::{SimplexBarycenterError, SimplexDataFillError};
pub use crate::deletion::DeleteVertexError;
pub use crate::io::visualization::{
    AdjacencyRecord, MESH_EXPORT_SCHEMA, MESH_EXPORT_SCHEMA_VERSION, MeshAdjacencyRecord,
    MeshExport, MeshExportError, MeshExportValidationError, MeshSimplexRecord, MeshVertexRecord,
    SimplexRecord, VISUALIZATION_SCHEMA, VISUALIZATION_SCHEMA_VERSION, ValidatedMeshExport,
    ValidatedVisualizationData, VertexRecord, VisualizationData, VisualizationDataValidationError,
    VisualizationExportError, VisualizationMetadata, VisualizationTopologyGuarantee,
    VisualizationTopologyKind,
};
pub use crate::repair::{
    DelaunayCheckPolicy, DelaunayRepairHeuristicConfig, DelaunayRepairHeuristicSeeds,
    DelaunayRepairOperation, DelaunayRepairOutcome, DelaunayRepairPolicy,
};
pub use crate::spherical::{
    SphericalDelaunayBuilder, SphericalDelaunayConstructionError, SphericalDelaunayTriangulation,
    SphericalDelaunayValidationError, SphericalSimplex, SphericalSimplexError,
    SphericalValidationLayer,
};
pub use crate::tds::{
    InvariantError, InvariantKind, InvariantViolation, TriangulationValidationReport,
};
pub use crate::topology::spaces::spherical::{
    SphericalMetric, SphericalPoint, SphericalPointError,
};
pub use crate::triangulation::*;
pub use crate::validation::{
    DelaunayTriangulationValidationError, DelaunayVerificationError, DelaunayVerificationErrorKind,
};

/// Creates vertices from points by re-validating coordinates at the public boundary.
///
/// This helper is useful when point generators or parsing code have already
/// produced [`Point`](crate::geometry::Point) values, but the caller still wants
/// vertex construction to pass through the same fallible validation path as
/// [`tds::Vertex::try_new`]. New vertices have fresh UUIDs, no user data, and no
/// incident simplex pointer until inserted into a triangulation data structure.
///
/// # Errors
///
/// Returns [`geometry::CoordinateConversionError`] when any point coordinate
/// cannot be converted exactly to finite `f64`.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::geometry::{
///     CoordinateConversionError, CoordinateValidationError, Point,
/// };
/// use delaunay::try_vertices_from_points;
///
/// # #[derive(Debug, thiserror::Error)]
/// # enum ExampleError {
/// #     #[error(transparent)]
/// #     Conversion(#[from] CoordinateConversionError),
/// #     #[error(transparent)]
/// #     Validation(#[from] CoordinateValidationError),
/// # }
/// # fn main() -> Result<(), ExampleError> {
/// let points = [Point::try_new([0.0, 0.0])?, Point::try_new([1.0, 0.0])?];
/// let vertices = try_vertices_from_points(&points)?;
/// assert_eq!(vertices.len(), 2);
/// # Ok(())
/// # }
/// ```
pub fn try_vertices_from_points<const D: usize>(
    points: &[geometry::Point<D>],
) -> Result<Vec<tds::Vertex<(), D>>, geometry::CoordinateConversionError> {
    points
        .iter()
        .map(|point| tds::Vertex::try_new(*point.coords()))
        .collect()
}

/// Topology analysis and validation for triangulated spaces.
///
/// This module provides traits, algorithms, and data structures for analyzing
/// and validating the topological properties of triangulations.
///
/// # Features
///
/// - **Euler Characteristic Calculation**: Compute topological invariants
/// - **Topology Classification**: Classify triangulations (Ball, Sphere, etc.)
/// - **Validation Framework**: Verify triangulation topological correctness
/// - **Dimensional Generic**: Works across all supported dimensions
///
/// # Applicability
///
/// These tools work for **any triangulation** (not just Delaunay triangulations).
/// The Euler characteristic and topological properties are combinatorial invariants
/// that depend only on the connectivity structure, not on geometric properties.
///
/// # Example
///
/// ```rust
/// use delaunay::prelude::construction::{
///     DelaunayTriangulationBuilder, DelaunayTriangulationConstructionError, vertex,
/// };
/// use delaunay::prelude::geometry::CoordinateConversionError;
/// use delaunay::prelude::topology::validation;
///
/// # #[derive(Debug, thiserror::Error)]
/// # enum ExampleError {
/// #     #[error(transparent)]
/// #     Construction(#[from] DelaunayTriangulationConstructionError),
/// #     #[error(transparent)]
/// #     Coordinate(#[from] CoordinateConversionError),
/// #     #[error(transparent)]
/// #     Topology(#[from] delaunay::topology::TopologyError),
/// # }
/// # fn main() -> Result<(), ExampleError> {
/// let vertices = vec![
///     vertex![0.0, 0.0, 0.0]?,
///     vertex![1.0, 0.0, 0.0]?,
///     vertex![0.0, 1.0, 0.0]?,
///     vertex![0.0, 0.0, 1.0]?,
/// ];
/// let dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
///
/// let result = dt.euler_check()?;
/// assert_eq!(result.chi, 1);  // Tetrahedron has χ = 1
/// assert!(result.is_valid());
/// # Ok(())
/// # }
/// ```
pub mod topology {
    /// Traits for topological spaces and error types
    pub mod traits {
        pub(crate) mod global_topology_model;
        pub mod topological_space;
        pub use global_topology_model::GlobalTopologyModelError;
        pub use topological_space::*;
    }
    /// Topological invariants and their computation
    pub mod characteristics {
        pub mod euler;
        pub mod validation;
        pub use euler::*;
        pub use validation::*;
    }

    /// Manifold / simplicial-complex validity checks (topology-only).
    pub mod manifold;

    /// Ridge candidates, borrowed ridge queries, and lifted ridge-link views.
    pub mod ridge;

    /// Concrete topology helper and coordinate backend implementations.
    ///
    /// This module contains the Euclidean and toroidal topology-space helpers,
    /// plus the spherical coordinate/metric backend for points on `S^D`
    /// realized in `R^(D+1)`.
    pub mod spaces {
        /// Euclidean space topology
        pub mod euclidean;
        /// Spherical space topology
        pub mod spherical;
        /// Toroidal space topology
        pub mod toroidal;

        pub use euclidean::EuclideanSpace;
        pub use spherical::{SphericalMetric, SphericalPoint, SphericalPointError};
        pub use toroidal::{LiftedLinkEdge, LiftedVertexId, ToroidalSpace};
    }

    // Re-export commonly used types
    pub use crate::TopologyGuarantee;
    pub use characteristics::*;
    pub use manifold::{
        BoundaryFacetClassification, ManifoldError, classify_boundary_facet,
        validate_closed_boundary, validate_ridge_links, validate_vertex_links,
    };
    pub use ridge::{
        RidgeCandidate, RidgeCandidateError, RidgeLinkView, RidgeQuery, RidgeView,
        ridge_star_simplices,
    };
    pub use traits::*;
}

/// Public collection aliases and small-buffer types used by low-level APIs.
///
/// This module is the public replacement for reaching through the internal
/// implementation namespace. It keeps common map, set, key-map, and
/// small-buffer aliases convenient without importing every algorithm-specific
/// scratch buffer.
///
/// # Examples
///
/// ```rust
/// use delaunay::collections::{FastHashMap, SmallBuffer};
///
/// let mut counts: FastHashMap<&'static str, usize> = FastHashMap::default();
/// counts.insert("simplices", 3);
///
/// let mut scratch: SmallBuffer<usize, 4> = SmallBuffer::new();
/// scratch.push(counts["simplices"]);
///
/// assert_eq!(scratch.as_slice(), &[3]);
/// ```
pub mod collections {
    pub use crate::core::collections::{
        Entry, FacetIndex, FacetIssuesMap, FacetSharingSimplicesBuffer, FacetVertexMap,
        FastBuildHasher, FastHashMap, FastHashSet, FastHasher, KeyBasedSimplexMap,
        KeyBasedVertexMap, MAX_PRACTICAL_DIMENSION_SIZE, NeighborBuffer, PeriodicOffsetBuffer,
        SecureHashMap, SecureHashSet, SimplexKeyBuffer, SimplexKeySet, SimplexNeighborsMap,
        SimplexSecondaryMap, SimplexToVertexUuidsMap, SimplexVertexBuffer, SimplexVertexKeyBuffer,
        SimplexVertexKeysMap, SimplexVertexUuidBuffer, SimplexVerticesMap, SmallBuffer, Uuid,
        UuidToSimplexKeyMap, UuidToVertexKeyMap, VertexKeyBuffer, VertexKeySet, VertexSecondaryMap,
        VertexToSimplicesMap, VertexUuidBuffer, VertexUuidSet, fast_hash_map_with_capacity,
        fast_hash_set_with_capacity, small_buffer_with_capacity_2, small_buffer_with_capacity_8,
        small_buffer_with_capacity_16,
    };

    /// Expert aliases for algorithm-local scratch buffers.
    ///
    /// These remain public for advanced users and APIs that expose exact buffer
    /// shapes, but they are separated from the common collection aliases to
    /// avoid accidental broad imports.
    pub mod algorithm_buffers {
        pub use crate::core::collections::{
            BadSimplexBuffer, CLEANUP_OPERATION_BUFFER_SIZE, CavityBoundaryBuffer, FacetInfoBuffer,
            GeometricPointBuffer, PointBuffer, SimplexRemovalBuffer, ValidSimplicesBuffer,
            ViolationBuffer,
        };
    }
}

/// Public low-level topology data structures and TDS helpers.
///
/// Use this module when you need simplices, facets, keys, the
/// [`Tds`](crate::tds::Tds) container, validation reports, or TDS-specific
/// helpers without reaching into the internal implementation namespace.
///
/// # Examples
///
/// ```rust
/// use delaunay::tds::Tds;
///
/// let tds: Tds<(), (), 2> = Tds::empty();
///
/// assert_eq!(tds.number_of_vertices(), 0);
/// assert_eq!(tds.number_of_simplices(), 0);
/// ```
pub mod tds {
    pub use crate::core::adjacency::*;
    pub use crate::core::collections::{
        FacetIndex, FastHashMap, FastHashSet, NeighborBuffer, PeriodicOffsetBuffer,
        SimplexKeyBuffer, SmallBuffer, Uuid,
    };
    pub use crate::core::edge::*;
    pub use crate::core::facet::*;
    pub use crate::core::simplex::*;
    pub use crate::core::tds::*;
    pub use crate::core::util::{
        UuidValidationError, checked_facet_key_from_vertex_keys, facet_view_to_vertices,
        facet_views_are_adjacent, format_jaccard_report, jaccard_distance, jaccard_index,
        make_uuid, measure_with_result, stable_hash_u64_slice, usize_to_u8, validate_uuid,
        verify_facet_index_consistency,
    };
    pub use crate::core::vertex::*;
}

/// Public low-level algorithms that are useful outside full construction.
///
/// This module currently exposes point-location and conflict-region building
/// blocks. Higher-level Delaunay construction, repair, and editing APIs are
/// available at the crate root and through the matching focused preludes.
///
/// # Examples
///
/// ```rust
/// use delaunay::algorithms::{LocateError, locate};
/// use delaunay::prelude::geometry::{AdaptiveKernel, Coordinate, Point};
/// use delaunay::tds::Tds;
///
/// # fn main() -> Result<(), delaunay::prelude::geometry::CoordinateConversionError> {
/// let tds: Tds<(), (), 2> = Tds::empty();
/// let kernel = AdaptiveKernel::new();
/// let point = Point::try_from([0.0, 0.0])?;
///
/// std::assert_matches!(
///     locate(&tds, &kernel, &point, None),
///     Err(LocateError::EmptyTriangulation)
/// );
/// # Ok(())
/// # }
/// ```
pub mod algorithms {
    #[cfg(feature = "diagnostics")]
    #[cfg_attr(docsrs, doc(cfg(feature = "diagnostics")))]
    pub use crate::core::algorithms::locate::verify_conflict_region_completeness;
    pub use crate::core::algorithms::locate::{
        ConflictError, InternalInconsistencySite, LocateError, LocateFallback,
        LocateFallbackReason, LocateResult, LocateStats, extract_cavity_boundary,
        find_conflict_region, locate, locate_with_stats,
    };
}

/// Public traversal, adjacency, barycenter, convex-hull, set-comparison, and query support APIs.
///
/// This module is intended for callers who need to inspect a triangulation or
/// compare derived topology without importing construction and repair surfaces,
/// or compute topology-aware local-editing points. It also re-exports
/// query-adjacent support types such as [`SimplexBarycenterError`] for
/// [`DelaunayTriangulation::simplex_barycenter`] and [`SimplexDataFillError`] for
/// follow-on simplex payload assignment.
///
/// # Examples
///
/// ```rust
/// use std::collections::HashSet;
///
/// use delaunay::query::{JaccardComputationError, jaccard_index};
///
/// # fn main() -> Result<(), JaccardComputationError> {
/// let a: HashSet<_> = [1, 2, 3].into_iter().collect();
/// let b: HashSet<_> = [3, 4].into_iter().collect();
///
/// let score = jaccard_index(&a, &b)?;
/// assert!((score - 0.25).abs() < 1e-12);
/// # Ok(())
/// # }
/// ```
pub mod query {
    pub use crate::assert_jaccard_gte;
    pub use crate::core::query::QueryError;
    pub use crate::core::traits::data_type::{
        DataCopy, DataDebug, DataDeserialize, DataIdentity, DataSerde, DataSerialize, DataType,
    };
    pub use crate::core::traits::facet_incidence_analysis::FacetIncidenceAnalysis;
    pub use crate::core::util::{
        JaccardComputationError, extract_edge_set, extract_facet_identifier_set,
        extract_hull_facet_set, extract_vertex_coordinate_set, format_jaccard_report,
        jaccard_distance, jaccard_index, measure_with_result,
    };
    pub use crate::flips::RidgeHandle;
    pub use crate::geometry::Point;
    pub use crate::geometry::algorithms::convex_hull::{
        ConvexHull, ConvexHullConstructionError, ConvexHullValidationError,
    };
    pub use crate::geometry::kernel::{
        AdaptiveKernel, ExactPredicates, FastKernel, Kernel, RobustKernel,
    };
    pub use crate::geometry::traits::coordinate::Coordinate;
    pub use crate::geometry::{insphere, insphere_distance, insphere_lifted};
    pub use crate::tds::{
        AllFacetsIter, BoundaryFacetsIter, EdgeIndex, EdgeKey, EdgeKeyError, EdgeView, FacetHandle,
        FacetIncidenceView, FacetToSimplicesIndex, FacetView, IncidenceView, OneSidedFacetsIter,
        Simplex, SimplexFacetsIter, SimplexKey, SimplexNeighborIndex, TopologyIndexBuildError,
        TriangulationAdjacency, Vertex, VertexKey,
    };
    pub use crate::topology::ridge::{
        RidgeCandidate, RidgeCandidateError, RidgeLinkView, RidgeQuery, RidgeView,
    };
    pub use crate::{DelaunayTriangulation, Triangulation};
    pub use crate::{SimplexBarycenterError, SimplexDataFillError};
}

/// A prelude module that re-exports commonly used types and macros.
/// This makes it easier to import the most commonly used items from the crate.
pub mod prelude {
    // Re-export the public low-level facades.
    pub use crate::query::{
        DataCopy, DataDebug, DataDeserialize, DataIdentity, DataSerde, DataSerialize, DataType,
        FacetIncidenceAnalysis, QueryError, RidgeCandidate, RidgeCandidateError, RidgeHandle,
        RidgeLinkView, RidgeQuery, RidgeView, SimplexBarycenterError, SimplexDataFillError,
    };
    pub use crate::tds::*;
    pub use crate::vertex;
    pub use crate::{
        ConstructionOptions, ConstructionSkipSample, ConstructionSlowInsertionSample,
        ConstructionStatistics, DedupPolicy, DedupTolerance, DelaunayCheckPolicy,
        DelaunayConstructionFailure, DelaunayConstructionRepairPhase,
        DelaunayConstructionRetryFailure, DelaunayError, DelaunayRepairHeuristicConfig,
        DelaunayRepairHeuristicSeeds, DelaunayRepairOperation, DelaunayRepairOutcome,
        DelaunayRepairPolicy, DelaunayResult, DelaunayTriangulation, DelaunayTriangulationBuilder,
        DelaunayTriangulationConstructionError,
        DelaunayTriangulationConstructionErrorWithStatistics, DelaunayTriangulationValidationError,
        DelaunayVerificationError, DelaunayVerificationErrorKind, DuplicateDetectionMetrics,
        FinalDelaunayValidationContext, FinalTopologyValidationContext, InitialSimplexStrategy,
        InsertionOrderStrategy, InsertionResult, PeriodicDomainPeriodError, PlManifoldRepairError,
        PlManifoldRepairStage, PlManifoldRepairStats, RepairDecision, RepairSkipReason,
        RetryPolicy, SphericalDelaunayBuilder, SphericalDelaunayConstructionError,
        SphericalDelaunayTriangulation, SphericalDelaunayValidationError, SphericalMetric,
        SphericalPoint, SphericalPointError, SphericalSimplex, SphericalSimplexError,
        SphericalValidationLayer, TopologicalOperation, TopologyGuarantee, Triangulation,
        TriangulationConstructionError, TriangulationRealizationIntersectionDetail,
        TriangulationRealizationSimplexDetail, TriangulationRealizationSimplexPairDetail,
        TriangulationRealizationValidationError, TriangulationRealizationValidationErrorKind,
        TriangulationRealizationValidationReport, TriangulationValidationError,
        TriangulationValidationReport, ValidationConfigurationError, ValidationPolicy,
        try_vertices_from_points,
    };

    // Re-export utility items, but avoid exporting the util module names themselves.
    //
    // In particular, exporting a local `uuid` module conflicts with the external `uuid`
    // crate name, making `use uuid::Uuid;` ambiguous for downstream users.
    pub use self::ordering::{
        HilbertBitDepth, HilbertError, HilbertQuantizedBatch, HilbertQuantizedVec,
        MAX_HILBERT_BITS, hilbert_index_in_range, hilbert_indices_for_quantized_batch,
        hilbert_indices_prequantized, hilbert_quantize_batch_in_range, hilbert_quantize_in_range,
        hilbert_sort_by_stable_in_range, hilbert_sort_by_unstable_in_range,
        hilbert_sorted_indices_in_range, try_hilbert_index, try_hilbert_quantize,
        try_hilbert_sort_by_stable, try_hilbert_sort_by_unstable, try_hilbert_sorted_indices,
    };
    pub use crate::core::util::{
        DeduplicationError, dedup_vertices_epsilon, dedup_vertices_exact,
        filter_vertices_excluding, try_dedup_vertices_epsilon,
    };
    pub use crate::delaunay_property_validation::{
        DelaunayValidationError, DelaunayViolationDetail, DelaunayViolationReport,
        delaunay_violation_report, find_delaunay_violations,
    };
    pub use crate::query::{
        JaccardComputationError, extract_edge_set, extract_facet_identifier_set,
        extract_hull_facet_set, extract_vertex_coordinate_set, format_jaccard_report,
        jaccard_distance, jaccard_index, measure_with_result,
    };
    pub use crate::tds::{
        UuidValidationError, checked_facet_key_from_vertex_keys, facet_view_to_vertices,
        facet_views_are_adjacent, make_uuid, stable_hash_u64_slice, usize_to_u8, validate_uuid,
        verify_facet_index_consistency,
    };
    pub use crate::topology::{
        GlobalTopology, GlobalTopologyModelError, TopologyError, TopologyKind,
        ToroidalConstructionMode, ToroidalDomain, ToroidalDomainError,
    };

    // Re-export point location algorithms from the public algorithms facade.
    pub use crate::algorithms::{
        ConflictError, InternalInconsistencySite, LocateError, LocateFallback,
        LocateFallbackReason, LocateResult, LocateStats, locate, locate_with_stats,
    };

    // Re-export incremental insertion types
    pub use crate::{
        CavityFillingError, CavityRepairStage, DelaunayRepairErrorKind,
        DelaunayRepairFailureContext, HullExtensionReason, InitialSimplexConstructionError,
        InitialSimplexUnexpectedInsertionStage, InsertionError, InsertionErrorKind,
        InsertionErrorSourceKind, InsertionTopologyValidationContext, NeighborRebuildError,
        NeighborWiringError, SpatialIndexConstructionFailure, TdsConstructionFailure,
        TdsValidationFailure,
    };
    pub use crate::{InsertionOutcome, InsertionStatistics, SuspicionFlags};

    // Re-export diagnostic types for scientific analysis of construction and repair
    pub use crate::flips::{
        DelaunayRepairDiagnostics, DelaunayRepairError, DelaunayRepairHeuristicRebuildFailure,
        DelaunayRepairHeuristicRebuildFailureKind, DelaunayRepairHeuristicVertexContext,
        DelaunayRepairOrientationCanonicalizationFailure,
        DelaunayRepairOrientationCanonicalizationFailureKind, DelaunayRepairPostconditionFailure,
        DelaunayRepairStats, DelaunayRepairVerificationContext, FlipContextError,
        FlipEdgeAdjacencyError, FlipError, FlipFailureKind, FlipMutationError,
        FlipNeighborCavityFailureKind, FlipNeighborDelaunayValidationFailureKind,
        FlipNeighborHullExtensionFailureKind, FlipNeighborRepairDiagnostics,
        FlipNeighborRepairFailure, FlipNeighborWiringError, FlipOrientationCheckStage,
        FlipPredicateError, FlipPredicateOperation, FlipTriangleAdjacencyError,
        FlipVertexAdjacencyError, RepairQueueOrder, TriangleHandleError,
    };

    // Re-export commonly used collection types from the public collections facade.
    // These are frequently used in advanced examples and downstream code
    pub use crate::collections::{
        FastHashMap, FastHashSet, SecureHashMap, SecureHashSet, SimplexNeighborsMap,
        SimplexSecondaryMap, SmallBuffer, VertexSecondaryMap, VertexToSimplicesMap,
        fast_hash_map_with_capacity, fast_hash_set_with_capacity,
    };

    // Re-export from geometry
    pub use crate::geometry::{
        algorithms::*, coordinate_range::*, kernel::*, matrix::*, point::*, predicates::*,
        quality::*, robust_predicates::*, traits::coordinate::*, util::*,
    };

    /// Batch construction options, builders, and construction errors.
    ///
    /// This focused prelude is for callers configuring Delaunay construction
    /// without importing the broader triangulation editing and repair
    /// surface.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::construction::{
    ///     DelaunayResult, DelaunayTriangulationBuilder, vertex,
    /// };
    ///
    /// # fn main() -> DelaunayResult<()> {
    /// let vertices = vec![
    ///     vertex![0.0, 0.0]?,
    ///     vertex![1.0, 0.0]?,
    ///     vertex![0.0, 1.0]?,
    /// ];
    /// let triangulation = DelaunayTriangulationBuilder::new(&vertices)
    ///     .build()?;
    ///
    /// assert_eq!(triangulation.number_of_vertices(), 3);
    /// # Ok(())
    /// # }
    /// ```
    pub mod construction {
        pub use crate::builder::{DelaunayTriangulationBuilder, ExplicitConstructionError};
        pub use crate::construction::{
            ConstructionOptions, ConstructionSkipSample, ConstructionSlowInsertionSample,
            ConstructionStatistics, DedupPolicy, DedupTolerance, DelaunayConstructionFailure,
            DelaunayConstructionRepairPhase, DelaunayConstructionRetryFailure, DelaunayError,
            DelaunayResult, DelaunayTriangulationConstructionError,
            DelaunayTriangulationConstructionErrorWithStatistics, InitialSimplexStrategy,
            InsertionOrderStrategy, RetryPolicy,
        };
        pub use crate::core::util::DeduplicationError;
        pub use crate::geometry::coordinate_range::{
            CoordinateRangeBound, CoordinateRangeError, CoordinateRangeOrdering,
            InvalidCoordinateValue,
        };
        pub use crate::geometry::traits::coordinate::CoordinateValidationError;
        pub use crate::geometry::util::{InvalidPositiveScalar, RandomPointGenerationError};
        pub use crate::repair::DelaunayRepairPolicy;
        pub use crate::spherical::{
            SphericalDelaunayBuilder, SphericalDelaunayConstructionError,
            SphericalDelaunayTriangulation, SphericalDelaunayValidationError, SphericalSimplex,
            SphericalSimplexError, SphericalValidationLayer,
        };
        pub use crate::tds::{
            SimplexValidationError, SimplexValidationReport, Vertex, VertexValidationError,
            VertexValidationReport,
        };
        pub use crate::topology::traits::{
            GlobalTopology, GlobalTopologyModelError, TopologyKind, ToroidalConstructionMode,
            ToroidalDomain, ToroidalDomainError,
        };
        pub use crate::validation::{
            DelaunayTriangulationValidationError, DelaunayVerificationError,
            DelaunayVerificationErrorKind,
        };
        pub use crate::vertex;
        pub use crate::{
            CavityFillingError, CavityRepairStage, DelaunayTriangulation, DeleteVertexError,
            FinalDelaunayValidationContext, FinalTopologyValidationContext,
            SpatialIndexConstructionFailure, TopologyGuarantee, Triangulation,
            TriangulationConstructionError, try_vertices_from_points,
        };
    }

    /// Generic triangulation construction, validation, query, and local repair.
    ///
    /// This focused prelude is for callers working directly with
    /// [`Triangulation`] rather than the higher-level
    /// [`DelaunayTriangulation`] wrapper. It keeps the generic TDS/kernel/error
    /// types needed by public `Triangulation` methods together without pulling
    /// in Delaunay repair, delaunayize, or batch-construction APIs.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::triangulation::{
    ///     FastKernel, Triangulation, TriangulationConstructionError, vertex,
    /// };
    /// use delaunay::prelude::geometry::CoordinateConversionError;
    ///
    /// # #[derive(Debug, thiserror::Error)]
    /// # enum ExampleError {
    /// #     #[error(transparent)]
    /// #     Source(#[from] TriangulationConstructionError),
    /// #     #[error(transparent)]
    /// #     Coordinate(#[from] CoordinateConversionError),
    /// # }
    /// # fn main() -> Result<(), ExampleError> {
    /// let vertices = vec![
    ///     vertex![0.0, 0.0]?,
    ///     vertex![1.0, 0.0]?,
    ///     vertex![0.0, 1.0]?,
    /// ];
    /// let tds = Triangulation::<FastKernel<f64>, (), (), 2>::build_initial_simplex(&vertices)?;
    ///
    /// assert_eq!(tds.number_of_vertices(), 3);
    /// assert_eq!(tds.number_of_simplices(), 1);
    /// # Ok(())
    /// # }
    /// ```
    pub mod triangulation {
        pub use crate::collections::{FacetIssuesMap, SimplexKeyBuffer, SmallBuffer};
        pub use crate::geometry::kernel::{
            AdaptiveKernel, ExactPredicates, FastKernel, Kernel, RobustKernel,
        };
        pub use crate::geometry::point::Point;
        pub use crate::query::{
            AllFacetsIter, BoundaryFacetsIter, DataCopy, DataDebug, DataDeserialize, DataIdentity,
            DataSerde, DataSerialize, DataType, EdgeIndex, EdgeKey, EdgeKeyError, EdgeView,
            FacetIncidenceAnalysis, FacetIncidenceView, FacetToSimplicesIndex, FacetView,
            IncidenceView, OneSidedFacetsIter, QueryError, RidgeCandidate, RidgeCandidateError,
            RidgeHandle, RidgeLinkView, RidgeQuery, RidgeView, SimplexFacetsIter,
            SimplexNeighborIndex, TopologyIndexBuildError, TriangulationAdjacency,
        };
        pub use crate::tds::{
            FacetHandle, InvariantError, NeighborSlot, Simplex, SimplexKey, Tds,
            TdsConstructionError, TdsError, TdsErrorKind, TdsMutationError,
            TriangulationValidationErrorKind, Vertex, VertexKey,
        };
        pub use crate::topology::manifold::ManifoldError;
        pub use crate::vertex;
        pub use crate::{
            InsertionError, PeriodicDomainPeriodError, SpatialIndexConstructionFailure,
            TopologyGuarantee, Triangulation, TriangulationConstructionError,
            TriangulationRealizationIntersectionDetail, TriangulationRealizationSimplexDetail,
            TriangulationRealizationSimplexPairDetail, TriangulationRealizationValidationError,
            TriangulationRealizationValidationErrorKind, TriangulationRealizationValidationReport,
            TriangulationValidationError, TriangulationValidationReport,
            ValidationConfigurationError, ValidationPolicy,
        };
    }

    /// Unified Pachner move workflow for local bistellar edits.
    ///
    /// This focused prelude exports the unified request/proposal/result/dispatch
    /// API, the handles and handle-construction errors needed to construct
    /// moves, result metadata needed to inspect moves, and [`vertex!`](crate::vertex)
    /// for k=1 insertion vertices. Low-level flip primitives stay under
    /// [`crate::flips`] for expert/debug workflows.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::construction::{
    ///     DelaunayResult, DelaunayTriangulationBuilder, TopologyGuarantee,
    /// };
    /// use delaunay::prelude::pachner::{
    ///     BistellarFlipKind, FlipDirection, PachnerMove, PachnerMoves, vertex,
    /// };
    ///
    /// # fn main() -> DelaunayResult<()> {
    /// let vertices = vec![
    ///     vertex![0.0, 0.0, 0.0]?,
    ///     vertex![1.0, 0.0, 0.0]?,
    ///     vertex![0.0, 1.0, 0.0]?,
    ///     vertex![0.0, 0.0, 1.0]?,
    /// ];
    /// let mut dt = DelaunayTriangulationBuilder::new(&vertices)
    ///     .topology_guarantee(TopologyGuarantee::PLManifold)
    ///     .build()?;
    /// let Some((simplex_key, _)) = dt.simplices().next() else {
    ///     return Ok(());
    /// };
    ///
    /// let result = dt
    ///     .propose_pachner(PachnerMove::K1Insert {
    ///         simplex_key,
    ///         vertex: vertex![0.2, 0.2, 0.2]?,
    ///     })?
    ///     .attempt_on(&mut dt)?;
    /// assert_eq!(result.kind, BistellarFlipKind::k1(3));
    /// assert_eq!(result.direction, FlipDirection::Forward);
    /// assert_eq!(result.inserted_face_vertices.len(), 1);
    /// assert_eq!(result.new_simplices.len(), 4);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// The focused prelude intentionally excludes the lower-level flip trait:
    ///
    /// ```compile_fail
    /// use delaunay::prelude::pachner::BistellarFlips;
    /// ```
    ///
    /// Unified Pachner imports do not expose the primitive flip methods:
    ///
    /// ```compile_fail
    /// use delaunay::prelude::construction::{DelaunayResult, DelaunayTriangulationBuilder};
    /// use delaunay::prelude::pachner::*;
    ///
    /// # fn main() -> DelaunayResult<()> {
    /// let vertices = vec![
    ///     vertex![0.0, 0.0, 0.0]?,
    ///     vertex![1.0, 0.0, 0.0]?,
    ///     vertex![0.0, 1.0, 0.0]?,
    ///     vertex![0.0, 0.0, 1.0]?,
    /// ];
    /// let mut dt = DelaunayTriangulationBuilder::new(&vertices).build()?;
    /// let Some((simplex_key, _)) = dt.simplices().next() else {
    ///     return Ok(());
    /// };
    /// let Ok(facet) = dt.facet_handle(simplex_key, 0) else {
    ///     return Ok(());
    /// };
    /// if dt.flip_k2(facet).is_err() {
    ///     return Ok(());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub mod pachner {
        pub use crate::flips::{
            BistellarFlipKind, FlipDirection, FlipError, RidgeHandle, TriangleHandle,
            TriangleHandleError,
        };
        pub use crate::pachner::{
            PachnerMove, PachnerMoveFeasibility, PachnerMoveResult, PachnerMoves, PachnerProposal,
        };
        pub use crate::tds::{
            EdgeKey, EdgeKeyError, FacetError, FacetHandle, SimplexKey, TopologyOwner,
            TopologyOwnerId, Vertex, VertexKey,
        };
        pub use crate::vertex;
    }

    /// Incremental insertion diagnostics and result types.
    pub mod insertion {
        pub use crate::{
            CavityFillingError, CavityRepairStage, DelaunayRepairErrorKind,
            DelaunayRepairFailureContext, HullExtensionReason, InitialSimplexConstructionError,
            InitialSimplexUnexpectedInsertionStage, InsertionError, InsertionErrorKind,
            InsertionErrorSourceKind, InsertionTopologyValidationContext, NeighborRebuildError,
            NeighborWiringError, SpatialIndexConstructionFailure, TdsConstructionFailure,
            TdsValidationFailure,
        };
        pub use crate::{InsertionOutcome, InsertionResult, InsertionStatistics};
    }

    /// Vertex deletion errors and key types.
    ///
    /// Deletion itself is an inherent method on
    /// [`DelaunayTriangulation`], so callers
    /// usually import the triangulation type from
    /// [`prelude::construction`](crate::prelude::construction) and import this
    /// focused prelude only when they need to match deletion-specific failures.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::deletion::{DeleteVertexError, VertexKey};
    /// use slotmap::KeyData;
    ///
    /// let err = DeleteVertexError::VertexNotFound {
    ///     vertex_key: VertexKey::from(KeyData::from_ffi(42)),
    /// };
    /// std::assert_matches!(err, DeleteVertexError::VertexNotFound { .. });
    /// ```
    pub mod deletion {
        pub use crate::DeleteVertexError;
        pub use crate::tds::VertexKey;
    }

    /// Topological operation telemetry and repair decisions.
    pub mod operations {
        pub use crate::{
            InsertionOutcome, InsertionResult, InsertionStatistics, RepairDecision,
            RepairSkipReason, SuspicionFlags, TopologicalOperation,
        };
    }

    /// Flip-based Delaunay repair, diagnostics, and Level 5 validation.
    ///
    /// ```rust
    /// use delaunay::prelude::repair::{
    ///     FlipNeighborHullExtensionFailureKind, FlipNeighborRepairFailure,
    /// };
    ///
    /// let reason = FlipNeighborHullExtensionFailureKind::DisconnectedVisiblePatch;
    /// std::assert_matches!(
    ///     reason,
    ///     FlipNeighborHullExtensionFailureKind::DisconnectedVisiblePatch
    /// );
    ///
    /// let _ = std::mem::size_of::<FlipNeighborRepairFailure>();
    /// ```
    pub mod repair {
        pub use crate::flips::{
            DelaunayRepairDiagnostics, DelaunayRepairError, DelaunayRepairHeuristicRebuildFailure,
            DelaunayRepairHeuristicRebuildFailureKind, DelaunayRepairHeuristicVertexContext,
            DelaunayRepairOrientationCanonicalizationFailure,
            DelaunayRepairOrientationCanonicalizationFailureKind,
            DelaunayRepairPostconditionFailure, DelaunayRepairStats,
            DelaunayRepairVerificationContext, FlipContextError, FlipEdgeAdjacencyError, FlipError,
            FlipFailureKind, FlipMutationError, FlipNeighborCavityFailureKind,
            FlipNeighborDelaunayValidationFailureKind, FlipNeighborHullExtensionFailureKind,
            FlipNeighborRepairDiagnostics, FlipNeighborRepairFailure, FlipNeighborWiringError,
            FlipOrientationCheckStage, FlipPredicateError, FlipPredicateOperation,
            FlipTriangleAdjacencyError, FlipVertexAdjacencyError, RepairQueueOrder,
            TriangleHandleError,
        };
        pub use crate::repair::{
            DelaunayCheckPolicy, DelaunayRepairHeuristicConfig, DelaunayRepairHeuristicSeeds,
            DelaunayRepairOutcome, DelaunayRepairPolicy,
        };
        pub use crate::{
            DelaunayRepairErrorKind, DelaunayRepairOperation, DelaunayTriangulation,
            DelaunayTriangulationValidationError, DelaunayVerificationError,
            DelaunayVerificationErrorKind,
        };
        pub use crate::{
            DelaunayValidationError, DelaunayViolationDetail, DelaunayViolationReport,
            delaunay_violation_report, find_delaunay_violations,
        };
        pub use crate::{
            TopologyGuarantee, Triangulation, ValidationConfigurationError, ValidationPolicy,
        };
    }

    /// End-to-end "repair then delaunayize" workflow.
    ///
    /// Self-contained: a single `use delaunay::prelude::delaunayize::*`
    /// import brings in [`DelaunayTriangulationBuilder`], [`DelaunayTriangulation`],
    /// PL-manifold repair types such as [`PlManifoldRepairStage`], and all
    /// delaunayize-specific types.
    pub mod delaunayize {
        pub use crate::delaunayize::*;
        pub use crate::{DelaunayTriangulation, DelaunayTriangulationBuilder};
        pub use crate::{PlManifoldRepairError, PlManifoldRepairStage, PlManifoldRepairStats};
    }

    /// Delaunay-level validation APIs, reports, and construction diagnostics.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::validation::ValidationCadence;
    ///
    /// let cadence = ValidationCadence::from_optional_every(Some(32));
    /// assert!(!cadence.should_validate(31));
    /// assert!(cadence.should_validate(32));
    /// ```
    pub mod validation {
        pub use crate::topology::manifold::ManifoldError;
        pub use crate::validation::*;
        pub use crate::{
            DelaunayTriangulationValidationError, DelaunayVerificationError,
            DelaunayVerificationErrorKind, OrientationWitness, PeriodicDomainPeriodError,
            SphericalDelaunayValidationError, SphericalValidationLayer, TopologyGuarantee,
            TriangulationRealizationIntersectionDetail, TriangulationRealizationSimplexDetail,
            TriangulationRealizationSimplexPairDetail, TriangulationRealizationValidationError,
            TriangulationRealizationValidationErrorKind, TriangulationRealizationValidationReport,
            TriangulationValidationError, TriangulationValidationReport,
            ValidationConfigurationError, ValidationPolicy,
        };
        pub use crate::{
            DelaunayValidationError, DelaunayViolationDetail, DelaunayViolationReport,
            delaunay_violation_report, find_delaunay_violations,
        };
    }

    /// Focused exports for collection types used throughout the crate.
    ///
    /// This prelude keeps common map, set, key-map, and small-buffer aliases
    /// convenient without importing every algorithm-specific scratch buffer.
    /// Expert-only buffers remain available from [`crate::collections`]
    /// or the nested [`crate::prelude::collections::algorithm_buffers`] module.
    ///
    /// ```compile_fail
    /// use delaunay::prelude::collections::SimplexRemovalBuffer;
    /// ```
    pub mod collections {
        pub use crate::collections::{
            Entry, FacetIndex, FacetIssuesMap, FacetSharingSimplicesBuffer, FastBuildHasher,
            FastHashMap, FastHashSet, FastHasher, KeyBasedSimplexMap, KeyBasedVertexMap,
            MAX_PRACTICAL_DIMENSION_SIZE, NeighborBuffer, PeriodicOffsetBuffer, SecureHashMap,
            SecureHashSet, SimplexKeyBuffer, SimplexKeySet, SimplexNeighborsMap,
            SimplexSecondaryMap, SimplexToVertexUuidsMap, SimplexVertexBuffer,
            SimplexVertexKeyBuffer, SimplexVertexKeysMap, SimplexVertexUuidBuffer,
            SimplexVerticesMap, SmallBuffer, Uuid, UuidToSimplexKeyMap, UuidToVertexKeyMap,
            VertexKeyBuffer, VertexKeySet, VertexSecondaryMap, VertexToSimplicesMap,
            VertexUuidBuffer, VertexUuidSet, fast_hash_map_with_capacity,
            fast_hash_set_with_capacity, small_buffer_with_capacity_2,
            small_buffer_with_capacity_8, small_buffer_with_capacity_16,
        };

        /// Expert aliases for algorithm-local scratch buffers.
        ///
        /// These remain public for advanced users and for APIs that expose their
        /// exact buffer shapes, but they are separated from the common
        /// collections prelude to avoid accidental broad imports.
        pub mod algorithm_buffers {
            pub use crate::collections::algorithm_buffers::{
                BadSimplexBuffer, CLEANUP_OPERATION_BUFFER_SIZE, CavityBoundaryBuffer,
                FacetInfoBuffer, GeometricPointBuffer, PointBuffer, SimplexRemovalBuffer,
                ValidSimplicesBuffer, ViolationBuffer,
            };
        }
    }

    /// Focused exports for low-level topology data structures.
    ///
    /// This prelude also exposes [`TopologyOwner`] and [`TopologyOwnerId`] for
    /// proposal and borrowed-view workflows that need runtime topology identity.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::tds::Tds;
    ///
    /// let tds: Tds<(), (), 2> = Tds::empty();
    ///
    /// assert_eq!(tds.number_of_vertices(), 0);
    /// assert_eq!(tds.number_of_simplices(), 0);
    /// ```
    pub mod tds {
        pub use crate::collections::{
            FacetIndex, FastHashMap, FastHashSet, NeighborBuffer, PeriodicOffsetBuffer,
            SimplexKeyBuffer, SmallBuffer, Uuid,
        };
        pub use crate::tds::*;
    }

    /// Focused exports for geometry types, simplex realizations, predicates, and helpers.
    pub mod geometry {
        pub use crate::geometry::{
            coordinate_range::{
                CoordinateRange, CoordinateRangeBound, CoordinateRangeError,
                CoordinateRangeOrdering, InvalidCoordinateValue,
            },
            kernel::{AdaptiveKernel, ExactPredicates, FastKernel, Kernel, RobustKernel},
            matrix::{LaError, Matrix, MatrixError, determinant},
            point::Point,
            predicates::{
                InSphere, Orientation, insphere, insphere_distance, insphere_lifted,
                simplex_orientation,
            },
            quality::{
                QualityDegeneracyMeasure, QualityError, QualityNumericOperation,
                QualitySimplexVerticesError, normalized_volume, radius_ratio,
            },
            realization::{
                LabeledSimplexRealization, LabeledSimplexRealizationError, PeriodicSimplexSpan,
                PeriodicSimplexSpanError, SimplexIntersectionFailure, SimplexIntersectionWitness,
                SimplexRealizationBuffer, axis_aligned_bounding_boxes_overlap,
                coordinate_range_for_axis, try_periodic_simplex_span,
                validate_simplex_realizations_intersect_only_in_shared_faces,
            },
            robust_predicates::{
                ConsistencyResult, InsphereConsistencyError, robust_insphere, robust_orientation,
            },
            traits::coordinate::{
                Coordinate, CoordinateConversionError, CoordinateConversionValue,
                CoordinateIdentity, CoordinateRepresentation, CoordinateValidationError,
                CoordinateValues, DEFAULT_TOLERANCE_F64, DegenerateSimplexReason,
                F64_MANTISSA_DIGITS, FiniteCheck, FiniteCoordinateValue, HashCoordinate,
                OrderedCmp, OrderedEq,
            },
            util::{
                ArrayConversionFailureReason, CircumcenterError, CircumcenterFailureReason,
                DegenerateGeometry, DegenerateMeasure, SurfaceMeasureError, ValueConversionError,
                ValueConversionFailureReason, circumcenter, circumradius, circumradius_with_center,
                facet_measure, hypot, inradius, safe_coords_from_f64, safe_coords_to_f64,
                safe_scalar_from_f64, safe_scalar_to_f64, safe_usize_to_scalar, simplex_volume,
                squared_norm, surface_measure,
            },
        };
    }

    /// Focused exports for core algorithms.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::algorithms::{LocateError, locate};
    /// use delaunay::prelude::geometry::{AdaptiveKernel, Coordinate, Point};
    /// use delaunay::prelude::tds::Tds;
    ///
    /// # fn main() -> Result<(), delaunay::prelude::geometry::CoordinateConversionError> {
    /// let tds: Tds<(), (), 2> = Tds::empty();
    /// let kernel = AdaptiveKernel::new();
    /// let point = Point::try_from([0.0, 0.0])?;
    ///
    /// std::assert_matches!(
    ///     locate(&tds, &kernel, &point, None),
    ///     Err(LocateError::EmptyTriangulation)
    /// );
    /// # Ok(())
    /// # }
    /// ```
    pub mod algorithms {
        pub use crate::algorithms::{
            ConflictError, InternalInconsistencySite, LocateError, LocateFallback,
            LocateFallbackReason, LocateResult, LocateStats, extract_cavity_boundary,
            find_conflict_region, locate, locate_with_stats,
        };
    }

    /// Focused exports for construction telemetry and opt-in diagnostic helpers.
    ///
    /// Construction telemetry is always available.  Expensive verification and
    /// violation-report helpers are compiled only with the `diagnostics`
    /// feature because they are intended for explicit debugging workflows, not
    /// the default public API surface.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::diagnostics::NeighborSlot;
    ///
    /// assert!(NeighborSlot::Boundary.is_boundary());
    /// ```
    pub mod diagnostics {
        #[cfg(feature = "diagnostics")]
        #[cfg_attr(docsrs, doc(cfg(feature = "diagnostics")))]
        pub use crate::algorithms::verify_conflict_region_completeness;
        #[cfg(feature = "diagnostics")]
        #[cfg_attr(docsrs, doc(cfg(feature = "diagnostics")))]
        pub use crate::debug_print_first_delaunay_violation;
        pub use crate::diagnostics::{
            BatchLocalRepairTrigger, ConstructionTelemetry, LocalRepairSample,
        };
        pub use crate::tds::NeighborSlot;
        pub use crate::{
            DelaunayViolationDetail, DelaunayViolationReport, delaunay_violation_report,
        };
    }

    /// Focused exports for generic simplicial-complex export data.
    ///
    /// These records are intended for notebooks, visualization tools, ML
    /// pipelines, and downstream crates that want stable vertex/simplex ids
    /// without depending on storage-local TDS handles.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::construction::{
    ///     DelaunayResult, DelaunayTriangulationBuilder, vertex,
    /// };
    /// use delaunay::prelude::export::MESH_EXPORT_SCHEMA;
    ///
    /// # fn main() -> DelaunayResult<()> {
    /// let vertices = vec![
    ///     vertex![0.0, 0.0]?,
    ///     vertex![1.0, 0.0]?,
    ///     vertex![0.0, 1.0]?,
    /// ];
    /// let triangulation = DelaunayTriangulationBuilder::new(&vertices).build()?;
    /// let export = triangulation.to_mesh_export()?;
    ///
    /// assert_eq!(export.metadata.schema, MESH_EXPORT_SCHEMA);
    /// # Ok(())
    /// # }
    /// ```
    pub mod export {
        pub use crate::geometry::traits::coordinate::InvalidCoordinateValue;
        pub use crate::io::visualization::{
            AdjacencyRecord, MESH_EXPORT_SCHEMA, MESH_EXPORT_SCHEMA_VERSION, MeshAdjacencyRecord,
            MeshExport, MeshExportError, MeshExportValidationError, MeshSimplexRecord,
            MeshVertexRecord, SimplexRecord, VISUALIZATION_SCHEMA, VISUALIZATION_SCHEMA_VERSION,
            ValidatedMeshExport, ValidatedVisualizationData, VertexRecord, VisualizationData,
            VisualizationDataValidationError, VisualizationExportError, VisualizationMetadata,
            VisualizationTopologyGuarantee, VisualizationTopologyKind,
        };
    }

    /// Convenience re-exports for common **read-only** workflows (topology traversal, adjacency,
    /// ridge views, simplex barycenters, convex-hull extraction, and common input types).
    ///
    /// This is useful if you want a smaller import surface than `delaunay::prelude::*`,
    /// while still having access to the key public APIs typically used in docs/tests/examples/benches.
    ///
    /// Includes:
    /// - Topology traversal: [`DelaunayTriangulation::facets`], [`DelaunayTriangulation::ridges`],
    ///   [`DelaunayTriangulation::edges`], [`DelaunayTriangulation::incident_edges`],
    ///   [`DelaunayTriangulation::simplex_neighbors`]
    /// - Fast repeated queries: [`DelaunayTriangulation::incidence`], [`DelaunayTriangulation::build_edge_index`],
    ///   [`DelaunayTriangulation::build_simplex_neighbor_index`], and composite
    ///   [`DelaunayTriangulation::adjacency`] / [`TriangulationAdjacency`]
    /// - Zero-allocation geometry accessors: [`DelaunayTriangulation::vertex_coords`],
    ///   [`DelaunayTriangulation::simplex_vertices`]
    /// - Local-editing coordinates: [`DelaunayTriangulation::simplex_barycenter`] and
    ///   [`SimplexBarycenterError`]
    /// - Convex hull extraction: [`ConvexHull::try_from_triangulation`]
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::collections::HashSet;
    ///
    /// use delaunay::prelude::query::{JaccardComputationError, jaccard_index};
    ///
    /// # fn main() -> Result<(), JaccardComputationError> {
    /// let a: HashSet<_> = [1, 2, 3].into_iter().collect();
    /// let b: HashSet<_> = [3, 4].into_iter().collect();
    ///
    /// let score = jaccard_index(&a, &b)?;
    /// assert!((score - 0.25).abs() < 1e-12);
    /// # Ok(())
    /// # }
    /// ```
    pub mod query {
        // Core read-only traversal / adjacency
        pub use crate::tds::{
            EdgeIndex, EdgeKey, EdgeKeyError, EdgeView, FacetHandle, FacetIncidenceView,
            FacetToSimplicesIndex, IncidenceView, SimplexKey, SimplexNeighborIndex,
            TopologyIndexBuildError, TriangulationAdjacency, VertexKey,
        };
        pub use crate::{DelaunayTriangulation, Triangulation};

        // Common input/output types (kept intentionally small)
        pub use crate::geometry::Point;
        pub use crate::geometry::kernel::{
            AdaptiveKernel, ExactPredicates, FastKernel, Kernel, RobustKernel,
        };
        pub use crate::geometry::traits::coordinate::Coordinate;
        pub use crate::query::{
            AllFacetsIter, BoundaryFacetsIter, DataCopy, DataDebug, DataDeserialize, DataIdentity,
            DataSerde, DataSerialize, DataType, FacetIncidenceAnalysis, FacetView,
            OneSidedFacetsIter, QueryError, RidgeCandidate, RidgeCandidateError, RidgeHandle,
            RidgeLinkView, RidgeQuery, RidgeView, Simplex, SimplexBarycenterError,
            SimplexDataFillError, SimplexFacetsIter, Vertex,
        };

        // Read-only predicates (useful in benchmarks / lightweight geometry checks)
        pub use crate::geometry::{insphere, insphere_distance, insphere_lifted};

        // Read-only algorithms
        pub use crate::assert_jaccard_gte;
        pub use crate::geometry::algorithms::convex_hull::{
            ConvexHull, ConvexHullConstructionError, ConvexHullValidationError,
        };
        pub use crate::query::{
            JaccardComputationError, extract_edge_set, extract_facet_identifier_set,
            extract_hull_facet_set, extract_vertex_coordinate_set, format_jaccard_report,
            jaccard_distance, jaccard_index,
        };

        // Instrumentation helpers (no-op unless features enable extra tracking)
        pub use crate::query::measure_with_result;
    }

    /// Focused exports for generating fixture data in doctests, integration tests,
    /// examples, and benchmarks.
    ///
    /// This module is intentionally separate from [`prelude::query`](crate::prelude::query)
    /// so read-only traversal imports do not need to imply random data generation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::generators::{
    ///     CoordinateRange, RandomPointGenerationError, generate_random_points_in_range_seeded,
    /// };
    /// use delaunay::prelude::geometry::Point;
    ///
    /// # fn main() -> Result<(), RandomPointGenerationError> {
    /// let range = CoordinateRange::try_new(0.0_f64, 1.0)?;
    /// let points: Vec<Point<3>> =
    ///     generate_random_points_in_range_seeded(4, range, 42)?;
    ///
    /// assert_eq!(points.len(), 4);
    /// # Ok(())
    /// # }
    /// ```
    pub mod generators {
        pub use crate::TopologyGuarantee;
        pub use crate::construction::InsertionOrderStrategy;
        pub use crate::geometry::coordinate_range::{
            CoordinateRange, CoordinateRangeBound, CoordinateRangeError, CoordinateRangeOrdering,
            InvalidCoordinateValue,
        };
        pub use crate::geometry::util::{
            InvalidPositiveScalar, RandomPointCount, RandomPointCountError,
            RandomPointGenerationError, RandomTriangulationBuilder,
            RandomTriangulationBuilderError, generate_grid_points,
            generate_poisson_points_in_range, generate_random_points_in_ball,
            generate_random_points_in_ball_seeded, generate_random_points_in_range,
            generate_random_points_in_range_seeded, generate_random_points_periodic,
            generate_random_triangulation_in_range,
            generate_random_triangulation_in_range_with_topology_guarantee,
            scaled_bounds_by_point_count, try_generate_poisson_points, try_generate_random_points,
            try_generate_random_points_seeded, try_generate_random_triangulation,
            try_generate_random_triangulation_with_topology_guarantee,
        };
    }

    /// Focused exports for Hilbert ordering and quantization utilities.
    ///
    /// These helpers are useful in doctests, integration tests, examples, and
    /// benchmarks that need deterministic space-filling-curve ordering without
    /// importing the broader triangulation or geometry preludes.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use delaunay::prelude::ordering::{HilbertBitDepth, HilbertError, try_hilbert_sorted_indices};
    ///
    /// let coords = [[0.9_f64, 0.9], [0.1, 0.1], [0.5, 0.5]];
    /// let bits = HilbertBitDepth::try_new(8)?;
    /// let order = try_hilbert_sorted_indices(&coords, (0.0, 1.0), bits)?;
    ///
    /// assert_eq!(order.len(), coords.len());
    /// # Ok::<(), HilbertError>(())
    /// ```
    pub mod ordering {
        pub use crate::core::util::{
            HilbertBitDepth, HilbertError, HilbertQuantizedBatch, HilbertQuantizedVec,
            MAX_HILBERT_BITS, hilbert_index_in_range, hilbert_indices_for_quantized_batch,
            hilbert_indices_prequantized, hilbert_quantize_batch_in_range,
            hilbert_quantize_in_range, hilbert_sort_by_stable_in_range,
            hilbert_sort_by_unstable_in_range, hilbert_sorted_indices_in_range, try_hilbert_index,
            try_hilbert_quantize, try_hilbert_sort_by_stable, try_hilbert_sort_by_unstable,
            try_hilbert_sorted_indices,
        };
    }

    /// Topology validation & analysis utilities.
    pub mod topology {
        /// Topology validation utilities.
        pub mod validation {
            pub use crate::topology::TopologyGuarantee;
            pub use crate::topology::characteristics::{euler, validation};
            pub use crate::topology::characteristics::{euler::*, validation::*};
            pub use crate::topology::manifold::{
                BoundaryFacetClassification, ManifoldError, classify_boundary_facet,
                validate_closed_boundary, validate_ridge_links, validate_ridge_links_for_simplices,
                validate_vertex_links,
            };
            pub use crate::topology::ridge::{
                RidgeCandidate, RidgeCandidateError, RidgeLinkView, RidgeQuery, RidgeView,
                ridge_star_simplices,
            };
            pub use crate::topology::traits::{
                GlobalTopology, GlobalTopologyModelError, TopologicalSpace, TopologyError,
                TopologyKind, ToroidalConstructionMode,
            };
        }

        /// Topological space models and traits.
        pub mod spaces {
            pub use crate::topology::spaces::*;
            pub use crate::topology::traits::{
                GlobalTopology, GlobalTopologyModelError, TopologicalSpace, TopologyError,
                TopologyKind, ToroidalConstructionMode, ToroidalDomain, ToroidalDomainError,
            };
        }
    }
}

/// The function `is_normal` checks that structs implement `auto` traits.
/// Traits are checked at compile time, so this function is only used for
/// testing.
#[must_use]
pub const fn is_normal<T: Send + Sync + Unpin>() -> bool {
    true
}

// =============================================================================
// TESTS
// =============================================================================

#[cfg(test)]
mod tests {
    use crate::geometry::matrix::LaError;
    use crate::{
        DelaunayTriangulation,
        core::{
            adjacency::TriangulationAdjacency, edge::EdgeKey, simplex::Simplex, tds::Tds,
            triangulation::Triangulation, vertex::Vertex,
        },
        geometry::{
            Point, algorithms::convex_hull::ConvexHull, kernel::FastKernel, util::CircumcenterError,
        },
        is_normal,
        prelude::delaunayize::{
            DelaunayTriangulationConstructionError, DelaunayizeConfig, DelaunayizeError,
            DelaunayizeOutcome, PlManifoldRepairError, PlManifoldRepairStage,
            PlManifoldRepairStats, SimplexDataRestoreError, SimplexValidationError,
        },
        prelude::repair::{
            DelaunayCheckPolicy, DelaunayRepairError, DelaunayRepairOutcome, DelaunayRepairPolicy,
            DelaunayRepairStats, DelaunayTriangulation as RepairDelaunayTriangulation,
            FlipContextError, FlipError, RepairQueueOrder, TopologyGuarantee,
        },
        prelude::*,
        vertex,
    };
    use std::assert_matches;

    #[cfg(feature = "count-allocations")]
    use allocation_counter::measure;

    // =============================================================================
    // TYPE SAFETY TESTS
    // =============================================================================

    #[test]
    fn normal_types() {
        assert!(is_normal::<Point<3>>());
        assert!(is_normal::<Vertex<(), 3>>());
        assert!(is_normal::<Simplex<(), 4>>());
        assert!(is_normal::<Tds<(), (), 4>>());
        assert!(is_normal::<Triangulation<FastKernel<f64>, (), (), 3>>());
        assert!(is_normal::<DelaunayTriangulation<FastKernel<f64>, (), (), 3>>());
        assert!(is_normal::<ConvexHull<(), (), 3>>());
        assert!(is_normal::<EdgeKey>());
        assert!(is_normal::<TriangulationAdjacency<'static>>());
        assert!(is_normal::<DelaunayizeConfig>());
        assert!(is_normal::<DelaunayizeOutcome<(), (), 3>>());
        assert!(is_normal::<DelaunayizeError>());
        assert!(is_normal::<DelaunayRepairError>());
        assert!(is_normal::<DelaunayRepairStats>());
        assert!(is_normal::<PlManifoldRepairError>());
        assert!(is_normal::<PlManifoldRepairStage>());
        assert!(is_normal::<PlManifoldRepairStats<(), (), 3>>());
        assert!(is_normal::<SimplexDataRestoreError>());
        assert!(is_normal::<SimplexValidationError>());
        assert!(is_normal::<DelaunayError>());
        assert!(is_normal::<DelaunayTriangulationConstructionError>());
    }

    #[test]
    fn circumcenter_error_clones_linear_algebra_source() {
        let source = LaError::non_finite_input_matrix(1, 2);
        let error = CircumcenterError::LinearAlgebraFailure { source };

        assert_eq!(error.clone(), error);
        assert!(error.to_string().contains("Linear algebra"));
    }

    #[test]
    fn la_errors_map_to_public_circumcenter_errors() {
        let unsupported = CircumcenterError::from(LaError::unsupported_dimension(9, 7));
        assert_eq!(
            unsupported,
            CircumcenterError::UnsupportedMatrixDimension {
                requested: 9,
                max: 7,
            }
        );

        let index_error = CircumcenterError::from(LaError::index_out_of_bounds(3, 4, 2));
        assert_eq!(
            index_error,
            CircumcenterError::MatrixError {
                source: MatrixError::OutOfBounds {
                    row: 3,
                    column: 4,
                    dimension: 2,
                },
            }
        );
    }

    #[test]
    fn prelude_collections_exports() {
        // Test that we can use the collections from the prelude
        let mut map: FastHashMap<u64, usize> = FastHashMap::default();
        map.insert(123, 456);
        assert_eq!(map.get(&123), Some(&456));

        let mut set: FastHashSet<u64> = FastHashSet::default();
        set.insert(789);
        assert!(set.contains(&789));

        let mut buffer: SmallBuffer<i32, 8> = SmallBuffer::new();
        buffer.push(42);
        assert_eq!(buffer.len(), 1);

        // Test capacity helpers
        let map_with_cap = fast_hash_map_with_capacity::<u64, usize>(100);
        assert!(map_with_cap.capacity() >= 100);

        let set_with_cap = fast_hash_set_with_capacity::<u64>(50);
        assert!(set_with_cap.capacity() >= 50);

        // Test domain-specific public types can be instantiated
        let _neighbors: SimplexNeighborsMap = SimplexNeighborsMap::default();
        let _vertex_simplices: VertexToSimplicesMap = VertexToSimplicesMap::default();
    }

    #[test]
    fn prelude_repair_exports() {
        let vertices = vec![
            vertex![0.0, 0.0].unwrap(),
            vertex![1.0, 0.0].unwrap(),
            vertex![0.0, 1.0].unwrap(),
        ];
        let dt: RepairDelaunayTriangulation<_, (), (), 2> =
            RepairDelaunayTriangulation::builder(&vertices)
                .build()
                .unwrap();

        assert!(dt.verify_via_flip_predicates().is_ok());
        assert!(dt.is_valid_delaunay().is_ok());

        let stats = DelaunayRepairStats::default();
        let outcome = DelaunayRepairOutcome {
            stats: stats.clone(),
            heuristic: None,
        };
        assert_eq!(outcome.stats.flips_performed, stats.flips_performed);
        let order = RepairQueueOrder::Fifo;
        assert_matches!(order, RepairQueueOrder::Fifo);
        assert_eq!(
            DelaunayRepairPolicy::default(),
            DelaunayRepairPolicy::EveryInsertion
        );
        assert_eq!(DelaunayCheckPolicy::default(), DelaunayCheckPolicy::EndOnly);

        let err = DelaunayRepairError::from(FlipError::DegenerateSimplex);
        assert_matches!(err, DelaunayRepairError::Flip { .. });
        let context_err = FlipContextError::ReplacementPeriodicOffsetCountMismatch {
            simplex_count: 1,
            offset_count: 0,
        };
        assert_matches!(
            context_err,
            FlipContextError::ReplacementPeriodicOffsetCountMismatch { .. }
        );
        let topo = TopologyGuarantee::PLManifold;
        assert_matches!(topo, TopologyGuarantee::PLManifold);
    }

    #[test]
    fn prelude_quality_exports() {
        // Test that quality functions are accessible from prelude
        let vertices = vec![
            vertex![0.0, 0.0].unwrap(),
            vertex![1.0, 0.0].unwrap(),
            vertex![0.0, 1.0].unwrap(),
        ];
        let dt: DelaunayTriangulation<_, (), (), 2> =
            DelaunayTriangulation::builder(&vertices).build().unwrap();

        // Get a simplex to test quality functions
        let (simplex_key, _) = dt.simplices().next().unwrap();

        // Test that quality functions are accessible
        let ratio = radius_ratio(dt.as_triangulation(), simplex_key).unwrap();
        assert!(ratio > 0.0);

        let norm_vol = normalized_volume(dt.as_triangulation(), simplex_key).unwrap();
        assert!(norm_vol > 0.0);
    }

    #[test]
    fn test_prelude_kernel_exports() {
        // Test that kernel types and predicates are accessible from prelude
        let fast_kernel = FastKernel::<f64>::new();
        let robust_kernel = RobustKernel::<f64>::new();

        // Test 2D orientation predicate
        let triangle = [
            Point::try_new([0.0, 0.0]).expect("finite point coordinates"),
            Point::try_new([1.0, 0.0]).expect("finite point coordinates"),
            Point::try_new([0.0, 1.0]).expect("finite point coordinates"),
        ];

        let fast_orientation = fast_kernel.orientation(&triangle).unwrap();
        assert_ne!(fast_orientation, 0, "Triangle should be non-degenerate");

        let robust_orientation = robust_kernel.orientation(&triangle).unwrap();
        assert_eq!(
            fast_orientation, robust_orientation,
            "Both kernels should agree"
        );

        // Test collinear detection
        let collinear = [
            Point::try_new([0.0, 0.0]).expect("finite point coordinates"),
            Point::try_new([1.0, 0.0]).expect("finite point coordinates"),
            Point::try_new([2.0, 0.0]).expect("finite point coordinates"),
        ];
        assert_eq!(
            fast_kernel.orientation(&collinear).unwrap(),
            0,
            "Collinear points should have zero orientation"
        );

        // Test in_sphere predicate
        let inside_point = Point::try_new([0.25, 0.25]).expect("finite point coordinates");
        let result = fast_kernel.in_sphere(&triangle, &inside_point).unwrap();
        assert_eq!(result, 1, "Point should be inside circumcircle");

        let outside_point = Point::try_new([2.0, 2.0]).expect("finite point coordinates");
        let result = fast_kernel.in_sphere(&triangle, &outside_point).unwrap();
        assert_eq!(result, -1, "Point should be outside circumcircle");
    }

    #[test]
    fn test_prelude_core_types() {
        // Test that core types are accessible and work from prelude
        // Point construction
        let p1 = Point::try_new([0.0, 0.0, 0.0]).expect("finite point coordinates");
        let p2 = Point::try_new([1.0, 0.0, 0.0]).expect("finite point coordinates");
        assert_ne!(p1, p2);

        // Vertex construction via the fallible smart constructor.
        let v1: Vertex<(), 3> = vertex!([0.0, 0.0, 0.0]).unwrap();
        let v2: Vertex<(), 3> = vertex!([1.0, 0.0, 0.0]).unwrap();
        assert_ne!(v1.point(), v2.point());

        // DelaunayTriangulation construction
        let vertices = vec![
            vertex![0.0, 0.0, 0.0].unwrap(),
            vertex![1.0, 0.0, 0.0].unwrap(),
            vertex![0.0, 1.0, 0.0].unwrap(),
            vertex![0.0, 0.0, 1.0].unwrap(),
        ];
        let dt: DelaunayTriangulation<_, (), (), 3> =
            DelaunayTriangulation::builder(&vertices).build().unwrap();
        assert_eq!(dt.number_of_vertices(), 4);
        assert_eq!(dt.number_of_simplices(), 1);

        // Access Triangulation and simplex query types
        let tri = dt.as_triangulation();
        assert_eq!(tri.number_of_vertices(), 4);
        assert_eq!(tri.number_of_simplices(), 1);

        // Iterate over simplices
        for (simplex_key, _simplex) in tri.simplices() {
            assert!(tri.simplex(simplex_key).is_some());
        }
    }

    #[test]
    fn test_prelude_point_location() {
        // Test that point location algorithms are accessible
        let vertices = vec![
            vertex![0.0, 0.0].unwrap(),
            vertex![1.0, 0.0].unwrap(),
            vertex![0.0, 1.0].unwrap(),
        ];
        let dt: DelaunayTriangulation<_, (), (), 2> =
            DelaunayTriangulation::builder(&vertices).build().unwrap();

        // Test locate via the owning triangulation.
        let query_point = Point::try_new([0.3, 0.3]).expect("finite point coordinates");
        let result = dt.locate(&query_point, None);
        assert!(result.is_ok());

        // Result should be a LocateResult
        match result.unwrap() {
            LocateResult::InsideSimplex(_)
            | LocateResult::OnFacet { .. }
            | LocateResult::OnEdge { .. }
            | LocateResult::OnVertex(_) => { /* expected or acceptable */ }
            LocateResult::Outside => panic!("Point should be inside triangulation"),
        }

        // Test outside point
        let outside_point = Point::try_new([10.0, 10.0]).expect("finite point coordinates");
        let result = dt.locate(&outside_point, None);
        assert!(result.is_ok());
    }

    #[test]
    fn test_prelude_geometry_types() {
        // Test Point with Coordinate trait
        let p = Point::try_new([1.0_f64, 2.0_f64, 3.0_f64]).expect("finite point coordinates");
        assert!((p.coords()[0] - 1.0_f64).abs() < f64::EPSILON);
        assert!((p.coords()[1] - 2.0_f64).abs() < f64::EPSILON);
        assert!((p.coords()[2] - 3.0_f64).abs() < f64::EPSILON);

        // Test predicates are accessible
        let triangle = [
            Point::try_new([0.0, 0.0]).expect("finite point coordinates"),
            Point::try_new([1.0, 0.0]).expect("finite point coordinates"),
            Point::try_new([0.0, 1.0]).expect("finite point coordinates"),
        ];

        // simplex_orientation is exported from predicates
        let orientation = simplex_orientation(&triangle).unwrap();
        assert_ne!(orientation, Orientation::DEGENERATE);

        // Test insphere predicate
        let test_point = Point::try_new([0.25, 0.25]).expect("finite point coordinates");
        let result = insphere(&triangle, test_point).unwrap();
        assert_eq!(result, InSphere::INSIDE);
    }

    #[test]
    fn test_prelude_convex_hull() {
        // Test that convex hull operations are accessible
        let vertices = vec![
            vertex![0.0, 0.0, 0.0].unwrap(),
            vertex![1.0, 0.0, 0.0].unwrap(),
            vertex![0.0, 1.0, 0.0].unwrap(),
            vertex![0.0, 0.0, 1.0].unwrap(),
        ];
        let dt: DelaunayTriangulation<_, (), (), 3> =
            DelaunayTriangulation::builder(&vertices).build().unwrap();

        // ConvexHull type should be accessible
        let hull = ConvexHull::try_from_triangulation(dt.as_triangulation()).unwrap();
        assert_eq!(hull.number_of_facets(), 4); // Tetrahedron has 4 faces

        // Test point visibility
        let outside_point = Point::try_new([2.0, 2.0, 2.0]).expect("finite point coordinates");
        let is_outside = hull
            .is_point_outside(&outside_point, dt.as_triangulation())
            .unwrap();
        assert!(is_outside);

        let inside_point = Point::try_new([0.25, 0.25, 0.25]).expect("finite point coordinates");
        let is_outside = hull
            .is_point_outside(&inside_point, dt.as_triangulation())
            .unwrap();
        assert!(!is_outside);
    }

    // =============================================================================
    // ALLOCATION COUNTING TESTS
    // =============================================================================

    /// Run these with `cargo test allocation_counting --features count-allocations`
    #[cfg(feature = "count-allocations")]
    #[test]
    fn basic_alloc_counting() {
        // Test a trivial operation that should not allocate
        let result = measure(|| {
            let x = 1 + 1;
            assert_eq!(x, 2);
        });

        // Assert that the returned struct has the expected fields
        // Available fields: count_total, count_current, count_max, bytes_total, bytes_current, bytes_max
        // For a trivial operation, we expect zero allocations
        assert_eq!(
            result.count_total, 0,
            "Expected zero total allocations for trivial operation, found: {}",
            result.count_total
        );
        assert_eq!(
            result.bytes_total, 0,
            "Expected zero total bytes allocated for trivial operation, found: {}",
            result.bytes_total
        );

        // Also check that current allocations are zero (no leaked allocations)
        assert_eq!(
            result.count_current, 0,
            "Expected zero current allocations after trivial operation, found: {}",
            result.count_current
        );
        assert_eq!(
            result.bytes_current, 0,
            "Expected zero current bytes allocated after trivial operation, found: {}",
            result.bytes_current
        );
    }

    #[cfg(feature = "count-allocations")]
    #[test]
    fn alloc_counting_with_vec() {
        // Test an operation that does allocate memory
        let result = measure(|| {
            let _vec: Vec<i32> = vec![1, 2, 3, 4, 5];
        });

        // For this operation, we expect some allocations
        assert!(
            result.count_total > 0,
            "Expected some allocations for Vec creation, found: {}",
            result.count_total
        );
        assert!(
            result.bytes_total > 0,
            "Expected some bytes allocated for Vec creation, found: {}",
            result.bytes_total
        );

        // After the operation, current allocations should be zero (Vec was dropped)
        assert_eq!(
            result.count_current, 0,
            "Expected zero current allocations after Vec drop, found: {}",
            result.count_current
        );
        assert_eq!(
            result.bytes_current, 0,
            "Expected zero current bytes after Vec drop, found: {}",
            result.bytes_current
        );

        // Max values should be at least as large as total (they track peak usage)
        assert!(
            result.count_max >= result.count_total,
            "Max count should be >= total count"
        );
        assert!(
            result.bytes_max >= result.bytes_total,
            "Max bytes should be >= total bytes"
        );
    }
}