Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add App and SubApp resource methods #13425

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
431 changes: 407 additions & 24 deletions crates/bevy_app/src/app.rs

Large diffs are not rendered by default.

90 changes: 90 additions & 0 deletions crates/bevy_app/src/sub_app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,96 @@ impl SubApp {
self
}

/// See [`App::insert_non_resource`].
pub fn insert_non_send_resource<R: 'static>(&mut self, resource: R) -> &mut Self {
self.world.insert_non_send_resource(resource);
self
}

/// See [`App::init_non_send_resource`].
pub fn init_non_send_resource<R: 'static + FromWorld>(&mut self) -> &mut Self {
self.world.init_non_send_resource::<R>();
self
}

/// See [`App::remove_resource`].
pub fn remove_resource<R: Resource>(&mut self) -> Option<R> {
self.world.remove_resource::<R>()
}

/// See [`App::remove_non_send_resource`].
pub fn remove_non_send_resource<R: 'static>(&mut self) -> Option<R> {
self.world.remove_non_send_resource::<R>()
}

/// See [`App::contains_resource`].
pub fn contains_resource<R: Resource>(&self) -> bool {
self.world.contains_resource::<R>()
}

/// See [`App::contains_non_send_resource`].
pub fn contains_non_send_resource<R: 'static>(&self) -> bool {
self.world.contains_non_send_resource::<R>()
}

/// See [`App::resource`].
pub fn resource<R: Resource>(&self) -> &R {
self.world.resource()
}

/// See [`App::resource_ref`].
pub fn resource_ref<R: Resource>(&self) -> Res<R> {
self.world.resource_ref()
}

/// See [`App::resource_mut`].
pub fn resource_mut<R: Resource>(&mut self) -> Mut<'_, R> {
self.world.resource_mut()
}

/// See [`App::get_resource`].
pub fn get_resource<R: Resource>(&self) -> Option<&R> {
self.world.get_resource()
}

/// See [`App::get_resource_ref`].
pub fn get_resource_ref<R: Resource>(&self) -> Option<Res<R>> {
self.world.get_resource_ref()
}

/// See [`App::get_resource_mut`].
pub fn get_resource_mut<R: Resource>(&mut self) -> Option<Mut<'_, R>> {
self.world.get_resource_mut()
}

/// See [`App::get_resource_or_insert_with`].
pub fn get_resource_or_insert_with<R: Resource>(
&mut self,
func: impl FnOnce() -> R,
) -> Mut<'_, R> {
self.world.get_resource_or_insert_with(func)
}

/// See [`App::non_send_resource`].
pub fn non_send_resource<R: 'static>(&self) -> &R {
self.world.non_send_resource()
}

/// See [`App::non_send_resource_mut`].
pub fn non_send_resource_mut<R: 'static>(&mut self) -> Mut<'_, R> {
self.world.non_send_resource_mut()
}

/// See [`App::get_non_send_resource`].
pub fn get_non_send_resource<R: 'static>(&self) -> Option<&R> {
self.world.get_non_send_resource()
}

/// See [`App::get_non_send_resource_mut`].
pub fn get_non_send_resource_mut<R: 'static>(&mut self) -> Option<Mut<'_, R>> {
self.world.get_non_send_resource_mut()
}

