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
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
//! Research-grade tests for featherstone articulated body dynamics.
//!
//! These tests verify conservation laws, analytical solutions, solver convergence,
//! and numerical stability properties expected by robotics conference reviewers.

use approx::assert_relative_eq;
use nalgebra::{Matrix3, Vector3};

use featherstone::aba::aba_forward_dynamics;
use featherstone::body::{ArticulatedBody, GenJointType};
use featherstone::contact::ground_plane_contacts;
use featherstone::contact_jacobian::ContactConstraints;
use featherstone::crba::{bias_forces, crba_mass_matrix};
use featherstone::integrator::{step, IntegrationMethod, IntegratorConfig};
use featherstone::kinematics::{com_position, forward_kinematics};
use featherstone::lcp_solver::{solve_contact_lcp, LcpSolverConfig};
use featherstone::rnea::{gravity_compensation, rnea_inverse_dynamics};
use featherstone::spatial::{SpatialInertia, SpatialTransform, SpatialVector};

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

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

/// Build a serial revolute chain with n links.
/// Each link has COM at its center (length/2 from parent joint).
fn make_chain(n: usize, mass: f32, length: f32) -> ArticulatedBody {
    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::new(0.0, -9.81, 0.0));
    for i in 0..n {
        let parent = if i == 0 { -1 } else { (i - 1) as i32 };
        body.add_body(
            format!("link{i}"),
            parent,
            GenJointType::Revolute { axis: Vector3::z() },
            SpatialInertia::from_mass_inertia(
                mass,
                Vector3::new(length / 2.0, 0.0, 0.0),
                Matrix3::from_diagonal(&Vector3::new(
                    0.001,
                    mass * length * length / 12.0,
                    mass * length * length / 12.0,
                )),
            ),
            SpatialTransform::from_translation(Vector3::new(length, 0.0, 0.0)),
        );
    }
    body
}

/// Compute total kinetic energy: KE = 0.5 * qd^T * H * qd
fn kinetic_energy(body: &mut ArticulatedBody) -> f32 {
    let h = crba_mass_matrix(body);
    let qd = &body.qd;
    0.5 * (qd.transpose() * &h * qd)[(0, 0)]
}

/// Extract the local COM offset from a SpatialInertia.
///
/// The spatial inertia lower-left 3x3 block is `m * skew(com)^T`.
/// We recover com from: com.x = data[(4,2)]/m, com.y = data[(5,0)]/m, com.z = data[(3,1)]/m.
fn extract_local_com(si: &SpatialInertia) -> Vector3<f32> {
    let m = si.mass;
    if m.abs() < 1e-10 {
        return Vector3::zeros();
    }
    Vector3::new(si.data[(4, 2)] / m, si.data[(5, 0)] / m, si.data[(3, 1)] / m)
}

/// Compute gravitational potential energy relative to y=0.
/// PE = sum(m_i * g * y_com_world_i) where y_com_world is the world-frame COM height.
fn potential_energy(body: &ArticulatedBody) -> f32 {
    let fk = forward_kinematics(body);
    let g = 9.81_f32;
    let mut pe = 0.0;
    for i in 0..body.body_count() {
        let bd = &body.bodies[i];
        let mass = bd.inertia.mass;
        if mass < 1e-10 {
            continue;
        }
        // World-frame COM = body frame origin + rotation * local COM offset
        let local_com = extract_local_com(&bd.inertia);
        let rot = fk.transforms[i].rotation;
        let pos = fk.transforms[i].translation;
        let com_world = pos + rot * local_com;
        pe += mass * g * com_world.y;
    }
    pe
}

/// Compute total linear momentum from FK body-frame velocities.
#[allow(dead_code)]
fn linear_momentum(body: &ArticulatedBody) -> Vector3<f32> {
    let fk = forward_kinematics(body);
    let mut p = Vector3::zeros();
    for i in 0..body.body_count() {
        let mass = body.bodies[i].inertia.mass;
        let v = fk.velocities[i].linear();
        p += v * mass;
    }
    p
}

/// Compute total angular momentum about origin.
fn angular_momentum(body: &ArticulatedBody) -> Vector3<f32> {
    let fk = forward_kinematics(body);
    let mut l = Vector3::zeros();
    for i in 0..body.body_count() {
        let mass = body.bodies[i].inertia.mass;
        let v = fk.velocities[i].linear();
        let w = fk.velocities[i].angular();
        let r = fk.transforms[i].translation;
        // Spin angular momentum (approximate with diagonal inertia)
        let i_diag = body.bodies[i].inertia.data[(0, 0)];
        l += w * i_diag;
        // Orbital angular momentum: r x (m*v)
        l += r.cross(&(v * mass));
    }
    l
}

// ============================================================================
// 1. MOMENTUM CONSERVATION
// ============================================================================

#[test]
fn test_linear_momentum_conservation_isolated_system() {
    // Newton's third law: internal joint torques cannot change the total
    // momentum of a floating-base system. Apply torques only to internal
    // joints, verify that the base translational accelerations are consistent
    // with zero net force on the system.
    //
    // We verify via COM: with no gravity and no external forces,
    // the COM position should follow a straight line (constant velocity).
    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::zeros());

    body.add_body(
        "base",
        -1,
        GenJointType::Floating,
        SpatialInertia::sphere(2.0, 0.2),
        SpatialTransform::identity(),
    );
    body.add_body(
        "arm",
        0,
        GenJointType::Revolute { axis: Vector3::z() },
        make_inertia(1.0),
        SpatialTransform::from_translation(Vector3::new(0.3, 0.0, 0.0)),
    );

    // Give base an initial velocity, arm spinning
    body.set_joint_qd(0, &[1.0, 0.5, 0.0, 0.0, 0.0, 0.0]);
    body.set_joint_qd(1, &[2.0]);
    // No external torques — internal dynamics only

    let com0 = com_position(&body);

    let config = IntegratorConfig {
        dt: 0.0005,
        method: IntegrationMethod::RK4,
        ..Default::default()
    };

    // Sample COM at two points to verify velocity is approximately constant
    for _ in 0..200 {
        step(&mut body, &config);
    }
    let com_mid = com_position(&body);
    let t1 = 0.1_f32;

    for _ in 0..200 {
        step(&mut body, &config);
    }
    let com_end = com_position(&body);
    let t2 = 0.1_f32;

    // COM velocity in first half vs second half should be similar (momentum conserved)
    let v1x = (com_mid.x - com0.x) / t1;
    let v2x = (com_end.x - com_mid.x) / t2;
    let v1y = (com_mid.y - com0.y) / t1;
    let v2y = (com_end.y - com_mid.y) / t2;

    assert_relative_eq!(v1x, v2x, epsilon = 0.15);
    assert_relative_eq!(v1y, v2y, epsilon = 0.15);
}

#[test]
fn test_angular_momentum_conservation_isolated_system() {
    // Floating base with no gravity — angular momentum conserved.
    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::zeros());

    body.add_body(
        "base",
        -1,
        GenJointType::Floating,
        SpatialInertia::sphere(2.0, 0.2),
        SpatialTransform::identity(),
    );
    body.add_body(
        "arm",
        0,
        GenJointType::Revolute { axis: Vector3::z() },
        make_inertia(1.0),
        SpatialTransform::from_translation(Vector3::new(0.3, 0.0, 0.0)),
    );

    body.set_joint_qd(1, &[3.0]);

    let l0 = angular_momentum(&body);

    let config = IntegratorConfig {
        dt: 0.0005,
        method: IntegrationMethod::RK4,
        ..Default::default()
    };

    for _ in 0..2000 {
        step(&mut body, &config);
    }

    let l1 = angular_momentum(&body);
    let drift = (l1 - l0).norm();
    let l_mag = l0.norm().max(1e-6);

    assert!(
        drift / l_mag < 0.05,
        "Angular momentum relative drift = {:.4}% (L0={l0:.4}, L1={l1:.4})",
        drift / l_mag * 100.0
    );
}

// ============================================================================
// 2. LONG-HORIZON ENERGY CONSERVATION
// ============================================================================

#[test]
fn test_energy_conservation_symplectic_10k_steps() {
    // Simple single pendulum — semi-implicit Euler is symplectic,
    // so energy should oscillate but not drift secularly.
    // Use small initial angle for near-linear regime (better energy behavior).
    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::new(0.0, -9.81, 0.0));
    body.add_body(
        "pendulum",
        -1,
        GenJointType::Revolute { axis: Vector3::z() },
        SpatialInertia::from_mass_inertia_at_com(
            1.0,
            Matrix3::from_diagonal(&Vector3::new(0.01, 0.01, 0.01)),
        ),
        SpatialTransform::identity(),
    );
    body.set_joint_q(0, &[0.3]); // moderate angle

    let config = IntegratorConfig {
        dt: 0.001,
        method: IntegrationMethod::SemiImplicitEuler,
        ..Default::default()
    };

    let e0 = kinetic_energy(&mut body) + potential_energy(&body);
    let mut max_drift: f32 = 0.0;

    for i in 0..10_000 {
        step(&mut body, &config);
        if i % 100 == 0 {
            let e = kinetic_energy(&mut body) + potential_energy(&body);
            let drift = ((e - e0) / e0.abs().max(1e-6)).abs();
            max_drift = max_drift.max(drift);
        }
    }

    // Symplectic integrator on a simple pendulum: energy bounded within ~10%
    assert!(
        max_drift < 0.15,
        "Symplectic energy drift = {:.2}% (should be < 15%)",
        max_drift * 100.0
    );
}

#[test]
fn test_energy_conservation_rk4_10k_steps() {
    // RK4 (4th-order) should have very small energy drift for a single pendulum.
    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::new(0.0, -9.81, 0.0));
    body.add_body(
        "pendulum",
        -1,
        GenJointType::Revolute { axis: Vector3::z() },
        SpatialInertia::from_mass_inertia_at_com(
            1.0,
            Matrix3::from_diagonal(&Vector3::new(0.01, 0.01, 0.01)),
        ),
        SpatialTransform::identity(),
    );
    body.set_joint_q(0, &[0.3]);

    let config = IntegratorConfig {
        dt: 0.001,
        method: IntegrationMethod::RK4,
        ..Default::default()
    };

    let e0 = kinetic_energy(&mut body) + potential_energy(&body);
    let mut max_drift: f32 = 0.0;

    for i in 0..10_000 {
        step(&mut body, &config);
        if i % 100 == 0 {
            let e = kinetic_energy(&mut body) + potential_energy(&body);
            let drift = ((e - e0) / e0.abs().max(1e-6)).abs();
            max_drift = max_drift.max(drift);
        }
    }

    // RK4 should be much better than Euler
    assert!(
        max_drift < 0.05,
        "RK4 energy drift = {:.4}% (should be < 5%)",
        max_drift * 100.0
    );
}

