From ac9fb32c2dfaf25ad9e7f13bc81354b7276f8c8b Mon Sep 17 00:00:00 2001 From: Wei Xu <1222863+xuwaters@users.noreply.github.com> Date: Tue, 3 Dec 2024 09:00:15 -0800 Subject: [PATCH] Update winit_runner to use spawn_app for wasm32 target --- crates/bevy_winit/src/state.rs | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/crates/bevy_winit/src/state.rs b/crates/bevy_winit/src/state.rs index a9d4831592ff2..c9ffcc17d19d7 100644 --- a/crates/bevy_winit/src/state.rs +++ b/crates/bevy_winit/src/state.rs @@ -32,6 +32,8 @@ use winit::{ event_loop::{ActiveEventLoop, ControlFlow, EventLoop}, window::WindowId, }; +#[cfg(target_arch = "wasm32")] +use winit::platform::web::EventLoopExtWebSys; use bevy_window::{ AppLifecycle, CursorEntered, CursorLeft, CursorMoved, FileDragAndDrop, Ime, RequestRedraw, @@ -858,16 +860,23 @@ pub fn winit_runner(mut app: App) -> AppExit { let mut runner_state = WinitAppRunnerState::new(app); trace!("starting winit event loop"); - // TODO(clean): the winit docs mention using `spawn` instead of `run` on Wasm. - if let Err(err) = event_loop.run_app(&mut runner_state) { - error!("winit event loop returned an error: {err}"); + // The winit docs mention using `spawn` instead of `run` on Wasm. + // https://docs.rs/winit/latest/winit/platform/web/trait.EventLoopExtWebSys.html#tymethod.spawn_app + cfg_if::cfg_if! { + if #[cfg(target_arch = "wasm32")] { + event_loop.spawn_app(runner_state); + AppExit::Success + } else { + if let Err(err) = event_loop.run_app(&mut runner_state) { + error!("winit event loop returned an error: {err}"); + } + // If everything is working correctly then the event loop only exits after it's sent an exit code. + runner_state.app_exit.unwrap_or_else(|| { + error!("Failed to receive a app exit code! This is a bug"); + AppExit::error() + }) + } } - - // If everything is working correctly then the event loop only exits after it's sent an exit code. - runner_state.app_exit.unwrap_or_else(|| { - error!("Failed to receive a app exit code! This is a bug"); - AppExit::error() - }) } pub(crate) fn react_to_resize(