From 8adb68630ee63c1bf615ada2907cd64e3e959ac4 Mon Sep 17 00:00:00 2001 From: lisyarus Date: Sat, 1 Feb 2025 07:16:58 +0100 Subject: [PATCH] Change mainloop for web builds --- libs/sdl2/source/main.cpp | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/libs/sdl2/source/main.cpp b/libs/sdl2/source/main.cpp index 20d433b0..1307cf03 100644 --- a/libs/sdl2/source/main.cpp +++ b/libs/sdl2/source/main.cpp @@ -11,6 +11,18 @@ #include #include +#ifdef __EMSCRIPTEN__ + #include + #include + #include + + struct em_state + { + std::unique_ptr application; + std::unique_ptr window; + } em_state; +#endif + #undef main int main(int argc, char ** argv) try @@ -40,7 +52,12 @@ int main(int argc, char ** argv) try auto const factory = app::make_application_factory(); auto const options = factory->options(); +#ifdef __EMSCRIPTEN__ + em_state.window = std::make_unique(options); + auto & window = *em_state.window; +#else sdl2::window window(options); +#endif app::application::context context; for (int i = 0; i < argc; ++i) @@ -61,7 +78,13 @@ int main(int argc, char ** argv) try context.device = window.wgpu_device(); #endif + +#ifdef __EMSCRIPTEN__ + em_state.application = factory->create(options, context); + auto application = em_state.application.get(); +#else auto application = factory->create(options, context); +#endif if (!application) return EXIT_FAILURE; @@ -75,6 +98,21 @@ int main(int argc, char ** argv) try SDL_StopTextInput(); +#ifdef __EMSCRIPTEN__ + emscripten_request_animation_frame_loop([](double, void*) -> EM_BOOL { + if (sdl2::poll_events(*em_state.application)) + em_state.application->stop(); + + if (!em_state.application->running()) + return EM_FALSE; + + em_state.application->update(); + em_state.application->present(); + em_state.window->swap(); + + return EM_TRUE; + }, nullptr); +#else while (application->running()) { if (sdl2::poll_events(*application)) @@ -84,6 +122,7 @@ int main(int argc, char ** argv) try application->present(); window.swap(); } +#endif log::info() << "Quitting"; return EXIT_SUCCESS;