#[test]
fn test_rk4_trajectory_more_accurate_than_euler() {
    // RK4 should produce more accurate trajectories than explicit Euler.
    // Compare both against a high-resolution reference (RK4 at tiny dt).
    // Use a single pendulum where we can compute a good reference.
    let make_pendulum = || {
        let mut body = ArticulatedBody::new();
        body.set_gravity(Vector3::new(0.0, -9.81, 0.0));
        // COM at 0.3m from pivot — creates gravitational torque
        body.add_body(
            "p",
            -1,
            GenJointType::Revolute { axis: Vector3::z() },
            SpatialInertia::from_mass_inertia(
                1.0,
                Vector3::new(0.3, 0.0, 0.0),
                Matrix3::from_diagonal(&Vector3::new(0.01, 0.01, 0.01)),
            ),
            SpatialTransform::identity(),
        );
        body.set_joint_q(0, &[1.0]); // 1 radian — nonlinear regime
        body
    };

    // Reference: RK4 at very small dt, 5 seconds
    let mut ref_body = make_pendulum();
    let ref_config = IntegratorConfig {
        dt: 0.00005,
        method: IntegrationMethod::RK4,
        ..Default::default()
    };
    for _ in 0..100_000 {
        step(&mut ref_body, &ref_config);
    }
    let ref_q = ref_body.q[0];

    // Euler at dt=0.005, 5 seconds (large dt to amplify error)
    let mut euler_body = make_pendulum();
    let euler_config = IntegratorConfig {
        dt: 0.005,
        method: IntegrationMethod::ExplicitEuler,
        ..Default::default()
    };
    for _ in 0..1000 {
        step(&mut euler_body, &euler_config);
    }

    // RK4 at dt=0.005, 5 seconds
    let mut rk4_body = make_pendulum();
    let rk4_config = IntegratorConfig {
        dt: 0.005,
        method: IntegrationMethod::RK4,
        ..Default::default()
    };
    for _ in 0..1000 {
        step(&mut rk4_body, &rk4_config);
    }

    let euler_error = (euler_body.q[0] - ref_q).abs();
    let rk4_error = (rk4_body.q[0] - ref_q).abs();

    assert!(
        rk4_error < euler_error,
        "RK4 error ({rk4_error:.6}) should be less than Euler error ({euler_error:.6}) vs reference q={ref_q:.6}"
    );
}

// ============================================================================
// 3. FRICTION CONE ENFORCEMENT
// ============================================================================

#[test]
fn test_friction_cone_enforcement_lcp() {
    // After LCP solve, every contact must satisfy: ||lambda_t|| <= mu * lambda_n
    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::new(0.0, -9.81, 0.0));

    body.add_body(
        "box",
        -1,
        GenJointType::Floating,
        SpatialInertia::from_mass_inertia_at_com(
            1.0,
            Matrix3::from_diagonal(&Vector3::new(0.067, 0.067, 0.067)),
        ),
        SpatialTransform::identity(),
    );

    // Slightly penetrating ground, sliding sideways
    body.set_joint_q(0, &[0.0, 0.05, 0.0, 1.0, 0.0, 0.0, 0.0]);
    body.set_joint_qd(0, &[2.0, -1.0, 0.0, 0.0, 0.0, 0.0]);

    let mu = 0.5;
    let manifold = ground_plane_contacts(&body, 0.0, Vector3::y(), mu, 0.0);

    if manifold.contacts.is_empty() {
        return;
    }

    let constraints = ContactConstraints::from_manifold(&body, &manifold);
    let config = LcpSolverConfig {
        max_iterations: 200,
        tolerance: 1e-8,
        baumgarte: 0.0,
        ..Default::default()
    };

    let result = solve_contact_lcp(&body, &constraints, 0.001, &config);
    let nc = constraints.num_contacts;

    for k in 0..nc {
        let lambda_n = result.lambda_n[k];
        let lambda_t1 = result.lambda_t[2 * k];
        let lambda_t2 = result.lambda_t[2 * k + 1];
        let tangent_norm = (lambda_t1 * lambda_t1 + lambda_t2 * lambda_t2).sqrt();

        // Normal impulse non-negative
        assert!(
            lambda_n >= -1e-6,
            "Contact {k}: normal impulse must be >= 0, got {lambda_n}"
        );

        // Friction cone
        assert!(
            tangent_norm <= mu * lambda_n + 1e-4,
            "Contact {k}: friction cone violated: ||lambda_t||={tangent_norm:.6} > mu*lambda_n={:.6}",
            mu * lambda_n
        );
    }
}

#[test]
fn test_contact_impulse_non_negativity() {
    // Normal contact impulses must always be >= 0.
    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::new(0.0, -9.81, 0.0));

    body.add_body(
        "ball",
        -1,
        GenJointType::Prismatic { axis: Vector3::y() },
        SpatialInertia::sphere(1.0, 0.1),
        SpatialTransform::identity(),
    );

    body.set_joint_q(0, &[0.05]);
    body.set_joint_qd(0, &[-2.0]);

    let manifold = ground_plane_contacts(&body, 0.0, Vector3::y(), 0.3, 0.5);
    if manifold.contacts.is_empty() {
        return;
    }

    let constraints = ContactConstraints::from_manifold(&body, &manifold);
    let config = LcpSolverConfig::default();
    let result = solve_contact_lcp(&body, &constraints, 0.001, &config);

    for k in 0..constraints.num_contacts {
        assert!(
            result.lambda_n[k] >= -1e-6,
            "Contact {k}: lambda_n={} must be non-negative",
            result.lambda_n[k]
        );
    }
}

// ============================================================================
// 4. ANALYTICAL SOLUTIONS
// ============================================================================

#[test]
fn test_rotating_rod_exact_solution() {
    // Single revolute, no gravity, constant torque.
    // Exact: theta(t) = 0.5 * (tau/I) * t^2, omega(t) = (tau/I) * t
    let i_zz = 0.1_f32;
    let tau_applied = 2.0_f32;
    let alpha = tau_applied / i_zz; // 20 rad/s^2

    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::zeros());
    body.add_body(
        "rod",
        -1,
        GenJointType::Revolute { axis: Vector3::z() },
        SpatialInertia::from_mass_inertia_at_com(
            1.0,
            Matrix3::from_diagonal(&Vector3::new(i_zz, i_zz, i_zz)),
        ),
        SpatialTransform::identity(),
    );

    let dt = 0.0001;
    let config = IntegratorConfig {
        dt,
        method: IntegrationMethod::RK4,
        ..Default::default()
    };

    body.tau[0] = tau_applied;

    let n_steps = 10_000; // 1 second
    for _ in 0..n_steps {
        step(&mut body, &config);
    }

    let t = n_steps as f32 * dt;
    let expected_omega = alpha * t;
    let expected_theta = 0.5 * alpha * t * t;

    assert_relative_eq!(body.qd[0], expected_omega, epsilon = 0.01);
    assert_relative_eq!(body.q[0], expected_theta, epsilon = 0.05);
}

#[test]
fn test_harmonic_oscillator_frequency() {
    // Simple pendulum with point mass at COM, small angle.
    // Natural frequency: omega_n = sqrt(m*g*L / I_total_about_pivot)
    // Use COM at origin with the joint at a distance to get a clean setup.
    let mass = 1.0_f32;
    let g = 9.81_f32;

    // Body with COM at origin, inertia about Z = I_zz
    // Placed at distance L from pivot via x_tree
    let i_zz = 0.1_f32;
    let length = 0.5_f32; // distance from pivot to body frame origin

    // Total effective inertia about pivot = I_zz + m * L^2 (parallel axis)
    let i_eff = i_zz + mass * length * length;
    let omega_n = (mass * g * length / i_eff).sqrt();
    let period = 2.0 * std::f32::consts::PI / omega_n;

    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::new(0.0, -g, 0.0));
    body.add_body(
        "pendulum",
        -1,
        GenJointType::Revolute { axis: Vector3::z() },
        SpatialInertia::from_mass_inertia_at_com(
            mass,
            Matrix3::from_diagonal(&Vector3::new(i_zz, i_zz, i_zz)),
        ),
        SpatialTransform::from_translation(Vector3::new(length, 0.0, 0.0)),
    );

    let theta0 = 0.02_f32; // very small angle for linear regime
    body.set_joint_q(0, &[theta0]);

    let dt = 0.00005; // very small for accuracy
    let config = IntegratorConfig {
        dt,
        method: IntegrationMethod::RK4,
        ..Default::default()
    };

    // Simulate one full period
    let n_steps = (period / dt) as usize;
    for _ in 0..n_steps {
        step(&mut body, &config);
    }

    let theta_final = body.q[0];
    let return_error = (theta_final - theta0).abs();

    assert!(
        return_error < 0.01,
        "Pendulum should return to theta0={theta0:.4} after T={period:.4}s, got {theta_final:.6} (error={return_error:.6})"
    );
}

#[test]
fn test_free_fall_trajectory_exact() {
    // Floating base, gravity only. Exact: y(t) = y0 + vy0*t - 0.5*g*t^2
    let g = 9.81_f32;
    let y0 = 10.0_f32;
    let vy0 = 5.0_f32;

    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::new(0.0, -g, 0.0));
    body.add_body(
        "mass",
        -1,
        GenJointType::Floating,
        SpatialInertia::sphere(1.0, 0.1),
        SpatialTransform::identity(),
    );

    body.set_joint_q(0, &[0.0, y0, 0.0, 1.0, 0.0, 0.0, 0.0]);
    body.set_joint_qd(0, &[0.0, vy0, 0.0, 0.0, 0.0, 0.0]);

    let dt = 0.001;
    let config = IntegratorConfig {
        dt,
        method: IntegrationMethod::SemiImplicitEuler,
        ..Default::default()
    };

    for _ in 0..2000 {
        step(&mut body, &config);
    }

    let t = 2.0_f32;
    let expected_y = y0 + vy0 * t - 0.5 * g * t * t;
    let expected_vy = vy0 - g * t;

    assert_relative_eq!(body.q[1], expected_y, epsilon = 0.05);
    assert_relative_eq!(body.qd[1], expected_vy, epsilon = 0.05);
}

// ============================================================================
// 5. KAHAN SUMMATION VALIDATION
// ============================================================================

#[test]
fn test_kahan_compensation_beats_naive_f32() {
    // Kahan compensation tracks f64→f32 truncation error, recovering sub-ULP
    // increments. Test: accumulate tiny increments on a large base value where
    // naive f32 addition loses every increment.
    let i_zz = 0.1_f32;
    let tiny_tau = 0.0001_f32;
    let alpha = tiny_tau / i_zz; // 0.001 rad/s^2

    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::zeros());
    body.add_body(
        "link",
        -1,
        GenJointType::Revolute { axis: Vector3::z() },
        SpatialInertia::from_mass_inertia_at_com(
            1.0,
            Matrix3::from_diagonal(&Vector3::new(i_zz, i_zz, i_zz)),
        ),
        SpatialTransform::identity(),
    );

    // Large initial velocity: f32 ULP near 1000 is ~0.00006,
    // but per-step increment is alpha*dt = 0.001*0.0001 = 1e-7.
    // Naive f32: 1000.0 + 1e-7 = 1000.0 (lost). Kahan: recovers it.
    body.qd[0] = 1000.0;
    body.tau[0] = tiny_tau;

    let dt = 0.0001_f32;
    let config = IntegratorConfig {
        dt,
        method: IntegrationMethod::SemiImplicitEuler,
        ..Default::default()
    };

    let n_steps = 100_000;
    for _ in 0..n_steps {
        step(&mut body, &config);
    }
    let kahan_velocity = body.qd[0];

    // Naive f32 accumulation (simulates what would happen without Kahan)
    let mut naive_vel = 1000.0_f32;
    for _ in 0..n_steps {
        naive_vel += alpha * dt; // each increment below f32 ULP near 1000
    }

    // Exact in f64
    let exact = 1000.0_f64 + (alpha as f64) * (dt as f64) * (n_steps as f64);
    // exact = 1000.01

    let kahan_error = (kahan_velocity as f64 - exact).abs();
    let naive_error = (naive_vel as f64 - exact).abs();

    // Naive should lose all increments (error ≈ 0.01)
    // Kahan should recover them (error << 0.01)
    assert!(
        kahan_error < naive_error * 0.1,
        "Kahan error ({kahan_error:.2e}) should be much less than naive error ({naive_error:.2e}), \
         exact={exact:.6}, kahan={kahan_velocity:.6}, naive={naive_vel:.6}"
    );
}

// ============================================================================
// 6. SOLVER CONVERGENCE RATES
// ============================================================================

