axioval-engine 0.3.0

Trusted capability compiler and deterministic source-neutral validation runtime
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
//! Source-neutral proximity evidence between two model objects.
//!
//! ADR 0004: the service measures how close two bodies come and how deeply
//! they overlap; whether that is a clash, a clearance shortfall or an
//! acceptable joint is decided by a capability against declared tolerances.
//!
//! Two properties of the measurement are carried explicitly rather than
//! folded into one number:
//!
//! - **Fidelity.** A mesh of a curved part is a tessellation. Its chords cut
//!   inside the true surface, so a separation measured on it can be wrong by up
//!   to the chord deviation of each participant. Such evidence is marked
//!   approximate and carries that deviation, so a policy can widen its
//!   comparison instead of trusting a number the geometry cannot support.
//! - **Penetration is witnessed, not computed.** Zero separation does not say
//!   whether two bodies touch or interpenetrate. The adapter reports the
//!   deepest point it found inside the other body. That is a lower bound on
//!   the true depth. Only a closed solid has an inside; a surface entering a
//!   solid is measured against the solid, and two open surfaces, which share
//!   no volume, report `None`.
//! - **Shape comparisons are intervals.** The extent of the intersection
//!   along each axis ([`OverlapExtents`]) and the Hausdorff distance between
//!   the two surfaces are reported as [`LengthInterval`]s the true values lie
//!   in, so a policy judging them against a tolerance can tell a certain
//!   answer from an open one.
//! - **Volumes are certified intervals.** The volume two closed bodies share
//!   and each body's own volume ([`IntersectionVolume`]) are
//!   [`VolumeInterval`]s sure to contain the true values, never a point
//!   estimate.
//!
//! - **Extents along the bodies' own axes.** World axes misjudge a wall at
//!   an angle: a slab edge sunk 10 mm into it reaches far along x and y. An
//!   [`OverlapAlongRequest`] names the directions to measure along (such as
//!   each body's placement axes), and [`OverlapAlongEvidence`] answers the
//!   intersection's extent along each as a [`LengthInterval`].
//!
//! A second question rides on the same service: how far a body lies from
//! one class of another body's faces ([`FaceDistanceRequest`]), signed by
//! whether the body lies inside the other. It is what cover and protrusion
//! checks measure.

use std::sync::Arc;

use axioval_ir::{Evidence, ObjectId};

use crate::{ConvexPlanRegion, LengthInterval, MetricDirection, SignedDistanceInterval};

/// Why a proximity measurement could not be produced.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum ProximityError {
    /// The adapter holds no measurable geometry for an object.
    #[error("proximity measurement is unavailable for the requested object")]
    Unavailable,
    /// The object is declared to occupy no material, such as a storey or an
    /// opening. A fact about the object, not a failure to measure it: an
    /// object whose body could not be measured is [`Self::Unavailable`].
    #[error("the requested object occupies no material")]
    NoBody,
    /// Coordinates or measured quantities are non-finite, negative or incoherent.
    #[error("proximity measurement is not finite, non-negative and coherent")]
    InvalidMeasurement,
    /// The evidence's exactness disagrees with the measured geometry's fidelity.
    #[error("proximity evidence exactness must match geometry fidelity and be reviewable")]
    EvidenceFidelityMismatch,
    /// A body cannot be measured against itself.
    #[error("proximity of an object to itself is undefined")]
    SameObject,
    /// The request's projection is not measured by this method or service.
    #[error("the requested proximity projection is not supported")]
    UnsupportedProjection,
}

/// An axis-aligned box in canonical metres.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Bounds3 {
    min: [f64; 3],
    max: [f64; 3],
}

impl Bounds3 {
    /// Creates a box, rejecting non-finite or inverted extents.
    pub fn try_new(min: [f64; 3], max: [f64; 3]) -> Result<Self, ProximityError> {
        let coherent = (0..3)
            .all(|axis| min[axis].is_finite() && max[axis].is_finite() && min[axis] <= max[axis]);
        if !coherent {
            return Err(ProximityError::InvalidMeasurement);
        }
        Ok(Self { min, max })
    }
    pub fn min(&self) -> [f64; 3] {
        self.min
    }
    pub fn max(&self) -> [f64; 3] {
        self.max
    }
    /// The box grown by `margin` metres on every side.
    #[must_use]
    pub fn expanded(&self, margin: f64) -> Self {
        Self {
            min: self.min.map(|value| value - margin),
            max: self.max.map(|value| value + margin),
        }
    }
    /// Euclidean distance between the two boxes; zero when they meet.
    ///
    /// A lower bound on the separation of anything the boxes enclose, which
    /// is what makes it safe to discard pairs by it.
    pub fn gap(&self, other: &Self) -> f64 {
        (0..3)
            .map(|axis| {
                let gap = (other.min[axis] - self.max[axis])
                    .max(self.min[axis] - other.max[axis])
                    .max(0.0);
                gap * gap
            })
            .sum::<f64>()
            .sqrt()
    }
}

/// How faithfully the measured geometry represents an object's true shape.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GeometryFidelity {
    /// The mesh is the shape: every face of the object is planar.
    Exact,
    /// The mesh approximates curved faces; no point of the true surface lies
    /// farther than `chord_deviation_metres` from the mesh.
    Tessellated { chord_deviation_metres: f64 },
}

impl GeometryFidelity {
    /// A tessellation with a declared chord deviation.
    pub fn tessellated(chord_deviation_metres: f64) -> Result<Self, ProximityError> {
        if !chord_deviation_metres.is_finite() || chord_deviation_metres < 0.0 {
            return Err(ProximityError::InvalidMeasurement);
        }
        Ok(Self::Tessellated {
            chord_deviation_metres,
        })
    }
    /// Whether measurements on this geometry are exact.
    pub fn is_exact(&self) -> bool {
        matches!(self, Self::Exact)
    }
    /// How far the true surface may lie from the measured mesh.
    pub fn deviation_metres(&self) -> f64 {
        match self {
            Self::Exact => 0.0,
            Self::Tessellated {
                chord_deviation_metres,
            } => *chord_deviation_metres,
        }
    }
    /// Fidelity of a measurement taken between two bodies.
    ///
    /// Deviations add: each body's true surface may sit its own deviation away
    /// from its mesh, in the direction that shortens or lengthens the gap.
    #[must_use]
    pub fn combined(self, other: Self) -> Self {
        if self.is_exact() && other.is_exact() {
            Self::Exact
        } else {
            Self::Tessellated {
                chord_deviation_metres: self.deviation_metres() + other.deviation_metres(),
            }
        }
    }
}

/// An object's axis-aligned extent, for broad-phase candidate search.
#[derive(Clone, Debug, PartialEq)]
pub struct ObjectBounds {
    object: ObjectId,
    bounds: Bounds3,
    fidelity: GeometryFidelity,
}

impl ObjectBounds {
    pub fn try_new(
        object: ObjectId,
        bounds: Bounds3,
        fidelity: GeometryFidelity,
    ) -> Result<Self, ProximityError> {
        // Re-validate: `Tessellated` is constructible directly.
        let deviation = fidelity.deviation_metres();
        if !deviation.is_finite() || deviation < 0.0 {
            return Err(ProximityError::InvalidMeasurement);
        }
        Ok(Self {
            object,
            bounds,
            fidelity,
        })
    }
    pub fn object(&self) -> &ObjectId {
        &self.object
    }
    /// The extent of the measured mesh.
    pub fn bounds(&self) -> Bounds3 {
        self.bounds
    }
    pub fn fidelity(&self) -> GeometryFidelity {
        self.fidelity
    }
    /// A box guaranteed to enclose the true body, mesh extent grown by the
    /// chord deviation. A tessellated cylinder's true surface bulges past its
    /// mesh, so the mesh box alone could discard a pair that really clashes.
    pub fn enclosing(&self) -> Bounds3 {
        self.bounds.expanded(self.fidelity.deviation_metres())
    }
}

/// The direction in which a distance between two bodies is measured.
///
/// No projection's distance bounds another's from below, so the broad phase
/// prunes each by its own box gap ([`crate::projected_candidate_pairs`]).
#[derive(Clone, Copy, Debug)]
pub enum ProximityProjection {
    /// Shortest distance between the two surfaces in space.
    Minimum3d,
    /// Plan distance between the two footprints: zero when they meet in plan.
    Horizontal,
    /// Gap between the two bodies' vertical extents (bottom to top), for
    /// bodies above or below one another. The bodies are related when their
    /// footprints overlap with positive area or, with a positive
    /// `footprint_offset_metres`, when the counterpart's footprint comes
    /// closer than the offset to the subject's (the subject's footprint grown
    /// by the offset), and when the counterpart lies in `direction` from the
    /// subject. Unrelated bodies have no distance in this projection.
    ///
    /// `surfaces` other than [`VerticalSurfaces::Extents`] measure between
    /// two chosen surfaces instead (see [`VerticalSurfaces`]).
    Vertical {
        footprint_offset_metres: f64,
        direction: VerticalDirection,
        surfaces: VerticalSurfaces,
    },
    /// Whether the footprints overlap with positive area: distance zero when
    /// they do, none when they do not.
    PlanOverlap,
}

