ferravex_play/
tween.rs

1//! Easing curves, tweens, springs and UI/screen transition timing.
2//!
3//! Everything here is `Copy`, allocation-free and advanced by a caller-supplied
4//! `dt` in seconds, so presentation stays deterministic for a given sequence of
5//! timesteps (subject to the platform's `exp`/`sin`/`powf`, as with
6//! [`crate::motion`]). Nothing reads a clock. Drive these from the frame delta
7//! for menus and HUD polish; drive them from the fixed tick when the motion is
8//! part of gameplay timing.
9//!
10//! Reduced motion is an explicit [`Motion`] argument. Build it from the player's
11//! [`FeedbackPolicy`] with `Motion::from(policy)`. Under [`Motion::Reduced`]
12//! tweens and springs snap to their targets, entrances only fade, roll counters
13//! show the final number and screen transitions become plain fades.
14//!
15//! ```
16//! use ferravex_play::tween::{Ease, Motion, Spring, Tween};
17//! let mut fade = Tween::new(0., 1., 0.25, Ease::CubicOut);
18//! let mut scale = Spring::underdamped(0.8, 6., 0.45);
19//! scale.set_target(1.);
20//! for _ in 0..30 {
21//!     let alpha = fade.advance(1. / 60., Motion::Full);
22//!     let s = scale.advance(1. / 60., Motion::Full);
23//!     assert!((0. ..=1.).contains(&alpha) && s.is_finite());
24//! }
25//! assert!(fade.is_finished() && fade.value() == 1.);
26//! ```
27use crate::feedback::FeedbackPolicy;
28use std::f32::consts::{FRAC_PI_2, PI, TAU};
29
30/// Whether presentation motion is full or reduced for accessibility.
31///
32/// ```
33/// use ferravex_play::{feedback::FeedbackPolicy, tween::Motion};
34/// let policy = FeedbackPolicy::new(true, false, 1.).unwrap();
35/// assert_eq!(Motion::from(policy), Motion::Reduced);
36/// assert_eq!(Motion::from_reduced(false), Motion::Full);
37/// ```
38#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
39pub enum Motion {
40    #[default]
41    Full,
42    Reduced,
43}
44
45impl Motion {
46    pub const fn from_reduced(reduced: bool) -> Self {
47        if reduced { Self::Reduced } else { Self::Full }
48    }
49    pub const fn is_reduced(self) -> bool {
50        matches!(self, Self::Reduced)
51    }
52}
53
54impl From<FeedbackPolicy> for Motion {
55    fn from(policy: FeedbackPolicy) -> Self {
56        Self::from_reduced(policy.reduced_motion())
57    }
58}
59
60impl From<&FeedbackPolicy> for Motion {
61    fn from(policy: &FeedbackPolicy) -> Self {
62        Self::from(*policy)
63    }
64}
65
66/// Standard easing curves. [`Ease::apply`] maps `t` in `[0, 1]` (clamped) to
67/// eased progress with exact endpoints `0 → 0` and `1 → 1`. Back and elastic
68/// curves overshoot outside `[0, 1]` in between; bounce stays inside it.
69///
70/// ```
71/// use ferravex_play::tween::Ease;
72/// for ease in Ease::ALL {
73///     assert_eq!((ease.apply(0.), ease.apply(1.)), (0., 1.));
74/// }
75/// assert!(Ease::QuadIn.apply(0.5) < 0.5 && Ease::QuadOut.apply(0.5) > 0.5);
76/// assert!(Ease::BackOut.apply(0.7) > 1.); // overshoot
77/// ```
78#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
79pub enum Ease {
80    #[default]
81    Linear,
82    SineIn,
83    SineOut,
84    SineInOut,
85    QuadIn,
86    QuadOut,
87    QuadInOut,
88    CubicIn,
89    CubicOut,
90    CubicInOut,
91    QuartIn,
92    QuartOut,
93    QuartInOut,
94    ExpoIn,
95    ExpoOut,
96    ExpoInOut,
97    BackIn,
98    BackOut,
99    BackInOut,
100    ElasticIn,
101    ElasticOut,
102    ElasticInOut,
103    BounceIn,
104    BounceOut,
105    BounceInOut,
106}
107
108fn bounce_out(t: f32) -> f32 {
109    const N: f32 = 7.5625;
110    const D: f32 = 2.75;
111    if t < 1. / D {
112        N * t * t
113    } else if t < 2. / D {
114        let t = t - 1.5 / D;
115        N * t * t + 0.75
116    } else if t < 2.5 / D {
117        let t = t - 2.25 / D;
118        N * t * t + 0.9375
119    } else {
120        let t = t - 2.625 / D;
121        N * t * t + 0.984375
122    }
123}
124
125impl Ease {
126    /// Every curve, in declaration order.
127    pub const ALL: [Self; 25] = [
128        Self::Linear,
129        Self::SineIn,
130        Self::SineOut,
131        Self::SineInOut,
132        Self::QuadIn,
133        Self::QuadOut,
134        Self::QuadInOut,
135        Self::CubicIn,
136        Self::CubicOut,
137        Self::CubicInOut,
138        Self::QuartIn,
139        Self::QuartOut,
140        Self::QuartInOut,
141        Self::ExpoIn,
142        Self::ExpoOut,
143        Self::ExpoInOut,
144        Self::BackIn,
145        Self::BackOut,
146        Self::BackInOut,
147        Self::ElasticIn,
148        Self::ElasticOut,
149        Self::ElasticInOut,
150        Self::BounceIn,
151        Self::BounceOut,
152        Self::BounceInOut,
153    ];
154
155    /// Eased progress for `t` (clamped to `[0, 1]`; NaN counts as 0).
156    pub fn apply(self, t: f32) -> f32 {
157        if t.is_nan() || t <= 0. {
158            return 0.;
159        }
160        if t >= 1. {
161            return 1.;
162        }
163        const C1: f32 = 1.70158;
164        const C2: f32 = C1 * 1.525;
165        const C3: f32 = C1 + 1.;
166        const C4: f32 = TAU / 3.;
167        const C5: f32 = TAU / 4.5;
168        let inout = |t: f32, f: fn(f32) -> f32| {
169            if t < 0.5 {
170                f(2. * t) * 0.5
171            } else {
172                1. - f(2. - 2. * t) * 0.5
173            }
174        };
175        match self {
176            Self::Linear => t,
177            Self::SineIn => 1. - (t * FRAC_PI_2).cos(),
178            Self::SineOut => (t * FRAC_PI_2).sin(),
179            Self::SineInOut => -((PI * t).cos() - 1.) * 0.5,
180            Self::QuadIn => t * t,
181            Self::QuadOut => 1. - (1. - t) * (1. - t),
182            Self::QuadInOut => inout(t, |t| t * t),
183            Self::CubicIn => t * t * t,
184            Self::CubicOut => 1. - (1. - t).powi(3),
185            Self::CubicInOut => inout(t, |t| t * t * t),
186            Self::QuartIn => t.powi(4),
187            Self::QuartOut => 1. - (1. - t).powi(4),
188            Self::QuartInOut => inout(t, |t| t.powi(4)),
189            Self::ExpoIn => 2_f32.powf(10. * t - 10.),
190            Self::ExpoOut => 1. - 2_f32.powf(-10. * t),
191            Self::ExpoInOut => inout(t, |t| 2_f32.powf(10. * t - 10.)),
192            Self::BackIn => C3 * t * t * t - C1 * t * t,
193            Self::BackOut => {
194                let u = t - 1.;
195                1. + C3 * u * u * u + C1 * u * u
196            }
197            Self::BackInOut => {
198                if t < 0.5 {
199                    let u = 2. * t;
200                    u * u * ((C2 + 1.) * u - C2) * 0.5
201                } else {
202                    let u = 2. * t - 2.;
203                    (u * u * ((C2 + 1.) * u + C2) + 2.) * 0.5
204                }
205            }
206            Self::ElasticIn => -(2_f32.powf(10. * t - 10.)) * ((t * 10. - 10.75) * C4).sin(),
207            Self::ElasticOut => 2_f32.powf(-10. * t) * ((t * 10. - 0.75) * C4).sin() + 1.,
208            Self::ElasticInOut => {
209                let s = ((20. * t - 11.125) * C5).sin();
210                if t < 0.5 {
211                    -(2_f32.powf(20. * t - 10.) * s) * 0.5
212                } else {
213                    2_f32.powf(-20. * t + 10.) * s * 0.5 + 1.
214                }
215            }
216            Self::BounceIn => 1. - bounce_out(1. - t),
217            Self::BounceOut => bounce_out(t),
218            Self::BounceInOut => {
219                if t < 0.5 {
220                    (1. - bounce_out(1. - 2. * t)) * 0.5
221                } else {
222                    (1. + bounce_out(2. * t - 1.)) * 0.5
223                }
224            }
225        }
226    }
227}
228
229/// Linear interpolation `a + (b - a) * t` (`t` is not clamped).
230///
231/// ```
232/// assert_eq!(ferravex_play::tween::lerp(10., 20., 0.25), 12.5);
233/// ```
234pub fn lerp(a: f32, b: f32, t: f32) -> f32 {
235    a + (b - a) * t
236}
237
238fn step(dt: f32) -> f32 {
239    if dt.is_finite() { dt.max(0.) } else { 0. }
240}
241
242/// A one-shot eased transition from `from` to `to` over `duration` seconds,
243/// optionally after a delay. Non-finite or negative timesteps count as zero;
244/// a nonpositive duration finishes immediately.
245///
246/// ```
247/// use ferravex_play::tween::{Ease, Motion, Tween};
248/// let mut slide = Tween::new(-40., 0., 0.4, Ease::BackOut).delayed(0.1);
249/// assert_eq!(slide.advance(0.1, Motion::Full), -40.); // still delayed
250/// slide.advance(0.2, Motion::Full);
251/// assert!(slide.value() > -40. && !slide.is_finished());
252/// slide.advance(1., Motion::Full);
253/// assert_eq!(slide.value(), 0.);
254/// slide.retarget(100.); // continue smoothly from the current value
255/// assert_eq!(Tween::new(0., 5., 1., Ease::Linear).advance(0.01, Motion::Reduced), 5.);
256/// ```
257#[derive(Clone, Copy, Debug, PartialEq)]
258pub struct Tween {
259    from: f32,
260    to: f32,
261    duration: f32,
262    delay: f32,
263    elapsed: f32,
264    ease: Ease,
265}
266
267impl Tween {
268    pub fn new(from: f32, to: f32, duration: f32, ease: Ease) -> Self {
269        Self {
270            from,
271            to,
272            duration: if duration.is_finite() {
273                duration.max(0.)
274            } else {
275                0.
276            },
277            delay: 0.,
278            elapsed: 0.,
279            ease,
280        }
281    }
282    /// A tween that already sits at `value`.
283    pub fn settled(value: f32) -> Self {
284        Self::new(value, value, 0., Ease::Linear)
285    }
286    /// Waits `delay` seconds before starting.
287    pub fn delayed(mut self, delay: f32) -> Self {
288        self.delay = if delay.is_finite() { delay.max(0.) } else { 0. };
289        self
290    }
291    /// Advances time and returns the new value. Reduced motion jumps to the end.
292    pub fn advance(&mut self, dt: f32, motion: Motion) -> f32 {
293        if motion.is_reduced() {
294            self.finish();
295        } else {
296            let end = self.delay + self.duration;
297            self.elapsed = (self.elapsed + step(dt)).min(end);
298        }
299        self.value()
300    }
301    /// Linear progress in `[0, 1]`, excluding the delay.
302    pub fn progress(&self) -> f32 {
303        if self.duration <= 0. {
304            return if self.elapsed >= self.delay { 1. } else { 0. };
305        }
306        ((self.elapsed - self.delay) / self.duration).clamp(0., 1.)
307    }
308    /// Current eased value; exactly `to` once finished.
309    pub fn value(&self) -> f32 {
310        let p = self.progress();
311        if p >= 1. {
312            self.to
313        } else {
314            lerp(self.from, self.to, self.ease.apply(p))
315        }
316    }
317    pub fn target(&self) -> f32 {
318        self.to
319    }
320    pub fn is_finished(&self) -> bool {
321        self.progress() >= 1.
322    }
323    /// Jumps to the end.
324    pub fn finish(&mut self) {
325        self.elapsed = self.delay + self.duration;
326    }
327    /// Restarts from `from` (keeping duration, delay and easing).
328    pub fn restart(&mut self) {
329        self.elapsed = 0.;
330    }
331    /// Starts a new tween from the current value toward `to` without a delay.
332    pub fn retarget(&mut self, to: f32) {
333        if to != self.to || !self.is_finished() {
334            self.from = self.value();
335            self.to = to;
336            self.delay = 0.;
337            self.elapsed = 0.;
338        }
339    }
340}
341
342/// A damped harmonic spring toward `target`, integrated analytically so any
343/// `dt` is stable and splitting a step gives the same result (up to rounding).
344///
345/// `frequency` is the undamped angular speed in Hz; `damping` is the damping
346/// ratio: `1` is critically damped (fastest without overshoot), below `1`
347/// overshoots and wobbles, above `1` is sluggish.
348///
349/// ```
350/// use ferravex_play::tween::{Motion, Spring};
351/// let mut hover = Spring::critical(0., 8.);
352/// hover.set_target(1.);
353/// let mut peak: f32 = 0.;
354/// for _ in 0..120 { peak = peak.max(hover.advance(1. / 60., Motion::Full)); }
355/// assert!(peak <= 1. && hover.is_settled(1e-3));
356///
357/// let mut pop = Spring::underdamped(0., 5., 0.3);
358/// pop.set_target(1.);
359/// let mut peak: f32 = 0.;
360/// for _ in 0..120 { peak = peak.max(pop.advance(1. / 60., Motion::Full)); }
361/// assert!(peak > 1.2); // springy overshoot
362/// ```
363#[derive(Clone, Copy, Debug, PartialEq)]
364pub struct Spring {
365    pub value: f32,
366    pub velocity: f32,
367    pub target: f32,
368    omega: f32,
369    damping: f32,
370}
371
372impl Spring {
373    /// Spring at rest at `value`. Invalid parameters fall back to 1 Hz / ratio 1.
374    pub fn new(value: f32, frequency: f32, damping: f32) -> Self {
375        let frequency = if frequency.is_finite() && frequency > 0. {
376            frequency
377        } else {
378            1.
379        };
380        let damping = if damping.is_finite() && damping > 0. {
381            damping
382        } else {
383            1.
384        };
385        let value = if value.is_finite() { value } else { 0. };
386        Self {
387            value,
388            velocity: 0.,
389            target: value,
390            omega: frequency * TAU,
391            damping,
392        }
393    }
394    /// Critically damped: settles as fast as possible without overshoot.
395    pub fn critical(value: f32, frequency: f32) -> Self {
396        Self::new(value, frequency, 1.)
397    }
398    /// Bouncy spring with damping ratio in `(0, 1)` (e.g. `0.3`–`0.6`).
399    pub fn underdamped(value: f32, frequency: f32, damping: f32) -> Self {
400        Self::new(value, frequency, damping.clamp(0.01, 0.999))
401    }
402    pub fn set_target(&mut self, target: f32) {
403        if target.is_finite() {
404            self.target = target;
405        }
406    }
407    /// Adds instantaneous velocity (a "kick" for pops and shakes).
408    pub fn impulse(&mut self, velocity: f32) {
409        if velocity.is_finite() {
410            self.velocity += velocity;
411        }
412    }
413    /// Places the spring at `value` with no velocity.
414    pub fn snap(&mut self, value: f32) {
415        if value.is_finite() {
416            self.value = value;
417            self.target = value;
418            self.velocity = 0.;
419        }
420    }
421    /// Within `epsilon` of the target with velocity below `epsilon`.
422    pub fn is_settled(&self, epsilon: f32) -> bool {
423        (self.value - self.target).abs() <= epsilon && self.velocity.abs() <= epsilon
424    }
425    /// Advances by `dt` and returns the value. Reduced motion snaps to target.
426    pub fn advance(&mut self, dt: f32, motion: Motion) -> f32 {
427        if motion.is_reduced() {
428            let target = self.target;
429            self.snap(target);
430            return self.value;
431        }
432        let t = step(dt);
433        if t == 0. {
434            return self.value;
435        }
436        let w = self.omega;
437        let z = self.damping;
438        let x0 = self.value - self.target;
439        let v0 = self.velocity;
440        let (x, v) = if (z - 1.).abs() < 1e-4 {
441            let e = (-w * t).exp();
442            let c = v0 + w * x0;
443            ((x0 + c * t) * e, (v0 - w * c * t) * e)
444        } else if z < 1. {
445            let wd = w * (1. - z * z).sqrt();
446            let a = z * w;
447            let b = (v0 + a * x0) / wd;
448            let e = (-a * t).exp();
449            let (sin, cos) = (wd * t).sin_cos();
450            (
451                e * (x0 * cos + b * sin),
452                e * ((b * wd - a * x0) * cos - (a * b + x0 * wd) * sin),
453            )
454        } else {
455            let root = (z * z - 1.).sqrt();
456            let r1 = -w * (z - root);
457            let r2 = -w * (z + root);
458            let c2 = (v0 - r1 * x0) / (r2 - r1);
459            let c1 = x0 - c2;
460            let (e1, e2) = ((r1 * t).exp(), (r2 * t).exp());
461            (c1 * e1 + c2 * e2, r1 * c1 * e1 + r2 * c2 * e2)
462        };
463        if x.is_finite() && v.is_finite() {
464            self.value = self.target + x;
465            self.velocity = v;
466        } else {
467            let target = self.target;
468            self.snap(target);
469        }
470        self.value
471    }
472}
473
474/// How a staggered UI element appears at one instant: multiply its alpha,
475/// translate it by `offset` and scale it about its center by `scale`.
476#[derive(Clone, Copy, Debug, PartialEq)]
477pub struct Appearance {
478    pub alpha: f32,
479    pub offset: [f32; 2],
480    pub scale: f32,
481}
482
483impl Appearance {
484    /// Fully shown, in place.
485    pub const SHOWN: Self = Self {
486        alpha: 1.,
487        offset: [0., 0.],
488        scale: 1.,
489    };
490    /// Fully hidden.
491    pub const HIDDEN: Self = Self {
492        alpha: 0.,
493        offset: [0., 0.],
494        scale: 1.,
495    };
496}
497
498/// Fade/slide/scale entrance shared by a list of elements with a per-item
499/// stagger. Sample with the time since the list opened; play it backwards
500/// (decreasing `elapsed`) for an exit.
501///
502/// ```
503/// use ferravex_play::tween::{Entrance, Motion};
504/// let menu = Entrance::fade_up(12.).with_stagger(0.05);
505/// let first = menu.sample(0.1, 0, Motion::Full);
506/// let third = menu.sample(0.1, 2, Motion::Full);
507/// assert!(first.alpha > third.alpha && first.offset[1] < third.offset[1]);
508/// assert_eq!(menu.sample(10., 5, Motion::Full).alpha, 1.);
509/// // Reduced motion keeps the fade but drops movement and stagger.
510/// let calm = menu.sample(0.1, 2, Motion::Reduced);
511/// assert_eq!((calm.offset, calm.scale), ([0., 0.], 1.));
512/// ```
513#[derive(Clone, Copy, Debug, PartialEq)]
514pub struct Entrance {
515    pub duration: f32,
516    /// Extra delay per item index.
517    pub stagger: f32,
518    pub ease: Ease,
519    pub fade: bool,
520    /// Starting offset, eased to zero.
521    pub slide: [f32; 2],
522    /// Starting scale, eased to one.
523    pub scale_from: f32,
524}
525
526impl Entrance {
527    /// Fades in while rising `distance` units (0.28 s, cubic out).
528    pub fn fade_up(distance: f32) -> Self {
529        Self {
530            duration: 0.28,
531            stagger: 0.04,
532            ease: Ease::CubicOut,
533            fade: true,
534            slide: [0., distance],
535            scale_from: 1.,
536        }
537    }
538    /// Fades in while growing from `scale_from` with a slight overshoot.
539    pub fn pop(scale_from: f32) -> Self {
540        Self {
541            duration: 0.32,
542            stagger: 0.04,
543            ease: Ease::BackOut,
544            fade: true,
545            slide: [0., 0.],
546            scale_from,
547        }
548    }
549    /// Plain fade.
550    pub fn fade() -> Self {
551        Self {
552            duration: 0.2,
553            stagger: 0.03,
554            ease: Ease::QuadOut,
555            fade: true,
556            slide: [0., 0.],
557            scale_from: 1.,
558        }
559    }
560    pub fn with_stagger(mut self, seconds: f32) -> Self {
561        self.stagger = seconds;
562        self
563    }
564    pub fn with_duration(mut self, seconds: f32) -> Self {
565        self.duration = seconds;
566        self
567    }
568    pub fn with_ease(mut self, ease: Ease) -> Self {
569        self.ease = ease;
570        self
571    }
572    /// Seconds until item `count - 1` has fully arrived.
573    pub fn total_duration(&self, count: usize) -> f32 {
574        self.duration.max(0.) + self.stagger.max(0.) * count.saturating_sub(1) as f32
575    }
576    /// Appearance of item `index` at `elapsed` seconds after the list opened.
577    pub fn sample(&self, elapsed: f32, index: usize, motion: Motion) -> Appearance {
578        let duration = self.duration.max(1e-6);
579        let elapsed = if elapsed.is_finite() { elapsed } else { 0. };
580        if motion.is_reduced() {
581            let t = (elapsed / duration).clamp(0., 1.);
582            return Appearance {
583                alpha: if self.fade { t } else { 1. },
584                ..Appearance::SHOWN
585            };
586        }
587        let local = elapsed - self.stagger.max(0.) * index as f32;
588        let t = (local / duration).clamp(0., 1.);
589        let eased = self.ease.apply(t);
590        let fade = Ease::QuadOut.apply(t);
591        let rest = 1. - eased;
592        Appearance {
593            alpha: if self.fade { fade } else { 1. },
594            offset: [self.slide[0] * rest, self.slide[1] * rest],
595            scale: lerp(self.scale_from, 1., eased),
596        }
597    }
598}
599
600/// An integer display that rolls toward its target, like a score counter.
601/// Every roll takes `duration` seconds regardless of size (eased, quick start
602/// and gentle landing) and the shown number never passes the target.
603///
604/// ```
605/// use ferravex_play::tween::{Motion, RollCounter};
606/// let mut score = RollCounter::new(0);
607/// score.set_target(1_250);
608/// let mut last = 0;
609/// for _ in 0..20 {
610///     let shown = score.advance(1. / 60., Motion::Full);
611///     assert!(shown >= last && shown <= 1_250);
612///     last = shown;
613/// }
614/// assert!(score.is_rolling());
615/// for _ in 0..60 { score.advance(1. / 60., Motion::Full); }
616/// assert_eq!(score.shown(), 1_250);
617/// score.set_target(2_000);
618/// assert_eq!(score.advance(0.016, Motion::Reduced), 2_000);
619/// ```
620#[derive(Clone, Copy, Debug, PartialEq)]
621pub struct RollCounter {
622    from: f64,
623    target: i64,
624    elapsed: f32,
625    /// Seconds per roll (default 0.6).
626    pub duration: f32,
627    /// Roll curve (default [`Ease::QuartOut`]).
628    pub ease: Ease,
629}
630
631impl RollCounter {
632    pub fn new(value: i64) -> Self {
633        Self {
634            from: value as f64,
635            target: value,
636            elapsed: 0.,
637            duration: 0.6,
638            ease: Ease::QuartOut,
639        }
640    }
641    /// Rolls from the currently shown value toward `target`.
642    pub fn set_target(&mut self, target: i64) {
643        if target != self.target {
644            self.from = self.exact();
645            self.target = target;
646            self.elapsed = 0.;
647        }
648    }
649    /// Shows `value` immediately.
650    pub fn snap(&mut self, value: i64) {
651        self.target = value;
652        self.from = value as f64;
653        self.elapsed = self.duration;
654    }
655    pub fn target(&self) -> i64 {
656        self.target
657    }
658    fn exact(&self) -> f64 {
659        let t = if self.duration > 0. {
660            self.elapsed / self.duration
661        } else {
662            1.
663        };
664        if t >= 1. {
665            return self.target as f64;
666        }
667        let k = self.ease.apply(t) as f64;
668        self.from + (self.target as f64 - self.from) * k
669    }
670    /// Number to display (rounded toward where the roll started).
671    pub fn shown(&self) -> i64 {
672        let value = self.exact();
673        let shown = if value < self.target as f64 {
674            value.floor()
675        } else {
676            value.ceil()
677        };
678        shown as i64
679    }
680    pub fn is_rolling(&self) -> bool {
681        self.shown() != self.target
682    }
683    /// Advances the roll and returns the number to display.
684    pub fn advance(&mut self, dt: f32, motion: Motion) -> i64 {
685        if motion.is_reduced() {
686            self.snap(self.target);
687        } else {
688            self.elapsed = (self.elapsed + step(dt)).min(self.duration.max(0.));
689        }
690        self.shown()
691    }
692}
693
694/// Visual style of a [`ScreenTransition`]. Drawing lives in the renderer
695/// (`ferravex_render::ui::kit::draw_screen_transition`).
696#[derive(Clone, Copy, Debug, Default, PartialEq)]
697pub enum TransitionKind {
698    /// Uniform fade to a color.
699    #[default]
700    Fade,
701    /// A soft-edged band sweeping across the screen in `direction`
702    /// (radians, 0 = left to right, Y down).
703    Wipe { direction: f32 },
704    /// A closing circle around a focus point.
705    Iris,
706}
707
708/// What a [`ScreenTransition`] is doing.
709#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
710pub enum TransitionPhase {
711    /// Nothing covers the screen.
712    #[default]
713    Idle,
714    /// Coverage rising toward 1.
715    Covering,
716    /// Fully covered; swap scenes, then call [`ScreenTransition::reveal`].
717    Covered,
718    /// Coverage falling toward 0.
719    Revealing,
720}
721
722/// Completion edge reported once by [`ScreenTransition::advance`].
723#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
724pub enum TransitionEvent {
725    Covered,
726    Revealed,
727}
728
729/// Cover → swap → reveal timing for scene changes (wipe, iris or fade).
730/// Under reduced motion [`ScreenTransition::kind`] reports [`TransitionKind::Fade`].
731///
732/// ```
733/// use ferravex_play::tween::{Motion, ScreenTransition, TransitionEvent, TransitionKind, TransitionPhase};
734/// let mut t = ScreenTransition::new(TransitionKind::Iris, 0.4);
735/// t.cover();
736/// let mut events = Vec::new();
737/// for _ in 0..60 {
738///     if let Some(e) = t.advance(1. / 60., Motion::Full) {
739///         events.push(e);
740///         if e == TransitionEvent::Covered { t.reveal(); } // load the next scene here
741///     }
742/// }
743/// assert_eq!(events, [TransitionEvent::Covered, TransitionEvent::Revealed]);
744/// assert_eq!((t.phase(), t.coverage()), (TransitionPhase::Idle, 0.));
745/// assert_eq!(t.kind(Motion::Reduced), TransitionKind::Fade);
746/// ```
747#[derive(Clone, Copy, Debug, PartialEq)]
748pub struct ScreenTransition {
749    kind: TransitionKind,
750    phase: TransitionPhase,
751    duration: f32,
752    elapsed: f32,
753    pub ease: Ease,
754}
755
756impl ScreenTransition {
757    /// `duration` is the time for each half (cover and reveal).
758    pub fn new(kind: TransitionKind, duration: f32) -> Self {
759        Self {
760            kind,
761            phase: TransitionPhase::Idle,
762            duration: if duration.is_finite() {
763                duration.max(0.)
764            } else {
765                0.
766            },
767            elapsed: 0.,
768            ease: Ease::CubicInOut,
769        }
770    }
771    pub fn phase(&self) -> TransitionPhase {
772        self.phase
773    }
774    /// The kind to draw this frame (reduced motion draws a fade).
775    pub fn kind(&self, motion: Motion) -> TransitionKind {
776        if motion.is_reduced() {
777            TransitionKind::Fade
778        } else {
779            self.kind
780        }
781    }
782    /// Starts covering the screen (from the current coverage).
783    pub fn cover(&mut self) {
784        if matches!(
785            self.phase,
786            TransitionPhase::Idle | TransitionPhase::Revealing
787        ) {
788            self.elapsed = self.duration * self.linear();
789            self.phase = TransitionPhase::Covering;
790        }
791    }
792    /// Starts revealing the screen (from the current coverage).
793    pub fn reveal(&mut self) {
794        if matches!(
795            self.phase,
796            TransitionPhase::Covered | TransitionPhase::Covering
797        ) {
798            self.elapsed = self.duration * (1. - self.linear());
799            self.phase = TransitionPhase::Revealing;
800        }
801    }
802    fn linear(&self) -> f32 {
803        let t = if self.duration > 0. {
804            (self.elapsed / self.duration).clamp(0., 1.)
805        } else {
806            1.
807        };
808        match self.phase {
809            TransitionPhase::Idle => 0.,
810            TransitionPhase::Covered => 1.,
811            TransitionPhase::Covering => t,
812            TransitionPhase::Revealing => 1. - t,
813        }
814    }
815    /// Eased screen coverage: 0 = clear, 1 = fully covered.
816    pub fn coverage(&self) -> f32 {
817        self.ease.apply(self.linear())
818    }
819    /// Advances time; returns an event on the frame a half completes.
820    /// Reduced motion halves the duration (the fade still reads as a cut).
821    pub fn advance(&mut self, dt: f32, motion: Motion) -> Option<TransitionEvent> {
822        let scale = if motion.is_reduced() { 2. } else { 1. };
823        match self.phase {
824            TransitionPhase::Covering | TransitionPhase::Revealing => {
825                self.elapsed += step(dt) * scale;
826                if self.elapsed < self.duration {
827                    return None;
828                }
829                self.elapsed = 0.;
830                if self.phase == TransitionPhase::Covering {
831                    self.phase = TransitionPhase::Covered;
832                    Some(TransitionEvent::Covered)
833                } else {
834                    self.phase = TransitionPhase::Idle;
835                    Some(TransitionEvent::Revealed)
836                }
837            }
838            _ => None,
839        }
840    }
841}
842
843#[cfg(test)]
844mod tests {
845    use super::*;
846
847    #[test]
848    fn every_ease_has_exact_endpoints_and_is_finite_and_continuous() {
849        for ease in Ease::ALL {
850            assert_eq!(ease.apply(0.), 0., "{ease:?}");
851            assert_eq!(ease.apply(1.), 1., "{ease:?}");
852            assert_eq!(ease.apply(-3.), 0.);
853            assert_eq!(ease.apply(f32::NAN), 0.);
854            assert_eq!(ease.apply(7.), 1.);
855            let mut prev = 0.;
856            for i in 1..=1000 {
857                let v = ease.apply(i as f32 / 1000.);
858                assert!(v.is_finite());
859                assert!(
860                    (v - prev).abs() < 0.05,
861                    "{ease:?} jumps at {i}: {prev} -> {v}"
862                );
863                prev = v;
864            }
865        }
866        // Symmetry of in/out pairs.
867        for (a, b) in [
868            (Ease::QuadIn, Ease::QuadOut),
869            (Ease::CubicIn, Ease::CubicOut),
870            (Ease::ExpoIn, Ease::ExpoOut),
871            (Ease::BackIn, Ease::BackOut),
872            (Ease::BounceIn, Ease::BounceOut),
873        ] {
874            for i in 0..=20 {
875                let t = i as f32 / 20.;
876                assert!(
877                    (a.apply(t) - (1. - b.apply(1. - t))).abs() < 1e-4,
878                    "{a:?} {t}"
879                );
880            }
881        }
882        for t in [0.25, 0.5, 0.75] {
883            assert!((Ease::QuadInOut.apply(t) + Ease::QuadInOut.apply(1. - t) - 1.).abs() < 1e-6);
884        }
885        assert!((0..=100).all(|i| (0. ..=1.).contains(&Ease::BounceOut.apply(i as f32 / 100.))));
886    }
887
888    #[test]
889    fn tween_endpoints_delay_retarget_and_bad_input() {
890        let mut t = Tween::new(2., 10., 1., Ease::QuadOut).delayed(0.5);
891        assert_eq!(t.value(), 2.);
892        t.advance(0.5, Motion::Full);
893        assert_eq!(t.value(), 2.);
894        t.advance(f32::NAN, Motion::Full);
895        t.advance(-1., Motion::Full);
896        assert_eq!(t.progress(), 0.);
897        t.advance(0.5, Motion::Full);
898        assert_eq!(t.value(), lerp(2., 10., Ease::QuadOut.apply(0.5)));
899        t.advance(100., Motion::Full);
900        assert_eq!((t.value(), t.is_finished()), (10., true));
901        t.retarget(0.);
902        assert_eq!(t.value(), 10.);
903        t.advance(0.5, Motion::Full);
904        assert!(t.value() < 10. && t.value() > 0.);
905        assert_eq!(Tween::new(1., 3., f32::NAN, Ease::Linear).value(), 3.);
906        // Splitting time gives the same value as one step.
907        let mut a = Tween::new(0., 1., 1., Ease::ElasticOut);
908        let mut b = a;
909        a.advance(0.6, Motion::Full);
910        for _ in 0..6 {
911            b.advance(0.1, Motion::Full);
912        }
913        assert!((a.value() - b.value()).abs() < 1e-5);
914    }
915
916    #[test]
917    fn springs_converge_split_steps_and_respect_damping() {
918        for damping in [0.2, 0.5, 1.0, 2.5] {
919            let mut a = Spring::new(0., 3., damping);
920            a.set_target(1.);
921            let mut b = a;
922            let mut peak: f32 = 0.;
923            for _ in 0..600 {
924                peak = peak.max(a.advance(1. / 120., Motion::Full));
925            }
926            for _ in 0..300 {
927                b.advance(1. / 60., Motion::Full);
928            }
929            assert!(a.is_settled(1e-3), "{damping}: {a:?}");
930            assert!((a.value - b.value).abs() < 1e-4);
931            if damping >= 1. {
932                assert!(peak <= 1. + 1e-5, "{damping} overshoots {peak}");
933            } else {
934                assert!(peak > 1.01, "{damping} should overshoot");
935            }
936        }
937        let mut s = Spring::critical(0., 2.);
938        s.set_target(5.);
939        assert_eq!(s.advance(1., Motion::Reduced), 5.);
940        s.impulse(f32::NAN);
941        s.advance(1e30, Motion::Full);
942        assert!(s.value.is_finite());
943    }
944
945    #[test]
946    fn entrance_roll_and_screen_transition_edges() {
947        let e = Entrance::pop(0.8);
948        let a = e.sample(0., 0, Motion::Full);
949        assert_eq!((a.alpha, a.scale), (0., 0.8));
950        assert_eq!(
951            e.sample(e.total_duration(4), 3, Motion::Full),
952            Appearance::SHOWN
953        );
954        assert_eq!(e.sample(f32::NAN, 0, Motion::Full).alpha, 0.);
955
956        let mut r = RollCounter::new(100);
957        r.set_target(40);
958        let mut prev = 100;
959        while r.is_rolling() {
960            let v = r.advance(1. / 60., Motion::Full);
961            assert!(v <= prev && v >= 40);
962            prev = v;
963        }
964        assert_eq!(r.shown(), 40);
965        let mut big = RollCounter::new(0);
966        big.set_target(1_000_000_000);
967        let mut frames = 0;
968        while big.is_rolling() {
969            big.advance(1. / 60., Motion::Full);
970            frames += 1;
971        }
972        assert!(frames < 120, "{frames}");
973
974        let mut t = ScreenTransition::new(TransitionKind::Wipe { direction: 0. }, 0.5);
975        assert_eq!(t.advance(1., Motion::Full), None);
976        t.cover();
977        t.advance(0.25, Motion::Full);
978        let half = t.coverage();
979        assert!(half > 0. && half < 1.);
980        t.reveal(); // reverse mid-way from the same coverage
981        assert!((t.coverage() - half).abs() < 1e-5);
982        assert_eq!(
983            t.advance(0.3, Motion::Full),
984            Some(TransitionEvent::Revealed)
985        );
986        t.cover();
987        assert_eq!(
988            t.advance(0.25, Motion::Reduced),
989            Some(TransitionEvent::Covered)
990        );
991        assert_eq!(t.coverage(), 1.);
992    }
993}