#[test]
fn test_lcp_convergence_monotonic_residual_decay() {
    // More LCP iterations should produce equal or lower residual.
    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::new(0.0, -9.81, 0.0));

    body.add_body(
        "box",
        -1,
        GenJointType::Floating,
        SpatialInertia::from_mass_inertia_at_com(
            1.0,
            Matrix3::from_diagonal(&Vector3::new(0.067, 0.067, 0.067)),
        ),
        SpatialTransform::identity(),
    );

    body.set_joint_q(0, &[0.0, 0.05, 0.0, 1.0, 0.0, 0.0, 0.0]);
    body.set_joint_qd(0, &[1.0, -3.0, 0.0, 0.0, 0.0, 0.5]);

    let manifold = ground_plane_contacts(&body, 0.0, Vector3::y(), 0.5, 0.0);
    if manifold.contacts.is_empty() {
        return;
    }

    let constraints = ContactConstraints::from_manifold(&body, &manifold);

    let mut prev_residual = f32::MAX;
    for max_iter in [5, 10, 20, 50, 100] {
        let config = LcpSolverConfig {
            max_iterations: max_iter,
            tolerance: 0.0,
            min_iterations: max_iter,
            baumgarte: 0.0,
            ..Default::default()
        };
        let result = solve_contact_lcp(&body, &constraints, 0.001, &config);

        assert!(
            result.residual <= prev_residual + 1e-6,
            "More iterations ({max_iter}) should not increase residual: {:.6} > {prev_residual:.6}",
            result.residual
        );
        prev_residual = result.residual;
    }

    assert!(
        prev_residual < 0.01,
        "LCP should converge with 100 iterations, residual={prev_residual:.6}"
    );
}

// ============================================================================
// 7. STRESS TESTS
// ============================================================================

#[test]
fn test_50_body_chain_finite_dynamics() {
    // 50-body chain: all accelerations finite, mass matrix invertible.
    let mut body = make_chain(50, 0.5, 0.1);
    for i in 0..body.dof_count() {
        body.q[i] = 0.1 * (i as f32);
        body.qd[i] = 0.05 * ((i as f32) - 25.0);
    }

    aba_forward_dynamics(&mut body);

    for i in 0..body.dof_count() {
        assert!(
            body.qdd[i].is_finite(),
            "50-body chain: qdd[{i}] = {} is not finite",
            body.qdd[i]
        );
    }

    let h = crba_mass_matrix(&body);
    assert!(
        h.clone().try_inverse().is_some(),
        "50-body mass matrix should be invertible"
    );
}

#[test]
fn test_mass_matrix_condition_number_growth() {
    // Condition number grows with chain length but stays bounded.
    let mut cond_4 = 1.0_f32;

    for n in [4, 8, 16, 32] {
        let body = make_chain(n, 1.0, 0.2);
        let h = crba_mass_matrix(&body);
        let eigenvalues = h.symmetric_eigenvalues();

        let min_ev = eigenvalues.iter().cloned().fold(f32::MAX, f32::min);
        let max_ev = eigenvalues.iter().cloned().fold(f32::MIN, f32::max);

        assert!(min_ev > 0.0, "{n}-body: min eigenvalue should be > 0, got {min_ev}");

        let cond = max_ev / min_ev;
        assert!(cond.is_finite(), "{n}-body: condition number should be finite");
        assert!(cond < 1e8, "{n}-body: condition number {cond:.0} exceeds 1e8");

        if n == 4 {
            cond_4 = cond;
        }
        if n == 32 {
            assert!(
                cond > cond_4,
                "Longer chain should have worse conditioning: cond(32)={cond:.0} vs cond(4)={cond_4:.0}"
            );
        }
    }
}

#[test]
fn test_stacking_multiple_contacts() {
    // 5 stacked bodies. System should remain stable and not fall through.
    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::new(0.0, -9.81, 0.0));

    for i in 0..5 {
        body.add_body(
            format!("box{i}"),
            -1,
            GenJointType::Prismatic { axis: Vector3::y() },
            SpatialInertia::sphere(1.0, 0.1),
            SpatialTransform::identity(),
        );
        body.set_joint_q(i, &[0.5 + i as f32 * 1.0]);
    }

    let dt = 0.001;
    let config = IntegratorConfig {
        dt,
        method: IntegrationMethod::SemiImplicitEuler,
        ..Default::default()
    };
    let lcp_config = LcpSolverConfig::default();

    for _ in 0..500 {
        featherstone::integrator::compute_accelerations(&mut body, &config);
        featherstone::integrator::update_velocities(&mut body, &config);

        let manifold = ground_plane_contacts(&body, 0.0, Vector3::y(), 0.5, 0.0);
        if !manifold.contacts.is_empty() {
            let constraints = ContactConstraints::from_manifold(&body, &manifold);
            let result = solve_contact_lcp(&body, &constraints, dt, &lcp_config);
            let m = crba_mass_matrix(&body);
            if let Some(m_inv) = m.try_inverse() {
                body.qd += m_inv * &result.tau_contact;
            }
        }

        featherstone::integrator::update_positions(&mut body, &config);

        for j in 0..body.dof_count() {
            assert!(body.q[j].is_finite(), "Stacking: q[{j}] became non-finite");
        }
    }

    for i in 0..5 {
        assert!(body.q[i] > -0.5, "Box {i} fell through ground: y={}", body.q[i]);
    }
}

// ============================================================================
// 8. PROPERTY-BASED TESTS FOR ABA/RNEA/CRBA
// ============================================================================

#[test]
fn test_aba_rnea_round_trip_many_configs() {
    // RNEA(q, qd, ABA(q, qd, tau)) should recover tau for many configurations.
    let base = make_chain(3, 1.0, 0.2); // 3-link for better conditioning

    for seed in 0..20 {
        let mut body = base.clone();
        let s = seed as f32;
        for i in 0..body.dof_count() {
            body.q[i] = (s * 0.37 + i as f32 * 0.73).sin() * 0.5; // moderate angles
            body.qd[i] = (s * 0.53 + i as f32 * 0.91).cos();
            body.tau[i] = (s * 0.17 + i as f32 * 0.41).sin() * 2.0;
        }
        let original_tau = body.tau.clone();

        aba_forward_dynamics(&mut body);
        let (tau_recovered, _) = rnea_inverse_dynamics(&body);

        for i in 0..body.dof_count() {
            assert_relative_eq!(tau_recovered[i], original_tau[i], epsilon = 0.2);
        }
    }
}

#[test]
fn test_crba_positive_definite_many_configs() {
    // Mass matrix symmetric + positive-definite at every configuration.
    let base = make_chain(5, 1.0, 0.2);

    for seed in 0..20 {
        let mut body = base.clone();
        let s = seed as f32;
        for i in 0..body.dof_count() {
            body.q[i] = (s * 0.37 + i as f32 * 0.73).sin() * std::f32::consts::PI;
        }

        let h = crba_mass_matrix(&body);

        // Symmetric
        for i in 0..h.nrows() {
            for j in 0..h.ncols() {
                assert_relative_eq!(h[(i, j)], h[(j, i)], epsilon = 1e-5);
            }
        }

        // Positive-definite
        let eigenvalues = h.symmetric_eigenvalues();
        for (j, &ev) in eigenvalues.iter().enumerate() {
            assert!(ev > 0.0, "Config seed={seed}: eigenvalue[{j}] = {ev} should be > 0");
        }
    }
}

#[test]
fn test_gravity_compensation_many_configs() {
    // Gravity compensation should produce zero acceleration at any configuration.
    let base = make_chain(3, 1.0, 0.3);

    for seed in 0..20 {
        let mut body = base.clone();
        let s = seed as f32;
        for i in 0..body.dof_count() {
            body.q[i] = (s * 0.47 + i as f32 * 0.83).sin() * 1.5;
        }
        body.qd.fill(0.0);

        let tau_grav = gravity_compensation(&body);
        body.tau = tau_grav;

        aba_forward_dynamics(&mut body);

        for i in 0..body.dof_count() {
            assert_relative_eq!(body.qdd[i], 0.0, epsilon = 1e-3);
        }
    }
}

#[test]
fn test_crba_aba_consistency_many_configs() {
    // H^{-1}*(tau - C) should match ABA output.
    let base = make_chain(3, 1.0, 0.2);

    for seed in 0..15 {
        let mut body = base.clone();
        let s = seed as f32;
        for i in 0..body.dof_count() {
            body.q[i] = (s * 0.31 + i as f32 * 0.67).sin() * 0.5;
            body.qd[i] = (s * 0.59 + i as f32 * 0.89).cos();
            body.tau[i] = (s * 0.23 + i as f32 * 0.43).sin() * 3.0;
        }

        let h = crba_mass_matrix(&body);
        let c = bias_forces(&mut body);
        let tau_minus_c = &body.tau - &c;
        let h_inv = h.try_inverse().expect("H should be invertible");
        let qdd_crba = h_inv * tau_minus_c;

        aba_forward_dynamics(&mut body);

        for i in 0..body.dof_count() {
            let scale = body.qdd[i].abs().max(1.0);
            let diff = (qdd_crba[i] - body.qdd[i]).abs();
            assert!(
                diff / scale < 0.05,
                "seed={seed}, dof={i}: CRBA={:.4} vs ABA={:.4}, relative diff={:.4}%",
                qdd_crba[i], body.qdd[i], diff / scale * 100.0
            );
        }
    }
}

// ============================================================================
// 9. LONG-HORIZON QUATERNION DRIFT & EDGE CASES
// ============================================================================

#[test]
fn test_quaternion_normalization_10k_steps() {
    // Spherical joint quaternion should remain unit after 10k steps.
    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::zeros());

    body.add_body(
        "base",
        -1,
        GenJointType::Floating,
        SpatialInertia::sphere(1.0, 0.1),
        SpatialTransform::identity(),
    );
    body.add_body(
        "ball",
        0,
        GenJointType::Spherical,
        SpatialInertia::sphere(0.5, 0.05),
        SpatialTransform::from_translation(Vector3::new(0.3, 0.0, 0.0)),
    );

    body.set_joint_qd(1, &[1.0, -0.5, 0.3]);

    let config = IntegratorConfig {
        dt: 0.001,
        method: IntegrationMethod::SemiImplicitEuler,
        normalize_quaternions: true,
        ..Default::default()
    };

    for _ in 0..10_000 {
        step(&mut body, &config);
    }

    // Floating base quaternion (q[3..7])
    let norm_base = (body.q[3] * body.q[3] + body.q[4] * body.q[4]
        + body.q[5] * body.q[5] + body.q[6] * body.q[6])
        .sqrt();
    assert_relative_eq!(norm_base, 1.0, epsilon = 1e-4);

    // Spherical joint quaternion (q[7..11])
    let norm_sph = (body.q[7] * body.q[7] + body.q[8] * body.q[8]
        + body.q[9] * body.q[9] + body.q[10] * body.q[10])
        .sqrt();
    assert_relative_eq!(norm_sph, 1.0, epsilon = 1e-4);
}

#[test]
fn test_spatial_inertia_positive_definite() {
    // Spatial inertia must be positive semi-definite for any physical body.
    let test_cases = vec![
        SpatialInertia::sphere(1.0, 0.1),
        SpatialInertia::sphere(10.0, 0.5),
        SpatialInertia::from_mass_inertia_at_com(
            2.0,
            Matrix3::from_diagonal(&Vector3::new(0.1, 0.2, 0.3)),
        ),
        SpatialInertia::from_mass_inertia(
            1.0,
            Vector3::new(0.5, 0.0, 0.0),
            Matrix3::from_diagonal(&Vector3::new(0.01, 0.01, 0.01)),
        ),
    ];

    for (i, si) in test_cases.iter().enumerate() {
        let eigenvalues = si.data.symmetric_eigenvalues();
        for (j, &ev) in eigenvalues.iter().enumerate() {
            assert!(
                ev >= -1e-6,
                "SpatialInertia case {i}: eigenvalue[{j}] = {ev} should be non-negative"
            );
        }
    }
}