/// Where the counterpart of a [`ProximityProjection::Vertical`] distance must
/// lie relative to the subject.
///
/// Compare the two vertical extents (bottom to top) end by end. A counterpart
/// lies **above** the subject unless it lies lower at both ends (its top
/// below the subject's top and its bottom below the subject's bottom), and
/// **below** unless it lies higher at both ends. A counterpart overlapping
/// the subject in height is therefore above, below or both at distance zero:
/// a pendant reaching down past a sprinkler's top is above it, a riser
/// passing the sprinkler is both. Every counterpart is above or below, so the
/// `Either` distance is the lesser of the two.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum VerticalDirection {
    /// Above or below: the gap between the two extents.
    Either,
    /// The counterpart lies above: the gap from the subject's top up to the
    /// counterpart's bottom, zero when the extents overlap.
    Above,
    /// The counterpart lies below: the gap from the subject's bottom down to
    /// the counterpart's top, zero when the extents overlap.
    Below,
}

/// Which surfaces a [`ProximityProjection::Vertical`] distance runs between.
///
/// A subject surface is a level: the subject's highest point (`Top`) or its
/// lowest (`Bottom`). A counterpart's `Top` and `Bottom` are levels too, and
/// the distance is the difference of the two levels in `direction`: a
/// counterpart level on the other side of the subject's is unrelated
/// (`Either` takes the absolute difference); the footprints must be related
/// as for [`Self::Extents`]. `Nearest` is the counterpart's surface directly
/// over or under the subject's footprint (the plan part of it overlapping
/// the footprint with positive area) nearest to the subject's level in
/// `direction`: a sprinkler's top to the underside of a sloped slab right
/// above it, not to the slab's lowest point elsewhere. A counterpart with no
/// such surface in that direction is unrelated. `Nearest` needs a footprint
/// offset of zero.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum VerticalSurfaces {
    /// The gap between the two vertical extents, zero when they overlap.
    #[default]
    Extents,
    /// From a level of the subject to a surface of the counterpart.
    Between {
        subject: SubjectSurface,
        counterpart: CounterpartSurface,
    },
}

/// The subject's level a [`VerticalSurfaces::Between`] distance starts at.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum SubjectSurface {
    Top,
    Bottom,
}

/// The counterpart's surface a [`VerticalSurfaces::Between`] distance ends at.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum CounterpartSurface {
    Top,
    Bottom,
    /// The nearest surface overlapping the subject's footprint in plan.
    Nearest,
}

impl SubjectSurface {
    /// The surface's spelling in rule parameters, evidence and messages.
    pub fn name(self) -> &'static str {
        match self {
            Self::Top => "top",
            Self::Bottom => "bottom",
        }
    }
}

impl CounterpartSurface {
    /// The surface's spelling in rule parameters, evidence and messages.
    pub fn name(self) -> &'static str {
        match self {
            Self::Top => "top",
            Self::Bottom => "bottom",
            Self::Nearest => "nearest",
        }
    }
}

impl VerticalDirection {
    /// The direction's spelling in rule parameters, evidence and messages.
    pub fn name(self) -> &'static str {
        match self {
            Self::Either => "either",
            Self::Above => "above",
            Self::Below => "below",
        }
    }
}

impl ProximityProjection {
    /// Whether the projection's offset is finite and non-negative.
    fn is_valid(&self) -> bool {
        match self {
            Self::Vertical {
                footprint_offset_metres,
                surfaces,
                ..
            } => {
                let nearest = matches!(
                    surfaces,
                    VerticalSurfaces::Between {
                        counterpart: CounterpartSurface::Nearest,
                        ..
                    }
                );
                footprint_offset_metres.is_finite()
                    && *footprint_offset_metres >= 0.0
                    && !(nearest && *footprint_offset_metres > 0.0)
            }
            _ => true,
        }
    }
    /// Whether a pair may have no distance at all in this projection.
    pub fn may_be_unrelated(&self) -> bool {
        matches!(self, Self::Vertical { .. } | Self::PlanOverlap)
    }
    /// The projection's spelling in evidence locators and messages.
    pub fn name(&self) -> &'static str {
        match self {
            Self::Minimum3d => "minimum_3d",
            Self::Horizontal => "horizontal",
            Self::Vertical { .. } => "vertical",
            Self::PlanOverlap => "plan_overlap",
        }
    }
    fn key(&self) -> (u8, f64, VerticalDirection, VerticalSurfaces) {
        let none = (VerticalDirection::Either, VerticalSurfaces::Extents);
        match self {
            Self::Minimum3d => (0, 0.0, none.0, none.1),
            Self::Horizontal => (1, 0.0, none.0, none.1),
            Self::Vertical {
                footprint_offset_metres,
                direction,
                surfaces,
            } => (2, *footprint_offset_metres, *direction, *surfaces),
            Self::PlanOverlap => (3, 0.0, none.0, none.1),
        }
    }
}

impl PartialEq for ProximityProjection {
    fn eq(&self, other: &Self) -> bool {
        self.cmp(other) == std::cmp::Ordering::Equal
    }
}
impl Eq for ProximityProjection {}
impl PartialOrd for ProximityProjection {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl Ord for ProximityProjection {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        let (a, a_offset, a_direction, a_surfaces) = self.key();
        let (b, b_offset, b_direction, b_surfaces) = other.key();
        a.cmp(&b)
            .then_with(|| a_offset.total_cmp(&b_offset))
            .then_with(|| a_direction.cmp(&b_direction))
            .then_with(|| a_surfaces.cmp(&b_surfaces))
    }
}

/// A request to measure the proximity of two distinct objects.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct ProximityRequest {
    subject: ObjectId,
    counterpart: ObjectId,
    projection: ProximityProjection,
}

impl ProximityRequest {
    /// A request in space ([`ProximityProjection::Minimum3d`]).
    pub fn try_new(subject: ObjectId, counterpart: ObjectId) -> Result<Self, ProximityError> {
        Self::projected(subject, counterpart, ProximityProjection::Minimum3d)
    }
    /// A request measured in `projection`; a vertical offset must be finite
    /// and non-negative.
    pub fn projected(
        subject: ObjectId,
        counterpart: ObjectId,
        projection: ProximityProjection,
    ) -> Result<Self, ProximityError> {
        if subject == counterpart {
            return Err(ProximityError::SameObject);
        }
        if !projection.is_valid() {
            return Err(ProximityError::InvalidMeasurement);
        }
        Ok(Self {
            subject,
            counterpart,
            projection,
        })
    }
    pub fn subject(&self) -> &ObjectId {
        &self.subject
    }
    pub fn counterpart(&self) -> &ObjectId {
        &self.counterpart
    }
    pub fn projection(&self) -> ProximityProjection {
        self.projection
    }
}

/// How far the intersection of two bodies reaches along each world axis.
///
/// Each axis carries a [`LengthInterval`]: the extent of the intersection's
/// axis-aligned box along it. The lower bound is witnessed (points found in
/// both bodies), the upper bound proven (the bodies' boxes overlap no
/// further), so exact geometry need not report a point. An empty
/// intersection has zero extent on every axis.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct OverlapExtents {
    axes: [LengthInterval; 3],
}

impl OverlapExtents {
    /// The extents along x, y and z.
    #[must_use]
    pub fn new(x: LengthInterval, y: LengthInterval, z: LengthInterval) -> Self {
        Self { axes: [x, y, z] }
    }
    pub fn x(&self) -> LengthInterval {
        self.axes[0]
    }
    pub fn y(&self) -> LengthInterval {
        self.axes[1]
    }
    pub fn z(&self) -> LengthInterval {
        self.axes[2]
    }
    /// The lesser of the x and y extents: how far the intersection reaches in
    /// plan along its narrower axis.
    pub fn horizontal(&self) -> LengthInterval {
        let (x, y) = (self.axes[0], self.axes[1]);
        LengthInterval::try_new(
            x.lower_metres().min(y.lower_metres()),
            x.upper_metres().min(y.upper_metres()),
        )
        .unwrap_or_else(|_| unreachable!("the lesser of two intervals is an interval"))
    }
    /// The z extent.
    pub fn vertical(&self) -> LengthInterval {
        self.axes[2]
    }
    fn is_empty(&self) -> bool {
        self.axes.iter().all(|axis| axis.lower_metres() == 0.0)
    }
}

/// A request for the extents of two bodies' intersection along stated
/// directions, such as each body's own placement axes.
#[derive(Clone, Debug, PartialEq)]
pub struct OverlapAlongRequest {
    subject: ObjectId,
    counterpart: ObjectId,
    directions: Vec<MetricDirection>,
}

impl OverlapAlongRequest {
    /// The most directions one request may name: two bodies' three axes.
    pub const MAX_DIRECTIONS: usize = 6;

