Skip to content

Commit

Permalink
Ensure clean exit
Browse files Browse the repository at this point in the history
Fixes two issues related to bevyengine#13208.

First, we ensure render resources for a window are always dropped first
to ensure that the `winit::Window` always drops on the main thread when
it is removed from `WinitWindows`. Previously, changes in bevyengine#12978 caused
the window to drop in the render world, causing issues.

We accomplish this by delaying despawning the window by a frame by
inserting a marker component `ClosingWindow` that indicates the window
has been requested to close and is in the process of closing. The
render world now responds to the equivalent `WindowClosing` event
rather than `WindowCloseed` which now fires after the render resources
are guarunteed to be cleaned up.

Secondly, fixing the above caused (revealed?) that additional events
were being delivered to the the event loop handler after exit had
already been requested: in my testing `RedrawRequested` and
`LoopExiting`. This caused errors to be reported try to send an
exit event on the close channel. There are two options here:
    - Guard the handler so no additional events are delivered once the
    app is exiting. I considered this but worried it might be
    confusing or bug prone if in the future someone wants to handle
   `LoopExiting` or some other event to clean-up while exiting.
    - Only send an exit signal if we are not already exiting. It
    doesn't appear to cause any problems to handle the extra events
    so this seems safer.
Fixing this also appears to have fixed bevyengine#13231.
  • Loading branch information
