diff --git a/src/game/time.c b/src/game/time.c new file mode 100644 index 0000000..6b5a9ae --- /dev/null +++ b/src/game/time.c @@ -0,0 +1,39 @@ +#include "time.h" + +#include +#include + +#if __has_include() +#include +#endif +#if __has_include() && _POSIX_C_SOURCE >= 199309L +#include +static void gettime(struct timespec* ts) { + clock_gettime(CLOCK_MONOTONIC, ts); +} +#elif defined(_WIN32) +#include +#include +#include +static void gettime(struct timespec* ts) { + LARGE_INTEGER cnt, frq; + QueryPerformanceCounter(&cnt); + QueryPerformanceFrequency(&frq); + ts->tv_sec = (time_t)(cnt.QuadPart / frq.QuadPart); + ts->tv_nsec = (time_t)((cnt.QuadPart % frq.QuadPart) * 1000000000 / frq.QuadPart); +} +#else +#error no implementation of a monotonic clock was available +#endif + +time_t time_pull(void) { + struct timespec ts; + gettime(&ts); + return ts.tv_sec * 1000 + ts.tv_nsec / 1000000; +} + +int time_poll(time_t curr, time_t delta, time_t* restrict proj) { + bool tpass = curr >= *proj; + *proj += tpass * ((curr + delta) - *proj); // adds 0, or the difference to proj + return tpass; +} diff --git a/src/game/time.h b/src/game/time.h new file mode 100644 index 0000000..47d4efd --- /dev/null +++ b/src/game/time.h @@ -0,0 +1,12 @@ +#pragma once + +#include +#include + +/* gets the current time in milliseconds */ +time_t time_pull(void); + +/* Polls the time whether a given timeout has passed, comparing against `curr` as the current time. + * if `curr` ≥ `*proj`, `curr` + `delta` is written to `*proj`. `1` is returned. + * otherwise, we just return `0`. */ +__nonnull((3)) int time_poll(time_t curr, time_t delta, time_t* restrict proj);