    /// Refuses one object measured against itself, and no directions or
    /// more than [`Self::MAX_DIRECTIONS`].
    pub fn try_new(
        subject: ObjectId,
        counterpart: ObjectId,
        directions: Vec<MetricDirection>,
    ) -> Result<Self, ProximityError> {
        if subject == counterpart {
            return Err(ProximityError::SameObject);
        }
        if directions.is_empty() || directions.len() > Self::MAX_DIRECTIONS {
            return Err(ProximityError::InvalidMeasurement);
        }
        Ok(Self {
            subject,
            counterpart,
            directions,
        })
    }
    pub fn subject(&self) -> &ObjectId {
        &self.subject
    }
    pub fn counterpart(&self) -> &ObjectId {
        &self.counterpart
    }
    /// The unit directions to measure along, in request order.
    pub fn directions(&self) -> &[MetricDirection] {
        &self.directions
    }
}

/// How far two bodies' intersection reaches along each direction of an
/// [`OverlapAlongRequest`].
///
/// Each extent is a [`LengthInterval`] as for [`OverlapExtents`]: its lower
/// bound witnessed (points found in both bodies), its upper bound proven
/// (the bodies' own extents along the direction overlap no further). An
/// empty intersection has zero extent along every direction. The evidence
/// is exact exactly when the geometry is.
#[derive(Clone, Debug, PartialEq)]
pub struct OverlapAlongEvidence {
    request: OverlapAlongRequest,
    extents: Vec<LengthInterval>,
    fidelity: GeometryFidelity,
    evidence: Evidence,
}

impl OverlapAlongEvidence {
    /// Refuses one extent too many or too few, and evidence whose
    /// exactness does not match the geometry.
    pub fn try_new(
        request: OverlapAlongRequest,
        extents: Vec<LengthInterval>,
        fidelity: GeometryFidelity,
        evidence: Evidence,
    ) -> Result<Self, ProximityError> {
        if extents.len() != request.directions.len() {
            return Err(ProximityError::InvalidMeasurement);
        }
        if evidence.exact != fidelity.is_exact() || evidence.locator.trim().is_empty() {
            return Err(ProximityError::EvidenceFidelityMismatch);
        }
        Ok(Self {
            request,
            extents,
            fidelity,
            evidence,
        })
    }
    pub fn request(&self) -> &OverlapAlongRequest {
        &self.request
    }
    /// The extent along each requested direction, in request order.
    pub fn extents(&self) -> &[LengthInterval] {
        &self.extents
    }
    pub fn fidelity(&self) -> GeometryFidelity {
        self.fidelity
    }
    pub fn evidence(&self) -> &Evidence {
        &self.evidence
    }
}

/// One body lying wholly inside the other without their surfaces meeting.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BodyContainment {
    SubjectInsideCounterpart,
    CounterpartInsideSubject,
}

/// Bounds on a volume in cubic metres: finite, non-negative, and sure to
/// contain the true value.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct VolumeInterval {
    lower_cubic_metres: f64,
    upper_cubic_metres: f64,
}

impl VolumeInterval {
    /// Validates inclusive lower and upper bounds.
    pub fn try_new(
        lower_cubic_metres: f64,
        upper_cubic_metres: f64,
    ) -> Result<Self, ProximityError> {
        let valid = |value: f64| value.is_finite() && value >= 0.0;
        if !valid(lower_cubic_metres)
            || !valid(upper_cubic_metres)
            || lower_cubic_metres > upper_cubic_metres
        {
            return Err(ProximityError::InvalidMeasurement);
        }
        Ok(Self {
            lower_cubic_metres,
            upper_cubic_metres,
        })
    }
    /// A volume known exactly.
    pub fn exact(cubic_metres: f64) -> Result<Self, ProximityError> {
        Self::try_new(cubic_metres, cubic_metres)
    }
    pub fn lower_cubic_metres(&self) -> f64 {
        self.lower_cubic_metres
    }
    pub fn upper_cubic_metres(&self) -> f64 {
        self.upper_cubic_metres
    }
    /// Whether the interval proves one value.
    #[allow(clippy::float_cmp)]
    pub fn is_exact(&self) -> bool {
        self.lower_cubic_metres == self.upper_cubic_metres
    }
    /// `(lower, upper)` bounds on this volume's share of `whole`, for a
    /// part that lies within the whole: outward rounded and clamped to
    /// `[0, 1]`, so the true share always lies inside.
    pub fn share_of(self, whole: Self) -> (f64, f64) {
        let lower = if whole.upper_cubic_metres > 0.0 {
            (self.lower_cubic_metres / whole.upper_cubic_metres).next_down()
        } else {
            0.0
        };
        let upper = if whole.lower_cubic_metres > 0.0 {
            (self.upper_cubic_metres / whole.lower_cubic_metres).next_up()
        } else {
            1.0
        };
        let upper = upper.clamp(0.0, 1.0);
        (lower.clamp(0.0, upper), upper)
    }
}

/// The volume two closed bodies share, with each body's own volume.
///
/// Every value is a certified [`VolumeInterval`]. The shared volume cannot
/// exceed either body's, so bounds claiming it must are refused.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct IntersectionVolume {
    shared: VolumeInterval,
    subject: VolumeInterval,
    counterpart: VolumeInterval,
}

impl IntersectionVolume {
    /// The shared volume and the volumes of the request's subject and
    /// counterpart.
    pub fn try_new(
        shared: VolumeInterval,
        subject: VolumeInterval,
        counterpart: VolumeInterval,
    ) -> Result<Self, ProximityError> {
        let most = subject
            .upper_cubic_metres
            .min(counterpart.upper_cubic_metres);
        if shared.lower_cubic_metres > most {
            return Err(ProximityError::InvalidMeasurement);
        }
        Ok(Self {
            shared,
            subject,
            counterpart,
        })
    }
    /// The volume both bodies occupy.
    pub fn shared(&self) -> VolumeInterval {
        self.shared
    }
    /// The subject's own volume.
    pub fn subject(&self) -> VolumeInterval {
        self.subject
    }
    /// The counterpart's own volume.
    pub fn counterpart(&self) -> VolumeInterval {
        self.counterpart
    }
    /// The volume of the smaller body: the lesser of the two volumes.
    pub fn smaller(&self) -> VolumeInterval {
        VolumeInterval {
            lower_cubic_metres: self
                .subject
                .lower_cubic_metres
                .min(self.counterpart.lower_cubic_metres),
            upper_cubic_metres: self
                .subject
                .upper_cubic_metres
                .min(self.counterpart.upper_cubic_metres),
        }
    }
    /// `(lower, upper)` bounds on the shared volume's share of the smaller
    /// body, between zero and one: one when one body lies wholly in the
    /// other. Rounded outward, so the true ratio always lies inside.
    pub fn ratio_of_smaller(&self) -> (f64, f64) {
        self.shared.share_of(self.smaller())
    }
}

/// The certified volume one closed body encloses.
///
/// A tessellated body's volume is widened by the band its chord deviation
/// allows, so the interval always holds the true volume; only an exact mesh
/// may carry exact evidence.
#[derive(Clone, Debug, PartialEq)]
pub struct BodyVolume {
    object: ObjectId,
    volume: VolumeInterval,
    fidelity: GeometryFidelity,
    evidence: Evidence,
}

impl BodyVolume {
    /// The volume of `object`. Exact evidence needs exact geometry, and
    /// every piece of evidence needs a reviewable locator.
    pub fn try_new(
        object: ObjectId,
        volume: VolumeInterval,
        fidelity: GeometryFidelity,
        evidence: Evidence,
    ) -> Result<Self, ProximityError> {
        if evidence.exact && !fidelity.is_exact() || evidence.locator.trim().is_empty() {
            return Err(ProximityError::EvidenceFidelityMismatch);
        }
        Ok(Self {
            object,
            volume,
            fidelity,
            evidence,
        })
    }
    /// The measured object.
    pub fn object(&self) -> &ObjectId {
        &self.object
    }
    /// Bounds on the enclosed volume.
    pub fn volume(&self) -> VolumeInterval {
        self.volume
    }
    pub fn fidelity(&self) -> GeometryFidelity {
        self.fidelity
    }
    pub fn evidence(&self) -> &Evidence {
        &self.evidence
    }
}

/// How close two bodies come and how far they overlap.
#[derive(Clone, Debug, PartialEq)]
pub struct ProximityEvidence {
    request: ProximityRequest,
    separation_metres: f64,
    penetration_metres: Option<f64>,
    plan_overlap_square_metres: f64,
    containment: Option<BodyContainment>,
    overlap_extents: Option<OverlapExtents>,
    hausdorff: Option<LengthInterval>,
    volume: Option<IntersectionVolume>,
    fidelity: GeometryFidelity,
    evidence: Evidence,
}

