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
//! Ragdoll Animation Blending
//!
//! Blends between keyframe animation and physics ragdoll simulation.
//! Extends neural.rs `RagdollController` with smooth transitions.
//!
//! # Modes
//!
//! - **Animated**: Pure keyframe animation (physics inactive)
//! - **Ragdoll**: Pure physics simulation (animation inactive)
//! - **Blend**: Weighted mix of animation and physics
//! - **Powered**: Physics with motor targets from animation
//!
//! Author: Moroya Sakamoto
use crate::math::{Fix128, QuatFix, Vec3Fix};
#[cfg(not(feature = "std"))]
use alloc::vec;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
// ============================================================================
// Blend Mode
// ============================================================================
/// Animation-physics blend mode
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BlendMode {
/// Pure animation (ignore physics)
Animated,
/// Pure physics (ignore animation)
Ragdoll,
/// Weighted blend between animation and physics
Blend,
/// Physics with animation-driven motor targets
Powered,
}
// ============================================================================
// Animation Pose
// ============================================================================
/// A single bone pose (position + rotation)
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BonePose {
/// Bone position (local space)
pub position: Vec3Fix,
/// Bone rotation (local space)
pub rotation: QuatFix,
}
impl Default for BonePose {
fn default() -> Self {
Self {
position: Vec3Fix::ZERO,
rotation: QuatFix::IDENTITY,
}
}
}
/// Complete skeleton pose (all bones)
#[derive(Clone, Debug)]
pub struct SkeletonPose {
/// Bone poses indexed by bone ID
pub bones: Vec<BonePose>,
}
impl SkeletonPose {
/// Create empty pose for N bones
#[must_use]
pub fn new(num_bones: usize) -> Self {
Self {
bones: vec![BonePose::default(); num_bones],
}
}
/// Number of bones
#[inline]
#[must_use]
pub fn bone_count(&self) -> usize {
self.bones.len()
}
/// Lerp between two poses
#[must_use]
pub fn lerp(a: &Self, b: &Self, t: Fix128) -> Self {
let n = a.bones.len().min(b.bones.len());
let one_minus_t = Fix128::ONE - t;
let bones: Vec<BonePose> = (0..n)
.map(|i| BonePose {
position: Vec3Fix::new(
a.bones[i].position.x * one_minus_t + b.bones[i].position.x * t,
a.bones[i].position.y * one_minus_t + b.bones[i].position.y * t,
a.bones[i].position.z * one_minus_t + b.bones[i].position.z * t,
),
rotation: quat_slerp(a.bones[i].rotation, b.bones[i].rotation, t),
})
.collect();
Self { bones }
}
}
// ============================================================================
// Animation Clip
// ============================================================================
/// Keyframe for a single bone
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Keyframe {
/// Time in seconds
pub time: Fix128,
/// Bone pose at this time
pub pose: BonePose,
}
/// Animation clip (sequence of keyframes per bone).
///
/// Uses a flat `keyframes` buffer with a `bone_offsets` table so that all
/// keyframe data is stored contiguously. `bone_offsets[b]..bone_offsets[b+1]`
/// gives the keyframe slice for bone `b`.
#[derive(Clone, Debug)]
pub struct AnimationClip {
/// Clip name
pub name: Vec<u8>,
/// Duration in seconds
pub duration: Fix128,
/// All keyframes packed flat (sorted per-bone by time)
pub keyframes: Vec<Keyframe>,
/// Start index in `keyframes` for each bone; length = num_bones + 1
pub bone_offsets: Vec<usize>,
/// Whether clip loops
pub looping: bool,
}
impl AnimationClip {
/// Create empty clip for `num_bones` bones.
#[must_use]
pub fn new(num_bones: usize, duration: Fix128) -> Self {
Self {
name: Vec::new(),
duration,
keyframes: Vec::new(),
bone_offsets: vec![0; num_bones + 1],
looping: true,
}
}
/// Number of bones this clip was created for.
#[inline]
#[must_use]
pub fn num_bones(&self) -> usize {
self.bone_offsets.len().saturating_sub(1)
}
/// Add a keyframe for a bone.
///
/// Inserts in time-sorted order and shifts subsequent bone offsets.
pub fn add_keyframe(&mut self, bone_idx: usize, keyframe: Keyframe) {
let num_bones = self.num_bones();
if bone_idx >= num_bones {
return;
}
let start = self.bone_offsets[bone_idx];
let end = self.bone_offsets[bone_idx + 1];
// Find insertion position (maintain sorted order by time)
let insert_pos = start
+ self.keyframes[start..end]
.iter()
.position(|kf| kf.time > keyframe.time)
.unwrap_or(end - start);
self.keyframes.insert(insert_pos, keyframe);
// Shift offsets for all subsequent bones
for off in &mut self.bone_offsets[bone_idx + 1..] {
*off += 1;
}
}
/// Sample pose at given time.
#[must_use]
pub fn sample(&self, time: Fix128) -> SkeletonPose {
let t = if self.looping && !self.duration.is_zero() {
let cycles = time / self.duration;
time - self.duration * Fix128::from_int(cycles.hi)
} else if time > self.duration {
self.duration
} else {
time
};
let num_bones = self.num_bones();
let mut pose = SkeletonPose::new(num_bones);
for bone_idx in 0..num_bones {
let start = self.bone_offsets[bone_idx];
let end = self.bone_offsets[bone_idx + 1];
let bone_keyframes = &self.keyframes[start..end];
if bone_keyframes.is_empty() {
continue;
}
if bone_keyframes.len() == 1 {
pose.bones[bone_idx] = bone_keyframes[0].pose;
continue;
}
// Find surrounding keyframes
let mut prev_idx = 0;
for (i, kf) in bone_keyframes.iter().enumerate() {
if kf.time <= t {
prev_idx = i;
}
}
let next_idx = (prev_idx + 1).min(bone_keyframes.len() - 1);
let prev = &bone_keyframes[prev_idx];
let next = &bone_keyframes[next_idx];
if prev_idx == next_idx {
pose.bones[bone_idx] = prev.pose;
} else {
let segment_duration = next.time - prev.time;
let local_t = if segment_duration.is_zero() {
Fix128::ZERO
} else {
(t - prev.time) / segment_duration
};
pose.bones[bone_idx] = BonePose {
position: Vec3Fix::new(
prev.pose.position.x
+ (next.pose.position.x - prev.pose.position.x) * local_t,
prev.pose.position.y
+ (next.pose.position.y - prev.pose.position.y) * local_t,
prev.pose.position.z
+ (next.pose.position.z - prev.pose.position.z) * local_t,
),
rotation: quat_slerp(prev.pose.rotation, next.pose.rotation, local_t),
};
}
}
pose
}
}
// ============================================================================
// Animation Blender
// ============================================================================
/// Animation-physics blender
pub struct AnimationBlender {
/// Current blend mode
pub mode: BlendMode,
/// Blend weight (0 = full animation, 1 = full physics)
pub blend_weight: Fix128,
/// Target blend weight (for smooth transitions)
target_weight: Fix128,
/// Blend transition speed (weight units per second)
pub transition_speed: Fix128,
/// Current animation pose
pub animation_pose: SkeletonPose,
/// Current physics pose
pub physics_pose: SkeletonPose,
/// Output blended pose
pub output_pose: SkeletonPose,
/// Motor stiffness when in Powered mode
pub motor_stiffness: Fix128,
}
impl AnimationBlender {
/// Create a new blender for N bones
#[must_use]
pub fn new(num_bones: usize) -> Self {
Self {
mode: BlendMode::Animated,
blend_weight: Fix128::ZERO,
target_weight: Fix128::ZERO,
transition_speed: Fix128::from_int(2),
animation_pose: SkeletonPose::new(num_bones),
physics_pose: SkeletonPose::new(num_bones),
output_pose: SkeletonPose::new(num_bones),
motor_stiffness: Fix128::from_int(100),
}
}
/// Transition to ragdoll mode
pub fn go_ragdoll(&mut self) {
self.mode = BlendMode::Blend;
self.target_weight = Fix128::ONE;
}
/// Transition to animated mode
pub fn go_animated(&mut self) {
self.mode = BlendMode::Blend;
self.target_weight = Fix128::ZERO;
}
/// Set to powered ragdoll (physics with animation targets)
pub fn go_powered(&mut self) {
self.mode = BlendMode::Powered;
self.target_weight = Fix128::ONE;
}
/// Immediately set ragdoll (no transition)
pub fn set_ragdoll(&mut self) {
self.mode = BlendMode::Ragdoll;
self.blend_weight = Fix128::ONE;
self.target_weight = Fix128::ONE;
}
/// Immediately set animated (no transition)
pub fn set_animated(&mut self) {
self.mode = BlendMode::Animated;
self.blend_weight = Fix128::ZERO;
self.target_weight = Fix128::ZERO;
}
/// Update blender state
pub fn update(&mut self, dt: Fix128) {
// Smooth weight transition
let diff = self.target_weight - self.blend_weight;
if diff.abs() > Fix128::from_ratio(1, 1000) {
let step = self.transition_speed * dt;
if diff > Fix128::ZERO {
self.blend_weight = self.blend_weight + step;
if self.blend_weight > self.target_weight {
self.blend_weight = self.target_weight;
}
} else {
self.blend_weight = self.blend_weight - step;
if self.blend_weight < self.target_weight {
self.blend_weight = self.target_weight;
}
}
} else {
self.blend_weight = self.target_weight;
}
// Auto-switch mode when transition completes
if self.mode == BlendMode::Blend {
if self.blend_weight >= Fix128::ONE {
self.mode = BlendMode::Ragdoll;
} else if self.blend_weight <= Fix128::ZERO {
self.mode = BlendMode::Animated;
}
}
// Compute output pose
match self.mode {
BlendMode::Animated => {
self.output_pose.clone_from(&self.animation_pose);
}
BlendMode::Ragdoll | BlendMode::Powered => {
self.output_pose.clone_from(&self.physics_pose);
}
BlendMode::Blend => {
self.output_pose =
SkeletonPose::lerp(&self.animation_pose, &self.physics_pose, self.blend_weight);
}
}
}
/// Get motor targets for powered mode (animation poses as motor goals)
#[must_use]
pub const fn get_motor_targets(&self) -> &SkeletonPose {
&self.animation_pose
}
/// Check if currently transitioning
#[must_use]
pub fn is_transitioning(&self) -> bool {
(self.blend_weight - self.target_weight).abs() > Fix128::from_ratio(1, 1000)
}
}
// ============================================================================
// Quaternion SLERP
// ============================================================================
/// Spherical linear interpolation between two quaternions
fn quat_slerp(a: QuatFix, b: QuatFix, t: Fix128) -> QuatFix {
let mut dot = a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
// Ensure shortest path
let b = if dot < Fix128::ZERO {
dot = -dot;
QuatFix::new(-b.x, -b.y, -b.z, -b.w)
} else {
b
};
// If quaternions are very close, use NLERP (faster, avoids division by near-zero)
if dot > Fix128::from_ratio(999, 1000) {
let one_minus_t = Fix128::ONE - t;
return QuatFix::new(
a.x * one_minus_t + b.x * t,
a.y * one_minus_t + b.y * t,
a.z * one_minus_t + b.z * t,
a.w * one_minus_t + b.w * t,
)
.normalize();
}
// Full SLERP: theta = acos(dot) via atan2(sqrt(1 - dot^2), dot)
let one_minus_dot_sq = Fix128::ONE - dot * dot;
// Clamp to avoid negative values from numerical error
let sin_half = if one_minus_dot_sq.is_negative() {
Fix128::ZERO
} else {
one_minus_dot_sq.sqrt()
};
let theta = Fix128::atan2(sin_half, dot);
let sin_theta = sin_half;
if sin_theta.is_zero() {
return a;
}
let one_minus_t = Fix128::ONE - t;
let s0 = (one_minus_t * theta).sin() / sin_theta;
let s1 = (t * theta).sin() / sin_theta;
QuatFix::new(
a.x * s0 + b.x * s1,
a.y * s0 + b.y * s1,
a.z * s0 + b.z * s1,
a.w * s0 + b.w * s1,
)
.normalize()
}
// ============================================================================
// Tests
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_blend_modes() {
let mut blender = AnimationBlender::new(3);
assert_eq!(blender.mode, BlendMode::Animated);
blender.go_ragdoll();
assert_eq!(blender.mode, BlendMode::Blend);
assert_eq!(blender.target_weight, Fix128::ONE);
}
#[test]
fn test_blend_transition() {
let mut blender = AnimationBlender::new(2);
blender.go_ragdoll();
let dt = Fix128::from_ratio(1, 60);
for _ in 0..120 {
// 2 seconds at 60fps
blender.update(dt);
}
// After transition, should be in ragdoll mode
assert_eq!(blender.mode, BlendMode::Ragdoll);
assert_eq!(blender.blend_weight, Fix128::ONE);
}
#[test]
fn test_pose_lerp() {
let a = SkeletonPose {
bones: vec![BonePose {
position: Vec3Fix::ZERO,
rotation: QuatFix::IDENTITY,
}],
};
let b = SkeletonPose {
bones: vec![BonePose {
position: Vec3Fix::from_int(10, 0, 0),
rotation: QuatFix::IDENTITY,
}],
};
let mid = SkeletonPose::lerp(&a, &b, Fix128::from_ratio(1, 2));
let x = mid.bones[0].position.x.to_f32();
assert!((x - 5.0).abs() < 0.1, "Midpoint should be at x=5, got {x}");
}
#[test]
fn test_animation_clip() {
let mut clip = AnimationClip::new(1, Fix128::from_int(2));
clip.add_keyframe(
0,
Keyframe {
time: Fix128::ZERO,
pose: BonePose {
position: Vec3Fix::ZERO,
rotation: QuatFix::IDENTITY,
},
},
);
clip.add_keyframe(
0,
Keyframe {
time: Fix128::from_int(2),
pose: BonePose {
position: Vec3Fix::from_int(10, 0, 0),
rotation: QuatFix::IDENTITY,
},
},
);
let pose = clip.sample(Fix128::ONE); // t=1s, midpoint
let x = pose.bones[0].position.x.to_f32();
assert!((x - 5.0).abs() < 0.5, "At t=1s, x should be ~5, got {x}");
}
#[test]
fn test_immediate_mode_switch() {
let mut blender = AnimationBlender::new(1);
blender.set_ragdoll();
assert_eq!(blender.mode, BlendMode::Ragdoll);
assert!(!blender.is_transitioning());
blender.set_animated();
assert_eq!(blender.mode, BlendMode::Animated);
}
}