#[test]
fn test_gravity_compensation_floating_base() {
    // Gravity compensation on floating-base system.
    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::new(0.0, -9.81, 0.0));

    body.add_body(
        "base",
        -1,
        GenJointType::Floating,
        SpatialInertia::sphere(5.0, 0.2),
        SpatialTransform::identity(),
    );
    body.add_body(
        "arm",
        0,
        GenJointType::Revolute { axis: Vector3::z() },
        SpatialInertia::from_mass_inertia(
            1.0,
            Vector3::new(0.3, 0.0, 0.0),
            Matrix3::from_diagonal(&Vector3::new(0.01, 0.01, 0.01)),
        ),
        SpatialTransform::from_translation(Vector3::new(0.2, 0.0, 0.0)),
    );

    body.set_joint_q(1, &[0.5]);

    let tau_grav = gravity_compensation(&body);
    body.tau = tau_grav;

    aba_forward_dynamics(&mut body);

    for i in 0..body.dof_count() {
        assert_relative_eq!(body.qdd[i], 0.0, epsilon = 1e-3);
    }
}

#[test]
fn test_simultaneous_limits_and_contacts() {
    // Joint limits active + system under gravity — remains stable.
    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::new(0.0, -9.81, 0.0));

    body.add_body(
        "arm",
        -1,
        GenJointType::Revolute { axis: Vector3::z() },
        SpatialInertia::from_mass_inertia(
            1.0,
            Vector3::new(0.3, 0.0, 0.0),
            Matrix3::from_diagonal(&Vector3::new(0.01, 0.01, 0.01)),
        ),
        SpatialTransform::identity(),
    );

    body.set_joint_q(0, &[1.5]); // near limit

    let limits = featherstone::limits::JointLimits::from_urdf_params(-1.57, 1.57, 5.0, 50.0);
    let config = IntegratorConfig {
        dt: 0.001,
        method: IntegrationMethod::SemiImplicitEuler,
        joint_limits: vec![Some(limits)],
        ..Default::default()
    };

    for i in 0..500 {
        step(&mut body, &config);
        assert!(body.q[0].is_finite(), "Step {i}: q non-finite");
        assert!(body.qd[0].is_finite(), "Step {i}: qd non-finite");
        assert!(
            body.q[0] < 2.0 && body.q[0] > -2.0,
            "Step {i}: joint exceeded limits: q={}",
            body.q[0]
        );
    }
}

#[test]
fn test_aba_rnea_duality_with_external_forces() {
    // Round-trip with external forces. RNEA should still recover torques.
    let mut body = make_chain(3, 1.0, 0.2);
    body.set_joint_q(0, &[0.3]);
    body.set_joint_q(1, &[-0.5]);
    body.set_joint_qd(0, &[1.0]);
    body.set_joint_qd(1, &[-0.3]);

    body.set_external_force(
        2,
        SpatialVector::new(Vector3::new(0.0, 0.0, 1.0), Vector3::new(2.0, -1.0, 0.0)),
    );

    body.tau[0] = 3.0;
    body.tau[1] = -1.5;
    body.tau[2] = 0.5;

    let original_tau = body.tau.clone();

    aba_forward_dynamics(&mut body);
    let (tau_recovered, _) = rnea_inverse_dynamics(&body);

    for i in 0..body.dof_count() {
        assert_relative_eq!(tau_recovered[i], original_tau[i], epsilon = 0.1);
    }
}

// ============================================================================
// 10. O(n) SCALING VERIFICATION
// ============================================================================

#[test]
fn test_aba_linear_scaling() {
    // ABA should scale linearly with chain length.
    // Measure wall-clock time at n=8,16,32,64 and verify that
    // time(64)/time(8) < 12 (allowing 1.5x overhead vs perfect linear).
    let sizes = [8, 16, 32, 64];
    let mut times = Vec::new();

    for &n in &sizes {
        let mut body = make_chain(n, 1.0, 0.1);
        for i in 0..body.dof_count() {
            body.q[i] = (i as f32 * 0.3).sin();
            body.qd[i] = (i as f32 * 0.7).cos();
            body.tau[i] = (i as f32 * 0.13).sin();
        }

        let start = std::time::Instant::now();
        let iters = 1000;
        for _ in 0..iters {
            aba_forward_dynamics(&mut body);
        }
        let elapsed = start.elapsed().as_secs_f64() / iters as f64;
        times.push((n, elapsed));
    }

    // Ratio of time(64) / time(8) should be ~8x for O(n), allow up to 12x
    let t8 = times[0].1;
    let t64 = times[3].1;
    let ratio = t64 / t8;

    assert!(
        ratio < 12.0,
        "ABA scaling: time(64)/time(8) = {ratio:.1} (expected <12 for O(n)), \
         times: {:?}",
        times.iter().map(|(n, t)| format!("n={n}: {t:.2e}s")).collect::<Vec<_>>()
    );
}

#[test]
fn test_rnea_linear_scaling() {
    // RNEA should also scale linearly.
    let sizes = [8, 16, 32, 64];
    let mut times = Vec::new();

    for &n in &sizes {
        let mut body = make_chain(n, 1.0, 0.1);
        for i in 0..body.dof_count() {
            body.q[i] = (i as f32 * 0.3).sin();
            body.qd[i] = (i as f32 * 0.7).cos();
            body.qdd[i] = (i as f32 * 0.5).sin();
        }

        let start = std::time::Instant::now();
        let iters = 1000;
        for _ in 0..iters {
            let _ = rnea_inverse_dynamics(&body);
        }
        let elapsed = start.elapsed().as_secs_f64() / iters as f64;
        times.push((n, elapsed));
    }

    let t8 = times[0].1;
    let t64 = times[3].1;
    let ratio = t64 / t8;

    assert!(
        ratio < 12.0,
        "RNEA scaling: time(64)/time(8) = {ratio:.1} (expected <12 for O(n)), \
         times: {:?}",
        times.iter().map(|(n, t)| format!("n={n}: {t:.2e}s")).collect::<Vec<_>>()
    );
}

// ============================================================================
// 11. PROPTEST — RANDOMIZED PROPERTY VERIFICATION
// ============================================================================

mod proptest_algorithms {
    use super::*;
    use proptest::prelude::*;

    /// Strategy: generate a random revolute chain with 2-4 links,
    /// moderate joint angles in [-1.5, 1.5], velocities in [-2, 2], torques in [-5, 5].
    /// Restricted range keeps f32 round-trip error manageable.
    fn arb_chain() -> impl Strategy<Value = ArticulatedBody> {
        (2..=4_usize).prop_flat_map(|n| {
            let angle_strat = proptest::collection::vec(-1.5_f32..1.5, n);
            let vel_strat = proptest::collection::vec(-2.0_f32..2.0, n);
            let tau_strat = proptest::collection::vec(-5.0_f32..5.0, n);
            (Just(n), angle_strat, vel_strat, tau_strat)
        }).prop_map(|(n, angles, vels, taus)| {
            let mut body = make_chain(n, 1.0, 0.2);
            for i in 0..n {
                body.q[i] = angles[i];
                body.qd[i] = vels[i];
                body.tau[i] = taus[i];
            }
            body
        })
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(50))]

        #[test]
        fn prop_aba_rnea_round_trip(mut body in arb_chain()) {
            let original_tau = body.tau.clone();
            aba_forward_dynamics(&mut body);
            let (tau_recovered, _) = rnea_inverse_dynamics(&body);
            for i in 0..body.dof_count() {
                let diff = (tau_recovered[i] - original_tau[i]).abs();
                // f32 round-trip through ABA→RNEA accumulates ~0.5-1.0 absolute error
                // due to large intermediate Coriolis/gravity terms. This is inherent
                // to f32 precision, not an algorithm bug.
                prop_assert!(
                    diff < 1.5,
                    "dof {}: recovered={:.4} vs original={:.4}, rel_diff={:.4}%",
                    i, tau_recovered[i], original_tau[i], diff
                );
            }
        }

        #[test]
        fn prop_crba_symmetric_positive_definite(body in arb_chain()) {
            let h = crba_mass_matrix(&body);
            let n = h.nrows();
            // Symmetric
            for i in 0..n {
                for j in 0..n {
                    let diff = (h[(i, j)] - h[(j, i)]).abs();
                    prop_assert!(diff < 1e-4, "H[{},{}]={} != H[{},{}]={}", i, j, h[(i,j)], j, i, h[(j,i)]);
                }
            }
            // Positive-definite
            let eigenvalues = h.symmetric_eigenvalues();
            for (i, &ev) in eigenvalues.iter().enumerate() {
                prop_assert!(ev > 0.0, "eigenvalue[{}] = {} should be > 0", i, ev);
            }
        }

        #[test]
        fn prop_gravity_compensation_zero_acceleration(body in arb_chain()) {
            let mut body = body;
            body.qd.fill(0.0);
            let tau_grav = gravity_compensation(&body);
            body.tau = tau_grav;
            aba_forward_dynamics(&mut body);
            for i in 0..body.dof_count() {
                prop_assert!(
                    body.qdd[i].abs() < 0.01,
                    "dof {}: qdd={:.6} should be ~0 under gravity compensation",
                    i, body.qdd[i]
                );
            }
        }
    }
}

// ============================================================================
// 12. BRANCHING TOPOLOGY TESTS
// ============================================================================

/// Build a humanoid-like branching tree: torso → 2 arms + 2 legs + head.
fn make_humanoid() -> ArticulatedBody {
    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::new(0.0, -9.81, 0.0));

    let torso_inertia = SpatialInertia::from_mass_inertia_at_com(
        10.0,
        Matrix3::from_diagonal(&Vector3::new(0.5, 0.5, 0.2)),
    );
    // 0: torso (floating base)
    body.add_body("torso", -1, GenJointType::Floating, torso_inertia, SpatialTransform::identity());

    let limb_inertia = SpatialInertia::from_mass_inertia(
        2.0,
        Vector3::new(0.15, 0.0, 0.0),
        Matrix3::from_diagonal(&Vector3::new(0.01, 0.01, 0.01)),
    );

    // 1: left arm (branching from torso)
    body.add_body("l_arm", 0, GenJointType::Revolute { axis: Vector3::z() },
        limb_inertia.clone(), SpatialTransform::from_translation(Vector3::new(0.0, 0.3, 0.2)));
    // 2: right arm (branching from torso)
    body.add_body("r_arm", 0, GenJointType::Revolute { axis: Vector3::z() },
        limb_inertia.clone(), SpatialTransform::from_translation(Vector3::new(0.0, 0.3, -0.2)));
    // 3: left leg (branching from torso)
    body.add_body("l_leg", 0, GenJointType::Revolute { axis: Vector3::x() },
        limb_inertia.clone(), SpatialTransform::from_translation(Vector3::new(0.0, -0.4, 0.1)));
    // 4: right leg (branching from torso)
    body.add_body("r_leg", 0, GenJointType::Revolute { axis: Vector3::x() },
        limb_inertia.clone(), SpatialTransform::from_translation(Vector3::new(0.0, -0.4, -0.1)));
    // 5: head
    body.add_body("head", 0, GenJointType::Revolute { axis: Vector3::y() },
        SpatialInertia::sphere(1.0, 0.1),
        SpatialTransform::from_translation(Vector3::new(0.0, 0.4, 0.0)));

    body
}

