Make get_resource (and friends) infallible (#4047)

# Objective

- In the large majority of cases, users were calling `.unwrap()` immediately after `.get_resource`.
- Attempting to add more helpful error messages here resulted in endless manual boilerplate (see #3899 and the linked PRs).

## Solution

- Add an infallible variant named `.resource` and so on.
- Use these infallible variants over `.get_resource().unwrap()` across the code base.

## Notes

I did not provide equivalent methods on `WorldCell`, in favor of removing it entirely in #3939.

## Migration Guide

Infallible variants of `.get_resource` have been added that implicitly panic, rather than needing to be unwrapped.

Replace `world.get_resource::<Foo>().unwrap()` with `world.resource::<Foo>()`.

## Impact

- `.unwrap` search results before: 1084
- `.unwrap` search results after: 942
- internal `unwrap_or_else` calls added: 4
- trivial unwrap calls removed from tests and code: 146
- uses of the new `try_get_resource` API: 11
- percentage of the time the unwrapping API was used internally: 93%
This commit is contained in:
Alice Cecile 2022-02-27 22:37:18 +00:00
parent 44bf66e436
commit 557ab9897a
52 changed files with 277 additions and 276 deletions

View file

@ -839,10 +839,7 @@ impl App {
#[cfg(feature = "bevy_reflect")]
pub fn register_type<T: bevy_reflect::GetTypeRegistration>(&mut self) -> &mut Self {
{
let registry = self
.world
.get_resource_mut::<bevy_reflect::TypeRegistryArc>()
.unwrap();
let registry = self.world.resource_mut::<bevy_reflect::TypeRegistryArc>();
registry.write().register::<T>();
}
self

View file

@ -794,24 +794,18 @@ mod test {
app.add_system(update_asset_storage_system::<PngAsset>.after(FreeUnusedAssets));
fn load_asset(path: AssetPath, world: &World) -> HandleUntyped {
let asset_server = world.get_resource::<AssetServer>().unwrap();
let asset_server = world.resource::<AssetServer>();
let id = futures_lite::future::block_on(asset_server.load_async(path.clone(), true))
.unwrap();
asset_server.get_handle_untyped(id)
}
fn get_asset(id: impl Into<HandleId>, world: &World) -> Option<&PngAsset> {
world
.get_resource::<Assets<PngAsset>>()
.unwrap()
.get(id.into())
world.resource::<Assets<PngAsset>>().get(id.into())
}
fn get_load_state(id: impl Into<HandleId>, world: &World) -> LoadState {
world
.get_resource::<AssetServer>()
.unwrap()
.get_load_state(id.into())
world.resource::<AssetServer>().get_load_state(id.into())
}
// ---

View file

@ -287,7 +287,7 @@ impl AddAsset for App {
return self;
}
let assets = {
let asset_server = self.world.get_resource::<AssetServer>().unwrap();
let asset_server = self.world.resource::<AssetServer>();
asset_server.register_asset_type::<T>()
};
@ -307,8 +307,7 @@ impl AddAsset for App {
self.add_system(crate::debug_asset_server::sync_debug_assets::<T>);
let mut app = self
.world
.get_non_send_resource_mut::<crate::debug_asset_server::DebugAssetApp>()
.unwrap();
.non_send_resource_mut::<crate::debug_asset_server::DebugAssetApp>();
app.add_asset::<T>()
.init_resource::<crate::debug_asset_server::HandleMap<T>>();
}
@ -331,8 +330,7 @@ impl AddAsset for App {
{
let mut app = self
.world
.get_non_send_resource_mut::<crate::debug_asset_server::DebugAssetApp>()
.unwrap();
.non_send_resource_mut::<crate::debug_asset_server::DebugAssetApp>();
app.init_asset_loader::<T>();
}
self
@ -342,10 +340,7 @@ impl AddAsset for App {
where
T: AssetLoader,
{
self.world
.get_resource_mut::<AssetServer>()
.expect("AssetServer does not exist. Consider adding it as a resource.")
.add_loader(loader);
self.world.resource_mut::<AssetServer>().add_loader(loader);
self
}
}
@ -357,8 +352,7 @@ macro_rules! load_internal_asset {
{
let mut debug_app = $app
.world
.get_non_send_resource_mut::<bevy_asset::debug_asset_server::DebugAssetApp>()
.unwrap();
.non_send_resource_mut::<bevy_asset::debug_asset_server::DebugAssetApp>();
bevy_asset::debug_asset_server::register_handle_with_loader(
$loader,
&mut debug_app,
@ -367,10 +361,7 @@ macro_rules! load_internal_asset {
$path_str,
);
}
let mut assets = $app
.world
.get_resource_mut::<bevy_asset::Assets<_>>()
.unwrap();
let mut assets = $app.world.resource_mut::<bevy_asset::Assets<_>>();
assets.set_untracked($handle, ($loader)(include_str!($path_str)));
}};
}
@ -379,10 +370,7 @@ macro_rules! load_internal_asset {
#[macro_export]
macro_rules! load_internal_asset {
($app: ident, $handle: ident, $path_str: expr, $loader: expr) => {{
let mut assets = $app
.world
.get_resource_mut::<bevy_asset::Assets<_>>()
.unwrap();
let mut assets = $app.world.resource_mut::<bevy_asset::Assets<_>>();
assets.set_untracked($handle, ($loader)(include_str!($path_str)));
}};
}
@ -402,10 +390,10 @@ mod tests {
app.add_plugin(bevy_core::CorePlugin)
.add_plugin(crate::AssetPlugin);
app.add_asset::<MyAsset>();
let mut assets_before = app.world.get_resource_mut::<Assets<MyAsset>>().unwrap();
let mut assets_before = app.world.resource_mut::<Assets<MyAsset>>();
let handle = assets_before.add(MyAsset);
app.add_asset::<MyAsset>(); // Ensure this doesn't overwrite the Asset
let assets_after = app.world.get_resource_mut::<Assets<MyAsset>>().unwrap();
let assets_after = app.world.resource_mut::<Assets<MyAsset>>();
assert!(assets_after.get(handle).is_some());
}
}

View file

@ -81,13 +81,8 @@ pub fn create_platform_default_asset_io(app: &mut App) -> Box<dyn AssetIo> {
impl Plugin for AssetPlugin {
fn build(&self, app: &mut App) {
if app.world.get_resource::<AssetServer>().is_none() {
let task_pool = app
.world
.get_resource::<IoTaskPool>()
.expect("`IoTaskPool` resource not found.")
.0
.clone();
if !app.world.contains_resource::<AssetServer>() {
let task_pool = app.world.resource::<IoTaskPool>().0.clone();
let source = create_platform_default_asset_io(app);

View file

@ -209,7 +209,7 @@ impl System for FixedTimestep {
)));
self.internal_system.initialize(world);
if let Some(ref label) = self.state.label {
let mut fixed_timesteps = world.get_resource_mut::<FixedTimesteps>().unwrap();
let mut fixed_timesteps = world.resource_mut::<FixedTimesteps>();
fixed_timesteps.fixed_timesteps.insert(
label.clone(),
FixedTimestepState {
@ -257,25 +257,25 @@ mod test {
// if time does not progress, the step does not run
schedule.run(&mut world);
schedule.run(&mut world);
assert_eq!(0, *world.get_resource::<Count>().unwrap());
assert_eq!(0, *world.resource::<Count>());
assert_eq!(0., get_accumulator_deciseconds(&world));
// let's progress less than one step
advance_time(&mut world, instance, 0.4);
schedule.run(&mut world);
assert_eq!(0, *world.get_resource::<Count>().unwrap());
assert_eq!(0, *world.resource::<Count>());
assert_eq!(4., get_accumulator_deciseconds(&world));
// finish the first step with 0.1s above the step length
advance_time(&mut world, instance, 0.6);
schedule.run(&mut world);
assert_eq!(1, *world.get_resource::<Count>().unwrap());
assert_eq!(1, *world.resource::<Count>());
assert_eq!(1., get_accumulator_deciseconds(&world));
// runs multiple times if the delta is multiple step lengths
advance_time(&mut world, instance, 1.7);
schedule.run(&mut world);
assert_eq!(3, *world.get_resource::<Count>().unwrap());
assert_eq!(3, *world.resource::<Count>());
assert_eq!(2., get_accumulator_deciseconds(&world));
}
@ -285,15 +285,13 @@ mod test {
fn advance_time(world: &mut World, instance: Instant, seconds: f32) {
world
.get_resource_mut::<Time>()
.unwrap()
.resource_mut::<Time>()
.update_with_instant(instance.add(Duration::from_secs_f32(seconds)));
}
fn get_accumulator_deciseconds(world: &World) -> f64 {
world
.get_resource::<FixedTimesteps>()
.unwrap()
.resource::<FixedTimesteps>()
.get(LABEL)
.unwrap()
.accumulator

View file

@ -50,8 +50,8 @@ impl Node for ClearPassNode {
world: &World,
) -> Result<(), NodeRunError> {
let mut cleared_targets = HashSet::new();
let clear_color = world.get_resource::<ClearColor>().unwrap();
let render_target_clear_colors = world.get_resource::<RenderTargetClearColors>().unwrap();
let clear_color = world.resource::<ClearColor>();
let render_target_clear_colors = world.resource::<RenderTargetClearColors>();
// This gets all ViewTargets and ViewDepthTextures and clears its attachments
// TODO: This has the potential to clear the same target multiple times, if there
@ -89,8 +89,8 @@ impl Node for ClearPassNode {
// TODO: This is a hack to ensure we don't call present() on frames without any work,
// which will cause panics. The real fix here is to clear "render targets" directly
// instead of "views". This should be removed once full RenderTargets are implemented.
let windows = world.get_resource::<ExtractedWindows>().unwrap();
let images = world.get_resource::<RenderAssets<Image>>().unwrap();
let windows = world.resource::<ExtractedWindows>();
let images = world.resource::<RenderAssets<Image>>();
for target in render_target_clear_colors.colors.keys().cloned().chain(
windows
.values()

View file

@ -145,7 +145,7 @@ impl Plugin for CorePipelinePlugin {
let clear_pass_node = ClearPassNode::new(&mut render_app.world);
let pass_node_2d = MainPass2dNode::new(&mut render_app.world);
let pass_node_3d = MainPass3dNode::new(&mut render_app.world);
let mut graph = render_app.world.get_resource_mut::<RenderGraph>().unwrap();
let mut graph = render_app.world.resource_mut::<RenderGraph>();
let mut draw_2d_graph = RenderGraph::default();
draw_2d_graph.add_node(draw_2d_graph::node::MAIN_PASS, pass_node_2d);

View file

@ -53,9 +53,7 @@ impl Node for MainPass2dNode {
depth_stencil_attachment: None,
};
let draw_functions = world
.get_resource::<DrawFunctions<Transparent2d>>()
.unwrap();
let draw_functions = world.resource::<DrawFunctions<Transparent2d>>();
let render_pass = render_context
.command_encoder

View file

@ -75,7 +75,7 @@ impl Node for MainPass3dNode {
}),
};
let draw_functions = world.get_resource::<DrawFunctions<Opaque3d>>().unwrap();
let draw_functions = world.resource::<DrawFunctions<Opaque3d>>();
let render_pass = render_context
.command_encoder
@ -109,7 +109,7 @@ impl Node for MainPass3dNode {
}),
};
let draw_functions = world.get_resource::<DrawFunctions<AlphaMask3d>>().unwrap();
let draw_functions = world.resource::<DrawFunctions<AlphaMask3d>>();
let render_pass = render_context
.command_encoder
@ -145,9 +145,7 @@ impl Node for MainPass3dNode {
}),
};
let draw_functions = world
.get_resource::<DrawFunctions<Transparent3d>>()
.unwrap();
let draw_functions = world.resource::<DrawFunctions<Transparent3d>>();
let render_pass = render_context
.command_encoder

View file

@ -14,7 +14,7 @@ impl Node for MainPassDriverNode {
_render_context: &mut RenderContext,
world: &World,
) -> Result<(), NodeRunError> {
let extracted_cameras = world.get_resource::<ExtractedCameraNames>().unwrap();
let extracted_cameras = world.resource::<ExtractedCameraNames>();
if let Some(camera_2d) = extracted_cameras.entities.get(CameraPlugin::CAMERA_2D) {
graph.run_sub_graph(
crate::draw_2d_graph::NAME,

View file

@ -1010,29 +1010,26 @@ mod tests {
.get_archetype_component_id(resource_id)
.unwrap();
assert_eq!(*world.get_resource::<i32>().expect("resource exists"), 123);
assert_eq!(*world.resource::<i32>(), 123);
assert!(world.contains_resource::<i32>());
assert!(world.is_resource_added::<i32>());
assert!(world.is_resource_changed::<i32>());
world.insert_resource(456u64);
assert_eq!(
*world.get_resource::<u64>().expect("resource exists"),
456u64
);
assert_eq!(*world.resource::<u64>(), 456u64);
world.insert_resource(789u64);
assert_eq!(*world.get_resource::<u64>().expect("resource exists"), 789);
assert_eq!(*world.resource::<u64>(), 789);
{
let mut value = world.get_resource_mut::<u64>().expect("resource exists");
let mut value = world.resource_mut::<u64>();
assert_eq!(*value, 789);
*value = 10;
}
assert_eq!(
world.get_resource::<u64>(),
Some(&10),
world.resource::<u64>(),
&10,
"resource changes are preserved"
);
@ -1183,8 +1180,8 @@ mod tests {
let mut world = World::default();
world.insert_non_send_resource(123i32);
world.insert_non_send_resource(456i64);
assert_eq!(*world.get_non_send_resource::<i32>().unwrap(), 123);
assert_eq!(*world.get_non_send_resource_mut::<i64>().unwrap(), 456);
assert_eq!(*world.non_send_resource::<i32>(), 123);
assert_eq!(*world.non_send_resource_mut::<i64>(), 456);
}
#[test]
@ -1193,7 +1190,7 @@ mod tests {
let mut world = World::default();
world.insert_non_send_resource(0i32);
std::thread::spawn(move || {
let _ = world.get_non_send_resource_mut::<i32>();
let _ = world.non_send_resource_mut::<i32>();
})
.join()
.unwrap();
@ -1323,7 +1320,7 @@ mod tests {
*value += 1;
assert!(!world.contains_resource::<i32>());
});
assert_eq!(*world.get_resource::<i32>().unwrap(), 1);
assert_eq!(*world.resource::<i32>(), 1);
}
#[test]
@ -1389,7 +1386,7 @@ mod tests {
"world should not have any entities"
);
assert_eq!(
*world.get_resource::<i32>().unwrap(),
*world.resource::<i32>(),
0,
"world should still contain resources"
);

View file

@ -350,11 +350,7 @@ mod tests {
fn receive_events(world: &World) -> Vec<SchedulingEvent> {
let mut events = Vec::new();
while let Ok(event) = world
.get_resource::<Receiver<SchedulingEvent>>()
.unwrap()
.try_recv()
{
while let Ok(event) = world.resource::<Receiver<SchedulingEvent>>().try_recv() {
events.push(event);
}
events

View file

@ -964,7 +964,7 @@ mod tests {
struct W<T>(T);
fn make_exclusive(tag: usize) -> impl FnMut(&mut World) {
move |world| world.get_resource_mut::<Vec<usize>>().unwrap().push(tag)
move |world| world.resource_mut::<Vec<usize>>().push(tag)
}
fn make_parallel(tag: usize) -> impl FnMut(ResMut<Vec<usize>>) {
@ -990,50 +990,41 @@ mod tests {
.with_system(make_exclusive(2).exclusive_system().before_commands())
.with_system(make_exclusive(3).exclusive_system().at_end());
stage.run(&mut world);
assert_eq!(
*world.get_resource_mut::<Vec<usize>>().unwrap(),
vec![0, 1, 2, 3]
);
assert_eq!(*world.resource_mut::<Vec<usize>>(), vec![0, 1, 2, 3]);
stage.set_executor(Box::new(SingleThreadedExecutor::default()));
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
*world.resource::<Vec<usize>>(),
vec![0, 1, 2, 3, 0, 1, 2, 3]
);
world.get_resource_mut::<Vec<usize>>().unwrap().clear();
world.resource_mut::<Vec<usize>>().clear();
let mut stage = SystemStage::parallel()
.with_system(make_exclusive(2).exclusive_system().before_commands())
.with_system(make_exclusive(3).exclusive_system().at_end())
.with_system(make_parallel(1))
.with_system(make_exclusive(0).exclusive_system().at_start());
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
vec![0, 1, 2, 3]
);
assert_eq!(*world.resource::<Vec<usize>>(), vec![0, 1, 2, 3]);
stage.set_executor(Box::new(SingleThreadedExecutor::default()));
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
*world.resource::<Vec<usize>>(),
vec![0, 1, 2, 3, 0, 1, 2, 3]
);
world.get_resource_mut::<Vec<usize>>().unwrap().clear();
world.resource_mut::<Vec<usize>>().clear();
let mut stage = SystemStage::parallel()
.with_system(make_parallel(2).exclusive_system().before_commands())
.with_system(make_parallel(3).exclusive_system().at_end())
.with_system(make_parallel(1))
.with_system(make_parallel(0).exclusive_system().at_start());
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
vec![0, 1, 2, 3]
);
assert_eq!(*world.resource::<Vec<usize>>(), vec![0, 1, 2, 3]);
stage.set_executor(Box::new(SingleThreadedExecutor::default()));
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
*world.resource::<Vec<usize>>(),
vec![0, 1, 2, 3, 0, 1, 2, 3]
);
}
@ -1049,10 +1040,7 @@ mod tests {
stage.run(&mut world);
stage.set_executor(Box::new(SingleThreadedExecutor::default()));
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
vec![0, 1, 2, 0, 1, 2]
);
assert_eq!(*world.resource::<Vec<usize>>(), vec![0, 1, 2, 0, 1, 2]);
}
#[test]
@ -1066,10 +1054,7 @@ mod tests {
stage.run(&mut world);
stage.set_executor(Box::new(SingleThreadedExecutor::default()));
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
vec![0, 1, 2, 0, 1, 2]
);
assert_eq!(*world.resource::<Vec<usize>>(), vec![0, 1, 2, 0, 1, 2]);
}
#[test]
@ -1086,7 +1071,7 @@ mod tests {
stage.set_executor(Box::new(SingleThreadedExecutor::default()));
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
*world.resource::<Vec<usize>>(),
vec![0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
);
}
@ -1112,12 +1097,9 @@ mod tests {
stage.run(&mut world);
stage.set_executor(Box::new(SingleThreadedExecutor::default()));
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
vec![0, 1, 2, 0, 1, 2]
);
assert_eq!(*world.resource::<Vec<usize>>(), vec![0, 1, 2, 0, 1, 2]);
world.get_resource_mut::<Vec<usize>>().unwrap().clear();
world.resource_mut::<Vec<usize>>().clear();
let mut stage = SystemStage::parallel()
.with_system(make_exclusive(2).exclusive_system().after("01").label("2"))
.with_system(make_exclusive(1).exclusive_system().label("01").after("0"))
@ -1128,11 +1110,11 @@ mod tests {
stage.set_executor(Box::new(SingleThreadedExecutor::default()));
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
*world.resource::<Vec<usize>>(),
vec![0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
);
world.get_resource_mut::<Vec<usize>>().unwrap().clear();
world.resource_mut::<Vec<usize>>().clear();
let mut stage = SystemStage::parallel()
.with_system(make_exclusive(2).exclusive_system().label("234").label("2"))
.with_system(
@ -1154,7 +1136,7 @@ mod tests {
stage.set_executor(Box::new(SingleThreadedExecutor::default()));
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
*world.resource::<Vec<usize>>(),
vec![0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
);
}
@ -1193,7 +1175,7 @@ mod tests {
stage.set_executor(Box::new(SingleThreadedExecutor::default()));
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
*world.resource::<Vec<usize>>(),
vec![0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
);
}
@ -1215,7 +1197,7 @@ mod tests {
stage.set_executor(Box::new(SingleThreadedExecutor::default()));
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
*world.resource::<Vec<usize>>(),
vec![0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
);
}
@ -1238,7 +1220,7 @@ mod tests {
stage.run(&mut world);
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
*world.resource::<Vec<usize>>(),
vec![0, 1, 2, 0, 2, 0, 1, 2, 0, 2]
);
}
@ -1287,10 +1269,7 @@ mod tests {
stage.run(&mut world);
stage.set_executor(Box::new(SingleThreadedExecutor::default()));
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
vec![0, 1, 2, 0, 1, 2]
);
assert_eq!(*world.resource::<Vec<usize>>(), vec![0, 1, 2, 0, 1, 2]);
}
#[test]
@ -1304,10 +1283,7 @@ mod tests {
stage.run(&mut world);
stage.set_executor(Box::new(SingleThreadedExecutor::default()));
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
vec![0, 1, 2, 0, 1, 2]
);
assert_eq!(*world.resource::<Vec<usize>>(), vec![0, 1, 2, 0, 1, 2]);
}
#[test]
@ -1324,7 +1300,7 @@ mod tests {
stage.set_executor(Box::new(SingleThreadedExecutor::default()));
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
*world.resource::<Vec<usize>>(),
vec![0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
);
}
@ -1340,12 +1316,9 @@ mod tests {
stage.run(&mut world);
stage.set_executor(Box::new(SingleThreadedExecutor::default()));
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
vec![0, 1, 2, 0, 1, 2]
);
assert_eq!(*world.resource::<Vec<usize>>(), vec![0, 1, 2, 0, 1, 2]);
world.get_resource_mut::<Vec<usize>>().unwrap().clear();
world.resource_mut::<Vec<usize>>().clear();
let mut stage = SystemStage::parallel()
.with_system(make_parallel(2).after("01").label("2"))
.with_system(make_parallel(1).label("01").after("0"))
@ -1356,11 +1329,11 @@ mod tests {
stage.set_executor(Box::new(SingleThreadedExecutor::default()));
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
*world.resource::<Vec<usize>>(),
vec![0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
);
world.get_resource_mut::<Vec<usize>>().unwrap().clear();
world.resource_mut::<Vec<usize>>().clear();
let mut stage = SystemStage::parallel()
.with_system(make_parallel(2).label("234").label("2"))
.with_system(make_parallel(1).before("234").after("0"))
@ -1371,7 +1344,7 @@ mod tests {
stage.set_executor(Box::new(SingleThreadedExecutor::default()));
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
*world.resource::<Vec<usize>>(),
vec![0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
);
}
@ -1405,7 +1378,7 @@ mod tests {
stage.set_executor(Box::new(SingleThreadedExecutor::default()));
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
*world.resource::<Vec<usize>>(),
vec![0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
);
}
@ -1427,7 +1400,7 @@ mod tests {
stage.set_executor(Box::new(SingleThreadedExecutor::default()));
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
*world.resource::<Vec<usize>>(),
vec![0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
);
}
@ -1449,12 +1422,9 @@ mod tests {
stage.set_executor(Box::new(SingleThreadedExecutor::default()));
stage.run(&mut world);
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
vec![0, 1, 1, 0, 1, 1]
);
assert_eq!(*world.resource::<Vec<usize>>(), vec![0, 1, 1, 0, 1, 1]);
world.get_resource_mut::<Vec<usize>>().unwrap().clear();
world.resource_mut::<Vec<usize>>().clear();
let mut stage = SystemStage::parallel()
.with_system(make_parallel(0).before("1"))
.with_system_set(
@ -1469,12 +1439,12 @@ mod tests {
stage.run(&mut world);
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
*world.resource::<Vec<usize>>(),
vec![0, 1, 2, 0, 2, 0, 1, 2, 0, 2]
);
// Reusing criteria.
world.get_resource_mut::<Vec<usize>>().unwrap().clear();
world.resource_mut::<Vec<usize>>().clear();
let mut stage = SystemStage::parallel()
.with_system_run_criteria(every_other_time.label("every other time"))
.with_system(make_parallel(0).before("1"))
@ -1496,13 +1466,13 @@ mod tests {
stage.run(&mut world);
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
*world.resource::<Vec<usize>>(),
vec![0, 1, 2, 3, 0, 3, 0, 1, 2, 3, 0, 3]
);
assert_eq!(stage.run_criteria.len(), 1);
// Piping criteria.
world.get_resource_mut::<Vec<usize>>().unwrap().clear();
world.resource_mut::<Vec<usize>>().clear();
fn eot_piped(input: In<ShouldRun>, has_ran: Local<bool>) -> ShouldRun {
if let ShouldRun::Yes | ShouldRun::YesAndCheckAgain = input.0 {
every_other_time(has_ran)
@ -1537,13 +1507,13 @@ mod tests {
stage.run(&mut world);
}
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
*world.resource::<Vec<usize>>(),
vec![0, 1, 2, 3, 4, 0, 0, 1, 0, 0, 1, 2, 3, 4, 0, 0, 1, 0, 0, 1, 2, 3, 4]
);
assert_eq!(stage.run_criteria.len(), 3);
// Discarding extra criteria with matching labels.
world.get_resource_mut::<Vec<usize>>().unwrap().clear();
world.resource_mut::<Vec<usize>>().clear();
let mut stage =
SystemStage::parallel()
.with_system(make_parallel(0).before("1"))
@ -1560,7 +1530,7 @@ mod tests {
stage.run(&mut world);
stage.run(&mut world);
assert_eq!(
*world.get_resource::<Vec<usize>>().unwrap(),
*world.resource::<Vec<usize>>(),
vec![0, 1, 2, 3, 0, 3, 0, 1, 2, 3, 0, 3]
);
assert_eq!(stage.run_criteria.len(), 1);
@ -2011,11 +1981,11 @@ mod tests {
let entity = world.spawn().insert_bundle(()).id();
stage.run(&mut world);
assert_eq!(*world.get_resource::<usize>().unwrap(), 1);
assert_eq!(*world.resource::<usize>(), 1);
world.get_entity_mut(entity).unwrap().insert(W(1));
stage.run(&mut world);
assert_eq!(*world.get_resource::<usize>().unwrap(), 1);
assert_eq!(*world.resource::<usize>(), 1);
}
#[test]
@ -2034,11 +2004,11 @@ mod tests {
let entity = world.spawn().insert_bundle(()).id();
stage.run(&mut world);
assert_eq!(*world.get_resource::<usize>().unwrap(), 1);
assert_eq!(*world.resource::<usize>(), 1);
world.get_entity_mut(entity).unwrap().insert(W(1));
stage.run(&mut world);
assert_eq!(*world.get_resource::<usize>().unwrap(), 1);
assert_eq!(*world.resource::<usize>(), 1);
}
#[test]
@ -2146,7 +2116,7 @@ mod tests {
stage.run(&mut world);
stage.run(&mut world);
stage.run(&mut world);
assert_eq!(*world.get_resource::<Vec<usize>>().unwrap(), vec![0, 2]);
assert_eq!(*world.resource::<Vec<usize>>(), vec![0, 2]);
}
#[test]
@ -2186,6 +2156,6 @@ mod tests {
stage_spawn.run(&mut world);
stage_count.run(&mut world);
stage_spawn.run(&mut world);
assert_eq!(*world.get_resource::<Vec<usize>>().unwrap(), vec![0, 2]);
assert_eq!(*world.resource::<Vec<usize>>(), vec![0, 2]);
}
}

View file

@ -629,7 +629,7 @@ mod test {
];
stage.run(&mut world);
let mut collected = world.get_resource_mut::<Vec<&'static str>>().unwrap();
let mut collected = world.resource_mut::<Vec<&'static str>>();
let mut count = 0;
for (found, expected) in collected.drain(..).zip(EXPECTED) {
assert_eq!(found, *expected);
@ -638,7 +638,7 @@ mod test {
// If not equal, some elements weren't executed
assert_eq!(EXPECTED.len(), count);
assert_eq!(
world.get_resource::<State<MyState>>().unwrap().current(),
world.resource::<State<MyState>>().current(),
&MyState::Final
);
}
@ -661,7 +661,7 @@ mod test {
world.insert_resource("control");
let mut stage = SystemStage::parallel().with_system(should_run_once);
stage.run(&mut world);
assert!(*world.get_resource::<bool>().unwrap(), "after control");
assert!(*world.resource::<bool>(), "after control");
world.insert_resource(false);
world.insert_resource("test");
@ -669,7 +669,7 @@ mod test {
.with_system_set(State::<AppState>::get_driver())
.with_system(should_run_once);
stage.run(&mut world);
assert!(*world.get_resource::<bool>().unwrap(), "after test");
assert!(*world.resource::<bool>(), "after test");
}
#[test]
@ -712,19 +712,19 @@ mod test {
stage.run(&mut world);
// A. Restart state
let mut state = world.get_resource_mut::<State<LoadState>>().unwrap();
let mut state = world.resource_mut::<State<LoadState>>();
let result = state.restart();
assert!(matches!(result, Ok(())));
stage.run(&mut world);
// B. Restart state (overwrite schedule)
let mut state = world.get_resource_mut::<State<LoadState>>().unwrap();
let mut state = world.resource_mut::<State<LoadState>>();
state.set(LoadState::Finish).unwrap();
state.overwrite_restart();
stage.run(&mut world);
// C. Fail restart state (transition already scheduled)
let mut state = world.get_resource_mut::<State<LoadState>>().unwrap();
let mut state = world.resource_mut::<State<LoadState>>();
state.set(LoadState::Finish).unwrap();
let result = state.restart();
assert!(matches!(result, Err(StateError::StateAlreadyQueued)));
@ -743,7 +743,7 @@ mod test {
LoadStatus::EnterFinish,
];
let mut collected = world.get_resource_mut::<Vec<LoadStatus>>().unwrap();
let mut collected = world.resource_mut::<Vec<LoadStatus>>();
let mut count = 0;
for (found, expected) in collected.drain(..).zip(EXPECTED) {
assert_eq!(found, *expected);
@ -752,7 +752,7 @@ mod test {
// If not equal, some elements weren't executed
assert_eq!(EXPECTED.len(), count);
assert_eq!(
world.get_resource::<State<LoadState>>().unwrap().current(),
world.resource::<State<LoadState>>().current(),
&LoadState::Finish
);
}

View file

@ -148,14 +148,14 @@ mod tests {
world.insert_resource(0usize);
stage.run(&mut world);
stage.run(&mut world);
assert_eq!(*world.get_resource::<usize>().unwrap(), 1);
assert_eq!(*world.resource::<usize>(), 1);
let mut stage = SystemStage::parallel().with_system(removal.exclusive_system());
world.spawn().insert(Foo(0.0f32));
world.insert_resource(0usize);
stage.run(&mut world);
stage.run(&mut world);
assert_eq!(*world.get_resource::<usize>().unwrap(), 1);
assert_eq!(*world.resource::<usize>(), 1);
}
#[test]
@ -175,6 +175,6 @@ mod tests {
.with_system(count_entities.exclusive_system());
stage.run(&mut world);
stage.run(&mut world);
assert_eq!(*world.get_resource::<Vec<usize>>().unwrap(), vec![0, 1]);
assert_eq!(*world.resource::<Vec<usize>>(), vec![0, 1]);
}
}

View file

@ -207,7 +207,7 @@ mod tests {
run_system(&mut world, query_system);
assert!(*world.get_resource::<bool>().unwrap(), "system ran");
assert!(*world.resource::<bool>(), "system ran");
}
#[test]
@ -235,7 +235,7 @@ mod tests {
run_system(&mut world, query_system);
assert!(*world.get_resource::<bool>().unwrap(), "system ran");
assert!(*world.resource::<bool>(), "system ran");
}
#[test]
@ -271,17 +271,17 @@ mod tests {
);
schedule.run(&mut world);
assert_eq!(world.get_resource::<Added>().unwrap().0, 1);
assert_eq!(world.get_resource::<Changed>().unwrap().0, 1);
assert_eq!(world.resource::<Added>().0, 1);
assert_eq!(world.resource::<Changed>().0, 1);
schedule.run(&mut world);
assert_eq!(world.get_resource::<Added>().unwrap().0, 1);
assert_eq!(world.get_resource::<Changed>().unwrap().0, 1);
assert_eq!(world.resource::<Added>().0, 1);
assert_eq!(world.resource::<Changed>().0, 1);
*world.get_resource_mut::<bool>().unwrap() = true;
*world.resource_mut::<bool>() = true;
schedule.run(&mut world);
assert_eq!(world.get_resource::<Added>().unwrap().0, 1);
assert_eq!(world.get_resource::<Changed>().unwrap().0, 2);
assert_eq!(world.resource::<Added>().0, 1);
assert_eq!(world.resource::<Changed>().0, 2);
}
#[test]
@ -399,7 +399,7 @@ mod tests {
impl FromWorld for Foo {
fn from_world(world: &mut World) -> Self {
Foo {
value: *world.get_resource::<u32>().unwrap() + 1,
value: *world.resource::<u32>() + 1,
}
}
}
@ -412,7 +412,7 @@ mod tests {
run_system(&mut world, sys);
// ensure the system actually ran
assert!(*world.get_resource::<bool>().unwrap());
assert!(*world.resource::<bool>());
}
#[test]
@ -435,7 +435,7 @@ mod tests {
run_system(&mut world, sys);
// ensure the system actually ran
assert!(*world.get_resource::<bool>().unwrap());
assert!(*world.resource::<bool>());
}
#[test]
@ -454,7 +454,7 @@ mod tests {
}
run_system(&mut world, sys);
assert!(*world.get_resource::<bool>().unwrap());
assert!(*world.resource::<bool>());
}
#[test]
@ -522,7 +522,7 @@ mod tests {
run_system(&mut world, validate_remove);
// Verify that both systems actually ran
assert_eq!(world.get_resource::<NSystems>().unwrap().0, 2);
assert_eq!(world.resource::<NSystems>().0, 2);
}
#[test]
@ -566,7 +566,7 @@ mod tests {
run_system(&mut world, sys);
// ensure the system actually ran
assert!(*world.get_resource::<bool>().unwrap());
assert!(*world.resource::<bool>());
}
#[test]

View file

@ -705,13 +705,6 @@ impl World {
self.get_populated_resource_column(component_id).is_some()
}
/// Gets a reference to the resource of the given type, if it exists. Otherwise returns [None]
#[inline]
pub fn get_resource<R: Resource>(&self) -> Option<&R> {
let component_id = self.components.get_resource_id(TypeId::of::<R>())?;
unsafe { self.get_resource_with_id(component_id) }
}
pub fn is_resource_added<R: Resource>(&self) -> bool {
let component_id =
if let Some(component_id) = self.components.get_resource_id(TypeId::of::<R>()) {
@ -746,7 +739,63 @@ impl World {
ticks.is_changed(self.last_change_tick(), self.read_change_tick())
}
/// Gets a mutable reference to the resource of the given type, if it exists. Otherwise returns
/// Gets a reference to the resource of the given type
///
/// # Panics
///
/// Panics if the resource does not exist.
/// Use [`get_resource`](World::get_resource) instead if you want to handle this case.
///
/// If you want to instead insert a value if the resource does not exist,
/// use [`get_resource_or_insert_with`](World::get_resource_or_insert_with).
#[inline]
#[track_caller]
pub fn resource<R: Resource>(&self) -> &R {
match self.get_resource() {
Some(x) => x,
None => panic!(
"Requested resource {} does not exist in the `World`.
Did you forget to add it using `app.add_resource` / `app.init_resource`?
Resources are also implicitly added via `app.add_event`,
and can be added by plugins.",
std::any::type_name::<R>()
),
}
}
/// Gets a mutable reference to the resource of the given type
///
/// # Panics
///
/// Panics if the resource does not exist.
/// Use [`get_resource_mut`](World::get_resource_mut) instead if you want to handle this case.
///
/// If you want to instead insert a value if the resource does not exist,
/// use [`get_resource_or_insert_with`](World::get_resource_or_insert_with).
#[inline]
#[track_caller]
pub fn resource_mut<R: Resource>(&mut self) -> Mut<'_, R> {
match self.get_resource_mut() {
Some(x) => x,
None => panic!(
"Requested resource {} does not exist in the `World`.
Did you forget to add it using `app.add_resource` / `app.init_resource`?
Resources are also implicitly added via `app.add_event`,
and can be added by plugins.",
std::any::type_name::<R>()
),
}
}
/// Gets a reference to the resource of the given type if it exists
#[inline]
pub fn get_resource<R: Resource>(&self) -> Option<&R> {
let component_id = self.components.get_resource_id(TypeId::of::<R>())?;
// SAFE: unique world access
unsafe { self.get_resource_with_id(component_id) }
}
/// Gets a mutable reference to the resource of the given type if it exists
#[inline]
pub fn get_resource_mut<R: Resource>(&mut self) -> Option<Mut<'_, R>> {
// SAFE: unique world access
@ -754,7 +803,7 @@ impl World {
}
// PERF: optimize this to avoid redundant lookups
/// Gets a resource of type `T` if it exists,
/// Gets a mutable reference to the resource of type `T` if it exists,
/// otherwise inserts the resource using the result of calling `func`.
#[inline]
pub fn get_resource_or_insert_with<R: Resource>(
@ -764,7 +813,7 @@ impl World {
if !self.contains_resource::<R>() {
self.insert_resource(func());
}
self.get_resource_mut().unwrap()
self.resource_mut()
}
/// Gets a mutable reference to the resource of the given type, if it exists
@ -779,6 +828,46 @@ impl World {
self.get_resource_unchecked_mut_with_id(component_id)
}
/// Gets an immutable reference to the non-send resource of the given type, if it exists.
///
/// # Panics
///
/// Panics if the resource does not exist.
/// Use [`get_non_send_resource`](World::get_non_send_resource) instead if you want to handle this case.
#[inline]
#[track_caller]
pub fn non_send_resource<R: 'static>(&self) -> &R {
match self.get_non_send_resource() {
Some(x) => x,
None => panic!(
"Requested non-send resource {} does not exist in the `World`.
Did you forget to add it using `app.add_non_send_resource` / `app.init_non_send_resource`?
Non-send resources can also be be added by plugins.",
std::any::type_name::<R>()
),
}
}
/// Gets a mutable reference to the non-send resource of the given type, if it exists.
///
/// # Panics
///
/// Panics if the resource does not exist.
/// Use [`get_non_send_resource_mut`](World::get_non_send_resource_mut) instead if you want to handle this case.
#[inline]
#[track_caller]
pub fn non_send_resource_mut<R: 'static>(&mut self) -> Mut<'_, R> {
match self.get_non_send_resource_mut() {
Some(x) => x,
None => panic!(
"Requested non-send resource {} does not exist in the `World`.
Did you forget to add it using `app.add_non_send_resource` / `app.init_non_send_resource`?
Non-send resources can also be be added by plugins.",
std::any::type_name::<R>()
),
}
}
/// Gets a reference to the non-send resource of the given type, if it exists.
/// Otherwise returns [None]
#[inline]

View file

@ -124,8 +124,7 @@ impl Plugin for PbrPlugin {
);
app.world
.get_resource_mut::<Assets<StandardMaterial>>()
.unwrap()
.resource_mut::<Assets<StandardMaterial>>()
.set_untracked(
Handle::<StandardMaterial>::default(),
StandardMaterial {
@ -180,7 +179,7 @@ impl Plugin for PbrPlugin {
let shadow_pass_node = ShadowPassNode::new(&mut render_app.world);
render_app.add_render_command::<Shadow, DrawShadowMesh>();
let mut graph = render_app.world.get_resource_mut::<RenderGraph>().unwrap();
let mut graph = render_app.world.resource_mut::<RenderGraph>();
let draw_3d_graph = graph
.get_sub_graph_mut(bevy_core_pipeline::draw_3d_graph::NAME)
.unwrap();

View file

@ -258,12 +258,12 @@ impl<M: SpecializedMaterial> SpecializedMeshPipeline for MaterialPipeline<M> {
impl<M: SpecializedMaterial> FromWorld for MaterialPipeline<M> {
fn from_world(world: &mut World) -> Self {
let asset_server = world.get_resource::<AssetServer>().unwrap();
let render_device = world.get_resource::<RenderDevice>().unwrap();
let asset_server = world.resource::<AssetServer>();
let render_device = world.resource::<RenderDevice>();
let material_layout = M::bind_group_layout(render_device);
MaterialPipeline {
mesh_pipeline: world.get_resource::<MeshPipeline>().unwrap().clone(),
mesh_pipeline: world.resource::<MeshPipeline>().clone(),
material_layout,
vertex_shader: M::vertex_shader(asset_server),
fragment_shader: M::fragment_shader(asset_server),

View file

@ -1187,7 +1187,7 @@ impl Node for ShadowPassNode {
}),
};
let draw_functions = world.get_resource::<DrawFunctions<Shadow>>().unwrap();
let draw_functions = world.resource::<DrawFunctions<Shadow>>();
let render_pass = render_context
.command_encoder
.begin_render_pass(&pass_descriptor);

View file

@ -165,7 +165,7 @@ pub struct MeshPipeline {
impl FromWorld for MeshPipeline {
fn from_world(world: &mut World) -> Self {
let render_device = world.get_resource::<RenderDevice>().unwrap();
let render_device = world.resource::<RenderDevice>();
let view_layout = render_device.create_bind_group_layout(&BindGroupLayoutDescriptor {
entries: &[
// View
@ -301,7 +301,7 @@ impl FromWorld for MeshPipeline {
let sampler = render_device.create_sampler(&image.sampler_descriptor);
let format_size = image.texture_descriptor.format.pixel_size();
let render_queue = world.get_resource_mut::<RenderQueue>().unwrap();
let render_queue = world.resource_mut::<RenderQueue>();
render_queue.write_texture(
ImageCopyTexture {
texture: &texture,

View file

@ -79,7 +79,7 @@ pub struct WireframePipeline {
impl FromWorld for WireframePipeline {
fn from_world(render_world: &mut World) -> Self {
WireframePipeline {
mesh_pipeline: render_world.get_resource::<MeshPipeline>().unwrap().clone(),
mesh_pipeline: render_world.resource::<MeshPipeline>().clone(),
shader: WIREFRAME_SHADER_HANDLE.typed(),
}
}

View file

@ -123,8 +123,7 @@ impl Plugin for RenderPlugin {
if let Some(backends) = options.backends {
let instance = wgpu::Instance::new(backends);
let surface = {
let world = app.world.cell();
let windows = world.get_resource_mut::<bevy_window::Windows>().unwrap();
let windows = app.world.resource_mut::<bevy_window::Windows>();
let raw_handle = windows.get_primary().map(|window| unsafe {
let handle = window.raw_window_handle().get_handle();
instance.create_surface(&handle)
@ -148,7 +147,7 @@ impl Plugin for RenderPlugin {
.register_type::<Frustum>()
.register_type::<CubemapFrusta>();
let render_pipeline_cache = RenderPipelineCache::new(device.clone());
let asset_server = app.world.get_resource::<AssetServer>().unwrap().clone();
let asset_server = app.world.resource::<AssetServer>().clone();
let mut render_app = App::empty();
let mut extract_stage =

View file

@ -398,7 +398,7 @@ impl RenderPipelineCache {
shaders: Res<Assets<Shader>>,
mut events: EventReader<AssetEvent<Shader>>,
) {
let mut cache = world.get_resource_mut::<Self>().unwrap();
let mut cache = world.resource_mut::<Self>();
for event in events.iter() {
match event {
AssetEvent::Created { handle } | AssetEvent::Modified { handle } => {

View file

@ -19,9 +19,9 @@ pub fn render_system(world: &mut World) {
world.resource_scope(|world, mut graph: Mut<RenderGraph>| {
graph.update(world);
});
let graph = world.get_resource::<RenderGraph>().unwrap();
let render_device = world.get_resource::<RenderDevice>().unwrap();
let render_queue = world.get_resource::<RenderQueue>().unwrap();
let graph = world.resource::<RenderGraph>();
let render_device = world.resource::<RenderDevice>();
let render_queue = world.resource::<RenderQueue>();
RenderGraphRunner::run(
graph,
render_device.clone(), // TODO: is this clone really necessary?
@ -43,7 +43,7 @@ pub fn render_system(world: &mut World) {
world.entity_mut(view_entity).remove::<ViewTarget>();
}
let mut windows = world.get_resource_mut::<ExtractedWindows>().unwrap();
let mut windows = world.resource_mut::<ExtractedWindows>();
for window in windows.values_mut() {
if let Some(texture_view) = window.swap_chain_texture.take() {
if let Some(surface_texture) = texture_view.take_surface_texture() {

View file

@ -43,8 +43,7 @@ impl Plugin for ImagePlugin {
app.add_plugin(RenderAssetPlugin::<Image>::default())
.add_asset::<Image>();
app.world
.get_resource_mut::<Assets<Image>>()
.unwrap()
.resource_mut::<Assets<Image>>()
.set_untracked(DEFAULT_IMAGE_HANDLE, Image::default());
if let Ok(render_app) = app.get_sub_app_mut(RenderApp) {

View file

@ -68,7 +68,7 @@ impl DerefMut for ExtractedWindows {
}
fn extract_windows(mut render_world: ResMut<RenderWorld>, windows: Res<Windows>) {
let mut extracted_windows = render_world.get_resource_mut::<ExtractedWindows>().unwrap();
let mut extracted_windows = render_world.resource_mut::<ExtractedWindows>();
for window in windows.iter() {
let (new_width, new_height) = (
window.physical_width().max(1),

View file

@ -14,7 +14,7 @@ pub struct SpawnScene {
impl Command for SpawnScene {
fn write(self, world: &mut World) {
let mut spawner = world.get_resource_mut::<SceneSpawner>().unwrap();
let mut spawner = world.resource_mut::<SceneSpawner>();
spawner.spawn(self.scene_handle);
}
}
@ -36,7 +36,7 @@ pub struct SpawnSceneAsChild {
impl Command for SpawnSceneAsChild {
fn write(self, world: &mut World) {
let mut spawner = world.get_resource_mut::<SceneSpawner>().unwrap();
let mut spawner = world.resource_mut::<SceneSpawner>();
spawner.spawn_as_child(self.scene_handle, self.parent);
}
}

View file

@ -79,7 +79,7 @@ impl DynamicScene {
world: &mut World,
entity_map: &mut EntityMap,
) -> Result<(), SceneSpawnError> {
let registry = world.get_resource::<TypeRegistryArc>().unwrap().clone();
let registry = world.resource::<TypeRegistryArc>().clone();
let type_registry = registry.read();
for scene_entity in &self.entities {

View file

@ -13,7 +13,7 @@ pub struct SceneLoader {
impl FromWorld for SceneLoader {
fn from_world(world: &mut World) -> Self {
let type_registry = world.get_resource::<TypeRegistryArc>().unwrap();
let type_registry = world.resource::<TypeRegistryArc>();
SceneLoader {
type_registry: (*type_registry).clone(),
}

View file

@ -144,7 +144,7 @@ impl SceneSpawner {
let mut instance_info = InstanceInfo {
entity_map: EntityMap::default(),
};
let type_registry = world.get_resource::<TypeRegistryArc>().unwrap().clone();
let type_registry = world.resource::<TypeRegistryArc>().clone();
let type_registry = type_registry.read();
world.resource_scope(|world, scenes: Mut<Assets<Scene>>| {
let scene =
@ -311,9 +311,7 @@ impl SceneSpawner {
pub fn scene_spawner_system(world: &mut World) {
world.resource_scope(|world, mut scene_spawner: Mut<SceneSpawner>| {
let scene_asset_events = world
.get_resource::<Events<AssetEvent<DynamicScene>>>()
.unwrap();
let scene_asset_events = world.resource::<Events<AssetEvent<DynamicScene>>>();
let mut updated_spawned_scenes = Vec::new();
let scene_spawner = &mut *scene_spawner;

View file

@ -52,7 +52,7 @@ pub enum SpriteSystem {
impl Plugin for SpritePlugin {
fn build(&self, app: &mut App) {
let mut shaders = app.world.get_resource_mut::<Assets<Shader>>().unwrap();
let mut shaders = app.world.resource_mut::<Assets<Shader>>();
let sprite_shader = Shader::from_wgsl(include_str!("render/sprite.wgsl"));
shaders.set_untracked(SPRITE_SHADER_HANDLE, sprite_shader);
app.add_asset::<TextureAtlas>()

View file

@ -35,8 +35,7 @@ impl Plugin for ColorMaterialPlugin {
app.add_plugin(Material2dPlugin::<ColorMaterial>::default());
app.world
.get_resource_mut::<Assets<ColorMaterial>>()
.unwrap()
.resource_mut::<Assets<ColorMaterial>>()
.set_untracked(
Handle::<ColorMaterial>::default(),
ColorMaterial {

View file

@ -242,12 +242,12 @@ impl<M: SpecializedMaterial2d> SpecializedMeshPipeline for Material2dPipeline<M>
impl<M: SpecializedMaterial2d> FromWorld for Material2dPipeline<M> {
fn from_world(world: &mut World) -> Self {
let asset_server = world.get_resource::<AssetServer>().unwrap();
let render_device = world.get_resource::<RenderDevice>().unwrap();
let asset_server = world.resource::<AssetServer>();
let render_device = world.resource::<RenderDevice>();
let material2d_layout = M::bind_group_layout(render_device);
Material2dPipeline {
mesh2d_pipeline: world.get_resource::<Mesh2dPipeline>().unwrap().clone(),
mesh2d_pipeline: world.resource::<Mesh2dPipeline>().clone(),
material2d_layout,
vertex_shader: M::vertex_shader(asset_server),
fragment_shader: M::fragment_shader(asset_server),

View file

@ -123,7 +123,7 @@ pub struct Mesh2dPipeline {
impl FromWorld for Mesh2dPipeline {
fn from_world(world: &mut World) -> Self {
let render_device = world.get_resource::<RenderDevice>().unwrap();
let render_device = world.resource::<RenderDevice>();
let view_layout = render_device.create_bind_group_layout(&BindGroupLayoutDescriptor {
entries: &[
// View
@ -166,7 +166,7 @@ impl FromWorld for Mesh2dPipeline {
let sampler = render_device.create_sampler(&image.sampler_descriptor);
let format_size = image.texture_descriptor.format.pixel_size();
let render_queue = world.get_resource_mut::<RenderQueue>().unwrap();
let render_queue = world.resource_mut::<RenderQueue>();
render_queue.write_texture(
ImageCopyTexture {
texture: &texture,

View file

@ -200,9 +200,7 @@ pub fn extract_sprite_events(
mut render_world: ResMut<RenderWorld>,
mut image_events: EventReader<AssetEvent<Image>>,
) {
let mut events = render_world
.get_resource_mut::<SpriteAssetEvents>()
.unwrap();
let mut events = render_world.resource_mut::<SpriteAssetEvents>();
let SpriteAssetEvents { ref mut images } = *events;
images.clear();
@ -233,7 +231,7 @@ pub fn extract_sprites(
&Handle<TextureAtlas>,
)>,
) {
let mut extracted_sprites = render_world.get_resource_mut::<ExtractedSprites>().unwrap();
let mut extracted_sprites = render_world.resource_mut::<ExtractedSprites>();
extracted_sprites.sprites.clear();
for (visibility, sprite, transform, handle) in sprite_query.iter() {
if !visibility.is_visible {

View file

@ -48,7 +48,7 @@ pub fn extract_text2d_sprite(
windows: Res<Windows>,
text2d_query: Query<(Entity, &Visibility, &Text, &GlobalTransform, &Text2dSize)>,
) {
let mut extracted_sprites = render_world.get_resource_mut::<ExtractedSprites>().unwrap();
let mut extracted_sprites = render_world.resource_mut::<ExtractedSprites>();
let scale_factor = if let Some(window) = windows.get_primary() {
window.scale_factor() as f32

View file

@ -61,7 +61,7 @@ pub enum RenderUiSystem {
pub fn build_ui_render(app: &mut App) {
load_internal_asset!(app, UI_SHADER_HANDLE, "ui.wgsl", Shader::from_wgsl);
let mut active_cameras = app.world.get_resource_mut::<ActiveCameras>().unwrap();
let mut active_cameras = app.world.resource_mut::<ActiveCameras>();
active_cameras.add(CAMERA_UI);
let render_app = match app.get_sub_app_mut(RenderApp) {
@ -92,7 +92,7 @@ pub fn build_ui_render(app: &mut App) {
// Render graph
let ui_pass_node = UiPassNode::new(&mut render_app.world);
let mut graph = render_app.world.get_resource_mut::<RenderGraph>().unwrap();
let mut graph = render_app.world.resource_mut::<RenderGraph>();
let mut draw_ui_graph = RenderGraph::default();
draw_ui_graph.add_node(draw_ui_graph::node::UI_PASS, ui_pass_node);
@ -145,7 +145,7 @@ pub fn extract_uinodes(
Option<&CalculatedClip>,
)>,
) {
let mut extracted_uinodes = render_world.get_resource_mut::<ExtractedUiNodes>().unwrap();
let mut extracted_uinodes = render_world.resource_mut::<ExtractedUiNodes>();
extracted_uinodes.uinodes.clear();
for (uinode, transform, color, image, visibility, clip) in uinode_query.iter() {
if !visibility.is_visible {
@ -184,7 +184,7 @@ pub fn extract_text_uinodes(
Option<&CalculatedClip>,
)>,
) {
let mut extracted_uinodes = render_world.get_resource_mut::<ExtractedUiNodes>().unwrap();
let mut extracted_uinodes = render_world.resource_mut::<ExtractedUiNodes>();
let scale_factor = if let Some(window) = windows.get_primary() {
window.scale_factor() as f32

View file

@ -25,7 +25,7 @@ impl bevy_render::render_graph::Node for UiPassDriverNode {
_render_context: &mut RenderContext,
world: &World,
) -> Result<(), NodeRunError> {
let extracted_cameras = world.get_resource::<ExtractedCameraNames>().unwrap();
let extracted_cameras = world.resource::<ExtractedCameraNames>();
if let Some(camera_ui) = extracted_cameras.entities.get(CAMERA_UI) {
graph.run_sub_graph(draw_ui_graph::NAME, vec![SlotValue::Entity(*camera_ui)])?;
}
@ -82,9 +82,7 @@ impl bevy_render::render_graph::Node for UiPassNode {
depth_stencil_attachment: None,
};
let draw_functions = world
.get_resource::<DrawFunctions<TransparentUi>>()
.unwrap();
let draw_functions = world.resource::<DrawFunctions<TransparentUi>>();
let render_pass = render_context
.command_encoder

View file

@ -60,10 +60,7 @@ impl Plugin for WindowPlugin {
.get_resource::<WindowDescriptor>()
.map(|descriptor| (*descriptor).clone())
.unwrap_or_default();
let mut create_window_event = app
.world
.get_resource_mut::<Events<CreateWindow>>()
.unwrap();
let mut create_window_event = app.world.resource_mut::<Events<CreateWindow>>();
create_window_event.send(CreateWindow {
id: WindowId::primary(),
descriptor: window_descriptor,

View file

@ -487,8 +487,7 @@ pub fn winit_runner_with(mut app: App) {
event: DeviceEvent::MouseMotion { delta },
..
} => {
let mut mouse_motion_events =
app.world.get_resource_mut::<Events<MouseMotion>>().unwrap();
let mut mouse_motion_events = app.world.resource_mut::<Events<MouseMotion>>();
mouse_motion_events.send(MouseMotion {
delta: Vec2::new(delta.0 as f32, delta.1 as f32),
});

View file

@ -270,7 +270,7 @@ pub const COLORED_MESH2D_SHADER_HANDLE: HandleUntyped =
impl Plugin for ColoredMesh2dPlugin {
fn build(&self, app: &mut App) {
// Load our custom shader
let mut shaders = app.world.get_resource_mut::<Assets<Shader>>().unwrap();
let mut shaders = app.world.resource_mut::<Assets<Shader>>();
shaders.set_untracked(
COLORED_MESH2D_SHADER_HANDLE,
Shader::from_wgsl(COLORED_MESH2D_SHADER),

View file

@ -40,7 +40,7 @@ fn main() {
// This will add 3D render phases for the new camera.
render_app.add_system_to_stage(RenderStage::Extract, extract_first_pass_camera_phases);
let mut graph = render_app.world.get_resource_mut::<RenderGraph>().unwrap();
let mut graph = render_app.world.resource_mut::<RenderGraph>();
// Add a node for the first pass.
graph.add_node(FIRST_PASS_DRIVER, FirstPassCameraDriver);
@ -82,7 +82,7 @@ impl bevy::render::render_graph::Node for FirstPassCameraDriver {
_render_context: &mut RenderContext,
world: &World,
) -> Result<(), NodeRunError> {
let extracted_cameras = world.get_resource::<ExtractedCameraNames>().unwrap();
let extracted_cameras = world.resource::<ExtractedCameraNames>();
if let Some(camera_3d) = extracted_cameras.entities.get(FIRST_PASS_CAMERA) {
graph.run_sub_graph(draw_3d_graph::NAME, vec![SlotValue::Entity(*camera_3d)])?;
}

View file

@ -9,7 +9,7 @@ fn my_runner(mut app: App) {
println!("Type stuff into the console");
for line in io::stdin().lock().lines() {
{
let mut input = app.world.get_resource_mut::<Input>().unwrap();
let mut input = app.world.resource_mut::<Input>();
input.0 = line.unwrap();
}
app.update();

View file

@ -49,12 +49,7 @@ impl Plugin for CustomAssetIoPlugin {
fn build(&self, app: &mut App) {
// must get a hold of the task pool in order to create the asset server
let task_pool = app
.world
.get_resource::<bevy::tasks::IoTaskPool>()
.expect("`IoTaskPool` resource not found.")
.0
.clone();
let task_pool = app.world.resource::<bevy::tasks::IoTaskPool>().0.clone();
let asset_io = {
// the platform default asset io requires a reference to the app

View file

@ -205,9 +205,9 @@ fn new_player_system(
#[allow(dead_code)]
fn exclusive_player_system(world: &mut World) {
// this does the same thing as "new_player_system"
let total_players = world.get_resource_mut::<GameState>().unwrap().total_players;
let total_players = world.resource_mut::<GameState>().total_players;
let should_add_player = {
let game_rules = world.get_resource::<GameRules>().unwrap();
let game_rules = world.resource::<GameRules>();
let add_new_player = random::<bool>();
add_new_player && total_players < game_rules.max_players
};
@ -220,7 +220,7 @@ fn exclusive_player_system(world: &mut World) {
Score { value: 0 },
));
let mut game_state = world.get_resource_mut::<GameState>().unwrap();
let mut game_state = world.resource_mut::<GameState>();
game_state.total_players += 1;
}
}

View file

@ -40,7 +40,7 @@ struct ComponentB {
impl FromWorld for ComponentB {
fn from_world(world: &mut World) -> Self {
let time = world.get_resource::<Time>().unwrap();
let time = world.resource::<Time>();
ComponentB {
_time_since_startup: time.time_since_startup(),
value: "Default Value".to_string(),
@ -91,7 +91,7 @@ fn save_scene_system(world: &mut World) {
// The TypeRegistry resource contains information about all registered types (including
// components). This is used to construct scenes.
let type_registry = world.get_resource::<TypeRegistry>().unwrap();
let type_registry = world.resource::<TypeRegistry>();
let scene = DynamicScene::from_world(&scene_world, type_registry);
// Scenes can be serialized like this:

View file

@ -53,7 +53,7 @@ pub struct CustomMaterialPlugin;
impl Plugin for CustomMaterialPlugin {
fn build(&self, app: &mut App) {
let render_device = app.world.get_resource::<RenderDevice>().unwrap();
let render_device = app.world.resource::<RenderDevice>();
let buffer = render_device.create_buffer(&BufferDescriptor {
label: Some("time uniform buffer"),
size: std::mem::size_of::<f32>() as u64,

View file

@ -66,7 +66,7 @@ impl Plugin for GameOfLifeComputePlugin {
.add_system_to_stage(RenderStage::Extract, extract_game_of_life_image)
.add_system_to_stage(RenderStage::Queue, queue_bind_group);
let mut render_graph = render_app.world.get_resource_mut::<RenderGraph>().unwrap();
let mut render_graph = render_app.world.resource_mut::<RenderGraph>();
render_graph.add_node("game_of_life", DispatchGameOfLife::default());
render_graph
.add_node_edge("game_of_life", MAIN_PASS_DEPENDENCIES)
@ -107,7 +107,7 @@ pub struct GameOfLifePipeline {
impl FromWorld for GameOfLifePipeline {
fn from_world(world: &mut World) -> Self {
let render_device = world.get_resource::<RenderDevice>().unwrap();
let render_device = world.resource::<RenderDevice>();
let shader_source = include_str!("../../assets/shaders/game_of_life.wgsl");
let shader = render_device.create_shader_module(&ShaderModuleDescriptor {
@ -187,8 +187,8 @@ impl render_graph::Node for DispatchGameOfLife {
render_context: &mut RenderContext,
world: &World,
) -> Result<(), render_graph::NodeRunError> {
let pipeline = world.get_resource::<GameOfLifePipeline>().unwrap();
let texture_bind_group = &world.get_resource::<GameOfLifeImageBindGroup>().unwrap().0;
let pipeline = world.resource::<GameOfLifePipeline>();
let texture_bind_group = &world.resource::<GameOfLifeImageBindGroup>().0;
let mut pass = render_context
.command_encoder

View file

@ -89,8 +89,8 @@ struct IsRedPipeline {
impl FromWorld for IsRedPipeline {
fn from_world(world: &mut World) -> Self {
let asset_server = world.get_resource::<AssetServer>().unwrap();
let mesh_pipeline = world.get_resource::<MeshPipeline>().unwrap();
let asset_server = world.resource::<AssetServer>();
let mesh_pipeline = world.resource::<MeshPipeline>();
let shader = asset_server.load("shaders/shader_defs.wgsl");
IsRedPipeline {
mesh_pipeline: mesh_pipeline.clone(),

View file

@ -20,7 +20,7 @@ fn main() {
let render_app = app.sub_app_mut(RenderApp);
render_app.add_system_to_stage(RenderStage::Extract, extract_secondary_camera_phases);
let mut graph = render_app.world.get_resource_mut::<RenderGraph>().unwrap();
let mut graph = render_app.world.resource_mut::<RenderGraph>();
graph.add_node(SECONDARY_PASS_DRIVER, SecondaryCameraDriver);
graph
.add_node_edge(node::MAIN_PASS_DEPENDENCIES, SECONDARY_PASS_DRIVER)
@ -84,7 +84,7 @@ impl Node for SecondaryCameraDriver {
_render_context: &mut RenderContext,
world: &World,
) -> Result<(), NodeRunError> {
let extracted_cameras = world.get_resource::<ExtractedCameraNames>().unwrap();
let extracted_cameras = world.resource::<ExtractedCameraNames>();
if let Some(camera_3d) = extracted_cameras.entities.get(SECONDARY_CAMERA_NAME) {
graph.run_sub_graph(
crate::draw_3d_graph::NAME,

View file

@ -87,7 +87,7 @@ fn spawn_enemy_using_input_resource() {
assert_eq!(world.query::<&Enemy>().iter(&world).len(), 1);
// Clear the `just_pressed` status for all `KeyCode`s
world.get_resource_mut::<Input<KeyCode>>().unwrap().clear();
world.resource_mut::<Input<KeyCode>>().clear();
// Run systems
update_stage.run(&mut world);