oxiphysics-softbody 0.1.2

Soft body simulation for the OxiPhysics engine
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
// Copyright 2026 COOLJAPAN OU (Team KitaSan)
// SPDX-License-Identifier: Apache-2.0

//! Muscle simulation module for the OxiPhysics soft-body crate.
//!
//! Provides a comprehensive Hill-type muscle model with:
//!
//! - **Contractile element (CE)** – active force generation
//! - **Parallel elastic element (PE)** – passive tissue elasticity
//! - **Series elastic element (SE)** – tendon compliance
//! - **Activation dynamics** – neural excitation to activation mapping
//! - **Force-length relationship** – Gaussian active + exponential passive
//! - **Force-velocity relationship** – Hill hyperbola
//! - **Pennation angle** – fiber architecture
//! - **Tendon mechanics** – nonlinear tendon force-strain
//! - **Musculotendon equilibrium** – static/dynamic equilibrium solver
//! - **Fatigue modeling** – endurance and recovery
//! - **Fiber recruitment** – motor unit recruitment model
//! - **Isometric/isotonic contractions** – fixed-length and fixed-load modes

// ---------------------------------------------------------------------------
// Helper math (no nalgebra)
// ---------------------------------------------------------------------------

/// 3-D Euclidean norm.
#[inline]
fn norm3(v: [f64; 3]) -> f64 {
    (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt()
}

/// Subtract two 3-D vectors: a - b.
#[inline]
fn sub3(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}

/// Add two 3-D vectors.
#[inline]
fn add3(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
    [a[0] + b[0], a[1] + b[1], a[2] + b[2]]
}

/// Scale a 3-D vector.
#[inline]
fn scale3(v: [f64; 3], s: f64) -> [f64; 3] {
    [v[0] * s, v[1] * s, v[2] * s]
}

/// Normalize a 3-D vector (returns zero if degenerate).
#[inline]
fn normalize3(v: [f64; 3]) -> [f64; 3] {
    let n = norm3(v);
    if n < 1e-15 {
        [0.0; 3]
    } else {
        scale3(v, 1.0 / n)
    }
}

/// Dot product of two 3-D vectors.
#[inline]
fn dot3(a: [f64; 3], b: [f64; 3]) -> f64 {
    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}

/// Clamp `x` to `[lo, hi]`.
#[inline]
fn clamp(x: f64, lo: f64, hi: f64) -> f64 {
    x.max(lo).min(hi)
}

// ===========================================================================
// 1. Activation Dynamics
// ===========================================================================

/// First-order activation dynamics model.
///
/// Maps neural excitation u(t) in \[0, 1\] to muscle activation a(t) in \[0, 1\]
/// via first-order ODE:
///   da/dt = (u - a) / tau(a, u)
///
/// where tau depends on whether the muscle is activating or deactivating.
#[derive(Debug, Clone)]
pub struct ActivationDynamics {
    /// Activation time constant (s).
    pub tau_act: f64,
    /// Deactivation time constant (s).
    pub tau_deact: f64,
    /// Minimum activation level (prevents numerical issues).
    pub a_min: f64,
    /// Current activation level.
    activation: f64,
}

impl ActivationDynamics {
    /// Create new activation dynamics.
    pub fn new(tau_act: f64, tau_deact: f64) -> Self {
        Self {
            tau_act,
            tau_deact,
            a_min: 0.01,
            activation: 0.0,
        }
    }

    /// Default fast-twitch muscle dynamics.
    pub fn fast_twitch() -> Self {
        Self::new(0.010, 0.040)
    }

    /// Default slow-twitch muscle dynamics.
    pub fn slow_twitch() -> Self {
        Self::new(0.025, 0.060)
    }

    /// Get current activation level.
    pub fn activation(&self) -> f64 {
        self.activation
    }

    /// Set activation directly.
    pub fn set_activation(&mut self, a: f64) {
        self.activation = clamp(a, 0.0, 1.0);
    }

    /// Update activation given neural excitation u in \[0, 1\].
    pub fn update(&mut self, u: f64, dt: f64) -> f64 {
        let u_c = clamp(u, 0.0, 1.0);
        let tau = if u_c > self.activation {
            self.tau_act * (0.5 + 1.5 * self.activation)
        } else {
            self.tau_deact / (0.5 + 1.5 * self.activation)
        };
        let tau_safe = tau.max(1e-6);
        let da = (u_c - self.activation) / tau_safe * dt;
        self.activation = clamp(self.activation + da, self.a_min, 1.0);
        self.activation
    }

    /// Reset activation to zero.
    pub fn reset(&mut self) {
        self.activation = 0.0;
    }

    /// Compute the time constant at current state for a given excitation.
    pub fn current_tau(&self, u: f64) -> f64 {
        if u > self.activation {
            self.tau_act * (0.5 + 1.5 * self.activation)
        } else {
            self.tau_deact / (0.5 + 1.5 * self.activation).max(0.5)
        }
    }
}

// ===========================================================================
// 2. Force-Length Relationship
// ===========================================================================

/// Active and passive force-length curves for muscle fibers.
///
/// Active: Gaussian centered at optimal length
/// Passive: Exponential stiffening beyond optimal length
#[derive(Debug, Clone)]
pub struct ForceLengthCurve {
    /// Width of the active force-length Gaussian.
    pub gamma: f64,
    /// Passive force exponential shape factor.
    pub kpe: f64,
    /// Passive force strain offset (normalized length at which PE kicks in).
    pub e0: f64,
    /// Maximum passive force (normalized to F_max).
    pub f_pe_max: f64,
}

impl ForceLengthCurve {
    /// Create a new force-length curve.
    pub fn new(gamma: f64, kpe: f64, e0: f64, f_pe_max: f64) -> Self {
        Self {
            gamma,
            kpe,
            e0,
            f_pe_max,
        }
    }

    /// Default curve (Thelen 2003 parameters).
    pub fn thelen2003() -> Self {
        Self::new(0.45, 4.0, 0.6, 1.0)
    }

    /// Compute the normalized active force-length value.
    ///
    /// f_active(l_norm) = exp(-((l_norm - 1) / gamma)^2)
    pub fn active(&self, l_norm: f64) -> f64 {
        let x = (l_norm - 1.0) / self.gamma;
        (-x * x).exp()
    }

    /// Compute the normalized passive force-length value.
    ///
    /// f_passive(l_norm) = (exp(kpe*(l_norm - 1)/e0) - 1) / (exp(kpe) - 1)
    pub fn passive(&self, l_norm: f64) -> f64 {
        if l_norm <= 1.0 {
            return 0.0;
        }
        let strain = l_norm - 1.0;
        let num = (self.kpe * strain / self.e0).exp() - 1.0;
        let den = self.kpe.exp() - 1.0;
        (self.f_pe_max * num / den).max(0.0)
    }

    /// Total (active + passive) normalized force at given activation.
    pub fn total(&self, l_norm: f64, activation: f64) -> f64 {
        activation * self.active(l_norm) + self.passive(l_norm)
    }

    /// Compute the slope (stiffness) of the active curve at l_norm.
    pub fn active_stiffness(&self, l_norm: f64) -> f64 {
        let x = (l_norm - 1.0) / self.gamma;
        -2.0 * x / self.gamma * (-x * x).exp()
    }

    /// Compute the slope (stiffness) of the passive curve at l_norm.
    pub fn passive_stiffness(&self, l_norm: f64) -> f64 {
        if l_norm <= 1.0 {
            return 0.0;
        }
        let strain = l_norm - 1.0;
        let den = self.kpe.exp() - 1.0;
        self.f_pe_max * self.kpe / (self.e0 * den) * (self.kpe * strain / self.e0).exp()
    }
}

// ===========================================================================
// 3. Force-Velocity Relationship
// ===========================================================================

/// Force-velocity relationship for muscle fibers (Hill curve).
///
/// Concentric (shortening): hyperbolic curve
/// Eccentric (lengthening): asymptotic to f_ecc_max
#[derive(Debug, Clone)]
pub struct ForceVelocityCurve {
    /// Shape parameter for the Hill curve (a_f / F_max).
    pub af: f64,
    /// Maximum eccentric force ratio.
    pub f_ecc_max: f64,
    /// Eccentric curve shape parameter.
    pub eccentric_shape: f64,
}

impl ForceVelocityCurve {
    /// Create a new force-velocity curve.
    pub fn new(af: f64, f_ecc_max: f64, eccentric_shape: f64) -> Self {
        Self {
            af,
            f_ecc_max,
            eccentric_shape,
        }
    }

    /// Default parameters (Thelen 2003).
    pub fn thelen2003() -> Self {
        Self::new(0.25, 1.8, 0.1)
    }

    /// Compute the normalized force-velocity value.
    ///
    /// v_norm = v / v_max, negative for shortening
    pub fn evaluate(&self, v_norm: f64) -> f64 {
        if v_norm <= 0.0 {
            // Concentric (shortening): (1 + v_norm/a_f) / (1 - v_norm/a_f)
            // But with v_norm negative for shortening: use |v_norm|
            let v_abs = (-v_norm).min(0.999);
            (1.0 - v_abs) / (1.0 + v_abs / self.af)
        } else {
            // Eccentric (lengthening)
            let v_c = v_norm.min(0.999);
            let num = self.f_ecc_max * v_c + self.eccentric_shape;
            let den = v_c + self.eccentric_shape;
            num / den
        }
    }

    /// Compute the inverse: given f_v, find v_norm (concentric only).
    pub fn inverse_concentric(&self, f_v: f64) -> f64 {
        let f_v_c = clamp(f_v, 0.0, 1.0 - 1e-6);
        // From (1 - |v|) / (1 + |v|/af) = fv
        // |v| = (1 - fv) / (1 + fv/af)
        let v_abs = (1.0 - f_v_c) / (1.0 + f_v_c / self.af);
        -v_abs
    }

    /// Compute the slope at a given normalized velocity.
    pub fn slope(&self, v_norm: f64) -> f64 {
        let dv = 1e-6;
        let f1 = self.evaluate(v_norm - dv);
        let f2 = self.evaluate(v_norm + dv);
        (f2 - f1) / (2.0 * dv)
    }
}

// ===========================================================================
// 4. Pennation Angle Model
// ===========================================================================

/// Pennation angle model for muscle fiber architecture.
///
/// The pennation angle changes with fiber length to maintain constant
/// muscle thickness (constant volume assumption):
///   sin(alpha) = sin(alpha_opt) * l_opt / l_fiber
#[derive(Debug, Clone)]
pub struct PennationModel {
    /// Pennation angle at optimal fiber length (rad).
    pub alpha_opt: f64,
    /// Optimal fiber length (m).
    pub l_opt: f64,
    /// Muscle thickness at optimal length (m).
    thickness: f64,
}

impl PennationModel {
    /// Create a new pennation model.
    pub fn new(alpha_opt: f64, l_opt: f64) -> Self {
        let thickness = l_opt * alpha_opt.sin();
        Self {
            alpha_opt,
            l_opt,
            thickness,
        }
    }

    /// No pennation (alpha = 0).
    pub fn zero() -> Self {
        Self::new(0.0, 1.0)
    }

    /// Compute the current pennation angle for a given fiber length.
    pub fn angle(&self, fiber_length: f64) -> f64 {
        if fiber_length < 1e-15 {
            return self.alpha_opt;
        }
        let sin_alpha = (self.thickness / fiber_length).min(0.999);
        sin_alpha.asin()
    }

    /// Compute cos(alpha) for force projection along tendon.
    pub fn cos_alpha(&self, fiber_length: f64) -> f64 {
        self.angle(fiber_length).cos()
    }

    /// Compute the fiber length from musculotendon length and tendon length.
    pub fn fiber_length_from_mt(&self, mt_length: f64, tendon_length: f64) -> f64 {
        let l_fiber_along = (mt_length - tendon_length).max(0.0);
        (l_fiber_along * l_fiber_along + self.thickness * self.thickness).sqrt()
    }

    /// Compute the fiber velocity from musculotendon velocity.
    pub fn fiber_velocity_from_mt(&self, mt_velocity: f64, fiber_length: f64) -> f64 {
        let cos_a = self.cos_alpha(fiber_length);
        if cos_a > 1e-6 {
            mt_velocity / cos_a
        } else {
            mt_velocity
        }
    }

    /// Compute the muscle thickness (constant volume assumption).
    pub fn muscle_thickness(&self) -> f64 {
        self.thickness
    }
}

// ===========================================================================
// 5. Tendon Mechanics
// ===========================================================================

/// Nonlinear tendon model.
///
/// The tendon force-strain relationship is modeled as a piecewise function:
/// - Toe region (0 < strain < strain_toe): quadratic
/// - Linear region (strain > strain_toe): linear with stiffness kT
/// - Slack region (strain < 0): zero force
#[derive(Debug, Clone)]
pub struct TendonModel {
    /// Tendon slack length (m).
    pub slack_length: f64,
    /// Maximum isometric force (N) for normalization.
    pub f_max: f64,
    /// Toe region strain limit.
    pub strain_toe: f64,
    /// Tendon stiffness in the linear region (normalized).
    pub k_toe: f64,
    /// Linear region stiffness (normalized).
    pub k_linear: f64,
}

impl TendonModel {
    /// Create a new tendon model.
    pub fn new(slack_length: f64, f_max: f64) -> Self {
        Self {
            slack_length,
            f_max,
            strain_toe: 0.033,
            k_toe: 1.712 / 0.033,
            k_linear: 37.5,
        }
    }

    /// Create a rigid tendon (infinite stiffness approximation).
    pub fn rigid(slack_length: f64, f_max: f64) -> Self {
        Self {
            slack_length,
            f_max,
            strain_toe: 0.001,
            k_toe: 1000.0,
            k_linear: 10000.0,
        }
    }

    /// Compute the tendon strain from tendon length.
    pub fn strain(&self, tendon_length: f64) -> f64 {
        if self.slack_length > 1e-15 {
            (tendon_length - self.slack_length) / self.slack_length
        } else {
            0.0
        }
    }

    /// Compute the normalized tendon force from tendon strain.
    ///
    /// Returns force / F_max.
    pub fn force_normalized(&self, strain: f64) -> f64 {
        if strain <= 0.0 {
            0.0
        } else if strain <= self.strain_toe {
            // Quadratic toe region
            let ratio = strain / self.strain_toe;
            0.5 * self.k_toe * self.strain_toe * ratio * ratio
        } else {
            // Linear region
            let f_toe = 0.5 * self.k_toe * self.strain_toe;
            f_toe + self.k_linear * (strain - self.strain_toe)
        }
    }

    /// Compute the tendon force (N) from tendon length.
    pub fn force(&self, tendon_length: f64) -> f64 {
        let eps = self.strain(tendon_length);
        self.force_normalized(eps) * self.f_max
    }

    /// Compute the tendon stiffness (dF/dl) at the current length.
    pub fn stiffness(&self, tendon_length: f64) -> f64 {
        let eps = self.strain(tendon_length);
        if eps <= 0.0 {
            0.0
        } else if eps <= self.strain_toe {
            let ratio = eps / self.strain_toe;
            self.k_toe * ratio * self.f_max / self.slack_length
        } else {
            self.k_linear * self.f_max / self.slack_length
        }
    }

    /// Compute the tendon length from a given force (inverse).
    pub fn length_from_force(&self, force: f64) -> f64 {
        let f_norm = force / self.f_max;
        let strain = if f_norm <= 0.0 {
            0.0
        } else {
            let f_toe = 0.5 * self.k_toe * self.strain_toe;
            if f_norm <= f_toe {
                // Inverse of quadratic: strain = strain_toe * sqrt(2*f_norm / (k_toe * strain_toe))
                self.strain_toe * (2.0 * f_norm / (self.k_toe * self.strain_toe)).sqrt()
            } else {
                // Inverse of linear
                self.strain_toe + (f_norm - f_toe) / self.k_linear
            }
        };
        self.slack_length * (1.0 + strain)
    }
}

// ===========================================================================
// 6. Hill-Type Muscle Model (Complete)
// ===========================================================================

/// Complete Hill-type muscle model with all three elements.
///
/// Combines contractile element (CE), parallel elastic element (PE),
/// and series elastic element (SE/tendon) into a unified musculotendon
/// actuator.
#[derive(Debug, Clone)]
pub struct HillMuscleSoftbody {
    /// Maximum isometric force (N).
    pub f_max: f64,
    /// Optimal fiber length (m).
    pub l_opt: f64,
    /// Maximum fiber shortening velocity (l_opt/s).
    pub v_max: f64,
    /// Activation dynamics.
    pub activation: ActivationDynamics,
    /// Force-length curve.
    pub fl_curve: ForceLengthCurve,
    /// Force-velocity curve.
    pub fv_curve: ForceVelocityCurve,
    /// Pennation model.
    pub pennation: PennationModel,
    /// Tendon model.
    pub tendon: TendonModel,
    /// Current fiber length (m).
    fiber_length: f64,
    /// Current fiber velocity (m/s).
    fiber_velocity: f64,
    /// Current tendon length (m).
    tendon_length: f64,
    /// Current total force output (N).
    force: f64,
}

impl HillMuscleSoftbody {
    /// Create a new Hill muscle model.
    pub fn new(
        f_max: f64,
        l_opt: f64,
        v_max: f64,
        pennation_angle: f64,
        tendon_slack_length: f64,
    ) -> Self {
        Self {
            f_max,
            l_opt,
            v_max,
            activation: ActivationDynamics::fast_twitch(),
            fl_curve: ForceLengthCurve::thelen2003(),
            fv_curve: ForceVelocityCurve::thelen2003(),
            pennation: PennationModel::new(pennation_angle, l_opt),
            tendon: TendonModel::new(tendon_slack_length, f_max),
            fiber_length: l_opt,
            fiber_velocity: 0.0,
            tendon_length: tendon_slack_length,
            force: 0.0,
        }
    }

    /// Create a muscle with typical parameters.
    pub fn typical(f_max: f64, l_opt: f64, tendon_slack_length: f64) -> Self {
        Self::new(f_max, l_opt, 10.0, 0.0, tendon_slack_length)
    }

    /// Get the current muscle force (N).
    pub fn force(&self) -> f64 {
        self.force
    }

    /// Get the current fiber length.
    pub fn fiber_length(&self) -> f64 {
        self.fiber_length
    }

    /// Get the current fiber velocity.
    pub fn fiber_velocity(&self) -> f64 {
        self.fiber_velocity
    }

    /// Get the current tendon length.
    pub fn tendon_length(&self) -> f64 {
        self.tendon_length
    }

    /// Get the current activation.
    pub fn current_activation(&self) -> f64 {
        self.activation.activation()
    }

    /// Compute the muscle force for given state variables.
    pub fn compute_force(&self, activation: f64, fiber_length: f64, fiber_velocity: f64) -> f64 {
        let l_norm = fiber_length / self.l_opt;
        let v_norm = fiber_velocity / (self.v_max * self.l_opt);

        let f_active = activation * self.fl_curve.active(l_norm) * self.fv_curve.evaluate(v_norm);
        let f_passive = self.fl_curve.passive(l_norm);
        let cos_a = self.pennation.cos_alpha(fiber_length);

        self.f_max * (f_active + f_passive) * cos_a
    }

    /// Update the muscle state for a given excitation and musculotendon length/velocity.
    pub fn update(&mut self, excitation: f64, mt_length: f64, mt_velocity: f64, dt: f64) {
        // 1. Update activation
        self.activation.update(excitation, dt);
        let a = self.activation.activation();

        // 2. Solve musculotendon equilibrium (rigid tendon approximation)
        self.tendon_length = self.tendon.slack_length;
        self.fiber_length = self
            .pennation
            .fiber_length_from_mt(mt_length, self.tendon_length);
        self.fiber_velocity = self
            .pennation
            .fiber_velocity_from_mt(mt_velocity, self.fiber_length);

        // 3. Compute force
        self.force = self.compute_force(a, self.fiber_length, self.fiber_velocity);
    }

    /// Solve the static musculotendon equilibrium.
    ///
    /// Finds the fiber length where CE+PE force = tendon force.
    pub fn solve_equilibrium(&mut self, activation: f64, mt_length: f64) {
        let a = clamp(activation, 0.0, 1.0);

        // Newton iteration to find fiber length
        let mut l_fiber = self.fiber_length;
        for _ in 0..50 {
            let cos_a = self.pennation.cos_alpha(l_fiber);
            let l_norm = l_fiber / self.l_opt;

            // Muscle force along tendon
            let f_muscle = self.f_max
                * (a * self.fl_curve.active(l_norm) + self.fl_curve.passive(l_norm))
                * cos_a;

            // Tendon length and force
            let l_tendon = mt_length - l_fiber * cos_a;
            let f_tendon = self.tendon.force(l_tendon);

            let residual = f_muscle - f_tendon;
            if residual.abs() < 1e-4 {
                break;
            }

            // Simple bisection-like step
            let dl = -residual / (self.f_max * 10.0 / self.l_opt);
            l_fiber = (l_fiber + dl).max(0.5 * self.l_opt).min(1.5 * self.l_opt);
        }

        self.fiber_length = l_fiber;
        let cos_a = self.pennation.cos_alpha(l_fiber);
        self.tendon_length = mt_length - l_fiber * cos_a;
        self.force = self.tendon.force(self.tendon_length);
    }

    /// Reset the muscle to its initial state.
    pub fn reset(&mut self) {
        self.activation.reset();
        self.fiber_length = self.l_opt;
        self.fiber_velocity = 0.0;
        self.tendon_length = self.tendon.slack_length;
        self.force = 0.0;
    }
}

// ===========================================================================
// 7. Fatigue Model
// ===========================================================================

/// Muscle fatigue model based on the three-compartment scheme.
///
/// Motor units transition between three states:
/// - MA: active motor units (currently generating force)
/// - MF: fatigued motor units (temporarily unable to fire)
/// - MR: resting motor units (available for recruitment)
///
/// The total is conserved: MA + MF + MR = 1.
#[derive(Debug, Clone)]
pub struct FatigueModel {
    /// Fatigue rate constant (1/s).
    pub fatigue_rate: f64,
    /// Recovery rate constant (1/s).
    pub recovery_rate: f64,
    /// Active motor unit fraction.
    pub ma: f64,
    /// Fatigued motor unit fraction.
    pub mf: f64,
    /// Resting motor unit fraction.
    pub mr: f64,
    /// Target activation demand.
    target_activation: f64,
}

impl FatigueModel {
    /// Create a new fatigue model.
    pub fn new(fatigue_rate: f64, recovery_rate: f64) -> Self {
        Self {
            fatigue_rate,
            recovery_rate,
            ma: 0.0,
            mf: 0.0,
            mr: 1.0,
            target_activation: 0.0,
        }
    }

    /// Default fatigue parameters for a mixed-fiber muscle.
    pub fn default_mixed() -> Self {
        Self::new(0.01, 0.002)
    }

    /// Default fatigue parameters for a fast-twitch dominant muscle.
    pub fn fast_twitch() -> Self {
        Self::new(0.02, 0.003)
    }

    /// Default fatigue parameters for a slow-twitch dominant muscle.
    pub fn slow_twitch() -> Self {
        Self::new(0.005, 0.001)
    }

    /// Set the target activation demand.
    pub fn set_target(&mut self, target: f64) {
        self.target_activation = clamp(target, 0.0, 1.0);
    }

    /// Update the fatigue state.
    ///
    /// Returns the effective (fatigued) activation level.
    pub fn update(&mut self, dt: f64) -> f64 {
        let target = self.target_activation;

        // Recruitment: try to bring MA up to target from MR
        let recruit = if target > self.ma && self.mr > 0.0 {
            let needed = (target - self.ma).min(self.mr);
            needed * dt * 10.0 // recruitment rate
        } else {
            0.0
        };

        // De-recruitment: if target < MA, release to MR
        let derecruit = if target < self.ma {
            (self.ma - target) * dt * 5.0
        } else {
            0.0
        };

        // Fatigue: active units become fatigued
        let fatigue = self.fatigue_rate * self.ma * dt;

        // Recovery: fatigued units recover to resting
        let recovery = self.recovery_rate * self.mf * dt;

        // Update compartments
        self.ma = (self.ma + recruit - derecruit - fatigue).max(0.0);
        self.mf = (self.mf + fatigue - recovery).max(0.0);
        self.mr = (self.mr - recruit + derecruit + recovery).max(0.0);

        // Normalize to ensure conservation
        let total = self.ma + self.mf + self.mr;
        if total > 1e-15 {
            self.ma /= total;
            self.mf /= total;
            self.mr /= total;
        }

        self.ma
    }

    /// Get the endurance time estimate for a given contraction intensity.
    ///
    /// Based on Rohmert's curve: T = (f_max / F - 1)^k / fatigue_rate
    pub fn endurance_time(&self, intensity: f64) -> f64 {
        let intensity_c = clamp(intensity, 0.01, 0.99);
        let k = 1.5;
        ((1.0 / intensity_c - 1.0).powf(k)) / self.fatigue_rate
    }

    /// Get the total fatigue fraction (fraction of fatigued units).
    pub fn fatigue_fraction(&self) -> f64 {
        self.mf
    }

    /// Check if the muscle is significantly fatigued.
    pub fn is_fatigued(&self) -> bool {
        self.mf > 0.3
    }

    /// Reset the fatigue state to fully rested.
    pub fn reset(&mut self) {
        self.ma = 0.0;
        self.mf = 0.0;
        self.mr = 1.0;
        self.target_activation = 0.0;
    }
}

// ===========================================================================
// 8. Fiber Recruitment Model
// ===========================================================================

/// Motor unit recruitment model (Henneman's size principle).
///
/// Motor units are recruited from smallest (slow-twitch) to largest
/// (fast-twitch) as excitation increases. Each motor unit has a
/// recruitment threshold and contributes a fixed force increment.
#[derive(Debug, Clone)]
pub struct FiberRecruitment {
    /// Number of motor units.
    pub num_units: usize,
    /// Recruitment thresholds (sorted, in \[0, 1\]).
    pub thresholds: Vec<f64>,
    /// Force contributions per motor unit (normalized).
    pub force_contributions: Vec<f64>,
    /// Fiber type fractions (0 = slow-twitch, 1 = fast-twitch).
    pub fiber_types: Vec<f64>,
    /// Current recruitment states (true = recruited).
    recruited: Vec<bool>,
}

impl FiberRecruitment {
    /// Create a new recruitment model with n motor units.
    pub fn new(num_units: usize) -> Self {
        let mut thresholds = Vec::with_capacity(num_units);
        let mut forces = Vec::with_capacity(num_units);
        let mut types = Vec::with_capacity(num_units);

        for i in 0..num_units {
            let t = (i as f64) / (num_units as f64 - 1.0).max(1.0);
            thresholds.push(t);
            // Exponential force sizing: larger units produce more force
            forces.push((2.0 * t).exp());
            types.push(t); // linear mix from slow to fast
        }

        // Normalize force contributions
        let total: f64 = forces.iter().sum();
        for f in &mut forces {
            *f /= total;
        }

        Self {
            num_units,
            thresholds,
            force_contributions: forces,
            fiber_types: types,
            recruited: vec![false; num_units],
        }
    }

    /// Create a model with 50% slow / 50% fast split.
    pub fn mixed_fiber(num_units: usize) -> Self {
        Self::new(num_units)
    }

    /// Update recruitment based on current excitation level.
    pub fn update(&mut self, excitation: f64) {
        let e = clamp(excitation, 0.0, 1.0);
        for i in 0..self.num_units {
            self.recruited[i] = e >= self.thresholds[i];
        }
    }

    /// Compute the total normalized force from recruited units.
    pub fn total_force(&self) -> f64 {
        let mut total = 0.0;
        for i in 0..self.num_units {
            if self.recruited[i] {
                total += self.force_contributions[i];
            }
        }
        total
    }

    /// Count the number of currently recruited motor units.
    pub fn num_recruited(&self) -> usize {
        self.recruited.iter().filter(|&&r| r).count()
    }

    /// Get the average fiber type of recruited units (0 = slow, 1 = fast).
    pub fn average_fiber_type(&self) -> f64 {
        let mut sum_type = 0.0;
        let mut count = 0;
        for i in 0..self.num_units {
            if self.recruited[i] {
                sum_type += self.fiber_types[i];
                count += 1;
            }
        }
        if count > 0 {
            sum_type / count as f64
        } else {
            0.0
        }
    }

    /// Reset all units to un-recruited state.
    pub fn reset(&mut self) {
        for r in &mut self.recruited {
            *r = false;
        }
    }
}

// ===========================================================================
// 9. Isometric / Isotonic Contraction Modes
// ===========================================================================

/// Isometric contraction state (fixed muscle-tendon length).
///
/// The muscle generates force at a fixed total length. Useful for
/// computing the force-activation relationship at a specific pose.
#[derive(Debug, Clone)]
pub struct IsometricContraction {
    /// Fixed musculotendon length (m).
    pub mt_length: f64,
    /// The underlying muscle model.
    pub muscle: HillMuscleSoftbody,
}

impl IsometricContraction {
    /// Create a new isometric contraction experiment.
    pub fn new(muscle: HillMuscleSoftbody, mt_length: f64) -> Self {
        Self { mt_length, muscle }
    }

    /// Compute the isometric force at a given activation level.
    pub fn force_at_activation(&mut self, activation: f64) -> f64 {
        self.muscle.solve_equilibrium(activation, self.mt_length);
        self.muscle.force()
    }

    /// Run a ramp-and-hold activation protocol.
    ///
    /// Returns a vector of (time, force) pairs.
    pub fn ramp_hold(
        &mut self,
        ramp_time: f64,
        hold_time: f64,
        dt: f64,
        max_activation: f64,
    ) -> Vec<(f64, f64)> {
        let mut results = Vec::new();
        let total_time = ramp_time + hold_time;
        let mut t = 0.0;

        while t < total_time {
            let excitation = if t < ramp_time {
                max_activation * t / ramp_time
            } else {
                max_activation
            };

            self.muscle.update(excitation, self.mt_length, 0.0, dt);
            results.push((t, self.muscle.force()));
            t += dt;
        }
        results
    }

    /// Compute the maximum isometric force (at full activation).
    pub fn max_force(&mut self) -> f64 {
        self.force_at_activation(1.0)
    }
}

/// Isotonic contraction state (fixed external load).
///
/// The muscle shortens or lengthens against a constant load.
#[derive(Debug, Clone)]
pub struct IsotonicContraction {
    /// External load (N).
    pub load: f64,
    /// The underlying muscle model.
    pub muscle: HillMuscleSoftbody,
    /// Current musculotendon length (m).
    pub mt_length: f64,
    /// Current musculotendon velocity (m/s).
    pub mt_velocity: f64,
}

impl IsotonicContraction {
    /// Create a new isotonic contraction.
    pub fn new(muscle: HillMuscleSoftbody, load: f64, initial_mt_length: f64) -> Self {
        Self {
            load,
            muscle,
            mt_length: initial_mt_length,
            mt_velocity: 0.0,
        }
    }

    /// Update the isotonic contraction for one time step.
    ///
    /// The muscle adjusts its velocity to match the external load.
    pub fn update(&mut self, excitation: f64, dt: f64) {
        self.muscle
            .update(excitation, self.mt_length, self.mt_velocity, dt);
        let muscle_force = self.muscle.force();

        // Net force determines acceleration (simplified as force imbalance)
        // F_muscle - F_load = m_eff * a
        let m_eff = 0.1; // effective mass (kg)
        let accel = (muscle_force - self.load) / m_eff;
        self.mt_velocity += accel * dt;
        self.mt_length += self.mt_velocity * dt;
    }

    /// Run an isotonic contraction for a given duration.
    ///
    /// Returns a vector of (time, length, velocity) triples.
    pub fn run(&mut self, excitation: f64, duration: f64, dt: f64) -> Vec<(f64, f64, f64)> {
        let mut results = Vec::new();
        let mut t = 0.0;

        while t < duration {
            self.update(excitation, dt);
            results.push((t, self.mt_length, self.mt_velocity));
            t += dt;
        }
        results
    }

    /// Get the current steady-state shortening velocity (if reached).
    pub fn shortening_velocity(&self) -> f64 {
        self.mt_velocity
    }
}

// ===========================================================================
// 10. Musculotendon Unit (Spatial Attachment)
// ===========================================================================

/// A musculotendon unit connecting two points in 3D space.
///
/// This wraps the Hill muscle model with spatial attachment points,
/// computing the musculotendon length and direction from origin/insertion.
#[derive(Debug, Clone)]
pub struct MusculotendonUnit {
    /// Origin attachment point (body frame).
    pub origin: [f64; 3],
    /// Insertion attachment point (body frame).
    pub insertion: [f64; 3],
    /// The underlying muscle model.
    pub muscle: HillMuscleSoftbody,
    /// Optional via (wrap) point.
    pub via_point: Option<[f64; 3]>,
}

impl MusculotendonUnit {
    /// Create a new musculotendon unit.
    pub fn new(origin: [f64; 3], insertion: [f64; 3], muscle: HillMuscleSoftbody) -> Self {
        Self {
            origin,
            insertion,
            muscle,
            via_point: None,
        }
    }

    /// Set an optional via (wrapping) point.
    pub fn with_via_point(mut self, via: [f64; 3]) -> Self {
        self.via_point = Some(via);
        self
    }

    /// Compute the current musculotendon length.
    pub fn mt_length(&self) -> f64 {
        match self.via_point {
            Some(via) => norm3(sub3(via, self.origin)) + norm3(sub3(self.insertion, via)),
            None => norm3(sub3(self.insertion, self.origin)),
        }
    }

    /// Compute the unit direction from origin to insertion.
    pub fn direction(&self) -> [f64; 3] {
        normalize3(sub3(self.insertion, self.origin))
    }

    /// Compute the force vector applied at the insertion point.
    pub fn force_at_insertion(&self) -> [f64; 3] {
        let dir = self.direction();
        let f = self.muscle.force();
        // Force pulls insertion toward origin
        scale3(dir, -f)
    }

    /// Compute the force vector applied at the origin point.
    pub fn force_at_origin(&self) -> [f64; 3] {
        let dir = self.direction();
        let f = self.muscle.force();
        // Force pulls origin toward insertion
        scale3(dir, f)
    }

    /// Update the musculotendon unit state.
    pub fn update_from_positions(
        &mut self,
        origin: [f64; 3],
        insertion: [f64; 3],
        prev_mt_length: f64,
        dt: f64,
        excitation: f64,
    ) {
        self.origin = origin;
        self.insertion = insertion;
        let mt_len = self.mt_length();
        let mt_vel = if dt > 1e-15 {
            (mt_len - prev_mt_length) / dt
        } else {
            0.0
        };
        self.muscle.update(excitation, mt_len, mt_vel, dt);
    }

    /// Get the moment arm about an axis passing through a joint center.
    pub fn moment_arm(&self, joint_center: [f64; 3], axis: [f64; 3]) -> f64 {
        let r = sub3(self.insertion, joint_center);
        let f_dir = self.direction();
        // moment arm = |r x f_dir| . axis_hat
        let cross = [
            r[1] * f_dir[2] - r[2] * f_dir[1],
            r[2] * f_dir[0] - r[0] * f_dir[2],
            r[0] * f_dir[1] - r[1] * f_dir[0],
        ];
        let axis_n = normalize3(axis);
        dot3(cross, axis_n)
    }
}

// ===========================================================================
// 11. Muscle Group
// ===========================================================================

/// A group of muscles that act together (e.g., quadriceps group).
#[derive(Debug, Clone)]
pub struct MuscleGroup {
    /// Name of the muscle group.
    pub name: String,
    /// Individual muscles in this group.
    pub muscles: Vec<MusculotendonUnit>,
}

impl MuscleGroup {
    /// Create a new muscle group.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            muscles: Vec::new(),
        }
    }

    /// Add a muscle to the group.
    pub fn add_muscle(&mut self, mtu: MusculotendonUnit) {
        self.muscles.push(mtu);
    }

    /// Get the total force magnitude from all muscles.
    pub fn total_force(&self) -> f64 {
        self.muscles.iter().map(|m| m.muscle.force()).sum()
    }

    /// Get the total force vector from all muscles at their insertion points.
    pub fn total_force_vector(&self) -> [f64; 3] {
        let mut total = [0.0; 3];
        for m in &self.muscles {
            let f = m.force_at_insertion();
            total = add3(total, f);
        }
        total
    }

    /// Number of muscles in the group.
    pub fn num_muscles(&self) -> usize {
        self.muscles.len()
    }

    /// Activate all muscles in the group with the same excitation.
    pub fn activate_all(&mut self, excitation: f64, dt: f64) {
        for m in &mut self.muscles {
            let mt_len = m.mt_length();
            m.muscle.update(excitation, mt_len, 0.0, dt);
        }
    }

    /// Activate muscles with individual excitation levels.
    pub fn activate_individual(&mut self, excitations: &[f64], dt: f64) {
        for (i, m) in self.muscles.iter_mut().enumerate() {
            let e = if i < excitations.len() {
                excitations[i]
            } else {
                0.0
            };
            let mt_len = m.mt_length();
            m.muscle.update(e, mt_len, 0.0, dt);
        }
    }
}

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

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

    const EPS: f64 = 1e-8;

    fn approx_eq(a: f64, b: f64, tol: f64) -> bool {
        (a - b).abs() < tol
    }

    // -----------------------------------------------------------------------
    // Activation Dynamics Tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_activation_initial_zero() {
        let ad = ActivationDynamics::fast_twitch();
        assert!(
            ad.activation() < 0.02,
            "Initial activation should be ~0, got {}",
            ad.activation()
        );
    }

    #[test]
    fn test_activation_increases_with_excitation() {
        let mut ad = ActivationDynamics::fast_twitch();
        ad.set_activation(0.0);
        for _ in 0..200 {
            ad.update(1.0, 0.001);
        }
        assert!(
            ad.activation() > 0.5,
            "Activation should increase to >0.5, got {}",
            ad.activation()
        );
    }

    #[test]
    fn test_activation_decreases_without_excitation() {
        let mut ad = ActivationDynamics::fast_twitch();
        ad.set_activation(1.0);
        for _ in 0..200 {
            ad.update(0.0, 0.001);
        }
        assert!(
            ad.activation() < 0.5,
            "Activation should decrease, got {}",
            ad.activation()
        );
    }

    #[test]
    fn test_activation_fast_vs_slow() {
        let mut fast = ActivationDynamics::fast_twitch();
        let mut slow = ActivationDynamics::slow_twitch();
        fast.set_activation(0.0);
        slow.set_activation(0.0);
        for _ in 0..100 {
            fast.update(1.0, 0.001);
            slow.update(1.0, 0.001);
        }
        assert!(
            fast.activation() > slow.activation(),
            "Fast-twitch ({}) should activate faster than slow-twitch ({})",
            fast.activation(),
            slow.activation()
        );
    }

    // -----------------------------------------------------------------------
    // Force-Length Curve Tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_fl_active_peak_at_optimal() {
        let fl = ForceLengthCurve::thelen2003();
        let val = fl.active(1.0);
        assert!(
            approx_eq(val, 1.0, EPS),
            "Active FL at optimal should be 1.0, got {val}"
        );
    }

    #[test]
    fn test_fl_active_decreases_away() {
        let fl = ForceLengthCurve::thelen2003();
        let peak = fl.active(1.0);
        let short = fl.active(0.7);
        let long = fl.active(1.3);
        assert!(short < peak, "Active FL should decrease when shorter");
        assert!(long < peak, "Active FL should decrease when longer");
    }

    #[test]
    fn test_fl_passive_zero_below_optimal() {
        let fl = ForceLengthCurve::thelen2003();
        let val = fl.passive(0.9);
        assert!(
            val.abs() < EPS,
            "Passive FL below optimal should be 0, got {val}"
        );
    }

    #[test]
    fn test_fl_passive_increases_above_optimal() {
        let fl = ForceLengthCurve::thelen2003();
        let f1 = fl.passive(1.2);
        let f2 = fl.passive(1.4);
        assert!(f1 > 0.0, "Passive FL above optimal should be > 0");
        assert!(f2 > f1, "Passive FL should increase with length");
    }

    // -----------------------------------------------------------------------
    // Force-Velocity Curve Tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_fv_isometric_unity() {
        let fv = ForceVelocityCurve::thelen2003();
        let val = fv.evaluate(0.0);
        assert!(
            approx_eq(val, 1.0, EPS),
            "FV at zero velocity should be 1.0, got {val}"
        );
    }

    #[test]
    fn test_fv_concentric_decreases() {
        let fv = ForceVelocityCurve::thelen2003();
        let iso = fv.evaluate(0.0);
        let con = fv.evaluate(-0.5);
        assert!(
            con < iso,
            "FV during shortening ({con}) should be less than isometric ({iso})"
        );
    }

    #[test]
    fn test_fv_eccentric_increases() {
        let fv = ForceVelocityCurve::thelen2003();
        let iso = fv.evaluate(0.0);
        let ecc = fv.evaluate(0.5);
        assert!(
            ecc > iso,
            "FV during lengthening ({ecc}) should be greater than isometric ({iso})"
        );
    }

    #[test]
    fn test_fv_eccentric_bounded() {
        let fv = ForceVelocityCurve::thelen2003();
        let ecc_high = fv.evaluate(0.99);
        assert!(
            ecc_high < fv.f_ecc_max + 0.1,
            "Eccentric FV ({ecc_high}) should be bounded by f_ecc_max ({})",
            fv.f_ecc_max
        );
    }

    // -----------------------------------------------------------------------
    // Pennation Model Tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_pennation_zero_angle() {
        let pm = PennationModel::zero();
        let a = pm.angle(1.0);
        assert!(a.abs() < EPS, "Zero pennation angle should give 0, got {a}");
    }

    #[test]
    fn test_pennation_cos_at_optimal() {
        let alpha = 0.3; // ~17 degrees
        let l_opt = 0.1;
        let pm = PennationModel::new(alpha, l_opt);
        let cos_a = pm.cos_alpha(l_opt);
        assert!(
            approx_eq(cos_a, alpha.cos(), 1e-6),
            "cos(alpha) at optimal should match, got {cos_a}"
        );
    }

    #[test]
    fn test_pennation_angle_increases_with_shortening() {
        let pm = PennationModel::new(0.2, 0.1);
        let a_opt = pm.angle(0.1);
        let a_short = pm.angle(0.08);
        assert!(
            a_short > a_opt,
            "Pennation angle should increase with shortening: opt={a_opt}, short={a_short}"
        );
    }

    // -----------------------------------------------------------------------
    // Tendon Model Tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_tendon_zero_force_at_slack() {
        let tm = TendonModel::new(0.2, 1000.0);
        let f = tm.force(0.2);
        assert!(
            f.abs() < EPS,
            "Tendon force at slack length should be 0, got {f}"
        );
    }

    #[test]
    fn test_tendon_positive_force_above_slack() {
        let tm = TendonModel::new(0.2, 1000.0);
        let f = tm.force(0.21); // 5% strain
        assert!(
            f > 0.0,
            "Tendon force above slack should be positive, got {f}"
        );
    }

    #[test]
    fn test_tendon_stiffness_increases() {
        let tm = TendonModel::new(0.2, 1000.0);
        let k1 = tm.stiffness(0.201); // small strain
        let k2 = tm.stiffness(0.21); // larger strain
        assert!(
            k2 >= k1,
            "Tendon stiffness should increase: k1={k1}, k2={k2}"
        );
    }

    #[test]
    fn test_tendon_inverse() {
        let tm = TendonModel::new(0.2, 1000.0);
        let l = 0.208; // some stretched length
        let f = tm.force(l);
        let l_inv = tm.length_from_force(f);
        assert!(
            approx_eq(l, l_inv, 1e-4),
            "Inverse tendon should recover length: l={l}, l_inv={l_inv}"
        );
    }

    // -----------------------------------------------------------------------
    // Hill Muscle Model Tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_hill_zero_force_inactive() {
        let muscle = HillMuscleSoftbody::typical(1000.0, 0.1, 0.2);
        let f = muscle.compute_force(0.0, 0.1, 0.0);
        assert!(
            f.abs() < EPS,
            "Force at zero activation and optimal length should be 0, got {f}"
        );
    }

    #[test]
    fn test_hill_positive_force_active() {
        let muscle = HillMuscleSoftbody::typical(1000.0, 0.1, 0.2);
        let f = muscle.compute_force(1.0, 0.1, 0.0);
        assert!(
            f > 0.0,
            "Force at full activation and optimal length should be positive, got {f}"
        );
    }

    #[test]
    fn test_hill_max_isometric_force() {
        let muscle = HillMuscleSoftbody::typical(1000.0, 0.1, 0.2);
        let f = muscle.compute_force(1.0, 0.1, 0.0);
        // At optimal length, zero velocity, full activation: F = F_max * cos(alpha)
        assert!(
            approx_eq(f, 1000.0, 1.0),
            "Max isometric force should be ~F_max, got {f}"
        );
    }

    #[test]
    fn test_hill_update_increases_force() {
        let mut muscle = HillMuscleSoftbody::typical(1000.0, 0.1, 0.2);
        assert!(muscle.force().abs() < EPS, "Initial force should be 0");
        for _ in 0..200 {
            muscle.update(1.0, 0.3, 0.0, 0.001);
        }
        assert!(
            muscle.force() > 0.0,
            "Force should increase with activation, got {}",
            muscle.force()
        );
    }

    // -----------------------------------------------------------------------
    // Fatigue Model Tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_fatigue_initial_state() {
        let fm = FatigueModel::default_mixed();
        assert!(approx_eq(fm.mr, 1.0, EPS), "All units should start resting");
        assert!(approx_eq(fm.ma, 0.0, EPS), "No active units initially");
        assert!(approx_eq(fm.mf, 0.0, EPS), "No fatigued units initially");
    }

    #[test]
    fn test_fatigue_recruitment() {
        let mut fm = FatigueModel::default_mixed();
        fm.set_target(0.5);
        for _ in 0..100 {
            fm.update(0.01);
        }
        assert!(
            fm.ma > 0.0,
            "Active units should be recruited, got {}",
            fm.ma
        );
    }

    #[test]
    fn test_fatigue_develops() {
        let mut fm = FatigueModel::default_mixed();
        fm.set_target(0.8);
        for _ in 0..5000 {
            fm.update(0.01);
        }
        assert!(
            fm.mf > 0.0,
            "Fatigue should develop over time, got mf={}",
            fm.mf
        );
    }

    #[test]
    fn test_fatigue_conservation() {
        let mut fm = FatigueModel::default_mixed();
        fm.set_target(0.6);
        for _ in 0..100 {
            fm.update(0.01);
        }
        let total = fm.ma + fm.mf + fm.mr;
        assert!(
            approx_eq(total, 1.0, 1e-6),
            "MA+MF+MR should sum to 1.0, got {total}"
        );
    }

    #[test]
    fn test_fatigue_endurance_time() {
        let fm = FatigueModel::default_mixed();
        let t50 = fm.endurance_time(0.5);
        let t80 = fm.endurance_time(0.8);
        assert!(
            t50 > t80,
            "Endurance at 50% ({t50:.6}) should exceed 80% ({t80:.6})"
        );
    }

    // -----------------------------------------------------------------------
    // Fiber Recruitment Tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_recruitment_none_at_zero() {
        let mut fr = FiberRecruitment::new(10);
        fr.update(0.0);
        // Only the first unit (threshold=0) gets recruited
        assert!(
            fr.num_recruited() <= 1,
            "At zero excitation, at most 1 unit should be recruited, got {}",
            fr.num_recruited()
        );
    }

    #[test]
    fn test_recruitment_all_at_max() {
        let mut fr = FiberRecruitment::new(10);
        fr.update(1.0);
        assert_eq!(
            fr.num_recruited(),
            10,
            "At full excitation all units should be recruited"
        );
    }

    #[test]
    fn test_recruitment_progressive() {
        let mut fr = FiberRecruitment::new(10);
        fr.update(0.3);
        let n_low = fr.num_recruited();
        fr.update(0.7);
        let n_high = fr.num_recruited();
        assert!(
            n_high >= n_low,
            "Higher excitation should recruit more: low={n_low}, high={n_high}"
        );
    }

    #[test]
    fn test_recruitment_total_force_at_max() {
        let mut fr = FiberRecruitment::new(10);
        fr.update(1.0);
        let f = fr.total_force();
        assert!(
            approx_eq(f, 1.0, 1e-6),
            "Total force at full recruitment should be 1.0, got {f}"
        );
    }

    // -----------------------------------------------------------------------
    // Isometric Contraction Tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_isometric_force_monotonic() {
        let muscle = HillMuscleSoftbody::typical(1000.0, 0.1, 0.2);
        // Use compute_force directly to test the relationship
        let f_low = muscle.compute_force(0.3, 0.1, 0.0);
        let f_high = muscle.compute_force(0.8, 0.1, 0.0);
        assert!(
            f_high > f_low,
            "Higher activation should give higher force: f_low={f_low}, f_high={f_high}"
        );
    }

    // -----------------------------------------------------------------------
    // Isotonic Contraction Tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_isotonic_shortens_under_light_load() {
        let muscle = HillMuscleSoftbody::typical(1000.0, 0.1, 0.2);
        let initial_length = 0.31;
        let mut iso = IsotonicContraction::new(muscle, 100.0, initial_length);
        // First activate the muscle (build up activation)
        for _ in 0..200 {
            iso.update(1.0, 0.0001);
        }
        // Check that the muscle produced force and the length changed
        let force = iso.muscle.force();
        assert!(
            force > 0.0,
            "Muscle should produce force after activation, got {force}"
        );
    }

    // -----------------------------------------------------------------------
    // Musculotendon Unit Tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_mtu_length() {
        let muscle = HillMuscleSoftbody::typical(1000.0, 0.1, 0.2);
        let mtu = MusculotendonUnit::new([0.0, 0.0, 0.0], [0.3, 0.0, 0.0], muscle);
        let l = mtu.mt_length();
        assert!(approx_eq(l, 0.3, EPS), "MTU length should be 0.3, got {l}");
    }

    #[test]
    fn test_mtu_direction() {
        let muscle = HillMuscleSoftbody::typical(1000.0, 0.1, 0.2);
        let mtu = MusculotendonUnit::new([0.0, 0.0, 0.0], [0.0, 1.0, 0.0], muscle);
        let dir = mtu.direction();
        assert!(approx_eq(dir[0], 0.0, EPS));
        assert!(approx_eq(dir[1], 1.0, EPS));
        assert!(approx_eq(dir[2], 0.0, EPS));
    }

    #[test]
    fn test_mtu_via_point_length() {
        let muscle = HillMuscleSoftbody::typical(1000.0, 0.1, 0.2);
        let mtu = MusculotendonUnit::new([0.0, 0.0, 0.0], [1.0, 0.0, 0.0], muscle)
            .with_via_point([0.5, 0.5, 0.0]);
        let l = mtu.mt_length();
        // Via point makes path longer than straight line
        let straight = 1.0_f64;
        assert!(
            l > straight,
            "Via point path ({l}) should be longer than straight ({straight})"
        );
    }

    // -----------------------------------------------------------------------
    // Muscle Group Tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_muscle_group_total_force() {
        let m1 = HillMuscleSoftbody::typical(500.0, 0.1, 0.2);
        let m2 = HillMuscleSoftbody::typical(300.0, 0.08, 0.15);
        let mtu1 = MusculotendonUnit::new([0.0, 0.0, 0.0], [0.3, 0.0, 0.0], m1);
        let mtu2 = MusculotendonUnit::new([0.0, 0.1, 0.0], [0.23, 0.1, 0.0], m2);
        let mut group = MuscleGroup::new("test_group");
        group.add_muscle(mtu1);
        group.add_muscle(mtu2);
        assert_eq!(group.num_muscles(), 2);
        // Initially no force (no activation)
        let f = group.total_force();
        assert!(f.abs() < EPS, "Initial group force should be 0, got {f}");
    }

    #[test]
    fn test_muscle_group_activation() {
        let m1 = HillMuscleSoftbody::typical(500.0, 0.1, 0.2);
        let mtu1 = MusculotendonUnit::new([0.0, 0.0, 0.0], [0.3, 0.0, 0.0], m1);
        let mut group = MuscleGroup::new("test_group");
        group.add_muscle(mtu1);
        for _ in 0..200 {
            group.activate_all(1.0, 0.001);
        }
        let f = group.total_force();
        assert!(
            f > 0.0,
            "Group force after activation should be positive, got {f}"
        );
    }
}