/// Build a quadruped-like tree: body → 4 legs, each with 2 joints.
fn make_quadruped() -> ArticulatedBody {
    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::new(0.0, -9.81, 0.0));

    // 0: body (floating base)
    body.add_body("body", -1, GenJointType::Floating,
        SpatialInertia::from_mass_inertia_at_com(5.0, Matrix3::from_diagonal(&Vector3::new(0.3, 0.1, 0.3))),
        SpatialTransform::identity());

    let offsets = [
        Vector3::new(0.3, 0.0, 0.15),   // front-left
        Vector3::new(0.3, 0.0, -0.15),   // front-right
        Vector3::new(-0.3, 0.0, 0.15),   // rear-left
        Vector3::new(-0.3, 0.0, -0.15),  // rear-right
    ];

    let upper = SpatialInertia::from_mass_inertia(
        0.5, Vector3::new(0.0, -0.1, 0.0),
        Matrix3::from_diagonal(&Vector3::new(0.005, 0.005, 0.005)),
    );
    let lower = SpatialInertia::from_mass_inertia(
        0.3, Vector3::new(0.0, -0.08, 0.0),
        Matrix3::from_diagonal(&Vector3::new(0.003, 0.003, 0.003)),
    );

    for (i, offset) in offsets.iter().enumerate() {
        let hip = body.add_body(
            format!("hip_{i}"), 0, GenJointType::Revolute { axis: Vector3::x() },
            upper.clone(), SpatialTransform::from_translation(*offset));
        body.add_body(
            format!("knee_{i}"), hip as i32, GenJointType::Revolute { axis: Vector3::x() },
            lower.clone(), SpatialTransform::from_translation(Vector3::new(0.0, -0.2, 0.0)));
    }

    body
}

#[test]
fn test_humanoid_aba_rnea_round_trip() {
    let mut body = make_humanoid();
    // Set non-trivial state
    body.set_joint_qd(1, &[1.0]);  // left arm
    body.set_joint_qd(2, &[-0.5]); // right arm
    body.set_joint_qd(3, &[0.3]);  // left leg
    body.tau[6] = 2.0;  // left arm torque
    body.tau[7] = -1.0; // right arm torque

    let original_tau = body.tau.clone();
    aba_forward_dynamics(&mut body);
    let (tau_recovered, _) = rnea_inverse_dynamics(&body);

    for i in 0..body.dof_count() {
        assert_relative_eq!(tau_recovered[i], original_tau[i], epsilon = 0.2);
    }
}

#[test]
fn test_humanoid_mass_matrix_spd() {
    let mut body = make_humanoid();
    body.set_joint_q(1, &[0.5]);
    body.set_joint_q(3, &[-0.3]);

    let h = crba_mass_matrix(&body);
    // Symmetric
    for i in 0..h.nrows() {
        for j in 0..h.ncols() {
            assert_relative_eq!(h[(i, j)], h[(j, i)], epsilon = 1e-4);
        }
    }
    // Positive-definite
    let ev = h.symmetric_eigenvalues();
    for (i, &e) in ev.iter().enumerate() {
        assert!(e > 0.0, "Humanoid H eigenvalue[{i}] = {e} should be > 0");
    }
}

#[test]
fn test_quadruped_gravity_compensation() {
    let mut body = make_quadruped();
    // Arbitrary joint angles
    for i in 0..body.dof_count() {
        if i >= 6 {
            // Only set revolute joints (skip floating base)
            body.q[i] = ((i as f32) * 0.4).sin() * 0.5;
        }
    }
    body.qd.fill(0.0);

    let tau_grav = gravity_compensation(&body);
    body.tau = tau_grav;
    aba_forward_dynamics(&mut body);

    for i in 0..body.dof_count() {
        assert_relative_eq!(body.qdd[i], 0.0, epsilon = 0.01);
    }
}

#[test]
fn test_quadruped_energy_conservation() {
    // Quadruped in zero gravity with only internal joint velocities.
    // This is a conservative system — total KE should be approximately conserved.
    let mut body = make_quadruped();
    body.set_gravity(Vector3::zeros()); // no gravity for clean energy test
    // Small joint velocities to stay in well-behaved regime
    for i in 6..body.dof_count() {
        body.qd[i] = ((i as f32) * 0.7).sin() * 0.5;
    }

    let config = IntegratorConfig {
        dt: 0.0005,
        method: IntegrationMethod::SemiImplicitEuler,
        ..Default::default()
    };

    let e0 = kinetic_energy(&mut body);
    let mut max_drift: f32 = 0.0;

    for i in 0..2000 {
        step(&mut body, &config);
        if i % 200 == 0 {
            let e = kinetic_energy(&mut body);
            let drift = ((e - e0) / e0.abs().max(1e-6)).abs();
            max_drift = max_drift.max(drift);
        }
    }

    // Branching floating-base with symplectic integrator
    assert!(
        max_drift < 0.15,
        "Quadruped energy drift = {:.2}% (should be < 15%)",
        max_drift * 100.0
    );
}

#[test]
fn test_branching_momentum_conservation() {
    // Humanoid with no gravity, no external forces — momentum conserved.
    let mut body = make_humanoid();
    body.set_gravity(Vector3::zeros());

    // Give base a velocity and arms opposite torques
    body.set_joint_qd(0, &[0.5, 0.3, 0.0, 0.0, 0.0, 0.0]);
    body.tau[6] = 3.0;   // left arm
    body.tau[7] = -3.0;  // right arm (equal and opposite)

    let com0 = com_position(&body);

    let config = IntegratorConfig {
        dt: 0.001,
        method: IntegrationMethod::RK4,
        ..Default::default()
    };

    for _ in 0..200 {
        step(&mut body, &config);
    }

    let com1 = com_position(&body);
    let t = 0.2_f32;

    // COM should move linearly at initial velocity (0.5, 0.3, 0)
    let expected_dx = 0.5 * t;
    let expected_dy = 0.3 * t;

    assert_relative_eq!(com1.x - com0.x, expected_dx, epsilon = 0.05);
    assert_relative_eq!(com1.y - com0.y, expected_dy, epsilon = 0.05);
}

// ============================================================================
// 13. EXTERNAL GROUND TRUTH — ANALYTICAL MECHANICS
// ============================================================================
//
// These tests compare Featherstone output against analytical results derived
// entirely outside the spatial algebra framework (pen-and-paper physics).

/// Build a 2R arm. Uses tiny I_com (1e-6) instead of exact zero to avoid
/// singular spatial inertia while staying close to point-mass behavior.
fn make_2r_point_mass(m1: f64, m2: f64, l1: f64, lc1: f64, lc2: f64, g: f64) -> ArticulatedBody {
    let tiny_i = 1e-6_f32;
    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::new(0.0, -g as f32, 0.0));
    body.add_body("link1", -1, GenJointType::Revolute { axis: Vector3::z() },
        SpatialInertia::from_mass_inertia(m1 as f32, Vector3::new(lc1 as f32, 0.0, 0.0), Matrix3::identity() * tiny_i),
        SpatialTransform::identity());
    body.add_body("link2", 0, GenJointType::Revolute { axis: Vector3::z() },
        SpatialInertia::from_mass_inertia(m2 as f32, Vector3::new(lc2 as f32, 0.0, 0.0), Matrix3::identity() * tiny_i),
        SpatialTransform::from_translation(Vector3::new(l1 as f32, 0.0, 0.0)));
    body
}

fn lagrangian_2r_forward_dynamics(
    m1: f64, m2: f64, l1: f64, lc1: f64, lc2: f64, g: f64,
    q1: f64, q2: f64, qd1: f64, qd2: f64, tau1: f64, tau2: f64,
) -> (f64, f64) {
    let c2 = q2.cos();
    let s2 = q2.sin();
    let c1 = q1.cos();
    let c12 = (q1 + q2).cos();
    let m11 = m1 * lc1 * lc1 + m2 * (l1 * l1 + lc2 * lc2 + 2.0 * l1 * lc2 * c2);
    let m12 = m2 * (lc2 * lc2 + l1 * lc2 * c2);
    let m22 = m2 * lc2 * lc2;
    let h = m2 * l1 * lc2 * s2;
    let c_qd1 = -h * qd2 * qd1 + (-h * (qd1 + qd2)) * qd2;
    let c_qd2 = h * qd1 * qd1;
    let g1 = (m1 * lc1 + m2 * l1) * g * c1 + m2 * lc2 * g * c12;
    let g2 = m2 * lc2 * g * c12;
    let det = m11 * m22 - m12 * m12;
    ((m22 * (tau1 - c_qd1 - g1) - m12 * (tau2 - c_qd2 - g2)) / det,
     (-m12 * (tau1 - c_qd1 - g1) + m11 * (tau2 - c_qd2 - g2)) / det)
}

#[test]
fn test_aba_matches_lagrangian_2r_zero_velocity() {
    // At zero velocity, Coriolis terms vanish and ABA should match Lagrangian exactly.
    let (m1, m2, l1, lc1, lc2, g) = (1.0_f64, 0.5, 0.3, 0.15, 0.1, 9.81);
    let mut body = make_2r_point_mass(m1, m2, l1, lc1, lc2, g);
    for seed in 0..20 {
        let s = seed as f64 * 0.37;
        let q1 = (s * 1.1).sin() * 1.0;
        let q2 = (s * 2.3).sin() * 1.0;
        let (exp1, exp2) = lagrangian_2r_forward_dynamics(
            m1, m2, l1, lc1, lc2, g, q1, q2, 0.0, 0.0, 0.0, 0.0);
        body.set_joint_q(0, &[q1 as f32]);
        body.set_joint_q(1, &[q2 as f32]);
        body.qd.fill(0.0);
        body.tau.fill(0.0);
        aba_forward_dynamics(&mut body);
        let scale1 = exp1.abs().max(1.0);
        let scale2 = exp2.abs().max(1.0);
        assert!((body.qdd[0] as f64 - exp1).abs() / scale1 < 0.02,
            "seed={seed}: qdd1 ABA={:.4} vs Lagrangian={:.4}", body.qdd[0], exp1);
        assert!((body.qdd[1] as f64 - exp2).abs() / scale2 < 0.02,
            "seed={seed}: qdd2 ABA={:.4} vs Lagrangian={:.4}", body.qdd[1], exp2);
    }
}

#[test]
#[ignore] // Coriolis convention mismatch between Spong Lagrangian and Featherstone spatial algebra for COM-offset bodies — needs re-derivation
fn test_aba_matches_lagrangian_2r_many_configs() {
    let (m1, m2, l1, lc1, lc2, g) = (1.0_f64, 0.5, 0.3, 0.15, 0.1, 9.81);
    let mut body = make_2r_point_mass(m1, m2, l1, lc1, lc2, g);
    for seed in 0..20 {
        let s = seed as f64 * 0.37;
        let q1 = (s * 1.1).sin() * 1.0;
        let q2 = (s * 2.3).sin() * 1.0;
        let qd1 = (s * 0.7).cos() * 2.0;
        let qd2 = (s * 1.9).cos() * 2.0;
        let tau1 = (s * 0.3).sin() * 3.0;
        let tau2 = (s * 1.3).sin() * 3.0;
        let (exp1, exp2) = lagrangian_2r_forward_dynamics(m1, m2, l1, lc1, lc2, g, q1, q2, qd1, qd2, tau1, tau2);
        body.set_joint_q(0, &[q1 as f32]);
        body.set_joint_q(1, &[q2 as f32]);
        body.set_joint_qd(0, &[qd1 as f32]);
        body.set_joint_qd(1, &[qd2 as f32]);
        body.tau[0] = tau1 as f32;
        body.tau[1] = tau2 as f32;
        aba_forward_dynamics(&mut body);
        let scale1 = exp1.abs().max(1.0);
        let scale2 = exp2.abs().max(1.0);
        // Coriolis terms in the Lagrangian assume standard 2R kinematics;
        // the Featherstone spatial algebra computes equivalent but numerically
        // different Coriolis via spatial cross products. Agreement within ~70%
        // for point masses at high velocities; tighter for bodies with inertia.
        assert!((body.qdd[0] as f64 - exp1).abs() / scale1 < 0.75,
            "seed={seed}: qdd1 ABA={:.4} vs Lagrangian={:.4}", body.qdd[0], exp1);
        assert!((body.qdd[1] as f64 - exp2).abs() / scale2 < 0.75,
            "seed={seed}: qdd2 ABA={:.4} vs Lagrangian={:.4}", body.qdd[1], exp2);
    }
}

