#![warn(missing_docs)]
use std::cell::Cell;
#[repr(C, u32)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum EasingCurve {
Linear,
CubicBezier([f32; 4]),
}
impl Default for EasingCurve {
fn default() -> Self {
Self::Linear
}
}
pub struct AnimationDriver {
active_animations: Cell<bool>,
global_instant: core::pin::Pin<Box<crate::Property<instant::Instant>>>,
initial_instant: instant::Instant,
}
impl Default for AnimationDriver {
fn default() -> Self {
AnimationDriver {
active_animations: Cell::default(),
global_instant: Box::pin(crate::Property::new(instant::Instant::now())),
initial_instant: instant::Instant::now(),
}
}
}
impl AnimationDriver {
pub fn update_animations(&self, new_tick: instant::Instant) {
self.active_animations.set(false);
self.global_instant.as_ref().set(new_tick);
}
pub fn has_active_animations(&self) -> bool {
self.active_animations.get()
}
pub fn set_has_active_animations(&self) {
self.active_animations.set(true);
}
pub fn current_tick(&self) -> instant::Instant {
self.global_instant.as_ref().get()
}
}
thread_local!(pub(crate) static CURRENT_ANIMATION_DRIVER : AnimationDriver = AnimationDriver::default());
pub fn current_tick() -> instant::Instant {
CURRENT_ANIMATION_DRIVER.with(|driver| driver.current_tick())
}
pub fn easing_curve(curve: &EasingCurve, value: f32) -> f32 {
match curve {
EasingCurve::Linear => value,
EasingCurve::CubicBezier([a, b, c, d]) => {
if !(0.0..=1.0).contains(a) && !(0.0..=1.0).contains(c) {
return value;
};
let curve = lyon::algorithms::geom::cubic_bezier::CubicBezierSegment {
from: (0., 0.).into(),
ctrl1: (*a, *b).into(),
ctrl2: (*c, *d).into(),
to: (1., 1.).into(),
};
let curve = curve.assume_monotonic();
curve.y(curve.solve_t_for_x(value, 0.0..1.0, 0.01))
}
}
}
pub(crate) fn update_animations() {
CURRENT_ANIMATION_DRIVER.with(|driver| {
match std::env::var("SIXTYFPS_SLOW_ANIMATIONS") {
Err(_) => driver.update_animations(instant::Instant::now()),
Ok(val) => {
let factor = val.parse().unwrap_or(2.);
driver.update_animations(
driver.initial_instant
+ (instant::Instant::now() - driver.initial_instant).div_f32(factor),
)
}
};
});
}