use std::fmt::Debug;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Curve {
#[default]
Linear,
EaseIn,
EaseOut,
EaseInOut,
}
impl Curve {
pub fn transform(&self, t: f32) -> f32 {
let t = t.clamp(0.0, 1.0);
match self {
Curve::Linear => t,
Curve::EaseIn => t * t,
Curve::EaseOut => 1.0 - (1.0 - t) * (1.0 - t),
Curve::EaseInOut => t * t * (3.0 - 2.0 * t),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AnimationStatus {
Dismissed,
Forward,
Reverse,
Completed,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Repeat {
#[default]
None,
Loop,
PingPong,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TickOutcome {
Value(f32),
Finished,
Idle,
}
pub struct AnimationController {
duration_ms: u64,
curve: Curve,
repeat: Repeat,
status: AnimationStatus,
anchor_ms: u64,
anchor_progress: f32,
on_status_changed: Option<Box<dyn FnMut(AnimationStatus)>>,
}
impl std::fmt::Debug for AnimationController {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AnimationController")
.field("duration_ms", &self.duration_ms)
.field("curve", &self.curve)
.field("repeat", &self.repeat)
.field("status", &self.status)
.field("anchor_ms", &self.anchor_ms)
.field("anchor_progress", &self.anchor_progress)
.field("has_callback", &self.on_status_changed.is_some())
.finish()
}
}
impl AnimationController {
pub fn new(duration_ms: u64) -> Self {
Self {
duration_ms: duration_ms.max(1),
curve: Curve::default(),
repeat: Repeat::default(),
status: AnimationStatus::Dismissed,
anchor_ms: 0,
anchor_progress: 0.0,
on_status_changed: None,
}
}
pub fn with_curve(mut self, curve: Curve) -> Self {
self.curve = curve;
self
}
pub fn with_repeat(mut self, repeat: Repeat) -> Self {
self.repeat = repeat;
self
}
pub fn with_on_status_changed(mut self, cb: impl FnMut(AnimationStatus) + 'static) -> Self {
self.on_status_changed = Some(Box::new(cb));
self
}
fn set_status(&mut self, new_status: AnimationStatus) {
if self.status != new_status {
self.status = new_status;
if let Some(cb) = self.on_status_changed.as_mut() {
cb(new_status);
}
}
}
pub fn status(&self) -> AnimationStatus {
self.status
}
pub fn is_animating(&self) -> bool {
matches!(self.status, AnimationStatus::Forward | AnimationStatus::Reverse)
}
pub fn curve(&self) -> Curve {
self.curve
}
pub fn repeat(&self) -> Repeat {
self.repeat
}
pub fn duration_ms(&self) -> u64 {
self.duration_ms
}
pub fn forward(&mut self, now_ms: u64) {
match self.status {
AnimationStatus::Reverse => self.reanchor(now_ms),
AnimationStatus::Dismissed | AnimationStatus::Completed => {
self.anchor_ms = now_ms;
self.anchor_progress = 0.0;
}
AnimationStatus::Forward => {}
}
self.set_status(AnimationStatus::Forward);
}
pub fn reverse(&mut self, now_ms: u64) {
match self.status {
AnimationStatus::Forward => self.reanchor(now_ms),
AnimationStatus::Completed => {
self.anchor_ms = now_ms;
self.anchor_progress = 1.0;
}
AnimationStatus::Dismissed | AnimationStatus::Reverse => {}
}
self.set_status(AnimationStatus::Reverse);
}
pub fn stop(&mut self) {
self.set_status(match self.status {
AnimationStatus::Completed => AnimationStatus::Completed,
_ => AnimationStatus::Dismissed,
});
}
fn reanchor(&mut self, now_ms: u64) {
let p = self.raw_progress(now_ms);
self.anchor_progress = if self.repeat == Repeat::None { p.clamp(0.0, 1.0) } else { p };
self.anchor_ms = now_ms;
}
pub fn value(&self, now_ms: u64) -> f32 {
if !self.is_animating() {
return match self.status {
AnimationStatus::Completed => 1.0,
_ => 0.0,
};
}
let linear = match self.repeat {
Repeat::None => self.linear_progress(now_ms),
Repeat::Loop => self.loop_phase(now_ms).rem_euclid(1.0),
Repeat::PingPong => {
let phase = self.loop_phase(now_ms).rem_euclid(2.0);
if phase <= 1.0 {
phase
} else {
2.0 - phase
}
}
};
self.curve.transform(linear)
}
pub fn tick(&mut self, now_ms: u64) -> TickOutcome {
if !self.is_animating() {
return TickOutcome::Idle;
}
let progress = self.raw_progress(now_ms);
match self.repeat {
Repeat::None => {
let done = if self.status == AnimationStatus::Forward { progress >= 1.0 } else { progress <= 0.0 };
if done {
let terminal = if self.status == AnimationStatus::Forward {
AnimationStatus::Completed
} else {
AnimationStatus::Dismissed
};
self.set_status(terminal);
TickOutcome::Finished
} else {
TickOutcome::Value(self.curve.transform(progress.clamp(0.0, 1.0)))
}
}
Repeat::Loop => {
let phase = self.loop_phase(now_ms).rem_euclid(1.0);
TickOutcome::Value(self.curve.transform(phase))
}
Repeat::PingPong => {
let phase = self.loop_phase(now_ms).rem_euclid(2.0);
let p = if phase <= 1.0 { phase } else { 2.0 - phase };
TickOutcome::Value(self.curve.transform(p.clamp(0.0, 1.0)))
}
}
}
fn loop_phase(&self, now_ms: u64) -> f32 {
let dt = now_ms.saturating_sub(self.anchor_ms) as f32 / self.duration_ms as f32;
match self.status {
AnimationStatus::Reverse => self.anchor_progress - dt,
_ => self.anchor_progress + dt,
}
}
fn raw_progress(&self, now_ms: u64) -> f32 {
let dt = now_ms.saturating_sub(self.anchor_ms) as f32 / self.duration_ms as f32;
match self.status {
AnimationStatus::Reverse => self.anchor_progress - dt,
AnimationStatus::Forward => self.anchor_progress + dt,
AnimationStatus::Dismissed => 0.0,
AnimationStatus::Completed => 1.0,
}
}
fn linear_progress(&self, now_ms: u64) -> f32 {
self.raw_progress(now_ms).clamp(0.0, 1.0)
}
}
pub fn tick_animation(controller: &mut AnimationController, now_ms: u64, mut on_value: impl FnMut(f32)) -> bool {
if let TickOutcome::Value(t) = controller.tick(now_ms) {
on_value(t);
}
controller.is_animating()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reverse_loop_wraps_negative_phase() {
let mut c = AnimationController::new(1000).with_repeat(Repeat::Loop);
c.forward(0);
c.tick(500);
c.reverse(500);
match c.tick(1200) {
TickOutcome::Value(v) => assert!((v - 0.8).abs() < 1e-4, "phase -0.2 应回绕到 0.8,实际 {v}"),
other => panic!("expected Value, got {other:?}"),
}
assert!((c.value(1200) - 0.8).abs() < 1e-4, "value() 也应回绕");
}
#[test]
fn ping_pong_reverse_wraps() {
let mut c = AnimationController::new(1000).with_repeat(Repeat::PingPong);
c.forward(0);
c.tick(500);
c.reverse(500);
match c.tick(1200) {
TickOutcome::Value(v) => assert!((v - 0.2).abs() < 1e-4, "expected 0.2, got {v}"),
other => panic!("expected Value, got {other:?}"),
}
}
}