shrooms-vb-native/game.c

63 lines
1.4 KiB
C
Raw Normal View History

#include <assets.h>
2024-10-15 04:24:13 +00:00
#include <game.h>
#include <SDL2/SDL.h>
2024-10-19 22:04:15 +00:00
#include <stdbool.h>
2024-10-15 04:24:13 +00:00
#include <time.h>
int sleepNanos(long int ns) {
struct timespec time;
time.tv_sec = ns / 1000000000;
time.tv_nsec = ns % 1000000000;
return nanosleep(&time, NULL);
}
2024-10-19 22:04:15 +00:00
typedef struct {
GraphicsContext *gfx;
} GameState;
int onFrame(VB *sim) {
static uint8_t leftEye[384*224];
static uint8_t rightEye[384*224];
GameState *state;
GraphicsContext *gfx;
state = vbGetUserData(sim);
gfx = state->gfx;
vbGetPixels(sim, leftEye, 1, 384, rightEye, 1, 384);
gfxUpdateLeftEye(gfx, leftEye);
gfxUpdateRightEye(gfx, rightEye);
gfxRender(gfx);
return 1;
}
#define MAX_STEP_CLOCKS 20000000
2024-10-15 04:24:13 +00:00
int runGame(VB *sim, GraphicsContext *gfx) {
2024-10-15 04:24:13 +00:00
uint32_t clocks;
SDL_Event event;
2024-10-19 22:04:15 +00:00
GameState state;
uint64_t ticks, prevTicks;
state.gfx = gfx;
vbSetUserData(sim, &state);
vbSetFrameCallback(sim, &onFrame);
2024-10-15 04:24:13 +00:00
gfxUpdateLeftEye(gfx, LEFT_EYE_DEFAULT);
gfxUpdateRightEye(gfx, RIGHT_EYE_DEFAULT);
2024-10-19 22:04:15 +00:00
prevTicks = SDL_GetTicks64();
2024-10-15 04:24:13 +00:00
while (1) {
clocks = MAX_STEP_CLOCKS;
vbEmulate(sim, &clocks);
2024-10-19 22:04:15 +00:00
ticks = SDL_GetTicks64();
2024-10-15 04:24:13 +00:00
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
return 0;
}
}
2024-10-19 22:04:15 +00:00
sleepNanos(((MAX_STEP_CLOCKS - clocks) * 50) - (ticks - prevTicks) * 1000);
prevTicks = ticks;
2024-10-15 04:24:13 +00:00
}
}