72 lines
1.6 KiB
C++
72 lines
1.6 KiB
C++
#include "core/system/director.hpp"
|
|
|
|
#include <SDL3/SDL.h>
|
|
|
|
#include <algorithm>
|
|
#include <cstdio>
|
|
#include <memory>
|
|
#include <utility>
|
|
|
|
#include "core/rendering/screen.hpp"
|
|
#include "core/scene/scene.hpp"
|
|
#include "core/system/event_buffer.hpp"
|
|
#include "game/scenes/black_scene.hpp"
|
|
|
|
Director::Director() {
|
|
if (!SDL_Init(0)) {
|
|
std::fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
|
|
}
|
|
|
|
Screen::init();
|
|
|
|
current_scene_ = std::make_unique<BlackScene>();
|
|
last_ticks_ms_ = SDL_GetTicks();
|
|
}
|
|
|
|
Director::~Director() {
|
|
current_scene_.reset();
|
|
Screen::destroy();
|
|
SDL_Quit();
|
|
}
|
|
|
|
void Director::processEvents() {
|
|
const bool QUIT_REQUESTED = std::ranges::any_of(
|
|
EventBuffer::events,
|
|
[](const SDL_Event& event) { return event.type == SDL_EVENT_QUIT; });
|
|
if (QUIT_REQUESTED) { current_scene_.reset(); }
|
|
}
|
|
|
|
void Director::switchSceneIfRequested() {
|
|
if (!current_scene_) { return; }
|
|
if (auto next = current_scene_->nextScene()) {
|
|
current_scene_ = std::move(next);
|
|
}
|
|
}
|
|
|
|
auto Director::iterate() -> SDL_AppResult {
|
|
processEvents();
|
|
|
|
if (!current_scene_) {
|
|
EventBuffer::events.clear();
|
|
return SDL_APP_SUCCESS;
|
|
}
|
|
|
|
const std::uint64_t NOW_MS = SDL_GetTicks();
|
|
int delta_ms = static_cast<int>(NOW_MS - last_ticks_ms_);
|
|
delta_ms = std::max(delta_ms, 0);
|
|
last_ticks_ms_ = NOW_MS;
|
|
|
|
current_scene_->update(delta_ms);
|
|
current_scene_->render();
|
|
|
|
if (current_scene_->wantsQuit()) {
|
|
EventBuffer::events.clear();
|
|
return SDL_APP_SUCCESS;
|
|
}
|
|
|
|
switchSceneIfRequested();
|
|
|
|
EventBuffer::events.clear();
|
|
return SDL_APP_CONTINUE;
|
|
}
|