featherstone 0.1.0

Robotics dynamics engine — O(n) forward/inverse dynamics for kinematic trees, contact solvers, and time integration
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
//! Contact manifold for articulated body dynamics
//!
//! Represents contact points between articulated body links and the environment
//! or other bodies. Provides the geometric data needed by the contact solver:
//! - Contact point positions (world and body local frames)
//! - Contact normals and penetration depths
//! - Friction and restitution coefficients
//!
//! This module is backend-agnostic: contact detection can come from Rapier's
//! narrow phase, custom GJK/EPA, or analytical geometry. The contact manifold
//! is the common interface consumed by the LCP solver and smooth contact model.

use nalgebra::{Matrix3, Vector3};

/// A single contact point between an articulated body link and another surface.
#[derive(Clone, Debug)]
pub struct ContactPoint {
    /// Index of the body/link in the ArticulatedBody tree
    pub body_id: usize,
    /// Contact point position in world frame
    pub point_world: Vector3<f32>,
    /// Contact point position in body-local frame
    pub point_body: Vector3<f32>,
    /// Contact normal in world frame (points away from body, into environment)
    pub normal: Vector3<f32>,
    /// Penetration depth (positive = overlapping, negative = separated)
    pub penetration: f32,
    /// Coulomb friction coefficient at this contact
    pub friction: f32,
    /// Coefficient of restitution (0 = perfectly inelastic, 1 = perfectly elastic)
    pub restitution: f32,
}

impl ContactPoint {
    /// Create a new contact point with default material properties.
    pub fn new(
        body_id: usize,
        point_world: Vector3<f32>,
        point_body: Vector3<f32>,
        normal: Vector3<f32>,
        penetration: f32,
    ) -> Self {
        Self {
            body_id,
            point_world,
            point_body,
            normal: if normal.norm_squared() > 1e-12 { normal.normalize() } else { Vector3::z() },
            penetration,
            friction: 0.5,
            restitution: 0.0,
        }
    }

    /// Set friction coefficient.
    pub fn with_friction(mut self, friction: f32) -> Self {
        self.friction = friction;
        self
    }

    /// Set restitution coefficient.
    pub fn with_restitution(mut self, restitution: f32) -> Self {
        self.restitution = restitution;
        self
    }

    /// Whether this contact is active (positive penetration).
    pub fn is_active(&self) -> bool {
        self.penetration > 0.0
    }

    /// Compute a tangent frame for this contact.
    ///
    /// Returns two orthonormal tangent vectors (t1, t2) perpendicular to the
    /// contact normal. Used for friction force decomposition.
    pub fn tangent_frame(&self) -> (Vector3<f32>, Vector3<f32>) {
        compute_tangent_frame(&self.normal)
    }
}

/// Collection of contact points forming a contact manifold.
///
/// A manifold groups all active contacts for processing by the solver.
/// Contacts can come from multiple body pairs and collision geometries.
#[derive(Clone, Debug, Default)]
pub struct ContactManifold {
    /// All contact points
    pub contacts: Vec<ContactPoint>,
}

impl ContactManifold {
    /// Create an empty manifold.
    pub fn new() -> Self {
        Self {
            contacts: Vec::new(),
        }
    }

    /// Create a manifold with pre-allocated capacity.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            contacts: Vec::with_capacity(capacity),
        }
    }

    /// Add a contact point to the manifold.
    pub fn add_contact(&mut self, contact: ContactPoint) {
        self.contacts.push(contact);
    }

    /// Number of contacts.
    pub fn len(&self) -> usize {
        self.contacts.len()
    }

    /// Whether the manifold is empty.
    pub fn is_empty(&self) -> bool {
        self.contacts.is_empty()
    }

    /// Remove contacts with penetration below threshold (separated contacts).
    pub fn prune_separated(&mut self, threshold: f32) {
        self.contacts.retain(|c| c.penetration > threshold);
    }

    /// Get only active contacts (positive penetration).
    pub fn active_contacts(&self) -> impl Iterator<Item = &ContactPoint> {
        self.contacts.iter().filter(|c| c.is_active())
    }

    /// Number of active contacts.
    pub fn active_count(&self) -> usize {
        self.contacts.iter().filter(|c| c.is_active()).count()
    }

    /// Get contacts for a specific body.
    pub fn contacts_for_body(&self, body_id: usize) -> impl Iterator<Item = &ContactPoint> {
        self.contacts.iter().filter(move |c| c.body_id == body_id)
    }

    /// Clear all contacts.
    pub fn clear(&mut self) {
        self.contacts.clear();
    }

    /// Merge another manifold into this one.
    pub fn merge(&mut self, other: &ContactManifold) {
        self.contacts.extend(other.contacts.iter().cloned());
    }

    /// Sort contacts by penetration depth (deepest first).
    pub fn sort_by_penetration(&mut self) {
        self.contacts
            .sort_by(|a, b| b.penetration.partial_cmp(&a.penetration).unwrap_or(std::cmp::Ordering::Equal));
    }

    /// Limit to N deepest contacts per body (for solver performance).
    pub fn limit_per_body(&mut self, max_per_body: usize) {
        self.sort_by_penetration();
        let mut counts = std::collections::HashMap::new();
        self.contacts.retain(|c| {
            let count = counts.entry(c.body_id).or_insert(0usize);
            if *count < max_per_body {
                *count += 1;
                true
            } else {
                false
            }
        });
    }

    /// Reduce contacts to the best N by maximizing the contact patch area.
    ///
    /// Greedy algorithm:
    /// 1. Keep the deepest contact (best penetration correction)
    /// 2. Find the contact farthest from #1 in the tangent plane
    /// 3. Find the contact maximizing triangle area with #1 and #2
    /// 4. Find the contact maximizing quadrilateral area with #1, #2, #3
    ///
    /// This produces a near-optimal contact patch for LCP stability.
    pub fn reduce_to_best_n(&mut self, max_contacts: usize) {
        if self.contacts.len() <= max_contacts || self.contacts.is_empty() {
            return;
        }

        let indices = select_max_area_contacts(&self.contacts, max_contacts);
        let selected: Vec<ContactPoint> = indices.iter().map(|&i| self.contacts[i].clone()).collect();
        self.contacts = selected;
    }
}

/// Generate a ground-plane contact manifold for an articulated body.
///
/// Checks each body's origin (plus optional collision geometry offset) against
/// a horizontal ground plane at the given height. This is a simple analytical
/// contact detector suitable for flat-ground locomotion tasks.
///
/// For complex geometries, use Rapier narrow-phase or custom GJK/EPA instead.
pub fn ground_plane_contacts(
    body: &super::body::ArticulatedBody,
    ground_height: f32,
    ground_normal: Vector3<f32>,
    friction: f32,
    restitution: f32,
) -> ContactManifold {
    let fk = super::kinematics::forward_kinematics(body);
    let normal = if ground_normal.norm_squared() > 1e-12 { ground_normal.normalize() } else { Vector3::y() };
    let mut manifold = ContactManifold::new();

    for i in 0..body.body_count() {
        let bd = &body.bodies[i];
        if bd.inertia.mass <= 0.0 {
            continue;
        }

        // Body origin in world frame
        let p_world = fk.transforms[i].translation;

        // Signed distance from ground plane (positive = above)
        let signed_dist = normal.dot(&(p_world - normal * ground_height));
        let penetration = -signed_dist;

        if penetration > -0.01 {
            // Near or in contact
            let point_world = p_world - normal * signed_dist;
            let r = &fk.transforms[i].rotation;
            let point_body = r.transpose() * (point_world - p_world);

            manifold.add_contact(
                ContactPoint::new(i, point_world, point_body, normal, penetration)
                    .with_friction(friction)
                    .with_restitution(restitution),
            );
        }
    }

    manifold
}

/// Generate contact points for sphere-on-ground collision geometry.
///
/// Each body can have an associated collision sphere (radius). This gives
/// more accurate contacts than body-origin checks for legged robots.
pub fn sphere_ground_contacts(
    body: &super::body::ArticulatedBody,
    radii: &[f32],
    ground_height: f32,
    ground_normal: Vector3<f32>,
    friction: f32,
    restitution: f32,
) -> ContactManifold {
    let fk = super::kinematics::forward_kinematics(body);
    let normal = if ground_normal.norm_squared() > 1e-12 { ground_normal.normalize() } else { Vector3::y() };
    let mut manifold = ContactManifold::new();

    for (i, &radius) in radii.iter().enumerate().take(body.body_count().min(radii.len())) {
        if radius <= 0.0 {
            continue;
        }

        let p_world = fk.transforms[i].translation;

        // Signed distance from sphere surface to ground
        let center_dist = normal.dot(&(p_world - normal * ground_height));
        let penetration = radius - center_dist;

        if penetration > -0.01 {
            // Contact point is on the sphere surface closest to ground
            let point_world = p_world - normal * center_dist;
            let r = &fk.transforms[i].rotation;
            let point_body = r.transpose() * (point_world - p_world);

            manifold.add_contact(
                ContactPoint::new(i, point_world, point_body, normal, penetration)
                    .with_friction(friction)
                    .with_restitution(restitution),
            );
        }
    }

    manifold
}

// ============================================================================
// Inter-body contact detection
// ============================================================================

use super::collider::ColliderShape as StoredShape;

/// Geometric pair for contact detection between two convex shapes.
///
/// Groups the per-shape world transform, body IDs, and material properties
/// that are repeated across every contact detection function. Pass this to
/// the `*_from_pair` family of functions to avoid 8+ parameter signatures.
#[derive(Clone, Debug)]
pub struct ShapePair {
    /// Position of shape A in world frame.
    pub pos_a: Vector3<f32>,
    /// Rotation of shape A in world frame.
    pub rot_a: Matrix3<f32>,
    /// Position of shape B in world frame.
    pub pos_b: Vector3<f32>,
    /// Rotation of shape B in world frame.
    pub rot_b: Matrix3<f32>,
    /// Body index for shape A (assigned to contacts on the A side).
    pub body_id_a: usize,
    /// Body index for shape B.
    pub body_id_b: usize,
    /// Coulomb friction coefficient at the contact.
    pub friction: f32,
    /// Coefficient of restitution at the contact.
    pub restitution: f32,
}

