diff options
-rw-r--r-- | src/level.c | 32 |
1 files changed, 30 insertions, 2 deletions
diff --git a/src/level.c b/src/level.c index cc15c53..8c6a1bd 100644 --- a/src/level.c +++ b/src/level.c @@ -106,6 +106,12 @@ _db_level_render(SDL_Renderer *renderer, struct db_level *level) int db_level_play(SDL_Renderer *renderer, struct db_level *level) { + int fr; + Uint32 prv_ticks; + Uint32 cur_ticks; + Uint32 delay; + SDL_Event event; + db_dbg("Playing %s/%s", level->game_id, level->level_id); level->map = db_map_new(level->game_id, level->level_id); @@ -120,8 +126,30 @@ db_level_play(SDL_Renderer *renderer, struct db_level *level) &level->target_r, &level->target_gid); level->balls = db_map_get_balls(level->map); - _db_level_render(renderer, level); - SDL_Delay(1000); + fr = db_map_get_framerate(level->map); + prv_ticks = SDL_GetTicks(); + while (1) { + while (SDL_PollEvent(&event)) { + switch (event.type) { + case SDL_QUIT: + return -1; + default: + break; + } + } + _db_level_render(renderer, level); + cur_ticks = SDL_GetTicks(); + if ((Uint32) (1000 / fr) > (cur_ticks - prv_ticks)) { + delay = 1000 / fr - (cur_ticks - prv_ticks); + } else { + db_warn("Frame took longer than frame period"); + delay = 0; + } + db_dbg("Frame took %u ms, delaying %u ms", + cur_ticks - prv_ticks, delay); + SDL_Delay(delay); + prv_ticks = cur_ticks; + } return 0; } |