Skip to main content

re_core/
animation.rs

1use crate::id::NodeId;
2use glam::{Quat, Vec3};
3use serde::{Deserialize, Serialize};
4
5/// Which TRS component a channel animates.
6#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
7pub enum ChannelPath {
8    Translation,
9    Rotation,
10    Scale,
11}
12
13#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
14pub enum Interpolation {
15    Step,
16    #[default]
17    Linear,
18    /// Accepted for import round-trips; sampled as linear for now.
19    Cubic,
20}
21
22/// Animated value: 3 components for Translation/Scale, quaternion `[x,y,z,w]` for Rotation.
23#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
24pub enum KeyValue {
25    Vec3([f32; 3]),
26    Quat([f32; 4]),
27}
28
29impl KeyValue {
30    pub fn lerp(&self, other: &KeyValue, t: f32) -> KeyValue {
31        match (self, other) {
32            (KeyValue::Vec3(a), KeyValue::Vec3(b)) => KeyValue::Vec3(
33                Vec3::from_array(*a)
34                    .lerp(Vec3::from_array(*b), t)
35                    .to_array(),
36            ),
37            (KeyValue::Quat(a), KeyValue::Quat(b)) => {
38                let qa = Quat::from_array(*a);
39                let qb = Quat::from_array(*b);
40                KeyValue::Quat(qa.slerp(qb, t).to_array())
41            }
42            _ => *self,
43        }
44    }
45
46    pub fn default_for(path: ChannelPath) -> KeyValue {
47        match path {
48            ChannelPath::Translation => KeyValue::Vec3([0.0, 0.0, 0.0]),
49            ChannelPath::Rotation => KeyValue::Quat([0.0, 0.0, 0.0, 1.0]),
50            ChannelPath::Scale => KeyValue::Vec3([1.0, 1.0, 1.0]),
51        }
52    }
53}
54
55#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
56pub struct Keyframe {
57    pub time: f32,
58    pub value: KeyValue,
59}
60
61/// What a channel drives.
62#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
63pub enum Target {
64    /// A concrete scene node.
65    Node(NodeId),
66    /// A joint by name — resolved against whatever skeleton instance the
67    /// animation plays on. This is what makes animations reusable across rigs.
68    Joint(String),
69}
70
71/// Space a keyframe value lives in.
72#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
73pub enum Space {
74    /// The value *is* the local TRS component (glTF behaviour). Translation
75    /// keys therefore replace the bind-pose offset of the joint.
76    #[default]
77    Absolute,
78    /// The value is applied on top of the bind/rest local transform
79    /// (`bind * delta`). Lets one clip drive rigs whose joints sit at
80    /// different heights or scales. Baked to absolute on glTF export.
81    RelativeToBind,
82}
83
84#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
85pub struct Channel {
86    pub target: Target,
87    pub path: ChannelPath,
88    #[serde(default)]
89    pub interpolation: Interpolation,
90    /// Absolute by default; older project files stay loadable.
91    #[serde(default)]
92    pub space: Space,
93    /// Sorted by time.
94    pub keys: Vec<Keyframe>,
95}
96
97impl Channel {
98    pub fn new(target: Target, path: ChannelPath) -> Self {
99        Self {
100            target,
101            path,
102            interpolation: Interpolation::default(),
103            space: Space::default(),
104            keys: Vec::new(),
105        }
106    }
107
108    /// Insert or replace a keyframe at (nearly) the same time, keeping order.
109    pub fn set_key(&mut self, time: f32, value: KeyValue) {
110        let pos = self.keys.partition_point(|k| k.time < time - 1e-6);
111        if pos < self.keys.len() && (self.keys[pos].time - time).abs() < 1e-5 {
112            self.keys[pos] = Keyframe { time, value };
113        } else {
114            self.keys.insert(pos, Keyframe { time, value });
115        }
116    }
117
118    /// Sample the channel value at time `t` (clamped to the key range).
119    pub fn sample(&self, t: f32) -> Option<KeyValue> {
120        let keys = &self.keys;
121        match keys.len() {
122            0 => None,
123            1 => Some(keys[0].value),
124            _ => {
125                if t <= keys[0].time {
126                    return Some(keys[0].value);
127                }
128                let last = keys.len() - 1;
129                if t >= keys[last].time {
130                    return Some(keys[last].value);
131                }
132                let i = keys.partition_point(|k| k.time <= t).min(last) - 1;
133                let a = keys[i];
134                let b = keys[i + 1];
135                match self.interpolation {
136                    Interpolation::Step => Some(a.value),
137                    _ => {
138                        let span = b.time - a.time;
139                        let f = if span > 0.0 { (t - a.time) / span } else { 0.0 };
140                        Some(a.value.lerp(&b.value, f))
141                    }
142                }
143            }
144        }
145    }
146}
147
148/// A named, reusable animation clip: a set of TRS channels over time.
149#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
150pub struct Animation {
151    pub name: String,
152    pub channels: Vec<Channel>,
153    /// Explicit loop flag (viewer/export may honour it).
154    #[serde(default)]
155    pub looping: bool,
156}
157
158impl Animation {
159    pub fn new(name: impl Into<String>) -> Self {
160        Self {
161            name: name.into(),
162            channels: Vec::new(),
163            looping: false,
164        }
165    }
166
167    pub fn duration(&self) -> f32 {
168        self.channels
169            .iter()
170            .filter_map(|c| c.keys.last().map(|k| k.time))
171            .fold(0.0f32, f32::max)
172    }
173
174    /// Find the channel for a target/path pair.
175    pub fn channel(&self, target: &Target, path: ChannelPath) -> Option<&Channel> {
176        self.channels
177            .iter()
178            .find(|c| &c.target == target && c.path == path)
179    }
180
181    pub fn channel_mut(&mut self, target: &Target, path: ChannelPath) -> Option<&mut Channel> {
182        self.channels
183            .iter_mut()
184            .find(|c| &c.target == target && c.path == path)
185    }
186
187    /// Get or create the channel for a target/path pair.
188    pub fn get_or_create(&mut self, target: Target, path: ChannelPath) -> &mut Channel {
189        let idx = match self
190            .channels
191            .iter()
192            .position(|c| c.target == target && c.path == path)
193        {
194            Some(i) => i,
195            None => {
196                self.channels.push(Channel::new(target, path));
197                self.channels.len() - 1
198            }
199        };
200        &mut self.channels[idx]
201    }
202
203    /// Sample every channel at time `t`.
204    pub fn sample(&self, t: f32) -> Vec<(&Channel, KeyValue)> {
205        let t = if self.looping && self.duration() > 0.0 {
206            t % self.duration()
207        } else {
208            t
209        };
210        self.channels
211            .iter()
212            .filter_map(|c| c.sample(t).map(|v| (c, v)))
213            .collect()
214    }
215}