Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
gpui: Add spring animations; examples (#62778)
David Barsky8b1497dbd22f
diff --git a/crates/gpui/examples/animation.rs b/crates/gpui/examples/animation.rsindex 6755b49ca0d..4e09d15c411 100644--- a/crates/gpui/examples/animation.rs+++ b/crates/gpui/examples/animation.rs@@ -4,9 +4,10 @@ use std::time::Duration;use anyhow::Result;use gpui::{- Animation, AnimationExt as _, App, AssetSource, Bounds, Context, SharedString, Transformation,- Window, WindowBounds, WindowOptions, bounce, div, ease_in_out, percentage, prelude::*, px,- size, svg,+ Animation, AnimationExt as _, AnimationPhase, App, AssetSource, Bounds, Context, MouseButton,+ MouseDownEvent, MouseMoveEvent, Pixels, SharedString, SpringAnimation, SpringConfig,+ Transformation, Window, WindowBounds, WindowOptions, bounce, div, ease_in_out, percentage,+ prelude::*, px, relative, rgba, size, svg,};use gpui_platform::application;@@ -36,10 +37,26 @@ const ARROW_CIRCLE_SVG: &str = concat!("/examples/image/arrow_circle.svg");-struct AnimationExample {}+struct AnimationExample {+ spring_phase: u8,+ spring_damping: f32,+ spring_damping_drag: Option<(Pixels, f32)>,+}impl Render for AnimationExample {- fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {+ fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ const MINIMUM_DAMPING: f32 = 2.0;+ const MAXIMUM_DAMPING: f32 = 32.0;+ const DAMPING_SLIDER_WIDTH: Pixels = px(224.0);++ let spring_phase = self.spring_phase;+ let spring_position = px(98.0 * f32::from(spring_phase));+ let spring_damping = self.spring_damping;+ let spring = SpringConfig::new(170.0, spring_damping, 1.0);+ let (_, damping_ratio) = spring.canonical();+ let damping_fraction =+ (spring_damping - MINIMUM_DAMPING) / (MAXIMUM_DAMPING - MINIMUM_DAMPING);+div().flex().flex_col()@@ -67,6 +84,190 @@ impl Render for AnimationExample {.text_xl().gap_4().child("Hello Animation")+ .child(+ div()+ .id("spring-demo")+ .flex()+ .flex_col()+ .gap_2()+ .p_2()+ .w(px(240.0))+ .rounded_md()+ .bg(rgba(0x00000010))+ .cursor_pointer()+ .on_mouse_down(+ MouseButton::Left,+ cx.listener(|this, _, _, cx| {+ this.spring_phase = (this.spring_phase + 1) % 3;+ cx.notify();+ }),+ )+ .child(format!(+ "Target phase {spring_phase}: click rapidly to redirect momentum"+ ))+ .child(+ div()+ .id("spring-damping-controls")+ .flex()+ .flex_col()+ .gap_1()+ .text_sm()+ .on_click(|_, _, cx| cx.stop_propagation())+ .child(format!(+ "Drag damping: {spring_damping:.1} (ζ {damping_ratio:.2})"+ ))+ .child(+ div()+ .id("spring-damping")+ .relative()+ .h(px(20.0))+ .w(DAMPING_SLIDER_WIDTH)+ .cursor_pointer()+ .on_mouse_down(+ MouseButton::Left,+ cx.listener(+ |this,+ event: &MouseDownEvent,+ _,+ cx| {+ this.spring_damping_drag = Some((+ event.position.x,+ this.spring_damping,+ ));+ cx.stop_propagation();+ },+ ),+ )+ .on_mouse_move(cx.listener(+ |this,+ event: &MouseMoveEvent,+ _,+ cx| {+ let Some((+ start_position,+ start_damping,+ )) = this.spring_damping_drag+ else {+ return;+ };++ let delta = (event.position.x+ - start_position)+ / DAMPING_SLIDER_WIDTH;+ this.spring_damping = (start_damping+ + delta+ * (MAXIMUM_DAMPING+ - MINIMUM_DAMPING))+ .clamp(+ MINIMUM_DAMPING,+ MAXIMUM_DAMPING,+ );+ cx.stop_propagation();+ cx.notify();+ },+ ))+ .on_mouse_up(+ MouseButton::Left,+ cx.listener(|this, _, _, cx| {+ this.spring_damping_drag = None;+ cx.stop_propagation();+ }),+ )+ .on_mouse_up_out(+ MouseButton::Left,+ cx.listener(|this, _, _, cx| {+ this.spring_damping_drag = None;+ cx.stop_propagation();+ }),+ )+ .child(+ div()+ .absolute()+ .top(px(8.0))+ .h(px(4.0))+ .w_full()+ .rounded_full()+ .bg(rgba(0x00000030)),+ )+ .child(+ div()+ .absolute()+ .top(px(8.0))+ .h(px(4.0))+ .w(relative(damping_fraction))+ .rounded_full()+ .bg(rgba(0x3b82f6ff)),+ )+ .child(+ div()+ .absolute()+ .top(px(3.0))+ .left(relative(damping_fraction))+ .ml(px(-7.0))+ .size(px(14.0))+ .rounded_full()+ .bg(rgba(0x2563ebff)),+ ),+ ),+ )+ .child(+ div().relative().h(px(32.0)).w_full().child(+ div()+ .absolute()+ .top_1()+ .size(px(24.0))+ .rounded_full()+ .bg(rgba(0x3b82f6ff))+ .cursor_pointer()+ .debug_selector(|| "spring-position".into())+ .with_spring(+ "spring-position",+ SpringAnimation::new(spring)+ .to(spring_position)+ .with_epsilon(0.25),+ |this, left| this.left(left),+ ),+ ),+ )+ .child(+ div().h(px(24.0)).rounded_sm().with_spring(+ "spring-phase",+ SpringAnimation::new(spring)+ .to(AnimationPhase(f32::from(spring_phase)))+ .with_epsilon(0.001),+ |this, phase| {+ let (width, color) = if phase.0 <= 1.0 {+ (+ phase.interpolate_between(+ 0.0..=1.0,+ px(48.0),+ px(224.0),+ ),+ phase.interpolate_between_clamped(+ 0.0..=1.0,+ rgba(0xf97316ff),+ rgba(0x22c55eff),+ ),+ )+ } else {+ (+ phase.interpolate_between(+ 1.0..=2.0,+ px(224.0),+ px(96.0),+ ),+ phase.interpolate_between_clamped(+ 1.0..=2.0,+ rgba(0x22c55eff),+ rgba(0xa855f7ff),+ ),+ )+ };+ this.w(width).bg(color)+ },+ ),+ ),+ ).child(svg().size_20()@@ -115,7 +316,11 @@ fn run_example() {};cx.open_window(options, |_, cx| {cx.activate(false);- cx.new(|_| AnimationExample {})+ cx.new(|_| AnimationExample {+ spring_phase: 0,+ spring_damping: 14.0,+ spring_damping_drag: None,+ })}).unwrap();});@@ -132,3 +337,31 @@ pub fn start() {gpui_platform::web_init();run_example();}++#[cfg(all(test, feature = "test-support"))]+mod tests {+ use gpui::{Modifiers, TestAppContext};++ use super::*;++ #[gpui::test]+ fn clicking_spring_position_changes_the_target(cx: &mut TestAppContext) {+ let (view, cx) = cx.add_window_view(|_, _| AnimationExample {+ spring_phase: 0,+ spring_damping: 14.0,+ spring_damping_drag: None,+ });+ cx.simulate_resize(size(px(300.0), px(300.0)));+ cx.run_until_parked();++ let position_bounds = cx+ .debug_bounds("spring-position")+ .expect("spring position should be rendered");+ let position = position_bounds.center();+ cx.simulate_mouse_move(position, None, Modifiers::default());+ cx.simulate_click(position, Modifiers::default());+ cx.run_until_parked();++ assert_eq!(cx.update(|_, cx| view.read(cx).spring_phase), 1);+ }+}diff --git a/crates/gpui/src/elements/animation.rs b/crates/gpui/src/elements/animation.rsindex 4cab1fbca2c..e0768935d91 100644--- a/crates/gpui/src/elements/animation.rs+++ b/crates/gpui/src/elements/animation.rs@@ -3,7 +3,8 @@ use std::{cell::Cell, rc::Rc, time::Duration};use crate::{AnyElement, App, Element, ElementId, GlobalElementId, InspectorElementId, IntoElement,- ParentElement, Window,+ ParentElement, SpringAnimation, SpringConfig, SpringPlayback, SpringState, SpringTarget,+ Window,};pub use easing::*;@@ -18,8 +19,8 @@ pub struct Animation {pub oneshot: bool,/// Whether to derive the phase from a shared clock. See [`Animation::repeat_synced`].pub synced: bool,- /// A function that takes a delta between 0 and 1 and returns a new delta- /// between 0 and 1 based on the given easing function.+ /// A function that maps normalized time to an animated value.+ /// The result may exceed 0..1 for easing functions that overshoot.pub easing: Rc<dyn Fn(f32) -> f32>,/// The maximum number of times per second this animation re-renders./// When `None`, the animation re-renders on every frame.@@ -52,9 +53,10 @@ impl Animation {self}- /// Set the easing function to use for this animation.- /// The easing function will take a time delta between 0 and 1 and return a new delta- /// between 0 and 1+ /// Sets the easing function used to map normalized time to an animated value.+ ///+ /// The output is not clamped, allowing physical easing functions such as+ /// springs to overshoot.pub fn with_easing(mut self, easing: impl Fn(f32) -> f32 + 'static) -> Self {self.easing = Rc::new(easing);self@@ -113,6 +115,44 @@ pub trait AnimationExt {animations: animations.into(),}}++ /// Renders this component or element at the value produced by a spring.+ ///+ /// The element ID preserves position and velocity across target changes.+ /// A newly mounted spring starts at its target unless configured with+ /// [`SpringAnimation::from`].+ fn with_spring<T>(+ self,+ id: impl Into<ElementId>,+ animation: SpringAnimation<T>,+ animator: impl FnOnce(Self, T::Output) -> Self + 'static,+ ) -> SpringAnimationElement<Self>+ where+ Self: Sized,+ T: SpringTarget,+ T::Output: 'static,+ {+ let SpringAnimation {+ config,+ target,+ epsilon,+ initial,+ playback,+ } = animation;+ let scalar_target = target.target();+ SpringAnimationElement {+ id: id.into(),+ element: Some(self),+ config,+ target: scalar_target,+ epsilon,+ initial,+ playback,+ animator: Some(Box::new(move |this, value| {+ animator(this, target.resolve(value))+ })),+ }+ }}impl<E: IntoElement + 'static> AnimationExt for E {}@@ -125,6 +165,45 @@ pub struct AnimationElement<E> {animator: Box<dyn Fn(E, usize, f32) -> E + 'static>,}+/// A GPUI element driven by a stateful spring.+pub struct SpringAnimationElement<E> {+ id: ElementId,+ element: Option<E>,+ config: SpringConfig,+ target: f32,+ epsilon: f32,+ initial: Option<f32>,+ playback: SpringPlayback,+ animator: Option<Box<dyn FnOnce(E, f32) -> E + 'static>>,+}++impl<E: ParentElement> ParentElement for SpringAnimationElement<E> {+ fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {+ let Some(element) = &mut self.element else {+ return;+ };++ element.extend(elements);+ }+}++impl<E> SpringAnimationElement<E> {+ /// Returns a new [`SpringAnimationElement<E>`] after applying the given function+ /// to the element being animated.+ pub fn map_element(mut self, f: impl FnOnce(E) -> E) -> SpringAnimationElement<E> {+ self.element = self.element.map(f);+ self+ }+}++impl<E: IntoElement + 'static> IntoElement for SpringAnimationElement<E> {+ type Element = SpringAnimationElement<E>;++ fn into_element(self) -> Self::Element {+ self+ }+}+impl<E: ParentElement> ParentElement for AnimationElement<E> {fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {let Some(element) = &mut self.element else {@@ -160,6 +239,146 @@ struct AnimationState {delayed_frame_pending: Rc<Cell<bool>>,}+struct SpringElementState {+ spring: SpringState,+ target: f32,+ config: SpringConfig,+ initial: f32,+ playback: SpringPlayback,+ updated_at: Instant,+}++impl<E: IntoElement + 'static> Element for SpringAnimationElement<E> {+ type RequestLayoutState = AnyElement;+ type PrepaintState = ();++ fn id(&self) -> Option<ElementId> {+ Some(self.id.clone())+ }++ fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {+ None+ }++ fn request_layout(+ &mut self,+ global_id: Option<&GlobalElementId>,+ _inspector_id: Option<&InspectorElementId>,+ window: &mut Window,+ cx: &mut App,+ ) -> (crate::LayoutId, Self::RequestLayoutState) {+ window.with_element_state(global_id.unwrap(), |state, window| {+ let now = Instant::now();+ let initial = self.initial.unwrap_or(self.target);+ let mut state = state.unwrap_or_else(|| SpringElementState {+ spring: SpringState {+ position: initial,+ velocity: 0.0,+ },+ target: self.target,+ config: self.config,+ initial,+ playback: self.playback,+ updated_at: now,+ });++ let elapsed = now.duration_since(state.updated_at).as_secs_f32();+ match state.playback {+ SpringPlayback::Running => {+ state.spring = state.config.step(state.spring, state.target, elapsed);+ }+ SpringPlayback::Paused+ | SpringPlayback::Stopped+ | SpringPlayback::Completed+ | SpringPlayback::Cancelled => {}+ }++ state.config = self.config;+ state.target = self.target;++ let done = match self.playback {+ SpringPlayback::Running => {+ if cx.reduce_motion() {+ state.spring = SpringState {+ position: state.target,+ velocity: 0.0,+ };+ true+ } else {+ let done =+ state+ .config+ .is_settled(state.spring, state.target, self.epsilon);+ if done {+ state.spring = SpringState {+ position: state.target,+ velocity: 0.0,+ };+ }+ done+ }+ }+ SpringPlayback::Paused => true,+ SpringPlayback::Stopped => {+ state.spring.velocity = 0.0;+ true+ }+ SpringPlayback::Completed => {+ state.spring = SpringState {+ position: state.target,+ velocity: 0.0,+ };+ true+ }+ SpringPlayback::Cancelled => {+ state.spring = SpringState {+ position: state.initial,+ velocity: 0.0,+ };+ true+ }+ };+ state.playback = self.playback;+ state.updated_at = now;++ let element = self.element.take().expect("should only be called once");+ let animator = self.animator.take().expect("should only be called once");+ let mut element = animator(element, state.spring.position).into_any_element();++ if !done {+ window.request_animation_frame();+ }++ ((element.request_layout(window, cx), element), state)+ })+ }++ fn prepaint(+ &mut self,+ _id: Option<&GlobalElementId>,+ _inspector_id: Option<&InspectorElementId>,+ _bounds: crate::Bounds<crate::Pixels>,+ element: &mut Self::RequestLayoutState,+ window: &mut Window,+ cx: &mut App,+ ) -> Self::PrepaintState {+ element.prepaint(window, cx);+ }++ fn paint(+ &mut self,+ _id: Option<&GlobalElementId>,+ _inspector_id: Option<&InspectorElementId>,+ _bounds: crate::Bounds<crate::Pixels>,+ element: &mut Self::RequestLayoutState,+ _: &mut Self::PrepaintState,+ window: &mut Window,+ cx: &mut App,+ ) {+ element.paint(window, cx);+ }+}+impl<E: IntoElement + 'static> Element for AnimationElement<E> {type RequestLayoutState = AnyElement;type PrepaintState = ();@@ -224,10 +443,7 @@ impl<E: IntoElement + 'static> Element for AnimationElement<E> {};let delta = (self.animations[animation_ix].easing)(delta);- debug_assert!(- (0.0..=1.0).contains(&delta),- "delta should always be between 0 and 1"- );+ debug_assert!(delta.is_finite(), "animated value should be finite");let element = self.element.take().expect("should only be called once");let mut element = (self.animator)(element, animation_ix, delta).into_any_element();@@ -344,8 +560,8 @@ mod tests {use std::{cell::RefCell, rc::Rc, time::Duration};use crate::{- Animation, Context, InteractiveElement, Render, TestAppContext, WindowHandle, div,- prelude::*, px, size,+ Animation, Context, InteractiveElement, Pixels, Render, SpringAnimation, SpringConfig,+ TestAppContext, WindowHandle, div, prelude::*, px, size,};use super::*;@@ -361,6 +577,30 @@ mod tests {second_deltas: Rc<RefCell<Vec<f32>>>,}+ struct SpringAnimationTestView {+ target: Pixels,+ initial: Option<Pixels>,+ playback: SpringPlayback,+ rendered_values: Rc<RefCell<Vec<Pixels>>>,+ }++ impl Render for SpringAnimationTestView {+ fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {+ let rendered_values = self.rendered_values.clone();+ let mut animation = SpringAnimation::new(SpringConfig::new(100.0, 2.0, 1.0))+ .to(self.target)+ .with_epsilon(0.01)+ .playback(self.playback);+ if let Some(initial) = self.initial {+ animation = animation.from(initial);+ }+ div().with_spring("spring-animation", animation, move |this, value| {+ rendered_values.borrow_mut().push(value);+ this.left(value)+ })+ }+ }+impl Render for SyncedAnimationTestView {fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {let record_deltas = |deltas: Rc<RefCell<Vec<f32>>>| {@@ -459,6 +699,225 @@ mod tests {);}+ #[test]+ fn test_spring_animation_parent() {+ div()+ .id("id")+ .with_spring(+ "spring-animation",+ SpringAnimation::new(SpringConfig::new(100.0, 10.0, 1.0))+ .to(px(10.0))+ .from(px(0.0)),+ |element, value| element.left(value),+ )+ .child(div());+ }++ #[gpui::test]+ fn test_spring_animation_preserves_velocity_when_retargeted(cx: &mut TestAppContext) {+ let rendered_values = Rc::new(RefCell::new(Vec::new()));+ let window = cx.open_window(size(px(100.0), px(100.0)), {+ let rendered_values = rendered_values.clone();+ move |_, _| SpringAnimationTestView {+ target: px(0.0),+ initial: None,+ playback: SpringPlayback::Running,+ rendered_values,+ }+ });+ cx.run_until_parked();+ assert_eq!(*rendered_values.borrow(), vec![px(0.0)]);++ window+ .update(cx, |view, _, cx| {+ view.target = px(100.0);+ cx.notify();+ })+ .unwrap();+ cx.run_until_parked();++ cx.executor().advance_clock(Duration::from_millis(50));+ assert!(simulate_next_frame(&window, cx) > 0);+ let value_before_retargeting = *rendered_values.borrow().last().unwrap();+ assert!(value_before_retargeting > px(0.0));+ assert!(value_before_retargeting < px(100.0));++ window+ .update(cx, |view, _, cx| {+ view.target = px(0.0);+ cx.notify();+ })+ .unwrap();+ cx.run_until_parked();++ cx.executor().advance_clock(Duration::from_millis(5));+ assert!(simulate_next_frame(&window, cx) > 0);+ let value_after_retargeting = *rendered_values.borrow().last().unwrap();+ assert!(value_after_retargeting > value_before_retargeting);+ }++ #[gpui::test]+ fn test_paused_spring_resumes_with_its_velocity(cx: &mut TestAppContext) {+ let rendered_values = Rc::new(RefCell::new(Vec::new()));+ let window = cx.open_window(size(px(100.0), px(100.0)), {+ let rendered_values = rendered_values.clone();+ move |_, _| SpringAnimationTestView {+ target: px(0.0),+ initial: None,+ playback: SpringPlayback::Running,+ rendered_values,+ }+ });+ cx.run_until_parked();++ window+ .update(cx, |view, _, cx| {+ view.target = px(100.0);+ cx.notify();+ })+ .unwrap();+ cx.run_until_parked();+ cx.executor().advance_clock(Duration::from_millis(50));+ assert!(simulate_next_frame(&window, cx) > 0);++ window+ .update(cx, |view, _, cx| {+ view.target = px(0.0);+ view.playback = SpringPlayback::Paused;+ cx.notify();+ })+ .unwrap();+ cx.run_until_parked();+ let paused_value = *rendered_values.borrow().last().unwrap();++ cx.executor().advance_clock(Duration::from_millis(500));+ assert!(simulate_next_frame(&window, cx) > 0);+ assert_eq!(*rendered_values.borrow().last().unwrap(), paused_value);+ assert_eq!(simulate_next_frame(&window, cx), 0);++ window+ .update(cx, |view, _, cx| {+ view.playback = SpringPlayback::Running;+ cx.notify();+ })+ .unwrap();+ cx.run_until_parked();+ cx.executor().advance_clock(Duration::from_millis(5));+ assert!(simulate_next_frame(&window, cx) > 0);+ assert!(*rendered_values.borrow().last().unwrap() > paused_value);+ }++ #[gpui::test]+ fn test_stopped_spring_resumes_without_velocity(cx: &mut TestAppContext) {+ let rendered_values = Rc::new(RefCell::new(Vec::new()));+ let window = cx.open_window(size(px(100.0), px(100.0)), {+ let rendered_values = rendered_values.clone();+ move |_, _| SpringAnimationTestView {+ target: px(0.0),+ initial: None,+ playback: SpringPlayback::Running,+ rendered_values,+ }+ });+ cx.run_until_parked();++ window+ .update(cx, |view, _, cx| {+ view.target = px(1_000_000.0);+ cx.notify();+ })+ .unwrap();+ cx.run_until_parked();+ cx.executor().advance_clock(Duration::from_millis(50));+ assert!(simulate_next_frame(&window, cx) > 0);++ window+ .update(cx, |view, _, cx| {+ view.target = px(0.0);+ view.playback = SpringPlayback::Stopped;+ cx.notify();+ })+ .unwrap();+ cx.run_until_parked();+ let stopped_value = *rendered_values.borrow().last().unwrap();++ cx.executor().advance_clock(Duration::from_millis(500));+ assert!(simulate_next_frame(&window, cx) > 0);+ assert_eq!(*rendered_values.borrow().last().unwrap(), stopped_value);+ assert_eq!(simulate_next_frame(&window, cx), 0);++ window+ .update(cx, |view, _, cx| {+ view.target = stopped_value;+ view.playback = SpringPlayback::Running;+ cx.notify();+ })+ .unwrap();+ cx.run_until_parked();+ assert_eq!(*rendered_values.borrow().last().unwrap(), stopped_value);+ assert_eq!(simulate_next_frame(&window, cx), 0);+ }++ #[gpui::test]+ fn test_cancelled_and_completed_springs_resolve_their_endpoints(cx: &mut TestAppContext) {+ let rendered_values = Rc::new(RefCell::new(Vec::new()));+ let window = cx.open_window(size(px(100.0), px(100.0)), {+ let rendered_values = rendered_values.clone();+ move |_, _| SpringAnimationTestView {+ target: px(100.0),+ initial: Some(px(20.0)),+ playback: SpringPlayback::Running,+ rendered_values,+ }+ });+ cx.run_until_parked();+ assert_eq!(*rendered_values.borrow(), vec![px(20.0)]);++ cx.executor().advance_clock(Duration::from_millis(50));+ assert!(simulate_next_frame(&window, cx) > 0);+ assert!(*rendered_values.borrow().last().unwrap() > px(20.0));++ window+ .update(cx, |view, _, cx| {+ view.playback = SpringPlayback::Cancelled;+ cx.notify();+ })+ .unwrap();+ cx.run_until_parked();+ assert_eq!(*rendered_values.borrow().last().unwrap(), px(20.0));+ assert!(simulate_next_frame(&window, cx) > 0);+ assert_eq!(simulate_next_frame(&window, cx), 0);++ window+ .update(cx, |view, _, cx| {+ view.playback = SpringPlayback::Completed;+ cx.notify();+ })+ .unwrap();+ cx.run_until_parked();+ assert_eq!(*rendered_values.borrow().last().unwrap(), px(100.0));+ assert_eq!(simulate_next_frame(&window, cx), 0);+ }++ #[gpui::test]+ fn test_spring_animation_respects_reduced_motion(cx: &mut TestAppContext) {+ cx.update(|cx| cx.set_reduce_motion(true));+ let rendered_values = Rc::new(RefCell::new(Vec::new()));+ let window = cx.open_window(size(px(100.0), px(100.0)), {+ let rendered_values = rendered_values.clone();+ move |_, _| SpringAnimationTestView {+ target: px(100.0),+ initial: None,+ playback: SpringPlayback::Running,+ rendered_values,+ }+ });+ cx.run_until_parked();++ assert_eq!(*rendered_values.borrow(), vec![px(100.0)]);+ assert_eq!(simulate_next_frame(&window, cx), 0);+ }+#[gpui::test]fn test_repeating_animation_schedules_animation_frames(cx: &mut TestAppContext) {let (rendered_deltas, window) = open_test_window(cx);diff --git a/crates/gpui/src/gpui.rs b/crates/gpui/src/gpui.rsindex 1cb41d46f7f..04264a6e153 100644--- a/crates/gpui/src/gpui.rs+++ b/crates/gpui/src/gpui.rs@@ -47,6 +47,7 @@ pub mod profiler;pub mod queue;mod scene;mod shared_uri;+mod spring;mod style;mod styled;mod subscription;@@ -104,6 +105,7 @@ pub use global::*;pub use gpui_macros::{AppContext, IntoElement, Render, VisualContext, bench, property_test, register_action, test,};+pub use spring::*;/// Defines a Criterion benchmark group for benchmarks annotated with [`gpui::bench`].///diff --git a/crates/gpui/src/spring.rs b/crates/gpui/src/spring.rsnew file mode 100644index 00000000000..efc878061be--- /dev/null+++ b/crates/gpui/src/spring.rs@@ -0,0 +1,830 @@+use std::{ops::RangeInclusive, time::Duration};++use crate::{Hsla, Pixels, Rems, Rgba};++const CRITICAL_DAMPING_TOLERANCE: f32 = 1e-4;+const DEFAULT_SPRING_EPSILON: f32 = 0.001;++/// The physical parameters of a damped harmonic oscillator.+///+/// `stiffness` and `mass` must be finite and positive. `damping` must be finite+/// and non-negative.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct SpringConfig {+ /// The spring stiffness, conventionally written as $k$.+ pub stiffness: f32,+ /// The viscous damping coefficient, conventionally written as $c$.+ pub damping: f32,+ /// The moving mass, conventionally written as $m$.+ pub mass: f32,+}++impl SpringConfig {+ /// Creates a spring from its physical parameters.+ pub const fn new(stiffness: f32, damping: f32, mass: f32) -> Self {+ Self {+ stiffness,+ damping,+ mass,+ }+ }++ /// Returns the natural angular frequency and damping ratio $(\omega_0, \zeta)$.+ pub fn canonical(&self) -> (f32, f32) {+ let natural_frequency = (self.stiffness / self.mass).sqrt();+ let damping_ratio = self.damping / (2.0 * (self.stiffness * self.mass).sqrt());+ (natural_frequency, damping_ratio)+ }++ /// Advances a spring toward a target that remains fixed for `delta_time`.+ ///+ /// This analytic step is independent of frame rate and preserves velocity,+ /// allowing an interrupted spring to be retargeted without restarting it.+ pub fn step(&self, state: SpringState, target: f32, delta_time: f32) -> SpringState {+ let propagator = self.propagator(delta_time);+ let displacement = state.position - target;++ SpringState {+ position: target + propagator[0][0] * displacement + propagator[0][1] * state.velocity,+ velocity: propagator[1][0] * displacement + propagator[1][1] * state.velocity,+ }+ }++ /// Advances a spring toward a target moving at a constant velocity.+ ///+ /// A first-order hold avoids the frame-rate-dependent lag introduced by+ /// treating a dragged target as stationary between frames.+ pub fn step_ramp(+ &self,+ state: SpringState,+ target: f32,+ target_velocity: f32,+ delta_time: f32,+ ) -> SpringState {+ let (natural_frequency, damping_ratio) = self.canonical();+ let steady_state_lag = -2.0 * damping_ratio * target_velocity / natural_frequency;+ let displacement = state.position - target - steady_state_lag;+ let velocity = state.velocity - target_velocity;+ let propagator = self.propagator(delta_time);+ let target = target + target_velocity * delta_time;++ SpringState {+ position: target+ + steady_state_lag+ + propagator[0][0] * displacement+ + propagator[0][1] * velocity,+ velocity: target_velocity+ + propagator[1][0] * displacement+ + propagator[1][1] * velocity,+ }+ }++ /// Returns the exact state-transition matrix for a constant target.+ ///+ /// Materializing this matrix is useful when many springs share the same+ /// configuration and frame delta. A matrix must not be reused when the+ /// frame delta changes.+ pub fn propagator(&self, delta_time: f32) -> [[f32; 2]; 2] {+ let (natural_frequency, damping_ratio) = self.canonical();++ if damping_ratio < 1.0 - CRITICAL_DAMPING_TOLERANCE {+ let decay = damping_ratio * natural_frequency;+ let damped_frequency = natural_frequency * (1.0 - damping_ratio * damping_ratio).sqrt();+ let exponential = (-decay * delta_time).exp();+ let (sine, cosine) = (damped_frequency * delta_time).sin_cos();+ let sine_over_frequency = sine / damped_frequency;++ [+ [+ exponential * (cosine + decay * sine_over_frequency),+ exponential * sine_over_frequency,+ ],+ [+ -exponential * natural_frequency * natural_frequency * sine_over_frequency,+ exponential * (cosine - decay * sine_over_frequency),+ ],+ ]+ } else if damping_ratio > 1.0 + CRITICAL_DAMPING_TOLERANCE {+ let root = (damping_ratio * damping_ratio - 1.0).sqrt();+ let root_sum = damping_ratio + root;+ let slow_root = -natural_frequency / root_sum;+ let fast_root = -natural_frequency * root_sum;+ let denominator = slow_root - fast_root;+ let slow_exponential = (slow_root * delta_time).exp();+ let fast_exponential = (fast_root * delta_time).exp();++ [+ [+ (-fast_root * slow_exponential + slow_root * fast_exponential) / denominator,+ (slow_exponential - fast_exponential) / denominator,+ ],+ [+ slow_root * fast_root * (fast_exponential - slow_exponential) / denominator,+ (slow_root * slow_exponential - fast_root * fast_exponential) / denominator,+ ],+ ]+ } else {+ let exponential = (-natural_frequency * delta_time).exp();++ [+ [+ exponential * (1.0 + natural_frequency * delta_time),+ exponential * delta_time,+ ],+ [+ -exponential * natural_frequency * natural_frequency * delta_time,+ exponential * (1.0 - natural_frequency * delta_time),+ ],+ ]+ }+ }++ /// Tests both displacement and velocity against a positional tolerance.+ ///+ /// Velocity is compared with `epsilon * natural_frequency`, giving it the+ /// corresponding animated-units-per-second scale.+ pub fn is_settled(&self, state: SpringState, target: f32, epsilon: f32) -> bool {+ let (natural_frequency, _) = self.canonical();+ epsilon.is_finite()+ && epsilon >= 0.0+ && (state.position - target).abs() <= epsilon+ && state.velocity.abs() <= epsilon * natural_frequency+ }++ /// Returns a conservative time after which the spring remains settled.+ ///+ /// An undamped spring has no finite settling time and returns+ /// [`Duration::MAX`].+ pub fn settle_time(&self, state: SpringState, target: f32, epsilon: f32) -> Duration {+ let displacement = state.position - target;+ if displacement == 0.0 && state.velocity == 0.0 {+ return Duration::ZERO;+ }++ let (natural_frequency, damping_ratio) = self.canonical();+ if !natural_frequency.is_finite()+ || natural_frequency <= 0.0+ || !damping_ratio.is_finite()+ || damping_ratio <= 0.0+ || !epsilon.is_finite()+ || epsilon <= 0.0+ {+ return Duration::MAX;+ }++ let velocity_threshold = epsilon * natural_frequency;++ if damping_ratio < 1.0 - CRITICAL_DAMPING_TOLERANCE {+ let decay = damping_ratio * natural_frequency;+ let damped_frequency = natural_frequency * (1.0 - damping_ratio * damping_ratio).sqrt();+ let sine_coefficient = (state.velocity + decay * displacement) / damped_frequency;+ let position_envelope = displacement.hypot(sine_coefficient);+ let velocity_cosine = damped_frequency * sine_coefficient - decay * displacement;+ let velocity_sine = -damped_frequency * displacement - decay * sine_coefficient;+ let velocity_envelope = velocity_cosine.hypot(velocity_sine);++ find_settle_time(+ epsilon,+ velocity_threshold,+ 0.0,+ natural_frequency,+ move |time| {+ let exponential = (-decay * time).exp();+ (+ position_envelope * exponential,+ velocity_envelope * exponential,+ )+ },+ )+ } else if damping_ratio > 1.0 + CRITICAL_DAMPING_TOLERANCE {+ let root = (damping_ratio * damping_ratio - 1.0).sqrt();+ let root_sum = damping_ratio + root;+ let slow_root = -natural_frequency / root_sum;+ let fast_root = -natural_frequency * root_sum;+ let denominator = slow_root - fast_root;+ let slow_coefficient = (state.velocity - fast_root * displacement) / denominator;+ let fast_coefficient = (slow_root * displacement - state.velocity) / denominator;++ find_settle_time(+ epsilon,+ velocity_threshold,+ 0.0,+ natural_frequency,+ move |time| {+ let slow_term = slow_coefficient.abs() * (slow_root * time).exp();+ let fast_term = fast_coefficient.abs() * (fast_root * time).exp();+ (+ slow_term + fast_term,+ slow_root.abs() * slow_term + fast_root.abs() * fast_term,+ )+ },+ )+ } else {+ let linear_coefficient = state.velocity + natural_frequency * displacement;+ let position_constant = displacement.abs();+ let position_linear = linear_coefficient.abs();+ let velocity_constant = (linear_coefficient - natural_frequency * displacement).abs();+ let velocity_linear = natural_frequency * linear_coefficient.abs();+ let position_decay_start =+ envelope_decay_start(position_constant, position_linear, natural_frequency);+ let velocity_decay_start =+ envelope_decay_start(velocity_constant, velocity_linear, natural_frequency);++ find_settle_time(+ epsilon,+ velocity_threshold,+ position_decay_start.max(velocity_decay_start),+ natural_frequency,+ move |time| {+ let exponential = (-natural_frequency * time).exp();+ (+ (position_constant + position_linear * time) * exponential,+ (velocity_constant + velocity_linear * time) * exponential,+ )+ },+ )+ }+ }+}++/// The instantaneous position and velocity of a spring.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct SpringState {+ /// The current value in the animated unit.+ pub position: f32,+ /// The current value's change per second.+ pub velocity: f32,+}++/// A value that can be targeted by a one-dimensional spring.+///+/// Implementations may project the spring coordinate into a richer output,+/// allowing a discrete state or a path through a multidimensional value to be+/// driven by one spring.+pub trait SpringTarget: 'static {+ /// The value supplied to the spring animator.+ type Output;++ /// Returns the target in the spring's coordinate space.+ fn target(&self) -> f32;++ /// Projects a spring coordinate into the animated output.+ fn resolve(&self, value: f32) -> Self::Output;+}++impl SpringTarget for f32 {+ type Output = f32;++ fn target(&self) -> f32 {+ *self+ }++ fn resolve(&self, value: f32) -> Self::Output {+ value+ }+}++impl SpringTarget for Pixels {+ type Output = Pixels;++ fn target(&self) -> f32 {+ self.as_f32()+ }++ fn resolve(&self, value: f32) -> Self::Output {+ Pixels::from(value)+ }+}++impl SpringTarget for Rems {+ type Output = Rems;++ fn target(&self) -> f32 {+ self.0+ }++ fn resolve(&self, value: f32) -> Self::Output {+ Rems(value)+ }+}++impl SpringTarget for bool {+ type Output = AnimationPhase;++ fn target(&self) -> f32 {+ if *self { 1.0 } else { 0.0 }+ }++ fn resolve(&self, value: f32) -> Self::Output {+ AnimationPhase(value)+ }+}++/// A potentially overshooting coordinate within an animation.+///+/// Phases are not restricted to 0..1. Multi-stage animations can assign each+/// stage its own coordinate and interpolate over ranges such as 1..=2.+#[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd)]+pub struct AnimationPhase(+ /// The unbounded phase coordinate.+ pub f32,+);++impl AnimationPhase {+ /// Restricts this phase to the bounds of a range.+ pub fn clamp(self, range: RangeInclusive<f32>) -> Self {+ let (first, second) = range.into_inner();+ Self(self.0.clamp(first.min(second), first.max(second)))+ }++ /// Interpolates between values using 0 and 1 as their phase coordinates.+ pub fn interpolate<T: Interpolate>(self, from: T, to: T) -> T {+ T::interpolate(from, to, self.0)+ }++ /// Interpolates between values without extrapolating beyond 0 and 1.+ pub fn interpolate_clamped<T: Interpolate>(self, from: T, to: T) -> T {+ T::interpolate(from, to, self.0.clamp(0.0, 1.0))+ }++ /// Interpolates between values assigned to arbitrary phase coordinates.+ pub fn interpolate_between<T: Interpolate>(+ self,+ range: RangeInclusive<f32>,+ from: T,+ to: T,+ ) -> T {+ let (start, end) = range.into_inner();+ let phase = if start == end {+ if self.0 < start { 0.0 } else { 1.0 }+ } else {+ (self.0 - start) / (end - start)+ };+ T::interpolate(from, to, phase)+ }++ /// Interpolates over arbitrary phase coordinates without extrapolating.+ pub fn interpolate_between_clamped<T: Interpolate>(+ self,+ range: RangeInclusive<f32>,+ from: T,+ to: T,+ ) -> T {+ let (start, end) = range.into_inner();+ let phase = if start == end {+ if self.0 < start { 0.0 } else { 1.0 }+ } else {+ ((self.0 - start) / (end - start)).clamp(0.0, 1.0)+ };+ T::interpolate(from, to, phase)+ }+}++impl From<f32> for AnimationPhase {+ fn from(value: f32) -> Self {+ Self(value)+ }+}++impl From<bool> for AnimationPhase {+ fn from(value: bool) -> Self {+ Self(if value { 1.0 } else { 0.0 })+ }+}++impl SpringTarget for AnimationPhase {+ type Output = AnimationPhase;++ fn target(&self) -> f32 {+ self.0+ }++ fn resolve(&self, value: f32) -> Self::Output {+ Self(value)+ }+}++/// A value that supports linear interpolation and extrapolation.+pub trait Interpolate: Sized {+ /// Resolves the value at `phase`, where 0 is `from` and 1 is `to`.+ fn interpolate(from: Self, to: Self, phase: f32) -> Self;+}++impl Interpolate for f32 {+ fn interpolate(from: Self, to: Self, phase: f32) -> Self {+ from + (to - from) * phase+ }+}++impl Interpolate for Pixels {+ fn interpolate(from: Self, to: Self, phase: f32) -> Self {+ from + (to - from) * phase+ }+}++impl Interpolate for Rems {+ fn interpolate(from: Self, to: Self, phase: f32) -> Self {+ from + (to - from) * phase+ }+}++impl Interpolate for Rgba {+ fn interpolate(from: Self, to: Self, phase: f32) -> Self {+ Self {+ r: f32::interpolate(from.r, to.r, phase),+ g: f32::interpolate(from.g, to.g, phase),+ b: f32::interpolate(from.b, to.b, phase),+ a: f32::interpolate(from.a, to.a, phase),+ }+ }+}++impl Interpolate for Hsla {+ fn interpolate(from: Self, to: Self, phase: f32) -> Self {+ let hue_delta = (to.h - from.h + 0.5).rem_euclid(1.0) - 0.5;+ Self {+ h: (from.h + hue_delta * phase).rem_euclid(1.0),+ s: f32::interpolate(from.s, to.s, phase),+ l: f32::interpolate(from.l, to.l, phase),+ a: f32::interpolate(from.a, to.a, phase),+ }+ }+}++/// Controls how a spring advances and resolves its presentation value.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub enum SpringPlayback {+ /// Advances toward the latest target, preserving velocity across retargets.+ #[default]+ Running,+ /// Holds the current position and velocity until playback resumes.+ Paused,+ /// Holds the current position and discards velocity.+ Stopped,+ /// Snaps to the latest target and discards velocity.+ Completed,+ /// Returns to the initial value and discards velocity.+ Cancelled,+}++/// A stateful spring animation targeting a value or projected path.+#[derive(Clone, Debug)]+pub struct SpringAnimation<T = ()> {+ pub(crate) config: SpringConfig,+ pub(crate) target: T,+ pub(crate) epsilon: f32,+ pub(crate) initial: Option<f32>,+ pub(crate) playback: SpringPlayback,+}++impl SpringAnimation<()> {+ /// Creates a spring animation builder.+ pub fn new(config: SpringConfig) -> Self {+ Self {+ config,+ target: (),+ epsilon: DEFAULT_SPRING_EPSILON,+ initial: None,+ playback: SpringPlayback::Running,+ }+ }++ /// Sets the value or path targeted by this spring.+ pub fn to<T: SpringTarget>(self, target: T) -> SpringAnimation<T> {+ let SpringAnimation {+ config,+ target: (),+ epsilon,+ initial,+ playback,+ } = self;+ SpringAnimation {+ config,+ target,+ epsilon,+ initial,+ playback,+ }+ }+}++impl<T> SpringAnimation<T> {+ /// Sets the settling tolerance in the target's scalar coordinate space.+ pub fn with_epsilon(mut self, epsilon: f32) -> Self {+ self.epsilon = epsilon;+ self+ }++ /// Sets how the spring advances or resolves its current value.+ pub fn playback(mut self, playback: SpringPlayback) -> Self {+ self.playback = playback;+ self+ }+}++impl<T: SpringTarget> SpringAnimation<T> {+ /// Sets the coordinate used when this element has no prior spring state.+ pub fn from(mut self, initial: T) -> Self {+ self.initial = Some(initial.target());+ self+ }+}++/// Adapts a spring starting at zero with no velocity to GPUI's duration-based easing API.+///+/// The returned easing can overshoot the normalized 0..1 output range. Retargeting+/// this duration-based form restarts the spring; use [`SpringConfig::step`] when+/// preserving velocity matters.+pub fn sampled_easing(config: SpringConfig, epsilon: f32) -> (Duration, impl Fn(f32) -> f32) {+ let initial_state = SpringState {+ position: 0.0,+ velocity: 0.0,+ };+ let duration = config.settle_time(initial_state, 1.0, epsilon);+ let duration_seconds = duration.as_secs_f32();++ (duration, move |progress| {+ if progress <= 0.0 {+ 0.0+ } else if progress >= 1.0 {+ 1.0+ } else {+ config+ .step(initial_state, 1.0, progress * duration_seconds)+ .position+ }+ })+}++fn envelope_decay_start(constant: f32, linear: f32, decay: f32) -> f32 {+ if linear == 0.0 {+ 0.0+ } else {+ (1.0 / decay - constant / linear).max(0.0)+ }+}++fn find_settle_time(+ position_threshold: f32,+ velocity_threshold: f32,+ decay_start: f32,+ natural_frequency: f32,+ envelope: impl Fn(f32) -> (f32, f32),+) -> Duration {+ let is_below_threshold = |time| {+ let (position, velocity) = envelope(time);+ position <= position_threshold && velocity <= velocity_threshold+ };++ if is_below_threshold(decay_start) {+ return duration_from_secs(decay_start);+ }++ let mut lower_bound = decay_start;+ let mut upper_bound = decay_start.max(natural_frequency.recip());+ while !is_below_threshold(upper_bound) {+ lower_bound = upper_bound;+ upper_bound *= 2.0;+ if !upper_bound.is_finite() {+ return Duration::MAX;+ }+ }++ for _ in 0..32 {+ let midpoint = (lower_bound + upper_bound) / 2.0;+ if is_below_threshold(midpoint) {+ upper_bound = midpoint;+ } else {+ lower_bound = midpoint;+ }+ }++ duration_from_secs(upper_bound)+}++fn duration_from_secs(seconds: f32) -> Duration {+ if !seconds.is_finite() || seconds >= Duration::MAX.as_secs_f32() {+ Duration::MAX+ } else if seconds <= 0.0 {+ Duration::ZERO+ } else {+ Duration::from_secs_f32(seconds)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ const EPSILON: f32 = 1e-4;++ #[test]+ fn spring_targets_resolve_typed_outputs() {+ assert_eq!(12.0_f32.target(), 12.0);+ assert_eq!(12.0_f32.resolve(14.0), 14.0);+ assert_eq!(Pixels::from(12.0).target(), 12.0);+ assert_eq!(Pixels::from(12.0).resolve(14.0), Pixels::from(14.0));+ assert_eq!(false.target(), 0.0);+ assert_eq!(true.target(), 1.0);+ assert_eq!(true.resolve(1.25), AnimationPhase(1.25));+ }++ #[test]+ fn animation_phases_interpolate_over_arbitrary_ranges() {+ let phase = AnimationPhase(1.5);+ assert_eq!(phase.interpolate_between(1.0..=2.0, 10.0, 20.0), 15.0);+ assert_eq!(+ phase.interpolate_between_clamped(2.0..=3.0, 10.0, 20.0),+ 10.0+ );+ assert_eq!(+ AnimationPhase(3.5).interpolate_between(2.0..=3.0, 10.0, 20.0),+ 25.0+ );+ }++ #[test]+ fn hsla_interpolation_takes_the_shortest_hue_path() {+ let from = Hsla {+ h: 0.9,+ s: 0.5,+ l: 0.5,+ a: 1.0,+ };+ let to = Hsla {+ h: 0.1,+ s: 1.0,+ l: 0.75,+ a: 0.5,+ };+ let result = AnimationPhase(0.5).interpolate(from, to);++ assert!(result.h < EPSILON || (1.0 - result.h) < EPSILON);+ assert!((result.s - 0.75).abs() < EPSILON);+ assert!((result.l - 0.625).abs() < EPSILON);+ assert!((result.a - 0.75).abs() < EPSILON);+ }++ #[test]+ fn propagators_compose_and_have_expected_determinant() {+ for damping_ratio in [0.4, 1.0, 1.5] {+ let natural_frequency = 12.0;+ let config = SpringConfig::new(+ natural_frequency * natural_frequency,+ 2.0 * damping_ratio * natural_frequency,+ 1.0,+ );+ let first = config.propagator(0.013);+ let second = config.propagator(0.021);+ let combined = multiply(second, first);+ let direct = config.propagator(0.034);++ for row in 0..2 {+ for column in 0..2 {+ assert!(+ (combined[row][column] - direct[row][column]).abs() < 2e-4,+ "{damping_ratio}: {combined:?} != {direct:?}"+ );+ }+ }++ let determinant = direct[0][0] * direct[1][1] - direct[0][1] * direct[1][0];+ let expected = (-2.0 * damping_ratio * natural_frequency * 0.034).exp();+ assert!((determinant - expected).abs() < 2e-4);+ }+ }++ #[test]+ fn step_preserves_semigroup_for_every_damping_regime() {+ let state = SpringState {+ position: -3.0,+ velocity: 5.0,+ };+ for damping in [4.0, 20.0, 40.0] {+ let config = SpringConfig::new(100.0, damping, 1.0);+ let stepped = config.step(config.step(state, 7.0, 0.013), 7.0, 0.021);+ let direct = config.step(state, 7.0, 0.034);++ assert!((stepped.position - direct.position).abs() < 2e-4);+ assert!((stepped.velocity - direct.velocity).abs() < 2e-4);+ }+ }++ #[test]+ fn ramp_tracks_steady_state_lag() {+ let natural_frequency = 10.0;+ let damping_ratio = 0.8;+ let target_velocity = 3.0;+ let config = SpringConfig::new(+ natural_frequency * natural_frequency,+ 2.0 * damping_ratio * natural_frequency,+ 1.0,+ );+ let lag = -2.0 * damping_ratio * target_velocity / natural_frequency;+ let state = SpringState {+ position: lag,+ velocity: target_velocity,+ };+ let next = config.step_ramp(state, 0.0, target_velocity, 0.25);++ assert!((next.position - (target_velocity * 0.25 + lag)).abs() < EPSILON);+ assert!((next.velocity - target_velocity).abs() < EPSILON);+ }++ #[test]+ fn settling_requires_low_velocity() {+ let config = SpringConfig::new(100.0, 10.0, 1.0);+ assert!(!config.is_settled(+ SpringState {+ position: 1.0,+ velocity: 1.0,+ },+ 1.0,+ 0.01,+ ));+ assert!(config.is_settled(+ SpringState {+ position: 1.005,+ velocity: 0.05,+ },+ 1.0,+ 0.01,+ ));+ }++ #[test]+ fn settle_time_is_conservative_for_every_damping_regime() {+ let initial_state = SpringState {+ position: -2.0,+ velocity: 4.0,+ };+ for damping in [4.0, 20.0, 40.0] {+ let config = SpringConfig::new(100.0, damping, 1.0);+ let duration = config.settle_time(initial_state, 3.0, 0.001);+ assert_ne!(duration, Duration::MAX);++ for additional_time in [0.0, 0.1, 1.0] {+ let state =+ config.step(initial_state, 3.0, duration.as_secs_f32() + additional_time);+ assert!(+ config.is_settled(state, 3.0, 0.001),+ "{damping}: {duration:?} produced {state:?}"+ );+ }+ }+ }++ #[test]+ fn settle_time_accounts_for_motion_outside_an_instantaneous_tolerance() {+ let config = SpringConfig::new(100.0, 2.0, 1.0);+ let state = SpringState {+ position: 1.125,+ velocity: 1.25,+ };+ assert!(config.is_settled(state, 1.0, 0.125));++ let duration = config.settle_time(state, 1.0, 0.125);+ assert!(duration > Duration::ZERO);+ assert!(config.is_settled(config.step(state, 1.0, duration.as_secs_f32()), 1.0, 0.125,));+ }++ #[test]+ fn undamped_spring_never_settles() {+ let config = SpringConfig::new(100.0, 0.0, 1.0);+ assert_eq!(+ config.settle_time(+ SpringState {+ position: 0.0,+ velocity: 0.0,+ },+ 1.0,+ 0.001,+ ),+ Duration::MAX+ );+ }++ #[test]+ fn sampled_easing_has_exact_endpoints_and_can_overshoot() {+ let config = SpringConfig::new(100.0, 6.0, 1.0);+ let (duration, easing) = sampled_easing(config, 0.001);++ assert_ne!(duration, Duration::MAX);+ assert_eq!(easing(0.0), 0.0);+ assert_eq!(easing(1.0), 1.0);+ assert!((1..100).any(|step| easing(step as f32 / 100.0) > 1.0));+ }++ fn multiply(left: [[f32; 2]; 2], right: [[f32; 2]; 2]) -> [[f32; 2]; 2] {+ [+ [+ left[0][0] * right[0][0] + left[0][1] * right[1][0],+ left[0][0] * right[0][1] + left[0][1] * right[1][1],+ ],+ [+ left[1][0] * right[0][0] + left[1][1] * right[1][0],+ left[1][0] * right[0][1] + left[1][1] * right[1][1],+ ],+ ]+ }+}