From 879e5af4eb1a8972fc944853a515e1003f94bd7c Mon Sep 17 00:00:00 2001 From: 3gg <3gg@shellblade.net> Date: Sat, 11 Apr 2026 12:27:23 -0700 Subject: Fix simloop divergence --- simloop/src/simloop.c | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) (limited to 'simloop/src/simloop.c') diff --git a/simloop/src/simloop.c b/simloop/src/simloop.c index 11f4d6d..aa2b6b7 100644 --- a/simloop/src/simloop.c +++ b/simloop/src/simloop.c @@ -12,12 +12,13 @@ Simloop simloop_make(const SimloopArgs* args) { assert(args->update_fps > 0); return (Simloop){ - .frame = 0, - .update = (SimloopTimeline){.ddt = ddt_from_fps(args->update_fps), - .last_step = args->timer->start_time}, - .render = (SimloopTimeline){ .ddt = ddt_from_fps(args->max_render_fps), - .last_step = args->timer->start_time}, - .timer = args->timer, + .frame = 0, + .update = (SimloopTimeline){.ddt = ddt_from_fps(args->update_fps), + .last_step = args->timer->start_time}, + .render = (SimloopTimeline){ .ddt = ddt_from_fps(args->max_render_fps), + .last_step = args->timer->start_time}, + .timer = args->timer, + .first_iter = true, }; } @@ -26,15 +27,16 @@ static time_delta time_elapsed(const Simloop* sim, time_point t) { return time_diff(sim->timer->start_time, t); } -static int step_update(const Simloop* sim, SimloopTimeline* timeline) { +static bool step_update(const Simloop* sim, SimloopTimeline* timeline) { assert(sim); assert(timeline); assert(timeline->ddt > 0); const time_delta dt = time_diff(timeline->last_step, sim->timer->last_tick); - const time_delta steps = dt / timeline->ddt; - timeline->last_step = time_add(timeline->last_step, dt); - return (int)steps; + const bool should_step = dt >= timeline->ddt; + timeline->last_step = + should_step ? time_add(timeline->last_step, dt) : timeline->last_step; + return should_step; } static bool step_render(const Simloop* sim, SimloopTimeline* timeline) { @@ -43,7 +45,7 @@ static bool step_render(const Simloop* sim, SimloopTimeline* timeline) { bool render = false; if (timeline->ddt > 0) { - render = step_update(sim, timeline) > 0; + render = step_update(sim, timeline); } else { timeline->last_step = sim->timer->last_tick; render = true; @@ -55,12 +57,12 @@ void simloop_update(Simloop* sim, SimloopOut* out) { assert(sim); assert(out); - const int new_frames = step_update(sim, &sim->update); - out->updates_pending = new_frames; + out->should_update = step_update(sim, &sim->update); out->should_render = step_render(sim, &sim->render) || - (sim->frame == 0); // Trigger an initial render on the first frame. - sim->frame += new_frames; + (sim->first_iter); // Trigger an initial render on the first frame. + sim->frame += (out->should_update ? 1 : 0); + sim->first_iter = false; out->frame = sim->frame; out->render_elapsed = time_elapsed(sim, sim->render.last_step); out->update_elapsed = time_elapsed(sim, sim->update.last_step); -- cgit v1.2.3