/// Detect contacts between two shapes at given world transforms.
///
/// Returns a `ContactManifold` with contacts between shape A and shape B.
/// Contact normals point from A to B. `body_id_a` and `body_id_b` are assigned
/// to contact points for identification in the manifold.
pub fn inter_body_contacts(
    shape_a: &StoredShape,
    shape_b: &StoredShape,
    pair: &ShapePair,
) -> ContactManifold {
    let pos_a = pair.pos_a;
    let rot_a = pair.rot_a;
    let pos_b = pair.pos_b;
    let rot_b = pair.rot_b;
    let body_id_a = pair.body_id_a;
    let body_id_b = pair.body_id_b;
    let friction = pair.friction;
    let restitution = pair.restitution;
    let mut manifold = ContactManifold::new();

    match (shape_a, shape_b) {
        (StoredShape::Sphere { radius: ra }, StoredShape::Sphere { radius: rb }) => {
            if let Some(c) = sphere_sphere_contact(
                pos_a, *ra, pos_b, *rb, body_id_a, friction, restitution,
            ) {
                manifold.add_contact(c);
            }
        }
        (StoredShape::Sphere { radius }, StoredShape::Box { half_extents }) => {
            if let Some(c) = sphere_box_contact(
                pos_a, *radius, pos_b, rot_b, *half_extents,
                body_id_a, friction, restitution,
            ) {
                manifold.add_contact(c);
            }
        }
        (StoredShape::Box { half_extents }, StoredShape::Sphere { radius }) => {
            // Flip: call sphere-box with sphere as first arg, negate normal
            if let Some(mut c) = sphere_box_contact(
                pos_b, *radius, pos_a, rot_a, *half_extents,
                body_id_b, friction, restitution,
            ) {
                c.normal = -c.normal;
                c.body_id = body_id_a;
                manifold.add_contact(c);
            }
        }
        (StoredShape::Box { half_extents: he_a }, StoredShape::Box { half_extents: he_b }) => {
            let contacts = box_box_contacts(
                pos_a, rot_a, *he_a, pos_b, rot_b, *he_b,
                body_id_a, friction, restitution,
            );
            for c in contacts {
                manifold.add_contact(c);
            }
        }
        // Capsule pairs
        (StoredShape::Capsule { half_height: hh_a, radius: ra },
         StoredShape::Capsule { half_height: hh_b, radius: rb }) => {
            if let Some(c) = capsule_capsule_contact(
                pos_a, rot_a, *hh_a, *ra, pos_b, rot_b, *hh_b, *rb,
                body_id_a, friction, restitution,
            ) { manifold.add_contact(c); }
        }
        (StoredShape::Capsule { half_height, radius },
         StoredShape::Sphere { radius: sr }) => {
            if let Some(c) = capsule_sphere_contact(
                pos_a, rot_a, *half_height, *radius, pos_b, *sr,
                body_id_a, friction, restitution,
            ) { manifold.add_contact(c); }
        }
        (StoredShape::Sphere { radius: sr },
         StoredShape::Capsule { half_height, radius }) => {
            if let Some(mut c) = capsule_sphere_contact(
                pos_b, rot_b, *half_height, *radius, pos_a, *sr,
                body_id_b, friction, restitution,
            ) { c.normal = -c.normal; c.body_id = body_id_a; manifold.add_contact(c); }
        }
        (StoredShape::Capsule { half_height, radius },
         StoredShape::Box { half_extents }) => {
            for c in capsule_box_contact(
                pos_a, rot_a, *half_height, *radius, pos_b, rot_b, *half_extents,
                body_id_a, friction, restitution,
            ) { manifold.add_contact(c); }
        }
        (StoredShape::Box { half_extents },
         StoredShape::Capsule { half_height, radius }) => {
            for mut c in capsule_box_contact(
                pos_b, rot_b, *half_height, *radius, pos_a, rot_a, *half_extents,
                body_id_b, friction, restitution,
            ) { c.normal = -c.normal; c.body_id = body_id_a; manifold.add_contact(c); }
        }
        // Cylinder treated as capsule with same half_height/radius
        (StoredShape::Cylinder { half_height, radius },
         StoredShape::Sphere { radius: sr }) => {
            if let Some(c) = capsule_sphere_contact(
                pos_a, rot_a, *half_height, *radius, pos_b, *sr,
                body_id_a, friction, restitution,
            ) { manifold.add_contact(c); }
        }
        (StoredShape::Sphere { radius: sr },
         StoredShape::Cylinder { half_height, radius }) => {
            if let Some(mut c) = capsule_sphere_contact(
                pos_b, rot_b, *half_height, *radius, pos_a, *sr,
                body_id_b, friction, restitution,
            ) { c.normal = -c.normal; c.body_id = body_id_a; manifold.add_contact(c); }
        }
        // Any pair involving ConvexHull or DecomposedMesh: use GJK/EPA
        _ if matches!(shape_a, StoredShape::ConvexHull { .. } | StoredShape::DecomposedMesh { .. })
          || matches!(shape_b, StoredShape::ConvexHull { .. } | StoredShape::DecomposedMesh { .. }) => {
            let contacts = gjk_contact_pair(
                shape_a, pos_a, rot_a, shape_b, pos_b, rot_b,
                body_id_a, friction, restitution,
            );
            for c in contacts { manifold.add_contact(c); }
        }
        // Cylinder-Cylinder: treat both as capsules
        (StoredShape::Cylinder { half_height: hh_a, radius: ra },
         StoredShape::Cylinder { half_height: hh_b, radius: rb }) => {
            if let Some(c) = capsule_capsule_contact(
                pos_a, rot_a, *hh_a, *ra, pos_b, rot_b, *hh_b, *rb,
                body_id_a, friction, restitution,
            ) { manifold.add_contact(c); }
        }
        // Cylinder-Box: treat cylinder as capsule
        (StoredShape::Cylinder { half_height, radius },
         StoredShape::Box { half_extents }) => {
            for c in capsule_box_contact(
                pos_a, rot_a, *half_height, *radius, pos_b, rot_b, *half_extents,
                body_id_a, friction, restitution,
            ) { manifold.add_contact(c); }
        }
        (StoredShape::Box { half_extents },
         StoredShape::Cylinder { half_height, radius }) => {
            for mut c in capsule_box_contact(
                pos_b, rot_b, *half_height, *radius, pos_a, rot_a, *half_extents,
                body_id_b, friction, restitution,
            ) { c.normal = -c.normal; c.body_id = body_id_a; manifold.add_contact(c); }
        }
        // Cylinder-Capsule: treat cylinder as capsule
        (StoredShape::Cylinder { half_height: hh_a, radius: ra },
         StoredShape::Capsule { half_height: hh_b, radius: rb }) => {
            if let Some(c) = capsule_capsule_contact(
                pos_a, rot_a, *hh_a, *ra, pos_b, rot_b, *hh_b, *rb,
                body_id_a, friction, restitution,
            ) { manifold.add_contact(c); }
        }
        (StoredShape::Capsule { half_height: hh_a, radius: ra },
         StoredShape::Cylinder { half_height: hh_b, radius: rb }) => {
            if let Some(c) = capsule_capsule_contact(
                pos_a, rot_a, *hh_a, *ra, pos_b, rot_b, *hh_b, *rb,
                body_id_a, friction, restitution,
            ) { manifold.add_contact(c); }
        }
        _ => {}
    }

    manifold
}

/// Sphere-sphere contact detection.
///
/// Returns a contact if the two spheres overlap or are within tolerance.
/// Normal points from A to B.
pub fn sphere_sphere_contact(
    pos_a: Vector3<f32>,
    radius_a: f32,
    pos_b: Vector3<f32>,
    radius_b: f32,
    body_id: usize,
    friction: f32,
    restitution: f32,
) -> Option<ContactPoint> {
    let diff = pos_b - pos_a;
    let dist = diff.norm();
    let penetration = radius_a + radius_b - dist;

    if penetration < -0.01 {
        return None;
    }

    let normal = if dist > 1e-8 {
        diff / dist
    } else {
        Vector3::y() // Degenerate: overlapping centers, push up
    };

    // Contact point at midpoint of overlap
    let point_world = pos_a + normal * (radius_a - penetration * 0.5);
    let point_body = -normal * (radius_a - penetration * 0.5);

    Some(
        ContactPoint::new(body_id, point_world, point_body, normal, penetration)
            .with_friction(friction)
            .with_restitution(restitution),
    )
}

/// Sphere-box contact detection.
///
/// Finds the closest point on the box to the sphere center, then checks distance.
/// Normal points from sphere (body A) toward box (body B).
#[allow(clippy::too_many_arguments)]
pub fn sphere_box_contact(
    sphere_pos: Vector3<f32>,
    radius: f32,
    box_pos: Vector3<f32>,
    box_rot: Matrix3<f32>,
    half_extents: Vector3<f32>,
    body_id: usize,
    friction: f32,
    restitution: f32,
) -> Option<ContactPoint> {
    // Transform sphere center to box local frame
    let local_center = box_rot.transpose() * (sphere_pos - box_pos);

    // Clamp to box surface (closest point on AABB)
    let closest_local = Vector3::new(
        local_center.x.clamp(-half_extents.x, half_extents.x),
        local_center.y.clamp(-half_extents.y, half_extents.y),
        local_center.z.clamp(-half_extents.z, half_extents.z),
    );

    let diff_local = local_center - closest_local;
    let dist = diff_local.norm();

    // Check if sphere center is inside the box
    let inside = local_center.x.abs() <= half_extents.x
        && local_center.y.abs() <= half_extents.y
        && local_center.z.abs() <= half_extents.z;

    let penetration = if inside {
        // Sphere center inside box: find closest face for pushout
        let face_dists = [
            half_extents.x - local_center.x.abs(),
            half_extents.y - local_center.y.abs(),
            half_extents.z - local_center.z.abs(),
        ];
        let min_dist = face_dists.iter().copied().fold(f32::MAX, f32::min);
        radius + min_dist
    } else {
        radius - dist
    };

    if penetration < -0.01 {
        return None;
    }

    let normal_local = if inside {
        // Push out along closest face
        let face_dists = [
            half_extents.x - local_center.x.abs(),
            half_extents.y - local_center.y.abs(),
            half_extents.z - local_center.z.abs(),
        ];
        let min_idx = face_dists
            .iter()
            .enumerate()
            .min_by(|a, b| a.1.partial_cmp(b.1).unwrap_or(std::cmp::Ordering::Equal))
            .map(|(i, _)| i)
            .unwrap_or(1);
        let mut n = Vector3::zeros();
        n[min_idx] = if local_center[min_idx] >= 0.0 { 1.0 } else { -1.0 };
        n
    } else if dist > 1e-8 {
        diff_local / dist
    } else {
        Vector3::y()
    };

    // Transform normal back to world frame
    let normal_world = box_rot * normal_local;
    let closest_world = box_pos + box_rot * closest_local;
    let point_body = -normal_world * (radius - penetration * 0.5);

    Some(
        ContactPoint::new(body_id, closest_world, point_body, normal_world, penetration)
            .with_friction(friction)
            .with_restitution(restitution),
    )
}