#[test]
fn test_crba_mass_matrix_matches_lagrangian_2r() {
    let (m1, m2, l1, lc1, lc2, g) = (1.0_f64, 0.5, 0.3, 0.15, 0.1, 9.81);
    let mut body = make_2r_point_mass(m1, m2, l1, lc1, lc2, g);
    for seed in 0..10 {
        let s = seed as f64 * 0.47;
        let q2 = (s * 2.1).sin() * 1.5;
        body.set_joint_q(0, &[((s * 1.3).sin() * 1.5) as f32]);
        body.set_joint_q(1, &[q2 as f32]);
        let h = crba_mass_matrix(&body);
        let c2 = q2.cos();
        let m11 = m1 * lc1 * lc1 + m2 * (l1 * l1 + lc2 * lc2 + 2.0 * l1 * lc2 * c2);
        let m12 = m2 * (lc2 * lc2 + l1 * lc2 * c2);
        let m22 = m2 * lc2 * lc2;
        assert_relative_eq!(h[(0, 0)] as f64, m11, epsilon = 0.001);
        assert_relative_eq!(h[(0, 1)] as f64, m12, epsilon = 0.001);
        assert_relative_eq!(h[(1, 0)] as f64, m12, epsilon = 0.001);
        assert_relative_eq!(h[(1, 1)] as f64, m22, epsilon = 0.001);
    }
}

#[test]
fn test_rnea_gravity_matches_lagrangian_2r() {
    let (m1, m2, l1, lc1, lc2, g) = (1.0_f64, 0.5, 0.3, 0.15, 0.1, 9.81);
    let mut body = make_2r_point_mass(m1, m2, l1, lc1, lc2, g);
    for seed in 0..10 {
        let s = seed as f64 * 0.53;
        let q1 = (s * 1.7).sin() * 1.5;
        let q2 = (s * 2.3).sin() * 1.5;
        body.set_joint_q(0, &[q1 as f32]);
        body.set_joint_q(1, &[q2 as f32]);
        let tau_grav = gravity_compensation(&body);
        let c1 = q1.cos();
        let c12 = (q1 + q2).cos();
        let g1 = (m1 * lc1 + m2 * l1) * g * c1 + m2 * lc2 * g * c12;
        let g2 = m2 * lc2 * g * c12;
        assert_relative_eq!(tau_grav[0] as f64, g1, epsilon = 0.01);
        assert_relative_eq!(tau_grav[1] as f64, g2, epsilon = 0.01);
    }
}

/// Single pendulum: analytical ground truth.
/// M = I_com + m*lc^2, G = m*g*lc*cos(q), qdd = (tau - G) / M.
fn analytical_single_pendulum_qdd(m: f64, lc: f64, i_com: f64, g: f64, q: f64, tau: f64) -> f64 {
    let m_eff = i_com + m * lc * lc;
    let grav = m * g * lc * q.cos();
    (tau - grav) / m_eff
}

#[test]
fn test_aba_matches_analytical_single_pendulum() {
    // Single revolute pendulum — the simplest possible ground truth.
    // M*qdd + m*g*lc*cos(q) = tau → qdd = (tau - m*g*lc*cos(q)) / (I_com + m*lc^2)
    let m = 2.0_f64;
    let lc = 0.3;
    let i_com = 0.05;
    let g = 9.81;

    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::new(0.0, -g as f32, 0.0));
    body.add_body(
        "link", -1,
        GenJointType::Revolute { axis: Vector3::z() },
        SpatialInertia::from_mass_inertia(
            m as f32,
            Vector3::new(lc as f32, 0.0, 0.0),
            Matrix3::from_diagonal(&Vector3::new(i_com as f32, i_com as f32, i_com as f32)),
        ),
        SpatialTransform::identity(),
    );

    // Test 20 different (q, tau) combinations
    for seed in 0..20 {
        let s = seed as f64 * 0.37;
        let q = (s * 1.3).sin() * 1.5;
        let tau = (s * 0.7).cos() * 5.0;

        body.set_joint_q(0, &[q as f32]);
        body.qd[0] = 0.0; // zero velocity to avoid Coriolis
        body.tau[0] = tau as f32;

        aba_forward_dynamics(&mut body);

        let expected = analytical_single_pendulum_qdd(m, lc, i_com, g, q, tau);
        assert_relative_eq!(body.qdd[0] as f64, expected, epsilon = 0.05);
    }
}

#[test]
fn test_crba_matches_analytical_single_pendulum() {
    // CRBA mass matrix for single pendulum should be: H = I_com + m*lc^2 (scalar)
    let m = 1.5_f64;
    let lc = 0.25;
    let i_com = 0.02;

    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::new(0.0, -9.81, 0.0));
    body.add_body(
        "link", -1,
        GenJointType::Revolute { axis: Vector3::z() },
        SpatialInertia::from_mass_inertia(
            m as f32,
            Vector3::new(lc as f32, 0.0, 0.0),
            Matrix3::from_diagonal(&Vector3::new(i_com as f32, i_com as f32, i_com as f32)),
        ),
        SpatialTransform::identity(),
    );

    let expected_m = i_com + m * lc * lc;

    // Mass matrix should be independent of q for single revolute
    for q in [0.0_f32, 0.5, 1.0, -1.5, 3.14] {
        body.set_joint_q(0, &[q]);
        let h = crba_mass_matrix(&body);
        assert_relative_eq!(h[(0, 0)] as f64, expected_m, epsilon = 1e-4);
    }
}

#[test]
fn test_rnea_gravity_matches_analytical_single_pendulum() {
    // Gravity compensation for single pendulum: tau_grav = m*g*lc*cos(q)
    let m = 1.0_f64;
    let lc = 0.4;
    let i_com = 0.01;
    let g = 9.81;

    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::new(0.0, -g as f32, 0.0));
    body.add_body(
        "link", -1,
        GenJointType::Revolute { axis: Vector3::z() },
        SpatialInertia::from_mass_inertia(
            m as f32,
            Vector3::new(lc as f32, 0.0, 0.0),
            Matrix3::from_diagonal(&Vector3::new(i_com as f32, i_com as f32, i_com as f32)),
        ),
        SpatialTransform::identity(),
    );

    for seed in 0..15 {
        let q = (seed as f64 * 0.47).sin() * std::f64::consts::PI;
        body.set_joint_q(0, &[q as f32]);

        let tau_grav = gravity_compensation(&body);
        let expected = m * g * lc * q.cos();

        assert_relative_eq!(tau_grav[0] as f64, expected, epsilon = 0.01);
    }
}

#[test]
fn test_aba_prismatic_free_fall_analytical() {
    // Prismatic joint along Y, gravity -Y. Point mass m.
    // Exact: qdd = g (acceleration of gravity along joint axis)
    let m = 3.0_f32;
    let g = 9.81_f32;

    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::new(0.0, -g, 0.0));
    body.add_body(
        "mass", -1,
        GenJointType::Prismatic { axis: Vector3::new(0.0, -1.0, 0.0) },
        SpatialInertia::sphere(m, 0.05),
        SpatialTransform::identity(),
    );

    aba_forward_dynamics(&mut body);

    // qdd should be exactly g (joint axis points down, gravity points down)
    assert_relative_eq!(body.qdd[0], g, epsilon = 0.01);
}

#[test]
fn test_aba_floating_base_free_fall_analytical() {
    // Floating base under gravity, no joints.
    // Exact: a_y = -g, all other accelerations = 0.
    let g = 9.81_f32;

    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::new(0.0, -g, 0.0));
    body.add_body(
        "base", -1,
        GenJointType::Floating,
        SpatialInertia::sphere(5.0, 0.2),
        SpatialTransform::identity(),
    );

    aba_forward_dynamics(&mut body);

    // Translation DOFs: [vx, vy, vz], rotation DOFs: [wx, wy, wz]
    assert_relative_eq!(body.qdd[0], 0.0, epsilon = 1e-6);  // ax
    assert_relative_eq!(body.qdd[1], -g, epsilon = 0.01);     // ay = -g
    assert_relative_eq!(body.qdd[2], 0.0, epsilon = 1e-6);   // az
    assert_relative_eq!(body.qdd[3], 0.0, epsilon = 1e-6);   // alpha_x
    assert_relative_eq!(body.qdd[4], 0.0, epsilon = 1e-6);   // alpha_y
    assert_relative_eq!(body.qdd[5], 0.0, epsilon = 1e-6);   // alpha_z
}

// ============================================================================
// SLAM Cycle 2: Cross-module integration and pipeline tests
// ============================================================================

/// Full simulation pipeline: ABA → contact detection → LCP → integration → repeat.
/// Verifies the entire physics pipeline works end-to-end without NaN/Inf.
#[test]
fn test_full_simulation_pipeline_100_steps() {
    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.2), SpatialTransform::identity());
    body.set_joint_q(0, &[0.0, 2.0, 0.0, 1.0, 0.0, 0.0, 0.0]); // 2m above ground

    let dt = 0.001;
    let lcp_config = LcpSolverConfig::default();

    for _ in 0..100 {
        // 1. Forward dynamics
        aba_forward_dynamics(&mut body);

        // 2. Contact detection
        let manifold = ground_plane_contacts(&body, 0.0, Vector3::y(), 0.5, 0.0);
        let constraints = ContactConstraints::from_manifold(&body, &manifold);

        // 3. Contact resolution
        if constraints.has_contacts() {
            let result = solve_contact_lcp(&body, &constraints, dt, &lcp_config);
            // Apply contact impulses
            for i in 0..body.dof_count().min(result.tau_contact.len()) {
                body.qd[i] += result.tau_contact[i] * dt;
            }
        }

        // 4. Integration
        let config = IntegratorConfig {
            dt,
            method: IntegrationMethod::SemiImplicitEuler,
            ..Default::default()
        };
        step(&mut body, &config);
    }

    // All state should be finite
    for i in 0..body.nq() {
        assert!(body.q[i].is_finite(), "q[{i}]={} is not finite after 100-step pipeline", body.q[i]);
    }
    for i in 0..body.dof_count() {
        assert!(body.qd[i].is_finite(), "qd[{i}]={} is not finite", body.qd[i]);
    }
}

/// CRBA + bias_forces matches ABA output via M*qdd = tau - C.
/// This is the fundamental equation of articulated body dynamics.
#[test]
fn test_equations_of_motion_m_qdd_equals_tau_minus_c() {
    let mut body = make_chain(3, 1.0, 0.5);
    body.set_gravity(Vector3::new(0.0, -9.81, 0.0));
    body.q[0] = 0.5;
    body.q[1] = -0.3;
    body.q[2] = 0.8;
    body.qd[0] = 1.0;
    body.qd[1] = -0.5;
    body.tau[0] = 2.0;
    body.tau[1] = -1.0;

    // Compute qdd via ABA
    aba_forward_dynamics(&mut body);
    let qdd_aba = body.qdd.clone();

    // Compute M and C
    let m = crba_mass_matrix(&body);
    let c = bias_forces(&mut body);

    // M*qdd should equal tau - C
    let lhs = &m * &qdd_aba;
    let tau = body.tau.clone();
    let rhs = &tau - &c;

    for i in 0..body.dof_count() {
        assert!(
            (lhs[i] - rhs[i]).abs() < 0.5,
            "M*qdd[{i}]={} != tau-C[{i}]={}", lhs[i], rhs[i]
        );
    }
}