impl ProximityEvidence {
    /// Rejects incoherent measurements and evidence whose exactness does not
    /// match the geometry it was measured on.
    ///
    /// - `separation_metres`: shortest distance between the two surfaces.
    /// - `penetration_metres`: depth of the deepest witnessed point of either
    ///   body inside the other; `None` when neither body is a closed solid.
    /// - `plan_overlap_square_metres`: area of the two footprints' overlap.
    pub fn try_new(
        request: ProximityRequest,
        separation_metres: f64,
        penetration_metres: Option<f64>,
        plan_overlap_square_metres: f64,
        containment: Option<BodyContainment>,
        fidelity: GeometryFidelity,
        evidence: Evidence,
    ) -> Result<Self, ProximityError> {
        let finite_non_negative = |v: f64| v.is_finite() && v >= 0.0;
        if !finite_non_negative(separation_metres)
            || !finite_non_negative(plan_overlap_square_metres)
            || penetration_metres.is_some_and(|depth| !finite_non_negative(depth))
            || !finite_non_negative(fidelity.deviation_metres())
        {
            return Err(ProximityError::InvalidMeasurement);
        }
        // Disjoint bodies cannot share volume. BodyContainment is the one way to be
        // apart at the surface and overlapping in volume, and it needs an
        // inside, so it cannot be claimed without a penetration measurement.
        let separated = separation_metres > 0.0;
        if (separated && containment.is_none() && penetration_metres.is_some_and(|d| d > 0.0))
            || (containment.is_some() && (!separated || penetration_metres.is_none()))
        {
            return Err(ProximityError::InvalidMeasurement);
        }
        if evidence.exact != fidelity.is_exact() || evidence.locator.trim().is_empty() {
            return Err(ProximityError::EvidenceFidelityMismatch);
        }
        // Penetration and containment are questions in space.
        if request.projection() != ProximityProjection::Minimum3d {
            return Err(ProximityError::UnsupportedProjection);
        }
        Ok(Self {
            request,
            separation_metres,
            penetration_metres,
            plan_overlap_square_metres,
            containment,
            overlap_extents: None,
            hausdorff: None,
            volume: None,
            fidelity,
            evidence,
        })
    }

    /// Adds the extents of the bodies' intersection along each axis.
    ///
    /// Refused when no penetration was measured (two open surfaces share no
    /// volume), and when bodies apart at the surface and not contained in
    /// one another claim a non-empty intersection.
    pub fn with_overlap_extents(mut self, extents: OverlapExtents) -> Result<Self, ProximityError> {
        let disjoint = self.separation_metres > 0.0 && self.containment.is_none();
        if self.penetration_metres.is_none() || (disjoint && !extents.is_empty()) {
            return Err(ProximityError::InvalidMeasurement);
        }
        self.overlap_extents = Some(extents);
        Ok(self)
    }

    /// Adds the Hausdorff distance between the two surfaces: the farthest
    /// any point of either surface lies from the other surface.
    ///
    /// It is never smaller than the separation, so an interval lying wholly
    /// below the separation's own interval is refused.
    pub fn with_hausdorff(mut self, interval: LengthInterval) -> Result<Self, ProximityError> {
        if interval.upper_metres() < self.separation_interval_metres().0 {
            return Err(ProximityError::InvalidMeasurement);
        }
        self.hausdorff = Some(interval);
        Ok(self)
    }

    /// Adds the certified volume the two bodies share, with their own
    /// volumes.
    ///
    /// Refused when no penetration was measured (open surfaces enclose no
    /// volume), when bodies apart at the surface and not contained in one
    /// another claim a shared volume, and when a body said to lie inside
    /// the other cannot share its whole volume with it.
    pub fn with_intersection_volume(
        mut self,
        volume: IntersectionVolume,
    ) -> Result<Self, ProximityError> {
        let disjoint = self.separation_metres > 0.0 && self.containment.is_none();
        let shared = volume.shared();
        let whole = |inner: VolumeInterval| {
            shared.upper_cubic_metres >= inner.lower_cubic_metres
                && shared.lower_cubic_metres <= inner.upper_cubic_metres
        };
        let contained = match self.containment {
            Some(BodyContainment::SubjectInsideCounterpart) => whole(volume.subject()),
            Some(BodyContainment::CounterpartInsideSubject) => whole(volume.counterpart()),
            None => true,
        };
        if self.penetration_metres.is_none()
            || (disjoint && shared.lower_cubic_metres > 0.0)
            || !contained
        {
            return Err(ProximityError::InvalidMeasurement);
        }
        self.volume = Some(volume);
        Ok(self)
    }

    pub fn request(&self) -> &ProximityRequest {
        &self.request
    }
    /// Shortest distance between the measured surfaces.
    pub fn separation_metres(&self) -> f64 {
        self.separation_metres
    }
    /// The separation the true surfaces may have, given the fidelity.
    ///
    /// `(lower, upper)`; both equal the measured separation for exact geometry.
    pub fn separation_interval_metres(&self) -> (f64, f64) {
        let deviation = self.fidelity.deviation_metres();
        (
            (self.separation_metres - deviation).max(0.0),
            self.separation_metres + deviation,
        )
    }
    /// Witnessed interpenetration depth, a lower bound on the true depth.
    pub fn penetration_metres(&self) -> Option<f64> {
        self.penetration_metres
    }
    pub fn plan_overlap_square_metres(&self) -> f64 {
        self.plan_overlap_square_metres
    }
    pub fn containment(&self) -> Option<BodyContainment> {
        self.containment
    }
    /// Extents of the intersection along each axis; `None` when the service
    /// did not measure them or neither body is a closed solid.
    pub fn overlap_extents(&self) -> Option<OverlapExtents> {
        self.overlap_extents
    }
    /// Hausdorff distance between the two surfaces; `None` when the service
    /// did not measure it. Zero exactly when the surfaces coincide, so it is
    /// what tells a duplicate from a mere overlap.
    pub fn hausdorff_interval_metres(&self) -> Option<LengthInterval> {
        self.hausdorff
    }
    /// The certified volume the bodies share and their own volumes; `None`
    /// when the service did not measure it or a body is not a closed solid.
    pub fn intersection_volume(&self) -> Option<IntersectionVolume> {
        self.volume
    }
    pub fn fidelity(&self) -> GeometryFidelity {
        self.fidelity
    }
    pub fn evidence(&self) -> &Evidence {
        &self.evidence
    }
}

/// The distance between two bodies in a request's projection, as an interval.
///
/// `(lower, upper)` in metres, both equal for exact geometry. An upper bound
/// of infinity says the bodies may be unrelated in the projection (not above
/// one another, not overlapping in plan); a lower bound of infinity says they
/// are. Only [`ProximityProjection::may_be_unrelated`] projections may report
/// an infinite bound, and exact evidence is a point: whether exact bodies are
/// related is decided, never left open.
#[derive(Clone, Debug, PartialEq)]
pub struct ProjectedDistanceEvidence {
    request: ProximityRequest,
    lower_metres: f64,
    upper_metres: f64,
    fidelity: GeometryFidelity,
    evidence: Evidence,
}

impl ProjectedDistanceEvidence {
    /// Rejects incoherent intervals and evidence whose exactness does not
    /// match the geometry it was measured on.
    pub fn try_new(
        request: ProximityRequest,
        lower_metres: f64,
        upper_metres: f64,
        fidelity: GeometryFidelity,
        evidence: Evidence,
    ) -> Result<Self, ProximityError> {
        let deviation = fidelity.deviation_metres();
        let unbounded_allowed = request.projection().may_be_unrelated();
        let bound_ok = |value: f64| {
            value >= 0.0 && (value.is_finite() || (unbounded_allowed && value == f64::INFINITY))
        };
        if !bound_ok(lower_metres)
            || !bound_ok(upper_metres)
            || lower_metres > upper_metres
            || !deviation.is_finite()
            || deviation < 0.0
            || (fidelity.is_exact() && lower_metres < upper_metres)
        {
            return Err(ProximityError::InvalidMeasurement);
        }
        if evidence.exact != fidelity.is_exact() || evidence.locator.trim().is_empty() {
            return Err(ProximityError::EvidenceFidelityMismatch);
        }
        Ok(Self {
            request,
            lower_metres,
            upper_metres,
            fidelity,
            evidence,
        })
    }

    /// The distance interval of a measurement in space.
    pub fn from_proximity(measured: &ProximityEvidence) -> Result<Self, ProximityError> {
        let (lower, upper) = measured.separation_interval_metres();
        Self::try_new(
            measured.request().clone(),
            lower,
            upper,
            measured.fidelity(),
            measured.evidence().clone(),
        )
    }

    pub fn request(&self) -> &ProximityRequest {
        &self.request
    }
    /// `(lower, upper)` bounds on the true distance; infinite when unrelated.
    pub fn interval_metres(&self) -> (f64, f64) {
        (self.lower_metres, self.upper_metres)
    }
    pub fn fidelity(&self) -> GeometryFidelity {
        self.fidelity
    }
    pub fn evidence(&self) -> &Evidence {
        &self.evidence
    }
}

/// A request for the plan distance from a stated convex region to an
/// object's footprint, such as from the floor area a door leaf sweeps to a
/// column.
#[derive(Clone, Debug, PartialEq)]
pub struct RegionDistanceRequest {
    region: ConvexPlanRegion,
    counterpart: ObjectId,
}