/// Box-box contact detection using Separating Axis Theorem (SAT).
///
/// Tests 15 potential separating axes (3 face normals × 2 + 9 edge cross products).
/// Returns contact points on the overlapping region.
#[allow(clippy::too_many_arguments)]
pub fn box_box_contacts(
    pos_a: Vector3<f32>,
    rot_a: Matrix3<f32>,
    he_a: Vector3<f32>,
    pos_b: Vector3<f32>,
    rot_b: Matrix3<f32>,
    he_b: Vector3<f32>,
    body_id: usize,
    friction: f32,
    restitution: f32,
) -> Vec<ContactPoint> {
    let d = pos_b - pos_a;

    // Axes of each box
    let ax_a = [rot_a.column(0).into_owned(), rot_a.column(1).into_owned(), rot_a.column(2).into_owned()];
    let ax_b = [rot_b.column(0).into_owned(), rot_b.column(1).into_owned(), rot_b.column(2).into_owned()];

    let he_a_arr = [he_a.x, he_a.y, he_a.z];
    let he_b_arr = [he_b.x, he_b.y, he_b.z];

    let mut min_penetration = f32::MAX;
    let mut best_axis = Vector3::y();
    let mut best_contact_type = BoxBoxContactType::FaceA(1);

    // Test a single SAT axis, return false if separating
    let test_axis = |axis: Vector3<f32>, contact_type: BoxBoxContactType,
                         min_pen: &mut f32, best_ax: &mut Vector3<f32>,
                         best_ct: &mut BoxBoxContactType| -> bool {
        let len = axis.norm();
        if len < 1e-6 {
            return true; // Degenerate axis, skip
        }
        let axis = axis / len;

        let proj_a: f32 = he_a_arr.iter().zip(ax_a.iter())
            .map(|(&h, a)| h * axis.dot(a).abs())
            .sum();
        let proj_b: f32 = he_b_arr.iter().zip(ax_b.iter())
            .map(|(&h, b)| h * axis.dot(b).abs())
            .sum();

        let dist = d.dot(&axis).abs();
        let penetration = proj_a + proj_b - dist;

        if penetration < -0.01 {
            return false;
        }

        if penetration < *min_pen {
            *min_pen = penetration;
            *best_ax = if d.dot(&axis) >= 0.0 { axis } else { -axis };
            *best_ct = contact_type;
        }
        true
    };

    // 3 face normals of A (indices 0-2)
    for (i, ax) in ax_a.iter().enumerate() {
        if !test_axis(*ax, BoxBoxContactType::FaceA(i),
                      &mut min_penetration, &mut best_axis, &mut best_contact_type) {
            return Vec::new();
        }
    }
    // 3 face normals of B (indices 3-5)
    for (i, ax) in ax_b.iter().enumerate() {
        if !test_axis(*ax, BoxBoxContactType::FaceB(i),
                      &mut min_penetration, &mut best_axis, &mut best_contact_type) {
            return Vec::new();
        }
    }
    // 9 edge cross products (indices 6-14)
    for (i, a) in ax_a.iter().enumerate() {
        for (j, b) in ax_b.iter().enumerate() {
            if !test_axis(a.cross(b), BoxBoxContactType::EdgeEdge(i, j),
                          &mut min_penetration, &mut best_axis, &mut best_contact_type) {
                return Vec::new();
            }
        }
    }

    if min_penetration < -0.01 {
        return Vec::new();
    }

    // Generate contact points based on contact type
    match best_contact_type {
        BoxBoxContactType::FaceA(ref_idx) => {
            // A's face is reference, B provides incident face
            let ref_sign = if best_axis.dot(&ax_a[ref_idx]) >= 0.0 { 1.0 } else { -1.0 };
            let _ref_face = get_box_face_polygon(pos_a, rot_a, he_a, ref_idx, ref_sign);
            let (inc_idx, inc_sign) = select_incident_face(rot_b, best_axis);
            let inc_face = get_box_face_polygon(pos_b, rot_b, he_b, inc_idx, inc_sign);

            // Build clip planes from reference face's 4 side edges
            let ref_normal = ax_a[ref_idx] * ref_sign;
            let ref_center = pos_a + ref_normal * he_a[ref_idx];
            let t1_idx = (ref_idx + 1) % 3;
            let t2_idx = (ref_idx + 2) % 3;
            let clip_planes = [
                (ax_a[t1_idx], ref_center.dot(&ax_a[t1_idx]) - he_a[t1_idx]),
                (-ax_a[t1_idx], -(ref_center.dot(&ax_a[t1_idx]) + he_a[t1_idx])),
                (ax_a[t2_idx], ref_center.dot(&ax_a[t2_idx]) - he_a[t2_idx]),
                (-ax_a[t2_idx], -(ref_center.dot(&ax_a[t2_idx]) + he_a[t2_idx])),
            ];

            let clipped = sutherland_hodgman_clip(&inc_face, &clip_planes);
            let ref_plane_offset = ref_center.dot(&ref_normal);

            clipped.iter().filter_map(|&v| {
                let pen = ref_plane_offset - v.dot(&ref_normal);
                if pen > -0.01 {
                    let point_body = rot_a.transpose() * (v - pos_a);
                    Some(ContactPoint::new(body_id, v, point_body, best_axis, pen)
                        .with_friction(friction)
                        .with_restitution(restitution))
                } else {
                    None
                }
            }).collect()
        }
        BoxBoxContactType::FaceB(ref_idx) => {
            // B's face is reference, A provides incident face
            let ref_sign = if (-best_axis).dot(&ax_b[ref_idx]) >= 0.0 { 1.0 } else { -1.0 };
            let _ref_face = get_box_face_polygon(pos_b, rot_b, he_b, ref_idx, ref_sign);
            let (inc_idx, inc_sign) = select_incident_face(rot_a, -best_axis);
            let inc_face = get_box_face_polygon(pos_a, rot_a, he_a, inc_idx, inc_sign);

            let ref_normal = ax_b[ref_idx] * ref_sign;
            let ref_center = pos_b + ref_normal * he_b[ref_idx];
            let t1_idx = (ref_idx + 1) % 3;
            let t2_idx = (ref_idx + 2) % 3;
            let clip_planes = [
                (ax_b[t1_idx], ref_center.dot(&ax_b[t1_idx]) - he_b[t1_idx]),
                (-ax_b[t1_idx], -(ref_center.dot(&ax_b[t1_idx]) + he_b[t1_idx])),
                (ax_b[t2_idx], ref_center.dot(&ax_b[t2_idx]) - he_b[t2_idx]),
                (-ax_b[t2_idx], -(ref_center.dot(&ax_b[t2_idx]) + he_b[t2_idx])),
            ];

            let clipped = sutherland_hodgman_clip(&inc_face, &clip_planes);
            let ref_plane_offset = ref_center.dot(&ref_normal);

            clipped.iter().filter_map(|&v| {
                let pen = ref_plane_offset - v.dot(&ref_normal);
                if pen > -0.01 {
                    let point_body = rot_a.transpose() * (v - pos_a);
                    Some(ContactPoint::new(body_id, v, point_body, best_axis, pen)
                        .with_friction(friction)
                        .with_restitution(restitution))
                } else {
                    None
                }
            }).collect()
        }
        BoxBoxContactType::EdgeEdge(_i, _j) => {
            // Edge-edge: single closest-point contact (to be improved in task 1.4)
            let point_on_a = pos_a + best_axis * project_box_onto_axis(&ax_a, &he_a_arr, &best_axis);
            let point_on_b = pos_b - best_axis * project_box_onto_axis(&ax_b, &he_b_arr, &(-best_axis));
            let point_world = (point_on_a + point_on_b) * 0.5;
            let point_body = rot_a.transpose() * (point_world - pos_a);

            vec![
                ContactPoint::new(body_id, point_world, point_body, best_axis, min_penetration)
                    .with_friction(friction)
                    .with_restitution(restitution),
            ]
        }
    }
}

/// Project a box onto an axis and return the signed support distance.
fn project_box_onto_axis(
    axes: &[Vector3<f32>; 3],
    half_extents: &[f32; 3],
    direction: &Vector3<f32>,
) -> f32 {
    half_extents.iter().zip(axes.iter())
        .map(|(&h, a)| h * direction.dot(a).signum() * direction.dot(a).abs().min(h))
        .sum::<f32>()
        .max(0.0)
}

/// SAT axis classification for box-box contacts.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BoxBoxContactType {
    /// Face normal of box A (axis index 0-2) → A is reference face
    FaceA(usize),
    /// Face normal of box B (axis index 0-2) → B is reference face
    FaceB(usize),
    /// Edge cross product (`ax_a[i] x ax_b[j]`) -- edge-edge contact.
    EdgeEdge(usize, usize),
}

/// Get the 4 world-space vertices of a box face.
///
/// `axis_idx` is 0/1/2 for X/Y/Z face, `sign` is +1.0 or -1.0 for positive/negative face.
/// Vertices are ordered counter-clockwise when viewed from outside the box.
pub fn get_box_face_polygon(
    pos: Vector3<f32>,
    rot: Matrix3<f32>,
    he: Vector3<f32>,
    axis_idx: usize,
    sign: f32,
) -> [Vector3<f32>; 4] {
    let he_arr = [he.x, he.y, he.z];
    // The two tangent axes (not the face normal axis)
    let t1_idx = (axis_idx + 1) % 3;
    let t2_idx = (axis_idx + 2) % 3;

    let face_normal_dir = rot.column(axis_idx).into_owned();
    let t1_dir = rot.column(t1_idx).into_owned();
    let t2_dir = rot.column(t2_idx).into_owned();

    let center = pos + face_normal_dir * (he_arr[axis_idx] * sign);

    // CCW winding when viewed from outside (sign > 0)
    let (s1, s2) = if sign >= 0.0 { (1.0, 1.0) } else { (-1.0, 1.0) };
    let _ = s1; let _ = s2;

    [
        center - t1_dir * he_arr[t1_idx] - t2_dir * he_arr[t2_idx],
        center + t1_dir * he_arr[t1_idx] - t2_dir * he_arr[t2_idx],
        center + t1_dir * he_arr[t1_idx] + t2_dir * he_arr[t2_idx],
        center - t1_dir * he_arr[t1_idx] + t2_dir * he_arr[t2_idx],
    ]
}

/// Select the incident face of a box — the face most anti-aligned with the reference normal.
///
/// Returns `(axis_idx, sign)` where `rot.column(axis_idx) * sign` has minimum dot product
/// with `reference_normal`.
pub fn select_incident_face(
    rot: Matrix3<f32>,
    reference_normal: Vector3<f32>,
) -> (usize, f32) {
    let mut best_idx = 0;
    let mut best_sign = 1.0_f32;
    let mut best_dot = f32::MAX;

    for i in 0..3 {
        let axis = rot.column(i).into_owned();
        let d_pos = axis.dot(&reference_normal);
        let d_neg = -d_pos;

        if d_pos < best_dot {
            best_dot = d_pos;
            best_idx = i;
            best_sign = 1.0;
        }
        if d_neg < best_dot {
            best_dot = d_neg;
            best_idx = i;
            best_sign = -1.0;
        }
    }

    (best_idx, best_sign)
}

// ============================================================================
// Helpers
// ============================================================================

/// Compute an orthonormal tangent frame for a contact normal.
///
/// Returns (t1, t2) such that (t1, t2, normal) forms a right-handed frame.
/// Uses the "most different axis" method for numerical stability.
/// Public version of tangent frame computation for use by contact_jacobian.
pub fn compute_tangent_frame_pub(normal: &Vector3<f32>) -> (Vector3<f32>, Vector3<f32>) {
    compute_tangent_frame(normal)
}

fn compute_tangent_frame(normal: &Vector3<f32>) -> (Vector3<f32>, Vector3<f32>) {
    if normal.norm_squared() < 1e-12 {
        return (Vector3::x(), Vector3::y());
    }
    let n = normal.normalize();

    // Choose the axis most different from normal to avoid near-parallel cross product
    let reference = if n.x.abs() < 0.9 {
        Vector3::x()
    } else {
        Vector3::y()
    };

    let t1 = n.cross(&reference).normalize();
    let t2 = n.cross(&t1);

    (t1, t2)
}

// ============================================================================
// GJK/EPA contact detection for ConvexHull and mixed pairs
// ============================================================================

use super::gjk::{self, Support, SphereSupport, BoxSupport, ConvexHullSupport, GjkResult};

/// Contact detection via GJK/EPA for any StoredShape pair.
#[allow(clippy::too_many_arguments)]
fn gjk_contact_pair(
    shape_a: &StoredShape, pos_a: Vector3<f32>, rot_a: Matrix3<f32>,
    shape_b: &StoredShape, pos_b: Vector3<f32>, rot_b: Matrix3<f32>,
    body_id: usize, friction: f32, restitution: f32,
) -> Vec<ContactPoint> {
    let support_a = make_support(shape_a, pos_a, rot_a);
    let support_b = make_support(shape_b, pos_b, rot_b);

    match gjk::gjk_distance(support_a.as_ref(), support_b.as_ref(), 64) {
        GjkResult::Overlap { simplex } => {
            if let Some(epa) = gjk::epa_penetration(support_a.as_ref(), support_b.as_ref(), &simplex, 32) {
                if epa.depth > -0.01 {
                    let point_body = rot_a.transpose() * (epa.point_a - pos_a);
                    return vec![ContactPoint::new(
                        body_id, epa.point_a, point_body, epa.normal, epa.depth,
                    ).with_friction(friction).with_restitution(restitution)];
                }
            }
            Vec::new()
        }
        GjkResult::Separated { distance, closest_a, closest_b } => {
            // Near-contact: if distance < margin, generate predictive contact
            if distance < 0.01 {
                let normal = if distance > 1e-8 {
                    (closest_b - closest_a) / distance
                } else {
                    Vector3::y()
                };
                let point_body = rot_a.transpose() * (closest_a - pos_a);
                vec![ContactPoint::new(
                    body_id, closest_a, point_body, normal, -distance,
                ).with_friction(friction).with_restitution(restitution)]
            } else {
                Vec::new()
            }
        }
    }
}

/// Create a boxed Support for any StoredShape. No memory leaks — all data owned.
fn make_support(shape: &StoredShape, pos: Vector3<f32>, rot: Matrix3<f32>) -> Box<dyn Support> {
    match shape {
        StoredShape::Sphere { radius } => Box::new(SphereSupport { center: pos, radius: *radius }),
        StoredShape::Box { half_extents } => Box::new(BoxSupport { center: pos, rotation: rot, half_extents: *half_extents }),
        StoredShape::ConvexHull { hull } => {
            let world_verts: Vec<Vector3<f32>> = hull.vertices.iter().map(|v| pos + rot * v).collect();
            Box::new(ConvexHullSupport { vertices_world: world_verts })
        }
        StoredShape::Capsule { half_height, radius } => {
            Box::new(SphereSupport { center: pos, radius: *half_height + *radius })
        }
        StoredShape::Cylinder { half_height, radius } => {
            Box::new(SphereSupport { center: pos, radius: (*half_height * *half_height + *radius * *radius).sqrt() })
        }
        StoredShape::DecomposedMesh { hulls } => {
            if let Some(hull) = hulls.first() {
                let world_verts: Vec<Vector3<f32>> = hull.vertices.iter().map(|v| pos + rot * v).collect();
                Box::new(ConvexHullSupport { vertices_world: world_verts })
            } else {
                Box::new(SphereSupport { center: pos, radius: 0.1 })
            }
        }
    }
}

