From 48106be8faecbc5ce40ebadca503af1bf38aeb3d Mon Sep 17 00:00:00 2001 From: Benjamin Brienen Date: Sat, 26 Oct 2024 23:59:22 +0200 Subject: [PATCH 1/5] fmt --- crates/bevy_app/src/plugin_group.rs | 6 +- crates/bevy_asset/src/io/file/file_watcher.rs | 16 +- crates/bevy_asset/src/processor/mod.rs | 10 +- crates/bevy_asset/src/server/info.rs | 24 +- crates/bevy_asset/src/server/loaders.rs | 12 +- crates/bevy_asset/src/server/mod.rs | 21 +- .../src/core_3d/main_opaque_pass_3d_node.rs | 10 +- crates/bevy_core_pipeline/src/dof/mod.rs | 4 +- crates/bevy_core_pipeline/src/taa/mod.rs | 4 +- crates/bevy_derive/src/derefs.rs | 5 +- crates/bevy_ecs/macros/src/component.rs | 6 +- crates/bevy_ecs/macros/src/lib.rs | 4 +- crates/bevy_ecs/macros/src/query_data.rs | 3 +- crates/bevy_ecs/src/bundle.rs | 10 +- crates/bevy_ecs/src/lib.rs | 14 +- crates/bevy_ecs/src/query/fetch.rs | 44 +- crates/bevy_ecs/src/query/filter.rs | 4 +- crates/bevy_ecs/src/query/iter.rs | 48 +-- crates/bevy_ecs/src/query/mod.rs | 4 +- crates/bevy_ecs/src/query/state.rs | 18 +- crates/bevy_ecs/src/schedule/schedule.rs | 4 +- crates/bevy_ecs/src/storage/resource.rs | 23 +- crates/bevy_ecs/src/system/commands/mod.rs | 20 +- crates/bevy_ecs/src/system/mod.rs | 12 +- crates/bevy_ecs/src/system/system_param.rs | 30 +- crates/bevy_ecs/src/world/deferred_world.rs | 5 +- crates/bevy_ecs/src/world/mod.rs | 11 +- crates/bevy_gilrs/src/rumble.rs | 4 +- crates/bevy_gizmos/src/primitives/dim2.rs | 2 - crates/bevy_gltf/src/loader.rs | 18 +- crates/bevy_image/src/basis.rs | 34 +- crates/bevy_image/src/ktx2.rs | 70 +--- crates/bevy_input/src/gamepad.rs | 22 +- crates/bevy_log/src/lib.rs | 4 +- crates/bevy_macro_utils/src/attrs.rs | 5 +- .../bevy_math/src/bounding/bounded2d/mod.rs | 6 +- .../bevy_math/src/bounding/bounded3d/mod.rs | 6 +- crates/bevy_math/src/curve/cores.rs | 4 +- crates/bevy_math/src/rotation2d.rs | 6 +- crates/bevy_mesh/src/conversions.rs | 3 +- crates/bevy_mesh/src/mesh.rs | 16 +- crates/bevy_pbr/src/cluster/mod.rs | 4 +- .../src/meshlet/meshlet_mesh_manager.rs | 4 +- crates/bevy_pbr/src/render/gpu_preprocess.rs | 19 +- crates/bevy_pbr/src/render/light.rs | 14 +- crates/bevy_pbr/src/render/mesh.rs | 38 +- crates/bevy_pbr/src/ssao/mod.rs | 7 +- .../derive/src/container_attributes.rs | 4 +- crates/bevy_reflect/derive/src/derive_data.rs | 20 +- .../bevy_reflect/derive/src/impls/common.rs | 21 +- crates/bevy_reflect/derive/src/impls/typed.rs | 4 +- crates/bevy_reflect/derive/src/remote.rs | 4 +- .../derive/src/trait_reflection.rs | 16 +- crates/bevy_reflect/src/enums/mod.rs | 4 +- crates/bevy_reflect/src/enums/variants.rs | 5 +- crates/bevy_reflect/src/kind.rs | 10 +- crates/bevy_reflect/src/lib.rs | 16 +- crates/bevy_reflect/src/map.rs | 22 +- crates/bevy_reflect/src/path/error.rs | 41 +- crates/bevy_reflect/src/path/mod.rs | 6 +- crates/bevy_reflect/src/path/parse.rs | 4 +- .../bevy_reflect/src/serde/de/deserializer.rs | 4 +- crates/bevy_reflect/src/serde/de/mod.rs | 15 +- .../src/serde/ser/custom_serialization.rs | 5 +- crates/bevy_reflect/src/serde/ser/mod.rs | 34 +- crates/bevy_reflect/src/set.rs | 4 +- crates/bevy_reflect/src/type_info.rs | 5 +- crates/bevy_reflect/src/type_registry.rs | 21 +- .../bevy_render/macros/src/as_bind_group.rs | 164 ++++---- .../src/batching/gpu_preprocessing.rs | 10 +- crates/bevy_render/src/camera/camera.rs | 4 +- crates/bevy_render/src/camera/projection.rs | 4 +- crates/bevy_render/src/lib.rs | 10 +- crates/bevy_render/src/pipelined_rendering.rs | 4 +- crates/bevy_render/src/render_graph/app.rs | 4 +- crates/bevy_render/src/render_graph/graph.rs | 4 +- .../src/render_resource/gpu_array_buffer.rs | 3 +- .../src/render_resource/pipeline_cache.rs | 20 +- .../bevy_render/src/renderer/graph_runner.rs | 4 +- crates/bevy_render/src/sync_world.rs | 2 +- crates/bevy_scene/src/dynamic_scene.rs | 22 +- crates/bevy_scene/src/serde.rs | 7 +- .../src/dynamic_texture_atlas_builder.rs | 6 +- .../bevy_sprite/src/texture_slice/slicer.rs | 10 +- crates/bevy_state/src/app.rs | 16 +- crates/bevy_text/src/text.rs | 29 +- crates/bevy_transform/src/systems.rs | 56 +-- crates/bevy_ui/src/layout/debug.rs | 13 +- crates/bevy_ui/src/layout/mod.rs | 47 +-- crates/bevy_ui/src/ui_node.rs | 4 +- crates/bevy_ui/src/widget/image.rs | 1 - crates/bevy_winit/src/cursor.rs | 4 +- crates/bevy_winit/src/state.rs | 3 +- examples/3d/atmospheric_fog.rs | 9 +- examples/3d/auto_exposure.rs | 9 +- examples/3d/blend_modes.rs | 10 +- examples/3d/meshlet.rs | 3 +- examples/app/log_layers.rs | 1 - examples/asset/processing/asset_processing.rs | 9 +- examples/camera/2d_screen_shake.rs | 3 +- examples/ecs/iter_combinations.rs | 1 - examples/games/desk_toy.rs | 7 +- examples/input/gamepad_rumble.rs | 4 +- examples/math/custom_primitives.rs | 13 +- examples/ui/display_and_visibility.rs | 93 +---- examples/ui/grid.rs | 55 +-- examples/ui/render_ui_to_texture.rs | 1 - examples/ui/scroll.rs | 384 +++++------------- examples/ui/text_debug.rs | 214 ++-------- examples/ui/text_wrap_debug.rs | 8 +- examples/window/monitor_info.rs | 4 +- tests/ecs/ambiguity_detection.rs | 12 +- tools/build-wasm-example/src/main.rs | 15 +- tools/ci/src/commands/compile_check_no_std.rs | 8 +- tools/ci/src/commands/compile_fail.rs | 24 +- tools/ci/src/commands/doc_check.rs | 9 +- tools/example-showcase/src/main.rs | 71 +--- 117 files changed, 593 insertions(+), 1748 deletions(-) diff --git a/crates/bevy_app/src/plugin_group.rs b/crates/bevy_app/src/plugin_group.rs index e828a012d0400..5555d4dde890a 100644 --- a/crates/bevy_app/src/plugin_group.rs +++ b/crates/bevy_app/src/plugin_group.rs @@ -416,11 +416,7 @@ impl PluginGroupBuilder { if let Err(AppError::DuplicatePlugin { plugin_name }) = app.add_boxed_plugin(entry.plugin) { - panic!( - "Error adding plugin {} in group {}: plugin was already added in application", - plugin_name, - self.group_name - ); + panic!("Error adding plugin {} in group {}: plugin was already added in application", plugin_name, self.group_name); } } } diff --git a/crates/bevy_asset/src/io/file/file_watcher.rs b/crates/bevy_asset/src/io/file/file_watcher.rs index 1da55fae97607..cb318b8049f0c 100644 --- a/crates/bevy_asset/src/io/file/file_watcher.rs +++ b/crates/bevy_asset/src/io/file/file_watcher.rs @@ -47,13 +47,7 @@ impl FileWatcher { impl AssetWatcher for FileWatcher {} pub(crate) fn get_asset_path(root: &Path, absolute_path: &Path) -> (PathBuf, bool) { - let relative_path = absolute_path.strip_prefix(root).unwrap_or_else(|_| { - panic!( - "FileWatcher::get_asset_path() failed to strip prefix from absolute path: absolute_path={:?}, root={:?}", - absolute_path, - root - ) - }); + let relative_path = absolute_path.strip_prefix(root).unwrap_or_else(|_| panic!("FileWatcher::get_asset_path() failed to strip prefix from absolute path: absolute_path={:?}, root={:?}", absolute_path, root)); let is_meta = relative_path .extension() .map(|e| e == "meta") @@ -187,14 +181,10 @@ pub(crate) fn new_asset_event_debouncer( ); } (true, false) => { - error!( - "Asset metafile {old_path:?} was changed to asset file {new_path:?}, which is not supported. Try restarting your app to see if configuration is still valid" - ); + error!("Asset metafile {old_path:?} was changed to asset file {new_path:?}, which is not supported. Try restarting your app to see if configuration is still valid"); } (false, true) => { - error!( - "Asset file {old_path:?} was changed to meta file {new_path:?}, which is not supported. Try restarting your app to see if configuration is still valid" - ); + error!("Asset file {old_path:?} was changed to meta file {new_path:?}, which is not supported. Try restarting your app to see if configuration is still valid"); } } } diff --git a/crates/bevy_asset/src/processor/mod.rs b/crates/bevy_asset/src/processor/mod.rs index a047cd7971032..40c6c827f1d5a 100644 --- a/crates/bevy_asset/src/processor/mod.rs +++ b/crates/bevy_asset/src/processor/mod.rs @@ -1320,10 +1320,7 @@ impl ProcessorAssetInfos { .await .unwrap(); if !info.dependents.is_empty() { - error!( - "The asset at {asset_path} was removed, but it had assets that depend on it to be processed. Consider updating the path in the following assets: {:?}", - info.dependents - ); + error!("The asset at {asset_path} was removed, but it had assets that depend on it to be processed. Consider updating the path in the following assets: {:?}", info.dependents); self.non_existent_dependents .insert(asset_path.clone(), info.dependents); } @@ -1342,10 +1339,7 @@ impl ProcessorAssetInfos { // If deps encoded "relativeness" as part of loading, that would also work (this seems like the right call). // TODO: it would be nice to log an error here for dependents that aren't also being moved + fixed. // (see the remove impl). - error!( - "The asset at {old} was removed, but it had assets that depend on it to be processed. Consider updating the path in the following assets: {:?}", - info.dependents - ); + error!("The asset at {old} was removed, but it had assets that depend on it to be processed. Consider updating the path in the following assets: {:?}", info.dependents); self.non_existent_dependents .insert(old.clone(), core::mem::take(&mut info.dependents)); } diff --git a/crates/bevy_asset/src/server/info.rs b/crates/bevy_asset/src/server/info.rs index 99bcb5a1e09d1..b755c9fee84fc 100644 --- a/crates/bevy_asset/src/server/info.rs +++ b/crates/bevy_asset/src/server/info.rs @@ -403,12 +403,9 @@ impl AssetInfos { loading_deps.retain(|dep_id| { if let Some(dep_info) = self.get_mut(*dep_id) { match dep_info.rec_dep_load_state { - RecursiveDependencyLoadState::Loading - | RecursiveDependencyLoadState::NotLoaded => { + RecursiveDependencyLoadState::Loading | RecursiveDependencyLoadState::NotLoaded => { // If dependency is loading, wait for it. - dep_info - .dependents_waiting_on_recursive_dep_load - .insert(loaded_asset_id); + dep_info.dependents_waiting_on_recursive_dep_load.insert(loaded_asset_id); } RecursiveDependencyLoadState::Loaded => { // If dependency is loaded, reduce our count by one @@ -442,10 +439,7 @@ impl AssetInfos { } } else { // the dependency id does not exist, which implies it was manually removed or never existed in the first place - warn!( - "Dependency {:?} from asset {:?} is unknown. This asset's dependency load status will not switch to 'Loaded' until the unknown dependency is loaded.", - dep_id, loaded_asset_id - ); + warn!("Dependency {:?} from asset {:?} is unknown. This asset's dependency load status will not switch to 'Loaded' until the unknown dependency is loaded.", dep_id, loaded_asset_id); true } }); @@ -779,12 +773,16 @@ pub(crate) fn unwrap_with_context( Err(GetOrCreateHandleInternalError::HandleMissingButTypeIdNotSpecified) => None, Err(GetOrCreateHandleInternalError::MissingHandleProviderError(_)) => match type_info { Either::Left(type_name) => { - panic!("Cannot allocate an Asset Handle of type '{type_name}' because the asset type has not been initialized. \ - Make sure you have called `app.init_asset::<{type_name}>()`"); + panic!( + "Cannot allocate an Asset Handle of type '{type_name}' because the asset type has not been initialized. \ + Make sure you have called `app.init_asset::<{type_name}>()`" + ); } Either::Right(type_id) => { - panic!("Cannot allocate an AssetHandle of type '{type_id:?}' because the asset type has not been initialized. \ - Make sure you have called `app.init_asset::<(actual asset type)>()`") + panic!( + "Cannot allocate an AssetHandle of type '{type_id:?}' because the asset type has not been initialized. \ + Make sure you have called `app.init_asset::<(actual asset type)>()`" + ) } }, } diff --git a/crates/bevy_asset/src/server/loaders.rs b/crates/bevy_asset/src/server/loaders.rs index 3850a7fb78886..98c5502338981 100644 --- a/crates/bevy_asset/src/server/loaders.rs +++ b/crates/bevy_asset/src/server/loaders.rs @@ -70,8 +70,10 @@ impl AssetLoaders { let duplicate_asset_registration = !list.is_empty(); if !duplicate_extensions.is_empty() && duplicate_asset_registration { - warn!("Duplicate AssetLoader registered for Asset type `{loader_asset_type_name}` with extensions `{duplicate_extensions:?}`. \ - Loader must be specified in a .meta file in order to load assets of this type with these extensions."); + warn!( + "Duplicate AssetLoader registered for Asset type `{loader_asset_type_name}` with extensions `{duplicate_extensions:?}`. \ + Loader must be specified in a .meta file in order to load assets of this type with these extensions." + ); } list.push(loader_index); @@ -129,8 +131,10 @@ impl AssetLoaders { let duplicate_asset_registration = !list.is_empty(); if !duplicate_extensions.is_empty() && duplicate_asset_registration { - warn!("Duplicate AssetLoader preregistered for Asset type `{loader_asset_type_name}` with extensions `{duplicate_extensions:?}`. \ - Loader must be specified in a .meta file in order to load assets of this type with these extensions."); + warn!( + "Duplicate AssetLoader preregistered for Asset type `{loader_asset_type_name}` with extensions `{duplicate_extensions:?}`. \ + Loader must be specified in a .meta file in order to load assets of this type with these extensions." + ); } list.push(loader_index); diff --git a/crates/bevy_asset/src/server/mod.rs b/crates/bevy_asset/src/server/mod.rs index 297164062906e..df69ffe2a3505 100644 --- a/crates/bevy_asset/src/server/mod.rs +++ b/crates/bevy_asset/src/server/mod.rs @@ -901,10 +901,7 @@ impl AssetServer { IoTaskPool::get() .spawn(async move { let Ok(source) = server.get_source(path.source()) else { - error!( - "Failed to load {path}. AssetSource {:?} does not exist", - path.source() - ); + error!("Failed to load {path}. AssetSource {:?} does not exist", path.source()); return; }; @@ -913,10 +910,7 @@ impl AssetServer { AssetServerMode::Processed { .. } => match source.processed_reader() { Ok(reader) => reader, Err(_) => { - error!( - "Failed to load {path}. AssetSource {:?} does not have a processed AssetReader", - path.source() - ); + error!("Failed to load {path}. AssetSource {:?} does not have a processed AssetReader", path.source()); return; } }, @@ -924,18 +918,11 @@ impl AssetServer { let mut handles = Vec::new(); match load_folder(source.id(), path.path(), asset_reader, &server, &mut handles).await { - Ok(_) => server.send_asset_event(InternalAssetEvent::Loaded { - id, - loaded_asset: LoadedAsset::new_with_dependencies( - LoadedFolder { handles }, - None, - ) - .into(), - }), + Ok(_) => server.send_asset_event(InternalAssetEvent::Loaded { id, loaded_asset: LoadedAsset::new_with_dependencies(LoadedFolder { handles }, None).into() }), Err(err) => { error!("Failed to load folder. {err}"); server.send_asset_event(InternalAssetEvent::Failed { id, error: err, path }); - }, + } } }) .detach(); diff --git a/crates/bevy_core_pipeline/src/core_3d/main_opaque_pass_3d_node.rs b/crates/bevy_core_pipeline/src/core_3d/main_opaque_pass_3d_node.rs index b51f36354340a..1e3a5acfe2e54 100644 --- a/crates/bevy_core_pipeline/src/core_3d/main_opaque_pass_3d_node.rs +++ b/crates/bevy_core_pipeline/src/core_3d/main_opaque_pass_3d_node.rs @@ -37,15 +37,7 @@ impl ViewNode for MainOpaquePass3dNode { &self, graph: &mut RenderGraphContext, render_context: &mut RenderContext<'w>, - ( - view, - camera, - target, - depth, - skybox_pipeline, - skybox_bind_group, - view_uniform_offset, - ): QueryItem<'w, Self::ViewQuery>, + (view, camera, target, depth, skybox_pipeline, skybox_bind_group, view_uniform_offset): QueryItem<'w, Self::ViewQuery>, world: &'w World, ) -> Result<(), NodeRunError> { let (Some(opaque_phases), Some(alpha_mask_phases)) = ( diff --git a/crates/bevy_core_pipeline/src/dof/mod.rs b/crates/bevy_core_pipeline/src/dof/mod.rs index ccf54dd4d5055..aaa406780a019 100644 --- a/crates/bevy_core_pipeline/src/dof/mod.rs +++ b/crates/bevy_core_pipeline/src/dof/mod.rs @@ -816,9 +816,7 @@ fn extract_depth_of_field_settings( mut query: Extract>, ) { if !DEPTH_TEXTURE_SAMPLING_SUPPORTED { - info_once!( - "Disabling depth of field on this platform because depth textures aren't supported correctly" - ); + info_once!("Disabling depth of field on this platform because depth textures aren't supported correctly"); return; } diff --git a/crates/bevy_core_pipeline/src/taa/mod.rs b/crates/bevy_core_pipeline/src/taa/mod.rs index f8333fc53827e..ad7d6c1af1761 100644 --- a/crates/bevy_core_pipeline/src/taa/mod.rs +++ b/crates/bevy_core_pipeline/src/taa/mod.rs @@ -185,9 +185,7 @@ impl ViewNode for TemporalAntiAliasNode { &self, _graph: &mut RenderGraphContext, render_context: &mut RenderContext, - (camera, view_target, taa_history_textures, prepass_textures, taa_pipeline_id, msaa): QueryItem< - Self::ViewQuery, - >, + (camera, view_target, taa_history_textures, prepass_textures, taa_pipeline_id, msaa): QueryItem, world: &World, ) -> Result<(), NodeRunError> { if *msaa != Msaa::Off { diff --git a/crates/bevy_derive/src/derefs.rs b/crates/bevy_derive/src/derefs.rs index 0dd3b152bfda5..1c5ec2e957959 100644 --- a/crates/bevy_derive/src/derefs.rs +++ b/crates/bevy_derive/src/derefs.rs @@ -91,10 +91,7 @@ fn get_deref_field(ast: &DeriveInput, is_mut: bool) -> syn::Result<(Member, &Typ if let Some(selected_field) = selected_field { Ok(selected_field) } else { - Err(syn::Error::new( - Span::call_site().into(), - format!("deriving {deref_kind} on multi-field structs requires one field to have the {deref_attr_str} attribute"), - )) + Err(syn::Error::new(Span::call_site().into(), format!("deriving {deref_kind} on multi-field structs requires one field to have the {deref_attr_str} attribute"))) } } _ => Err(syn::Error::new( diff --git a/crates/bevy_ecs/macros/src/component.rs b/crates/bevy_ecs/macros/src/component.rs index 08b4e73056635..ec5918125b6d2 100644 --- a/crates/bevy_ecs/macros/src/component.rs +++ b/crates/bevy_ecs/macros/src/component.rs @@ -128,11 +128,7 @@ pub fn derive_component(input: TokenStream) -> TokenStream { let (impl_generics, type_generics, where_clause) = &ast.generics.split_for_impl(); let required_component_docs = attrs.requires.map(|r| { - let paths = r - .iter() - .map(|r| format!("[`{}`]", r.path.to_token_stream())) - .collect::>() - .join(", "); + let paths = r.iter().map(|r| format!("[`{}`]", r.path.to_token_stream())).collect::>().join(", "); let doc = format!("Required Components: {paths}. \n\n A component's Required Components are inserted whenever it is inserted. Note that this will also insert the required components _of_ the required components, recursively, in depth-first order."); quote! { #[doc = #doc] diff --git a/crates/bevy_ecs/macros/src/lib.rs b/crates/bevy_ecs/macros/src/lib.rs index 10f794075466c..9c822bcd03c5f 100644 --- a/crates/bevy_ecs/macros/src/lib.rs +++ b/crates/bevy_ecs/macros/src/lib.rs @@ -569,8 +569,8 @@ pub fn derive_system_param(input: TokenStream) -> TokenStream { } }; let lifetimes: Vec<_> = generics.lifetimes().collect(); - let generic_struct = quote!{ #struct_name <#(#lifetimes,)* #punctuated_generic_idents> }; - let builder_impl = quote!{ + let generic_struct = quote! { #struct_name <#(#lifetimes,)* #punctuated_generic_idents> }; + let builder_impl = quote! { // SAFETY: This delegates to the `SystemParamBuilder` for tuples. unsafe impl< #(#lifetimes,)* diff --git a/crates/bevy_ecs/macros/src/query_data.rs b/crates/bevy_ecs/macros/src/query_data.rs index 3f198b1ad1b18..6e778970af6c2 100644 --- a/crates/bevy_ecs/macros/src/query_data.rs +++ b/crates/bevy_ecs/macros/src/query_data.rs @@ -56,9 +56,8 @@ pub fn derive_query_data_impl(input: TokenStream) -> TokenStream { meta.parse_nested_meta(|meta| { attributes.derive_args.push(Meta::Path(meta.path)); Ok(()) - }).map_err(|_| { - meta.error(format_args!("`{DERIVE_ATTRIBUTE_NAME}` requires at least one argument")) }) + .map_err(|_| meta.error(format_args!("`{DERIVE_ATTRIBUTE_NAME}` requires at least one argument"))) } else { Err(meta.error(format_args!("invalid attribute, expected `{MUTABLE_ATTRIBUTE_NAME}` or `{DERIVE_ATTRIBUTE_NAME}`"))) } diff --git a/crates/bevy_ecs/src/bundle.rs b/crates/bevy_ecs/src/bundle.rs index 384b7517c77b2..299380bc09f29 100644 --- a/crates/bevy_ecs/src/bundle.rs +++ b/crates/bevy_ecs/src/bundle.rs @@ -1332,7 +1332,7 @@ impl Bundles { ) -> BundleId { let bundle_infos = &mut self.bundle_infos; let id = *self.bundle_ids.entry(TypeId::of::()).or_insert_with(|| { - let mut component_ids= Vec::new(); + let mut component_ids = Vec::new(); T::component_ids(components, storages, &mut |id| component_ids.push(id)); let id = BundleId(bundle_infos.len()); let bundle_info = @@ -1460,13 +1460,7 @@ fn initialize_dynamic_bundle( component_ids: Vec, ) -> (BundleId, Vec) { // Assert component existence - let storage_types = component_ids.iter().map(|&id| { - components.get_info(id).unwrap_or_else(|| { - panic!( - "init_dynamic_info called with component id {id:?} which doesn't exist in this world" - ) - }).storage_type() - }).collect(); + let storage_types = component_ids.iter().map(|&id| components.get_info(id).unwrap_or_else(|| panic!("init_dynamic_info called with component id {id:?} which doesn't exist in this world")).storage_type()).collect(); let id = BundleId(bundle_infos.len()); let bundle_info = diff --git a/crates/bevy_ecs/src/lib.rs b/crates/bevy_ecs/src/lib.rs index 67254d6298f11..5f062fd85f306 100644 --- a/crates/bevy_ecs/src/lib.rs +++ b/crates/bevy_ecs/src/lib.rs @@ -218,7 +218,7 @@ mod tests { world.entity_mut(e1).take::().unwrap(), FooBundle { x: TableStored("xyz"), - y: SparseStored(123), + y: SparseStored(123) } ); @@ -269,9 +269,9 @@ mod tests { a: A(1), foo: FooBundle { x: TableStored("ghi"), - y: SparseStored(789), + y: SparseStored(789) }, - b: B(2), + b: B(2) } ); @@ -310,7 +310,7 @@ mod tests { world.entity_mut(e4).take::().unwrap(), BundleWithIgnored { c: C, - ignored: Ignored, + ignored: Ignored } ); } @@ -1744,11 +1744,7 @@ mod tests { let mut query = world.query::<(Option<&A>, &B, &C)>(); let component_values = query.get_many(&world, [e0, e1, e2]).unwrap(); - assert_eq!( - component_values, - [(Some(&A(0)), &B(1), &C), (Some(&A(0)), &B(2), &C), (None, &B(3), &C)], - "all entities should have had their B component replaced, received C component, and had their A component (or lack thereof) unchanged" - ); + assert_eq!(component_values, [(Some(&A(0)), &B(1), &C), (Some(&A(0)), &B(2), &C), (None, &B(3), &C)], "all entities should have had their B component replaced, received C component, and had their A component (or lack thereof) unchanged"); } #[test] diff --git a/crates/bevy_ecs/src/query/fetch.rs b/crates/bevy_ecs/src/query/fetch.rs index 75c551e53f4e3..de7832de3aad4 100644 --- a/crates/bevy_ecs/src/query/fetch.rs +++ b/crates/bevy_ecs/src/query/fetch.rs @@ -491,10 +491,7 @@ unsafe impl<'a> WorldQuery for EntityRef<'a> { } fn update_component_access(_state: &Self::State, access: &mut FilteredAccess) { - assert!( - !access.access().has_any_component_write(), - "EntityRef conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.", - ); + assert!(!access.access().has_any_component_write(), "EntityRef conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.",); access.read_all_components(); } @@ -571,10 +568,7 @@ unsafe impl<'a> WorldQuery for EntityMut<'a> { } fn update_component_access(_state: &Self::State, access: &mut FilteredAccess) { - assert!( - !access.access().has_any_component_read(), - "EntityMut conflicts with a previous access in this query. Exclusive access cannot coincide with any other accesses.", - ); + assert!(!access.access().has_any_component_read(), "EntityMut conflicts with a previous access in this query. Exclusive access cannot coincide with any other accesses.",); access.write_all_components(); } @@ -661,10 +655,7 @@ unsafe impl<'a> WorldQuery for FilteredEntityRef<'a> { state: &Self::State, filtered_access: &mut FilteredAccess, ) { - assert!( - filtered_access.access().is_compatible(&state.access), - "FilteredEntityRef conflicts with a previous access in this query. Exclusive access cannot coincide with any other accesses.", - ); + assert!(filtered_access.access().is_compatible(&state.access), "FilteredEntityRef conflicts with a previous access in this query. Exclusive access cannot coincide with any other accesses.",); filtered_access.access.extend(&state.access); } @@ -755,10 +746,7 @@ unsafe impl<'a> WorldQuery for FilteredEntityMut<'a> { state: &Self::State, filtered_access: &mut FilteredAccess, ) { - assert!( - filtered_access.access().is_compatible(&state.access), - "FilteredEntityMut conflicts with a previous access in this query. Exclusive access cannot coincide with any other accesses.", - ); + assert!(filtered_access.access().is_compatible(&state.access), "FilteredEntityMut conflicts with a previous access in this query. Exclusive access cannot coincide with any other accesses.",); filtered_access.access.extend(&state.access); } @@ -1184,11 +1172,7 @@ unsafe impl WorldQuery for &T { &component_id: &ComponentId, access: &mut FilteredAccess, ) { - assert!( - !access.access().has_component_write(component_id), - "&{} conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.", - core::any::type_name::(), - ); + assert!(!access.access().has_component_write(component_id), "&{} conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.", core::any::type_name::(),); access.add_component_read(component_id); } @@ -1383,11 +1367,7 @@ unsafe impl<'__w, T: Component> WorldQuery for Ref<'__w, T> { &component_id: &ComponentId, access: &mut FilteredAccess, ) { - assert!( - !access.access().has_component_write(component_id), - "&{} conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.", - core::any::type_name::(), - ); + assert!(!access.access().has_component_write(component_id), "&{} conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.", core::any::type_name::(),); access.add_component_read(component_id); } @@ -1582,11 +1562,7 @@ unsafe impl<'__w, T: Component> WorldQuery for &'__w mut T { &component_id: &ComponentId, access: &mut FilteredAccess, ) { - assert!( - !access.access().has_component_read(component_id), - "&mut {} conflicts with a previous access in this query. Mutable component access must be unique.", - core::any::type_name::(), - ); + assert!(!access.access().has_component_read(component_id), "&mut {} conflicts with a previous access in this query. Mutable component access must be unique.", core::any::type_name::(),); access.add_component_write(component_id); } @@ -1684,11 +1660,7 @@ unsafe impl<'__w, T: Component> WorldQuery for Mut<'__w, T> { ) { // Update component access here instead of in `<&mut T as WorldQuery>` to avoid erroneously referencing // `&mut T` in error message. - assert!( - !access.access().has_component_read(component_id), - "Mut<{}> conflicts with a previous access in this query. Mutable component access mut be unique.", - core::any::type_name::(), - ); + assert!(!access.access().has_component_read(component_id), "Mut<{}> conflicts with a previous access in this query. Mutable component access mut be unique.", core::any::type_name::(),); access.add_component_write(component_id); } diff --git a/crates/bevy_ecs/src/query/filter.rs b/crates/bevy_ecs/src/query/filter.rs index 024332b914294..4254bbaa1a3ba 100644 --- a/crates/bevy_ecs/src/query/filter.rs +++ b/crates/bevy_ecs/src/query/filter.rs @@ -745,7 +745,7 @@ unsafe impl WorldQuery for Added { #[inline] fn update_component_access(&id: &ComponentId, access: &mut FilteredAccess) { if access.access().has_component_write(id) { - panic!("$state_name<{}> conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.",core::any::type_name::()); + panic!("$state_name<{}> conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.", core::any::type_name::()); } access.add_component_read(id); } @@ -978,7 +978,7 @@ unsafe impl WorldQuery for Changed { #[inline] fn update_component_access(&id: &ComponentId, access: &mut FilteredAccess) { if access.access().has_component_write(id) { - panic!("$state_name<{}> conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.",core::any::type_name::()); + panic!("$state_name<{}> conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.", core::any::type_name::()); } access.add_component_read(id); } diff --git a/crates/bevy_ecs/src/query/iter.rs b/crates/bevy_ecs/src/query/iter.rs index bf4c5432546f9..294bf36f1898d 100644 --- a/crates/bevy_ecs/src/query/iter.rs +++ b/crates/bevy_ecs/src/query/iter.rs @@ -2106,21 +2106,9 @@ mod tests { { let mut query = world.query::<&Sparse>(); let mut iter = query.iter(&world); - println!( - "before_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", - iter.cursor.archetype_entities.len(), - iter.cursor.table_entities.len(), - iter.cursor.current_len, - iter.cursor.current_row - ); + println!("before_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", iter.cursor.archetype_entities.len(), iter.cursor.table_entities.len(), iter.cursor.current_len, iter.cursor.current_row); _ = iter.next(); - println!( - "after_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", - iter.cursor.archetype_entities.len(), - iter.cursor.table_entities.len(), - iter.cursor.current_len, - iter.cursor.current_row - ); + println!("after_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", iter.cursor.archetype_entities.len(), iter.cursor.table_entities.len(), iter.cursor.current_len, iter.cursor.current_row); println!("{}", iter.sort::().len()); } } @@ -2131,21 +2119,9 @@ mod tests { { let mut query = world.query::<(&A, &Sparse)>(); let mut iter = query.iter(&world); - println!( - "before_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", - iter.cursor.archetype_entities.len(), - iter.cursor.table_entities.len(), - iter.cursor.current_len, - iter.cursor.current_row - ); + println!("before_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", iter.cursor.archetype_entities.len(), iter.cursor.table_entities.len(), iter.cursor.current_len, iter.cursor.current_row); _ = iter.next(); - println!( - "after_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", - iter.cursor.archetype_entities.len(), - iter.cursor.table_entities.len(), - iter.cursor.current_len, - iter.cursor.current_row - ); + println!("after_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", iter.cursor.archetype_entities.len(), iter.cursor.table_entities.len(), iter.cursor.current_len, iter.cursor.current_row); println!("{}", iter.sort::().len()); } } @@ -2159,22 +2135,10 @@ mod tests { { let mut query = world.query::<(&A, &Sparse)>(); let mut iter = query.iter(&world); - println!( - "before_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", - iter.cursor.archetype_entities.len(), - iter.cursor.table_entities.len(), - iter.cursor.current_len, - iter.cursor.current_row - ); + println!("before_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", iter.cursor.archetype_entities.len(), iter.cursor.table_entities.len(), iter.cursor.current_len, iter.cursor.current_row); assert!(iter.cursor.table_entities.len() | iter.cursor.archetype_entities.len() == 0); _ = iter.next(); - println!( - "after_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", - iter.cursor.archetype_entities.len(), - iter.cursor.table_entities.len(), - iter.cursor.current_len, - iter.cursor.current_row - ); + println!("after_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", iter.cursor.archetype_entities.len(), iter.cursor.table_entities.len(), iter.cursor.current_len, iter.cursor.current_row); assert!( ( iter.cursor.table_entities.len(), diff --git a/crates/bevy_ecs/src/query/mod.rs b/crates/bevy_ecs/src/query/mod.rs index 0a9f664fb50ba..b101a9c09e2aa 100644 --- a/crates/bevy_ecs/src/query/mod.rs +++ b/crates/bevy_ecs/src/query/mod.rs @@ -289,9 +289,7 @@ mod tests { values.iter().for_each(|pair| { let mut sorted = *pair; sorted.sort(); - assert!(expected.contains(&sorted), - "the results of iter_combinations should contain this combination {:?}. Expected: {:?}, got: {:?}", - &sorted, &expected, &values); + assert!(expected.contains(&sorted), "the results of iter_combinations should contain this combination {:?}. Expected: {:?}, got: {:?}", &sorted, &expected, &values); }); } diff --git a/crates/bevy_ecs/src/query/state.rs b/crates/bevy_ecs/src/query/state.rs index 69b67368fe4f3..9d9e2d289db97 100644 --- a/crates/bevy_ecs/src/query/state.rs +++ b/crates/bevy_ecs/src/query/state.rs @@ -587,11 +587,7 @@ impl QueryState { NewF::update_component_access(&filter_state, &mut filter_component_access); component_access.extend(&filter_component_access); - assert!( - component_access.is_subset(&self.component_access), - "Transmuted state for {} attempts to access terms that are not allowed by original state {}.", - core::any::type_name::<(NewD, NewF)>(), core::any::type_name::<(D, F)>() - ); + assert!(component_access.is_subset(&self.component_access), "Transmuted state for {} attempts to access terms that are not allowed by original state {}.", core::any::type_name::<(NewD, NewF)>(), core::any::type_name::<(D, F)>()); QueryState { world_id: self.world_id, @@ -665,10 +661,8 @@ impl QueryState { self.validate_world(world.id()); let mut component_access = FilteredAccess::default(); - let mut new_fetch_state = NewD::get_state(world.components()) - .expect("Could not create fetch_state, Please initialize all referenced components before transmuting."); - let new_filter_state = NewF::get_state(world.components()) - .expect("Could not create filter_state, Please initialize all referenced components before transmuting."); + let mut new_fetch_state = NewD::get_state(world.components()).expect("Could not create fetch_state, Please initialize all referenced components before transmuting."); + let new_filter_state = NewF::get_state(world.components()).expect("Could not create filter_state, Please initialize all referenced components before transmuting."); NewD::set_access(&mut new_fetch_state, &self.component_access); NewD::update_component_access(&new_fetch_state, &mut component_access); @@ -681,11 +675,7 @@ impl QueryState { let mut joined_component_access = self.component_access.clone(); joined_component_access.extend(&other.component_access); - assert!( - component_access.is_subset(&joined_component_access), - "Joined state for {} attempts to access terms that are not allowed by state {} joined with {}.", - core::any::type_name::<(NewD, NewF)>(), core::any::type_name::<(D, F)>(), core::any::type_name::<(OtherD, OtherF)>() - ); + assert!(component_access.is_subset(&joined_component_access), "Joined state for {} attempts to access terms that are not allowed by state {} joined with {}.", core::any::type_name::<(NewD, NewF)>(), core::any::type_name::<(D, F)>(), core::any::type_name::<(OtherD, OtherF)>()); if self.archetype_generation != other.archetype_generation { warn!("You have tried to join queries with different archetype_generations. This could lead to unpredictable results."); diff --git a/crates/bevy_ecs/src/schedule/schedule.rs b/crates/bevy_ecs/src/schedule/schedule.rs index 129f8e97a7fe1..49cac29f45975 100644 --- a/crates/bevy_ecs/src/schedule/schedule.rs +++ b/crates/bevy_ecs/src/schedule/schedule.rs @@ -1868,9 +1868,9 @@ impl ScheduleGraph { let n_ambiguities = ambiguities.len(); let mut message = format!( - "{n_ambiguities} pairs of systems with conflicting data access have indeterminate execution order. \ + "{n_ambiguities} pairs of systems with conflicting data access have indeterminate execution order. \ Consider adding `before`, `after`, or `ambiguous_with` relationships between these:\n", - ); + ); for (name_a, name_b, conflicts) in self.conflicts_to_string(ambiguities, components) { writeln!(message, " -- {name_a} and {name_b}").unwrap(); diff --git a/crates/bevy_ecs/src/storage/resource.rs b/crates/bevy_ecs/src/storage/resource.rs index ed8700e1c74e2..6e546c802102d 100644 --- a/crates/bevy_ecs/src/storage/resource.rs +++ b/crates/bevy_ecs/src/storage/resource.rs @@ -65,12 +65,7 @@ impl ResourceData { } if self.origin_thread_id != Some(std::thread::current().id()) { // Panic in tests, as testing for aborting is nearly impossible - panic!( - "Attempted to access or drop non-send resource {} from thread {:?} on a thread {:?}. This is not allowed. Aborting.", - self.type_name, - self.origin_thread_id, - std::thread::current().id() - ); + panic!("Attempted to access or drop non-send resource {} from thread {:?} on a thread {:?}. This is not allowed. Aborting.", self.type_name, self.origin_thread_id, std::thread::current().id()); } } @@ -353,20 +348,10 @@ impl Resources { self.resources.get_or_insert_with(component_id, || { let component_info = components.get_info(component_id).unwrap(); if SEND { - assert!( - component_info.is_send_and_sync(), - "Send + Sync resource {} initialized as non_send. It may have been inserted via World::insert_non_send_resource by accident. Try using World::insert_resource instead.", - component_info.name(), - ); + assert!(component_info.is_send_and_sync(), "Send + Sync resource {} initialized as non_send. It may have been inserted via World::insert_non_send_resource by accident. Try using World::insert_resource instead.", component_info.name(),); } // SAFETY: component_info.drop() is valid for the types that will be inserted. - let data = unsafe { - BlobVec::new( - component_info.layout(), - component_info.drop(), - 1 - ) - }; + let data = unsafe { BlobVec::new(component_info.layout(), component_info.drop(), 1) }; ResourceData { data: ManuallyDrop::new(data), added_ticks: UnsafeCell::new(Tick::new(0)), @@ -375,7 +360,7 @@ impl Resources { id: f(), origin_thread_id: None, #[cfg(feature = "track_change_detection")] - changed_by: UnsafeCell::new(Location::caller()) + changed_by: UnsafeCell::new(Location::caller()), } }) } diff --git a/crates/bevy_ecs/src/system/commands/mod.rs b/crates/bevy_ecs/src/system/commands/mod.rs index 08eda1e5d59fc..8bc73603b78f3 100644 --- a/crates/bevy_ecs/src/system/commands/mod.rs +++ b/crates/bevy_ecs/src/system/commands/mod.rs @@ -168,7 +168,7 @@ const _: () = { world: UnsafeWorldCell<'w>, change_tick: bevy_ecs::component::Tick, ) -> Self::Item<'w, 's> { - let(f0, f1) = <(Deferred<'s, CommandQueue>, &'w Entities) as bevy_ecs::system::SystemParam>::get_param(&mut state.state, system_meta, world, change_tick); + let (f0, f1) = <(Deferred<'s, CommandQueue>, &'w Entities) as bevy_ecs::system::SystemParam>::get_param(&mut state.state, system_meta, world, change_tick); Commands { queue: InternalQueue::CommandQueue(f0), entities: f1, @@ -438,9 +438,7 @@ impl<'w, 's> Commands<'w, 's> { #[cold] #[track_caller] fn panic_no_entity(entity: Entity) -> ! { - panic!( - "Attempting to create an EntityCommands for entity {entity:?}, which doesn't exist.", - ); + panic!("Attempting to create an EntityCommands for entity {entity:?}, which doesn't exist.",); } match self.get_entity(entity) { @@ -1264,9 +1262,11 @@ impl<'a> EntityCommands<'a> { ) -> &mut Self { let caller = Location::caller(); // SAFETY: same invariants as parent call - self.queue(unsafe {insert_by_id(component_id, value, move |entity| { - panic!("error[B0003]: {caller}: Could not insert a component {component_id:?} (with type {}) for entity {entity:?} because it doesn't exist in this World. See: https://bevyengine.org/learn/errors/b0003", core::any::type_name::()); - })}) + self.queue(unsafe { + insert_by_id(component_id, value, move |entity| { + panic!("error[B0003]: {caller}: Could not insert a component {component_id:?} (with type {}) for entity {entity:?} because it doesn't exist in this World. See: https://bevyengine.org/learn/errors/b0003", core::any::type_name::()); + }) + }) } /// Attempts to add a dynamic component to an entity. @@ -1827,11 +1827,7 @@ where #[cfg(feature = "track_change_detection")] caller, ) { - error!( - "Failed to 'insert or spawn' bundle of type {} into the following invalid entities: {:?}", - core::any::type_name::(), - invalid_entities - ); + error!("Failed to 'insert or spawn' bundle of type {} into the following invalid entities: {:?}", core::any::type_name::(), invalid_entities); } } } diff --git a/crates/bevy_ecs/src/system/mod.rs b/crates/bevy_ecs/src/system/mod.rs index cd2452bcbca4e..01b9cae286849 100644 --- a/crates/bevy_ecs/src/system/mod.rs +++ b/crates/bevy_ecs/src/system/mod.rs @@ -965,11 +965,7 @@ mod tests { despawned: Res, mut n_systems: ResMut, ) { - assert_eq!( - removed_i32.read().collect::>(), - &[despawned.0], - "despawning causes the correct entity to show up in the 'RemovedComponent' system parameter." - ); + assert_eq!(removed_i32.read().collect::>(), &[despawned.0], "despawning causes the correct entity to show up in the 'RemovedComponent' system parameter."); n_systems.0 += 1; } @@ -993,11 +989,7 @@ mod tests { ) { // The despawned entity from the previous frame was // double buffered so we now have it in this system as well. - assert_eq!( - removed_i32.read().collect::>(), - &[despawned.0, removed.0], - "removing a component causes the correct entity to show up in the 'RemovedComponent' system parameter." - ); + assert_eq!(removed_i32.read().collect::>(), &[despawned.0, removed.0], "removing a component causes the correct entity to show up in the 'RemovedComponent' system parameter."); n_systems.0 += 1; } diff --git a/crates/bevy_ecs/src/system/system_param.rs b/crates/bevy_ecs/src/system/system_param.rs index c3e2645864094..d0ef3fcd09865 100644 --- a/crates/bevy_ecs/src/system/system_param.rs +++ b/crates/bevy_ecs/src/system/system_param.rs @@ -750,12 +750,7 @@ unsafe impl<'a, T: Resource> SystemParam for Res<'a, T> { let archetype_component_id = world.initialize_resource_internal(component_id).id(); let combined_access = system_meta.component_access_set.combined_access(); - assert!( - !combined_access.has_resource_write(component_id), - "error[B0002]: Res<{}> in system {} conflicts with a previous ResMut<{0}> access. Consider removing the duplicate access. See: https://bevyengine.org/learn/errors/b0002", - core::any::type_name::(), - system_meta.name, - ); + assert!(!combined_access.has_resource_write(component_id), "error[B0002]: Res<{}> in system {} conflicts with a previous ResMut<{0}> access. Consider removing the duplicate access. See: https://bevyengine.org/learn/errors/b0002", core::any::type_name::(), system_meta.name,); system_meta .component_access_set .add_unfiltered_resource_read(component_id); @@ -862,13 +857,9 @@ unsafe impl<'a, T: Resource> SystemParam for ResMut<'a, T> { let combined_access = system_meta.component_access_set.combined_access(); if combined_access.has_resource_write(component_id) { - panic!( - "error[B0002]: ResMut<{}> in system {} conflicts with a previous ResMut<{0}> access. Consider removing the duplicate access. See: https://bevyengine.org/learn/errors/b0002", - core::any::type_name::(), system_meta.name); + panic!("error[B0002]: ResMut<{}> in system {} conflicts with a previous ResMut<{0}> access. Consider removing the duplicate access. See: https://bevyengine.org/learn/errors/b0002", core::any::type_name::(), system_meta.name); } else if combined_access.has_resource_read(component_id) { - panic!( - "error[B0002]: ResMut<{}> in system {} conflicts with a previous Res<{0}> access. Consider removing the duplicate access. See: https://bevyengine.org/learn/errors/b0002", - core::any::type_name::(), system_meta.name); + panic!("error[B0002]: ResMut<{}> in system {} conflicts with a previous Res<{0}> access. Consider removing the duplicate access. See: https://bevyengine.org/learn/errors/b0002", core::any::type_name::(), system_meta.name); } system_meta .component_access_set @@ -1413,12 +1404,7 @@ unsafe impl<'a, T: 'static> SystemParam for NonSend<'a, T> { let archetype_component_id = world.initialize_non_send_internal(component_id).id(); let combined_access = system_meta.component_access_set.combined_access(); - assert!( - !combined_access.has_resource_write(component_id), - "error[B0002]: NonSend<{}> in system {} conflicts with a previous mutable resource access ({0}). Consider removing the duplicate access. See: https://bevyengine.org/learn/errors/b0002", - core::any::type_name::(), - system_meta.name, - ); + assert!(!combined_access.has_resource_write(component_id), "error[B0002]: NonSend<{}> in system {} conflicts with a previous mutable resource access ({0}). Consider removing the duplicate access. See: https://bevyengine.org/learn/errors/b0002", core::any::type_name::(), system_meta.name,); system_meta .component_access_set .add_unfiltered_resource_read(component_id); @@ -1522,13 +1508,9 @@ unsafe impl<'a, T: 'static> SystemParam for NonSendMut<'a, T> { let combined_access = system_meta.component_access_set.combined_access(); if combined_access.has_component_write(component_id) { - panic!( - "error[B0002]: NonSendMut<{}> in system {} conflicts with a previous mutable resource access ({0}). Consider removing the duplicate access. See: https://bevyengine.org/learn/errors/b0002", - core::any::type_name::(), system_meta.name); + panic!("error[B0002]: NonSendMut<{}> in system {} conflicts with a previous mutable resource access ({0}). Consider removing the duplicate access. See: https://bevyengine.org/learn/errors/b0002", core::any::type_name::(), system_meta.name); } else if combined_access.has_component_read(component_id) { - panic!( - "error[B0002]: NonSendMut<{}> in system {} conflicts with a previous immutable resource access ({0}). Consider removing the duplicate access. See: https://bevyengine.org/learn/errors/b0002", - core::any::type_name::(), system_meta.name); + panic!("error[B0002]: NonSendMut<{}> in system {} conflicts with a previous immutable resource access ({0}). Consider removing the duplicate access. See: https://bevyengine.org/learn/errors/b0002", core::any::type_name::(), system_meta.name); } system_meta .component_access_set diff --git a/crates/bevy_ecs/src/world/deferred_world.rs b/crates/bevy_ecs/src/world/deferred_world.rs index 0ffd94e01e2f1..d403850a2589e 100644 --- a/crates/bevy_ecs/src/world/deferred_world.rs +++ b/crates/bevy_ecs/src/world/deferred_world.rs @@ -353,10 +353,7 @@ impl<'w> DeferredWorld<'w> { events: impl IntoIterator, ) -> Option> { let Some(mut events_resource) = self.get_resource_mut::>() else { - bevy_utils::tracing::error!( - "Unable to send event `{}`\n\tEvent must be added to the app with `add_event()`\n\thttps://docs.rs/bevy/*/bevy/app/struct.App.html#method.add_event ", - core::any::type_name::() - ); + bevy_utils::tracing::error!("Unable to send event `{}`\n\tEvent must be added to the app with `add_event()`\n\thttps://docs.rs/bevy/*/bevy/app/struct.App.html#method.add_event ", core::any::type_name::()); return None; }; Some(events_resource.send_batch(events)) diff --git a/crates/bevy_ecs/src/world/mod.rs b/crates/bevy_ecs/src/world/mod.rs index d50f8f421cfc2..ee4b77635ebd2 100644 --- a/crates/bevy_ecs/src/world/mod.rs +++ b/crates/bevy_ecs/src/world/mod.rs @@ -2822,10 +2822,12 @@ impl World { changed_by: &mut _caller, }; let result = f(self, value_mut); - assert!(!self.contains_resource::(), + assert!( + !self.contains_resource::(), "Resource `{}` was inserted during a call to World::resource_scope.\n\ This is not allowed as the original resource is reinserted to the world after the closure is invoked.", - core::any::type_name::()); + core::any::type_name::() + ); OwningPtr::make(value, |ptr| { // SAFETY: pointer is of type R @@ -2878,10 +2880,7 @@ impl World { events: impl IntoIterator, ) -> Option> { let Some(mut events_resource) = self.get_resource_mut::>() else { - bevy_utils::tracing::error!( - "Unable to send event `{}`\n\tEvent must be added to the app with `add_event()`\n\thttps://docs.rs/bevy/*/bevy/app/struct.App.html#method.add_event ", - core::any::type_name::() - ); + bevy_utils::tracing::error!("Unable to send event `{}`\n\tEvent must be added to the app with `add_event()`\n\thttps://docs.rs/bevy/*/bevy/app/struct.App.html#method.add_event ", core::any::type_name::()); return None; }; Some(events_resource.send_batch(events)) diff --git a/crates/bevy_gilrs/src/rumble.rs b/crates/bevy_gilrs/src/rumble.rs index a4466e49aec86..d7dab2baaa085 100644 --- a/crates/bevy_gilrs/src/rumble.rs +++ b/crates/bevy_gilrs/src/rumble.rs @@ -152,9 +152,7 @@ pub(crate) fn play_gilrs_rumble( if let ff::Error::FfNotSupported(_) = err { debug!("Tried to rumble {gamepad:?}, but it doesn't support force feedback"); } else { - warn!( - "Tried to handle rumble request for {gamepad:?} but an error occurred: {err}" - ); + warn!("Tried to handle rumble request for {gamepad:?} but an error occurred: {err}"); } } Err(RumbleError::GamepadNotFound) => { diff --git a/crates/bevy_gizmos/src/primitives/dim2.rs b/crates/bevy_gizmos/src/primitives/dim2.rs index 0c3b44cd67dee..028bfa285f13b 100644 --- a/crates/bevy_gizmos/src/primitives/dim2.rs +++ b/crates/bevy_gizmos/src/primitives/dim2.rs @@ -618,10 +618,8 @@ where gizmos: self, direction: primitive.direction, half_length: primitive.half_length, - isometry: isometry.into(), color: color.into(), - draw_arrow: Default::default(), } } diff --git a/crates/bevy_gltf/src/loader.rs b/crates/bevy_gltf/src/loader.rs index 1cc747264e7a7..c386c3ab3108f 100644 --- a/crates/bevy_gltf/src/loader.rs +++ b/crates/bevy_gltf/src/loader.rs @@ -607,11 +607,7 @@ async fn load_gltf<'a, 'b, 'c>( for (semantic, accessor) in primitive.attributes() { if [Semantic::Joints(0), Semantic::Weights(0)].contains(&semantic) { if !meshes_on_skinned_nodes.contains(&gltf_mesh.index()) { - warn!( - "Ignoring attribute {:?} for skinned mesh {:?} used on non skinned nodes (NODE_SKINNED_MESH_WITHOUT_SKIN)", - semantic, - primitive_label - ); + warn!("Ignoring attribute {:?} for skinned mesh {:?} used on non skinned nodes (NODE_SKINNED_MESH_WITHOUT_SKIN)", semantic, primitive_label); continue; } else if meshes_on_non_skinned_nodes.contains(&gltf_mesh.index()) { error!("Skinned mesh {:?} used on both skinned and non skin nodes, this is likely to cause an error (NODE_SKINNED_MESH_WITHOUT_SKIN)", primitive_label); @@ -690,18 +686,13 @@ async fn load_gltf<'a, 'b, 'c>( } else if mesh.attribute(Mesh::ATTRIBUTE_NORMAL).is_some() && material_needs_tangents(&primitive.material()) { - bevy_utils::tracing::debug!( - "Missing vertex tangents for {}, computing them using the mikktspace algorithm. Consider using a tool such as Blender to pre-compute the tangents.", file_name - ); + bevy_utils::tracing::debug!("Missing vertex tangents for {}, computing them using the mikktspace algorithm. Consider using a tool such as Blender to pre-compute the tangents.", file_name); let generate_tangents_span = info_span!("generate_tangents", name = file_name); generate_tangents_span.in_scope(|| { if let Err(err) = mesh.generate_tangents() { - warn!( - "Failed to generate vertex tangents using the mikktspace algorithm: {:?}", - err - ); + warn!("Failed to generate vertex tangents using the mikktspace algorithm: {:?}", err); } }); } @@ -1328,7 +1319,8 @@ fn warn_on_differing_texture_transforms( .unwrap_or_else(|| "default".to_string()); warn!( "Only texture transforms on base color textures are supported, but {material_name} ({material_index}) \ - has a texture transform on {texture_name} (index {}), which will be ignored.", info.texture().index() + has a texture transform on {texture_name} (index {}), which will be ignored.", + info.texture().index() ); } } diff --git a/crates/bevy_image/src/basis.rs b/crates/bevy_image/src/basis.rs index e91c40e840d47..7b839dbdb1229 100644 --- a/crates/bevy_image/src/basis.rs +++ b/crates/bevy_image/src/basis.rs @@ -46,9 +46,7 @@ pub fn basis_buffer_to_image( let image_count = transcoder.image_count(buffer); let texture_type = transcoder.basis_texture_type(buffer); if texture_type == BasisTextureType::TextureTypeCubemapArray && image_count % 6 != 0 { - return Err(TextureError::InvalidData(format!( - "Basis file with cube map array texture with non-modulo 6 number of images: {image_count}", - ))); + return Err(TextureError::InvalidData(format!("Basis file with cube map array texture with non-modulo 6 number of images: {image_count}",))); } let image0_mip_level_count = transcoder.image_level_count(buffer, 0); @@ -58,39 +56,15 @@ pub fn basis_buffer_to_image( && (image_info.m_orig_width != image0_info.m_orig_width || image_info.m_orig_height != image0_info.m_orig_height) { - return Err(TextureError::UnsupportedTextureFormat(format!( - "Basis file with multiple 2D textures with different sizes not supported. Image {} {}x{}, image 0 {}x{}", - image_index, - image_info.m_orig_width, - image_info.m_orig_height, - image0_info.m_orig_width, - image0_info.m_orig_height, - ))); + return Err(TextureError::UnsupportedTextureFormat(format!("Basis file with multiple 2D textures with different sizes not supported. Image {} {}x{}, image 0 {}x{}", image_index, image_info.m_orig_width, image_info.m_orig_height, image0_info.m_orig_width, image0_info.m_orig_height,))); } } let mip_level_count = transcoder.image_level_count(buffer, image_index); if mip_level_count != image0_mip_level_count { - return Err(TextureError::InvalidData(format!( - "Array or volume texture has inconsistent number of mip levels. Image {image_index} has {mip_level_count} but image 0 has {image0_mip_level_count}", - ))); + return Err(TextureError::InvalidData(format!("Array or volume texture has inconsistent number of mip levels. Image {image_index} has {mip_level_count} but image 0 has {image0_mip_level_count}",))); } for level_index in 0..mip_level_count { - let mut data = transcoder - .transcode_image_level( - buffer, - transcode_format, - TranscodeParameters { - image_index, - level_index, - decode_flags: Some(DecodeFlags::HIGH_QUALITY), - ..Default::default() - }, - ) - .map_err(|error| { - TextureError::TranscodeError(format!( - "Failed to transcode mip level {level_index} from {basis_texture_format:?} to {transcode_format:?}: {error:?}", - )) - })?; + let mut data = transcoder.transcode_image_level(buffer, transcode_format, TranscodeParameters { image_index, level_index, decode_flags: Some(DecodeFlags::HIGH_QUALITY), ..Default::default() }).map_err(|error| TextureError::TranscodeError(format!("Failed to transcode mip level {level_index} from {basis_texture_format:?} to {transcode_format:?}: {error:?}",)))?; transcoded.append(&mut data); } } diff --git a/crates/bevy_image/src/ktx2.rs b/crates/bevy_image/src/ktx2.rs index cb202bc863a27..705989fa00a5c 100644 --- a/crates/bevy_image/src/ktx2.rs +++ b/crates/bevy_image/src/ktx2.rs @@ -51,11 +51,7 @@ pub fn ktx2_buffer_to_image( SupercompressionScheme::ZLIB => { let mut decoder = flate2::bufread::ZlibDecoder::new(_level_data); let mut decompressed = Vec::new(); - decoder.read_to_end(&mut decompressed).map_err(|err| { - TextureError::SuperDecompressionError(format!( - "Failed to decompress {supercompression_scheme:?} for mip {_level}: {err:?}", - )) - })?; + decoder.read_to_end(&mut decompressed).map_err(|err| TextureError::SuperDecompressionError(format!("Failed to decompress {supercompression_scheme:?} for mip {_level}: {err:?}",)))?; levels.push(decompressed); } #[cfg(feature = "ruzstd")] @@ -64,11 +60,7 @@ pub fn ktx2_buffer_to_image( let mut decoder = ruzstd::StreamingDecoder::new(&mut cursor) .map_err(|err| TextureError::SuperDecompressionError(err.to_string()))?; let mut decompressed = Vec::new(); - decoder.read_to_end(&mut decompressed).map_err(|err| { - TextureError::SuperDecompressionError(format!( - "Failed to decompress {supercompression_scheme:?} for mip {_level}: {err:?}", - )) - })?; + decoder.read_to_end(&mut decompressed).map_err(|err| TextureError::SuperDecompressionError(format!("Failed to decompress {supercompression_scheme:?} for mip {_level}: {err:?}",)))?; levels.push(decompressed); } _ => { @@ -92,11 +84,7 @@ pub fn ktx2_buffer_to_image( let (mut original_width, mut original_height) = (width, height); for (level, level_data) in levels.iter().enumerate() { - transcoded[level] = level_data - .iter() - .copied() - .map(|v| (Srgba::gamma_function(v as f32 / 255.) * 255.).floor() as u8) - .collect::>(); + transcoded[level] = level_data.iter().copied().map(|v| (Srgba::gamma_function(v as f32 / 255.) * 255.).floor() as u8).collect::>(); // Next mip dimensions are half the current, minimum 1x1 original_width = (original_width / 2).max(1); @@ -109,11 +97,7 @@ pub fn ktx2_buffer_to_image( let (mut original_width, mut original_height) = (width, height); for (level, level_data) in levels.iter().enumerate() { - transcoded[level] = level_data - .iter() - .copied() - .map(|v| (Srgba::gamma_function(v as f32 / 255.) * 255.).floor() as u8) - .collect::>(); + transcoded[level] = level_data.iter().copied().map(|v| (Srgba::gamma_function(v as f32 / 255.) * 255.).floor() as u8).collect::>(); // Next mip dimensions are half the current, minimum 1x1 original_width = (original_width / 2).max(1); @@ -149,26 +133,16 @@ pub fn ktx2_buffer_to_image( } #[cfg(feature = "basis-universal")] TranscodeFormat::Uastc(data_format) => { - let (transcode_block_format, texture_format) = - get_transcoded_formats(supported_compressed_formats, data_format, is_srgb); + let (transcode_block_format, texture_format) = get_transcoded_formats(supported_compressed_formats, data_format, is_srgb); let texture_format_info = texture_format; - let (block_width_pixels, block_height_pixels) = ( - texture_format_info.block_dimensions().0, - texture_format_info.block_dimensions().1, - ); + let (block_width_pixels, block_height_pixels) = (texture_format_info.block_dimensions().0, texture_format_info.block_dimensions().1); // Texture is not a depth or stencil format, it is possible to pass `None` and unwrap let block_bytes = texture_format_info.block_copy_size(None).unwrap(); let transcoder = LowLevelUastcTranscoder::new(); for (level, level_data) in levels.iter().enumerate() { - let (level_width, level_height) = ( - (width >> level as u32).max(1), - (height >> level as u32).max(1), - ); - let (num_blocks_x, num_blocks_y) = ( - level_width.div_ceil(block_width_pixels) .max(1), - level_height.div_ceil(block_height_pixels) .max(1), - ); + let (level_width, level_height) = ((width >> level as u32).max(1), (height >> level as u32).max(1)); + let (num_blocks_x, num_blocks_y) = (level_width.div_ceil(block_width_pixels).max(1), level_height.div_ceil(block_height_pixels).max(1)); let level_bytes = (num_blocks_x * num_blocks_y * block_bytes) as usize; let mut offset = 0; @@ -176,26 +150,8 @@ pub fn ktx2_buffer_to_image( for _face in 0..face_count { // NOTE: SliceParametersUastc does not implement Clone nor Copy so // it has to be created per use - let slice_parameters = SliceParametersUastc { - num_blocks_x, - num_blocks_y, - has_alpha: false, - original_width: level_width, - original_height: level_height, - }; - transcoder - .transcode_slice( - &level_data[offset..(offset + level_bytes)], - slice_parameters, - DecodeFlags::HIGH_QUALITY, - transcode_block_format, - ) - .map(|mut transcoded_level| transcoded[level].append(&mut transcoded_level)) - .map_err(|error| { - TextureError::SuperDecompressionError(format!( - "Failed to transcode mip level {level} from UASTC to {transcode_block_format:?}: {error:?}", - )) - })?; + let slice_parameters = SliceParametersUastc { num_blocks_x, num_blocks_y, has_alpha: false, original_width: level_width, original_height: level_height }; + transcoder.transcode_slice(&level_data[offset..(offset + level_bytes)], slice_parameters, DecodeFlags::HIGH_QUALITY, transcode_block_format).map(|mut transcoded_level| transcoded[level].append(&mut transcoded_level)).map_err(|error| TextureError::SuperDecompressionError(format!("Failed to transcode mip level {level} from UASTC to {transcode_block_format:?}: {error:?}",)))?; offset += level_bytes; } } @@ -205,11 +161,7 @@ pub fn ktx2_buffer_to_image( // ETC1S is a subset of ETC1 which is a subset of ETC2 // TODO: Implement transcoding TranscodeFormat::Etc1s => { - let texture_format = if is_srgb { - TextureFormat::Etc2Rgb8UnormSrgb - } else { - TextureFormat::Etc2Rgb8Unorm - }; + let texture_format = if is_srgb { TextureFormat::Etc2Rgb8UnormSrgb } else { TextureFormat::Etc2Rgb8Unorm }; if !supported_compressed_formats.supports(texture_format) { return Err(error); } diff --git a/crates/bevy_input/src/gamepad.rs b/crates/bevy_input/src/gamepad.rs index 8c9d369063746..dd47aa702af44 100644 --- a/crates/bevy_input/src/gamepad.rs +++ b/crates/bevy_input/src/gamepad.rs @@ -1642,10 +1642,7 @@ mod tests { expected: Option, ) { let actual = settings.filter(new_value, old_value); - assert_eq!( - expected, actual, - "Testing filtering for {settings:?} with new_value = {new_value:?}, old_value = {old_value:?}", - ); + assert_eq!(expected, actual, "Testing filtering for {settings:?} with new_value = {new_value:?}, old_value = {old_value:?}",); } #[test] @@ -1697,10 +1694,7 @@ mod tests { expected: Option, ) { let actual = settings.filter(new_value, old_value); - assert_eq!( - expected, actual, - "Testing filtering for {settings:?} with new_value = {new_value:?}, old_value = {old_value:?}", - ); + assert_eq!(expected, actual, "Testing filtering for {settings:?} with new_value = {new_value:?}, old_value = {old_value:?}",); } #[test] @@ -1833,9 +1827,7 @@ mod tests { assert_eq!(button_settings.release_threshold, release_threshold); } Err(_) => { - panic!( - "ButtonSettings::new({press_threshold}, {release_threshold}) should be valid" - ); + panic!("ButtonSettings::new({press_threshold}, {release_threshold}) should be valid"); } } } @@ -1858,9 +1850,7 @@ mod tests { let bs = ButtonSettings::new(press_threshold, release_threshold); match bs { Ok(_) => { - panic!( - "ButtonSettings::new({press_threshold}, {release_threshold}) should be invalid" - ); + panic!("ButtonSettings::new({press_threshold}, {release_threshold}) should be invalid"); } Err(err_code) => match err_code { ButtonSettingsError::PressThresholdOutOfRange(_press_threshold) => {} @@ -1884,7 +1874,7 @@ mod tests { deadzone_lowerbound: -0.05, deadzone_upperbound: 0.05, livezone_upperbound: 0.95, - threshold: 0.001, + threshold: 0.001 }) ); assert_eq!( @@ -1927,7 +1917,7 @@ mod tests { Err( AxisSettingsError::LiveZoneLowerBoundGreaterThanDeadZoneLowerBound { livezone_lowerbound: -0.1, - deadzone_lowerbound: -0.3, + deadzone_lowerbound: -0.3 } ), axis_settings.try_set_livezone_lowerbound(-0.1) diff --git a/crates/bevy_log/src/lib.rs b/crates/bevy_log/src/lib.rs index 3b98a2c23199f..b87dc95ea3914 100644 --- a/crates/bevy_log/src/lib.rs +++ b/crates/bevy_log/src/lib.rs @@ -304,9 +304,7 @@ impl Plugin for LogPlugin { bevy_utils::tracing::subscriber::set_global_default(finished_subscriber).is_err(); match (logger_already_set, subscriber_already_set) { - (true, true) => error!( - "Could not set global logger and tracing subscriber as they are already set. Consider disabling LogPlugin." - ), + (true, true) => error!("Could not set global logger and tracing subscriber as they are already set. Consider disabling LogPlugin."), (true, false) => error!("Could not set global logger as it is already set. Consider disabling LogPlugin."), (false, true) => error!("Could not set global tracing subscriber as it is already set. Consider disabling LogPlugin."), (false, false) => (), diff --git a/crates/bevy_macro_utils/src/attrs.rs b/crates/bevy_macro_utils/src/attrs.rs index 9e000f217bbe3..00b6dc590fc7c 100644 --- a/crates/bevy_macro_utils/src/attrs.rs +++ b/crates/bevy_macro_utils/src/attrs.rs @@ -26,9 +26,6 @@ pub fn get_lit_bool(attr_name: Symbol, value: &Expr) -> syn::Result { { Ok(lit.value()) } else { - Err(syn::Error::new_spanned( - value, - format!("expected {attr_name} attribute to be a bool value, `true` or `false`: `{attr_name} = ...`"), - ))? + Err(syn::Error::new_spanned(value, format!("expected {attr_name} attribute to be a bool value, `true` or `false`: `{attr_name} = ...`")))? } } diff --git a/crates/bevy_math/src/bounding/bounded2d/mod.rs b/crates/bevy_math/src/bounding/bounded2d/mod.rs index 7e824101bc790..9a9a6ad7b6805 100644 --- a/crates/bevy_math/src/bounding/bounded2d/mod.rs +++ b/crates/bevy_math/src/bounding/bounded2d/mod.rs @@ -421,15 +421,15 @@ mod aabb2d_tests { assert!(aabb.intersects(&aabb)); assert!(aabb.intersects(&Aabb2d { min: Vec2::new(0.5, 0.5), - max: Vec2::new(2.0, 2.0), + max: Vec2::new(2.0, 2.0) })); assert!(aabb.intersects(&Aabb2d { min: Vec2::new(-2.0, -2.0), - max: Vec2::new(-0.5, -0.5), + max: Vec2::new(-0.5, -0.5) })); assert!(!aabb.intersects(&Aabb2d { min: Vec2::new(1.1, 0.0), - max: Vec2::new(2.0, 0.5), + max: Vec2::new(2.0, 0.5) })); } diff --git a/crates/bevy_math/src/bounding/bounded3d/mod.rs b/crates/bevy_math/src/bounding/bounded3d/mod.rs index 38460fc08e09f..1219946aba6ba 100644 --- a/crates/bevy_math/src/bounding/bounded3d/mod.rs +++ b/crates/bevy_math/src/bounding/bounded3d/mod.rs @@ -425,15 +425,15 @@ mod aabb3d_tests { assert!(aabb.intersects(&aabb)); assert!(aabb.intersects(&Aabb3d { min: Vec3A::splat(0.5), - max: Vec3A::splat(2.0), + max: Vec3A::splat(2.0) })); assert!(aabb.intersects(&Aabb3d { min: Vec3A::splat(-2.0), - max: Vec3A::splat(-0.5), + max: Vec3A::splat(-0.5) })); assert!(!aabb.intersects(&Aabb3d { min: Vec3A::new(1.1, 0.0, 0.0), - max: Vec3A::new(2.0, 0.5, 0.25), + max: Vec3A::new(2.0, 0.5, 0.25) })); } diff --git a/crates/bevy_math/src/curve/cores.rs b/crates/bevy_math/src/curve/cores.rs index 6c63eabb29cfa..cb4570db05b81 100644 --- a/crates/bevy_math/src/curve/cores.rs +++ b/crates/bevy_math/src/curve/cores.rs @@ -480,9 +480,7 @@ pub enum ChunkedUnevenCoreError { ZeroWidth, /// At least two sample times are necessary to interpolate in `ChunkedUnevenCore`. - #[display( - "Need at least two unique samples to create a ChunkedUnevenCore, but {samples} were provided" - )] + #[display("Need at least two unique samples to create a ChunkedUnevenCore, but {samples} were provided")] NotEnoughSamples { /// The number of samples that were provided. samples: usize, diff --git a/crates/bevy_math/src/rotation2d.rs b/crates/bevy_math/src/rotation2d.rs index d4df9548f5741..b111796b20e35 100644 --- a/crates/bevy_math/src/rotation2d.rs +++ b/crates/bevy_math/src/rotation2d.rs @@ -653,7 +653,7 @@ mod tests { // Valid assert!(Rot2 { sin: 10.0, - cos: 5.0, + cos: 5.0 } .try_normalize() .is_some()); @@ -661,7 +661,7 @@ mod tests { // NaN assert!(Rot2 { sin: f32::NAN, - cos: 5.0, + cos: 5.0 } .try_normalize() .is_none()); @@ -672,7 +672,7 @@ mod tests { // Non-finite assert!(Rot2 { sin: f32::INFINITY, - cos: 5.0, + cos: 5.0 } .try_normalize() .is_none()); diff --git a/crates/bevy_mesh/src/conversions.rs b/crates/bevy_mesh/src/conversions.rs index 58cb9b42d0d58..f2b32e754c5bd 100644 --- a/crates/bevy_mesh/src/conversions.rs +++ b/crates/bevy_mesh/src/conversions.rs @@ -453,7 +453,6 @@ mod tests { error.to_string(), "cannot convert VertexAttributeValues::Uint32x4 to alloc::vec::Vec" ); - assert_eq!(format!("{error:?}"), - "FromVertexAttributeError { from: Uint32x4([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]), variant: \"Uint32x4\", into: \"alloc::vec::Vec\" }"); + assert_eq!(format!("{error:?}"), "FromVertexAttributeError { from: Uint32x4([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]), variant: \"Uint32x4\", into: \"alloc::vec::Vec\" }"); } } diff --git a/crates/bevy_mesh/src/mesh.rs b/crates/bevy_mesh/src/mesh.rs index f2a9646d049b3..4ac0ed5f55ebc 100644 --- a/crates/bevy_mesh/src/mesh.rs +++ b/crates/bevy_mesh/src/mesh.rs @@ -225,10 +225,7 @@ impl Mesh { let values = values.into(); let values_format = VertexFormat::from(&values); if values_format != attribute.format { - panic!( - "Failed to insert attribute. Invalid attribute format for {}. Given format is {values_format:?} but expected {:?}", - attribute.name, attribute.format - ); + panic!("Failed to insert attribute. Invalid attribute format for {}. Given format is {values_format:?} but expected {:?}", attribute.name, attribute.format); } self.attributes @@ -432,8 +429,10 @@ impl Mesh { .map(|data| data.attribute.name.to_string()) .unwrap_or_else(|| format!("{attribute_id:?}")); - warn!("{name} has a different vertex count ({attribute_len}) than other attributes ({previous_vertex_count}) in this mesh, \ - all attributes will be truncated to match the smallest."); + warn!( + "{name} has a different vertex count ({attribute_len}) than other attributes ({previous_vertex_count}) in this mesh, \ + all attributes will be truncated to match the smallest." + ); vertex_count = Some(core::cmp::min(previous_vertex_count, attribute_len)); } } else { @@ -638,10 +637,7 @@ impl Mesh { /// mesh loading where we can't really blame users for loading meshes that might /// not conform to the limitations here! pub fn compute_flat_normals(&mut self) { - assert!( - self.indices().is_none(), - "`compute_flat_normals` can't work on indexed geometry. Consider calling either `Mesh::compute_smooth_normals` or `Mesh::duplicate_vertices` followed by `Mesh::compute_flat_normals`." - ); + assert!(self.indices().is_none(), "`compute_flat_normals` can't work on indexed geometry. Consider calling either `Mesh::compute_smooth_normals` or `Mesh::duplicate_vertices` followed by `Mesh::compute_flat_normals`."); assert!( matches!(self.primitive_topology, PrimitiveTopology::TriangleList), "`compute_flat_normals` can only work on `TriangleList`s" diff --git a/crates/bevy_pbr/src/cluster/mod.rs b/crates/bevy_pbr/src/cluster/mod.rs index f30dc0f432d24..17542ef7347c5 100644 --- a/crates/bevy_pbr/src/cluster/mod.rs +++ b/crates/bevy_pbr/src/cluster/mod.rs @@ -267,9 +267,7 @@ impl ClusterConfig { ClusterConfig::FixedZ { total, z_slices, .. } => { - let aspect_ratio: f32 = AspectRatio::try_from_pixels(screen_size.x, screen_size.y) - .expect("Failed to calculate aspect ratio for Cluster: screen dimensions must be positive, non-zero values") - .ratio(); + let aspect_ratio: f32 = AspectRatio::try_from_pixels(screen_size.x, screen_size.y).expect("Failed to calculate aspect ratio for Cluster: screen dimensions must be positive, non-zero values").ratio(); let mut z_slices = *z_slices; if *total < z_slices { warn!("ClusterConfig has more z-slices than total clusters!"); diff --git a/crates/bevy_pbr/src/meshlet/meshlet_mesh_manager.rs b/crates/bevy_pbr/src/meshlet/meshlet_mesh_manager.rs index 4170ac6279446..24ae5c2fa89ff 100644 --- a/crates/bevy_pbr/src/meshlet/meshlet_mesh_manager.rs +++ b/crates/bevy_pbr/src/meshlet/meshlet_mesh_manager.rs @@ -59,9 +59,7 @@ impl MeshletMeshManager { assets: &mut Assets, ) -> Range { let queue_meshlet_mesh = |asset_id: &AssetId| { - let meshlet_mesh = assets.remove_untracked(*asset_id).expect( - "MeshletMesh asset was already unloaded but is not registered with MeshletMeshManager", - ); + let meshlet_mesh = assets.remove_untracked(*asset_id).expect("MeshletMesh asset was already unloaded but is not registered with MeshletMeshManager"); let vertex_positions_slice = self .vertex_positions diff --git a/crates/bevy_pbr/src/render/gpu_preprocess.rs b/crates/bevy_pbr/src/render/gpu_preprocess.rs index 3db9508c17b65..f336c7ea4d0f2 100644 --- a/crates/bevy_pbr/src/render/gpu_preprocess.rs +++ b/crates/bevy_pbr/src/render/gpu_preprocess.rs @@ -136,24 +136,7 @@ impl Plugin for GpuMeshPreprocessPlugin { } // Stitch the node in. - render_app - .add_render_graph_node::(Core3d, NodePbr::GpuPreprocess) - .add_render_graph_edges(Core3d, (NodePbr::GpuPreprocess, Node3d::Prepass)) - .add_render_graph_edges(Core3d, (NodePbr::GpuPreprocess, NodePbr::ShadowPass)) - .init_resource::() - .init_resource::>() - .add_systems( - Render, - ( - prepare_preprocess_pipelines.in_set(RenderSet::Prepare), - prepare_preprocess_bind_groups - .run_if( - resource_exists::>, - ) - .in_set(RenderSet::PrepareBindGroups), - write_mesh_culling_data_buffer.in_set(RenderSet::PrepareResourcesFlush), - ) - ); + render_app.add_render_graph_node::(Core3d, NodePbr::GpuPreprocess).add_render_graph_edges(Core3d, (NodePbr::GpuPreprocess, Node3d::Prepass)).add_render_graph_edges(Core3d, (NodePbr::GpuPreprocess, NodePbr::ShadowPass)).init_resource::().init_resource::>().add_systems(Render, (prepare_preprocess_pipelines.in_set(RenderSet::Prepare), prepare_preprocess_bind_groups.run_if(resource_exists::>).in_set(RenderSet::PrepareBindGroups), write_mesh_culling_data_buffer.in_set(RenderSet::PrepareResourcesFlush))); } } diff --git a/crates/bevy_pbr/src/render/light.rs b/crates/bevy_pbr/src/render/light.rs index bd0248789d5b3..07aa81eef0e36 100644 --- a/crates/bevy_pbr/src/render/light.rs +++ b/crates/bevy_pbr/src/render/light.rs @@ -743,10 +743,7 @@ pub fn prepare_lights( .iter() .any(|(_, light)| light.cascade_shadow_config.bounds.len() > MAX_CASCADES_PER_LIGHT) { - warn!( - "The number of cascades configured for a directional light exceeds the supported limit of {}.", - MAX_CASCADES_PER_LIGHT - ); + warn!("The number of cascades configured for a directional light exceeds the supported limit of {}.", MAX_CASCADES_PER_LIGHT); *max_cascades_per_light_warning_emitted = true; } @@ -1173,8 +1170,13 @@ pub fn prepare_lights( let spot_world_from_view = spot_light_world_from_view(&light.transform); let spot_world_from_view = spot_world_from_view.into(); - let angle = light.spot_light_angles.expect("lights should be sorted so that \ - [point_light_count..point_light_count + spot_light_shadow_maps_count] are spot lights").1; + let angle = light + .spot_light_angles + .expect( + "lights should be sorted so that \ + [point_light_count..point_light_count + spot_light_shadow_maps_count] are spot lights", + ) + .1; let spot_projection = spot_light_clip_from_view(angle, light.shadow_map_near_z); let depth_texture_view = diff --git a/crates/bevy_pbr/src/render/mesh.rs b/crates/bevy_pbr/src/render/mesh.rs index e996dbb8f0436..b20042ab374e4 100644 --- a/crates/bevy_pbr/src/render/mesh.rs +++ b/crates/bevy_pbr/src/render/mesh.rs @@ -194,30 +194,20 @@ impl Plugin for MeshRenderPlugin { render_app.insert_resource(render_mesh_instances); if use_gpu_instance_buffer_builder { - render_app - .init_resource::>() - .init_resource::() - .add_systems( - ExtractSchedule, - extract_meshes_for_gpu_building.in_set(ExtractMeshesSet), - ) - .add_systems( - Render, - ( - gpu_preprocessing::write_batched_instance_buffers:: - .in_set(RenderSet::PrepareResourcesFlush), - gpu_preprocessing::delete_old_work_item_buffers:: - .in_set(RenderSet::ManageViews) - .after(prepare_view_targets), - collect_meshes_for_gpu_building - .in_set(RenderSet::PrepareAssets) - .after(allocator::allocate_and_free_meshes) - // This must be before - // `set_mesh_motion_vector_flags` so it doesn't - // overwrite those flags. - .before(set_mesh_motion_vector_flags), - ), - ); + render_app.init_resource::>().init_resource::().add_systems(ExtractSchedule, extract_meshes_for_gpu_building.in_set(ExtractMeshesSet)).add_systems( + Render, + ( + gpu_preprocessing::write_batched_instance_buffers::.in_set(RenderSet::PrepareResourcesFlush), + gpu_preprocessing::delete_old_work_item_buffers::.in_set(RenderSet::ManageViews).after(prepare_view_targets), + collect_meshes_for_gpu_building + .in_set(RenderSet::PrepareAssets) + .after(allocator::allocate_and_free_meshes) + // This must be before + // `set_mesh_motion_vector_flags` so it doesn't + // overwrite those flags. + .before(set_mesh_motion_vector_flags), + ), + ); } else { let render_device = render_app.world().resource::(); let cpu_batched_instance_buffer = diff --git a/crates/bevy_pbr/src/ssao/mod.rs b/crates/bevy_pbr/src/ssao/mod.rs index 42ac9978f6192..27a939955df86 100644 --- a/crates/bevy_pbr/src/ssao/mod.rs +++ b/crates/bevy_pbr/src/ssao/mod.rs @@ -466,12 +466,10 @@ impl FromWorld for SsaoPipelines { Self { preprocess_depth_pipeline, spatial_denoise_pipeline, - common_bind_group_layout, preprocess_depth_bind_group_layout, ssao_bind_group_layout, spatial_denoise_bind_group_layout, - hilbert_index_lut, point_clamp_sampler, linear_clamp_sampler, @@ -528,10 +526,7 @@ fn extract_ssao_settings( ) { for (entity, camera, ssao_settings, msaa) in &cameras { if *msaa != Msaa::Off { - error!( - "SSAO is being used which requires Msaa::Off, but Msaa is currently set to Msaa::{:?}", - *msaa - ); + error!("SSAO is being used which requires Msaa::Off, but Msaa is currently set to Msaa::{:?}", *msaa); return; } let mut entity_commands = commands diff --git a/crates/bevy_reflect/derive/src/container_attributes.rs b/crates/bevy_reflect/derive/src/container_attributes.rs index b134c571c0501..17ead52731f50 100644 --- a/crates/bevy_reflect/derive/src/container_attributes.rs +++ b/crates/bevy_reflect/derive/src/container_attributes.rs @@ -263,9 +263,7 @@ impl ContainerAttributes { let ident = input.parse::()?; if input.peek(token::Paren) { - return Err(syn::Error::new(ident.span(), format!( - "only [{DEBUG_ATTR:?}, {PARTIAL_EQ_ATTR:?}, {HASH_ATTR:?}] may specify custom functions", - ))); + return Err(syn::Error::new(ident.span(), format!("only [{DEBUG_ATTR:?}, {PARTIAL_EQ_ATTR:?}, {HASH_ATTR:?}] may specify custom functions",))); } let ident_name = ident.to_string(); diff --git a/crates/bevy_reflect/derive/src/derive_data.rs b/crates/bevy_reflect/derive/src/derive_data.rs index 3d7363dec103f..772e6d7465aa5 100644 --- a/crates/bevy_reflect/derive/src/derive_data.rs +++ b/crates/bevy_reflect/derive/src/derive_data.rs @@ -200,10 +200,7 @@ impl<'a> ReflectDerive<'a> { .. }) = &pair.value else { - return Err(syn::Error::new( - pair.span(), - format_args!("`#[{TYPE_PATH_ATTRIBUTE_NAME} = \"...\"]` must be a string literal"), - )); + return Err(syn::Error::new(pair.span(), format_args!("`#[{TYPE_PATH_ATTRIBUTE_NAME} = \"...\"]` must be a string literal"))); }; custom_path = Some(syn::parse::Parser::parse_str( @@ -217,10 +214,7 @@ impl<'a> ReflectDerive<'a> { .. }) = &pair.value else { - return Err(syn::Error::new( - pair.span(), - format_args!("`#[{TYPE_NAME_ATTRIBUTE_NAME} = \"...\"]` must be a string literal"), - )); + return Err(syn::Error::new(pair.span(), format_args!("`#[{TYPE_NAME_ATTRIBUTE_NAME} = \"...\"]` must be a string literal"))); }; custom_type_name = Some(parse_str(&lit.value())?); @@ -244,10 +238,7 @@ impl<'a> ReflectDerive<'a> { path.segments.push(PathSegment::from(ident)); } (None, Some(name)) => { - return Err(syn::Error::new( - name.span(), - format!("cannot use `#[{TYPE_NAME_ATTRIBUTE_NAME} = \"...\"]` without a `#[{TYPE_PATH_ATTRIBUTE_NAME} = \"...\"]` attribute."), - )); + return Err(syn::Error::new(name.span(), format!("cannot use `#[{TYPE_NAME_ATTRIBUTE_NAME} = \"...\"]` without a `#[{TYPE_PATH_ATTRIBUTE_NAME} = \"...\"]` attribute."))); } _ => (), } @@ -264,10 +255,7 @@ impl<'a> ReflectDerive<'a> { && meta.type_path_attrs().should_auto_derive() && !meta.type_path().has_custom_path() { - return Err(syn::Error::new( - meta.type_path().span(), - format!("a #[{TYPE_PATH_ATTRIBUTE_NAME} = \"...\"] attribute must be specified when using {provenance}") - )); + return Err(syn::Error::new(meta.type_path().span(), format!("a #[{TYPE_PATH_ATTRIBUTE_NAME} = \"...\"] attribute must be specified when using {provenance}"))); } #[cfg(feature = "documentation")] diff --git a/crates/bevy_reflect/derive/src/impls/common.rs b/crates/bevy_reflect/derive/src/impls/common.rs index 12f324c330dd0..8095be9219a7f 100644 --- a/crates/bevy_reflect/derive/src/impls/common.rs +++ b/crates/bevy_reflect/derive/src/impls/common.rs @@ -89,19 +89,16 @@ pub fn common_partial_reflect_methods( let bevy_reflect_path = meta.bevy_reflect_path(); let debug_fn = meta.attrs().get_debug_impl(); - let partial_eq_fn = meta - .attrs() - .get_partial_eq_impl(bevy_reflect_path) - .or_else(move || { - let default_delegate = default_partial_eq_delegate(); - default_delegate.map(|func| { - quote! { - fn reflect_partial_eq(&self, value: &dyn #bevy_reflect_path::PartialReflect) -> #FQOption { - (#func)(self, value) - } + let partial_eq_fn = meta.attrs().get_partial_eq_impl(bevy_reflect_path).or_else(move || { + let default_delegate = default_partial_eq_delegate(); + default_delegate.map(|func| { + quote! { + fn reflect_partial_eq(&self, value: &dyn #bevy_reflect_path::PartialReflect) -> #FQOption { + (#func)(self, value) } - }) - }); + } + }) + }); let hash_fn = meta .attrs() .get_hash_impl(bevy_reflect_path) diff --git a/crates/bevy_reflect/derive/src/impls/typed.rs b/crates/bevy_reflect/derive/src/impls/typed.rs index b158973a7b613..07ad67301f375 100644 --- a/crates/bevy_reflect/derive/src/impls/typed.rs +++ b/crates/bevy_reflect/derive/src/impls/typed.rs @@ -28,9 +28,7 @@ fn static_type_cell( } } else { let cell_type = match property { - TypedProperty::TypePath => unreachable!( - "Cannot have a non-generic type path cell. Use string literals and core::concat instead." - ), + TypedProperty::TypePath => unreachable!("Cannot have a non-generic type path cell. Use string literals and core::concat instead."), TypedProperty::TypeInfo => quote!(NonGenericTypeInfoCell), }; diff --git a/crates/bevy_reflect/derive/src/remote.rs b/crates/bevy_reflect/derive/src/remote.rs index 13cbe681ed4c7..887c2a4175e7e 100644 --- a/crates/bevy_reflect/derive/src/remote.rs +++ b/crates/bevy_reflect/derive/src/remote.rs @@ -300,9 +300,7 @@ pub(crate) fn generate_remote_assertions( }; let (impl_generics, _, where_clause) = field.generics.split_for_impl(); - let where_reflect_clause = derive_data - .where_clause_options() - .extend_where_clause(where_clause); + let where_reflect_clause = derive_data.where_clause_options().extend_where_clause(where_clause); let ty = &field.ty; let remote_ty = field.remote_ty; diff --git a/crates/bevy_reflect/derive/src/trait_reflection.rs b/crates/bevy_reflect/derive/src/trait_reflection.rs index 6516c5ab7e8bc..3af0e39f80465 100644 --- a/crates/bevy_reflect/derive/src/trait_reflection.rs +++ b/crates/bevy_reflect/derive/src/trait_reflection.rs @@ -36,18 +36,10 @@ pub(crate) fn reflect_trait(_args: &TokenStream, input: TokenStream) -> TokenStr let reflect_trait_ident = crate::ident::get_reflect_ident(&item_trait.ident.to_string()); let bevy_reflect_path = BevyManifest::default().get_path("bevy_reflect"); - let struct_doc = format!( - " A type generated by the #[reflect_trait] macro for the `{trait_ident}` trait.\n\n This allows casting from `dyn Reflect` to `dyn {trait_ident}`.", - ); - let get_doc = format!( - " Downcast a `&dyn Reflect` type to `&dyn {trait_ident}`.\n\n If the type cannot be downcast, `None` is returned.", - ); - let get_mut_doc = format!( - " Downcast a `&mut dyn Reflect` type to `&mut dyn {trait_ident}`.\n\n If the type cannot be downcast, `None` is returned.", - ); - let get_box_doc = format!( - " Downcast a `Box` type to `Box`.\n\n If the type cannot be downcast, this will return `Err(Box)`.", - ); + let struct_doc = format!(" A type generated by the #[reflect_trait] macro for the `{trait_ident}` trait.\n\n This allows casting from `dyn Reflect` to `dyn {trait_ident}`.",); + let get_doc = format!(" Downcast a `&dyn Reflect` type to `&dyn {trait_ident}`.\n\n If the type cannot be downcast, `None` is returned.",); + let get_mut_doc = format!(" Downcast a `&mut dyn Reflect` type to `&mut dyn {trait_ident}`.\n\n If the type cannot be downcast, `None` is returned.",); + let get_box_doc = format!(" Downcast a `Box` type to `Box`.\n\n If the type cannot be downcast, this will return `Err(Box)`.",); TokenStream::from(quote! { #item_trait diff --git a/crates/bevy_reflect/src/enums/mod.rs b/crates/bevy_reflect/src/enums/mod.rs index 95a94e68e97e1..393ba1938487d 100644 --- a/crates/bevy_reflect/src/enums/mod.rs +++ b/crates/bevy_reflect/src/enums/mod.rs @@ -113,7 +113,7 @@ mod tests { assert_eq!( MyEnum::C { foo: 1.23, - bar: true, + bar: true }, value ); @@ -147,7 +147,7 @@ mod tests { assert_eq!( MyEnum::C { foo: 1.23, - bar: true, + bar: true }, value ); diff --git a/crates/bevy_reflect/src/enums/variants.rs b/crates/bevy_reflect/src/enums/variants.rs index 0830914794da1..7226d1b72ee2a 100644 --- a/crates/bevy_reflect/src/enums/variants.rs +++ b/crates/bevy_reflect/src/enums/variants.rs @@ -131,10 +131,7 @@ macro_rules! impl_cast_method { pub fn $name(&self) -> Result<&$info, VariantInfoError> { match self { Self::$kind(info) => Ok(info), - _ => Err(VariantInfoError::TypeMismatch { - expected: VariantType::$kind, - received: self.variant_type(), - }), + _ => Err(VariantInfoError::TypeMismatch { expected: VariantType::$kind, received: self.variant_type() }), } } }; diff --git a/crates/bevy_reflect/src/kind.rs b/crates/bevy_reflect/src/kind.rs index 2e3928162a73f..6b20804c22ae4 100644 --- a/crates/bevy_reflect/src/kind.rs +++ b/crates/bevy_reflect/src/kind.rs @@ -144,10 +144,7 @@ macro_rules! impl_cast_method { pub fn $name(self) -> Result<$retval, ReflectKindMismatchError> { match self { Self::Opaque(value) => Ok(value), - _ => Err(ReflectKindMismatchError { - expected: ReflectKind::Opaque, - received: self.kind(), - }), + _ => Err(ReflectKindMismatchError { expected: ReflectKind::Opaque, received: self.kind() }), } } }; @@ -157,10 +154,7 @@ macro_rules! impl_cast_method { pub fn $name(self) -> Result<$retval, ReflectKindMismatchError> { match self { Self::$kind(value) => Ok(value), - _ => Err(ReflectKindMismatchError { - expected: ReflectKind::$kind, - received: self.kind(), - }), + _ => Err(ReflectKindMismatchError { expected: ReflectKind::$kind, received: self.kind() }), } } }; diff --git a/crates/bevy_reflect/src/lib.rs b/crates/bevy_reflect/src/lib.rs index ab69019ee1128..43d58119a5ebf 100644 --- a/crates/bevy_reflect/src/lib.rs +++ b/crates/bevy_reflect/src/lib.rs @@ -1971,10 +1971,7 @@ mod tests { struct SomeStruct; let info = ::type_info(); - assert_eq!( - Some(" Some struct.\n\n # Example\n\n ```ignore (This is only used for a unit test, no need to doc test)\n let some_struct = SomeStruct;\n ```"), - info.docs() - ); + assert_eq!(Some(" Some struct.\n\n # Example\n\n ```ignore (This is only used for a unit test, no need to doc test)\n let some_struct = SomeStruct;\n ```"), info.docs()); #[doc = "The compiler automatically converts `///`-style comments into `#[doc]` attributes."] #[doc = "Of course, you _could_ use the attribute directly if you wanted to."] @@ -1983,10 +1980,7 @@ mod tests { struct SomeOtherStruct; let info = ::type_info(); - assert_eq!( - Some("The compiler automatically converts `///`-style comments into `#[doc]` attributes.\nOf course, you _could_ use the attribute directly if you wanted to.\nBoth will be reflected."), - info.docs() - ); + assert_eq!(Some("The compiler automatically converts `///`-style comments into `#[doc]` attributes.\nOf course, you _could_ use the attribute directly if you wanted to.\nBoth will be reflected."), info.docs()); /// Some tuple struct. #[derive(Reflect)] @@ -2902,7 +2896,7 @@ bevy_reflect::tests::Test { .expect("should downcast to `external_crate::TheirType`"); assert_eq!( external_crate::TheirType { - value: "Hello".to_string(), + value: "Hello".to_string() }, output ); @@ -2934,7 +2928,7 @@ bevy_reflect::tests::Test { .expect("should downcast to `external_crate::TheirType`"); assert_eq!( external_crate::TheirType { - value: "Hello".to_string(), + value: "Hello".to_string() }, output, ); @@ -2969,7 +2963,7 @@ bevy_reflect::tests::Test { .expect("should downcast to `external_crate::TheirOuter`"); assert_eq!( external_crate::TheirOuter { - inner: external_crate::TheirInner(123), + inner: external_crate::TheirInner(123) }, output ); diff --git a/crates/bevy_reflect/src/map.rs b/crates/bevy_reflect/src/map.rs index 03a4a325ef6f5..274b221710056 100644 --- a/crates/bevy_reflect/src/map.rs +++ b/crates/bevy_reflect/src/map.rs @@ -190,24 +190,17 @@ macro_rules! hash_error { ( $key:expr ) => {{ let type_path = (*$key).reflect_type_path(); if !$key.is_dynamic() { - format!( - "the given key of type `{}` does not support hashing", - type_path - ) + format!("the given key of type `{}` does not support hashing", type_path) } else { match (*$key).get_represented_type_info() { // Handle dynamic types that do not represent a type (i.e a plain `DynamicStruct`): None => format!("the dynamic type `{}` does not support hashing", type_path), // Handle dynamic types that do represent a type (i.e. a `DynamicStruct` proxying `Foo`): - Some(s) => format!( - "the dynamic type `{}` (representing `{}`) does not support hashing", - type_path, - s.type_path() - ), + Some(s) => format!("the dynamic type `{}` (representing `{}`) does not support hashing", type_path, s.type_path()), } } .as_str() - }} + }}; } /// An ordered mapping between reflected values. @@ -252,9 +245,7 @@ impl DynamicMap { values: &'a [(Box, Box)], ) -> impl FnMut(&usize) -> bool + 'a { |&index| { - value - .reflect_partial_eq(&*values[index].0) - .expect("underlying type does not reflect `PartialEq` and hence doesn't support equality checks") + value.reflect_partial_eq(&*values[index].0).expect("underlying type does not reflect `PartialEq` and hence doesn't support equality checks") } } } @@ -361,10 +352,7 @@ impl Map for DynamicMap { // whose index needs to be fixed up. if let Some((moved_key, _)) = self.values.get(index) { let hash = Self::internal_hash(&**moved_key); - let moved_index = self - .indices - .find_mut(hash, |&moved_index| moved_index == self.values.len()) - .expect("key inserted in a `DynamicMap` is no longer present, this means its reflected `Hash` might be incorrect"); + let moved_index = self.indices.find_mut(hash, |&moved_index| moved_index == self.values.len()).expect("key inserted in a `DynamicMap` is no longer present, this means its reflected `Hash` might be incorrect"); *moved_index = index; } diff --git a/crates/bevy_reflect/src/path/error.rs b/crates/bevy_reflect/src/path/error.rs index 0e900c8315ecb..a92933fe87fa2 100644 --- a/crates/bevy_reflect/src/path/error.rs +++ b/crates/bevy_reflect/src/path/error.rs @@ -89,40 +89,13 @@ impl fmt::Display for AccessError<'_> { write!(f, ": ")?; match kind { - AccessErrorKind::MissingField(type_accessed) => { - match access { - Access::Field(field) => write!( - f, - "The {type_accessed} accessed doesn't have {} `{}` field", - if let Some("a" | "e" | "i" | "o" | "u") = field.get(0..1) { - "an" - } else { - "a" - }, - access.display_value() - ), - Access::FieldIndex(_) => write!( - f, - "The {type_accessed} accessed doesn't have field index `{}`", - access.display_value(), - ), - Access::TupleIndex(_) | Access::ListIndex(_) => write!( - f, - "The {type_accessed} accessed doesn't have index `{}`", - access.display_value() - ) - } - } - AccessErrorKind::IncompatibleTypes { expected, actual } => write!( - f, - "Expected {} access to access a {expected}, found a {actual} instead.", - access.kind() - ), - AccessErrorKind::IncompatibleEnumVariantTypes { expected, actual } => write!( - f, - "Expected variant {} access to access a {expected:?} variant, found a {actual:?} variant instead.", - access.kind() - ), + AccessErrorKind::MissingField(type_accessed) => match access { + Access::Field(field) => write!(f, "The {type_accessed} accessed doesn't have {} `{}` field", if let Some("a" | "e" | "i" | "o" | "u") = field.get(0..1) { "an" } else { "a" }, access.display_value()), + Access::FieldIndex(_) => write!(f, "The {type_accessed} accessed doesn't have field index `{}`", access.display_value(),), + Access::TupleIndex(_) | Access::ListIndex(_) => write!(f, "The {type_accessed} accessed doesn't have index `{}`", access.display_value()), + }, + AccessErrorKind::IncompatibleTypes { expected, actual } => write!(f, "Expected {} access to access a {expected}, found a {actual} instead.", access.kind()), + AccessErrorKind::IncompatibleEnumVariantTypes { expected, actual } => write!(f, "Expected variant {} access to access a {expected:?} variant, found a {actual:?} variant instead.", access.kind()), } } } diff --git a/crates/bevy_reflect/src/path/mod.rs b/crates/bevy_reflect/src/path/mod.rs index 9fc7d1b9f2213..cc8d888ca8d60 100644 --- a/crates/bevy_reflect/src/path/mod.rs +++ b/crates/bevy_reflect/src/path/mod.rs @@ -758,7 +758,7 @@ mod tests { ReflectPathError::InvalidAccess(AccessError { kind: AccessErrorKind::MissingField(ReflectKind::Struct), access: access_field("notreal"), - offset: Some(2), + offset: Some(2) }) ); @@ -767,12 +767,12 @@ mod tests { ReflectPathError::InvalidAccess(AccessError { kind: AccessErrorKind::IncompatibleEnumVariantTypes { actual: VariantType::Unit, - expected: VariantType::Tuple, + expected: VariantType::Tuple }, access: ParsedPath::parse_static("unit_variant.0").unwrap()[1] .access .clone(), - offset: Some(13), + offset: Some(13) }) ); assert_eq!( diff --git a/crates/bevy_reflect/src/path/parse.rs b/crates/bevy_reflect/src/path/parse.rs index 40b39365ff054..230baf9b90929 100644 --- a/crates/bevy_reflect/src/path/parse.rs +++ b/crates/bevy_reflect/src/path/parse.rs @@ -187,7 +187,7 @@ mod test { Err(ReflectPathError::ParseError { error: ParseError(Error::ExpectedIdent(Token::Dot)), offset: 2, - path: "x..", + path: "x.." }), ); assert!(matches!( @@ -195,7 +195,7 @@ mod test { Err(ReflectPathError::ParseError { error: ParseError(Error::InvalidIndex(_)), offset: 2, - path: "y[badindex]", + path: "y[badindex]" }), )); } diff --git a/crates/bevy_reflect/src/serde/de/deserializer.rs b/crates/bevy_reflect/src/serde/de/deserializer.rs index a1a97e3877ef3..9780798679f81 100644 --- a/crates/bevy_reflect/src/serde/de/deserializer.rs +++ b/crates/bevy_reflect/src/serde/de/deserializer.rs @@ -384,9 +384,7 @@ impl<'a, 'de> DeserializeSeed<'de> for TypedReflectDeserializer<'a> { } TypeInfo::Opaque(_) => { // This case should already be handled - Err(make_custom_error(format_args!( - "type `{type_path}` did not register the `ReflectDeserialize` type data. For certain types, this may need to be registered manually using `register_type_data`", - ))) + Err(make_custom_error(format_args!("type `{type_path}` did not register the `ReflectDeserialize` type data. For certain types, this may need to be registered manually using `register_type_data`",))) } } }; diff --git a/crates/bevy_reflect/src/serde/de/mod.rs b/crates/bevy_reflect/src/serde/de/mod.rs index 92a43ed17565d..ac7df8a2e5ffe 100644 --- a/crates/bevy_reflect/src/serde/de/mod.rs +++ b/crates/bevy_reflect/src/serde/de/mod.rs @@ -547,13 +547,7 @@ mod tests { .unwrap_err(); #[cfg(feature = "debug_stack")] - assert_eq!( - error, - ron::Error::Message( - "no registration found for type `bevy_reflect::DynamicFunction` (stack: `bevy_reflect::serde::de::tests::functions::MyStruct`)" - .to_string() - ) - ); + assert_eq!(error, ron::Error::Message("no registration found for type `bevy_reflect::DynamicFunction` (stack: `bevy_reflect::serde::de::tests::functions::MyStruct`)".to_string())); #[cfg(not(feature = "debug_stack"))] assert_eq!( @@ -599,12 +593,7 @@ mod tests { let error = reflect_deserializer .deserialize(&mut deserializer) .unwrap_err(); - assert_eq!( - error, - ron::Error::Message( - "type `core::ops::RangeInclusive` did not register the `ReflectDeserialize` type data. For certain types, this may need to be registered manually using `register_type_data` (stack: `bevy_reflect::serde::de::tests::debug_stack::Foo` -> `bevy_reflect::serde::de::tests::debug_stack::Bar` -> `bevy_reflect::serde::de::tests::debug_stack::Baz` -> `alloc::vec::Vec>` -> `core::ops::RangeInclusive`)".to_string() - ) - ); + assert_eq!(error, ron::Error::Message("type `core::ops::RangeInclusive` did not register the `ReflectDeserialize` type data. For certain types, this may need to be registered manually using `register_type_data` (stack: `bevy_reflect::serde::de::tests::debug_stack::Foo` -> `bevy_reflect::serde::de::tests::debug_stack::Bar` -> `bevy_reflect::serde::de::tests::debug_stack::Baz` -> `alloc::vec::Vec>` -> `core::ops::RangeInclusive`)".to_string())); } } } diff --git a/crates/bevy_reflect/src/serde/ser/custom_serialization.rs b/crates/bevy_reflect/src/serde/ser/custom_serialization.rs index 18d2abed9c010..4663f3e09bcad 100644 --- a/crates/bevy_reflect/src/serde/ser/custom_serialization.rs +++ b/crates/bevy_reflect/src/serde/ser/custom_serialization.rs @@ -54,9 +54,6 @@ pub(super) fn try_custom_serialize( Ok(reflect_serialize_with_registry.serialize(value, serializer, type_registry)) } else { - Err((serializer, make_custom_error(format_args!( - "type `{}` did not register the `ReflectSerialize` or `ReflectSerializeWithRegistry` type data. For certain types, this may need to be registered manually using `register_type_data`", - info.type_path(), - )))) + Err((serializer, make_custom_error(format_args!("type `{}` did not register the `ReflectSerialize` or `ReflectSerializeWithRegistry` type data. For certain types, this may need to be registered manually using `register_type_data`", info.type_path(),)))) } } diff --git a/crates/bevy_reflect/src/serde/ser/mod.rs b/crates/bevy_reflect/src/serde/ser/mod.rs index ead36d4819898..708f6f2cac967 100644 --- a/crates/bevy_reflect/src/serde/ser/mod.rs +++ b/crates/bevy_reflect/src/serde/ser/mod.rs @@ -433,13 +433,7 @@ mod tests { let serializer = ReflectSerializer::new(&value, ®istry); let error = ron::ser::to_string(&serializer).unwrap_err(); #[cfg(feature = "debug_stack")] - assert_eq!( - error, - ron::Error::Message( - "type `core::ops::RangeInclusive` is not registered in the type registry (stack: `core::ops::RangeInclusive`)" - .to_string(), - ) - ); + assert_eq!(error, ron::Error::Message("type `core::ops::RangeInclusive` is not registered in the type registry (stack: `core::ops::RangeInclusive`)".to_string(),)); #[cfg(not(feature = "debug_stack"))] assert_eq!( error, @@ -459,19 +453,9 @@ mod tests { let serializer = ReflectSerializer::new(&value, ®istry); let error = ron::ser::to_string(&serializer).unwrap_err(); #[cfg(feature = "debug_stack")] - assert_eq!( - error, - ron::Error::Message( - "type `core::ops::RangeInclusive` did not register the `ReflectSerialize` or `ReflectSerializeWithRegistry` type data. For certain types, this may need to be registered manually using `register_type_data` (stack: `core::ops::RangeInclusive`)".to_string() - ) - ); + assert_eq!(error, ron::Error::Message("type `core::ops::RangeInclusive` did not register the `ReflectSerialize` or `ReflectSerializeWithRegistry` type data. For certain types, this may need to be registered manually using `register_type_data` (stack: `core::ops::RangeInclusive`)".to_string())); #[cfg(not(feature = "debug_stack"))] - assert_eq!( - error, - ron::Error::Message( - "type `core::ops::RangeInclusive` did not register the `ReflectSerialize` type data. For certain types, this may need to be registered manually using `register_type_data`".to_string() - ) - ); + assert_eq!(error, ron::Error::Message("type `core::ops::RangeInclusive` did not register the `ReflectSerialize` type data. For certain types, this may need to be registered manually using `register_type_data`".to_string())); } #[cfg(feature = "functions")] @@ -497,10 +481,7 @@ mod tests { let error = ron::ser::to_string(&serializer).unwrap_err(); #[cfg(feature = "debug_stack")] - assert_eq!( - error, - ron::Error::Message("functions cannot be serialized (stack: `bevy_reflect::serde::ser::tests::functions::MyStruct`)".to_string()) - ); + assert_eq!(error, ron::Error::Message("functions cannot be serialized (stack: `bevy_reflect::serde::ser::tests::functions::MyStruct`)".to_string())); #[cfg(not(feature = "debug_stack"))] assert_eq!( @@ -545,12 +526,7 @@ mod tests { let serializer = ReflectSerializer::new(&value, ®istry); let error = ron::ser::to_string(&serializer).unwrap_err(); - assert_eq!( - error, - ron::Error::Message( - "type `core::ops::RangeInclusive` is not registered in the type registry (stack: `bevy_reflect::serde::ser::tests::debug_stack::Foo` -> `bevy_reflect::serde::ser::tests::debug_stack::Bar` -> `bevy_reflect::serde::ser::tests::debug_stack::Baz` -> `alloc::vec::Vec>` -> `core::ops::RangeInclusive`)".to_string() - ) - ); + assert_eq!(error, ron::Error::Message("type `core::ops::RangeInclusive` is not registered in the type registry (stack: `bevy_reflect::serde::ser::tests::debug_stack::Foo` -> `bevy_reflect::serde::ser::tests::debug_stack::Bar` -> `bevy_reflect::serde::ser::tests::debug_stack::Baz` -> `alloc::vec::Vec>` -> `core::ops::RangeInclusive`)".to_string())); } } } diff --git a/crates/bevy_reflect/src/set.rs b/crates/bevy_reflect/src/set.rs index 50c5a752d920c..ad50ce0fb45ca 100644 --- a/crates/bevy_reflect/src/set.rs +++ b/crates/bevy_reflect/src/set.rs @@ -172,9 +172,7 @@ impl DynamicSet { value: &dyn PartialReflect, ) -> impl FnMut(&Box) -> bool + '_ { |other| { - value - .reflect_partial_eq(&**other) - .expect("Underlying type does not reflect `PartialEq` and hence doesn't support equality checks") + value.reflect_partial_eq(&**other).expect("Underlying type does not reflect `PartialEq` and hence doesn't support equality checks") } } } diff --git a/crates/bevy_reflect/src/type_info.rs b/crates/bevy_reflect/src/type_info.rs index 3493e1e06d744..06b08dc4a91b1 100644 --- a/crates/bevy_reflect/src/type_info.rs +++ b/crates/bevy_reflect/src/type_info.rs @@ -316,10 +316,7 @@ macro_rules! impl_cast_method { pub fn $name(&self) -> Result<&$info, TypeInfoError> { match self { Self::$kind(info) => Ok(info), - _ => Err(TypeInfoError::KindMismatch { - expected: ReflectKind::$kind, - received: self.kind(), - }), + _ => Err(TypeInfoError::KindMismatch { expected: ReflectKind::$kind, received: self.kind() }), } } }; diff --git a/crates/bevy_reflect/src/type_registry.rs b/crates/bevy_reflect/src/type_registry.rs index 1b0fd84c71e0c..6ec58dc9474da 100644 --- a/crates/bevy_reflect/src/type_registry.rs +++ b/crates/bevy_reflect/src/type_registry.rs @@ -262,13 +262,7 @@ impl TypeRegistry { /// type_registry.register_type_data::, ReflectDeserialize>(); /// ``` pub fn register_type_data>(&mut self) { - let data = self.get_mut(TypeId::of::()).unwrap_or_else(|| { - panic!( - "attempted to call `TypeRegistry::register_type_data` for type `{T}` with data `{D}` without registering `{T}` first", - T = T::type_path(), - D = core::any::type_name::(), - ) - }); + let data = self.get_mut(TypeId::of::()).unwrap_or_else(|| panic!("attempted to call `TypeRegistry::register_type_data` for type `{T}` with data `{D}` without registering `{T}` first", T = T::type_path(), D = core::any::type_name::(),)); data.insert(D::from_type()); } @@ -677,16 +671,9 @@ impl FromType for Reflec fn from_type() -> Self { ReflectSerialize { get_serializable: |value| { - value - .downcast_ref::() - .map(|value| Serializable::Borrowed(value)) - .or_else(|| T::from_reflect(value.as_partial_reflect()).map(|value| Serializable::Owned(Box::new(value)))) - .unwrap_or_else(|| { - panic!( - "FromReflect::from_reflect failed when called on type `{}` with this value: {value:?}", - T::type_path(), - ); - }) + value.downcast_ref::().map(|value| Serializable::Borrowed(value)).or_else(|| T::from_reflect(value.as_partial_reflect()).map(|value| Serializable::Owned(Box::new(value)))).unwrap_or_else(|| { + panic!("FromReflect::from_reflect failed when called on type `{}` with this value: {value:?}", T::type_path(),); + }) }, } } diff --git a/crates/bevy_render/macros/src/as_bind_group.rs b/crates/bevy_render/macros/src/as_bind_group.rs index d0edd18dd633c..8d88db6bcf055 100644 --- a/crates/bevy_render/macros/src/as_bind_group.rs +++ b/crates/bevy_render/macros/src/as_bind_group.rs @@ -77,7 +77,7 @@ pub fn derive_as_bind_group(ast: syn::DeriveInput) -> Result { ) }}); - binding_layouts.push(quote!{ + binding_layouts.push(quote! { #render_path::render_resource::BindGroupLayoutEntry { binding: #binding_index, visibility: #render_path::render_resource::ShaderStages::all(), @@ -174,26 +174,17 @@ pub fn derive_as_bind_group(ast: syn::DeriveInput) -> Result { binding_type, ident: occupied_ident, } => { - return Err(Error::new_spanned( - attr, - format!("The '{field_name}' field cannot be assigned to binding {binding_index} because it is already occupied by the field '{occupied_ident}' of type {binding_type:?}.") - )); + return Err(Error::new_spanned(attr, format!("The '{field_name}' field cannot be assigned to binding {binding_index} because it is already occupied by the field '{occupied_ident}' of type {binding_type:?}."))); } BindingState::OccupiedConvertedUniform => { - return Err(Error::new_spanned( - attr, - format!("The '{field_name}' field cannot be assigned to binding {binding_index} because it is already occupied by a struct-level uniform binding at the same index.") - )); + return Err(Error::new_spanned(attr, format!("The '{field_name}' field cannot be assigned to binding {binding_index} because it is already occupied by a struct-level uniform binding at the same index."))); } BindingState::OccupiedMergeableUniform { uniform_fields } => match binding_type { BindingType::Uniform => { uniform_fields.push(field); } _ => { - return Err(Error::new_spanned( - attr, - format!("The '{field_name}' field cannot be assigned to binding {binding_index} because it is already occupied by a {:?}.", BindingType::Uniform) - )); + return Err(Error::new_spanned(attr, format!("The '{field_name}' field cannot be assigned to binding {binding_index} because it is already occupied by a {:?}.", BindingType::Uniform))); } }, } @@ -261,18 +252,21 @@ pub fn derive_as_bind_group(ast: syn::DeriveInput) -> Result { let fallback_image = get_fallback_image(&render_path, dimension); // insert fallible texture-based entries at 0 so that if we fail here, we exit before allocating any buffers - binding_impls.insert(0, quote! { - ( #binding_index, - #render_path::render_resource::OwnedBindingResource::TextureView({ - let handle: Option<&#asset_path::Handle<#render_path::texture::Image>> = (&self.#field_name).into(); - if let Some(handle) = handle { - images.get(handle).ok_or_else(|| #render_path::render_resource::AsBindGroupError::RetryNextUpdate)?.texture_view.clone() - } else { - #fallback_image.texture_view.clone() - } - }) - ) - }); + binding_impls.insert( + 0, + quote! { + ( #binding_index, + #render_path::render_resource::OwnedBindingResource::TextureView({ + let handle: Option<&#asset_path::Handle<#render_path::texture::Image>> = (&self.#field_name).into(); + if let Some(handle) = handle { + images.get(handle).ok_or_else(|| #render_path::render_resource::AsBindGroupError::RetryNextUpdate)?.texture_view.clone() + } else { + #fallback_image.texture_view.clone() + } + }) + ) + }, + ); binding_layouts.push(quote! { #render_path::render_resource::BindGroupLayoutEntry { @@ -301,19 +295,22 @@ pub fn derive_as_bind_group(ast: syn::DeriveInput) -> Result { let fallback_image = get_fallback_image(&render_path, *dimension); // insert fallible texture-based entries at 0 so that if we fail here, we exit before allocating any buffers - binding_impls.insert(0, quote! { - ( - #binding_index, - #render_path::render_resource::OwnedBindingResource::TextureView({ - let handle: Option<&#asset_path::Handle<#render_path::texture::Image>> = (&self.#field_name).into(); - if let Some(handle) = handle { - images.get(handle).ok_or_else(|| #render_path::render_resource::AsBindGroupError::RetryNextUpdate)?.texture_view.clone() - } else { - #fallback_image.texture_view.clone() - } - }) - ) - }); + binding_impls.insert( + 0, + quote! { + ( + #binding_index, + #render_path::render_resource::OwnedBindingResource::TextureView({ + let handle: Option<&#asset_path::Handle<#render_path::texture::Image>> = (&self.#field_name).into(); + if let Some(handle) = handle { + images.get(handle).ok_or_else(|| #render_path::render_resource::AsBindGroupError::RetryNextUpdate)?.texture_view.clone() + } else { + #fallback_image.texture_view.clone() + } + }) + ) + }, + ); binding_layouts.push(quote! { #render_path::render_resource::BindGroupLayoutEntry { @@ -358,40 +355,43 @@ pub fn derive_as_bind_group(ast: syn::DeriveInput) -> Result { }; // insert fallible texture-based entries at 0 so that if we fail here, we exit before allocating any buffers - binding_impls.insert(0, quote! { - ( - #binding_index, - #render_path::render_resource::OwnedBindingResource::Sampler({ - let handle: Option<&#asset_path::Handle<#render_path::texture::Image>> = (&self.#field_name).into(); - if let Some(handle) = handle { - let image = images.get(handle).ok_or_else(|| #render_path::render_resource::AsBindGroupError::RetryNextUpdate)?; - - let Some(sample_type) = image.texture_format.sample_type(None, Some(render_device.features())) else { - return Err(#render_path::render_resource::AsBindGroupError::InvalidSamplerType( - #binding_index, - "None".to_string(), - format!("{:?}", #expected_samplers), - )); - }; - - let valid = #expected_samplers.contains(&sample_type); - - if !valid { - return Err(#render_path::render_resource::AsBindGroupError::InvalidSamplerType( - #binding_index, - format!("{:?}", sample_type), - format!("{:?}", #expected_samplers), - )); + binding_impls.insert( + 0, + quote! { + ( + #binding_index, + #render_path::render_resource::OwnedBindingResource::Sampler({ + let handle: Option<&#asset_path::Handle<#render_path::texture::Image>> = (&self.#field_name).into(); + if let Some(handle) = handle { + let image = images.get(handle).ok_or_else(|| #render_path::render_resource::AsBindGroupError::RetryNextUpdate)?; + + let Some(sample_type) = image.texture_format.sample_type(None, Some(render_device.features())) else { + return Err(#render_path::render_resource::AsBindGroupError::InvalidSamplerType( + #binding_index, + "None".to_string(), + format!("{:?}", #expected_samplers), + )); + }; + + let valid = #expected_samplers.contains(&sample_type); + + if !valid { + return Err(#render_path::render_resource::AsBindGroupError::InvalidSamplerType( + #binding_index, + format!("{:?}", sample_type), + format!("{:?}", #expected_samplers), + )); + } + image.sampler.clone() + } else { + #fallback_image.sampler.clone() } - image.sampler.clone() - } else { - #fallback_image.sampler.clone() - } - }) - ) - }); + }) + ) + }, + ); - binding_layouts.push(quote!{ + binding_layouts.push(quote! { #render_path::render_resource::BindGroupLayoutEntry { binding: #binding_index, visibility: #visibility, @@ -432,7 +432,7 @@ pub fn derive_as_bind_group(ast: syn::DeriveInput) -> Result { ) }}); - binding_layouts.push(quote!{ + binding_layouts.push(quote! { #render_path::render_resource::BindGroupLayoutEntry { binding: #binding_index, visibility: #render_path::render_resource::ShaderStages::all(), @@ -478,7 +478,7 @@ pub fn derive_as_bind_group(ast: syn::DeriveInput) -> Result { ) }}); - binding_layouts.push(quote!{ + binding_layouts.push(quote! { #render_path::render_resource::BindGroupLayoutEntry { binding: #binding_index, visibility: #render_path::render_resource::ShaderStages::all(), @@ -720,10 +720,7 @@ fn get_visibility_flag_value(meta_list: &MetaList) -> Result Result) -> Result { - return Err(Error::new_spanned( - m.path, - "Not a valid name. Available attributes: `dimension`, `image_format`, `access`.", - )); + return Err(Error::new_spanned(m.path, "Not a valid name. Available attributes: `dimension`, `image_format`, `access`.")); } _ => { return Err(Error::new_spanned( @@ -944,10 +935,7 @@ fn get_texture_attrs(metas: Vec) -> Result { visibility = get_visibility_flag_value(&m)?; } NameValue(m) => { - return Err(Error::new_spanned( - m.path, - "Not a valid name. Available attributes: `dimension`, `sample_type`, `multisampled`, or `filterable`." - )); + return Err(Error::new_spanned(m.path, "Not a valid name. Available attributes: `dimension`, `sample_type`, `multisampled`, or `filterable`.")); } _ => { return Err(Error::new_spanned( diff --git a/crates/bevy_render/src/batching/gpu_preprocessing.rs b/crates/bevy_render/src/batching/gpu_preprocessing.rs index d6b490f8c40b4..f6800af485b6e 100644 --- a/crates/bevy_render/src/batching/gpu_preprocessing.rs +++ b/crates/bevy_render/src/batching/gpu_preprocessing.rs @@ -249,15 +249,9 @@ impl FromWorld for GpuPreprocessingSupport { } } - if device.limits().max_compute_workgroup_size_x == 0 || is_non_supported_android_device(adapter) - { + if device.limits().max_compute_workgroup_size_x == 0 || is_non_supported_android_device(adapter) { GpuPreprocessingSupport::None - } else if !device - .features() - .contains(Features::INDIRECT_FIRST_INSTANCE) || - !adapter.get_downlevel_capabilities().flags.contains( - DownlevelFlags::VERTEX_AND_INSTANCE_INDEX_RESPECTS_RESPECTIVE_FIRST_VALUE_IN_INDIRECT_DRAW) - { + } else if !device.features().contains(Features::INDIRECT_FIRST_INSTANCE) || !adapter.get_downlevel_capabilities().flags.contains(DownlevelFlags::VERTEX_AND_INSTANCE_INDEX_RESPECTS_RESPECTIVE_FIRST_VALUE_IN_INDIRECT_DRAW) { GpuPreprocessingSupport::PreprocessingOnly } else { GpuPreprocessingSupport::Culling diff --git a/crates/bevy_render/src/camera/camera.rs b/crates/bevy_render/src/camera/camera.rs index f00ebb5e9d5f3..440df62074170 100644 --- a/crates/bevy_render/src/camera/camera.rs +++ b/crates/bevy_render/src/camera/camera.rs @@ -1247,9 +1247,7 @@ pub struct TemporalJitter { impl TemporalJitter { pub fn jitter_projection(&self, clip_from_view: &mut Mat4, view_size: Vec2) { if clip_from_view.w_axis.w == 1.0 { - warn!( - "TemporalJitter not supported with OrthographicProjection. Use PerspectiveProjection instead." - ); + warn!("TemporalJitter not supported with OrthographicProjection. Use PerspectiveProjection instead."); return; } diff --git a/crates/bevy_render/src/camera/projection.rs b/crates/bevy_render/src/camera/projection.rs index 7deb061fdcbfc..abb39104715f4 100644 --- a/crates/bevy_render/src/camera/projection.rs +++ b/crates/bevy_render/src/camera/projection.rs @@ -225,9 +225,7 @@ impl CameraProjection for PerspectiveProjection { } fn update(&mut self, width: f32, height: f32) { - self.aspect_ratio = AspectRatio::try_new(width, height) - .expect("Failed to update PerspectiveProjection: width and height must be positive, non-zero values") - .ratio(); + self.aspect_ratio = AspectRatio::try_new(width, height).expect("Failed to update PerspectiveProjection: width and height must be positive, non-zero values").ratio(); } fn far(&self) -> f32 { diff --git a/crates/bevy_render/src/lib.rs b/crates/bevy_render/src/lib.rs index a682f2b954413..3b0291dc82186 100644 --- a/crates/bevy_render/src/lib.rs +++ b/crates/bevy_render/src/lib.rs @@ -308,16 +308,10 @@ impl Plugin for RenderPlugin { // SAFETY: Plugins should be set up on the main thread. let surface = primary_window.and_then(|wrapper| unsafe { - let maybe_handle = wrapper.0.lock().expect( - "Couldn't get the window handle in time for renderer initialization", - ); + let maybe_handle = wrapper.0.lock().expect("Couldn't get the window handle in time for renderer initialization"); if let Some(wrapper) = maybe_handle.as_ref() { let handle = wrapper.get_handle(); - Some( - instance - .create_surface(handle) - .expect("Failed to create wgpu surface"), - ) + Some(instance.create_surface(handle).expect("Failed to create wgpu surface")) } else { None } diff --git a/crates/bevy_render/src/pipelined_rendering.rs b/crates/bevy_render/src/pipelined_rendering.rs index 41279e7d25db1..0d2563d2ed57e 100644 --- a/crates/bevy_render/src/pipelined_rendering.rs +++ b/crates/bevy_render/src/pipelined_rendering.rs @@ -131,9 +131,7 @@ impl Plugin for PipelinedRenderingPlugin { let (app_to_render_sender, app_to_render_receiver) = async_channel::bounded::(1); let (render_to_app_sender, render_to_app_receiver) = async_channel::bounded::(1); - let mut render_app = app - .remove_sub_app(RenderApp) - .expect("Unable to get RenderApp. Another plugin may have removed the RenderApp before PipelinedRenderingPlugin"); + let mut render_app = app.remove_sub_app(RenderApp).expect("Unable to get RenderApp. Another plugin may have removed the RenderApp before PipelinedRenderingPlugin"); // clone main thread executor to render world let executor = app.world().get_resource::().unwrap(); diff --git a/crates/bevy_render/src/render_graph/app.rs b/crates/bevy_render/src/render_graph/app.rs index 80ffcdb2a1f8d..74679902919ec 100644 --- a/crates/bevy_render/src/render_graph/app.rs +++ b/crates/bevy_render/src/render_graph/app.rs @@ -59,9 +59,7 @@ impl RenderGraphApp for SubApp { edges: impl IntoRenderNodeArray, ) -> &mut Self { let sub_graph = sub_graph.intern(); - let mut render_graph = self.world_mut().get_resource_mut::().expect( - "RenderGraph not found. Make sure you are using add_render_graph_edges on the RenderApp", - ); + let mut render_graph = self.world_mut().get_resource_mut::().expect("RenderGraph not found. Make sure you are using add_render_graph_edges on the RenderApp"); if let Some(graph) = render_graph.get_sub_graph_mut(sub_graph) { graph.add_node_edges(edges); } else { diff --git a/crates/bevy_render/src/render_graph/graph.rs b/crates/bevy_render/src/render_graph/graph.rs index 4b315e22a0869..53179e80a493e 100644 --- a/crates/bevy_render/src/render_graph/graph.rs +++ b/crates/bevy_render/src/render_graph/graph.rs @@ -841,7 +841,7 @@ mod tests { Err(RenderGraphError::NodeInputSlotAlreadyOccupied { node: TestLabel::C.intern(), input_slot: 0, - occupied_by_node: TestLabel::A.intern(), + occupied_by_node: TestLabel::A.intern() }), "Adding to a slot that is already occupied should return an error" ); @@ -861,7 +861,7 @@ mod tests { output_node: TestLabel::A.intern(), output_index: 0, input_node: TestLabel::B.intern(), - input_index: 0, + input_index: 0 })), "Adding to a duplicate edge should return an error" ); diff --git a/crates/bevy_render/src/render_resource/gpu_array_buffer.rs b/crates/bevy_render/src/render_resource/gpu_array_buffer.rs index c4c5906373029..7e00995adb655 100644 --- a/crates/bevy_render/src/render_resource/gpu_array_buffer.rs +++ b/crates/bevy_render/src/render_resource/gpu_array_buffer.rs @@ -78,8 +78,7 @@ impl GpuArrayBuffer { pub fn binding_layout(device: &RenderDevice) -> BindGroupLayoutEntryBuilder { if device.limits().max_storage_buffers_per_shader_stage == 0 { uniform_buffer_sized( - true, - // BatchedUniformBuffer uses a MaxCapacityArray that is runtime-sized, so we use + true, // BatchedUniformBuffer uses a MaxCapacityArray that is runtime-sized, so we use // None here and let wgpu figure out the size. None, ) diff --git a/crates/bevy_render/src/render_resource/pipeline_cache.rs b/crates/bevy_render/src/render_resource/pipeline_cache.rs index 1cb64d06bff32..4ce4bbb965890 100644 --- a/crates/bevy_render/src/render_resource/pipeline_cache.rs +++ b/crates/bevy_render/src/render_resource/pipeline_cache.rs @@ -685,17 +685,15 @@ impl PipelineCache { }; let fragment_module = match &descriptor.fragment { - Some(fragment) => { - match shader_cache.get( - &device, - id, - fragment.shader.id(), - &fragment.shader_defs, - ) { - Ok(module) => Some(module), - Err(err) => return Err(err), - } - } + Some(fragment) => match shader_cache.get( + &device, + id, + fragment.shader.id(), + &fragment.shader_defs, + ) { + Ok(module) => Some(module), + Err(err) => return Err(err), + }, None => None, }; diff --git a/crates/bevy_render/src/renderer/graph_runner.rs b/crates/bevy_render/src/renderer/graph_runner.rs index f2e90d33ea986..410aafb0b759d 100644 --- a/crates/bevy_render/src/renderer/graph_runner.rs +++ b/crates/bevy_render/src/renderer/graph_runner.rs @@ -51,9 +51,7 @@ pub enum RenderGraphRunnerError { expected: SlotType, actual: SlotType, }, - #[display( - "node (name: '{node_name:?}') has {slot_count} input slots, but was provided {value_count} values" - )] + #[display("node (name: '{node_name:?}') has {slot_count} input slots, but was provided {value_count} values")] MismatchedInputCount { node_name: InternedRenderLabel, slot_count: usize, diff --git a/crates/bevy_render/src/sync_world.rs b/crates/bevy_render/src/sync_world.rs index eefe7753ffd19..d1cf0c72060b5 100644 --- a/crates/bevy_render/src/sync_world.rs +++ b/crates/bevy_render/src/sync_world.rs @@ -225,7 +225,7 @@ pub(crate) fn entity_sync_system(main_world: &mut World, render_world: &mut Worl let id = render_world.spawn(MainEntity(main_entity)).id(); render_entity.0 = id; } - }, + } } } }); diff --git a/crates/bevy_scene/src/dynamic_scene.rs b/crates/bevy_scene/src/dynamic_scene.rs index 123ebf93aecb2..f0e4c5783df01 100644 --- a/crates/bevy_scene/src/dynamic_scene.rs +++ b/crates/bevy_scene/src/dynamic_scene.rs @@ -313,26 +313,8 @@ mod tests { .get(), "something about reloading the scene is touching entities with the same scene Ids" ); - assert_eq!( - original_child_entity, - world - .get_entity(from_scene_parent_entity) - .unwrap() - .get::() - .unwrap() - .get(), - "something about reloading the scene is touching components not defined in the scene but on entities defined in the scene" - ); - assert_eq!( - from_scene_parent_entity, - world - .get_entity(from_scene_child_entity) - .unwrap() - .get::() - .expect("something is wrong with this test, and the scene components don't have a parent/child relationship") - .get(), - "something is wrong with the this test or the code reloading scenes since the relationship between scene entities is broken" - ); + assert_eq!(original_child_entity, world.get_entity(from_scene_parent_entity).unwrap().get::().unwrap().get(), "something about reloading the scene is touching components not defined in the scene but on entities defined in the scene"); + assert_eq!(from_scene_parent_entity, world.get_entity(from_scene_child_entity).unwrap().get::().expect("something is wrong with this test, and the scene components don't have a parent/child relationship").get(), "something is wrong with the this test or the code reloading scenes since the relationship between scene entities is broken"); } // Regression test for https://github.com/bevyengine/bevy/issues/14300 diff --git a/crates/bevy_scene/src/serde.rs b/crates/bevy_scene/src/serde.rs index e1498ccc1c978..691570b8203cf 100644 --- a/crates/bevy_scene/src/serde.rs +++ b/crates/bevy_scene/src/serde.rs @@ -954,12 +954,7 @@ mod tests { ) }); - assert!( - expected - .reflect_partial_eq(received.as_ref()) - .unwrap_or_default(), - "components did not match: (expected: `{expected:?}`, received: `{received:?}`)", - ); + assert!(expected.reflect_partial_eq(received.as_ref()).unwrap_or_default(), "components did not match: (expected: `{expected:?}`, received: `{received:?}`)",); } } } diff --git a/crates/bevy_sprite/src/dynamic_texture_atlas_builder.rs b/crates/bevy_sprite/src/dynamic_texture_atlas_builder.rs index 879a9af3a497a..07aec26404453 100644 --- a/crates/bevy_sprite/src/dynamic_texture_atlas_builder.rs +++ b/crates/bevy_sprite/src/dynamic_texture_atlas_builder.rs @@ -51,11 +51,7 @@ impl DynamicTextureAtlasBuilder { (texture.height() + self.padding).try_into().unwrap(), )); if let Some(allocation) = allocation { - assert!( - ::asset_usage(atlas_texture) - .contains(RenderAssetUsages::MAIN_WORLD), - "The asset at atlas_texture_handle must have the RenderAssetUsages::MAIN_WORLD usage flag set" - ); + assert!(::asset_usage(atlas_texture).contains(RenderAssetUsages::MAIN_WORLD), "The asset at atlas_texture_handle must have the RenderAssetUsages::MAIN_WORLD usage flag set"); self.place_texture(atlas_texture, allocation, texture); let mut rect: URect = to_rect(allocation.rectangle); diff --git a/crates/bevy_sprite/src/texture_slice/slicer.rs b/crates/bevy_sprite/src/texture_slice/slicer.rs index ea32f1122b892..0eedc5e7668ca 100644 --- a/crates/bevy_sprite/src/texture_slice/slicer.rs +++ b/crates/bevy_sprite/src/texture_slice/slicer.rs @@ -318,7 +318,7 @@ mod test { max: Vec2::splat(10.0) }, draw_size: Vec2::new(10.0, 10.0), - offset: Vec2::new(-45.0, 45.0), + offset: Vec2::new(-45.0, 45.0) } ); } @@ -350,7 +350,7 @@ mod test { max: Vec2::new(20.0, 10.0) }, draw_size: Vec2::new(20.0, 10.0), - offset: Vec2::new(-40.0, 45.0), + offset: Vec2::new(-40.0, 45.0) } ); } @@ -384,7 +384,7 @@ mod test { max: Vec2::new(5.0, 10.0) }, draw_size: Vec2::new(5.0, 10.0), - offset: Vec2::new(-47.5, 45.0), + offset: Vec2::new(-47.5, 45.0) } ); assert_eq!( @@ -395,7 +395,7 @@ mod test { max: Vec2::new(40.0, 10.0) }, draw_size: Vec2::new(85.0, 10.0), - offset: Vec2::new(-2.5, 45.0), + offset: Vec2::new(-2.5, 45.0) } ); } @@ -427,7 +427,7 @@ mod test { max: Vec2::new(0.0, 10.0) }, draw_size: Vec2::new(0.0, 10.0), - offset: Vec2::new(-50.0, 45.0), + offset: Vec2::new(-50.0, 45.0) } ); } diff --git a/crates/bevy_state/src/app.rs b/crates/bevy_state/src/app.rs index 666b35ce846a6..2d37efa776211 100644 --- a/crates/bevy_state/src/app.rs +++ b/crates/bevy_state/src/app.rs @@ -95,9 +95,7 @@ impl AppExtStates for SubApp { self.init_resource::>() .init_resource::>() .add_event::>(); - let schedule = self.get_schedule_mut(StateTransition).expect( - "The `StateTransition` schedule is missing. Did you forget to add StatesPlugin or DefaultPlugins before calling init_state?" - ); + let schedule = self.get_schedule_mut(StateTransition).expect("The `StateTransition` schedule is missing. Did you forget to add StatesPlugin or DefaultPlugins before calling init_state?"); S::register_state(schedule); let state = self.world().resource::>().get().clone(); self.world_mut().send_event(StateTransitionEvent { @@ -118,9 +116,7 @@ impl AppExtStates for SubApp { self.insert_resource::>(State::new(state.clone())) .init_resource::>() .add_event::>(); - let schedule = self.get_schedule_mut(StateTransition).expect( - "The `StateTransition` schedule is missing. Did you forget to add StatesPlugin or DefaultPlugins before calling insert_state?" - ); + let schedule = self.get_schedule_mut(StateTransition).expect("The `StateTransition` schedule is missing. Did you forget to add StatesPlugin or DefaultPlugins before calling insert_state?"); S::register_state(schedule); self.world_mut().send_event(StateTransitionEvent { exited: None, @@ -148,9 +144,7 @@ impl AppExtStates for SubApp { .contains_resource::>>() { self.add_event::>(); - let schedule = self.get_schedule_mut(StateTransition).expect( - "The `StateTransition` schedule is missing. Did you forget to add StatesPlugin or DefaultPlugins before calling add_computed_state?" - ); + let schedule = self.get_schedule_mut(StateTransition).expect("The `StateTransition` schedule is missing. Did you forget to add StatesPlugin or DefaultPlugins before calling add_computed_state?"); S::register_computed_state_systems(schedule); let state = self .world() @@ -176,9 +170,7 @@ impl AppExtStates for SubApp { { self.init_resource::>(); self.add_event::>(); - let schedule = self.get_schedule_mut(StateTransition).expect( - "The `StateTransition` schedule is missing. Did you forget to add StatesPlugin or DefaultPlugins before calling add_sub_state?" - ); + let schedule = self.get_schedule_mut(StateTransition).expect("The `StateTransition` schedule is missing. Did you forget to add StatesPlugin or DefaultPlugins before calling add_sub_state?"); S::register_sub_state_systems(schedule); let state = self .world() diff --git a/crates/bevy_text/src/text.rs b/crates/bevy_text/src/text.rs index 8543daea3d145..a72c96f4db9a3 100644 --- a/crates/bevy_text/src/text.rs +++ b/crates/bevy_text/src/text.rs @@ -417,8 +417,12 @@ pub fn detect_text_needs_rerender( // - Root children changed (can include additions and removals). for root in changed_roots.iter() { let Ok((_, Some(mut computed), _)) = computed.get_mut(root) else { - warn_once!("found entity {:?} with a root text component ({}) but no ComputedTextBlock; this warning only \ - prints once", root, core::any::type_name::()); + warn_once!( + "found entity {:?} with a root text component ({}) but no ComputedTextBlock; this warning only \ + prints once", + root, + core::any::type_name::() + ); continue; }; computed.needs_rerender = true; @@ -430,9 +434,12 @@ pub fn detect_text_needs_rerender( // - Span children changed (can include additions and removals). for (entity, maybe_span_parent, has_text_block) in changed_spans.iter() { if has_text_block { - warn_once!("found entity {:?} with a TextSpan that has a TextLayout, which should only be on root \ + warn_once!( + "found entity {:?} with a TextSpan that has a TextLayout, which should only be on root \ text entities (that have {}); this warning only prints once", - entity, core::any::type_name::()); + entity, + core::any::type_name::() + ); } let Some(span_parent) = maybe_span_parent else { @@ -451,9 +458,12 @@ pub fn detect_text_needs_rerender( // is outweighed by the expense of tracking visited spans. loop { let Ok((maybe_parent, maybe_computed, has_span)) = computed.get_mut(parent) else { - warn_once!("found entity {:?} with a TextSpan that is part of a broken hierarchy with a Parent \ + warn_once!( + "found entity {:?} with a TextSpan that is part of a broken hierarchy with a Parent \ component that points at non-existent entity {:?}; this warning only prints once", - entity, parent); + entity, + parent + ); break; }; if let Some(mut computed) = maybe_computed { @@ -461,9 +471,12 @@ pub fn detect_text_needs_rerender( break; } if !has_span { - warn_once!("found entity {:?} with a TextSpan that has an ancestor ({}) that does not have a text \ + warn_once!( + "found entity {:?} with a TextSpan that has an ancestor ({}) that does not have a text \ span component or a ComputedTextBlock component; this warning only prints once", - entity, parent); + entity, + parent + ); break; } let Some(next_parent) = maybe_parent else { diff --git a/crates/bevy_transform/src/systems.rs b/crates/bevy_transform/src/systems.rs index 4935d05f8ffed..0781bb8c03716 100644 --- a/crates/bevy_transform/src/systems.rs +++ b/crates/bevy_transform/src/systems.rs @@ -59,39 +59,28 @@ pub fn propagate_transforms( orphaned_entities.clear(); orphaned_entities.extend(orphaned.read()); orphaned_entities.sort_unstable(); - root_query.par_iter_mut().for_each( - |(entity, children, transform, mut global_transform)| { - let changed = transform.is_changed() || global_transform.is_added() || orphaned_entities.binary_search(&entity).is_ok(); - if changed { - *global_transform = GlobalTransform::from(*transform); - } + root_query.par_iter_mut().for_each(|(entity, children, transform, mut global_transform)| { + let changed = transform.is_changed() || global_transform.is_added() || orphaned_entities.binary_search(&entity).is_ok(); + if changed { + *global_transform = GlobalTransform::from(*transform); + } - for (child, actual_parent) in parent_query.iter_many(children) { - assert_eq!( - actual_parent.get(), entity, - "Malformed hierarchy. This probably means that your hierarchy has been improperly maintained, or contains a cycle" - ); - // SAFETY: - // - `child` must have consistent parentage, or the above assertion would panic. - // Since `child` is parented to a root entity, the entire hierarchy leading to it is consistent. - // - We may operate as if all descendants are consistent, since `propagate_recursive` will panic before - // continuing to propagate if it encounters an entity with inconsistent parentage. - // - Since each root entity is unique and the hierarchy is consistent and forest-like, - // other root entities' `propagate_recursive` calls will not conflict with this one. - // - Since this is the only place where `transform_query` gets used, there will be no conflicting fetches elsewhere. - #[expect(unsafe_code, reason = "`propagate_recursive()` is unsafe due to its use of `Query::get_unchecked()`.")] - unsafe { - propagate_recursive( - &global_transform, - &transform_query, - &parent_query, - child, - changed || actual_parent.is_changed(), - ); - } + for (child, actual_parent) in parent_query.iter_many(children) { + assert_eq!(actual_parent.get(), entity, "Malformed hierarchy. This probably means that your hierarchy has been improperly maintained, or contains a cycle"); + // SAFETY: + // - `child` must have consistent parentage, or the above assertion would panic. + // Since `child` is parented to a root entity, the entire hierarchy leading to it is consistent. + // - We may operate as if all descendants are consistent, since `propagate_recursive` will panic before + // continuing to propagate if it encounters an entity with inconsistent parentage. + // - Since each root entity is unique and the hierarchy is consistent and forest-like, + // other root entities' `propagate_recursive` calls will not conflict with this one. + // - Since this is the only place where `transform_query` gets used, there will be no conflicting fetches elsewhere. + #[expect(unsafe_code, reason = "`propagate_recursive()` is unsafe due to its use of `Query::get_unchecked()`.")] + unsafe { + propagate_recursive(&global_transform, &transform_query, &parent_query, child, changed || actual_parent.is_changed()); } - }, - ); + } + }); } /// Recursively propagates the transforms for `entity` and all of its descendants. @@ -162,10 +151,7 @@ unsafe fn propagate_recursive( let Some(children) = children else { return }; for (child, actual_parent) in parent_query.iter_many(children) { - assert_eq!( - actual_parent.get(), entity, - "Malformed hierarchy. This probably means that your hierarchy has been improperly maintained, or contains a cycle" - ); + assert_eq!(actual_parent.get(), entity, "Malformed hierarchy. This probably means that your hierarchy has been improperly maintained, or contains a cycle"); // SAFETY: The caller guarantees that `transform_query` will not be fetched // for any descendants of `entity`, so it is safe to call `propagate_recursive` for each child. // diff --git a/crates/bevy_ui/src/layout/debug.rs b/crates/bevy_ui/src/layout/debug.rs index 359658f59dbe9..9ac8a28747260 100644 --- a/crates/bevy_ui/src/layout/debug.rs +++ b/crates/bevy_ui/src/layout/debug.rs @@ -60,18 +60,7 @@ fn print_node( } else { "└── " }; - writeln!( - acc, - "{lines}{fork} {display} [x: {x:<4} y: {y:<4} width: {width:<4} height: {height:<4}] ({entity:?}) {measured}", - lines = lines_string, - fork = fork_string, - display = display_variant, - x = layout.location.x, - y = layout.location.y, - width = layout.size.width, - height = layout.size.height, - measured = if tree.get_node_context(node).is_some() { "measured" } else { "" } - ).ok(); + writeln!(acc, "{lines}{fork} {display} [x: {x:<4} y: {y:<4} width: {width:<4} height: {height:<4}] ({entity:?}) {measured}", lines = lines_string, fork = fork_string, display = display_variant, x = layout.location.x, y = layout.location.y, width = layout.size.width, height = layout.size.height, measured = if tree.get_node_context(node).is_some() { "measured" } else { "" }).ok(); let bar = if has_sibling { "│ " } else { " " }; let new_string = lines_string + bar; diff --git a/crates/bevy_ui/src/layout/mod.rs b/crates/bevy_ui/src/layout/mod.rs index 4af52cd4432c6..dc44e045afd5f 100644 --- a/crates/bevy_ui/src/layout/mod.rs +++ b/crates/bevy_ui/src/layout/mod.rs @@ -170,38 +170,27 @@ pub fn ui_layout_system( // Precalculate the layout info for each camera, so we have fast access to it for each node camera_layout_info.clear(); - node_query - .iter_many(root_nodes.iter()) - .for_each(|(entity, _, _, target_camera)| { - match camera_with_default(target_camera) { - Some(camera_entity) => { - let Ok((_, camera)) = cameras.get(camera_entity) else { - warn!( - "TargetCamera (of root UI node {entity:?}) is pointing to a camera {:?} which doesn't exist", - camera_entity - ); - return; - }; - let layout_info = camera_layout_info - .entry(camera_entity) - .or_insert_with(|| calculate_camera_layout_info(camera)); - layout_info.root_nodes.push(entity); - } - None => { - if cameras.is_empty() { - warn!("No camera found to render UI to. To fix this, add at least one camera to the scene."); - } else { - warn!( - "Multiple cameras found, causing UI target ambiguity. \ + node_query.iter_many(root_nodes.iter()).for_each(|(entity, _, _, target_camera)| match camera_with_default(target_camera) { + Some(camera_entity) => { + let Ok((_, camera)) = cameras.get(camera_entity) else { + warn!("TargetCamera (of root UI node {entity:?}) is pointing to a camera {:?} which doesn't exist", camera_entity); + return; + }; + let layout_info = camera_layout_info.entry(camera_entity).or_insert_with(|| calculate_camera_layout_info(camera)); + layout_info.root_nodes.push(entity); + } + None => { + if cameras.is_empty() { + warn!("No camera found to render UI to. To fix this, add at least one camera to the scene."); + } else { + warn!( + "Multiple cameras found, causing UI target ambiguity. \ To fix this, add an explicit `TargetCamera` component to the root UI node {:?}", - entity - ); - } - } + entity + ); } - } - ); + }); // When a `ContentSize` component is removed from an entity, we need to remove the measure from the corresponding taffy node. for entity in removed_components.removed_content_sizes.read() { diff --git a/crates/bevy_ui/src/ui_node.rs b/crates/bevy_ui/src/ui_node.rs index 88b950b7b479b..9e97c89bff03a 100644 --- a/crates/bevy_ui/src/ui_node.rs +++ b/crates/bevy_ui/src/ui_node.rs @@ -2630,9 +2630,7 @@ impl<'w, 's> DefaultUiCamera<'w, 's> { .iter() .filter(|(_, c)| match c.target { RenderTarget::Window(WindowRef::Primary) => true, - RenderTarget::Window(WindowRef::Entity(w)) => { - self.primary_window.get(w).is_ok() - } + RenderTarget::Window(WindowRef::Entity(w)) => self.primary_window.get(w).is_ok(), _ => false, }) .max_by_key(|(e, c)| (c.order, *e)) diff --git a/crates/bevy_ui/src/widget/image.rs b/crates/bevy_ui/src/widget/image.rs index 60a0ac5292738..b467d08ceea80 100644 --- a/crates/bevy_ui/src/widget/image.rs +++ b/crates/bevy_ui/src/widget/image.rs @@ -95,7 +95,6 @@ pub fn update_image_content_size_system( windows: Query<&Window, With>, ui_scale: Res, textures: Res>, - atlases: Res>, mut query: Query<(&mut ContentSize, &UiImage, &mut UiImageSize), UpdateImageFilter>, ) { diff --git a/crates/bevy_winit/src/cursor.rs b/crates/bevy_winit/src/cursor.rs index 524a6ceb3c493..0e634b92a1ff0 100644 --- a/crates/bevy_winit/src/cursor.rs +++ b/crates/bevy_winit/src/cursor.rs @@ -107,9 +107,7 @@ fn update_cursors( CursorSource::CustomCached(cache_key) } else { let Some(image) = images.get(handle) else { - warn!( - "Cursor image {handle:?} is not loaded yet and couldn't be used. Trying again next frame." - ); + warn!("Cursor image {handle:?} is not loaded yet and couldn't be used. Trying again next frame."); queue.insert(entity); continue; }; diff --git a/crates/bevy_winit/src/state.rs b/crates/bevy_winit/src/state.rs index 9217968d31d7e..9e93b99a45f3f 100644 --- a/crates/bevy_winit/src/state.rs +++ b/crates/bevy_winit/src/state.rs @@ -502,8 +502,7 @@ impl ApplicationHandler for WinitAppRunnerState { { // Get windows that are cached but without raw handles. Those window were already created, but got their // handle wrapper removed when the app was suspended. - let mut query = self.world_mut() - .query_filtered::<(Entity, &Window), (With, Without)>(); + let mut query = self.world_mut().query_filtered::<(Entity, &Window), (With, Without)>(); if let Ok((entity, window)) = query.get_single(&self.world()) { let window = window.clone(); diff --git a/examples/3d/atmospheric_fog.rs b/examples/3d/atmospheric_fog.rs index e24736cdd1644..8a34c913e41ab 100644 --- a/examples/3d/atmospheric_fog.rs +++ b/examples/3d/atmospheric_fog.rs @@ -85,14 +85,7 @@ fn setup_terrain_scene( } fn setup_instructions(mut commands: Commands) { - commands.spawn((Text::new("Press Spacebar to Toggle Atmospheric Fog.\nPress S to Toggle Directional Light Fog Influence."), - Node { - position_type: PositionType::Absolute, - bottom: Val::Px(12.0), - left: Val::Px(12.0), - ..default() - }) - ); + commands.spawn((Text::new("Press Spacebar to Toggle Atmospheric Fog.\nPress S to Toggle Directional Light Fog Influence."), Node { position_type: PositionType::Absolute, bottom: Val::Px(12.0), left: Val::Px(12.0), ..default() })); } fn toggle_system(keycode: Res>, mut fog: Single<&mut DistanceFog>) { diff --git a/examples/3d/auto_exposure.rs b/examples/3d/auto_exposure.rs index ee623982db189..03a4daec62ee7 100644 --- a/examples/3d/auto_exposure.rs +++ b/examples/3d/auto_exposure.rs @@ -128,14 +128,7 @@ fn setup( let text_font = TextFont::default(); - commands.spawn((Text::new("Left / Right - Rotate Camera\nC - Toggle Compensation Curve\nM - Toggle Metering Mask\nV - Visualize Metering Mask"), - text_font.clone(), Node { - position_type: PositionType::Absolute, - top: Val::Px(12.0), - left: Val::Px(12.0), - ..default() - }) - ); + commands.spawn((Text::new("Left / Right - Rotate Camera\nC - Toggle Compensation Curve\nM - Toggle Metering Mask\nV - Visualize Metering Mask"), text_font.clone(), Node { position_type: PositionType::Absolute, top: Val::Px(12.0), left: Val::Px(12.0), ..default() })); commands.spawn(( Text::default(), diff --git a/examples/3d/blend_modes.rs b/examples/3d/blend_modes.rs index 4de01cb4aca4c..76bb1d7882496 100644 --- a/examples/3d/blend_modes.rs +++ b/examples/3d/blend_modes.rs @@ -167,15 +167,7 @@ fn setup( let label_text_style = (text_style.clone(), TextColor(ORANGE.into())); - commands.spawn((Text::new("Up / Down — Increase / Decrease Alpha\nLeft / Right — Rotate Camera\nH - Toggle HDR\nSpacebar — Toggle Unlit\nC — Randomize Colors"), - text_style.clone(), - Node { - position_type: PositionType::Absolute, - top: Val::Px(12.0), - left: Val::Px(12.0), - ..default() - }) - ); + commands.spawn((Text::new("Up / Down — Increase / Decrease Alpha\nLeft / Right — Rotate Camera\nH - Toggle HDR\nSpacebar — Toggle Unlit\nC — Randomize Colors"), text_style.clone(), Node { position_type: PositionType::Absolute, top: Val::Px(12.0), left: Val::Px(12.0), ..default() })); commands.spawn(( Text::default(), diff --git a/examples/3d/meshlet.rs b/examples/3d/meshlet.rs index c3aeb76480764..d59c1344bc6b1 100644 --- a/examples/3d/meshlet.rs +++ b/examples/3d/meshlet.rs @@ -16,8 +16,7 @@ use bevy::{ use camera_controller::{CameraController, CameraControllerPlugin}; use std::{f32::consts::PI, path::Path, process::ExitCode}; -const ASSET_URL: &str = - "https://raw.githubusercontent.com/JMS55/bevy_meshlet_asset/8483db58832542383820c3f44e4730e566910be7/bunny.meshlet_mesh"; +const ASSET_URL: &str = "https://raw.githubusercontent.com/JMS55/bevy_meshlet_asset/8483db58832542383820c3f44e4730e566910be7/bunny.meshlet_mesh"; fn main() -> ExitCode { if !Path::new("./assets/models/bunny.meshlet_mesh").exists() { diff --git a/examples/app/log_layers.rs b/examples/app/log_layers.rs index fa7ddd1470bde..19ecd1f59f5ed 100644 --- a/examples/app/log_layers.rs +++ b/examples/app/log_layers.rs @@ -37,7 +37,6 @@ fn main() { App::new() .add_plugins(DefaultPlugins.set(bevy::log::LogPlugin { custom_layer, - ..default() })) .add_systems(Update, log_system) diff --git a/examples/asset/processing/asset_processing.rs b/examples/asset/processing/asset_processing.rs index e7eefd3aafba0..e04c01d5d61d0 100644 --- a/examples/asset/processing/asset_processing.rs +++ b/examples/asset/processing/asset_processing.rs @@ -55,14 +55,7 @@ struct TextPlugin; impl Plugin for TextPlugin { fn build(&self, app: &mut App) { embedded_asset!(app, "examples/asset/processing/", "e.txt"); - app.init_asset::() - .init_asset::() - .register_asset_loader(CoolTextLoader) - .register_asset_loader(TextLoader) - .register_asset_processor::>( - LoadTransformAndSave::new(CoolTextTransformer, CoolTextSaver), - ) - .set_default_asset_processor::>("cool.ron"); + app.init_asset::().init_asset::().register_asset_loader(CoolTextLoader).register_asset_loader(TextLoader).register_asset_processor::>(LoadTransformAndSave::new(CoolTextTransformer, CoolTextSaver)).set_default_asset_processor::>("cool.ron"); } } diff --git a/examples/camera/2d_screen_shake.rs b/examples/camera/2d_screen_shake.rs index 29f5cfc241c3b..4ec76cdccfffa 100644 --- a/examples/camera/2d_screen_shake.rs +++ b/examples/camera/2d_screen_shake.rs @@ -129,7 +129,8 @@ fn trigger_shake_on_space( MAX_OFFSET, screen_shake_clone.trauma + TRAUMA_INCREMENT * time.delta_secs(), Vec2 { x: 0.0, y: 0.0 }, - ); // final_position should be your current player position + ); + // final_position should be your current player position } } diff --git a/examples/ecs/iter_combinations.rs b/examples/ecs/iter_combinations.rs index b112a0a698a24..2aceb28fb45a6 100644 --- a/examples/ecs/iter_combinations.rs +++ b/examples/ecs/iter_combinations.rs @@ -100,7 +100,6 @@ fn generate_bodies( emissive: LinearRgba::from(ORANGE_RED) * 2., ..default() })), - mass: Mass(500.0), ..default() }, diff --git a/examples/games/desk_toy.rs b/examples/games/desk_toy.rs index 2c985dad9460d..387dad6a1e553 100644 --- a/examples/games/desk_toy.rs +++ b/examples/games/desk_toy.rs @@ -112,12 +112,7 @@ fn setup( font_size: 25.0, ..default() }; - commands.spawn(( - Text2d::new("Press Space to play on your desktop! Press it again to return.\nRight click Bevy logo to exit."), - text_style.clone(), - Transform::from_xyz(0.0, -300.0, 100.0), - InstructionsText, - )); + commands.spawn((Text2d::new("Press Space to play on your desktop! Press it again to return.\nRight click Bevy logo to exit."), text_style.clone(), Transform::from_xyz(0.0, -300.0, 100.0), InstructionsText)); // Create a circle mesh. We will reuse this mesh for all our circles. let circle = meshes.add(Circle { radius: 1.0 }); diff --git a/examples/input/gamepad_rumble.rs b/examples/input/gamepad_rumble.rs index cdc5a9c85ede4..7366e7d0ce498 100644 --- a/examples/input/gamepad_rumble.rs +++ b/examples/input/gamepad_rumble.rs @@ -20,9 +20,7 @@ fn gamepad_system( ) { for (entity, gamepad) in &gamepads { if gamepad.just_pressed(GamepadButton::North) { - info!( - "North face button: strong (low-frequency) with low intensity for rumble for 5 seconds. Press multiple times to increase intensity." - ); + info!("North face button: strong (low-frequency) with low intensity for rumble for 5 seconds. Press multiple times to increase intensity."); rumble_requests.send(GamepadRumbleRequest::Add { gamepad: entity, intensity: GamepadRumbleIntensity::strong_motor(0.1), diff --git a/examples/math/custom_primitives.rs b/examples/math/custom_primitives.rs index a072b4476412c..71ebbb094e78d 100644 --- a/examples/math/custom_primitives.rs +++ b/examples/math/custom_primitives.rs @@ -158,14 +158,11 @@ fn setup( // Example instructions commands.spawn(( - Text::new("Press 'B' to toggle between no bounding shapes, bounding boxes (AABBs) and bounding spheres / circles\n\ - Press 'Space' to switch between 3D and 2D"), - Node { - position_type: PositionType::Absolute, - top: Val::Px(12.0), - left: Val::Px(12.0), - ..default() - }, + Text::new( + "Press 'B' to toggle between no bounding shapes, bounding boxes (AABBs) and bounding spheres / circles\n\ + Press 'Space' to switch between 3D and 2D", + ), + Node { position_type: PositionType::Absolute, top: Val::Px(12.0), left: Val::Px(12.0), ..default() }, )); } diff --git a/examples/ui/display_and_visibility.rs b/examples/ui/display_and_visibility.rs index ca3f29376c52f..5918b1431ab67 100644 --- a/examples/ui/display_and_visibility.rs +++ b/examples/ui/display_and_visibility.rs @@ -82,87 +82,28 @@ fn setup(mut commands: Commands, asset_server: Res) { }; commands.spawn(Camera2d); - commands - .spawn(( - Node { - width: Val::Percent(100.), - height: Val::Percent(100.), - flex_direction: FlexDirection::Column, - align_items: AlignItems::Center, - justify_content: JustifyContent::SpaceEvenly, - ..Default::default() - }, - BackgroundColor(Color::BLACK), - )) - .with_children(|parent| { - parent.spawn(( - Text::new("Use the panel on the right to change the Display and Visibility properties for the respective nodes of the panel on the left"), - text_font.clone(), - TextLayout::new_with_justify(JustifyText::Center), - Node { - margin: UiRect::bottom(Val::Px(10.)), - ..Default::default() - }, - )); + commands.spawn((Node { width: Val::Percent(100.), height: Val::Percent(100.), flex_direction: FlexDirection::Column, align_items: AlignItems::Center, justify_content: JustifyContent::SpaceEvenly, ..Default::default() }, BackgroundColor(Color::BLACK))).with_children(|parent| { + parent.spawn((Text::new("Use the panel on the right to change the Display and Visibility properties for the respective nodes of the panel on the left"), text_font.clone(), TextLayout::new_with_justify(JustifyText::Center), Node { margin: UiRect::bottom(Val::Px(10.)), ..Default::default() })); - parent - .spawn(Node { - width: Val::Percent(100.), - ..default() - }) - .with_children(|parent| { - let mut target_ids = vec![]; - parent - .spawn(Node { - width: Val::Percent(50.), - height: Val::Px(520.), - justify_content: JustifyContent::Center, - ..default() - }) - .with_children(|parent| { - target_ids = spawn_left_panel(parent, &palette); - }); + parent.spawn(Node { width: Val::Percent(100.), ..default() }).with_children(|parent| { + let mut target_ids = vec![]; + parent.spawn(Node { width: Val::Percent(50.), height: Val::Px(520.), justify_content: JustifyContent::Center, ..default() }).with_children(|parent| { + target_ids = spawn_left_panel(parent, &palette); + }); - parent - .spawn(Node { - width: Val::Percent(50.), - justify_content: JustifyContent::Center, - ..default() - }) - .with_children(|parent| { - spawn_right_panel(parent, text_font, &palette, target_ids); - }); - }); + parent.spawn(Node { width: Val::Percent(50.), justify_content: JustifyContent::Center, ..default() }).with_children(|parent| { + spawn_right_panel(parent, text_font, &palette, target_ids); + }); + }); - parent - .spawn(Node { - flex_direction: FlexDirection::Row, - align_items: AlignItems::Start, - justify_content: JustifyContent::Start, - column_gap: Val::Px(10.), - ..default() - }) - .with_children(|builder| { - let text_font = TextFont { - font: asset_server.load("fonts/FiraSans-Bold.ttf"), - ..default() - }; + parent.spawn(Node { flex_direction: FlexDirection::Row, align_items: AlignItems::Start, justify_content: JustifyContent::Start, column_gap: Val::Px(10.), ..default() }).with_children(|builder| { + let text_font = TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf"), ..default() }; - builder.spawn(( - Text::new("Display::None\nVisibility::Hidden\nVisibility::Inherited"), - text_font.clone(), - TextColor(HIDDEN_COLOR), - TextLayout::new_with_justify(JustifyText::Center), - )); - builder.spawn(( - Text::new("-\n-\n-"), - text_font.clone(), - TextColor(DARK_GRAY.into()), - TextLayout::new_with_justify(JustifyText::Center), - )); - builder.spawn((Text::new("The UI Node and its descendants will not be visible and will not be allotted any space in the UI layout.\nThe UI Node will not be visible but will still occupy space in the UI layout.\nThe UI node will inherit the visibility property of its parent. If it has no parent it will be visible."), text_font)); - }); + builder.spawn((Text::new("Display::None\nVisibility::Hidden\nVisibility::Inherited"), text_font.clone(), TextColor(HIDDEN_COLOR), TextLayout::new_with_justify(JustifyText::Center))); + builder.spawn((Text::new("-\n-\n-"), text_font.clone(), TextColor(DARK_GRAY.into()), TextLayout::new_with_justify(JustifyText::Center))); + builder.spawn((Text::new("The UI Node and its descendants will not be visible and will not be allotted any space in the UI layout.\nThe UI Node will not be visible but will still occupy space in the UI layout.\nThe UI node will inherit the visibility property of its parent. If it has no parent it will be visible."), text_font)); }); + }); } fn spawn_left_panel(builder: &mut ChildBuilder, palette: &[Color; 4]) -> Vec { diff --git a/examples/ui/grid.rs b/examples/ui/grid.rs index 6315283bec040..58e59d40b192f 100644 --- a/examples/ui/grid.rs +++ b/examples/ui/grid.rs @@ -36,11 +36,7 @@ fn spawn_layout(mut commands: Commands, asset_server: Res) { // - The first row will size to the size of its contents // - The second row take up remaining available space (after rows 1 and 3 have both been sized) // - The third row will be exactly 20px high - grid_template_rows: vec![ - GridTrack::auto(), - GridTrack::flex(1.0), - GridTrack::px(20.), - ], + grid_template_rows: vec![GridTrack::auto(), GridTrack::flex(1.0), GridTrack::px(20.)], ..default() }, BackgroundColor(Color::WHITE), @@ -48,15 +44,13 @@ fn spawn_layout(mut commands: Commands, asset_server: Res) { .with_children(|builder| { // Header builder - .spawn( - Node { - display: Display::Grid, - // Make this node span two grid columns so that it takes up the entire top tow - grid_column: GridPlacement::span(2), - padding: UiRect::all(Val::Px(6.0)), - ..default() - }, - ) + .spawn(Node { + display: Display::Grid, + // Make this node span two grid columns so that it takes up the entire top tow + grid_column: GridPlacement::span(2), + padding: UiRect::all(Val::Px(6.0)), + ..default() + }) .with_children(|builder| { spawn_nested_text_bundle(builder, font.clone(), "Bevy CSS Grid Layout Example"); }); @@ -132,19 +126,8 @@ fn spawn_layout(mut commands: Commands, asset_server: Res) { BackgroundColor(BLACK.into()), )) .with_children(|builder| { - builder.spawn((Text::new("Sidebar"), - TextFont { - font: font.clone(), - ..default() - }, - )); - builder.spawn((Text::new("A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely."), - TextFont { - font: font.clone(), - font_size: 13.0, - ..default() - }, - )); + builder.spawn((Text::new("Sidebar"), TextFont { font: font.clone(), ..default() })); + builder.spawn((Text::new("A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely. A paragraph of text which ought to wrap nicely."), TextFont { font: font.clone(), font_size: 13.0, ..default() })); builder.spawn(Node::default()); }); @@ -159,23 +142,7 @@ fn spawn_layout(mut commands: Commands, asset_server: Res) { )); // Modal (absolutely positioned on top of content - currently hidden: to view it, change its visibility) - builder.spawn(( - Node { - position_type: PositionType::Absolute, - margin: UiRect { - top: Val::Px(100.), - bottom: Val::Auto, - left: Val::Auto, - right: Val::Auto, - }, - width: Val::Percent(60.), - height: Val::Px(300.), - max_width: Val::Px(600.), - ..default() - }, - Visibility::Hidden, - BackgroundColor(Color::WHITE.with_alpha(0.8)), - )); + builder.spawn((Node { position_type: PositionType::Absolute, margin: UiRect { top: Val::Px(100.), bottom: Val::Auto, left: Val::Auto, right: Val::Auto }, width: Val::Percent(60.), height: Val::Px(300.), max_width: Val::Px(600.), ..default() }, Visibility::Hidden, BackgroundColor(Color::WHITE.with_alpha(0.8)))); }); } diff --git a/examples/ui/render_ui_to_texture.rs b/examples/ui/render_ui_to_texture.rs index 69083dd2ece14..0b30f5780e864 100644 --- a/examples/ui/render_ui_to_texture.rs +++ b/examples/ui/render_ui_to_texture.rs @@ -96,7 +96,6 @@ fn setup( base_color_texture: Some(image_handle), reflectance: 0.02, unlit: false, - ..default() }); diff --git a/examples/ui/scroll.rs b/examples/ui/scroll.rs index 152ea7189ffc1..c3ebf754d4ac2 100644 --- a/examples/ui/scroll.rs +++ b/examples/ui/scroll.rs @@ -29,302 +29,122 @@ fn setup(mut commands: Commands, asset_server: Res) { commands.spawn((Camera2d, IsDefaultUiCamera)); // root node - commands - .spawn(Node { - width: Val::Percent(100.0), - height: Val::Percent(100.0), - justify_content: JustifyContent::SpaceBetween, - flex_direction: FlexDirection::Column, - ..default() - }) - .insert(PickingBehavior::IGNORE) - .with_children(|parent| { - // horizontal scroll example + commands.spawn(Node { width: Val::Percent(100.0), height: Val::Percent(100.0), justify_content: JustifyContent::SpaceBetween, flex_direction: FlexDirection::Column, ..default() }).insert(PickingBehavior::IGNORE).with_children(|parent| { + // horizontal scroll example + parent.spawn(Node { width: Val::Percent(100.), flex_direction: FlexDirection::Column, ..default() }).with_children(|parent| { + // header + parent.spawn((Text::new("Horizontally Scrolling list (Ctrl + Mousewheel)"), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf"), font_size: FONT_SIZE, ..default() }, Label)); + + // horizontal scroll container parent - .spawn(Node { - width: Val::Percent(100.), - flex_direction: FlexDirection::Column, - ..default() - }) + .spawn(( + Node { + width: Val::Percent(80.), + margin: UiRect::all(Val::Px(10.)), + flex_direction: FlexDirection::Row, + overflow: Overflow::scroll_x(), // n.b. + ..default() + }, + BackgroundColor(Color::srgb(0.10, 0.10, 0.10)), + )) .with_children(|parent| { - // header - parent.spawn(( - Text::new("Horizontally Scrolling list (Ctrl + Mousewheel)"), - TextFont { - font: asset_server.load("fonts/FiraSans-Bold.ttf"), - font_size: FONT_SIZE, - ..default() - }, - Label, - )); - - // horizontal scroll container - parent - .spawn(( - Node { - width: Val::Percent(80.), - margin: UiRect::all(Val::Px(10.)), - flex_direction: FlexDirection::Row, - overflow: Overflow::scroll_x(), // n.b. - ..default() - }, - BackgroundColor(Color::srgb(0.10, 0.10, 0.10)), - )) - .with_children(|parent| { - for i in 0..100 { - parent.spawn((Text(format!("Item {i}")), - TextFont { - font: asset_server - .load("fonts/FiraSans-Bold.ttf"), - ..default() - }, - Label, - AccessibilityNode(NodeBuilder::new(Role::ListItem)), - )) - .insert(Node { - min_width: Val::Px(200.), - align_content: AlignContent::Center, - ..default() - }) - .insert(PickingBehavior { - should_block_lower: false, - ..default() - }) - .observe(| - trigger: Trigger>, - mut commands: Commands - | { - if trigger.event().button == PointerButton::Primary { - commands.entity(trigger.entity()).despawn_recursive(); - } - }); + for i in 0..100 { + parent.spawn((Text(format!("Item {i}")), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf"), ..default() }, Label, AccessibilityNode(NodeBuilder::new(Role::ListItem)))).insert(Node { min_width: Val::Px(200.), align_content: AlignContent::Center, ..default() }).insert(PickingBehavior { should_block_lower: false, ..default() }).observe(|trigger: Trigger>, mut commands: Commands| { + if trigger.event().button == PointerButton::Primary { + commands.entity(trigger.entity()).despawn_recursive(); } }); + } }); + }); - // container for all other examples - parent - .spawn(Node { - width: Val::Percent(100.), - height: Val::Percent(100.), - flex_direction: FlexDirection::Row, - justify_content: JustifyContent::SpaceBetween, - ..default() - }) - .with_children(|parent| { - // vertical scroll example - parent - .spawn(Node { + // container for all other examples + parent.spawn(Node { width: Val::Percent(100.), height: Val::Percent(100.), flex_direction: FlexDirection::Row, justify_content: JustifyContent::SpaceBetween, ..default() }).with_children(|parent| { + // vertical scroll example + parent.spawn(Node { flex_direction: FlexDirection::Column, justify_content: JustifyContent::Center, align_items: AlignItems::Center, width: Val::Px(200.), ..default() }).with_children(|parent| { + // Title + parent.spawn((Text::new("Vertically Scrolling List"), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf"), font_size: FONT_SIZE, ..default() }, Label)); + // Scrolling list + parent + .spawn(( + Node { flex_direction: FlexDirection::Column, - justify_content: JustifyContent::Center, - align_items: AlignItems::Center, - width: Val::Px(200.), + align_self: AlignSelf::Stretch, + height: Val::Percent(50.), + overflow: Overflow::scroll_y(), // n.b. ..default() - }) - .with_children(|parent| { - // Title - parent.spawn(( - Text::new("Vertically Scrolling List"), - TextFont { - font: asset_server.load("fonts/FiraSans-Bold.ttf"), - font_size: FONT_SIZE, - ..default() - }, - Label, - )); - // Scrolling list - parent - .spawn(( - Node { - flex_direction: FlexDirection::Column, - align_self: AlignSelf::Stretch, - height: Val::Percent(50.), - overflow: Overflow::scroll_y(), // n.b. - ..default() - }, - BackgroundColor(Color::srgb(0.10, 0.10, 0.10)), - )) - .with_children(|parent| { - // List items - for i in 0..25 { - parent - .spawn(Node { - min_height: Val::Px(LINE_HEIGHT), - max_height: Val::Px(LINE_HEIGHT), - ..default() - }) - .insert(PickingBehavior { - should_block_lower: false, - ..default() - }) - .with_children(|parent| { - parent - .spawn(( - Text(format!("Item {i}")), - TextFont { - font: asset_server - .load("fonts/FiraSans-Bold.ttf"), - ..default() - }, - Label, - AccessibilityNode(NodeBuilder::new( - Role::ListItem, - )), - )) - .insert(PickingBehavior { - should_block_lower: false, - ..default() - }); - }); - } - }); - }); + }, + BackgroundColor(Color::srgb(0.10, 0.10, 0.10)), + )) + .with_children(|parent| { + // List items + for i in 0..25 { + parent.spawn(Node { min_height: Val::Px(LINE_HEIGHT), max_height: Val::Px(LINE_HEIGHT), ..default() }).insert(PickingBehavior { should_block_lower: false, ..default() }).with_children(|parent| { + parent.spawn((Text(format!("Item {i}")), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf"), ..default() }, Label, AccessibilityNode(NodeBuilder::new(Role::ListItem)))).insert(PickingBehavior { should_block_lower: false, ..default() }); + }); + } + }); + }); - // Bidirectional scroll example - parent - .spawn(Node { + // Bidirectional scroll example + parent.spawn(Node { flex_direction: FlexDirection::Column, justify_content: JustifyContent::Center, align_items: AlignItems::Center, width: Val::Px(200.), ..default() }).with_children(|parent| { + // Title + parent.spawn((Text::new("Bidirectionally Scrolling List"), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf"), font_size: FONT_SIZE, ..default() }, Label)); + // Scrolling list + parent + .spawn(( + Node { flex_direction: FlexDirection::Column, - justify_content: JustifyContent::Center, - align_items: AlignItems::Center, - width: Val::Px(200.), + align_self: AlignSelf::Stretch, + height: Val::Percent(50.), + overflow: Overflow::scroll(), // n.b. ..default() - }) - .with_children(|parent| { - // Title - parent.spawn(( - Text::new("Bidirectionally Scrolling List"), - TextFont { - font: asset_server.load("fonts/FiraSans-Bold.ttf"), - font_size: FONT_SIZE, - ..default() - }, - Label, - )); - // Scrolling list - parent - .spawn(( - Node { - flex_direction: FlexDirection::Column, - align_self: AlignSelf::Stretch, - height: Val::Percent(50.), - overflow: Overflow::scroll(), // n.b. - ..default() - }, - BackgroundColor(Color::srgb(0.10, 0.10, 0.10)), - )) - .with_children(|parent| { - // Rows in each column - for oi in 0..10 { - parent - .spawn(Node { - flex_direction: FlexDirection::Row, - ..default() - }) - .insert(PickingBehavior::IGNORE) - .with_children(|parent| { - // Elements in each row - for i in 0..25 { - parent - .spawn(( - Text(format!("Item {}", (oi * 25) + i)), - TextFont { - font: asset_server.load( - "fonts/FiraSans-Bold.ttf", - ), - ..default() - }, - Label, - AccessibilityNode(NodeBuilder::new( - Role::ListItem, - )), - )) - .insert(PickingBehavior { - should_block_lower: false, - ..default() - }); - } - }); - } - }); - }); + }, + BackgroundColor(Color::srgb(0.10, 0.10, 0.10)), + )) + .with_children(|parent| { + // Rows in each column + for oi in 0..10 { + parent.spawn(Node { flex_direction: FlexDirection::Row, ..default() }).insert(PickingBehavior::IGNORE).with_children(|parent| { + // Elements in each row + for i in 0..25 { + parent.spawn((Text(format!("Item {}", (oi * 25) + i)), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf"), ..default() }, Label, AccessibilityNode(NodeBuilder::new(Role::ListItem)))).insert(PickingBehavior { should_block_lower: false, ..default() }); + } + }); + } + }); + }); - // Nested scrolls example - parent - .spawn(Node { - flex_direction: FlexDirection::Column, - justify_content: JustifyContent::Center, - align_items: AlignItems::Center, - width: Val::Px(200.), + // Nested scrolls example + parent.spawn(Node { flex_direction: FlexDirection::Column, justify_content: JustifyContent::Center, align_items: AlignItems::Center, width: Val::Px(200.), ..default() }).with_children(|parent| { + // Title + parent.spawn((Text::new("Nested Scrolling Lists"), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf"), font_size: FONT_SIZE, ..default() }, Label)); + // Outer, horizontal scrolling container + parent + .spawn(( + Node { + column_gap: Val::Px(20.), + flex_direction: FlexDirection::Row, + align_self: AlignSelf::Stretch, + height: Val::Percent(50.), + overflow: Overflow::scroll_x(), // n.b. ..default() - }) - .with_children(|parent| { - // Title - parent.spawn(( - Text::new("Nested Scrolling Lists"), - TextFont { - font: asset_server.load("fonts/FiraSans-Bold.ttf"), - font_size: FONT_SIZE, - ..default() - }, - Label, - )); - // Outer, horizontal scrolling container - parent - .spawn(( - Node { - column_gap: Val::Px(20.), - flex_direction: FlexDirection::Row, - align_self: AlignSelf::Stretch, - height: Val::Percent(50.), - overflow: Overflow::scroll_x(), // n.b. - ..default() - }, - BackgroundColor(Color::srgb(0.10, 0.10, 0.10)), - )) - .with_children(|parent| { - // Inner, scrolling columns - for oi in 0..30 { - parent - .spawn(( - Node { - flex_direction: FlexDirection::Column, - align_self: AlignSelf::Stretch, - overflow: Overflow::scroll_y(), - ..default() - }, - BackgroundColor(Color::srgb(0.05, 0.05, 0.05)), - )) - .insert(PickingBehavior { - should_block_lower: false, - ..default() - }) - .with_children(|parent| { - for i in 0..25 { - parent - .spawn(( - Text(format!("Item {}", (oi * 25) + i)), - TextFont { - font: asset_server.load( - "fonts/FiraSans-Bold.ttf", - ), - ..default() - }, - Label, - AccessibilityNode(NodeBuilder::new( - Role::ListItem, - )), - )) - .insert(PickingBehavior { - should_block_lower: false, - ..default() - }); - } - }); - } - }); - }); - }); + }, + BackgroundColor(Color::srgb(0.10, 0.10, 0.10)), + )) + .with_children(|parent| { + // Inner, scrolling columns + for oi in 0..30 { + parent.spawn((Node { flex_direction: FlexDirection::Column, align_self: AlignSelf::Stretch, overflow: Overflow::scroll_y(), ..default() }, BackgroundColor(Color::srgb(0.05, 0.05, 0.05)))).insert(PickingBehavior { should_block_lower: false, ..default() }).with_children(|parent| { + for i in 0..25 { + parent.spawn((Text(format!("Item {}", (oi * 25) + i)), TextFont { font: asset_server.load("fonts/FiraSans-Bold.ttf"), ..default() }, Label, AccessibilityNode(NodeBuilder::new(Role::ListItem)))).insert(PickingBehavior { should_block_lower: false, ..default() }); + } + }); + } + }); + }); }); + }); } /// Updates the scroll position of scrollable nodes in response to mouse input diff --git a/examples/ui/text_debug.rs b/examples/ui/text_debug.rs index 3c9e42b54dadb..52f7213c60322 100644 --- a/examples/ui/text_debug.rs +++ b/examples/ui/text_debug.rs @@ -45,199 +45,33 @@ fn infotext_system(mut commands: Commands, asset_server: Res) { .id(); let left_column = commands - .spawn(Node { - flex_direction: FlexDirection::Column, - justify_content: JustifyContent::SpaceBetween, - align_items: AlignItems::Start, - flex_grow: 1., - margin: UiRect::axes(Val::Px(15.), Val::Px(5.)), - ..default() - }).with_children(|builder| { - builder.spawn(( - Text::new("This is\ntext with\nline breaks\nin the top left."), - TextFont { - font: font.clone(), - font_size: 25.0, - ..default() - }, - BackgroundColor(background_color) - )); - builder.spawn(( - Text::new( - "This text is right-justified. The `JustifyText` component controls the horizontal alignment of the lines of multi-line text relative to each other, and does not affect the text node's position in the UI layout.", - ), - TextFont { - font: font.clone(), - font_size: 25.0, - ..default() - }, - TextColor(YELLOW.into()), - TextLayout::new_with_justify(JustifyText::Right), - Node { - max_width: Val::Px(300.), - ..default() - }, - BackgroundColor(background_color) - )); - builder.spawn(( - Text::new( - "This\ntext has\nline breaks and also a set width in the bottom left."), - TextFont { - font: font.clone(), - font_size: 25.0, - ..default() - }, - Node { - max_width: Val::Px(300.), - ..default() - }, - BackgroundColor(background_color) - ) - ); - }).id(); + .spawn(Node { flex_direction: FlexDirection::Column, justify_content: JustifyContent::SpaceBetween, align_items: AlignItems::Start, flex_grow: 1., margin: UiRect::axes(Val::Px(15.), Val::Px(5.)), ..default() }) + .with_children(|builder| { + builder.spawn((Text::new("This is\ntext with\nline breaks\nin the top left."), TextFont { font: font.clone(), font_size: 25.0, ..default() }, BackgroundColor(background_color))); + builder.spawn((Text::new("This text is right-justified. The `JustifyText` component controls the horizontal alignment of the lines of multi-line text relative to each other, and does not affect the text node's position in the UI layout."), TextFont { font: font.clone(), font_size: 25.0, ..default() }, TextColor(YELLOW.into()), TextLayout::new_with_justify(JustifyText::Right), Node { max_width: Val::Px(300.), ..default() }, BackgroundColor(background_color))); + builder.spawn((Text::new("This\ntext has\nline breaks and also a set width in the bottom left."), TextFont { font: font.clone(), font_size: 25.0, ..default() }, Node { max_width: Val::Px(300.), ..default() }, BackgroundColor(background_color))); + }) + .id(); let right_column = commands - .spawn(Node { - flex_direction: FlexDirection::Column, - justify_content: JustifyContent::SpaceBetween, - align_items: AlignItems::End, - flex_grow: 1., - margin: UiRect::axes(Val::Px(15.), Val::Px(5.)), - ..default() - }) + .spawn(Node { flex_direction: FlexDirection::Column, justify_content: JustifyContent::SpaceBetween, align_items: AlignItems::End, flex_grow: 1., margin: UiRect::axes(Val::Px(15.), Val::Px(5.)), ..default() }) .with_children(|builder| { - builder.spawn(( - Text::new("This text is very long, has a limited width, is center-justified, is positioned in the top right and is also colored pink."), - TextFont { - font: font.clone(), - font_size: 33.0, - ..default() - }, - TextColor(Color::srgb(0.8, 0.2, 0.7)), - TextLayout::new_with_justify(JustifyText::Center), - Node { - max_width: Val::Px(400.), - ..default() - }, - BackgroundColor(background_color), - )); - - builder.spawn(( - Text::new("This text is left-justified and is vertically positioned to distribute the empty space equally above and below it."), - TextFont { - font: font.clone(), - font_size: 29.0, - ..default() - }, - TextColor(YELLOW.into()), - TextLayout::new_with_justify(JustifyText::Left), - Node { - max_width: Val::Px(300.), - ..default() - }, - BackgroundColor(background_color), - )); - - builder.spawn(( - Text::new("This text is fully justified and is positioned in the same way."), - TextFont { - font: font.clone(), - font_size: 29.0, - ..default() - }, - TextLayout::new_with_justify(JustifyText::Justified), - TextColor(GREEN_YELLOW.into()), - Node { - max_width: Val::Px(300.), - ..default() - }, - BackgroundColor(background_color), - )); - - builder - .spawn(( - Text::default(), - TextFont { - font: font.clone(), - font_size: 21.0, - ..default() - }, - TextChanges, - BackgroundColor(background_color), - )) - .with_children(|p| { - p.spawn(( - TextSpan::new("\nThis text changes in the bottom right"), - TextFont { - font: font.clone(), - font_size: 21.0, - ..default() - }, - )); - p.spawn(( - TextSpan::new(" this text has zero fontsize"), - TextFont { - font: font.clone(), - font_size: 0.0, - ..default() - }, - TextColor(BLUE.into()), - )); - p.spawn(( - TextSpan::new("\nThis text changes in the bottom right - "), - TextFont { - font: font.clone(), - font_size: 21.0, - ..default() - }, - TextColor(RED.into()), - )); - p.spawn(( - TextSpan::default(), - TextFont { - font: font.clone(), - font_size: 21.0, - ..default() - }, - TextColor(ORANGE_RED.into()), - )); - p.spawn(( - TextSpan::new(" fps, "), - TextFont { - font: font.clone(), - font_size: 10.0, - ..default() - }, - TextColor(YELLOW.into()), - )); - p.spawn(( - TextSpan::default(), - TextFont { - font: font.clone(), - font_size: 21.0, - ..default() - }, - TextColor(LIME.into()), - )); - p.spawn(( - TextSpan::new(" ms/frame"), - TextFont { - font: font.clone(), - font_size: 42.0, - ..default() - }, - TextColor(BLUE.into()), - )); - p.spawn(( - TextSpan::new(" this text has negative fontsize"), - TextFont { - font: font.clone(), - font_size: -42.0, - ..default() - }, - TextColor(BLUE.into()), - )); - }); + builder.spawn((Text::new("This text is very long, has a limited width, is center-justified, is positioned in the top right and is also colored pink."), TextFont { font: font.clone(), font_size: 33.0, ..default() }, TextColor(Color::srgb(0.8, 0.2, 0.7)), TextLayout::new_with_justify(JustifyText::Center), Node { max_width: Val::Px(400.), ..default() }, BackgroundColor(background_color))); + + builder.spawn((Text::new("This text is left-justified and is vertically positioned to distribute the empty space equally above and below it."), TextFont { font: font.clone(), font_size: 29.0, ..default() }, TextColor(YELLOW.into()), TextLayout::new_with_justify(JustifyText::Left), Node { max_width: Val::Px(300.), ..default() }, BackgroundColor(background_color))); + + builder.spawn((Text::new("This text is fully justified and is positioned in the same way."), TextFont { font: font.clone(), font_size: 29.0, ..default() }, TextLayout::new_with_justify(JustifyText::Justified), TextColor(GREEN_YELLOW.into()), Node { max_width: Val::Px(300.), ..default() }, BackgroundColor(background_color))); + + builder.spawn((Text::default(), TextFont { font: font.clone(), font_size: 21.0, ..default() }, TextChanges, BackgroundColor(background_color))).with_children(|p| { + p.spawn((TextSpan::new("\nThis text changes in the bottom right"), TextFont { font: font.clone(), font_size: 21.0, ..default() })); + p.spawn((TextSpan::new(" this text has zero fontsize"), TextFont { font: font.clone(), font_size: 0.0, ..default() }, TextColor(BLUE.into()))); + p.spawn((TextSpan::new("\nThis text changes in the bottom right - "), TextFont { font: font.clone(), font_size: 21.0, ..default() }, TextColor(RED.into()))); + p.spawn((TextSpan::default(), TextFont { font: font.clone(), font_size: 21.0, ..default() }, TextColor(ORANGE_RED.into()))); + p.spawn((TextSpan::new(" fps, "), TextFont { font: font.clone(), font_size: 10.0, ..default() }, TextColor(YELLOW.into()))); + p.spawn((TextSpan::default(), TextFont { font: font.clone(), font_size: 21.0, ..default() }, TextColor(LIME.into()))); + p.spawn((TextSpan::new(" ms/frame"), TextFont { font: font.clone(), font_size: 42.0, ..default() }, TextColor(BLUE.into()))); + p.spawn((TextSpan::new(" this text has negative fontsize"), TextFont { font: font.clone(), font_size: -42.0, ..default() }, TextColor(BLUE.into()))); + }); }) .id(); commands diff --git a/examples/ui/text_wrap_debug.rs b/examples/ui/text_wrap_debug.rs index 227fb15116eb0..0a17ae5d7bbff 100644 --- a/examples/ui/text_wrap_debug.rs +++ b/examples/ui/text_wrap_debug.rs @@ -105,13 +105,7 @@ fn spawn(mut commands: Commands, asset_server: Res) { )) .id(); - let messages = [ - format!("JustifyContent::{justification:?}"), - format!("LineBreakOn::{linebreak:?}"), - "Line 1\nLine 2".to_string(), - "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas auctor, nunc ac faucibus fringilla.".to_string(), - "pneumonoultramicroscopicsilicovolcanoconiosis".to_string() - ]; + let messages = [format!("JustifyContent::{justification:?}"), format!("LineBreakOn::{linebreak:?}"), "Line 1\nLine 2".to_string(), "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas auctor, nunc ac faucibus fringilla.".to_string(), "pneumonoultramicroscopicsilicovolcanoconiosis".to_string()]; for (j, message) in messages.into_iter().enumerate() { commands.entity(column_id).with_child(( diff --git a/examples/window/monitor_info.rs b/examples/window/monitor_info.rs index 930aca48f90ba..2eec17d1da0e3 100644 --- a/examples/window/monitor_info.rs +++ b/examples/window/monitor_info.rs @@ -62,9 +62,7 @@ fn update( )) .id(); - let info_text = format!( - "Monitor: {name}\nSize: {size}\nRefresh rate: {hz}\nPosition: {position}\nScale: {scale}\n\n", - ); + let info_text = format!("Monitor: {name}\nSize: {size}\nRefresh rate: {hz}\nPosition: {position}\nScale: {scale}\n\n",); commands.spawn(( Text(info_text), Node { diff --git a/tests/ecs/ambiguity_detection.rs b/tests/ecs/ambiguity_detection.rs index f6971b1ca2b23..938f78e587718 100644 --- a/tests/ecs/ambiguity_detection.rs +++ b/tests/ecs/ambiguity_detection.rs @@ -31,19 +31,11 @@ fn main() { app.update(); let main_app_ambiguities = count_ambiguities(app.main()); - assert_eq!( - main_app_ambiguities.total(), - 0, - "Main app has unexpected ambiguities among the following schedules: \n{main_app_ambiguities:#?}.", - ); + assert_eq!(main_app_ambiguities.total(), 0, "Main app has unexpected ambiguities among the following schedules: \n{main_app_ambiguities:#?}.",); // RenderApp is not checked here, because it is not within the App at this point. let render_extract_ambiguities = count_ambiguities(app.sub_app(RenderExtractApp)); - assert_eq!( - render_extract_ambiguities.total(), - 0, - "RenderExtract app has unexpected ambiguities among the following schedules: \n{render_extract_ambiguities:#?}", - ); + assert_eq!(render_extract_ambiguities.total(), 0, "RenderExtract app has unexpected ambiguities among the following schedules: \n{render_extract_ambiguities:#?}",); } /// Contains the number of conflicting systems per schedule. diff --git a/tools/build-wasm-example/src/main.rs b/tools/build-wasm-example/src/main.rs index 1162aaece7449..228ab5a502232 100644 --- a/tools/build-wasm-example/src/main.rs +++ b/tools/build-wasm-example/src/main.rs @@ -73,22 +73,13 @@ fn main() { parameters.push("--features"); parameters.push(&features_string); } - let cmd = cmd!( - sh, - "cargo build {parameters...} --profile release --target wasm32-unknown-unknown --example {example}" - ); + let cmd = cmd!(sh, "cargo build {parameters...} --profile release --target wasm32-unknown-unknown --example {example}"); cmd.run().expect("Error building example"); - cmd!( - sh, - "wasm-bindgen --out-dir examples/wasm/target --out-name wasm_example --target web target/wasm32-unknown-unknown/release/examples/{example}.wasm" - ) - .run() - .expect("Error creating wasm binding"); + cmd!(sh, "wasm-bindgen --out-dir examples/wasm/target --out-name wasm_example --target web target/wasm32-unknown-unknown/release/examples/{example}.wasm").run().expect("Error creating wasm binding"); if cli.optimize_size { - cmd!(sh, "wasm-opt -Oz --output examples/wasm/target/wasm_example_bg.wasm.optimized examples/wasm/target/wasm_example_bg.wasm") - .run().expect("Failed to optimize for size. Do you have wasm-opt correctly set up?"); + cmd!(sh, "wasm-opt -Oz --output examples/wasm/target/wasm_example_bg.wasm.optimized examples/wasm/target/wasm_example_bg.wasm").run().expect("Failed to optimize for size. Do you have wasm-opt correctly set up?"); } if cli.test { diff --git a/tools/ci/src/commands/compile_check_no_std.rs b/tools/ci/src/commands/compile_check_no_std.rs index ddb7c5b4e8bd5..0aaf7d5e38227 100644 --- a/tools/ci/src/commands/compile_check_no_std.rs +++ b/tools/ci/src/commands/compile_check_no_std.rs @@ -54,13 +54,7 @@ impl Prepare for CompileCheckNoStdCommand { "Please fix compiler errors in output above for bevy_utils no_std compatibility.", )); - commands.push(PreparedCommand::new::( - cmd!( - sh, - "cargo check -p bevy_mikktspace --no-default-features --features libm --target {target}" - ), - "Please fix compiler errors in output above for bevy_mikktspace no_std compatibility.", - )); + commands.push(PreparedCommand::new::(cmd!(sh, "cargo check -p bevy_mikktspace --no-default-features --features libm --target {target}"), "Please fix compiler errors in output above for bevy_mikktspace no_std compatibility.")); commands } diff --git a/tools/ci/src/commands/compile_fail.rs b/tools/ci/src/commands/compile_fail.rs index 65a91e6d2f039..aa93cc107b4b0 100644 --- a/tools/ci/src/commands/compile_fail.rs +++ b/tools/ci/src/commands/compile_fail.rs @@ -19,35 +19,17 @@ impl Prepare for CompileFailCommand { // Macro Compile Fail Tests // Run tests (they do not get executed with the workspace tests) // - See crates/bevy_macros_compile_fail_tests/README.md - commands.push( - PreparedCommand::new::( - cmd!(sh, "cargo test --target-dir ../../../target {no_fail_fast}"), - "Compiler errors of the macros compile fail tests seem to be different than expected! Check locally and compare rust versions.", - ) - .with_subdir("crates/bevy_derive/compile_fail"), - ); + commands.push(PreparedCommand::new::(cmd!(sh, "cargo test --target-dir ../../../target {no_fail_fast}"), "Compiler errors of the macros compile fail tests seem to be different than expected! Check locally and compare rust versions.").with_subdir("crates/bevy_derive/compile_fail")); // ECS Compile Fail Tests // Run UI tests (they do not get executed with the workspace tests) // - See crates/bevy_ecs_compile_fail_tests/README.md - commands.push( - PreparedCommand::new::( - cmd!(sh, "cargo test --target-dir ../../../target {no_fail_fast}"), - "Compiler errors of the ECS compile fail tests seem to be different than expected! Check locally and compare rust versions.", - ) - .with_subdir("crates/bevy_ecs/compile_fail"), - ); + commands.push(PreparedCommand::new::(cmd!(sh, "cargo test --target-dir ../../../target {no_fail_fast}"), "Compiler errors of the ECS compile fail tests seem to be different than expected! Check locally and compare rust versions.").with_subdir("crates/bevy_ecs/compile_fail")); // Reflect Compile Fail Tests // Run tests (they do not get executed with the workspace tests) // - See crates/bevy_reflect_compile_fail_tests/README.md - commands.push( - PreparedCommand::new::( - cmd!(sh, "cargo test --target-dir ../../../target {no_fail_fast}"), - "Compiler errors of the Reflect compile fail tests seem to be different than expected! Check locally and compare rust versions.", - ) - .with_subdir("crates/bevy_reflect/compile_fail"), - ); + commands.push(PreparedCommand::new::(cmd!(sh, "cargo test --target-dir ../../../target {no_fail_fast}"), "Compiler errors of the Reflect compile fail tests seem to be different than expected! Check locally and compare rust versions.").with_subdir("crates/bevy_reflect/compile_fail")); commands } diff --git a/tools/ci/src/commands/doc_check.rs b/tools/ci/src/commands/doc_check.rs index ef5fc502df579..5c114a632effd 100644 --- a/tools/ci/src/commands/doc_check.rs +++ b/tools/ci/src/commands/doc_check.rs @@ -9,13 +9,6 @@ pub struct DocCheckCommand {} impl Prepare for DocCheckCommand { fn prepare<'a>(&self, sh: &'a xshell::Shell, _flags: Flag) -> Vec> { - vec![PreparedCommand::new::( - cmd!( - sh, - "cargo doc --workspace --all-features --no-deps --document-private-items --keep-going" - ), - "Please fix doc warnings in output above.", - ) - .with_env_var("RUSTDOCFLAGS", "-D warnings")] + vec![PreparedCommand::new::(cmd!(sh, "cargo doc --workspace --all-features --no-deps --document-private-items --keep-going"), "Please fix doc warnings in output above.").with_env_var("RUSTDOCFLAGS", "-D warnings")] } } diff --git a/tools/example-showcase/src/main.rs b/tools/example-showcase/src/main.rs index af3f4e0f699ce..2b9653a39bd84 100644 --- a/tools/example-showcase/src/main.rs +++ b/tools/example-showcase/src/main.rs @@ -187,10 +187,7 @@ fn main() { // When the example does not automatically stop. (0, _) => { let mut file = File::create("example_showcase_config.ron").unwrap(); - file.write_all( - format!("(setup: (fixed_frame_time: Some({fixed_frame_time})), events: [({screenshot_frame}, Screenshot)])").as_bytes(), - ) - .unwrap(); + file.write_all(format!("(setup: (fixed_frame_time: Some({fixed_frame_time})), events: [({screenshot_frame}, Screenshot)])").as_bytes()).unwrap(); extra_parameters.push("--features"); extra_parameters.push("bevy_ci_testing"); } @@ -205,10 +202,7 @@ fn main() { // When the example both automatically stops and takes a screenshot. (_, _) => { let mut file = File::create("example_showcase_config.ron").unwrap(); - file.write_all( - format!("(setup: (fixed_frame_time: Some({fixed_frame_time})), events: [({screenshot_frame}, Screenshot), ({stop_frame}, AppExit)])").as_bytes(), - ) - .unwrap(); + file.write_all(format!("(setup: (fixed_frame_time: Some({fixed_frame_time})), events: [({screenshot_frame}, Screenshot), ({stop_frame}, AppExit)])").as_bytes()).unwrap(); extra_parameters.push("--features"); extra_parameters.push("bevy_ci_testing"); } @@ -217,40 +211,20 @@ fn main() { if in_ci { // Removing desktop mode as is slows down too much in CI let sh = Shell::new().unwrap(); - cmd!( - sh, - "git apply --ignore-whitespace tools/example-showcase/remove-desktop-app-mode.patch" - ) - .run() - .unwrap(); + cmd!(sh, "git apply --ignore-whitespace tools/example-showcase/remove-desktop-app-mode.patch").run().unwrap(); // Don't use automatic position as it's "random" on Windows and breaks screenshot comparison // using the cursor position let sh = Shell::new().unwrap(); - cmd!( - sh, - "git apply --ignore-whitespace tools/example-showcase/fixed-window-position.patch" - ) - .run() - .unwrap(); + cmd!(sh, "git apply --ignore-whitespace tools/example-showcase/fixed-window-position.patch").run().unwrap(); // Setting lights ClusterConfig to have less clusters by default // This is needed as the default config is too much for the CI runner - cmd!( - sh, - "git apply --ignore-whitespace tools/example-showcase/reduce-light-cluster-config.patch" - ) - .run() - .unwrap(); + cmd!(sh, "git apply --ignore-whitespace tools/example-showcase/reduce-light-cluster-config.patch").run().unwrap(); // Sending extra WindowResize events. They are not sent on CI with xvfb x11 server // This is needed for example split_screen that uses the window size to set the panels - cmd!( - sh, - "git apply --ignore-whitespace tools/example-showcase/extra-window-resized-events.patch" - ) - .run() - .unwrap(); + cmd!(sh, "git apply --ignore-whitespace tools/example-showcase/extra-window-resized-events.patch").run().unwrap(); // Don't try to get an audio output stream in CI as there isn't one // On macOS m1 runner in GitHub Actions, getting one timeouts after 15 minutes @@ -311,10 +285,7 @@ fn main() { cmd!(sh, "{exe} {args...}").run().unwrap(); } - let _ = cmd!( - sh, - "cargo build --profile {profile} --example {example} {local_extra_parameters...}" - ).run(); + let _ = cmd!(sh, "cargo build --profile {profile} --example {example} {local_extra_parameters...}").run(); let local_extra_parameters = extra_parameters .iter() .map(ToString::to_string) @@ -637,20 +608,10 @@ header_message = \"Examples ({})\" let sh = Shell::new().unwrap(); // setting a canvas by default to help with integration - cmd!( - sh, - "git apply --ignore-whitespace tools/example-showcase/window-settings-wasm.patch" - ) - .run() - .unwrap(); + cmd!(sh, "git apply --ignore-whitespace tools/example-showcase/window-settings-wasm.patch").run().unwrap(); // setting the asset folder root to the root url of this domain - cmd!( - sh, - "git apply --ignore-whitespace tools/example-showcase/asset-source-website.patch" - ) - .run() - .unwrap(); + cmd!(sh, "git apply --ignore-whitespace tools/example-showcase/asset-source-website.patch").run().unwrap(); } let work_to_do = || { @@ -675,19 +636,9 @@ header_message = \"Examples ({})\" }; if optimize_size { - cmd!( - sh, - "cargo run -p build-wasm-example -- --api {api} {example} --optimize-size {required_features...}" - ) - .run() - .unwrap(); + cmd!(sh, "cargo run -p build-wasm-example -- --api {api} {example} --optimize-size {required_features...}").run().unwrap(); } else { - cmd!( - sh, - "cargo run -p build-wasm-example -- --api {api} {example} {required_features...}" - ) - .run() - .unwrap(); + cmd!(sh, "cargo run -p build-wasm-example -- --api {api} {example} {required_features...}").run().unwrap(); } let category_path = root_path.join(&to_build.category); From a7f5d7218b54f78bb05e55557a05a32170480469 Mon Sep 17 00:00:00 2001 From: Benjamin Brienen Date: Sun, 27 Oct 2024 00:50:13 +0200 Subject: [PATCH 2/5] fix too long lines --- crates/bevy_animation/src/animation_curves.rs | 10 +++++----- crates/bevy_animation/src/gltf_curves.rs | 11 ++++++----- crates/bevy_animation/src/lib.rs | 9 ++++++--- crates/bevy_asset/src/server/mod.rs | 9 ++++++++- 4 files changed, 25 insertions(+), 14 deletions(-) diff --git a/crates/bevy_animation/src/animation_curves.rs b/crates/bevy_animation/src/animation_curves.rs index 14ee7f24fc8f8..d2c4f9920e076 100644 --- a/crates/bevy_animation/src/animation_curves.rs +++ b/crates/bevy_animation/src/animation_curves.rs @@ -153,11 +153,11 @@ use crate::{ /// .expect("Failed to create font size curve") /// ); /// -/// Here, the use of [`AnimatableKeyframeCurve`] creates a curve out of the given keyframe time-value -/// pairs, using the [`Animatable`] implementation of `f32` to interpolate between them. The -/// invocation of [`AnimatableCurve::from_curve`] with `FieldOfViewProperty` indicates that the `f32` -/// output from that curve is to be used to animate the font size of a `PerspectiveProjection` component (as -/// configured above). +/// Here, the use of [`AnimatableKeyframeCurve`] creates a curve out of the given keyframe +/// time-value pairs, using the [`Animatable`] implementation of `f32` to interpolate between them. +/// The invocation of [`AnimatableCurve::from_curve`] with `FieldOfViewProperty` indicates that +/// the `f32` output from that curve is to be used to animate the font size of a +/// `PerspectiveProjection` component (as configured above). /// /// [`AnimationClip`]: crate::AnimationClip pub trait AnimatableProperty: Reflect + TypePath { diff --git a/crates/bevy_animation/src/gltf_curves.rs b/crates/bevy_animation/src/gltf_curves.rs index 8d3b6cc248442..08095df3ce5f1 100644 --- a/crates/bevy_animation/src/gltf_curves.rs +++ b/crates/bevy_animation/src/gltf_curves.rs @@ -152,12 +152,13 @@ impl CubicRotationCurve { /// - The actual value `v_k` for the sample at time `t_k` /// - The out-tangent `b_k` for the sample at time `t_k` /// - /// For example, for a curve built from two keyframes, the inputs would have the following form: + /// For example, for a curve built from two keyframes, + /// the inputs would have the following form: /// - `times`: `[t_0, t_1]` /// - `values`: `[a_0, v_0, b_0, a_1, v_1, b_1]` /// - /// To sample quaternions from this curve, the resulting interpolated `Vec4` output is normalized - /// and interpreted as a quaternion. + /// To sample quaternions from this curve, the resulting interpolated `Vec4` output is + /// normalized and interpreted as a quaternion. pub fn new( times: impl IntoIterator, values: impl IntoIterator, @@ -300,8 +301,8 @@ where InterpolationDatum::Exact((_, v)) | InterpolationDatum::LeftTail((_, v)) | InterpolationDatum::RightTail((_, v)) => { - // Pick out the part of this that actually represents the position (instead of tangents), - // which is the middle third. + // Pick out the part of this that actually represents the + // position (instead of tangents), which is the middle third. let width = self.core.width(); Either::Left(v[width..(width * 2)].iter().copied()) } diff --git a/crates/bevy_animation/src/lib.rs b/crates/bevy_animation/src/lib.rs index e437769d41d7b..e74ac692880be 100755 --- a/crates/bevy_animation/src/lib.rs +++ b/crates/bevy_animation/src/lib.rs @@ -371,13 +371,15 @@ pub struct AnimationTarget { impl AnimationClip { #[inline] - /// [`VariableCurve`]s for each animation target. Indexed by the [`AnimationTargetId`]. + /// [`VariableCurve`]s for each animation target. + /// Indexed by the [`AnimationTargetId`]. pub fn curves(&self) -> &AnimationCurves { &self.curves } #[inline] - /// Get mutable references of [`VariableCurve`]s for each animation target. Indexed by the [`AnimationTargetId`]. + /// Get mutable references of [`VariableCurve`]s for each animation target. + /// Indexed by the [`AnimationTargetId`]. pub fn curves_mut(&mut self) -> &mut AnimationCurves { &mut self.curves } @@ -596,7 +598,8 @@ impl Default for ActiveAnimation { } impl ActiveAnimation { - /// Check if the animation has finished, based on its repetition behavior and the number of times it has repeated. + /// Check if the animation has finished, based on its repetition behavior + /// and the number of times it has repeated. /// /// Note: An animation with `RepeatAnimation::Forever` will never finish. #[inline] diff --git a/crates/bevy_asset/src/server/mod.rs b/crates/bevy_asset/src/server/mod.rs index df69ffe2a3505..9bf9541e1716c 100644 --- a/crates/bevy_asset/src/server/mod.rs +++ b/crates/bevy_asset/src/server/mod.rs @@ -918,7 +918,14 @@ impl AssetServer { let mut handles = Vec::new(); match load_folder(source.id(), path.path(), asset_reader, &server, &mut handles).await { - Ok(_) => server.send_asset_event(InternalAssetEvent::Loaded { id, loaded_asset: LoadedAsset::new_with_dependencies(LoadedFolder { handles }, None).into() }), + Ok(_) => server.send_asset_event( + InternalAssetEvent::Loaded { + id, + loaded_asset: LoadedAsset::new_with_dependencies( + LoadedFolder { handles }, None + ).into() + } + ), Err(err) => { error!("Failed to load folder. {err}"); server.send_asset_event(InternalAssetEvent::Failed { id, error: err, path }); From 35cb9791b6bca092aaac993d0601d96284afbfd4 Mon Sep 17 00:00:00 2001 From: Benjamin Brienen Date: Sun, 27 Oct 2024 00:52:06 +0200 Subject: [PATCH 3/5] feedback --- .../src/core_3d/main_opaque_pass_3d_node.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/bevy_core_pipeline/src/core_3d/main_opaque_pass_3d_node.rs b/crates/bevy_core_pipeline/src/core_3d/main_opaque_pass_3d_node.rs index 1e3a5acfe2e54..ce0a78358a472 100644 --- a/crates/bevy_core_pipeline/src/core_3d/main_opaque_pass_3d_node.rs +++ b/crates/bevy_core_pipeline/src/core_3d/main_opaque_pass_3d_node.rs @@ -37,9 +37,11 @@ impl ViewNode for MainOpaquePass3dNode { &self, graph: &mut RenderGraphContext, render_context: &mut RenderContext<'w>, - (view, camera, target, depth, skybox_pipeline, skybox_bind_group, view_uniform_offset): QueryItem<'w, Self::ViewQuery>, + query_item: QueryItem<'w, Self::ViewQuery>, world: &'w World, ) -> Result<(), NodeRunError> { + let (view, camera, target, depth, skybox_pipeline, skybox_bind_group, view_uniform_offset) = + query_item; let (Some(opaque_phases), Some(alpha_mask_phases)) = ( world.get_resource::>(), world.get_resource::>(), From 77d8f0ed9d08f6efb011e2c9d00ad741a53e9733 Mon Sep 17 00:00:00 2001 From: Benjamin Brienen Date: Sun, 27 Oct 2024 00:54:11 +0200 Subject: [PATCH 4/5] improve fmt stability --- crates/bevy_asset/src/server/mod.rs | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/crates/bevy_asset/src/server/mod.rs b/crates/bevy_asset/src/server/mod.rs index 9bf9541e1716c..ff107d26ad7a8 100644 --- a/crates/bevy_asset/src/server/mod.rs +++ b/crates/bevy_asset/src/server/mod.rs @@ -918,14 +918,11 @@ impl AssetServer { let mut handles = Vec::new(); match load_folder(source.id(), path.path(), asset_reader, &server, &mut handles).await { - Ok(_) => server.send_asset_event( - InternalAssetEvent::Loaded { - id, - loaded_asset: LoadedAsset::new_with_dependencies( - LoadedFolder { handles }, None - ).into() - } - ), + Ok(_) => { + let loaded_asset = LoadedAsset::new_with_dependencies(LoadedFolder { handles }, None).into(); + let event = InternalAssetEvent::Loaded { id, loaded_asset }; + server.send_asset_event(event) + }, Err(err) => { error!("Failed to load folder. {err}"); server.send_asset_event(InternalAssetEvent::Failed { id, error: err, path }); From 025180becffd23c4e724b2fa64baffe322f3269a Mon Sep 17 00:00:00 2001 From: Benjamin Brienen Date: Sun, 27 Oct 2024 01:07:51 +0200 Subject: [PATCH 5/5] missing ; --- crates/bevy_asset/src/server/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_asset/src/server/mod.rs b/crates/bevy_asset/src/server/mod.rs index ff107d26ad7a8..f2f0822dc779f 100644 --- a/crates/bevy_asset/src/server/mod.rs +++ b/crates/bevy_asset/src/server/mod.rs @@ -921,7 +921,7 @@ impl AssetServer { Ok(_) => { let loaded_asset = LoadedAsset::new_with_dependencies(LoadedFolder { handles }, None).into(); let event = InternalAssetEvent::Loaded { id, loaded_asset }; - server.send_asset_event(event) + server.send_asset_event(event); }, Err(err) => { error!("Failed to load folder. {err}");