Fix sleep timing

This commit is contained in:
Simon Gellis 2024-10-19 21:05:56 -04:00
parent addff55c24
commit 9f955be5dc
1 changed files with 9 additions and 3 deletions

12
game.c
View File

@ -6,10 +6,16 @@
int sleepNanos(long int ns) { int sleepNanos(long int ns) {
struct timespec time; struct timespec time;
if (ns < 0) return 0;
time.tv_sec = ns / 1000000000; time.tv_sec = ns / 1000000000;
time.tv_nsec = ns % 1000000000; time.tv_nsec = ns % 1000000000;
return nanosleep(&time, NULL); return nanosleep(&time, NULL);
} }
long int tickNs() {
struct timespec time;
clock_gettime(CLOCK_MONOTONIC, &time);
return (time.tv_sec * 1000000000) + time.tv_nsec;
}
typedef struct { typedef struct {
GraphicsContext *gfx; GraphicsContext *gfx;
@ -46,17 +52,17 @@ int runGame(VB *sim, GraphicsContext *gfx) {
gfxUpdateLeftEye(gfx, LEFT_EYE_DEFAULT); gfxUpdateLeftEye(gfx, LEFT_EYE_DEFAULT);
gfxUpdateRightEye(gfx, RIGHT_EYE_DEFAULT); gfxUpdateRightEye(gfx, RIGHT_EYE_DEFAULT);
prevTicks = SDL_GetTicks64();
while (1) { while (1) {
clocks = MAX_STEP_CLOCKS; clocks = MAX_STEP_CLOCKS;
prevTicks = tickNs();
vbEmulate(sim, &clocks); vbEmulate(sim, &clocks);
ticks = SDL_GetTicks64(); ticks = tickNs();
while (SDL_PollEvent(&event)) { while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) { if (event.type == SDL_QUIT) {
return 0; return 0;
} }
} }
sleepNanos(((MAX_STEP_CLOCKS - clocks) * 50) - (ticks - prevTicks) * 1000); sleepNanos(((MAX_STEP_CLOCKS - clocks) * 50) - (ticks - prevTicks));
prevTicks = ticks; prevTicks = ticks;
} }
} }