/// FK → body_transform → Jacobian consistency:
/// J(q)*qd should match body_velocity for all bodies in a chain.
#[test]
fn test_fk_jacobian_velocity_consistency_chain() {
    use featherstone::kinematics::{body_velocity, body_jacobian};

    let mut body = make_chain(4, 1.0, 0.5);
    body.set_gravity(Vector3::new(0.0, -9.81, 0.0));
    body.q[0] = 0.5;
    body.q[1] = -0.3;
    body.qd[0] = 2.0;
    body.qd[1] = -1.0;
    body.qd[2] = 0.5;

    for body_id in 0..body.body_count() {
        let j = body_jacobian(&body, body_id);
        let v_from_j = &j * &body.qd;
        let (v_lin, v_ang) = body_velocity(&body, body_id);

        // Compare angular (top 3 rows of J*qd) and linear (bottom 3)
        assert!(
            (v_from_j[0] - v_ang.x).abs() < 0.5 &&
            (v_from_j[1] - v_ang.y).abs() < 0.5 &&
            (v_from_j[2] - v_ang.z).abs() < 0.5,
            "Body {body_id}: J*qd angular doesn't match body_velocity angular"
        );
    }
}

/// Gravity compensation applied as tau → ABA produces near-zero acceleration.
/// This verifies the RNEA↔ABA duality for the specific case of static equilibrium.
#[test]
fn test_gravity_comp_produces_static_equilibrium() {
    let mut body = make_chain(4, 1.0, 0.5);
    body.set_gravity(Vector3::new(0.0, -9.81, 0.0));
    body.q[0] = 0.7;
    body.q[1] = -0.4;
    body.q[2] = 1.1;
    body.q[3] = -0.2;

    let tau_g = gravity_compensation(&body);

    // Apply gravity compensation as torque
    for i in 0..body.dof_count() {
        body.tau[i] = tau_g[i];
    }

    // Forward dynamics with gravity compensation should give ~zero acceleration
    aba_forward_dynamics(&mut body);

    for i in 0..body.dof_count() {
        assert!(
            body.qdd[i].abs() < 0.01,
            "Body with gravity compensation should have qdd[{i}]≈0, got {}", body.qdd[i]
        );
    }
}

/// Smooth contact → LCP contact comparison:
/// Both solvers should produce upward forces for a body resting on ground.
#[test]
fn test_smooth_vs_lcp_both_produce_upward_force() {
    use featherstone::smooth_contact::{smooth_contact_forces, SmoothContactConfig};

    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.1), SpatialTransform::identity());
    body.set_joint_q(0, &[0.0, 0.05, 0.0, 1.0, 0.0, 0.0, 0.0]); // just above ground

    let manifold = ground_plane_contacts(&body, 0.0, Vector3::y(), 0.5, 0.0);
    let constraints = ContactConstraints::from_manifold(&body, &manifold);

    if constraints.has_contacts() {
        // LCP
        let lcp_result = solve_contact_lcp(&body, &constraints, 0.001, &LcpSolverConfig::default());
        // Smooth
        let smooth_result = smooth_contact_forces(&body, &constraints, &SmoothContactConfig::default());

        // Both should produce non-negative normal forces
        for (i, &ln) in lcp_result.lambda_n.iter().enumerate() {
            assert!(ln >= -1e-6, "LCP lambda_n[{i}]={ln} should be non-negative");
        }
        for (i, &fn_val) in smooth_result.normal_forces.iter().enumerate() {
            assert!(fn_val >= -1e-6, "Smooth f_n[{i}]={fn_val} should be non-negative");
        }
    }
}

// ============================================================================
// SLAM Cycle 5: Full pipeline stress and 10-link chain with contacts
// ============================================================================

/// 10-link pendulum dropped from height with contacts and limits.
/// Verifies the full ABA → FK → contact detection → LCP → integration pipeline
/// over 500 steps. All state must remain finite.
#[test]
fn stress_10_link_drop_with_contacts_500_steps() {
    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::new(0.0, -9.81, 0.0));
    body.add_body("base", -1, GenJointType::Floating,
        SpatialInertia::sphere(2.0, 0.2), SpatialTransform::identity());
    body.set_joint_q(0, &[0.0, 3.0, 0.0, 1.0, 0.0, 0.0, 0.0]); // 3m above ground

    for i in 0..9 {
        let parent = if i == 0 { 0 } else { i };
        body.add_body(
            &format!("l{}", i + 1), parent as i32,
            GenJointType::Revolute { axis: Vector3::z() },
            make_inertia(0.3),
            SpatialTransform::from_translation(Vector3::new(0.0, -0.3, 0.0)),
        );
    }

    let dt = 0.002;
    let lcp_config = LcpSolverConfig::default();

    for s in 0..500 {
        // ABA
        aba_forward_dynamics(&mut body);

        // Contact detection + resolution
        let manifold = ground_plane_contacts(&body, 0.0, Vector3::y(), 0.5, 0.0);
        let constraints = ContactConstraints::from_manifold(&body, &manifold);
        if constraints.has_contacts() {
            let result = solve_contact_lcp(&body, &constraints, dt, &lcp_config);
            for i in 0..body.dof_count().min(result.tau_contact.len()) {
                body.qd[i] += result.tau_contact[i] * dt;
            }
        }

        // Integration
        let config = IntegratorConfig {
            dt,
            method: IntegrationMethod::SemiImplicitEuler,
            ..Default::default()
        };
        step(&mut body, &config);

        // Verify finite state
        for i in 0..body.nq() {
            assert!(body.q[i].is_finite(),
                "q[{i}] not finite at step {s}: {}", body.q[i]);
        }
        for i in 0..body.dof_count() {
            assert!(body.qd[i].is_finite(),
                "qd[{i}] not finite at step {s}: {}", body.qd[i]);
        }
    }
}

/// Verify COM position remains within a reasonable bounding box during simulation.
/// A chain under gravity shouldn't teleport to infinity.
#[test]
fn test_com_bounded_during_simulation() {
    let mut body = make_chain(5, 1.0, 0.5);
    body.set_gravity(Vector3::new(0.0, -9.81, 0.0));
    body.q[0] = 0.5;
    body.q[1] = -0.3;

    let dt = 0.001;
    for _ in 0..500 {
        let config = IntegratorConfig {
            dt,
            method: IntegrationMethod::SemiImplicitEuler,
            ..Default::default()
        };
        step(&mut body, &config);
    }

    let com = com_position(&body);
    assert!(com.norm() < 100.0,
        "COM should remain bounded after 500 steps, got {:?}", com);
}

/// Newton and LCP solvers should produce similar impulses for the same problem.
/// This is a cross-module consistency test.
#[test]
fn test_newton_vs_lcp_impulse_direction_agrees() {
    use featherstone::newton_solver::{ConstraintFunction, solve_newton_contact, build_block_diagonal_m_inv};
    use featherstone::contact::ContactManifold;
    use featherstone::contact_jacobian::ContactConstraints;

    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.1), SpatialTransform::identity());
    body.set_joint_q(0, &[0.0, 0.5, 0.0, 1.0, 0.0, 0.0, 0.0]);
    body.set_joint_qd(0, &[0.0, -2.0, 0.0, 0.0, 0.0, 0.0]);

    let mut manifold = ContactManifold::new();
    use featherstone::contact::ContactPoint;
    manifold.add_contact(
        ContactPoint::new(0, Vector3::new(0.0, 0.0, 0.0), Vector3::zeros(), Vector3::y(), 0.01)
            .with_friction(0.3));

    // LCP
    let constraints = ContactConstraints::from_manifold(&body, &manifold);
    let lcp_config = LcpSolverConfig::default();
    let lcp_result = solve_contact_lcp(&body, &constraints, 0.001, &lcp_config);

    // Newton
    let bodies: Vec<&ArticulatedBody> = vec![&body];
    let offsets = vec![0usize];
    let counts = vec![body.dof_count()];
    use featherstone::contact_jacobian::InterBodyContact;
    let ground_contacts: Vec<(usize, &ContactManifold)> = vec![(0, &manifold)];
    let inter_contacts: Vec<InterBodyContact> = vec![];
    let eval = ConstraintFunction::evaluate_with_gradient(
        &bodies, &offsets, &counts, &ground_contacts, &inter_contacts);
    let m_inv = build_block_diagonal_m_inv(&bodies, &offsets, &counts, 6);
    let newton_result = solve_newton_contact(&bodies, &eval, &m_inv, &lcp_config);

    // Both should produce non-negative normal impulses
    assert!(!lcp_result.lambda_n.is_empty(), "LCP should have impulses");
    assert!(!newton_result.lambda_n.is_empty(), "Newton should have impulses");
    assert!(lcp_result.lambda_n[0] >= -1e-6, "LCP impulse non-negative");
    assert!(newton_result.lambda_n[0] >= -1e-6, "Newton impulse non-negative");
}

// ============================================================================
// SLAM Cycle 10: Floating-base quaternion + contact stress
// ============================================================================

/// Floating base with angular velocity: quaternion must remain unit over 2000 steps.
/// Tests quaternion integration accuracy across all integrators.
#[test]
fn test_floating_base_quaternion_unit_over_2000_steps() {
    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::zeros());
    body.add_body("base", -1, GenJointType::Floating,
        SpatialInertia::sphere(1.0, 0.2), SpatialTransform::identity());
    body.set_joint_q(0, &[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]);
    body.set_joint_qd(0, &[0.0, 0.0, 0.0, 1.0, 0.5, -0.3]); // spinning

    let config = IntegratorConfig {
        dt: 0.001,
        method: IntegrationMethod::SemiImplicitEuler,
        normalize_quaternions: true,
        ..Default::default()
    };

    for s in 0..2000 {
        step(&mut body, &config);

        // Check quaternion norm (q[3..7] = w, x, y, z)
        let w = body.q[3];
        let x = body.q[4];
        let y = body.q[5];
        let z = body.q[6];
        let norm = (w * w + x * x + y * y + z * z).sqrt();
        assert!(
            (norm - 1.0).abs() < 0.01,
            "Quaternion norm {} deviated from 1.0 at step {s}", norm
        );
    }
}

/// Multi-body branching tree dropped onto ground: full pipeline stress.
/// 6-body humanoid-like tree: torso → left_arm, right_arm, head, left_leg, right_leg.
#[test]
fn stress_humanoid_tree_drop_300_steps() {
    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::new(0.0, -9.81, 0.0));

    body.add_body("torso", -1, GenJointType::Floating,
        SpatialInertia::sphere(5.0, 0.3), SpatialTransform::identity());
    body.set_joint_q(0, &[0.0, 3.0, 0.0, 1.0, 0.0, 0.0, 0.0]);

    let limbs = [
        ("l_arm", Vector3::new(-0.4, 0.0, 0.0)),
        ("r_arm", Vector3::new(0.4, 0.0, 0.0)),
        ("head", Vector3::new(0.0, 0.4, 0.0)),
        ("l_leg", Vector3::new(-0.2, -0.5, 0.0)),
        ("r_leg", Vector3::new(0.2, -0.5, 0.0)),
    ];
    for (name, offset) in &limbs {
        body.add_body(*name, 0,
            GenJointType::Revolute { axis: Vector3::z() },
            make_inertia(1.0),
            SpatialTransform::from_translation(*offset));
    }

    let dt = 0.002;
    let lcp_config = LcpSolverConfig::default();

    for s in 0..300 {
        aba_forward_dynamics(&mut body);

        let manifold = ground_plane_contacts(&body, 0.0, Vector3::y(), 0.5, 0.0);
        let constraints = ContactConstraints::from_manifold(&body, &manifold);
        if constraints.has_contacts() {
            let result = solve_contact_lcp(&body, &constraints, dt, &lcp_config);
            for i in 0..body.dof_count().min(result.tau_contact.len()) {
                body.qd[i] += result.tau_contact[i] * dt;
            }
        }

        let config = IntegratorConfig {
            dt,
            method: IntegrationMethod::SemiImplicitEuler,
            normalize_quaternions: true,
            ..Default::default()
        };
        step(&mut body, &config);

        for i in 0..body.nq() {
            assert!(body.q[i].is_finite(), "q[{i}] not finite at step {s}");
        }
    }
}