impl RegionDistanceRequest {
    pub fn new(region: ConvexPlanRegion, counterpart: ObjectId) -> Self {
        Self {
            region,
            counterpart,
        }
    }
    pub fn region(&self) -> &ConvexPlanRegion {
        &self.region
    }
    pub fn counterpart(&self) -> &ObjectId {
        &self.counterpart
    }
}

/// The plan distance from a region to an object's footprint, as an
/// interval: zero when they meet in plan, a point exactly when the
/// counterpart's geometry is exact.
#[derive(Clone, Debug, PartialEq)]
pub struct RegionDistanceEvidence {
    request: RegionDistanceRequest,
    lower_metres: f64,
    upper_metres: f64,
    fidelity: GeometryFidelity,
    evidence: Evidence,
}

impl RegionDistanceEvidence {
    /// Rejects incoherent intervals, evidence whose exactness does not match
    /// the counterpart's geometry, and evidence from another source than the
    /// counterpart's.
    pub fn try_new(
        request: RegionDistanceRequest,
        lower_metres: f64,
        upper_metres: f64,
        fidelity: GeometryFidelity,
        evidence: Evidence,
    ) -> Result<Self, ProximityError> {
        let bound_ok = |value: f64| value.is_finite() && value >= 0.0;
        if !bound_ok(lower_metres)
            || !bound_ok(upper_metres)
            || lower_metres > upper_metres
            || (fidelity.is_exact() && lower_metres < upper_metres)
        {
            return Err(ProximityError::InvalidMeasurement);
        }
        if evidence.exact != fidelity.is_exact()
            || evidence.locator.trim().is_empty()
            || evidence.source != request.counterpart().source
        {
            return Err(ProximityError::EvidenceFidelityMismatch);
        }
        Ok(Self {
            request,
            lower_metres,
            upper_metres,
            fidelity,
            evidence,
        })
    }
    pub fn request(&self) -> &RegionDistanceRequest {
        &self.request
    }
    /// `(lower, upper)` bounds on the true plan distance.
    pub fn interval_metres(&self) -> (f64, f64) {
        (self.lower_metres, self.upper_metres)
    }
    pub fn fidelity(&self) -> GeometryFidelity {
        self.fidelity
    }
    pub fn evidence(&self) -> &Evidence {
        &self.evidence
    }
}

/// Which faces of a body a [`FaceDistanceRequest`] measures to, by the
/// direction of their outward normal.
///
/// A face is **top** when its outward normal points upwards within 45° of
/// vertical (its z component is at least √½), **bottom** when it points
/// downwards within 45°, and a **side** face otherwise. `Any` takes every
/// face.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum FaceClass {
    Top,
    Side,
    Bottom,
    Any,
}

impl FaceClass {
    /// The class's spelling in rule parameters, evidence and messages.
    pub fn name(self) -> &'static str {
        match self {
            Self::Top => "top",
            Self::Side => "side",
            Self::Bottom => "bottom",
            Self::Any => "any",
        }
    }
    /// Parses [`Self::name`].
    pub fn parse(name: &str) -> Option<Self> {
        [Self::Top, Self::Side, Self::Bottom, Self::Any]
            .into_iter()
            .find(|class| class.name() == name)
    }
}

/// Why a face distance could not be measured.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum FaceDistanceError {
    /// The service does not measure face distances.
    #[error("face distances are not measured by this service")]
    Unsupported,
    /// The adapter holds no measurable geometry for an object.
    #[error("face distance is unavailable for the requested object")]
    Unavailable,
    /// An object is declared to occupy no material.
    #[error("the requested object occupies no material")]
    NoBody,
    /// The host is not a closed solid, so it has no inside and no outward
    /// normals.
    #[error("the host body is not a closed solid")]
    NotClosed,
    /// The host has no face of the requested class.
    #[error("the host body has no face of the requested class")]
    NoFaces,
    /// The host is a tessellation: its chords do not state the true faces'
    /// normals, so no face class can be read from them.
    #[error("the host body is tessellated, so its face classes are unknown")]
    InexactHost,
    /// A face of the host lies at the 45° boundary between two classes
    /// within rounding, so which class it belongs to is undecided.
    #[error("a face of the host lies on the boundary between two face classes")]
    AmbiguousFace,
    /// Coordinates or measured quantities are non-finite or incoherent.
    #[error("face distance is not finite and coherent")]
    InvalidMeasurement,
    /// The evidence's exactness disagrees with the measured geometry's fidelity.
    #[error("face distance evidence exactness must match geometry fidelity and be reviewable")]
    EvidenceFidelityMismatch,
    /// A body cannot be measured against its own faces.
    #[error("the face distance of an object to itself is undefined")]
    SameObject,
}

/// A request for the signed distance from one body to one class of another
/// body's faces.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct FaceDistanceRequest {
    body: ObjectId,
    host: ObjectId,
    faces: FaceClass,
}

impl FaceDistanceRequest {
    /// The distance from `body` to the `faces` of `host`.
    pub fn try_new(
        body: ObjectId,
        host: ObjectId,
        faces: FaceClass,
    ) -> Result<Self, FaceDistanceError> {
        if body == host {
            return Err(FaceDistanceError::SameObject);
        }
        Ok(Self { body, host, faces })
    }
    /// The body measured from.
    pub fn body(&self) -> &ObjectId {
        &self.body
    }
    /// The body whose faces are measured to.
    pub fn host(&self) -> &ObjectId {
        &self.host
    }
    pub fn faces(&self) -> FaceClass {
        self.faces
    }
}

/// The signed distance from a body to a class of a host body's faces.
///
/// With `F` the host's faces of the class, each point `p` of the body has
/// the signed distance `+d(p, F)` when it lies in the host (boundary
/// included) and `-d(p, F)` when it lies outside. The body's distance is the
/// least over its points:
///
/// - **positive**: the whole body lies in the host, that far from the faces
///   (a cover);
/// - **negative**: part of the body lies outside the host, the farthest of
///   it that far from the faces (a protrusion);
/// - **zero**: the body reaches the faces.
///
/// It is a [`SignedDistanceInterval`] sure to contain the true value, a
/// point only when the measurement proves one.
#[derive(Clone, Debug, PartialEq)]
pub struct FaceDistanceEvidence {
    request: FaceDistanceRequest,
    signed: SignedDistanceInterval,
    fidelity: GeometryFidelity,
    evidence: Evidence,
}

impl FaceDistanceEvidence {
    /// Rejects evidence whose exactness does not match the geometry it was
    /// measured on.
    pub fn try_new(
        request: FaceDistanceRequest,
        signed: SignedDistanceInterval,
        fidelity: GeometryFidelity,
        evidence: Evidence,
    ) -> Result<Self, FaceDistanceError> {
        let deviation = fidelity.deviation_metres();
        if !deviation.is_finite() || deviation < 0.0 {
            return Err(FaceDistanceError::InvalidMeasurement);
        }
        if evidence.exact != fidelity.is_exact() || evidence.locator.trim().is_empty() {
            return Err(FaceDistanceError::EvidenceFidelityMismatch);
        }
        Ok(Self {
            request,
            signed,
            fidelity,
            evidence,
        })
    }
    pub fn request(&self) -> &FaceDistanceRequest {
        &self.request
    }
    /// Bounds on the signed distance: positive inside the host, negative
    /// outside.
    pub fn signed(&self) -> SignedDistanceInterval {
        self.signed
    }
    pub fn fidelity(&self) -> GeometryFidelity {
        self.fidelity
    }
    pub fn evidence(&self) -> &Evidence {
        &self.evidence
    }
}

/// Measures extents and pairwise proximity of model objects.
///
/// ADR 0004: every method returns a measurement. None decides a clash.
pub trait ProximityService: Send + Sync + 'static {
    /// The extent of one object's measured geometry.
    fn bounds(&self, object: &ObjectId) -> Result<ObjectBounds, ProximityError>;
    /// How close two objects come and how far they overlap, in space.
    ///
    /// A request in any other projection is refused with
    /// [`ProximityError::UnsupportedProjection`].
    fn measure_proximity(
        &self,
        request: &ProximityRequest,
    ) -> Result<ProximityEvidence, ProximityError>;
    /// The distance between two objects in the request's projection.
    ///
    /// The default answers [`ProximityProjection::Minimum3d`] from
    /// [`Self::measure_proximity`] and refuses every other projection, so a
    /// service that does not measure projections fails closed.
    fn measure_distance(
        &self,
        request: &ProximityRequest,
    ) -> Result<ProjectedDistanceEvidence, ProximityError> {
        match request.projection() {
            ProximityProjection::Minimum3d => {
                ProjectedDistanceEvidence::from_proximity(&self.measure_proximity(request)?)
            }
            _ => Err(ProximityError::UnsupportedProjection),
        }
    }
    /// The signed distance from one body to a class of another's faces.
    ///
    /// The default refuses with [`FaceDistanceError::Unsupported`], so a
    /// service that does not measure face distances fails closed.
    fn measure_face_distance(
        &self,
        request: &FaceDistanceRequest,
    ) -> Result<FaceDistanceEvidence, FaceDistanceError> {
        let _ = request;
        Err(FaceDistanceError::Unsupported)
    }
    /// The plan distance from a stated region to an object's footprint.
    ///
    /// The default refuses with [`ProximityError::UnsupportedProjection`],
    /// so a service that does not measure regions fails closed.
    fn measure_region_distance(
        &self,
        request: &RegionDistanceRequest,
    ) -> Result<RegionDistanceEvidence, ProximityError> {
        let _ = request;
        Err(ProximityError::UnsupportedProjection)
    }
    /// The extents of two bodies' intersection along stated directions.
    ///
    /// The default refuses with [`ProximityError::UnsupportedProjection`],
    /// so a service that does not measure them fails closed.
    fn measure_overlap_along(
        &self,
        request: &OverlapAlongRequest,
    ) -> Result<OverlapAlongEvidence, ProximityError> {
        let _ = request;
        Err(ProximityError::UnsupportedProjection)
    }

    /// The volume one closed body encloses.
    ///
    /// The default refuses with [`ProximityError::Unavailable`], so a
    /// service that does not measure volumes fails closed.
    fn measure_body_volume(&self, object: &ObjectId) -> Result<BodyVolume, ProximityError> {
        let _ = object;
        Err(ProximityError::Unavailable)
    }
}

