Skip to main content

waft_physics/
spring_simulation.rs

1//! Flutter counterpart: `physics/spring_simulation.dart`.
2
3use std::fmt::{self, Debug};
4use std::time::Duration;
5
6use crate::{Simulation, Tolerance, near_zero};
7
8/// Structure that describes a spring's constants.
9///
10/// Used to configure a [`SpringSimulation`].
11#[derive(Clone, Copy)]
12pub struct SpringDescription {
13    /// The mass of the spring (m).
14    ///
15    /// The units are arbitrary, but all springs within a system should use
16    /// the same mass units.
17    ///
18    /// The greater the mass, the larger the amplitude of oscillation,
19    /// and the longer the time to return to the equilibrium position.
20    pub mass: f64,
21
22    /// The spring constant (k).
23    ///
24    /// The units of stiffness are M/T², where M is the mass unit used for the
25    /// value of the [`mass`](SpringDescription::mass) property, and T is the
26    /// time unit used for driving the [`SpringSimulation`].
27    ///
28    /// Stiffness defines the spring constant, which measures the strength of
29    /// the spring. A stiff spring applies more force to the object that is
30    /// attached for some deviation from the rest position.
31    pub stiffness: f64,
32
33    /// The damping coefficient (c).
34    ///
35    /// It is a pure number without physical meaning and describes the
36    /// oscillation and decay of a system after being disturbed. The larger the
37    /// damping, the fewer oscillations and smaller the amplitude of the elastic
38    /// motion.
39    ///
40    /// Do not confuse the damping _coefficient_ (c) with the damping _ratio_
41    /// (ζ). To create a [`SpringDescription`] with a damping ratio, use
42    /// [`with_damping_ratio`](SpringDescription::with_damping_ratio).
43    ///
44    /// The units of the damping coefficient are M/T, where M is the mass unit
45    /// used for the value of the [`mass`](SpringDescription::mass) property,
46    /// and T is the time unit used for driving the [`SpringSimulation`].
47    pub damping: f64,
48}
49
50impl SpringDescription {
51    /// Creates a spring given the mass, stiffness, and the damping coefficient.
52    ///
53    /// See [`mass`](SpringDescription::mass),
54    /// [`stiffness`](SpringDescription::stiffness), and
55    /// [`damping`](SpringDescription::damping) for the units of the arguments.
56    pub const fn new(mass: f64, stiffness: f64, damping: f64) -> SpringDescription {
57        SpringDescription {
58            mass,
59            stiffness,
60            damping,
61        }
62    }
63
64    /// Creates a spring given the mass (m), stiffness (k), and damping ratio
65    /// (ζ). The damping ratio describes a gradual reduction in a spring
66    /// oscillation. By using the damping ratio, you can define how rapidly the
67    /// oscillations decay from one bounce to the next.
68    ///
69    /// The damping ratio is especially useful when trying to determining the
70    /// type of spring to create. A ratio of 1.0 creates a critically damped
71    /// spring, > 1.0 creates an overdamped spring and < 1.0 an underdamped one.
72    ///
73    /// See [`mass`](SpringDescription::mass) and
74    /// [`stiffness`](SpringDescription::stiffness) for the units for those
75    /// arguments. The damping ratio is unitless.
76    pub fn with_damping_ratio(mass: f64, stiffness: f64) -> SpringDescription {
77        SpringDescription::with_damping_ratio_value(mass, stiffness, 1.0)
78    }
79
80    /// Dart's `withDampingRatio` `ratio` argument (default 1.0).
81    pub fn with_damping_ratio_value(mass: f64, stiffness: f64, ratio: f64) -> SpringDescription {
82        SpringDescription {
83            mass,
84            stiffness,
85            damping: ratio * 2.0 * (mass * stiffness).sqrt(),
86        }
87    }
88
89    /// Creates a [`SpringDescription`] based on a desired animation duration
90    /// and bounce.
91    ///
92    /// This provides an intuitive way to define a spring based on its visual
93    /// properties, [`duration`](SpringDescription::duration) and
94    /// [`bounce`](SpringDescription::bounce).
95    ///
96    /// This constructor produces the same result as SwiftUI's
97    /// `spring(duration:bounce:blendDuration:)` animation.
98    pub fn with_duration_and_bounce(duration: Duration, bounce: f64) -> SpringDescription {
99        debug_assert!(duration.as_millis() > 0, "Duration must be positive");
100        let duration_in_seconds = duration.as_millis() as f64 / 1000.0;
101        let mass = 1.0;
102        let stiffness = (4.0 * std::f64::consts::PI * std::f64::consts::PI * mass)
103            / duration_in_seconds.powi(2);
104        let damping_ratio = if bounce > 0.0 {
105            1.0 - bounce
106        } else {
107            1.0 / (bounce + 1.0)
108        };
109        let damping = damping_ratio * 2.0 * (mass * stiffness).sqrt();
110        SpringDescription {
111            mass,
112            stiffness,
113            damping,
114        }
115    }
116
117    /// The duration parameter used in
118    /// [`with_duration_and_bounce`](SpringDescription::with_duration_and_bounce).
119    ///
120    /// This value defines the perceptual duration of the spring, controlling
121    /// its overall pace. It is approximately equal to the time it takes for
122    /// the spring to settle, but for highly bouncy springs, it instead
123    /// corresponds to the oscillation period.
124    ///
125    /// This duration does not represent the exact time for the spring to stop
126    /// moving. For example, when [`bounce`](SpringDescription::bounce) is 1,
127    /// the spring oscillates indefinitely, even though duration has a finite
128    /// value. To determine when the motion has effectively stopped within a
129    /// certain tolerance, use [`SpringSimulation::is_done`](Simulation::is_done).
130    ///
131    /// Defaults to 0.5 seconds.
132    pub fn duration(&self) -> Duration {
133        let duration_in_seconds = ((4.0 * std::f64::consts::PI * std::f64::consts::PI * self.mass)
134            / self.stiffness)
135            .sqrt();
136        let milliseconds = (duration_in_seconds * 1000.0).round() as u64;
137        Duration::from_millis(milliseconds)
138    }
139
140    /// The bounce parameter used in
141    /// [`with_duration_and_bounce`](SpringDescription::with_duration_and_bounce).
142    ///
143    /// This value controls how bouncy the spring is:
144    ///
145    ///  * A value of 0 results in a critically damped spring with no oscillation.
146    ///  * Values between 0 and 1 produce underdamping, where the spring oscillates a few times
147    ///    before settling. A value of 1 represents an undamped spring that
148    ///    oscillates indefinitely.
149    ///  * Negative values indicate overdamping, where the motion is slow and
150    ///    resistive, like moving through a thick fluid.
151    ///
152    /// Defaults to 0.
153    pub fn bounce(&self) -> f64 {
154        let damping_ratio = self.damping / (2.0 * (self.mass * self.stiffness).sqrt());
155        if damping_ratio < 1.0 {
156            1.0 - damping_ratio
157        } else {
158            (1.0 / damping_ratio) - 1.0
159        }
160    }
161}
162
163impl Debug for SpringDescription {
164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165        write!(
166            f,
167            "SpringDescription(mass: {:.1}, stiffness: {:.1}, damping: {:.1})",
168            self.mass, self.stiffness, self.damping
169        )
170    }
171}
172
173/// The kind of spring solution that the [`SpringSimulation`] is using to
174/// simulate the spring.
175///
176/// See [`SpringSimulation::spring_type`].
177#[derive(Clone, Copy, PartialEq, Eq)]
178pub enum SpringType {
179    /// A spring that does not bounce and returns to its rest position in the
180    /// shortest possible time.
181    CriticallyDamped,
182    /// A spring that bounces.
183    UnderDamped,
184    /// A spring that does not bounce but takes longer to return to its rest
185    /// position than a [`CriticallyDamped`](SpringType::CriticallyDamped) one.
186    OverDamped,
187}
188
189impl fmt::Display for SpringType {
190    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191        Debug::fmt(self, f)
192    }
193}
194
195impl Debug for SpringType {
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        match self {
198            SpringType::CriticallyDamped => write!(f, "SpringType.criticallyDamped"),
199            SpringType::UnderDamped => write!(f, "SpringType.underDamped"),
200            SpringType::OverDamped => write!(f, "SpringType.overDamped"),
201        }
202    }
203}
204
205/// A spring simulation.
206///
207/// Models a particle attached to a spring that follows Hooke's law.
208pub struct SpringSimulation {
209    end_position: f64,
210    solution: SpringSolution,
211    snap_to_end: bool,
212    /// How close to the actual end of the simulation a value at a particular
213    /// time must be before [`is_done`](Simulation::is_done) considers the
214    /// simulation to be "done".
215    pub tolerance: Tolerance,
216}
217
218impl SpringSimulation {
219    /// Creates a spring simulation from the provided spring description, start
220    /// distance, end distance, and initial velocity.
221    ///
222    /// The units for the start and end distance arguments are arbitrary, but
223    /// must be consistent with the units used for other lengths in the system.
224    ///
225    /// The units for the velocity are L/T, where L is the aforementioned
226    /// arbitrary unit of length, and T is the time unit used for driving the
227    /// [`SpringSimulation`].
228    ///
229    /// If `snap_to_end` is true, [`x`](Simulation::x) will be set to `end` and
230    /// [`dx`](Simulation::dx) to 0 when [`is_done`](Simulation::is_done)
231    /// returns true. This is useful for transitions that require the simulation
232    /// to stop exactly at the end value, since the spring may not naturally
233    /// reach the target precisely. Defaults to false.
234    pub fn new(spring: SpringDescription, start: f64, end: f64, velocity: f64) -> SpringSimulation {
235        SpringSimulation::with_options(
236            spring,
237            start,
238            end,
239            velocity,
240            false,
241            Tolerance::DEFAULT_TOLERANCE,
242        )
243    }
244
245    /// Dart's `snapToEnd` / `tolerance` named arguments.
246    pub fn with_options(
247        spring: SpringDescription,
248        start: f64,
249        end: f64,
250        velocity: f64,
251        snap_to_end: bool,
252        tolerance: Tolerance,
253    ) -> SpringSimulation {
254        SpringSimulation {
255            end_position: end,
256            solution: SpringSolution::new(spring, start - end, velocity),
257            snap_to_end,
258            tolerance,
259        }
260    }
261
262    /// The kind of spring being simulated, for debugging purposes.
263    ///
264    /// This is derived from the [`SpringDescription`] provided to the
265    /// [`SpringSimulation::new`] constructor.
266    pub fn spring_type(&self) -> SpringType {
267        self.solution.spring_type()
268    }
269}
270
271impl Simulation for SpringSimulation {
272    fn x(&self, time: f64) -> f64 {
273        if self.snap_to_end && self.is_done(time) {
274            self.end_position
275        } else {
276            self.end_position + self.solution.x(time)
277        }
278    }
279
280    fn dx(&self, time: f64) -> f64 {
281        if self.snap_to_end && self.is_done(time) {
282            0.0
283        } else {
284            self.solution.dx(time)
285        }
286    }
287
288    fn is_done(&self, time: f64) -> bool {
289        near_zero(self.solution.x(time), self.tolerance.distance)
290            && near_zero(self.solution.dx(time), self.tolerance.velocity)
291    }
292
293    fn tolerance(&self) -> Tolerance {
294        self.tolerance
295    }
296
297    fn set_tolerance(&mut self, tolerance: Tolerance) {
298        self.tolerance = tolerance;
299    }
300}
301
302impl Debug for SpringSimulation {
303    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
304        write!(
305            f,
306            "SpringSimulation(end: {:.1}, {})",
307            self.end_position,
308            self.spring_type()
309        )
310    }
311}
312
313/// A [`SpringSimulation`] where the value of [`x`](Simulation::x) is
314/// guaranteed to have exactly the end value when the simulation
315/// [`is_done`](Simulation::is_done).
316pub struct ScrollSpringSimulation {
317    inner: SpringSimulation,
318}
319
320impl ScrollSpringSimulation {
321    /// Creates a spring simulation from the provided spring description, start
322    /// distance, end distance, and initial velocity.
323    ///
324    /// See [`SpringSimulation::new`] on the superclass for a discussion of the
325    /// arguments' units.
326    pub fn new(
327        spring: SpringDescription,
328        start: f64,
329        end: f64,
330        velocity: f64,
331        tolerance: Tolerance,
332    ) -> ScrollSpringSimulation {
333        ScrollSpringSimulation {
334            inner: SpringSimulation::with_options(spring, start, end, velocity, false, tolerance),
335        }
336    }
337}
338
339impl Simulation for ScrollSpringSimulation {
340    fn x(&self, time: f64) -> f64 {
341        if self.is_done(time) {
342            self.inner.end_position
343        } else {
344            self.inner.x(time)
345        }
346    }
347
348    fn dx(&self, time: f64) -> f64 {
349        self.inner.dx(time)
350    }
351
352    fn is_done(&self, time: f64) -> bool {
353        self.inner.is_done(time)
354    }
355
356    fn tolerance(&self) -> Tolerance {
357        self.inner.tolerance()
358    }
359
360    fn set_tolerance(&mut self, tolerance: Tolerance) {
361        self.inner.set_tolerance(tolerance);
362    }
363}
364
365impl Debug for ScrollSpringSimulation {
366    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
367        Debug::fmt(&self.inner, f)
368    }
369}
370
371enum SpringSolution {
372    Critical { r: f64, c1: f64, c2: f64 },
373    Overdamped { r1: f64, r2: f64, c1: f64, c2: f64 },
374    Underdamped { w: f64, r: f64, c1: f64, c2: f64 },
375}
376
377impl SpringSolution {
378    fn new(
379        spring: SpringDescription,
380        initial_position: f64,
381        initial_velocity: f64,
382    ) -> SpringSolution {
383        let cmk = spring.damping * spring.damping - 4.0 * spring.mass * spring.stiffness;
384        if cmk > 0.0 {
385            SpringSolution::overdamped(spring, initial_position, initial_velocity)
386        } else if cmk < 0.0 {
387            SpringSolution::underdamped(spring, initial_position, initial_velocity)
388        } else {
389            SpringSolution::critical(spring, initial_position, initial_velocity)
390        }
391    }
392
393    fn critical(spring: SpringDescription, distance: f64, velocity: f64) -> SpringSolution {
394        let r = -spring.damping / (2.0 * spring.mass);
395        let c1 = distance;
396        let c2 = velocity - (r * distance);
397        SpringSolution::Critical { r, c1, c2 }
398    }
399
400    fn overdamped(spring: SpringDescription, distance: f64, velocity: f64) -> SpringSolution {
401        let cmk = spring.damping * spring.damping - 4.0 * spring.mass * spring.stiffness;
402        let r1 = (-spring.damping - cmk.sqrt()) / (2.0 * spring.mass);
403        let r2 = (-spring.damping + cmk.sqrt()) / (2.0 * spring.mass);
404        let c2 = (velocity - r1 * distance) / (r2 - r1);
405        let c1 = distance - c2;
406        SpringSolution::Overdamped { r1, r2, c1, c2 }
407    }
408
409    fn underdamped(spring: SpringDescription, distance: f64, velocity: f64) -> SpringSolution {
410        let w = (4.0 * spring.mass * spring.stiffness - spring.damping * spring.damping).sqrt()
411            / (2.0 * spring.mass);
412        let r = -(spring.damping / 2.0 / spring.mass);
413        let c1 = distance;
414        let c2 = (velocity - r * distance) / w;
415        SpringSolution::Underdamped { w, r, c1, c2 }
416    }
417
418    fn x(&self, time: f64) -> f64 {
419        match *self {
420            SpringSolution::Critical { r, c1, c2 } => (c1 + c2 * time) * (r * time).exp(),
421            SpringSolution::Overdamped { r1, r2, c1, c2 } => {
422                c1 * (r1 * time).exp() + c2 * (r2 * time).exp()
423            }
424            SpringSolution::Underdamped { w, r, c1, c2 } => {
425                (r * time).exp() * (c1 * (w * time).cos() + c2 * (w * time).sin())
426            }
427        }
428    }
429
430    fn dx(&self, time: f64) -> f64 {
431        match *self {
432            SpringSolution::Critical { r, c1, c2 } => {
433                let power = (r * time).exp();
434                r * (c1 + c2 * time) * power + c2 * power
435            }
436            SpringSolution::Overdamped { r1, r2, c1, c2 } => {
437                c1 * r1 * (r1 * time).exp() + c2 * r2 * (r2 * time).exp()
438            }
439            SpringSolution::Underdamped { w, r, c1, c2 } => {
440                let power = (r * time).exp();
441                let cosine = (w * time).cos();
442                let sine = (w * time).sin();
443                power * (c2 * w * cosine - c1 * w * sine) + r * power * (c2 * sine + c1 * cosine)
444            }
445        }
446    }
447
448    fn spring_type(&self) -> SpringType {
449        match self {
450            SpringSolution::Critical { .. } => SpringType::CriticallyDamped,
451            SpringSolution::Overdamped { .. } => SpringType::OverDamped,
452            SpringSolution::Underdamped { .. } => SpringType::UnderDamped,
453        }
454    }
455}
456
457#[cfg(test)]
458mod tests {
459    use std::time::Duration;
460
461    use super::*;
462    use crate::Simulation;
463
464    fn approx(actual: f64, expected: f64, epsilon: f64) {
465        assert!(
466            (actual - expected).abs() <= epsilon,
467            "{actual} != {expected} ±{epsilon}"
468        );
469    }
470
471    #[test]
472    fn when_snap_to_end_is_set_value_is_exactly_end_after_completion() {
473        let description = SpringDescription::with_damping_ratio(1.0, 400.0);
474        let time = 0.4;
475
476        let regular = SpringSimulation::with_options(
477            description,
478            0.0,
479            1.0,
480            0.0,
481            false,
482            Tolerance {
483                distance: 0.1,
484                velocity: 0.1,
485                ..Tolerance::DEFAULT_TOLERANCE
486            },
487        );
488        assert!(regular.x(time) < 1.0);
489        assert!(regular.dx(time) > 0.0);
490
491        let snapping = SpringSimulation::with_options(
492            description,
493            0.0,
494            1.0,
495            0.0,
496            true,
497            Tolerance {
498                distance: 0.1,
499                velocity: 0.1,
500                ..Tolerance::DEFAULT_TOLERANCE
501            },
502        );
503        assert_eq!(snapping.x(time), 1.0);
504        assert_eq!(snapping.dx(time), 0.0);
505    }
506
507    #[test]
508    fn spring_simulation_results_are_continuous_near_critical_damping() {
509        let time = 0.4;
510        let stiffness = 0.4;
511        let mass = 0.4;
512        let critical = SpringSimulation::new(
513            SpringDescription::with_damping_ratio(mass, stiffness),
514            0.0,
515            1.0,
516            0.0,
517        );
518        approx(critical.x(time), 0.06155, 0.01);
519        approx(critical.dx(time), 0.2681, 0.01);
520
521        let slightly_over = SpringSimulation::new(
522            SpringDescription::with_damping_ratio_value(mass, stiffness, 1.0 + 1e-3),
523            0.0,
524            1.0,
525            0.0,
526        );
527        approx(slightly_over.x(time), 0.06155, 0.01);
528        approx(slightly_over.dx(time), 0.2681, 0.01);
529
530        let slightly_under = SpringSimulation::new(
531            SpringDescription::with_damping_ratio_value(mass, stiffness, 1.0 - 1e-3),
532            0.0,
533            1.0,
534            0.0,
535        );
536        approx(slightly_under.x(time), 0.06155, 0.01);
537        approx(slightly_under.dx(time), 0.2681, 0.01);
538    }
539
540    #[test]
541    fn with_duration_and_bounce_creates_spring_with_expected_results() {
542        let spring = SpringDescription::with_duration_and_bounce(Duration::from_millis(500), 0.3);
543
544        assert_eq!(spring.mass, 1.0);
545        approx(spring.stiffness, 157.91, 0.01);
546        approx(spring.damping, 17.59, 0.01);
547        approx(spring.bounce(), 0.3, 0.0001);
548        assert_eq!(spring.duration().as_millis(), 500);
549    }
550
551    #[test]
552    fn with_duration_and_bounce_creates_spring_with_negative_bounce() {
553        let spring = SpringDescription::with_duration_and_bounce(Duration::from_millis(500), -0.3);
554
555        assert_eq!(spring.mass, 1.0);
556        approx(spring.stiffness, 157.91, 0.01);
557        approx(spring.damping, 35.90, 0.01);
558        approx(spring.bounce(), -0.3, 0.0001);
559        assert_eq!(spring.duration().as_millis(), 500);
560    }
561
562    #[test]
563    fn get_duration_and_bounce_based_on_mass_and_stiffness() {
564        let spring = SpringDescription::new(1.0, 157.91, 17.59);
565        approx(spring.bounce(), 0.3, 0.001);
566        assert_eq!(spring.duration().as_millis(), 500);
567    }
568
569    #[test]
570    fn custom_duration() {
571        let spring = SpringDescription::with_duration_and_bounce(Duration::from_millis(100), 0.0);
572
573        assert_eq!(spring.mass, 1.0);
574        approx(spring.stiffness, 3947.84, 0.01);
575        approx(spring.damping, 125.66, 0.01);
576        approx(spring.bounce(), 0.0, 0.001);
577        assert_eq!(spring.duration().as_millis(), 100);
578    }
579
580    #[test]
581    #[should_panic(expected = "Duration must be positive")]
582    fn duration_zero_should_fail() {
583        SpringDescription::with_duration_and_bounce(Duration::ZERO, 0.3);
584    }
585
586    #[test]
587    fn spring_types() {
588        let crit = SpringSimulation::new(
589            SpringDescription::with_damping_ratio(1.0, 100.0),
590            0.0,
591            300.0,
592            0.0,
593        );
594        assert_eq!(crit.spring_type(), SpringType::CriticallyDamped);
595
596        let under = SpringSimulation::new(
597            SpringDescription::with_damping_ratio_value(1.0, 100.0, 0.75),
598            0.0,
599            300.0,
600            0.0,
601        );
602        assert_eq!(under.spring_type(), SpringType::UnderDamped);
603
604        let over = SpringSimulation::new(
605            SpringDescription::with_damping_ratio_value(1.0, 100.0, 1.25),
606            0.0,
607            300.0,
608            0.0,
609        );
610        assert_eq!(over.spring_type(), SpringType::OverDamped);
611
612        let other =
613            SpringSimulation::new(SpringDescription::new(1.0, 100.0, 20.0), 0.0, 20.0, 20.0);
614        assert_eq!(other.spring_type(), SpringType::CriticallyDamped);
615    }
616
617    #[test]
618    fn crit_spring() {
619        let mut crit = SpringSimulation::new(
620            SpringDescription::with_damping_ratio(1.0, 100.0),
621            0.0,
622            500.0,
623            0.0,
624        );
625        crit.tolerance = Tolerance {
626            distance: 0.01,
627            velocity: 0.01,
628            ..Tolerance::DEFAULT_TOLERANCE
629        };
630
631        assert_eq!(crit.spring_type(), SpringType::CriticallyDamped);
632        assert!(!crit.is_done(0.0));
633        assert_eq!(crit.x(0.0), 0.0);
634        assert_eq!(crit.dx(0.0), 0.0);
635
636        assert_eq!(crit.x(0.25).floor() as i32, 356);
637        assert_eq!(crit.x(0.50).floor() as i32, 479);
638        assert_eq!(crit.x(0.75).floor() as i32, 497);
639
640        assert_eq!(crit.dx(0.25).floor() as i32, 1026);
641        assert_eq!(crit.dx(0.50).floor() as i32, 168);
642        assert_eq!(crit.dx(0.75).floor() as i32, 20);
643
644        assert!(crit.x(1.5) > 499.0 && crit.x(1.5) < 501.0);
645        assert!(crit.dx(1.5) < 0.1);
646        assert!(crit.is_done(1.60));
647    }
648
649    #[test]
650    fn overdamped_spring() {
651        let mut over = SpringSimulation::new(
652            SpringDescription::with_damping_ratio_value(1.0, 100.0, 1.25),
653            0.0,
654            500.0,
655            0.0,
656        );
657        over.tolerance = Tolerance {
658            distance: 0.01,
659            velocity: 0.01,
660            ..Tolerance::DEFAULT_TOLERANCE
661        };
662
663        assert_eq!(over.spring_type(), SpringType::OverDamped);
664        assert!(!over.is_done(0.0));
665        assert_eq!(over.x(0.0), 0.0);
666        approx(over.dx(0.0), 0.0, 1e-10);
667
668        assert_eq!(over.x(0.5).floor() as i32, 445);
669        assert_eq!(over.x(1.0).floor() as i32, 495);
670        assert_eq!(over.x(1.5).floor() as i32, 499);
671
672        assert_eq!(over.dx(0.5).floor() as i32, 273);
673        assert_eq!(over.dx(1.0).floor() as i32, 22);
674        assert_eq!(over.dx(1.5).floor() as i32, 1);
675
676        assert!(over.is_done(3.0));
677    }
678
679    #[test]
680    fn underdamped_spring() {
681        let under = SpringSimulation::new(
682            SpringDescription::with_damping_ratio_value(1.0, 100.0, 0.25),
683            0.0,
684            300.0,
685            0.0,
686        );
687        assert_eq!(under.spring_type(), SpringType::UnderDamped);
688        assert!(!under.is_done(0.0));
689        approx(under.x(0.0), 0.0, 1e-10);
690        approx(under.dx(0.0), 0.0, 1e-10);
691
692        assert_eq!(under.x(1.0).floor() as i32, 325);
693        assert_eq!(under.dx(1.0).floor() as i32, -65);
694
695        assert_eq!(under.dx(6.0).floor() as i32, 0);
696        assert_eq!(under.x(6.0).floor() as i32, 299);
697
698        assert!(under.is_done(6.0));
699    }
700}