// ============================================================================
// Capsule & Cylinder contacts
// ============================================================================

/// Closest points between two line segments (for capsule-capsule).
/// Returns (t_a, t_b) parameters in [0,1] along each segment.
fn closest_points_segments(
    a0: Vector3<f32>, a1: Vector3<f32>,
    b0: Vector3<f32>, b1: Vector3<f32>,
) -> (f32, f32) {
    let d1 = a1 - a0;
    let d2 = b1 - b0;
    let r = a0 - b0;

    let a = d1.dot(&d1);
    let e = d2.dot(&d2);
    let f = d2.dot(&r);

    if a < 1e-10 && e < 1e-10 {
        return (0.0, 0.0);
    }
    if a < 1e-10 {
        return (0.0, (f / e).clamp(0.0, 1.0));
    }
    let c = d1.dot(&r);
    if e < 1e-10 {
        return ((-c / a).clamp(0.0, 1.0), 0.0);
    }

    let b = d1.dot(&d2);
    let denom = a * e - b * b;

    let mut s = if denom.abs() > 1e-10 {
        ((b * f - c * e) / denom).clamp(0.0, 1.0)
    } else {
        0.0
    };

    let mut t = (b * s + f) / e;
    if t < 0.0 {
        t = 0.0;
        s = (-c / a).clamp(0.0, 1.0);
    } else if t > 1.0 {
        t = 1.0;
        s = ((b - c) / a).clamp(0.0, 1.0);
    }

    (s, t)
}

/// Capsule-capsule contact detection.
#[allow(clippy::too_many_arguments)]
pub fn capsule_capsule_contact(
    pos_a: Vector3<f32>, rot_a: Matrix3<f32>, half_h_a: f32, radius_a: f32,
    pos_b: Vector3<f32>, rot_b: Matrix3<f32>, half_h_b: f32, radius_b: f32,
    body_id: usize, friction: f32, restitution: f32,
) -> Option<ContactPoint> {
    let axis_a = rot_a.column(1).into_owned();
    let axis_b = rot_b.column(1).into_owned();

    let a0 = pos_a - axis_a * half_h_a;
    let a1 = pos_a + axis_a * half_h_a;
    let b0 = pos_b - axis_b * half_h_b;
    let b1 = pos_b + axis_b * half_h_b;

    let (s, t) = closest_points_segments(a0, a1, b0, b1);
    let pa = a0 + (a1 - a0) * s;
    let pb = b0 + (b1 - b0) * t;

    let diff = pb - pa;
    let dist = diff.norm();
    let penetration = radius_a + radius_b - dist;

    if penetration < -0.01 { return None; }

    let normal = if dist > 1e-8 { diff / dist } else { Vector3::y() };
    let point_world = pa + normal * (radius_a - penetration * 0.5);
    let point_body = -normal * (radius_a - penetration * 0.5);

    Some(ContactPoint::new(body_id, point_world, point_body, normal, penetration)
        .with_friction(friction).with_restitution(restitution))
}

/// Capsule-sphere contact detection.
#[allow(clippy::too_many_arguments)]
pub fn capsule_sphere_contact(
    cap_pos: Vector3<f32>, cap_rot: Matrix3<f32>, half_h: f32, cap_radius: f32,
    sphere_pos: Vector3<f32>, sphere_radius: f32,
    body_id: usize, friction: f32, restitution: f32,
) -> Option<ContactPoint> {
    let axis = cap_rot.column(1).into_owned();
    let a0 = cap_pos - axis * half_h;
    let a1 = cap_pos + axis * half_h;

    // Project sphere center onto capsule segment
    let d = a1 - a0;
    let t = ((sphere_pos - a0).dot(&d) / d.dot(&d)).clamp(0.0, 1.0);
    let closest = a0 + d * t;

    let diff = sphere_pos - closest;
    let dist = diff.norm();
    let penetration = cap_radius + sphere_radius - dist;

    if penetration < -0.01 { return None; }

    let normal = if dist > 1e-8 { diff / dist } else { Vector3::y() };
    let point_world = closest + normal * (cap_radius - penetration * 0.5);
    let point_body = Vector3::zeros();

    Some(ContactPoint::new(body_id, point_world, point_body, normal, penetration)
        .with_friction(friction).with_restitution(restitution))
}

/// Capsule-box contact: closest point on capsule axis to box, then offset by radii.
#[allow(clippy::too_many_arguments)]
pub fn capsule_box_contact(
    cap_pos: Vector3<f32>, cap_rot: Matrix3<f32>, half_h: f32, cap_radius: f32,
    box_pos: Vector3<f32>, box_rot: Matrix3<f32>, box_he: Vector3<f32>,
    body_id: usize, friction: f32, restitution: f32,
) -> Vec<ContactPoint> {
    let axis = cap_rot.column(1).into_owned();
    let mut contacts = Vec::new();

    // Test both hemisphere endpoints + midpoint against box
    for &t in &[-1.0_f32, 0.0, 1.0] {
        let sphere_pos = cap_pos + axis * (half_h * t);
        if let Some(c) = sphere_box_contact(
            sphere_pos, cap_radius, box_pos, box_rot, box_he,
            body_id, friction, restitution,
        ) {
            contacts.push(c);
        }
    }
    contacts
}

// ============================================================================
// ShapePair convenience wrappers
// ============================================================================

/// Box-box contact detection using a [`ShapePair`] to group shared parameters.
///
/// Delegates to [`box_box_contacts`]; see that function for algorithm details.
pub fn box_box_contacts_from_pair(
    pair: &ShapePair,
    he_a: Vector3<f32>,
    he_b: Vector3<f32>,
) -> Vec<ContactPoint> {
    box_box_contacts(
        pair.pos_a, pair.rot_a, he_a,
        pair.pos_b, pair.rot_b, he_b,
        pair.body_id_a, pair.friction, pair.restitution,
    )
}

/// Capsule-capsule contact detection using a [`ShapePair`] to group shared parameters.
///
/// Delegates to [`capsule_capsule_contact`]; see that function for algorithm details.
pub fn capsule_capsule_contact_from_pair(
    pair: &ShapePair,
    half_h_a: f32,
    radius_a: f32,
    half_h_b: f32,
    radius_b: f32,
) -> Option<ContactPoint> {
    capsule_capsule_contact(
        pair.pos_a, pair.rot_a, half_h_a, radius_a,
        pair.pos_b, pair.rot_b, half_h_b, radius_b,
        pair.body_id_a, pair.friction, pair.restitution,
    )
}

/// Capsule-box contact detection using a [`ShapePair`] to group shared parameters.
///
/// Delegates to [`capsule_box_contact`]; see that function for algorithm details.
pub fn capsule_box_contact_from_pair(
    pair: &ShapePair,
    half_h: f32,
    cap_radius: f32,
    box_he: Vector3<f32>,
) -> Vec<ContactPoint> {
    capsule_box_contact(
        pair.pos_a, pair.rot_a, half_h, cap_radius,
        pair.pos_b, pair.rot_b, box_he,
        pair.body_id_a, pair.friction, pair.restitution,
    )
}

/// Inter-body contact detection using a [`ShapePair`] to group shared parameters.
///
/// Delegates to [`inter_body_contacts`]; see that function for algorithm details.
pub fn inter_body_contacts_from_pair(
    pair: &ShapePair,
    shape_a: &StoredShape,
    shape_b: &StoredShape,
) -> ContactManifold {
    inter_body_contacts(shape_a, shape_b, pair)
}

// ============================================================================
// Contact reduction (max-area selection)
// ============================================================================

/// Select up to `max_n` contacts that maximize the contact patch area.
///
/// Returns indices into the `contacts` slice. Greedy algorithm:
/// 1. Deepest contact (best penetration correction)
/// 2. Farthest from #1 in tangent plane
/// 3. Maximizes triangle area with #1, #2
/// 4. Maximizes quad area with #1, #2, #3
pub fn select_max_area_contacts(contacts: &[ContactPoint], max_n: usize) -> Vec<usize> {
    let n = contacts.len();
    if n <= max_n {
        return (0..n).collect();
    }
    if n == 0 || max_n == 0 {
        return Vec::new();
    }

    // Use the first contact's normal as the projection axis
    let normal = contacts[0].normal;

    // Project contact points onto tangent plane (2D coordinates)
    let (t1, t2) = compute_tangent_frame(&normal);
    let project = |p: &Vector3<f32>| -> (f32, f32) {
        (p.dot(&t1), p.dot(&t2))
    };

    let projected: Vec<(f32, f32)> = contacts.iter()
        .map(|c| project(&c.point_world))
        .collect();

    let mut selected = Vec::with_capacity(max_n);

    // Step 1: Deepest contact
    let idx0 = contacts.iter().enumerate()
        .max_by(|a, b| a.1.penetration.partial_cmp(&b.1.penetration).unwrap_or(std::cmp::Ordering::Equal))
        .map(|(i, _)| i)
        .unwrap_or(0);
    selected.push(idx0);

    if max_n == 1 { return selected; }

    // Step 2: Farthest from #1
    let (px0, py0) = projected[idx0];
    let idx1 = (0..n)
        .filter(|i| !selected.contains(i))
        .max_by(|&a, &b| {
            let da = (projected[a].0 - px0).powi(2) + (projected[a].1 - py0).powi(2);
            let db = (projected[b].0 - px0).powi(2) + (projected[b].1 - py0).powi(2);
            da.partial_cmp(&db).unwrap_or(std::cmp::Ordering::Equal)
        })
        .unwrap_or(0);
    selected.push(idx1);

    if max_n == 2 { return selected; }

    // Step 3: Maximizes triangle area with #1, #2
    let (px1, py1) = projected[idx1];
    let idx2 = (0..n)
        .filter(|i| !selected.contains(i))
        .max_by(|&a, &b| {
            let area_a = triangle_area_2d(px0, py0, px1, py1, projected[a].0, projected[a].1);
            let area_b = triangle_area_2d(px0, py0, px1, py1, projected[b].0, projected[b].1);
            area_a.partial_cmp(&area_b).unwrap_or(std::cmp::Ordering::Equal)
        })
        .unwrap_or(0);
    selected.push(idx2);

    if max_n == 3 { return selected; }

    // Step 4+: Maximize area incrementally
    for _ in 3..max_n {
        let best = (0..n)
            .filter(|i| !selected.contains(i))
            .max_by(|&a, &b| {
                let area_a = polygon_area_with_point(&projected, &selected, projected[a]);
                let area_b = polygon_area_with_point(&projected, &selected, projected[b]);
                area_a.partial_cmp(&area_b).unwrap_or(std::cmp::Ordering::Equal)
            });
        if let Some(idx) = best {
            selected.push(idx);
        } else {
            break;
        }
    }

    selected
}

/// Signed area of a 2D triangle (absolute value).
fn triangle_area_2d(x0: f32, y0: f32, x1: f32, y1: f32, x2: f32, y2: f32) -> f32 {
    ((x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0)).abs() * 0.5
}

/// Area of a polygon formed by existing selected points plus a candidate point.
fn polygon_area_with_point(
    projected: &[(f32, f32)],
    selected: &[usize],
    candidate: (f32, f32),
) -> f32 {
    // Sum triangle areas from the first selected point to all edges
    let mut total = 0.0_f32;
    let n = selected.len();
    if n < 2 { return 0.0; }

    let (cx, cy) = candidate;
    for i in 0..n {
        let (ax, ay) = projected[selected[i]];
        let (bx, by) = projected[selected[(i + 1) % n]];
        total += triangle_area_2d(cx, cy, ax, ay, bx, by);
    }
    total
}

// ============================================================================
// Polygon clipping (Sutherland-Hodgman)
// ============================================================================

/// Epsilon for polygon clipping vertex classification.
const CLIP_EPSILON: f32 = 1e-7;

