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