use std::time::{Duration, Instant};
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Easing {
EaseInOut,
EaseIn,
EaseOut,
Linear,
}
impl Easing {
pub fn apply(self, t: f32) -> f32 {
let t = t.clamp(0.0, 1.0);
match self {
Easing::Linear => t,
Easing::EaseIn => t * t * t,
Easing::EaseOut => {
let inv = 1.0 - t;
1.0 - inv * inv * inv
}
Easing::EaseInOut => {
if t < 0.5 {
4.0 * t * t * t
} else {
1.0 - (-2.0 * t + 2.0).powi(3) / 2.0
}
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AnimKind {
FadeIn,
FadeOut,
SlideIn(Edge),
SlideOut(Edge),
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Edge {
Top,
Bottom,
Left,
Right,
}
#[derive(Debug, Clone)]
pub struct Animation {
kind: AnimKind,
easing: Easing,
duration: Duration,
started: Option<Instant>,
progress: f32, }
impl Default for Animation {
fn default() -> Self {
Self {
kind: AnimKind::FadeIn,
easing: Easing::EaseInOut,
duration: Duration::from_millis(500),
started: None,
progress: 0.0,
}
}
}
impl Animation {
pub fn new() -> Self {
Self::default()
}
pub fn start(&mut self, kind: AnimKind, duration: Duration) {
self.kind = kind;
self.duration = duration;
self.started = Some(Instant::now());
self.progress = 0.0;
}
pub fn start_with(&mut self, kind: AnimKind, duration: Duration, easing: Easing) {
self.easing = easing;
self.start(kind, duration);
}
pub fn tick(&mut self, now: Instant) {
if let Some(start) = self.started {
let elapsed = now.duration_since(start);
self.progress = (elapsed.as_secs_f32() / self.duration.as_secs_f32()).min(1.0);
if self.progress >= 1.0 {
self.started = None; }
}
}
pub fn is_running(&self) -> bool {
self.started.is_some()
}
pub fn is_done(&self) -> bool {
self.started.is_none() && self.progress >= 1.0
}
pub fn is_idle(&self) -> bool {
self.started.is_none() && self.progress == 0.0
}
pub fn reset(&mut self) {
self.started = None;
self.progress = 0.0;
}
pub fn linear_progress(&self) -> f32 {
self.progress
}
fn eased(&self) -> f32 {
self.easing.apply(self.progress)
}
pub fn value(&self) -> f32 {
let e = self.eased();
match self.kind {
AnimKind::FadeIn => e,
AnimKind::FadeOut => 1.0 - e,
AnimKind::SlideIn(_) => 1.0 - e,
AnimKind::SlideOut(_) => e,
}
}
pub fn alpha(&self) -> f32 {
match self.kind {
AnimKind::FadeIn | AnimKind::FadeOut => self.value(),
_ => 1.0,
}
}
pub fn offset(&self) -> f32 {
match self.kind {
AnimKind::SlideIn(_) | AnimKind::SlideOut(_) => self.value(),
_ => 0.0,
}
}
pub fn edge(&self) -> Option<Edge> {
match self.kind {
AnimKind::SlideIn(e) | AnimKind::SlideOut(e) => Some(e),
_ => None,
}
}
pub fn slide_padding(&self, distance: f32) -> [f32; 4] {
let px = self.offset() * distance;
match self.edge() {
Some(Edge::Top) => [px, 0.0, 0.0, 0.0],
Some(Edge::Bottom) => [0.0, 0.0, px, 0.0],
Some(Edge::Left) => [0.0, 0.0, 0.0, px],
Some(Edge::Right) => [0.0, px, 0.0, 0.0],
None => [0.0; 4],
}
}
}