From e97bd18127fe019dd14256d807f9ea5d06cc36b1 Mon Sep 17 00:00:00 2001 From: 3gg <3gg@shellblade.net> Date: Sun, 5 Apr 2026 14:47:39 -0700 Subject: Add timer_advance for virtual simulation --- timer/include/timer.h | 17 +++++++++++++---- timer/src/timer.c | 15 ++++++++++++--- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/timer/include/timer.h b/timer/include/timer.h index 6dc87d9..75ae367 100644 --- a/timer/include/timer.h +++ b/timer/include/timer.h @@ -21,10 +21,10 @@ typedef uint64_t time_delta; /// A high resolution timer. typedef struct Timer { - time_point start_time; // The instant the timer was last started. - time_point last_tick; // The instant the timer was last ticked. - time_delta running_time; // Time elapsed since the timer was last started. - time_delta delta_time; // Time elapsed since the last tick. + time_point start_time; ///< The instant the timer was last started. + time_point last_tick; ///< The instant the timer was last ticked. + time_delta running_time; ///< Time elapsed since the timer was last started. + time_delta delta_time; ///< Time elapsed since the last tick. } Timer; /// Construct a new timer. @@ -38,6 +38,15 @@ void timer_start(Timer*); /// Update the timer's running and delta times. void timer_tick(Timer*); +/// Advance the timer. +/// +/// This is used for simulations that wish control over time. It should not be +/// used together with timer_tick(). +/// +/// The input time is relative to the timer's start time. Successive calls to +/// this function must use increasing values of time. +void timer_advance(Timer* timer, time_delta t); + /// Get the current time. time_point time_now(void); diff --git a/timer/src/timer.c b/timer/src/timer.c index d886f59..c934077 100644 --- a/timer/src/timer.c +++ b/timer/src/timer.c @@ -37,11 +37,20 @@ void timer_start(Timer* timer) { timer->delta_time = 0; } +static void timer_update(Timer* timer, time_point this_tick) { + timer->running_time = time_diff(timer->start_time, this_tick); + timer->delta_time = time_diff(timer->last_tick, this_tick); + timer->last_tick = this_tick; +} + void timer_tick(Timer* timer) { const time_point this_tick = time_now(); - timer->running_time = time_diff(timer->start_time, this_tick); - timer->delta_time = time_diff(timer->last_tick, this_tick); - timer->last_tick = this_tick; + timer_update(timer, this_tick); +} + +void timer_advance(Timer* timer, time_delta t) { + const time_point this_tick = time_add(timer->start_time, t); + timer_update(timer, this_tick); } time_point time_now(void) { -- cgit v1.2.3