From b03c941b8b0ab51227aa52d10616dbd47f75e5d9 Mon Sep 17 00:00:00 2001 From: 3gg <3gg@shellblade.net> Date: Sat, 2 May 2026 14:58:00 -0700 Subject: Handle large time spikes --- simloop/src/simloop.c | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) (limited to 'simloop/src') diff --git a/simloop/src/simloop.c b/simloop/src/simloop.c index d231ab3..4fa5f62 100644 --- a/simloop/src/simloop.c +++ b/simloop/src/simloop.c @@ -31,15 +31,23 @@ void simloop_update(Simloop* sim, simloop_time_t dt, SimloopOut* out) { sim->clock += dt; // Simulation update. - // If the update falls behind the clock, we advance by a single ddt increment - // per loop iteration here and give it a chance to catch up over subsequent - // iterations. + // If the simulation falls behind the clock, we advance by a single ddt + // increment per loop iteration here and give it a chance to catch up over + // subsequent iterations. // This has the implication that percent_frame can fall out of range (>1) if - // we are not careful with how it is defined. See the general update function - // below. - const simloop_time_t delta = sim->clock - sim->update.time; - const bool update_this_tick = delta >= sim->update.ddt; - sim->update.time += update_this_tick ? sim->update.ddt : 0; + // we are not careful with how it is defined. See the logic below. + // If the delta is too large, then we simply warp the simulation to the wall + // clock. This avoids the appearance of the simulation playing in fast-forward + // as it tries to catch up. Large time spikes can typically occur at the start + // of the simulation when the application loads assets, compiles shaders, etc. + static const uint64_t max_catchup_frames = 10; + const simloop_time_t delta = sim->clock - sim->update.time; + const uint64_t delta_frames = delta / sim->update.ddt; + const bool update_this_tick = delta >= sim->update.ddt; + const bool warp = delta_frames > max_catchup_frames; + sim->update.time = + warp ? sim->clock + : (sim->update.time + (update_this_tick ? sim->update.ddt : 0)); // Loop-state update. sim->frame += (update_this_tick ? 1 : 0); -- cgit v1.2.3