use std::{
cell::RefCell,
collections::{HashMap, HashSet},
time::{Duration, Instant},
};
use gpui::{App, ElementId, EntityId, Global, Hsla, Pixels, Rgba, Styled, Window, WindowId, px};
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Spring {
pub stiffness: f32,
pub damping_ratio: f32,
}
impl Spring {
pub const SPATIAL_FAST: Spring = Spring {
stiffness: 800.,
damping_ratio: 0.6,
};
pub const SPATIAL: Spring = Spring {
stiffness: 380.,
damping_ratio: 0.8,
};
pub const SPATIAL_SLOW: Spring = Spring {
stiffness: 200.,
damping_ratio: 0.8,
};
pub const EFFECTS_FAST: Spring = Spring {
stiffness: 3800.,
damping_ratio: 1.,
};
pub const EFFECTS: Spring = Spring {
stiffness: 1600.,
damping_ratio: 1.,
};
pub const EFFECTS_SLOW: Spring = Spring {
stiffness: 800.,
damping_ratio: 1.,
};
pub fn solve(self, x0: f32, v0: f32, t: f32) -> (f32, f32) {
let w0 = self.stiffness.sqrt();
let z = self.damping_ratio;
if z < 1. {
let wd = w0 * (1. - z * z).sqrt();
let decay = (-z * w0 * t).exp();
let a = x0;
let b = (v0 + z * w0 * x0) / wd;
let (sin, cos) = (wd * t).sin_cos();
let x = decay * (a * cos + b * sin);
let v = decay * ((b * wd - z * w0 * a) * cos - (a * wd + z * w0 * b) * sin);
(x, v)
} else {
let decay = (-w0 * t).exp();
let b = v0 + w0 * x0;
((x0 + b * t) * decay, (v0 - w0 * b * t) * decay)
}
}
pub fn step(self, t: f32) -> f32 {
1. - self.solve(1., 0., t).0
}
pub fn settle_time(self) -> Duration {
let w0 = self.stiffness.sqrt();
let z = self.damping_ratio;
let seconds = if z < 1. {
(1000. / (1. - z * z).sqrt()).ln() / (z * w0)
} else {
9.25 / w0
};
Duration::from_secs_f32(seconds)
}
}
#[derive(Clone, Copy, Debug)]
pub struct MotionSettings {
pub time_scale: f32,
pub reduced: bool,
}
impl Default for MotionSettings {
fn default() -> Self {
Self {
time_scale: 1.,
reduced: false,
}
}
}
impl Global for MotionSettings {}
impl MotionSettings {
pub fn get(cx: &App) -> MotionSettings {
cx.try_global::<MotionSettings>()
.copied()
.unwrap_or_default()
}
pub fn sync(reduced: bool, cx: &mut App) -> bool {
let current = Self::get(cx);
if current.reduced == reduced && cx.has_global::<MotionSettings>() {
return false;
}
cx.set_global(MotionSettings {
reduced,
..current
});
cx.refresh_windows();
true
}
}
pub fn elapsed(start: Instant, cx: &App) -> f32 {
start.elapsed().as_secs_f32() / MotionSettings::get(cx).time_scale.max(0.01)
}
pub fn clock(cx: &App) -> f32 {
static START: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
elapsed(*START.get_or_init(Instant::now), cx)
}
#[cfg(feature = "frame-stats")]
static FRAME_REQUESTS: std::sync::Mutex<Vec<(&'static std::panic::Location<'static>, u32)>> =
std::sync::Mutex::new(Vec::new());
#[track_caller]
pub(crate) fn request_frame(window: &mut Window) {
count_frame_request();
window.request_animation_frame();
}
#[track_caller]
pub fn request_animation_frame(window: &mut Window) {
request_frame(window);
}
#[track_caller]
pub(crate) fn request_frame_for(window: &mut Window, label: &FrameLabel) {
#[cfg(feature = "frame-stats")]
note_frame_id(std::panic::Location::caller(), label);
#[cfg(not(feature = "frame-stats"))]
let _ = label;
request_frame(window);
}
#[cfg(feature = "frame-stats")]
pub(crate) type FrameLabel = ElementId;
#[cfg(not(feature = "frame-stats"))]
pub(crate) type FrameLabel = ();
pub(crate) fn frame_label(id: &ElementId) -> FrameLabel {
#[cfg(feature = "frame-stats")]
{
id.clone()
}
#[cfg(not(feature = "frame-stats"))]
{
let _ = id;
}
}
#[cfg(feature = "frame-stats")]
const FRAME_IDS_MAX: usize = 16;
#[cfg(feature = "frame-stats")]
type FrameIds = Vec<(&'static std::panic::Location<'static>, Vec<(ElementId, u32)>)>;
#[cfg(feature = "frame-stats")]
thread_local! {
static FRAME_IDS: RefCell<FrameIds> = const { RefCell::new(Vec::new()) };
}
#[cfg(feature = "frame-stats")]
fn note_frame_id(at: &'static std::panic::Location<'static>, id: &ElementId) {
FRAME_IDS.with(|sites| {
let mut sites = sites.borrow_mut();
let ids = match sites.iter_mut().position(|(loc, _)| std::ptr::eq(*loc, at)) {
Some(i) => &mut sites[i].1,
None => {
sites.push((at, Vec::new()));
&mut sites.last_mut().expect("just pushed").1
}
};
if let Some((_, n)) = ids.iter_mut().find(|(seen, _)| seen == id) {
*n += 1;
} else if ids.len() < FRAME_IDS_MAX {
ids.push((id.clone(), 1));
}
});
}
#[track_caller]
fn count_frame_request() {
#[cfg(feature = "frame-stats")]
{
let at = std::panic::Location::caller();
if let Ok(mut list) = FRAME_REQUESTS.lock() {
match list.iter_mut().find(|(loc, _)| std::ptr::eq(*loc, at)) {
Some((_, n)) => *n += 1,
None => list.push((at, 1)),
}
}
}
}
const TICK_GRID: f64 = 60.;
fn tick_origin() -> Instant {
static START: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
*START.get_or_init(Instant::now)
}
pub fn tick_delay(fps: f32) -> Duration {
let now = tick_origin().elapsed().as_secs_f64();
Duration::from_secs_f64(delay_to_tick(now, fps as f64))
}
fn delay_to_tick(now: f64, fps: f64) -> f64 {
let period = 1. / fps.clamp(0.1, TICK_GRID);
let mut next = ((now / period).floor() + 1.) * period;
if next - now < 1e-4 {
next += period;
}
let next = ((next * TICK_GRID) - 1e-6).ceil() / TICK_GRID;
(next - now).max(1e-4)
}
pub fn take_frame_requests() -> Vec<(String, u32)> {
#[cfg(feature = "frame-stats")]
{
let Ok(mut list) = FRAME_REQUESTS.lock() else {
return Vec::new();
};
let ids = FRAME_IDS.with(|sites| std::mem::take(&mut *sites.borrow_mut()));
let mut out: Vec<(String, u32)> = list
.drain(..)
.map(|(at, n)| {
let top = ids
.iter()
.find(|(loc, _)| std::ptr::eq(*loc, at))
.and_then(|(_, ids)| ids.iter().max_by_key(|(_, n)| *n));
let site = match top {
Some((id, k)) => format!("{}:{} [{id} ×{k}]", at.file(), at.line()),
None => format!("{}:{}", at.file(), at.line()),
};
(site, n)
})
.collect();
out.sort_by_key(|entry| std::cmp::Reverse(entry.1));
out
}
#[cfg(not(feature = "frame-stats"))]
Vec::new()
}
#[track_caller]
pub fn continuous(window: &mut Window, cx: &App) -> f32 {
if MotionSettings::get(cx).reduced {
return 0.;
}
request_frame(window);
clock(cx)
}
const BACKGROUND_FPS: f32 = 4.;
thread_local! {
static PENDING: RefCell<HashSet<EntityId>> = RefCell::new(HashSet::new());
static AMBIENT: RefCell<HashMap<WindowId, Ambient>> = RefCell::new(HashMap::new());
}
struct Ambient {
real: f32,
shown: f32,
active: bool,
held: bool,
}
impl Ambient {
fn new(now: f32, active: bool) -> Self {
Ambient {
real: now,
shown: now,
active,
held: false,
}
}
fn advance(&mut self, now: f32, active: bool, held: bool) -> f32 {
if active && self.active && !held && !self.held {
self.shown += (now - self.real).clamp(0., 0.5);
}
self.real = now;
self.active = active;
self.held = held;
self.shown
}
}
pub fn ambient_clock(window: &Window, cx: &App) -> f32 {
ambient_tick(window, cx, false)
}
pub(crate) fn held_ambient_clock(window: &Window, cx: &App) -> f32 {
ambient_tick(window, cx, true)
}
fn ambient_tick(window: &Window, cx: &App, held: bool) -> f32 {
if MotionSettings::get(cx).reduced {
return 0.;
}
let now = clock(cx);
let active = window.is_window_active();
AMBIENT.with(|map| {
map.borrow_mut()
.entry(window.window_handle().window_id())
.or_insert_with(|| Ambient::new(now, active))
.advance(now, active, held)
})
}
#[track_caller]
pub fn continuous_at(fps: f32, window: &mut Window, cx: &mut App) -> f32 {
if MotionSettings::get(cx).reduced {
return 0.;
}
let fps = if window.is_window_active() {
fps
} else {
fps.min(BACKGROUND_FPS)
};
if fps >= 60. {
request_frame(window);
return clock(cx);
}
let view = window.current_view();
if PENDING.with(|p| p.borrow_mut().insert(view)) {
count_frame_request();
let timer = cx.background_executor().timer(tick_delay(fps.max(1.)));
cx.spawn(async move |cx| {
timer.await;
PENDING.with(|p| p.borrow_mut().remove(&view));
cx.update(|cx| cx.notify(view)).ok();
})
.detach();
}
clock(cx)
}
#[derive(Clone, Debug)]
pub struct SpringValue<const N: usize> {
spring: Spring,
target: [f32; N],
offset: [f32; N],
velocity: [f32; N],
start: Instant,
settled: bool,
}
impl<const N: usize> SpringValue<N> {
pub fn new(spring: Spring, value: [f32; N]) -> Self {
Self {
spring,
target: value,
offset: [0.; N],
velocity: [0.; N],
start: Instant::now(),
settled: true,
}
}
fn sample(&self, t: f32) -> ([f32; N], [f32; N]) {
let mut value = self.target;
let mut velocity = [0.; N];
if !self.settled {
for i in 0..N {
let (x, v) = self.spring.solve(self.offset[i], self.velocity[i], t);
value[i] = self.target[i] + x;
velocity[i] = v;
}
}
(value, velocity)
}
pub fn update(
&mut self,
target: [f32; N],
spring: Spring,
t: f32,
now: Instant,
) -> ([f32; N], bool) {
if target != self.target || spring != self.spring {
let (value, velocity) = self.sample(t);
for i in 0..N {
self.offset[i] = value[i] - target[i];
self.velocity[i] = velocity[i];
}
self.target = target;
self.spring = spring;
self.start = now;
self.settled = false;
return (value, true);
}
if self.settled {
return (self.target, false);
}
let (value, velocity) = self.sample(t);
let resting =
(0..N).all(|i| (value[i] - self.target[i]).abs() < 0.002 && velocity[i].abs() < 0.05);
if resting {
self.settled = true;
return (self.target, false);
}
(value, true)
}
pub fn kick(&mut self, from: [f32; N], now: Instant) {
for (offset, (from, target)) in self.offset.iter_mut().zip(from.iter().zip(&self.target)) {
*offset = from - target;
}
self.velocity = [0.; N];
self.start = now;
self.settled = false;
}
}
#[track_caller]
pub fn animate<const N: usize>(
id: impl Into<ElementId>,
spring: Spring,
target: [f32; N],
window: &mut Window,
cx: &mut App,
) -> [f32; N] {
animate_inner(id.into(), spring, target, None, window, cx)
}
#[track_caller]
pub fn animate_from<const N: usize>(
id: impl Into<ElementId>,
spring: Spring,
from: [f32; N],
target: [f32; N],
window: &mut Window,
cx: &mut App,
) -> [f32; N] {
animate_inner(id.into(), spring, target, Some(from), window, cx)
}
#[track_caller]
fn animate_inner<const N: usize>(
id: ElementId,
spring: Spring,
target: [f32; N],
from: Option<[f32; N]>,
window: &mut Window,
cx: &mut App,
) -> [f32; N] {
let settings = MotionSettings::get(cx);
let label = frame_label(&id);
let (value, moving) = element_state(id, window, |state: Option<SpringValue<N>>, _| {
let mut s = state.unwrap_or_else(|| {
let mut value = SpringValue::new(spring, target);
if let Some(from) = from {
value.kick(from, Instant::now());
}
value
});
if settings.reduced {
return ((target, false), SpringValue::new(spring, target));
}
if s.settled && s.target == target && s.spring == spring {
return ((target, false), s);
}
let now = Instant::now();
let t = now.duration_since(s.start).as_secs_f32() / settings.time_scale.max(0.01);
#[cfg(feature = "frame-stats")]
if (target != s.target || spring != s.spring) && t < 0.004 {
log::warn!("spring {label:?} retargeted twice within a frame (duplicate element id)");
}
(s.update(target, spring, t, now), s)
});
if moving {
request_frame_for(window, &label);
}
value
}
pub(crate) fn element_state<S: 'static, R>(
id: ElementId,
window: &mut Window,
f: impl FnOnce(Option<S>, &mut Window) -> (R, S),
) -> R {
window.with_global_id(id, |global_id, window| {
window.with_element_state(global_id, f)
})
}
struct Triggered<const N: usize> {
value: SpringValue<N>,
active: bool,
}
#[track_caller]
pub fn animate_on_activate<const N: usize>(
id: impl Into<ElementId>,
spring: Spring,
active: bool,
from: [f32; N],
rest: [f32; N],
window: &mut Window,
cx: &mut App,
) -> [f32; N] {
let settings = MotionSettings::get(cx);
let id = id.into();
let label = frame_label(&id);
let (value, moving) = element_state(id, window, |state: Option<Triggered<N>>, _| {
let mut s = state.unwrap_or_else(|| {
let mut value = SpringValue::new(spring, rest);
if active {
value.kick(from, Instant::now());
}
Triggered { value, active }
});
if settings.reduced {
return ((rest, false), s);
}
let now = Instant::now();
if active && !s.active {
s.value.kick(from, now);
}
s.active = active;
if s.value.settled && s.value.target == rest {
return ((rest, false), s);
}
let t = now.duration_since(s.value.start).as_secs_f32() / settings.time_scale.max(0.01);
(s.value.update(rest, spring, t, now), s)
});
if moving {
request_frame_for(window, &label);
}
value
}
#[track_caller]
pub fn entrance(
id: impl Into<ElementId>,
spring: Spring,
delay: f32,
window: &mut Window,
cx: &mut App,
) -> f32 {
let settings = MotionSettings::get(cx);
let id = id.into();
let label = frame_label(&id);
let start = element_state(id, window, |start: Option<Instant>, _| {
let start = start.unwrap_or_else(Instant::now);
(start, start)
});
if settings.reduced {
return 1.;
}
match entrance_progress(spring, elapsed(start, cx) - delay) {
Some(p) => {
request_frame_for(window, &label);
p
}
None => 1.,
}
}
#[track_caller]
pub fn entrance_since(
start: Instant,
spring: Spring,
delay: f32,
window: &mut Window,
cx: &App,
) -> f32 {
if MotionSettings::get(cx).reduced {
return 1.;
}
match entrance_progress(spring, elapsed(start, cx) - delay) {
Some(p) => {
request_frame(window);
p
}
None => 1.,
}
}
fn entrance_progress(spring: Spring, t: f32) -> Option<f32> {
(t < spring.settle_time().as_secs_f32()).then(|| spring.step(t.max(0.)))
}
#[track_caller]
pub fn animate_f32(
id: impl Into<ElementId>,
spring: Spring,
target: f32,
window: &mut Window,
cx: &mut App,
) -> f32 {
animate(id, spring, [target], window, cx)[0]
}
#[track_caller]
pub fn animate_px(
id: impl Into<ElementId>,
spring: Spring,
target: Pixels,
window: &mut Window,
cx: &mut App,
) -> Pixels {
px(animate(id, spring, [f32::from(target)], window, cx)[0])
}
#[track_caller]
pub fn animate_color(
id: impl Into<ElementId>,
spring: Spring,
target: Hsla,
window: &mut Window,
cx: &mut App,
) -> Hsla {
let c = Rgba::from(target);
let [r, g, b, a] = animate(id, spring, [c.r, c.g, c.b, c.a], window, cx);
Rgba {
r: r.clamp(0., 1.),
g: g.clamp(0., 1.),
b: b.clamp(0., 1.),
a: a.clamp(0., 1.),
}
.into()
}
pub fn cubic_bezier(x1: f32, y1: f32, x2: f32, y2: f32) -> impl Fn(f32) -> f32 + Copy {
move |x: f32| {
if x <= 0. {
return 0.;
}
if x >= 1. {
return 1.;
}
let bez = |t: f32, a: f32, b: f32| {
3. * a * t * (1. - t).powi(2) + 3. * b * t * t * (1. - t) + t.powi(3)
};
let (mut lo, mut hi) = (0f32, 1f32);
let mut t = x;
for _ in 0..24 {
let v = bez(t, x1, x2);
if (v - x).abs() < 1e-5 {
break;
}
if v < x {
lo = t;
} else {
hi = t;
}
t = (lo + hi) / 2.;
}
bez(t, y1, y2)
}
}
#[track_caller]
pub fn pulse(period: f32, window: &mut Window, cx: &mut App) -> f32 {
if MotionSettings::get(cx).reduced {
return 1.;
}
let t = continuous_at(30., window, cx);
0.725 + 0.275 * (t / period.max(0.1) * std::f32::consts::TAU).cos()
}
#[track_caller]
pub fn replay(
id: impl Into<ElementId>,
generation: u64,
duration: f32,
window: &mut Window,
cx: &mut App,
) -> Option<f32> {
let settings = MotionSettings::get(cx);
let id = id.into();
let label = frame_label(&id);
let start = element_state(
id,
window,
|state: Option<(u64, Option<Instant>)>, _| {
let state = match state {
Some((g, start)) if g == generation => (g, start),
Some(_) => (generation, Some(Instant::now())),
None => (generation, None),
};
(state.1, state)
},
);
if settings.reduced {
return None;
}
let t = elapsed(start?, cx);
(t < duration).then(|| {
request_frame_for(window, &label);
t
})
}
#[track_caller]
pub fn play_on_rise(
id: impl Into<ElementId>,
active: bool,
duration: f32,
window: &mut Window,
cx: &mut App,
) -> Option<f32> {
let settings = MotionSettings::get(cx);
let id = id.into();
let label = frame_label(&id);
let start = element_state(
id,
window,
|state: Option<(bool, Option<Instant>)>, _| {
let state = match state {
Some((false, _)) if active => (true, Some(Instant::now())),
Some((_, start)) => (active, start),
None => (active, None),
};
(state.1, state)
},
);
if settings.reduced {
return None;
}
let t = elapsed(start?, cx);
(t < duration).then(|| {
request_frame_for(window, &label);
t
})
}
#[track_caller]
pub fn presence(
id: impl Into<ElementId>,
show: bool,
window: &mut Window,
cx: &mut App,
) -> Option<f32> {
let settings = MotionSettings::get(cx);
let spring = Spring::EFFECTS_FAST;
let id = id.into();
let label = frame_label(&id);
let (value, moving) = element_state(id, window, |state: Option<Presence>, _| {
let mut s = state.unwrap_or(Presence {
value: SpringValue::new(spring, [if show { 1. } else { 0. }]),
mounted: show,
});
let now = Instant::now();
if show {
s.mounted = true;
s.value = SpringValue::new(spring, [1.]);
return ((Some(1.), false), s);
}
if !s.mounted || settings.reduced {
s.mounted = false;
return ((None, false), s);
}
if s.value.target != [0.] {
s.value.update([0.], spring, 0., now);
}
let t = now.duration_since(s.value.start).as_secs_f32() / settings.time_scale.max(0.01);
let ([value], moving) = s.value.update([0.], spring, t, now);
if !moving || value <= 0.01 {
s.mounted = false;
return ((None, false), s);
}
((Some(value.clamp(0., 1.)), true), s)
});
if moving {
request_frame_for(window, &label);
}
value
}
struct Presence {
value: SpringValue<1>,
mounted: bool,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Expand {
Hidden,
Natural,
Clipped(Pixels),
}
struct ExpandState {
open: bool,
value: Option<SpringValue<1>>,
}
#[track_caller]
pub fn expand(
id: impl Into<ElementId>,
open: bool,
measured: Pixels,
spring: Spring,
window: &mut Window,
cx: &mut App,
) -> Expand {
let settings = MotionSettings::get(cx);
let measured = f32::from(measured).max(0.);
let id = id.into();
let label = frame_label(&id);
let (result, moving) = element_state(id, window, |state: Option<ExpandState>, _| {
let mut s = state.unwrap_or(ExpandState { open, value: None });
let rest = if open {
Expand::Natural
} else {
Expand::Hidden
};
if settings.reduced {
s.open = open;
s.value = None;
return ((rest, false), s);
}
let now = Instant::now();
if s.open != open {
s.open = open;
if s.value.is_none() {
let from = if open { 0. } else { measured };
s.value = Some(SpringValue::new(spring, [from]));
}
}
let Some(value) = s.value.as_mut() else {
return ((rest, false), s);
};
if open && measured <= 0. {
return ((Expand::Clipped(px(0.)), true), s);
}
let target = if open { measured } else { 0. };
let t = now.duration_since(value.start).as_secs_f32() / settings.time_scale.max(0.01);
let ([h], moving) = value.update([target], spring, t, now);
if !moving {
s.value = None;
return ((rest, false), s);
}
((Expand::Clipped(px(h.max(0.))), true), s)
});
if moving {
request_frame_for(window, &label);
}
result
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum SharedAxis {
#[default]
X,
Y,
Z,
}
#[derive(Clone)]
pub struct Enter {
id: ElementId,
delay: f32,
dx: f32,
dy: f32,
spring: Spring,
generation: Option<u64>,
}
impl Enter {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
delay: 0.,
dx: 0.,
dy: 12.,
spring: Spring::SPATIAL,
generation: None,
}
}
pub fn shared_axis(mut self, axis: SharedAxis, forward: bool) -> Self {
let distance = if forward { 30. } else { -30. };
(self.dx, self.dy) = match axis {
SharedAxis::X => (distance, 0.),
SharedAxis::Y => (0., distance),
SharedAxis::Z => (0., 0.),
};
self
}
pub fn delay(mut self, delay: f32) -> Self {
self.delay = delay.max(0.);
self
}
pub fn from(mut self, dx: f32, dy: f32) -> Self {
self.dx = dx;
self.dy = dy;
self
}
pub fn spring(mut self, spring: Spring) -> Self {
self.spring = spring;
self
}
pub fn on_change(mut self, generation: u64) -> Self {
self.generation = Some(generation);
self
}
#[track_caller]
pub fn progress(self, window: &mut Window, cx: &mut App) -> f32 {
match self.generation {
None => entrance(self.id, self.spring, self.delay, window, cx),
Some(generation) => {
let duration = self.spring.settle_time().as_secs_f32() + self.delay;
match replay(self.id, generation, duration, window, cx) {
Some(t) => self.spring.step((t - self.delay).max(0.)),
None => 1.,
}
}
}
}
#[track_caller]
pub fn apply<E: Styled>(self, el: E, window: &mut Window, cx: &mut App) -> E {
let (dx, dy) = (self.dx, self.dy);
let p = self.progress(window, cx);
if p == 1. {
return el;
}
el.relative()
.left(px((1. - p) * dx))
.top(px((1. - p) * dy))
.opacity(p.clamp(0., 1.))
}
}
pub fn stagger(index: usize, step: f32, max: usize) -> f32 {
index.min(max) as f32 * step
}
pub fn key(id: &ElementId, name: &'static str) -> ElementId {
ElementId::NamedChild(Box::new(id.clone()), name.into())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ticks_land_on_a_shared_grid() {
let at = |now: f64, fps: f64| now + delay_to_tick(now, fps);
let on_grid = |t: f64| ((t * 60.) - (t * 60.).round()).abs() < 1e-6;
assert!((at(0.010, 30.) - 1. / 30.).abs() < 1e-9);
assert!((at(1. / 30., 30.) - 2. / 30.).abs() < 1e-9);
assert!((at(0.20, 4.) - 0.25).abs() < 1e-9);
for i in 0..200 {
let now = i as f64 * 0.0137;
assert!(on_grid(at(now, 30.)) && on_grid(at(now, 4.)) && on_grid(at(now, 12.)));
}
let t = at(0.0, 24.);
assert!(t >= 1. / 24. && on_grid(t));
for i in 0..1000 {
let now = i as f64 * 0.00731;
let delay = delay_to_tick(now, 30.);
assert!(delay > 0. && delay <= 1. / 30. + 1. / 60. + 1e-3);
}
}
#[test]
fn stagger_has_a_cap() {
assert_eq!(stagger(0, 0.03, 6), 0.);
assert!((stagger(2, 0.03, 6) - 0.06).abs() < 1e-6);
assert!((stagger(40, 0.03, 6) - 0.18).abs() < 1e-6);
}
#[test]
fn shared_axis_comes_from_the_leading_side() {
let enter = |axis, forward| {
let e = Enter::new("e").shared_axis(axis, forward);
(e.dx, e.dy)
};
assert_eq!(enter(SharedAxis::X, true), (30., 0.));
assert_eq!(enter(SharedAxis::X, false), (-30., 0.));
assert_eq!(enter(SharedAxis::Y, true), (0., 30.));
assert_eq!(enter(SharedAxis::Z, false), (0., 0.));
}
#[test]
fn springs_settle_on_target() {
for spring in [
Spring::SPATIAL_FAST,
Spring::SPATIAL,
Spring::SPATIAL_SLOW,
Spring::EFFECTS_FAST,
Spring::EFFECTS,
Spring::EFFECTS_SLOW,
] {
let end = spring.step(spring.settle_time().as_secs_f32());
assert!((end - 1.).abs() < 0.002, "{spring:?} ends at {end}");
}
}
#[test]
fn spatial_springs_bounce_and_effects_do_not() {
let peak = |s: Spring| {
(0..400)
.map(|i| s.step(i as f32 / 400.))
.fold(0f32, f32::max)
};
assert!((peak(Spring::SPATIAL_FAST) - 1.095).abs() < 0.005);
assert!(peak(Spring::EFFECTS) <= 1.0001);
}
#[test]
fn retargeting_from_rest_starts_from_the_old_value() {
let now = Instant::now();
let mut value = SpringValue::new(Spring::SPATIAL, [120.]);
let (start, moving) = value.update([0.], Spring::SPATIAL, 0., now);
assert!(moving);
assert!((start[0] - 120.).abs() < 1e-4);
let (later, _) = value.update([0.], Spring::SPATIAL, 0.1, now);
assert!(later[0] < 120. && later[0] > 0.);
}
#[test]
fn retargeting_keeps_position() {
let now = Instant::now();
let mut value = SpringValue::new(Spring::SPATIAL, [0.]);
value.update([10.], Spring::SPATIAL, 0., now);
let (mid, _) = value.update([10.], Spring::SPATIAL, 0.1, now);
let (after, moving) = value.update([0.], Spring::SPATIAL, 0.1, now);
assert!(moving);
assert!((after[0] - mid[0]).abs() < 1e-4);
}
fn moving_frames(value: &mut SpringValue<1>, target: f32, seconds: f32) -> usize {
let now = Instant::now();
(0..(seconds * 120.) as usize)
.filter(|&i| value.update([target], value.spring, i as f32 / 120., now).1)
.count()
}
#[test]
fn a_settled_spring_asks_for_no_more_frames() {
for spring in [Spring::SPATIAL_FAST, Spring::SPATIAL, Spring::EFFECTS] {
for target in [1., 600.] {
let mut value = SpringValue::new(spring, [0.]);
let busy = moving_frames(&mut value, target, 2.);
let limit = (spring.settle_time().as_secs_f32() * 2. * 120.) as usize;
assert!(busy > 0 && busy < limit, "{spring:?} → {target}: {busy} frames");
assert_eq!(moving_frames(&mut value, target, 1.), 0);
let (rest, moving) = value.update([target], spring, 60., Instant::now());
assert!(!moving && rest == [target]);
}
}
}
#[test]
fn entrances_stop_asking_for_frames_once_settled() {
for spring in [Spring::SPATIAL, Spring::EFFECTS] {
let settle = spring.settle_time().as_secs_f32();
assert_eq!(entrance_progress(spring, -0.1), Some(0.));
assert!(entrance_progress(spring, settle * 0.5).is_some());
assert_eq!(entrance_progress(spring, settle), None);
assert_eq!(entrance_progress(spring, 3600.), None);
}
}
#[test]
fn a_held_ambient_clock_keeps_its_pose_and_resumes_without_a_jump() {
let mut clock = Ambient::new(10., true);
let close = |a: f32, b: f32| (a - b).abs() < 1e-4;
assert!(close(clock.advance(10.5, true, false), 10.5));
assert!(close(clock.advance(11., true, true), 10.5));
assert!(close(clock.advance(40., true, true), 10.5));
assert!(close(clock.advance(60., true, false), 10.5));
assert!(close(clock.advance(60.1, true, false), 10.6));
assert!(close(clock.advance(61., false, false), 10.6));
}
}