[nostalgia/core/glfw] Put wait for event in main loop to prevent processor waste

This commit is contained in:
Gary Talent 2022-02-10 21:31:00 -06:00
parent f9d3521fe7
commit 8847b2b2ed
2 changed files with 13 additions and 7 deletions

View File

@ -30,19 +30,25 @@ ox::Result<ox::UniquePtr<Context>> init(ox::UniquePtr<ox::FileSystem> fs, const
ox::Error run(Context *ctx) noexcept {
const auto id = ctx->windowerData<GlfwImplData>();
int sleepTime = 0;
while (!glfwWindowShouldClose(id->window)) {
glfwPollEvents();
const auto ticks = ticksMs(ctx);
if (id->wakeupTime <= ticks && id->eventHandler) {
auto sleepTime = id->eventHandler(ctx);
if (sleepTime >= 0) {
id->wakeupTime = ticks + static_cast<unsigned>(sleepTime);
} else {
id->wakeupTime = ~uint64_t(0);
if (id->eventHandler) {
if (id->wakeupTime <= ticks) {
sleepTime = id->eventHandler(ctx);
if (sleepTime >= 0) {
id->wakeupTime = ticks + static_cast<unsigned>(sleepTime);
} else {
id->wakeupTime = ~uint64_t(0);
}
}
} else {
sleepTime = 2;
}
draw(ctx);
glfwSwapBuffers(id->window);
glfwWaitEventsTimeout(sleepTime);
}
// destroy GLFW window
renderer::shutdown(ctx, ctx->rendererData<void>());

View File

@ -31,7 +31,7 @@ static void handleKeyPress(Context *ctx, int key) noexcept {
}
static void handleGlfwKeyEvent(GLFWwindow *window, int key, int, int action, int) noexcept {
const auto ctx = static_cast<Context *>(glfwGetWindowUserPointer(window));
const auto ctx = static_cast<Context*>(glfwGetWindowUserPointer(window));
if (action == GLFW_PRESS) {
handleKeyPress(ctx, key);
}