mgui-core 0.4.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
//! 动画系统 —— 原 mgui-animation crate,已合入 mgui-core
//!
//! 分层:
//! - **core(本模块)**: 纯逻辑的 `AnimationController` — 时间驱动、无时钟、
//!   无副作用。app/runtime 提供 `now_ms`(winit 事件循环 / AboutToWait),
//!   每帧调 `tick(now_ms)` 拿插值,写进 `Signal` 后由响应式系统触发 rebuild。
//! - **runtime/app**: 持有 controller,在 `AboutToWait` 里 tick →
//!   `Signal::set` → request_redraw(见 showcase 的自动旋转演示)。
//!
//! 设计取舍:
//! - **不引入独立 Ticker trait** — winit 的 redraw 循环就是天然的 ticker,
//!   controller 的 `is_animating()` 决定是否继续请求下一帧。
//! - **状态机不依赖外部时钟源** — `forward(now_ms)` 记录起始时刻,
//!   `tick(now_ms)` 按时间差推进,暂停/恢复语义清晰。
//! - **曲线纯函数** — `Curve::transform(t)` 可独立单测。

use std::fmt::Debug;

/// 缓动曲线(输入输出均为 0..1)
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Curve {
    /// 匀速
    #[default]
    Linear,
    /// 先慢后快(二次)
    EaseIn,
    /// 先快后慢(二次)
    EaseOut,
    /// 慢-快-慢(平滑对称,3t²-2t³)
    EaseInOut,
}

impl Curve {
    /// 把线性进度 t(0..1)映射为缓动后进度(0..1)
    ///
    /// 输入会被 clamp 到 0..1,输出天然落在 0..1。
    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 {
    /// 播一次就停(status → Completed)
    #[default]
    None,
    /// 到头后从头再来(循环)
    Loop,
    /// 到头后反向播放(0→1→0→1…,适合呼吸/摆动效果)
    PingPong,
}

/// `tick()` 的推进结果
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TickOutcome {
    /// 产生新插值(controller 已按 now_ms 推进)
    Value(f32),
    /// 本轮(含重复)播放完成,不再产生新值
    Finished,
    /// 未在播放(Dismissed / Completed),无值
    Idle,
}

/// 时间驱动的动画控制器
///
/// 纯逻辑:不持有时钟、不触发副作用。典型用法(runtime 侧):
///
/// ```ignore
/// let mut ctrl = AnimationController::new(3000)
///     .with_curve(Curve::EaseInOut)
///     .with_repeat(Repeat::Loop);
/// ctrl.forward(now_ms());
/// // 每帧:
/// if let TickOutcome::Value(t) = ctrl.tick(now_ms()) {
///     hue.set(t);           // 响应式 → rebuild → 重画
///     window.request_redraw();
/// }
/// ```
///
/// `value(now_ms)` 是无状态查询(不推进 status),适合 hit_test / 立即绘制。
///
/// 内部用 **锚点模型**:`anchor_ms` 时刻的线性进度为 `anchor_progress`,
/// 之后按播放方向推进。forward/reverse 可在任意时刻无缝切换
/// (切换即重新锚定到当前进度),不依赖可回退的时钟。
pub struct AnimationController {
    duration_ms: u64,
    curve: Curve,
    repeat: Repeat,
    status: AnimationStatus,
    /// 锚点时刻(ms):此刻的线性进度 = anchor_progress
    anchor_ms: u64,
    /// 锚点进度(正向语义 0..1)
    anchor_progress: f32,
    /// status 转换时的回调(可选,fire at every Forward/Reverse/Completed/Dismissed 切换)
    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
    }

    /// 私有:统一 status 赋值入口。每次转换都 fire callback。
    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
    }

    /// 是否在播放(AboutToWait 里决定要不要 request_redraw)
    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
    }

    /// 从当前进度正向播放(Dismissed/Completed → 从 0 重新开始)
    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);
    }

    /// 从当前进度反向播放(Dismissed → 立即结束;Completed → 从 1 往回)
    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);
    }

    /// 立即停止;tick 之后返回 Idle(value 冻结在当前端点语义)
    pub fn stop(&mut self) {
        self.set_status(match self.status {
            AnimationStatus::Completed => AnimationStatus::Completed,
            _ => AnimationStatus::Dismissed,
        });
    }

    /// 把锚点移到 now_ms,进度取当前原始进度(无缝换向的关键)
    fn reanchor(&mut self, now_ms: u64) {
        let p = self.raw_progress(now_ms);
        // Repeat::None 的值域语义是 [0,1](linear_progress/value 均钳制);
        // 若调用方未逐帧 tick,raw 会 overshoot(如 forward 后长时间未 tick),
        // 不钳制会导致换向后的播放时长被放大(反向从 2.5 回到 0)。
        // Loop/PingPong 保留原始进度以维持相位连续。
        self.anchor_progress = if self.repeat == Repeat::None { p.clamp(0.0, 1.0) } else { p };
        self.anchor_ms = now_ms;
    }

    /// 无状态查询当前插值(0..1,已过曲线;不播放时返回端点值)
    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)
    }

    /// 推进状态机到 now_ms,返回本轮结果。
    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 => {
                // rem_euclid:Reverse 时 loop_phase 为负,fract() 也返回负数,
                // 会被 curve.transform 的 clamp 吞成 0(反向循环永远停在起点)。
                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)))
            }
        }
    }

    /// 循环模式的无界相位(轮数可 >1;Reverse 为负方向)
    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,
        }
    }

    /// 原始线性进度(有符号;Reverse 时随时间递减)
    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)
    }
}

// =================================================================
// State 集成帮助:tick_animation(可选,一行代码让 State 自动推进)
// =================================================================
//
// 框架已经在 `ElementTree::tick_states(root, now_ms)` 每帧调每个 State 的
// `state.tick(now_ms)`,所以 State 里持有的 AnimationController 可以直接
// 在 tick 里被推进。
//
// 用法示例:State 持有 controller + Signal
// ```ignore
// fn tick(&mut self, now_ms: u64) {
//     tick_animation(&mut self.controller, now_ms, |t| { self.value.set(t); });
// }
// fn is_animating(&self) -> bool { self.controller.is_animating() }
// ```
//
// `tick_animation` 同时返回 `controller.is_animating()`,方便 `is_animating()`
// 实现直接 return:
// ```ignore
// fn tick(&mut self, now_ms: u64) -> bool {
//     tick_animation(&mut self.controller, now_ms, |t| { self.value.set(t); })
// }
// ```

/// 对一个 `AnimationController` 调 `tick(now_ms)`,
/// 若产生 `Value(t)` 则把 t 传给 `on_value` 闭包(通常写 Signal)。
///
/// 返回值:`controller.is_animating()`(方便 `is_animating()` 实现直接 return)
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::*;

    /// Reverse + Loop:phase 变负时必须回绕(此前 fract() 负值被 clamp 成 0)
    #[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);
        // anchor_progress=0.5,1200ms 时 phase = 0.5 - 0.7 = -0.2 → 0.8
        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);
        // phase = -0.2 → rem_euclid(2) = 1.8 → 2-1.8 = 0.2
        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:?}"),
        }
    }
}