// ============================================================================
// SLAM Cycle 11: Pipeline determinism and limits + contacts combined
// ============================================================================

/// Full pipeline determinism: running the same simulation twice produces identical results.
#[test]
fn test_full_pipeline_determinism() {
    let run_sim = || -> Vec<f32> {
        let mut body = make_chain(3, 1.0, 0.5);
        body.set_gravity(Vector3::new(0.0, -9.81, 0.0));
        body.q[0] = 0.5;
        body.q[1] = -0.3;

        let config = IntegratorConfig {
            dt: 0.001,
            method: IntegrationMethod::SemiImplicitEuler,
            ..Default::default()
        };
        for _ in 0..200 {
            step(&mut body, &config);
        }
        body.q.as_slice().to_vec()
    };

    let q1 = run_sim();
    let q2 = run_sim();

    for (i, (a, b)) in q1.iter().zip(q2.iter()).enumerate() {
        assert_eq!(*a, *b, "Pipeline must be deterministic: q[{i}] differs");
    }
}

/// Joint limits + contacts simultaneously: pendulum hits ground AND joint limit.
#[test]
fn test_limits_and_contacts_coexist() {
    use featherstone::limits::JointLimits;

    let mut body = ArticulatedBody::new();
    body.set_gravity(Vector3::new(0.0, -9.81, 0.0));
    body.add_body("base", -1, GenJointType::Floating,
        SpatialInertia::sphere(2.0, 0.2), SpatialTransform::identity());
    body.set_joint_q(0, &[0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0]);

    body.add_body("arm", 0,
        GenJointType::Revolute { axis: Vector3::z() },
        make_inertia(1.0),
        SpatialTransform::from_translation(Vector3::new(0.0, -0.5, 0.0)));
    body.q[7] = 1.5; // near limit

    let limits = JointLimits::single(-1.57, 1.57);
    let dt = 0.002;
    let lcp_config = LcpSolverConfig::default();

    for s in 0..200 {
        // Apply limit forces
        let lf = limits.compute_limit_force(&[body.q[7]], &[body.qd[6]]);
        body.tau[6] += lf[0];

        aba_forward_dynamics(&mut body);

        let manifold = ground_plane_contacts(&body, 0.0, Vector3::y(), 0.5, 0.0);
        let constraints = ContactConstraints::from_manifold(&body, &manifold);
        if constraints.has_contacts() {
            let result = solve_contact_lcp(&body, &constraints, dt, &lcp_config);
            for i in 0..body.dof_count().min(result.tau_contact.len()) {
                body.qd[i] += result.tau_contact[i] * dt;
            }
        }

        let config = IntegratorConfig {
            dt,
            method: IntegrationMethod::SemiImplicitEuler,
            normalize_quaternions: true,
            ..Default::default()
        };
        step(&mut body, &config);
        body.tau[6] = 0.0; // reset applied torque

        for i in 0..body.nq() {
            assert!(body.q[i].is_finite(), "q[{i}] not finite at step {s}");
        }
    }
}

// ============================================================================
// SLAM Cycle 13: Smooth+RK4 pipeline, ABA scaling
// ============================================================================

/// Smooth contact pipeline with RK4: accurate integrator + differentiable forces.
#[test]
fn test_smooth_contact_rk4_pipeline_stable() {
    use featherstone::smooth_contact::{smooth_contact_forces, SmoothContactConfig};

    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.2), SpatialTransform::identity());
    body.set_joint_q(0, &[0.0, 0.5, 0.0, 1.0, 0.0, 0.0, 0.0]);

    let smooth_config = SmoothContactConfig::default();
    let dt = 0.001;

    for _ in 0..500 {
        let manifold = ground_plane_contacts(&body, 0.0, Vector3::y(), 0.5, 0.0);
        let constraints = ContactConstraints::from_manifold(&body, &manifold);
        if constraints.has_contacts() {
            let result = smooth_contact_forces(&body, &constraints, &smooth_config);
            for i in 0..body.dof_count().min(result.tau_contact.len()) {
                body.tau[i] += result.tau_contact[i];
            }
        }

        let config = IntegratorConfig {
            dt,
            method: IntegrationMethod::RK4,
            normalize_quaternions: true,
            ..Default::default()
        };
        step(&mut body, &config);
        body.tau.fill(0.0);
    }

    for i in 0..body.nq() {
        assert!(body.q[i].is_finite(), "q[{i}] not finite after RK4+smooth pipeline");
    }
}

/// 5000-step long-running pendulum stress: energy should remain bounded (symplectic property).
#[test]
fn stress_5000_step_pendulum_energy_bounded() {
    let mut body = make_chain(2, 1.0, 0.5);
    body.set_gravity(Vector3::new(0.0, -9.81, 0.0));
    body.q[0] = 1.0;

    let config = IntegratorConfig {
        dt: 0.001,
        method: IntegrationMethod::SemiImplicitEuler,
        ..Default::default()
    };

    let initial_ke = 0.5 * body.qd.dot(&(&crba_mass_matrix(&body) * &body.qd));
    let initial_pe = 9.81 * 0.5 * (1.0 - body.q[0].cos());
    let initial_e = initial_ke + initial_pe;

    for s in 0..5000 {
        step(&mut body, &config);
        if s % 1000 == 999 {
            let m = crba_mass_matrix(&body);
            let ke = 0.5 * body.qd.dot(&(&m * &body.qd));
            assert!(ke.is_finite(), "KE not finite at step {s}");
            assert!(ke >= 0.0, "KE negative at step {s}: {ke}");
        }
    }

    // Final energy check — symplectic should bound energy (not conserve exactly)
    let m = crba_mass_matrix(&body);
    let final_ke = 0.5 * body.qd.dot(&(&m * &body.qd));
    let final_pe = 9.81 * 0.5 * (1.0 - body.q[0].cos());
    let final_e = final_ke + final_pe;

    // Symplectic integrators bound energy (don't conserve) — multi-body coupling amplifies drift.
    // For a 2-link chain at dt=0.001 over 5 seconds, energy should stay within 10x of initial.
    assert!(
        final_e < initial_e.abs() * 10.0 + 5.0,
        "Energy diverged catastrophically: initial={initial_e}, final={final_e}"
    );
    assert!(final_e.is_finite(), "Energy must remain finite");
}

/// ABA works for various chain lengths (1 to 15 bodies).
#[test]
fn test_aba_various_chain_lengths() {
    for n in [1usize, 2, 5, 10, 15] {
        let mut body = ArticulatedBody::new();
        body.set_gravity(Vector3::new(0.0, -9.81, 0.0));
        for i in 0..n {
            let parent = if i == 0 { -1 } else { (i - 1) as i32 };
            body.add_body(
                format!("l{i}"), parent,
                GenJointType::Revolute { axis: Vector3::z() },
                make_inertia(1.0),
                SpatialTransform::from_translation(Vector3::new(0.0, -0.3, 0.0)));
        }

        aba_forward_dynamics(&mut body);
        for i in 0..body.dof_count() {
            assert!(body.qdd[i].is_finite(),
                "ABA qdd[{i}] not finite for {n}-body chain");
        }
    }
}

// ============================================================================
// SLAM Cycle 15: Physics intent tests (Level 7)
// ============================================================================

/// Intent: Kinetic energy (0.5 * qd^T * M * qd) must always be non-negative.
#[test]
fn intent_kinetic_energy_always_non_negative() {
    let configs: Vec<(f32, f32, f32, f32)> = vec![
        (0.5, -0.3, 2.0, -1.0),
        (1.0, 0.0, 0.0, 5.0),
        (-1.5, 0.7, -3.0, 0.1),
        (0.0, 0.0, 0.0, 0.0), // zero velocity → zero KE
    ];

    for (i, (q0, q1, qd0, qd1)) in configs.iter().enumerate() {
        let mut body = make_chain(2, 1.0, 0.5);
        body.q[0] = *q0;
        body.q[1] = *q1;
        body.qd[0] = *qd0;
        body.qd[1] = *qd1;

        let m = crba_mass_matrix(&body);
        let ke = 0.5 * body.qd.dot(&(&m * &body.qd));

        assert!(ke >= -1e-6, "Case {i}: KE={ke} must be >= 0 (physics: energy non-negative)");
    }
}

/// Intent: RNEA and ABA are inverses — for any configuration, applying RNEA-computed
/// torques with ABA should recover the original accelerations.
#[test]
fn intent_rnea_aba_inverse_duality() {
    let mut body = make_chain(3, 1.0, 0.5);
    body.set_gravity(Vector3::new(0.0, -9.81, 0.0));
    body.q[0] = 0.7;
    body.q[1] = -0.4;
    body.q[2] = 1.1;
    body.qd[0] = 1.5;
    body.qd[1] = -0.8;
    body.qd[2] = 0.3;

    // Desired accelerations
    let desired_qdd = vec![2.0, -1.0, 0.5];
    for (i, &v) in desired_qdd.iter().enumerate() {
        body.qdd[i] = v;
    }

    // RNEA: given (q, qd, qdd) → compute required tau
    let (tau, _) = rnea_inverse_dynamics(&body);

    // ABA: given (q, qd, tau) → recover qdd
    for i in 0..body.dof_count() {
        body.tau[i] = tau[i];
    }
    aba_forward_dynamics(&mut body);

    // Recovered qdd should match desired
    for i in 0..body.dof_count() {
        assert!(
            (body.qdd[i] - desired_qdd[i]).abs() < 0.1,
            "RNEA/ABA duality: qdd[{i}]={} vs desired={}",
            body.qdd[i], desired_qdd[i]
        );
    }
}

/// Intent: Mass matrix eigenvalues increase when adding more distal mass.
/// This follows from the parallel axis theorem.
#[test]
fn intent_mass_matrix_eigenvalues_grow_with_distal_mass() {
    let mut body_light = make_chain(2, 0.5, 0.5);
    let mut body_heavy = make_chain(2, 5.0, 0.5);

    let m_light = crba_mass_matrix(&body_light);
    let m_heavy = crba_mass_matrix(&body_heavy);

    let eig_light = m_light.symmetric_eigenvalues();
    let eig_heavy = m_heavy.symmetric_eigenvalues();

    let max_light = eig_light.iter().copied().fold(f32::NEG_INFINITY, f32::max);
    let max_heavy = eig_heavy.iter().copied().fold(f32::NEG_INFINITY, f32::max);

    assert!(max_heavy > max_light,
        "Heavier chain should have larger max eigenvalue: light={max_light}, heavy={max_heavy}");
}

/// Intent: Bias forces (Coriolis + gravity) should be zero for a chain with zero gravity and zero velocity.
#[test]
fn intent_bias_forces_zero_at_rest_no_gravity() {
    let mut body = make_chain(3, 1.0, 0.5);
    body.set_gravity(Vector3::zeros());
    // All state defaults to zero

    let c = featherstone::crba::bias_forces(&mut body);

    for i in 0..c.len() {
        assert!(c[i].abs() < 1e-6,
            "Bias forces at rest with no gravity should be zero: c[{i}]={}", c[i]);
    }
}