Skip to main content

waft_physics/
clamped_simulation.rs

1//! Flutter counterpart: `physics/clamped_simulation.dart`.
2
3use std::fmt::{self, Debug};
4
5use waft_embedder::clamp_double;
6
7use crate::{Simulation, Tolerance};
8
9/// A simulation that applies limits to another simulation.
10///
11/// The limits are only applied to the other simulation's outputs. For example,
12/// if a maximum position was applied to a gravity simulation with the
13/// particle's initial velocity being up, and the acceleration being down, and
14/// the maximum position being between the initial position and the curve's
15/// apogee, then the particle would return to its initial position in the same
16/// amount of time as it would have if the maximum had not been applied; the
17/// difference would just be that the position would be reported as pinned to
18/// the maximum value for the times that it would otherwise have been reported
19/// as higher.
20///
21/// Similarly, this means that the [`x`](Simulation::x) value will change at a
22/// rate that does not match the reported [`dx`](Simulation::dx) value while
23/// one or the other is being clamped.
24///
25/// The [`is_done`](Simulation::is_done) logic is unaffected by the clamping;
26/// it reflects the logic of the underlying simulation.
27pub struct ClampedSimulation {
28    /// The simulation being clamped. Calls to [`x`](Simulation::x),
29    /// [`dx`](Simulation::dx), and [`is_done`](Simulation::is_done) are
30    /// forwarded to the simulation.
31    pub simulation: Box<dyn Simulation>,
32    /// The minimum to apply to [`x`](Simulation::x).
33    pub x_min: f64,
34    /// The maximum to apply to [`x`](Simulation::x).
35    pub x_max: f64,
36    /// The minimum to apply to [`dx`](Simulation::dx).
37    pub dx_min: f64,
38    /// The maximum to apply to [`dx`](Simulation::dx).
39    pub dx_max: f64,
40    /// How close to the actual end of the simulation a value at a particular
41    /// time must be before [`is_done`](Simulation::is_done) considers the
42    /// simulation to be "done".
43    pub tolerance: Tolerance,
44}
45
46impl ClampedSimulation {
47    /// Creates a [`ClampedSimulation`] that clamps the given simulation.
48    ///
49    /// The named arguments specify the ranges for the clamping behavior, as
50    /// applied to [`x`](Simulation::x) and [`dx`](Simulation::dx).
51    pub fn new(
52        simulation: Box<dyn Simulation>,
53        x_min: f64,
54        x_max: f64,
55        dx_min: f64,
56        dx_max: f64,
57    ) -> ClampedSimulation {
58        debug_assert!(x_max >= x_min);
59        debug_assert!(dx_max >= dx_min);
60        ClampedSimulation {
61            simulation,
62            x_min,
63            x_max,
64            dx_min,
65            dx_max,
66            tolerance: Tolerance::DEFAULT_TOLERANCE,
67        }
68    }
69}
70
71impl Simulation for ClampedSimulation {
72    fn x(&self, time: f64) -> f64 {
73        clamp_double(self.simulation.x(time), self.x_min, self.x_max)
74    }
75
76    fn dx(&self, time: f64) -> f64 {
77        clamp_double(self.simulation.dx(time), self.dx_min, self.dx_max)
78    }
79
80    fn is_done(&self, time: f64) -> bool {
81        self.simulation.is_done(time)
82    }
83
84    fn tolerance(&self) -> Tolerance {
85        self.tolerance
86    }
87
88    fn set_tolerance(&mut self, tolerance: Tolerance) {
89        self.tolerance = tolerance;
90    }
91}
92
93impl Debug for ClampedSimulation {
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        write!(
96            f,
97            "ClampedSimulation(simulation: {:?}, x: {:.1}..{:.1}, dx: {:.1}..{:.1})",
98            self.simulation, self.x_min, self.x_max, self.dx_min, self.dx_max
99        )
100    }
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106    use crate::Simulation;
107    use crate::gravity_simulation::GravitySimulation;
108
109    struct TestSimulation;
110
111    impl Simulation for TestSimulation {
112        fn x(&self, _time: f64) -> f64 {
113            0.0
114        }
115
116        fn dx(&self, _time: f64) -> f64 {
117            0.0
118        }
119
120        fn is_done(&self, _time: f64) -> bool {
121            true
122        }
123
124        fn tolerance(&self) -> Tolerance {
125            Tolerance::DEFAULT_TOLERANCE
126        }
127
128        fn set_tolerance(&mut self, _tolerance: Tolerance) {}
129    }
130
131    impl Debug for TestSimulation {
132        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133            write!(f, "TestSimulation")
134        }
135    }
136
137    #[test]
138    fn clamped_simulation_1() {
139        let gravity = GravitySimulation::new(9.81, 10.0, 0.0, 0.0);
140        let clamped = ClampedSimulation::new(Box::new(gravity), 20.0, 100.0, 7.0, 11.0);
141
142        assert_eq!(clamped.x(0.0), 20.0);
143        assert_eq!(clamped.dx(0.0), 7.0);
144
145        assert_eq!(clamped.x(100.0), 100.0);
146        assert_eq!(clamped.dx(100.0), 11.0);
147    }
148
149    #[test]
150    fn clamped_simulation_2() {
151        let gravity = GravitySimulation::new(-10.0, 0.0, 6.0, 10.0);
152        let clamped = ClampedSimulation::new(Box::new(gravity), 0.0, 2.5, -1.0, 1.0);
153
154        assert_eq!(clamped.x(0.0), 0.0);
155        assert_eq!(clamped.dx(0.0), 1.0);
156        assert!(!clamped.is_done(0.0));
157
158        assert_eq!(clamped.x(1.0), 2.5);
159        assert_eq!(clamped.dx(1.0), 0.0);
160        assert!(!clamped.is_done(0.2));
161
162        assert_eq!(clamped.x(2.0), 0.0);
163        assert_eq!(clamped.dx(2.0), -1.0);
164        assert!(!clamped.is_done(2.0));
165
166        assert_eq!(clamped.x(3.0), 0.0);
167        assert_eq!(clamped.dx(3.0), -1.0);
168        assert!(clamped.is_done(3.0));
169    }
170
171    #[test]
172    fn simulation_to_string() {
173        assert_eq!(
174            format!(
175                "{:?}",
176                ClampedSimulation::new(Box::new(TestSimulation), -1.0, 2.0, -3.0, 4.0)
177            ),
178            "ClampedSimulation(simulation: TestSimulation, x: -1.0..2.0, dx: -3.0..4.0)"
179        );
180        assert_eq!(format!("{:?}", TestSimulation), "TestSimulation");
181        assert_eq!(
182            format!("{:?}", GravitySimulation::new(1.0, -2.0, 3.0, -4.0)),
183            "GravitySimulation(g: 1.0, x₀: -2.0, dx₀: -4.0, xₘₐₓ: ±3.0)"
184        );
185        assert_eq!(
186            format!("{:?}", crate::FrictionSimulation::new(1.0, -2.0, 3.0)),
187            "FrictionSimulation(cₓ: 1.0, x₀: -2.0, dx₀: 3.0)"
188        );
189        assert_eq!(
190            format!(
191                "{:?}",
192                crate::BoundedFrictionSimulation::new(1.0, -2.0, 3.0, -4.0, 5.0)
193            ),
194            "BoundedFrictionSimulation(cₓ: 1.0, x₀: -2.0, dx₀: 3.0, x: -4.0..5.0)"
195        );
196        assert_eq!(
197            format!("{:?}", crate::SpringDescription::new(1.0, -2.0, 3.0)),
198            "SpringDescription(mass: 1.0, stiffness: -2.0, damping: 3.0)"
199        );
200        assert_eq!(
201            format!(
202                "{:?}",
203                crate::SpringDescription::with_damping_ratio(1.0, 9.0)
204            ),
205            "SpringDescription(mass: 1.0, stiffness: 9.0, damping: 6.0)"
206        );
207        assert_eq!(
208            format!(
209                "{:?}",
210                crate::SpringSimulation::new(
211                    crate::SpringDescription::new(1.0, 2.0, 3.0),
212                    0.0,
213                    1.0,
214                    2.0,
215                )
216            ),
217            "SpringSimulation(end: 1.0, SpringType.overDamped)"
218        );
219    }
220}