Skip to main content

rayengine_core/
tween.rs

1//! Display-independent tweens, easing, sequences, parallel groups and screen shake.
2//!
3//! Tweens are plain game-owned values advanced by explicitly supplied time,
4//! like [`crate::time::Timer`] and [`crate::sprite::AnimationPlayer`]. Timing uses
5//! integer nanoseconds, so loops never drift and even [`Duration::MAX`] steps run
6//! in constant time. Nothing allocates while advancing; a [`Tween`] is `Copy`
7//! whenever its value is, and groups reuse the storage they were built with.
8//!
9//! ```
10//! use rayengine_core::{events::Events, glam::Vec2, tween::*};
11//! use std::time::Duration;
12//!
13//! const PANEL: TweenId = TweenId(1);
14//! let mut slide = Tween::new(Vec2::new(-200.0, 20.0), Vec2::new(16.0, 20.0), Duration::from_millis(400))
15//!     .with_ease(Ease::BackOut)
16//!     .with_delay(Duration::from_millis(100))
17//!     .with_id(PANEL);
18//! let mut completed = Events::with_capacity(4);
19//! for _ in 0..60 {
20//!     if let Some(done) = slide.advance(Duration::from_secs_f32(1.0 / 120.0)) {
21//!         completed.send(done);
22//!     }
23//! }
24//! assert_eq!(slide.value(), Vec2::new(16.0, 20.0)); // exact end value
25//! assert_eq!(completed.read(), &[TweenCompleted { id: PANEL }]); // reported once
26//! ```
27
28pub mod ease;
29mod shake;
30
31pub use ease::Ease;
32pub use shake::{Shake, ShakeConfig, ShakeError, ShakeSample};
33
34use glam::{Quat, Vec2, Vec3, Vec4};
35use std::time::Duration;
36
37/// Values that can be interpolated by a tween.
38///
39/// `t` is eased progress. It is `0.0` and `1.0` at the endpoints but may lie
40/// outside `[0, 1]` for overshooting curves such as [`Ease::BackOut`].
41pub trait Tweenable: Copy {
42    /// Interpolates (or extrapolates) from `from` toward `to`.
43    fn interpolate(from: Self, to: Self, t: f32) -> Self;
44}
45
46impl Tweenable for f32 {
47    fn interpolate(from: Self, to: Self, t: f32) -> Self {
48        from + (to - from) * t
49    }
50}
51impl Tweenable for Vec2 {
52    fn interpolate(from: Self, to: Self, t: f32) -> Self {
53        from.lerp(to, t)
54    }
55}
56impl Tweenable for Vec3 {
57    fn interpolate(from: Self, to: Self, t: f32) -> Self {
58        from.lerp(to, t)
59    }
60}
61/// Also suitable for linear RGBA colors in `[0, 1]`.
62impl Tweenable for Vec4 {
63    fn interpolate(from: Self, to: Self, t: f32) -> Self {
64        from.lerp(to, t)
65    }
66}
67/// Spherical interpolation for rotations such as doors and hinges.
68impl Tweenable for Quat {
69    fn interpolate(from: Self, to: Self, t: f32) -> Self {
70        from.slerp(to, t)
71    }
72}
73/// 8-bit RGBA colors (the core's mesh and manifest color layout). Each channel
74/// is interpolated independently, rounded and clamped to `0..=255`.
75impl Tweenable for [u8; 4] {
76    fn interpolate(from: Self, to: Self, t: f32) -> Self {
77        std::array::from_fn(|i| {
78            let (a, b) = (f32::from(from[i]), f32::from(to[i]));
79            (a + (b - a) * t).round().clamp(0.0, 255.0) as u8
80        })
81    }
82}
83
84/// Game-defined tween identity carried by [`TweenCompleted`], like input actions.
85#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
86pub struct TweenId(pub u32);
87
88/// Returned exactly once when a tween, sequence or group completes.
89/// Send it to a game-owned [`crate::events::Events`] queue.
90#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
91pub struct TweenCompleted {
92    /// Identity of the completed tween or group.
93    pub id: TweenId,
94}
95
96/// Behavior after one traversal of a tween's duration.
97#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
98pub enum TweenMode {
99    /// Run from start to end once, then complete.
100    #[default]
101    Once,
102    /// Restart from the start after each cycle.
103    Loop,
104    /// Alternate direction each cycle: start→end, end→start, ...
105    PingPong,
106}
107
108#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
109enum Status {
110    Active,
111    Finished,
112    Cancelled,
113}
114
115/// Something that can be advanced inside a [`Sequence`] or [`Parallel`] group.
116///
117/// Implemented by [`Tween`], [`Sequence`] and [`Parallel`], so groups nest.
118/// Games can implement it for their own timed behaviors.
119pub trait Animate {
120    /// Advances unless paused, finished or cancelled. Returns the unused part
121    /// of `dt` from the call that completes the animation, otherwise `None`.
122    fn step(&mut self, dt: Duration) -> Option<Duration>;
123    /// Returns to the start and rearms completion, preserving pause state.
124    fn rewind(&mut self);
125    /// Jumps to the final state and marks it finished, without reporting completion.
126    fn skip_to_end(&mut self);
127    /// Whether finished or cancelled; a group skips done members.
128    fn is_done(&self) -> bool;
129}
130
131/// Shared explicit controls with the same meaning for tweens and groups.
132macro_rules! controls {
133    () => {
134        /// Advances by explicitly supplied time. Returns one completion on the call
135        /// that reaches the end; paused, finished and cancelled playback do nothing.
136        pub fn advance(&mut self, dt: Duration) -> Option<TweenCompleted> {
137            self.step(dt).map(|_| TweenCompleted { id: self.id })
138        }
139        /// Sets the identity reported on completion.
140        pub fn with_id(mut self, id: TweenId) -> Self {
141            self.id = id;
142            self
143        }
144        /// Identity reported on completion.
145        pub fn id(&self) -> TweenId {
146            self.id
147        }
148        /// Stops advancement; time supplied while paused is discarded.
149        pub fn pause(&mut self) {
150            self.paused = true;
151        }
152        /// Allows advancement again. Finished or cancelled playback stays so until reset.
153        pub fn resume(&mut self) {
154            self.paused = false;
155        }
156        /// Whether explicit time advancement is paused.
157        pub fn is_paused(&self) -> bool {
158            self.paused
159        }
160        /// Rewinds to the start and rearms completion, preserving pause state.
161        pub fn reset(&mut self) {
162            self.rewind();
163        }
164        /// Stops at the current value without completing; [`Self::reset`] rearms.
165        pub fn cancel(&mut self) {
166            if self.status == Status::Active {
167                self.status = Status::Cancelled;
168            }
169        }
170        /// Jumps to the final value and returns the completion immediately, even
171        /// while paused. Returns `None` if already finished or cancelled.
172        pub fn finish(&mut self) -> Option<TweenCompleted> {
173            if self.status != Status::Active {
174                return None;
175            }
176            self.skip_to_end();
177            Some(TweenCompleted { id: self.id })
178        }
179        /// Whether the end was reached (by advancing or [`Self::finish`]).
180        pub fn is_finished(&self) -> bool {
181            self.status == Status::Finished
182        }
183        /// Whether [`Self::cancel`] stopped playback before the end.
184        pub fn is_cancelled(&self) -> bool {
185            self.status == Status::Cancelled
186        }
187    };
188}
189
190fn from_nanos(nanos: u128) -> Duration {
191    Duration::new(
192        (nanos / 1_000_000_000) as u64,
193        (nanos % 1_000_000_000) as u32,
194    )
195}
196
197/// Typed interpolation between two values with duration, delay, easing and repetition.
198///
199/// The delay applies once, before the first cycle. Repeating tweens run until
200/// [`Self::with_cycles`] repetitions complete, or forever. Exact cycle boundaries
201/// wrap to the next cycle; a finished tween holds its exact final value.
202/// [`Self::finish`] on an endless tween ends its current cycle, so a ping-pong
203/// leg running backward finishes at the start value.
204#[derive(Clone, Copy, Debug, PartialEq)]
205pub struct Tween<T> {
206    from: T,
207    to: T,
208    duration: Duration,
209    delay: Duration,
210    ease: Ease,
211    mode: TweenMode,
212    cycles: Option<u32>,
213    id: TweenId,
214    waited: Duration,
215    position: Duration,
216    completed: u32,
217    reversed: bool,
218    paused: bool,
219    status: Status,
220}
221
222impl<T: Tweenable> Tween<T> {
223    /// Linear one-shot tween without delay. A zero duration completes on its
224    /// first advance, including a zero-length one.
225    pub fn new(from: T, to: T, duration: Duration) -> Self {
226        Self {
227            from,
228            to,
229            duration,
230            delay: Duration::ZERO,
231            ease: Ease::Linear,
232            mode: TweenMode::Once,
233            cycles: None,
234            id: TweenId::default(),
235            waited: Duration::ZERO,
236            position: Duration::ZERO,
237            completed: 0,
238            reversed: false,
239            paused: false,
240            status: Status::Active,
241        }
242    }
243    /// Waits this long, holding the start value, before the first cycle.
244    /// A tween already past its delay keeps running; the new delay applies after reset.
245    pub fn with_delay(mut self, delay: Duration) -> Self {
246        let started = self.waited >= self.delay
247            && (!self.position.is_zero() || self.completed > 0 || self.status != Status::Active);
248        self.delay = delay;
249        if started {
250            self.waited = delay;
251        }
252        self
253    }
254    /// Selects the easing curve applied to each cycle.
255    pub fn with_ease(mut self, ease: Ease) -> Self {
256        self.ease = ease;
257        self
258    }
259    /// Selects one-shot, looping or ping-pong playback.
260    /// Panics if a repeating mode is selected with a zero duration.
261    pub fn with_mode(mut self, mode: TweenMode) -> Self {
262        assert!(
263            mode == TweenMode::Once || !self.duration.is_zero(),
264            "repeating tween duration must be nonzero"
265        );
266        self.mode = mode;
267        // Only ping-pong legs run backward; other modes continue forward.
268        self.reversed &= mode == TweenMode::PingPong;
269        self
270    }
271    /// Completes a repeating tween after this many cycles; a ping-pong cycle is
272    /// one leg, so `2` goes there and back. Ignored by [`TweenMode::Once`].
273    /// Panics for zero.
274    pub fn with_cycles(mut self, cycles: u32) -> Self {
275        assert!(cycles > 0, "tween cycle count must be positive");
276        self.cycles = Some(cycles);
277        self
278    }
279
280    /// Start value.
281    pub fn from(&self) -> T {
282        self.from
283    }
284    /// End value of a forward cycle.
285    pub fn to(&self) -> T {
286        self.to
287    }
288    /// Duration of one cycle.
289    pub fn duration(&self) -> Duration {
290        self.duration
291    }
292    /// Delay before the first cycle.
293    pub fn delay(&self) -> Duration {
294        self.delay
295    }
296    /// Easing curve.
297    pub fn ease(&self) -> Ease {
298        self.ease
299    }
300    /// Repetition behavior.
301    pub fn mode(&self) -> TweenMode {
302        self.mode
303    }
304    /// Completed cycles; saturates for endless repetition.
305    pub fn completed_cycles(&self) -> u32 {
306        self.completed
307    }
308
309    /// Un-eased progress through the current cycle, in `[0, 1]`; zero during the delay.
310    pub fn progress(&self) -> f32 {
311        if self.duration.is_zero() {
312            return if self.status == Status::Finished {
313                1.0
314            } else {
315                0.0
316            };
317        }
318        (self.position.as_nanos() as f64 / self.duration.as_nanos() as f64) as f32
319    }
320
321    /// Current value. Reading never advances playback. The endpoints are returned
322    /// exactly, so a finished tween reports precisely its final value.
323    pub fn value(&self) -> T {
324        let t = self.progress();
325        let eased = self.ease.apply(if self.reversed { 1.0 - t } else { t });
326        if eased == 0.0 {
327            self.from
328        } else if eased == 1.0 {
329            self.to
330        } else {
331            T::interpolate(self.from, self.to, eased)
332        }
333    }
334
335    /// Restarts toward a new end value from the current value, preserving
336    /// duration, easing, mode, identity and pause state. The delay is skipped, so
337    /// an interrupted UI slide turns around immediately instead of stalling.
338    pub fn retarget(&mut self, to: T) {
339        self.from = self.value();
340        self.to = to;
341        self.rewind();
342        self.waited = self.delay;
343    }
344
345    controls!();
346}
347
348impl<T: Tweenable> Animate for Tween<T> {
349    fn step(&mut self, dt: Duration) -> Option<Duration> {
350        if self.paused || self.status != Status::Active {
351            return None;
352        }
353        let mut left = dt;
354        if self.waited < self.delay {
355            let wait = self.delay - self.waited;
356            if left < wait {
357                self.waited += left;
358                return None;
359            }
360            left -= wait;
361            self.waited = self.delay;
362        }
363        // Even two Duration::MAX values fit in u128 nanoseconds.
364        let period = self.duration.as_nanos();
365        let next = self.position.as_nanos() + left.as_nanos();
366        if self.mode == TweenMode::Once {
367            if next < period {
368                self.position = from_nanos(next);
369                return None;
370            }
371            self.skip_to_end();
372            return Some(from_nanos(next - period));
373        }
374        // Repeating modes always have a nonzero period.
375        let crossed = next / period;
376        if let Some(cycles) = self.cycles {
377            // A limit set after more cycles already ran finishes on this step.
378            let remaining = u128::from(cycles.saturating_sub(self.completed));
379            if crossed >= remaining {
380                self.skip_to_end();
381                return Some(from_nanos((next - remaining * period).min(left.as_nanos())));
382            }
383        }
384        self.completed = (u128::from(self.completed) + crossed).min(u128::from(u32::MAX)) as u32;
385        if self.mode == TweenMode::PingPong && crossed % 2 == 1 {
386            self.reversed = !self.reversed;
387        }
388        self.position = from_nanos(next % period);
389        None
390    }
391
392    fn rewind(&mut self) {
393        self.waited = Duration::ZERO;
394        self.position = Duration::ZERO;
395        self.completed = 0;
396        self.reversed = false;
397        self.status = Status::Active;
398    }
399
400    fn skip_to_end(&mut self) {
401        self.waited = self.delay;
402        self.position = self.duration;
403        (self.completed, self.reversed) = match (self.mode, self.cycles) {
404            (TweenMode::Once, _) => (1, false),
405            // The last ping-pong leg runs backward when it is an even-numbered leg.
406            (mode, Some(cycles)) => (cycles, mode == TweenMode::PingPong && cycles % 2 == 0),
407            // Endless repetition finishes its current cycle, keeping its direction.
408            (_, None) => (self.completed.saturating_add(1), self.reversed),
409        };
410        self.status = Status::Finished;
411    }
412
413    fn is_done(&self) -> bool {
414        self.status != Status::Active
415    }
416}
417
418/// Fixed-size storage of group members, indexed without allocation.
419///
420/// Implemented for arrays and `Vec`s of one [`Animate`] type (allocated once by
421/// the game) and for tuples of up to eight different [`Animate`] types.
422pub trait Tracks {
423    /// Number of members.
424    fn len(&self) -> usize;
425    /// Whether there are no members.
426    fn is_empty(&self) -> bool {
427        self.len() == 0
428    }
429    /// Member at `index`, which must be less than [`Self::len`].
430    fn track(&self, index: usize) -> &dyn Animate;
431    /// Mutable member at `index`, which must be less than [`Self::len`].
432    fn track_mut(&mut self, index: usize) -> &mut dyn Animate;
433}
434
435impl<A: Animate, const N: usize> Tracks for [A; N] {
436    fn len(&self) -> usize {
437        N
438    }
439    fn track(&self, index: usize) -> &dyn Animate {
440        &self[index]
441    }
442    fn track_mut(&mut self, index: usize) -> &mut dyn Animate {
443        &mut self[index]
444    }
445}
446
447impl<A: Animate> Tracks for Vec<A> {
448    fn len(&self) -> usize {
449        self.as_slice().len()
450    }
451    fn track(&self, index: usize) -> &dyn Animate {
452        &self[index]
453    }
454    fn track_mut(&mut self, index: usize) -> &mut dyn Animate {
455        &mut self[index]
456    }
457}
458
459macro_rules! tuple_tracks {
460    ($len:literal: $($name:ident $index:tt),+) => {
461        impl<$($name: Animate),+> Tracks for ($($name,)+) {
462            fn len(&self) -> usize {
463                $len
464            }
465            fn track(&self, index: usize) -> &dyn Animate {
466                match index {
467                    $($index => &self.$index,)+
468                    _ => panic!("track index {index} out of range for {} tracks", $len),
469                }
470            }
471            fn track_mut(&mut self, index: usize) -> &mut dyn Animate {
472                match index {
473                    $($index => &mut self.$index,)+
474                    _ => panic!("track index {index} out of range for {} tracks", $len),
475                }
476            }
477        }
478    };
479}
480tuple_tracks!(1: A 0);
481tuple_tracks!(2: A 0, B 1);
482tuple_tracks!(3: A 0, B 1, C 2);
483tuple_tracks!(4: A 0, B 1, C 2, D 3);
484tuple_tracks!(5: A 0, B 1, C 2, D 3, E 4);
485tuple_tracks!(6: A 0, B 1, C 2, D 3, E 4, F 5);
486tuple_tracks!(7: A 0, B 1, C 2, D 3, E 4, F 5, G 6);
487tuple_tracks!(8: A 0, B 1, C 2, D 3, E 4, F 5, G 6, H 7);
488
489/// Runs members one after another. Time left over when a member completes
490/// carries into the next, so frame/tick partitioning never shifts later members.
491///
492/// An empty sequence completes on its first advance. A paused member holds
493/// the sequence; cancelled members are skipped. An endlessly repeating member
494/// never yields to later members. Control members through the sequence.
495///
496/// ```
497/// use rayengine_core::tween::*;
498/// use std::time::Duration;
499/// let ms = Duration::from_millis;
500/// // Flash red, then fade back to white.
501/// let mut flash = Sequence::new([
502///     Tween::new([255, 255, 255, 255], [255, 40, 40, 255], ms(50)),
503///     Tween::new([255, 40, 40, 255], [255, 255, 255, 255], ms(200)).with_ease(Ease::QuadOut),
504/// ]);
505/// assert!(flash.advance(ms(100)).is_none());
506/// assert_eq!(flash.current(), 1);
507/// assert!(flash.advance(ms(150)).is_some());
508/// assert_eq!(flash.value(), Some([255, 255, 255, 255]));
509/// ```
510#[derive(Clone, Debug)]
511pub struct Sequence<S> {
512    tracks: S,
513    current: usize,
514    id: TweenId,
515    paused: bool,
516    status: Status,
517}
518
519impl<S: Tracks> Sequence<S> {
520    /// Starts at the first member, unpaused, with the default identity.
521    pub fn new(tracks: S) -> Self {
522        Self {
523            tracks,
524            current: 0,
525            id: TweenId::default(),
526            paused: false,
527            status: Status::Active,
528        }
529    }
530    /// Members, for reading their values.
531    pub fn tracks(&self) -> &S {
532        &self.tracks
533    }
534    /// Members, for adjusting them in place. Changes to a member the group has
535    /// already finished with take effect only after resetting the group.
536    pub fn tracks_mut(&mut self) -> &mut S {
537        &mut self.tracks
538    }
539    /// Index of the running member; equals the member count once finished.
540    pub fn current(&self) -> usize {
541        self.current
542    }
543
544    controls!();
545}
546
547impl<S: Tracks> Sequence<S> {
548    /// Value of the running (or, once finished, last) member of a sequence of
549    /// same-typed tweens. `None` only for an empty sequence.
550    pub fn value<T: Tweenable>(&self) -> Option<T>
551    where
552        S: AsRef<[Tween<T>]>,
553    {
554        let tweens = self.tracks.as_ref();
555        tweens
556            .get(self.current.min(tweens.len().saturating_sub(1)))
557            .map(Tween::value)
558    }
559}
560
561impl<S: Tracks> Animate for Sequence<S> {
562    fn step(&mut self, dt: Duration) -> Option<Duration> {
563        if self.paused || self.status != Status::Active {
564            return None;
565        }
566        let mut left = dt;
567        while self.current < self.tracks.len() {
568            let track = self.tracks.track_mut(self.current);
569            if !track.is_done() {
570                left = track.step(left)?;
571            }
572            self.current += 1;
573        }
574        self.status = Status::Finished;
575        Some(left)
576    }
577
578    fn rewind(&mut self) {
579        for index in 0..self.tracks.len() {
580            self.tracks.track_mut(index).rewind();
581        }
582        self.current = 0;
583        self.status = Status::Active;
584    }
585
586    fn skip_to_end(&mut self) {
587        for index in 0..self.tracks.len() {
588            self.tracks.track_mut(index).skip_to_end();
589        }
590        self.current = self.tracks.len();
591        self.status = Status::Finished;
592    }
593
594    fn is_done(&self) -> bool {
595        self.status != Status::Active
596    }
597}
598
599/// Runs members simultaneously and completes when every member is done.
600///
601/// An empty group completes on its first advance. Paused members hold the
602/// group open; cancelled members count as done. Read member values through
603/// [`Self::tracks`].
604///
605/// ```
606/// use rayengine_core::{glam::Vec2, tween::*};
607/// use std::time::Duration;
608/// let ms = Duration::from_millis;
609/// let mut pickup = Parallel::new((
610///     Tween::new(Vec2::ZERO, Vec2::new(0.0, -12.0), ms(300)).with_ease(Ease::QuadOut),
611///     Tween::new(1.0_f32, 0.0, ms(500)).with_delay(ms(100)),
612/// ))
613/// .with_id(TweenId(7));
614/// assert!(pickup.advance(ms(300)).is_none());
615/// assert_eq!(pickup.tracks().0.value(), Vec2::new(0.0, -12.0));
616/// assert_eq!(pickup.advance(ms(300)), Some(TweenCompleted { id: TweenId(7) }));
617/// ```
618#[derive(Clone, Debug)]
619pub struct Parallel<S> {
620    tracks: S,
621    id: TweenId,
622    paused: bool,
623    status: Status,
624}
625
626impl<S: Tracks> Parallel<S> {
627    /// Starts every member together, unpaused, with the default identity.
628    pub fn new(tracks: S) -> Self {
629        Self {
630            tracks,
631            id: TweenId::default(),
632            paused: false,
633            status: Status::Active,
634        }
635    }
636    /// Members, for reading their values.
637    pub fn tracks(&self) -> &S {
638        &self.tracks
639    }
640    /// Members, for adjusting them in place. Changes to a member the group has
641    /// already finished with take effect only after resetting the group.
642    pub fn tracks_mut(&mut self) -> &mut S {
643        &mut self.tracks
644    }
645
646    controls!();
647}
648
649impl<S: Tracks> Animate for Parallel<S> {
650    fn step(&mut self, dt: Duration) -> Option<Duration> {
651        if self.paused || self.status != Status::Active {
652            return None;
653        }
654        // The group ends with its longest member: the smallest leftover.
655        let mut left = dt;
656        let mut done = true;
657        for index in 0..self.tracks.len() {
658            let track = self.tracks.track_mut(index);
659            if track.is_done() {
660                continue;
661            }
662            match track.step(dt) {
663                Some(rest) => left = left.min(rest),
664                None => done &= track.is_done(),
665            }
666        }
667        if !done {
668            return None;
669        }
670        self.status = Status::Finished;
671        Some(left)
672    }
673
674    fn rewind(&mut self) {
675        for index in 0..self.tracks.len() {
676            self.tracks.track_mut(index).rewind();
677        }
678        self.status = Status::Active;
679    }
680
681    fn skip_to_end(&mut self) {
682        for index in 0..self.tracks.len() {
683            self.tracks.track_mut(index).skip_to_end();
684        }
685        self.status = Status::Finished;
686    }
687
688    fn is_done(&self) -> bool {
689        self.status != Status::Active
690    }
691}
692
693#[cfg(test)]
694mod tests;