diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6fca335bdd670..02da3c27436d5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -263,6 +263,7 @@ jobs: run: cargo check --target wasm32-unknown-unknown build-wasm-atomics: + if: ${{ false }} # Disabled temporarily due to https://github.com/rust-lang/rust/issues/145101 runs-on: ubuntu-latest timeout-minutes: 30 needs: build diff --git a/Cargo.toml b/Cargo.toml index e33ac34bcf09c..33f4c77164034 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -73,6 +73,8 @@ allow_attributes = "warn" allow_attributes_without_reason = "warn" [workspace.lints.rust] +# Strictly temporary until encase fixes dead code generation from ShaderType macros +dead_code = "allow" missing_docs = "warn" unexpected_cfgs = { level = "warn", check-cfg = ['cfg(docsrs_dep)'] } unsafe_code = "deny" @@ -118,6 +120,8 @@ allow_attributes = "warn" allow_attributes_without_reason = "warn" [lints.rust] +# Strictly temporary until encase fixes dead code generation from ShaderType macros +dead_code = "allow" missing_docs = "warn" unexpected_cfgs = { level = "warn", check-cfg = ['cfg(docsrs_dep)'] } unsafe_code = "deny" diff --git a/crates/bevy_animation/src/animation_curves.rs b/crates/bevy_animation/src/animation_curves.rs index 782daf0f552bc..0e1d5866df41b 100644 --- a/crates/bevy_animation/src/animation_curves.rs +++ b/crates/bevy_animation/src/animation_curves.rs @@ -199,7 +199,7 @@ pub trait AnimatableProperty: Send + Sync + 'static { /// The [`EvaluatorId`] used to look up the [`AnimationCurveEvaluator`] for this [`AnimatableProperty`]. /// For a given animated property, this ID should always be the same to allow things like animation blending to occur. - fn evaluator_id(&self) -> EvaluatorId; + fn evaluator_id(&self) -> EvaluatorId<'_>; } /// A [`Component`] field that can be animated, defined by a function that reads the component and returns @@ -236,7 +236,7 @@ where Ok((self.func)(c.into_inner())) } - fn evaluator_id(&self) -> EvaluatorId { + fn evaluator_id(&self) -> EvaluatorId<'_> { EvaluatorId::ComponentField(&self.evaluator_id) } } @@ -357,7 +357,7 @@ where self.curve.domain() } - fn evaluator_id(&self) -> EvaluatorId { + fn evaluator_id(&self) -> EvaluatorId<'_> { self.property.evaluator_id() } @@ -476,7 +476,7 @@ where self.0.domain() } - fn evaluator_id(&self) -> EvaluatorId { + fn evaluator_id(&self) -> EvaluatorId<'_> { EvaluatorId::Type(TypeId::of::()) } @@ -768,7 +768,7 @@ pub trait AnimationCurve: Debug + Send + Sync + 'static { /// /// This must match the type returned by [`Self::create_evaluator`]. It must /// be a single type that doesn't depend on the type of the curve. - fn evaluator_id(&self) -> EvaluatorId; + fn evaluator_id(&self) -> EvaluatorId<'_>; /// Returns a newly-instantiated [`AnimationCurveEvaluator`] for use with /// this curve. diff --git a/crates/bevy_animation/src/lib.rs b/crates/bevy_animation/src/lib.rs index 67e5cde0466a9..3c9c7d9e4c3f1 100644 --- a/crates/bevy_animation/src/lib.rs +++ b/crates/bevy_animation/src/lib.rs @@ -772,7 +772,7 @@ struct CurrentEvaluators { } impl CurrentEvaluators { - pub(crate) fn keys(&self) -> impl Iterator { + pub(crate) fn keys(&self) -> impl Iterator> { self.component_properties .keys() .map(EvaluatorId::ComponentField) @@ -1007,12 +1007,11 @@ pub fn advance_animations( if let Some(active_animation) = active_animations.get_mut(&node_index) { // Tick the animation if necessary. - if !active_animation.paused { - if let AnimationNodeType::Clip(ref clip_handle) = node.node_type { - if let Some(clip) = animation_clips.get(clip_handle) { - active_animation.update(delta_seconds, clip.duration); - } - } + if !active_animation.paused + && let AnimationNodeType::Clip(ref clip_handle) = node.node_type + && let Some(clip) = animation_clips.get(clip_handle) + { + active_animation.update(delta_seconds, clip.duration); } } } @@ -1158,21 +1157,20 @@ pub fn animate_targets( AnimationEventTarget::Node(target_id), clip, active_animation, - ) { - if !triggered_events.is_empty() { - par_commands.command_scope(move |mut commands| { - for TimedAnimationEvent { time, event } in - triggered_events.iter() - { - event.trigger( - &mut commands, - entity, - *time, - active_animation.weight, - ); - } - }); - } + ) && !triggered_events.is_empty() + { + par_commands.command_scope(move |mut commands| { + for TimedAnimationEvent { time, event } in + triggered_events.iter() + { + event.trigger( + &mut commands, + entity, + *time, + active_animation.weight, + ); + } + }); } } @@ -1462,7 +1460,7 @@ impl<'a> TriggeredEvents<'a> { self.lower.is_empty() && self.upper.is_empty() } - fn iter(&self) -> TriggeredEventsIter { + fn iter(&self) -> TriggeredEventsIter<'_> { match self.direction { TriggeredEventsDir::Forward => TriggeredEventsIter::Forward(self.lower.iter()), TriggeredEventsDir::Reverse => TriggeredEventsIter::Reverse(self.lower.iter().rev()), diff --git a/crates/bevy_animation/src/transition.rs b/crates/bevy_animation/src/transition.rs index 494855970441d..42a4addfae6ec 100644 --- a/crates/bevy_animation/src/transition.rs +++ b/crates/bevy_animation/src/transition.rs @@ -81,16 +81,15 @@ impl AnimationTransitions { new_animation: AnimationNodeIndex, transition_duration: Duration, ) -> &'p mut ActiveAnimation { - if let Some(old_animation_index) = self.main_animation.replace(new_animation) { - if let Some(old_animation) = player.animation_mut(old_animation_index) { - if !old_animation.is_paused() { - self.transitions.push(AnimationTransition { - current_weight: old_animation.weight, - weight_decline_per_sec: 1.0 / transition_duration.as_secs_f32(), - animation: old_animation_index, - }); - } - } + if let Some(old_animation_index) = self.main_animation.replace(new_animation) + && let Some(old_animation) = player.animation_mut(old_animation_index) + && !old_animation.is_paused() + { + self.transitions.push(AnimationTransition { + current_weight: old_animation.weight, + weight_decline_per_sec: 1.0 / transition_duration.as_secs_f32(), + animation: old_animation_index, + }); } // If already transitioning away from this animation, cancel the transition. @@ -135,10 +134,10 @@ pub fn advance_transitions( remaining_weight -= animation.weight; } - if let Some(main_animation_index) = animation_transitions.main_animation { - if let Some(ref mut animation) = player.animation_mut(main_animation_index) { - animation.weight = remaining_weight; - } + if let Some(main_animation_index) = animation_transitions.main_animation + && let Some(ref mut animation) = player.animation_mut(main_animation_index) + { + animation.weight = remaining_weight; } } } diff --git a/crates/bevy_anti_aliasing/src/taa/mod.rs b/crates/bevy_anti_aliasing/src/taa/mod.rs index 3055160a820c9..d32b28251bc23 100644 --- a/crates/bevy_anti_aliasing/src/taa/mod.rs +++ b/crates/bevy_anti_aliasing/src/taa/mod.rs @@ -350,16 +350,17 @@ fn extract_taa_settings(mut commands: Commands, mut main_world: ResMut, )>(); - for (entity, camera, camera_projection, mut taa_settings) in - cameras_3d.iter_mut(&mut main_world) - { + for (entity, camera, camera_projection, taa_settings) in cameras_3d.iter_mut(&mut main_world) { let has_perspective_projection = matches!(camera_projection, Projection::Perspective(_)); let mut entity_commands = commands .get_entity(entity) .expect("Camera entity wasn't synced."); - if taa_settings.is_some() && camera.is_active && has_perspective_projection { - entity_commands.insert(taa_settings.as_deref().unwrap().clone()); - taa_settings.as_mut().unwrap().reset = false; + if let Some(mut taa_settings) = taa_settings + && camera.is_active + && has_perspective_projection + { + entity_commands.insert(taa_settings.clone()); + taa_settings.reset = false; } else { entity_commands.remove::<( TemporalAntiAliasing, diff --git a/crates/bevy_app/src/plugin_group.rs b/crates/bevy_app/src/plugin_group.rs index 60897d5453066..ee1c8cb44b3cc 100644 --- a/crates/bevy_app/src/plugin_group.rs +++ b/crates/bevy_app/src/plugin_group.rs @@ -517,18 +517,18 @@ impl PluginGroupBuilder { #[track_caller] pub fn finish(mut self, app: &mut App) { for ty in &self.order { - if let Some(entry) = self.plugins.remove(ty) { - if entry.enabled { - debug!("added plugin: {}", entry.plugin.name()); - 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 - ); - } + if let Some(entry) = self.plugins.remove(ty) + && entry.enabled + { + debug!("added plugin: {}", entry.plugin.name()); + 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 + ); } } } diff --git a/crates/bevy_asset/src/io/embedded/embedded_watcher.rs b/crates/bevy_asset/src/io/embedded/embedded_watcher.rs index 06a0791a501c0..b7773cb404e2c 100644 --- a/crates/bevy_asset/src/io/embedded/embedded_watcher.rs +++ b/crates/bevy_asset/src/io/embedded/embedded_watcher.rs @@ -73,15 +73,15 @@ impl FilesystemEventHandler for EmbeddedEventHandler { fn handle(&mut self, absolute_paths: &[PathBuf], event: AssetSourceEvent) { if self.last_event.as_ref() != Some(&event) { - if let AssetSourceEvent::ModifiedAsset(path) = &event { - if let Ok(file) = File::open(&absolute_paths[0]) { - let mut reader = BufReader::new(file); - let mut buffer = Vec::new(); + if let AssetSourceEvent::ModifiedAsset(path) = &event + && let Ok(file) = File::open(&absolute_paths[0]) + { + let mut reader = BufReader::new(file); + let mut buffer = Vec::new(); - // Read file into vector. - if reader.read_to_end(&mut buffer).is_ok() { - self.dir.insert_asset(path, buffer); - } + // Read file into vector. + if reader.read_to_end(&mut buffer).is_ok() { + self.dir.insert_asset(path, buffer); } } self.last_event = Some(event.clone()); diff --git a/crates/bevy_asset/src/io/file/file_asset.rs b/crates/bevy_asset/src/io/file/file_asset.rs index 58ae546e7f260..290891440c4e1 100644 --- a/crates/bevy_asset/src/io/file/file_asset.rs +++ b/crates/bevy_asset/src/io/file/file_asset.rs @@ -69,10 +69,10 @@ impl AssetReader for FileAssetReader { f.ok().and_then(|dir_entry| { let path = dir_entry.path(); // filter out meta files as they are not considered assets - if let Some(ext) = path.extension().and_then(|e| e.to_str()) { - if ext.eq_ignore_ascii_case("meta") { - return None; - } + if let Some(ext) = path.extension().and_then(|e| e.to_str()) + && ext.eq_ignore_ascii_case("meta") + { + return None; } // filter out hidden files. they are not listed by default but are directly targetable if path diff --git a/crates/bevy_asset/src/io/file/mod.rs b/crates/bevy_asset/src/io/file/mod.rs index 96c43072e8f47..0ab9267fff679 100644 --- a/crates/bevy_asset/src/io/file/mod.rs +++ b/crates/bevy_asset/src/io/file/mod.rs @@ -75,14 +75,12 @@ impl FileAssetWriter { /// watching for changes. pub fn new + core::fmt::Debug>(path: P, create_root: bool) -> Self { let root_path = get_base_path().join(path.as_ref()); - if create_root { - if let Err(e) = std::fs::create_dir_all(&root_path) { - error!( - "Failed to create root directory {} for file asset writer: {}", - root_path.display(), - e - ); - } + if create_root && let Err(e) = std::fs::create_dir_all(&root_path) { + error!( + "Failed to create root directory {} for file asset writer: {}", + root_path.display(), + e + ); } Self { root_path } } diff --git a/crates/bevy_asset/src/lib.rs b/crates/bevy_asset/src/lib.rs index 3c939b07cf8b0..2bcb6b136dd80 100644 --- a/crates/bevy_asset/src/lib.rs +++ b/crates/bevy_asset/src/lib.rs @@ -1629,37 +1629,37 @@ mod tests { let loaded_folders = world.resource::>(); let cool_texts = world.resource::>(); for event in reader.read(events) { - if let AssetEvent::LoadedWithDependencies { id } = event { - if *id == handle.id() { - let loaded_folder = loaded_folders.get(&handle).unwrap(); - let a_handle: Handle = - asset_server.get_handle("text/a.cool.ron").unwrap(); - let c_handle: Handle = - asset_server.get_handle("text/c.cool.ron").unwrap(); - - let mut found_a = false; - let mut found_c = false; - for asset_handle in &loaded_folder.handles { - if asset_handle.id() == a_handle.id().untyped() { - found_a = true; - } else if asset_handle.id() == c_handle.id().untyped() { - found_c = true; - } + if let AssetEvent::LoadedWithDependencies { id } = event + && *id == handle.id() + { + let loaded_folder = loaded_folders.get(&handle).unwrap(); + let a_handle: Handle = + asset_server.get_handle("text/a.cool.ron").unwrap(); + let c_handle: Handle = + asset_server.get_handle("text/c.cool.ron").unwrap(); + + let mut found_a = false; + let mut found_c = false; + for asset_handle in &loaded_folder.handles { + if asset_handle.id() == a_handle.id().untyped() { + found_a = true; + } else if asset_handle.id() == c_handle.id().untyped() { + found_c = true; } - assert!(found_a); - assert!(found_c); - assert_eq!(loaded_folder.handles.len(), 2); + } + assert!(found_a); + assert!(found_c); + assert_eq!(loaded_folder.handles.len(), 2); - let a_text = cool_texts.get(&a_handle).unwrap(); - let b_text = cool_texts.get(&a_text.dependencies[0]).unwrap(); - let c_text = cool_texts.get(&c_handle).unwrap(); + let a_text = cool_texts.get(&a_handle).unwrap(); + let b_text = cool_texts.get(&a_text.dependencies[0]).unwrap(); + let c_text = cool_texts.get(&c_handle).unwrap(); - assert_eq!("a", a_text.text); - assert_eq!("b", b_text.text); - assert_eq!("c", c_text.text); + assert_eq!("a", a_text.text); + assert_eq!("b", b_text.text); + assert_eq!("c", c_text.text); - return Some(()); - } + return Some(()); } } None diff --git a/crates/bevy_asset/src/loader.rs b/crates/bevy_asset/src/loader.rs index 24405f0657d5e..8065d32b53bc5 100644 --- a/crates/bevy_asset/src/loader.rs +++ b/crates/bevy_asset/src/loader.rs @@ -371,7 +371,7 @@ impl<'a> LoadContext<'a> { /// load_context.add_loaded_labeled_asset(label, loaded_asset); /// } /// ``` - pub fn begin_labeled_asset(&self) -> LoadContext { + pub fn begin_labeled_asset(&self) -> LoadContext<'_> { LoadContext::new( self.asset_server, self.asset_path.clone(), diff --git a/crates/bevy_asset/src/path.rs b/crates/bevy_asset/src/path.rs index ed189a683b35d..d4e8b9a0370af 100644 --- a/crates/bevy_asset/src/path.rs +++ b/crates/bevy_asset/src/path.rs @@ -246,7 +246,7 @@ impl<'a> AssetPath<'a> { /// Gets the "asset source", if one was defined. If none was defined, the default source /// will be used. #[inline] - pub fn source(&self) -> &AssetSourceId { + pub fn source(&self) -> &AssetSourceId<'_> { &self.source } diff --git a/crates/bevy_asset/src/processor/mod.rs b/crates/bevy_asset/src/processor/mod.rs index a239d66a9b59a..7b3d36e686b02 100644 --- a/crates/bevy_asset/src/processor/mod.rs +++ b/crates/bevy_asset/src/processor/mod.rs @@ -642,11 +642,12 @@ impl AssetProcessor { )) .await?; } - if !contains_files && path.parent().is_some() { - if let Some(writer) = clean_empty_folders_writer { - // it is ok for this to fail as it is just a cleanup job. - let _ = writer.remove_empty_directory(&path).await; - } + if !contains_files + && path.parent().is_some() + && let Some(writer) = clean_empty_folders_writer + { + // it is ok for this to fail as it is just a cleanup job. + let _ = writer.remove_empty_directory(&path).await; } Ok(contains_files) } else { @@ -892,23 +893,22 @@ impl AssetProcessor { if let Some(current_processed_info) = infos .get(asset_path) .and_then(|i| i.processed_info.as_ref()) + && current_processed_info.hash == new_hash { - if current_processed_info.hash == new_hash { - let mut dependency_changed = false; - for current_dep_info in ¤t_processed_info.process_dependencies { - let live_hash = infos - .get(¤t_dep_info.path) - .and_then(|i| i.processed_info.as_ref()) - .map(|i| i.full_hash); - if live_hash != Some(current_dep_info.full_hash) { - dependency_changed = true; - break; - } - } - if !dependency_changed { - return Ok(ProcessResult::SkippedNotChanged); + let mut dependency_changed = false; + for current_dep_info in ¤t_processed_info.process_dependencies { + let live_hash = infos + .get(¤t_dep_info.path) + .and_then(|i| i.processed_info.as_ref()) + .map(|i| i.full_hash); + if live_hash != Some(current_dep_info.full_hash) { + dependency_changed = true; + break; } } + if !dependency_changed { + return Ok(ProcessResult::SkippedNotChanged); + } } } // Note: this lock must remain alive until all processed asset and meta writes have finished (or failed) diff --git a/crates/bevy_asset/src/saver.rs b/crates/bevy_asset/src/saver.rs index c8b96012eea72..0f3e3987f264a 100644 --- a/crates/bevy_asset/src/saver.rs +++ b/crates/bevy_asset/src/saver.rs @@ -114,7 +114,7 @@ impl<'a, A: Asset> SavedAsset<'a, A> { } /// Returns the labeled asset, if it exists and matches this type. - pub fn get_labeled(&self, label: &Q) -> Option> + pub fn get_labeled(&self, label: &Q) -> Option> where CowArc<'static, str>: Borrow, Q: ?Sized + Hash + Eq, diff --git a/crates/bevy_asset/src/server/info.rs b/crates/bevy_asset/src/server/info.rs index 1b3bb3cb65d68..3651cd2efebf2 100644 --- a/crates/bevy_asset/src/server/info.rs +++ b/crates/bevy_asset/src/server/info.rs @@ -133,13 +133,11 @@ impl AssetInfos { .get(&type_id) .ok_or(MissingHandleProviderError(type_id))?; - if watching_for_changes { - if let Some(path) = &path { - let mut without_label = path.to_owned(); - if let Some(label) = without_label.take_label() { - let labels = living_labeled_assets.entry(without_label).or_default(); - labels.insert(label.as_ref().into()); - } + if watching_for_changes && let Some(path) = &path { + let mut without_label = path.to_owned(); + if let Some(label) = without_label.take_label() { + let labels = living_labeled_assets.entry(without_label).or_default(); + labels.insert(label.as_ref().into()); } } diff --git a/crates/bevy_asset/src/server/loaders.rs b/crates/bevy_asset/src/server/loaders.rs index 08384e9efeaa4..9c13c861bd986 100644 --- a/crates/bevy_asset/src/server/loaders.rs +++ b/crates/bevy_asset/src/server/loaders.rs @@ -59,15 +59,13 @@ impl AssetLoaders { .entry((*extension).into()) .or_default(); - if !list.is_empty() { - if let Some(existing_loaders_for_type_id) = existing_loaders_for_type_id { - if list - .iter() - .any(|index| existing_loaders_for_type_id.contains(index)) - { - duplicate_extensions.push(extension); - } - } + if !list.is_empty() + && let Some(existing_loaders_for_type_id) = existing_loaders_for_type_id + && list + .iter() + .any(|index| existing_loaders_for_type_id.contains(index)) + { + duplicate_extensions.push(extension); } list.push(loader_index); @@ -125,15 +123,13 @@ impl AssetLoaders { .entry((*extension).into()) .or_default(); - if !list.is_empty() { - if let Some(existing_loaders_for_type_id) = existing_loaders_for_type_id { - if list - .iter() - .any(|index| existing_loaders_for_type_id.contains(index)) - { - duplicate_extensions.push(extension); - } - } + if !list.is_empty() + && let Some(existing_loaders_for_type_id) = existing_loaders_for_type_id + && list + .iter() + .any(|index| existing_loaders_for_type_id.contains(index)) + { + duplicate_extensions.push(extension); } list.push(loader_index); @@ -218,10 +214,10 @@ impl AssetLoaders { }; // Try the provided extension - if let Some(extension) = extension { - if let Some(&index) = try_extension(extension) { - return self.get_by_index(index); - } + if let Some(extension) = extension + && let Some(&index) = try_extension(extension) + { + return self.get_by_index(index); } // Try extracting the extension from the path diff --git a/crates/bevy_asset/src/server/mod.rs b/crates/bevy_asset/src/server/mod.rs index 69dc8428da87d..641952a67150e 100644 --- a/crates/bevy_asset/src/server/mod.rs +++ b/crates/bevy_asset/src/server/mod.rs @@ -846,10 +846,11 @@ impl AssetServer { } } - if !reloaded && server.data.infos.read().should_reload(&path) { - if let Err(err) = server.load_internal(None, path, true, None).await { - error!("{}", err); - } + if !reloaded + && server.data.infos.read().should_reload(&path) + && let Err(err) = server.load_internal(None, path, true, None).await + { + error!("{}", err); } }) .detach(); @@ -1272,7 +1273,7 @@ impl AssetServer { } /// Returns the path for the given `id`, if it has one. - pub fn get_path(&self, id: impl Into) -> Option { + pub fn get_path(&self, id: impl Into) -> Option> { let infos = self.data.infos.read(); let info = infos.get(id.into())?; Some(info.path.as_ref()?.clone()) diff --git a/crates/bevy_asset/src/transformer.rs b/crates/bevy_asset/src/transformer.rs index 802e3aeaa7eff..f80f44511ab4c 100644 --- a/crates/bevy_asset/src/transformer.rs +++ b/crates/bevy_asset/src/transformer.rs @@ -87,7 +87,7 @@ impl TransformedAsset { &mut self.value } /// Returns the labeled asset, if it exists and matches this type. - pub fn get_labeled(&mut self, label: &Q) -> Option> + pub fn get_labeled(&mut self, label: &Q) -> Option> where CowArc<'static, str>: Borrow, Q: ?Sized + Hash + Eq, @@ -187,7 +187,7 @@ impl<'a, A: Asset> TransformedSubAsset<'a, A> { self.value } /// Returns the labeled asset, if it exists and matches this type. - pub fn get_labeled(&mut self, label: &Q) -> Option> + pub fn get_labeled(&mut self, label: &Q) -> Option> where CowArc<'static, str>: Borrow, Q: ?Sized + Hash + Eq, diff --git a/crates/bevy_camera/src/visibility/mod.rs b/crates/bevy_camera/src/visibility/mod.rs index 275715cb26b33..f059beab829ef 100644 --- a/crates/bevy_camera/src/visibility/mod.rs +++ b/crates/bevy_camera/src/visibility/mod.rs @@ -384,10 +384,10 @@ pub fn calculate_bounds( without_aabb: Query<(Entity, &Mesh3d), (Without, Without)>, ) { for (entity, mesh_handle) in &without_aabb { - if let Some(mesh) = meshes.get(mesh_handle) { - if let Some(aabb) = mesh.compute_aabb() { - commands.entity(entity).try_insert(aabb); - } + if let Some(mesh) = meshes.get(mesh_handle) + && let Some(aabb) = mesh.compute_aabb() + { + commands.entity(entity).try_insert(aabb); } } } @@ -580,21 +580,22 @@ pub fn check_visibility( } // If we have an aabb, do frustum culling - if !no_frustum_culling && !no_cpu_culling { - if let Some(model_aabb) = maybe_model_aabb { - let world_from_local = transform.affine(); - let model_sphere = Sphere { - center: world_from_local.transform_point3a(model_aabb.center), - radius: transform.radius_vec3a(model_aabb.half_extents), - }; - // Do quick sphere-based frustum culling - if !frustum.intersects_sphere(&model_sphere, false) { - return; - } - // Do aabb-based frustum culling - if !frustum.intersects_obb(model_aabb, &world_from_local, true, false) { - return; - } + if !no_frustum_culling + && !no_cpu_culling + && let Some(model_aabb) = maybe_model_aabb + { + let world_from_local = transform.affine(); + let model_sphere = Sphere { + center: world_from_local.transform_point3a(model_aabb.center), + radius: transform.radius_vec3a(model_aabb.half_extents), + }; + // Do quick sphere-based frustum culling + if !frustum.intersects_sphere(&model_sphere, false) { + return; + } + // Do aabb-based frustum culling + if !frustum.intersects_obb(model_aabb, &world_from_local, true, false) { + return; } } diff --git a/crates/bevy_core_pipeline/src/oit/mod.rs b/crates/bevy_core_pipeline/src/oit/mod.rs index 774d18efe55bf..f08fa2ffd701e 100644 --- a/crates/bevy_core_pipeline/src/oit/mod.rs +++ b/crates/bevy_core_pipeline/src/oit/mod.rs @@ -67,13 +67,13 @@ impl Component for OrderIndependentTransparencySettings { fn on_add() -> Option { Some(|world, context| { - if let Some(value) = world.get::(context.entity) { - if value.layer_count > 32 { - warn!("{}OrderIndependentTransparencySettings layer_count set to {} might be too high.", + if let Some(value) = world.get::(context.entity) + && value.layer_count > 32 + { + warn!("{}OrderIndependentTransparencySettings layer_count set to {} might be too high.", context.caller.map(|location|format!("{location}: ")).unwrap_or_default(), value.layer_count ); - } } }) } diff --git a/crates/bevy_core_pipeline/src/oit/resolve/mod.rs b/crates/bevy_core_pipeline/src/oit/resolve/mod.rs index 650b65f494bc2..882251f072857 100644 --- a/crates/bevy_core_pipeline/src/oit/resolve/mod.rs +++ b/crates/bevy_core_pipeline/src/oit/resolve/mod.rs @@ -167,11 +167,11 @@ pub fn queue_oit_resolve_pipeline( layer_count: oit_settings.layer_count, }; - if let Some((cached_key, id)) = cached_pipeline_id.get(&e) { - if *cached_key == key { - commands.entity(e).insert(OitResolvePipelineId(*id)); - continue; - } + if let Some((cached_key, id)) = cached_pipeline_id.get(&e) + && *cached_key == key + { + commands.entity(e).insert(OitResolvePipelineId(*id)); + continue; } let desc = specialize_oit_resolve_pipeline( diff --git a/crates/bevy_core_pipeline/src/prepass/node.rs b/crates/bevy_core_pipeline/src/prepass/node.rs index 1b54ee8c5d393..de59578d0e4bc 100644 --- a/crates/bevy_core_pipeline/src/prepass/node.rs +++ b/crates/bevy_core_pipeline/src/prepass/node.rs @@ -238,14 +238,14 @@ fn run_prepass<'w>( drop(render_pass); // After rendering to the view depth texture, copy it to the prepass depth texture if deferred isn't going to - if deferred_prepass.is_none() { - if let Some(prepass_depth_texture) = &view_prepass_textures.depth { - command_encoder.copy_texture_to_texture( - view_depth_texture.texture.as_image_copy(), - prepass_depth_texture.texture.texture.as_image_copy(), - view_prepass_textures.size, - ); - } + if deferred_prepass.is_none() + && let Some(prepass_depth_texture) = &view_prepass_textures.depth + { + command_encoder.copy_texture_to_texture( + view_depth_texture.texture.as_image_copy(), + prepass_depth_texture.texture.texture.as_image_copy(), + view_prepass_textures.size, + ); } command_encoder.finish() diff --git a/crates/bevy_core_pipeline/src/upscaling/node.rs b/crates/bevy_core_pipeline/src/upscaling/node.rs index 93fc7d447856b..7f75f3a2d4225 100644 --- a/crates/bevy_core_pipeline/src/upscaling/node.rs +++ b/crates/bevy_core_pipeline/src/upscaling/node.rs @@ -84,12 +84,12 @@ impl ViewNode for UpscalingNode { .begin_render_pass(&pass_descriptor); let pass_span = diagnostics.pass_span(&mut render_pass, "upscaling"); - if let Some(camera) = camera { - if let Some(viewport) = &camera.viewport { - let size = viewport.physical_size; - let position = viewport.physical_position; - render_pass.set_scissor_rect(position.x, position.y, size.x, size.y); - } + if let Some(camera) = camera + && let Some(viewport) = &camera.viewport + { + let size = viewport.physical_size; + let position = viewport.physical_position; + render_pass.set_scissor_rect(position.x, position.y, size.x, size.y); } render_pass.set_pipeline(pipeline); diff --git a/crates/bevy_core_widgets/src/core_button.rs b/crates/bevy_core_widgets/src/core_button.rs index 5ef0d33ef0c30..70b6fb1cb355f 100644 --- a/crates/bevy_core_widgets/src/core_button.rs +++ b/crates/bevy_core_widgets/src/core_button.rs @@ -34,16 +34,16 @@ fn button_on_key_event( q_state: Query<(&CoreButton, Has)>, mut commands: Commands, ) { - if let Ok((bstate, disabled)) = q_state.get(trigger.target()) { - if !disabled { - let event = &trigger.event().input; - if !event.repeat - && event.state == ButtonState::Pressed - && (event.key_code == KeyCode::Enter || event.key_code == KeyCode::Space) - { - trigger.propagate(false); - commands.notify_with(&bstate.on_activate, Activate(trigger.target())); - } + if let Ok((bstate, disabled)) = q_state.get(trigger.target()) + && !disabled + { + let event = &trigger.event().input; + if !event.repeat + && event.state == ButtonState::Pressed + && (event.key_code == KeyCode::Enter || event.key_code == KeyCode::Space) + { + trigger.propagate(false); + commands.notify_with(&bstate.on_activate, Activate(trigger.target())); } } } diff --git a/crates/bevy_core_widgets/src/core_scrollbar.rs b/crates/bevy_core_widgets/src/core_scrollbar.rs index 9065617413256..5f5a7087483d1 100644 --- a/crates/bevy_core_widgets/src/core_scrollbar.rs +++ b/crates/bevy_core_widgets/src/core_scrollbar.rs @@ -164,14 +164,14 @@ fn scrollbar_on_drag_start( ) { if let Ok((ChildOf(thumb_parent), mut drag)) = q_thumb.get_mut(ev.target()) { ev.propagate(false); - if let Ok(scrollbar) = q_scrollbar.get(*thumb_parent) { - if let Ok(scroll_area) = q_scroll_area.get(scrollbar.target) { - drag.dragging = true; - drag.drag_origin = match scrollbar.orientation { - ControlOrientation::Horizontal => scroll_area.x, - ControlOrientation::Vertical => scroll_area.y, - }; - } + if let Ok(scrollbar) = q_scrollbar.get(*thumb_parent) + && let Ok(scroll_area) = q_scroll_area.get(scrollbar.target) + { + drag.dragging = true; + drag.drag_origin = match scrollbar.orientation { + ControlOrientation::Horizontal => scroll_area.x, + ControlOrientation::Vertical => scroll_area.y, + }; } } } @@ -183,36 +183,34 @@ fn scrollbar_on_drag( mut q_scroll_pos: Query<(&mut ScrollPosition, &ComputedNode), Without>, ui_scale: Res, ) { - if let Ok((ChildOf(thumb_parent), drag)) = q_thumb.get_mut(ev.target()) { - if let Ok((node, scrollbar)) = q_scrollbar.get_mut(*thumb_parent) { - ev.propagate(false); - let Ok((mut scroll_pos, scroll_content)) = q_scroll_pos.get_mut(scrollbar.target) - else { - return; - }; + if let Ok((ChildOf(thumb_parent), drag)) = q_thumb.get_mut(ev.target()) + && let Ok((node, scrollbar)) = q_scrollbar.get_mut(*thumb_parent) + { + ev.propagate(false); + let Ok((mut scroll_pos, scroll_content)) = q_scroll_pos.get_mut(scrollbar.target) else { + return; + }; - if drag.dragging { - let distance = ev.event().distance / ui_scale.0; - let visible_size = scroll_content.size() * scroll_content.inverse_scale_factor; - let content_size = - scroll_content.content_size() * scroll_content.inverse_scale_factor; - let scrollbar_size = (node.size() * node.inverse_scale_factor).max(Vec2::ONE); + if drag.dragging { + let distance = ev.event().distance / ui_scale.0; + let visible_size = scroll_content.size() * scroll_content.inverse_scale_factor; + let content_size = scroll_content.content_size() * scroll_content.inverse_scale_factor; + let scrollbar_size = (node.size() * node.inverse_scale_factor).max(Vec2::ONE); - match scrollbar.orientation { - ControlOrientation::Horizontal => { - let range = (content_size.x - visible_size.x).max(0.); - scroll_pos.x = (drag.drag_origin - + (distance.x * content_size.x) / scrollbar_size.x) - .clamp(0., range); - } - ControlOrientation::Vertical => { - let range = (content_size.y - visible_size.y).max(0.); - scroll_pos.y = (drag.drag_origin - + (distance.y * content_size.y) / scrollbar_size.y) - .clamp(0., range); - } - }; - } + match scrollbar.orientation { + ControlOrientation::Horizontal => { + let range = (content_size.x - visible_size.x).max(0.); + scroll_pos.x = (drag.drag_origin + + (distance.x * content_size.x) / scrollbar_size.x) + .clamp(0., range); + } + ControlOrientation::Vertical => { + let range = (content_size.y - visible_size.y).max(0.); + scroll_pos.y = (drag.drag_origin + + (distance.y * content_size.y) / scrollbar_size.y) + .clamp(0., range); + } + }; } } } diff --git a/crates/bevy_dev_tools/src/fps_overlay.rs b/crates/bevy_dev_tools/src/fps_overlay.rs index 435a0d2faf0c6..aa66c97560632 100644 --- a/crates/bevy_dev_tools/src/fps_overlay.rs +++ b/crates/bevy_dev_tools/src/fps_overlay.rs @@ -212,10 +212,10 @@ fn update_text( if *time_since_rerender >= config.refresh_interval { *time_since_rerender = Duration::ZERO; for entity in &query { - if let Some(fps) = diagnostic.get(&FrameTimeDiagnosticsPlugin::FPS) { - if let Some(value) = fps.smoothed() { - *writer.text(entity, 1) = format!("{value:.2}"); - } + if let Some(fps) = diagnostic.get(&FrameTimeDiagnosticsPlugin::FPS) + && let Some(value) = fps.smoothed() + { + *writer.text(entity, 1) = format!("{value:.2}"); } } } diff --git a/crates/bevy_diagnostic/src/diagnostic.rs b/crates/bevy_diagnostic/src/diagnostic.rs index 1f67d5220aae9..dd1e3576431d6 100644 --- a/crates/bevy_diagnostic/src/diagnostic.rs +++ b/crates/bevy_diagnostic/src/diagnostic.rs @@ -149,12 +149,11 @@ impl Diagnostic { } if self.max_history_length > 1 { - if self.history.len() >= self.max_history_length { - if let Some(removed_diagnostic) = self.history.pop_front() { - if !removed_diagnostic.value.is_nan() { - self.sum -= removed_diagnostic.value; - } - } + if self.history.len() >= self.max_history_length + && let Some(removed_diagnostic) = self.history.pop_front() + && !removed_diagnostic.value.is_nan() + { + self.sum -= removed_diagnostic.value; } if measurement.value.is_finite() { @@ -273,13 +272,9 @@ impl Diagnostic { return None; } - if let Some(newest) = self.history.back() { - if let Some(oldest) = self.history.front() { - return Some(newest.time.duration_since(oldest.time)); - } - } - - None + let newest = self.history.back()?; + let oldest = self.history.front()?; + Some(newest.time.duration_since(oldest.time)) } /// Return the maximum number of elements for this diagnostic. diff --git a/crates/bevy_diagnostic/src/log_diagnostics_plugin.rs b/crates/bevy_diagnostic/src/log_diagnostics_plugin.rs index f6888ea7230c8..43435351081ae 100644 --- a/crates/bevy_diagnostic/src/log_diagnostics_plugin.rs +++ b/crates/bevy_diagnostic/src/log_diagnostics_plugin.rs @@ -128,10 +128,10 @@ impl LogDiagnosticsPlugin { ) { if let Some(filter) = &state.filter { for path in filter.iter() { - if let Some(diagnostic) = diagnostics.get(path) { - if diagnostic.is_enabled { - callback(diagnostic); - } + if let Some(diagnostic) = diagnostics.get(path) + && diagnostic.is_enabled + { + callback(diagnostic); } } } else { diff --git a/crates/bevy_ecs/src/change_detection.rs b/crates/bevy_ecs/src/change_detection.rs index 1ba4f23db2721..af42d9c44176d 100644 --- a/crates/bevy_ecs/src/change_detection.rs +++ b/crates/bevy_ecs/src/change_detection.rs @@ -1051,7 +1051,7 @@ impl<'w> MutUntyped<'w> { /// Returns a [`MutUntyped`] with a smaller lifetime. /// This is useful if you have `&mut MutUntyped`, but you need a `MutUntyped`. #[inline] - pub fn reborrow(&mut self) -> MutUntyped { + pub fn reborrow(&mut self) -> MutUntyped<'_> { MutUntyped { value: self.value.reborrow(), ticks: TicksMut { diff --git a/crates/bevy_ecs/src/component/clone.rs b/crates/bevy_ecs/src/component/clone.rs index ff90255e2e6b7..3a3784350e36a 100644 --- a/crates/bevy_ecs/src/component/clone.rs +++ b/crates/bevy_ecs/src/component/clone.rs @@ -7,7 +7,7 @@ use crate::entity::{ComponentCloneCtx, SourceComponent}; pub type ComponentCloneFn = fn(&SourceComponent, &mut ComponentCloneCtx); /// The clone behavior to use when cloning or moving a [`Component`]. -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, Default)] pub enum ComponentCloneBehavior { /// Uses the default behavior (which is passed to [`ComponentCloneBehavior::resolve`]) #[default] diff --git a/crates/bevy_ecs/src/entity/clone_entities.rs b/crates/bevy_ecs/src/entity/clone_entities.rs index 2ba536a114b21..b2e78d79c1084 100644 --- a/crates/bevy_ecs/src/entity/clone_entities.rs +++ b/crates/bevy_ecs/src/entity/clone_entities.rs @@ -445,7 +445,7 @@ impl EntityCloner { /// explicitly denied, for example by using the [`deny`](EntityClonerBuilder::deny) method. /// /// Required components are not considered by denied components and must be explicitly denied as well if desired. - pub fn build_opt_out(world: &mut World) -> EntityClonerBuilder { + pub fn build_opt_out(world: &mut World) -> EntityClonerBuilder<'_, OptOut> { EntityClonerBuilder { world, filter: Default::default(), @@ -461,7 +461,7 @@ impl EntityCloner { /// Components allowed to be cloned through this builder would also allow their required components, /// which will be cloned from the source entity only if the target entity does not contain them already. /// To skip adding required components see [`without_required_components`](EntityClonerBuilder::without_required_components). - pub fn build_opt_in(world: &mut World) -> EntityClonerBuilder { + pub fn build_opt_in(world: &mut World) -> EntityClonerBuilder<'_, OptIn> { EntityClonerBuilder { world, filter: Default::default(), diff --git a/crates/bevy_ecs/src/entity/mod.rs b/crates/bevy_ecs/src/entity/mod.rs index 64a8c8952e0df..07404459c6c36 100644 --- a/crates/bevy_ecs/src/entity/mod.rs +++ b/crates/bevy_ecs/src/entity/mod.rs @@ -774,7 +774,7 @@ impl Entities { clippy::unnecessary_fallible_conversions, reason = "`IdCursor::try_from` may fail on 32-bit platforms." )] - pub fn reserve_entities(&self, count: u32) -> ReserveEntitiesIterator { + pub fn reserve_entities(&self, count: u32) -> ReserveEntitiesIterator<'_> { // Use one atomic subtract to grab a range of new IDs. The range might be // entirely nonnegative, meaning all IDs come from the freelist, or entirely // negative, meaning they are all new IDs to allocate, or a mix of both. diff --git a/crates/bevy_ecs/src/observer/mod.rs b/crates/bevy_ecs/src/observer/mod.rs index dd43cb090d181..40a4ee3db6a06 100644 --- a/crates/bevy_ecs/src/observer/mod.rs +++ b/crates/bevy_ecs/src/observer/mod.rs @@ -182,7 +182,7 @@ impl World { pub fn add_observer( &mut self, system: impl IntoObserverSystem, - ) -> EntityWorldMut { + ) -> EntityWorldMut<'_> { self.spawn(Observer::new(system)) } @@ -515,9 +515,6 @@ mod tests { #[derive(Component)] struct B; - #[derive(Component)] - struct C; - #[derive(Component)] #[component(storage = "SparseSet")] struct S; diff --git a/crates/bevy_ecs/src/observer/system_param.rs b/crates/bevy_ecs/src/observer/system_param.rs index 6e165ccd6df67..6637a0ce2472c 100644 --- a/crates/bevy_ecs/src/observer/system_param.rs +++ b/crates/bevy_ecs/src/observer/system_param.rs @@ -64,7 +64,7 @@ impl<'w, E, B: Bundle> On<'w, E, B> { } /// Returns a pointer to the triggered event. - pub fn event_ptr(&self) -> Ptr { + pub fn event_ptr(&self) -> Ptr<'_> { Ptr::from(&self.event) } diff --git a/crates/bevy_ecs/src/relationship/related_methods.rs b/crates/bevy_ecs/src/relationship/related_methods.rs index 22b5ea128187b..dbbe015f6b7f5 100644 --- a/crates/bevy_ecs/src/relationship/related_methods.rs +++ b/crates/bevy_ecs/src/relationship/related_methods.rs @@ -642,7 +642,7 @@ impl<'w, R: Relationship> RelatedSpawnerCommands<'w, R> { } /// Returns the underlying [`Commands`]. - pub fn commands(&mut self) -> Commands { + pub fn commands(&mut self) -> Commands<'_, '_> { self.commands.reborrow() } diff --git a/crates/bevy_ecs/src/schedule/stepping.rs b/crates/bevy_ecs/src/schedule/stepping.rs index d765ebe060ac2..72bdd752a9a32 100644 --- a/crates/bevy_ecs/src/schedule/stepping.rs +++ b/crates/bevy_ecs/src/schedule/stepping.rs @@ -365,13 +365,11 @@ impl Stepping { /// lookup the first system for the supplied schedule index fn first_system_index_for_schedule(&self, index: usize) -> usize { - let label = match self.schedule_order.get(index) { - None => return 0, - Some(label) => label, + let Some(label) = self.schedule_order.get(index) else { + return 0; }; - let state = match self.schedule_states.get(label) { - None => return 0, - Some(state) => state, + let Some(state) = self.schedule_states.get(label) else { + return 0; }; state.first.unwrap_or(0) } diff --git a/crates/bevy_ecs/src/system/commands/mod.rs b/crates/bevy_ecs/src/system/commands/mod.rs index c2df1823f70ea..3f3e75c37f700 100644 --- a/crates/bevy_ecs/src/system/commands/mod.rs +++ b/crates/bevy_ecs/src/system/commands/mod.rs @@ -313,7 +313,7 @@ impl<'w, 's> Commands<'w, 's> { /// - [`spawn_batch`](Self::spawn_batch) to spawn many entities /// with the same combination of components. #[track_caller] - pub fn spawn_empty(&mut self) -> EntityCommands { + pub fn spawn_empty(&mut self) -> EntityCommands<'_> { let entity = self.entities.reserve_entity(); let mut entity_commands = EntityCommands { entity, @@ -375,7 +375,7 @@ impl<'w, 's> Commands<'w, 's> { /// - [`spawn_batch`](Self::spawn_batch) to spawn many entities /// with the same combination of components. #[track_caller] - pub fn spawn(&mut self, bundle: T) -> EntityCommands { + pub fn spawn(&mut self, bundle: T) -> EntityCommands<'_> { let entity = self.entities.reserve_entity(); let mut entity_commands = EntityCommands { entity, @@ -436,7 +436,7 @@ impl<'w, 's> Commands<'w, 's> { /// - [`get_entity`](Self::get_entity) for the fallible version. #[inline] #[track_caller] - pub fn entity(&mut self, entity: Entity) -> EntityCommands { + pub fn entity(&mut self, entity: Entity) -> EntityCommands<'_> { EntityCommands { entity, commands: self.reborrow(), @@ -487,7 +487,7 @@ impl<'w, 's> Commands<'w, 's> { pub fn get_entity( &mut self, entity: Entity, - ) -> Result { + ) -> Result, EntityDoesNotExistError> { if self.entities.contains(entity) { Ok(EntityCommands { entity, @@ -1120,7 +1120,7 @@ impl<'w, 's> Commands<'w, 's> { pub fn add_observer( &mut self, observer: impl IntoObserverSystem, - ) -> EntityCommands { + ) -> EntityCommands<'_> { self.spawn(Observer::new(observer)) } @@ -1269,7 +1269,7 @@ impl<'a> EntityCommands<'a> { /// Returns an [`EntityCommands`] with a smaller lifetime. /// /// This is useful if you have `&mut EntityCommands` but you need `EntityCommands`. - pub fn reborrow(&mut self) -> EntityCommands { + pub fn reborrow(&mut self) -> EntityCommands<'_> { EntityCommands { entity: self.entity, commands: self.commands.reborrow(), @@ -1319,7 +1319,7 @@ impl<'a> EntityCommands<'a> { /// /// # bevy_ecs::system::assert_is_system(level_up_system); /// ``` - pub fn entry(&mut self) -> EntityEntryCommands { + pub fn entry(&mut self) -> EntityEntryCommands<'_, T> { EntityEntryCommands { entity_commands: self.reborrow(), marker: PhantomData, @@ -1982,7 +1982,7 @@ impl<'a> EntityCommands<'a> { } /// Returns the underlying [`Commands`]. - pub fn commands(&mut self) -> Commands { + pub fn commands(&mut self) -> Commands<'_, '_> { self.commands.reborrow() } @@ -2381,7 +2381,7 @@ impl<'a, T: Component> EntityEntryCommands<'a, T> { /// } /// # bevy_ecs::system::assert_is_system(level_up_system); /// ``` - pub fn entity(&mut self) -> EntityCommands { + pub fn entity(&mut self) -> EntityCommands<'_> { self.entity_commands.reborrow() } } diff --git a/crates/bevy_ecs/src/system/system_param.rs b/crates/bevy_ecs/src/system/system_param.rs index dcf5f4f3327fe..d9adab6fe34b7 100644 --- a/crates/bevy_ecs/src/system/system_param.rs +++ b/crates/bevy_ecs/src/system/system_param.rs @@ -1270,7 +1270,7 @@ impl<'a, T: SystemBuffer> DerefMut for Deferred<'a, T> { impl Deferred<'_, T> { /// Returns a [`Deferred`] with a smaller lifetime. /// This is useful if you have `&mut Deferred` but need `Deferred`. - pub fn reborrow(&mut self) -> Deferred { + pub fn reborrow(&mut self) -> Deferred<'_, T> { Deferred(self.0) } } diff --git a/crates/bevy_ecs/src/world/deferred_world.rs b/crates/bevy_ecs/src/world/deferred_world.rs index 3b146d2c0589c..92d2e98e5da69 100644 --- a/crates/bevy_ecs/src/world/deferred_world.rs +++ b/crates/bevy_ecs/src/world/deferred_world.rs @@ -62,13 +62,13 @@ impl<'w> From<&'w mut World> for DeferredWorld<'w> { impl<'w> DeferredWorld<'w> { /// Reborrow self as a new instance of [`DeferredWorld`] #[inline] - pub fn reborrow(&mut self) -> DeferredWorld { + pub fn reborrow(&mut self) -> DeferredWorld<'_> { DeferredWorld { world: self.world } } /// Creates a [`Commands`] instance that pushes to the world's command queue #[inline] - pub fn commands(&mut self) -> Commands { + pub fn commands(&mut self) -> Commands<'_, '_> { // SAFETY: &mut self ensure that there are no outstanding accesses to the queue let command_queue = unsafe { self.world.get_raw_command_queue() }; // SAFETY: command_queue is stored on world and always valid while the world exists @@ -81,7 +81,7 @@ impl<'w> DeferredWorld<'w> { pub fn get_mut>( &mut self, entity: Entity, - ) -> Option> { + ) -> Option> { self.get_entity_mut(entity).ok()?.into_mut() } @@ -418,7 +418,7 @@ impl<'w> DeferredWorld<'w> { /// # assert_eq!(_world.get::(e1).unwrap().0, eid); /// # assert_eq!(_world.get::(e2).unwrap().0, eid); /// ``` - pub fn entities_and_commands(&mut self) -> (EntityFetcher, Commands) { + pub fn entities_and_commands(&mut self) -> (EntityFetcher<'_>, Commands<'_, '_>) { let cell = self.as_unsafe_world_cell(); // SAFETY: `&mut self` gives mutable access to the entire world, and prevents simultaneous access. let fetcher = unsafe { EntityFetcher::new(cell) }; @@ -887,7 +887,7 @@ impl<'w> DeferredWorld<'w> { /// # Safety /// - must only be used to make non-structural ECS changes #[inline] - pub(crate) fn as_unsafe_world_cell(&mut self) -> UnsafeWorldCell { + pub(crate) fn as_unsafe_world_cell(&mut self) -> UnsafeWorldCell<'_> { self.world } } diff --git a/crates/bevy_ecs/src/world/mod.rs b/crates/bevy_ecs/src/world/mod.rs index d251206c37720..9e36484cc5141 100644 --- a/crates/bevy_ecs/src/world/mod.rs +++ b/crates/bevy_ecs/src/world/mod.rs @@ -232,14 +232,14 @@ impl World { /// **NOTE:** [`ComponentsQueuedRegistrator`] is easily misused. /// See its docs for important notes on when and how it should be used. #[inline] - pub fn components_queue(&self) -> ComponentsQueuedRegistrator { + pub fn components_queue(&self) -> ComponentsQueuedRegistrator<'_> { // SAFETY: These are from the same world. unsafe { ComponentsQueuedRegistrator::new(&self.components, &self.component_ids) } } /// Prepares a [`ComponentsRegistrator`] for the world. #[inline] - pub fn components_registrator(&mut self) -> ComponentsRegistrator { + pub fn components_registrator(&mut self) -> ComponentsRegistrator<'_> { // SAFETY: These are from the same world. unsafe { ComponentsRegistrator::new(&mut self.components, &mut self.component_ids) } } @@ -271,7 +271,7 @@ impl World { /// Creates a new [`Commands`] instance that writes to the world's command queue /// Use [`World::flush`] to apply all queued commands #[inline] - pub fn commands(&mut self) -> Commands { + pub fn commands(&mut self) -> Commands<'_, '_> { // SAFETY: command_queue is stored on world and always valid while the world exists unsafe { Commands::new_raw_from_entities(self.command_queue.clone(), &self.entities) } } @@ -1047,7 +1047,7 @@ impl World { /// # assert_eq!(world.get::(e1).unwrap().0, eid); /// # assert_eq!(world.get::(e2).unwrap().0, eid); /// ``` - pub fn entities_and_commands(&mut self) -> (EntityFetcher, Commands) { + pub fn entities_and_commands(&mut self) -> (EntityFetcher<'_>, Commands<'_, '_>) { let cell = self.as_unsafe_world_cell(); // SAFETY: `&mut self` gives mutable access to the entire world, and prevents simultaneous access. let fetcher = unsafe { EntityFetcher::new(cell) }; @@ -1087,7 +1087,7 @@ impl World { /// assert_eq!(position.x, 0.0); /// ``` #[track_caller] - pub fn spawn_empty(&mut self) -> EntityWorldMut { + pub fn spawn_empty(&mut self) -> EntityWorldMut<'_> { self.flush(); let entity = self.entities.alloc(); // SAFETY: entity was just allocated @@ -1155,7 +1155,7 @@ impl World { /// assert_eq!(position.x, 2.0); /// ``` #[track_caller] - pub fn spawn(&mut self, bundle: B) -> EntityWorldMut { + pub fn spawn(&mut self, bundle: B) -> EntityWorldMut<'_> { self.spawn_with_caller(bundle, MaybeLocation::caller()) } @@ -1163,7 +1163,7 @@ impl World { &mut self, bundle: B, caller: MaybeLocation, - ) -> EntityWorldMut { + ) -> EntityWorldMut<'_> { self.flush(); let change_tick = self.change_tick(); let entity = self.entities.alloc(); @@ -1192,7 +1192,7 @@ impl World { &mut self, entity: Entity, caller: MaybeLocation, - ) -> EntityWorldMut { + ) -> EntityWorldMut<'_> { let archetype = self.archetypes.empty_mut(); // PERF: consider avoiding allocating entities in the empty archetype unless needed let table_row = self.storages.tables[archetype.table_id()].allocate(entity); @@ -1279,7 +1279,7 @@ impl World { pub fn get_mut>( &mut self, entity: Entity, - ) -> Option> { + ) -> Option> { self.get_entity_mut(entity).ok()?.into_mut() } @@ -1980,7 +1980,7 @@ impl World { /// use [`get_resource_or_insert_with`](World::get_resource_or_insert_with). #[inline] #[track_caller] - pub fn resource_ref(&self) -> Ref { + pub fn resource_ref(&self) -> Ref<'_, R> { match self.get_resource_ref() { Some(x) => x, None => panic!( @@ -2028,7 +2028,7 @@ impl World { /// Gets a reference including change detection to the resource of the given type if it exists. #[inline] - pub fn get_resource_ref(&self) -> Option> { + pub fn get_resource_ref(&self) -> Option> { // SAFETY: // - `as_unsafe_world_cell_readonly` gives permission to access everything immutably // - `&self` ensures nothing in world is borrowed mutably diff --git a/crates/bevy_feathers/src/controls/color_slider.rs b/crates/bevy_feathers/src/controls/color_slider.rs index a086bbc7f1d10..76ad6523ab4c0 100644 --- a/crates/bevy_feathers/src/controls/color_slider.rs +++ b/crates/bevy_feathers/src/controls/color_slider.rs @@ -328,34 +328,31 @@ fn update_track_color( cap_bg.0 = start; } - if let Ok(mut gradient) = q_gradient.get_mut(track_children[1]) { - if let [Gradient::Linear(linear_gradient)] = &mut gradient.0[..] { - linear_gradient.stops[0].color = start; - linear_gradient.stops[1].color = middle; - linear_gradient.stops[2].color = end; - linear_gradient.color_space = match slider.channel { - ColorChannel::Red | ColorChannel::Green | ColorChannel::Blue => { + if let Ok(mut gradient) = q_gradient.get_mut(track_children[1]) + && let [Gradient::Linear(linear_gradient)] = &mut gradient.0[..] + { + linear_gradient.stops[0].color = start; + linear_gradient.stops[1].color = middle; + linear_gradient.stops[2].color = end; + linear_gradient.color_space = match slider.channel { + ColorChannel::Red | ColorChannel::Green | ColorChannel::Blue => { + InterpolationColorSpace::Srgba + } + ColorChannel::HslHue + | ColorChannel::HslLightness + | ColorChannel::HslSaturation => InterpolationColorSpace::Hsla, + ColorChannel::Alpha => match base_color { + Color::Srgba(_) => InterpolationColorSpace::Srgba, + Color::LinearRgba(_) => InterpolationColorSpace::LinearRgba, + Color::Oklaba(_) => InterpolationColorSpace::Oklaba, + Color::Oklcha(_) => InterpolationColorSpace::OklchaLong, + Color::Hsla(_) | Color::Hsva(_) => InterpolationColorSpace::Hsla, + _ => { + warn_once!("Unsupported color space for ColorSlider: {:?}", base_color); InterpolationColorSpace::Srgba } - ColorChannel::HslHue - | ColorChannel::HslLightness - | ColorChannel::HslSaturation => InterpolationColorSpace::Hsla, - ColorChannel::Alpha => match base_color { - Color::Srgba(_) => InterpolationColorSpace::Srgba, - Color::LinearRgba(_) => InterpolationColorSpace::LinearRgba, - Color::Oklaba(_) => InterpolationColorSpace::Oklaba, - Color::Oklcha(_) => InterpolationColorSpace::OklchaLong, - Color::Hsla(_) | Color::Hsva(_) => InterpolationColorSpace::Hsla, - _ => { - warn_once!( - "Unsupported color space for ColorSlider: {:?}", - base_color - ); - InterpolationColorSpace::Srgba - } - }, - }; - } + }, + }; } if let Ok(mut cap_bg) = q_background.get_mut(track_children[2]) { diff --git a/crates/bevy_feathers/src/cursor.rs b/crates/bevy_feathers/src/cursor.rs index ea10a3910e999..8c6b5c103b20a 100644 --- a/crates/bevy_feathers/src/cursor.rs +++ b/crates/bevy_feathers/src/cursor.rs @@ -93,10 +93,10 @@ pub(crate) fn update_cursor( .unwrap_or(&r_default_cursor.0); for (entity, prev_cursor) in q_windows.iter() { - if let Some(prev_cursor) = prev_cursor { - if cursor.eq_cursor_icon(prev_cursor) { - continue; - } + if let Some(prev_cursor) = prev_cursor + && cursor.eq_cursor_icon(prev_cursor) + { + continue; } commands.entity(entity).insert(cursor.to_cursor_icon()); } diff --git a/crates/bevy_feathers/src/font_styles.rs b/crates/bevy_feathers/src/font_styles.rs index f09a4af3ed916..6419696bb70f4 100644 --- a/crates/bevy_feathers/src/font_styles.rs +++ b/crates/bevy_feathers/src/font_styles.rs @@ -50,16 +50,16 @@ pub(crate) fn on_changed_font( assets: Res, mut commands: Commands, ) { - if let Ok(style) = font_style.get(ev.target()) { - if let Some(font) = match style.font { + if let Ok(style) = font_style.get(ev.target()) + && let Some(font) = match style.font { HandleOrPath::Handle(ref h) => Some(h.clone()), HandleOrPath::Path(ref p) => Some(assets.load::(p)), - } { - commands.entity(ev.target()).insert(Propagate(TextFont { - font, - font_size: style.font_size, - ..Default::default() - })); } + { + commands.entity(ev.target()).insert(Propagate(TextFont { + font, + font_size: style.font_size, + ..Default::default() + })); } } diff --git a/crates/bevy_gizmos/src/gizmos.rs b/crates/bevy_gizmos/src/gizmos.rs index 0299b4700a3a1..d13fe8240be78 100644 --- a/crates/bevy_gizmos/src/gizmos.rs +++ b/crates/bevy_gizmos/src/gizmos.rs @@ -355,7 +355,7 @@ where } /// Read-only view into the buffers data. - pub fn buffer(&self) -> GizmoBufferView { + pub fn buffer(&self) -> GizmoBufferView<'_> { let GizmoBuffer { list_positions, list_colors, diff --git a/crates/bevy_gltf/src/loader/mod.rs b/crates/bevy_gltf/src/loader/mod.rs index 15047cf41062e..fce607437db57 100644 --- a/crates/bevy_gltf/src/loader/mod.rs +++ b/crates/bevy_gltf/src/loader/mod.rs @@ -1462,49 +1462,49 @@ fn load_node( } // create camera node - if settings.load_cameras { - if let Some(camera) = gltf_node.camera() { - let projection = match camera.projection() { - gltf::camera::Projection::Orthographic(orthographic) => { - let xmag = orthographic.xmag(); - let orthographic_projection = OrthographicProjection { - near: orthographic.znear(), - far: orthographic.zfar(), - scaling_mode: ScalingMode::FixedHorizontal { - viewport_width: xmag, - }, - ..OrthographicProjection::default_3d() - }; - Projection::Orthographic(orthographic_projection) + if settings.load_cameras + && let Some(camera) = gltf_node.camera() + { + let projection = match camera.projection() { + gltf::camera::Projection::Orthographic(orthographic) => { + let xmag = orthographic.xmag(); + let orthographic_projection = OrthographicProjection { + near: orthographic.znear(), + far: orthographic.zfar(), + scaling_mode: ScalingMode::FixedHorizontal { + viewport_width: xmag, + }, + ..OrthographicProjection::default_3d() + }; + Projection::Orthographic(orthographic_projection) + } + gltf::camera::Projection::Perspective(perspective) => { + let mut perspective_projection: PerspectiveProjection = PerspectiveProjection { + fov: perspective.yfov(), + near: perspective.znear(), + ..Default::default() + }; + if let Some(zfar) = perspective.zfar() { + perspective_projection.far = zfar; } - gltf::camera::Projection::Perspective(perspective) => { - let mut perspective_projection: PerspectiveProjection = PerspectiveProjection { - fov: perspective.yfov(), - near: perspective.znear(), - ..Default::default() - }; - if let Some(zfar) = perspective.zfar() { - perspective_projection.far = zfar; - } - if let Some(aspect_ratio) = perspective.aspect_ratio() { - perspective_projection.aspect_ratio = aspect_ratio; - } - Projection::Perspective(perspective_projection) + if let Some(aspect_ratio) = perspective.aspect_ratio() { + perspective_projection.aspect_ratio = aspect_ratio; } - }; + Projection::Perspective(perspective_projection) + } + }; - node.insert(( - Camera3d::default(), - projection, - transform, - Camera { - is_active: !*active_camera_found, - ..Default::default() - }, - )); + node.insert(( + Camera3d::default(), + projection, + transform, + Camera { + is_active: !*active_camera_found, + ..Default::default() + }, + )); - *active_camera_found = true; - } + *active_camera_found = true; } // Map node index to entity @@ -1514,161 +1514,161 @@ fn load_node( node.with_children(|parent| { // Only include meshes in the output if they're set to be retained in the MAIN_WORLD and/or RENDER_WORLD by the load_meshes flag - if !settings.load_meshes.is_empty() { - if let Some(mesh) = gltf_node.mesh() { - // append primitives - for primitive in mesh.primitives() { - let material = primitive.material(); - let material_label = material_label(&material, is_scale_inverted).to_string(); - - // This will make sure we load the default material now since it would not have been - // added when iterating over all the gltf materials (since the default material is - // not explicitly listed in the gltf). - // It also ensures an inverted scale copy is instantiated if required. - if !root_load_context.has_labeled_asset(&material_label) - && !load_context.has_labeled_asset(&material_label) - { - load_material(&material, load_context, document, is_scale_inverted); - } + if !settings.load_meshes.is_empty() + && let Some(mesh) = gltf_node.mesh() + { + // append primitives + for primitive in mesh.primitives() { + let material = primitive.material(); + let material_label = material_label(&material, is_scale_inverted).to_string(); + + // This will make sure we load the default material now since it would not have been + // added when iterating over all the gltf materials (since the default material is + // not explicitly listed in the gltf). + // It also ensures an inverted scale copy is instantiated if required. + if !root_load_context.has_labeled_asset(&material_label) + && !load_context.has_labeled_asset(&material_label) + { + load_material(&material, load_context, document, is_scale_inverted); + } - let primitive_label = GltfAssetLabel::Primitive { - mesh: mesh.index(), - primitive: primitive.index(), - }; - let bounds = primitive.bounding_box(); - - let mut mesh_entity = parent.spawn(( - // TODO: handle missing label handle errors here? - Mesh3d(load_context.get_label_handle(primitive_label.to_string())), - MeshMaterial3d::( - load_context.get_label_handle(&material_label), - ), - )); - - let target_count = primitive.morph_targets().len(); - if target_count != 0 { - let weights = match mesh.weights() { - Some(weights) => weights.to_vec(), - None => vec![0.0; target_count], - }; + let primitive_label = GltfAssetLabel::Primitive { + mesh: mesh.index(), + primitive: primitive.index(), + }; + let bounds = primitive.bounding_box(); + + let mut mesh_entity = parent.spawn(( + // TODO: handle missing label handle errors here? + Mesh3d(load_context.get_label_handle(primitive_label.to_string())), + MeshMaterial3d::( + load_context.get_label_handle(&material_label), + ), + )); - if morph_weights.is_none() { - morph_weights = Some(weights.clone()); - } + let target_count = primitive.morph_targets().len(); + if target_count != 0 { + let weights = match mesh.weights() { + Some(weights) => weights.to_vec(), + None => vec![0.0; target_count], + }; - // unwrap: the parent's call to `MeshMorphWeights::new` - // means this code doesn't run if it returns an `Err`. - // According to https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#morph-targets - // they should all have the same length. - // > All morph target accessors MUST have the same count as - // > the accessors of the original primitive. - mesh_entity.insert(MeshMorphWeights::new(weights).unwrap()); + if morph_weights.is_none() { + morph_weights = Some(weights.clone()); } - mesh_entity.insert(Aabb::from_min_max( - Vec3::from_slice(&bounds.min), - Vec3::from_slice(&bounds.max), - )); - if let Some(extras) = primitive.extras() { - mesh_entity.insert(GltfExtras { - value: extras.get().to_string(), - }); - } + // unwrap: the parent's call to `MeshMorphWeights::new` + // means this code doesn't run if it returns an `Err`. + // According to https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#morph-targets + // they should all have the same length. + // > All morph target accessors MUST have the same count as + // > the accessors of the original primitive. + mesh_entity.insert(MeshMorphWeights::new(weights).unwrap()); + } + mesh_entity.insert(Aabb::from_min_max( + Vec3::from_slice(&bounds.min), + Vec3::from_slice(&bounds.max), + )); - if let Some(extras) = mesh.extras() { - mesh_entity.insert(GltfMeshExtras { - value: extras.get().to_string(), - }); - } + if let Some(extras) = primitive.extras() { + mesh_entity.insert(GltfExtras { + value: extras.get().to_string(), + }); + } - if let Some(extras) = material.extras() { - mesh_entity.insert(GltfMaterialExtras { - value: extras.get().to_string(), - }); - } + if let Some(extras) = mesh.extras() { + mesh_entity.insert(GltfMeshExtras { + value: extras.get().to_string(), + }); + } - if let Some(name) = mesh.name() { - mesh_entity.insert(GltfMeshName(name.to_string())); - } + if let Some(extras) = material.extras() { + mesh_entity.insert(GltfMaterialExtras { + value: extras.get().to_string(), + }); + } - if let Some(name) = material.name() { - mesh_entity.insert(GltfMaterialName(name.to_string())); - } + if let Some(name) = mesh.name() { + mesh_entity.insert(GltfMeshName(name.to_string())); + } - mesh_entity.insert(Name::new(primitive_name(&mesh, &material))); + if let Some(name) = material.name() { + mesh_entity.insert(GltfMaterialName(name.to_string())); + } - // Mark for adding skinned mesh - if let Some(skin) = gltf_node.skin() { - entity_to_skin_index_map.insert(mesh_entity.id(), skin.index()); - } + mesh_entity.insert(Name::new(primitive_name(&mesh, &material))); + + // Mark for adding skinned mesh + if let Some(skin) = gltf_node.skin() { + entity_to_skin_index_map.insert(mesh_entity.id(), skin.index()); } } } - if settings.load_lights { - if let Some(light) = gltf_node.light() { - match light.kind() { - gltf::khr_lights_punctual::Kind::Directional => { - let mut entity = parent.spawn(DirectionalLight { - color: Color::srgb_from_array(light.color()), - // NOTE: KHR_punctual_lights defines the intensity units for directional - // lights in lux (lm/m^2) which is what we need. - illuminance: light.intensity(), - ..Default::default() + if settings.load_lights + && let Some(light) = gltf_node.light() + { + match light.kind() { + gltf::khr_lights_punctual::Kind::Directional => { + let mut entity = parent.spawn(DirectionalLight { + color: Color::srgb_from_array(light.color()), + // NOTE: KHR_punctual_lights defines the intensity units for directional + // lights in lux (lm/m^2) which is what we need. + illuminance: light.intensity(), + ..Default::default() + }); + if let Some(name) = light.name() { + entity.insert(Name::new(name.to_string())); + } + if let Some(extras) = light.extras() { + entity.insert(GltfExtras { + value: extras.get().to_string(), }); - if let Some(name) = light.name() { - entity.insert(Name::new(name.to_string())); - } - if let Some(extras) = light.extras() { - entity.insert(GltfExtras { - value: extras.get().to_string(), - }); - } } - gltf::khr_lights_punctual::Kind::Point => { - let mut entity = parent.spawn(PointLight { - color: Color::srgb_from_array(light.color()), - // NOTE: KHR_punctual_lights defines the intensity units for point lights in - // candela (lm/sr) which is luminous intensity and we need luminous power. - // For a point light, luminous power = 4 * pi * luminous intensity - intensity: light.intensity() * core::f32::consts::PI * 4.0, - range: light.range().unwrap_or(20.0), - radius: 0.0, - ..Default::default() + } + gltf::khr_lights_punctual::Kind::Point => { + let mut entity = parent.spawn(PointLight { + color: Color::srgb_from_array(light.color()), + // NOTE: KHR_punctual_lights defines the intensity units for point lights in + // candela (lm/sr) which is luminous intensity and we need luminous power. + // For a point light, luminous power = 4 * pi * luminous intensity + intensity: light.intensity() * core::f32::consts::PI * 4.0, + range: light.range().unwrap_or(20.0), + radius: 0.0, + ..Default::default() + }); + if let Some(name) = light.name() { + entity.insert(Name::new(name.to_string())); + } + if let Some(extras) = light.extras() { + entity.insert(GltfExtras { + value: extras.get().to_string(), }); - if let Some(name) = light.name() { - entity.insert(Name::new(name.to_string())); - } - if let Some(extras) = light.extras() { - entity.insert(GltfExtras { - value: extras.get().to_string(), - }); - } } - gltf::khr_lights_punctual::Kind::Spot { - inner_cone_angle, - outer_cone_angle, - } => { - let mut entity = parent.spawn(SpotLight { - color: Color::srgb_from_array(light.color()), - // NOTE: KHR_punctual_lights defines the intensity units for spot lights in - // candela (lm/sr) which is luminous intensity and we need luminous power. - // For a spot light, we map luminous power = 4 * pi * luminous intensity - intensity: light.intensity() * core::f32::consts::PI * 4.0, - range: light.range().unwrap_or(20.0), - radius: light.range().unwrap_or(0.0), - inner_angle: inner_cone_angle, - outer_angle: outer_cone_angle, - ..Default::default() + } + gltf::khr_lights_punctual::Kind::Spot { + inner_cone_angle, + outer_cone_angle, + } => { + let mut entity = parent.spawn(SpotLight { + color: Color::srgb_from_array(light.color()), + // NOTE: KHR_punctual_lights defines the intensity units for spot lights in + // candela (lm/sr) which is luminous intensity and we need luminous power. + // For a spot light, we map luminous power = 4 * pi * luminous intensity + intensity: light.intensity() * core::f32::consts::PI * 4.0, + range: light.range().unwrap_or(20.0), + radius: light.range().unwrap_or(0.0), + inner_angle: inner_cone_angle, + outer_angle: outer_cone_angle, + ..Default::default() + }); + if let Some(name) = light.name() { + entity.insert(Name::new(name.to_string())); + } + if let Some(extras) = light.extras() { + entity.insert(GltfExtras { + value: extras.get().to_string(), }); - if let Some(name) = light.name() { - entity.insert(Name::new(name.to_string())); - } - if let Some(extras) = light.extras() { - entity.insert(GltfExtras { - value: extras.get().to_string(), - }); - } } } } @@ -1700,16 +1700,16 @@ fn load_node( }); // Only include meshes in the output if they're set to be retained in the MAIN_WORLD and/or RENDER_WORLD by the load_meshes flag - if !settings.load_meshes.is_empty() { - if let (Some(mesh), Some(weights)) = (gltf_node.mesh(), morph_weights) { - let primitive_label = mesh.primitives().next().map(|p| GltfAssetLabel::Primitive { - mesh: mesh.index(), - primitive: p.index(), - }); - let first_mesh = - primitive_label.map(|label| load_context.get_label_handle(label.to_string())); - node.insert(MorphWeights::new(weights, first_mesh)?); - } + if !settings.load_meshes.is_empty() + && let (Some(mesh), Some(weights)) = (gltf_node.mesh(), morph_weights) + { + let primitive_label = mesh.primitives().next().map(|p| GltfAssetLabel::Primitive { + mesh: mesh.index(), + primitive: p.index(), + }); + let first_mesh = + primitive_label.map(|label| load_context.get_label_handle(label.to_string())); + node.insert(MorphWeights::new(weights, first_mesh)?); } if let Some(err) = gltf_error { diff --git a/crates/bevy_image/src/basis.rs b/crates/bevy_image/src/basis.rs index 553140b0024bf..396129e678634 100644 --- a/crates/bevy_image/src/basis.rs +++ b/crates/bevy_image/src/basis.rs @@ -53,12 +53,12 @@ pub fn basis_buffer_to_image( let image0_mip_level_count = transcoder.image_level_count(buffer, 0); for image_index in 0..image_count { - if let Some(image_info) = transcoder.image_info(buffer, image_index) { - if texture_type == BasisTextureType::TextureType2D - && (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!( + if let Some(image_info) = transcoder.image_info(buffer, image_index) + && texture_type == BasisTextureType::TextureType2D + && (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, @@ -66,7 +66,6 @@ pub fn basis_buffer_to_image( 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 { diff --git a/crates/bevy_macro_utils/src/bevy_manifest.rs b/crates/bevy_macro_utils/src/bevy_manifest.rs index b6df0e0e0f89c..0b8a496812376 100644 --- a/crates/bevy_macro_utils/src/bevy_manifest.rs +++ b/crates/bevy_macro_utils/src/bevy_manifest.rs @@ -29,10 +29,9 @@ impl BevyManifest { if let Ok(manifest) = RwLockReadGuard::try_map(MANIFESTS.read(), |manifests| manifests.get(&manifest_path)) + && manifest.modified_time == modified_time { - if manifest.modified_time == modified_time { - return manifest; - } + return manifest; } let manifest = BevyManifest { diff --git a/crates/bevy_math/src/cubic_splines/mod.rs b/crates/bevy_math/src/cubic_splines/mod.rs index 5ad32ed2100af..6a45103393ffc 100644 --- a/crates/bevy_math/src/cubic_splines/mod.rs +++ b/crates/bevy_math/src/cubic_splines/mod.rs @@ -1605,7 +1605,7 @@ impl> RationalCurve

