Skip to main content

xrack_runtime/
image_animation.rs

1use crate::{Image, ImageAsset, ImageFormat, LoadedAnimation, 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, PartialEq, Eq)]
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    #[doc(hidden)]
54    pub fn frames(&self) -> impl ExactSizeIterator<Item = (u32, &[u8])> {
55        self.frames.iter().map(|frame| (frame.end_ms, frame.png))
56    }
57
58    pub(crate) fn matches_loaded(&self, other: &LoadedAnimation) -> bool {
59        self.size == other.size && self.plays == other.plays && self.frames().eq(other.frames())
60    }
61}
62
63impl PartialEq for ImageAnimation {
64    fn eq(&self, other: &Self) -> bool {
65        std::ptr::eq(self, other)
66            || (self.size == other.size && self.plays == other.plays && self.frames == other.frames)
67    }
68}
69
70impl Eq for ImageAnimation {}
71
72enum Timeline<'a> {
73    Embedded(&'a ImageAnimation),
74    Loaded(&'a LoadedAnimation),
75}
76
77impl<'a> Timeline<'a> {
78    fn for_image(image: &'a ImageAsset) -> Option<Self> {
79        match image {
80            ImageAsset::Embedded(Image::Animated(animation)) => Some(Self::Embedded(animation)),
81            ImageAsset::Animated(animation) => Some(Self::Loaded(animation)),
82            _ => None,
83        }
84    }
85
86    fn plays(&self) -> u32 {
87        match self {
88            Self::Embedded(animation) => animation.plays,
89            Self::Loaded(animation) => animation.plays,
90        }
91    }
92
93    fn end(&self, frame: usize) -> f64 {
94        f64::from(match self {
95            Self::Embedded(animation) => animation.frames[frame].end_ms,
96            Self::Loaded(animation) => animation.frames[frame].0,
97        })
98    }
99
100    fn frame_at(&self, position: f64) -> usize {
101        match self {
102            Self::Embedded(animation) => animation
103                .frames
104                .partition_point(|frame| f64::from(frame.end_ms) <= position),
105            Self::Loaded(animation) => animation
106                .frames
107                .partition_point(|(end, _)| f64::from(*end) <= position),
108        }
109    }
110}
111
112#[derive(Clone, Debug, Default, PartialEq, Eq)]
113struct Sample {
114    source: ImageAsset,
115    frame: usize,
116}
117
118#[derive(Clone, Debug, PartialEq)]
119struct Playback {
120    source: ImageAsset,
121    playing: bool,
122    paused: bool,
123    speed: f64,
124    loops: i64,
125}
126
127impl Playback {
128    fn from_node(node: &Node) -> Self {
129        let speed = node.number("speed").unwrap_or(1.0);
130        Self {
131            source: node.image_asset("source").unwrap_or_default(),
132            playing: node.boolean("playing", true),
133            paused: node.boolean("paused", false),
134            speed: if speed.is_finite() {
135                speed.clamp(0.0, 16.0)
136            } else {
137                0.0
138            },
139            loops: node.int("loops").unwrap_or(0),
140        }
141    }
142
143    fn active(&self) -> bool {
144        self.playing && !self.paused && self.speed > 0.0
145    }
146
147    fn plays(&self, animation: &Timeline<'_>) -> u32 {
148        match self.loops {
149            i64::MIN..=-1 => 0,
150            0 => animation.plays(),
151            count => count.min(i64::from(u32::MAX)) as u32,
152        }
153    }
154}
155
156#[doc(hidden)]
157#[derive(Default)]
158pub struct ImagePlaybackSlot(Rc<Property<Sample>>);
159
160impl ImagePlaybackSlot {
161    pub fn current_frame(&self) -> i64 {
162        self.0.get(Sample::default).frame as i64
163    }
164
165    pub fn frame_count(&self) -> i64 {
166        self.0.get(Sample::default).source.frame_count() as i64
167    }
168
169    pub fn populate(&self, node: &mut Node, finished: impl Fn() -> bool + 'static) {
170        let config = Playback::from_node(node);
171        let sample = self.0.get(Sample::default);
172        let frame = if config.playing && sample.source == config.source {
173            sample.frame
174        } else {
175            0
176        };
177        node.properties
178            .insert("current-frame", (frame as i64).into());
179        node.image_playback = Some(Rc::new(ImagePlaybackRegistration {
180            sample: self.0.clone(),
181            config,
182            finished: Rc::new(finished),
183        }));
184    }
185}
186
187#[doc(hidden)]
188pub struct ImagePlaybackRegistration {
189    sample: Rc<Property<Sample>>,
190    config: Playback,
191    finished: Rc<dyn Fn() -> bool>,
192}
193
194impl ImagePlaybackRegistration {
195    fn key(&self) -> usize {
196        Rc::as_ptr(&self.sample) as usize
197    }
198
199    pub fn finish(&self) -> bool {
200        (self.finished)()
201    }
202}
203
204impl PartialEq for ImagePlaybackRegistration {
205    fn eq(&self, other: &Self) -> bool {
206        Rc::ptr_eq(&self.sample, &other.sample) && self.config == other.config
207    }
208}
209
210impl fmt::Debug for ImagePlaybackRegistration {
211    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212        f.debug_struct("ImagePlaybackRegistration")
213            .field("key", &self.key())
214            .field("config", &self.config)
215            .finish_non_exhaustive()
216    }
217}
218
219struct Entry {
220    registration: Rc<ImagePlaybackRegistration>,
221    anchor: Instant,
222    presented: bool,
223    position_ms: f64,
224    next: Option<Instant>,
225    ended: bool,
226    pending_finished: bool,
227}
228
229impl Entry {
230    fn integrate(&mut self, now: Instant) {
231        let config = &self.registration.config;
232        if self.next.is_some() {
233            let elapsed_ms =
234                now.saturating_duration_since(self.anchor).as_nanos() as f64 / 1_000_000.0;
235            self.position_ms += elapsed_ms * config.speed;
236        }
237        self.anchor = now;
238    }
239
240    fn sample(&mut self) -> bool {
241        let config = &self.registration.config;
242        let mut frame = 0;
243        let mut ended = false;
244        self.next = None;
245        if config.playing
246            && let Some(animation) = Timeline::for_image(&config.source)
247            && config.source.frame_count() >= 2
248        {
249            let count = config.source.frame_count();
250            let duration = animation.end(count - 1);
251            if duration > 0.0 {
252                let plays = config.plays(&animation);
253                ended = plays != 0 && self.position_ms >= duration * f64::from(plays);
254                if ended {
255                    frame = count - 1;
256                } else {
257                    let within = self.position_ms % duration;
258                    frame = animation.frame_at(within);
259                    if self.presented && config.active() {
260                        let remaining_ms = animation.end(frame) - within;
261                        self.next = Duration::try_from_secs_f64(
262                            (remaining_ms / config.speed / 1000.0).max(0.001),
263                        )
264                        .ok()
265                        .and_then(|delay| self.anchor.checked_add(delay));
266                    }
267                }
268            }
269        }
270        self.pending_finished |= ended && !self.ended;
271        self.ended = ended;
272        let sample = Sample {
273            source: config.source.clone(),
274            frame,
275        };
276        if self.registration.sample.get(Sample::default) == sample {
277            return false;
278        }
279        self.registration.sample.set(sample);
280        true
281    }
282}
283
284/// Clock and deadlines for visible playback registrations. The host owns time.
285#[doc(hidden)]
286#[derive(Default)]
287pub struct ImagePlaybackQueue {
288    entries: BTreeMap<usize, Entry>,
289}
290
291impl ImagePlaybackQueue {
292    pub fn sync<'a>(
293        &mut self,
294        now: Instant,
295        registrations: impl IntoIterator<Item = (&'a Rc<ImagePlaybackRegistration>, bool)>,
296    ) -> bool {
297        let mut changed = false;
298        let mut previous = std::mem::take(&mut self.entries);
299        for (registration, presented) in registrations {
300            let key = registration.key();
301            if self.entries.contains_key(&key) {
302                continue;
303            }
304            let mut entry = if let Some(mut entry) = previous.remove(&key) {
305                let old = &entry.registration.config;
306                let next = &registration.config;
307                if old == next && entry.presented == presented {
308                    entry.registration = registration.clone();
309                    self.entries.insert(key, entry);
310                    continue;
311                }
312                let reset = old.source != next.source || !next.playing || !old.playing;
313                entry.integrate(now);
314                if reset {
315                    entry.position_ms = 0.0;
316                    entry.ended = false;
317                    entry.pending_finished = false;
318                }
319                entry.registration = registration.clone();
320                entry.presented = presented;
321                entry
322            } else {
323                Entry {
324                    registration: registration.clone(),
325                    anchor: now,
326                    presented,
327                    position_ms: 0.0,
328                    next: None,
329                    ended: false,
330                    pending_finished: false,
331                }
332            };
333            changed |= entry.sample();
334            self.entries.insert(key, entry);
335        }
336        for entry in previous.into_values() {
337            let sample = &entry.registration.sample;
338            let empty = Sample::default();
339            if sample.get(Sample::default) != empty {
340                sample.set(empty);
341                changed = true;
342            }
343        }
344        changed
345    }
346
347    pub fn deadline(&self) -> Option<Instant> {
348        self.entries
349            .values()
350            .filter_map(|entry| {
351                if entry.pending_finished {
352                    Some(entry.anchor)
353                } else {
354                    entry.next
355                }
356            })
357            .min()
358    }
359
360    /// Coalesce missed ticks and publish only the frame visible at `now`.
361    pub fn advance(&mut self, now: Instant) -> bool {
362        let mut changed = false;
363        for entry in self
364            .entries
365            .values_mut()
366            .filter(|entry| entry.next.is_some_and(|next| next <= now))
367        {
368            entry.integrate(now);
369            changed |= entry.sample();
370        }
371        changed
372    }
373
374    pub fn next_finished(&mut self) -> Option<Rc<ImagePlaybackRegistration>> {
375        let entry = self
376            .entries
377            .values_mut()
378            .find(|entry| entry.pending_finished)?;
379        entry.pending_finished = false;
380        Some(entry.registration.clone())
381    }
382}