/// Clip a convex polygon against a single half-plane.
///
/// Keeps the portion of the polygon on the *positive* side of the plane
/// (where `dot(vertex, plane_normal) >= plane_offset`).
///
/// Uses the Sutherland-Hodgman edge-walking algorithm:
/// - inside→inside: keep end vertex
/// - inside→outside: emit intersection
/// - outside→inside: emit intersection + end vertex
/// - outside→outside: emit nothing
pub fn clip_polygon_by_plane(
    polygon: &[Vector3<f32>],
    plane_normal: Vector3<f32>,
    plane_offset: f32,
) -> Vec<Vector3<f32>> {
    if polygon.is_empty() {
        return Vec::new();
    }

    let n = polygon.len();
    let mut output = Vec::with_capacity(n + 1);

    for i in 0..n {
        let current = polygon[i];
        let next = polygon[(i + 1) % n];

        let d_current = plane_normal.dot(&current) - plane_offset;
        let d_next = plane_normal.dot(&next) - plane_offset;

        let current_inside = d_current >= -CLIP_EPSILON;
        let next_inside = d_next >= -CLIP_EPSILON;

        if current_inside && next_inside {
            // Both inside: keep end vertex
            output.push(next);
        } else if current_inside && !next_inside {
            // Going out: emit intersection
            let t = d_current / (d_current - d_next);
            let intersection = current + (next - current) * t.clamp(0.0, 1.0);
            output.push(intersection);
        } else if !current_inside && next_inside {
            // Coming in: emit intersection + end vertex
            let t = d_current / (d_current - d_next);
            let intersection = current + (next - current) * t.clamp(0.0, 1.0);
            output.push(intersection);
            output.push(next);
        }
        // outside→outside: emit nothing
    }

    output
}

