use std::any::Any;
use std::cell::{Cell, RefCell};
use std::future::Future;
use std::ops::ControlFlow;
use std::pin::Pin;
use std::rc::Rc;
use std::task::{Context, Poll, Waker};
use day_reactive::Signal;
use day_spec::{AnimSample, AnimSpec, Curve};
use crate::frame::{FrameClock, FrameHandle};
use crate::tween::Lerp;
use std::f64::consts::PI;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Ease {
In,
Out,
InOut,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Easing {
Linear,
Bezier(f64, f64, f64, f64),
Power(Ease, f64),
Sine(Ease),
Circle(Ease),
Exponential(Ease),
Back(Ease, f64),
ElasticOut(f64),
BounceOut,
}
impl Easing {
pub const EASE: Easing = Easing::Bezier(0.25, 0.1, 0.25, 1.0);
pub const EASE_IN_OUT: Easing = Easing::Bezier(0.42, 0.0, 0.58, 1.0);
#[must_use]
pub fn value(self, t: f64) -> f64 {
let t = t.clamp(0.0, 1.0);
match self {
Easing::Linear => t,
Easing::Bezier(x1, y1, x2, y2) => bezier(t, x1, y1, x2, y2),
Easing::Power(ease, power) => shaped(ease, t, |t| t.powf(power)),
Easing::Sine(ease) => shaped(ease, t, |t| 1.0 - (t * PI / 2.0).cos()),
Easing::Circle(ease) => shaped(ease, t, |t| 1.0 - (1.0 - t * t).max(0.0).sqrt()),
Easing::Exponential(ease) => shaped(ease, t, |t| {
if t <= 0.0 {
0.0
} else {
2f64.powf(10.0 * (t - 1.0))
}
}),
Easing::Back(ease, overshoot) => {
shaped(ease, t, |t| t * t * ((overshoot + 1.0) * t - overshoot))
}
Easing::ElasticOut(bounciness) => {
if t <= 0.0 || t >= 1.0 {
t
} else {
let p = bounciness.max(0.01) * PI;
1.0 - (t * PI / 2.0).cos().powi(3) * (t * p).cos()
}
}
Easing::BounceOut => bounce(t),
}
}
#[must_use]
pub fn samples(self, count: usize) -> Vec<f64> {
let last = count.saturating_sub(1).max(1) as f64;
(0..count).map(|i| self.value(i as f64 / last)).collect()
}
}
fn shaped(ease: Ease, t: f64, ease_in: impl Fn(f64) -> f64) -> f64 {
match ease {
Ease::In => ease_in(t),
Ease::Out => 1.0 - ease_in(1.0 - t),
Ease::InOut => {
if t < 0.5 {
ease_in(t * 2.0) / 2.0
} else {
1.0 - ease_in((1.0 - t) * 2.0) / 2.0
}
}
}
}
fn bounce(t: f64) -> f64 {
const N: f64 = 7.5625;
const D: f64 = 2.75;
if t < 1.0 / D {
N * t * t
} else if t < 2.0 / D {
let t = t - 1.5 / D;
N * t * t + 0.75
} else if t < 2.5 / D {
let t = t - 2.25 / D;
N * t * t + 0.9375
} else {
let t = t - 2.625 / D;
N * t * t + 0.984_375
}
}
fn bezier(x: f64, x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
let axis = |t: f64, a: f64, b: f64| {
let u = 1.0 - t;
3.0 * u * u * t * a + 3.0 * u * t * t * b + t * t * t
};
let slope = |t: f64, a: f64, b: f64| {
let u = 1.0 - t;
3.0 * u * u * a + 6.0 * u * t * (b - a) + 3.0 * t * t * (1.0 - b)
};
let mut t = x;
for _ in 0..8 {
let error = axis(t, x1, x2) - x;
if error.abs() < 1e-6 {
return axis(t, y1, y2);
}
let d = slope(t, x1, x2);
if d.abs() < 1e-6 {
break;
}
t = (t - error / d).clamp(0.0, 1.0);
}
let (mut lo, mut hi) = (0.0, 1.0);
t = x;
for _ in 0..24 {
let at = axis(t, x1, x2);
if (at - x).abs() < 1e-6 {
break;
}
if at < x {
lo = t;
} else {
hi = t;
}
t = f64::midpoint(lo, hi);
}
axis(t, y1, y2)
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Spring {
pub stiffness: f64,
pub damping: f64,
pub mass: f64,
}
impl Default for Spring {
fn default() -> Self {
Spring::new(170.0, 26.0)
}
}
impl Spring {
#[must_use]
pub const fn new(stiffness: f64, damping: f64) -> Self {
Spring {
stiffness,
damping,
mass: 1.0,
}
}
#[must_use]
pub const fn mass(mut self, mass: f64) -> Self {
self.mass = mass;
self
}
#[must_use]
pub fn from_response(response: f64, ratio: f64) -> Self {
let (stiffness, damping) = Curve::Spring {
response,
damping: ratio,
}
.spring_constants()
.unwrap_or((170.0, 26.0));
Spring::new(stiffness, damping)
}
#[must_use]
pub fn curve(self) -> Curve {
let mass = self.mass.max(1e-6);
let omega0 = (self.stiffness.max(0.0) / mass).sqrt().max(1e-6);
Curve::Spring {
response: std::f64::consts::TAU / omega0,
damping: self.damping / (2.0 * mass * omega0),
}
}
pub fn step(self, state: &mut SpringState, target: f64, dt: f64) {
let mut left = dt.clamp(0.0, 0.25);
let mass = self.mass.max(1e-6);
while left > 0.0 {
let h = left.min(0.001);
let force = -self.stiffness * (state.value - target) - self.damping * state.velocity;
state.velocity += force / mass * h;
state.value += state.velocity * h;
left -= h;
}
}
#[must_use]
pub fn settled(self, state: SpringState, target: f64) -> bool {
(state.value - target).abs() < 0.01 && state.velocity.abs() < 0.01
}
#[must_use]
pub fn response(self, seconds: f64, count: usize) -> Vec<f64> {
let mut state = SpringState::default();
let dt = seconds / count.saturating_sub(1).max(1) as f64;
(0..count)
.map(|i| {
if i > 0 {
self.step(&mut state, 1.0, dt);
}
state.value
})
.collect()
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct SpringState {
pub value: f64,
pub velocity: f64,
}
impl SpringState {
#[must_use]
pub const fn at(value: f64) -> Self {
SpringState {
value,
velocity: 0.0,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Decay {
pub rate: f64,
}
impl Decay {
pub fn step(self, state: &mut SpringState, dt: f64) {
let ms = (dt * 1000.0).clamp(0.0, 250.0);
let rate = self.rate.clamp(0.0, 0.999_999);
let k = rate.ln();
let factor = rate.powf(ms);
state.value += state.velocity * (factor - 1.0) / k / 1000.0;
state.velocity *= factor;
}
#[must_use]
pub fn stopped(self, state: SpringState) -> bool {
state.velocity.abs() < 1.0
}
#[must_use]
pub fn rest(self, state: SpringState) -> f64 {
let k = self.rate.clamp(0.0, 0.999_999).ln();
state.value - state.velocity / k / 1000.0
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Interpolation<T: Lerp> {
first: (f64, T),
rest: Vec<(f64, T)>,
extend_start: bool,
extend_end: bool,
}
impl<T: Lerp> Interpolation<T> {
#[must_use]
pub fn new<const N: usize>(input: [f64; N], output: [T; N]) -> Self {
const { assert!(N >= 1, "an interpolation needs at least one stop") };
let mut stops = input.into_iter().zip(output);
let Some(first) = stops.next() else {
unreachable!("N >= 1 is asserted at compile time")
};
Interpolation {
first,
rest: stops.collect(),
extend_start: false,
extend_end: false,
}
}
#[must_use]
pub fn extend(mut self) -> Self {
self.extend_start = true;
self.extend_end = true;
self
}
#[must_use]
pub fn extend_start(mut self) -> Self {
self.extend_start = true;
self
}
#[must_use]
pub fn extend_end(mut self) -> Self {
self.extend_end = true;
self
}
#[must_use]
pub fn at(&self, x: f64) -> T {
let mut lo = &self.first;
let Some(mut hi) = self.rest.first() else {
return lo.1.clone();
};
if x < lo.0 && !self.extend_start {
return lo.1.clone();
}
for stop in self.rest.iter().skip(1) {
if x <= hi.0 {
break;
}
lo = hi;
hi = stop;
}
if x > hi.0 && !self.extend_end {
return hi.1.clone();
}
let span = hi.0 - lo.0;
if span <= 0.0 {
return if x < lo.0 { lo.1.clone() } else { hi.1.clone() };
}
lo.1.lerp(&hi.1, (x - lo.0) / span)
}
}
struct Slot<T> {
target: T,
claim: u64,
flight: Option<Playing>,
clock: FrameClock,
}
pub struct Animated<T: Lerp + 'static = f64> {
value: Signal<T>,
velocity: Signal<f64>,
moving: Signal<bool>,
slot: Signal<Slot<T>>,
}
#[expect(
clippy::expl_impl_clone_on_copy,
reason = "a derive would demand `T: Copy`, and the handle is `Copy` whatever it holds"
)]
impl<T: Lerp + 'static> Clone for Animated<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T: Lerp + 'static> Copy for Animated<T> {}
impl<T: Lerp + std::fmt::Debug + 'static> std::fmt::Debug for Animated<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Animated")
.field("value", &self.try_now())
.finish_non_exhaustive()
}
}
impl<T: Lerp + 'static> Animated<T> {
#[must_use]
pub fn new(initial: T) -> Self {
Self::on(FrameClock::current(), initial)
}
#[must_use]
pub fn on(clock: FrameClock, initial: T) -> Self {
Animated {
value: Signal::new(initial.clone()),
velocity: Signal::new(0.0),
moving: Signal::new(false),
slot: Signal::new(Slot {
target: initial,
claim: 0,
flight: None,
clock,
}),
}
}
#[must_use]
pub fn get(self) -> T {
self.value.get()
}
#[must_use]
pub fn get_untracked(self) -> T {
self.value.get_untracked()
}
#[must_use]
pub fn target(self) -> T {
self.slot.with_untracked(|slot| slot.target.clone())
}
#[must_use]
pub fn is_animating(self) -> bool {
self.moving.get()
}
pub fn set(self, value: T) {
self.claim(Some(value.clone()));
if let Some(flight) = self.take_flight() {
flight.stop();
}
self.value.set(value);
self.velocity.set_if_changed(0.0);
self.moving.set_if_changed(false);
}
pub fn animate_to(self, target: T, spec: AnimSpec) -> Playing {
if let Some(flight) = self.take_flight() {
flight.stop();
}
let playing = Animation::tween(self, target, spec).start();
if !playing.is_finished() {
let flight = playing.clone();
self.slot.update(|slot| slot.flight = Some(flight));
}
playing
}
pub fn interpolate<U: Lerp + 'static, const N: usize>(
self,
input: [f64; N],
output: [U; N],
) -> impl Fn() -> U + Clone + 'static
where
T: Into<f64>,
{
self.interpolate_with(Interpolation::new(input, output))
}
pub fn interpolate_with<U: Lerp + 'static>(
self,
map: Interpolation<U>,
) -> impl Fn() -> U + Clone + 'static
where
T: Into<f64>,
{
let map = Rc::new(map);
move || map.at(self.get().into())
}
fn try_now(self) -> Option<T> {
day_reactive::untrack(|| self.value.try_get())
}
fn claim(self, target: Option<T>) -> u64 {
let mut claim = 0;
self.slot.update(|slot| {
slot.claim += 1;
if let Some(target) = target {
slot.target = target;
}
claim = slot.claim;
});
claim
}
fn take_flight(self) -> Option<Playing> {
let mut flight = None;
self.slot.update(|slot| flight = slot.flight.take());
flight
}
fn clock(self) -> Option<FrameClock> {
day_reactive::untrack(|| self.slot.try_with(|slot| slot.clock))
}
}
impl Animated<f64> {
#[must_use]
pub fn velocity(self) -> f64 {
self.velocity.get()
}
pub fn set_velocity(self, velocity: f64) {
self.velocity.set(velocity);
}
}
struct Hold<T: Lerp + 'static> {
value: Animated<T>,
claim: u64,
}
impl<T: Lerp + 'static> Hold<T> {
fn take(value: Animated<T>, target: Option<T>) -> Option<(Self, T)> {
let from = value.try_now()?;
let claim = value.claim(target);
value.moving.set_if_changed(true);
Some((Hold { value, claim }, from))
}
fn owns(&self) -> Option<bool> {
day_reactive::untrack(|| self.value.slot.try_with(|slot| slot.claim == self.claim))
}
fn write(&self, next: T, dt: f64) {
if dt > 0.0
&& let Some(next) = (&next as &dyn Any).downcast_ref::<f64>()
&& let Some(prev) = self
.value
.try_now()
.as_ref()
.and_then(|p| (p as &dyn Any).downcast_ref::<f64>().copied())
{
self.value.velocity.set((next - prev) / dt);
}
self.value.value.set(next);
}
fn land(&self, end: T) {
self.value.value.set(end);
self.value.velocity.set_if_changed(0.0);
self.release();
}
fn release(&self) {
if self.owns() == Some(true) {
self.value.moving.set_if_changed(false);
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Flow {
Running,
Ended(f64),
Gone,
}
trait Leaf {
fn begin(&self) -> Option<Box<dyn LeafRun>>;
fn finish(&self);
fn endless(&self) -> bool {
false
}
fn snapshot(&self) -> Option<Box<dyn Fn()>> {
None
}
fn clock(&self) -> Option<FrameClock> {
None
}
}
trait LeafRun {
fn advance(&mut self, dt: f64) -> Flow;
fn release(&self);
}
fn snapshot_of<T: Lerp + 'static>(value: Animated<T>) -> Option<Box<dyn Fn()>> {
let at = value.try_now()?;
let velocity = day_reactive::untrack(|| value.velocity.try_get())?;
Some(Box::new(move || {
value.set(at.clone());
value.velocity.set_if_changed(velocity);
}))
}
struct TimingLeaf<T: Lerp + 'static> {
value: Animated<T>,
to: T,
secs: f64,
easing: Easing,
}
impl<T: Lerp + 'static> Leaf for TimingLeaf<T> {
fn begin(&self) -> Option<Box<dyn LeafRun>> {
let (hold, from) = Hold::take(self.value, Some(self.to.clone()))?;
Some(Box::new(TimingRun {
hold,
from,
to: self.to.clone(),
secs: self.secs,
easing: self.easing,
elapsed: 0.0,
}))
}
fn finish(&self) {
self.value.set(self.to.clone());
}
fn snapshot(&self) -> Option<Box<dyn Fn()>> {
snapshot_of(self.value)
}
fn clock(&self) -> Option<FrameClock> {
self.value.clock()
}
}
struct TimingRun<T: Lerp + 'static> {
hold: Hold<T>,
from: T,
to: T,
secs: f64,
easing: Easing,
elapsed: f64,
}
impl<T: Lerp + 'static> LeafRun for TimingRun<T> {
fn advance(&mut self, dt: f64) -> Flow {
self.elapsed += dt;
let left = self.elapsed - self.secs;
match self.hold.owns() {
None => Flow::Gone,
Some(false) if left >= 0.0 => Flow::Ended(left.min(dt)),
Some(false) => Flow::Running,
Some(true) if left >= 0.0 => {
self.hold.land(self.to.clone());
Flow::Ended(left.min(dt))
}
Some(true) => {
let t = self.easing.value(self.elapsed / self.secs);
self.hold.write(self.from.lerp(&self.to, t), dt);
Flow::Running
}
}
}
fn release(&self) {
self.hold.release();
}
}
struct TweenLeaf<T: Lerp + 'static> {
value: Animated<T>,
to: T,
spec: AnimSpec,
}
impl<T: Lerp + 'static> Leaf for TweenLeaf<T> {
fn begin(&self) -> Option<Box<dyn LeafRun>> {
let (hold, from) = Hold::take(self.value, Some(self.to.clone()))?;
Some(Box::new(TweenRun {
hold,
from,
to: self.to.clone(),
spec: self.spec,
elapsed: 0.0,
}))
}
fn finish(&self) {
self.value.set(self.to.clone());
}
fn endless(&self) -> bool {
self.spec.repeats_forever()
}
fn snapshot(&self) -> Option<Box<dyn Fn()>> {
snapshot_of(self.value)
}
fn clock(&self) -> Option<FrameClock> {
self.value.clock()
}
}
struct TweenRun<T: Lerp + 'static> {
hold: Hold<T>,
from: T,
to: T,
spec: AnimSpec,
elapsed: f64,
}
impl<T: Lerp + 'static> LeafRun for TweenRun<T> {
fn advance(&mut self, dt: f64) -> Flow {
self.elapsed += dt;
let sample = self.spec.sample(self.elapsed);
let left = self
.spec
.total_secs()
.map_or(0.0, |total| (self.elapsed - total).clamp(0.0, dt));
match self.hold.owns() {
None => Flow::Gone,
Some(false) if sample.done => Flow::Ended(left),
Some(false) => Flow::Running,
Some(true) if sample.done => {
self.hold.land(self.to.clone());
Flow::Ended(left)
}
Some(true) => {
self.hold
.write(self.from.lerp(&self.to, sample.progress), dt);
Flow::Running
}
}
}
fn release(&self) {
self.hold.release();
}
}
struct SpringLeaf {
value: Animated<f64>,
to: f64,
spring: Spring,
}
impl Leaf for SpringLeaf {
fn begin(&self) -> Option<Box<dyn LeafRun>> {
let (hold, from) = Hold::take(self.value, Some(self.to))?;
let velocity = day_reactive::untrack(|| self.value.velocity.try_get())?;
let mass = self.spring.mass.max(1e-6);
let omega0 = (self.spring.stiffness.max(1e-6) / mass).sqrt();
let reach = (self.to - from).abs().max(velocity.abs() / omega0);
Some(Box::new(SpringRun {
hold,
to: self.to,
spring: self.spring,
rest: (reach * 1e-3).max(f64::EPSILON),
rest_speed: (reach * omega0 * 1e-3).max(f64::EPSILON),
}))
}
fn finish(&self) {
self.value.set(self.to);
}
fn snapshot(&self) -> Option<Box<dyn Fn()>> {
snapshot_of(self.value)
}
fn clock(&self) -> Option<FrameClock> {
self.value.clock()
}
}
struct SpringRun {
hold: Hold<f64>,
to: f64,
spring: Spring,
rest: f64,
rest_speed: f64,
}
impl LeafRun for SpringRun {
fn advance(&mut self, dt: f64) -> Flow {
match self.hold.owns() {
None => return Flow::Gone,
Some(false) => return Flow::Ended(0.0),
Some(true) => {}
}
let value = self.hold.value;
let (Some(at), Some(velocity)) = (
value.try_now(),
day_reactive::untrack(|| value.velocity.try_get()),
) else {
return Flow::Gone;
};
let mut state = SpringState {
value: at,
velocity,
};
self.spring.step(&mut state, self.to, dt);
if (state.value - self.to).abs() < self.rest && state.velocity.abs() < self.rest_speed {
self.hold.land(self.to);
return Flow::Ended(0.0);
}
value.value.set(state.value);
value.velocity.set(state.velocity);
Flow::Running
}
fn release(&self) {
self.hold.release();
}
}
struct DecayLeaf {
value: Animated<f64>,
decay: Decay,
}
impl DecayLeaf {
fn state(&self) -> Option<SpringState> {
Some(SpringState {
value: self.value.try_now()?,
velocity: day_reactive::untrack(|| self.value.velocity.try_get())?,
})
}
}
impl Leaf for DecayLeaf {
fn begin(&self) -> Option<Box<dyn LeafRun>> {
let (hold, _) = Hold::take(self.value, self.state().map(|s| self.decay.rest(s)))?;
Some(Box::new(DecayRun {
hold,
decay: self.decay,
}))
}
fn finish(&self) {
if let Some(state) = self.state() {
self.value.set(self.decay.rest(state));
}
}
fn snapshot(&self) -> Option<Box<dyn Fn()>> {
snapshot_of(self.value)
}
fn clock(&self) -> Option<FrameClock> {
self.value.clock()
}
}
struct DecayRun {
hold: Hold<f64>,
decay: Decay,
}
impl LeafRun for DecayRun {
fn advance(&mut self, dt: f64) -> Flow {
match self.hold.owns() {
None => return Flow::Gone,
Some(false) => return Flow::Ended(0.0),
Some(true) => {}
}
let value = self.hold.value;
let (Some(at), Some(velocity)) = (
value.try_now(),
day_reactive::untrack(|| value.velocity.try_get()),
) else {
return Flow::Gone;
};
let mut state = SpringState {
value: at,
velocity,
};
self.decay.step(&mut state, dt);
if self.decay.stopped(state) {
self.hold.land(state.value);
return Flow::Ended(0.0);
}
value.value.set(state.value);
value.velocity.set(state.velocity);
Flow::Running
}
fn release(&self) {
self.hold.release();
}
}
struct DriveLeaf {
spec: AnimSpec,
step: Rc<RefCell<dyn FnMut(AnimSample)>>,
}
impl DriveLeaf {
fn call(step: &Rc<RefCell<dyn FnMut(AnimSample)>>, sample: AnimSample) {
if let Ok(mut step) = step.try_borrow_mut() {
step(sample);
}
}
}
impl Leaf for DriveLeaf {
fn begin(&self) -> Option<Box<dyn LeafRun>> {
Some(Box::new(DriveRun {
spec: self.spec,
step: self.step.clone(),
elapsed: 0.0,
}))
}
fn finish(&self) {
let end = self.spec.total_secs().unwrap_or(0.0);
Self::call(
&self.step,
AnimSample {
done: true,
..self.spec.sample(end)
},
);
}
fn endless(&self) -> bool {
self.spec.repeats_forever()
}
}
struct DriveRun {
spec: AnimSpec,
step: Rc<RefCell<dyn FnMut(AnimSample)>>,
elapsed: f64,
}
impl LeafRun for DriveRun {
fn advance(&mut self, dt: f64) -> Flow {
self.elapsed += dt;
let sample = self.spec.sample(self.elapsed);
DriveLeaf::call(&self.step, sample);
if sample.done {
let total = self.spec.total_secs().unwrap_or(self.elapsed);
Flow::Ended((self.elapsed - total).clamp(0.0, dt))
} else {
Flow::Running
}
}
fn release(&self) {}
}
#[derive(Clone)]
enum Node {
Leaf(Rc<dyn Leaf>),
Delay(f64),
Sequence(Vec<Node>),
Parallel(Vec<Node>),
Repeat(Box<Node>, Option<u32>),
}
impl Node {
fn endless(&self) -> bool {
match self {
Node::Leaf(leaf) => leaf.endless(),
Node::Delay(_) | Node::Repeat(_, Some(0)) => false,
Node::Sequence(parts) | Node::Parallel(parts) => parts.iter().any(Node::endless),
Node::Repeat(part, times) => times.is_none() || part.endless(),
}
}
fn finish(&self) {
match self {
Node::Leaf(leaf) => leaf.finish(),
Node::Delay(_) | Node::Repeat(_, Some(0)) => {}
Node::Sequence(parts) | Node::Parallel(parts) => parts.iter().for_each(Node::finish),
Node::Repeat(part, _) => part.finish(),
}
}
fn leaves(&self, visit: &mut dyn FnMut(&dyn Leaf)) {
match self {
Node::Leaf(leaf) => visit(leaf.as_ref()),
Node::Delay(_) => {}
Node::Sequence(parts) | Node::Parallel(parts) => {
for part in parts {
part.leaves(visit);
}
}
Node::Repeat(part, _) => part.leaves(visit),
}
}
fn begin(&self) -> Option<Run> {
Some(match self {
Node::Leaf(leaf) => Run::Leaf(leaf.begin()?),
Node::Delay(secs) => Run::Delay(*secs),
Node::Sequence(parts) => Run::Sequence {
parts: parts.clone(),
at: 0,
current: match parts.first() {
Some(first) => Some(Box::new(first.begin()?)),
None => None,
},
},
Node::Parallel(parts) => {
let mut runs = Vec::with_capacity(parts.len());
for part in parts {
let Some(run) = part.begin() else {
for (run, _) in &runs {
Run::release(run);
}
return None;
};
runs.push((run, false));
}
Run::Parallel(runs)
}
Node::Repeat(_, Some(0)) => Run::Delay(0.0),
Node::Repeat(part, times) => Run::Repeat {
part: (**part).clone(),
times: *times,
done: 0,
current: Box::new(part.begin()?),
},
})
}
}
const INSTANT_PASSES_PER_FRAME: u32 = 64;
enum Run {
Leaf(Box<dyn LeafRun>),
Delay(f64),
Sequence {
parts: Vec<Node>,
at: usize,
current: Option<Box<Run>>,
},
Parallel(Vec<(Run, bool)>),
Repeat {
part: Node,
times: Option<u32>,
done: u32,
current: Box<Run>,
},
}
impl Run {
fn advance(&mut self, dt: f64) -> Flow {
match self {
Run::Leaf(run) => run.advance(dt),
Run::Delay(left) => {
*left -= dt;
if *left <= 0.0 {
Flow::Ended((-*left).min(dt))
} else {
Flow::Running
}
}
Run::Sequence { parts, at, current } => {
let mut dt = dt;
loop {
let Some(run) = current else {
return Flow::Ended(dt);
};
match run.advance(dt) {
Flow::Ended(left) => dt = left,
flow => return flow,
}
*at += 1;
*current = match parts.get(*at) {
Some(next) => match next.begin() {
Some(run) => Some(Box::new(run)),
None => return Flow::Gone,
},
None => None,
};
}
}
Run::Parallel(runs) => {
let mut left = dt;
for (run, ended) in runs.iter_mut().filter(|(_, ended)| !*ended) {
match run.advance(dt) {
Flow::Running => {}
Flow::Ended(unused) => {
*ended = true;
left = left.min(unused);
}
Flow::Gone => return Flow::Gone,
}
}
if runs.iter().all(|(_, ended)| *ended) {
Flow::Ended(left)
} else {
Flow::Running
}
}
Run::Repeat {
part,
times,
done,
current,
} => {
let mut dt = dt;
let mut instant = 0;
loop {
let before = dt;
match current.advance(dt) {
Flow::Ended(left) => {
*done = done.saturating_add(1);
if times.is_some_and(|times| *done >= times) {
return Flow::Ended(left);
}
match part.begin() {
Some(run) => **current = run,
None => return Flow::Gone,
}
if left <= 0.0 {
return Flow::Running;
}
if left < before || times.is_some() {
instant = 0;
} else {
instant += 1;
if instant >= INSTANT_PASSES_PER_FRAME {
return Flow::Running;
}
}
dt = left;
}
flow => return flow,
}
}
}
}
}
fn release(&self) {
match self {
Run::Leaf(run) => run.release(),
Run::Delay(_) => {}
Run::Sequence { current, .. } => {
if let Some(run) = current {
run.release();
}
}
Run::Parallel(runs) => runs
.iter()
.filter(|(_, ended)| !*ended)
.for_each(|(run, _)| run.release()),
Run::Repeat { current, .. } => current.release(),
}
}
}
#[derive(Clone)]
#[must_use = "an animation does nothing until it is started"]
pub struct Animation {
node: Node,
}
impl Animation {
pub fn timing<T: Lerp + 'static>(value: Animated<T>, to: T, ms: u32, easing: Easing) -> Self {
Self::leaf(TimingLeaf {
value,
to,
secs: f64::from(ms) / 1000.0,
easing,
})
}
pub fn tween<T: Lerp + 'static>(value: Animated<T>, to: T, spec: AnimSpec) -> Self {
Self::leaf(TweenLeaf { value, to, spec })
}
pub fn spring(value: Animated<f64>, to: f64, spring: Spring) -> Self {
Self::leaf(SpringLeaf { value, to, spring })
}
pub fn decay(value: Animated<f64>, decay: Decay) -> Self {
Self::leaf(DecayLeaf { value, decay })
}
pub fn drive(spec: AnimSpec, step: impl FnMut(AnimSample) + 'static) -> Self {
Self::leaf(DriveLeaf {
spec,
step: Rc::new(RefCell::new(step)),
})
}
pub fn delay(ms: u32) -> Self {
Animation {
node: Node::Delay(f64::from(ms) / 1000.0),
}
}
pub fn sequence(steps: impl IntoIterator<Item = Animation>) -> Self {
Animation {
node: Node::Sequence(steps.into_iter().map(|step| step.node).collect()),
}
}
pub fn parallel(steps: impl IntoIterator<Item = Animation>) -> Self {
Animation {
node: Node::Parallel(steps.into_iter().map(|step| step.node).collect()),
}
}
pub fn stagger(gap_ms: u32, steps: impl IntoIterator<Item = Animation>) -> Self {
let gap = f64::from(gap_ms) / 1000.0;
Animation {
node: Node::Parallel(
steps
.into_iter()
.enumerate()
.map(|(i, step)| {
if i == 0 {
step.node
} else {
Node::Sequence(vec![Node::Delay(gap * i as f64), step.node])
}
})
.collect(),
),
}
}
pub fn repeat(self, times: u32) -> Self {
Animation {
node: Node::Repeat(Box::new(self.node), Some(times)),
}
}
pub fn looped(self) -> Self {
Animation {
node: Node::Repeat(Box::new(self.node), None),
}
}
#[must_use]
pub fn is_endless(&self) -> bool {
self.node.endless()
}
pub fn jump_to_end(&self) {
day_reactive::batch(|| self.node.finish());
}
pub fn start(&self) -> Playing {
let mut clock = None;
self.node
.leaves(&mut |leaf| clock = clock.or_else(|| leaf.clock()));
self.start_on(clock.unwrap_or_else(FrameClock::current))
}
pub fn start_on(&self, clock: FrameClock) -> Playing {
let mut restore = Vec::new();
self.node
.leaves(&mut |leaf| restore.extend(leaf.snapshot()));
let shared = Rc::new(Shared {
outcome: Cell::new(None),
handle: RefCell::new(None),
run: RefCell::new(None),
wakers: RefCell::new(Vec::new()),
listeners: RefCell::new(Vec::new()),
restore,
});
let playing = Playing {
shared: shared.clone(),
};
let endless = self.node.endless();
if crate::reduce_motion_now() && !endless {
self.jump_to_end();
shared.end(Outcome::Finished);
return playing;
}
let Some(run) = day_reactive::batch(|| self.node.begin()) else {
shared.end(Outcome::Stopped);
return playing;
};
*shared.run.borrow_mut() = Some(run);
let node = self.node.clone();
let guard = Guard(shared.clone());
let handle = clock.subscribe(move |frame| {
let shared = &guard.0;
if shared.outcome.get().is_some() {
return ControlFlow::Break(());
}
let flow = if crate::reduce_motion_now() && !endless {
node.finish();
Flow::Ended(0.0)
} else {
shared
.run
.try_borrow_mut()
.ok()
.and_then(|mut run| {
run.as_mut()
.map(|run| run.advance(frame.delta.as_secs_f64()))
})
.unwrap_or(Flow::Gone)
};
match flow {
Flow::Running if shared.outcome.get().is_none() => {
return ControlFlow::Continue(());
}
Flow::Running => shared.cleanup(),
Flow::Ended(_) => shared.end(Outcome::Finished),
Flow::Gone => shared.end(Outcome::Stopped),
}
ControlFlow::Break(())
});
if shared.outcome.get().is_none() {
*shared.handle.borrow_mut() = Some(handle);
}
playing
}
fn leaf(leaf: impl Leaf + 'static) -> Self {
Animation {
node: Node::Leaf(Rc::new(leaf)),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Outcome {
Finished,
Stopped,
}
type Listener = Box<dyn FnOnce(Outcome)>;
struct Shared {
outcome: Cell<Option<Outcome>>,
handle: RefCell<Option<FrameHandle>>,
run: RefCell<Option<Run>>,
wakers: RefCell<Vec<Waker>>,
listeners: RefCell<Vec<Listener>>,
restore: Vec<Box<dyn Fn()>>,
}
impl Shared {
fn end(&self, outcome: Outcome) {
if self.outcome.get().is_some() {
return;
}
self.outcome.set(Some(outcome));
self.cleanup();
}
fn cleanup(&self) {
let Some(outcome) = self.outcome.get() else {
return;
};
let Ok(mut run) = self.run.try_borrow_mut() else {
return;
};
if let Some(run) = run.take() {
day_reactive::batch(|| run.release());
}
drop(run);
let handle = self.handle.borrow_mut().take();
drop(handle);
for waker in std::mem::take(&mut *self.wakers.borrow_mut()) {
waker.wake();
}
for listener in std::mem::take(&mut *self.listeners.borrow_mut()) {
listener(outcome);
}
}
}
struct Guard(Rc<Shared>);
impl Drop for Guard {
fn drop(&mut self) {
if crate::frame::alive() {
self.0.end(Outcome::Stopped);
}
}
}
#[derive(Clone)]
pub struct Playing {
shared: Rc<Shared>,
}
impl Playing {
#[expect(
clippy::must_use_candidate,
reason = "stopping is the point; whether it was running is incidental"
)]
pub fn stop(&self) -> bool {
let running = self.is_running();
self.shared.end(Outcome::Stopped);
running
}
pub fn reset(&self) {
self.stop();
day_reactive::batch(|| self.shared.restore.iter().for_each(|restore| restore()));
}
#[must_use]
pub fn is_running(&self) -> bool {
self.shared.outcome.get().is_none()
}
#[must_use]
pub fn is_finished(&self) -> bool {
self.shared.outcome.get() == Some(Outcome::Finished)
}
#[must_use]
pub fn outcome(&self) -> Option<Outcome> {
self.shared.outcome.get()
}
pub fn on_end(&self, f: impl FnOnce(Outcome) + 'static) {
match self.shared.outcome.get() {
Some(outcome) => f(outcome),
None => self.shared.listeners.borrow_mut().push(Box::new(f)),
}
}
}
impl std::fmt::Debug for Playing {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Playing")
.field("outcome", &self.shared.outcome.get())
.finish()
}
}
impl Future for Playing {
type Output = Outcome;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Outcome> {
if let Some(outcome) = self.shared.outcome.get() {
return Poll::Ready(outcome);
}
self.shared.wakers.borrow_mut().push(cx.waker().clone());
Poll::Pending
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_curve_starts_at_zero_and_ends_at_one() {
let curves = [
Easing::Linear,
Easing::EASE,
Easing::EASE_IN_OUT,
Easing::Power(Ease::Out, 2.0),
Easing::Power(Ease::InOut, 3.0),
Easing::Sine(Ease::In),
Easing::Circle(Ease::Out),
Easing::Exponential(Ease::InOut),
Easing::Back(Ease::Out, 1.70158),
Easing::ElasticOut(1.0),
Easing::BounceOut,
];
for curve in curves {
assert!(curve.value(0.0).abs() < 1e-3, "{curve:?} at 0");
assert!((curve.value(1.0) - 1.0).abs() < 1e-3, "{curve:?} at 1");
}
}
#[test]
fn back_out_overshoots_and_linear_bezier_is_linear() {
let peak = Easing::Back(Ease::Out, 1.70158)
.samples(101)
.into_iter()
.fold(0.0, f64::max);
assert!(peak > 1.05 && peak < 1.2, "{peak}");
let straight = Easing::Bezier(0.25, 0.25, 0.75, 0.75);
assert!((straight.value(0.3) - 0.3).abs() < 1e-3);
}
#[test]
fn a_spring_settles_on_its_target_and_a_loose_one_overshoots() {
let firm = Spring::new(400.0, 30.0);
let mut state = SpringState::default();
for _ in 0..240 {
firm.step(&mut state, 100.0, 1.0 / 60.0);
}
assert!(firm.settled(state, 100.0), "{state:?}");
let peak = Spring::new(180.0, 8.0)
.response(1.8, 200)
.into_iter()
.fold(0.0, f64::max);
assert!(peak > 1.2, "{peak}");
}
#[test]
fn a_decay_stops_at_a_finite_distance() {
let decay = Decay { rate: 0.992 };
let mut state = SpringState {
value: 0.0,
velocity: 1000.0,
};
for _ in 0..600 {
decay.step(&mut state, 1.0 / 60.0);
}
assert!(decay.stopped(state));
assert!((state.value - 124.5).abs() < 2.0, "{}", state.value);
}
use crate::tree::RNode;
use day_spec::{Color, FrameStamp};
use std::collections::VecDeque;
struct Frames {
pending: Rc<RefCell<VecDeque<day_spec::FrameCallback>>>,
now: Cell<f64>,
}
impl Frames {
fn new() -> Self {
let pending: Rc<RefCell<VecDeque<day_spec::FrameCallback>>> = Rc::default();
let q = pending.clone();
crate::frame::install_frame_requester(move |_, cb| {
q.borrow_mut().push_back(cb);
Box::new(|| {})
});
Frames {
pending,
now: Cell::new(10.0),
}
}
fn clock() -> FrameClock {
FrameClock::for_root(RNode::default())
}
fn step(&self, secs: f64) -> bool {
self.now.set(self.now.get() + secs);
let due: Vec<_> = self.pending.borrow_mut().drain(..).collect();
let wanted = !due.is_empty();
for cb in due {
cb(FrameStamp::new(self.now.get()));
}
wanted
}
fn run(&self, secs: f64) {
for _ in 0..(secs * 60.0).round() as usize {
self.step(1.0 / 60.0);
}
}
fn idle() -> bool {
crate::frame_consumer_count() == 0
}
}
fn close(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-6
}
#[test]
fn a_timing_moves_its_value_and_releases_the_clock_on_arrival() {
let frames = Frames::new();
let v = Animated::on(Frames::clock(), 0.0);
let playing = Animation::timing(v, 100.0, 100, Easing::Linear).start();
assert!(v.is_animating() && playing.is_running());
assert!(close(v.target(), 100.0));
frames.step(0.0); assert!(close(v.get_untracked(), 0.0));
frames.step(0.05);
assert!(close(v.get_untracked(), 50.0));
assert!(close(v.velocity.get_untracked(), 1000.0));
frames.step(0.06);
assert!(close(v.get_untracked(), 100.0));
assert_eq!(playing.outcome(), Some(Outcome::Finished));
assert!(!v.is_animating());
assert!(Frames::idle(), "no frames wanted after arrival");
}
#[test]
fn animate_to_retargets_from_the_value_on_screen() {
let frames = Frames::new();
let v = Animated::on(Frames::clock(), 0.0);
let first = v.animate_to(100.0, AnimSpec::linear(100));
frames.step(0.0);
frames.step(0.05);
assert!(close(v.get_untracked(), 50.0));
let second = v.animate_to(0.0, AnimSpec::linear(100));
assert_eq!(first.outcome(), Some(Outcome::Stopped));
frames.step(0.01); assert!(close(v.get_untracked(), 50.0));
frames.step(0.05);
assert!(close(v.get_untracked(), 25.0));
frames.step(0.06);
assert!(close(v.get_untracked(), 0.0));
assert!(second.is_finished() && !v.is_animating() && Frames::idle());
}
#[test]
fn a_tween_follows_its_spec_and_rests_on_the_target() {
let frames = Frames::new();
let v = Animated::on(Frames::clock(), 0.0);
let spec = AnimSpec::linear(100).delay(100).repeat(1, true);
let playing = Animation::tween(v, 10.0, spec).start();
frames.step(0.0);
frames.step(0.05);
assert!(close(v.get_untracked(), 0.0), "held through the delay");
frames.step(0.1); assert!(close(v.get_untracked(), 5.0));
frames.step(0.125); assert!(close(v.get_untracked(), 2.5));
frames.step(0.05);
assert!(close(v.get_untracked(), 10.0));
assert!(playing.is_finished());
}
#[test]
fn a_sequence_runs_in_order_and_carries_time_across_its_steps() {
let frames = Frames::new();
let (a, b) = (
Animated::on(Frames::clock(), 0.0),
Animated::on(Frames::clock(), 0.0),
);
let playing = Animation::sequence([
Animation::timing(a, 1.0, 100, Easing::Linear),
Animation::delay(100),
Animation::timing(b, 1.0, 100, Easing::Linear),
])
.start();
frames.step(0.0);
frames.step(0.15);
assert!(close(a.get_untracked(), 1.0) && close(b.get_untracked(), 0.0));
assert!(!b.is_animating());
frames.step(0.1);
assert!(close(b.get_untracked(), 0.5), "{}", b.get_untracked());
frames.step(0.06);
assert!(playing.is_finished() && close(b.get_untracked(), 1.0));
}
#[test]
fn a_stagger_starts_each_step_a_gap_after_the_one_before() {
let frames = Frames::new();
let values: Vec<Animated> = (0..3).map(|_| Animated::on(Frames::clock(), 0.0)).collect();
let playing = Animation::stagger(
100,
values
.iter()
.map(|&v| Animation::timing(v, 1.0, 200, Easing::Linear)),
)
.start();
frames.step(0.0);
frames.step(0.2);
let at: Vec<f64> = values.iter().map(|v| v.get_untracked()).collect();
assert!(
close(at[0], 1.0) && close(at[1], 0.5) && close(at[2], 0.0),
"{at:?}"
);
frames.step(0.2);
assert!(playing.is_finished());
assert!(values.iter().all(|v| close(v.get_untracked(), 1.0)));
}
#[test]
fn repeat_plays_a_number_of_times_and_looped_never_ends() {
let frames = Frames::new();
let v = Animated::on(Frames::clock(), 0.0);
let there_and_back = Animation::sequence([
Animation::timing(v, 1.0, 100, Easing::Linear),
Animation::timing(v, 0.0, 100, Easing::Linear),
]);
assert!(!there_and_back.is_endless());
let twice = there_and_back.clone().repeat(2).start();
frames.step(0.0);
frames.step(0.25); assert!(close(v.get_untracked(), 0.5), "{}", v.get_untracked());
assert!(twice.is_running());
frames.step(0.2);
assert!(twice.is_finished() && close(v.get_untracked(), 0.0));
let pulse = there_and_back.looped();
assert!(pulse.is_endless());
let playing = pulse.start();
frames.run(3.0);
assert!(playing.is_running());
assert!(playing.stop());
assert_eq!(playing.outcome(), Some(Outcome::Stopped));
assert!(!v.is_animating() && Frames::idle());
assert!(!playing.stop(), "stopping twice is harmless");
}
#[test]
fn a_spring_settles_carries_velocity_and_a_decay_coasts_to_its_rest() {
let frames = Frames::new();
let v = Animated::on(Frames::clock(), 0.0);
let playing = Animation::spring(v, 100.0, Spring::new(180.0, 8.0)).start();
let mut peak = 0.0_f64;
frames.step(0.0);
for _ in 0..600 {
frames.step(1.0 / 60.0);
peak = peak.max(v.get_untracked());
}
assert!(peak > 110.0, "a loose spring overshoots: {peak}");
assert!(playing.is_finished() && close(v.get_untracked(), 100.0));
assert!(close(v.velocity.get_untracked(), 0.0));
v.set(0.0);
v.set_velocity(-2000.0);
let back = Animation::spring(v, 0.0, Spring::new(180.0, 26.0)).start();
frames.step(0.0);
frames.step(1.0 / 60.0);
assert!(v.get_untracked() < -10.0);
frames.run(5.0);
assert!(back.is_finished() && close(v.get_untracked(), 0.0));
let decay = Decay { rate: 0.992 };
v.set(0.0);
v.set_velocity(1000.0);
let rest = decay.rest(SpringState {
value: 0.0,
velocity: 1000.0,
});
assert!((rest - 124.5).abs() < 0.1, "{rest}");
let fling = Animation::decay(v, decay).start();
assert!(close(v.target(), rest));
frames.run(10.0);
assert!(fling.is_finished());
assert!(
(v.get_untracked() - rest).abs() < 1.0,
"{}",
v.get_untracked()
);
}
#[test]
fn the_latest_step_owns_a_value_and_set_takes_it_from_any() {
let frames = Frames::new();
let v = Animated::on(Frames::clock(), 0.0);
let slow = Animation::timing(v, 100.0, 1000, Easing::Linear).start();
frames.step(0.0);
frames.step(0.1);
let quick = Animation::timing(v, -10.0, 100, Easing::Linear).start();
frames.step(0.0);
frames.step(0.2);
assert!(quick.is_finished() && close(v.get_untracked(), -10.0));
frames.run(1.0);
assert!(slow.is_finished() && close(v.get_untracked(), -10.0));
let again = Animation::timing(v, 100.0, 1000, Easing::Linear).start();
frames.step(0.0);
frames.step(0.1);
v.set(7.0);
assert!(!v.is_animating());
frames.run(1.5);
assert!(again.is_finished() && close(v.get_untracked(), 7.0));
}
#[test]
fn reset_puts_values_back_and_jump_to_end_lands_them() {
let frames = Frames::new();
let (a, b) = (
Animated::on(Frames::clock(), 1.0),
Animated::on(Frames::clock(), 2.0),
);
let animation = Animation::parallel([
Animation::timing(a, 10.0, 100, Easing::Linear),
Animation::sequence([
Animation::delay(50),
Animation::spring(b, 20.0, Spring::default()),
]),
]);
let playing = animation.start();
frames.step(0.0);
frames.step(0.08);
assert!(a.get_untracked() > 1.0 && b.get_untracked() > 2.0);
playing.reset();
assert_eq!(playing.outcome(), Some(Outcome::Stopped));
assert!(close(a.get_untracked(), 1.0) && close(b.get_untracked(), 2.0));
assert!(Frames::idle());
animation.jump_to_end();
assert!(close(a.get_untracked(), 10.0) && close(b.get_untracked(), 20.0));
}
#[test]
fn an_animation_stops_when_a_value_it_moves_is_disposed() {
let frames = Frames::new();
let scope = day_reactive::Scope::root().create_child();
let v = scope.enter(|| Animated::on(Frames::clock(), 0.0));
let kept = Animated::on(Frames::clock(), 0.0);
let playing = Animation::parallel([
Animation::timing(v, 1.0, 1000, Easing::Linear),
Animation::timing(kept, 1.0, 1000, Easing::Linear),
])
.looped()
.start();
frames.step(0.0);
frames.step(0.1);
scope.dispose();
frames.step(0.1);
assert_eq!(playing.outcome(), Some(Outcome::Stopped));
assert!(!kept.is_animating() && Frames::idle());
let late = Animation::timing(v, 1.0, 100, Easing::Linear).start_on(Frames::clock());
assert_eq!(late.outcome(), Some(Outcome::Stopped));
}
#[test]
fn a_group_that_cannot_start_lets_go_of_what_it_started() {
let _frames = Frames::new();
let scope = day_reactive::Scope::root().create_child();
let gone = scope.enter(|| Animated::on(Frames::clock(), 0.0));
scope.dispose();
let step = |v: Animated<f64>| Animation::timing(v, 1.0, 100, Easing::Linear);
for gone_at in 0..3 {
let live: Vec<Animated<f64>> =
(0..2).map(|_| Animated::on(Frames::clock(), 0.0)).collect();
let mut parts: Vec<Animation> = live.iter().map(|v| step(*v)).collect();
parts.insert(gone_at, step(gone));
let nested = Animation::parallel([
Animation::sequence([step(live[0]), step(live[1])]),
Animation::parallel(parts),
]);
for playing in [
nested.start(),
Animation::parallel([step(live[1]), step(gone)]).start(),
] {
assert_eq!(playing.outcome(), Some(Outcome::Stopped), "at {gone_at}");
assert!(
live.iter()
.all(|v| !v.is_animating() && close(v.get_untracked(), 0.0)),
"a live value stayed claimed (gone at {gone_at})"
);
}
}
assert!(Frames::idle());
}
#[test]
fn a_repeat_of_zero_plays_nothing_and_a_late_frame_plays_every_pass_it_covers() {
let frames = Frames::new();
let v = Animated::on(Frames::clock(), 0.0);
let none = Animation::timing(v, 10.0, 100, Easing::Linear).repeat(0);
assert!(!none.is_endless());
let playing = none.start();
frames.step(0.0);
frames.step(0.2);
assert_eq!(playing.outcome(), Some(Outcome::Finished));
assert!(close(v.get_untracked(), 0.0) && !v.is_animating());
let ten = Animation::delay(10).repeat(10).start_on(Frames::clock());
frames.step(0.0);
frames.step(0.2);
assert_eq!(ten.outcome(), Some(Outcome::Finished));
let ticks = Animated::on(Frames::clock(), 0.0);
let counted = Animation::sequence([
Animation::delay(1),
Animation::timing(ticks, 1.0, 0, Easing::Linear),
])
.repeat(1000)
.start();
frames.step(0.0);
frames.step(2.0);
assert_eq!(counted.outcome(), Some(Outcome::Finished));
let after = Animation::sequence([Animation::delay(0).repeat(100), Animation::delay(100)])
.start_on(Frames::clock());
frames.step(0.0);
frames.step(0.2);
assert_eq!(after.outcome(), Some(Outcome::Finished));
let forever = Animation::delay(0).looped().start_on(Frames::clock());
frames.step(0.0);
frames.step(0.1);
assert!(forever.is_running());
assert!(forever.stop() && Frames::idle());
}
#[test]
fn the_handle_resolves_for_callbacks_and_for_tasks() {
let frames = Frames::new();
let v = Animated::on(Frames::clock(), 0.0);
let playing = Animation::timing(v, 1.0, 100, Easing::Linear).start();
let heard = Rc::new(Cell::new(None));
let h = heard.clone();
playing.on_end(move |outcome| h.set(Some(outcome)));
let mut task = Box::pin(playing.clone());
let waker = std::task::Waker::noop();
let mut cx = Context::from_waker(waker);
assert!(task.as_mut().poll(&mut cx).is_pending());
frames.run(0.2);
assert_eq!(heard.get(), Some(Outcome::Finished));
assert_eq!(task.as_mut().poll(&mut cx), Poll::Ready(Outcome::Finished));
let late = Rc::new(Cell::new(false));
let l = late.clone();
playing.on_end(move |_| l.set(true));
assert!(late.get());
}
#[test]
fn every_write_of_a_frame_reaches_a_binding_in_one_pass() {
let frames = Frames::new();
let values: Vec<Animated> = (0..4).map(|_| Animated::on(Frames::clock(), 0.0)).collect();
let runs = Rc::new(Cell::new(0));
let (r, read) = (runs.clone(), values.clone());
day_reactive::Effect::new(move || {
let _sum: f64 = read.iter().map(|v| v.get()).sum();
r.set(r.get() + 1);
});
day_reactive::flush_sync();
let before = runs.get();
let playing = Animation::parallel(
values
.iter()
.map(|&v| Animation::timing(v, 1.0, 1000, Easing::Linear)),
)
.start();
frames.step(0.0);
let started = runs.get();
assert!(started <= before + 2);
for _ in 0..10 {
frames.step(1.0 / 60.0);
}
assert_eq!(runs.get() - started, 10);
playing.stop();
}
#[test]
fn interpolation_clamps_extends_and_blends_colors() {
let fade = Interpolation::new([0.0, 120.0], [1.0, 0.0]);
assert!(close(fade.at(60.0), 0.5));
assert!(close(fade.at(-30.0), 1.0) && close(fade.at(500.0), 0.0));
let open = fade.clone().extend();
assert!(close(open.at(-60.0), 1.5) && close(open.at(240.0), -1.0));
let one_way = Interpolation::new([0.0, 1.0], [0.0, 10.0]).extend_end();
assert!(close(one_way.at(-1.0), 0.0) && close(one_way.at(2.0), 20.0));
let steps = Interpolation::new([0.0, 1.0, 3.0], [0.0, 10.0, 30.0]);
assert!(close(steps.at(0.5), 5.0) && close(steps.at(2.0), 20.0));
assert!(close(steps.at(1.0), 10.0) && close(steps.at(9.0), 30.0));
assert!(close(Interpolation::new([4.0], [7.0]).at(100.0), 7.0));
let (blue, yellow) = (Color::rgb(0.0, 0.0, 1.0), Color::rgb(1.0, 1.0, 0.0));
let heat = Interpolation::new([0.0, 1.0], [blue, yellow]);
assert_eq!(heat.at(0.0), blue);
assert_eq!(heat.at(1.0), yellow);
assert_eq!(heat.at(0.5), crate::tween::mix_oklab(blue, yellow, 0.5));
assert_eq!(heat.at(7.0), yellow);
let _frames = Frames::new();
let scroll = Animated::on(Frames::clock(), 60.0);
let opacity = scroll.interpolate([0.0, 120.0], [1.0, 0.0]);
assert!(close(opacity(), 0.5));
scroll.set(120.0);
assert!(close(opacity(), 0.0));
}
#[test]
fn a_spring_and_its_curve_describe_the_same_motion() {
let spring = Spring::from_response(0.5, 0.4);
let Curve::Spring { response, damping } = spring.curve() else {
panic!("a spring's curve is a spring");
};
assert!(close(response, 0.5) && close(damping, 0.4));
let spec = AnimSpec::spring(0.5, 0.4);
let mut state = SpringState::default();
for i in 1..=60 {
spring.step(&mut state, 1.0, 0.01);
let exact = spec.curve.fraction(f64::from(i) * 0.01, 0.0);
assert!(
(state.value - exact).abs() < 0.01,
"{i}: {} {exact}",
state.value
);
}
}
}