Skip to main content

xrack_runtime/
image_animation.rs

1use crate::{Image, ImageFormat, Node, Property};
2use std::{
3    collections::BTreeMap,
4    fmt,
5    rc::Rc,
6    time::{Duration, Instant},
7};
8
9/// A composited frame and its exclusive end on the source's timeline.
10#[derive(Debug)]
11pub struct ImageAnimationFrame {
12    pub end_ms: u32,
13    pub png: &'static [u8],
14}
15
16/// Immutable, compiler-prepared frames shared by every use of an image.
17#[derive(Debug)]
18pub struct ImageAnimation {
19    size: [u32; 2],
20    frames: &'static [ImageAnimationFrame],
21    plays: u32,
22}
23
24impl ImageAnimation {
25    #[doc(hidden)]
26    pub const fn new(size: [u32; 2], frames: &'static [ImageAnimationFrame], plays: u32) -> Self {
27        Self {
28            size,
29            frames,
30            plays,
31        }
32    }
33
34    pub fn frame_count(&self) -> usize {
35        self.frames.len()
36    }
37
38    pub fn frame(&self, index: usize) -> Image {
39        self.frames
40            .get(index)
41            .or_else(|| self.frames.first())
42            .map_or(Image::Empty, |frame| Image::Embedded {
43                format: ImageFormat::Png,
44                bytes: frame.png,
45                size: self.size,
46            })
47    }
48
49    pub fn size(&self) -> [u32; 2] {
50        self.size
51    }
52}
53
54impl PartialEq for ImageAnimation {
55    fn eq(&self, other: &Self) -> bool {
56        std::ptr::eq(self, other)
57    }
58}
59
60impl Eq for ImageAnimation {}
61
62#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
63struct Sample {
64    source: Image,
65    frame: usize,
66}
67
68#[derive(Clone, Copy, Debug, PartialEq)]
69struct Playback {
70    source: Image,
71    playing: bool,
72    paused: bool,
73    speed: f64,
74    loops: i64,
75}
76
77impl Playback {
78    fn from_node(node: &Node) -> Self {
79        let speed = node.number("speed").unwrap_or(1.0);
80        Self {
81            source: node.image("source").unwrap_or_default(),
82            playing: node.boolean("playing", true),
83            paused: node.boolean("paused", false),
84            speed: if speed.is_finite() {
85                speed.clamp(0.0, 16.0)
86            } else {
87                0.0
88            },
89            loops: node.int("loops").unwrap_or(0),
90        }
91    }
92
93    fn active(self) -> bool {
94        self.playing && !self.paused && self.speed > 0.0
95    }
96
97    fn plays(self, animation: &ImageAnimation) -> u32 {
98        match self.loops {
99            i64::MIN..=-1 => 0,
100            0 => animation.plays,
101            count => count.min(i64::from(u32::MAX)) as u32,
102        }
103    }
104}
105
106#[doc(hidden)]
107#[derive(Default)]
108pub struct ImagePlaybackSlot(Rc<Property<Sample>>);
109
110impl ImagePlaybackSlot {
111    pub fn current_frame(&self) -> i64 {
112        self.0.get(Sample::default).frame as i64
113    }
114
115    pub fn frame_count(&self) -> i64 {
116        self.0.get(Sample::default).source.frame_count() as i64
117    }
118
119    pub fn populate(&self, node: &mut Node, finished: impl Fn() -> bool + 'static) {
120        let config = Playback::from_node(node);
121        let sample = self.0.get(Sample::default);
122        let frame = if config.playing && sample.source == config.source {
123            sample.frame
124        } else {
125            0
126        };
127        node.properties
128            .insert("current-frame", (frame as i64).into());
129        node.image_playback = Some(Rc::new(ImagePlaybackRegistration {
130            sample: self.0.clone(),
131            config,
132            finished: Rc::new(finished),
133        }));
134    }
135}
136
137#[doc(hidden)]
138pub struct ImagePlaybackRegistration {
139    sample: Rc<Property<Sample>>,
140    config: Playback,
141    finished: Rc<dyn Fn() -> bool>,
142}
143
144impl ImagePlaybackRegistration {
145    fn key(&self) -> usize {
146        Rc::as_ptr(&self.sample) as usize
147    }
148
149    pub fn finish(&self) -> bool {
150        (self.finished)()
151    }
152}
153
154impl PartialEq for ImagePlaybackRegistration {
155    fn eq(&self, other: &Self) -> bool {
156        Rc::ptr_eq(&self.sample, &other.sample) && self.config == other.config
157    }
158}
159
160impl fmt::Debug for ImagePlaybackRegistration {
161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162        f.debug_struct("ImagePlaybackRegistration")
163            .field("key", &self.key())
164            .field("config", &self.config)
165            .finish_non_exhaustive()
166    }
167}
168
169struct Entry {
170    registration: Rc<ImagePlaybackRegistration>,
171    anchor: Instant,
172    presented: bool,
173    position_ms: f64,
174    next: Option<Instant>,
175    ended: bool,
176    pending_finished: bool,
177}
178
179impl Entry {
180    fn integrate(&mut self, now: Instant) {
181        let config = self.registration.config;
182        if self.next.is_some() {
183            let elapsed_ms =
184                now.saturating_duration_since(self.anchor).as_nanos() as f64 / 1_000_000.0;
185            self.position_ms += elapsed_ms * config.speed;
186        }
187        self.anchor = now;
188    }
189
190    fn sample(&mut self) -> bool {
191        let config = self.registration.config;
192        let mut frame = 0;
193        let mut ended = false;
194        self.next = None;
195        if config.playing
196            && let Image::Animated(animation) = config.source
197            && let [_, _, ..] = animation.frames
198        {
199            let duration = f64::from(animation.frames.last().unwrap().end_ms);
200            if duration > 0.0 {
201                let plays = config.plays(animation);
202                ended = plays != 0 && self.position_ms >= duration * f64::from(plays);
203                if ended {
204                    frame = animation.frame_count() - 1;
205                } else {
206                    let within = self.position_ms % duration;
207                    frame = animation
208                        .frames
209                        .partition_point(|frame| f64::from(frame.end_ms) <= within);
210                    if self.presented && config.active() {
211                        let remaining_ms = f64::from(animation.frames[frame].end_ms) - within;
212                        self.next = Duration::try_from_secs_f64(
213                            (remaining_ms / config.speed / 1000.0).max(0.001),
214                        )
215                        .ok()
216                        .and_then(|delay| self.anchor.checked_add(delay));
217                    }
218                }
219            }
220        }
221        self.pending_finished |= ended && !self.ended;
222        self.ended = ended;
223        let sample = Sample {
224            source: config.source,
225            frame,
226        };
227        if self.registration.sample.get(Sample::default) == sample {
228            return false;
229        }
230        self.registration.sample.set(sample);
231        true
232    }
233}
234
235/// Clock and deadlines for visible playback registrations. The host owns time.
236#[doc(hidden)]
237#[derive(Default)]
238pub struct ImagePlaybackQueue {
239    entries: BTreeMap<usize, Entry>,
240}
241
242impl ImagePlaybackQueue {
243    pub fn sync<'a>(
244        &mut self,
245        now: Instant,
246        registrations: impl IntoIterator<Item = (&'a Rc<ImagePlaybackRegistration>, bool)>,
247    ) {
248        let mut previous = std::mem::take(&mut self.entries);
249        for (registration, presented) in registrations {
250            let key = registration.key();
251            if self.entries.contains_key(&key) {
252                continue;
253            }
254            let mut entry = if let Some(mut entry) = previous.remove(&key) {
255                let old = entry.registration.config;
256                let next = registration.config;
257                if old == next && entry.presented == presented {
258                    entry.registration = registration.clone();
259                    self.entries.insert(key, entry);
260                    continue;
261                }
262                entry.integrate(now);
263                if old.source != next.source || !next.playing || !old.playing {
264                    entry.position_ms = 0.0;
265                    entry.ended = false;
266                    entry.pending_finished = false;
267                }
268                entry.registration = registration.clone();
269                entry.presented = presented;
270                entry
271            } else {
272                Entry {
273                    registration: registration.clone(),
274                    anchor: now,
275                    presented,
276                    position_ms: 0.0,
277                    next: None,
278                    ended: false,
279                    pending_finished: false,
280                }
281            };
282            entry.sample();
283            self.entries.insert(key, entry);
284        }
285        for entry in previous.into_values() {
286            entry.registration.sample.set_if_changed(Sample::default());
287        }
288    }
289
290    pub fn deadline(&self) -> Option<Instant> {
291        self.entries
292            .values()
293            .filter_map(|entry| {
294                if entry.pending_finished {
295                    Some(entry.anchor)
296                } else {
297                    entry.next
298                }
299            })
300            .min()
301    }
302
303    /// Coalesce missed ticks and publish only the frame visible at `now`.
304    pub fn advance(&mut self, now: Instant) -> bool {
305        let mut changed = false;
306        for entry in self
307            .entries
308            .values_mut()
309            .filter(|entry| entry.next.is_some_and(|next| next <= now))
310        {
311            entry.integrate(now);
312            changed |= entry.sample();
313        }
314        changed
315    }
316
317    pub fn next_finished(&mut self) -> Option<Rc<ImagePlaybackRegistration>> {
318        let entry = self
319            .entries
320            .values_mut()
321            .find(|entry| entry.pending_finished)?;
322        entry.pending_finished = false;
323        Some(entry.registration.clone())
324    }
325}