/// See [`App::add_systems`].
pub fn add_systems<M>(
&mut self,
Expand Down
6 changes: 3 additions & 3 deletions crates/bevy_asset/src/io/embedded/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ pub fn watched_path(_source_file_path: &'static str, _asset_path: &'static str)
#[macro_export]
macro_rules! load_internal_asset {
($app: ident, $handle: expr, $path_str: expr, $loader: expr) => {{
let mut assets = $app.world_mut().resource_mut::<$crate::Assets<_>>();
let mut assets = $app.resource_mut::<$crate::Assets<_>>();
assets.insert($handle.id(), ($loader)(
include_str!($path_str),
std::path::Path::new(file!())
Expand All @@ -265,7 +265,7 @@ macro_rules! load_internal_asset {
}};
// we can't support params without variadic arguments, so internal assets with additional params can't be hot-reloaded
($app: ident, $handle: ident, $path_str: expr, $loader: expr $(, $param:expr)+) => {{
let mut assets = $app.world_mut().resource_mut::<$crate::Assets<_>>();
let mut assets = $app.resource_mut::<$crate::Assets<_>>();
assets.insert($handle.id(), ($loader)(
include_str!($path_str),
std::path::Path::new(file!())
Expand All @@ -282,7 +282,7 @@ macro_rules! load_internal_asset {
#[macro_export]
macro_rules! load_internal_binary_asset {
($app: ident, $handle: expr, $path_str: expr, $loader: expr) => {{
let mut assets = $app.world_mut().resource_mut::<$crate::Assets<_>>();
let mut assets = $app.resource_mut::<$crate::Assets<_>>();
assets.insert(
$handle.id(),
($loader)(
Expand Down
22 changes: 11 additions & 11 deletions crates/bevy_asset/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ impl Plugin for AssetPlugin {
}
match self.mode {
AssetMode::Unprocessed => {
let mut builders = app.world_mut().resource_mut::<AssetSourceBuilders>();
let mut builders = app.resource_mut::<AssetSourceBuilders>();
let sources = builders.build_sources(watch, false);

app.insert_resource(AssetServer::new_with_meta_check(
Expand All @@ -183,7 +183,7 @@ impl Plugin for AssetPlugin {
AssetMode::Processed => {
#[cfg(feature = "asset_processor")]
{
let mut builders = app.world_mut().resource_mut::<AssetSourceBuilders>();
let mut builders = app.resource_mut::<AssetSourceBuilders>();
let processor = AssetProcessor::new(&mut builders);
let mut sources = builders.build_sources(false, watch);
sources.gate_on_processor(processor.data.clone());
Expand All @@ -200,7 +200,7 @@ impl Plugin for AssetPlugin {
}
#[cfg(not(feature = "asset_processor"))]
{
let mut builders = app.world_mut().resource_mut::<AssetSourceBuilders>();
let mut builders = app.resource_mut::<AssetSourceBuilders>();
let sources = builders.build_sources(false, watch);
app.insert_resource(AssetServer::new_with_meta_check(
sources,
Expand Down Expand Up @@ -364,7 +364,7 @@ impl AssetApp for App {
self.world()
.resource::<AssetServer>()
.register_asset(&assets);
if self.world().contains_resource::<AssetProcessor>() {
if self.contains_resource::<AssetProcessor>() {
let processor = self.world().resource::<AssetProcessor>();
// The processor should have its own handle provider separate from the Asset storage
// to ensure the id spaces are entirely separate. Not _strictly_ necessary, but
Expand Down Expand Up @@ -906,7 +906,7 @@ mod tests {
});

{
let mut texts = app.world_mut().resource_mut::<Assets<CoolText>>();
let mut texts = app.resource_mut::<Assets<CoolText>>();
let a = texts.get_mut(a_id).unwrap();
a.text = "Changed".to_string();
}
Expand All @@ -925,8 +925,8 @@ mod tests {
0,
"SubText asset entities should be despawned when no more handles exist"
);
let events = app.world_mut().remove_resource::<StoredEvents>().unwrap();
let id_results = app.world_mut().remove_resource::<IdResults>().unwrap();
let events = app.remove_resource::<StoredEvents>().unwrap();
let id_results = app.remove_resource::<IdResults>().unwrap();
let expected_events = vec![
AssetEvent::Added { id: a_id },
AssetEvent::LoadedWithDependencies {
Expand Down Expand Up @@ -1190,7 +1190,7 @@ mod tests {
);
// remove event is emitted
app.update();
let events = std::mem::take(&mut app.world_mut().resource_mut::<StoredEvents>().0);
let events = std::mem::take(&mut app.resource_mut::<StoredEvents>().0);
let expected_events = vec![
AssetEvent::Added { id },
AssetEvent::Unused { id },
Expand All @@ -1211,14 +1211,14 @@ mod tests {
// TODO: ideally it doesn't take two updates for the added event to emit
app.update();

let events = std::mem::take(&mut app.world_mut().resource_mut::<StoredEvents>().0);
let events = std::mem::take(&mut app.resource_mut::<StoredEvents>().0);
let expected_events = vec![AssetEvent::Added { id: a_handle.id() }];
assert_eq!(events, expected_events);

gate_opener.open(dep_path);
loop {
app.update();
let events = std::mem::take(&mut app.world_mut().resource_mut::<StoredEvents>().0);
let events = std::mem::take(&mut app.resource_mut::<StoredEvents>().0);
if events.is_empty() {
continue;
}
Expand All @@ -1232,7 +1232,7 @@ mod tests {
break;
}
app.update();
let events = std::mem::take(&mut app.world_mut().resource_mut::<StoredEvents>().0);
let events = std::mem::take(&mut app.resource_mut::<StoredEvents>().0);
let expected_events = vec![AssetEvent::Added {
id: dep_handle.id(),
}];
Expand Down
21 changes: 14 additions & 7 deletions crates/bevy_ecs/src/world/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1189,7 +1189,7 @@ impl World {
});
}

/// Removes the resource of a given type and returns it, if it exists. Otherwise returns `None`.
/// Removes the resource of a given type and returns it, if it exists. Otherwise, returns `None`.
#[inline]
pub fn remove_resource<R: Resource>(&mut self) -> Option<R> {
let component_id = self.components.get_resource_id(TypeId::of::<R>())?;
Expand Down Expand Up @@ -1221,7 +1221,7 @@ impl World {
unsafe { Some(ptr.read::<R>()) }
}

/// Returns `true` if a resource of type `R` exists. Otherwise returns `false`.
/// Returns `true` if a resource of type `R` exists. Otherwise, returns `false`.
#[inline]
pub fn contains_resource<R: Resource>(&self) -> bool {
self.components
Expand All @@ -1231,9 +1231,16 @@ impl World {
.unwrap_or(false)
}

/// Returns `true` if a resource of type `R` exists. Otherwise returns `false`.
/// Returns `true` if a resource of type `R` exists. Otherwise, returns `false`.
#[inline]
#[deprecated = "Use `World::contains_non_send_resource` instead"]
pub fn contains_non_send<R: 'static>(&self) -> bool {
self.contains_non_send_resource::<R>()
}

/// Returns `true` if a resource of type `R` exists. Otherwise, returns `false`.
#[inline]
pub fn contains_non_send_resource<R: 'static>(&self) -> bool {
self.components
.get_resource_id(TypeId::of::<R>())
.and_then(|component_id| self.storages.non_send_resources.get(component_id))
Expand Down Expand Up @@ -1501,7 +1508,7 @@ impl World {
}

/// Gets a reference to the non-send resource of the given type, if it exists.
/// Otherwise returns `None`.
/// Otherwise, returns `None`.
///
/// # Panics
/// This function will panic if it isn't called from the same thread that the resource was inserted from.
Expand All @@ -1514,7 +1521,7 @@ impl World {
}

/// Gets a mutable reference to the non-send resource of the given type, if it exists.
/// Otherwise returns `None`.
/// Otherwise, returns `None`.
///
/// # Panics
/// This function will panic if it isn't called from the same thread that the resource was inserted from.
Expand Down Expand Up @@ -2379,7 +2386,7 @@ impl World {
}
}

/// Removes the resource of a given type, if it exists. Otherwise returns `None`.
/// Removes the resource of a given type, if it exists. Otherwise, returns `None`.
///
/// **You should prefer to use the typed API [`World::remove_resource`] where possible and only
/// use this in cases where the actual types are not known at compile time.**
Expand All @@ -2391,7 +2398,7 @@ impl World {
Some(())
}

/// Removes the resource of a given type, if it exists. Otherwise returns `None`.
/// Removes the resource of a given type, if it exists. Otherwise, returns `None`.
///
/// **You should prefer to use the typed API [`World::remove_resource`] where possible and only
/// use this in cases where the actual types are not known at compile time.**
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_gizmos/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ pub trait AppGizmoBuilder {

impl AppGizmoBuilder for App {
fn init_gizmo_group<Config: GizmoConfigGroup>(&mut self) -> &mut Self {
if self.world().contains_resource::<GizmoStorage<Config, ()>>() {
if self.contains_resource::<GizmoStorage<Config, ()>>() {
return self;
}

Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_pbr/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,7 @@ impl Plugin for PbrPlugin {
.init_resource::<LightMeta>();

let shadow_pass_node = ShadowPassNode::new(render_app.world_mut());
let mut graph = render_app.world_mut().resource_mut::<RenderGraph>();
let mut graph = render_app.resource_mut::<RenderGraph>();
let draw_3d_graph = graph.get_sub_graph_mut(Core3d).unwrap();
draw_3d_graph.add_node(NodePbr::ShadowPass, shadow_pass_node);
draw_3d_graph.add_node_edge(NodePbr::ShadowPass, Node3d::StartMainPass);
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_render/src/camera/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ impl Plugin for CameraPlugin {
.add_systems(ExtractSchedule, extract_cameras)
.add_systems(Render, sort_cameras.in_set(RenderSet::ManageViews));
let camera_driver_node = CameraDriverNode::new(render_app.world_mut());
let mut render_graph = render_app.world_mut().resource_mut::<RenderGraph>();
let mut render_graph = render_app.resource_mut::<RenderGraph>();
render_graph.add_node(crate::graph::CameraDriverLabel, camera_driver_node);
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_render/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ impl Plugin for RenderPlugin {
Shader::from_wgsl
);
if let Some(future_renderer_resources) =
app.world_mut().remove_resource::<FutureRendererResources>()
app.remove_resource::<FutureRendererResources>()
{
let (device, queue, adapter_info, render_adapter, instance) =
future_renderer_resources.0.lock().unwrap().take().unwrap();
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_render/src/pipelined_rendering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ impl Plugin for PipelinedRenderingPlugin {

// clone main thread executor to render world
let executor = app.world().get_resource::<MainThreadExecutor>().unwrap();
render_app.world_mut().insert_resource(executor.clone());
render_app.insert_resource(executor.clone());

render_to_app_sender.send_blocking(render_app).unwrap();

Expand Down
3 changes: 1 addition & 2 deletions crates/bevy_render/src/texture/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,7 @@ impl Plugin for ImagePlugin {
.init_asset::<Image>()
.register_asset_reflect::<Image>();

app.world_mut()
.resource_mut::<Assets<Image>>()
app.resource_mut::<Assets<Image>>()
.insert(&Handle::default(), Image::default());
#[cfg(feature = "basis-universal")]
if let Some(processor) = app
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_scene/src/bundle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ mod tests {
);

// let's try to delete the scene
let mut scene_spawner = app.world_mut().resource_mut::<SceneSpawner>();
let mut scene_spawner = app.resource_mut::<SceneSpawner>();
scene_spawner.despawn(&scene_handle);

// run the scene spawner system to despawn the scene
Expand Down
3 changes: 1 addition & 2 deletions crates/bevy_sprite/src/mesh2d/color_material.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@ impl Plugin for ColorMaterialPlugin {
app.add_plugins(Material2dPlugin::<ColorMaterial>::default())
.register_asset_reflect::<ColorMaterial>();

app.world_mut()
.resource_mut::<Assets<ColorMaterial>>()
app.resource_mut::<Assets<ColorMaterial>>()
.insert(
&Handle::<ColorMaterial>::default(),
ColorMaterial {
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_ui/src/render/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ pub fn build_ui_render(app: &mut App) {
// Render graph
let ui_graph_2d = get_ui_graph(render_app);
let ui_graph_3d = get_ui_graph(render_app);
let mut graph = render_app.world_mut().resource_mut::<RenderGraph>();
let mut graph = render_app.resource_mut::<RenderGraph>();

if let Some(graph_2d) = graph.get_sub_graph_mut(Core2d) {
graph_2d.add_sub_graph(SubGraphUi, ui_graph_2d);
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_window/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ impl Plugin for WindowPlugin {
.spawn(primary_window.clone())
.insert(PrimaryWindow)
.id();
if let Some(mut focus) = app.world_mut().get_resource_mut::<Focus>() {
if let Some(mut focus) = app.get_resource_mut::<Focus>() {
**focus = Some(initial_focus);
}
}
Expand Down
3 changes: 1 addition & 2 deletions crates/bevy_winit/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -276,8 +276,7 @@ pub fn winit_runner(mut app: App) -> AppExit {
.remove_non_send_resource::<EventLoop<UserEvent>>()
.unwrap();

app.world_mut()
.insert_non_send_resource(event_loop.create_proxy());
app.insert_non_send_resource(event_loop.create_proxy());

let mut runner_state = WinitAppRunnerState::default();

Expand Down
3 changes: 1 addition & 2 deletions crates/bevy_winit/src/winit_event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,6 @@ pub(crate) fn forward_winit_events(buffered_events: &mut Vec<WinitEvent>, app: &
}
}
}
app.world_mut()
.resource_mut::<Events<WinitEvent>>()
app.resource_mut::<Events<WinitEvent>>()
.send_batch(buffered_events.drain(..));
}
Loading