{ } t -= segment.knot_span; } - return (self.segments.last().unwrap(), 1.0); + (self.segments.last().unwrap(), 1.0) } } diff --git a/crates/bevy_mesh/src/conversions.rs b/crates/bevy_mesh/src/conversions.rs index f68c2d6f74321..a4148ae24353e 100644 --- a/crates/bevy_mesh/src/conversions.rs +++ b/crates/bevy_mesh/src/conversions.rs @@ -445,9 +445,8 @@ mod tests { let buffer = vec![[0_u32; 4]; 3]; let values = VertexAttributeValues::from(buffer); let error_result: Result, _> = values.try_into(); - let error = match error_result { - Ok(..) => unreachable!(), - Err(error) => error, + let Err(error) = error_result else { + unreachable!() }; assert_eq!( error.to_string(), diff --git a/crates/bevy_pbr/src/cluster.rs b/crates/bevy_pbr/src/cluster.rs index f3d242a512fcc..bc473a509f666 100644 --- a/crates/bevy_pbr/src/cluster.rs +++ b/crates/bevy_pbr/src/cluster.rs @@ -216,7 +216,7 @@ impl GpuClusterableObjects { } } - pub fn binding(&self) -> Option { + pub fn binding(&self) -> Option> { match self { GpuClusterableObjects::Uniform(buffer) => buffer.binding(), GpuClusterableObjects::Storage(buffer) => buffer.binding(), @@ -456,7 +456,7 @@ impl ViewClusterBindings { } } - pub fn clusterable_object_index_lists_binding(&self) -> Option { + pub fn clusterable_object_index_lists_binding(&self) -> Option> { match &self.buffers { ViewClusterBuffers::Uniform { clusterable_object_index_lists, @@ -469,7 +469,7 @@ impl ViewClusterBindings { } } - pub fn offsets_and_counts_binding(&self) -> Option { + pub fn offsets_and_counts_binding(&self) -> Option> { match &self.buffers { ViewClusterBuffers::Uniform { cluster_offsets_and_counts, diff --git a/crates/bevy_pbr/src/light_probe/environment_map.rs b/crates/bevy_pbr/src/light_probe/environment_map.rs index e6dfebd903ad1..b7b5a104da460 100644 --- a/crates/bevy_pbr/src/light_probe/environment_map.rs +++ b/crates/bevy_pbr/src/light_probe/environment_map.rs @@ -215,18 +215,16 @@ impl<'a> RenderViewEnvironmentMapBindGroupEntries<'a> { }; } - if let Some(environment_maps) = render_view_environment_maps { - if let Some(cubemap) = environment_maps.binding_index_to_textures.first() { - if let (Some(diffuse_image), Some(specular_image)) = - (images.get(cubemap.diffuse), images.get(cubemap.specular)) - { - return RenderViewEnvironmentMapBindGroupEntries::Single { - diffuse_texture_view: &diffuse_image.texture_view, - specular_texture_view: &specular_image.texture_view, - sampler: &diffuse_image.sampler, - }; - } - } + if let Some(environment_maps) = render_view_environment_maps + && let Some(cubemap) = environment_maps.binding_index_to_textures.first() + && let (Some(diffuse_image), Some(specular_image)) = + (images.get(cubemap.diffuse), images.get(cubemap.specular)) + { + return RenderViewEnvironmentMapBindGroupEntries::Single { + diffuse_texture_view: &diffuse_image.texture_view, + specular_texture_view: &specular_image.texture_view, + sampler: &diffuse_image.sampler, + }; } RenderViewEnvironmentMapBindGroupEntries::Single { @@ -280,23 +278,20 @@ impl LightProbeComponent for EnvironmentMapLight { affects_lightmapped_mesh_diffuse, .. }) = view_component - { - if let (Some(_), Some(specular_map)) = ( + && let (Some(_), Some(specular_map)) = ( image_assets.get(diffuse_map_handle), image_assets.get(specular_map_handle), - ) { - render_view_light_probes.view_light_probe_info = EnvironmentMapViewLightProbeInfo { - cubemap_index: render_view_light_probes.get_or_insert_cubemap( - &EnvironmentMapIds { - diffuse: diffuse_map_handle.id(), - specular: specular_map_handle.id(), - }, - ) as i32, - smallest_specular_mip_level: specular_map.mip_level_count - 1, - intensity: *intensity, - affects_lightmapped_mesh_diffuse: *affects_lightmapped_mesh_diffuse, - }; - } + ) + { + render_view_light_probes.view_light_probe_info = EnvironmentMapViewLightProbeInfo { + cubemap_index: render_view_light_probes.get_or_insert_cubemap(&EnvironmentMapIds { + diffuse: diffuse_map_handle.id(), + specular: specular_map_handle.id(), + }) as i32, + smallest_specular_mip_level: specular_map.mip_level_count - 1, + intensity: *intensity, + affects_lightmapped_mesh_diffuse: *affects_lightmapped_mesh_diffuse, + }; }; render_view_light_probes diff --git a/crates/bevy_pbr/src/light_probe/irradiance_volume.rs b/crates/bevy_pbr/src/light_probe/irradiance_volume.rs index e1931d30b82aa..a7320792b2ef4 100644 --- a/crates/bevy_pbr/src/light_probe/irradiance_volume.rs +++ b/crates/bevy_pbr/src/light_probe/irradiance_volume.rs @@ -253,22 +253,18 @@ impl<'a> RenderViewIrradianceVolumeBindGroupEntries<'a> { images: &'a RenderAssets, fallback_image: &'a FallbackImage, ) -> RenderViewIrradianceVolumeBindGroupEntries<'a> { - if let Some(irradiance_volumes) = render_view_irradiance_volumes { - if let Some(irradiance_volume) = irradiance_volumes.render_light_probes.first() { - if irradiance_volume.texture_index >= 0 { - if let Some(image_id) = irradiance_volumes - .binding_index_to_textures - .get(irradiance_volume.texture_index as usize) - { - if let Some(image) = images.get(*image_id) { - return RenderViewIrradianceVolumeBindGroupEntries::Single { - texture_view: &image.texture_view, - sampler: &image.sampler, - }; - } - } - } - } + if let Some(irradiance_volumes) = render_view_irradiance_volumes + && let Some(irradiance_volume) = irradiance_volumes.render_light_probes.first() + && irradiance_volume.texture_index >= 0 + && let Some(image_id) = irradiance_volumes + .binding_index_to_textures + .get(irradiance_volume.texture_index as usize) + && let Some(image) = images.get(*image_id) + { + return RenderViewIrradianceVolumeBindGroupEntries::Single { + texture_view: &image.texture_view, + sampler: &image.sampler, + }; } RenderViewIrradianceVolumeBindGroupEntries::Single { diff --git a/crates/bevy_pbr/src/material_bind_groups.rs b/crates/bevy_pbr/src/material_bind_groups.rs index c984cfb85db7d..0851760bbfd03 100644 --- a/crates/bevy_pbr/src/material_bind_groups.rs +++ b/crates/bevy_pbr/src/material_bind_groups.rs @@ -478,7 +478,7 @@ impl MaterialBindGroupAllocator { } /// Returns the slab with the given index, if one exists. - pub fn get(&self, group: MaterialBindGroupIndex) -> Option { + pub fn get(&self, group: MaterialBindGroupIndex) -> Option> { match *self { MaterialBindGroupAllocator::Bindless(ref bindless_allocator) => bindless_allocator .get(group) @@ -673,7 +673,7 @@ impl MaterialBindlessIndexTable { } /// Returns the [`BindGroupEntry`] for the index table itself. - fn bind_group_entry(&self) -> BindGroupEntry { + fn bind_group_entry(&self) -> BindGroupEntry<'_> { BindGroupEntry { binding: *self.binding_number, resource: self @@ -1837,7 +1837,7 @@ impl MaterialBindGroupNonBindlessAllocator { } /// Returns a wrapper around the bind group with the given index. - fn get(&self, group: MaterialBindGroupIndex) -> Option { + fn get(&self, group: MaterialBindGroupIndex) -> Option> { self.bind_groups[group.0 as usize] .as_ref() .map(|bind_group| match bind_group { diff --git a/crates/bevy_pbr/src/meshlet/instance_manager.rs b/crates/bevy_pbr/src/meshlet/instance_manager.rs index 94d03a925a490..a210accea7ff9 100644 --- a/crates/bevy_pbr/src/meshlet/instance_manager.rs +++ b/crates/bevy_pbr/src/meshlet/instance_manager.rs @@ -282,16 +282,15 @@ pub fn queue_material_meshlet_meshes( let instance_manager = instance_manager.deref_mut(); for (i, (instance, _, _)) in instance_manager.instances.iter().enumerate() { - if let Some(material_instance) = render_material_instances.instances.get(instance) { - if let Some(material_id) = instance_manager + if let Some(material_instance) = render_material_instances.instances.get(instance) + && let Some(material_id) = instance_manager .material_id_lookup .get(&material_instance.asset_id) - { - instance_manager - .material_ids_present_in_scene - .insert(*material_id); - instance_manager.instance_material_ids.get_mut()[i] = *material_id; - } + { + instance_manager + .material_ids_present_in_scene + .insert(*material_id); + instance_manager.instance_material_ids.get_mut()[i] = *material_id; } } } diff --git a/crates/bevy_pbr/src/meshlet/material_shade_nodes.rs b/crates/bevy_pbr/src/meshlet/material_shade_nodes.rs index 9c0b4c4843fcf..60be5117e8886 100644 --- a/crates/bevy_pbr/src/meshlet/material_shade_nodes.rs +++ b/crates/bevy_pbr/src/meshlet/material_shade_nodes.rs @@ -132,15 +132,14 @@ impl ViewNode for MeshletMainOpaquePass3dNode { for (material_id, material_pipeline_id, material_bind_group) in meshlet_view_materials.iter() { - if instance_manager.material_present_in_scene(material_id) { - if let Some(material_pipeline) = + if instance_manager.material_present_in_scene(material_id) + && let Some(material_pipeline) = pipeline_cache.get_render_pipeline(*material_pipeline_id) - { - let x = *material_id * 3; - render_pass.set_render_pipeline(material_pipeline); - render_pass.set_bind_group(3, material_bind_group, &[]); - render_pass.draw(x..(x + 3), 0..1); - } + { + let x = *material_id * 3; + render_pass.set_render_pipeline(material_pipeline); + render_pass.set_bind_group(3, material_bind_group, &[]); + render_pass.draw(x..(x + 3), 0..1); } } @@ -265,15 +264,14 @@ impl ViewNode for MeshletPrepassNode { for (material_id, material_pipeline_id, material_bind_group) in meshlet_view_materials.iter() { - if instance_manager.material_present_in_scene(material_id) { - if let Some(material_pipeline) = + if instance_manager.material_present_in_scene(material_id) + && let Some(material_pipeline) = pipeline_cache.get_render_pipeline(*material_pipeline_id) - { - let x = *material_id * 3; - render_pass.set_render_pipeline(material_pipeline); - render_pass.set_bind_group(2, material_bind_group, &[]); - render_pass.draw(x..(x + 3), 0..1); - } + { + let x = *material_id * 3; + render_pass.set_render_pipeline(material_pipeline); + render_pass.set_bind_group(2, material_bind_group, &[]); + render_pass.draw(x..(x + 3), 0..1); } } @@ -404,15 +402,14 @@ impl ViewNode for MeshletDeferredGBufferPrepassNode { for (material_id, material_pipeline_id, material_bind_group) in meshlet_view_materials.iter() { - if instance_manager.material_present_in_scene(material_id) { - if let Some(material_pipeline) = + if instance_manager.material_present_in_scene(material_id) + && let Some(material_pipeline) = pipeline_cache.get_render_pipeline(*material_pipeline_id) - { - let x = *material_id * 3; - render_pass.set_render_pipeline(material_pipeline); - render_pass.set_bind_group(2, material_bind_group, &[]); - render_pass.draw(x..(x + 3), 0..1); - } + { + let x = *material_id * 3; + render_pass.set_render_pipeline(material_pipeline); + render_pass.set_bind_group(2, material_bind_group, &[]); + render_pass.draw(x..(x + 3), 0..1); } } diff --git a/crates/bevy_pbr/src/render/mesh.rs b/crates/bevy_pbr/src/render/mesh.rs index 9795d442ddd99..97b28e865a059 100644 --- a/crates/bevy_pbr/src/render/mesh.rs +++ b/crates/bevy_pbr/src/render/mesh.rs @@ -903,7 +903,7 @@ impl RenderMeshInstances { /// Constructs [`RenderMeshQueueData`] for the given entity, if it has a /// mesh attached. - pub fn render_mesh_queue_data(&self, entity: MainEntity) -> Option { + pub fn render_mesh_queue_data(&self, entity: MainEntity) -> Option> { match *self { RenderMeshInstances::CpuBuilding(ref instances) => { instances.render_mesh_queue_data(entity) @@ -934,7 +934,7 @@ impl RenderMeshInstancesCpu { .map(|render_mesh_instance| render_mesh_instance.mesh_asset_id) } - fn render_mesh_queue_data(&self, entity: MainEntity) -> Option { + fn render_mesh_queue_data(&self, entity: MainEntity) -> Option> { self.get(&entity) .map(|render_mesh_instance| RenderMeshQueueData { shared: &render_mesh_instance.shared, @@ -958,7 +958,7 @@ impl RenderMeshInstancesGpu { .map(|render_mesh_instance| render_mesh_instance.mesh_asset_id) } - fn render_mesh_queue_data(&self, entity: MainEntity) -> Option { + fn render_mesh_queue_data(&self, entity: MainEntity) -> Option> { self.get(&entity) .map(|render_mesh_instance| RenderMeshQueueData { shared: &render_mesh_instance.shared, @@ -2712,27 +2712,26 @@ pub fn prepare_mesh_bind_groups( mut render_lightmaps: ResMut, ) { // CPU mesh preprocessing path. - if let Some(cpu_batched_instance_buffer) = cpu_batched_instance_buffer { - if let Some(instance_data_binding) = cpu_batched_instance_buffer + if let Some(cpu_batched_instance_buffer) = cpu_batched_instance_buffer + && let Some(instance_data_binding) = cpu_batched_instance_buffer .into_inner() .instance_data_binding() - { - // In this path, we only have a single set of bind groups for all phases. - let cpu_preprocessing_mesh_bind_groups = prepare_mesh_bind_groups_for_phase( - instance_data_binding, - &meshes, - &mesh_pipeline, - &render_device, - &skins_uniform, - &weights_uniform, - &mut render_lightmaps, - ); + { + // In this path, we only have a single set of bind groups for all phases. + let cpu_preprocessing_mesh_bind_groups = prepare_mesh_bind_groups_for_phase( + instance_data_binding, + &meshes, + &mesh_pipeline, + &render_device, + &skins_uniform, + &weights_uniform, + &mut render_lightmaps, + ); - commands.insert_resource(MeshBindGroups::CpuPreprocessing( - cpu_preprocessing_mesh_bind_groups, - )); - return; - } + commands.insert_resource(MeshBindGroups::CpuPreprocessing( + cpu_preprocessing_mesh_bind_groups, + )); + return; } // GPU mesh preprocessing path. @@ -3022,11 +3021,11 @@ impl RenderCommand

for SetMeshBindGroup { dynamic_offsets[offset_count] = dynamic_offset; offset_count += 1; } - if let Some(current_skin_index) = current_skin_byte_offset { - if skins_use_uniform_buffers(&render_device) { - dynamic_offsets[offset_count] = current_skin_index.byte_offset; - offset_count += 1; - } + if let Some(current_skin_index) = current_skin_byte_offset + && skins_use_uniform_buffers(&render_device) + { + dynamic_offsets[offset_count] = current_skin_index.byte_offset; + offset_count += 1; } if let Some(current_morph_index) = current_morph_index { dynamic_offsets[offset_count] = current_morph_index.index; @@ -3036,11 +3035,11 @@ impl RenderCommand

for SetMeshBindGroup { // Attach motion vectors if needed. if has_motion_vector_prepass { // Attach the previous skin index for motion vector computation. - if skins_use_uniform_buffers(&render_device) { - if let Some(current_skin_byte_offset) = current_skin_byte_offset { - dynamic_offsets[offset_count] = current_skin_byte_offset.byte_offset; - offset_count += 1; - } + if skins_use_uniform_buffers(&render_device) + && let Some(current_skin_byte_offset) = current_skin_byte_offset + { + dynamic_offsets[offset_count] = current_skin_byte_offset.byte_offset; + offset_count += 1; } // Attach the previous morph index for motion vector computation. If @@ -3094,13 +3093,12 @@ impl RenderCommand

for DrawMesh { // If we're using GPU preprocessing, then we're dependent on that // compute shader having been run, which of course can only happen if // it's compiled. Otherwise, our mesh instance data won't be present. - if let Some(preprocess_pipelines) = preprocess_pipelines { - if !has_preprocess_bind_group + if let Some(preprocess_pipelines) = preprocess_pipelines + && (!has_preprocess_bind_group || !preprocess_pipelines - .pipelines_are_loaded(&pipeline_cache, &preprocessing_support) - { - return RenderCommandResult::Skip; - } + .pipelines_are_loaded(&pipeline_cache, &preprocessing_support)) + { + return RenderCommandResult::Skip; } let meshes = meshes.into_inner(); diff --git a/crates/bevy_pbr/src/render/mesh_bindings.rs b/crates/bevy_pbr/src/render/mesh_bindings.rs index 51b28389dcd0c..b8f095af72a86 100644 --- a/crates/bevy_pbr/src/render/mesh_bindings.rs +++ b/crates/bevy_pbr/src/render/mesh_bindings.rs @@ -91,7 +91,7 @@ mod entry { renderer::RenderDevice, }; - fn entry(binding: u32, size: Option, buffer: &Buffer) -> BindGroupEntry { + fn entry(binding: u32, size: Option, buffer: &Buffer) -> BindGroupEntry<'_> { BindGroupEntry { binding, resource: BindingResource::Buffer(BufferBinding { @@ -116,22 +116,25 @@ mod entry { }; entry(binding, size, buffer) } - pub(super) fn weights(binding: u32, buffer: &Buffer) -> BindGroupEntry { + pub(super) fn weights(binding: u32, buffer: &Buffer) -> BindGroupEntry<'_> { entry(binding, Some(MORPH_BUFFER_SIZE as u64), buffer) } - pub(super) fn targets(binding: u32, texture: &TextureView) -> BindGroupEntry { + pub(super) fn targets(binding: u32, texture: &TextureView) -> BindGroupEntry<'_> { BindGroupEntry { binding, resource: BindingResource::TextureView(texture), } } - pub(super) fn lightmaps_texture_view(binding: u32, texture: &TextureView) -> BindGroupEntry { + pub(super) fn lightmaps_texture_view( + binding: u32, + texture: &TextureView, + ) -> BindGroupEntry<'_> { BindGroupEntry { binding, resource: BindingResource::TextureView(texture), } } - pub(super) fn lightmaps_sampler(binding: u32, sampler: &Sampler) -> BindGroupEntry { + pub(super) fn lightmaps_sampler(binding: u32, sampler: &Sampler) -> BindGroupEntry<'_> { BindGroupEntry { binding, resource: BindingResource::Sampler(sampler), diff --git a/crates/bevy_pbr/src/render/mesh_view_bindings.rs b/crates/bevy_pbr/src/render/mesh_view_bindings.rs index 0f40327dc7ea6..71f5dddf1bbfe 100644 --- a/crates/bevy_pbr/src/render/mesh_view_bindings.rs +++ b/crates/bevy_pbr/src/render/mesh_view_bindings.rs @@ -684,8 +684,8 @@ pub fn prepare_mesh_view_bind_groups( entries = entries.extend_with_indices(((24, transmission_view), (25, transmission_sampler))); - if has_oit { - if let ( + if has_oit + && let ( Some(oit_layers_binding), Some(oit_layer_ids_binding), Some(oit_settings_binding), @@ -693,13 +693,13 @@ pub fn prepare_mesh_view_bind_groups( oit_buffers.layers.binding(), oit_buffers.layer_ids.binding(), oit_buffers.settings.binding(), - ) { - entries = entries.extend_with_indices(( - (26, oit_layers_binding.clone()), - (27, oit_layer_ids_binding.clone()), - (28, oit_settings_binding.clone()), - )); - } + ) + { + entries = entries.extend_with_indices(( + (26, oit_layers_binding.clone()), + (27, oit_layer_ids_binding.clone()), + (28, oit_settings_binding.clone()), + )); } let mut entries_binding_array = DynamicBindGroupEntries::new(); diff --git a/crates/bevy_picking/src/events.rs b/crates/bevy_picking/src/events.rs index 51d653af5c7f8..e100662389448 100644 --- a/crates/bevy_picking/src/events.rs +++ b/crates/bevy_picking/src/events.rs @@ -95,10 +95,10 @@ where }; // Otherwise, send it to the window entity (unless this is a window entity). - if window.is_none() { - if let NormalizedRenderTarget::Window(window_ref) = pointer.pointer_location.target { - return Some(window_ref.entity()); - } + if window.is_none() + && let NormalizedRenderTarget::Window(window_ref) = pointer.pointer_location.target + { + return Some(window_ref.entity()); } None diff --git a/crates/bevy_picking/src/hover.rs b/crates/bevy_picking/src/hover.rs index f6755683940be..2621f105c2c40 100644 --- a/crates/bevy_picking/src/hover.rs +++ b/crates/bevy_picking/src/hover.rs @@ -243,10 +243,10 @@ pub fn update_interactions( }; for entity in previously_hovered_entities.keys() { - if !new_interaction_state.contains_key(entity) { - if let Ok(mut interaction) = interact.get_mut(*entity) { - interaction.set_if_neq(PickingInteraction::None); - } + if !new_interaction_state.contains_key(entity) + && let Ok(mut interaction) = interact.get_mut(*entity) + { + interaction.set_if_neq(PickingInteraction::None); } } } diff --git a/crates/bevy_picking/src/mesh_picking/ray_cast/mod.rs b/crates/bevy_picking/src/mesh_picking/ray_cast/mod.rs index e42dc160e26fc..dfc6a22c11353 100644 --- a/crates/bevy_picking/src/mesh_picking/ray_cast/mod.rs +++ b/crates/bevy_picking/src/mesh_picking/ray_cast/mod.rs @@ -229,14 +229,14 @@ impl<'w, 's> MeshRayCast<'w, 's> { RayCastVisibility::Visible => inherited_visibility.get(), RayCastVisibility::VisibleInView => view_visibility.get(), }; - if should_ray_cast { - if let Some(distance) = ray_aabb_intersection_3d( + if should_ray_cast + && let Some(distance) = ray_aabb_intersection_3d( ray, &Aabb3d::new(aabb.center, aabb.half_extents), &transform.to_matrix(), - ) { - aabb_hits_tx.send((FloatOrd(distance), entity)).ok(); - } + ) + { + aabb_hits_tx.send((FloatOrd(distance), entity)).ok(); } }, ); diff --git a/crates/bevy_reflect/derive/src/derive_data.rs b/crates/bevy_reflect/derive/src/derive_data.rs index 9e3e169bc21f6..ce985d39bd2f3 100644 --- a/crates/bevy_reflect/derive/src/derive_data.rs +++ b/crates/bevy_reflect/derive/src/derive_data.rs @@ -332,7 +332,7 @@ impl<'a> ReflectDerive<'a> { } /// Get the remote type path, if any. - pub fn remote_ty(&self) -> Option { + pub fn remote_ty(&self) -> Option> { match self { Self::Struct(data) | Self::TupleStruct(data) | Self::UnitStruct(data) => { data.meta.remote_ty() @@ -343,7 +343,7 @@ impl<'a> ReflectDerive<'a> { } /// Get the [`ReflectMeta`] for this derived type. - pub fn meta(&self) -> &ReflectMeta { + pub fn meta(&self) -> &ReflectMeta<'_> { match self { Self::Struct(data) | Self::TupleStruct(data) | Self::UnitStruct(data) => data.meta(), Self::Enum(data) => data.meta(), @@ -351,7 +351,7 @@ impl<'a> ReflectDerive<'a> { } } - pub fn where_clause_options(&self) -> WhereClauseOptions { + pub fn where_clause_options(&self) -> WhereClauseOptions<'_, '_> { match self { Self::Struct(data) | Self::TupleStruct(data) | Self::UnitStruct(data) => { data.where_clause_options() @@ -462,7 +462,7 @@ impl<'a> ReflectMeta<'a> { } /// Get the remote type path, if any. - pub fn remote_ty(&self) -> Option { + pub fn remote_ty(&self) -> Option> { self.remote_ty } @@ -631,7 +631,7 @@ impl<'a> ReflectStruct<'a> { &self.fields } - pub fn where_clause_options(&self) -> WhereClauseOptions { + pub fn where_clause_options(&self) -> WhereClauseOptions<'_, '_> { WhereClauseOptions::new_with_types(self.meta(), self.active_types()) } @@ -851,7 +851,7 @@ impl<'a> ReflectEnum<'a> { self.variants.iter().flat_map(EnumVariant::active_fields) } - pub fn where_clause_options(&self) -> WhereClauseOptions { + pub fn where_clause_options(&self) -> WhereClauseOptions<'_, '_> { WhereClauseOptions::new_with_types(self.meta(), self.active_types()) } diff --git a/crates/bevy_reflect/derive/src/enum_utility.rs b/crates/bevy_reflect/derive/src/enum_utility.rs index c717b7723eb3d..2b32ce1e4d0f3 100644 --- a/crates/bevy_reflect/derive/src/enum_utility.rs +++ b/crates/bevy_reflect/derive/src/enum_utility.rs @@ -37,7 +37,7 @@ pub(crate) struct VariantField<'a, 'b> { /// Trait used to control how enum variants are built. pub(crate) trait VariantBuilder: Sized { /// Returns the enum data. - fn reflect_enum(&self) -> &ReflectEnum; + fn reflect_enum(&self) -> &ReflectEnum<'_>; /// Returns a token stream that accesses a field of a variant as an `Option`. /// @@ -212,7 +212,7 @@ impl<'a> FromReflectVariantBuilder<'a> { } impl<'a> VariantBuilder for FromReflectVariantBuilder<'a> { - fn reflect_enum(&self) -> &ReflectEnum { + fn reflect_enum(&self) -> &ReflectEnum<'_> { self.reflect_enum } @@ -244,7 +244,7 @@ impl<'a> TryApplyVariantBuilder<'a> { } impl<'a> VariantBuilder for TryApplyVariantBuilder<'a> { - fn reflect_enum(&self) -> &ReflectEnum { + fn reflect_enum(&self) -> &ReflectEnum<'_> { self.reflect_enum } @@ -300,7 +300,7 @@ impl<'a> ReflectCloneVariantBuilder<'a> { } impl<'a> VariantBuilder for ReflectCloneVariantBuilder<'a> { - fn reflect_enum(&self) -> &ReflectEnum { + fn reflect_enum(&self) -> &ReflectEnum<'_> { self.reflect_enum } diff --git a/crates/bevy_reflect/src/array.rs b/crates/bevy_reflect/src/array.rs index df9580b8201e9..55412a1e79fba 100644 --- a/crates/bevy_reflect/src/array.rs +++ b/crates/bevy_reflect/src/array.rs @@ -63,7 +63,7 @@ pub trait Array: PartialReflect { } /// Returns an iterator over the array. - fn iter(&self) -> ArrayIter; + fn iter(&self) -> ArrayIter<'_>; /// Drain the elements of this array to get a vector of owned values. fn drain(self: Box) -> Vec>; @@ -242,12 +242,12 @@ impl PartialReflect for DynamicArray { } #[inline] - fn reflect_ref(&self) -> ReflectRef { + fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::Array(self) } #[inline] - fn reflect_mut(&mut self) -> ReflectMut { + fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::Array(self) } @@ -294,7 +294,7 @@ impl Array for DynamicArray { } #[inline] - fn iter(&self) -> ArrayIter { + fn iter(&self) -> ArrayIter<'_> { ArrayIter::new(self) } @@ -351,7 +351,7 @@ pub struct ArrayIter<'a> { impl ArrayIter<'_> { /// Creates a new [`ArrayIter`]. #[inline] - pub const fn new(array: &dyn Array) -> ArrayIter { + pub const fn new(array: &dyn Array) -> ArrayIter<'_> { ArrayIter { array, index: 0 } } } diff --git a/crates/bevy_reflect/src/enums/dynamic_enum.rs b/crates/bevy_reflect/src/enums/dynamic_enum.rs index 214d54c5e302d..8f218a5f04bbc 100644 --- a/crates/bevy_reflect/src/enums/dynamic_enum.rs +++ b/crates/bevy_reflect/src/enums/dynamic_enum.rs @@ -255,7 +255,7 @@ impl Enum for DynamicEnum { } } - fn iter_fields(&self) -> VariantFieldIter { + fn iter_fields(&self) -> VariantFieldIter<'_> { VariantFieldIter::new(self) } @@ -372,12 +372,12 @@ impl PartialReflect for DynamicEnum { } #[inline] - fn reflect_ref(&self) -> ReflectRef { + fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::Enum(self) } #[inline] - fn reflect_mut(&mut self) -> ReflectMut { + fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::Enum(self) } diff --git a/crates/bevy_reflect/src/enums/enum_trait.rs b/crates/bevy_reflect/src/enums/enum_trait.rs index 32e4b9612402f..a24fe65f6d97f 100644 --- a/crates/bevy_reflect/src/enums/enum_trait.rs +++ b/crates/bevy_reflect/src/enums/enum_trait.rs @@ -115,7 +115,7 @@ pub trait Enum: PartialReflect { /// For non-[`VariantType::Struct`] variants, this should return `None`. fn name_at(&self, index: usize) -> Option<&str>; /// Returns an iterator over the values of the current variant's fields. - fn iter_fields(&self) -> VariantFieldIter; + fn iter_fields(&self) -> VariantFieldIter<'_>; /// Returns the number of fields in the current variant. fn field_len(&self) -> usize; /// The name of the current variant. diff --git a/crates/bevy_reflect/src/func/args/from_arg.rs b/crates/bevy_reflect/src/func/args/from_arg.rs index c49d065169902..a79fe511cbf45 100644 --- a/crates/bevy_reflect/src/func/args/from_arg.rs +++ b/crates/bevy_reflect/src/func/args/from_arg.rs @@ -29,13 +29,13 @@ pub trait FromArg { /// Creates an item from an argument. /// /// The argument must be of the expected type and ownership. - fn from_arg(arg: Arg) -> Result, ArgError>; + fn from_arg(arg: Arg<'_>) -> Result, ArgError>; } // Blanket impl. impl FromArg for &'static T { type This<'a> = &'a T; - fn from_arg(arg: Arg) -> Result, ArgError> { + fn from_arg(arg: Arg<'_>) -> Result, ArgError> { arg.take_ref() } } @@ -43,7 +43,7 @@ impl FromArg for &'static T { // Blanket impl. impl FromArg for &'static mut T { type This<'a> = &'a mut T; - fn from_arg(arg: Arg) -> Result, ArgError> { + fn from_arg(arg: Arg<'_>) -> Result, ArgError> { arg.take_mut() } } @@ -77,7 +77,7 @@ macro_rules! impl_from_arg { )? { type This<'from_arg> = $ty; - fn from_arg(arg: $crate::func::args::Arg) -> + fn from_arg(arg: $crate::func::args::Arg<'_>) -> Result, $crate::func::args::ArgError> { arg.take_owned() diff --git a/crates/bevy_reflect/src/func/dynamic_function.rs b/crates/bevy_reflect/src/func/dynamic_function.rs index ab1d70e4ed47a..d9f881af33626 100644 --- a/crates/bevy_reflect/src/func/dynamic_function.rs +++ b/crates/bevy_reflect/src/func/dynamic_function.rs @@ -409,11 +409,11 @@ impl PartialReflect for DynamicFunction<'static> { ReflectKind::Function } - fn reflect_ref(&self) -> ReflectRef { + fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::Function(self) } - fn reflect_mut(&mut self) -> ReflectMut { + fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::Function(self) } diff --git a/crates/bevy_reflect/src/func/info.rs b/crates/bevy_reflect/src/func/info.rs index 2f5f82fbf5499..f3675ca185f7a 100644 --- a/crates/bevy_reflect/src/func/info.rs +++ b/crates/bevy_reflect/src/func/info.rs @@ -177,7 +177,7 @@ impl FunctionInfo { /// let pretty = info.pretty_printer(); /// assert_eq!(format!("{:?}", pretty), "(_: i32, _: i32) -> i32"); /// ``` - pub fn pretty_printer(&self) -> PrettyPrintFunctionInfo { + pub fn pretty_printer(&self) -> PrettyPrintFunctionInfo<'_> { PrettyPrintFunctionInfo::new(self) } diff --git a/crates/bevy_reflect/src/impls/alloc/borrow.rs b/crates/bevy_reflect/src/impls/alloc/borrow.rs index 9021343c67b75..8326ff9728922 100644 --- a/crates/bevy_reflect/src/impls/alloc/borrow.rs +++ b/crates/bevy_reflect/src/impls/alloc/borrow.rs @@ -55,11 +55,11 @@ impl PartialReflect for Cow<'static, str> { ReflectKind::Opaque } - fn reflect_ref(&self) -> ReflectRef { + fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::Opaque(self) } - fn reflect_mut(&mut self) -> ReflectMut { + fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::Opaque(self) } @@ -180,7 +180,7 @@ impl List self.as_ref().len() } - fn iter(&self) -> ListIter { + fn iter(&self) -> ListIter<'_> { ListIter::new(self) } @@ -228,11 +228,11 @@ impl Parti ReflectKind::List } - fn reflect_ref(&self) -> ReflectRef { + fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::List(self) } - fn reflect_mut(&mut self) -> ReflectMut { + fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::List(self) } diff --git a/crates/bevy_reflect/src/impls/alloc/collections/btree/map.rs b/crates/bevy_reflect/src/impls/alloc/collections/btree/map.rs index d5559a2985abd..ffa6ee34225a3 100644 --- a/crates/bevy_reflect/src/impls/alloc/collections/btree/map.rs +++ b/crates/bevy_reflect/src/impls/alloc/collections/btree/map.rs @@ -128,11 +128,11 @@ where ReflectKind::Map } - fn reflect_ref(&self) -> ReflectRef { + fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::Map(self) } - fn reflect_mut(&mut self) -> ReflectMut { + fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::Map(self) } diff --git a/crates/bevy_reflect/src/impls/core/panic.rs b/crates/bevy_reflect/src/impls/core/panic.rs index 3d1cebe53e536..8bc583c64ba78 100644 --- a/crates/bevy_reflect/src/impls/core/panic.rs +++ b/crates/bevy_reflect/src/impls/core/panic.rs @@ -57,11 +57,11 @@ impl PartialReflect for &'static Location<'static> { ReflectKind::Opaque } - fn reflect_ref(&self) -> ReflectRef { + fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::Opaque(self) } - fn reflect_mut(&mut self) -> ReflectMut { + fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::Opaque(self) } diff --git a/crates/bevy_reflect/src/impls/core/primitives.rs b/crates/bevy_reflect/src/impls/core/primitives.rs index 75825598233bc..8d53193ac6d03 100644 --- a/crates/bevy_reflect/src/impls/core/primitives.rs +++ b/crates/bevy_reflect/src/impls/core/primitives.rs @@ -191,11 +191,11 @@ impl PartialReflect for &'static str { Some(self) } - fn reflect_ref(&self) -> ReflectRef { + fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::Opaque(self) } - fn reflect_mut(&mut self) -> ReflectMut { + fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::Opaque(self) } @@ -310,7 +310,7 @@ impl A } #[inline] - fn iter(&self) -> ArrayIter { + fn iter(&self) -> ArrayIter<'_> { ArrayIter::new(self) } @@ -360,12 +360,12 @@ impl P } #[inline] - fn reflect_ref(&self) -> ReflectRef { + fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::Array(self) } #[inline] - fn reflect_mut(&mut self) -> ReflectMut { + fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::Array(self) } diff --git a/crates/bevy_reflect/src/impls/core/sync.rs b/crates/bevy_reflect/src/impls/core/sync.rs index 06b930e8a9b92..5cd46e7dc431d 100644 --- a/crates/bevy_reflect/src/impls/core/sync.rs +++ b/crates/bevy_reflect/src/impls/core/sync.rs @@ -102,11 +102,11 @@ macro_rules! impl_reflect_for_atomic { ReflectKind::Opaque } #[inline] - fn reflect_ref(&self) -> ReflectRef { + fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::Opaque(self) } #[inline] - fn reflect_mut(&mut self) -> ReflectMut { + fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::Opaque(self) } #[inline] diff --git a/crates/bevy_reflect/src/impls/macros/list.rs b/crates/bevy_reflect/src/impls/macros/list.rs index 81a27047cb687..16fd6661348e6 100644 --- a/crates/bevy_reflect/src/impls/macros/list.rs +++ b/crates/bevy_reflect/src/impls/macros/list.rs @@ -48,7 +48,7 @@ macro_rules! impl_reflect_for_veclike { } #[inline] - fn iter(&self) -> $crate::list::ListIter { + fn iter(&self) -> $crate::list::ListIter<'_> { $crate::list::ListIter::new(self) } @@ -98,11 +98,11 @@ macro_rules! impl_reflect_for_veclike { $crate::kind::ReflectKind::List } - fn reflect_ref(&self) -> $crate::kind::ReflectRef { + fn reflect_ref(&self) -> $crate::kind::ReflectRef<'_> { $crate::kind::ReflectRef::List(self) } - fn reflect_mut(&mut self) -> $crate::kind::ReflectMut { + fn reflect_mut(&mut self) -> $crate::kind::ReflectMut<'_> { $crate::kind::ReflectMut::List(self) } diff --git a/crates/bevy_reflect/src/impls/macros/map.rs b/crates/bevy_reflect/src/impls/macros/map.rs index e87bb314b5a18..5ac779f3a747d 100644 --- a/crates/bevy_reflect/src/impls/macros/map.rs +++ b/crates/bevy_reflect/src/impls/macros/map.rs @@ -131,11 +131,11 @@ macro_rules! impl_reflect_for_hashmap { $crate::kind::ReflectKind::Map } - fn reflect_ref(&self) -> $crate::kind::ReflectRef { + fn reflect_ref(&self) -> $crate::kind::ReflectRef<'_> { $crate::kind::ReflectRef::Map(self) } - fn reflect_mut(&mut self) -> $crate::kind::ReflectMut { + fn reflect_mut(&mut self) -> $crate::kind::ReflectMut<'_> { $crate::kind::ReflectMut::Map(self) } diff --git a/crates/bevy_reflect/src/impls/macros/set.rs b/crates/bevy_reflect/src/impls/macros/set.rs index 844b904cdec4c..69506a88e4549 100644 --- a/crates/bevy_reflect/src/impls/macros/set.rs +++ b/crates/bevy_reflect/src/impls/macros/set.rs @@ -114,11 +114,11 @@ macro_rules! impl_reflect_for_hashset { $crate::kind::ReflectKind::Set } - fn reflect_ref(&self) -> $crate::kind::ReflectRef { + fn reflect_ref(&self) -> $crate::kind::ReflectRef<'_> { $crate::kind::ReflectRef::Set(self) } - fn reflect_mut(&mut self) -> $crate::kind::ReflectMut { + fn reflect_mut(&mut self) -> $crate::kind::ReflectMut<'_> { $crate::kind::ReflectMut::Set(self) } diff --git a/crates/bevy_reflect/src/impls/smallvec.rs b/crates/bevy_reflect/src/impls/smallvec.rs index 86b7284381c39..21e5240683178 100644 --- a/crates/bevy_reflect/src/impls/smallvec.rs +++ b/crates/bevy_reflect/src/impls/smallvec.rs @@ -67,7 +67,7 @@ where >::len(self) } - fn iter(&self) -> ListIter { + fn iter(&self) -> ListIter<'_> { ListIter::new(self) } @@ -123,11 +123,11 @@ where ReflectKind::List } - fn reflect_ref(&self) -> ReflectRef { + fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::List(self) } - fn reflect_mut(&mut self) -> ReflectMut { + fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::List(self) } diff --git a/crates/bevy_reflect/src/impls/std/path.rs b/crates/bevy_reflect/src/impls/std/path.rs index a669068ae3aa4..df955d896855c 100644 --- a/crates/bevy_reflect/src/impls/std/path.rs +++ b/crates/bevy_reflect/src/impls/std/path.rs @@ -63,11 +63,11 @@ impl PartialReflect for &'static Path { ReflectKind::Opaque } - fn reflect_ref(&self) -> ReflectRef { + fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::Opaque(self) } - fn reflect_mut(&mut self) -> ReflectMut { + fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::Opaque(self) } @@ -194,11 +194,11 @@ impl PartialReflect for Cow<'static, Path> { ReflectKind::Opaque } - fn reflect_ref(&self) -> ReflectRef { + fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::Opaque(self) } - fn reflect_mut(&mut self) -> ReflectMut { + fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::Opaque(self) } diff --git a/crates/bevy_reflect/src/lib.rs b/crates/bevy_reflect/src/lib.rs index 401faa297c1fe..4e2592daaeb69 100644 --- a/crates/bevy_reflect/src/lib.rs +++ b/crates/bevy_reflect/src/lib.rs @@ -2711,11 +2711,9 @@ bevy_reflect::tests::Test { #[reflect(where T: Default)] struct Foo(String, #[reflect(ignore)] PhantomData); - #[expect(dead_code, reason = "Bar is never constructed")] #[derive(Default, TypePath)] struct Bar; - #[expect(dead_code, reason = "Baz is never constructed")] #[derive(TypePath)] struct Baz; @@ -2729,7 +2727,6 @@ bevy_reflect::tests::Test { #[reflect(where)] struct Foo(String, #[reflect(ignore)] PhantomData); - #[expect(dead_code, reason = "Bar is never constructed")] #[derive(TypePath)] struct Bar; @@ -2764,7 +2761,6 @@ bevy_reflect::tests::Test { #[reflect(where T::Assoc: core::fmt::Display)] struct Foo(T::Assoc); - #[expect(dead_code, reason = "Bar is never constructed")] #[derive(TypePath)] struct Bar; @@ -2772,7 +2768,6 @@ bevy_reflect::tests::Test { type Assoc = usize; } - #[expect(dead_code, reason = "Baz is never constructed")] #[derive(TypePath)] struct Baz; diff --git a/crates/bevy_reflect/src/list.rs b/crates/bevy_reflect/src/list.rs index 4ecdb632755d8..783eca12976d2 100644 --- a/crates/bevy_reflect/src/list.rs +++ b/crates/bevy_reflect/src/list.rs @@ -95,7 +95,7 @@ pub trait List: PartialReflect { } /// Returns an iterator over the list. - fn iter(&self) -> ListIter; + fn iter(&self) -> ListIter<'_>; /// Drain the elements of this list to get a vector of owned values. /// @@ -238,7 +238,7 @@ impl List for DynamicList { self.values.len() } - fn iter(&self) -> ListIter { + fn iter(&self) -> ListIter<'_> { ListIter::new(self) } @@ -294,12 +294,12 @@ impl PartialReflect for DynamicList { } #[inline] - fn reflect_ref(&self) -> ReflectRef { + fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::List(self) } #[inline] - fn reflect_mut(&mut self) -> ReflectMut { + fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::List(self) } @@ -382,7 +382,7 @@ pub struct ListIter<'a> { impl ListIter<'_> { /// Creates a new [`ListIter`]. #[inline] - pub const fn new(list: &dyn List) -> ListIter { + pub const fn new(list: &dyn List) -> ListIter<'_> { ListIter { list, index: 0 } } } diff --git a/crates/bevy_reflect/src/map.rs b/crates/bevy_reflect/src/map.rs index e7178692023e2..c2264ecf2d3d0 100644 --- a/crates/bevy_reflect/src/map.rs +++ b/crates/bevy_reflect/src/map.rs @@ -375,11 +375,11 @@ impl PartialReflect for DynamicMap { ReflectKind::Map } - fn reflect_ref(&self) -> ReflectRef { + fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::Map(self) } - fn reflect_mut(&mut self) -> ReflectMut { + fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::Map(self) } diff --git a/crates/bevy_reflect/src/path/error.rs b/crates/bevy_reflect/src/path/error.rs index 00188a4cc37b0..3287333b89f31 100644 --- a/crates/bevy_reflect/src/path/error.rs +++ b/crates/bevy_reflect/src/path/error.rs @@ -64,7 +64,7 @@ impl<'a> AccessError<'a> { } /// The returns the [`Access`] that this [`AccessError`] occurred in. - pub const fn access(&self) -> &Access { + pub const fn access(&self) -> &Access<'_> { &self.access } diff --git a/crates/bevy_reflect/src/path/mod.rs b/crates/bevy_reflect/src/path/mod.rs index f0434686eef4f..fad18746c27b5 100644 --- a/crates/bevy_reflect/src/path/mod.rs +++ b/crates/bevy_reflect/src/path/mod.rs @@ -414,7 +414,7 @@ impl ParsedPath { /// /// assert_eq!(parsed_path.element::(&foo).unwrap(), &123); /// ``` - pub fn parse(string: &str) -> PathResult { + pub fn parse(string: &str) -> PathResult<'_, Self> { let mut parts = Vec::new(); for (access, offset) in PathParser::new(string) { parts.push(OffsetAccess { diff --git a/crates/bevy_reflect/src/reflect.rs b/crates/bevy_reflect/src/reflect.rs index ffe9be54fef1f..1c86d8d4d2841 100644 --- a/crates/bevy_reflect/src/reflect.rs +++ b/crates/bevy_reflect/src/reflect.rs @@ -226,12 +226,12 @@ where /// Returns an immutable enumeration of "kinds" of type. /// /// See [`ReflectRef`]. - fn reflect_ref(&self) -> ReflectRef; + fn reflect_ref(&self) -> ReflectRef<'_>; /// Returns a mutable enumeration of "kinds" of type. /// /// See [`ReflectMut`]. - fn reflect_mut(&mut self) -> ReflectMut; + fn reflect_mut(&mut self) -> ReflectMut<'_>; /// Returns an owned enumeration of "kinds" of type. /// diff --git a/crates/bevy_reflect/src/set.rs b/crates/bevy_reflect/src/set.rs index e464ee4aab699..a49ee03cd86bb 100644 --- a/crates/bevy_reflect/src/set.rs +++ b/crates/bevy_reflect/src/set.rs @@ -301,11 +301,11 @@ impl PartialReflect for DynamicSet { ReflectKind::Set } - fn reflect_ref(&self) -> ReflectRef { + fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::Set(self) } - fn reflect_mut(&mut self) -> ReflectMut { + fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::Set(self) } diff --git a/crates/bevy_reflect/src/struct_trait.rs b/crates/bevy_reflect/src/struct_trait.rs index e419947b3ab5a..46c7a546fab42 100644 --- a/crates/bevy_reflect/src/struct_trait.rs +++ b/crates/bevy_reflect/src/struct_trait.rs @@ -69,7 +69,7 @@ pub trait Struct: PartialReflect { fn field_len(&self) -> usize; /// Returns an iterator over the values of the reflectable fields for this struct. - fn iter_fields(&self) -> FieldIter; + fn iter_fields(&self) -> FieldIter<'_>; /// Creates a new [`DynamicStruct`] from this struct. fn to_dynamic_struct(&self) -> DynamicStruct { @@ -371,7 +371,7 @@ impl Struct for DynamicStruct { } #[inline] - fn iter_fields(&self) -> FieldIter { + fn iter_fields(&self) -> FieldIter<'_> { FieldIter { struct_val: self, index: 0, @@ -429,12 +429,12 @@ impl PartialReflect for DynamicStruct { } #[inline] - fn reflect_ref(&self) -> ReflectRef { + fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::Struct(self) } #[inline] - fn reflect_mut(&mut self) -> ReflectMut { + fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::Struct(self) } diff --git a/crates/bevy_reflect/src/tuple.rs b/crates/bevy_reflect/src/tuple.rs index 97da69b5e2c73..fce437292bea9 100644 --- a/crates/bevy_reflect/src/tuple.rs +++ b/crates/bevy_reflect/src/tuple.rs @@ -50,7 +50,7 @@ pub trait Tuple: PartialReflect { fn field_len(&self) -> usize; /// Returns an iterator over the values of the tuple's fields. - fn iter_fields(&self) -> TupleFieldIter; + fn iter_fields(&self) -> TupleFieldIter<'_>; /// Drain the fields of this tuple to get a vector of owned values. fn drain(self: Box) -> Vec>; @@ -264,7 +264,7 @@ impl Tuple for DynamicTuple { } #[inline] - fn iter_fields(&self) -> TupleFieldIter { + fn iter_fields(&self) -> TupleFieldIter<'_> { TupleFieldIter { tuple: self, index: 0, @@ -318,12 +318,12 @@ impl PartialReflect for DynamicTuple { } #[inline] - fn reflect_ref(&self) -> ReflectRef { + fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::Tuple(self) } #[inline] - fn reflect_mut(&mut self) -> ReflectMut { + fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::Tuple(self) } @@ -493,7 +493,7 @@ macro_rules! impl_reflect_tuple { } #[inline] - fn iter_fields(&self) -> TupleFieldIter { + fn iter_fields(&self) -> TupleFieldIter<'_> { TupleFieldIter { tuple: self, index: 0, @@ -542,11 +542,11 @@ macro_rules! impl_reflect_tuple { ReflectKind::Tuple } - fn reflect_ref(&self) -> ReflectRef { + fn reflect_ref(&self) -> ReflectRef <'_> { ReflectRef::Tuple(self) } - fn reflect_mut(&mut self) -> ReflectMut { + fn reflect_mut(&mut self) -> ReflectMut <'_> { ReflectMut::Tuple(self) } diff --git a/crates/bevy_reflect/src/tuple_struct.rs b/crates/bevy_reflect/src/tuple_struct.rs index cceab9904e91a..f2eb4ae3adef2 100644 --- a/crates/bevy_reflect/src/tuple_struct.rs +++ b/crates/bevy_reflect/src/tuple_struct.rs @@ -53,7 +53,7 @@ pub trait TupleStruct: PartialReflect { fn field_len(&self) -> usize; /// Returns an iterator over the values of the tuple struct's fields. - fn iter_fields(&self) -> TupleStructFieldIter; + fn iter_fields(&self) -> TupleStructFieldIter<'_>; /// Creates a new [`DynamicTupleStruct`] from this tuple struct. fn to_dynamic_tuple_struct(&self) -> DynamicTupleStruct { @@ -278,7 +278,7 @@ impl TupleStruct for DynamicTupleStruct { } #[inline] - fn iter_fields(&self) -> TupleStructFieldIter { + fn iter_fields(&self) -> TupleStructFieldIter<'_> { TupleStructFieldIter { tuple_struct: self, index: 0, @@ -337,12 +337,12 @@ impl PartialReflect for DynamicTupleStruct { } #[inline] - fn reflect_ref(&self) -> ReflectRef { + fn reflect_ref(&self) -> ReflectRef<'_> { ReflectRef::TupleStruct(self) } #[inline] - fn reflect_mut(&mut self) -> ReflectMut { + fn reflect_mut(&mut self) -> ReflectMut<'_> { ReflectMut::TupleStruct(self) } diff --git a/crates/bevy_reflect/src/type_info.rs b/crates/bevy_reflect/src/type_info.rs index 122ace029364d..0a2db8d57a9ed 100644 --- a/crates/bevy_reflect/src/type_info.rs +++ b/crates/bevy_reflect/src/type_info.rs @@ -69,8 +69,8 @@ use thiserror::Error; /// # fn try_as_reflect(&self) -> Option<&dyn Reflect> { todo!() } /// # fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> { todo!() } /// # fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> { todo!() } -/// # fn reflect_ref(&self) -> ReflectRef { todo!() } -/// # fn reflect_mut(&mut self) -> ReflectMut { todo!() } +/// # fn reflect_ref(&self) -> ReflectRef<'_> { todo!() } +/// # fn reflect_mut(&mut self) -> ReflectMut<'_> { todo!() } /// # fn reflect_owned(self: Box) -> ReflectOwned { todo!() } /// # } /// # impl Reflect for MyStruct { diff --git a/crates/bevy_reflect/src/type_info_stack.rs b/crates/bevy_reflect/src/type_info_stack.rs index cdc19244de295..940bf4b6eafe7 100644 --- a/crates/bevy_reflect/src/type_info_stack.rs +++ b/crates/bevy_reflect/src/type_info_stack.rs @@ -30,7 +30,7 @@ impl TypeInfoStack { } /// Get an iterator over the stack in the order they were pushed. - pub fn iter(&self) -> Iter<&'static TypeInfo> { + pub fn iter(&self) -> Iter<'_, &'static TypeInfo> { self.stack.iter() } } diff --git a/crates/bevy_reflect/src/utility.rs b/crates/bevy_reflect/src/utility.rs index db8416bd6cbe1..cb0bf0f097121 100644 --- a/crates/bevy_reflect/src/utility.rs +++ b/crates/bevy_reflect/src/utility.rs @@ -86,8 +86,8 @@ mod sealed { /// # fn try_as_reflect(&self) -> Option<&dyn Reflect> { todo!() } /// # fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> { todo!() } /// # fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> { todo!() } -/// # fn reflect_ref(&self) -> ReflectRef { todo!() } -/// # fn reflect_mut(&mut self) -> ReflectMut { todo!() } +/// # fn reflect_ref(&self) -> ReflectRef<'_> { todo!() } +/// # fn reflect_mut(&mut self) -> ReflectMut<'_> { todo!() } /// # fn reflect_owned(self: Box) -> ReflectOwned { todo!() } /// # } /// # impl Reflect for Foo { @@ -173,8 +173,8 @@ impl Default for NonGenericTypeCell { /// # fn try_as_reflect(&self) -> Option<&dyn Reflect> { todo!() } /// # fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> { todo!() } /// # fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> { todo!() } -/// # fn reflect_ref(&self) -> ReflectRef { todo!() } -/// # fn reflect_mut(&mut self) -> ReflectMut { todo!() } +/// # fn reflect_ref(&self) -> ReflectRef<'_> { todo!() } +/// # fn reflect_mut(&mut self) -> ReflectMut<'_> { todo!() } /// # fn reflect_owned(self: Box) -> ReflectOwned { todo!() } /// # } /// # impl Reflect for Foo { diff --git a/crates/bevy_remote/src/builtin_methods.rs b/crates/bevy_remote/src/builtin_methods.rs index a959b69d7be36..42ae39887497b 100644 --- a/crates/bevy_remote/src/builtin_methods.rs +++ b/crates/bevy_remote/src/builtin_methods.rs @@ -590,11 +590,11 @@ pub fn process_remote_get_components_watching_request( continue; }; - if let Some(ticks) = entity_ref.get_change_ticks_by_id(component_id) { - if ticks.is_changed(world.last_change_tick(), world.read_change_tick()) { - changed.push(component_path); - continue; - } + if let Some(ticks) = entity_ref.get_change_ticks_by_id(component_id) + && ticks.is_changed(world.last_change_tick(), world.read_change_tick()) + { + changed.push(component_path); + continue; }; let Some(events) = world.removed_components().get(component_id) else { @@ -914,10 +914,10 @@ fn serialize_components( }; if let Some(reflect_component) = type_registration.data::() { // If a component_id is provided, check if the entity has it - if let Some(component_id) = component_id_opt { - if !entity_ref.contains_id(component_id) { - continue; - } + if let Some(component_id) = component_id_opt + && !entity_ref.contains_id(component_id) + { + continue; } if let Some(reflected) = reflect_component.reflect(entity_ref) { let reflect_serializer = diff --git a/crates/bevy_render/macros/src/as_bind_group.rs b/crates/bevy_render/macros/src/as_bind_group.rs index b426088e22794..0fc325136c166 100644 --- a/crates/bevy_render/macros/src/as_bind_group.rs +++ b/crates/bevy_render/macros/src/as_bind_group.rs @@ -154,17 +154,18 @@ pub fn derive_as_bind_group(ast: syn::DeriveInput) -> Result { // Read struct-level attributes, second pass. for attr in &ast.attrs { - if let Some(attr_ident) = attr.path().get_ident() { - if attr_ident == UNIFORM_ATTRIBUTE_NAME || attr_ident == DATA_ATTRIBUTE_NAME { - let UniformBindingAttr { - binding_type, - binding_index, - converted_shader_type, - binding_array: binding_array_binding, - } = get_uniform_binding_attr(attr)?; - match binding_type { - UniformBindingAttrType::Uniform => { - binding_impls.push(quote! {{ + if let Some(attr_ident) = attr.path().get_ident() + && (attr_ident == UNIFORM_ATTRIBUTE_NAME || attr_ident == DATA_ATTRIBUTE_NAME) + { + let UniformBindingAttr { + binding_type, + binding_index, + converted_shader_type, + binding_array: binding_array_binding, + } = get_uniform_binding_attr(attr)?; + match binding_type { + UniformBindingAttrType::Uniform => { + binding_impls.push(quote! {{ use #render_path::render_resource::AsBindGroupShaderType; let mut buffer = #render_path::render_resource::encase::UniformBuffer::new(Vec::new()); let converted: #converted_shader_type = self.as_bind_group_shader_type(&images); @@ -181,26 +182,26 @@ pub fn derive_as_bind_group(ast: syn::DeriveInput) -> Result { ) }}); - match (&binding_array_binding, &attr_bindless_count) { - (&None, &Some(_)) => { - return Err(Error::new_spanned( - attr, - "Must specify `binding_array(...)` with `#[uniform]` if the \ + match (&binding_array_binding, &attr_bindless_count) { + (&None, &Some(_)) => { + return Err(Error::new_spanned( + attr, + "Must specify `binding_array(...)` with `#[uniform]` if the \ object is bindless", - )); - } - (&Some(_), &None) => { - return Err(Error::new_spanned( - attr, - "`binding_array(...)` with `#[uniform]` requires the object to \ + )); + } + (&Some(_), &None) => { + return Err(Error::new_spanned( + attr, + "`binding_array(...)` with `#[uniform]` requires the object to \ be bindless", - )); - } - _ => {} + )); } + _ => {} + } - let binding_array_binding = binding_array_binding.unwrap_or(0); - bindless_binding_layouts.push(quote! { + let binding_array_binding = binding_array_binding.unwrap_or(0); + bindless_binding_layouts.push(quote! { #bind_group_layout_entries.push( #render_path::render_resource::BindGroupLayoutEntry { binding: #binding_array_binding, @@ -215,16 +216,16 @@ pub fn derive_as_bind_group(ast: syn::DeriveInput) -> Result { ); }); - add_bindless_resource_type( - &render_path, - &mut bindless_resource_types, - binding_index, - quote! { #render_path::render_resource::BindlessResourceType::Buffer }, - ); - } + add_bindless_resource_type( + &render_path, + &mut bindless_resource_types, + binding_index, + quote! { #render_path::render_resource::BindlessResourceType::Buffer }, + ); + } - UniformBindingAttrType::Data => { - binding_impls.push(quote! {{ + UniformBindingAttrType::Data => { + binding_impls.push(quote! {{ use #render_path::render_resource::AsBindGroupShaderType; use #render_path::render_resource::encase::{ShaderType, internal::WriteInto}; let mut buffer: Vec = Vec::new(); @@ -248,8 +249,8 @@ pub fn derive_as_bind_group(ast: syn::DeriveInput) -> Result { ) }}); - let binding_array_binding = binding_array_binding.unwrap_or(0); - bindless_binding_layouts.push(quote! { + let binding_array_binding = binding_array_binding.unwrap_or(0); + bindless_binding_layouts.push(quote! { #bind_group_layout_entries.push( #render_path::render_resource::BindGroupLayoutEntry { binding: #binding_array_binding, @@ -264,18 +265,18 @@ pub fn derive_as_bind_group(ast: syn::DeriveInput) -> Result { ); }); - add_bindless_resource_type( - &render_path, - &mut bindless_resource_types, - binding_index, - quote! { #render_path::render_resource::BindlessResourceType::DataBuffer }, - ); - } + add_bindless_resource_type( + &render_path, + &mut bindless_resource_types, + binding_index, + quote! { #render_path::render_resource::BindlessResourceType::DataBuffer }, + ); } + } - // Push the non-bindless binding layout. + // Push the non-bindless binding layout. - non_bindless_binding_layouts.push(quote!{ + non_bindless_binding_layouts.push(quote!{ #bind_group_layout_entries.push( #render_path::render_resource::BindGroupLayoutEntry { binding: #binding_index, @@ -290,33 +291,32 @@ pub fn derive_as_bind_group(ast: syn::DeriveInput) -> Result { ); }); - bindless_buffer_descriptors.push(quote! { - #render_path::render_resource::BindlessBufferDescriptor { - // Note that, because this is bindless, *binding - // index* here refers to the index in the - // bindless index table (`bindless_index`), and - // the actual binding number is the *binding - // array binding*. - binding_number: #render_path::render_resource::BindingNumber( - #binding_array_binding - ), - bindless_index: - #render_path::render_resource::BindlessIndex(#binding_index), - size: Some( - < - #converted_shader_type as - #render_path::render_resource::ShaderType - >::min_size().get() as usize - ), - } - }); - - let required_len = binding_index as usize + 1; - if required_len > binding_states.len() { - binding_states.resize(required_len, BindingState::Free); + bindless_buffer_descriptors.push(quote! { + #render_path::render_resource::BindlessBufferDescriptor { + // Note that, because this is bindless, *binding + // index* here refers to the index in the + // bindless index table (`bindless_index`), and + // the actual binding number is the *binding + // array binding*. + binding_number: #render_path::render_resource::BindingNumber( + #binding_array_binding + ), + bindless_index: + #render_path::render_resource::BindlessIndex(#binding_index), + size: Some( + < + #converted_shader_type as + #render_path::render_resource::ShaderType + >::min_size().get() as usize + ), } - binding_states[binding_index as usize] = BindingState::OccupiedConvertedUniform; + }); + + let required_len = binding_index as usize + 1; + if required_len > binding_states.len() { + binding_states.resize(required_len, BindingState::Free); } + binding_states[binding_index as usize] = BindingState::OccupiedConvertedUniform; } } @@ -1390,13 +1390,13 @@ fn get_visibility_flag_value(meta_list: &MetaList) -> Result syn::Result { let specialize_attr = ast.attrs.iter().find_map(|attr| { - if attr.path().is_ident(SPECIALIZE_ATTR_IDENT) { - if let Meta::List(meta_list) = &attr.meta { - return Some(meta_list); - } + if attr.path().is_ident(SPECIALIZE_ATTR_IDENT) + && let Meta::List(meta_list) = &attr.meta + { + return Some(meta_list); } None }); diff --git a/crates/bevy_render/src/batching/gpu_preprocessing.rs b/crates/bevy_render/src/batching/gpu_preprocessing.rs index c8a0f1817e65c..35671a84e0ef9 100644 --- a/crates/bevy_render/src/batching/gpu_preprocessing.rs +++ b/crates/bevy_render/src/batching/gpu_preprocessing.rs @@ -1185,7 +1185,7 @@ where /// Returns the binding of the buffer that contains the per-instance data. /// /// This buffer needs to be filled in via a compute shader. - pub fn instance_data_binding(&self) -> Option { + pub fn instance_data_binding(&self) -> Option> { self.data_buffer .buffer() .map(|buffer| buffer.as_entire_binding()) diff --git a/crates/bevy_render/src/batching/no_gpu_preprocessing.rs b/crates/bevy_render/src/batching/no_gpu_preprocessing.rs index 8bbbff8dd9e46..a6127255911bd 100644 --- a/crates/bevy_render/src/batching/no_gpu_preprocessing.rs +++ b/crates/bevy_render/src/batching/no_gpu_preprocessing.rs @@ -42,7 +42,7 @@ where /// /// If we're in the GPU instance buffer building mode, this buffer needs to /// be filled in via a compute shader. - pub fn instance_data_binding(&self) -> Option { + pub fn instance_data_binding(&self) -> Option> { self.binding() } } diff --git a/crates/bevy_render/src/camera.rs b/crates/bevy_render/src/camera.rs index c3f720b619fca..c53ffd82f5da2 100644 --- a/crates/bevy_render/src/camera.rs +++ b/crates/bevy_render/src/camera.rs @@ -316,64 +316,57 @@ pub fn camera_system( .as_ref() .map(|viewport| viewport.physical_size); - if let Some(normalized_target) = &camera.target.normalize(primary_window) { - if normalized_target.is_changed(&changed_window_ids, &changed_image_handles) + if let Some(normalized_target) = &camera.target.normalize(primary_window) + && (normalized_target.is_changed(&changed_window_ids, &changed_image_handles) || camera.is_added() || camera_projection.is_changed() || camera.computed.old_viewport_size != viewport_size - || camera.computed.old_sub_camera_view != camera.sub_camera_view + || camera.computed.old_sub_camera_view != camera.sub_camera_view) + { + let new_computed_target_info = + normalized_target.get_render_target_info(windows, &images, &manual_texture_views); + // Check for the scale factor changing, and resize the viewport if needed. + // This can happen when the window is moved between monitors with different DPIs. + // Without this, the viewport will take a smaller portion of the window moved to + // a higher DPI monitor. + if normalized_target.is_changed(&scale_factor_changed_window_ids, &HashSet::default()) + && let (Some(new_scale_factor), Some(old_scale_factor)) = ( + new_computed_target_info + .as_ref() + .map(|info| info.scale_factor), + camera + .computed + .target_info + .as_ref() + .map(|info| info.scale_factor), + ) { - let new_computed_target_info = normalized_target.get_render_target_info( - windows, - &images, - &manual_texture_views, - ); - // Check for the scale factor changing, and resize the viewport if needed. - // This can happen when the window is moved between monitors with different DPIs. - // Without this, the viewport will take a smaller portion of the window moved to - // a higher DPI monitor. - if normalized_target - .is_changed(&scale_factor_changed_window_ids, &HashSet::default()) - { - if let (Some(new_scale_factor), Some(old_scale_factor)) = ( - new_computed_target_info - .as_ref() - .map(|info| info.scale_factor), - camera - .computed - .target_info - .as_ref() - .map(|info| info.scale_factor), - ) { - let resize_factor = new_scale_factor / old_scale_factor; - if let Some(ref mut viewport) = camera.viewport { - let resize = |vec: UVec2| (vec.as_vec2() * resize_factor).as_uvec2(); - viewport.physical_position = resize(viewport.physical_position); - viewport.physical_size = resize(viewport.physical_size); - viewport_size = Some(viewport.physical_size); - } - } + let resize_factor = new_scale_factor / old_scale_factor; + if let Some(ref mut viewport) = camera.viewport { + let resize = |vec: UVec2| (vec.as_vec2() * resize_factor).as_uvec2(); + viewport.physical_position = resize(viewport.physical_position); + viewport.physical_size = resize(viewport.physical_size); + viewport_size = Some(viewport.physical_size); } - // This check is needed because when changing WindowMode to Fullscreen, the viewport may have invalid - // arguments due to a sudden change on the window size to a lower value. - // If the size of the window is lower, the viewport will match that lower value. - if let Some(viewport) = &mut camera.viewport { - let target_info = &new_computed_target_info; - if let Some(target) = target_info { - viewport.clamp_to_size(target.physical_size); - } + } + // This check is needed because when changing WindowMode to Fullscreen, the viewport may have invalid + // arguments due to a sudden change on the window size to a lower value. + // If the size of the window is lower, the viewport will match that lower value. + if let Some(viewport) = &mut camera.viewport { + let target_info = &new_computed_target_info; + if let Some(target) = target_info { + viewport.clamp_to_size(target.physical_size); } - camera.computed.target_info = new_computed_target_info; - if let Some(size) = camera.logical_viewport_size() { - if size.x != 0.0 && size.y != 0.0 { - camera_projection.update(size.x, size.y); - camera.computed.clip_from_view = match &camera.sub_camera_view { - Some(sub_view) => { - camera_projection.get_clip_from_view_for_sub(sub_view) - } - None => camera_projection.get_clip_from_view(), - } - } + } + camera.computed.target_info = new_computed_target_info; + if let Some(size) = camera.logical_viewport_size() + && size.x != 0.0 + && size.y != 0.0 + { + camera_projection.update(size.x, size.y); + camera.computed.clip_from_view = match &camera.sub_camera_view { + Some(sub_view) => camera_projection.get_clip_from_view_for_sub(sub_view), + None => camera_projection.get_clip_from_view(), } } } @@ -616,10 +609,10 @@ pub fn sort_cameras( let mut target_counts = >::default(); for sorted_camera in &mut sorted_cameras.0 { let new_order_target = (sorted_camera.order, sorted_camera.target.clone()); - if let Some(previous_order_target) = previous_order_target { - if previous_order_target == new_order_target { - ambiguities.insert(new_order_target.clone()); - } + if let Some(previous_order_target) = previous_order_target + && previous_order_target == new_order_target + { + ambiguities.insert(new_order_target.clone()); } if let Some(target) = &sorted_camera.target { let count = target_counts diff --git a/crates/bevy_render/src/extract_instances.rs b/crates/bevy_render/src/extract_instances.rs index cf0d0c0cce4ba..d85f8fa646b34 100644 --- a/crates/bevy_render/src/extract_instances.rs +++ b/crates/bevy_render/src/extract_instances.rs @@ -128,10 +128,10 @@ fn extract_visible( { extracted_instances.clear(); for (entity, view_visibility, other) in &query { - if view_visibility.get() { - if let Some(extract_instance) = EI::extract(other) { - extracted_instances.insert(entity.into(), extract_instance); - } + if view_visibility.get() + && let Some(extract_instance) = EI::extract(other) + { + extracted_instances.insert(entity.into(), extract_instance); } } } diff --git a/crates/bevy_render/src/lib.rs b/crates/bevy_render/src/lib.rs index 79a769effe737..bd7b350d93da4 100644 --- a/crates/bevy_render/src/lib.rs +++ b/crates/bevy_render/src/lib.rs @@ -642,13 +642,13 @@ pub fn get_mali_driver_version(adapter: &RenderAdapter) -> Option { return None; } let driver_info = adapter.get_info().driver_info; - if let Some(start_pos) = driver_info.find("v1.r") { - if let Some(end_pos) = driver_info[start_pos..].find('p') { - let start_idx = start_pos + 4; // Skip "v1.r" - let end_idx = start_pos + end_pos; + if let Some(start_pos) = driver_info.find("v1.r") + && let Some(end_pos) = driver_info[start_pos..].find('p') + { + let start_idx = start_pos + 4; // Skip "v1.r" + let end_idx = start_pos + end_pos; - return driver_info[start_idx..end_idx].parse::().ok(); - } + return driver_info[start_idx..end_idx].parse::().ok(); } None diff --git a/crates/bevy_render/src/mesh/allocator.rs b/crates/bevy_render/src/mesh/allocator.rs index bbdb543116b6e..3746acbbc4f3d 100644 --- a/crates/bevy_render/src/mesh/allocator.rs +++ b/crates/bevy_render/src/mesh/allocator.rs @@ -384,7 +384,7 @@ impl MeshAllocator { /// the mesh with the given ID. /// /// If the mesh wasn't allocated, returns None. - pub fn mesh_vertex_slice(&self, mesh_id: &AssetId) -> Option { + pub fn mesh_vertex_slice(&self, mesh_id: &AssetId) -> Option> { self.mesh_slice_in_slab(mesh_id, *self.mesh_id_to_vertex_slab.get(mesh_id)?) } @@ -392,7 +392,7 @@ impl MeshAllocator { /// the mesh with the given ID. /// /// If the mesh has no index data or wasn't allocated, returns None. - pub fn mesh_index_slice(&self, mesh_id: &AssetId) -> Option { + pub fn mesh_index_slice(&self, mesh_id: &AssetId) -> Option> { self.mesh_slice_in_slab(mesh_id, *self.mesh_id_to_index_slab.get(mesh_id)?) } @@ -415,7 +415,7 @@ impl MeshAllocator { &self, mesh_id: &AssetId, slab_id: SlabId, - ) -> Option { + ) -> Option> { match self.slabs.get(&slab_id)? { Slab::General(general_slab) => { let slab_allocation = general_slab.resident_allocations.get(mesh_id)?; diff --git a/crates/bevy_render/src/render_graph/graph.rs b/crates/bevy_render/src/render_graph/graph.rs index d1a7020bcfcab..a7c4851d869b5 100644 --- a/crates/bevy_render/src/render_graph/graph.rs +++ b/crates/bevy_render/src/render_graph/graph.rs @@ -478,14 +478,13 @@ impl RenderGraph { } else { false } - }) { - if should_exist == EdgeExistence::DoesNotExist { - return Err(RenderGraphError::NodeInputSlotAlreadyOccupied { - node: input_node, - input_slot: input_index, - occupied_by_node: *current_output_node, - }); - } + }) && should_exist == EdgeExistence::DoesNotExist + { + return Err(RenderGraphError::NodeInputSlotAlreadyOccupied { + node: input_node, + input_slot: input_index, + occupied_by_node: *current_output_node, + }); } if output_slot.slot_type != input_slot.slot_type { @@ -507,14 +506,12 @@ impl RenderGraph { pub fn has_edge(&self, edge: &Edge) -> bool { let output_node_state = self.get_node_state(edge.get_output_node()); let input_node_state = self.get_node_state(edge.get_input_node()); - if let Ok(output_node_state) = output_node_state { - if output_node_state.edges.output_edges().contains(edge) { - if let Ok(input_node_state) = input_node_state { - if input_node_state.edges.input_edges().contains(edge) { - return true; - } - } - } + if let Ok(output_node_state) = output_node_state + && output_node_state.edges.output_edges().contains(edge) + && let Ok(input_node_state) = input_node_state + && input_node_state.edges.input_edges().contains(edge) + { + return true; } false diff --git a/crates/bevy_render/src/render_phase/mod.rs b/crates/bevy_render/src/render_phase/mod.rs index fb9433d804e2b..253d06f48521e 100644 --- a/crates/bevy_render/src/render_phase/mod.rs +++ b/crates/bevy_render/src/render_phase/mod.rs @@ -612,13 +612,13 @@ where // If the entity changed bins, record its old bin so that we can remove // the entity from it. - if let Some(old_cached_binned_entity) = old_cached_binned_entity { - if old_cached_binned_entity.cached_bin_key != new_cached_binned_entity.cached_bin_key { - self.entities_that_changed_bins.push(EntityThatChangedBins { - main_entity, - old_cached_binned_entity, - }); - } + if let Some(old_cached_binned_entity) = old_cached_binned_entity + && old_cached_binned_entity.cached_bin_key != new_cached_binned_entity.cached_bin_key + { + self.entities_that_changed_bins.push(EntityThatChangedBins { + main_entity, + old_cached_binned_entity, + }); } // Mark the entity as valid. @@ -904,11 +904,10 @@ where ) -> bool { if let indexmap::map::Entry::Occupied(entry) = self.cached_entity_bin_keys.entry(visible_entity) + && entry.get().change_tick == current_change_tick { - if entry.get().change_tick == current_change_tick { - self.valid_cached_entity_bin_keys.insert(entry.index()); - return true; - } + self.valid_cached_entity_bin_keys.insert(entry.index()); + return true; } false diff --git a/crates/bevy_render/src/render_resource/batched_uniform_buffer.rs b/crates/bevy_render/src/render_resource/batched_uniform_buffer.rs index fecc90feac1a4..ad36839398715 100644 --- a/crates/bevy_render/src/render_resource/batched_uniform_buffer.rs +++ b/crates/bevy_render/src/render_resource/batched_uniform_buffer.rs @@ -109,7 +109,7 @@ impl BatchedUniformBuffer { } #[inline] - pub fn binding(&self) -> Option { + pub fn binding(&self) -> Option> { let mut binding = self.uniforms.binding(); if let Some(BindingResource::Buffer(binding)) = &mut binding { // MaxCapacityArray is runtime-sized so can't use T::min_size() diff --git a/crates/bevy_render/src/render_resource/bind_group.rs b/crates/bevy_render/src/render_resource/bind_group.rs index 1772c0082e8a4..3d808b31c4a3b 100644 --- a/crates/bevy_render/src/render_resource/bind_group.rs +++ b/crates/bevy_render/src/render_resource/bind_group.rs @@ -659,7 +659,7 @@ impl OwnedBindingResource { /// [`OwnedBindingResource::Data`], because [`OwnedData`] doesn't itself /// correspond to any binding and instead requires the /// `MaterialBindGroupAllocator` to pack it into a buffer. - pub fn get_binding(&self) -> BindingResource { + pub fn get_binding(&self) -> BindingResource<'_> { match self { OwnedBindingResource::Buffer(buffer) => buffer.as_entire_binding(), OwnedBindingResource::TextureView(_, view) => BindingResource::TextureView(view), diff --git a/crates/bevy_render/src/render_resource/buffer.rs b/crates/bevy_render/src/render_resource/buffer.rs index 811930da83667..22b8a933e0118 100644 --- a/crates/bevy_render/src/render_resource/buffer.rs +++ b/crates/bevy_render/src/render_resource/buffer.rs @@ -16,7 +16,7 @@ impl Buffer { self.id } - pub fn slice(&self, bounds: impl RangeBounds) -> BufferSlice { + pub fn slice(&self, bounds: impl RangeBounds) -> BufferSlice<'_> { // need to compute and store this manually because wgpu doesn't export offset and size on wgpu::BufferSlice let offset = match bounds.start_bound() { Bound::Included(&bound) => bound, diff --git a/crates/bevy_render/src/render_resource/buffer_vec.rs b/crates/bevy_render/src/render_resource/buffer_vec.rs index 1fdb26655dd45..e51f78cbc13e4 100644 --- a/crates/bevy_render/src/render_resource/buffer_vec.rs +++ b/crates/bevy_render/src/render_resource/buffer_vec.rs @@ -68,7 +68,7 @@ impl RawBufferVec { /// Returns the binding for the buffer if the data has been uploaded. #[inline] - pub fn binding(&self) -> Option { + pub fn binding(&self) -> Option> { Some(BindingResource::Buffer( self.buffer()?.as_entire_buffer_binding(), )) @@ -310,7 +310,7 @@ where /// Returns the binding for the buffer if the data has been uploaded. #[inline] - pub fn binding(&self) -> Option { + pub fn binding(&self) -> Option> { Some(BindingResource::Buffer( self.buffer()?.as_entire_buffer_binding(), )) @@ -498,7 +498,7 @@ where /// Returns the binding for the buffer if the data has been uploaded. #[inline] - pub fn binding(&self) -> Option { + pub fn binding(&self) -> Option> { Some(BindingResource::Buffer( self.buffer()?.as_entire_buffer_binding(), )) 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 0c5bf36bf6e35..2c81f56019d94 100644 --- a/crates/bevy_render/src/render_resource/gpu_array_buffer.rs +++ b/crates/bevy_render/src/render_resource/gpu_array_buffer.rs @@ -89,7 +89,7 @@ impl GpuArrayBuffer { } } - pub fn binding(&self) -> Option { + pub fn binding(&self) -> Option> { match self { GpuArrayBuffer::Uniform(buffer) => buffer.binding(), GpuArrayBuffer::Storage(buffer) => buffer.binding(), diff --git a/crates/bevy_render/src/render_resource/storage_buffer.rs b/crates/bevy_render/src/render_resource/storage_buffer.rs index b407e22d8f9e6..dd76f46a9c1c4 100644 --- a/crates/bevy_render/src/render_resource/storage_buffer.rs +++ b/crates/bevy_render/src/render_resource/storage_buffer.rs @@ -76,7 +76,7 @@ impl StorageBuffer { } #[inline] - pub fn binding(&self) -> Option { + pub fn binding(&self) -> Option> { Some(BindingResource::Buffer(BufferBinding { buffer: self.buffer()?, offset: 0, @@ -209,7 +209,7 @@ impl DynamicStorageBuffer { } #[inline] - pub fn binding(&self) -> Option { + pub fn binding(&self) -> Option> { Some(BindingResource::Buffer(BufferBinding { buffer: self.buffer()?, offset: 0, diff --git a/crates/bevy_render/src/render_resource/uniform_buffer.rs b/crates/bevy_render/src/render_resource/uniform_buffer.rs index b7d22972df469..03cfb8c644991 100644 --- a/crates/bevy_render/src/render_resource/uniform_buffer.rs +++ b/crates/bevy_render/src/render_resource/uniform_buffer.rs @@ -78,7 +78,7 @@ impl UniformBuffer { } #[inline] - pub fn binding(&self) -> Option { + pub fn binding(&self) -> Option> { Some(BindingResource::Buffer( self.buffer()?.as_entire_buffer_binding(), )) @@ -213,7 +213,7 @@ impl DynamicUniformBuffer { } #[inline] - pub fn binding(&self) -> Option { + pub fn binding(&self) -> Option> { Some(BindingResource::Buffer(BufferBinding { buffer: self.buffer()?, offset: 0, diff --git a/crates/bevy_render/src/renderer/mod.rs b/crates/bevy_render/src/renderer/mod.rs index d0ccd526e1235..e06053cfd3cc0 100644 --- a/crates/bevy_render/src/renderer/mod.rs +++ b/crates/bevy_render/src/renderer/mod.rs @@ -155,10 +155,10 @@ fn find_adapter_by_name( { tracing::trace!("Checking adapter: {:?}", adapter.get_info()); let info = adapter.get_info(); - if let Some(surface) = compatible_surface { - if !adapter.is_surface_supported(surface) { - continue; - } + if let Some(surface) = compatible_surface + && !adapter.is_surface_supported(surface) + { + continue; } if info.name.eq_ignore_ascii_case(adapter_name) { diff --git a/crates/bevy_render/src/renderer/render_device.rs b/crates/bevy_render/src/renderer/render_device.rs index 6785ad9c997c7..c965a9fb14424 100644 --- a/crates/bevy_render/src/renderer/render_device.rs +++ b/crates/bevy_render/src/renderer/render_device.rs @@ -139,7 +139,7 @@ impl RenderDevice { pub fn create_render_bundle_encoder( &self, desc: &wgpu::RenderBundleEncoderDescriptor, - ) -> wgpu::RenderBundleEncoder { + ) -> wgpu::RenderBundleEncoder<'_> { self.device.create_render_bundle_encoder(desc) } diff --git a/crates/bevy_render/src/texture/texture_attachment.rs b/crates/bevy_render/src/texture/texture_attachment.rs index 17ae6ea6c957f..cf0e057db0f21 100644 --- a/crates/bevy_render/src/texture/texture_attachment.rs +++ b/crates/bevy_render/src/texture/texture_attachment.rs @@ -34,7 +34,7 @@ impl ColorAttachment { /// `clear_color` if this is the first time calling this function, otherwise it will be loaded. /// /// The returned attachment will always have writing enabled (`store: StoreOp::Load`). - pub fn get_attachment(&self) -> RenderPassColorAttachment { + pub fn get_attachment(&self) -> RenderPassColorAttachment<'_> { if let Some(resolve_target) = self.resolve_target.as_ref() { let first_call = self.is_first_call.fetch_and(false, Ordering::SeqCst); @@ -59,7 +59,7 @@ impl ColorAttachment { /// a value of `clear_color` if this is the first time calling this function, otherwise it will be loaded. /// /// The returned attachment will always have writing enabled (`store: StoreOp::Load`). - pub fn get_unsampled_attachment(&self) -> RenderPassColorAttachment { + pub fn get_unsampled_attachment(&self) -> RenderPassColorAttachment<'_> { let first_call = self.is_first_call.fetch_and(false, Ordering::SeqCst); RenderPassColorAttachment { @@ -101,7 +101,7 @@ impl DepthAttachment { /// Get this texture view as an attachment. The attachment will be cleared with a value of /// `clear_value` if this is the first time calling this function with `store` == [`StoreOp::Store`], /// and a clear value was provided, otherwise it will be loaded. - pub fn get_attachment(&self, store: StoreOp) -> RenderPassDepthStencilAttachment { + pub fn get_attachment(&self, store: StoreOp) -> RenderPassDepthStencilAttachment<'_> { let first_call = self .is_first_call .fetch_and(store != StoreOp::Store, Ordering::SeqCst); @@ -143,7 +143,7 @@ impl OutputColorAttachment { /// Get this texture view as an attachment. The attachment will be cleared with a value of /// the provided `clear_color` if this is the first time calling this function, otherwise it /// will be loaded. - pub fn get_attachment(&self, clear_color: Option) -> RenderPassColorAttachment { + pub fn get_attachment(&self, clear_color: Option) -> RenderPassColorAttachment<'_> { let first_call = self.is_first_call.fetch_and(false, Ordering::SeqCst); RenderPassColorAttachment { diff --git a/crates/bevy_render/src/view/mod.rs b/crates/bevy_render/src/view/mod.rs index cb46c9215a085..2ffe9a24cbe3d 100644 --- a/crates/bevy_render/src/view/mod.rs +++ b/crates/bevy_render/src/view/mod.rs @@ -725,7 +725,7 @@ impl ViewTarget { pub const TEXTURE_FORMAT_HDR: TextureFormat = TextureFormat::Rgba16Float; /// Retrieve this target's main texture's color attachment. - pub fn get_color_attachment(&self) -> RenderPassColorAttachment { + pub fn get_color_attachment(&self) -> RenderPassColorAttachment<'_> { if self.main_texture.load(Ordering::SeqCst) == 0 { self.main_textures.a.get_attachment() } else { @@ -734,7 +734,7 @@ impl ViewTarget { } /// Retrieve this target's "unsampled" main texture's color attachment. - pub fn get_unsampled_color_attachment(&self) -> RenderPassColorAttachment { + pub fn get_unsampled_color_attachment(&self) -> RenderPassColorAttachment<'_> { if self.main_texture.load(Ordering::SeqCst) == 0 { self.main_textures.a.get_unsampled_attachment() } else { @@ -826,7 +826,7 @@ impl ViewTarget { pub fn out_texture_color_attachment( &self, clear_color: Option, - ) -> RenderPassColorAttachment { + ) -> RenderPassColorAttachment<'_> { self.out_texture.get_attachment(clear_color) } @@ -843,7 +843,7 @@ impl ViewTarget { /// [`ViewTarget`]'s main texture to the `destination` texture, so the caller /// _must_ ensure `source` is copied to `destination`, with or without modifications. /// Failing to do so will cause the current main texture information to be lost. - pub fn post_process_write(&self) -> PostProcessWrite { + pub fn post_process_write(&self) -> PostProcessWrite<'_> { let old_is_a_main_texture = self.main_texture.fetch_xor(1, Ordering::SeqCst); // if the old main texture is a, then the post processing must write from a to b if old_is_a_main_texture == 0 { @@ -880,7 +880,7 @@ impl ViewDepthTexture { } } - pub fn get_attachment(&self, store: StoreOp) -> RenderPassDepthStencilAttachment { + pub fn get_attachment(&self, store: StoreOp) -> RenderPassDepthStencilAttachment<'_> { self.attachment.get_attachment(store) } diff --git a/crates/bevy_scene/src/dynamic_scene.rs b/crates/bevy_scene/src/dynamic_scene.rs index fc3b223ce2b60..e6740090c65a4 100644 --- a/crates/bevy_scene/src/dynamic_scene.rs +++ b/crates/bevy_scene/src/dynamic_scene.rs @@ -122,7 +122,10 @@ impl DynamicScene { #[expect(unsafe_code, reason = "this is faster")] let component_info = unsafe { world.components().get_info_unchecked(component_id) }; - if *component_info.clone_behavior() == ComponentCloneBehavior::Ignore { + if matches!( + *component_info.clone_behavior(), + ComponentCloneBehavior::Ignore + ) { continue; } } diff --git a/crates/bevy_scene/src/scene.rs b/crates/bevy_scene/src/scene.rs index 2293beef1e9a2..255f688673c86 100644 --- a/crates/bevy_scene/src/scene.rs +++ b/crates/bevy_scene/src/scene.rs @@ -126,7 +126,10 @@ impl Scene { .get_info(component_id) .expect("component_ids in archetypes should have ComponentInfo"); - if *component_info.clone_behavior() == ComponentCloneBehavior::Ignore { + if matches!( + *component_info.clone_behavior(), + ComponentCloneBehavior::Ignore + ) { continue; } diff --git a/crates/bevy_scene/src/scene_spawner.rs b/crates/bevy_scene/src/scene_spawner.rs index afd8958149e05..386e81080a106 100644 --- a/crates/bevy_scene/src/scene_spawner.rs +++ b/crates/bevy_scene/src/scene_spawner.rs @@ -552,10 +552,10 @@ pub fn scene_spawner_system(world: &mut World) { .scene_asset_event_reader .read(scene_asset_events) { - if let AssetEvent::Modified { id } = event { - if scene_spawner.spawned_scenes.contains_key(id) { - updated_spawned_scenes.push(*id); - } + if let AssetEvent::Modified { id } = event + && scene_spawner.spawned_scenes.contains_key(id) + { + updated_spawned_scenes.push(*id); } } let mut updated_spawned_dynamic_scenes = Vec::new(); @@ -563,10 +563,10 @@ pub fn scene_spawner_system(world: &mut World) { .dynamic_scene_asset_event_reader .read(dynamic_scene_asset_events) { - if let AssetEvent::Modified { id } = event { - if scene_spawner.spawned_dynamic_scenes.contains_key(id) { - updated_spawned_dynamic_scenes.push(*id); - } + if let AssetEvent::Modified { id } = event + && scene_spawner.spawned_dynamic_scenes.contains_key(id) + { + updated_spawned_dynamic_scenes.push(*id); } } diff --git a/crates/bevy_shader/src/shader_cache.rs b/crates/bevy_shader/src/shader_cache.rs index 5974209cb522e..77a004ecebb8e 100644 --- a/crates/bevy_shader/src/shader_cache.rs +++ b/crates/bevy_shader/src/shader_cache.rs @@ -357,11 +357,11 @@ impl ShaderCache { } #[cfg(feature = "shader_format_wesl")] - if let Source::Wesl(_) = shader.source { - if let ShaderImport::AssetPath(path) = shader.import_path() { - self.asset_paths - .insert(wesl::syntax::ModulePath::from_path(path), id); - } + if let Source::Wesl(_) = shader.source + && let ShaderImport::AssetPath(path) = shader.import_path() + { + self.asset_paths + .insert(wesl::syntax::ModulePath::from_path(path), id); } self.shaders.insert(id, shader); pipelines_to_queue @@ -401,7 +401,7 @@ impl<'a> wesl::Resolver for ShaderResolver<'a> { fn resolve_source( &self, module_path: &wesl::syntax::ModulePath, - ) -> Result, wesl::ResolveError> { + ) -> Result, wesl::ResolveError> { let asset_id = self.asset_paths.get(module_path).ok_or_else(|| { wesl::ResolveError::ModuleNotFound(module_path.clone(), "Invalid asset id".to_string()) })?; diff --git a/crates/bevy_solari/src/pathtracer/extract.rs b/crates/bevy_solari/src/pathtracer/extract.rs index 38f27968a609d..c90302dd11ec1 100644 --- a/crates/bevy_solari/src/pathtracer/extract.rs +++ b/crates/bevy_solari/src/pathtracer/extract.rs @@ -22,8 +22,10 @@ pub fn extract_pathtracer( let mut entity_commands = commands .get_entity(entity) .expect("Camera entity wasn't synced."); - if pathtracer.is_some() && camera.is_active { - let mut pathtracer = pathtracer.unwrap().clone(); + if let Some(pathtracer) = pathtracer + && camera.is_active + { + let mut pathtracer = pathtracer.clone(); pathtracer.reset |= global_transform.is_changed(); entity_commands.insert(pathtracer); } else { diff --git a/crates/bevy_solari/src/realtime/extract.rs b/crates/bevy_solari/src/realtime/extract.rs index 8e80f023275ee..28b7d36e6fa1b 100644 --- a/crates/bevy_solari/src/realtime/extract.rs +++ b/crates/bevy_solari/src/realtime/extract.rs @@ -6,16 +6,15 @@ use bevy_render::{camera::Camera, sync_world::RenderEntity, MainWorld}; pub fn extract_solari_lighting(mut main_world: ResMut, mut commands: Commands) { let mut cameras_3d = main_world.query::<(RenderEntity, &Camera, Option<&mut SolariLighting>)>(); - for (entity, camera, mut solari_lighting) in cameras_3d.iter_mut(&mut main_world) { + for (entity, camera, solari_lighting) in cameras_3d.iter_mut(&mut main_world) { let mut entity_commands = commands .get_entity(entity) .expect("Camera entity wasn't synced."); - if solari_lighting.is_some() && camera.is_active { - entity_commands.insert(( - solari_lighting.as_deref().unwrap().clone(), - SkipDeferredLighting, - )); - solari_lighting.as_mut().unwrap().reset = false; + if let Some(mut solari_lighting) = solari_lighting + && camera.is_active + { + entity_commands.insert((solari_lighting.clone(), SkipDeferredLighting)); + solari_lighting.reset = false; } else { entity_commands.remove::<( SolariLighting, diff --git a/crates/bevy_sprite/src/lib.rs b/crates/bevy_sprite/src/lib.rs index 01a259cf8f27d..2a2a7353d28df 100644 --- a/crates/bevy_sprite/src/lib.rs +++ b/crates/bevy_sprite/src/lib.rs @@ -160,10 +160,10 @@ pub fn calculate_bounds_2d( >, ) { for (entity, mesh_handle) in &meshes_without_aabb { - if let Some(mesh) = meshes.get(&mesh_handle.0) { - if let Some(aabb) = mesh.compute_aabb() { - commands.entity(entity).try_insert(aabb); - } + if let Some(mesh) = meshes.get(&mesh_handle.0) + && let Some(aabb) = mesh.compute_aabb() + { + commands.entity(entity).try_insert(aabb); } } for (entity, sprite, anchor) in &sprites_to_recalculate_aabb { diff --git a/crates/bevy_sprite/src/picking_backend.rs b/crates/bevy_sprite/src/picking_backend.rs index 3bc021b21db24..a3a7c3a3db24f 100644 --- a/crates/bevy_sprite/src/picking_backend.rs +++ b/crates/bevy_sprite/src/picking_backend.rs @@ -143,11 +143,11 @@ fn sprite_picking( }; let viewport_pos = location.position; - if let Some(viewport) = camera.logical_viewport_rect() { - if !viewport.contains(viewport_pos) { - // The pointer is outside the viewport, skip it - continue; - } + if let Some(viewport) = camera.logical_viewport_rect() + && !viewport.contains(viewport_pos) + { + // The pointer is outside the viewport, skip it + continue; } let Ok(cursor_ray_world) = camera.viewport_to_world(cam_transform, viewport_pos) else { diff --git a/crates/bevy_state/src/commands.rs b/crates/bevy_state/src/commands.rs index 46170117265d1..2484a2d8a2b95 100644 --- a/crates/bevy_state/src/commands.rs +++ b/crates/bevy_state/src/commands.rs @@ -19,10 +19,10 @@ impl CommandsStatesExt for Commands<'_, '_> { fn set_state(&mut self, state: S) { self.queue(move |w: &mut World| { let mut next = w.resource_mut::>(); - if let NextState::Pending(prev) = &*next { - if *prev != state { - debug!("overwriting next state {prev:?} with {state:?}"); - } + if let NextState::Pending(prev) = &*next + && *prev != state + { + debug!("overwriting next state {prev:?} with {state:?}"); } next.set(state); }); diff --git a/crates/bevy_text/src/text_access.rs b/crates/bevy_text/src/text_access.rs index 7aafa28ef63e2..3c1e83c959e3a 100644 --- a/crates/bevy_text/src/text_access.rs +++ b/crates/bevy_text/src/text_access.rs @@ -74,7 +74,7 @@ pub struct TextReader<'w, 's, R: TextRoot> { impl<'w, 's, R: TextRoot> TextReader<'w, 's, R> { /// Returns an iterator over text spans in a text block, starting with the root entity. - pub fn iter(&mut self, root_entity: Entity) -> TextSpanIter { + pub fn iter(&mut self, root_entity: Entity) -> TextSpanIter<'_, R> { let stack = self.scratch.take(); TextSpanIter { @@ -254,7 +254,13 @@ impl<'w, 's, R: TextRoot> TextWriter<'w, 's, R> { &mut self, root_entity: Entity, index: usize, - ) -> Option<(Entity, usize, Mut, Mut, Mut)> { + ) -> Option<( + Entity, + usize, + Mut<'_, String>, + Mut<'_, TextFont>, + Mut<'_, TextColor>, + )> { // Root if index == 0 { let (text, font, color) = self.roots.get_mut(root_entity).ok()?; @@ -321,17 +327,17 @@ impl<'w, 's, R: TextRoot> TextWriter<'w, 's, R> { } /// Gets the text value of a text span within a text block at a specific index in the flattened span list. - pub fn get_text(&mut self, root_entity: Entity, index: usize) -> Option> { + pub fn get_text(&mut self, root_entity: Entity, index: usize) -> Option> { self.get(root_entity, index).map(|(_, _, text, ..)| text) } /// Gets the [`TextFont`] of a text span within a text block at a specific index in the flattened span list. - pub fn get_font(&mut self, root_entity: Entity, index: usize) -> Option> { + pub fn get_font(&mut self, root_entity: Entity, index: usize) -> Option> { self.get(root_entity, index).map(|(_, _, _, font, _)| font) } /// Gets the [`TextColor`] of a text span within a text block at a specific index in the flattened span list. - pub fn get_color(&mut self, root_entity: Entity, index: usize) -> Option> { + pub fn get_color(&mut self, root_entity: Entity, index: usize) -> Option> { self.get(root_entity, index) .map(|(_, _, _, _, color)| color) } @@ -339,21 +345,21 @@ impl<'w, 's, R: TextRoot> TextWriter<'w, 's, R> { /// Gets the text value of a text span within a text block at a specific index in the flattened span list. /// /// Panics if there is no span at the requested index. - pub fn text(&mut self, root_entity: Entity, index: usize) -> Mut { + pub fn text(&mut self, root_entity: Entity, index: usize) -> Mut<'_, String> { self.get_text(root_entity, index).unwrap() } /// Gets the [`TextFont`] of a text span within a text block at a specific index in the flattened span list. /// /// Panics if there is no span at the requested index. - pub fn font(&mut self, root_entity: Entity, index: usize) -> Mut { + pub fn font(&mut self, root_entity: Entity, index: usize) -> Mut<'_, TextFont> { self.get_font(root_entity, index).unwrap() } /// Gets the [`TextColor`] of a text span within a text block at a specific index in the flattened span list. /// /// Panics if there is no span at the requested index. - pub fn color(&mut self, root_entity: Entity, index: usize) -> Mut { + pub fn color(&mut self, root_entity: Entity, index: usize) -> Mut<'_, TextColor> { self.get_color(root_entity, index).unwrap() } diff --git a/crates/bevy_ui/src/focus.rs b/crates/bevy_ui/src/focus.rs index cfa4b818b0600..4584eab6a27f6 100644 --- a/crates/bevy_ui/src/focus.rs +++ b/crates/bevy_ui/src/focus.rs @@ -178,10 +178,10 @@ pub fn ui_focus_system( mouse_button_input.just_released(MouseButton::Left) || touches_input.any_just_released(); if mouse_released { for node in &mut node_query { - if let Some(mut interaction) = node.interaction { - if *interaction == Interaction::Pressed { - *interaction = Interaction::None; - } + if let Some(mut interaction) = node.interaction + && *interaction == Interaction::Pressed + { + *interaction = Interaction::None; } } } @@ -275,12 +275,11 @@ pub fn ui_focus_system( if contains_cursor { Some(*entity) } else { - if let Some(mut interaction) = node.interaction { - if *interaction == Interaction::Hovered - || (normalized_cursor_position.is_none()) - { - interaction.set_if_neq(Interaction::None); - } + if let Some(mut interaction) = node.interaction + && (*interaction == Interaction::Hovered + || (normalized_cursor_position.is_none())) + { + interaction.set_if_neq(Interaction::None); } None } @@ -338,14 +337,13 @@ pub fn clip_check_recursive( ) -> bool { if let Ok(child_of) = child_of_query.get(entity) { let parent = child_of.0; - if let Ok((computed_node, transform, node)) = clipping_query.get(parent) { - if !computed_node + if let Ok((computed_node, transform, node)) = clipping_query.get(parent) + && !computed_node .resolve_clip_rect(node.overflow, node.overflow_clip_margin) .contains(transform.inverse().transform_point2(point)) - { - // The point is clipped and should be ignored by picking - return false; - } + { + // The point is clipped and should be ignored by picking + return false; } return clip_check_recursive(point, parent, clipping_query, child_of_query); } diff --git a/crates/bevy_ui_render/src/lib.rs b/crates/bevy_ui_render/src/lib.rs index 0fb10b19e5352..f993d4860dae6 100644 --- a/crates/bevy_ui_render/src/lib.rs +++ b/crates/bevy_ui_render/src/lib.rs @@ -610,64 +610,64 @@ pub fn extract_uinode_borders( }; // Don't extract borders with zero width along all edges - if computed_node.border() != BorderRect::ZERO { - if let Some(border_color) = maybe_border_color { - let border_colors = [ - border_color.left.to_linear(), - border_color.top.to_linear(), - border_color.right.to_linear(), - border_color.bottom.to_linear(), - ]; - - const BORDER_FLAGS: [u32; 4] = [ - shader_flags::BORDER_LEFT, - shader_flags::BORDER_TOP, - shader_flags::BORDER_RIGHT, - shader_flags::BORDER_BOTTOM, - ]; - let mut completed_flags = 0; - - for (i, &color) in border_colors.iter().enumerate() { - if color.is_fully_transparent() { - continue; - } + if computed_node.border() != BorderRect::ZERO + && let Some(border_color) = maybe_border_color + { + let border_colors = [ + border_color.left.to_linear(), + border_color.top.to_linear(), + border_color.right.to_linear(), + border_color.bottom.to_linear(), + ]; + + const BORDER_FLAGS: [u32; 4] = [ + shader_flags::BORDER_LEFT, + shader_flags::BORDER_TOP, + shader_flags::BORDER_RIGHT, + shader_flags::BORDER_BOTTOM, + ]; + let mut completed_flags = 0; + + for (i, &color) in border_colors.iter().enumerate() { + if color.is_fully_transparent() { + continue; + } - let mut border_flags = BORDER_FLAGS[i]; + let mut border_flags = BORDER_FLAGS[i]; - if completed_flags & border_flags != 0 { - continue; - } + if completed_flags & border_flags != 0 { + continue; + } - for j in i + 1..4 { - if color == border_colors[j] { - border_flags |= BORDER_FLAGS[j]; - } + for j in i + 1..4 { + if color == border_colors[j] { + border_flags |= BORDER_FLAGS[j]; } - completed_flags |= border_flags; - - extracted_uinodes.uinodes.push(ExtractedUiNode { - z_order: computed_node.stack_index as f32 + stack_z_offsets::BORDER, - color, - rect: Rect { - max: computed_node.size(), - ..Default::default() - }, - image, - clip: maybe_clip.map(|clip| clip.clip), - extracted_camera_entity, - item: ExtractedUiItem::Node { - atlas_scaling: None, - transform: transform.into(), - flip_x: false, - flip_y: false, - border: computed_node.border(), - border_radius: computed_node.border_radius(), - node_type: NodeType::Border(border_flags), - }, - main_entity: entity.into(), - render_entity: commands.spawn(TemporaryRenderEntity).id(), - }); } + completed_flags |= border_flags; + + extracted_uinodes.uinodes.push(ExtractedUiNode { + z_order: computed_node.stack_index as f32 + stack_z_offsets::BORDER, + color, + rect: Rect { + max: computed_node.size(), + ..Default::default() + }, + image, + clip: maybe_clip.map(|clip| clip.clip), + extracted_camera_entity, + item: ExtractedUiItem::Node { + atlas_scaling: None, + transform: transform.into(), + flip_x: false, + flip_y: false, + border: computed_node.border(), + border_radius: computed_node.border_radius(), + node_type: NodeType::Border(border_flags), + }, + main_entity: entity.into(), + render_entity: commands.spawn(TemporaryRenderEntity).id(), + }); } } @@ -1365,9 +1365,11 @@ pub fn prepare_uinodes( } else if batch_image_handle == AssetId::default() && extracted_uinode.image != AssetId::default() { - if let Some(gpu_image) = gpu_images.get(extracted_uinode.image) { + if let Some(ref mut existing_batch) = existing_batch + && let Some(gpu_image) = gpu_images.get(extracted_uinode.image) + { batch_image_handle = extracted_uinode.image; - existing_batch.as_mut().unwrap().1.image = extracted_uinode.image; + existing_batch.1.image = extracted_uinode.image; image_bind_groups .values diff --git a/crates/bevy_ui_render/src/ui_texture_slice_pipeline.rs b/crates/bevy_ui_render/src/ui_texture_slice_pipeline.rs index aa05f106ff034..9b3323bd8fb8e 100644 --- a/crates/bevy_ui_render/src/ui_texture_slice_pipeline.rs +++ b/crates/bevy_ui_render/src/ui_texture_slice_pipeline.rs @@ -445,13 +445,14 @@ pub fn prepare_ui_slices( } else { continue; } - } else if batch_image_handle == AssetId::default() + } else if let Some(ref mut existing_batch) = existing_batch + && batch_image_handle == AssetId::default() && texture_slices.image != AssetId::default() { if let Some(gpu_image) = gpu_images.get(texture_slices.image) { batch_image_handle = texture_slices.image; batch_image_size = gpu_image.size_2d().as_vec2(); - existing_batch.as_mut().unwrap().1.image = texture_slices.image; + existing_batch.1.image = texture_slices.image; image_bind_groups .values diff --git a/crates/bevy_utils/src/debug_info.rs b/crates/bevy_utils/src/debug_info.rs index 71ce96ea0026e..afedfbe7984e8 100644 --- a/crates/bevy_utils/src/debug_info.rs +++ b/crates/bevy_utils/src/debug_info.rs @@ -82,7 +82,7 @@ impl DebugName { /// Get the [`ShortName`] corresponding to this debug name /// /// The value will be a static string if the `debug` feature is not enabled - pub fn shortname(&self) -> ShortName { + pub fn shortname(&self) -> ShortName<'_> { #[cfg(feature = "debug")] return ShortName(self.name.as_ref()); #[cfg(not(feature = "debug"))] diff --git a/crates/bevy_window/src/raw_handle.rs b/crates/bevy_window/src/raw_handle.rs index 0943315055fb6..635b06da7f309 100644 --- a/crates/bevy_window/src/raw_handle.rs +++ b/crates/bevy_window/src/raw_handle.rs @@ -138,7 +138,7 @@ unsafe impl Sync for RawHandleWrapper {} pub struct ThreadLockedRawWindowHandleWrapper(RawHandleWrapper); impl HasWindowHandle for ThreadLockedRawWindowHandleWrapper { - fn window_handle(&self) -> Result { + fn window_handle(&self) -> Result, HandleError> { // SAFETY: the caller has validated that this is a valid context to get [`RawHandleWrapper`] // as otherwise an instance of this type could not have been constructed // NOTE: we cannot simply impl HasRawWindowHandle for RawHandleWrapper, @@ -150,7 +150,7 @@ impl HasWindowHandle for ThreadLockedRawWindowHandleWrapper { } impl HasDisplayHandle for ThreadLockedRawWindowHandleWrapper { - fn display_handle(&self) -> Result { + fn display_handle(&self) -> Result, HandleError> { // SAFETY: the caller has validated that this is a valid context to get [`RawDisplayHandle`] // as otherwise an instance of this type could not have been constructed // NOTE: we cannot simply impl HasRawDisplayHandle for RawHandleWrapper, diff --git a/crates/bevy_winit/src/accessibility.rs b/crates/bevy_winit/src/accessibility.rs index b14fd4f57f5a3..634e6eac90436 100644 --- a/crates/bevy_winit/src/accessibility.rs +++ b/crates/bevy_winit/src/accessibility.rs @@ -214,10 +214,10 @@ fn update_accessibility_nodes( if focus.is_changed() || !nodes.is_empty() { // Don't panic if the focused entity does not currently exist // It's probably waiting to be spawned - if let Some(focused_entity) = focus.0 { - if !node_entities.contains(focused_entity) { - return; - } + if let Some(focused_entity) = focus.0 + && !node_entities.contains(focused_entity) + { + return; } adapter.update_if_active(|| { diff --git a/crates/bevy_winit/src/state.rs b/crates/bevy_winit/src/state.rs index 4f90905463351..6c1ed3dd446f0 100644 --- a/crates/bevy_winit/src/state.rs +++ b/crates/bevy_winit/src/state.rs @@ -232,10 +232,10 @@ impl ApplicationHandler for WinitAppRunnerState { // Allow AccessKit to respond to `WindowEvent`s before they reach // the engine. - if let Some(adapter) = access_kit_adapters.get_mut(&window) { - if let Some(winit_window) = winit_windows.get_window(window) { - adapter.process_event(winit_window, &event); - } + if let Some(adapter) = access_kit_adapters.get_mut(&window) + && let Some(winit_window) = winit_windows.get_window(window) + { + adapter.process_event(winit_window, &event); } match event { @@ -417,10 +417,9 @@ impl ApplicationHandler for WinitAppRunnerState { let mut windows = self.world_mut().query::<(&mut Window, &mut CachedWindow)>(); if let Ok((window_component, mut cache)) = windows.get_mut(self.world_mut(), window) + && window_component.is_changed() { - if window_component.is_changed() { - **cache = window_component.clone(); - } + **cache = window_component.clone(); } }); }); @@ -505,10 +504,10 @@ impl WinitAppRunnerState { let mut focused_windows_state: SystemState<(Res, Query<(Entity, &Window)>)> = SystemState::new(self.world_mut()); - if let Some(app_redraw_events) = self.world().get_resource::>() { - if redraw_event_reader.read(app_redraw_events).last().is_some() { - self.redraw_requested = true; - } + if let Some(app_redraw_events) = self.world().get_resource::>() + && redraw_event_reader.read(app_redraw_events).last().is_some() + { + self.redraw_requested = true; } let (config, windows) = focused_windows_state.get(self.world()); @@ -673,10 +672,10 @@ impl WinitAppRunnerState { } UpdateMode::Reactive { wait, .. } => { // Set the next timeout, starting from the instant before running app.update() to avoid frame delays - if let Some(next) = begin_frame_time.checked_add(wait) { - if self.wait_elapsed { - event_loop.set_control_flow(ControlFlow::WaitUntil(next)); - } + if let Some(next) = begin_frame_time.checked_add(wait) + && self.wait_elapsed + { + event_loop.set_control_flow(ControlFlow::WaitUntil(next)); } } } diff --git a/crates/bevy_winit/src/system.rs b/crates/bevy_winit/src/system.rs index 6d3a76c9b3728..30c12acfec804 100644 --- a/crates/bevy_winit/src/system.rs +++ b/crates/bevy_winit/src/system.rs @@ -349,11 +349,10 @@ pub(crate) fn changed_windows( WindowMode::Windowed => Some(None), }; - if let Some(new_mode) = new_mode { - if winit_window.fullscreen() != new_mode { + if let Some(new_mode) = new_mode + && winit_window.fullscreen() != new_mode { winit_window.set_fullscreen(new_mode); } - } } if window.resolution != cache.resolution { @@ -394,22 +393,20 @@ pub(crate) fn changed_windows( } } - if physical_size != cached_physical_size { - if let Some(new_physical_size) = winit_window.request_inner_size(physical_size) { + if physical_size != cached_physical_size + && let Some(new_physical_size) = winit_window.request_inner_size(physical_size) { react_to_resize(entity, &mut window, new_physical_size, &mut window_resized); } - } } - if window.physical_cursor_position() != cache.physical_cursor_position() { - if let Some(physical_position) = window.physical_cursor_position() { + if window.physical_cursor_position() != cache.physical_cursor_position() + && let Some(physical_position) = window.physical_cursor_position() { let position = PhysicalPosition::new(physical_position.x, physical_position.y); if let Err(err) = winit_window.set_cursor_position(position) { error!("could not set cursor position: {}", err); } } - } if window.decorations != cache.decorations && window.decorations != winit_window.is_decorated() @@ -444,8 +441,8 @@ pub(crate) fn changed_windows( } } - if window.position != cache.position { - if let Some(position) = crate::winit_window_position( + if window.position != cache.position + && let Some(position) = crate::winit_window_position( &window.position, &window.resolution, &monitors, @@ -461,7 +458,6 @@ pub(crate) fn changed_windows( winit_window.set_outer_position(position); } } - } if let Some(maximized) = window.internal.take_maximize_request() { winit_window.set_maximized(maximized); @@ -471,19 +467,17 @@ pub(crate) fn changed_windows( winit_window.set_minimized(minimized); } - if window.internal.take_move_request() { - if let Err(e) = winit_window.drag_window() { + if window.internal.take_move_request() + && let Err(e) = winit_window.drag_window() { warn!("Winit returned an error while attempting to drag the window: {e}"); } - } - if let Some(resize_direction) = window.internal.take_resize_request() { - if let Err(e) = + if let Some(resize_direction) = window.internal.take_resize_request() + && let Err(e) = winit_window.drag_resize_window(convert_resize_direction(resize_direction)) { warn!("Winit returned an error while attempting to drag resize the window: {e}"); } - } if window.focused != cache.focused && window.focused { winit_window.focus_window(); diff --git a/crates/bevy_winit/src/winit_windows.rs b/crates/bevy_winit/src/winit_windows.rs index 8cc5dcfac7aac..40151845c46f9 100644 --- a/crates/bevy_winit/src/winit_windows.rs +++ b/crates/bevy_winit/src/winit_windows.rs @@ -324,13 +324,13 @@ impl WinitWindows { // Do not set the cursor hittest on window creation if it's false, as it will always fail on // some platforms and log an unfixable warning. - if !cursor_options.hit_test { - if let Err(err) = winit_window.set_cursor_hittest(cursor_options.hit_test) { - warn!( - "Could not set cursor hit test for window {}: {}", - window.title, err - ); - } + if !cursor_options.hit_test + && let Err(err) = winit_window.set_cursor_hittest(cursor_options.hit_test) + { + warn!( + "Could not set cursor hit test for window {}: {}", + window.title, err + ); } self.entity_to_winit.insert(entity, winit_window.id()); diff --git a/examples/2d/sprite_animation.rs b/examples/2d/sprite_animation.rs index 8f96ef44de390..c57fd500bff18 100644 --- a/examples/2d/sprite_animation.rs +++ b/examples/2d/sprite_animation.rs @@ -60,17 +60,17 @@ fn execute_animations(time: Res