Skip to main content

waft_physics/
gravity_simulation.rs

1//! Flutter counterpart: `physics/gravity_simulation.dart`.
2
3use std::fmt::{self, Debug};
4
5use crate::{Simulation, Tolerance};
6
7/// A simulation that applies a constant accelerating force.
8///
9/// Models a particle that follows Newton's second law of motion. The simulation
10/// ends when the position exceeds a defined threshold.
11pub struct GravitySimulation {
12    x0: f64,
13    v0: f64,
14    a: f64,
15    end: f64,
16    /// How close to the actual end of the simulation a value at a particular
17    /// time must be before [`is_done`](Simulation::is_done) considers the
18    /// simulation to be "done".
19    pub tolerance: Tolerance,
20}
21
22impl GravitySimulation {
23    /// Creates a [`GravitySimulation`] using the given arguments, which are,
24    /// respectively: an acceleration that is to be applied continually over
25    /// time; an initial position relative to an origin; the magnitude of the
26    /// distance from that origin beyond which (in either direction) to consider
27    /// the simulation to be "done", which must be positive; and an initial
28    /// velocity.
29    ///
30    /// The initial position and maximum distance are measured in arbitrary
31    /// length units L from an arbitrary origin. The units will match those used
32    /// for [`x`](Simulation::x).
33    ///
34    /// The time unit T used for the arguments to [`x`](Simulation::x),
35    /// [`dx`](Simulation::dx), and [`is_done`](Simulation::is_done), combined
36    /// with the aforementioned length unit, together determine the units that
37    /// must be used for the velocity and acceleration arguments: L/T and L/T²
38    /// respectively. The same units of velocity are used for the velocity
39    /// obtained from [`dx`](Simulation::dx).
40    pub fn new(
41        acceleration: f64,
42        distance: f64,
43        end_distance: f64,
44        velocity: f64,
45    ) -> GravitySimulation {
46        debug_assert!(end_distance >= 0.0);
47        GravitySimulation {
48            x0: distance,
49            v0: velocity,
50            a: acceleration,
51            end: end_distance,
52            tolerance: Tolerance::DEFAULT_TOLERANCE,
53        }
54    }
55}
56
57impl Simulation for GravitySimulation {
58    fn x(&self, time: f64) -> f64 {
59        self.x0 + self.v0 * time + 0.5 * self.a * time * time
60    }
61
62    fn dx(&self, time: f64) -> f64 {
63        self.v0 + time * self.a
64    }
65
66    fn is_done(&self, time: f64) -> bool {
67        self.x(time).abs() >= self.end
68    }
69
70    fn tolerance(&self) -> Tolerance {
71        self.tolerance
72    }
73
74    fn set_tolerance(&mut self, tolerance: Tolerance) {
75        self.tolerance = tolerance;
76    }
77}
78
79impl Debug for GravitySimulation {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        write!(
82            f,
83            "GravitySimulation(g: {:.1}, x₀: {:.1}, dx₀: {:.1}, xₘₐₓ: ±{:.1})",
84            self.a, self.x0, self.v0, self.end
85        )
86    }
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92    use crate::Simulation;
93
94    fn approx(actual: f64, expected: f64, epsilon: f64) {
95        assert!(
96            (actual - expected).abs() <= epsilon,
97            "{actual} != {expected} ±{epsilon}"
98        );
99    }
100
101    #[test]
102    fn gravity_simulation_1() {
103        let gravity = GravitySimulation::new(9.81, 10.0, 0.0, 0.0);
104        let text = format!("{gravity:?}");
105        assert!(!text.contains('\n'));
106        approx(gravity.x(10.0), 50.0 * 9.81 + 10.0, 1e-10);
107    }
108
109    #[test]
110    fn gravity_simulation_2() {
111        let gravity = GravitySimulation::new(-10.0, 0.0, 6.0, 10.0);
112
113        assert_eq!(gravity.x(0.0), 0.0);
114        assert_eq!(gravity.dx(0.0), 10.0);
115        assert!(!gravity.is_done(0.0));
116
117        assert_eq!(gravity.x(1.0), 5.0);
118        assert_eq!(gravity.dx(1.0), 0.0);
119        assert!(!gravity.is_done(0.2));
120
121        assert_eq!(gravity.x(2.0), 0.0);
122        assert_eq!(gravity.dx(2.0), -10.0);
123        assert!(!gravity.is_done(2.0));
124
125        assert_eq!(gravity.x(3.0), -15.0);
126        assert_eq!(gravity.dx(3.0), -20.0);
127        assert!(gravity.is_done(3.0));
128    }
129
130    #[test]
131    fn test_gravity() {
132        let gravity = GravitySimulation::new(200.0, 100.0, 600.0, 0.0);
133
134        assert!(!gravity.is_done(0.0));
135        assert_eq!(gravity.x(0.0), 100.0);
136        assert_eq!(gravity.dx(0.0), 0.0);
137
138        assert_eq!(gravity.x(0.25), 106.25);
139        assert_eq!(gravity.x(0.50), 125.0);
140        assert_eq!(gravity.x(0.75), 156.25);
141        assert_eq!(gravity.x(1.00), 200.0);
142        assert_eq!(gravity.x(1.25), 256.25);
143        assert_eq!(gravity.x(1.50), 325.0);
144        assert_eq!(gravity.x(1.75), 406.25);
145
146        assert_eq!(gravity.dx(0.25), 50.0);
147        assert_eq!(gravity.dx(0.50), 100.0);
148        assert_eq!(gravity.dx(0.75), 150.00);
149        assert_eq!(gravity.dx(1.00), 200.0);
150        assert_eq!(gravity.dx(1.25), 250.0);
151        assert_eq!(gravity.dx(1.50), 300.0);
152        assert_eq!(gravity.dx(1.75), 350.0);
153
154        assert!(gravity.is_done(2.5));
155        assert_eq!(gravity.x(2.5), 725.0);
156        assert_eq!(gravity.dx(2.5), 500.0);
157    }
158}