/// Registry handle for a [`ProximityService`].
#[derive(Clone)]
pub struct ProximityServiceHandle(Arc<dyn ProximityService>);

impl ProximityServiceHandle {
    pub fn new(service: Arc<dyn ProximityService>) -> Self {
        Self(service)
    }
    pub fn bounds(&self, object: &ObjectId) -> Result<ObjectBounds, ProximityError> {
        self.0.bounds(object)
    }
    pub fn measure_proximity(
        &self,
        request: &ProximityRequest,
    ) -> Result<ProximityEvidence, ProximityError> {
        self.0.measure_proximity(request)
    }
    /// The distance in the request's projection. Evidence answering another
    /// request, projection included, is refused.
    pub fn measure_distance(
        &self,
        request: &ProximityRequest,
    ) -> Result<ProjectedDistanceEvidence, ProximityError> {
        let measured = self.0.measure_distance(request)?;
        if measured.request() != request {
            return Err(ProximityError::InvalidMeasurement);
        }
        Ok(measured)
    }
    /// The signed face distance. Evidence answering another request is
    /// refused.
    pub fn measure_face_distance(
        &self,
        request: &FaceDistanceRequest,
    ) -> Result<FaceDistanceEvidence, FaceDistanceError> {
        let measured = self.0.measure_face_distance(request)?;
        if measured.request() != request {
            return Err(FaceDistanceError::InvalidMeasurement);
        }
        Ok(measured)
    }
    /// The intersection's extents along stated directions. Evidence
    /// answering another request is refused.
    pub fn measure_overlap_along(
        &self,
        request: &OverlapAlongRequest,
    ) -> Result<OverlapAlongEvidence, ProximityError> {
        let measured = self.0.measure_overlap_along(request)?;
        if measured.request() != request {
            return Err(ProximityError::InvalidMeasurement);
        }
        Ok(measured)
    }
    /// The volume `object` encloses. A volume naming another object answers
    /// a different question and is refused.
    pub fn measure_body_volume(&self, object: &ObjectId) -> Result<BodyVolume, ProximityError> {
        let measured = self.0.measure_body_volume(object)?;
        if measured.object() != object {
            return Err(ProximityError::InvalidMeasurement);
        }
        Ok(measured)
    }
    /// The plan distance from a region. Evidence answering another request
    /// is refused.
    pub fn measure_region_distance(
        &self,
        request: &RegionDistanceRequest,
    ) -> Result<RegionDistanceEvidence, ProximityError> {
        let measured = self.0.measure_region_distance(request)?;
        if measured.request() != request {
            return Err(ProximityError::InvalidMeasurement);
        }
        Ok(measured)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axioval_ir::SourceId;

    fn id(local: &str) -> ObjectId {
        ObjectId::new(SourceId::new("cad", "m").unwrap(), local).unwrap()
    }
    fn request() -> ProximityRequest {
        ProximityRequest::try_new(id("pipe"), id("wall")).unwrap()
    }

    /// A service answering one volume whatever it is asked.
    struct OneVolume(BodyVolume);

    #[test]
    fn a_body_volume_keeps_its_exactness_honest_and_names_its_object() {
        let tessellated = GeometryFidelity::Tessellated {
            chord_deviation_metres: 0.01,
        };
        let volume = VolumeInterval::try_new(1.0, 1.1).unwrap();
        assert_eq!(
            BodyVolume::try_new(id("wall"), volume, tessellated, exact()),
            Err(ProximityError::EvidenceFidelityMismatch)
        );
        let measured = BodyVolume::try_new(id("wall"), volume, tessellated, approximate()).unwrap();
        let handle = ProximityServiceHandle::new(Arc::new(OneVolume(measured.clone())));
        assert_eq!(handle.measure_body_volume(&id("wall")), Ok(measured));
        assert_eq!(
            handle.measure_body_volume(&id("pipe")),
            Err(ProximityError::InvalidMeasurement)
        );
    }

    impl ProximityService for OneVolume {
        fn bounds(&self, _: &ObjectId) -> Result<ObjectBounds, ProximityError> {
            Err(ProximityError::Unavailable)
        }
        fn measure_proximity(
            &self,
            _: &ProximityRequest,
        ) -> Result<ProximityEvidence, ProximityError> {
            Err(ProximityError::Unavailable)
        }
        fn measure_body_volume(&self, _: &ObjectId) -> Result<BodyVolume, ProximityError> {
            Ok(self.0.clone())
        }
    }
    fn exact() -> Evidence {
        Evidence::exact(SourceId::new("cad", "m").unwrap(), "proximity:pipe:wall")
    }
    fn approximate() -> Evidence {
        Evidence {
            exact: false,
            ..exact()
        }
    }

    #[test]
    fn an_object_is_not_measured_against_itself() {
        assert_eq!(
            ProximityRequest::try_new(id("pipe"), id("pipe")),
            Err(ProximityError::SameObject)
        );
    }

    /// A tessellation cannot be presented as fact, nor exact geometry as an
    /// estimate: either would misstate what a reviewer can rely on.
    #[test]
    fn evidence_exactness_must_match_fidelity() {
        let tessellated = GeometryFidelity::tessellated(0.002).unwrap();
        assert_eq!(
            ProximityEvidence::try_new(request(), 0.1, Some(0.0), 0.0, None, tessellated, exact()),
            Err(ProximityError::EvidenceFidelityMismatch)
        );
        assert_eq!(
            ProximityEvidence::try_new(
                request(),
                0.1,
                Some(0.0),
                0.0,
                None,
                GeometryFidelity::Exact,
                approximate()
            ),
            Err(ProximityError::EvidenceFidelityMismatch)
        );
        assert!(
            ProximityEvidence::try_new(
                request(),
                0.1,
                Some(0.0),
                0.0,
                None,
                tessellated,
                approximate()
            )
            .is_ok()
        );
    }

    #[test]
    fn separated_bodies_cannot_penetrate_unless_one_contains_the_other() {
        let exact_fidelity = GeometryFidelity::Exact;
        assert_eq!(
            ProximityEvidence::try_new(
                request(),
                0.1,
                Some(0.05),
                0.0,
                None,
                exact_fidelity,
                exact()
            ),
            Err(ProximityError::InvalidMeasurement)
        );
        assert!(
            ProximityEvidence::try_new(
                request(),
                0.1,
                Some(0.05),
                0.0,
                Some(BodyContainment::SubjectInsideCounterpart),
                exact_fidelity,
                exact()
            )
            .is_ok()
        );
        // Touching bodies are not contained in one another.
        assert_eq!(
            ProximityEvidence::try_new(
                request(),
                0.0,
                Some(0.05),
                0.0,
                Some(BodyContainment::SubjectInsideCounterpart),
                exact_fidelity,
                exact()
            ),
            Err(ProximityError::InvalidMeasurement)
        );
    }

    #[test]
    fn tessellated_separation_widens_by_the_combined_deviation() {
        let fidelity = GeometryFidelity::tessellated(0.002)
            .unwrap()
            .combined(GeometryFidelity::tessellated(0.001).unwrap());
        let measured = ProximityEvidence::try_new(
            request(),
            0.01,
            Some(0.0),
            0.0,
            None,
            fidelity,
            approximate(),
        )
        .unwrap();
        let (lower, upper) = measured.separation_interval_metres();
        assert!((lower - 0.007).abs() < 1e-12 && (upper - 0.013).abs() < 1e-12);
    }

    #[test]
    fn a_vertical_offset_must_be_finite_and_non_negative() {
        for offset in [-0.1, f64::NAN, f64::INFINITY] {
            assert_eq!(
                ProximityRequest::projected(
                    id("pipe"),
                    id("wall"),
                    ProximityProjection::Vertical {
                        footprint_offset_metres: offset,
                        direction: VerticalDirection::Either,
                        surfaces: crate::VerticalSurfaces::Extents,
                    }
                ),
                Err(ProximityError::InvalidMeasurement)
            );
        }
    }

    #[test]
    fn surface_pairs_are_distinct_projections_and_nearest_takes_no_offset() {
        use crate::{CounterpartSurface, SubjectSurface, VerticalSurfaces};
        let between = |counterpart, offset| ProximityProjection::Vertical {
            footprint_offset_metres: offset,
            direction: VerticalDirection::Above,
            surfaces: VerticalSurfaces::Between {
                subject: SubjectSurface::Top,
                counterpart,
            },
        };
        let extents = ProximityProjection::Vertical {
            footprint_offset_metres: 0.0,
            direction: VerticalDirection::Above,
            surfaces: VerticalSurfaces::Extents,
        };
        assert_ne!(between(CounterpartSurface::Nearest, 0.0), extents);
        assert_ne!(
            between(CounterpartSurface::Nearest, 0.0),
            between(CounterpartSurface::Bottom, 0.0)
        );
        assert!(
            ProximityRequest::projected(
                id("pipe"),
                id("wall"),
                between(CounterpartSurface::Bottom, 0.5)
            )
            .is_ok()
        );
        assert_eq!(
            ProximityRequest::projected(
                id("pipe"),
                id("wall"),
                between(CounterpartSurface::Nearest, 0.5)
            ),
            Err(ProximityError::InvalidMeasurement)
        );
        assert_eq!(SubjectSurface::Bottom.name(), "bottom");
        assert_eq!(CounterpartSurface::Nearest.name(), "nearest");
    }

    /// Above and below are different questions.
    #[test]
    fn a_vertical_direction_distinguishes_requests() {
        let vertical = |direction| ProximityProjection::Vertical {
            footprint_offset_metres: 0.0,
            direction,
            surfaces: crate::VerticalSurfaces::Extents,
        };
        let above = vertical(VerticalDirection::Above);
        assert_ne!(above, vertical(VerticalDirection::Below));
        assert_ne!(above, vertical(VerticalDirection::Either));
        assert!(vertical(VerticalDirection::Either) < above);
    }

    /// Penetration is a question in space; a projected request cannot carry it.
    #[test]
    fn full_proximity_evidence_is_only_measured_in_space() {
        let horizontal =
            ProximityRequest::projected(id("pipe"), id("wall"), ProximityProjection::Horizontal)
                .unwrap();
        assert_eq!(
            ProximityEvidence::try_new(
                horizontal,
                0.1,
                Some(0.0),
                0.0,
                None,
                GeometryFidelity::Exact,
                exact()
            ),
            Err(ProximityError::UnsupportedProjection)
        );
    }

    #[test]
    fn projected_distance_intervals_are_coherent() {
        let plan =
            ProximityRequest::projected(id("pipe"), id("wall"), ProximityProjection::PlanOverlap)
                .unwrap();
        let tessellated = GeometryFidelity::tessellated(0.002).unwrap();
        // Exact evidence is a point, related or not.
        assert!(
            ProjectedDistanceEvidence::try_new(
                plan.clone(),
                f64::INFINITY,
                f64::INFINITY,
                GeometryFidelity::Exact,
                exact()
            )
            .is_ok()
        );
        assert_eq!(
            ProjectedDistanceEvidence::try_new(
                plan.clone(),
                0.0,
                f64::INFINITY,
                GeometryFidelity::Exact,
                exact()
            ),
            Err(ProximityError::InvalidMeasurement)
        );
        // A tessellation may leave the relation open, but never claim exactness.
        assert!(
            ProjectedDistanceEvidence::try_new(
                plan.clone(),
                0.0,
                f64::INFINITY,
                tessellated,
                approximate()
            )
            .is_ok()
        );
        assert_eq!(
            ProjectedDistanceEvidence::try_new(plan, 0.0, 0.0, tessellated, exact()),
            Err(ProximityError::EvidenceFidelityMismatch)
        );
        // Bodies always have a distance in space and in plan.
        assert_eq!(
            ProjectedDistanceEvidence::try_new(
                request(),
                0.0,
                f64::INFINITY,
                tessellated,
                approximate()
            ),
            Err(ProximityError::InvalidMeasurement)
        );
        assert_eq!(
            ProjectedDistanceEvidence::try_new(request(), 0.3, 0.2, tessellated, approximate()),
            Err(ProximityError::InvalidMeasurement)
        );
    }

    /// The narrower plan axis bounds how far an intersection reaches in plan.
    #[test]
    fn horizontal_extent_is_the_narrower_plan_axis() {
        let extents = OverlapExtents::new(
            LengthInterval::try_new(0.1, 0.3).unwrap(),
            LengthInterval::try_new(0.2, 0.25).unwrap(),
            LengthInterval::exact(1.0).unwrap(),
        );
        assert_eq!(
            extents.horizontal(),
            LengthInterval::try_new(0.1, 0.25).unwrap()
        );
        assert_eq!(extents.vertical(), LengthInterval::exact(1.0).unwrap());
    }

    #[test]
    fn overlap_extents_need_a_shared_volume() {
        let extents = OverlapExtents::new(
            LengthInterval::exact(0.1).unwrap(),
            LengthInterval::exact(0.1).unwrap(),
            LengthInterval::exact(0.1).unwrap(),
        );
        let measured = |separation: f64, penetration: Option<f64>| {
            ProximityEvidence::try_new(
                request(),
                separation,
                penetration,
                0.0,
                None,
                GeometryFidelity::Exact,
                exact(),
            )
            .unwrap()
        };
        assert!(
            measured(0.0, Some(0.1))
                .with_overlap_extents(extents)
                .is_ok()
        );
        // Two open surfaces have no inside to share.
        assert_eq!(
            measured(0.0, None).with_overlap_extents(extents),
            Err(ProximityError::InvalidMeasurement)
        );
        // Bodies apart at the surface, neither inside the other, share nothing.
        assert_eq!(
            measured(0.2, Some(0.0)).with_overlap_extents(extents),
            Err(ProximityError::InvalidMeasurement)
        );
    }

    /// No point of a surface lies closer to the other than the separation.
    #[test]
    fn hausdorff_distance_is_never_below_the_separation() {
        let measured = ProximityEvidence::try_new(
            request(),
            0.2,
            Some(0.0),
            0.0,
            None,
            GeometryFidelity::Exact,
            exact(),
        )
        .unwrap();
        assert_eq!(
            measured
                .clone()
                .with_hausdorff(LengthInterval::try_new(0.0, 0.1).unwrap()),
            Err(ProximityError::InvalidMeasurement)
        );
        assert!(
            measured
                .with_hausdorff(LengthInterval::try_new(0.2, 0.5).unwrap())
                .is_ok()
        );
    }

    fn volume(lower: f64, upper: f64) -> VolumeInterval {
        VolumeInterval::try_new(lower, upper).unwrap()
    }

    #[test]
    fn volume_intervals_are_finite_non_negative_and_ordered() {
        for (lower, upper) in [
            (-0.1, 0.1),
            (0.2, 0.1),
            (0.0, f64::INFINITY),
            (f64::NAN, 1.0),
        ] {
            assert_eq!(
                VolumeInterval::try_new(lower, upper),
                Err(ProximityError::InvalidMeasurement)
            );
        }
        assert!(VolumeInterval::exact(0.0).unwrap().is_exact());
    }

    /// Two bodies cannot share more than the smaller of them holds.
    #[test]
    fn a_shared_volume_never_exceeds_either_body() {
        assert_eq!(
            IntersectionVolume::try_new(volume(0.5, 0.6), volume(1.0, 1.0), volume(0.4, 0.4)),
            Err(ProximityError::InvalidMeasurement)
        );
        let measured =
            IntersectionVolume::try_new(volume(0.3, 0.4), volume(1.0, 1.0), volume(0.4, 0.5))
                .unwrap();
        assert_eq!(measured.smaller(), volume(0.4, 0.5));
        let (lower, upper) = measured.ratio_of_smaller();
        assert!(lower <= 0.6 && lower > 0.599, "{lower}");
        assert!((upper - 1.0).abs() < f64::EPSILON, "{upper}");
    }

    /// A share's bounds are rounded outward, so the true share lies inside.
    #[test]
    fn a_volume_share_is_rounded_outward_and_clamped() {
        let third = volume(1.0 / 3.0, 1.0 / 3.0);
        let (lower, upper) = third.share_of(volume(1.0, 1.0));
        assert!(lower < 1.0 / 3.0 && upper > 1.0 / 3.0);
        assert_eq!(volume(0.0, 0.0).share_of(volume(0.0, 0.0)), (0.0, 1.0));
        assert!((volume(1.0, 1.0).share_of(volume(1.0, 1.0)).1 - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn an_intersection_volume_needs_a_shared_inside() {
        let measured = |separation: f64, penetration: Option<f64>, containment| {
            ProximityEvidence::try_new(
                request(),
                separation,
                penetration,
                0.0,
                containment,
                GeometryFidelity::Exact,
                exact(),
            )
            .unwrap()
        };
        let shared = |lower: f64, upper: f64| {
            IntersectionVolume::try_new(volume(lower, upper), volume(1.0, 1.0), volume(8.0, 8.0))
                .unwrap()
        };
        assert!(
            measured(0.0, Some(0.1), None)
                .with_intersection_volume(shared(0.2, 0.2))
                .is_ok()
        );
        // Open surfaces enclose nothing.
        assert_eq!(
            measured(0.0, None, None).with_intersection_volume(shared(0.0, 0.0)),
            Err(ProximityError::InvalidMeasurement)
        );
        // Bodies apart at the surface share nothing unless one holds the
        // other,
        assert_eq!(
            measured(0.2, Some(0.0), None).with_intersection_volume(shared(0.1, 0.2)),
            Err(ProximityError::InvalidMeasurement)
        );
        assert!(
            measured(0.2, Some(0.0), None)
                .with_intersection_volume(shared(0.0, 0.0))
                .is_ok()
        );
        // and then they share the whole of the inner body.
        let inside = || {
            measured(
                0.2,
                Some(0.1),
                Some(BodyContainment::SubjectInsideCounterpart),
            )
        };
        assert!(inside().with_intersection_volume(shared(1.0, 1.0)).is_ok());
        assert_eq!(
            inside().with_intersection_volume(shared(0.5, 0.6)),
            Err(ProximityError::InvalidMeasurement)
        );
    }

    #[test]
    fn a_face_distance_is_between_two_objects() {
        assert_eq!(
            FaceDistanceRequest::try_new(id("pipe"), id("pipe"), FaceClass::Top),
            Err(FaceDistanceError::SameObject)
        );
        for class in [
            FaceClass::Top,
            FaceClass::Side,
            FaceClass::Bottom,
            FaceClass::Any,
        ] {
            assert_eq!(FaceClass::parse(class.name()), Some(class));
        }
        assert_eq!(FaceClass::parse("front"), None);
        let request =
            FaceDistanceRequest::try_new(id("pipe"), id("wall"), FaceClass::Side).unwrap();
        let signed = SignedDistanceInterval::try_new(-0.1, 0.2).unwrap();
        assert_eq!(
            FaceDistanceEvidence::try_new(
                request.clone(),
                signed,
                GeometryFidelity::tessellated(0.001).unwrap(),
                exact()
            ),
            Err(FaceDistanceError::EvidenceFidelityMismatch)
        );
        assert!(
            FaceDistanceEvidence::try_new(request, signed, GeometryFidelity::Exact, exact())
                .is_ok()
        );
    }

    /// A service that does not measure face distances says so.
    #[test]
    fn face_distances_are_refused_by_default() {
        struct Silent;
        impl ProximityService for Silent {
            fn bounds(&self, _: &ObjectId) -> Result<ObjectBounds, ProximityError> {
                Err(ProximityError::Unavailable)
            }
            fn measure_proximity(
                &self,
                _: &ProximityRequest,
            ) -> Result<ProximityEvidence, ProximityError> {
                Err(ProximityError::Unavailable)
            }
        }
        let request = FaceDistanceRequest::try_new(id("pipe"), id("wall"), FaceClass::Any).unwrap();
        assert_eq!(
            ProximityServiceHandle::new(Arc::new(Silent)).measure_face_distance(&request),
            Err(FaceDistanceError::Unsupported)
        );
    }

    #[test]
    fn box_gap_is_euclidean_and_zero_when_boxes_meet() {
        let a = Bounds3::try_new([0.0; 3], [1.0; 3]).unwrap();
        let b = Bounds3::try_new([4.0, 5.0, 0.0], [5.0, 6.0, 1.0]).unwrap();
        assert!((a.gap(&b) - 5.0).abs() < 1e-12);
        let touching = Bounds3::try_new([1.0, 0.0, 0.0], [2.0, 1.0, 1.0]).unwrap();
        assert!(a.gap(&touching).abs() < f64::EPSILON);
        assert_eq!(
            Bounds3::try_new([1.0, 0.0, 0.0], [0.0, 1.0, 1.0]),
            Err(ProximityError::InvalidMeasurement)
        );
    }

    #[test]
    fn region_distances_bind_their_request_and_default_to_refusal() {
        struct Nothing;
        impl ProximityService for Nothing {
            fn bounds(&self, _: &ObjectId) -> Result<ObjectBounds, ProximityError> {
                Err(ProximityError::Unavailable)
            }
            fn measure_proximity(
                &self,
                _: &ProximityRequest,
            ) -> Result<ProximityEvidence, ProximityError> {
                Err(ProximityError::Unavailable)
            }
        }
        let region = ConvexPlanRegion::try_new(vec![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]).unwrap();
        let request = RegionDistanceRequest::new(region, id("wall"));
        let evidence = |exact: bool| Evidence {
            source: SourceId::new("cad", "m").unwrap(),
            locator: "region".into(),
            exact,
        };
        assert!(
            RegionDistanceEvidence::try_new(
                request.clone(),
                0.5,
                0.5,
                GeometryFidelity::Exact,
                evidence(true)
            )
            .is_ok()
        );
        // Exact evidence is a point; tessellated evidence is not exact.
        assert_eq!(
            RegionDistanceEvidence::try_new(
                request.clone(),
                0.4,
                0.5,
                GeometryFidelity::Exact,
                evidence(true)
            ),
            Err(ProximityError::InvalidMeasurement)
        );
        assert_eq!(
            RegionDistanceEvidence::try_new(
                request.clone(),
                0.4,
                0.5,
                GeometryFidelity::tessellated(0.05).unwrap(),
                evidence(true)
            ),
            Err(ProximityError::EvidenceFidelityMismatch)
        );
        assert_eq!(
            ProximityServiceHandle::new(Arc::new(Nothing)).measure_region_distance(&request),
            Err(ProximityError::UnsupportedProjection)
        );
    }

    /// Extents along stated directions: one per direction, bound to their
    /// request, refused by default.
    #[test]
    fn extents_along_directions_bind_their_request_and_default_to_refusal() {
        struct Nothing;
        impl ProximityService for Nothing {
            fn bounds(&self, _: &ObjectId) -> Result<ObjectBounds, ProximityError> {
                Err(ProximityError::Unavailable)
            }
            fn measure_proximity(
                &self,
                _: &ProximityRequest,
            ) -> Result<ProximityEvidence, ProximityError> {
                Err(ProximityError::Unavailable)
            }
        }
        /// Answers every request with the evidence for another.
        struct Other(OverlapAlongEvidence);
        impl ProximityService for Other {
            fn bounds(&self, _: &ObjectId) -> Result<ObjectBounds, ProximityError> {
                Err(ProximityError::Unavailable)
            }
            fn measure_proximity(
                &self,
                _: &ProximityRequest,
            ) -> Result<ProximityEvidence, ProximityError> {
                Err(ProximityError::Unavailable)
            }
            fn measure_overlap_along(
                &self,
                _: &OverlapAlongRequest,
            ) -> Result<OverlapAlongEvidence, ProximityError> {
                Ok(self.0.clone())
            }
        }
        let axis = |vector| MetricDirection::try_new(vector).unwrap();
        let along = |directions: Vec<MetricDirection>| {
            OverlapAlongRequest::try_new(id("pipe"), id("wall"), directions)
        };
        assert_eq!(along(Vec::new()), Err(ProximityError::InvalidMeasurement));
        assert_eq!(
            along(vec![axis([1.0, 0.0, 0.0]); 7]),
            Err(ProximityError::InvalidMeasurement)
        );
        assert_eq!(
            OverlapAlongRequest::try_new(id("pipe"), id("pipe"), vec![axis([0.0, 0.0, 1.0])]),
            Err(ProximityError::SameObject)
        );
        let request = along(vec![axis([1.0, 1.0, 0.0]), axis([0.0, 0.0, 1.0])]).unwrap();
        let extent = LengthInterval::try_new(0.01, 0.02).unwrap();
        assert_eq!(
            OverlapAlongEvidence::try_new(
                request.clone(),
                vec![extent],
                GeometryFidelity::Exact,
                exact()
            ),
            Err(ProximityError::InvalidMeasurement)
        );
        assert_eq!(
            OverlapAlongEvidence::try_new(
                request.clone(),
                vec![extent, extent],
                GeometryFidelity::tessellated(0.001).unwrap(),
                exact()
            ),
            Err(ProximityError::EvidenceFidelityMismatch)
        );
        let measured = OverlapAlongEvidence::try_new(
            request.clone(),
            vec![extent, extent],
            GeometryFidelity::Exact,
            exact(),
        )
        .unwrap();
        assert_eq!(measured.extents(), &[extent, extent]);

        assert_eq!(
            ProximityServiceHandle::new(Arc::new(Nothing)).measure_overlap_along(&request),
            Err(ProximityError::UnsupportedProjection)
        );

        let other = along(vec![axis([0.0, 1.0, 0.0]), axis([0.0, 0.0, 1.0])]).unwrap();
        assert_eq!(
            ProximityServiceHandle::new(Arc::new(Other(measured))).measure_overlap_along(&other),
            Err(ProximityError::InvalidMeasurement)
        );
    }
}