Skip to main content

unbanished_game/behaviour/
animation.rs

1//! Animation as the engine plays it: sampling a pose, the clock of each playing clip, and the
2//! events (such as sounds) a clip fires.
3//!
4//! Original: `Animation::GetPoseAtTime`, `Quaternion::Lerp`, `AnimationState::Update`,
5//! `Animation::ApplyEvents`.
6//!
7//! Original: Runtime `0x1800fd530`, Runtime `0x18001dde0`, Runtime `0x1801003b0`, Runtime
8//! `0x1800fd230`.
9
10use crate::scheduler::{seconds, ticks};
11use unbanished_formats::skeleton::Transform;
12use unbanished_formats::types::AnimationClip;
13
14/// Single, unique animation playback. Tree expiry starts from an empty animation state.
15/// Blended stacks and AnimationManager's shared instances require their separate lifecycle port.
16#[derive(Debug, Clone, PartialEq)]
17pub struct Playback {
18    /// The clip.
19    pub clip: usize,
20    /// The time played so far.
21    pub elapsed: i64,
22    /// UpdateNodes publishes the pose at the OLD clock, then Update advances elapsed.
23    pub sample_time: i64,
24    /// The time step of the last sample.
25    pub sample_delta: i64,
26    /// The playback speed.
27    pub speed: f32,
28}
29
30impl Playback {
31    /// A clip that starts playing at `start`, at speed 1. Tree removal starts at time zero.
32    ///
33    /// Original: `FUN_14012a5c0`; `AnimationState::PlayAnimation`, Runtime `0x1801007e0`.
34    pub fn new(clip: usize, start: i64) -> Self {
35        Self {
36            clip,
37            elapsed: start,
38            sample_time: start,
39            sample_delta: 0,
40            speed: 1.0,
41        }
42    }
43
44    /// Whether the clip is still playing. The end comes from the clip's stored duration (with its
45    /// rounded value), not from frames and rate.
46    ///
47    /// Original: `MeshInstance::IsAnimating`, Runtime `0x180102060`.
48    pub fn is_animating(&self, clip: &AnimationClip) -> bool {
49        clip.looping || self.elapsed < clip.duration_ticks
50    }
51
52    /// Port of AnimationState::Update's unique-state clock and ApplyEvents interval. Returns
53    /// indices of callbacks in resource order; effect dispatch remains the caller's responsibility.
54    pub fn update(&mut self, clip: &AnimationClip, dt: i64) -> Vec<usize> {
55        self.sample_time = self.elapsed;
56        self.sample_delta = ticks(seconds(dt) * self.speed);
57        let delta = if self.speed == 1.0 {
58            dt
59        } else {
60            self.sample_delta
61        };
62        let next = self.elapsed + delta;
63        let events = clip
64            .events
65            .iter()
66            .enumerate()
67            .filter_map(|(index, event)| {
68                let time = ticks(
69                    (event.frame - clip.start_frame) as f32
70                        / (clip.end_frame - clip.start_frame) as f32
71                        * clip.frames.len() as f32
72                        * clip.sample_interval,
73                );
74                let crossed = self.elapsed <= time && time < next;
75                let wrapped = next >= clip.duration_ticks
76                    && self.elapsed - clip.duration_ticks <= time
77                    && time < next - clip.duration_ticks;
78                (crossed || wrapped).then_some(index)
79            })
80            .collect();
81        self.elapsed = next;
82        if !clip.looping {
83            if self.elapsed >= clip.duration_ticks {
84                self.elapsed = clip.duration_ticks;
85            }
86        } else if clip.duration_ticks > 0 && self.elapsed >= clip.duration_ticks {
87            // Original repeatedly subtracts the full duration, then adds the source loop point.
88            self.elapsed %= clip.duration_ticks;
89            let loop_seconds = if clip.loop_start_frame == 0 {
90                0.0
91            } else {
92                (clip.loop_start_frame - clip.start_frame) as f32
93                    / (clip.end_frame - clip.start_frame) as f32
94                    * clip.frames.len() as f32
95                    * clip.sample_interval
96            };
97            self.elapsed += ticks(loop_seconds);
98        }
99        events
100    }
101
102    /// The pose of the clip at the current time.
103    pub fn pose(&self, clip: &AnimationClip) -> Vec<Transform> {
104        sample_pose(clip, self.sample_time, self.sample_delta)
105    }
106}
107
108/// Port of Math::Quaternion::Lerp 0x18001dde0, including its dot <= 0 sign choice and y/x/z/w
109/// normalization sum. Input/output use the format reader's conjugated quaternion convention.
110fn quaternion_lerp(a: [f32; 4], b: [f32; 4], fraction: f32) -> [f32; 4] {
111    // Perform the arithmetic in the native convention before conjugating its result. Flipping
112    // signs before summation changes signed-zero results even when the rotations are equivalent.
113    let native = |mut q: [f32; 4]| {
114        for value in &mut q[..3] {
115            *value = -*value;
116        }
117        q
118    };
119    let a = native(a);
120    let b = native(b);
121    let old = 1.0 - fraction;
122    let dot = a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
123    let new = if dot <= 0.0 { -fraction } else { fraction };
124    let q = std::array::from_fn::<_, 4, _>(|i| a[i] * old + b[i] * new);
125    let length = (q[1] * q[1] + q[0] * q[0] + q[2] * q[2] + q[3] * q[3]).sqrt();
126    let inverse = 1.0 / length;
127    native(q.map(|v| v * inverse))
128}
129
130/// The pose of a clip at a time: the two samples around it, interpolated (normalised quaternion
131/// lerp for rotations, linear for translations), with the original's loop arithmetic. The root's
132/// rotation is reset and its translation becomes a movement delta, as in the original.
133///
134/// Original: `Animation::GetPoseAtTime`, Runtime `0x1800fd530`.
135pub fn sample_pose(clip: &AnimationClip, time: i64, delta: i64) -> Vec<Transform> {
136    let count = clip.frames.len();
137    if count == 0 {
138        return Vec::new();
139    }
140    let position = seconds(time) * clip.sample_rate;
141    let raw = position as i32;
142    let loop_start = if clip.loop_start_frame == 0 {
143        0
144    } else {
145        ((clip.loop_start_frame - clip.start_frame) as f32
146            / (clip.end_frame - clip.start_frame) as f32
147            * count as f32) as i32
148    };
149    // Deviation: malformed negative times and empty loop spans must not index outside resources.
150    let span = (count as i32 - loop_start).max(1);
151    let first = if raw < count as i32 {
152        raw.max(0)
153    } else if clip.looping {
154        loop_start + raw % span
155    } else {
156        count as i32 - 1
157    } as usize;
158    let second = if first + 1 < count {
159        first + 1
160    } else if clip.looping {
161        (first as i32 + 1) as usize % span as usize + loop_start as usize
162    } else {
163        count - 1
164    };
165    let fraction = position - raw as f32;
166    let mut pose = if first == second || fraction == 0.0 {
167        clip.frames[first].clone()
168    } else {
169        clip.frames[first]
170            .iter()
171            .zip(&clip.frames[second])
172            .map(|(a, b)| Transform {
173                rotation: quaternion_lerp(a.rotation, b.rotation, fraction),
174                translation: std::array::from_fn(|i| {
175                    a.translation[i] + (b.translation[i] - a.translation[i]) * fraction
176                }),
177            })
178            .collect()
179    };
180    if let Some(root) = pose.first_mut() {
181        root.rotation = Transform::IDENTITY.rotation;
182        let scale = seconds(delta) * clip.sample_rate;
183        root.translation = root.translation.map(|v| v * scale);
184    }
185    pose
186}
187
188// +0x20; +0x28
189/// One layer of an [`AnimationStack`] (`AnimationState` entry, 0x38 bytes): its clip and clock, and
190/// while it fades out under a newer layer, the blend time and what is left of it.
191#[derive(Debug, Clone, PartialEq)]
192pub struct Layer {
193    /// The clip and its clock.
194    pub playback: Playback,
195    /// The blend time.
196    pub blend: i64,
197    /// The blend time left.
198    pub left: i64,
199    // +0x30
200    /// The layer has been updated once.
201    pub started: bool,
202    // +0x0c
203    /// The shared instance it follows (an instanced clip), see [`shared`].
204    pub instance: Option<i32>,
205}
206
207/// `Graphics::AnimationState` with its blend stack, newest layer first. Each play pushes a
208/// layer; the one it covers fades out over the group's blend time, and the pose mixes them.
209#[derive(Debug, Clone, PartialEq, Default)]
210pub struct AnimationStack {
211    /// The layers, newest first.
212    pub layers: Vec<Layer>,
213    /// The pose `UpdateNodes` published at the last update.
214    pose: Vec<Transform>,
215}
216
217/// `AnimationGroup` `+0x48`: the blend time from `old` to `new` (`[new][old]`, the group's
218/// clips square), else the default (`+0x30`).
219fn blend_seconds(group: &unbanished_formats::types::AnimationGroup, old: usize, new: usize) -> f32 {
220    let n = group.clips.len();
221    group
222        .blend_matrix
223        .get(n * new + old)
224        .copied()
225        .unwrap_or(group.default_blend)
226}
227
228impl AnimationStack {
229    /// One layer playing `clip` from `start`.
230    pub fn new(clip: usize, start: i64) -> Self {
231        Self {
232            layers: vec![Layer {
233                playback: Playback::new(clip, start),
234                blend: 0,
235                left: 0,
236                started: false,
237                instance: None,
238            }],
239            pose: Vec::new(),
240        }
241    }
242
243    /// The layers a save holds, newest first, with no pose yet: the first update makes it.
244    ///
245    /// Original: `MeshInstance::Serialize`, Runtime `0x180101f10` (reading).
246    pub fn restored(layers: Vec<Layer>) -> Self {
247        Self {
248            layers,
249            pose: Vec::new(),
250        }
251    }
252
253    /// The newest layer's clip.
254    pub fn clip(&self) -> Option<usize> {
255        self.layers.first().map(|l| l.playback.clip)
256    }
257
258    /// `AnimationState::PlayAnimation`. A looping clip already on top keeps its time (speed back to
259    /// 1). Otherwise the top layer starts fading over the blend time from its clip to `clip` and
260    /// the new layer goes on top; a top layer never updated is replaced instead, the one below
261    /// taking the blend.
262    ///
263    /// Original: Runtime `0x1801007e0`.
264    pub fn play(
265        &mut self,
266        group: &unbanished_formats::types::AnimationGroup,
267        clip: usize,
268        start: i64,
269    ) {
270        if let Some(top) = self.layers.first_mut() {
271            if top.playback.clip == clip && group.clips.get(clip).is_some_and(|c| c.looping) {
272                top.playback.speed = 1.0;
273                return;
274            }
275        }
276        // `MeshInstance::PlayAnimation` asks for a shared instance (`GetInstanceId`) when the
277        // clip is instanced.
278        let instance = group
279            .clips
280            .get(clip)
281            .filter(|c| c.instanced && c.instance_count > 0)
282            .map(|_| shared::instance_id(group, clip));
283        let layer = Layer {
284            playback: Playback::new(clip, start),
285            blend: 0,
286            left: 0,
287            started: false,
288            instance,
289        };
290        if self.layers.is_empty() {
291            self.layers.push(layer);
292            return;
293        }
294        if !self.layers[0].started && self.layers.len() != 1 {
295            let t = ticks(blend_seconds(group, self.layers[1].playback.clip, clip));
296            self.layers[1].blend = t;
297            self.layers[1].left = t;
298            self.layers[0] = layer;
299            return;
300        }
301        let t = ticks(blend_seconds(group, self.layers[0].playback.clip, clip));
302        self.layers[0].blend = t;
303        self.layers[0].left = t;
304        self.layers.insert(0, layer);
305    }
306
307    /// `AnimationState::Update` with `UpdateNodes`: the pose at the old clocks, the oldest layer's
308    /// first and each newer one mixed over it by the older layer's share left (`Quaternion::Lerp`
309    /// and a linear translation); then every clock advances (only the newest fires its events), and
310    /// the fading layers count down, a layer leaving once less than a tick is left. Returns the
311    /// newest layer's events.
312    ///
313    /// Original: Runtime `0x1801003b0`, Runtime `0x1800ff4b0`.
314    pub fn update(
315        &mut self,
316        group: &unbanished_formats::types::AnimationGroup,
317        dt: i64,
318    ) -> Vec<usize> {
319        let Some(top) = self.layers.first_mut() else {
320            return Vec::new();
321        };
322        top.started = true;
323        let weights: Vec<f32> = self
324            .layers
325            .iter()
326            .map(|l| {
327                if l.blend > 0 {
328                    seconds(l.left) / seconds(l.blend)
329                } else {
330                    0.0
331                }
332            })
333            .collect();
334        let mut events = Vec::new();
335        for (i, layer) in self.layers.iter_mut().enumerate() {
336            if let Some(clip) = group.clips.get(layer.playback.clip) {
337                let fired = layer.playback.update(clip, dt);
338                if i == 0 {
339                    events = fired;
340                }
341            }
342        }
343        // `UpdateNodes`: an instanced layer takes its shared instance's pose
344        // (`AnimationManager::GetPose`), the others their own clocks'.
345        let poses: Vec<Option<Vec<Transform>>> = self
346            .layers
347            .iter()
348            .map(|l| match l.instance {
349                Some(id) => shared::pose(id),
350                None => group.clips.get(l.playback.clip).map(|c| l.playback.pose(c)),
351            })
352            .collect();
353        let mut pose: Option<Vec<Transform>> = None;
354        for i in (0..self.layers.len()).rev() {
355            let Some(new) = &poses[i] else { continue };
356            pose = Some(match pose {
357                None => new.clone(),
358                Some(old) => {
359                    let w = weights.get(i + 1).copied().unwrap_or(0.0);
360                    new.iter()
361                        .zip(&old)
362                        .map(|(n, o)| Transform {
363                            rotation: quaternion_lerp(n.rotation, o.rotation, w),
364                            translation: std::array::from_fn(|k| {
365                                n.translation[k] + (o.translation[k] - n.translation[k]) * w
366                            }),
367                        })
368                        .collect()
369                }
370            });
371        }
372        self.pose = pose.unwrap_or_default();
373        let step = ticks(seconds(dt));
374        let mut i = 0;
375        while i < self.layers.len() {
376            let l = &mut self.layers[i];
377            if l.blend > 0 {
378                l.left -= step;
379                if l.left < 1 {
380                    if let Some(id) = l.instance {
381                        shared::free(id);
382                    }
383                    self.layers.remove(i);
384                    continue;
385                }
386            }
387            i += 1;
388        }
389        events
390    }
391
392    /// The pose of the last update, or the newest layer's at its clock before any update.
393    pub fn pose(
394        &self,
395        group: &unbanished_formats::types::AnimationGroup,
396    ) -> Option<Vec<Transform>> {
397        if !self.pose.is_empty() {
398            return Some(self.pose.clone());
399        }
400        let top = self.layers.first()?;
401        group
402            .clips
403            .get(top.playback.clip)
404            .map(|c| top.playback.pose(c))
405    }
406}
407
408// +0x2c; +0x28
409pub mod shared;