Skip to content

Commit 6a19539

Browse files
committed
Don't simulate more than 1 second
1 parent cf610b6 commit 6a19539

File tree

1 file changed

+24
-15
lines changed

1 file changed

+24
-15
lines changed

src/window/update_loop.rs

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ impl ShouldRender {
6666
}
6767
}
6868

69-
const MAX_ANIMATION_DT: f32 = 1.0 / 120.0;
69+
const MAX_ANIMATION_DT: f64 = 1.0 / 120.0;
7070

7171
pub struct UpdateLoop {
7272
idle: bool,
@@ -139,28 +139,37 @@ impl UpdateLoop {
139139
}
140140

141141
fn animate(&mut self, window_wrapper: &mut WinitWindowWrapper) {
142-
let dt = window_wrapper
143-
.vsync
144-
.get_refresh_rate(window_wrapper.skia_renderer.window());
142+
let dt = Duration::from_secs_f32(
143+
window_wrapper
144+
.vsync
145+
.get_refresh_rate(window_wrapper.skia_renderer.window()),
146+
);
145147

146148
let now = Instant::now();
147-
let target_animation_time = (now - self.animation_start).as_secs_f64();
148-
let delta = target_animation_time - self.animation_time.as_secs_f64();
149+
let target_animation_time = now - self.animation_start;
150+
let mut delta = target_animation_time.saturating_sub(self.animation_time);
151+
// Don't try to animate way too big deltas
152+
// Instead reset the animation times, and simulate a single frame
153+
if delta > Duration::from_millis(1000) {
154+
self.animation_start = now;
155+
self.animation_time = Duration::ZERO;
156+
delta = dt;
157+
}
149158
// Catchup immediately if the delta is more than one frame, otherwise smooth it over 10 frames
150-
let catchup = if delta >= dt as f64 {
159+
let catchup = if delta >= dt {
151160
delta
152161
} else {
153-
delta / 10.0
162+
delta.div_f64(10.0)
154163
};
155164

156-
let dt = (dt + catchup as f32).max(0.0);
157-
tracy_plot!("Simulation dt", dt as f64);
158-
self.animation_time += Duration::from_secs_f32(dt);
165+
let dt = dt + catchup;
166+
tracy_plot!("Simulation dt", dt.as_secs_f64());
167+
self.animation_time += dt;
159168

160-
let num_steps = (dt / MAX_ANIMATION_DT).ceil();
169+
let num_steps = (dt.as_secs_f64() / MAX_ANIMATION_DT).ceil() as u32;
161170
let step = dt / num_steps;
162-
for _ in 0..num_steps as usize {
163-
if window_wrapper.animate_frame(step) {
171+
for _ in 0..num_steps {
172+
if window_wrapper.animate_frame(step.as_secs_f32()) {
164173
self.should_render = ShouldRender::Immediately;
165174
}
166175
}
@@ -196,7 +205,7 @@ impl UpdateLoop {
196205
self.should_render = ShouldRender::Wait;
197206
if self.num_consecutive_rendered == 0 {
198207
self.animation_start = Instant::now();
199-
self.animation_time = Duration::from_millis(0);
208+
self.animation_time = Duration::ZERO;
200209
}
201210
}
202211

0 commit comments

Comments
 (0)