diff --git a/crates/bevy_animation/src/gltf_curves.rs b/crates/bevy_animation/src/gltf_curves.rs index d5b2cbb6b984e..bfe0491764f61 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 d7375d674cccf..6f8210ae59398 100644 --- a/crates/bevy_animation/src/lib.rs +++ b/crates/bevy_animation/src/lib.rs @@ -223,13 +223,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 } @@ -508,7 +510,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_app/src/plugin_group.rs b/crates/bevy_app/src/plugin_group.rs index 312b94ad91847..e6d84355a0f0a 100644 --- a/crates/bevy_app/src/plugin_group.rs +++ b/crates/bevy_app/src/plugin_group.rs @@ -522,11 +522,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 9aee5717814b3..18b1786a8d825 100644 --- a/crates/bevy_asset/src/io/file/file_watcher.rs +++ b/crates/bevy_asset/src/io/file/file_watcher.rs @@ -184,14 +184,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 26bde8cd33b9a..cd3d259368a0c 100644 --- a/crates/bevy_asset/src/processor/mod.rs +++ b/crates/bevy_asset/src/processor/mod.rs @@ -1322,10 +1322,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); } @@ -1344,10 +1341,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 9b3edd5d8c8c9..f39e18a2eb893 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 @@ -779,12 +776,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 007dea47b0504..53d7e17a5af90 100644 --- a/crates/bevy_asset/src/server/loaders.rs +++ b/crates/bevy_asset/src/server/loaders.rs @@ -69,8 +69,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); @@ -128,8 +130,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 0270aefc66eeb..d9c681bba6af7 100644 --- a/crates/bevy_asset/src/server/mod.rs +++ b/crates/bevy_asset/src/server/mod.rs @@ -938,7 +938,7 @@ impl AssetServer { 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..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,17 +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::>(), diff --git a/crates/bevy_core_pipeline/src/dof/mod.rs b/crates/bevy_core_pipeline/src/dof/mod.rs index 06cbbe3e9d312..6901c9769f451 100644 --- a/crates/bevy_core_pipeline/src/dof/mod.rs +++ b/crates/bevy_core_pipeline/src/dof/mod.rs @@ -818,9 +818,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 559ce4e3a55bc..c86ee71fa665b 100644 --- a/crates/bevy_core_pipeline/src/taa/mod.rs +++ b/crates/bevy_core_pipeline/src/taa/mod.rs @@ -186,9 +186,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/lib.rs b/crates/bevy_ecs/macros/src/lib.rs index 0893e721aef8e..04d8314125d12 100644 --- a/crates/bevy_ecs/macros/src/lib.rs +++ b/crates/bevy_ecs/macros/src/lib.rs @@ -437,8 +437,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 972f7e33b8ae0..be23b11ecf384 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 14d80cf9aba2f..415d1f86b260f 100644 --- a/crates/bevy_ecs/src/bundle.rs +++ b/crates/bevy_ecs/src/bundle.rs @@ -1476,7 +1476,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 = @@ -1607,13 +1607,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 ab949045ef5b6..872d49249070e 100644 --- a/crates/bevy_ecs/src/lib.rs +++ b/crates/bevy_ecs/src/lib.rs @@ -245,7 +245,7 @@ mod tests { world.entity_mut(e1).take::().unwrap(), FooBundle { x: TableStored("xyz"), - y: SparseStored(123), + y: SparseStored(123) } ); @@ -296,9 +296,9 @@ mod tests { a: A(1), foo: FooBundle { x: TableStored("ghi"), - y: SparseStored(789), + y: SparseStored(789) }, - b: B(2), + b: B(2) } ); @@ -337,7 +337,7 @@ mod tests { world.entity_mut(e4).take::().unwrap(), BundleWithIgnored { c: C, - ignored: Ignored, + ignored: Ignored } ); } @@ -1806,11 +1806,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 6df9b8e2de745..19ae83ef992ab 100644 --- a/crates/bevy_ecs/src/query/fetch.rs +++ b/crates/bevy_ecs/src/query/fetch.rs @@ -492,10 +492,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(); } @@ -572,10 +569,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(); } @@ -662,10 +656,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); } @@ -756,10 +747,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); } @@ -1185,11 +1173,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); } @@ -1384,11 +1368,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); } @@ -1583,11 +1563,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); } @@ -1685,11 +1661,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 2540e7cc7abe3..cb6af5edd5cab 100644 --- a/crates/bevy_ecs/src/query/filter.rs +++ b/crates/bevy_ecs/src/query/filter.rs @@ -754,7 +754,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); } @@ -987,7 +987,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 c7303382f68d8..3a0d7d37f8d25 100644 --- a/crates/bevy_ecs/src/query/iter.rs +++ b/crates/bevy_ecs/src/query/iter.rs @@ -3075,21 +3075,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()); } } @@ -3100,21 +3088,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()); } } @@ -3128,22 +3104,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 c6c1383ceb7b9..816aebcadbb4f 100644 --- a/crates/bevy_ecs/src/query/mod.rs +++ b/crates/bevy_ecs/src/query/mod.rs @@ -294,9 +294,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 36d82772d4783..ebc78a12e9955 100644 --- a/crates/bevy_ecs/src/query/state.rs +++ b/crates/bevy_ecs/src/query/state.rs @@ -643,11 +643,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, @@ -721,10 +717,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); @@ -737,11 +731,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 e406d0555ef11..24ee36579de5e 100644 --- a/crates/bevy_ecs/src/schedule/schedule.rs +++ b/crates/bevy_ecs/src/schedule/schedule.rs @@ -1872,9 +1872,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 501c6e80a535b..28af9d2973556 100644 --- a/crates/bevy_ecs/src/storage/resource.rs +++ b/crates/bevy_ecs/src/storage/resource.rs @@ -76,12 +76,7 @@ impl ResourceData { #[cfg(feature = "std")] 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()); } // TODO: Handle no_std non-send. @@ -370,20 +365,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)), diff --git a/crates/bevy_ecs/src/system/commands/mod.rs b/crates/bevy_ecs/src/system/commands/mod.rs index aebe1d8bd70ef..6c090d11e3ede 100644 --- a/crates/bevy_ecs/src/system/commands/mod.rs +++ b/crates/bevy_ecs/src/system/commands/mod.rs @@ -172,7 +172,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, diff --git a/crates/bevy_ecs/src/system/mod.rs b/crates/bevy_ecs/src/system/mod.rs index b5020313c6656..e7a06efe08f4c 100644 --- a/crates/bevy_ecs/src/system/mod.rs +++ b/crates/bevy_ecs/src/system/mod.rs @@ -974,11 +974,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; } @@ -1002,11 +998,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 94c78c85e936e..13ced759cc38a 100644 --- a/crates/bevy_ecs/src/system/system_param.rs +++ b/crates/bevy_ecs/src/system/system_param.rs @@ -855,12 +855,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); @@ -967,13 +962,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 @@ -1518,12 +1509,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); @@ -1627,13 +1613,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/mod.rs b/crates/bevy_ecs/src/world/mod.rs index 1a7f87cd91a31..6d2b2b7cdb1df 100644 --- a/crates/bevy_ecs/src/world/mod.rs +++ b/crates/bevy_ecs/src/world/mod.rs @@ -2770,10 +2770,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 diff --git a/crates/bevy_gilrs/src/rumble.rs b/crates/bevy_gilrs/src/rumble.rs index 62c6b0dc7d639..229a0201b5a31 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 beb9c6f315f24..10f1bb44a0d0c 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 116ecb23c39a7..0c7ff8921541f 100644 --- a/crates/bevy_gltf/src/loader.rs +++ b/crates/bevy_gltf/src/loader.rs @@ -728,9 +728,7 @@ 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); @@ -1366,7 +1364,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 7772f38c0b952..b93bc66d8f25b 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 ff89a95ef218b..cbe7e7087f7c0 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 6762627e14f5f..1af931064abcb 100644 --- a/crates/bevy_input/src/gamepad.rs +++ b/crates/bevy_input/src/gamepad.rs @@ -1653,10 +1653,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] @@ -1708,10 +1705,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] @@ -1844,9 +1838,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"); } } } @@ -1869,9 +1861,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) => {} @@ -1895,7 +1885,7 @@ mod tests { deadzone_lowerbound: -0.05, deadzone_upperbound: 0.05, livezone_upperbound: 0.95, - threshold: 0.001, + threshold: 0.001 }) ); assert_eq!( @@ -1938,7 +1928,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 29ecc831097ea..8a077f3cfa38b 100644 --- a/crates/bevy_log/src/lib.rs +++ b/crates/bevy_log/src/lib.rs @@ -367,9 +367,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 c5be831a86f86..8ca6200021c02 100644 --- a/crates/bevy_math/src/bounding/bounded2d/mod.rs +++ b/crates/bevy_math/src/bounding/bounded2d/mod.rs @@ -422,15 +422,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 c4f3c979f67cb..30c54688a72a9 100644 --- a/crates/bevy_math/src/bounding/bounded3d/mod.rs +++ b/crates/bevy_math/src/bounding/bounded3d/mod.rs @@ -428,15 +428,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/rotation2d.rs b/crates/bevy_math/src/rotation2d.rs index 5b0bc816bc5ca..20ebe28ff84b3 100644 --- a/crates/bevy_math/src/rotation2d.rs +++ b/crates/bevy_math/src/rotation2d.rs @@ -660,7 +660,7 @@ mod tests { // Valid assert!(Rot2 { sin: 10.0, - cos: 5.0, + cos: 5.0 } .try_normalize() .is_some()); @@ -668,7 +668,7 @@ mod tests { // NaN assert!(Rot2 { sin: f32::NAN, - cos: 5.0, + cos: 5.0 } .try_normalize() .is_none()); @@ -679,7 +679,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 f68c2d6f74321..379300e345c34 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 f643cc6674240..69cc413a27c3c 100644 --- a/crates/bevy_mesh/src/mesh.rs +++ b/crates/bevy_mesh/src/mesh.rs @@ -226,10 +226,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 @@ -433,8 +430,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 { @@ -639,10 +638,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 25fe23b9536c6..d37fb32e85dc0 100644 --- a/crates/bevy_pbr/src/cluster/mod.rs +++ b/crates/bevy_pbr/src/cluster/mod.rs @@ -285,9 +285,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 4cae0d50d19f5..b616000368b76 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/light.rs b/crates/bevy_pbr/src/render/light.rs index cd2c37f345ca0..ad56be2d0a9bf 100644 --- a/crates/bevy_pbr/src/render/light.rs +++ b/crates/bevy_pbr/src/render/light.rs @@ -776,10 +776,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; } @@ -1287,8 +1284,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 mut first = false; diff --git a/crates/bevy_pbr/src/ssao/mod.rs b/crates/bevy_pbr/src/ssao/mod.rs index fd47511da5d16..00b41147999c5 100644 --- a/crates/bevy_pbr/src/ssao/mod.rs +++ b/crates/bevy_pbr/src/ssao/mod.rs @@ -468,12 +468,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, @@ -531,10 +529,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 bdb94db06bc7e..8c3ea497ce916 100644 --- a/crates/bevy_reflect/derive/src/container_attributes.rs +++ b/crates/bevy_reflect/derive/src/container_attributes.rs @@ -257,9 +257,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 e739c91ebb912..868296d5c1611 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 e8fdadb03e368..74a0332de2887 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 da8254d149339..bc9abdd034bb0 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 24c452f2f1249..14cadb9fe5fab 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::shared().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 3397df50ddc92..2448f471d2f53 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 d5d16715c09c4..4c42f0c453339 100644 --- a/crates/bevy_reflect/src/kind.rs +++ b/crates/bevy_reflect/src/kind.rs @@ -145,10 +145,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() }), } } }; @@ -158,10 +155,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 c6e5ba0b4515d..ee410c9c6c404 100644 --- a/crates/bevy_reflect/src/lib.rs +++ b/crates/bevy_reflect/src/lib.rs @@ -1991,10 +1991,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."] @@ -2003,10 +2000,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)] @@ -2922,7 +2916,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 ); @@ -2954,7 +2948,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, ); @@ -2989,7 +2983,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 e5205e90afa38..f5e8ce51f81e6 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 3fe0504cf7408..80dd938f528d8 100644 --- a/crates/bevy_reflect/src/path/mod.rs +++ b/crates/bevy_reflect/src/path/mod.rs @@ -765,7 +765,7 @@ mod tests { ReflectPathError::InvalidAccess(AccessError { kind: AccessErrorKind::MissingField(ReflectKind::Struct), access: access_field("notreal"), - offset: Some(2), + offset: Some(2) }) ); @@ -774,12 +774,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 bc48fe9c01be0..34a7156658885 100644 --- a/crates/bevy_reflect/src/path/parse.rs +++ b/crates/bevy_reflect/src/path/parse.rs @@ -182,7 +182,7 @@ mod test { Err(ReflectPathError::ParseError { error: ParseError(Error::ExpectedIdent(Token::Dot)), offset: 2, - path: "x..", + path: "x.." }), ); assert!(matches!( @@ -190,7 +190,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 1c20eaad07abc..88151f0963ed1 100644 --- a/crates/bevy_reflect/src/serde/de/deserializer.rs +++ b/crates/bevy_reflect/src/serde/de/deserializer.rs @@ -511,9 +511,7 @@ impl<'de, P: ReflectDeserializerProcessor> DeserializeSeed<'de> } 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 e55897166e926..ca8dd0097aecc 100644 --- a/crates/bevy_reflect/src/serde/de/mod.rs +++ b/crates/bevy_reflect/src/serde/de/mod.rs @@ -790,13 +790,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!( @@ -842,12 +836,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 53afacde37430..cb3a3b47e5948 100644 --- a/crates/bevy_reflect/src/serde/ser/mod.rs +++ b/crates/bevy_reflect/src/serde/ser/mod.rs @@ -436,13 +436,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, @@ -462,19 +456,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())); } #[test] @@ -666,10 +650,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!( @@ -714,12 +695,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 0d46d9f9df771..c7b6ada4c4d3b 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 4ccac40508a43..7b143049fae9f 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 609c66d1856ac..9c639f94773f7 100644 --- a/crates/bevy_reflect/src/type_registry.rs +++ b/crates/bevy_reflect/src/type_registry.rs @@ -268,13 +268,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()); } @@ -691,16 +685,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 96176e071ca6c..c9047fbcaadf5 100644 --- a/crates/bevy_render/macros/src/as_bind_group.rs +++ b/crates/bevy_render/macros/src/as_bind_group.rs @@ -91,7 +91,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(), @@ -194,26 +194,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))); } }, } @@ -409,15 +400,12 @@ pub fn derive_as_bind_group(ast: syn::DeriveInput) -> Result { format!("{:?}", #expected_samplers), )); } - 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, @@ -490,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(), @@ -536,7 +524,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(), @@ -816,10 +804,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( @@ -1040,10 +1019,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/camera/camera.rs b/crates/bevy_render/src/camera/camera.rs index e7c853b843eb9..94c6548972c6e 100644 --- a/crates/bevy_render/src/camera/camera.rs +++ b/crates/bevy_render/src/camera/camera.rs @@ -1271,9 +1271,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 fd3880c1db6bf..eb29e142a1ada 100644 --- a/crates/bevy_render/src/camera/projection.rs +++ b/crates/bevy_render/src/camera/projection.rs @@ -227,9 +227,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/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 220f5bd326af5..cfc1ed24005f2 100644 --- a/crates/bevy_render/src/render_resource/pipeline_cache.rs +++ b/crates/bevy_render/src/render_resource/pipeline_cache.rs @@ -686,17 +686,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/sync_world.rs b/crates/bevy_render/src/sync_world.rs index 15fb582fb7682..ea3726f6f8bf3 100644 --- a/crates/bevy_render/src/sync_world.rs +++ b/crates/bevy_render/src/sync_world.rs @@ -243,7 +243,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/serde.rs b/crates/bevy_scene/src/serde.rs index a59fa67692ca1..aee3955aa469c 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/texture_slice/slicer.rs b/crates/bevy_sprite/src/texture_slice/slicer.rs index 310be429796a5..aafa368a3bc89 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 b00c60de53738..c4c869ef10636 100644 --- a/crates/bevy_state/src/app.rs +++ b/crates/bevy_state/src/app.rs @@ -101,9 +101,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 { @@ -127,9 +125,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, @@ -160,9 +156,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() @@ -191,9 +185,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 9ac844c099a75..9d46334959fbd 100644 --- a/crates/bevy_text/src/text.rs +++ b/crates/bevy_text/src/text.rs @@ -458,7 +458,9 @@ pub fn detect_text_needs_rerender( if has_text_block { 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 { @@ -489,7 +491,9 @@ pub fn detect_text_needs_rerender( if !has_span { 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 f41fc50bd3a14..0ee274876be14 100644 --- a/crates/bevy_transform/src/systems.rs +++ b/crates/bevy_transform/src/systems.rs @@ -60,39 +60,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. @@ -163,10 +152,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/mod.rs b/crates/bevy_ui/src/layout/mod.rs index a228bf82646aa..2ffa488cd319c 100644 --- a/crates/bevy_ui/src/layout/mod.rs +++ b/crates/bevy_ui/src/layout/mod.rs @@ -193,9 +193,8 @@ pub fn ui_layout_system( } } } - } - ); + }); // 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 392ee86d115c9..988bd493bf613 100644 --- a/crates/bevy_ui/src/ui_node.rs +++ b/crates/bevy_ui/src/ui_node.rs @@ -2676,9 +2676,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 55fb34373765f..e734f9e9613c7 100644 --- a/crates/bevy_ui/src/widget/image.rs +++ b/crates/bevy_ui/src/widget/image.rs @@ -258,7 +258,6 @@ pub fn update_image_content_size_system( windows: Query<&Window, With>, ui_scale: Res, textures: Res>, - atlases: Res>, mut query: Query<(&mut ContentSize, Ref, &mut ImageNodeSize), UpdateImageFilter>, ) { diff --git a/crates/bevy_winit/src/cursor.rs b/crates/bevy_winit/src/cursor.rs index 6a121dae2276c..8336214bfdc35 100644 --- a/crates/bevy_winit/src/cursor.rs +++ b/crates/bevy_winit/src/cursor.rs @@ -124,9 +124,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 4a8927db0754e..f92cfdf4b069e 100644 --- a/crates/bevy_winit/src/state.rs +++ b/crates/bevy_winit/src/state.rs @@ -511,8 +511,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 79fece61c8e36..cc23b380865ba 100644 --- a/examples/3d/auto_exposure.rs +++ b/examples/3d/auto_exposure.rs @@ -129,14 +129,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 b9f4343102898..0a6d39eddb7cb 100644 --- a/examples/3d/blend_modes.rs +++ b/examples/3d/blend_modes.rs @@ -166,15 +166,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/app/log_layers.rs b/examples/app/log_layers.rs index 36fdb6c4e58e3..a226d64063b9d 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 d88dbc7e46225..3c1def885e2ed 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 48cf17c767953..dd571629e8187 100644 --- a/examples/ui/display_and_visibility.rs +++ b/examples/ui/display_and_visibility.rs @@ -83,87 +83,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 119230c808073..dc493ccdbe8b5 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 16a41328935f5..036259cac2203 100644 --- a/examples/ui/scroll.rs +++ b/examples/ui/scroll.rs @@ -27,23 +27,24 @@ 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(( @@ -98,25 +99,24 @@ fn setup(mut commands: Commands, asset_server: Res) { }); } }); + } }); + }); - // 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| { @@ -178,13 +178,18 @@ fn setup(mut commands: Commands, asset_server: Res) { }); }); - // 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| { @@ -246,13 +251,19 @@ fn setup(mut commands: Commands, asset_server: Res) { }); }); - // 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| { @@ -323,6 +334,7 @@ fn setup(mut commands: Commands, asset_server: Res) { }); }); }); + }); } /// 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 b53450ba22bbf..d3754d1d73fbc 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 6e5864b13da95..99a60a3254962 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.push(PreparedCommand::new::( cmd!( 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 49afb15c2048c..c7598aa32812b 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);