Skip to main content

xrack_runtime/
animation.rs

1use crate::{Brush, Color, GradientStop, Length, Node, Percent, Value};
2use std::{borrow::Cow, collections::BTreeMap, sync::Arc, time::Duration};
3
4#[derive(Clone, Copy, Debug, Default, PartialEq)]
5pub struct Easing(Option<[f64; 4]>);
6
7impl Easing {
8    pub const LINEAR: Self = Self(None);
9
10    pub fn cubic_bezier(x1: f64, y1: f64, x2: f64, y2: f64) -> Option<Self> {
11        ((0.0..=1.0).contains(&x1) && (0.0..=1.0).contains(&x2) && y1.is_finite() && y2.is_finite())
12            .then_some(Self(Some([x1, y1, x2, y2])))
13    }
14
15    fn sample(self, progress: f64) -> f64 {
16        let Some([x1, y1, x2, y2]) = self.0 else {
17            return progress;
18        };
19        if progress == 0.0 || progress == 1.0 {
20            return progress;
21        }
22        let coordinate = |p1: f64, p2: f64, t: f64| {
23            let inverse = 1.0 - t;
24            (3.0 * inverse * inverse * t) * p1 + (3.0 * inverse * t * t) * p2 + t * t * t
25        };
26        // The x axis is monotonic. Bisection also handles horizontal tangents
27        // and curves whose two x control points coincide.
28        let (mut low, mut high) = (0.0, 1.0);
29        for _ in 0..24 {
30            let mid = (low + high) * 0.5;
31            if coordinate(x1, x2, mid) < progress {
32                low = mid;
33            } else {
34                high = mid;
35            }
36        }
37        coordinate(y1, y2, (low + high) * 0.5)
38    }
39}
40
41#[derive(Clone, Copy, Debug, Default, PartialEq)]
42pub struct Animation {
43    duration: Duration,
44    delay: Duration,
45    easing: Easing,
46}
47
48impl Animation {
49    pub fn new(duration_ms: u64, delay_ms: u64, easing: Easing) -> Self {
50        Self {
51            duration: Duration::from_millis(duration_ms),
52            delay: Duration::from_millis(delay_ms),
53            easing,
54        }
55    }
56}
57
58#[derive(Clone, Copy, Debug, PartialEq)]
59pub struct StateTiming {
60    pub case: i64,
61    pub enter: Option<Animation>,
62    pub exit: Option<Animation>,
63}
64
65struct Track {
66    from: Value,
67    begin: Duration,
68    end: Duration,
69    easing: Easing,
70}
71
72impl Track {
73    fn sample(&self, to: &Value, now: Duration) -> Option<Value> {
74        if now >= self.end {
75            return None;
76        }
77        if now <= self.begin {
78            return Some(self.from.clone());
79        }
80        let progress = (now - self.begin).as_secs_f64() / (self.end - self.begin).as_secs_f64();
81        interpolate(&self.from, to, self.easing.sample(progress))
82    }
83}
84
85type Tracks = BTreeMap<Vec<usize>, BTreeMap<&'static str, Track>>;
86
87#[derive(Default)]
88pub struct SceneTransition {
89    tracks: Tracks,
90}
91
92impl SceneTransition {
93    pub fn between(previous: &Node, next: &Node) -> Self {
94        let mut result = Self::default();
95        result.retarget(previous, next, Duration::ZERO);
96        result
97    }
98
99    /// Replace the targets at this instant on the same scene clock.
100    /// Unchanged targets keep their original start and end times.
101    pub fn retarget(&mut self, previous: &Node, next: &Node, now: Duration) {
102        fn collect(
103            previous: &Node,
104            next: &Node,
105            path: &mut Vec<usize>,
106            old: &mut Tracks,
107            new: &mut Tracks,
108            now: Duration,
109        ) {
110            if previous.kind != next.kind
111                || previous.id != next.id
112                || previous.row_key != next.row_key
113            {
114                return;
115            }
116            let mut old_at_path = old.remove(path.as_slice()).unwrap_or_default();
117            let mut tracks = BTreeMap::new();
118            let mut track = |property, timing: Option<Animation>| {
119                if timing.is_some_and(|timing| timing.duration.is_zero() && timing.delay.is_zero())
120                {
121                    return;
122                }
123                let (Some(previous_target), Some(next_target)) = (
124                    previous.properties.get(property),
125                    next.properties.get(property),
126                ) else {
127                    return;
128                };
129                let old = old_at_path.remove(property).filter(|track| now < track.end);
130                if previous_target == next_target {
131                    if let Some(old) = old {
132                        tracks.insert(property, old);
133                    }
134                    return;
135                }
136                let Some(timing) = timing else {
137                    return;
138                };
139                let from = old
140                    .and_then(|track| track.sample(previous_target, now))
141                    .unwrap_or_else(|| previous_target.clone());
142                if from != *next_target && interpolate(&from, next_target, 0.0).is_some() {
143                    let begin = now.saturating_add(timing.delay);
144                    tracks.insert(
145                        property,
146                        Track {
147                            from,
148                            begin,
149                            end: begin.saturating_add(timing.duration),
150                            easing: timing.easing,
151                        },
152                    );
153                }
154            };
155            for (&property, &timing) in &next.animations {
156                track(property, Some(timing));
157            }
158            if let Some(timings) = &next.state_timings {
159                for (&property, next_state) in timings.iter() {
160                    let previous_state = previous
161                        .state_timings
162                        .as_ref()
163                        .and_then(|timings| timings.get(property));
164                    let timing = previous_state
165                        .filter(|state| state.case != next_state.case)
166                        .and_then(|state| next_state.enter.or(state.exit));
167                    track(property, timing);
168                }
169            }
170            if !tracks.is_empty() {
171                new.insert(path.clone(), tracks);
172            }
173            for (index, (previous, next)) in
174                previous.children.iter().zip(&next.children).enumerate()
175            {
176                path.push(index);
177                collect(previous, next, path, old, new, now);
178                path.pop();
179            }
180        }
181        let mut old = std::mem::take(&mut self.tracks);
182        collect(
183            previous,
184            next,
185            &mut Vec::new(),
186            &mut old,
187            &mut self.tracks,
188            now,
189        );
190    }
191
192    /// Return the earliest useful frame time. Pending delays can sleep until
193    /// their start time. A running interpolation needs another frame now.
194    pub fn next_frame(&self, elapsed: Duration) -> Option<Duration> {
195        self.tracks
196            .values()
197            .flat_map(|tracks| tracks.values())
198            .filter(|track| elapsed < track.end)
199            .map(|track| track.begin.max(elapsed))
200            .min()
201    }
202
203    pub fn running(&self, elapsed: Duration) -> bool {
204        self.next_frame(elapsed).is_some()
205    }
206
207    pub fn frame<'a>(&self, target: &'a Node, elapsed: Duration) -> Cow<'a, Node> {
208        if !self.running(elapsed) {
209            return Cow::Borrowed(target);
210        }
211        let mut frame = target.clone();
212        for (path, tracks) in &self.tracks {
213            if tracks.values().all(|track| elapsed >= track.end) {
214                continue;
215            }
216            let mut node = Some(&mut frame);
217            for &index in path {
218                node = node.and_then(|node| node.children.get_mut(index));
219            }
220            let Some(node) = node else {
221                continue;
222            };
223            for (&property, track) in tracks {
224                if let Some(value) = node.properties.get_mut(property)
225                    && let Some(interpolated) = track.sample(value, elapsed)
226                {
227                    *value = interpolated;
228                }
229            }
230        }
231        Cow::Owned(frame)
232    }
233}
234
235fn mix(a: f64, b: f64, amount: f64) -> f64 {
236    a * (1.0 - amount) + b * amount
237}
238
239fn mix_color(a: Color, b: Color, amount: f64) -> Color {
240    let channels = [24, 16, 8, 0].map(|shift| {
241        mix(
242            f64::from((a.0 >> shift) & 255),
243            f64::from((b.0 >> shift) & 255),
244            amount,
245        )
246        .round()
247        .clamp(0.0, 255.0) as u32
248    });
249    let [r, g, b, a] = channels;
250    Color((r << 24) | (g << 16) | (b << 8) | a)
251}
252
253fn mix_stops(a: &[GradientStop], b: &[GradientStop], amount: f64) -> Option<Arc<[GradientStop]>> {
254    if a.len() != b.len() {
255        return None;
256    }
257    let position_progress = amount.clamp(0.0, 1.0);
258    Some(
259        a.iter()
260            .zip(b)
261            .map(|(a, b)| GradientStop {
262                offset: mix(a.offset, b.offset, position_progress),
263                color: mix_color(a.color, b.color, amount),
264            })
265            .collect(),
266    )
267}
268
269fn interpolate(from: &Value, to: &Value, amount: f64) -> Option<Value> {
270    if !amount.is_finite() {
271        return None;
272    }
273    let number = |a: f64, b: f64| {
274        let result = mix(a, b, amount);
275        result.is_finite().then_some(result)
276    };
277    Some(match (from, to) {
278        (Value::Int(a), Value::Int(b)) => {
279            Value::Int(mix(*a as f64, *b as f64, amount).round() as i64)
280        }
281        (Value::Float(a), Value::Float(b)) => Value::Float(number(*a, *b)?),
282        (Value::Length(Length(a)), Value::Length(Length(b))) => {
283            Value::Length(Length(number(*a, *b)?))
284        }
285        (Value::Percent(Percent(a)), Value::Percent(Percent(b))) => {
286            Value::Percent(Percent(number(*a, *b)?))
287        }
288        (Value::Color(a) | Value::Brush(Brush::Solid(a)), Value::Color(b)) => {
289            Value::Color(mix_color(*a, *b, amount))
290        }
291        (Value::Color(a) | Value::Brush(Brush::Solid(a)), Value::Brush(Brush::Solid(b))) => {
292            Value::Brush(Brush::Solid(mix_color(*a, *b, amount)))
293        }
294        (
295            Value::Brush(Brush::Linear {
296                angle_degrees: a,
297                stops: from,
298            }),
299            Value::Brush(Brush::Linear {
300                angle_degrees: b,
301                stops: to,
302            }),
303        ) => Value::Brush(Brush::Linear {
304            angle_degrees: number(*a, *b)?,
305            stops: mix_stops(from, to, amount)?,
306        }),
307        (
308            Value::Brush(Brush::Radial { stops: from }),
309            Value::Brush(Brush::Radial { stops: to }),
310        ) => Value::Brush(Brush::Radial {
311            stops: mix_stops(from, to, amount)?,
312        }),
313        _ => return None,
314    })
315}
316
317#[cfg(test)]
318mod tests {
319    use super::*;
320
321    fn time(ms: u64) -> Duration {
322        Duration::from_millis(ms)
323    }
324
325    fn rectangle(width: f64, timing: Animation) -> Node {
326        let mut node = Node::new("Rectangle", Some("bar"));
327        node.properties.insert("width", Length(width).into());
328        node.animations.insert("width", timing);
329        node
330    }
331
332    #[test]
333    fn unrelated_updates_keep_deadlines_and_retargeting_starts_at_the_visible_value() {
334        let timing = Animation::new(200, 100, Easing::LINEAR);
335        let initial = rectangle(10.0, timing);
336        let target = rectangle(110.0, timing);
337        let mut transition = SceneTransition::between(&initial, &target);
338        assert_eq!(transition.next_frame(time(20)), Some(time(100)));
339        assert_eq!(
340            transition.frame(&target, time(20)).length("width"),
341            Some(10.0)
342        );
343
344        let mut updated = target.clone();
345        updated.properties.insert("height", Length(40.0).into());
346        transition.retarget(&target, &updated, time(50));
347        assert_eq!(transition.next_frame(time(50)), Some(time(100)));
348        assert_eq!(
349            transition.frame(&updated, time(200)).length("width"),
350            Some(60.0)
351        );
352
353        let reversed = rectangle(0.0, timing);
354        transition.retarget(&updated, &reversed, time(200));
355        assert_eq!(transition.next_frame(time(200)), Some(time(300)));
356        assert_eq!(
357            transition.frame(&reversed, time(200)).length("width"),
358            Some(60.0)
359        );
360        assert_eq!(
361            transition.frame(&reversed, time(400)).length("width"),
362            Some(30.0)
363        );
364        assert!(matches!(
365            transition.frame(&reversed, time(500)),
366            Cow::Borrowed(_)
367        ));
368
369        let mut immediate = reversed.clone();
370        immediate.animations.clear();
371        transition.retarget(&reversed, &immediate, time(400));
372        assert_eq!(transition.next_frame(time(400)), None);
373        assert_eq!(
374            transition.frame(&immediate, time(400)).length("width"),
375            Some(0.0)
376        );
377    }
378
379    #[test]
380    fn a_delayed_zero_duration_track_jumps_only_at_its_deadline() {
381        let timing = Animation::new(0, 90, Easing::LINEAR);
382        let initial = rectangle(20.0, timing);
383        let target = rectangle(100.0, timing);
384        let transition = SceneTransition::between(&initial, &target);
385        assert_eq!(transition.next_frame(time(0)), Some(time(90)));
386        assert_eq!(
387            transition.frame(&target, time(89)).length("width"),
388            Some(20.0)
389        );
390        assert_eq!(
391            transition.frame(&target, time(90)).length("width"),
392            Some(100.0)
393        );
394        assert_eq!(transition.next_frame(time(90)), None);
395    }
396
397    #[test]
398    fn easing_clamps_overshooting_channels_and_interpolates_matching_gradients() {
399        let fast = Easing::cubic_bezier(0.0, 0.8, 1.0, 0.8).unwrap();
400        assert!((fast.sample(0.5) - 0.725).abs() < 1e-6);
401        let overshoot = Easing::cubic_bezier(0.0, 2.0, 1.0, 2.0)
402            .unwrap()
403            .sample(0.5);
404        assert!(overshoot > 1.0);
405        assert_eq!(
406            mix_color(Color(0x001020ff), Color(0xeeeeeeff), overshoot),
407            Color(0xffffffff)
408        );
409
410        let brush = |angle_degrees, start, end, color| {
411            Value::Brush(Brush::Linear {
412                angle_degrees,
413                stops: [
414                    GradientStop {
415                        color,
416                        offset: start,
417                    },
418                    GradientStop { color, offset: end },
419                ]
420                .into(),
421            })
422        };
423        let from = brush(0.0, 0.0, 0.8, Color(0xff0000ff));
424        let to = brush(90.0, 0.2, 1.0, Color(0x0000ffff));
425        assert_eq!(
426            interpolate(&from, &to, 0.5),
427            Some(brush(45.0, 0.1, 0.9, Color(0x800080ff)))
428        );
429    }
430}