tychedelia committed May 4, 2024
1 parent 4083750 commit 3d3022a
Show file tree
Hide file tree
Showing 7 changed files with 53 additions and 12 deletions.
10 changes: 5 additions & 5 deletions crates/bevy_render/src/view/window/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use bevy_ecs::{entity::EntityHashMap, prelude::*};
use bevy_utils::warn_once;
use bevy_utils::{default, tracing::debug, HashSet};
use bevy_window::{
CompositeAlphaMode, PresentMode, PrimaryWindow, RawHandleWrapper, Window, WindowClosed,
CompositeAlphaMode, PresentMode, PrimaryWindow, RawHandleWrapper, Window, WindowClosing,
};
use std::{
num::NonZeroU32,
Expand Down Expand Up @@ -117,7 +117,7 @@ impl DerefMut for ExtractedWindows {
fn extract_windows(
mut extracted_windows: ResMut<ExtractedWindows>,
screenshot_manager: Extract<Res<ScreenshotManager>>,
mut closed: Extract<EventReader<WindowClosed>>,
mut closing: Extract<EventReader<WindowClosing>>,
windows: Extract<Query<(Entity, &Window, &RawHandleWrapper, Option<&PrimaryWindow>)>>,
mut removed: Extract<RemovedComponents<RawHandleWrapper>>,
mut window_surfaces: ResMut<WindowSurfaces>,
Expand Down Expand Up @@ -177,9 +177,9 @@ fn extract_windows(
}
}

for closed_window in closed.read() {
extracted_windows.remove(&closed_window.window);
window_surfaces.remove(&closed_window.window);
for closing_window in closing.read() {
extracted_windows.remove(&closing_window.window);
window_surfaces.remove(&closing_window.window);
}
for removed_window in removed.read() {
extracted_windows.remove(&removed_window);
Expand Down
14 changes: 14 additions & 0 deletions crates/bevy_window/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,20 @@ pub struct WindowClosed {
pub window: Entity,
}

/// An event that is sent whenever a window is closing. This will be sent when
/// after a [`WindowCloseRequested`] event is received and the window is in the process of closing.
#[derive(Event, Debug, Clone, PartialEq, Eq, Reflect)]
#[reflect(Debug, PartialEq)]
#[cfg_attr(
feature = "serialize",
derive(serde::Serialize, serde::Deserialize),
reflect(Serialize, Deserialize)
)]
pub struct WindowClosing {
/// Window that has been requested to close and is the process of closing.
pub window: Entity,
}

/// An event that is sent whenever a window is destroyed by the underlying window system.
///
/// Note that if your application only has a single window, this event may be your last chance to
Expand Down
2 changes: 2 additions & 0 deletions crates/bevy_window/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ impl Plugin for WindowPlugin {
#[allow(deprecated)]
app.add_event::<WindowResized>()
.add_event::<WindowCreated>()
.add_event::<WindowClosing>()
.add_event::<WindowClosed>()
.add_event::<WindowCloseRequested>()
.add_event::<WindowDestroyed>()
Expand Down Expand Up @@ -139,6 +140,7 @@ impl Plugin for WindowPlugin {
.register_type::<RequestRedraw>()
.register_type::<WindowCreated>()
.register_type::<WindowCloseRequested>()
.register_type::<WindowClosing>()
.register_type::<WindowClosed>()
.register_type::<CursorMoved>()
.register_type::<CursorEntered>()
Expand Down
13 changes: 10 additions & 3 deletions crates/bevy_window/src/system.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{PrimaryWindow, Window, WindowCloseRequested};
use crate::{ClosingWindow, PrimaryWindow, Window, WindowCloseRequested};

use bevy_app::AppExit;
use bevy_ecs::prelude::*;
Expand Down Expand Up @@ -39,8 +39,15 @@ pub fn exit_on_primary_closed(
/// Ensure that you read the caveats documented on that field if doing so.
///
/// [`WindowPlugin`]: crate::WindowPlugin
pub fn close_when_requested(mut commands: Commands, mut closed: EventReader<WindowCloseRequested>) {
pub fn close_when_requested(
mut commands: Commands,
mut closed: EventReader<WindowCloseRequested>,
closing: Query<Entity, With<ClosingWindow>>,
) {
for window in closing.iter() {
commands.entity(window).despawn();
}
for event in closed.read() {
commands.entity(event.window).despawn();
commands.entity(event.window).insert(ClosingWindow);
}
}
5 changes: 5 additions & 0 deletions crates/bevy_window/src/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1171,6 +1171,11 @@ impl Default for EnabledButtons {
}
}

/// Marker component for a [`Window`] that has been requested to close and
/// is in the process of closing (on the next frame).
#[derive(Component)]
pub struct ClosingWindow;

#[cfg(test)]
mod tests {
use super::*;
Expand Down
5 changes: 5 additions & 0 deletions crates/bevy_winit/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -776,6 +776,11 @@ fn handle_winit_event(
}

if let Some(app_exit) = app.should_exit() {
// The event loop is in the process of exiting, but we might still be processing events.
if event_loop.exiting() {
return;
}

if let Err(err) = exit_notify.try_send(app_exit) {
error!("Failed to send a app exit notification! This is a bug. Reason: {err}");
};
Expand Down
16 changes: 12 additions & 4 deletions crates/bevy_winit/src/system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,16 @@ use bevy_ecs::{
};
use bevy_utils::tracing::{error, info, warn};
use bevy_window::{
RawHandleWrapper, Window, WindowClosed, WindowCreated, WindowMode, WindowResized,
ClosingWindow, RawHandleWrapper, Window, WindowClosed, WindowClosing, WindowCreated,
WindowMode, WindowResized,
};

use winit::{
dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize},
event_loop::EventLoopWindowTarget,
};

use bevy_ecs::query::With;
#[cfg(target_arch = "wasm32")]
use winit::platform::web::WindowExtWebSys;

Expand Down Expand Up @@ -97,18 +99,24 @@ pub fn create_windows<F: QueryFilter + 'static>(
}

pub(crate) fn despawn_windows(
closing: Query<Entity, With<ClosingWindow>>,
mut closed: RemovedComponents<Window>,
window_entities: Query<&Window>,
mut close_events: EventWriter<WindowClosed>,
mut closing_events: EventWriter<WindowClosing>,
mut closed_events: EventWriter<WindowClosed>,
mut winit_windows: NonSendMut<WinitWindows>,
) {
for window in closing.iter() {
closing_events.send(WindowClosing { window });
}
for window in closed.read() {
info!("Closing window {:?}", window);
// Guard to verify that the window is in fact actually gone,
// rather than having the component added and removed in the same frame.
// rather than having the component added
// and removed in the same frame.
if !window_entities.contains(window) {
winit_windows.remove_window(window);
close_events.send(WindowClosed { window });
closed_events.send(WindowClosed { window });
}
}
}
Expand Down

0 comments on commit 3d3022a

Please sign in to comment.