/// Clip a convex polygon against multiple half-planes (Sutherland-Hodgman).
///
/// Each plane is `(normal, offset)` — keeps the side where `dot(v, normal) >= offset`.
/// Iteratively clips against each plane in sequence.
pub fn sutherland_hodgman_clip(
    polygon: &[Vector3<f32>],
    clip_planes: &[(Vector3<f32>, f32)],
) -> Vec<Vector3<f32>> {
    let mut current = polygon.to_vec();

    for &(normal, offset) in clip_planes {
        if current.is_empty() {
            break;
        }
        current = clip_polygon_by_plane(&current, normal, offset);
    }

    current
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use super::super::collider::ColliderShape as StoredShape;
    use super::super::body::{ArticulatedBody, GenJointType};
    use super::super::spatial::{SpatialInertia, SpatialTransform};
    use approx::assert_relative_eq;
    use nalgebra::Matrix3;

    fn make_inertia(mass: f32) -> SpatialInertia {
        SpatialInertia::from_mass_inertia_at_com(mass, Matrix3::identity() * 0.01 * mass)
    }

    #[test]
    fn test_contact_point_creation() {
        let cp = ContactPoint::new(
            0,
            Vector3::new(1.0, 0.0, 0.0),
            Vector3::zeros(),
            Vector3::y(),
            0.001,
        );

        assert_eq!(cp.body_id, 0);
        assert!(cp.is_active());
        assert_relative_eq!(cp.friction, 0.5);
        assert_relative_eq!(cp.restitution, 0.0);
    }

    #[test]
    fn test_contact_point_inactive() {
        let cp = ContactPoint::new(
            0,
            Vector3::zeros(),
            Vector3::zeros(),
            Vector3::y(),
            -0.01,
        );
        assert!(!cp.is_active());
    }

    #[test]
    fn test_contact_point_with_material() {
        let cp = ContactPoint::new(
            0,
            Vector3::zeros(),
            Vector3::zeros(),
            Vector3::y(),
            0.001,
        )
        .with_friction(0.8)
        .with_restitution(0.3);

        assert_relative_eq!(cp.friction, 0.8);
        assert_relative_eq!(cp.restitution, 0.3);
    }

    #[test]
    fn test_tangent_frame_orthonormal() {
        let normals = [
            Vector3::y(),
            Vector3::x(),
            Vector3::z(),
            Vector3::new(1.0, 1.0, 1.0).normalize(),
            Vector3::new(-0.3, 0.9, 0.2).normalize(),
        ];

        for normal in &normals {
            let (t1, t2) = compute_tangent_frame(normal);

            // Orthogonality
            assert_relative_eq!(t1.dot(normal), 0.0, epsilon = 1e-5);
            assert_relative_eq!(t2.dot(normal), 0.0, epsilon = 1e-5);
            assert_relative_eq!(t1.dot(&t2), 0.0, epsilon = 1e-5);

            // Unit length
            assert_relative_eq!(t1.norm(), 1.0, epsilon = 1e-5);
            assert_relative_eq!(t2.norm(), 1.0, epsilon = 1e-5);
        }
    }

    #[test]
    fn test_manifold_operations() {
        let mut manifold = ContactManifold::new();
        assert!(manifold.is_empty());
        assert_eq!(manifold.len(), 0);

        manifold.add_contact(ContactPoint::new(
            0, Vector3::zeros(), Vector3::zeros(), Vector3::y(), 0.01,
        ));
        manifold.add_contact(ContactPoint::new(
            1, Vector3::zeros(), Vector3::zeros(), Vector3::y(), -0.01,
        ));
        manifold.add_contact(ContactPoint::new(
            0, Vector3::x(), Vector3::zeros(), Vector3::y(), 0.005,
        ));

        assert_eq!(manifold.len(), 3);
        assert_eq!(manifold.active_count(), 2);
        assert_eq!(manifold.contacts_for_body(0).count(), 2);
        assert_eq!(manifold.contacts_for_body(1).count(), 1);
    }

    #[test]
    fn test_manifold_prune() {
        let mut manifold = ContactManifold::new();
        manifold.add_contact(ContactPoint::new(
            0, Vector3::zeros(), Vector3::zeros(), Vector3::y(), 0.01,
        ));
        manifold.add_contact(ContactPoint::new(
            1, Vector3::zeros(), Vector3::zeros(), Vector3::y(), -0.01,
        ));

        manifold.prune_separated(0.0);
        assert_eq!(manifold.len(), 1);
        assert_eq!(manifold.contacts[0].body_id, 0);
    }

    #[test]
    fn test_manifold_limit_per_body() {
        let mut manifold = ContactManifold::new();
        for j in 0..5 {
            manifold.add_contact(ContactPoint::new(
                0,
                Vector3::new(j as f32, 0.0, 0.0),
                Vector3::zeros(),
                Vector3::y(),
                0.001 * (j + 1) as f32,
            ));
        }
        manifold.add_contact(ContactPoint::new(
            1, Vector3::zeros(), Vector3::zeros(), Vector3::y(), 0.01,
        ));

        manifold.limit_per_body(2);
        // Body 0: keep 2 deepest, body 1: keep 1
        assert_eq!(manifold.contacts_for_body(0).count(), 2);
        assert_eq!(manifold.contacts_for_body(1).count(), 1);
    }

    #[test]
    fn test_manifold_merge() {
        let mut m1 = ContactManifold::new();
        m1.add_contact(ContactPoint::new(
            0, Vector3::zeros(), Vector3::zeros(), Vector3::y(), 0.01,
        ));

        let mut m2 = ContactManifold::new();
        m2.add_contact(ContactPoint::new(
            1, Vector3::zeros(), Vector3::zeros(), Vector3::y(), 0.02,
        ));

        m1.merge(&m2);
        assert_eq!(m1.len(), 2);
    }

    #[test]
    fn test_ground_plane_contacts() {
        let mut body = ArticulatedBody::new();
        body.set_gravity(Vector3::new(0.0, -9.81, 0.0));

        // Pendulum hanging down — body origin at world origin
        body.add_body(
            "link",
            -1,
            GenJointType::Revolute { axis: Vector3::z() },
            make_inertia(1.0),
            SpatialTransform::identity(),
        );

        // Ground at y = -0.1 with normal pointing up
        let manifold = ground_plane_contacts(
            &body, -0.1, Vector3::y(), 0.5, 0.0,
        );

        // Body origin at (0, 0, 0), ground at y=-0.1
        // signed_dist = y - (-0.1) = 0.1, penetration = -0.1
        // Since -0.1 > -0.01 is false, no contact
        assert_eq!(manifold.active_count(), 0);

        // Ground at y = 0.05 — body is below ground
        let manifold = ground_plane_contacts(
            &body, 0.05, Vector3::y(), 0.5, 0.0,
        );
        assert!(manifold.active_count() > 0);
        assert!(manifold.contacts[0].penetration > 0.0);
    }

    #[test]
    fn test_sphere_ground_contacts() {
        let mut body = ArticulatedBody::new();
        body.add_body(
            "link",
            -1,
            GenJointType::Fixed,
            make_inertia(1.0),
            SpatialTransform::from_translation(Vector3::new(0.0, 0.1, 0.0)),
        );

        let radii = [0.05];
        // Body center at y=0.1, radius=0.05, ground at y=0
        // center_dist = 0.1, penetration = 0.05 - 0.1 = -0.05 → no active contact
        let manifold = sphere_ground_contacts(
            &body, &radii, 0.0, Vector3::y(), 0.5, 0.0,
        );
        assert_eq!(manifold.active_count(), 0);

        // Ground at y=0.08 → center_dist = 0.02, penetration = 0.05 - 0.02 = 0.03
        let manifold = sphere_ground_contacts(
            &body, &radii, 0.08, Vector3::y(), 0.5, 0.0,
        );
        assert_eq!(manifold.active_count(), 1);
        assert_relative_eq!(manifold.contacts[0].penetration, 0.03, epsilon = 1e-4);
    }

    #[test]
    fn test_sort_by_penetration() {
        let mut manifold = ContactManifold::new();
        manifold.add_contact(ContactPoint::new(
            0, Vector3::zeros(), Vector3::zeros(), Vector3::y(), 0.001,
        ));
        manifold.add_contact(ContactPoint::new(
            1, Vector3::zeros(), Vector3::zeros(), Vector3::y(), 0.01,
        ));
        manifold.add_contact(ContactPoint::new(
            2, Vector3::zeros(), Vector3::zeros(), Vector3::y(), 0.005,
        ));

        manifold.sort_by_penetration();

        assert_eq!(manifold.contacts[0].body_id, 1); // deepest
        assert_eq!(manifold.contacts[1].body_id, 2);
        assert_eq!(manifold.contacts[2].body_id, 0); // shallowest
    }

    // ==========================================================================
    // Inter-body contact tests
    // ==========================================================================

    #[test]
    fn test_sphere_sphere_contact() {
        // Two spheres overlapping: radius 0.5 each, centers 0.8 apart
        let c = sphere_sphere_contact(
            Vector3::new(0.0, 0.0, 0.0), 0.5,
            Vector3::new(0.8, 0.0, 0.0), 0.5,
            0, 0.5, 0.0,
        );
        assert!(c.is_some());
        let c = c.unwrap();
        assert_relative_eq!(c.penetration, 0.2, epsilon = 1e-5);
        // Normal should point from A to B (positive x)
        assert!(c.normal.x > 0.9);
    }

    #[test]
    fn test_sphere_sphere_separated() {
        // Two spheres far apart: radius 0.5 each, centers 2.0 apart
        let c = sphere_sphere_contact(
            Vector3::new(0.0, 0.0, 0.0), 0.5,
            Vector3::new(2.0, 0.0, 0.0), 0.5,
            0, 0.5, 0.0,
        );
        assert!(c.is_none());
    }

    #[test]
    fn test_sphere_sphere_touching() {
        // Exactly touching: radius 0.5 each, centers 1.0 apart
        let c = sphere_sphere_contact(
            Vector3::zeros(), 0.5,
            Vector3::new(1.0, 0.0, 0.0), 0.5,
            0, 0.5, 0.0,
        );
        assert!(c.is_some());
        let c = c.unwrap();
        assert_relative_eq!(c.penetration, 0.0, epsilon = 1e-5);
    }

    #[test]
    fn test_sphere_box_contact_face() {
        // Sphere above a box, touching the top face
        let c = sphere_box_contact(
            Vector3::new(0.0, 0.55, 0.0), 0.1, // sphere at y=0.55, r=0.1
            Vector3::zeros(), Matrix3::identity(), // box at origin, axis-aligned
            Vector3::new(0.5, 0.5, 0.5), // half-extents 0.5
            0, 0.5, 0.0,
        );
        assert!(c.is_some());
        let c = c.unwrap();
        // Penetration: sphere surface at y=0.45, box top at y=0.5 → pen = 0.05
        assert_relative_eq!(c.penetration, 0.05, epsilon = 1e-4);
        // Normal should point from sphere toward box (negative y — pushing sphere up)
        assert!(c.normal.y > 0.9, "normal.y = {}", c.normal.y);
    }

    #[test]
    fn test_sphere_box_separated() {
        // Sphere well above the box
        let c = sphere_box_contact(
            Vector3::new(0.0, 1.0, 0.0), 0.1,
            Vector3::zeros(), Matrix3::identity(),
            Vector3::new(0.5, 0.5, 0.5),
            0, 0.5, 0.0,
        );
        assert!(c.is_none());
    }

    #[test]
    fn test_box_box_contact() {
        // Two axis-aligned boxes overlapping
        let contacts = box_box_contacts(
            Vector3::new(0.0, 0.0, 0.0), Matrix3::identity(), Vector3::new(0.5, 0.5, 0.5),
            Vector3::new(0.9, 0.0, 0.0), Matrix3::identity(), Vector3::new(0.5, 0.5, 0.5),
            0, 0.5, 0.0,
        );
        assert!(!contacts.is_empty());
        let c = &contacts[0];
        assert_relative_eq!(c.penetration, 0.1, epsilon = 1e-4);
        // Normal should point from A to B (positive x)
        assert!(c.normal.x > 0.9, "normal.x = {}", c.normal.x);
    }

    #[test]
    fn test_box_box_separated() {
        // Two boxes far apart
        let contacts = box_box_contacts(
            Vector3::zeros(), Matrix3::identity(), Vector3::new(0.5, 0.5, 0.5),
            Vector3::new(3.0, 0.0, 0.0), Matrix3::identity(), Vector3::new(0.5, 0.5, 0.5),
            0, 0.5, 0.0,
        );
        assert!(contacts.is_empty());
    }

    #[test]
    fn test_inter_body_contacts_dispatch() {
        // Verify inter_body_contacts dispatches correctly
        let shape_s = StoredShape::Sphere { radius: 0.3 };
        let shape_b = StoredShape::Box { half_extents: Vector3::new(0.5, 0.5, 0.5) };

        // Sphere-sphere
        let pair = ShapePair {
            pos_a: Vector3::zeros(), rot_a: Matrix3::identity(),
            pos_b: Vector3::new(0.4, 0.0, 0.0), rot_b: Matrix3::identity(),
            body_id_a: 0, body_id_b: 1, friction: 0.5, restitution: 0.0,
        };
        let m = inter_body_contacts(&shape_s, &shape_s, &pair);
        assert!(!m.is_empty());

        // Sphere-box
        let pair = ShapePair {
            pos_a: Vector3::new(0.0, 0.75, 0.0), rot_a: Matrix3::identity(),
            pos_b: Vector3::zeros(), rot_b: Matrix3::identity(),
            body_id_a: 0, body_id_b: 1, friction: 0.5, restitution: 0.0,
        };
        let m = inter_body_contacts(&shape_s, &shape_b, &pair);
        assert!(!m.is_empty());

        // Box-sphere (reversed)
        let pair = ShapePair {
            pos_a: Vector3::zeros(), rot_a: Matrix3::identity(),
            pos_b: Vector3::new(0.0, 0.75, 0.0), rot_b: Matrix3::identity(),
            body_id_a: 0, body_id_b: 1, friction: 0.5, restitution: 0.0,
        };
        let m = inter_body_contacts(&shape_b, &shape_s, &pair);
        assert!(!m.is_empty());
    }

    // ==========================================================================
    // Polygon clipping tests
    // ==========================================================================

    #[test]
    fn test_clip_polygon_no_clip() {
        // Square fully on positive side of plane → unchanged
        let square = vec![
            Vector3::new(0.0, 0.0, 0.0),
            Vector3::new(1.0, 0.0, 0.0),
            Vector3::new(1.0, 1.0, 0.0),
            Vector3::new(0.0, 1.0, 0.0),
        ];
        let result = clip_polygon_by_plane(&square, Vector3::x(), -1.0);
        assert_eq!(result.len(), 4);
    }

    #[test]
    fn test_clip_polygon_full_clip() {
        // Square fully on negative side of plane → empty
        let square = vec![
            Vector3::new(0.0, 0.0, 0.0),
            Vector3::new(1.0, 0.0, 0.0),
            Vector3::new(1.0, 1.0, 0.0),
            Vector3::new(0.0, 1.0, 0.0),
        ];
        let result = clip_polygon_by_plane(&square, Vector3::x(), 5.0);
        assert!(result.is_empty());
    }

    #[test]
    fn test_clip_polygon_half_clip() {
        // Square [0,1]x[0,1] clipped by x >= 0.5 → right half (4 vertices)
        let square = vec![
            Vector3::new(0.0, 0.0, 0.0),
            Vector3::new(1.0, 0.0, 0.0),
            Vector3::new(1.0, 1.0, 0.0),
            Vector3::new(0.0, 1.0, 0.0),
        ];
        let result = clip_polygon_by_plane(&square, Vector3::x(), 0.5);
        assert_eq!(result.len(), 4);
        // All resulting vertices should have x >= 0.5
        for v in &result {
            assert!(v.x >= 0.5 - 1e-5, "x={}", v.x);
        }
    }

    #[test]
    fn test_sutherland_hodgman_clip_quad_against_quad() {
        // Clip a 2x2 square centered at origin against a 1x1 square's side planes
        let big_square = vec![
            Vector3::new(-1.0, -1.0, 0.0),
            Vector3::new(1.0, -1.0, 0.0),
            Vector3::new(1.0, 1.0, 0.0),
            Vector3::new(-1.0, 1.0, 0.0),
        ];
        let clip_planes = vec![
            (Vector3::x(), -0.5),   // x >= -0.5
            (-Vector3::x(), -0.5),  // x <= 0.5 (i.e., -x >= -0.5)
            (Vector3::y(), -0.5),   // y >= -0.5
            (-Vector3::y(), -0.5),  // y <= 0.5
        ];
        let result = sutherland_hodgman_clip(&big_square, &clip_planes);
        assert_eq!(result.len(), 4);
        for v in &result {
            assert!(v.x >= -0.5 - 1e-5 && v.x <= 0.5 + 1e-5, "x={}", v.x);
            assert!(v.y >= -0.5 - 1e-5 && v.y <= 0.5 + 1e-5, "y={}", v.y);
        }
    }

    #[test]
    fn test_clip_degenerate_empty() {
        let result = clip_polygon_by_plane(&[], Vector3::x(), 0.0);
        assert!(result.is_empty());

        let result = sutherland_hodgman_clip(&[], &[(Vector3::x(), 0.0)]);
        assert!(result.is_empty());
    }

    #[test]
    fn test_clip_numerical_stability() {
        // Edge nearly parallel to clip plane (within epsilon)
        let polygon = vec![
            Vector3::new(0.0, 0.0, 0.0),
            Vector3::new(1.0, 1e-8, 0.0),
            Vector3::new(1.0, 1.0, 0.0),
            Vector3::new(0.0, 1.0, 0.0),
        ];
        // Clip at y >= 0.0 — bottom edge is nearly on the plane
        let result = clip_polygon_by_plane(&polygon, Vector3::y(), 0.0);
        // Should not panic or produce NaN
        assert!(!result.is_empty());
        for v in &result {
            assert!(v.x.is_finite() && v.y.is_finite() && v.z.is_finite());
        }
    }

    // ==========================================================================
    // Contact reduction tests
    // ==========================================================================

    #[test]
    fn test_reduce_fewer_than_max() {
        let mut manifold = ContactManifold::new();
        for i in 0..3 {
            manifold.add_contact(ContactPoint::new(
                0, Vector3::new(i as f32, 0.0, 0.0), Vector3::zeros(), Vector3::y(), 0.01,
            ));
        }
        manifold.reduce_to_best_n(4);
        assert_eq!(manifold.len(), 3); // No reduction needed
    }

    #[test]
    fn test_reduce_preserves_deepest() {
        let mut manifold = ContactManifold::new();
        // 6 contacts, one very deep
        for i in 0..6 {
            let pen = if i == 3 { 0.1 } else { 0.001 };
            manifold.add_contact(ContactPoint::new(
                0, Vector3::new(i as f32 * 0.1, 0.0, 0.0), Vector3::zeros(),
                Vector3::y(), pen,
            ));
        }
        manifold.reduce_to_best_n(4);
        assert_eq!(manifold.len(), 4);
        // Deepest contact (pen=0.1) must be in result
        assert!(manifold.contacts.iter().any(|c| (c.penetration - 0.1).abs() < 1e-5));
    }

    #[test]
    fn test_reduce_square_patch() {
        let mut manifold = ContactManifold::new();
        // 4 corners of a square + 4 midpoints
        let corners = [
            Vector3::new(-0.5, 0.0, -0.5),
            Vector3::new(0.5, 0.0, -0.5),
            Vector3::new(0.5, 0.0, 0.5),
            Vector3::new(-0.5, 0.0, 0.5),
        ];
        let mids = [
            Vector3::new(0.0, 0.0, -0.5),
            Vector3::new(0.5, 0.0, 0.0),
            Vector3::new(0.0, 0.0, 0.5),
            Vector3::new(-0.5, 0.0, 0.0),
        ];
        for &p in corners.iter().chain(mids.iter()) {
            manifold.add_contact(ContactPoint::new(
                0, p, Vector3::zeros(), Vector3::y(), 0.01,
            ));
        }
        manifold.reduce_to_best_n(4);
        assert_eq!(manifold.len(), 4);
        // Result should maximize area — corners should be selected (area=1.0)
        // vs midpoints which form a smaller diamond (area=0.5)
    }

    #[test]
    fn test_select_max_area_indices() {
        let contacts: Vec<ContactPoint> = (0..6).map(|i| {
            ContactPoint::new(
                0, Vector3::new(i as f32 * 0.2, 0.0, (i % 2) as f32 * 0.5),
                Vector3::zeros(), Vector3::y(), 0.01,
            )
        }).collect();
        let indices = select_max_area_contacts(&contacts, 4);
        assert_eq!(indices.len(), 4);
        // All indices should be valid
        for &idx in &indices {
            assert!(idx < 6);
        }
        // No duplicates
        let unique: std::collections::HashSet<_> = indices.iter().collect();
        assert_eq!(unique.len(), 4);
    }

    // ======================================================================
    // Capsule contact geometry tests
    // ======================================================================

    #[test]
    fn test_capsule_capsule_aligned_overlapping() {
        // Two upright capsules side by side, overlapping
        let c = capsule_capsule_contact(
            Vector3::new(0.0, 0.0, 0.0), Matrix3::identity(), 0.5, 0.1,
            Vector3::new(0.15, 0.0, 0.0), Matrix3::identity(), 0.5, 0.1,
            0, 0.5, 0.0,
        );
        assert!(c.is_some(), "Overlapping capsules should produce contact");
        let c = c.unwrap();
        assert!(c.penetration > 0.0, "Penetration should be positive");
        // Normal should point from A to B (positive x)
        assert!(c.normal.x > 0.5, "Normal should point along x: {:?}", c.normal);
    }

    #[test]
    fn test_capsule_capsule_separated() {
        let c = capsule_capsule_contact(
            Vector3::zeros(), Matrix3::identity(), 0.5, 0.1,
            Vector3::new(5.0, 0.0, 0.0), Matrix3::identity(), 0.5, 0.1,
            0, 0.5, 0.0,
        );
        assert!(c.is_none(), "Far-apart capsules should produce no contact");
    }

    #[test]
    fn test_capsule_sphere_contact_touching() {
        // Sphere beside capsule
        let c = capsule_sphere_contact(
            Vector3::zeros(), Matrix3::identity(), 0.5, 0.1,
            Vector3::new(0.15, 0.0, 0.0), 0.1,
            0, 0.5, 0.0,
        );
        assert!(c.is_some(), "Touching capsule-sphere should produce contact");
        let c = c.unwrap();
        assert!(c.penetration > 0.0);
    }

    #[test]
    fn test_capsule_sphere_at_endpoint() {
        // Sphere at the top endpoint of capsule
        let c = capsule_sphere_contact(
            Vector3::zeros(), Matrix3::identity(), 0.5, 0.1,
            Vector3::new(0.0, 0.55, 0.0), 0.1, // just above top hemisphere
            0, 0.5, 0.0,
        );
        assert!(c.is_some(), "Sphere at capsule endpoint should produce contact");
        let c = c.unwrap();
        assert!(c.penetration > 0.0);
        // Normal should point upward (from capsule to sphere)
        assert!(c.normal.y > 0.5, "Normal should point up: {:?}", c.normal);
    }

    #[test]
    fn test_sphere_box_inside_box() {
        // Sphere center is inside the box - should still produce valid contact
        let c = sphere_box_contact(
            Vector3::new(0.0, 0.0, 0.0), 0.1, // sphere at box center
            Vector3::zeros(), Matrix3::identity(),
            Vector3::new(0.5, 0.5, 0.5),
            0, 0.5, 0.0,
        );
        assert!(c.is_some(), "Sphere inside box should produce contact");
        let c = c.unwrap();
        assert!(c.penetration > 0.0, "Penetration should be positive");
        // Normal should push toward closest face
        let n_abs = Vector3::new(c.normal.x.abs(), c.normal.y.abs(), c.normal.z.abs());
        let max_component = n_abs.x.max(n_abs.y).max(n_abs.z);
        assert!(max_component > 0.9, "Normal should be axis-aligned for centered sphere");
    }

    #[test]
    fn test_sphere_sphere_coincident_centers() {
        // Degenerate case: sphere centers at same position
        let c = sphere_sphere_contact(
            Vector3::zeros(), 0.5,
            Vector3::zeros(), 0.5,
            0, 0.5, 0.0,
        );
        assert!(c.is_some(), "Coincident spheres should produce contact");
        let c = c.unwrap();
        assert_relative_eq!(c.penetration, 1.0, epsilon = 1e-5); // ra + rb - 0
        // Normal should default to y-up for degenerate case
        assert_relative_eq!(c.normal.y, 1.0, epsilon = 1e-5);
    }

    #[test]
    fn test_contact_normal_always_normalized() {
        // Intent: all contact functions should return unit normals
        let test_cases: Vec<Option<ContactPoint>> = vec![
            sphere_sphere_contact(
                Vector3::zeros(), 0.5,
                Vector3::new(0.8, 0.0, 0.0), 0.5,
                0, 0.5, 0.0,
            ),
            sphere_box_contact(
                Vector3::new(0.0, 0.55, 0.0), 0.1,
                Vector3::zeros(), Matrix3::identity(),
                Vector3::new(0.5, 0.5, 0.5),
                0, 0.5, 0.0,
            ),
            capsule_sphere_contact(
                Vector3::zeros(), Matrix3::identity(), 0.5, 0.1,
                Vector3::new(0.15, 0.0, 0.0), 0.1,
                0, 0.5, 0.0,
            ),
        ];

        for (i, case) in test_cases.into_iter().enumerate() {
            if let Some(c) = case {
                let norm = c.normal.norm();
                assert!(
                    (norm - 1.0).abs() < 1e-4,
                    "Contact {i} normal should be unit length, got {norm}"
                );
            }
        }
    }

    #[test]
    fn test_inter_body_capsule_dispatch() {
        // Verify inter_body_contacts dispatches capsule-capsule
        let shape_c = StoredShape::Capsule { half_height: 0.5, radius: 0.1 };
        let pair = ShapePair {
            pos_a: Vector3::zeros(), rot_a: Matrix3::identity(),
            pos_b: Vector3::new(0.15, 0.0, 0.0), rot_b: Matrix3::identity(),
            body_id_a: 0, body_id_b: 1, friction: 0.5, restitution: 0.0,
        };
        let m = inter_body_contacts(&shape_c, &shape_c, &pair);
        assert!(!m.is_empty(), "Capsule-capsule dispatch should find contact");
    }

    #[test]
    fn test_contact_zero_normal_fallback() {
        // Intent: zero-length normal should fallback to z-axis, not NaN
        let cp = ContactPoint::new(
            0,
            Vector3::zeros(),
            Vector3::zeros(),
            Vector3::zeros(), // zero normal!
            0.01,
        );
        let norm = cp.normal.norm();
        assert!(
            (norm - 1.0).abs() < 1e-5,
            "Zero normal should be replaced with fallback, got norm={norm}"
        );
    }

    // ====================================================================
    // Builder chaining tests
    // ====================================================================

    #[test]
    fn test_with_friction_and_restitution_chaining() {
        let cp = ContactPoint::new(0, Vector3::zeros(), Vector3::zeros(), Vector3::y(), 0.01)
            .with_friction(0.8)
            .with_restitution(0.6);
        assert_relative_eq!(cp.friction, 0.8, epsilon = 1e-10);
        assert_relative_eq!(cp.restitution, 0.6, epsilon = 1e-10);
        // Other fields unchanged
        assert_relative_eq!(cp.penetration, 0.01, epsilon = 1e-10);
    }

    // ====================================================================
    // Box face polygon tests
    // ====================================================================

    #[test]
    fn test_get_box_face_polygon_identity_z_positive() {
        let poly = get_box_face_polygon(
            Vector3::zeros(), Matrix3::identity(), Vector3::new(1.0, 1.0, 1.0),
            2, 1.0, // Z-axis, positive face
        );
        // All 4 vertices should have z = 1.0 (the +Z face)
        for (i, v) in poly.iter().enumerate() {
            assert!((v.z - 1.0).abs() < 1e-5,
                "vertex {i} should be on z=1 face, got z={}", v.z);
        }
        // Vertices should span the face: x in [-1,1], y in [-1,1]
        let xs: Vec<f32> = poly.iter().map(|v| v.x).collect();
        let ys: Vec<f32> = poly.iter().map(|v| v.y).collect();
        assert!(xs.iter().any(|&x| x < -0.5), "should have x < -0.5");
        assert!(xs.iter().any(|&x| x > 0.5), "should have x > 0.5");
        assert!(ys.iter().any(|&y| y < -0.5), "should have y < -0.5");
        assert!(ys.iter().any(|&y| y > 0.5), "should have y > 0.5");
    }

    #[test]
    fn test_get_box_face_polygon_negative_face() {
        let poly = get_box_face_polygon(
            Vector3::zeros(), Matrix3::identity(), Vector3::new(2.0, 3.0, 4.0),
            1, -1.0, // Y-axis, negative face → y = -3
        );
        for (i, v) in poly.iter().enumerate() {
            assert!((v.y - (-3.0)).abs() < 1e-5,
                "vertex {i} should be on y=-3 face, got y={}", v.y);
        }
    }

    // ====================================================================
    // Select incident face tests
    // ====================================================================

    #[test]
    fn test_select_incident_face_aligned_with_y() {
        // Reference normal pointing +Y → incident face is the -Y face
        let (idx, sign) = select_incident_face(Matrix3::identity(), Vector3::y());
        assert_eq!(idx, 1, "should select Y axis");
        assert!((sign - (-1.0)).abs() < 1e-5,
            "should pick negative Y face (most anti-aligned), got sign={sign}");
    }

    #[test]
    fn test_select_incident_face_aligned_with_neg_x() {
        let (idx, sign) = select_incident_face(Matrix3::identity(), -Vector3::x());
        assert_eq!(idx, 0, "should select X axis");
        assert!((sign - 1.0).abs() < 1e-5,
            "should pick positive X face (anti-aligned with -X normal), got sign={sign}");
    }

    // ====================================================================
    // Tangent frame tests
    // ====================================================================

    #[test]
    fn test_compute_tangent_frame_orthonormal() {
        for normal in &[Vector3::x(), Vector3::y(), Vector3::z(),
                        Vector3::new(1.0, 1.0, 1.0).normalize()] {
            let (t1, t2) = compute_tangent_frame_pub(normal);
            // Orthogonality
            assert!(t1.dot(normal).abs() < 1e-5, "t1 should be perpendicular to normal");
            assert!(t2.dot(normal).abs() < 1e-5, "t2 should be perpendicular to normal");
            assert!(t1.dot(&t2).abs() < 1e-5, "t1 should be perpendicular to t2");
            // Unit length
            assert_relative_eq!(t1.norm(), 1.0, epsilon = 1e-5);
            assert_relative_eq!(t2.norm(), 1.0, epsilon = 1e-5);
        }
    }

    // ====================================================================
    // ShapePair / from_pair dispatch tests
    // ====================================================================

    #[test]
    fn test_box_box_contacts_from_pair_overlapping() {
        let pair = ShapePair {
            pos_a: Vector3::new(0.0, 0.0, 0.0),
            rot_a: Matrix3::identity(),
            pos_b: Vector3::new(0.9, 0.0, 0.0), // overlapping by 0.1
            rot_b: Matrix3::identity(),
            body_id_a: 0,
            body_id_b: 1,
            friction: 0.4,
            restitution: 0.2,
        };
        let contacts = box_box_contacts_from_pair(&pair,
            Vector3::new(0.5, 0.5, 0.5), Vector3::new(0.5, 0.5, 0.5));
        // Should detect contact
        assert!(!contacts.is_empty(), "overlapping boxes should produce contacts");
        // Friction/restitution should come from pair
        assert_relative_eq!(contacts[0].friction, 0.4, epsilon = 1e-5);
        assert_relative_eq!(contacts[0].restitution, 0.2, epsilon = 1e-5);
    }

    #[test]
    fn test_capsule_capsule_from_pair_overlapping() {
        let pair = ShapePair {
            pos_a: Vector3::zeros(),
            rot_a: Matrix3::identity(),
            pos_b: Vector3::new(0.15, 0.0, 0.0), // close together
            rot_b: Matrix3::identity(),
            body_id_a: 0,
            body_id_b: 1,
            friction: 0.3,
            restitution: 0.1,
        };
        let result = capsule_capsule_contact_from_pair(&pair, 0.5, 0.1, 0.5, 0.1);
        assert!(result.is_some(), "close capsules should produce contact");
        let cp = result.unwrap();
        assert_relative_eq!(cp.friction, 0.3, epsilon = 1e-5);
    }

    #[test]
    fn test_inter_body_contacts_from_pair_spheres() {
        let pair = ShapePair {
            pos_a: Vector3::zeros(),
            rot_a: Matrix3::identity(),
            pos_b: Vector3::new(0.15, 0.0, 0.0),
            rot_b: Matrix3::identity(),
            body_id_a: 0,
            body_id_b: 1,
            friction: 0.5,
            restitution: 0.0,
        };
        let shape_a = StoredShape::Sphere { radius: 0.1 };
        let shape_b = StoredShape::Sphere { radius: 0.1 };
        let manifold = inter_body_contacts_from_pair(&pair, &shape_a, &shape_b);
        // Two spheres separated by 0.15, radii 0.1 each → overlap = 0.05
        assert!(manifold.active_count() > 0, "overlapping spheres should produce contacts");
    }

    // ── SLAM Cycle 1: Contact intent/property tests ───────────────────

    #[test]
    fn intent_ground_contacts_only_for_penetrating_bodies() {
        // Intent: ground_plane_contacts should not generate contacts for bodies above ground
        let mut body = ArticulatedBody::new();
        body.set_gravity(Vector3::new(0.0, -9.81, 0.0));
        body.add_body("link", -1, GenJointType::Floating,
            SpatialInertia::sphere(1.0, 0.5),
            SpatialTransform::identity());
        body.set_joint_q(0, &[0.0, 5.0, 0.0, 1.0, 0.0, 0.0, 0.0]); // high up

        let manifold = ground_plane_contacts(&body, 0.0, Vector3::y(), 0.5, 0.0);
        assert_eq!(manifold.active_count(), 0,
            "body at y=5 should have no ground contacts, got {}", manifold.active_count());
    }

    #[test]
    fn intent_sphere_sphere_separated_no_contact() {
        // Intent: Two non-touching spheres should produce no active contacts
        let pos_a = Vector3::new(0.0, 0.0, 0.0);
        let pos_b = Vector3::new(5.0, 0.0, 0.0);
        let result = sphere_sphere_contact(pos_a, 0.5, pos_b, 0.5, 0, 0.5, 0.0);
        assert!(result.is_none() || result.as_ref().map_or(true, |c| c.penetration < 0.0),
            "Spheres 5m apart with r=0.5 should not contact");
    }

    #[test]
    fn property_contact_normal_always_unit() {
        // Property: Contact normals must always be unit vectors
        let pos_a = Vector3::new(0.0, 0.0, 0.0);
        let pos_b = Vector3::new(0.8, 0.0, 0.0);
        if let Some(contact) = sphere_sphere_contact(pos_a, 0.5, pos_b, 0.5, 0, 0.5, 0.0) {
            let norm = contact.normal.norm();
            assert!((norm - 1.0).abs() < 0.01,
                "Contact normal should be unit, got norm={norm}");
        }
    }

    #[test]
    fn intent_manifold_prune_removes_separated() {
        // Intent: prune_separated should remove contacts with negative penetration
        let mut manifold = ContactManifold::new();
        manifold.add_contact(ContactPoint::new(0, Vector3::zeros(), Vector3::zeros(), Vector3::y(), 0.01));
        manifold.add_contact(ContactPoint::new(0, Vector3::zeros(), Vector3::zeros(), Vector3::y(), -0.5));
        manifold.add_contact(ContactPoint::new(0, Vector3::zeros(), Vector3::zeros(), Vector3::y(), 0.005));

        manifold.prune_separated(-0.001);
        assert_eq!(manifold.active_count(), 2, "Should keep 2 active contacts, got {}", manifold.active_count());
    }

    // ── SLAM Cycle 6: Tests for untested public functions ─────────────

    #[test]
    fn test_capsule_box_contact_overlapping() {
        // Capsule inside box should detect contacts
        let cap_pos = Vector3::new(0.0, 0.0, 0.0);
        let cap_rot = Matrix3::identity();
        let half_h = 0.3;
        let cap_radius = 0.1;
        let box_pos = Vector3::new(0.0, 0.0, 0.0);
        let box_rot = Matrix3::identity();
        let box_he = Vector3::new(0.5, 0.5, 0.5);

        let contacts = capsule_box_contact(
            cap_pos, cap_rot, half_h, cap_radius,
            box_pos, box_rot, box_he,
            0, 0.5, 0.0,
        );
        // Capsule is fully inside the box, so contacts may or may not be generated
        // depending on sphere_box_contact behavior for inside-box case.
        // At minimum, verify no panic and finite values.
        for c in &contacts {
            assert!(c.point_world.x.is_finite(), "contact point must be finite");
            assert!(c.normal.norm() > 0.5, "contact normal must be non-zero");
        }
    }

    #[test]
    fn test_capsule_box_contact_separated() {
        // Capsule far from box should produce no contacts
        let cap_pos = Vector3::new(10.0, 0.0, 0.0);
        let cap_rot = Matrix3::identity();
        let box_pos = Vector3::new(0.0, 0.0, 0.0);
        let box_rot = Matrix3::identity();
        let box_he = Vector3::new(0.5, 0.5, 0.5);

        let contacts = capsule_box_contact(
            cap_pos, cap_rot, 0.3, 0.1,
            box_pos, box_rot, box_he,
            0, 0.5, 0.0,
        );
        assert!(contacts.is_empty(), "separated capsule-box should have no contacts");
    }

    #[test]
    fn test_select_max_area_contacts_returns_correct_count() {
        // select_max_area_contacts should return at most max_n indices
        let contacts = vec![
            ContactPoint::new(0, Vector3::new(0.0, 0.0, 0.0), Vector3::zeros(), Vector3::y(), 0.01),
            ContactPoint::new(0, Vector3::new(1.0, 0.0, 0.0), Vector3::zeros(), Vector3::y(), 0.01),
            ContactPoint::new(0, Vector3::new(0.0, 0.0, 1.0), Vector3::zeros(), Vector3::y(), 0.01),
            ContactPoint::new(0, Vector3::new(1.0, 0.0, 1.0), Vector3::zeros(), Vector3::y(), 0.01),
            ContactPoint::new(0, Vector3::new(0.5, 0.0, 0.5), Vector3::zeros(), Vector3::y(), 0.01),
        ];
        let selected = select_max_area_contacts(&contacts, 3);
        assert!(selected.len() <= 3, "should select at most 3, got {}", selected.len());
        // All indices should be valid
        for &idx in &selected {
            assert!(idx < contacts.len(), "index {idx} out of range");
        }
    }

    // ── SLAM Cycle 8: Edge cases and wrapper tests ────────────────────

    #[test]
    fn test_inter_body_contacts_sphere_sphere() {
        let shape = StoredShape::Sphere { radius: 0.5 };
        let pair = ShapePair {
            pos_a: Vector3::new(0.0, 0.0, 0.0),
            rot_a: Matrix3::identity(),
            pos_b: Vector3::new(0.8, 0.0, 0.0),
            rot_b: Matrix3::identity(),
            body_id_a: 0,
            body_id_b: 1,
            friction: 0.5,
            restitution: 0.0,
        };
        let manifold = inter_body_contacts(&shape, &shape, &pair);
        // Spheres with 0.8m gap and 0.5 radii overlap by 0.2
        assert!(!manifold.is_empty(), "overlapping spheres should produce contacts");
    }

    #[test]
    fn test_inter_body_contacts_separated_spheres() {
        let shape = StoredShape::Sphere { radius: 0.5 };
        let pair = ShapePair {
            pos_a: Vector3::new(0.0, 0.0, 0.0),
            rot_a: Matrix3::identity(),
            pos_b: Vector3::new(5.0, 0.0, 0.0),
            rot_b: Matrix3::identity(),
            body_id_a: 0,
            body_id_b: 1,
            friction: 0.5,
            restitution: 0.0,
        };
        let manifold = inter_body_contacts(&shape, &shape, &pair);
        assert_eq!(manifold.active_count(), 0, "separated spheres should have no active contacts");
    }

    #[test]
    fn test_box_box_contacts_from_pair_wrapper() {
        let pair = ShapePair {
            pos_a: Vector3::new(0.0, 0.0, 0.0),
            rot_a: Matrix3::identity(),
            pos_b: Vector3::new(0.9, 0.0, 0.0),
            rot_b: Matrix3::identity(),
            body_id_a: 0,
            body_id_b: 1,
            friction: 0.5,
            restitution: 0.0,
        };
        let he = Vector3::new(0.5, 0.5, 0.5);
        let manifold = box_box_contacts_from_pair(&pair, he, he);
        // Boxes at 0 and 0.9 with half_extent 0.5 overlap by 0.1
        assert!(!manifold.is_empty(), "overlapping boxes should produce contacts");
    }

    #[test]
    fn test_manifold_merge_three_contacts() {
        let mut m1 = ContactManifold::new();
        m1.add_contact(ContactPoint::new(0, Vector3::zeros(), Vector3::zeros(), Vector3::y(), 0.01));
        let mut m2 = ContactManifold::new();
        m2.add_contact(ContactPoint::new(1, Vector3::zeros(), Vector3::zeros(), Vector3::y(), 0.02));
        m2.add_contact(ContactPoint::new(1, Vector3::zeros(), Vector3::zeros(), Vector3::y(), 0.03));

        m1.merge(&m2);
        assert_eq!(m1.len(), 3, "merged manifold should have 3 contacts");
    }

    #[test]
    fn test_manifold_clear() {
        let mut manifold = ContactManifold::new();
        manifold.add_contact(ContactPoint::new(0, Vector3::zeros(), Vector3::zeros(), Vector3::y(), 0.01));
        manifold.add_contact(ContactPoint::new(0, Vector3::zeros(), Vector3::zeros(), Vector3::y(), 0.02));
        assert_eq!(manifold.len(), 2);
        manifold.clear();
        assert_eq!(manifold.len(), 0, "cleared manifold should be empty");
    }

    #[test]
    fn test_manifold_sort_by_penetration_ordering() {
        let mut manifold = ContactManifold::new();
        manifold.add_contact(ContactPoint::new(0, Vector3::zeros(), Vector3::zeros(), Vector3::y(), 0.01));
        manifold.add_contact(ContactPoint::new(0, Vector3::zeros(), Vector3::zeros(), Vector3::y(), 0.05));
        manifold.add_contact(ContactPoint::new(0, Vector3::zeros(), Vector3::zeros(), Vector3::y(), 0.02));

        manifold.sort_by_penetration();
        // After sort, deepest (0.05) should be first
        assert!(manifold.contacts[0].penetration >= manifold.contacts[1].penetration,
            "sort should put deepest first");
    }

    #[test]
    fn test_reduce_to_best_n_fewer_than_max() {
        // If we have fewer contacts than max, all should be kept
        let mut manifold = ContactManifold::new();
        manifold.add_contact(ContactPoint::new(0, Vector3::new(0.0, 0.0, 0.0), Vector3::zeros(), Vector3::y(), 0.01));
        manifold.add_contact(ContactPoint::new(0, Vector3::new(1.0, 0.0, 0.0), Vector3::zeros(), Vector3::y(), 0.02));

        manifold.reduce_to_best_n(5);
        assert_eq!(manifold.len(), 2, "should keep all when fewer than max");
    }

    #[test]
    fn test_reduce_to_best_n_exactly_max() {
        let mut manifold = ContactManifold::new();
        for i in 0..4 {
            manifold.add_contact(ContactPoint::new(0,
                Vector3::new(i as f32, 0.0, 0.0), Vector3::zeros(), Vector3::y(), 0.01));
        }
        manifold.reduce_to_best_n(4);
        assert_eq!(manifold.len(), 4, "should keep all when exactly max");
    }

    // ── SLAM Cycle 16: Inter-body box, manifold capacity ──────────────

    #[test]
    fn test_inter_body_contacts_box_box() {
        let shape = StoredShape::Box { half_extents: Vector3::new(0.5, 0.5, 0.5) };
        let pair = ShapePair {
            pos_a: Vector3::new(0.0, 0.0, 0.0),
            rot_a: Matrix3::identity(),
            pos_b: Vector3::new(0.9, 0.0, 0.0),
            rot_b: Matrix3::identity(),
            body_id_a: 0,
            body_id_b: 1,
            friction: 0.5,
            restitution: 0.0,
        };
        let manifold = inter_body_contacts(&shape, &shape, &pair);
        assert!(!manifold.is_empty(), "overlapping boxes via inter_body should produce contacts");
    }

    #[test]
    fn test_capsule_sphere_contact_overlapping() {
        let result = capsule_sphere_contact(
            Vector3::new(0.0, 0.0, 0.0), Matrix3::identity(), 0.3, 0.1, // capsule
            Vector3::new(0.15, 0.0, 0.0), 0.2, // sphere overlapping capsule
            0, 0.5, 0.0,
        );
        assert!(result.is_some(), "overlapping capsule-sphere should produce a contact");
        let c = result.unwrap();
        assert!(c.penetration > 0.0, "should have positive penetration");
    }

    #[test]
    fn test_capsule_capsule_contact_from_pair_wrapper() {
        let pair = ShapePair {
            pos_a: Vector3::new(0.0, 0.0, 0.0),
            rot_a: Matrix3::identity(),
            pos_b: Vector3::new(0.3, 0.0, 0.0),
            rot_b: Matrix3::identity(),
            body_id_a: 0, body_id_b: 1, friction: 0.5, restitution: 0.0,
        };
        let result = capsule_capsule_contact_from_pair(&pair, 0.3, 0.1, 0.3, 0.1);
        // Two capsules close together
        for c in &result {
            assert!(c.normal.norm() > 0.5, "contact normal should be non-zero");
        }
    }

    #[test]
    fn test_manifold_with_capacity_empty() {
        let manifold = ContactManifold::with_capacity(10);
        assert!(manifold.is_empty());
        assert_eq!(manifold.len(), 0);
    }
}