From 3861fbdf02af72ef38d5852ba404ccd40952f1eb Mon Sep 17 00:00:00 2001 From: Felix de Maneville Date: Tue, 18 Jan 2022 15:40:30 +0100 Subject: [PATCH 01/11] Clippy fixes --- crates/bevy_app/src/app.rs | 24 +- crates/bevy_app/src/schedule_runner.rs | 10 +- crates/bevy_asset/src/asset_server.rs | 4 +- crates/bevy_asset/src/assets.rs | 13 +- crates/bevy_asset/src/filesystem_watcher.rs | 2 +- crates/bevy_asset/src/handle.rs | 34 +- crates/bevy_asset/src/io/file_asset_io.rs | 2 +- crates/bevy_asset/src/loader.rs | 8 +- crates/bevy_asset/src/path.rs | 12 +- crates/bevy_audio/src/audio_source.rs | 4 +- crates/bevy_core/src/float_ord.rs | 4 +- crates/bevy_core/src/name.rs | 8 +- crates/bevy_core/src/task_pool_options.rs | 4 +- crates/bevy_core/src/time/fixed_timestep.rs | 6 +- crates/bevy_core/src/time/stopwatch.rs | 4 +- crates/bevy_core/src/time/time.rs | 18 +- crates/bevy_core/src/time/timer.rs | 14 +- crates/bevy_core_pipeline/src/main_pass_2d.rs | 2 +- crates/bevy_core_pipeline/src/main_pass_3d.rs | 2 +- .../src/std140/dynamic_uniform.rs | 2 +- crates/bevy_crevice/src/std140/sizer.rs | 4 +- crates/bevy_crevice/src/std430/sizer.rs | 4 +- crates/bevy_diagnostic/src/diagnostic.rs | 12 +- .../src/log_diagnostics_plugin.rs | 46 ++- crates/bevy_ecs/macros/src/lib.rs | 2 +- crates/bevy_ecs/src/archetype.rs | 28 +- crates/bevy_ecs/src/bundle.rs | 4 +- crates/bevy_ecs/src/component.rs | 32 +- crates/bevy_ecs/src/entity/mod.rs | 21 +- crates/bevy_ecs/src/event.rs | 8 +- crates/bevy_ecs/src/query/access.rs | 10 +- crates/bevy_ecs/src/query/fetch.rs | 4 +- crates/bevy_ecs/src/reflect.rs | 4 +- crates/bevy_ecs/src/schedule/run_criteria.rs | 8 +- crates/bevy_ecs/src/schedule/stage.rs | 2 +- crates/bevy_ecs/src/schedule/state.rs | 14 +- .../bevy_ecs/src/schedule/system_container.rs | 6 +- crates/bevy_ecs/src/schedule/system_set.rs | 16 +- crates/bevy_ecs/src/storage/blob_vec.rs | 14 +- crates/bevy_ecs/src/storage/sparse_set.rs | 4 +- crates/bevy_ecs/src/storage/table.rs | 30 +- crates/bevy_ecs/src/system/commands/mod.rs | 4 +- crates/bevy_ecs/src/system/function_system.rs | 2 +- crates/bevy_ecs/src/system/system_param.rs | 6 +- crates/bevy_ecs/src/world/entity_ref.rs | 23 +- crates/bevy_ecs/src/world/mod.rs | 37 +- crates/bevy_gilrs/src/converter.rs | 4 +- crates/bevy_gltf/src/loader.rs | 68 ++-- crates/bevy_input/src/axis.rs | 2 +- crates/bevy_input/src/gamepad.rs | 6 +- crates/bevy_input/src/lib.rs | 2 +- crates/bevy_input/src/touch.rs | 16 +- crates/bevy_log/src/lib.rs | 22 +- crates/bevy_math/src/face_toward.rs | 2 +- crates/bevy_math/src/geometry.rs | 12 +- crates/bevy_pbr/src/alpha.rs | 2 +- crates/bevy_pbr/src/bundle.rs | 2 +- crates/bevy_pbr/src/light.rs | 21 +- crates/bevy_pbr/src/material.rs | 4 +- crates/bevy_pbr/src/pbr_material.rs | 10 +- crates/bevy_pbr/src/render/light.rs | 12 +- crates/bevy_pbr/src/render/mesh.rs | 49 +-- crates/bevy_pbr/src/wireframe.rs | 2 +- .../bevy_reflect_derive/src/lib.rs | 15 +- .../bevy_reflect_derive/src/reflect_trait.rs | 2 +- crates/bevy_reflect/src/impls/smallvec.rs | 8 +- crates/bevy_reflect/src/impls/std.rs | 28 +- crates/bevy_reflect/src/list.rs | 6 +- crates/bevy_reflect/src/map.rs | 4 +- crates/bevy_reflect/src/serde/de.rs | 2 +- crates/bevy_reflect/src/struct_trait.rs | 4 +- crates/bevy_reflect/src/tuple.rs | 4 +- crates/bevy_reflect/src/tuple_struct.rs | 4 +- crates/bevy_reflect/src/type_registry.rs | 8 +- crates/bevy_render/src/camera/bundle.rs | 10 +- crates/bevy_render/src/camera/camera.rs | 2 +- crates/bevy_render/src/camera/projection.rs | 4 +- crates/bevy_render/src/color/colorspace.rs | 4 +- crates/bevy_render/src/color/mod.rs | 342 +++++++++--------- .../bevy_render/src/mesh/mesh/conversions.rs | 26 +- crates/bevy_render/src/mesh/mesh/mod.rs | 188 +++++----- crates/bevy_render/src/mesh/shape/capsule.rs | 16 +- .../bevy_render/src/mesh/shape/icosphere.rs | 8 +- crates/bevy_render/src/mesh/shape/mod.rs | 44 +-- crates/bevy_render/src/mesh/shape/torus.rs | 14 +- crates/bevy_render/src/mesh/shape/uvsphere.rs | 8 +- crates/bevy_render/src/render_component.rs | 2 +- .../bevy_render/src/render_graph/context.rs | 6 +- crates/bevy_render/src/render_graph/edge.rs | 12 +- crates/bevy_render/src/render_graph/graph.rs | 10 +- crates/bevy_render/src/render_graph/node.rs | 16 +- .../bevy_render/src/render_graph/node_slot.rs | 34 +- crates/bevy_render/src/render_phase/draw.rs | 13 +- .../src/render_phase/draw_state.rs | 18 +- .../src/render_resource/bind_group.rs | 4 +- .../src/render_resource/bind_group_layout.rs | 4 +- .../bevy_render/src/render_resource/buffer.rs | 8 +- .../src/render_resource/pipeline.rs | 8 +- .../src/render_resource/pipeline_cache.rs | 2 +- .../bevy_render/src/render_resource/shader.rs | 25 +- .../src/render_resource/texture.rs | 14 +- .../bevy_render/src/renderer/graph_runner.rs | 9 +- .../bevy_render/src/renderer/render_device.rs | 2 +- crates/bevy_render/src/texture/image.rs | 8 +- crates/bevy_render/src/texture/mod.rs | 4 +- crates/bevy_render/src/view/mod.rs | 9 +- .../src/view/visibility/render_layers.rs | 16 +- crates/bevy_scene/src/dynamic_scene.rs | 2 +- crates/bevy_scene/src/scene.rs | 2 +- crates/bevy_scene/src/scene_loader.rs | 2 +- crates/bevy_scene/src/scene_spawner.rs | 2 +- crates/bevy_scene/src/serde.rs | 2 +- .../src/dynamic_texture_atlas_builder.rs | 2 +- .../bevy_sprite/src/mesh2d/color_material.rs | 10 +- crates/bevy_sprite/src/mesh2d/material.rs | 2 +- crates/bevy_sprite/src/mesh2d/mesh.rs | 49 +-- crates/bevy_sprite/src/render/mod.rs | 6 +- crates/bevy_sprite/src/texture_atlas.rs | 11 +- .../bevy_sprite/src/texture_atlas_builder.rs | 8 +- crates/bevy_tasks/src/countdown_event.rs | 2 +- crates/bevy_tasks/src/task_pool.rs | 17 +- crates/bevy_text/src/font.rs | 2 +- crates/bevy_text/src/font_atlas.rs | 2 +- crates/bevy_text/src/font_atlas_set.rs | 2 +- crates/bevy_text/src/glyph_brush.rs | 4 +- crates/bevy_text/src/pipeline.rs | 2 +- crates/bevy_text/src/text.rs | 14 +- crates/bevy_text/src/text2d.rs | 16 +- .../src/components/global_transform.rs | 28 +- .../bevy_transform/src/components/parent.rs | 4 +- .../src/components/transform.rs | 26 +- .../src/hierarchy/child_builder.rs | 2 +- .../src/transform_propagate_system.rs | 9 +- crates/bevy_ui/src/entity.rs | 6 +- crates/bevy_ui/src/flex/convert.rs | 74 ++-- crates/bevy_ui/src/flex/mod.rs | 31 +- crates/bevy_ui/src/focus.rs | 4 +- crates/bevy_ui/src/margins.rs | 6 +- crates/bevy_ui/src/render/mod.rs | 53 ++- crates/bevy_ui/src/render/pipeline.rs | 2 +- crates/bevy_ui/src/render/render_pass.rs | 2 +- crates/bevy_ui/src/ui_node.rs | 58 +-- crates/bevy_ui/src/update.rs | 12 +- crates/bevy_ui/src/widget/image.rs | 2 +- crates/bevy_ui/src/widget/text.rs | 8 +- crates/bevy_utils/src/lib.rs | 8 +- crates/bevy_window/src/lib.rs | 2 +- crates/bevy_window/src/raw_window_handle.rs | 4 +- crates/bevy_window/src/window.rs | 56 +-- crates/bevy_winit/src/converters.rs | 8 +- crates/bevy_winit/src/winit_windows.rs | 2 +- 151 files changed, 1137 insertions(+), 1162 deletions(-) diff --git a/crates/bevy_app/src/app.rs b/crates/bevy_app/src/app.rs index 6dc3ef9bcf9c2..870cade0ad1d5 100644 --- a/crates/bevy_app/src/app.rs +++ b/crates/bevy_app/src/app.rs @@ -65,7 +65,7 @@ struct SubApp { impl Default for App { fn default() -> Self { - let mut app = App::empty(); + let mut app = Self::empty(); #[cfg(feature = "bevy_reflect")] app.init_resource::(); @@ -85,14 +85,14 @@ impl Default for App { impl App { /// Creates a new [`App`] with some default structure to enable core engine features. /// This is the preferred constructor for most use cases. - pub fn new() -> App { - App::default() + pub fn new() -> Self { + Self::default() } /// Creates a new empty [`App`] with minimal default configuration. /// /// This constructor should be used if you wish to provide a custom schedule, exit handling, cleanup, etc. - pub fn empty() -> App { + pub fn empty() -> Self { Self { world: Default::default(), schedule: Default::default(), @@ -127,7 +127,7 @@ impl App { #[cfg(feature = "trace")] let _bevy_app_run_guard = bevy_app_run_span.enter(); - let mut app = std::mem::replace(self, App::empty()); + let mut app = std::mem::replace(self, Self::empty()); let runner = std::mem::replace(&mut app.runner, Box::new(run_once)); (runner)(app); } @@ -746,7 +746,7 @@ impl App { /// App::new() /// .set_runner(my_runner); /// ``` - pub fn set_runner(&mut self, run_fn: impl Fn(App) + 'static) -> &mut Self { + pub fn set_runner(&mut self, run_fn: impl Fn(Self) + 'static) -> &mut Self { self.runner = Box::new(run_fn); self } @@ -862,8 +862,8 @@ impl App { pub fn add_sub_app( &mut self, label: impl AppLabel, - app: App, - sub_app_runner: impl Fn(&mut World, &mut App) + 'static, + app: Self, + sub_app_runner: impl Fn(&mut World, &mut Self) + 'static, ) -> &mut Self { self.sub_apps.insert( Box::new(label), @@ -876,7 +876,7 @@ impl App { } /// Retrieves a "sub app" stored inside this [App]. This will panic if the sub app does not exist. - pub fn sub_app_mut(&mut self, label: impl AppLabel) -> &mut App { + pub fn sub_app_mut(&mut self, label: impl AppLabel) -> &mut Self { match self.get_sub_app_mut(label) { Ok(app) => app, Err(label) => panic!("Sub-App with label '{:?}' does not exist", label), @@ -885,7 +885,7 @@ impl App { /// Retrieves a "sub app" inside this [App] with the given label, if it exists. Otherwise returns /// an [Err] containing the given label. - pub fn get_sub_app_mut(&mut self, label: impl AppLabel) -> Result<&mut App, impl AppLabel> { + pub fn get_sub_app_mut(&mut self, label: impl AppLabel) -> Result<&mut Self, impl AppLabel> { self.sub_apps .get_mut((&label) as &dyn AppLabel) .map(|sub_app| &mut sub_app.app) @@ -893,7 +893,7 @@ impl App { } /// Retrieves a "sub app" stored inside this [App]. This will panic if the sub app does not exist. - pub fn sub_app(&self, label: impl AppLabel) -> &App { + pub fn sub_app(&self, label: impl AppLabel) -> &Self { match self.get_sub_app(label) { Ok(app) => app, Err(label) => panic!("Sub-App with label '{:?}' does not exist", label), @@ -902,7 +902,7 @@ impl App { /// Retrieves a "sub app" inside this [App] with the given label, if it exists. Otherwise returns /// an [Err] containing the given label. - pub fn get_sub_app(&self, label: impl AppLabel) -> Result<&App, impl AppLabel> { + pub fn get_sub_app(&self, label: impl AppLabel) -> Result<&Self, impl AppLabel> { self.sub_apps .get((&label) as &dyn AppLabel) .map(|sub_app| &sub_app.app) diff --git a/crates/bevy_app/src/schedule_runner.rs b/crates/bevy_app/src/schedule_runner.rs index 3227826f70d06..cd5d4babf2180 100644 --- a/crates/bevy_app/src/schedule_runner.rs +++ b/crates/bevy_app/src/schedule_runner.rs @@ -26,7 +26,7 @@ pub enum RunMode { impl Default for RunMode { fn default() -> Self { - RunMode::Loop { wait: None } + Self::Loop { wait: None } } } @@ -39,15 +39,15 @@ pub struct ScheduleRunnerSettings { impl ScheduleRunnerSettings { /// [`RunMode::Once`] - pub fn run_once() -> Self { - ScheduleRunnerSettings { + pub const fn run_once() -> Self { + Self { run_mode: RunMode::Once, } } /// [`RunMode::Loop`] - pub fn run_loop(wait_duration: Duration) -> Self { - ScheduleRunnerSettings { + pub const fn run_loop(wait_duration: Duration) -> Self { + Self { run_mode: RunMode::Loop { wait: Some(wait_duration), }, diff --git a/crates/bevy_asset/src/asset_server.rs b/crates/bevy_asset/src/asset_server.rs index 88f20511ab79c..e80052d0bab94 100644 --- a/crates/bevy_asset/src/asset_server.rs +++ b/crates/bevy_asset/src/asset_server.rs @@ -78,7 +78,7 @@ impl AssetServer { } pub fn with_boxed_io(asset_io: Box, task_pool: TaskPool) -> Self { - AssetServer { + Self { server: Arc::new(AssetServerInternal { loaders: Default::default(), extension_to_loader_index: Default::default(), @@ -426,7 +426,7 @@ impl AssetServer { let asset_sources = self.server.asset_sources.read(); let asset_lifecycles = self.server.asset_lifecycles.read(); for potential_free in potential_frees.drain(..) { - if let Some(&0) = ref_counts.get(&potential_free) { + if ref_counts.get(&potential_free) == Some(&0) { let type_uuid = match potential_free { HandleId::Id(type_uuid, _) => Some(type_uuid), HandleId::AssetPathId(id) => asset_sources diff --git a/crates/bevy_asset/src/assets.rs b/crates/bevy_asset/src/assets.rs index ade30b169dcd6..d0120816a28ae 100644 --- a/crates/bevy_asset/src/assets.rs +++ b/crates/bevy_asset/src/assets.rs @@ -20,21 +20,21 @@ pub enum AssetEvent { impl Debug for AssetEvent { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - AssetEvent::Created { handle } => f + Self::Created { handle } => f .debug_struct(&format!( "AssetEvent<{}>::Created", std::any::type_name::() )) .field("handle", &handle.id) .finish(), - AssetEvent::Modified { handle } => f + Self::Modified { handle } => f .debug_struct(&format!( "AssetEvent<{}>::Modified", std::any::type_name::() )) .field("handle", &handle.id) .finish(), - AssetEvent::Removed { handle } => f + Self::Removed { handle } => f .debug_struct(&format!( "AssetEvent<{}>::Removed", std::any::type_name::() @@ -67,7 +67,7 @@ pub struct Assets { impl Assets { pub(crate) fn new(ref_change_sender: Sender) -> Self { - Assets { + Self { assets: HashMap::default(), events: Events::default(), ref_change_sender, @@ -234,10 +234,7 @@ impl Assets { self.assets.shrink_to_fit() } - pub fn asset_event_system( - mut events: EventWriter>, - mut assets: ResMut>, - ) { + pub fn asset_event_system(mut events: EventWriter>, mut assets: ResMut) { // Check if the events are empty before calling `drain`. // As `drain` triggers change detection. if !assets.events.is_empty() { diff --git a/crates/bevy_asset/src/filesystem_watcher.rs b/crates/bevy_asset/src/filesystem_watcher.rs index 19b131780a078..df828b0eb679d 100644 --- a/crates/bevy_asset/src/filesystem_watcher.rs +++ b/crates/bevy_asset/src/filesystem_watcher.rs @@ -16,7 +16,7 @@ impl Default for FilesystemWatcher { sender.send(res).expect("Watch event send failure."); }) .expect("Failed to create filesystem watcher."); - FilesystemWatcher { watcher, receiver } + Self { watcher, receiver } } } diff --git a/crates/bevy_asset/src/handle.rs b/crates/bevy_asset/src/handle.rs index d5287a2f174d9..33ba6cfd46671 100644 --- a/crates/bevy_asset/src/handle.rs +++ b/crates/bevy_asset/src/handle.rs @@ -38,30 +38,30 @@ pub enum HandleId { impl From for HandleId { fn from(value: AssetPathId) -> Self { - HandleId::AssetPathId(value) + Self::AssetPathId(value) } } impl<'a> From> for HandleId { fn from(value: AssetPath<'a>) -> Self { - HandleId::AssetPathId(AssetPathId::from(value)) + Self::AssetPathId(AssetPathId::from(value)) } } impl HandleId { #[inline] pub fn random() -> Self { - HandleId::Id(T::TYPE_UUID, rand::random()) + Self::Id(T::TYPE_UUID, rand::random()) } #[inline] pub fn default() -> Self { - HandleId::Id(T::TYPE_UUID, 0) + Self::Id(T::TYPE_UUID, 0) } #[inline] pub const fn new(type_uuid: Uuid, id: u64) -> Self { - HandleId::Id(type_uuid, id) + Self::Id(type_uuid, id) } } @@ -180,7 +180,7 @@ impl Handle { #[inline] pub fn clone_weak(&self) -> Self { - Handle::weak(self.id) + Self::weak(self.id) } pub fn clone_untyped(&self) -> HandleUntyped { @@ -272,7 +272,7 @@ impl Ord for Handle { impl Default for Handle { fn default() -> Self { - Handle::weak(HandleId::default::()) + Self::weak(HandleId::default::()) } } @@ -286,8 +286,8 @@ impl Debug for Handle { impl Clone for Handle { fn clone(&self) -> Self { match self.handle_type { - HandleType::Strong(ref sender) => Handle::strong(self.id, sender.clone()), - HandleType::Weak => Handle::weak(self.id), + HandleType::Strong(ref sender) => Self::strong(self.id, sender.clone()), + HandleType::Weak => Self::weak(self.id), } } } @@ -320,22 +320,22 @@ impl HandleUntyped { } } - pub fn weak(id: HandleId) -> Self { + pub const fn weak(id: HandleId) -> Self { Self { id, handle_type: HandleType::Weak, } } - pub fn clone_weak(&self) -> HandleUntyped { - HandleUntyped::weak(self.id) + pub const fn clone_weak(&self) -> Self { + Self::weak(self.id) } - pub fn is_weak(&self) -> bool { + pub const fn is_weak(&self) -> bool { matches!(self.handle_type, HandleType::Weak) } - pub fn is_strong(&self) -> bool { + pub const fn is_strong(&self) -> bool { matches!(self.handle_type, HandleType::Strong(_)) } @@ -398,8 +398,8 @@ impl Eq for HandleUntyped {} impl Clone for HandleUntyped { fn clone(&self) -> Self { match self.handle_type { - HandleType::Strong(ref sender) => HandleUntyped::strong(self.id, sender.clone()), - HandleType::Weak => HandleUntyped::weak(self.id), + HandleType::Strong(ref sender) => Self::strong(self.id, sender.clone()), + HandleType::Weak => Self::weak(self.id), } } } @@ -418,6 +418,6 @@ pub(crate) struct RefChangeChannel { impl Default for RefChangeChannel { fn default() -> Self { let (sender, receiver) = crossbeam_channel::unbounded(); - RefChangeChannel { sender, receiver } + Self { sender, receiver } } } diff --git a/crates/bevy_asset/src/io/file_asset_io.rs b/crates/bevy_asset/src/io/file_asset_io.rs index a7124c5982d43..da19166e6759b 100644 --- a/crates/bevy_asset/src/io/file_asset_io.rs +++ b/crates/bevy_asset/src/io/file_asset_io.rs @@ -28,7 +28,7 @@ pub struct FileAssetIo { impl FileAssetIo { pub fn new>(path: P) -> Self { - FileAssetIo { + Self { #[cfg(feature = "filesystem_watcher")] filesystem_watcher: Default::default(), root_path: Self::get_root_path().join(path.as_ref()), diff --git a/crates/bevy_asset/src/loader.rs b/crates/bevy_asset/src/loader.rs index 7b665bf8befe1..3c212ea64a576 100644 --- a/crates/bevy_asset/src/loader.rs +++ b/crates/bevy_asset/src/loader.rs @@ -67,7 +67,7 @@ pub(crate) struct BoxedLoadedAsset { impl From> for BoxedLoadedAsset { fn from(asset: LoadedAsset) -> Self { - BoxedLoadedAsset { + Self { value: asset .value .map(|value| Box::new(value) as Box), @@ -103,7 +103,7 @@ impl<'a> LoadContext<'a> { } } - pub fn path(&self) -> &Path { + pub const fn path(&self) -> &Path { self.path } @@ -142,7 +142,7 @@ impl<'a> LoadContext<'a> { asset_metas } - pub fn task_pool(&self) -> &TaskPool { + pub const fn task_pool(&self) -> &TaskPool { self.task_pool } } @@ -199,7 +199,7 @@ impl AssetLifecycle for AssetLifecycleChannel { impl Default for AssetLifecycleChannel { fn default() -> Self { let (sender, receiver) = crossbeam_channel::unbounded(); - AssetLifecycleChannel { sender, receiver } + Self { sender, receiver } } } diff --git a/crates/bevy_asset/src/path.rs b/crates/bevy_asset/src/path.rs index df99eaee19da1..f00f49662cf7e 100644 --- a/crates/bevy_asset/src/path.rs +++ b/crates/bevy_asset/src/path.rs @@ -79,7 +79,7 @@ impl<'a> From<&'a Path> for SourcePathId { fn from(value: &'a Path) -> Self { let mut hasher = get_hasher(); value.hash(&mut hasher); - SourcePathId(hasher.finish()) + Self(hasher.finish()) } } @@ -99,16 +99,16 @@ impl<'a> From> for LabelId { fn from(value: Option<&'a str>) -> Self { let mut hasher = get_hasher(); value.hash(&mut hasher); - LabelId(hasher.finish()) + Self(hasher.finish()) } } impl AssetPathId { - pub fn source_path_id(&self) -> SourcePathId { + pub const fn source_path_id(&self) -> SourcePathId { self.0 } - pub fn label_id(&self) -> LabelId { + pub const fn label_id(&self) -> LabelId { self.1 } } @@ -124,7 +124,7 @@ where { fn from(value: T) -> Self { let asset_path: AssetPath = value.into(); - AssetPathId( + Self( SourcePathId::from(asset_path.path()), LabelId::from(asset_path.label()), ) @@ -133,7 +133,7 @@ where impl<'a, 'b> From<&'a AssetPath<'b>> for AssetPathId { fn from(asset_path: &'a AssetPath<'b>) -> Self { - AssetPathId( + Self( SourcePathId::from(asset_path.path()), LabelId::from(asset_path.label()), ) diff --git a/crates/bevy_audio/src/audio_source.rs b/crates/bevy_audio/src/audio_source.rs index 823526046c7c3..8df5dc29b6f29 100644 --- a/crates/bevy_audio/src/audio_source.rs +++ b/crates/bevy_audio/src/audio_source.rs @@ -63,8 +63,8 @@ pub trait Decodable: Send + Sync + 'static { } impl Decodable for AudioSource { - type Decoder = rodio::Decoder>; - type DecoderItem = > as Iterator>::Item; + type Decoder = rodio::Decoder>; + type DecoderItem = > as Iterator>::Item; fn decoder(&self) -> Self::Decoder { rodio::Decoder::new(Cursor::new(self.clone())).unwrap() diff --git a/crates/bevy_core/src/float_ord.rs b/crates/bevy_core/src/float_ord.rs index cd573ca5fc016..42f8987109b27 100644 --- a/crates/bevy_core/src/float_ord.rs +++ b/crates/bevy_core/src/float_ord.rs @@ -52,9 +52,9 @@ impl Hash for FloatOrd { } impl Neg for FloatOrd { - type Output = FloatOrd; + type Output = Self; fn neg(self) -> Self::Output { - FloatOrd(-self.0) + Self(-self.0) } } diff --git a/crates/bevy_core/src/name.rs b/crates/bevy_core/src/name.rs index f7d992e9c12a2..186906e52c6d3 100644 --- a/crates/bevy_core/src/name.rs +++ b/crates/bevy_core/src/name.rs @@ -22,7 +22,7 @@ pub struct Name { impl Default for Name { fn default() -> Self { - Name::new("") + Self::new("") } } @@ -32,7 +32,7 @@ impl Name { /// The internal hash will be computed immediately. pub fn new(name: impl Into>) -> Self { let name = name.into(); - let mut name = Name { name, hash: 0 }; + let mut name = Self { name, hash: 0 }; name.update_hash(); name } @@ -42,7 +42,7 @@ impl Name { /// The internal hash will be re-computed. #[inline(always)] pub fn set(&mut self, name: impl Into>) { - *self = Name::new(name); + *self = Self::new(name); } /// Updates the name of the entity in place. @@ -71,7 +71,7 @@ impl Name { impl From<&str> for Name { #[inline(always)] fn from(name: &str) -> Self { - Name::new(name.to_owned()) + Self::new(name.to_owned()) } } diff --git a/crates/bevy_core/src/task_pool_options.rs b/crates/bevy_core/src/task_pool_options.rs index 19c9dad5bfe2f..2cf7ccca47390 100644 --- a/crates/bevy_core/src/task_pool_options.rs +++ b/crates/bevy_core/src/task_pool_options.rs @@ -53,7 +53,7 @@ pub struct DefaultTaskPoolOptions { impl Default for DefaultTaskPoolOptions { fn default() -> Self { - DefaultTaskPoolOptions { + Self { // By default, use however many cores are available on the system min_total_threads: 1, max_total_threads: std::usize::MAX, @@ -85,7 +85,7 @@ impl Default for DefaultTaskPoolOptions { impl DefaultTaskPoolOptions { /// Create a configuration that forces using the given number of threads. pub fn with_num_threads(thread_count: usize) -> Self { - DefaultTaskPoolOptions { + Self { min_total_threads: thread_count, max_total_threads: thread_count, ..Default::default() diff --git a/crates/bevy_core/src/time/fixed_timestep.rs b/crates/bevy_core/src/time/fixed_timestep.rs index efc2af50152ad..03d9ddf5f52c9 100644 --- a/crates/bevy_core/src/time/fixed_timestep.rs +++ b/crates/bevy_core/src/time/fixed_timestep.rs @@ -19,7 +19,7 @@ pub struct FixedTimestepState { impl FixedTimestepState { /// The amount of time each step takes. - pub fn step(&self) -> f64 { + pub const fn step(&self) -> f64 { self.step } @@ -29,7 +29,7 @@ impl FixedTimestepState { } /// The amount of time (in seconds) left over from the last step. - pub fn accumulator(&self) -> f64 { + pub const fn accumulator(&self) -> f64 { self.accumulator } @@ -171,7 +171,7 @@ impl System for FixedTimestep { type Out = ShouldRun; fn name(&self) -> Cow<'static, str> { - Cow::Borrowed(std::any::type_name::()) + Cow::Borrowed(std::any::type_name::()) } fn new_archetype(&mut self, archetype: &Archetype) { diff --git a/crates/bevy_core/src/time/stopwatch.rs b/crates/bevy_core/src/time/stopwatch.rs index 9fa84cba07a6b..d59223c53a554 100644 --- a/crates/bevy_core/src/time/stopwatch.rs +++ b/crates/bevy_core/src/time/stopwatch.rs @@ -60,7 +60,7 @@ impl Stopwatch { /// /// [`elapsed_secs`](Stopwatch::elapsed) - if a `f32` value is desirable instead. #[inline] - pub fn elapsed(&self) -> Duration { + pub const fn elapsed(&self) -> Duration { self.elapsed } @@ -168,7 +168,7 @@ impl Stopwatch { /// assert!(!stopwatch.paused()); /// ``` #[inline] - pub fn paused(&self) -> bool { + pub const fn paused(&self) -> bool { self.paused } diff --git a/crates/bevy_core/src/time/time.rs b/crates/bevy_core/src/time/time.rs index c47855e974a74..8a18c017fb3eb 100644 --- a/crates/bevy_core/src/time/time.rs +++ b/crates/bevy_core/src/time/time.rs @@ -14,8 +14,8 @@ pub struct Time { } impl Default for Time { - fn default() -> Time { - Time { + fn default() -> Self { + Self { delta: Duration::from_secs(0), last_update: None, startup: Instant::now(), @@ -47,43 +47,43 @@ impl Time { /// The delta between the current tick and last tick as a [`Duration`] #[inline] - pub fn delta(&self) -> Duration { + pub const fn delta(&self) -> Duration { self.delta } /// The delta between the current and last tick as [`f32`] seconds #[inline] - pub fn delta_seconds(&self) -> f32 { + pub const fn delta_seconds(&self) -> f32 { self.delta_seconds } /// The delta between the current and last tick as [`f64`] seconds #[inline] - pub fn delta_seconds_f64(&self) -> f64 { + pub const fn delta_seconds_f64(&self) -> f64 { self.delta_seconds_f64 } /// The time from startup to the last update in seconds #[inline] - pub fn seconds_since_startup(&self) -> f64 { + pub const fn seconds_since_startup(&self) -> f64 { self.seconds_since_startup } /// The [`Instant`] the app was started #[inline] - pub fn startup(&self) -> Instant { + pub const fn startup(&self) -> Instant { self.startup } /// The ['Instant'] when [`Time::update`] was last called, if it exists #[inline] - pub fn last_update(&self) -> Option { + pub const fn last_update(&self) -> Option { self.last_update } /// The ['Duration'] from startup to the last update #[inline] - pub fn time_since_startup(&self) -> Duration { + pub const fn time_since_startup(&self) -> Duration { self.time_since_startup } } diff --git a/crates/bevy_core/src/time/timer.rs b/crates/bevy_core/src/time/timer.rs index b9bd0800de38e..85503fb986cd7 100644 --- a/crates/bevy_core/src/time/timer.rs +++ b/crates/bevy_core/src/time/timer.rs @@ -60,7 +60,7 @@ impl Timer { /// assert!(timer.finished()); /// ``` #[inline] - pub fn finished(&self) -> bool { + pub const fn finished(&self) -> bool { self.finished } @@ -77,7 +77,7 @@ impl Timer { /// assert!(!timer.just_finished()); /// ``` #[inline] - pub fn just_finished(&self) -> bool { + pub const fn just_finished(&self) -> bool { self.times_finished > 0 } @@ -95,7 +95,7 @@ impl Timer { /// assert_eq!(timer.elapsed(), Duration::from_secs_f32(0.5)); /// ``` #[inline] - pub fn elapsed(&self) -> Duration { + pub const fn elapsed(&self) -> Duration { self.stopwatch.elapsed() } @@ -135,7 +135,7 @@ impl Timer { /// assert_eq!(timer.duration(), Duration::from_secs(1)); /// ``` #[inline] - pub fn duration(&self) -> Duration { + pub const fn duration(&self) -> Duration { self.duration } @@ -163,7 +163,7 @@ impl Timer { /// assert!(timer.repeating()); /// ``` #[inline] - pub fn repeating(&self) -> bool { + pub const fn repeating(&self) -> bool { self.repeating } @@ -285,7 +285,7 @@ impl Timer { /// assert!(!timer.paused()); /// ``` #[inline] - pub fn paused(&self) -> bool { + pub const fn paused(&self) -> bool { self.stopwatch.paused() } @@ -359,7 +359,7 @@ impl Timer { /// assert_eq!(timer.times_finished(), 0); /// ``` #[inline] - pub fn times_finished(&self) -> u32 { + pub const fn times_finished(&self) -> u32 { self.times_finished } } diff --git a/crates/bevy_core_pipeline/src/main_pass_2d.rs b/crates/bevy_core_pipeline/src/main_pass_2d.rs index 8195a64cecca2..034327c4b45e5 100644 --- a/crates/bevy_core_pipeline/src/main_pass_2d.rs +++ b/crates/bevy_core_pipeline/src/main_pass_2d.rs @@ -25,7 +25,7 @@ impl MainPass2dNode { impl Node for MainPass2dNode { fn input(&self) -> Vec { - vec![SlotInfo::new(MainPass2dNode::IN_VIEW, SlotType::Entity)] + vec![SlotInfo::new(Self::IN_VIEW, SlotType::Entity)] } fn update(&mut self, world: &mut World) { diff --git a/crates/bevy_core_pipeline/src/main_pass_3d.rs b/crates/bevy_core_pipeline/src/main_pass_3d.rs index bd1e491fe8e36..e4658ff6c8e3a 100644 --- a/crates/bevy_core_pipeline/src/main_pass_3d.rs +++ b/crates/bevy_core_pipeline/src/main_pass_3d.rs @@ -33,7 +33,7 @@ impl MainPass3dNode { impl Node for MainPass3dNode { fn input(&self) -> Vec { - vec![SlotInfo::new(MainPass3dNode::IN_VIEW, SlotType::Entity)] + vec![SlotInfo::new(Self::IN_VIEW, SlotType::Entity)] } fn update(&mut self, world: &mut World) { diff --git a/crates/bevy_crevice/src/std140/dynamic_uniform.rs b/crates/bevy_crevice/src/std140/dynamic_uniform.rs index 262f8ea449842..1dc8deed55875 100644 --- a/crates/bevy_crevice/src/std140/dynamic_uniform.rs +++ b/crates/bevy_crevice/src/std140/dynamic_uniform.rs @@ -18,7 +18,7 @@ impl AsStd140 for DynamicUniform { } fn from_std140(value: Self::Output) -> Self { - DynamicUniform(::from_std140(value.0)) + Self(::from_std140(value.0)) } } diff --git a/crates/bevy_crevice/src/std140/sizer.rs b/crates/bevy_crevice/src/std140/sizer.rs index 87c27cb63b3d9..0a5fed82ed2cf 100644 --- a/crates/bevy_crevice/src/std140/sizer.rs +++ b/crates/bevy_crevice/src/std140/sizer.rs @@ -51,7 +51,7 @@ pub struct Sizer { impl Sizer { /// Create a new `Sizer`. - pub fn new() -> Self { + pub const fn new() -> Self { Self { offset: 0 } } @@ -75,7 +75,7 @@ impl Sizer { /// Returns the number of bytes required to contain all the types added to /// the `Sizer`. - pub fn len(&self) -> usize { + pub const fn len(&self) -> usize { self.offset } } diff --git a/crates/bevy_crevice/src/std430/sizer.rs b/crates/bevy_crevice/src/std430/sizer.rs index 05203d5577d9c..fb872c5a49216 100644 --- a/crates/bevy_crevice/src/std430/sizer.rs +++ b/crates/bevy_crevice/src/std430/sizer.rs @@ -51,7 +51,7 @@ pub struct Sizer { impl Sizer { /// Create a new `Sizer`. - pub fn new() -> Self { + pub const fn new() -> Self { Self { offset: 0 } } @@ -75,7 +75,7 @@ impl Sizer { /// Returns the number of bytes required to contain all the types added to /// the `Sizer`. - pub fn len(&self) -> usize { + pub const fn len(&self) -> usize { self.offset } } diff --git a/crates/bevy_diagnostic/src/diagnostic.rs b/crates/bevy_diagnostic/src/diagnostic.rs index 90df2c41888ef..d38100767ebc5 100644 --- a/crates/bevy_diagnostic/src/diagnostic.rs +++ b/crates/bevy_diagnostic/src/diagnostic.rs @@ -10,13 +10,13 @@ pub struct DiagnosticId(pub Uuid); impl DiagnosticId { pub const fn from_u128(value: u128) -> Self { - DiagnosticId(Uuid::from_u128(value)) + Self(Uuid::from_u128(value)) } } impl Default for DiagnosticId { fn default() -> Self { - DiagnosticId(Uuid::new_v4()) + Self(Uuid::new_v4()) } } @@ -57,7 +57,7 @@ impl Diagnostic { id: DiagnosticId, name: impl Into>, max_history_length: usize, - ) -> Diagnostic { + ) -> Self { let name = name.into(); if name.chars().count() > MAX_DIAGNOSTIC_NAME_WIDTH { // This could be a false positive due to a unicode width being shorter @@ -67,7 +67,7 @@ impl Diagnostic { name, MAX_DIAGNOSTIC_NAME_WIDTH ) } - Diagnostic { + Self { id, name, suffix: Cow::Borrowed(""), @@ -86,7 +86,7 @@ impl Diagnostic { self.history.back().map(|measurement| measurement.value) } - pub fn sum(&self) -> f64 { + pub const fn sum(&self) -> f64 { self.sum } @@ -116,7 +116,7 @@ impl Diagnostic { None } - pub fn get_max_history_length(&self) -> usize { + pub const fn get_max_history_length(&self) -> usize { self.max_history_length } diff --git a/crates/bevy_diagnostic/src/log_diagnostics_plugin.rs b/crates/bevy_diagnostic/src/log_diagnostics_plugin.rs index 571b050a1d877..b0f48b2735109 100644 --- a/crates/bevy_diagnostic/src/log_diagnostics_plugin.rs +++ b/crates/bevy_diagnostic/src/log_diagnostics_plugin.rs @@ -20,7 +20,7 @@ struct LogDiagnosticsState { impl Default for LogDiagnosticsPlugin { fn default() -> Self { - LogDiagnosticsPlugin { + Self { debug: false, wait_duration: Duration::from_secs(1), filter: None, @@ -45,7 +45,7 @@ impl Plugin for LogDiagnosticsPlugin { impl LogDiagnosticsPlugin { pub fn filtered(filter: Vec) -> Self { - LogDiagnosticsPlugin { + Self { filter: Some(filter), ..Default::default() } @@ -86,15 +86,18 @@ impl LogDiagnosticsPlugin { diagnostics: Res, ) { if state.timer.tick(time.delta()).finished() { - if let Some(ref filter) = state.filter { - for diagnostic in filter.iter().map(|id| diagnostics.get(*id).unwrap()) { - Self::log_diagnostic(diagnostic); - } - } else { - for diagnostic in diagnostics.iter() { - Self::log_diagnostic(diagnostic); - } - } + state.filter.as_ref().map_or_else( + || { + for diagnostic in diagnostics.iter() { + Self::log_diagnostic(diagnostic); + } + }, + |filter| { + for diagnostic in filter.iter().map(|id| diagnostics.get(*id).unwrap()) { + Self::log_diagnostic(diagnostic); + } + }, + ) } } @@ -104,15 +107,18 @@ impl LogDiagnosticsPlugin { diagnostics: Res, ) { if state.timer.tick(time.delta()).finished() { - if let Some(ref filter) = state.filter { - for diagnostic in filter.iter().map(|id| diagnostics.get(*id).unwrap()) { - debug!("{:#?}\n", diagnostic); - } - } else { - for diagnostic in diagnostics.iter() { - debug!("{:#?}\n", diagnostic); - } - } + state.filter.as_ref().map_or_else( + || { + for diagnostic in diagnostics.iter() { + debug!("{:#?}\n", diagnostic); + } + }, + |filter| { + for diagnostic in filter.iter().map(|id| diagnostics.get(*id).unwrap()) { + debug!("{:#?}\n", diagnostic); + } + }, + ) } } } diff --git a/crates/bevy_ecs/macros/src/lib.rs b/crates/bevy_ecs/macros/src/lib.rs index 548f2310a162f..63a517b9ace57 100644 --- a/crates/bevy_ecs/macros/src/lib.rs +++ b/crates/bevy_ecs/macros/src/lib.rs @@ -34,7 +34,7 @@ impl Parse for AllTuples { idents.push(input.parse::()?); } - Ok(AllTuples { + Ok(Self { macro_ident, start, end, diff --git a/crates/bevy_ecs/src/archetype.rs b/crates/bevy_ecs/src/archetype.rs index ca9d62cb46314..524c22b5b0dac 100644 --- a/crates/bevy_ecs/src/archetype.rs +++ b/crates/bevy_ecs/src/archetype.rs @@ -18,17 +18,17 @@ use std::{ pub struct ArchetypeId(usize); impl ArchetypeId { - pub const EMPTY: ArchetypeId = ArchetypeId(0); - pub const RESOURCE: ArchetypeId = ArchetypeId(1); - pub const INVALID: ArchetypeId = ArchetypeId(usize::MAX); + pub const EMPTY: Self = Self(0); + pub const RESOURCE: Self = Self(1); + pub const INVALID: Self = Self(usize::MAX); #[inline] pub const fn new(index: usize) -> Self { - ArchetypeId(index) + Self(index) } #[inline] - pub fn index(self) -> usize { + pub const fn index(self) -> usize { self.0 } } @@ -178,12 +178,12 @@ impl Archetype { } #[inline] - pub fn id(&self) -> ArchetypeId { + pub const fn id(&self) -> ArchetypeId { self.id } #[inline] - pub fn table_id(&self) -> TableId { + pub const fn table_id(&self) -> TableId { self.table_info.id } @@ -208,7 +208,7 @@ impl Archetype { } #[inline] - pub fn unique_components(&self) -> &SparseSet { + pub const fn unique_components(&self) -> &SparseSet { &self.unique_components } @@ -223,7 +223,7 @@ impl Archetype { } #[inline] - pub fn edges(&self) -> &Edges { + pub const fn edges(&self) -> &Edges { &self.edges } @@ -320,11 +320,11 @@ pub struct ArchetypeGeneration(usize); impl ArchetypeGeneration { #[inline] pub const fn initial() -> Self { - ArchetypeGeneration(0) + Self(0) } #[inline] - pub fn value(self) -> usize { + pub const fn value(self) -> usize { self.0 } } @@ -345,7 +345,7 @@ impl ArchetypeComponentId { } #[inline] - pub fn index(self) -> usize { + pub const fn index(self) -> usize { self.0 } } @@ -369,7 +369,7 @@ pub struct Archetypes { impl Default for Archetypes { fn default() -> Self { - let mut archetypes = Archetypes { + let mut archetypes = Self { archetypes: Vec::new(), archetype_ids: Default::default(), archetype_component_count: 0, @@ -515,7 +515,7 @@ impl Archetypes { } #[inline] - pub fn archetype_components_len(&self) -> usize { + pub const fn archetype_components_len(&self) -> usize { self.archetype_component_count } diff --git a/crates/bevy_ecs/src/bundle.rs b/crates/bevy_ecs/src/bundle.rs index 3bf6881eb31d2..d52d09a6e14f9 100644 --- a/crates/bevy_ecs/src/bundle.rs +++ b/crates/bevy_ecs/src/bundle.rs @@ -133,7 +133,7 @@ pub struct BundleId(usize); impl BundleId { #[inline] - pub fn index(self) -> usize { + pub const fn index(self) -> usize { self.0 } } @@ -157,7 +157,7 @@ pub struct BundleInfo { impl BundleInfo { #[inline] - pub fn id(&self) -> BundleId { + pub const fn id(&self) -> BundleId { self.id } diff --git a/crates/bevy_ecs/src/component.rs b/crates/bevy_ecs/src/component.rs index 69b3254dea8cb..a1481f7053159 100644 --- a/crates/bevy_ecs/src/component.rs +++ b/crates/bevy_ecs/src/component.rs @@ -86,7 +86,7 @@ pub enum StorageType { impl Default for StorageType { fn default() -> Self { - StorageType::Table + Self::Table } } @@ -98,7 +98,7 @@ pub struct ComponentInfo { impl ComponentInfo { #[inline] - pub fn id(&self) -> ComponentId { + pub const fn id(&self) -> ComponentId { self.id } @@ -108,12 +108,12 @@ impl ComponentInfo { } #[inline] - pub fn type_id(&self) -> Option { + pub const fn type_id(&self) -> Option { self.descriptor.type_id } #[inline] - pub fn layout(&self) -> Layout { + pub const fn layout(&self) -> Layout { self.descriptor.layout } @@ -123,17 +123,17 @@ impl ComponentInfo { } #[inline] - pub fn storage_type(&self) -> StorageType { + pub const fn storage_type(&self) -> StorageType { self.descriptor.storage_type } #[inline] - pub fn is_send_and_sync(&self) -> bool { + pub const fn is_send_and_sync(&self) -> bool { self.descriptor.is_send_and_sync } - fn new(id: ComponentId, descriptor: ComponentDescriptor) -> Self { - ComponentInfo { id, descriptor } + const fn new(id: ComponentId, descriptor: ComponentDescriptor) -> Self { + Self { id, descriptor } } } @@ -142,12 +142,12 @@ pub struct ComponentId(usize); impl ComponentId { #[inline] - pub const fn new(index: usize) -> ComponentId { - ComponentId(index) + pub const fn new(index: usize) -> Self { + Self(index) } #[inline] - pub fn index(self) -> usize { + pub const fn index(self) -> usize { self.0 } } @@ -222,12 +222,12 @@ impl ComponentDescriptor { } #[inline] - pub fn storage_type(&self) -> StorageType { + pub const fn storage_type(&self) -> StorageType { self.storage_type } #[inline] - pub fn type_id(&self) -> Option { + pub const fn type_id(&self) -> Option { self.type_id } @@ -357,7 +357,7 @@ pub struct ComponentTicks { impl ComponentTicks { #[inline] - pub fn is_added(&self, last_change_tick: u32, change_tick: u32) -> bool { + pub const fn is_added(&self, last_change_tick: u32, change_tick: u32) -> bool { // The comparison is relative to `change_tick` so that we can detect changes over the whole // `u32` range. Comparing directly the ticks would limit to half that due to overflow // handling. @@ -368,14 +368,14 @@ impl ComponentTicks { } #[inline] - pub fn is_changed(&self, last_change_tick: u32, change_tick: u32) -> bool { + pub const fn is_changed(&self, last_change_tick: u32, change_tick: u32) -> bool { let component_delta = change_tick.wrapping_sub(self.changed); let system_delta = change_tick.wrapping_sub(last_change_tick); component_delta < system_delta } - pub(crate) fn new(change_tick: u32) -> Self { + pub(crate) const fn new(change_tick: u32) -> Self { Self { added: change_tick, changed: change_tick, diff --git a/crates/bevy_ecs/src/entity/mod.rs b/crates/bevy_ecs/src/entity/mod.rs index 75ee18ee49dfb..ddb908b21c13c 100644 --- a/crates/bevy_ecs/src/entity/mod.rs +++ b/crates/bevy_ecs/src/entity/mod.rs @@ -104,8 +104,8 @@ impl Entity { /// } /// } /// ``` - pub fn from_raw(id: u32) -> Entity { - Entity { id, generation: 0 } + pub const fn from_raw(id: u32) -> Self { + Self { id, generation: 0 } } /// Convert to a form convenient for passing outside of rust. @@ -121,7 +121,7 @@ impl Entity { /// Reconstruct an `Entity` previously destructured with [`Entity::to_bits`]. /// /// Only useful when applied to results from `to_bits` in the same instance of an application. - pub fn from_bits(bits: u64) -> Self { + pub const fn from_bits(bits: u64) -> Self { Self { generation: (bits >> 32) as u32, id: bits as u32, @@ -134,7 +134,7 @@ impl Entity { /// with both live and dead entities. Useful for compactly representing entities within a /// specific snapshot of the world, such as when serializing. #[inline] - pub fn id(self) -> u32 { + pub const fn id(self) -> u32 { self.id } @@ -142,7 +142,7 @@ impl Entity { /// entity with a given id is despawned. This serves as a "count" of the number of times a /// given id has been reused (id, generation) pairs uniquely identify a given Entity. #[inline] - pub fn generation(self) -> u32 { + pub const fn generation(self) -> u32 { self.generation } } @@ -159,7 +159,7 @@ impl SparseSetIndex for Entity { } fn get_sparse_set_index(value: usize) -> Self { - Entity::from_raw(value as u32) + Self::from_raw(value as u32) } } @@ -312,8 +312,9 @@ impl Entities { /// Check that we do not have pending work requiring `flush()` to be called. fn verify_flushed(&mut self) { + let needs_flush = !self.needs_flush(); debug_assert!( - !self.needs_flush(), + needs_flush, "flush() needs to be called before this operation is legal" ); } @@ -545,12 +546,12 @@ impl Entities { } #[inline] - pub fn len(&self) -> u32 { + pub const fn len(&self) -> u32 { self.len } #[inline] - pub fn is_empty(&self) -> bool { + pub const fn is_empty(&self) -> bool { self.len == 0 } } @@ -562,7 +563,7 @@ pub struct EntityMeta { } impl EntityMeta { - const EMPTY: EntityMeta = EntityMeta { + const EMPTY: Self = Self { generation: 0, location: EntityLocation { archetype_id: ArchetypeId::INVALID, diff --git a/crates/bevy_ecs/src/event.rs b/crates/bevy_ecs/src/event.rs index 5d6cb12c49b76..f62c536329a90 100644 --- a/crates/bevy_ecs/src/event.rs +++ b/crates/bevy_ecs/src/event.rs @@ -134,7 +134,7 @@ pub struct Events { impl Default for Events { fn default() -> Self { - Events { + Self { a_start_event_count: 0, b_start_event_count: 0, event_count: 0, @@ -145,11 +145,11 @@ impl Default for Events { } } -fn map_instance_event_with_id(event_instance: &EventInstance) -> (&T, EventId) { +const fn map_instance_event_with_id(event_instance: &EventInstance) -> (&T, EventId) { (&event_instance.event, event_instance.event_id) } -fn map_instance_event(event_instance: &EventInstance) -> &T { +const fn map_instance_event(event_instance: &EventInstance) -> &T { &event_instance.event } @@ -185,7 +185,7 @@ pub struct ManualEventReader { impl Default for ManualEventReader { fn default() -> Self { - ManualEventReader { + Self { last_event_count: 0, _marker: Default::default(), } diff --git a/crates/bevy_ecs/src/query/access.rs b/crates/bevy_ecs/src/query/access.rs index 25c1f39054008..57df955082385 100644 --- a/crates/bevy_ecs/src/query/access.rs +++ b/crates/bevy_ecs/src/query/access.rs @@ -77,7 +77,7 @@ impl Access { } /// Extends this `Access` with another, copying all accesses of `other` into this. - pub fn extend(&mut self, other: &Access) { + pub fn extend(&mut self, other: &Self) { self.reads_all = self.reads_all || other.reads_all; self.reads_and_writes.union_with(&other.reads_and_writes); self.writes.union_with(&other.writes); @@ -87,7 +87,7 @@ impl Access { /// /// Two `Access` instances are incompatible with each other if one `Access` has a write for /// which the other also has a write or a read. - pub fn is_compatible(&self, other: &Access) -> bool { + pub fn is_compatible(&self, other: &Self) -> bool { if self.reads_all { 0 == other.writes.count_ones(..) } else if other.reads_all { @@ -99,7 +99,7 @@ impl Access { } /// Calculates conflicting accesses between this `Access` and `other`. - pub fn get_conflicts(&self, other: &Access) -> Vec { + pub fn get_conflicts(&self, other: &Self) -> Vec { let mut conflicts = FixedBitSet::default(); if self.reads_all { conflicts.extend(other.writes.ones()); @@ -172,7 +172,7 @@ impl FilteredAccess { self.without.insert(index.sparse_set_index()); } - pub fn is_compatible(&self, other: &FilteredAccess) -> bool { + pub fn is_compatible(&self, other: &Self) -> bool { if self.access.is_compatible(&other.access) { true } else { @@ -181,7 +181,7 @@ impl FilteredAccess { } } - pub fn extend(&mut self, access: &FilteredAccess) { + pub fn extend(&mut self, access: &Self) { self.access.extend(&access.access); self.with.union_with(&access.with); self.without.union_with(&access.without); diff --git a/crates/bevy_ecs/src/query/fetch.rs b/crates/bevy_ecs/src/query/fetch.rs index a98cdd9dcd298..f9963f44d6586 100644 --- a/crates/bevy_ecs/src/query/fetch.rs +++ b/crates/bevy_ecs/src/query/fetch.rs @@ -243,7 +243,7 @@ pub struct ReadState { unsafe impl FetchState for ReadState { fn init(world: &mut World) -> Self { let component_id = world.init_component::(); - ReadState { + Self { component_id, marker: PhantomData, } @@ -445,7 +445,7 @@ pub struct WriteState { unsafe impl FetchState for WriteState { fn init(world: &mut World) -> Self { let component_id = world.init_component::(); - WriteState { + Self { component_id, marker: PhantomData, } diff --git a/crates/bevy_ecs/src/reflect.rs b/crates/bevy_ecs/src/reflect.rs index 4881dd83f0edd..ec3af547966ba 100644 --- a/crates/bevy_ecs/src/reflect.rs +++ b/crates/bevy_ecs/src/reflect.rs @@ -82,7 +82,7 @@ impl ReflectComponent { impl FromType for ReflectComponent { fn from_type() -> Self { - ReflectComponent { + Self { add_component: |world, entity, reflected_component| { let mut component = C::from_world(world); component.apply(reflected_component); @@ -142,7 +142,7 @@ impl ReflectMapEntities { impl FromType for ReflectMapEntities { fn from_type() -> Self { - ReflectMapEntities { + Self { map_entities: |world, entity_map| { for entity in entity_map.values() { if let Some(mut component) = world.get_mut::(entity) { diff --git a/crates/bevy_ecs/src/schedule/run_criteria.rs b/crates/bevy_ecs/src/schedule/run_criteria.rs index 5ba47a1c5337e..b6a6bc7cbf724 100644 --- a/crates/bevy_ecs/src/schedule/run_criteria.rs +++ b/crates/bevy_ecs/src/schedule/run_criteria.rs @@ -223,7 +223,7 @@ impl IntoRunCriteria for RunCriteriaDescriptor { } } -impl IntoRunCriteria> for BoxedSystem<(), ShouldRun> { +impl IntoRunCriteria for BoxedSystem<(), ShouldRun> { fn into(self) -> RunCriteriaDescriptorOrLabel { RunCriteriaDescriptorOrLabel::Descriptor(new_run_criteria_descriptor(self)) } @@ -240,7 +240,7 @@ where } } -impl IntoRunCriteria for BoxedRunCriteriaLabel { +impl IntoRunCriteria for BoxedRunCriteriaLabel { fn into(self) -> RunCriteriaDescriptorOrLabel { RunCriteriaDescriptorOrLabel::Label(self) } @@ -255,7 +255,7 @@ where } } -impl IntoRunCriteria for RunCriteria { +impl IntoRunCriteria for RunCriteria { fn into(self) -> RunCriteriaDescriptorOrLabel { RunCriteriaDescriptorOrLabel::Label(self.label) } @@ -408,7 +408,7 @@ impl System for RunOnce { type Out = ShouldRun; fn name(&self) -> Cow<'static, str> { - Cow::Borrowed(std::any::type_name::()) + Cow::Borrowed(std::any::type_name::()) } fn new_archetype(&mut self, _archetype: &Archetype) {} diff --git a/crates/bevy_ecs/src/schedule/stage.rs b/crates/bevy_ecs/src/schedule/stage.rs index 117fc2c6c81b4..0696f78796b1d 100644 --- a/crates/bevy_ecs/src/schedule/stage.rs +++ b/crates/bevy_ecs/src/schedule/stage.rs @@ -90,7 +90,7 @@ pub struct SystemStage { impl SystemStage { pub fn new(executor: Box) -> Self { - SystemStage { + Self { world_id: None, executor, stage_run_criteria: Default::default(), diff --git a/crates/bevy_ecs/src/schedule/state.rs b/crates/bevy_ecs/src/schedule/state.rs index 24b8801917cf5..809710a481c7f 100644 --- a/crates/bevy_ecs/src/schedule/state.rs +++ b/crates/bevy_ecs/src/schedule/state.rs @@ -96,7 +96,7 @@ where T: StateData, { pub fn on_update(s: T) -> RunCriteriaDescriptor { - (|state: Res>, pred: Local>| { + (|state: Res, pred: Local>| { state.stack.last().unwrap() == pred.as_ref().unwrap() && state.transition.is_none() }) .config(|(_, pred)| *pred = Some(Some(s.clone()))) @@ -106,7 +106,7 @@ where } pub fn on_inactive_update(s: T) -> RunCriteriaDescriptor { - (|state: Res>, mut is_inactive: Local, pred: Local>| match &state + (|state: Res, mut is_inactive: Local, pred: Local>| match &state .transition { Some(StateTransition::Pausing(ref relevant, _)) @@ -126,7 +126,7 @@ where } pub fn on_in_stack_update(s: T) -> RunCriteriaDescriptor { - (|state: Res>, mut is_in_stack: Local, pred: Local>| match &state + (|state: Res, mut is_in_stack: Local, pred: Local>| match &state .transition { Some(StateTransition::Entering(ref relevant, _)) @@ -158,7 +158,7 @@ where } pub fn on_enter(s: T) -> RunCriteriaDescriptor { - (|state: Res>, pred: Local>| { + (|state: Res, pred: Local>| { state .transition .as_ref() @@ -177,7 +177,7 @@ where } pub fn on_exit(s: T) -> RunCriteriaDescriptor { - (|state: Res>, pred: Local>| { + (|state: Res, pred: Local>| { state .transition .as_ref() @@ -194,7 +194,7 @@ where } pub fn on_pause(s: T) -> RunCriteriaDescriptor { - (|state: Res>, pred: Local>| { + (|state: Res, pred: Local>| { state .transition .as_ref() @@ -210,7 +210,7 @@ where } pub fn on_resume(s: T) -> RunCriteriaDescriptor { - (|state: Res>, pred: Local>| { + (|state: Res, pred: Local>| { state .transition .as_ref() diff --git a/crates/bevy_ecs/src/schedule/system_container.rs b/crates/bevy_ecs/src/schedule/system_container.rs index 108e391d606f8..336729b12d3ee 100644 --- a/crates/bevy_ecs/src/schedule/system_container.rs +++ b/crates/bevy_ecs/src/schedule/system_container.rs @@ -37,7 +37,7 @@ pub(super) struct ExclusiveSystemContainer { impl ExclusiveSystemContainer { pub(super) fn from_descriptor(descriptor: ExclusiveSystemDescriptor) -> Self { - ExclusiveSystemContainer { + Self { system: descriptor.system, run_criteria_index: None, run_criteria_label: None, @@ -122,7 +122,7 @@ unsafe impl Sync for ParallelSystemContainer {} impl ParallelSystemContainer { pub(crate) fn from_descriptor(descriptor: ParallelSystemDescriptor) -> Self { - ParallelSystemContainer { + Self { system: descriptor.system, should_run: false, run_criteria_index: None, @@ -147,7 +147,7 @@ impl ParallelSystemContainer { &mut *self.system } - pub fn should_run(&self) -> bool { + pub const fn should_run(&self) -> bool { self.should_run } diff --git a/crates/bevy_ecs/src/schedule/system_set.rs b/crates/bevy_ecs/src/schedule/system_set.rs index 0702445c79fd0..0cf09773abf74 100644 --- a/crates/bevy_ecs/src/schedule/system_set.rs +++ b/crates/bevy_ecs/src/schedule/system_set.rs @@ -21,49 +21,49 @@ impl SystemSet { Default::default() } - pub fn on_update(s: T) -> SystemSet + pub fn on_update(s: T) -> Self where T: StateData, { Self::new().with_run_criteria(State::::on_update(s)) } - pub fn on_inactive_update(s: T) -> SystemSet + pub fn on_inactive_update(s: T) -> Self where T: StateData, { Self::new().with_run_criteria(State::::on_inactive_update(s)) } - pub fn on_in_stack_update(s: T) -> SystemSet + pub fn on_in_stack_update(s: T) -> Self where T: StateData, { Self::new().with_run_criteria(State::::on_in_stack_update(s)) } - pub fn on_enter(s: T) -> SystemSet + pub fn on_enter(s: T) -> Self where T: StateData, { Self::new().with_run_criteria(State::::on_enter(s)) } - pub fn on_exit(s: T) -> SystemSet + pub fn on_exit(s: T) -> Self where T: StateData, { Self::new().with_run_criteria(State::::on_exit(s)) } - pub fn on_pause(s: T) -> SystemSet + pub fn on_pause(s: T) -> Self where T: StateData, { Self::new().with_run_criteria(State::::on_pause(s)) } - pub fn on_resume(s: T) -> SystemSet + pub fn on_resume(s: T) -> Self where T: StateData, { @@ -101,7 +101,7 @@ impl SystemSet { } pub(crate) fn bake(self) -> (Option, Vec) { - let SystemSet { + let Self { mut systems, run_criteria, labels, diff --git a/crates/bevy_ecs/src/storage/blob_vec.rs b/crates/bevy_ecs/src/storage/blob_vec.rs index ac2e61e2746fb..f92f3df72866c 100644 --- a/crates/bevy_ecs/src/storage/blob_vec.rs +++ b/crates/bevy_ecs/src/storage/blob_vec.rs @@ -17,9 +17,9 @@ pub struct BlobVec { } impl BlobVec { - pub fn new(item_layout: Layout, drop: unsafe fn(*mut u8), capacity: usize) -> BlobVec { + pub fn new(item_layout: Layout, drop: unsafe fn(*mut u8), capacity: usize) -> Self { if item_layout.size() == 0 { - BlobVec { + Self { swap_scratch: NonNull::dangling(), data: NonNull::dangling(), capacity: usize::MAX, @@ -30,7 +30,7 @@ impl BlobVec { } else { let swap_scratch = NonNull::new(unsafe { std::alloc::alloc(item_layout) }) .unwrap_or_else(|| std::alloc::handle_alloc_error(item_layout)); - let mut blob_vec = BlobVec { + let mut blob_vec = Self { swap_scratch, data: NonNull::dangling(), capacity: 0, @@ -44,17 +44,17 @@ impl BlobVec { } #[inline] - pub fn len(&self) -> usize { + pub const fn len(&self) -> usize { self.len } #[inline] - pub fn is_empty(&self) -> bool { + pub const fn is_empty(&self) -> bool { self.len == 0 } #[inline] - pub fn capacity(&self) -> usize { + pub const fn capacity(&self) -> usize { self.capacity } @@ -196,7 +196,7 @@ impl BlobVec { /// # Safety /// must ensure rust mutability rules are not violated #[inline] - pub unsafe fn get_ptr(&self) -> NonNull { + pub const unsafe fn get_ptr(&self) -> NonNull { self.data } diff --git a/crates/bevy_ecs/src/storage/sparse_set.rs b/crates/bevy_ecs/src/storage/sparse_set.rs index 0b4efbe9bf339..d5e7ae7cabf68 100644 --- a/crates/bevy_ecs/src/storage/sparse_set.rs +++ b/crates/bevy_ecs/src/storage/sparse_set.rs @@ -117,12 +117,12 @@ impl ComponentSparseSet { } #[inline] - pub fn len(&self) -> usize { + pub const fn len(&self) -> usize { self.dense.len() } #[inline] - pub fn is_empty(&self) -> bool { + pub const fn is_empty(&self) -> bool { self.dense.len() == 0 } diff --git a/crates/bevy_ecs/src/storage/table.rs b/crates/bevy_ecs/src/storage/table.rs index afa5375c62e08..16a5a2bbe1438 100644 --- a/crates/bevy_ecs/src/storage/table.rs +++ b/crates/bevy_ecs/src/storage/table.rs @@ -16,18 +16,18 @@ pub struct TableId(usize); impl TableId { #[inline] - pub fn new(index: usize) -> Self { - TableId(index) + pub const fn new(index: usize) -> Self { + Self(index) } #[inline] - pub fn index(self) -> usize { + pub const fn index(self) -> usize { self.0 } #[inline] - pub const fn empty() -> TableId { - TableId(0) + pub const fn empty() -> Self { + Self(0) } } @@ -40,7 +40,7 @@ pub struct Column { impl Column { #[inline] pub fn with_capacity(component_info: &ComponentInfo, capacity: usize) -> Self { - Column { + Self { component_id: component_info.id(), data: BlobVec::new(component_info.layout(), component_info.drop(), capacity), ticks: Vec::with_capacity(capacity), @@ -84,12 +84,12 @@ impl Column { } #[inline] - pub fn len(&self) -> usize { + pub const fn len(&self) -> usize { self.data.len() } #[inline] - pub fn is_empty(&self) -> bool { + pub const fn is_empty(&self) -> bool { self.data.is_empty() } @@ -136,7 +136,7 @@ impl Column { /// # Safety /// must ensure rust mutability rules are not violated #[inline] - pub unsafe fn get_data_ptr(&self) -> NonNull { + pub const unsafe fn get_data_ptr(&self) -> NonNull { self.data.get_ptr() } @@ -198,14 +198,14 @@ pub struct Table { } impl Table { - pub const fn new() -> Table { + pub const fn new() -> Self { Self { columns: SparseSet::new(), entities: Vec::new(), } } - pub fn with_capacity(capacity: usize, column_capacity: usize) -> Table { + pub fn with_capacity(capacity: usize, column_capacity: usize) -> Self { Self { columns: SparseSet::with_capacity(column_capacity), entities: Vec::with_capacity(capacity), @@ -252,7 +252,7 @@ impl Table { pub unsafe fn move_to_and_forget_missing_unchecked( &mut self, row: usize, - new_table: &mut Table, + new_table: &mut Self, ) -> TableMoveResult { debug_assert!(row < self.len()); let is_last = row == self.entities.len() - 1; @@ -282,7 +282,7 @@ impl Table { pub unsafe fn move_to_and_drop_missing_unchecked( &mut self, row: usize, - new_table: &mut Table, + new_table: &mut Self, ) -> TableMoveResult { debug_assert!(row < self.len()); let is_last = row == self.entities.len() - 1; @@ -314,7 +314,7 @@ impl Table { pub unsafe fn move_to_superset_unchecked( &mut self, row: usize, - new_table: &mut Table, + new_table: &mut Self, ) -> TableMoveResult { debug_assert!(row < self.len()); let is_last = row == self.entities.len() - 1; @@ -421,7 +421,7 @@ pub struct Tables { impl Default for Tables { fn default() -> Self { let empty_table = Table::with_capacity(0, 0); - Tables { + Self { tables: vec![empty_table], table_ids: HashMap::default(), } diff --git a/crates/bevy_ecs/src/system/commands/mod.rs b/crates/bevy_ecs/src/system/commands/mod.rs index 6de329856cf2a..01b7b5a51ddc0 100644 --- a/crates/bevy_ecs/src/system/commands/mod.rs +++ b/crates/bevy_ecs/src/system/commands/mod.rs @@ -372,7 +372,7 @@ impl<'w, 's, 'a> EntityCommands<'w, 's, 'a> { /// # my_system.system(); /// ``` #[inline] - pub fn id(&self) -> Entity { + pub const fn id(&self) -> Entity { self.entity } @@ -746,7 +746,7 @@ mod tests { impl DropCk { fn new_pair() -> (Self, Arc) { let atomic = Arc::new(AtomicUsize::new(0)); - (DropCk(atomic.clone()), atomic) + (Self(atomic.clone()), atomic) } } diff --git a/crates/bevy_ecs/src/system/function_system.rs b/crates/bevy_ecs/src/system/function_system.rs index 3e255423e972e..d7a16b86afc87 100644 --- a/crates/bevy_ecs/src/system/function_system.rs +++ b/crates/bevy_ecs/src/system/function_system.rs @@ -35,7 +35,7 @@ impl SystemMeta { /// Returns true if the system is [`Send`]. #[inline] - pub fn is_send(&self) -> bool { + pub const fn is_send(&self) -> bool { self.is_send } diff --git a/crates/bevy_ecs/src/system/system_param.rs b/crates/bevy_ecs/src/system/system_param.rs index d919f2788052c..6a5446ea603c8 100644 --- a/crates/bevy_ecs/src/system/system_param.rs +++ b/crates/bevy_ecs/src/system/system_param.rs @@ -124,7 +124,7 @@ where type Config = (); fn init(world: &mut World, system_meta: &mut SystemMeta, _config: Self::Config) -> Self { - let state = QueryState::new(world); + let state = Self::new(world); assert_component_access_compatibility( &system_meta.name, std::any::type_name::(), @@ -747,13 +747,13 @@ where impl<'w, T: 'static> NonSend<'w, T> { /// Returns true if (and only if) this resource been added since the last execution of this /// system. - pub fn is_added(&self) -> bool { + pub const fn is_added(&self) -> bool { self.ticks.is_added(self.last_change_tick, self.change_tick) } /// Returns true if (and only if) this resource been changed since the last execution of this /// system. - pub fn is_changed(&self) -> bool { + pub const fn is_changed(&self) -> bool { self.ticks .is_changed(self.last_change_tick, self.change_tick) } diff --git a/crates/bevy_ecs/src/world/entity_ref.rs b/crates/bevy_ecs/src/world/entity_ref.rs index b85fa2b74f0f2..e7227e3177173 100644 --- a/crates/bevy_ecs/src/world/entity_ref.rs +++ b/crates/bevy_ecs/src/world/entity_ref.rs @@ -17,7 +17,7 @@ pub struct EntityRef<'w> { impl<'w> EntityRef<'w> { #[inline] - pub(crate) fn new(world: &'w World, entity: Entity, location: EntityLocation) -> Self { + pub(crate) const fn new(world: &'w World, entity: Entity, location: EntityLocation) -> Self { Self { world, entity, @@ -26,12 +26,12 @@ impl<'w> EntityRef<'w> { } #[inline] - pub fn id(&self) -> Entity { + pub const fn id(&self) -> Entity { self.entity } #[inline] - pub fn location(&self) -> EntityLocation { + pub const fn location(&self) -> EntityLocation { self.location } @@ -113,12 +113,12 @@ impl<'w> EntityMut<'w> { } #[inline] - pub fn id(&self) -> Entity { + pub const fn id(&self) -> Entity { self.entity } #[inline] - pub fn location(&self) -> EntityLocation { + pub const fn location(&self) -> EntityLocation { self.location } @@ -369,7 +369,7 @@ impl<'w> EntityMut<'w> { // Make sure to drop components stored in sparse sets. // Dense components are dropped later in `move_to_and_drop_missing_unchecked`. - if let Some(StorageType::SparseSet) = old_archetype.get_storage_type(component_id) { + if old_archetype.get_storage_type(component_id) == Some(StorageType::SparseSet) { storages .sparse_sets .get_mut(component_id) @@ -591,11 +591,12 @@ pub(crate) unsafe fn get_component_and_ticks_with_type( } fn contains_component_with_type(world: &World, type_id: TypeId, location: EntityLocation) -> bool { - if let Some(component_id) = world.components.get_id(type_id) { - contains_component_with_id(world, component_id, location) - } else { - false - } + world + .components + .get_id(type_id) + .map_or(false, |component_id| { + contains_component_with_id(world, component_id, location) + }) } fn contains_component_with_id( diff --git a/crates/bevy_ecs/src/world/mod.rs b/crates/bevy_ecs/src/world/mod.rs index c07892a35243a..4e2c5ca010e0f 100644 --- a/crates/bevy_ecs/src/world/mod.rs +++ b/crates/bevy_ecs/src/world/mod.rs @@ -111,19 +111,19 @@ impl World { /// This guarantee allows System Parameters to safely uniquely identify a [`World`], /// since its [`WorldId`] is unique #[inline] - pub fn new() -> World { - World::default() + pub fn new() -> Self { + Self::default() } /// Retrieves this [`World`]'s unique ID #[inline] - pub fn id(&self) -> WorldId { + pub const fn id(&self) -> WorldId { self.id } /// Retrieves this world's [Entities] collection #[inline] - pub fn entities(&self) -> &Entities { + pub const fn entities(&self) -> &Entities { &self.entities } @@ -135,13 +135,13 @@ impl World { /// Retrieves this world's [Archetypes] collection #[inline] - pub fn archetypes(&self) -> &Archetypes { + pub const fn archetypes(&self) -> &Archetypes { &self.archetypes } /// Retrieves this world's [Components] collection #[inline] - pub fn components(&self) -> &Components { + pub const fn components(&self) -> &Components { &self.components } @@ -153,13 +153,13 @@ impl World { /// Retrieves this world's [Storages] collection #[inline] - pub fn storages(&self) -> &Storages { + pub const fn storages(&self) -> &Storages { &self.storages } /// Retrieves this world's [Bundles] collection #[inline] - pub fn bundles(&self) -> &Bundles { + pub const fn bundles(&self) -> &Bundles { &self.bundles } @@ -571,11 +571,10 @@ impl World { /// Returns an iterator of entities that had components of type `T` removed /// since the last call to [`World::clear_trackers`]. pub fn removed(&self) -> std::iter::Cloned> { - if let Some(component_id) = self.components.get_id(TypeId::of::()) { - self.removed_with_id(component_id) - } else { - [].iter().cloned() - } + self.components.get_id(TypeId::of::()).map_or_else( + || [].iter().cloned(), + |component_id| self.removed_with_id(component_id), + ) } /// Returns an iterator of entities that had components with the given `component_id` removed @@ -584,11 +583,9 @@ impl World { &self, component_id: ComponentId, ) -> std::iter::Cloned> { - if let Some(removed) = self.removed_components.get(component_id) { - removed.iter().cloned() - } else { - [].iter().cloned() - } + self.removed_components + .get(component_id) + .map_or_else(|| [].iter().cloned(), |removed| removed.iter().cloned()) } /// Inserts a new resource with the given `value`. @@ -907,7 +904,7 @@ impl World { /// }); /// assert_eq!(world.get_resource::().unwrap().0, 2); /// ``` - pub fn resource_scope(&mut self, f: impl FnOnce(&mut World, Mut) -> U) -> U { + pub fn resource_scope(&mut self, f: impl FnOnce(&mut Self, Mut) -> U) -> U { let component_id = self .components .get_resource_id(TypeId::of::()) @@ -1120,7 +1117,7 @@ impl World { } #[inline] - pub fn last_change_tick(&self) -> u32 { + pub const fn last_change_tick(&self) -> u32 { self.last_change_tick } diff --git a/crates/bevy_gilrs/src/converter.rs b/crates/bevy_gilrs/src/converter.rs index a2e68b7db27e1..0e0b56e79a184 100644 --- a/crates/bevy_gilrs/src/converter.rs +++ b/crates/bevy_gilrs/src/converter.rs @@ -4,7 +4,7 @@ pub fn convert_gamepad_id(gamepad_id: gilrs::GamepadId) -> Gamepad { Gamepad(gamepad_id.into()) } -pub fn convert_button(button: gilrs::Button) -> Option { +pub const fn convert_button(button: gilrs::Button) -> Option { match button { gilrs::Button::South => Some(GamepadButtonType::South), gilrs::Button::East => Some(GamepadButtonType::East), @@ -29,7 +29,7 @@ pub fn convert_button(button: gilrs::Button) -> Option { } } -pub fn convert_axis(axis: gilrs::Axis) -> Option { +pub const fn convert_axis(axis: gilrs::Axis) -> Option { match axis { gilrs::Axis::LeftStickX => Some(GamepadAxisType::LeftStickX), gilrs::Axis::LeftStickY => Some(GamepadAxisType::LeftStickY), diff --git a/crates/bevy_gltf/src/loader.rs b/crates/bevy_gltf/src/loader.rs index db59b3a8f25ba..945a7edb1892b 100644 --- a/crates/bevy_gltf/src/loader.rs +++ b/crates/bevy_gltf/src/loader.rs @@ -383,55 +383,44 @@ fn load_material(material: &Material, load_context: &mut LoadContext) -> Handle< let pbr = material.pbr_metallic_roughness(); let color = pbr.base_color_factor(); - let base_color_texture = if let Some(info) = pbr.base_color_texture() { + let base_color_texture = pbr.base_color_texture().map(|info| { // TODO: handle info.tex_coord() (the *set* index for the right texcoords) let label = texture_label(&info.texture()); let path = AssetPath::new_ref(load_context.path(), Some(&label)); - Some(load_context.get_handle(path)) - } else { - None - }; + load_context.get_handle(path) + }); - let normal_map_texture: Option> = - if let Some(normal_texture) = material.normal_texture() { - // TODO: handle normal_texture.scale - // TODO: handle normal_texture.tex_coord() (the *set* index for the right texcoords) - let label = texture_label(&normal_texture.texture()); - let path = AssetPath::new_ref(load_context.path(), Some(&label)); - Some(load_context.get_handle(path)) - } else { - None - }; + let normal_map_texture = material.normal_texture().map(|normal_texture| { + // TODO: handle normal_texture.scale + // TODO: handle normal_texture.tex_coord() (the *set* index for the right texcoords) + let label = texture_label(&normal_texture.texture()); + let path = AssetPath::new_ref(load_context.path(), Some(&label)); + load_context.get_handle(path) + }); - let metallic_roughness_texture = if let Some(info) = pbr.metallic_roughness_texture() { + let metallic_roughness_texture = pbr.metallic_roughness_texture().map(|info| { // TODO: handle info.tex_coord() (the *set* index for the right texcoords) let label = texture_label(&info.texture()); let path = AssetPath::new_ref(load_context.path(), Some(&label)); - Some(load_context.get_handle(path)) - } else { - None - }; + load_context.get_handle(path) + }); - let occlusion_texture = if let Some(occlusion_texture) = material.occlusion_texture() { + let occlusion_texture = material.occlusion_texture().map(|occlusion_texture| { // TODO: handle occlusion_texture.tex_coord() (the *set* index for the right texcoords) // TODO: handle occlusion_texture.strength() (a scalar multiplier for occlusion strength) let label = texture_label(&occlusion_texture.texture()); let path = AssetPath::new_ref(load_context.path(), Some(&label)); - Some(load_context.get_handle(path)) - } else { - None - }; + load_context.get_handle(path) + }); let emissive = material.emissive_factor(); - let emissive_texture = if let Some(info) = material.emissive_texture() { + let emissive_texture = material.emissive_texture().map(|info| { // TODO: handle occlusion_texture.tex_coord() (the *set* index for the right texcoords) // TODO: handle occlusion_texture.strength() (a scalar multiplier for occlusion strength) let label = texture_label(&info.texture()); let path = AssetPath::new_ref(load_context.path(), Some(&label)); - Some(load_context.get_handle(path)) - } else { - None - }; + load_context.get_handle(path) + }); load_context.set_labeled_asset( &material_label, @@ -607,11 +596,7 @@ fn load_node( } } }); - if let Some(err) = gltf_error { - Err(err) - } else { - Ok(()) - } + gltf_error.map_or(Ok(()), |err| Err(err)) } /// Returns the label for the `mesh`. @@ -626,11 +611,10 @@ fn primitive_label(mesh: &gltf::Mesh, primitive: &Primitive) -> String { /// Returns the label for the `material`. fn material_label(material: &gltf::Material) -> String { - if let Some(index) = material.index() { - format!("Material{}", index) - } else { - "MaterialDefault".to_string() - } + material.index().map_or_else( + || "MaterialDefault".to_string(), + |index| format!("Material{}", index), + ) } /// Returns the label for the `texture`. @@ -694,7 +678,7 @@ fn texture_sampler<'a>(texture: &gltf::Texture) -> SamplerDescriptor<'a> { } /// Maps the texture address mode form glTF to wgpu. -fn texture_address_mode(gltf_address_mode: &gltf::texture::WrappingMode) -> AddressMode { +const fn texture_address_mode(gltf_address_mode: &gltf::texture::WrappingMode) -> AddressMode { match gltf_address_mode { WrappingMode::ClampToEdge => AddressMode::ClampToEdge, WrappingMode::Repeat => AddressMode::Repeat, @@ -703,7 +687,7 @@ fn texture_address_mode(gltf_address_mode: &gltf::texture::WrappingMode) -> Addr } /// Maps the `primitive_topology` form glTF to `wgpu`. -fn get_primitive_topology(mode: Mode) -> Result { +const fn get_primitive_topology(mode: Mode) -> Result { match mode { Mode::Points => Ok(PrimitiveTopology::PointList), Mode::Lines => Ok(PrimitiveTopology::LineList), diff --git a/crates/bevy_input/src/axis.rs b/crates/bevy_input/src/axis.rs index 842527b015c22..1cc441d6fb8a8 100644 --- a/crates/bevy_input/src/axis.rs +++ b/crates/bevy_input/src/axis.rs @@ -15,7 +15,7 @@ where T: Copy + Eq + Hash, { fn default() -> Self { - Axis { + Self { axis_data: HashMap::default(), } } diff --git a/crates/bevy_input/src/gamepad.rs b/crates/bevy_input/src/gamepad.rs index b71457983d8de..ad0ce2582aa16 100644 --- a/crates/bevy_input/src/gamepad.rs +++ b/crates/bevy_input/src/gamepad.rs @@ -137,7 +137,7 @@ pub struct ButtonSettings { impl Default for ButtonSettings { fn default() -> Self { - ButtonSettings { + Self { press: 0.75, release: 0.65, } @@ -174,7 +174,7 @@ pub struct AxisSettings { impl Default for AxisSettings { fn default() -> Self { - AxisSettings { + Self { positive_high: 0.95, positive_low: 0.05, negative_high: -0.95, @@ -215,7 +215,7 @@ pub struct ButtonAxisSettings { impl Default for ButtonAxisSettings { fn default() -> Self { - ButtonAxisSettings { + Self { high: 0.95, low: 0.05, threshold: 0.01, diff --git a/crates/bevy_input/src/lib.rs b/crates/bevy_input/src/lib.rs index a9dbc2d3301d3..ec8a4ebdb0382 100644 --- a/crates/bevy_input/src/lib.rs +++ b/crates/bevy_input/src/lib.rs @@ -96,7 +96,7 @@ pub enum ElementState { } impl ElementState { - pub fn is_pressed(&self) -> bool { + pub const fn is_pressed(&self) -> bool { matches!(self, ElementState::Pressed) } } diff --git a/crates/bevy_input/src/touch.rs b/crates/bevy_input/src/touch.rs index 44fb2329392e5..0409a948b8891 100644 --- a/crates/bevy_input/src/touch.rs +++ b/crates/bevy_input/src/touch.rs @@ -98,39 +98,39 @@ impl Touch { } #[inline] - pub fn id(&self) -> u64 { + pub const fn id(&self) -> u64 { self.id } #[inline] - pub fn start_position(&self) -> Vec2 { + pub const fn start_position(&self) -> Vec2 { self.start_position } #[inline] - pub fn start_force(&self) -> Option { + pub const fn start_force(&self) -> Option { self.start_force } #[inline] - pub fn previous_position(&self) -> Vec2 { + pub const fn previous_position(&self) -> Vec2 { self.previous_position } #[inline] - pub fn position(&self) -> Vec2 { + pub const fn position(&self) -> Vec2 { self.position } #[inline] - pub fn force(&self) -> Option { + pub const fn force(&self) -> Option { self.force } } impl From<&TouchInput> for Touch { - fn from(input: &TouchInput) -> Touch { - Touch { + fn from(input: &TouchInput) -> Self { + Self { id: input.id, start_position: input.position, start_force: input.force, diff --git a/crates/bevy_log/src/lib.rs b/crates/bevy_log/src/lib.rs index 184b1214849dd..df6910a6d37b6 100644 --- a/crates/bevy_log/src/lib.rs +++ b/crates/bevy_log/src/lib.rs @@ -102,15 +102,19 @@ impl Plugin for LogPlugin { let (chrome_layer, guard) = tracing_chrome::ChromeLayerBuilder::new() .name_fn(Box::new(|event_or_span| match event_or_span { tracing_chrome::EventOrSpan::Event(event) => event.metadata().name().into(), - tracing_chrome::EventOrSpan::Span(span) => { - if let Some(fields) = - span.extensions().get::>() - { - format!("{}: {}", span.metadata().name(), fields.fields.as_str()) - } else { - span.metadata().name().into() - } - } + tracing_chrome::EventOrSpan::Span(span) => span + .extensions() + .get::>() + .map_or_else( + || span.metadata().name().into(), + |fields| { + format!( + "{}: {}", + span.metadata().name(), + fields.fields.as_str() + ) + }, + ), })) .build(); app.world.insert_non_send(guard); diff --git a/crates/bevy_math/src/face_toward.rs b/crates/bevy_math/src/face_toward.rs index f873964b18afc..a4f8d698c4ab0 100644 --- a/crates/bevy_math/src/face_toward.rs +++ b/crates/bevy_math/src/face_toward.rs @@ -11,7 +11,7 @@ impl FaceToward for Mat4 { let forward = (eye - center).normalize(); let right = up.cross(forward).normalize(); let up = forward.cross(right); - Mat4::from_cols( + Self::from_cols( right.extend(0.0), up.extend(0.0), forward.extend(0.0), diff --git a/crates/bevy_math/src/geometry.rs b/crates/bevy_math/src/geometry.rs index 0a449e5d026f9..e474c55d2ef5f 100644 --- a/crates/bevy_math/src/geometry.rs +++ b/crates/bevy_math/src/geometry.rs @@ -12,7 +12,7 @@ pub struct Size { impl Size { pub fn new(width: T, height: T) -> Self { - Size { width, height } + Self { width, height } } } @@ -40,7 +40,7 @@ impl Rect { where T: Clone, { - Rect { + Self { left: value.clone(), right: value.clone(), top: value.clone(), @@ -64,7 +64,7 @@ impl Add for Size where T: Add, { - type Output = Size; + type Output = Self; fn add(self, rhs: Vec2) -> Self::Output { Self { @@ -88,7 +88,7 @@ impl Sub for Size where T: Sub, { - type Output = Size; + type Output = Self; fn sub(self, rhs: Vec2) -> Self::Output { Self { @@ -112,7 +112,7 @@ impl Mul for Size where T: Mul, { - type Output = Size; + type Output = Self; fn mul(self, rhs: f32) -> Self::Output { Self::Output { @@ -136,7 +136,7 @@ impl Div for Size where T: Div, { - type Output = Size; + type Output = Self; fn div(self, rhs: f32) -> Self::Output { Self::Output { diff --git a/crates/bevy_pbr/src/alpha.rs b/crates/bevy_pbr/src/alpha.rs index 9af73fc764011..1607df1303a26 100644 --- a/crates/bevy_pbr/src/alpha.rs +++ b/crates/bevy_pbr/src/alpha.rs @@ -17,6 +17,6 @@ impl Eq for AlphaMode {} impl Default for AlphaMode { fn default() -> Self { - AlphaMode::Opaque + Self::Opaque } } diff --git a/crates/bevy_pbr/src/bundle.rs b/crates/bevy_pbr/src/bundle.rs index ba235c56b5791..a520a411bff54 100644 --- a/crates/bevy_pbr/src/bundle.rs +++ b/crates/bevy_pbr/src/bundle.rs @@ -46,7 +46,7 @@ pub struct CubemapVisibleEntities { } impl CubemapVisibleEntities { - pub fn get(&self, i: usize) -> &VisibleEntities { + pub const fn get(&self, i: usize) -> &VisibleEntities { &self.data[i] } diff --git a/crates/bevy_pbr/src/light.rs b/crates/bevy_pbr/src/light.rs index a0380e1d6aeab..329bfc53c72fa 100644 --- a/crates/bevy_pbr/src/light.rs +++ b/crates/bevy_pbr/src/light.rs @@ -51,7 +51,7 @@ pub struct PointLight { impl Default for PointLight { fn default() -> Self { - PointLight { + Self { color: Color::rgb(1.0, 1.0, 1.0), /// Luminous power in lumens intensity: 800.0, // Roughly a 60W non-halogen incandescent bulb @@ -123,7 +123,7 @@ pub struct DirectionalLight { impl Default for DirectionalLight { fn default() -> Self { let size = 100.0; - DirectionalLight { + Self { color: Color::rgb(1.0, 1.0, 1.0), illuminance: 100000.0, shadows_enabled: false, @@ -240,7 +240,7 @@ impl Clusters { (aspect_ratio * n_tiles_y).floor() as u32, n_tiles_y.floor() as u32, ); - Clusters::new((screen_size + UVec2::ONE) / n_tiles, screen_size, Z_SLICES) + Self::new((screen_size + UVec2::ONE) / n_tiles, screen_size, Z_SLICES) } fn update(&mut self, tile_size: UVec2, screen_size: UVec2, z_slices: u32) { @@ -295,9 +295,7 @@ fn compute_aabb_for_cluster( let p_min = ijk.xy() * tile_size; let p_max = p_min + tile_size; - let cluster_min; - let cluster_max; - if is_orthographic { + let (cluster_min, cluster_max) = if is_orthographic { // Use linear depth slicing for orthographic // Convert to view space at the cluster near and far planes @@ -317,8 +315,7 @@ fn compute_aabb_for_cluster( ) .xyz(); - cluster_min = p_min.min(p_max); - cluster_max = p_min.max(p_max); + (p_min.min(p_max), p_min.max(p_max)) } else { // Convert to view space at the near plane // NOTE: 1.0 is the near plane due to using reverse z projections @@ -342,9 +339,11 @@ fn compute_aabb_for_cluster( let p_max_near = line_intersection_to_z_plane(Vec3::ZERO, p_max.xyz(), cluster_near); let p_max_far = line_intersection_to_z_plane(Vec3::ZERO, p_max.xyz(), cluster_far); - cluster_min = p_min_near.min(p_min_far).min(p_max_near.min(p_max_far)); - cluster_max = p_min_near.max(p_min_far).max(p_max_near.max(p_max_far)); - } + ( + p_min_near.min(p_min_far).min(p_max_near.min(p_max_far)), + p_min_near.max(p_min_far).max(p_max_near.max(p_max_far)), + ) + }; Aabb::from_min_max(cluster_min, cluster_max) } diff --git a/crates/bevy_pbr/src/material.rs b/crates/bevy_pbr/src/material.rs index d1c521397511e..393bae0692d84 100644 --- a/crates/bevy_pbr/src/material.rs +++ b/crates/bevy_pbr/src/material.rs @@ -231,7 +231,7 @@ impl FromWorld for MaterialPipeline { let render_device = world.get_resource::().unwrap(); let material_layout = M::bind_group_layout(render_device); - MaterialPipeline { + Self { mesh_pipeline: world.get_resource::().unwrap().clone(), material_layout, vertex_shader: M::vertex_shader(asset_server), @@ -323,7 +323,7 @@ pub fn queue_material_meshes( MeshPipelineKey::from_primitive_topology(mesh.primitive_topology); } let alpha_mode = M::alpha_mode(material); - if let AlphaMode::Blend = alpha_mode { + if alpha_mode == AlphaMode::Blend { mesh_key |= MeshPipelineKey::TRANSPARENT_MAIN_PASS } diff --git a/crates/bevy_pbr/src/pbr_material.rs b/crates/bevy_pbr/src/pbr_material.rs index 26ed132faf25f..02cf3180bdb5c 100644 --- a/crates/bevy_pbr/src/pbr_material.rs +++ b/crates/bevy_pbr/src/pbr_material.rs @@ -54,7 +54,7 @@ pub struct StandardMaterial { impl Default for StandardMaterial { fn default() -> Self { - StandardMaterial { + Self { base_color: Color::rgb(1.0, 1.0, 1.0), base_color_texture: None, emissive: Color::BLACK, @@ -84,7 +84,7 @@ impl Default for StandardMaterial { impl From for StandardMaterial { fn from(color: Color) -> Self { - StandardMaterial { + Self { base_color: color, ..Default::default() } @@ -93,7 +93,7 @@ impl From for StandardMaterial { impl From> for StandardMaterial { fn from(texture: Handle) -> Self { - StandardMaterial { + Self { base_color_texture: Some(texture), ..Default::default() } @@ -156,11 +156,11 @@ pub struct GpuStandardMaterial { } impl RenderAsset for StandardMaterial { - type ExtractedAsset = StandardMaterial; + type ExtractedAsset = Self; type PreparedAsset = GpuStandardMaterial; type Param = ( SRes, - SRes>, + SRes>, SRes>, ); diff --git a/crates/bevy_pbr/src/render/light.rs b/crates/bevy_pbr/src/render/light.rs index d939be0b593b1..851e1688233b3 100644 --- a/crates/bevy_pbr/src/render/light.rs +++ b/crates/bevy_pbr/src/render/light.rs @@ -184,7 +184,7 @@ impl FromWorld for ShadowPipeline { let mesh_pipeline = world.get_resource::().unwrap(); - ShadowPipeline { + Self { view_layout, mesh_layout: mesh_pipeline.mesh_layout.clone(), point_light_sampler: render_device.create_sampler(&SamplerDescriptor { @@ -216,7 +216,7 @@ bitflags::bitflags! { pub struct ShadowPipelineKey: u32 { const NONE = 0; const VERTEX_TANGENTS = (1 << 0); - const PRIMITIVE_TOPOLOGY_RESERVED_BITS = ShadowPipelineKey::PRIMITIVE_TOPOLOGY_MASK_BITS << ShadowPipelineKey::PRIMITIVE_TOPOLOGY_SHIFT_BITS; + const PRIMITIVE_TOPOLOGY_RESERVED_BITS = Self::PRIMITIVE_TOPOLOGY_MASK_BITS << Self::PRIMITIVE_TOPOLOGY_SHIFT_BITS; } } @@ -515,7 +515,7 @@ pub(crate) const CUBE_MAP_FACES: [CubeMapFace; 6] = [ }, ]; -fn face_index_to_name(face_index: usize) -> &'static str { +const fn face_index_to_name(face_index: usize) -> &'static str { match face_index { 0 => "+x", 1 => "-x", @@ -946,7 +946,7 @@ const POINT_LIGHT_INDEX_MASK: u32 = (1 << 8) - 1; // and the count into the lower 8 bits. // NOTE: This assumes CPU and GPU endianness are the same which is true // for all common and tested x86/ARM CPUs and AMD/NVIDIA/Intel/Apple/etc GPUs -fn pack_offset_and_count(offset: usize, count: usize) -> u32 { +const fn pack_offset_and_count(offset: usize, count: usize) -> u32 { ((offset as u32 & CLUSTER_OFFSET_MASK) << CLUSTER_COUNT_SIZE) | (count as u32 & CLUSTER_COUNT_MASK) } @@ -989,7 +989,7 @@ impl ViewClusterBindings { self.n_offsets += 1; } - pub fn n_indices(&self) -> usize { + pub const fn n_indices(&self) -> usize { self.n_indices } @@ -1197,7 +1197,7 @@ impl ShadowPassNode { impl Node for ShadowPassNode { fn input(&self) -> Vec { - vec![SlotInfo::new(ShadowPassNode::IN_VIEW, SlotType::Entity)] + vec![SlotInfo::new(Self::IN_VIEW, SlotType::Entity)] } fn update(&mut self, world: &mut World) { diff --git a/crates/bevy_pbr/src/render/mesh.rs b/crates/bevy_pbr/src/render/mesh.rs index 3e8965aa28ee1..e8ca0018e2e59 100644 --- a/crates/bevy_pbr/src/render/mesh.rs +++ b/crates/bevy_pbr/src/render/mesh.rs @@ -336,7 +336,7 @@ impl FromWorld for MeshPipeline { ), } }; - MeshPipeline { + Self { view_layout, mesh_layout, dummy_white_gpu_image, @@ -370,8 +370,8 @@ bitflags::bitflags! { const NONE = 0; const VERTEX_TANGENTS = (1 << 0); const TRANSPARENT_MAIN_PASS = (1 << 1); - const MSAA_RESERVED_BITS = MeshPipelineKey::MSAA_MASK_BITS << MeshPipelineKey::MSAA_SHIFT_BITS; - const PRIMITIVE_TOPOLOGY_RESERVED_BITS = MeshPipelineKey::PRIMITIVE_TOPOLOGY_MASK_BITS << MeshPipelineKey::PRIMITIVE_TOPOLOGY_SHIFT_BITS; + const MSAA_RESERVED_BITS = Self::MSAA_MASK_BITS << Self::MSAA_SHIFT_BITS; + const PRIMITIVE_TOPOLOGY_RESERVED_BITS = Self::PRIMITIVE_TOPOLOGY_MASK_BITS << Self::PRIMITIVE_TOPOLOGY_SHIFT_BITS; } } @@ -383,10 +383,10 @@ impl MeshPipelineKey { pub fn from_msaa_samples(msaa_samples: u32) -> Self { let msaa_bits = ((msaa_samples - 1) & Self::MSAA_MASK_BITS) << Self::MSAA_SHIFT_BITS; - MeshPipelineKey::from_bits(msaa_bits).unwrap() + Self::from_bits(msaa_bits).unwrap() } - pub fn msaa_samples(&self) -> u32 { + pub const fn msaa_samples(&self) -> u32 { ((self.bits >> Self::MSAA_SHIFT_BITS) & Self::MSAA_MASK_BITS) + 1 } @@ -394,7 +394,7 @@ impl MeshPipelineKey { let primitive_topology_bits = ((primitive_topology as u32) & Self::PRIMITIVE_TOPOLOGY_MASK_BITS) << Self::PRIMITIVE_TOPOLOGY_SHIFT_BITS; - MeshPipelineKey::from_bits(primitive_topology_bits).unwrap() + Self::from_bits(primitive_topology_bits).unwrap() } pub fn primitive_topology(&self) -> PrimitiveTopology { @@ -719,25 +719,26 @@ impl EntityRenderCommand for DrawMesh { pass: &mut TrackedRenderPass<'w>, ) -> RenderCommandResult { let mesh_handle = mesh_query.get(item).unwrap(); - if let Some(gpu_mesh) = meshes.into_inner().get(mesh_handle) { - pass.set_vertex_buffer(0, gpu_mesh.vertex_buffer.slice(..)); - match &gpu_mesh.buffer_info { - GpuBufferInfo::Indexed { - buffer, - index_format, - count, - } => { - pass.set_index_buffer(buffer.slice(..), 0, *index_format); - pass.draw_indexed(0..*count, 0, 0..1); + meshes + .into_inner() + .get(mesh_handle) + .map_or(RenderCommandResult::Failure, |gpu_mesh| { + pass.set_vertex_buffer(0, gpu_mesh.vertex_buffer.slice(..)); + match &gpu_mesh.buffer_info { + GpuBufferInfo::Indexed { + buffer, + index_format, + count, + } => { + pass.set_index_buffer(buffer.slice(..), 0, *index_format); + pass.draw_indexed(0..*count, 0, 0..1); + } + GpuBufferInfo::NonIndexed { vertex_count } => { + pass.draw(0..*vertex_count, 0..1); + } } - GpuBufferInfo::NonIndexed { vertex_count } => { - pass.draw(0..*vertex_count, 0..1); - } - } - RenderCommandResult::Success - } else { - RenderCommandResult::Failure - } + RenderCommandResult::Success + }) } } diff --git a/crates/bevy_pbr/src/wireframe.rs b/crates/bevy_pbr/src/wireframe.rs index 9f1308179e518..cca4a0e014558 100644 --- a/crates/bevy_pbr/src/wireframe.rs +++ b/crates/bevy_pbr/src/wireframe.rs @@ -72,7 +72,7 @@ pub struct WireframePipeline { } impl FromWorld for WireframePipeline { fn from_world(render_world: &mut World) -> Self { - WireframePipeline { + Self { mesh_pipeline: render_world.get_resource::().unwrap().clone(), shader: WIREFRAME_SHADER_HANDLE.typed(), } diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index 55201bff9116e..1cd4feb79b9e1 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -534,14 +534,15 @@ impl Parse for ReflectDef { lookahead = input.lookahead1(); } - let mut attrs = None; - if lookahead.peek(Paren) { + let attrs = if lookahead.peek(Paren) { let content; parenthesized!(content in input); - attrs = Some(content.parse::()?); - } + Some(content.parse::()?) + } else { + None + }; - Ok(ReflectDef { + Ok(Self { type_name: type_ident, generics: Generics { where_clause, @@ -585,7 +586,7 @@ struct ReflectAttrs { impl ReflectAttrs { fn from_nested_metas(nested_metas: &Punctuated) -> Self { - let mut attrs = ReflectAttrs::default(); + let mut attrs = Self::default(); for nested_meta in nested_metas.iter() { match nested_meta { NestedMeta::Lit(_) => {} @@ -703,7 +704,7 @@ impl ReflectAttrs { impl Parse for ReflectAttrs { fn parse(input: ParseStream) -> syn::Result { let result = Punctuated::::parse_terminated(input)?; - Ok(ReflectAttrs::from_nested_metas(&result)) + Ok(Self::from_nested_metas(&result)) } } diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/reflect_trait.rs b/crates/bevy_reflect/bevy_reflect_derive/src/reflect_trait.rs index 64b0aea378368..a5b9b04b05201 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/reflect_trait.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/reflect_trait.rs @@ -15,7 +15,7 @@ impl Parse for TraitInfo { if lookahead.peek(Token![pub]) || lookahead.peek(Token![trait]) { let mut item_trait: ItemTrait = input.parse()?; item_trait.attrs = attrs; - Ok(TraitInfo { item_trait }) + Ok(Self { item_trait }) } else { Err(lookahead.error()) } diff --git a/crates/bevy_reflect/src/impls/smallvec.rs b/crates/bevy_reflect/src/impls/smallvec.rs index 4d6417c6df068..be6a676661d8e 100644 --- a/crates/bevy_reflect/src/impls/smallvec.rs +++ b/crates/bevy_reflect/src/impls/smallvec.rs @@ -8,7 +8,7 @@ where T::Item: FromReflect + Clone, { fn get(&self, index: usize) -> Option<&dyn Reflect> { - if index < SmallVec::len(self) { + if index < Self::len(self) { Some(&self[index] as &dyn Reflect) } else { None @@ -16,7 +16,7 @@ where } fn get_mut(&mut self, index: usize) -> Option<&mut dyn Reflect> { - if index < SmallVec::len(self) { + if index < Self::len(self) { Some(&mut self[index] as &mut dyn Reflect) } else { None @@ -24,7 +24,7 @@ where } fn len(&self) -> usize { - >::len(self) + self.len() } fn push(&mut self, value: Box) { @@ -36,7 +36,7 @@ where ) }) }); - SmallVec::push(self, value); + self.push(value); } fn iter(&self) -> ListIter { diff --git a/crates/bevy_reflect/src/impls/std.rs b/crates/bevy_reflect/src/impls/std.rs index 801ce2c0329b6..de816eb1c0ddb 100644 --- a/crates/bevy_reflect/src/impls/std.rs +++ b/crates/bevy_reflect/src/impls/std.rs @@ -92,7 +92,7 @@ impl List for Vec { ) }) }); - Vec::push(self, value); + self.push(value); } } @@ -146,8 +146,8 @@ unsafe impl Reflect for Vec { impl Deserialize<'de>> GetTypeRegistration for Vec { fn get_type_registration() -> TypeRegistration { - let mut registration = TypeRegistration::of::>(); - registration.insert::(FromType::>::from_type()); + let mut registration = TypeRegistration::of::(); + registration.insert::(FromType::::from_type()); registration } } @@ -169,13 +169,13 @@ impl FromReflect for Vec { impl Map for HashMap { fn get(&self, key: &dyn Reflect) -> Option<&dyn Reflect> { key.downcast_ref::() - .and_then(|key| HashMap::get(self, key)) + .and_then(|key| self.get(key)) .map(|value| value as &dyn Reflect) } fn get_mut(&mut self, key: &dyn Reflect) -> Option<&mut dyn Reflect> { key.downcast_ref::() - .and_then(move |key| HashMap::get_mut(self, key)) + .and_then(move |key| self.get_mut(key)) .map(|value| value as &mut dyn Reflect) } @@ -186,7 +186,7 @@ impl Map for HashMap { } fn len(&self) -> usize { - HashMap::len(self) + self.len() } fn iter(&self) -> MapIter { @@ -199,7 +199,7 @@ impl Map for HashMap { fn clone_dynamic(&self) -> DynamicMap { let mut dynamic_map = DynamicMap::default(); dynamic_map.set_name(self.type_name().to_string()); - for (k, v) in HashMap::iter(self) { + for (k, v) in self.iter() { dynamic_map.insert_boxed(k.clone_value(), v.clone_value()); } dynamic_map @@ -268,8 +268,8 @@ where V: Reflect + Clone + for<'de> Deserialize<'de>, { fn get_type_registration() -> TypeRegistration { - let mut registration = TypeRegistration::of::>(); - registration.insert::(FromType::>::from_type()); + let mut registration = TypeRegistration::of::(); + registration.insert::(FromType::::from_type()); registration } } @@ -339,11 +339,11 @@ unsafe impl Reflect for Cow<'static, str> { fn reflect_partial_eq(&self, value: &dyn Reflect) -> Option { let value = value.any(); - if let Some(value) = value.downcast_ref::() { - Some(std::cmp::PartialEq::eq(self, value)) - } else { - Some(false) - } + Some( + value + .downcast_ref::() + .map_or(false, |value| std::cmp::PartialEq::eq(self, value)), + ) } fn serializable(&self) -> Option { diff --git a/crates/bevy_reflect/src/list.rs b/crates/bevy_reflect/src/list.rs index d9572cd1b42db..6752b9d43861e 100644 --- a/crates/bevy_reflect/src/list.rs +++ b/crates/bevy_reflect/src/list.rs @@ -81,8 +81,8 @@ impl List for DynamicList { self.values.len() } - fn clone_dynamic(&self) -> DynamicList { - DynamicList { + fn clone_dynamic(&self) -> Self { + Self { name: self.name.clone(), values: self .values @@ -100,7 +100,7 @@ impl List for DynamicList { } fn push(&mut self, value: Box) { - DynamicList::push_box(self, value); + Self::push_box(self, value); } } diff --git a/crates/bevy_reflect/src/map.rs b/crates/bevy_reflect/src/map.rs index f2ad17d6671c1..942fc33277e84 100644 --- a/crates/bevy_reflect/src/map.rs +++ b/crates/bevy_reflect/src/map.rs @@ -107,8 +107,8 @@ impl Map for DynamicMap { self.values.len() } - fn clone_dynamic(&self) -> DynamicMap { - DynamicMap { + fn clone_dynamic(&self) -> Self { + Self { name: self.name.clone(), values: self .values diff --git a/crates/bevy_reflect/src/serde/de.rs b/crates/bevy_reflect/src/serde/de.rs index 216b25e106f40..0cc95c1f9ef00 100644 --- a/crates/bevy_reflect/src/serde/de.rs +++ b/crates/bevy_reflect/src/serde/de.rs @@ -17,7 +17,7 @@ pub struct ReflectDeserializer<'a> { } impl<'a> ReflectDeserializer<'a> { - pub fn new(registry: &'a TypeRegistry) -> Self { + pub const fn new(registry: &'a TypeRegistry) -> Self { ReflectDeserializer { registry } } } diff --git a/crates/bevy_reflect/src/struct_trait.rs b/crates/bevy_reflect/src/struct_trait.rs index 40d3ed3d1995b..7771cb25702de 100644 --- a/crates/bevy_reflect/src/struct_trait.rs +++ b/crates/bevy_reflect/src/struct_trait.rs @@ -238,8 +238,8 @@ impl Struct for DynamicStruct { } } - fn clone_dynamic(&self) -> DynamicStruct { - DynamicStruct { + fn clone_dynamic(&self) -> Self { + Self { name: self.name.clone(), field_names: self.field_names.clone(), field_indices: self.field_indices.clone(), diff --git a/crates/bevy_reflect/src/tuple.rs b/crates/bevy_reflect/src/tuple.rs index 44423c3099cfb..3c036d26b44db 100644 --- a/crates/bevy_reflect/src/tuple.rs +++ b/crates/bevy_reflect/src/tuple.rs @@ -193,8 +193,8 @@ impl Tuple for DynamicTuple { } #[inline] - fn clone_dynamic(&self) -> DynamicTuple { - DynamicTuple { + fn clone_dynamic(&self) -> Self { + Self { name: self.name.clone(), fields: self .fields diff --git a/crates/bevy_reflect/src/tuple_struct.rs b/crates/bevy_reflect/src/tuple_struct.rs index dd053932cadbb..432194658e487 100644 --- a/crates/bevy_reflect/src/tuple_struct.rs +++ b/crates/bevy_reflect/src/tuple_struct.rs @@ -180,8 +180,8 @@ impl TupleStruct for DynamicTupleStruct { } } - fn clone_dynamic(&self) -> DynamicTupleStruct { - DynamicTupleStruct { + fn clone_dynamic(&self) -> Self { + Self { name: self.name.clone(), fields: self .fields diff --git a/crates/bevy_reflect/src/type_registry.rs b/crates/bevy_reflect/src/type_registry.rs index d0ae8c412bc76..7ac4c78148ec7 100644 --- a/crates/bevy_reflect/src/type_registry.rs +++ b/crates/bevy_reflect/src/type_registry.rs @@ -174,7 +174,7 @@ impl TypeRegistration { /// /// [`TypeId`]: std::any::TypeId #[inline] - pub fn type_id(&self) -> TypeId { + pub const fn type_id(&self) -> TypeId { self.type_id } @@ -225,7 +225,7 @@ impl TypeRegistration { } /// Returns the name of the type. - pub fn name(&self) -> &'static str { + pub const fn name(&self) -> &'static str { self.name } @@ -280,7 +280,7 @@ impl Clone for TypeRegistration { data.insert(*id, (*type_data).clone_type_data()); } - TypeRegistration { + Self { data, name: self.name, short_name: self.short_name.clone(), @@ -344,7 +344,7 @@ impl ReflectDeserialize { impl Deserialize<'a> + Reflect> FromType for ReflectDeserialize { fn from_type() -> Self { - ReflectDeserialize { + Self { func: |deserializer| Ok(Box::new(T::deserialize(deserializer)?)), } } diff --git a/crates/bevy_render/src/camera/bundle.rs b/crates/bevy_render/src/camera/bundle.rs index 920a12bb35335..e8e8d2f1062c5 100644 --- a/crates/bevy_render/src/camera/bundle.rs +++ b/crates/bevy_render/src/camera/bundle.rs @@ -39,7 +39,7 @@ impl PerspectiveCameraBundle { &Vec3::Z, perspective_projection.far(), ); - PerspectiveCameraBundle { + Self { camera: Camera { name: Some(name.to_string()), near: perspective_projection.near, @@ -57,7 +57,7 @@ impl PerspectiveCameraBundle { impl Default for PerspectiveCameraBundle { fn default() -> Self { - PerspectiveCameraBundle::with_name(CameraPlugin::CAMERA_3D) + Self::with_name(CameraPlugin::CAMERA_3D) } } @@ -110,7 +110,7 @@ impl OrthographicCameraBundle { &transform.back(), orthographic_projection.far(), ); - OrthographicCameraBundle { + Self { camera: Camera { name: Some(CameraPlugin::CAMERA_2D.to_string()), near: orthographic_projection.near, @@ -138,7 +138,7 @@ impl OrthographicCameraBundle { &Vec3::Z, orthographic_projection.far(), ); - OrthographicCameraBundle { + Self { camera: Camera { name: Some(CameraPlugin::CAMERA_3D.to_string()), near: orthographic_projection.near, @@ -162,7 +162,7 @@ impl OrthographicCameraBundle { &Vec3::Z, orthographic_projection.far(), ); - OrthographicCameraBundle { + Self { camera: Camera { name: Some(name.to_string()), near: orthographic_projection.near, diff --git a/crates/bevy_render/src/camera/camera.rs b/crates/bevy_render/src/camera/camera.rs index 4f73ebaf90230..824f5cfa2f873 100644 --- a/crates/bevy_render/src/camera/camera.rs +++ b/crates/bevy_render/src/camera/camera.rs @@ -38,7 +38,7 @@ pub enum DepthCalculation { impl Default for DepthCalculation { fn default() -> Self { - DepthCalculation::Distance + Self::Distance } } diff --git a/crates/bevy_render/src/camera/projection.rs b/crates/bevy_render/src/camera/projection.rs index b0ea170c75f6e..33eb187ca09d6 100644 --- a/crates/bevy_render/src/camera/projection.rs +++ b/crates/bevy_render/src/camera/projection.rs @@ -40,7 +40,7 @@ impl CameraProjection for PerspectiveProjection { impl Default for PerspectiveProjection { fn default() -> Self { - PerspectiveProjection { + Self { fov: std::f32::consts::PI / 4.0, near: 0.1, far: 1000.0, @@ -159,7 +159,7 @@ impl CameraProjection for OrthographicProjection { impl Default for OrthographicProjection { fn default() -> Self { - OrthographicProjection { + Self { left: -1.0, right: 1.0, bottom: -1.0, diff --git a/crates/bevy_render/src/color/colorspace.rs b/crates/bevy_render/src/color/colorspace.rs index 43d3f7986f3c8..1b586d90aaf57 100644 --- a/crates/bevy_render/src/color/colorspace.rs +++ b/crates/bevy_render/src/color/colorspace.rs @@ -6,7 +6,7 @@ pub trait SrgbColorSpace { // source: https://entropymine.com/imageworsener/srgbformula/ impl SrgbColorSpace for f32 { #[inline] - fn linear_to_nonlinear_srgb(self) -> f32 { + fn linear_to_nonlinear_srgb(self) -> Self { if self <= 0.0 { return self; } @@ -19,7 +19,7 @@ impl SrgbColorSpace for f32 { } #[inline] - fn nonlinear_to_linear_srgb(self) -> f32 { + fn nonlinear_to_linear_srgb(self) -> Self { if self <= 0.0 { return self; } diff --git a/crates/bevy_render/src/color/mod.rs b/crates/bevy_render/src/color/mod.rs index 14cb8e8dba1b4..caa83cd2feaea 100644 --- a/crates/bevy_render/src/color/mod.rs +++ b/crates/bevy_render/src/color/mod.rs @@ -47,48 +47,48 @@ pub enum Color { } impl Color { - pub const ALICE_BLUE: Color = Color::rgb(0.94, 0.97, 1.0); - pub const ANTIQUE_WHITE: Color = Color::rgb(0.98, 0.92, 0.84); - pub const AQUAMARINE: Color = Color::rgb(0.49, 1.0, 0.83); - pub const AZURE: Color = Color::rgb(0.94, 1.0, 1.0); - pub const BEIGE: Color = Color::rgb(0.96, 0.96, 0.86); - pub const BISQUE: Color = Color::rgb(1.0, 0.89, 0.77); - pub const BLACK: Color = Color::rgb(0.0, 0.0, 0.0); - pub const BLUE: Color = Color::rgb(0.0, 0.0, 1.0); - pub const CRIMSON: Color = Color::rgb(0.86, 0.08, 0.24); - pub const CYAN: Color = Color::rgb(0.0, 1.0, 1.0); - pub const DARK_GRAY: Color = Color::rgb(0.25, 0.25, 0.25); - pub const DARK_GREEN: Color = Color::rgb(0.0, 0.5, 0.0); - pub const FUCHSIA: Color = Color::rgb(1.0, 0.0, 1.0); - pub const GOLD: Color = Color::rgb(1.0, 0.84, 0.0); - pub const GRAY: Color = Color::rgb(0.5, 0.5, 0.5); - pub const GREEN: Color = Color::rgb(0.0, 1.0, 0.0); - pub const INDIGO: Color = Color::rgb(0.29, 0.0, 0.51); - pub const LIME_GREEN: Color = Color::rgb(0.2, 0.8, 0.2); - pub const MAROON: Color = Color::rgb(0.5, 0.0, 0.0); - pub const MIDNIGHT_BLUE: Color = Color::rgb(0.1, 0.1, 0.44); - pub const NAVY: Color = Color::rgb(0.0, 0.0, 0.5); - pub const NONE: Color = Color::rgba(0.0, 0.0, 0.0, 0.0); - pub const OLIVE: Color = Color::rgb(0.5, 0.5, 0.0); - pub const ORANGE: Color = Color::rgb(1.0, 0.65, 0.0); - pub const ORANGE_RED: Color = Color::rgb(1.0, 0.27, 0.0); - pub const PINK: Color = Color::rgb(1.0, 0.08, 0.58); - pub const PURPLE: Color = Color::rgb(0.5, 0.0, 0.5); - pub const RED: Color = Color::rgb(1.0, 0.0, 0.0); - pub const SALMON: Color = Color::rgb(0.98, 0.5, 0.45); - pub const SEA_GREEN: Color = Color::rgb(0.18, 0.55, 0.34); - pub const SILVER: Color = Color::rgb(0.75, 0.75, 0.75); - pub const TEAL: Color = Color::rgb(0.0, 0.5, 0.5); - pub const TOMATO: Color = Color::rgb(1.0, 0.39, 0.28); - pub const TURQUOISE: Color = Color::rgb(0.25, 0.88, 0.82); - pub const VIOLET: Color = Color::rgb(0.93, 0.51, 0.93); - pub const WHITE: Color = Color::rgb(1.0, 1.0, 1.0); - pub const YELLOW: Color = Color::rgb(1.0, 1.0, 0.0); - pub const YELLOW_GREEN: Color = Color::rgb(0.6, 0.8, 0.2); + pub const ALICE_BLUE: Self = Self::rgb(0.94, 0.97, 1.0); + pub const ANTIQUE_WHITE: Self = Self::rgb(0.98, 0.92, 0.84); + pub const AQUAMARINE: Self = Self::rgb(0.49, 1.0, 0.83); + pub const AZURE: Self = Self::rgb(0.94, 1.0, 1.0); + pub const BEIGE: Self = Self::rgb(0.96, 0.96, 0.86); + pub const BISQUE: Self = Self::rgb(1.0, 0.89, 0.77); + pub const BLACK: Self = Self::rgb(0.0, 0.0, 0.0); + pub const BLUE: Self = Self::rgb(0.0, 0.0, 1.0); + pub const CRIMSON: Self = Self::rgb(0.86, 0.08, 0.24); + pub const CYAN: Self = Self::rgb(0.0, 1.0, 1.0); + pub const DARK_GRAY: Self = Self::rgb(0.25, 0.25, 0.25); + pub const DARK_GREEN: Self = Self::rgb(0.0, 0.5, 0.0); + pub const FUCHSIA: Self = Self::rgb(1.0, 0.0, 1.0); + pub const GOLD: Self = Self::rgb(1.0, 0.84, 0.0); + pub const GRAY: Self = Self::rgb(0.5, 0.5, 0.5); + pub const GREEN: Self = Self::rgb(0.0, 1.0, 0.0); + pub const INDIGO: Self = Self::rgb(0.29, 0.0, 0.51); + pub const LIME_GREEN: Self = Self::rgb(0.2, 0.8, 0.2); + pub const MAROON: Self = Self::rgb(0.5, 0.0, 0.0); + pub const MIDNIGHT_BLUE: Self = Self::rgb(0.1, 0.1, 0.44); + pub const NAVY: Self = Self::rgb(0.0, 0.0, 0.5); + pub const NONE: Self = Self::rgba(0.0, 0.0, 0.0, 0.0); + pub const OLIVE: Self = Self::rgb(0.5, 0.5, 0.0); + pub const ORANGE: Self = Self::rgb(1.0, 0.65, 0.0); + pub const ORANGE_RED: Self = Self::rgb(1.0, 0.27, 0.0); + pub const PINK: Self = Self::rgb(1.0, 0.08, 0.58); + pub const PURPLE: Self = Self::rgb(0.5, 0.0, 0.5); + pub const RED: Self = Self::rgb(1.0, 0.0, 0.0); + pub const SALMON: Self = Self::rgb(0.98, 0.5, 0.45); + pub const SEA_GREEN: Self = Self::rgb(0.18, 0.55, 0.34); + pub const SILVER: Self = Self::rgb(0.75, 0.75, 0.75); + pub const TEAL: Self = Self::rgb(0.0, 0.5, 0.5); + pub const TOMATO: Self = Self::rgb(1.0, 0.39, 0.28); + pub const TURQUOISE: Self = Self::rgb(0.25, 0.88, 0.82); + pub const VIOLET: Self = Self::rgb(0.93, 0.51, 0.93); + pub const WHITE: Self = Self::rgb(1.0, 1.0, 1.0); + pub const YELLOW: Self = Self::rgb(1.0, 1.0, 0.0); + pub const YELLOW_GREEN: Self = Self::rgb(0.6, 0.8, 0.2); /// New `Color` from sRGB colorspace. - pub const fn rgb(r: f32, g: f32, b: f32) -> Color { - Color::Rgba { + pub const fn rgb(r: f32, g: f32, b: f32) -> Self { + Self::Rgba { red: r, green: g, blue: b, @@ -97,8 +97,8 @@ impl Color { } /// New `Color` from sRGB colorspace. - pub const fn rgba(r: f32, g: f32, b: f32, a: f32) -> Color { - Color::Rgba { + pub const fn rgba(r: f32, g: f32, b: f32, a: f32) -> Self { + Self::Rgba { red: r, green: g, blue: b, @@ -107,8 +107,8 @@ impl Color { } /// New `Color` from linear RGB colorspace. - pub const fn rgb_linear(r: f32, g: f32, b: f32) -> Color { - Color::RgbaLinear { + pub const fn rgb_linear(r: f32, g: f32, b: f32) -> Self { + Self::RgbaLinear { red: r, green: g, blue: b, @@ -117,8 +117,8 @@ impl Color { } /// New `Color` from linear RGB colorspace. - pub const fn rgba_linear(r: f32, g: f32, b: f32, a: f32) -> Color { - Color::RgbaLinear { + pub const fn rgba_linear(r: f32, g: f32, b: f32, a: f32) -> Self { + Self::RgbaLinear { red: r, green: g, blue: b, @@ -127,8 +127,8 @@ impl Color { } /// New `Color` with HSL representation in sRGB colorspace. - pub const fn hsl(hue: f32, saturation: f32, lightness: f32) -> Color { - Color::Hsla { + pub const fn hsl(hue: f32, saturation: f32, lightness: f32) -> Self { + Self::Hsla { hue, saturation, lightness, @@ -137,8 +137,8 @@ impl Color { } /// New `Color` with HSL representation in sRGB colorspace. - pub const fn hsla(hue: f32, saturation: f32, lightness: f32, alpha: f32) -> Color { - Color::Hsla { + pub const fn hsla(hue: f32, saturation: f32, lightness: f32, alpha: f32) -> Self { + Self::Hsla { hue, saturation, lightness, @@ -147,7 +147,7 @@ impl Color { } /// New `Color` from sRGB colorspace. - pub fn hex>(hex: T) -> Result { + pub fn hex>(hex: T) -> Result { let hex = hex.as_ref(); // RGB @@ -184,15 +184,15 @@ impl Color { } /// New `Color` from sRGB colorspace. - pub fn rgb_u8(r: u8, g: u8, b: u8) -> Color { - Color::rgba_u8(r, g, b, u8::MAX) + pub fn rgb_u8(r: u8, g: u8, b: u8) -> Self { + Self::rgba_u8(r, g, b, u8::MAX) } // Float operations in const fn are not stable yet // see https://github.com/rust-lang/rust/issues/57241 /// New `Color` from sRGB colorspace. - pub fn rgba_u8(r: u8, g: u8, b: u8, a: u8) -> Color { - Color::rgba( + pub fn rgba_u8(r: u8, g: u8, b: u8, a: u8) -> Self { + Self::rgba( r as f32 / u8::MAX as f32, g as f32 / u8::MAX as f32, b as f32 / u8::MAX as f32, @@ -203,7 +203,7 @@ impl Color { /// Get red in sRGB colorspace. pub fn r(&self) -> f32 { match self.as_rgba() { - Color::Rgba { red, .. } => red, + Self::Rgba { red, .. } => red, _ => unreachable!(), } } @@ -211,7 +211,7 @@ impl Color { /// Get green in sRGB colorspace. pub fn g(&self) -> f32 { match self.as_rgba() { - Color::Rgba { green, .. } => green, + Self::Rgba { green, .. } => green, _ => unreachable!(), } } @@ -219,7 +219,7 @@ impl Color { /// Get blue in sRGB colorspace. pub fn b(&self) -> f32 { match self.as_rgba() { - Color::Rgba { blue, .. } => blue, + Self::Rgba { blue, .. } => blue, _ => unreachable!(), } } @@ -228,7 +228,7 @@ impl Color { pub fn set_r(&mut self, r: f32) -> &mut Self { *self = self.as_rgba(); match self { - Color::Rgba { red, .. } => *red = r, + Self::Rgba { red, .. } => *red = r, _ => unreachable!(), } self @@ -238,7 +238,7 @@ impl Color { pub fn set_g(&mut self, g: f32) -> &mut Self { *self = self.as_rgba(); match self { - Color::Rgba { green, .. } => *green = g, + Self::Rgba { green, .. } => *green = g, _ => unreachable!(), } self @@ -248,27 +248,27 @@ impl Color { pub fn set_b(&mut self, b: f32) -> &mut Self { *self = self.as_rgba(); match self { - Color::Rgba { blue, .. } => *blue = b, + Self::Rgba { blue, .. } => *blue = b, _ => unreachable!(), } self } /// Get alpha. - pub fn a(&self) -> f32 { + pub const fn a(&self) -> f32 { match self { - Color::Rgba { alpha, .. } - | Color::RgbaLinear { alpha, .. } - | Color::Hsla { alpha, .. } => *alpha, + Self::Rgba { alpha, .. } + | Self::RgbaLinear { alpha, .. } + | Self::Hsla { alpha, .. } => *alpha, } } /// Set alpha. pub fn set_a(&mut self, a: f32) -> &mut Self { match self { - Color::Rgba { alpha, .. } - | Color::RgbaLinear { alpha, .. } - | Color::Hsla { alpha, .. } => { + Self::Rgba { alpha, .. } + | Self::RgbaLinear { alpha, .. } + | Self::Hsla { alpha, .. } => { *alpha = a; } } @@ -276,21 +276,21 @@ impl Color { } /// Converts a `Color` to variant `Color::Rgba` - pub fn as_rgba(self: &Color) -> Color { + pub fn as_rgba(&self) -> Self { match self { - Color::Rgba { .. } => *self, - Color::RgbaLinear { + Self::Rgba { .. } => *self, + Self::RgbaLinear { red, green, blue, alpha, - } => Color::Rgba { + } => Self::Rgba { red: red.linear_to_nonlinear_srgb(), green: green.linear_to_nonlinear_srgb(), blue: blue.linear_to_nonlinear_srgb(), alpha: *alpha, }, - Color::Hsla { + Self::Hsla { hue, saturation, lightness, @@ -298,7 +298,7 @@ impl Color { } => { let [red, green, blue] = HslRepresentation::hsl_to_nonlinear_srgb(*hue, *saturation, *lightness); - Color::Rgba { + Self::Rgba { red, green, blue, @@ -309,21 +309,21 @@ impl Color { } /// Converts a `Color` to variant `Color::RgbaLinear` - pub fn as_rgba_linear(self: &Color) -> Color { + pub fn as_rgba_linear(&self) -> Self { match self { - Color::Rgba { + Self::Rgba { red, green, blue, alpha, - } => Color::RgbaLinear { + } => Self::RgbaLinear { red: red.nonlinear_to_linear_srgb(), green: green.nonlinear_to_linear_srgb(), blue: blue.nonlinear_to_linear_srgb(), alpha: *alpha, }, - Color::RgbaLinear { .. } => *self, - Color::Hsla { + Self::RgbaLinear { .. } => *self, + Self::Hsla { hue, saturation, lightness, @@ -331,7 +331,7 @@ impl Color { } => { let [red, green, blue] = HslRepresentation::hsl_to_nonlinear_srgb(*hue, *saturation, *lightness); - Color::RgbaLinear { + Self::RgbaLinear { red: red.nonlinear_to_linear_srgb(), green: green.nonlinear_to_linear_srgb(), blue: blue.nonlinear_to_linear_srgb(), @@ -342,9 +342,9 @@ impl Color { } /// Converts a `Color` to variant `Color::Hsla` - pub fn as_hsla(self: &Color) -> Color { + pub fn as_hsla(&self) -> Self { match self { - Color::Rgba { + Self::Rgba { red, green, blue, @@ -352,14 +352,14 @@ impl Color { } => { let (hue, saturation, lightness) = HslRepresentation::nonlinear_srgb_to_hsl([*red, *green, *blue]); - Color::Hsla { + Self::Hsla { hue, saturation, lightness, alpha: *alpha, } } - Color::RgbaLinear { + Self::RgbaLinear { red, green, blue, @@ -370,27 +370,27 @@ impl Color { green.linear_to_nonlinear_srgb(), blue.linear_to_nonlinear_srgb(), ]); - Color::Hsla { + Self::Hsla { hue, saturation, lightness, alpha: *alpha, } } - Color::Hsla { .. } => *self, + Self::Hsla { .. } => *self, } } /// Converts a `Color` to a `[f32; 4]` from sRGB colorspace - pub fn as_rgba_f32(self: Color) -> [f32; 4] { + pub fn as_rgba_f32(self) -> [f32; 4] { match self { - Color::Rgba { + Self::Rgba { red, green, blue, alpha, } => [red, green, blue, alpha], - Color::RgbaLinear { + Self::RgbaLinear { red, green, blue, @@ -401,7 +401,7 @@ impl Color { blue.linear_to_nonlinear_srgb(), alpha, ], - Color::Hsla { + Self::Hsla { hue, saturation, lightness, @@ -416,9 +416,9 @@ impl Color { /// Converts a `Color` to a `[f32; 4]` from linear RBG colorspace #[inline] - pub fn as_linear_rgba_f32(self: Color) -> [f32; 4] { + pub fn as_linear_rgba_f32(self) -> [f32; 4] { match self { - Color::Rgba { + Self::Rgba { red, green, blue, @@ -429,13 +429,13 @@ impl Color { blue.nonlinear_to_linear_srgb(), alpha, ], - Color::RgbaLinear { + Self::RgbaLinear { red, green, blue, alpha, } => [red, green, blue, alpha], - Color::Hsla { + Self::Hsla { hue, saturation, lightness, @@ -454,9 +454,9 @@ impl Color { } /// Converts a `Color` to a `[f32; 4]` from HLS colorspace - pub fn as_hlsa_f32(self: Color) -> [f32; 4] { + pub fn as_hlsa_f32(self) -> [f32; 4] { match self { - Color::Rgba { + Self::Rgba { red, green, blue, @@ -466,7 +466,7 @@ impl Color { HslRepresentation::nonlinear_srgb_to_hsl([red, green, blue]); [hue, saturation, lightness, alpha] } - Color::RgbaLinear { + Self::RgbaLinear { red, green, blue, @@ -479,7 +479,7 @@ impl Color { ]); [hue, saturation, lightness, alpha] } - Color::Hsla { + Self::Hsla { hue, saturation, lightness, @@ -491,14 +491,14 @@ impl Color { impl Default for Color { fn default() -> Self { - Color::WHITE + Self::WHITE } } -impl AddAssign for Color { - fn add_assign(&mut self, rhs: Color) { +impl AddAssign for Color { + fn add_assign(&mut self, rhs: Self) { match self { - Color::Rgba { + Self::Rgba { red, green, blue, @@ -510,7 +510,7 @@ impl AddAssign for Color { *blue += rhs[2]; *alpha += rhs[3]; } - Color::RgbaLinear { + Self::RgbaLinear { red, green, blue, @@ -522,7 +522,7 @@ impl AddAssign for Color { *blue += rhs[2]; *alpha += rhs[3]; } - Color::Hsla { + Self::Hsla { hue, saturation, lightness, @@ -538,47 +538,47 @@ impl AddAssign for Color { } } -impl Add for Color { - type Output = Color; +impl Add for Color { + type Output = Self; - fn add(self, rhs: Color) -> Self::Output { + fn add(self, rhs: Self) -> Self::Output { match self { - Color::Rgba { + Self::Rgba { red, green, blue, alpha, } => { let rhs = rhs.as_rgba_f32(); - Color::Rgba { + Self::Rgba { red: red + rhs[0], green: green + rhs[1], blue: blue + rhs[2], alpha: alpha + rhs[3], } } - Color::RgbaLinear { + Self::RgbaLinear { red, green, blue, alpha, } => { let rhs = rhs.as_linear_rgba_f32(); - Color::RgbaLinear { + Self::RgbaLinear { red: red + rhs[0], green: green + rhs[1], blue: blue + rhs[2], alpha: alpha + rhs[3], } } - Color::Hsla { + Self::Hsla { hue, saturation, lightness, alpha, } => { let rhs = rhs.as_linear_rgba_f32(); - Color::Hsla { + Self::Hsla { hue: hue + rhs[0], saturation: saturation + rhs[1], lightness: lightness + rhs[2], @@ -591,16 +591,16 @@ impl Add for Color { impl AddAssign for Color { fn add_assign(&mut self, rhs: Vec4) { - let rhs: Color = rhs.into(); + let rhs: Self = rhs.into(); *self += rhs } } impl Add for Color { - type Output = Color; + type Output = Self; fn add(self, rhs: Vec4) -> Self::Output { - let rhs: Color = rhs.into(); + let rhs: Self = rhs.into(); self + rhs } } @@ -613,26 +613,26 @@ impl From for [f32; 4] { impl From<[f32; 4]> for Color { fn from([r, g, b, a]: [f32; 4]) -> Self { - Color::rgba(r, g, b, a) + Self::rgba(r, g, b, a) } } impl From<[f32; 3]> for Color { fn from([r, g, b]: [f32; 3]) -> Self { - Color::rgb(r, g, b) + Self::rgb(r, g, b) } } impl From for Vec4 { fn from(color: Color) -> Self { let color: [f32; 4] = color.into(); - Vec4::new(color[0], color[1], color[2], color[3]) + Self::new(color[0], color[1], color[2], color[3]) } } impl From for Color { fn from(vec4: Vec4) -> Self { - Color::rgba(vec4.x, vec4.y, vec4.z, vec4.w) + Self::rgba(vec4.x, vec4.y, vec4.z, vec4.w) } } @@ -645,7 +645,7 @@ impl From for wgpu::Color { alpha, } = color.as_rgba_linear() { - wgpu::Color { + Self { r: red as f64, g: green as f64, b: blue as f64, @@ -658,38 +658,38 @@ impl From for wgpu::Color { } impl Mul for Color { - type Output = Color; + type Output = Self; fn mul(self, rhs: f32) -> Self::Output { match self { - Color::Rgba { + Self::Rgba { red, green, blue, alpha, - } => Color::Rgba { + } => Self::Rgba { red: red * rhs, green: green * rhs, blue: blue * rhs, alpha, }, - Color::RgbaLinear { + Self::RgbaLinear { red, green, blue, alpha, - } => Color::RgbaLinear { + } => Self::RgbaLinear { red: red * rhs, green: green * rhs, blue: blue * rhs, alpha, }, - Color::Hsla { + Self::Hsla { hue, saturation, lightness, alpha, - } => Color::Hsla { + } => Self::Hsla { hue: hue * rhs, saturation: saturation * rhs, lightness: lightness * rhs, @@ -702,21 +702,21 @@ impl Mul for Color { impl MulAssign for Color { fn mul_assign(&mut self, rhs: f32) { match self { - Color::Rgba { + Self::Rgba { red, green, blue, .. } => { *red *= rhs; *green *= rhs; *blue *= rhs; } - Color::RgbaLinear { + Self::RgbaLinear { red, green, blue, .. } => { *red *= rhs; *green *= rhs; *blue *= rhs; } - Color::Hsla { + Self::Hsla { hue, saturation, lightness, @@ -731,38 +731,38 @@ impl MulAssign for Color { } impl Mul for Color { - type Output = Color; + type Output = Self; fn mul(self, rhs: Vec4) -> Self::Output { match self { - Color::Rgba { + Self::Rgba { red, green, blue, alpha, - } => Color::Rgba { + } => Self::Rgba { red: red * rhs.x, green: green * rhs.y, blue: blue * rhs.z, alpha: alpha * rhs.w, }, - Color::RgbaLinear { + Self::RgbaLinear { red, green, blue, alpha, - } => Color::RgbaLinear { + } => Self::RgbaLinear { red: red * rhs.x, green: green * rhs.y, blue: blue * rhs.z, alpha: alpha * rhs.w, }, - Color::Hsla { + Self::Hsla { hue, saturation, lightness, alpha, - } => Color::Hsla { + } => Self::Hsla { hue: hue * rhs.x, saturation: saturation * rhs.y, lightness: lightness * rhs.z, @@ -775,7 +775,7 @@ impl Mul for Color { impl MulAssign for Color { fn mul_assign(&mut self, rhs: Vec4) { match self { - Color::Rgba { + Self::Rgba { red, green, blue, @@ -786,7 +786,7 @@ impl MulAssign for Color { *blue *= rhs.z; *alpha *= rhs.w; } - Color::RgbaLinear { + Self::RgbaLinear { red, green, blue, @@ -797,7 +797,7 @@ impl MulAssign for Color { *blue *= rhs.z; *alpha *= rhs.w; } - Color::Hsla { + Self::Hsla { hue, saturation, lightness, @@ -813,38 +813,38 @@ impl MulAssign for Color { } impl Mul for Color { - type Output = Color; + type Output = Self; fn mul(self, rhs: Vec3) -> Self::Output { match self { - Color::Rgba { + Self::Rgba { red, green, blue, alpha, - } => Color::Rgba { + } => Self::Rgba { red: red * rhs.x, green: green * rhs.y, blue: blue * rhs.z, alpha, }, - Color::RgbaLinear { + Self::RgbaLinear { red, green, blue, alpha, - } => Color::RgbaLinear { + } => Self::RgbaLinear { red: red * rhs.x, green: green * rhs.y, blue: blue * rhs.z, alpha, }, - Color::Hsla { + Self::Hsla { hue, saturation, lightness, alpha, - } => Color::Hsla { + } => Self::Hsla { hue: hue * rhs.x, saturation: saturation * rhs.y, lightness: lightness * rhs.z, @@ -857,21 +857,21 @@ impl Mul for Color { impl MulAssign for Color { fn mul_assign(&mut self, rhs: Vec3) { match self { - Color::Rgba { + Self::Rgba { red, green, blue, .. } => { *red *= rhs.x; *green *= rhs.y; *blue *= rhs.z; } - Color::RgbaLinear { + Self::RgbaLinear { red, green, blue, .. } => { *red *= rhs.x; *green *= rhs.y; *blue *= rhs.z; } - Color::Hsla { + Self::Hsla { hue, saturation, lightness, @@ -886,38 +886,38 @@ impl MulAssign for Color { } impl Mul<[f32; 4]> for Color { - type Output = Color; + type Output = Self; fn mul(self, rhs: [f32; 4]) -> Self::Output { match self { - Color::Rgba { + Self::Rgba { red, green, blue, alpha, - } => Color::Rgba { + } => Self::Rgba { red: red * rhs[0], green: green * rhs[1], blue: blue * rhs[2], alpha: alpha * rhs[3], }, - Color::RgbaLinear { + Self::RgbaLinear { red, green, blue, alpha, - } => Color::RgbaLinear { + } => Self::RgbaLinear { red: red * rhs[0], green: green * rhs[1], blue: blue * rhs[2], alpha: alpha * rhs[3], }, - Color::Hsla { + Self::Hsla { hue, saturation, lightness, alpha, - } => Color::Hsla { + } => Self::Hsla { hue: hue * rhs[0], saturation: saturation * rhs[1], lightness: lightness * rhs[2], @@ -930,7 +930,7 @@ impl Mul<[f32; 4]> for Color { impl MulAssign<[f32; 4]> for Color { fn mul_assign(&mut self, rhs: [f32; 4]) { match self { - Color::Rgba { + Self::Rgba { red, green, blue, @@ -941,7 +941,7 @@ impl MulAssign<[f32; 4]> for Color { *blue *= rhs[2]; *alpha *= rhs[3]; } - Color::RgbaLinear { + Self::RgbaLinear { red, green, blue, @@ -952,7 +952,7 @@ impl MulAssign<[f32; 4]> for Color { *blue *= rhs[2]; *alpha *= rhs[3]; } - Color::Hsla { + Self::Hsla { hue, saturation, lightness, @@ -968,38 +968,38 @@ impl MulAssign<[f32; 4]> for Color { } impl Mul<[f32; 3]> for Color { - type Output = Color; + type Output = Self; fn mul(self, rhs: [f32; 3]) -> Self::Output { match self { - Color::Rgba { + Self::Rgba { red, green, blue, alpha, - } => Color::Rgba { + } => Self::Rgba { red: red * rhs[0], green: green * rhs[1], blue: blue * rhs[2], alpha, }, - Color::RgbaLinear { + Self::RgbaLinear { red, green, blue, alpha, - } => Color::RgbaLinear { + } => Self::RgbaLinear { red: red * rhs[0], green: green * rhs[1], blue: blue * rhs[2], alpha, }, - Color::Hsla { + Self::Hsla { hue, saturation, lightness, alpha, - } => Color::Hsla { + } => Self::Hsla { hue: hue * rhs[0], saturation: saturation * rhs[1], lightness: lightness * rhs[2], @@ -1012,21 +1012,21 @@ impl Mul<[f32; 3]> for Color { impl MulAssign<[f32; 3]> for Color { fn mul_assign(&mut self, rhs: [f32; 3]) { match self { - Color::Rgba { + Self::Rgba { red, green, blue, .. } => { *red *= rhs[0]; *green *= rhs[1]; *blue *= rhs[2]; } - Color::RgbaLinear { + Self::RgbaLinear { red, green, blue, .. } => { *red *= rhs[0]; *green *= rhs[1]; *blue *= rhs[2]; } - Color::Hsla { + Self::Hsla { hue, saturation, lightness, diff --git a/crates/bevy_render/src/mesh/mesh/conversions.rs b/crates/bevy_render/src/mesh/mesh/conversions.rs index 9bf4a55f76488..29acb829103f5 100644 --- a/crates/bevy_render/src/mesh/mesh/conversions.rs +++ b/crates/bevy_render/src/mesh/mesh/conversions.rs @@ -48,79 +48,79 @@ impl FromVertexAttributeError { impl From> for VertexAttributeValues { fn from(vec: Vec) -> Self { - VertexAttributeValues::Float32(vec) + Self::Float32(vec) } } impl From> for VertexAttributeValues { fn from(vec: Vec) -> Self { - VertexAttributeValues::Sint32(vec) + Self::Sint32(vec) } } impl From> for VertexAttributeValues { fn from(vec: Vec) -> Self { - VertexAttributeValues::Uint32(vec) + Self::Uint32(vec) } } impl From> for VertexAttributeValues { fn from(vec: Vec<[f32; 2]>) -> Self { - VertexAttributeValues::Float32x2(vec) + Self::Float32x2(vec) } } impl From> for VertexAttributeValues { fn from(vec: Vec<[i32; 2]>) -> Self { - VertexAttributeValues::Sint32x2(vec) + Self::Sint32x2(vec) } } impl From> for VertexAttributeValues { fn from(vec: Vec<[u32; 2]>) -> Self { - VertexAttributeValues::Uint32x2(vec) + Self::Uint32x2(vec) } } impl From> for VertexAttributeValues { fn from(vec: Vec<[f32; 3]>) -> Self { - VertexAttributeValues::Float32x3(vec) + Self::Float32x3(vec) } } impl From> for VertexAttributeValues { fn from(vec: Vec<[i32; 3]>) -> Self { - VertexAttributeValues::Sint32x3(vec) + Self::Sint32x3(vec) } } impl From> for VertexAttributeValues { fn from(vec: Vec<[u32; 3]>) -> Self { - VertexAttributeValues::Uint32x3(vec) + Self::Uint32x3(vec) } } impl From> for VertexAttributeValues { fn from(vec: Vec<[f32; 4]>) -> Self { - VertexAttributeValues::Float32x4(vec) + Self::Float32x4(vec) } } impl From> for VertexAttributeValues { fn from(vec: Vec<[i32; 4]>) -> Self { - VertexAttributeValues::Sint32x4(vec) + Self::Sint32x4(vec) } } impl From> for VertexAttributeValues { fn from(vec: Vec<[u32; 4]>) -> Self { - VertexAttributeValues::Uint32x4(vec) + Self::Uint32x4(vec) } } impl From> for VertexAttributeValues { fn from(vec: Vec<[u8; 4]>) -> Self { - VertexAttributeValues::Unorm8x4(vec) + Self::Unorm8x4(vec) } } diff --git a/crates/bevy_render/src/mesh/mesh/mod.rs b/crates/bevy_render/src/mesh/mesh/mod.rs index faba4b3a179ea..b21de05112aa4 100644 --- a/crates/bevy_render/src/mesh/mesh/mod.rs +++ b/crates/bevy_render/src/mesh/mesh/mod.rs @@ -72,7 +72,7 @@ impl Mesh { /// renderer knows how to treat the vertex data. Most of the time this will be /// [`PrimitiveTopology::TriangleList`]. pub fn new(primitive_topology: PrimitiveTopology) -> Self { - Mesh { + Self { primitive_topology, attributes: Default::default(), indices: None, @@ -80,7 +80,7 @@ impl Mesh { } /// Returns the topology of the mesh. - pub fn primitive_topology(&self) -> PrimitiveTopology { + pub const fn primitive_topology(&self) -> PrimitiveTopology { self.primitive_topology } @@ -116,7 +116,7 @@ impl Mesh { } /// Retrieves the vertex `indices` of the mesh. - pub fn indices(&self) -> Option<&Indices> { + pub const fn indices(&self) -> Option<&Indices> { self.indices.as_ref() } @@ -276,7 +276,7 @@ impl Mesh { } let positions = self - .attribute(Mesh::ATTRIBUTE_POSITION) + .attribute(Self::ATTRIBUTE_POSITION) .unwrap() .as_float3() .expect("`Mesh::ATTRIBUTE_POSITION` vertex attributes should be of type `float3`"); @@ -287,13 +287,13 @@ impl Mesh { .flat_map(|normal| [normal; 3]) .collect(); - self.set_attribute(Mesh::ATTRIBUTE_NORMAL, normals); + self.set_attribute(Self::ATTRIBUTE_NORMAL, normals); } /// Compute the Axis-Aligned Bounding Box of the mesh vertices in model space pub fn compute_aabb(&self) -> Option { if let Some(VertexAttributeValues::Float32x3(values)) = - self.attribute(Mesh::ATTRIBUTE_POSITION) + self.attribute(Self::ATTRIBUTE_POSITION) { let mut minimum = VEC3_MAX; let mut maximum = VEC3_MIN; @@ -408,34 +408,34 @@ impl VertexAttributeValues { /// mesh, all of the [`VertexAttributeValues`] must have the same length. pub fn len(&self) -> usize { match *self { - VertexAttributeValues::Float32(ref values) => values.len(), - VertexAttributeValues::Sint32(ref values) => values.len(), - VertexAttributeValues::Uint32(ref values) => values.len(), - VertexAttributeValues::Float32x2(ref values) => values.len(), - VertexAttributeValues::Sint32x2(ref values) => values.len(), - VertexAttributeValues::Uint32x2(ref values) => values.len(), - VertexAttributeValues::Float32x3(ref values) => values.len(), - VertexAttributeValues::Sint32x3(ref values) => values.len(), - VertexAttributeValues::Uint32x3(ref values) => values.len(), - VertexAttributeValues::Float32x4(ref values) => values.len(), - VertexAttributeValues::Sint32x4(ref values) => values.len(), - VertexAttributeValues::Uint32x4(ref values) => values.len(), - VertexAttributeValues::Sint16x2(ref values) => values.len(), - VertexAttributeValues::Snorm16x2(ref values) => values.len(), - VertexAttributeValues::Uint16x2(ref values) => values.len(), - VertexAttributeValues::Unorm16x2(ref values) => values.len(), - VertexAttributeValues::Sint16x4(ref values) => values.len(), - VertexAttributeValues::Snorm16x4(ref values) => values.len(), - VertexAttributeValues::Uint16x4(ref values) => values.len(), - VertexAttributeValues::Unorm16x4(ref values) => values.len(), - VertexAttributeValues::Sint8x2(ref values) => values.len(), - VertexAttributeValues::Snorm8x2(ref values) => values.len(), - VertexAttributeValues::Uint8x2(ref values) => values.len(), - VertexAttributeValues::Unorm8x2(ref values) => values.len(), - VertexAttributeValues::Sint8x4(ref values) => values.len(), - VertexAttributeValues::Snorm8x4(ref values) => values.len(), - VertexAttributeValues::Uint8x4(ref values) => values.len(), - VertexAttributeValues::Unorm8x4(ref values) => values.len(), + Self::Float32(ref values) => values.len(), + Self::Sint32(ref values) => values.len(), + Self::Uint32(ref values) => values.len(), + Self::Float32x2(ref values) => values.len(), + Self::Sint32x2(ref values) => values.len(), + Self::Uint32x2(ref values) => values.len(), + Self::Float32x3(ref values) => values.len(), + Self::Sint32x3(ref values) => values.len(), + Self::Uint32x3(ref values) => values.len(), + Self::Float32x4(ref values) => values.len(), + Self::Sint32x4(ref values) => values.len(), + Self::Uint32x4(ref values) => values.len(), + Self::Sint16x2(ref values) => values.len(), + Self::Snorm16x2(ref values) => values.len(), + Self::Uint16x2(ref values) => values.len(), + Self::Unorm16x2(ref values) => values.len(), + Self::Sint16x4(ref values) => values.len(), + Self::Snorm16x4(ref values) => values.len(), + Self::Uint16x4(ref values) => values.len(), + Self::Unorm16x4(ref values) => values.len(), + Self::Sint8x2(ref values) => values.len(), + Self::Snorm8x2(ref values) => values.len(), + Self::Uint8x2(ref values) => values.len(), + Self::Unorm8x2(ref values) => values.len(), + Self::Sint8x4(ref values) => values.len(), + Self::Snorm8x4(ref values) => values.len(), + Self::Uint8x4(ref values) => values.len(), + Self::Unorm8x4(ref values) => values.len(), } } @@ -457,34 +457,34 @@ impl VertexAttributeValues { /// useful for serialization and sending to the GPU. pub fn get_bytes(&self) -> &[u8] { match self { - VertexAttributeValues::Float32(values) => cast_slice(&values[..]), - VertexAttributeValues::Sint32(values) => cast_slice(&values[..]), - VertexAttributeValues::Uint32(values) => cast_slice(&values[..]), - VertexAttributeValues::Float32x2(values) => cast_slice(&values[..]), - VertexAttributeValues::Sint32x2(values) => cast_slice(&values[..]), - VertexAttributeValues::Uint32x2(values) => cast_slice(&values[..]), - VertexAttributeValues::Float32x3(values) => cast_slice(&values[..]), - VertexAttributeValues::Sint32x3(values) => cast_slice(&values[..]), - VertexAttributeValues::Uint32x3(values) => cast_slice(&values[..]), - VertexAttributeValues::Float32x4(values) => cast_slice(&values[..]), - VertexAttributeValues::Sint32x4(values) => cast_slice(&values[..]), - VertexAttributeValues::Uint32x4(values) => cast_slice(&values[..]), - VertexAttributeValues::Sint16x2(values) => cast_slice(&values[..]), - VertexAttributeValues::Snorm16x2(values) => cast_slice(&values[..]), - VertexAttributeValues::Uint16x2(values) => cast_slice(&values[..]), - VertexAttributeValues::Unorm16x2(values) => cast_slice(&values[..]), - VertexAttributeValues::Sint16x4(values) => cast_slice(&values[..]), - VertexAttributeValues::Snorm16x4(values) => cast_slice(&values[..]), - VertexAttributeValues::Uint16x4(values) => cast_slice(&values[..]), - VertexAttributeValues::Unorm16x4(values) => cast_slice(&values[..]), - VertexAttributeValues::Sint8x2(values) => cast_slice(&values[..]), - VertexAttributeValues::Snorm8x2(values) => cast_slice(&values[..]), - VertexAttributeValues::Uint8x2(values) => cast_slice(&values[..]), - VertexAttributeValues::Unorm8x2(values) => cast_slice(&values[..]), - VertexAttributeValues::Sint8x4(values) => cast_slice(&values[..]), - VertexAttributeValues::Snorm8x4(values) => cast_slice(&values[..]), - VertexAttributeValues::Uint8x4(values) => cast_slice(&values[..]), - VertexAttributeValues::Unorm8x4(values) => cast_slice(&values[..]), + Self::Float32(values) => cast_slice(&values[..]), + Self::Sint32(values) => cast_slice(&values[..]), + Self::Uint32(values) => cast_slice(&values[..]), + Self::Float32x2(values) => cast_slice(&values[..]), + Self::Sint32x2(values) => cast_slice(&values[..]), + Self::Uint32x2(values) => cast_slice(&values[..]), + Self::Float32x3(values) => cast_slice(&values[..]), + Self::Sint32x3(values) => cast_slice(&values[..]), + Self::Uint32x3(values) => cast_slice(&values[..]), + Self::Float32x4(values) => cast_slice(&values[..]), + Self::Sint32x4(values) => cast_slice(&values[..]), + Self::Uint32x4(values) => cast_slice(&values[..]), + Self::Sint16x2(values) => cast_slice(&values[..]), + Self::Snorm16x2(values) => cast_slice(&values[..]), + Self::Uint16x2(values) => cast_slice(&values[..]), + Self::Unorm16x2(values) => cast_slice(&values[..]), + Self::Sint16x4(values) => cast_slice(&values[..]), + Self::Snorm16x4(values) => cast_slice(&values[..]), + Self::Uint16x4(values) => cast_slice(&values[..]), + Self::Unorm16x4(values) => cast_slice(&values[..]), + Self::Sint8x2(values) => cast_slice(&values[..]), + Self::Snorm8x2(values) => cast_slice(&values[..]), + Self::Uint8x2(values) => cast_slice(&values[..]), + Self::Unorm8x2(values) => cast_slice(&values[..]), + Self::Sint8x4(values) => cast_slice(&values[..]), + Self::Snorm8x4(values) => cast_slice(&values[..]), + Self::Uint8x4(values) => cast_slice(&values[..]), + Self::Unorm8x4(values) => cast_slice(&values[..]), } } } @@ -492,34 +492,34 @@ impl VertexAttributeValues { impl From<&VertexAttributeValues> for VertexFormat { fn from(values: &VertexAttributeValues) -> Self { match values { - VertexAttributeValues::Float32(_) => VertexFormat::Float32, - VertexAttributeValues::Sint32(_) => VertexFormat::Sint32, - VertexAttributeValues::Uint32(_) => VertexFormat::Uint32, - VertexAttributeValues::Float32x2(_) => VertexFormat::Float32x2, - VertexAttributeValues::Sint32x2(_) => VertexFormat::Sint32x2, - VertexAttributeValues::Uint32x2(_) => VertexFormat::Uint32x2, - VertexAttributeValues::Float32x3(_) => VertexFormat::Float32x3, - VertexAttributeValues::Sint32x3(_) => VertexFormat::Sint32x3, - VertexAttributeValues::Uint32x3(_) => VertexFormat::Uint32x3, - VertexAttributeValues::Float32x4(_) => VertexFormat::Float32x4, - VertexAttributeValues::Sint32x4(_) => VertexFormat::Sint32x4, - VertexAttributeValues::Uint32x4(_) => VertexFormat::Uint32x4, - VertexAttributeValues::Sint16x2(_) => VertexFormat::Sint16x2, - VertexAttributeValues::Snorm16x2(_) => VertexFormat::Snorm16x2, - VertexAttributeValues::Uint16x2(_) => VertexFormat::Uint16x2, - VertexAttributeValues::Unorm16x2(_) => VertexFormat::Unorm16x2, - VertexAttributeValues::Sint16x4(_) => VertexFormat::Sint16x4, - VertexAttributeValues::Snorm16x4(_) => VertexFormat::Snorm16x4, - VertexAttributeValues::Uint16x4(_) => VertexFormat::Uint16x4, - VertexAttributeValues::Unorm16x4(_) => VertexFormat::Unorm16x4, - VertexAttributeValues::Sint8x2(_) => VertexFormat::Sint8x2, - VertexAttributeValues::Snorm8x2(_) => VertexFormat::Snorm8x2, - VertexAttributeValues::Uint8x2(_) => VertexFormat::Uint8x2, - VertexAttributeValues::Unorm8x2(_) => VertexFormat::Unorm8x2, - VertexAttributeValues::Sint8x4(_) => VertexFormat::Sint8x4, - VertexAttributeValues::Snorm8x4(_) => VertexFormat::Snorm8x4, - VertexAttributeValues::Uint8x4(_) => VertexFormat::Uint8x4, - VertexAttributeValues::Unorm8x4(_) => VertexFormat::Unorm8x4, + VertexAttributeValues::Float32(_) => Self::Float32, + VertexAttributeValues::Sint32(_) => Self::Sint32, + VertexAttributeValues::Uint32(_) => Self::Uint32, + VertexAttributeValues::Float32x2(_) => Self::Float32x2, + VertexAttributeValues::Sint32x2(_) => Self::Sint32x2, + VertexAttributeValues::Uint32x2(_) => Self::Uint32x2, + VertexAttributeValues::Float32x3(_) => Self::Float32x3, + VertexAttributeValues::Sint32x3(_) => Self::Sint32x3, + VertexAttributeValues::Uint32x3(_) => Self::Uint32x3, + VertexAttributeValues::Float32x4(_) => Self::Float32x4, + VertexAttributeValues::Sint32x4(_) => Self::Sint32x4, + VertexAttributeValues::Uint32x4(_) => Self::Uint32x4, + VertexAttributeValues::Sint16x2(_) => Self::Sint16x2, + VertexAttributeValues::Snorm16x2(_) => Self::Snorm16x2, + VertexAttributeValues::Uint16x2(_) => Self::Uint16x2, + VertexAttributeValues::Unorm16x2(_) => Self::Unorm16x2, + VertexAttributeValues::Sint16x4(_) => Self::Sint16x4, + VertexAttributeValues::Snorm16x4(_) => Self::Snorm16x4, + VertexAttributeValues::Uint16x4(_) => Self::Uint16x4, + VertexAttributeValues::Unorm16x4(_) => Self::Unorm16x4, + VertexAttributeValues::Sint8x2(_) => Self::Sint8x2, + VertexAttributeValues::Snorm8x2(_) => Self::Snorm8x2, + VertexAttributeValues::Uint8x2(_) => Self::Uint8x2, + VertexAttributeValues::Unorm8x2(_) => Self::Unorm8x2, + VertexAttributeValues::Sint8x4(_) => Self::Sint8x4, + VertexAttributeValues::Snorm8x4(_) => Self::Snorm8x4, + VertexAttributeValues::Uint8x4(_) => Self::Uint8x4, + VertexAttributeValues::Unorm8x4(_) => Self::Unorm8x4, } } } @@ -579,8 +579,8 @@ impl Iterator for IndicesIter<'_> { impl From<&Indices> for IndexFormat { fn from(indices: &Indices) -> Self { match indices { - Indices::U16(_) => IndexFormat::Uint16, - Indices::U32(_) => IndexFormat::Uint32, + Indices::U16(_) => Self::Uint16, + Indices::U32(_) => Self::Uint32, } } } @@ -611,7 +611,7 @@ pub enum GpuBufferInfo { } impl RenderAsset for Mesh { - type ExtractedAsset = Mesh; + type ExtractedAsset = Self; type PreparedAsset = GpuMesh; type Param = SRes; @@ -650,7 +650,7 @@ impl RenderAsset for Mesh { Ok(GpuMesh { vertex_buffer, buffer_info, - has_tangents: mesh.attributes.contains_key(Mesh::ATTRIBUTE_TANGENT), + has_tangents: mesh.attributes.contains_key(Self::ATTRIBUTE_TANGENT), primitive_topology: mesh.primitive_topology(), }) } diff --git a/crates/bevy_render/src/mesh/shape/capsule.rs b/crates/bevy_render/src/mesh/shape/capsule.rs index 7b6d268a9a9a6..a139ecf3d6538 100644 --- a/crates/bevy_render/src/mesh/shape/capsule.rs +++ b/crates/bevy_render/src/mesh/shape/capsule.rs @@ -20,7 +20,7 @@ pub struct Capsule { } impl Default for Capsule { fn default() -> Self { - Capsule { + Self { radius: 0.5, rings: 0, depth: 1.0, @@ -45,7 +45,7 @@ pub enum CapsuleUvProfile { impl Default for CapsuleUvProfile { fn default() -> Self { - CapsuleUvProfile::Aspect + Self::Aspect } } @@ -180,7 +180,7 @@ impl From for Mesh { // For texture coordinates. let t_tex_fac = ip1f * to_tex_vertical; let cmpl_tex_fac = 1.0 - t_tex_fac; - let t_tex_north = cmpl_tex_fac + vt_aspect_north * t_tex_fac; + let t_tex_north = vt_aspect_north.mul_add(t_tex_fac, cmpl_tex_fac); let t_tex_south = cmpl_tex_fac * vt_aspect_south; let i_lonsp1 = i * lonsp1; @@ -225,7 +225,7 @@ impl From for Mesh { for h in 1..ringsp1 { let fac = h as f32 * to_fac; let cmpl_fac = 1.0 - fac; - let t_texture = cmpl_fac * vt_aspect_north + fac * vt_aspect_south; + let t_texture = cmpl_fac.mul_add(vt_aspect_north, fac * vt_aspect_south); let z = half_depth - depth * fac; for j in 0..lonsp1 { @@ -369,10 +369,10 @@ impl From for Mesh { assert_eq!(vs.len(), vert_len); assert_eq!(tris.len(), fs_len); - let mut mesh = Mesh::new(PrimitiveTopology::TriangleList); - mesh.set_attribute(Mesh::ATTRIBUTE_POSITION, vs); - mesh.set_attribute(Mesh::ATTRIBUTE_NORMAL, vns); - mesh.set_attribute(Mesh::ATTRIBUTE_UV_0, vts); + let mut mesh = Self::new(PrimitiveTopology::TriangleList); + mesh.set_attribute(Self::ATTRIBUTE_POSITION, vs); + mesh.set_attribute(Self::ATTRIBUTE_NORMAL, vns); + mesh.set_attribute(Self::ATTRIBUTE_UV_0, vts); mesh.set_indices(Some(Indices::U32(tris))); mesh } diff --git a/crates/bevy_render/src/mesh/shape/icosphere.rs b/crates/bevy_render/src/mesh/shape/icosphere.rs index ff2068469ec51..c0e570b25ebc9 100644 --- a/crates/bevy_render/src/mesh/shape/icosphere.rs +++ b/crates/bevy_render/src/mesh/shape/icosphere.rs @@ -93,11 +93,11 @@ impl From for Mesh { let indices = Indices::U32(indices); - let mut mesh = Mesh::new(PrimitiveTopology::TriangleList); + let mut mesh = Self::new(PrimitiveTopology::TriangleList); mesh.set_indices(Some(indices)); - mesh.set_attribute(Mesh::ATTRIBUTE_POSITION, points); - mesh.set_attribute(Mesh::ATTRIBUTE_NORMAL, normals); - mesh.set_attribute(Mesh::ATTRIBUTE_UV_0, uvs); + mesh.set_attribute(Self::ATTRIBUTE_POSITION, points); + mesh.set_attribute(Self::ATTRIBUTE_NORMAL, normals); + mesh.set_attribute(Self::ATTRIBUTE_UV_0, uvs); mesh } } diff --git a/crates/bevy_render/src/mesh/shape/mod.rs b/crates/bevy_render/src/mesh/shape/mod.rs index e2aa285d2085a..f27fda9074f23 100644 --- a/crates/bevy_render/src/mesh/shape/mod.rs +++ b/crates/bevy_render/src/mesh/shape/mod.rs @@ -7,14 +7,14 @@ pub struct Cube { } impl Cube { - pub fn new(size: f32) -> Cube { - Cube { size } + pub const fn new(size: f32) -> Self { + Self { size } } } impl Default for Cube { fn default() -> Self { - Cube { size: 1.0 } + Self { size: 1.0 } } } @@ -39,8 +39,8 @@ pub struct Box { impl Box { /// Creates a new box centered at the origin with the supplied side lengths. - pub fn new(x_length: f32, y_length: f32, z_length: f32) -> Box { - Box { + pub fn new(x_length: f32, y_length: f32, z_length: f32) -> Self { + Self { max_x: x_length / 2.0, min_x: -x_length / 2.0, max_y: y_length / 2.0, @@ -53,7 +53,7 @@ impl Box { impl Default for Box { fn default() -> Self { - Box::new(2.0, 1.0, 1.0) + Self::new(2.0, 1.0, 1.0) } } @@ -111,10 +111,10 @@ impl From for Mesh { 20, 21, 22, 22, 23, 20, // back ]); - let mut mesh = Mesh::new(PrimitiveTopology::TriangleList); - mesh.set_attribute(Mesh::ATTRIBUTE_POSITION, positions); - mesh.set_attribute(Mesh::ATTRIBUTE_NORMAL, normals); - mesh.set_attribute(Mesh::ATTRIBUTE_UV_0, uvs); + let mut mesh = Self::new(PrimitiveTopology::TriangleList); + mesh.set_attribute(Self::ATTRIBUTE_POSITION, positions); + mesh.set_attribute(Self::ATTRIBUTE_NORMAL, normals); + mesh.set_attribute(Self::ATTRIBUTE_UV_0, uvs); mesh.set_indices(Some(indices)); mesh } @@ -131,16 +131,16 @@ pub struct Quad { impl Default for Quad { fn default() -> Self { - Quad::new(Vec2::ONE) + Self::new(Vec2::ONE) } } impl Quad { - pub fn new(size: Vec2) -> Self { + pub const fn new(size: Vec2) -> Self { Self { size, flip: false } } - pub fn flipped(size: Vec2) -> Self { + pub const fn flipped(size: Vec2) -> Self { Self { size, flip: true } } } @@ -213,11 +213,11 @@ impl From for Mesh { uvs.push(*uv); } - let mut mesh = Mesh::new(PrimitiveTopology::TriangleList); + let mut mesh = Self::new(PrimitiveTopology::TriangleList); mesh.set_indices(Some(indices)); - mesh.set_attribute(Mesh::ATTRIBUTE_POSITION, positions); - mesh.set_attribute(Mesh::ATTRIBUTE_NORMAL, normals); - mesh.set_attribute(Mesh::ATTRIBUTE_UV_0, uvs); + mesh.set_attribute(Self::ATTRIBUTE_POSITION, positions); + mesh.set_attribute(Self::ATTRIBUTE_NORMAL, normals); + mesh.set_attribute(Self::ATTRIBUTE_UV_0, uvs); mesh } } @@ -231,7 +231,7 @@ pub struct Plane { impl Default for Plane { fn default() -> Self { - Plane { size: 1.0 } + Self { size: 1.0 } } } @@ -257,11 +257,11 @@ impl From for Mesh { uvs.push(*uv); } - let mut mesh = Mesh::new(PrimitiveTopology::TriangleList); + let mut mesh = Self::new(PrimitiveTopology::TriangleList); mesh.set_indices(Some(indices)); - mesh.set_attribute(Mesh::ATTRIBUTE_POSITION, positions); - mesh.set_attribute(Mesh::ATTRIBUTE_NORMAL, normals); - mesh.set_attribute(Mesh::ATTRIBUTE_UV_0, uvs); + mesh.set_attribute(Self::ATTRIBUTE_POSITION, positions); + mesh.set_attribute(Self::ATTRIBUTE_NORMAL, normals); + mesh.set_attribute(Self::ATTRIBUTE_UV_0, uvs); mesh } } diff --git a/crates/bevy_render/src/mesh/shape/torus.rs b/crates/bevy_render/src/mesh/shape/torus.rs index abe63e00c5c27..ab8da133926d5 100644 --- a/crates/bevy_render/src/mesh/shape/torus.rs +++ b/crates/bevy_render/src/mesh/shape/torus.rs @@ -13,7 +13,7 @@ pub struct Torus { impl Default for Torus { fn default() -> Self { - Torus { + Self { radius: 1.0, ring_radius: 0.5, subdivisions_segments: 32, @@ -41,8 +41,8 @@ impl From for Mesh { for side in 0..=torus.subdivisions_sides { let phi = side_stride * side as f32; - let x = theta.cos() * (torus.radius + torus.ring_radius * phi.cos()); - let z = theta.sin() * (torus.radius + torus.ring_radius * phi.cos()); + let x = theta.cos() * torus.ring_radius.mul_add(phi.cos(), torus.radius); + let z = theta.sin() * torus.ring_radius.mul_add(phi.cos(), torus.radius); let y = torus.ring_radius * phi.sin(); let tan_ring = Vec3::new( @@ -88,11 +88,11 @@ impl From for Mesh { } } - let mut mesh = Mesh::new(PrimitiveTopology::TriangleList); + let mut mesh = Self::new(PrimitiveTopology::TriangleList); mesh.set_indices(Some(Indices::U32(indices))); - mesh.set_attribute(Mesh::ATTRIBUTE_POSITION, positions); - mesh.set_attribute(Mesh::ATTRIBUTE_NORMAL, normals); - mesh.set_attribute(Mesh::ATTRIBUTE_UV_0, uvs); + mesh.set_attribute(Self::ATTRIBUTE_POSITION, positions); + mesh.set_attribute(Self::ATTRIBUTE_NORMAL, normals); + mesh.set_attribute(Self::ATTRIBUTE_UV_0, uvs); mesh } } diff --git a/crates/bevy_render/src/mesh/shape/uvsphere.rs b/crates/bevy_render/src/mesh/shape/uvsphere.rs index 571c3123d9aa1..97c7e636339b8 100644 --- a/crates/bevy_render/src/mesh/shape/uvsphere.rs +++ b/crates/bevy_render/src/mesh/shape/uvsphere.rs @@ -80,11 +80,11 @@ impl From for Mesh { } } - let mut mesh = Mesh::new(PrimitiveTopology::TriangleList); + let mut mesh = Self::new(PrimitiveTopology::TriangleList); mesh.set_indices(Some(Indices::U32(indices))); - mesh.set_attribute(Mesh::ATTRIBUTE_POSITION, vertices); - mesh.set_attribute(Mesh::ATTRIBUTE_NORMAL, normals); - mesh.set_attribute(Mesh::ATTRIBUTE_UV_0, uvs); + mesh.set_attribute(Self::ATTRIBUTE_POSITION, vertices); + mesh.set_attribute(Self::ATTRIBUTE_NORMAL, normals); + mesh.set_attribute(Self::ATTRIBUTE_UV_0, uvs); mesh } } diff --git a/crates/bevy_render/src/render_component.rs b/crates/bevy_render/src/render_component.rs index 35774683f74c1..a8e13a82475f5 100644 --- a/crates/bevy_render/src/render_component.rs +++ b/crates/bevy_render/src/render_component.rs @@ -153,7 +153,7 @@ where } impl ExtractComponent for Handle { - type Query = Read>; + type Query = Read; type Filter = (); #[inline] diff --git a/crates/bevy_render/src/render_graph/context.rs b/crates/bevy_render/src/render_graph/context.rs index ec300ac25eb22..a35928d4e9d2b 100644 --- a/crates/bevy_render/src/render_graph/context.rs +++ b/crates/bevy_render/src/render_graph/context.rs @@ -48,17 +48,17 @@ impl<'a> RenderGraphContext<'a> { /// Returns the input slot values for the node. #[inline] - pub fn inputs(&self) -> &[SlotValue] { + pub const fn inputs(&self) -> &[SlotValue] { self.inputs } /// Returns the [`SlotInfos`] of the inputs. - pub fn input_info(&self) -> &SlotInfos { + pub const fn input_info(&self) -> &SlotInfos { &self.node.input_slots } /// Returns the [`SlotInfos`] of the outputs. - pub fn output_info(&self) -> &SlotInfos { + pub const fn output_info(&self) -> &SlotInfos { &self.node.output_slots } diff --git a/crates/bevy_render/src/render_graph/edge.rs b/crates/bevy_render/src/render_graph/edge.rs index bfb05eb04bf3c..93749c074b3ea 100644 --- a/crates/bevy_render/src/render_graph/edge.rs +++ b/crates/bevy_render/src/render_graph/edge.rs @@ -33,18 +33,18 @@ pub enum Edge { impl Edge { /// Returns the id of the `input_node`. - pub fn get_input_node(&self) -> NodeId { + pub const fn get_input_node(&self) -> NodeId { match self { - Edge::SlotEdge { input_node, .. } => *input_node, - Edge::NodeEdge { input_node, .. } => *input_node, + Self::SlotEdge { input_node, .. } => *input_node, + Self::NodeEdge { input_node, .. } => *input_node, } } /// Returns the id of the `output_node`. - pub fn get_output_node(&self) -> NodeId { + pub const fn get_output_node(&self) -> NodeId { match self { - Edge::SlotEdge { output_node, .. } => *output_node, - Edge::NodeEdge { output_node, .. } => *output_node, + Self::SlotEdge { output_node, .. } => *output_node, + Self::NodeEdge { output_node, .. } => *output_node, } } } diff --git a/crates/bevy_render/src/render_graph/graph.rs b/crates/bevy_render/src/render_graph/graph.rs index fe4ded9fe767a..7fd7ba8e05485 100644 --- a/crates/bevy_render/src/render_graph/graph.rs +++ b/crates/bevy_render/src/render_graph/graph.rs @@ -319,14 +319,14 @@ impl RenderGraph { } /// Returns an iterator over the sub graphs. - pub fn iter_sub_graphs(&self) -> impl Iterator { + pub fn iter_sub_graphs(&self) -> impl Iterator { self.sub_graphs .iter() .map(|(name, graph)| (name.as_ref(), graph)) } /// Returns an iterator over the sub graphs, that allows modifying each value. - pub fn iter_sub_graphs_mut(&mut self) -> impl Iterator { + pub fn iter_sub_graphs_mut(&mut self) -> impl Iterator { self.sub_graphs .iter_mut() .map(|(name, graph)| (name.as_ref(), graph)) @@ -366,17 +366,17 @@ impl RenderGraph { /// Adds the `sub_graph` with the `name` to the graph. /// If the name is already present replaces it instead. - pub fn add_sub_graph(&mut self, name: impl Into>, sub_graph: RenderGraph) { + pub fn add_sub_graph(&mut self, name: impl Into>, sub_graph: Self) { self.sub_graphs.insert(name.into(), sub_graph); } /// Retrieves the sub graph corresponding to the `name`. - pub fn get_sub_graph(&self, name: impl AsRef) -> Option<&RenderGraph> { + pub fn get_sub_graph(&self, name: impl AsRef) -> Option<&Self> { self.sub_graphs.get(name.as_ref()) } /// Retrieves the sub graph corresponding to the `name` mutably. - pub fn get_sub_graph_mut(&mut self, name: impl AsRef) -> Option<&mut RenderGraph> { + pub fn get_sub_graph_mut(&mut self, name: impl AsRef) -> Option<&mut Self> { self.sub_graphs.get_mut(name.as_ref()) } } diff --git a/crates/bevy_render/src/render_graph/node.rs b/crates/bevy_render/src/render_graph/node.rs index eaaead9b0377c..d3392262eb865 100644 --- a/crates/bevy_render/src/render_graph/node.rs +++ b/crates/bevy_render/src/render_graph/node.rs @@ -21,10 +21,10 @@ pub struct NodeId(Uuid); impl NodeId { #[allow(clippy::new_without_default)] pub fn new() -> Self { - NodeId(Uuid::new_v4()) + Self(Uuid::new_v4()) } - pub fn uuid(&self) -> &Uuid { + pub const fn uuid(&self) -> &Uuid { &self.0 } } @@ -182,7 +182,7 @@ impl NodeState { where T: Node, { - NodeState { + Self { id, name: None, input_slots: node.input().into(), @@ -244,27 +244,27 @@ pub enum NodeLabel { Name(Cow<'static, str>), } -impl From<&NodeLabel> for NodeLabel { - fn from(value: &NodeLabel) -> Self { +impl From<&Self> for NodeLabel { + fn from(value: &Self) -> Self { value.clone() } } impl From for NodeLabel { fn from(value: String) -> Self { - NodeLabel::Name(value.into()) + Self::Name(value.into()) } } impl From<&'static str> for NodeLabel { fn from(value: &'static str) -> Self { - NodeLabel::Name(value.into()) + Self::Name(value.into()) } } impl From for NodeLabel { fn from(value: NodeId) -> Self { - NodeLabel::Id(value) + Self::Id(value) } } diff --git a/crates/bevy_render/src/render_graph/node_slot.rs b/crates/bevy_render/src/render_graph/node_slot.rs index 471322c0db9c7..f93858ddd0f3e 100644 --- a/crates/bevy_render/src/render_graph/node_slot.rs +++ b/crates/bevy_render/src/render_graph/node_slot.rs @@ -24,37 +24,37 @@ pub enum SlotValue { impl SlotValue { /// Returns the [`SlotType`] of this value. - pub fn slot_type(&self) -> SlotType { + pub const fn slot_type(&self) -> SlotType { match self { - SlotValue::Buffer(_) => SlotType::Buffer, - SlotValue::TextureView(_) => SlotType::TextureView, - SlotValue::Sampler(_) => SlotType::Sampler, - SlotValue::Entity(_) => SlotType::Entity, + Self::Buffer(_) => SlotType::Buffer, + Self::TextureView(_) => SlotType::TextureView, + Self::Sampler(_) => SlotType::Sampler, + Self::Entity(_) => SlotType::Entity, } } } impl From for SlotValue { fn from(value: Buffer) -> Self { - SlotValue::Buffer(value) + Self::Buffer(value) } } impl From for SlotValue { fn from(value: TextureView) -> Self { - SlotValue::TextureView(value) + Self::TextureView(value) } } impl From for SlotValue { fn from(value: Sampler) -> Self { - SlotValue::Sampler(value) + Self::Sampler(value) } } impl From for SlotValue { fn from(value: Entity) -> Self { - SlotValue::Entity(value) + Self::Entity(value) } } @@ -82,33 +82,33 @@ pub enum SlotLabel { Name(Cow<'static, str>), } -impl From<&SlotLabel> for SlotLabel { - fn from(value: &SlotLabel) -> Self { +impl From<&Self> for SlotLabel { + fn from(value: &Self) -> Self { value.clone() } } impl From for SlotLabel { fn from(value: String) -> Self { - SlotLabel::Name(value.into()) + Self::Name(value.into()) } } impl From<&'static str> for SlotLabel { fn from(value: &'static str) -> Self { - SlotLabel::Name(value.into()) + Self::Name(value.into()) } } impl From> for SlotLabel { fn from(value: Cow<'static, str>) -> Self { - SlotLabel::Name(value.clone()) + Self::Name(value.clone()) } } impl From for SlotLabel { fn from(value: usize) -> Self { - SlotLabel::Index(value) + Self::Index(value) } } @@ -121,7 +121,7 @@ pub struct SlotInfo { impl SlotInfo { pub fn new(name: impl Into>, slot_type: SlotType) -> Self { - SlotInfo { + Self { name: name.into(), slot_type, } @@ -137,7 +137,7 @@ pub struct SlotInfos { impl> From for SlotInfos { fn from(slots: T) -> Self { - SlotInfos { + Self { slots: slots.into_iter().collect(), } } diff --git a/crates/bevy_render/src/render_phase/draw.rs b/crates/bevy_render/src/render_phase/draw.rs index b21e65e468a90..036bfe3274a83 100644 --- a/crates/bevy_render/src/render_phase/draw.rs +++ b/crates/bevy_render/src/render_phase/draw.rs @@ -233,12 +233,13 @@ impl RenderCommand

for SetItemPipeline { pipeline_cache: SystemParamItem<'w, '_, Self::Param>, pass: &mut TrackedRenderPass<'w>, ) -> RenderCommandResult { - if let Some(pipeline) = pipeline_cache.into_inner().get(item.cached_pipeline()) { - pass.set_render_pipeline(pipeline); - RenderCommandResult::Success - } else { - RenderCommandResult::Failure - } + pipeline_cache + .into_inner() + .get(item.cached_pipeline()) + .map_or(RenderCommandResult::Failure, |pipeline| { + pass.set_render_pipeline(pipeline); + RenderCommandResult::Success + }) } } diff --git a/crates/bevy_render/src/render_phase/draw_state.rs b/crates/bevy_render/src/render_phase/draw_state.rs index ec17b2902ab9d..2d0fbb5be52c2 100644 --- a/crates/bevy_render/src/render_phase/draw_state.rs +++ b/crates/bevy_render/src/render_phase/draw_state.rs @@ -39,11 +39,11 @@ impl DrawState { bind_group: BindGroupId, dynamic_indices: &[u32], ) -> bool { - if let Some(current_bind_group) = self.bind_groups.get(index) { - current_bind_group.0 == Some(bind_group) && dynamic_indices == current_bind_group.1 - } else { - false - } + self.bind_groups + .get(index) + .map_or(false, |current_bind_group| { + current_bind_group.0 == Some(bind_group) && dynamic_indices == current_bind_group.1 + }) } pub fn set_vertex_buffer(&mut self, index: usize, buffer: BufferId, offset: u64) { @@ -54,11 +54,9 @@ impl DrawState { } pub fn is_vertex_buffer_set(&self, index: usize, buffer: BufferId, offset: u64) -> bool { - if let Some(current) = self.vertex_buffers.get(index) { - *current == Some((buffer, offset)) - } else { - false - } + self.vertex_buffers + .get(index) + .map_or(false, |current| *current == Some((buffer, offset))) } pub fn set_index_buffer(&mut self, buffer: BufferId, offset: u64, index_format: IndexFormat) { diff --git a/crates/bevy_render/src/render_resource/bind_group.rs b/crates/bevy_render/src/render_resource/bind_group.rs index 6ee9633c2b0ec..0c449f25e123d 100644 --- a/crates/bevy_render/src/render_resource/bind_group.rs +++ b/crates/bevy_render/src/render_resource/bind_group.rs @@ -20,14 +20,14 @@ pub struct BindGroup { impl BindGroup { /// Returns the [`BindGroupId`]. #[inline] - pub fn id(&self) -> BindGroupId { + pub const fn id(&self) -> BindGroupId { self.id } } impl From for BindGroup { fn from(value: wgpu::BindGroup) -> Self { - BindGroup { + Self { id: BindGroupId(Uuid::new_v4()), value: Arc::new(value), } diff --git a/crates/bevy_render/src/render_resource/bind_group_layout.rs b/crates/bevy_render/src/render_resource/bind_group_layout.rs index d17d639c3a77f..ded5efc1e23b5 100644 --- a/crates/bevy_render/src/render_resource/bind_group_layout.rs +++ b/crates/bevy_render/src/render_resource/bind_group_layout.rs @@ -12,7 +12,7 @@ pub struct BindGroupLayout { impl BindGroupLayout { #[inline] - pub fn id(&self) -> BindGroupLayoutId { + pub const fn id(&self) -> BindGroupLayoutId { self.id } @@ -24,7 +24,7 @@ impl BindGroupLayout { impl From for BindGroupLayout { fn from(value: wgpu::BindGroupLayout) -> Self { - BindGroupLayout { + Self { id: BindGroupLayoutId(Uuid::new_v4()), value: Arc::new(value), } diff --git a/crates/bevy_render/src/render_resource/buffer.rs b/crates/bevy_render/src/render_resource/buffer.rs index a902af5834975..b13b52797ab0f 100644 --- a/crates/bevy_render/src/render_resource/buffer.rs +++ b/crates/bevy_render/src/render_resource/buffer.rs @@ -15,7 +15,7 @@ pub struct Buffer { impl Buffer { #[inline] - pub fn id(&self) -> BufferId { + pub const fn id(&self) -> BufferId { self.id } @@ -40,7 +40,7 @@ impl Buffer { impl From for Buffer { fn from(value: wgpu::Buffer) -> Self { - Buffer { + Self { id: BufferId(Uuid::new_v4()), value: Arc::new(value), } @@ -65,12 +65,12 @@ pub struct BufferSlice<'a> { impl<'a> BufferSlice<'a> { #[inline] - pub fn id(&self) -> BufferId { + pub const fn id(&self) -> BufferId { self.id } #[inline] - pub fn offset(&self) -> wgpu::BufferAddress { + pub const fn offset(&self) -> wgpu::BufferAddress { self.offset } } diff --git a/crates/bevy_render/src/render_resource/pipeline.rs b/crates/bevy_render/src/render_resource/pipeline.rs index adeab97652715..b26e0c082c67b 100644 --- a/crates/bevy_render/src/render_resource/pipeline.rs +++ b/crates/bevy_render/src/render_resource/pipeline.rs @@ -23,14 +23,14 @@ pub struct RenderPipeline { impl RenderPipeline { #[inline] - pub fn id(&self) -> RenderPipelineId { + pub const fn id(&self) -> RenderPipelineId { self.id } } impl From for RenderPipeline { fn from(value: wgpu::RenderPipeline) -> Self { - RenderPipeline { + Self { id: RenderPipelineId(Uuid::new_v4()), value: Arc::new(value), } @@ -63,14 +63,14 @@ pub struct ComputePipeline { impl ComputePipeline { /// Returns the [`ComputePipelineId`]. #[inline] - pub fn id(&self) -> ComputePipelineId { + pub const fn id(&self) -> ComputePipelineId { self.id } } impl From for ComputePipeline { fn from(value: wgpu::ComputePipeline) -> Self { - ComputePipeline { + Self { id: ComputePipelineId(Uuid::new_v4()), value: Arc::new(value), } diff --git a/crates/bevy_render/src/render_resource/pipeline_cache.rs b/crates/bevy_render/src/render_resource/pipeline_cache.rs index e5fcede3cbec9..9cbb075cf3c6f 100644 --- a/crates/bevy_render/src/render_resource/pipeline_cache.rs +++ b/crates/bevy_render/src/render_resource/pipeline_cache.rs @@ -29,7 +29,7 @@ pub struct ShaderData { pub struct CachedPipelineId(usize); impl CachedPipelineId { - pub const INVALID: Self = CachedPipelineId(usize::MAX); + pub const INVALID: Self = Self(usize::MAX); } #[derive(Default)] diff --git a/crates/bevy_render/src/render_resource/shader.rs b/crates/bevy_render/src/render_resource/shader.rs index 7f71488aef379..e8e955d47ceeb 100644 --- a/crates/bevy_render/src/render_resource/shader.rs +++ b/crates/bevy_render/src/render_resource/shader.rs @@ -17,7 +17,7 @@ pub struct ShaderId(Uuid); impl ShaderId { #[allow(clippy::new_without_default)] pub fn new() -> Self { - ShaderId(Uuid::new_v4()) + Self(Uuid::new_v4()) } } @@ -43,26 +43,26 @@ pub struct Shader { } impl Shader { - pub fn from_wgsl(source: impl Into>) -> Shader { + pub fn from_wgsl(source: impl Into>) -> Self { let source = source.into(); - Shader { + Self { imports: SHADER_IMPORT_PROCESSOR.get_imports_from_str(&source), source: Source::Wgsl(source), import_path: None, } } - pub fn from_glsl(source: impl Into>, stage: naga::ShaderStage) -> Shader { + pub fn from_glsl(source: impl Into>, stage: naga::ShaderStage) -> Self { let source = source.into(); - Shader { + Self { imports: SHADER_IMPORT_PROCESSOR.get_imports_from_str(&source), source: Source::Glsl(source, stage), import_path: None, } } - pub fn from_spirv(source: impl Into>) -> Shader { - Shader { + pub fn from_spirv(source: impl Into>) -> Self { + Self { imports: Vec::new(), source: Source::SpirV(source.into()), import_path: None, @@ -79,7 +79,7 @@ impl Shader { } #[inline] - pub fn import_path(&self) -> Option<&ShaderImport> { + pub const fn import_path(&self) -> Option<&ShaderImport> { self.import_path.as_ref() } @@ -374,10 +374,11 @@ impl ShaderProcessor { let def = cap.get(1).unwrap(); scopes.push(*scopes.last().unwrap() && !shader_defs_unique.contains(def.as_str())); } else if self.else_regex.is_match(line) { - let mut is_parent_scope_truthy = true; - if scopes.len() > 1 { - is_parent_scope_truthy = scopes[scopes.len() - 2]; - } + let is_parent_scope_truthy = if scopes.len() > 1 { + scopes[scopes.len() - 2] + } else { + true + }; if let Some(last) = scopes.last_mut() { *last = is_parent_scope_truthy && !*last; } diff --git a/crates/bevy_render/src/render_resource/texture.rs b/crates/bevy_render/src/render_resource/texture.rs index 4a7d582d7559e..d7630a709966c 100644 --- a/crates/bevy_render/src/render_resource/texture.rs +++ b/crates/bevy_render/src/render_resource/texture.rs @@ -18,7 +18,7 @@ pub struct Texture { impl Texture { /// Returns the [`TextureId`]. #[inline] - pub fn id(&self) -> TextureId { + pub const fn id(&self) -> TextureId { self.id } @@ -30,7 +30,7 @@ impl Texture { impl From for Texture { fn from(value: wgpu::Texture) -> Self { - Texture { + Self { id: TextureId(Uuid::new_v4()), value: Arc::new(value), } @@ -80,7 +80,7 @@ pub struct TextureView { impl TextureView { /// Returns the [`TextureViewId`]. #[inline] - pub fn id(&self) -> TextureViewId { + pub const fn id(&self) -> TextureViewId { self.id } @@ -96,7 +96,7 @@ impl TextureView { impl From for TextureView { fn from(value: wgpu::TextureView) -> Self { - TextureView { + Self { id: TextureViewId(Uuid::new_v4()), value: TextureViewValue::TextureView(Arc::new(value)), } @@ -108,7 +108,7 @@ impl From for TextureView { let texture = Arc::new(value); let view = Arc::new(texture.texture.create_view(&Default::default())); - TextureView { + Self { id: TextureViewId(Uuid::new_v4()), value: TextureViewValue::SurfaceTexture { texture, view }, } @@ -145,14 +145,14 @@ pub struct Sampler { impl Sampler { /// Returns the [`SamplerId`]. #[inline] - pub fn id(&self) -> SamplerId { + pub const fn id(&self) -> SamplerId { self.id } } impl From for Sampler { fn from(value: wgpu::Sampler) -> Self { - Sampler { + Self { id: SamplerId(Uuid::new_v4()), value: Arc::new(value), } diff --git a/crates/bevy_render/src/renderer/graph_runner.rs b/crates/bevy_render/src/renderer/graph_runner.rs index 5df63dd3ad88c..09a7056d76e4f 100644 --- a/crates/bevy_render/src/renderer/graph_runner.rs +++ b/crates/bevy_render/src/renderer/graph_runner.rs @@ -77,11 +77,10 @@ impl RenderGraphRunner { ) -> Result<(), RenderGraphRunnerError> { let mut node_outputs: HashMap> = HashMap::default(); #[cfg(feature = "trace")] - let span = if let Some(name) = &graph_name { - info_span!("run_graph", name = name.deref()) - } else { - info_span!("run_graph", name = "main_graph") - }; + let span = graph_name.as_ref().map_or_else( + || info_span!("run_graph", name = "main_graph"), + |name| info_span!("run_graph", name = name.deref()), + ); #[cfg(feature = "trace")] let _guard = span.enter(); diff --git a/crates/bevy_render/src/renderer/render_device.rs b/crates/bevy_render/src/renderer/render_device.rs index 9135498bb05a4..004947f0c5ce9 100644 --- a/crates/bevy_render/src/renderer/render_device.rs +++ b/crates/bevy_render/src/renderer/render_device.rs @@ -160,7 +160,7 @@ impl RenderDevice { } } - pub fn align_copy_bytes_per_row(row_bytes: usize) -> usize { + pub const fn align_copy_bytes_per_row(row_bytes: usize) -> usize { let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize; let padded_bytes_per_row_padding = (align - row_bytes % align) % align; row_bytes + padded_bytes_per_row_padding diff --git a/crates/bevy_render/src/texture/image.rs b/crates/bevy_render/src/texture/image.rs index f6d3dfd4bb095..6bccba4fc71ae 100644 --- a/crates/bevy_render/src/texture/image.rs +++ b/crates/bevy_render/src/texture/image.rs @@ -33,7 +33,7 @@ impl Default for Image { fn default() -> Self { let format = wgpu::TextureFormat::bevy_default(); let data = vec![255; format.pixel_size() as usize]; - Image { + Self { data, texture_descriptor: wgpu::TextureDescriptor { size: wgpu::Extent3d { @@ -92,7 +92,7 @@ impl Image { pixel: &[u8], format: TextureFormat, ) -> Self { - let mut value = Image::default(); + let mut value = Self::default(); value.texture_descriptor.format = format; value.texture_descriptor.dimension = dimension; value.resize(size); @@ -190,7 +190,7 @@ impl Image { /// Load a bytes buffer in a [`Image`], according to type `image_type`, using the `image` /// crate - pub fn from_buffer(buffer: &[u8], image_type: ImageType) -> Result { + pub fn from_buffer(buffer: &[u8], image_type: ImageType) -> Result { let format = match image_type { ImageType::MimeType(mime_type) => match mime_type { "image/png" => Ok(image::ImageFormat::Png), @@ -384,7 +384,7 @@ pub struct GpuImage { } impl RenderAsset for Image { - type ExtractedAsset = Image; + type ExtractedAsset = Self; type PreparedAsset = GpuImage; type Param = (SRes, SRes); diff --git a/crates/bevy_render/src/texture/mod.rs b/crates/bevy_render/src/texture/mod.rs index e6658195bff54..132f00b3b8704 100644 --- a/crates/bevy_render/src/texture/mod.rs +++ b/crates/bevy_render/src/texture/mod.rs @@ -51,9 +51,9 @@ impl BevyDefault for wgpu::TextureFormat { fn bevy_default() -> Self { if cfg!(target_os = "android") || cfg!(target_arch = "wasm32") { // Bgra8UnormSrgb texture missing on some Android devices - wgpu::TextureFormat::Rgba8UnormSrgb + Self::Rgba8UnormSrgb } else { - wgpu::TextureFormat::Bgra8UnormSrgb + Self::Bgra8UnormSrgb } } } diff --git a/crates/bevy_render/src/view/mod.rs b/crates/bevy_render/src/view/mod.rs index 40e5dbb335913..2bfc30d294e40 100644 --- a/crates/bevy_render/src/view/mod.rs +++ b/crates/bevy_render/src/view/mod.rs @@ -114,11 +114,10 @@ pub struct ViewTarget { impl ViewTarget { pub fn get_color_attachment(&self, ops: Operations) -> RenderPassColorAttachment { RenderPassColorAttachment { - view: if let Some(sampled_target) = &self.sampled_target { - sampled_target - } else { - &self.view - }, + view: self + .sampled_target + .as_ref() + .map_or(&self.view, |sampled_target| sampled_target), resolve_target: if self.sampled_target.is_some() { Some(&self.view) } else { diff --git a/crates/bevy_render/src/view/visibility/render_layers.rs b/crates/bevy_render/src/view/visibility/render_layers.rs index 59cc40e41cd0e..bad6ff48afb1c 100644 --- a/crates/bevy_render/src/view/visibility/render_layers.rs +++ b/crates/bevy_render/src/view/visibility/render_layers.rs @@ -40,7 +40,7 @@ impl std::iter::FromIterator for RenderLayers { /// Defaults to containing to layer `0`, the first layer. impl Default for RenderLayers { fn default() -> Self { - RenderLayers::layer(0) + Self::layer(0) } } @@ -50,17 +50,17 @@ impl RenderLayers { /// Create a new `RenderLayers` belonging to the given layer. pub fn layer(n: Layer) -> Self { - RenderLayers(0).with(n) + Self(0).with(n) } /// Create a new `RenderLayers` that belongs to all layers. - pub fn all() -> Self { - RenderLayers(u32::MAX) + pub const fn all() -> Self { + Self(u32::MAX) } /// Create a new `RenderLayers` that belongs to no layers. - pub fn none() -> Self { - RenderLayers(0) + pub const fn none() -> Self { + Self(0) } /// Create a `RenderLayers` from a list of layers. @@ -95,7 +95,7 @@ impl RenderLayers { pub fn iter(&self) -> impl Iterator { let total: Layer = std::convert::TryInto::try_into(Self::TOTAL_LAYERS).unwrap(); let mask = *self; - (0..total).filter(move |g| RenderLayers::layer(*g).intersects(&mask)) + (0..total).filter(move |g| Self::layer(*g).intersects(&mask)) } /// Determine if a `RenderLayers` intersects another. @@ -104,7 +104,7 @@ impl RenderLayers { /// /// A `RenderLayers` with no layers will not match any other /// `RenderLayers`, even another with no layers. - pub fn intersects(&self, other: &RenderLayers) -> bool { + pub const fn intersects(&self, other: &Self) -> bool { (self.0 & other.0) > 0 } } diff --git a/crates/bevy_scene/src/dynamic_scene.rs b/crates/bevy_scene/src/dynamic_scene.rs index ab15cbd61dbdd..22c4ffe5e614d 100644 --- a/crates/bevy_scene/src/dynamic_scene.rs +++ b/crates/bevy_scene/src/dynamic_scene.rs @@ -32,7 +32,7 @@ impl DynamicScene { /// Create a new dynamic scene from a given world. pub fn from_world(world: &World, type_registry: &TypeRegistryArc) -> Self { - let mut scene = DynamicScene::default(); + let mut scene = Self::default(); let type_registry = type_registry.read(); for archetype in world.archetypes().iter() { diff --git a/crates/bevy_scene/src/scene.rs b/crates/bevy_scene/src/scene.rs index 0a8bd50b82492..4333fa0f28f40 100644 --- a/crates/bevy_scene/src/scene.rs +++ b/crates/bevy_scene/src/scene.rs @@ -8,7 +8,7 @@ pub struct Scene { } impl Scene { - pub fn new(world: World) -> Self { + pub const fn new(world: World) -> Self { Self { world } } } diff --git a/crates/bevy_scene/src/scene_loader.rs b/crates/bevy_scene/src/scene_loader.rs index 06c7fb9192cf0..30dded075b8c1 100644 --- a/crates/bevy_scene/src/scene_loader.rs +++ b/crates/bevy_scene/src/scene_loader.rs @@ -14,7 +14,7 @@ pub struct SceneLoader { impl FromWorld for SceneLoader { fn from_world(world: &mut World) -> Self { let type_registry = world.get_resource::().unwrap(); - SceneLoader { + Self { type_registry: (&*type_registry).clone(), } } diff --git a/crates/bevy_scene/src/scene_spawner.rs b/crates/bevy_scene/src/scene_spawner.rs index 7015195757d79..c951c474b3cb5 100644 --- a/crates/bevy_scene/src/scene_spawner.rs +++ b/crates/bevy_scene/src/scene_spawner.rs @@ -23,7 +23,7 @@ pub struct InstanceId(Uuid); impl InstanceId { fn new() -> Self { - InstanceId(Uuid::new_v4()) + Self(Uuid::new_v4()) } } diff --git a/crates/bevy_scene/src/serde.rs b/crates/bevy_scene/src/serde.rs index 38af61851033f..a90d1f0ead50c 100644 --- a/crates/bevy_scene/src/serde.rs +++ b/crates/bevy_scene/src/serde.rs @@ -16,7 +16,7 @@ pub struct SceneSerializer<'a> { } impl<'a> SceneSerializer<'a> { - pub fn new(scene: &'a DynamicScene, registry: &'a TypeRegistryArc) -> Self { + pub const fn new(scene: &'a DynamicScene, registry: &'a TypeRegistryArc) -> Self { SceneSerializer { scene, registry } } } diff --git a/crates/bevy_sprite/src/dynamic_texture_atlas_builder.rs b/crates/bevy_sprite/src/dynamic_texture_atlas_builder.rs index 2cdf99a1710f2..f02c6e6da7f98 100644 --- a/crates/bevy_sprite/src/dynamic_texture_atlas_builder.rs +++ b/crates/bevy_sprite/src/dynamic_texture_atlas_builder.rs @@ -88,7 +88,7 @@ impl DynamicTextureAtlasBuilder { impl From for Rect { fn from(rectangle: guillotiere::Rectangle) -> Self { - Rect { + Self { min: Vec2::new(rectangle.min.x as f32, rectangle.min.y as f32), max: Vec2::new(rectangle.max.x as f32, rectangle.max.y as f32), } diff --git a/crates/bevy_sprite/src/mesh2d/color_material.rs b/crates/bevy_sprite/src/mesh2d/color_material.rs index eed38c3f14a1f..a8b0210885ce5 100644 --- a/crates/bevy_sprite/src/mesh2d/color_material.rs +++ b/crates/bevy_sprite/src/mesh2d/color_material.rs @@ -56,7 +56,7 @@ pub struct ColorMaterial { impl Default for ColorMaterial { fn default() -> Self { - ColorMaterial { + Self { color: Color::rgb(1.0, 0.0, 1.0), texture: None, } @@ -65,7 +65,7 @@ impl Default for ColorMaterial { impl From for ColorMaterial { fn from(color: Color) -> Self { - ColorMaterial { + Self { color, ..Default::default() } @@ -74,7 +74,7 @@ impl From for ColorMaterial { impl From> for ColorMaterial { fn from(texture: Handle) -> Self { - ColorMaterial { + Self { texture: Some(texture), color: Color::WHITE, } @@ -111,11 +111,11 @@ pub struct GpuColorMaterial { } impl RenderAsset for ColorMaterial { - type ExtractedAsset = ColorMaterial; + type ExtractedAsset = Self; type PreparedAsset = GpuColorMaterial; type Param = ( SRes, - SRes>, + SRes>, SRes>, ); diff --git a/crates/bevy_sprite/src/mesh2d/material.rs b/crates/bevy_sprite/src/mesh2d/material.rs index 0e3ceaae55cc0..2bea2fedb378e 100644 --- a/crates/bevy_sprite/src/mesh2d/material.rs +++ b/crates/bevy_sprite/src/mesh2d/material.rs @@ -215,7 +215,7 @@ impl FromWorld for Material2dPipeline { let render_device = world.get_resource::().unwrap(); let material2d_layout = M::bind_group_layout(render_device); - Material2dPipeline { + Self { mesh2d_pipeline: world.get_resource::().unwrap().clone(), material2d_layout, vertex_shader: M::vertex_shader(asset_server), diff --git a/crates/bevy_sprite/src/mesh2d/mesh.rs b/crates/bevy_sprite/src/mesh2d/mesh.rs index 7468990b47ea8..4ff6cc45e8a7d 100644 --- a/crates/bevy_sprite/src/mesh2d/mesh.rs +++ b/crates/bevy_sprite/src/mesh2d/mesh.rs @@ -201,7 +201,7 @@ impl FromWorld for Mesh2dPipeline { ), } }; - Mesh2dPipeline { + Self { view_layout, mesh_layout, dummy_white_gpu_image, @@ -235,8 +235,8 @@ bitflags::bitflags! { pub struct Mesh2dPipelineKey: u32 { const NONE = 0; const VERTEX_TANGENTS = (1 << 0); - const MSAA_RESERVED_BITS = Mesh2dPipelineKey::MSAA_MASK_BITS << Mesh2dPipelineKey::MSAA_SHIFT_BITS; - const PRIMITIVE_TOPOLOGY_RESERVED_BITS = Mesh2dPipelineKey::PRIMITIVE_TOPOLOGY_MASK_BITS << Mesh2dPipelineKey::PRIMITIVE_TOPOLOGY_SHIFT_BITS; + const MSAA_RESERVED_BITS = Self::MSAA_MASK_BITS << Self::MSAA_SHIFT_BITS; + const PRIMITIVE_TOPOLOGY_RESERVED_BITS = Self::PRIMITIVE_TOPOLOGY_MASK_BITS << Self::PRIMITIVE_TOPOLOGY_SHIFT_BITS; } } @@ -248,10 +248,10 @@ impl Mesh2dPipelineKey { pub fn from_msaa_samples(msaa_samples: u32) -> Self { let msaa_bits = ((msaa_samples - 1) & Self::MSAA_MASK_BITS) << Self::MSAA_SHIFT_BITS; - Mesh2dPipelineKey::from_bits(msaa_bits).unwrap() + Self::from_bits(msaa_bits).unwrap() } - pub fn msaa_samples(&self) -> u32 { + pub const fn msaa_samples(&self) -> u32 { ((self.bits >> Self::MSAA_SHIFT_BITS) & Self::MSAA_MASK_BITS) + 1 } @@ -259,7 +259,7 @@ impl Mesh2dPipelineKey { let primitive_topology_bits = ((primitive_topology as u32) & Self::PRIMITIVE_TOPOLOGY_MASK_BITS) << Self::PRIMITIVE_TOPOLOGY_SHIFT_BITS; - Mesh2dPipelineKey::from_bits(primitive_topology_bits).unwrap() + Self::from_bits(primitive_topology_bits).unwrap() } pub fn primitive_topology(&self) -> PrimitiveTopology { @@ -491,24 +491,25 @@ impl EntityRenderCommand for DrawMesh2d { pass: &mut TrackedRenderPass<'w>, ) -> RenderCommandResult { let mesh_handle = &mesh2d_query.get(item).unwrap().0; - if let Some(gpu_mesh) = meshes.into_inner().get(mesh_handle) { - pass.set_vertex_buffer(0, gpu_mesh.vertex_buffer.slice(..)); - match &gpu_mesh.buffer_info { - GpuBufferInfo::Indexed { - buffer, - index_format, - count, - } => { - pass.set_index_buffer(buffer.slice(..), 0, *index_format); - pass.draw_indexed(0..*count, 0, 0..1); + meshes + .into_inner() + .get(mesh_handle) + .map_or(RenderCommandResult::Failure, |gpu_mesh| { + pass.set_vertex_buffer(0, gpu_mesh.vertex_buffer.slice(..)); + match &gpu_mesh.buffer_info { + GpuBufferInfo::Indexed { + buffer, + index_format, + count, + } => { + pass.set_index_buffer(buffer.slice(..), 0, *index_format); + pass.draw_indexed(0..*count, 0, 0..1); + } + GpuBufferInfo::NonIndexed { vertex_count } => { + pass.draw(0..*vertex_count, 0..1); + } } - GpuBufferInfo::NonIndexed { vertex_count } => { - pass.draw(0..*vertex_count, 0..1); - } - } - RenderCommandResult::Success - } else { - RenderCommandResult::Failure - } + RenderCommandResult::Success + }) } } diff --git a/crates/bevy_sprite/src/render/mod.rs b/crates/bevy_sprite/src/render/mod.rs index f4d0f035a98bb..cecec21a1eea6 100644 --- a/crates/bevy_sprite/src/render/mod.rs +++ b/crates/bevy_sprite/src/render/mod.rs @@ -77,7 +77,7 @@ impl FromWorld for SpritePipeline { label: Some("sprite_material_layout"), }); - SpritePipeline { + Self { view_layout, material_layout, } @@ -91,7 +91,7 @@ bitflags::bitflags! { pub struct SpritePipelineKey: u32 { const NONE = 0; const COLORED = (1 << 0); - const MSAA_RESERVED_BITS = SpritePipelineKey::MSAA_MASK_BITS << SpritePipelineKey::MSAA_SHIFT_BITS; + const MSAA_RESERVED_BITS = Self::MSAA_MASK_BITS << Self::MSAA_SHIFT_BITS; } } @@ -101,7 +101,7 @@ impl SpritePipelineKey { pub fn from_msaa_samples(msaa_samples: u32) -> Self { let msaa_bits = ((msaa_samples - 1) & Self::MSAA_MASK_BITS) << Self::MSAA_SHIFT_BITS; - SpritePipelineKey::from_bits(msaa_bits).unwrap() + Self::from_bits(msaa_bits).unwrap() } pub fn msaa_samples(&self) -> u32 { diff --git a/crates/bevy_sprite/src/texture_atlas.rs b/crates/bevy_sprite/src/texture_atlas.rs index 49d366fa64ff1..ca95148a74d48 100644 --- a/crates/bevy_sprite/src/texture_atlas.rs +++ b/crates/bevy_sprite/src/texture_atlas.rs @@ -68,12 +68,7 @@ impl TextureAtlas { /// Generate a `TextureAtlas` by splitting a texture into a grid where each /// cell of the grid of `tile_size` is one of the textures in the atlas - pub fn from_grid( - texture: Handle, - tile_size: Vec2, - columns: usize, - rows: usize, - ) -> TextureAtlas { + pub fn from_grid(texture: Handle, tile_size: Vec2, columns: usize, rows: usize) -> Self { Self::from_grid_with_padding(texture, tile_size, columns, rows, Vec2::new(0f32, 0f32)) } @@ -86,7 +81,7 @@ impl TextureAtlas { columns: usize, rows: usize, padding: Vec2, - ) -> TextureAtlas { + ) -> Self { let mut sprites = Vec::new(); let mut x_padding = 0.0; let mut y_padding = 0.0; @@ -112,7 +107,7 @@ impl TextureAtlas { } } - TextureAtlas { + Self { size: Vec2::new( ((tile_size.x + x_padding) * columns as f32) - x_padding, ((tile_size.y + y_padding) * rows as f32) - y_padding, diff --git a/crates/bevy_sprite/src/texture_atlas_builder.rs b/crates/bevy_sprite/src/texture_atlas_builder.rs index bb5d6ca5afcdd..2adcee20f17a8 100644 --- a/crates/bevy_sprite/src/texture_atlas_builder.rs +++ b/crates/bevy_sprite/src/texture_atlas_builder.rs @@ -55,25 +55,25 @@ pub type TextureAtlasBuilderResult = Result; impl TextureAtlasBuilder { /// Sets the initial size of the atlas in pixels. - pub fn initial_size(mut self, size: Vec2) -> Self { + pub const fn initial_size(mut self, size: Vec2) -> Self { self.initial_size = size; self } /// Sets the max size of the atlas in pixels. - pub fn max_size(mut self, size: Vec2) -> Self { + pub const fn max_size(mut self, size: Vec2) -> Self { self.max_size = size; self } /// Sets the texture format for textures in the atlas. - pub fn format(mut self, format: TextureFormat) -> Self { + pub const fn format(mut self, format: TextureFormat) -> Self { self.format = format; self } /// Control whether the added texture should be converted to the atlas format, if different. - pub fn auto_format_conversion(mut self, auto_format_conversion: bool) -> Self { + pub const fn auto_format_conversion(mut self, auto_format_conversion: bool) -> Self { self.auto_format_conversion = auto_format_conversion; self } diff --git a/crates/bevy_tasks/src/countdown_event.rs b/crates/bevy_tasks/src/countdown_event.rs index eceef9697cd1a..3dd9f1a96e2d4 100644 --- a/crates/bevy_tasks/src/countdown_event.rs +++ b/crates/bevy_tasks/src/countdown_event.rs @@ -29,7 +29,7 @@ impl CountdownEvent { counter: AtomicIsize::new(n), }; - CountdownEvent { + Self { inner: Arc::new(inner), } } diff --git a/crates/bevy_tasks/src/task_pool.rs b/crates/bevy_tasks/src/task_pool.rs index 4d50555f92f37..e074e26805cd3 100644 --- a/crates/bevy_tasks/src/task_pool.rs +++ b/crates/bevy_tasks/src/task_pool.rs @@ -31,13 +31,13 @@ impl TaskPoolBuilder { /// Override the number of threads created for the pool. If unset, we default to the number /// of logical cores of the system - pub fn num_threads(mut self, num_threads: usize) -> Self { + pub const fn num_threads(mut self, num_threads: usize) -> Self { self.num_threads = Some(num_threads); self } /// Override the stack size of the threads created for the pool - pub fn stack_size(mut self, stack_size: usize) -> Self { + pub const fn stack_size(mut self, stack_size: usize) -> Self { self.stack_size = Some(stack_size); self } @@ -120,11 +120,10 @@ impl TaskPool { let ex = Arc::clone(&executor); let shutdown_rx = shutdown_rx.clone(); - let thread_name = if let Some(thread_name) = thread_name { - format!("{} ({})", thread_name, i) - } else { - format!("TaskPool ({})", i) - }; + let thread_name = thread_name.map_or_else( + || format!("TaskPool ({})", i), + |thread_name| format!("{} ({})", thread_name, i), + ); let mut thread_builder = thread::Builder::new().name(thread_name); @@ -166,7 +165,7 @@ impl TaskPool { F: FnOnce(&mut Scope<'scope, T>) + 'scope + Send, T: Send + 'static, { - TaskPool::LOCAL_EXECUTOR.with(|local_executor| { + Self::LOCAL_EXECUTOR.with(|local_executor| { // SAFETY: This function blocks until all futures complete, so this future must return // before this function returns. However, rust has no way of knowing // this so we must convert to 'static here to appease the compiler as it is unable to @@ -247,7 +246,7 @@ impl TaskPool { where T: 'static, { - Task::new(TaskPool::LOCAL_EXECUTOR.with(|executor| executor.spawn(future))) + Task::new(Self::LOCAL_EXECUTOR.with(|executor| executor.spawn(future))) } } diff --git a/crates/bevy_text/src/font.rs b/crates/bevy_text/src/font.rs index fced2cbc1a046..f12e9d5ff889c 100644 --- a/crates/bevy_text/src/font.rs +++ b/crates/bevy_text/src/font.rs @@ -15,7 +15,7 @@ impl Font { pub fn try_from_bytes(font_data: Vec) -> Result { let font = FontVec::try_from_vec(font_data)?; let font = FontArc::new(font); - Ok(Font { font }) + Ok(Self { font }) } pub fn get_outlined_glyph_texture(outlined_glyph: OutlinedGlyph) -> Image { diff --git a/crates/bevy_text/src/font_atlas.rs b/crates/bevy_text/src/font_atlas.rs index be1903c121b36..77b5f37044413 100644 --- a/crates/bevy_text/src/font_atlas.rs +++ b/crates/bevy_text/src/font_atlas.rs @@ -50,7 +50,7 @@ impl FontAtlas { textures: &mut Assets, texture_atlases: &mut Assets, size: Vec2, - ) -> FontAtlas { + ) -> Self { let atlas_texture = textures.add(Image::new_fill( Extent3d { width: size.x as u32, diff --git a/crates/bevy_text/src/font_atlas_set.rs b/crates/bevy_text/src/font_atlas_set.rs index 29ede6cb53490..7941978ef668f 100644 --- a/crates/bevy_text/src/font_atlas_set.rs +++ b/crates/bevy_text/src/font_atlas_set.rs @@ -24,7 +24,7 @@ pub struct GlyphAtlasInfo { impl Default for FontAtlasSet { fn default() -> Self { - FontAtlasSet { + Self { font_atlases: HashMap::with_capacity_and_hasher(1, Default::default()), } } diff --git a/crates/bevy_text/src/glyph_brush.rs b/crates/bevy_text/src/glyph_brush.rs index fc9d5fffc76c5..37f8e9d9c8050 100644 --- a/crates/bevy_text/src/glyph_brush.rs +++ b/crates/bevy_text/src/glyph_brush.rs @@ -17,7 +17,7 @@ pub struct GlyphBrush { impl Default for GlyphBrush { fn default() -> Self { - GlyphBrush { + Self { fonts: Vec::new(), handles: Vec::new(), latest_font_id: FontId(0), @@ -156,7 +156,7 @@ impl GlyphPlacementAdjuster { } #[inline(always)] - pub fn position(&self, p: Vec2) -> Vec2 { + pub const fn position(&self, p: Vec2) -> Vec2 { p } } diff --git a/crates/bevy_text/src/pipeline.rs b/crates/bevy_text/src/pipeline.rs index 4a13ecffdf1b0..5a4604938f14d 100644 --- a/crates/bevy_text/src/pipeline.rs +++ b/crates/bevy_text/src/pipeline.rs @@ -22,7 +22,7 @@ pub struct TextPipeline { impl Default for TextPipeline { fn default() -> Self { - TextPipeline { + Self { brush: GlyphBrush::default(), glyph_map: Default::default(), map_font_id: Default::default(), diff --git a/crates/bevy_text/src/text.rs b/crates/bevy_text/src/text.rs index 2f2b37ab9a19e..d22a2b0c0b146 100644 --- a/crates/bevy_text/src/text.rs +++ b/crates/bevy_text/src/text.rs @@ -79,7 +79,7 @@ pub struct TextAlignment { impl Default for TextAlignment { fn default() -> Self { - TextAlignment { + Self { vertical: VerticalAlign::Top, horizontal: HorizontalAlign::Left, } @@ -104,9 +104,9 @@ pub enum HorizontalAlign { impl From for glyph_brush_layout::HorizontalAlign { fn from(val: HorizontalAlign) -> Self { match val { - HorizontalAlign::Left => glyph_brush_layout::HorizontalAlign::Left, - HorizontalAlign::Center => glyph_brush_layout::HorizontalAlign::Center, - HorizontalAlign::Right => glyph_brush_layout::HorizontalAlign::Right, + HorizontalAlign::Left => Self::Left, + HorizontalAlign::Center => Self::Center, + HorizontalAlign::Right => Self::Right, } } } @@ -127,9 +127,9 @@ pub enum VerticalAlign { impl From for glyph_brush_layout::VerticalAlign { fn from(val: VerticalAlign) -> Self { match val { - VerticalAlign::Top => glyph_brush_layout::VerticalAlign::Top, - VerticalAlign::Center => glyph_brush_layout::VerticalAlign::Center, - VerticalAlign::Bottom => glyph_brush_layout::VerticalAlign::Bottom, + VerticalAlign::Top => Self::Top, + VerticalAlign::Center => Self::Center, + VerticalAlign::Bottom => Self::Bottom, } } } diff --git a/crates/bevy_text/src/text2d.rs b/crates/bevy_text/src/text2d.rs index bee204e755fa3..7e27038f88e93 100644 --- a/crates/bevy_text/src/text2d.rs +++ b/crates/bevy_text/src/text2d.rs @@ -50,11 +50,9 @@ pub fn extract_text2d_sprite( ) { let mut extracted_sprites = render_world.get_resource_mut::().unwrap(); - let scale_factor = if let Some(window) = windows.get_primary() { - window.scale_factor() as f32 - } else { - 1. - }; + let scale_factor = windows + .get_primary() + .map_or(1., |window| window.scale_factor() as f32); for (entity, visibility, text, transform, calculated_size) in text2d_query.iter() { if !visibility.is_visible { @@ -138,11 +136,9 @@ pub fn text2d_system( return; } - let scale_factor = if let Some(window) = windows.get_primary() { - window.scale_factor() - } else { - 1. - }; + let scale_factor = windows + .get_primary() + .map_or(1., |window| window.scale_factor()); // Computes all text in the local queue let mut new_queue = Vec::new(); diff --git a/crates/bevy_transform/src/components/global_transform.rs b/crates/bevy_transform/src/components/global_transform.rs index 7540fd90dff6e..283d1606b2d11 100644 --- a/crates/bevy_transform/src/components/global_transform.rs +++ b/crates/bevy_transform/src/components/global_transform.rs @@ -55,7 +55,7 @@ impl GlobalTransform { /// on all axes. #[inline] pub const fn identity() -> Self { - GlobalTransform { + Self { translation: Vec3::ZERO, rotation: Quat::IDENTITY, scale: Vec3::ONE, @@ -67,7 +67,7 @@ impl GlobalTransform { pub fn from_matrix(matrix: Mat4) -> Self { let (scale, rotation, translation) = matrix.to_scale_rotation_translation(); - GlobalTransform { + Self { translation, rotation, scale, @@ -77,7 +77,7 @@ impl GlobalTransform { #[doc(hidden)] #[inline] pub fn from_translation(translation: Vec3) -> Self { - GlobalTransform { + Self { translation, ..Default::default() } @@ -86,7 +86,7 @@ impl GlobalTransform { #[doc(hidden)] #[inline] pub fn from_rotation(rotation: Quat) -> Self { - GlobalTransform { + Self { rotation, ..Default::default() } @@ -95,7 +95,7 @@ impl GlobalTransform { #[doc(hidden)] #[inline] pub fn from_scale(scale: Vec3) -> Self { - GlobalTransform { + Self { scale, ..Default::default() } @@ -110,21 +110,21 @@ impl GlobalTransform { #[doc(hidden)] #[inline] - pub fn with_translation(mut self, translation: Vec3) -> Self { + pub const fn with_translation(mut self, translation: Vec3) -> Self { self.translation = translation; self } #[doc(hidden)] #[inline] - pub fn with_rotation(mut self, rotation: Quat) -> Self { + pub const fn with_rotation(mut self, rotation: Quat) -> Self { self.rotation = rotation; self } #[doc(hidden)] #[inline] - pub fn with_scale(mut self, scale: Vec3) -> Self { + pub const fn with_scale(mut self, scale: Vec3) -> Self { self.scale = scale; self } @@ -199,11 +199,11 @@ impl GlobalTransform { /// Multiplies `self` with `transform` component by component, returning the /// resulting [`GlobalTransform`] #[inline] - pub fn mul_transform(&self, transform: Transform) -> GlobalTransform { + pub fn mul_transform(&self, transform: Transform) -> Self { let translation = self.mul_vec3(transform.translation); let rotation = self.rotation * transform.rotation; let scale = self.scale * transform.scale; - GlobalTransform { + Self { translation, rotation, scale, @@ -251,17 +251,17 @@ impl From for GlobalTransform { } } -impl Mul for GlobalTransform { - type Output = GlobalTransform; +impl Mul for GlobalTransform { + type Output = Self; #[inline] - fn mul(self, global_transform: GlobalTransform) -> Self::Output { + fn mul(self, global_transform: Self) -> Self::Output { self.mul_transform(global_transform.into()) } } impl Mul for GlobalTransform { - type Output = GlobalTransform; + type Output = Self; #[inline] fn mul(self, transform: Transform) -> Self::Output { diff --git a/crates/bevy_transform/src/components/parent.rs b/crates/bevy_transform/src/components/parent.rs index ddc0e2a634ee6..5b359be676219 100644 --- a/crates/bevy_transform/src/components/parent.rs +++ b/crates/bevy_transform/src/components/parent.rs @@ -19,7 +19,7 @@ pub struct Parent(pub Entity); // better ways to handle cases like this. impl FromWorld for Parent { fn from_world(_world: &mut World) -> Self { - Parent(Entity::from_raw(u32::MAX)) + Self(Entity::from_raw(u32::MAX)) } } @@ -59,6 +59,6 @@ impl MapEntities for PreviousParent { // TODO: Better handle this case see `impl FromWorld for Parent` impl FromWorld for PreviousParent { fn from_world(_world: &mut World) -> Self { - PreviousParent(Entity::from_raw(u32::MAX)) + Self(Entity::from_raw(u32::MAX)) } } diff --git a/crates/bevy_transform/src/components/transform.rs b/crates/bevy_transform/src/components/transform.rs index dcf5d8ba2516f..c0fe493dcbc15 100644 --- a/crates/bevy_transform/src/components/transform.rs +++ b/crates/bevy_transform/src/components/transform.rs @@ -58,7 +58,7 @@ impl Transform { /// all axes. #[inline] pub const fn identity() -> Self { - Transform { + Self { translation: Vec3::ZERO, rotation: Quat::IDENTITY, scale: Vec3::ONE, @@ -71,7 +71,7 @@ impl Transform { pub fn from_matrix(matrix: Mat4) -> Self { let (scale, rotation, translation) = matrix.to_scale_rotation_translation(); - Transform { + Self { translation, rotation, scale, @@ -82,7 +82,7 @@ impl Transform { /// all axes. #[inline] pub fn from_translation(translation: Vec3) -> Self { - Transform { + Self { translation, ..Default::default() } @@ -92,7 +92,7 @@ impl Transform { /// all axes. #[inline] pub fn from_rotation(rotation: Quat) -> Self { - Transform { + Self { rotation, ..Default::default() } @@ -102,7 +102,7 @@ impl Transform { /// all axes. #[inline] pub fn from_scale(scale: Vec3) -> Self { - Transform { + Self { scale, ..Default::default() } @@ -119,21 +119,21 @@ impl Transform { /// Returns this [`Transform`] with a new translation. #[inline] - pub fn with_translation(mut self, translation: Vec3) -> Self { + pub const fn with_translation(mut self, translation: Vec3) -> Self { self.translation = translation; self } /// Returns this [`Transform`] with a new rotation. #[inline] - pub fn with_rotation(mut self, rotation: Quat) -> Self { + pub const fn with_rotation(mut self, rotation: Quat) -> Self { self.rotation = rotation; self } /// Returns this [`Transform`] with a new scale. #[inline] - pub fn with_scale(mut self, scale: Vec3) -> Self { + pub const fn with_scale(mut self, scale: Vec3) -> Self { self.scale = scale; self } @@ -208,11 +208,11 @@ impl Transform { /// Multiplies `self` with `transform` component by component, returning the /// resulting [`Transform`] #[inline] - pub fn mul_transform(&self, transform: Transform) -> Self { + pub fn mul_transform(&self, transform: Self) -> Self { let translation = self.mul_vec3(transform.translation); let rotation = self.rotation * transform.rotation; let scale = self.scale * transform.scale; - Transform { + Self { translation, rotation, scale, @@ -262,10 +262,10 @@ impl From for Transform { } } -impl Mul for Transform { - type Output = Transform; +impl Mul for Transform { + type Output = Self; - fn mul(self, transform: Transform) -> Self::Output { + fn mul(self, transform: Self) -> Self::Output { self.mul_transform(transform) } } diff --git a/crates/bevy_transform/src/hierarchy/child_builder.rs b/crates/bevy_transform/src/hierarchy/child_builder.rs index 3dd47da3878a6..83f0d75f658cb 100644 --- a/crates/bevy_transform/src/hierarchy/child_builder.rs +++ b/crates/bevy_transform/src/hierarchy/child_builder.rs @@ -151,7 +151,7 @@ impl<'w, 's, 'a> ChildBuilder<'w, 's, 'a> { } /// Returns the parent entity of this [`ChildBuilder`] - pub fn parent_entity(&self) -> Entity { + pub const fn parent_entity(&self) -> Entity { self.push_children.parent } diff --git a/crates/bevy_transform/src/transform_propagate_system.rs b/crates/bevy_transform/src/transform_propagate_system.rs index a4ab7aadcdf89..dda732b494076 100644 --- a/crates/bevy_transform/src/transform_propagate_system.rs +++ b/crates/bevy_transform/src/transform_propagate_system.rs @@ -17,11 +17,12 @@ pub fn transform_propagate_system( children_query: Query, (With, With)>, ) { for (entity, children, transform, mut global_transform) in root_query.iter_mut() { - let mut changed = false; - if changed_transform_query.get(entity).is_ok() { + let changed = if changed_transform_query.get(entity).is_ok() { *global_transform = GlobalTransform::from(*transform); - changed = true; - } + true + } else { + false + }; if let Some(children) = children { for child in children.0.iter() { diff --git a/crates/bevy_ui/src/entity.rs b/crates/bevy_ui/src/entity.rs index 6f145ac7805d2..aef2fcb41b4cd 100644 --- a/crates/bevy_ui/src/entity.rs +++ b/crates/bevy_ui/src/entity.rs @@ -77,7 +77,7 @@ pub struct TextBundle { impl Default for TextBundle { fn default() -> Self { - TextBundle { + Self { focus_policy: FocusPolicy::Pass, text: Default::default(), node: Default::default(), @@ -117,7 +117,7 @@ pub struct ButtonBundle { impl Default for ButtonBundle { fn default() -> Self { - ButtonBundle { + Self { button: Button, interaction: Default::default(), focus_policy: Default::default(), @@ -153,7 +153,7 @@ impl Default for UiCameraBundle { // we want 0 to be "closest" and +far to be "farthest" in 2d, so we offset // the camera's translation by far and use a right handed coordinate system let far = 1000.0; - UiCameraBundle { + Self { camera: Camera { name: Some(CAMERA_UI.to_string()), ..Default::default() diff --git a/crates/bevy_ui/src/flex/convert.rs b/crates/bevy_ui/src/flex/convert.rs index 10e6839134349..003902c1ffbdd 100644 --- a/crates/bevy_ui/src/flex/convert.rs +++ b/crates/bevy_ui/src/flex/convert.rs @@ -75,11 +75,11 @@ pub fn from_val(scale_factor: f64, val: Val) -> stretch::style::Dimension { impl From for stretch::style::AlignItems { fn from(value: AlignItems) -> Self { match value { - AlignItems::FlexStart => stretch::style::AlignItems::FlexStart, - AlignItems::FlexEnd => stretch::style::AlignItems::FlexEnd, - AlignItems::Center => stretch::style::AlignItems::Center, - AlignItems::Baseline => stretch::style::AlignItems::Baseline, - AlignItems::Stretch => stretch::style::AlignItems::Stretch, + AlignItems::FlexStart => Self::FlexStart, + AlignItems::FlexEnd => Self::FlexEnd, + AlignItems::Center => Self::Center, + AlignItems::Baseline => Self::Baseline, + AlignItems::Stretch => Self::Stretch, } } } @@ -87,12 +87,12 @@ impl From for stretch::style::AlignItems { impl From for stretch::style::AlignSelf { fn from(value: AlignSelf) -> Self { match value { - AlignSelf::Auto => stretch::style::AlignSelf::Auto, - AlignSelf::FlexStart => stretch::style::AlignSelf::FlexStart, - AlignSelf::FlexEnd => stretch::style::AlignSelf::FlexEnd, - AlignSelf::Center => stretch::style::AlignSelf::Center, - AlignSelf::Baseline => stretch::style::AlignSelf::Baseline, - AlignSelf::Stretch => stretch::style::AlignSelf::Stretch, + AlignSelf::Auto => Self::Auto, + AlignSelf::FlexStart => Self::FlexStart, + AlignSelf::FlexEnd => Self::FlexEnd, + AlignSelf::Center => Self::Center, + AlignSelf::Baseline => Self::Baseline, + AlignSelf::Stretch => Self::Stretch, } } } @@ -100,12 +100,12 @@ impl From for stretch::style::AlignSelf { impl From for stretch::style::AlignContent { fn from(value: AlignContent) -> Self { match value { - AlignContent::FlexStart => stretch::style::AlignContent::FlexStart, - AlignContent::FlexEnd => stretch::style::AlignContent::FlexEnd, - AlignContent::Center => stretch::style::AlignContent::Center, - AlignContent::Stretch => stretch::style::AlignContent::Stretch, - AlignContent::SpaceBetween => stretch::style::AlignContent::SpaceBetween, - AlignContent::SpaceAround => stretch::style::AlignContent::SpaceAround, + AlignContent::FlexStart => Self::FlexStart, + AlignContent::FlexEnd => Self::FlexEnd, + AlignContent::Center => Self::Center, + AlignContent::Stretch => Self::Stretch, + AlignContent::SpaceBetween => Self::SpaceBetween, + AlignContent::SpaceAround => Self::SpaceAround, } } } @@ -113,9 +113,9 @@ impl From for stretch::style::AlignContent { impl From for stretch::style::Direction { fn from(value: Direction) -> Self { match value { - Direction::Inherit => stretch::style::Direction::Inherit, - Direction::LeftToRight => stretch::style::Direction::LTR, - Direction::RightToLeft => stretch::style::Direction::RTL, + Direction::Inherit => Self::Inherit, + Direction::LeftToRight => Self::LTR, + Direction::RightToLeft => Self::RTL, } } } @@ -123,8 +123,8 @@ impl From for stretch::style::Direction { impl From for stretch::style::Display { fn from(value: Display) -> Self { match value { - Display::Flex => stretch::style::Display::Flex, - Display::None => stretch::style::Display::None, + Display::Flex => Self::Flex, + Display::None => Self::None, } } } @@ -132,10 +132,10 @@ impl From for stretch::style::Display { impl From for stretch::style::FlexDirection { fn from(value: FlexDirection) -> Self { match value { - FlexDirection::Row => stretch::style::FlexDirection::Row, - FlexDirection::Column => stretch::style::FlexDirection::Column, - FlexDirection::RowReverse => stretch::style::FlexDirection::RowReverse, - FlexDirection::ColumnReverse => stretch::style::FlexDirection::ColumnReverse, + FlexDirection::Row => Self::Row, + FlexDirection::Column => Self::Column, + FlexDirection::RowReverse => Self::RowReverse, + FlexDirection::ColumnReverse => Self::ColumnReverse, } } } @@ -143,12 +143,12 @@ impl From for stretch::style::FlexDirection { impl From for stretch::style::JustifyContent { fn from(value: JustifyContent) -> Self { match value { - JustifyContent::FlexStart => stretch::style::JustifyContent::FlexStart, - JustifyContent::FlexEnd => stretch::style::JustifyContent::FlexEnd, - JustifyContent::Center => stretch::style::JustifyContent::Center, - JustifyContent::SpaceBetween => stretch::style::JustifyContent::SpaceBetween, - JustifyContent::SpaceAround => stretch::style::JustifyContent::SpaceAround, - JustifyContent::SpaceEvenly => stretch::style::JustifyContent::SpaceEvenly, + JustifyContent::FlexStart => Self::FlexStart, + JustifyContent::FlexEnd => Self::FlexEnd, + JustifyContent::Center => Self::Center, + JustifyContent::SpaceBetween => Self::SpaceBetween, + JustifyContent::SpaceAround => Self::SpaceAround, + JustifyContent::SpaceEvenly => Self::SpaceEvenly, } } } @@ -156,8 +156,8 @@ impl From for stretch::style::JustifyContent { impl From for stretch::style::PositionType { fn from(value: PositionType) -> Self { match value { - PositionType::Relative => stretch::style::PositionType::Relative, - PositionType::Absolute => stretch::style::PositionType::Absolute, + PositionType::Relative => Self::Relative, + PositionType::Absolute => Self::Absolute, } } } @@ -165,9 +165,9 @@ impl From for stretch::style::PositionType { impl From for stretch::style::FlexWrap { fn from(value: FlexWrap) -> Self { match value { - FlexWrap::NoWrap => stretch::style::FlexWrap::NoWrap, - FlexWrap::Wrap => stretch::style::FlexWrap::Wrap, - FlexWrap::WrapReverse => stretch::style::FlexWrap::WrapReverse, + FlexWrap::NoWrap => Self::NoWrap, + FlexWrap::Wrap => Self::Wrap, + FlexWrap::WrapReverse => Self::WrapReverse, } } } diff --git a/crates/bevy_ui/src/flex/mod.rs b/crates/bevy_ui/src/flex/mod.rs index cbe1da12a4924..e79172e5dd0ef 100644 --- a/crates/bevy_ui/src/flex/mod.rs +++ b/crates/bevy_ui/src/flex/mod.rs @@ -177,17 +177,20 @@ without UI components as a child of an entity with UI components, results may be } pub fn get_layout(&self, entity: Entity) -> Result<&stretch::result::Layout, FlexError> { - if let Some(stretch_node) = self.entity_to_stretch.get(&entity) { - self.stretch - .layout(*stretch_node) - .map_err(FlexError::StretchError) - } else { - warn!( - "Styled child in a non-UI entity hierarchy. You are using an entity \ + self.entity_to_stretch.get(&entity).map_or_else( + || { + warn!( + "Styled child in a non-UI entity hierarchy. You are using an entity \ with UI components as a child of an entity without UI components, results may be unexpected." - ); - Err(FlexError::InvalidHierarchy) - } + ); + Err(FlexError::InvalidHierarchy) + }, + |stretch_node| { + self.stretch + .layout(*stretch_node) + .map_err(FlexError::StretchError) + }, + ) } } @@ -218,11 +221,9 @@ pub fn flex_node_system( } // assume one window for time being... - let logical_to_physical_factor = if let Some(primary_window) = windows.get_primary() { - primary_window.scale_factor() - } else { - 1. - }; + let logical_to_physical_factor = windows + .get_primary() + .map_or(1., |primary_window| primary_window.scale_factor()); if scale_factor_events.iter().next_back().is_some() { update_changed( diff --git a/crates/bevy_ui/src/focus.rs b/crates/bevy_ui/src/focus.rs index 20bfa328cb60d..251e766efc178 100644 --- a/crates/bevy_ui/src/focus.rs +++ b/crates/bevy_ui/src/focus.rs @@ -30,7 +30,7 @@ pub enum Interaction { impl Default for Interaction { fn default() -> Self { - Interaction::None + Self::None } } @@ -46,7 +46,7 @@ pub enum FocusPolicy { impl Default for FocusPolicy { fn default() -> Self { - FocusPolicy::Block + Self::Block } } diff --git a/crates/bevy_ui/src/margins.rs b/crates/bevy_ui/src/margins.rs index 124467c7f5529..c28c7d30a0229 100644 --- a/crates/bevy_ui/src/margins.rs +++ b/crates/bevy_ui/src/margins.rs @@ -13,8 +13,8 @@ pub struct Margins { impl Margins { /// Creates a new Margins based on the input - pub fn new(left: f32, right: f32, bottom: f32, top: f32) -> Self { - Margins { + pub const fn new(left: f32, right: f32, bottom: f32, top: f32) -> Self { + Self { left, right, bottom, @@ -25,7 +25,7 @@ impl Margins { impl Default for Margins { fn default() -> Self { - Margins { + Self { left: 0.0, right: 0.0, bottom: 0.0, diff --git a/crates/bevy_ui/src/render/mod.rs b/crates/bevy_ui/src/render/mod.rs index e632b4eee18cb..e9ac806434c65 100644 --- a/crates/bevy_ui/src/render/mod.rs +++ b/crates/bevy_ui/src/render/mod.rs @@ -188,11 +188,9 @@ pub fn extract_text_uinodes( ) { let mut extracted_uinodes = render_world.get_resource_mut::().unwrap(); - let scale_factor = if let Some(window) = windows.get_primary() { - window.scale_factor() as f32 - } else { - 1. - }; + let scale_factor = windows + .get_primary() + .map_or(1., |window| window.scale_factor() as f32); for (entity, uinode, transform, text, visibility, clip) in uinode_query.iter() { if !visibility.is_visible { @@ -314,28 +312,29 @@ pub fn prepare_uinodes( // Calculate the effect of clipping // Note: this won't work with rotation/scaling, but that's much more complex (may need more that 2 quads) - let positions_diff = if let Some(clip) = extracted_uinode.clip { - [ - Vec2::new( - f32::max(clip.min.x - positions[0].x, 0.), - f32::max(clip.min.y - positions[0].y, 0.), - ), - Vec2::new( - f32::min(clip.max.x - positions[1].x, 0.), - f32::max(clip.min.y - positions[1].y, 0.), - ), - Vec2::new( - f32::min(clip.max.x - positions[2].x, 0.), - f32::min(clip.max.y - positions[2].y, 0.), - ), - Vec2::new( - f32::max(clip.min.x - positions[3].x, 0.), - f32::min(clip.max.y - positions[3].y, 0.), - ), - ] - } else { - [Vec2::ZERO; 4] - }; + let positions_diff = extracted_uinode.clip.map_or_else( + || [Vec2::ZERO; 4], + |clip| { + [ + Vec2::new( + f32::max(clip.min.x - positions[0].x, 0.), + f32::max(clip.min.y - positions[0].y, 0.), + ), + Vec2::new( + f32::min(clip.max.x - positions[1].x, 0.), + f32::max(clip.min.y - positions[1].y, 0.), + ), + Vec2::new( + f32::min(clip.max.x - positions[2].x, 0.), + f32::min(clip.max.y - positions[2].y, 0.), + ), + Vec2::new( + f32::max(clip.min.x - positions[3].x, 0.), + f32::min(clip.max.y - positions[3].y, 0.), + ), + ] + }, + ); let positions_clipped = [ positions[0] + positions_diff[0].extend(0.), diff --git a/crates/bevy_ui/src/render/pipeline.rs b/crates/bevy_ui/src/render/pipeline.rs index 4538dc922b131..273eff24f05ec 100644 --- a/crates/bevy_ui/src/render/pipeline.rs +++ b/crates/bevy_ui/src/render/pipeline.rs @@ -52,7 +52,7 @@ impl FromWorld for UiPipeline { label: Some("ui_image_layout"), }); - UiPipeline { + Self { view_layout, image_layout, } diff --git a/crates/bevy_ui/src/render/render_pass.rs b/crates/bevy_ui/src/render/render_pass.rs index 83b608bf0cd22..2ad7357bde8ae 100644 --- a/crates/bevy_ui/src/render/render_pass.rs +++ b/crates/bevy_ui/src/render/render_pass.rs @@ -51,7 +51,7 @@ impl UiPassNode { impl bevy_render::render_graph::Node for UiPassNode { fn input(&self) -> Vec { - vec![SlotInfo::new(UiPassNode::IN_VIEW, SlotType::Entity)] + vec![SlotInfo::new(Self::IN_VIEW, SlotType::Entity)] } fn update(&mut self, world: &mut World) { diff --git a/crates/bevy_ui/src/ui_node.rs b/crates/bevy_ui/src/ui_node.rs index f29e087c825bc..986f3dd281cb8 100644 --- a/crates/bevy_ui/src/ui_node.rs +++ b/crates/bevy_ui/src/ui_node.rs @@ -33,19 +33,19 @@ pub enum Val { impl Default for Val { fn default() -> Self { - Val::Undefined + Self::Undefined } } impl Add for Val { - type Output = Val; + type Output = Self; fn add(self, rhs: f32) -> Self::Output { match self { - Val::Undefined => Val::Undefined, - Val::Auto => Val::Auto, - Val::Px(value) => Val::Px(value + rhs), - Val::Percent(value) => Val::Percent(value + rhs), + Self::Undefined => Self::Undefined, + Self::Auto => Self::Auto, + Self::Px(value) => Self::Px(value + rhs), + Self::Percent(value) => Self::Percent(value + rhs), } } } @@ -53,9 +53,9 @@ impl Add for Val { impl AddAssign for Val { fn add_assign(&mut self, rhs: f32) { match self { - Val::Undefined | Val::Auto => {} - Val::Px(value) => *value += rhs, - Val::Percent(value) => *value += rhs, + Self::Undefined | Self::Auto => {} + Self::Px(value) => *value += rhs, + Self::Percent(value) => *value += rhs, } } } @@ -159,8 +159,8 @@ pub enum AlignItems { } impl Default for AlignItems { - fn default() -> AlignItems { - AlignItems::Stretch + fn default() -> Self { + Self::Stretch } } @@ -183,8 +183,8 @@ pub enum AlignSelf { } impl Default for AlignSelf { - fn default() -> AlignSelf { - AlignSelf::Auto + fn default() -> Self { + Self::Auto } } @@ -211,8 +211,8 @@ pub enum AlignContent { } impl Default for AlignContent { - fn default() -> AlignContent { - AlignContent::Stretch + fn default() -> Self { + Self::Stretch } } @@ -231,8 +231,8 @@ pub enum Direction { } impl Default for Direction { - fn default() -> Direction { - Direction::Inherit + fn default() -> Self { + Self::Inherit } } @@ -247,8 +247,8 @@ pub enum Display { } impl Default for Display { - fn default() -> Display { - Display::Flex + fn default() -> Self { + Self::Flex } } @@ -267,8 +267,8 @@ pub enum FlexDirection { } impl Default for FlexDirection { - fn default() -> FlexDirection { - FlexDirection::Row + fn default() -> Self { + Self::Row } } @@ -291,8 +291,8 @@ pub enum JustifyContent { } impl Default for JustifyContent { - fn default() -> JustifyContent { - JustifyContent::FlexStart + fn default() -> Self { + Self::FlexStart } } @@ -307,8 +307,8 @@ pub enum Overflow { } impl Default for Overflow { - fn default() -> Overflow { - Overflow::Visible + fn default() -> Self { + Self::Visible } } @@ -325,8 +325,8 @@ pub enum PositionType { } impl Default for PositionType { - fn default() -> PositionType { - PositionType::Relative + fn default() -> Self { + Self::Relative } } @@ -343,8 +343,8 @@ pub enum FlexWrap { } impl Default for FlexWrap { - fn default() -> FlexWrap { - FlexWrap::NoWrap + fn default() -> Self { + Self::NoWrap } } diff --git a/crates/bevy_ui/src/update.rs b/crates/bevy_ui/src/update.rs index f1bc965584a20..1cd763b1ceedf 100644 --- a/crates/bevy_ui/src/update.rs +++ b/crates/bevy_ui/src/update.rs @@ -111,14 +111,10 @@ fn update_clipping( min: node_center - node.size / 2., max: node_center + node.size / 2., }; - if let Some(clip) = clip { - Some(Rect { - min: Vec2::max(clip.min, node_rect.min), - max: Vec2::min(clip.max, node_rect.max), - }) - } else { - Some(node_rect) - } + Some(clip.map_or(node_rect, |clip| Rect { + min: Vec2::max(clip.min, node_rect.min), + max: Vec2::min(clip.max, node_rect.max), + })) } }; diff --git a/crates/bevy_ui/src/widget/image.rs b/crates/bevy_ui/src/widget/image.rs index 9d1a24b55e488..0cd91c9eecdf8 100644 --- a/crates/bevy_ui/src/widget/image.rs +++ b/crates/bevy_ui/src/widget/image.rs @@ -21,7 +21,7 @@ pub enum ImageMode { impl Default for ImageMode { fn default() -> Self { - ImageMode::KeepAspect + Self::KeepAspect } } diff --git a/crates/bevy_ui/src/widget/text.rs b/crates/bevy_ui/src/widget/text.rs index ce5cbc1bd07b5..9ba9f71626bbb 100644 --- a/crates/bevy_ui/src/widget/text.rs +++ b/crates/bevy_ui/src/widget/text.rs @@ -52,11 +52,9 @@ pub fn text_system( QueryState<(&Text, &Style, &mut CalculatedSize)>, )>, ) { - let scale_factor = if let Some(window) = windows.get_primary() { - window.scale_factor() - } else { - 1. - }; + let scale_factor = windows + .get_primary() + .map_or(1., |window| window.scale_factor()); let inv_scale_factor = 1. / scale_factor; diff --git a/crates/bevy_utils/src/lib.rs b/crates/bevy_utils/src/lib.rs index eeb0ba668311d..5af8b1780c64e 100644 --- a/crates/bevy_utils/src/lib.rs +++ b/crates/bevy_utils/src/lib.rs @@ -90,7 +90,7 @@ impl AHashExt for HashMap { /// ``` #[inline] fn with_capacity(capacity: usize) -> Self { - HashMap::with_capacity_and_hasher(capacity, RandomState::default()) + Self::with_capacity_and_hasher(capacity, RandomState::default()) } } @@ -118,7 +118,7 @@ impl AHashExt for StableHashMap { /// ``` #[inline] fn with_capacity(capacity: usize) -> Self { - StableHashMap::with_capacity_and_hasher(capacity, FixedState::default()) + Self::with_capacity_and_hasher(capacity, FixedState::default()) } } @@ -176,7 +176,7 @@ impl AHashExt for HashSet { /// ``` #[inline] fn with_capacity(capacity: usize) -> Self { - HashSet::with_capacity_and_hasher(capacity, RandomState::default()) + Self::with_capacity_and_hasher(capacity, RandomState::default()) } } @@ -204,6 +204,6 @@ impl AHashExt for StableHashSet { /// ``` #[inline] fn with_capacity(capacity: usize) -> Self { - StableHashSet::with_capacity_and_hasher(capacity, FixedState::default()) + Self::with_capacity_and_hasher(capacity, FixedState::default()) } } diff --git a/crates/bevy_window/src/lib.rs b/crates/bevy_window/src/lib.rs index a63ca57a96b7d..f6dcae4d8b253 100644 --- a/crates/bevy_window/src/lib.rs +++ b/crates/bevy_window/src/lib.rs @@ -29,7 +29,7 @@ pub struct WindowPlugin { impl Default for WindowPlugin { fn default() -> Self { - WindowPlugin { + Self { add_primary_window: true, exit_on_close: true, } diff --git a/crates/bevy_window/src/raw_window_handle.rs b/crates/bevy_window/src/raw_window_handle.rs index 76f1411261c80..bf6b2cc402c71 100644 --- a/crates/bevy_window/src/raw_window_handle.rs +++ b/crates/bevy_window/src/raw_window_handle.rs @@ -6,7 +6,7 @@ use raw_window_handle::{HasRawWindowHandle, RawWindowHandle}; pub struct RawWindowHandleWrapper(RawWindowHandle); impl RawWindowHandleWrapper { - pub(crate) fn new(handle: RawWindowHandle) -> Self { + pub(crate) const fn new(handle: RawWindowHandle) -> Self { Self(handle) } @@ -14,7 +14,7 @@ impl RawWindowHandleWrapper { /// This returns a [`HasRawWindowHandle`] impl, which exposes [`RawWindowHandle`]. Some platforms /// have constraints on where/how this handle can be used. For example, some platforms don't support doing window /// operations off of the main thread. The caller must ensure the [`RawWindowHandle`] is only used in valid contexts. - pub unsafe fn get_handle(&self) -> HasRawWindowHandleWrapper { + pub const unsafe fn get_handle(&self) -> HasRawWindowHandleWrapper { HasRawWindowHandleWrapper(self.0) } } diff --git a/crates/bevy_window/src/window.rs b/crates/bevy_window/src/window.rs index 7381a32134ef7..71b8269a95b30 100644 --- a/crates/bevy_window/src/window.rs +++ b/crates/bevy_window/src/window.rs @@ -7,15 +7,15 @@ pub struct WindowId(Uuid); impl WindowId { pub fn new() -> Self { - WindowId(Uuid::new_v4()) + Self(Uuid::new_v4()) } - pub fn primary() -> Self { - WindowId(Uuid::from_u128(0)) + pub const fn primary() -> Self { + Self(Uuid::from_u128(0)) } pub fn is_primary(&self) -> bool { - *self == WindowId::primary() + *self == Self::primary() } } @@ -32,7 +32,7 @@ impl fmt::Display for WindowId { impl Default for WindowId { fn default() -> Self { - WindowId::primary() + Self::primary() } } @@ -62,8 +62,8 @@ impl Default for WindowResizeConstraints { } impl WindowResizeConstraints { - pub fn check_constraints(&self) -> WindowResizeConstraints { - let WindowResizeConstraints { + pub fn check_constraints(&self) -> Self { + let Self { mut min_width, mut min_height, mut max_width, @@ -85,7 +85,7 @@ impl WindowResizeConstraints { ); max_height = min_height; } - WindowResizeConstraints { + Self { min_width, min_height, max_width, @@ -211,7 +211,7 @@ impl Window { position: Option, raw_window_handle: RawWindowHandle, ) -> Self { - Window { + Self { id, requested_width: window_descriptor.width, requested_height: window_descriptor.height, @@ -239,7 +239,7 @@ impl Window { } #[inline] - pub fn id(&self) -> WindowId { + pub const fn id(&self) -> WindowId { self.id } @@ -261,7 +261,7 @@ impl Window { /// This may differ from the actual width depending on OS size limits and /// the scaling factor for high DPI monitors. #[inline] - pub fn requested_width(&self) -> f32 { + pub const fn requested_width(&self) -> f32 { self.requested_width } @@ -271,31 +271,31 @@ impl Window { /// This may differ from the actual width depending on OS size limits and /// the scaling factor for high DPI monitors. #[inline] - pub fn requested_height(&self) -> f32 { + pub const fn requested_height(&self) -> f32 { self.requested_height } /// The window's client area width in physical pixels. #[inline] - pub fn physical_width(&self) -> u32 { + pub const fn physical_width(&self) -> u32 { self.physical_width } /// The window's client area height in physical pixels. #[inline] - pub fn physical_height(&self) -> u32 { + pub const fn physical_height(&self) -> u32 { self.physical_height } /// The window's client resize constraint in logical pixels. #[inline] - pub fn resize_constraints(&self) -> WindowResizeConstraints { + pub const fn resize_constraints(&self) -> WindowResizeConstraints { self.resize_constraints } /// The window's client position in physical pixels. #[inline] - pub fn position(&self) -> Option { + pub const fn position(&self) -> Option { self.position } @@ -405,12 +405,12 @@ impl Window { /// The window scale factor as reported by the window backend. /// This value is unaffected by [`scale_factor_override`](Window::scale_factor_override). #[inline] - pub fn backend_scale_factor(&self) -> f64 { + pub const fn backend_scale_factor(&self) -> f64 { self.backend_scale_factor } #[inline] - pub fn scale_factor_override(&self) -> Option { + pub const fn scale_factor_override(&self) -> Option { self.scale_factor_override } @@ -425,7 +425,7 @@ impl Window { } #[inline] - pub fn vsync(&self) -> bool { + pub const fn vsync(&self) -> bool { self.vsync } @@ -436,7 +436,7 @@ impl Window { } #[inline] - pub fn resizable(&self) -> bool { + pub const fn resizable(&self) -> bool { self.resizable } @@ -447,7 +447,7 @@ impl Window { } #[inline] - pub fn decorations(&self) -> bool { + pub const fn decorations(&self) -> bool { self.decorations } @@ -458,7 +458,7 @@ impl Window { } #[inline] - pub fn cursor_locked(&self) -> bool { + pub const fn cursor_locked(&self) -> bool { self.cursor_locked } @@ -469,7 +469,7 @@ impl Window { } #[inline] - pub fn cursor_visible(&self) -> bool { + pub const fn cursor_visible(&self) -> bool { self.cursor_visible } @@ -481,7 +481,7 @@ impl Window { } #[inline] - pub fn cursor_icon(&self) -> CursorIcon { + pub const fn cursor_icon(&self) -> CursorIcon { self.cursor_icon } @@ -492,7 +492,7 @@ impl Window { /// The current mouse position, in physical pixels. #[inline] - pub fn physical_cursor_position(&self) -> Option { + pub const fn physical_cursor_position(&self) -> Option { self.physical_cursor_position } @@ -522,7 +522,7 @@ impl Window { } #[inline] - pub fn mode(&self) -> WindowMode { + pub const fn mode(&self) -> WindowMode { self.mode } @@ -540,7 +540,7 @@ impl Window { } #[inline] - pub fn is_focused(&self) -> bool { + pub const fn is_focused(&self) -> bool { self.focused } @@ -577,7 +577,7 @@ pub struct WindowDescriptor { impl Default for WindowDescriptor { fn default() -> Self { - WindowDescriptor { + Self { title: "bevy".to_string(), width: 1280., height: 720., diff --git a/crates/bevy_winit/src/converters.rs b/crates/bevy_winit/src/converters.rs index e1e7451d07dd9..cf92a532519a6 100644 --- a/crates/bevy_winit/src/converters.rs +++ b/crates/bevy_winit/src/converters.rs @@ -15,14 +15,14 @@ pub fn convert_keyboard_input(keyboard_input: &winit::event::KeyboardInput) -> K } } -pub fn convert_element_state(element_state: winit::event::ElementState) -> ElementState { +pub const fn convert_element_state(element_state: winit::event::ElementState) -> ElementState { match element_state { winit::event::ElementState::Pressed => ElementState::Pressed, winit::event::ElementState::Released => ElementState::Released, } } -pub fn convert_mouse_button(mouse_button: winit::event::MouseButton) -> MouseButton { +pub const fn convert_mouse_button(mouse_button: winit::event::MouseButton) -> MouseButton { match mouse_button { winit::event::MouseButton::Left => MouseButton::Left, winit::event::MouseButton::Right => MouseButton::Right, @@ -59,7 +59,7 @@ pub fn convert_touch_input( } } -pub fn convert_virtual_key_code(virtual_key_code: winit::event::VirtualKeyCode) -> KeyCode { +pub const fn convert_virtual_key_code(virtual_key_code: winit::event::VirtualKeyCode) -> KeyCode { match virtual_key_code { winit::event::VirtualKeyCode::Key1 => KeyCode::Key1, winit::event::VirtualKeyCode::Key2 => KeyCode::Key2, @@ -227,7 +227,7 @@ pub fn convert_virtual_key_code(virtual_key_code: winit::event::VirtualKeyCode) } } -pub fn convert_cursor_icon(cursor_icon: CursorIcon) -> winit::window::CursorIcon { +pub const fn convert_cursor_icon(cursor_icon: CursorIcon) -> winit::window::CursorIcon { match cursor_icon { CursorIcon::Default => winit::window::CursorIcon::Default, CursorIcon::Crosshair => winit::window::CursorIcon::Crosshair, diff --git a/crates/bevy_winit/src/winit_windows.rs b/crates/bevy_winit/src/winit_windows.rs index f3fd83c6e8420..6a9c484373a62 100644 --- a/crates/bevy_winit/src/winit_windows.rs +++ b/crates/bevy_winit/src/winit_windows.rs @@ -193,7 +193,7 @@ pub fn get_fitting_videomode( ) -> winit::monitor::VideoMode { let mut modes = monitor.video_modes().collect::>(); - fn abs_diff(a: u32, b: u32) -> u32 { + const fn abs_diff(a: u32, b: u32) -> u32 { if a > b { return a - b; } From 75b04bee35f665f1e7880ce6880236672521a31d Mon Sep 17 00:00:00 2001 From: Felix de Maneville Date: Tue, 18 Jan 2022 15:54:53 +0100 Subject: [PATCH 02/11] Fixed CI --- crates/bevy_gltf/src/loader.rs | 2 +- crates/bevy_sprite/src/render/mod.rs | 2 +- crates/bevy_sprite/src/texture_atlas.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/bevy_gltf/src/loader.rs b/crates/bevy_gltf/src/loader.rs index 945a7edb1892b..75187f1147b7e 100644 --- a/crates/bevy_gltf/src/loader.rs +++ b/crates/bevy_gltf/src/loader.rs @@ -596,7 +596,7 @@ fn load_node( } } }); - gltf_error.map_or(Ok(()), |err| Err(err)) + gltf_error.map_or(Ok(()), Err) } /// Returns the label for the `mesh`. diff --git a/crates/bevy_sprite/src/render/mod.rs b/crates/bevy_sprite/src/render/mod.rs index cecec21a1eea6..89d1e729f620f 100644 --- a/crates/bevy_sprite/src/render/mod.rs +++ b/crates/bevy_sprite/src/render/mod.rs @@ -104,7 +104,7 @@ impl SpritePipelineKey { Self::from_bits(msaa_bits).unwrap() } - pub fn msaa_samples(&self) -> u32 { + pub const fn msaa_samples(&self) -> u32 { ((self.bits >> Self::MSAA_SHIFT_BITS) & Self::MSAA_MASK_BITS) + 1 } } diff --git a/crates/bevy_sprite/src/texture_atlas.rs b/crates/bevy_sprite/src/texture_atlas.rs index ca95148a74d48..0c62df090a234 100644 --- a/crates/bevy_sprite/src/texture_atlas.rs +++ b/crates/bevy_sprite/src/texture_atlas.rs @@ -46,7 +46,7 @@ impl Default for TextureAtlasSprite { } impl TextureAtlasSprite { - pub fn new(index: usize) -> TextureAtlasSprite { + pub fn new(index: usize) -> Self { Self { index, ..Default::default() From fa3de677900307a467d8ed621a5917280683ff16 Mon Sep 17 00:00:00 2001 From: Felix de Maneville Date: Tue, 18 Jan 2022 16:14:16 +0100 Subject: [PATCH 03/11] Fixed some redundant match arms --- crates/bevy_ecs/src/schedule/stage.rs | 7 +-- crates/bevy_ecs/src/schedule/state.rs | 9 +-- crates/bevy_render/src/color/mod.rs | 59 ++++--------------- .../bevy_render/src/mesh/mesh/conversions.rs | 35 ++++++----- crates/bevy_render/src/mesh/mesh/mod.rs | 54 ++++++++--------- crates/bevy_ui/src/render/mod.rs | 5 +- crates/bevy_ui/src/ui_node.rs | 3 +- crates/bevy_ui/src/widget/text.rs | 5 +- crates/bevy_winit/src/winit_windows.rs | 3 +- 9 files changed, 69 insertions(+), 111 deletions(-) diff --git a/crates/bevy_ecs/src/schedule/stage.rs b/crates/bevy_ecs/src/schedule/stage.rs index 0696f78796b1d..19b3ddeb42c41 100644 --- a/crates/bevy_ecs/src/schedule/stage.rs +++ b/crates/bevy_ecs/src/schedule/stage.rs @@ -920,10 +920,9 @@ impl Stage for SystemStage { } } match criteria.should_run { - ShouldRun::Yes => { - run_system_loop = true; - } - ShouldRun::YesAndCheckAgain | ShouldRun::NoAndCheckAgain => { + ShouldRun::Yes + | ShouldRun::YesAndCheckAgain + | ShouldRun::NoAndCheckAgain => { run_system_loop = true; } ShouldRun::No => (), diff --git a/crates/bevy_ecs/src/schedule/state.rs b/crates/bevy_ecs/src/schedule/state.rs index 809710a481c7f..ac937564c7e3e 100644 --- a/crates/bevy_ecs/src/schedule/state.rs +++ b/crates/bevy_ecs/src/schedule/state.rs @@ -130,13 +130,8 @@ where .transition { Some(StateTransition::Entering(ref relevant, _)) - | Some(StateTransition::ExitingToResume(_, ref relevant)) => { - if relevant == pred.as_ref().unwrap() { - *is_in_stack = !*is_in_stack; - } - false - } - Some(StateTransition::ExitingFull(_, ref relevant)) => { + | Some(StateTransition::ExitingToResume(_, ref relevant)) + | Some(StateTransition::ExitingFull(_, ref relevant)) => { if relevant == pred.as_ref().unwrap() { *is_in_stack = !*is_in_stack; } diff --git a/crates/bevy_render/src/color/mod.rs b/crates/bevy_render/src/color/mod.rs index caa83cd2feaea..0a607efeea858 100644 --- a/crates/bevy_render/src/color/mod.rs +++ b/crates/bevy_render/src/color/mod.rs @@ -704,12 +704,8 @@ impl MulAssign for Color { match self { Self::Rgba { red, green, blue, .. - } => { - *red *= rhs; - *green *= rhs; - *blue *= rhs; } - Self::RgbaLinear { + | Self::RgbaLinear { red, green, blue, .. } => { *red *= rhs; @@ -780,13 +776,8 @@ impl MulAssign for Color { green, blue, alpha, - } => { - *red *= rhs.x; - *green *= rhs.y; - *blue *= rhs.z; - *alpha *= rhs.w; } - Self::RgbaLinear { + | Self::RgbaLinear { red, green, blue, @@ -822,13 +813,8 @@ impl Mul for Color { green, blue, alpha, - } => Self::Rgba { - red: red * rhs.x, - green: green * rhs.y, - blue: blue * rhs.z, - alpha, - }, - Self::RgbaLinear { + } + | Self::RgbaLinear { red, green, blue, @@ -859,12 +845,8 @@ impl MulAssign for Color { match self { Self::Rgba { red, green, blue, .. - } => { - *red *= rhs.x; - *green *= rhs.y; - *blue *= rhs.z; } - Self::RgbaLinear { + | Self::RgbaLinear { red, green, blue, .. } => { *red *= rhs.x; @@ -895,13 +877,8 @@ impl Mul<[f32; 4]> for Color { green, blue, alpha, - } => Self::Rgba { - red: red * rhs[0], - green: green * rhs[1], - blue: blue * rhs[2], - alpha: alpha * rhs[3], - }, - Self::RgbaLinear { + } + | Self::RgbaLinear { red, green, blue, @@ -935,13 +912,8 @@ impl MulAssign<[f32; 4]> for Color { green, blue, alpha, - } => { - *red *= rhs[0]; - *green *= rhs[1]; - *blue *= rhs[2]; - *alpha *= rhs[3]; } - Self::RgbaLinear { + | Self::RgbaLinear { red, green, blue, @@ -977,13 +949,8 @@ impl Mul<[f32; 3]> for Color { green, blue, alpha, - } => Self::Rgba { - red: red * rhs[0], - green: green * rhs[1], - blue: blue * rhs[2], - alpha, - }, - Self::RgbaLinear { + } + | Self::RgbaLinear { red, green, blue, @@ -1014,12 +981,8 @@ impl MulAssign<[f32; 3]> for Color { match self { Self::Rgba { red, green, blue, .. - } => { - *red *= rhs[0]; - *green *= rhs[1]; - *blue *= rhs[2]; } - Self::RgbaLinear { + | Self::RgbaLinear { red, green, blue, .. } => { *red *= rhs[0]; diff --git a/crates/bevy_render/src/mesh/mesh/conversions.rs b/crates/bevy_render/src/mesh/mesh/conversions.rs index 29acb829103f5..9d70b54bd4535 100644 --- a/crates/bevy_render/src/mesh/mesh/conversions.rs +++ b/crates/bevy_render/src/mesh/mesh/conversions.rs @@ -129,8 +129,9 @@ impl TryFrom for Vec<[u8; 4]> { fn try_from(value: VertexAttributeValues) -> Result { match value { - VertexAttributeValues::Uint8x4(value) => Ok(value), - VertexAttributeValues::Unorm8x4(value) => Ok(value), + VertexAttributeValues::Uint8x4(value) | VertexAttributeValues::Unorm8x4(value) => { + Ok(value) + } _ => Err(FromVertexAttributeError::new::(value)), } } @@ -141,8 +142,9 @@ impl TryFrom for Vec<[i8; 4]> { fn try_from(value: VertexAttributeValues) -> Result { match value { - VertexAttributeValues::Sint8x4(value) => Ok(value), - VertexAttributeValues::Snorm8x4(value) => Ok(value), + VertexAttributeValues::Sint8x4(value) | VertexAttributeValues::Snorm8x4(value) => { + Ok(value) + } _ => Err(FromVertexAttributeError::new::(value)), } } @@ -153,8 +155,9 @@ impl TryFrom for Vec<[u8; 2]> { fn try_from(value: VertexAttributeValues) -> Result { match value { - VertexAttributeValues::Uint8x2(value) => Ok(value), - VertexAttributeValues::Unorm8x2(value) => Ok(value), + VertexAttributeValues::Uint8x2(value) | VertexAttributeValues::Unorm8x2(value) => { + Ok(value) + } _ => Err(FromVertexAttributeError::new::(value)), } } @@ -165,8 +168,9 @@ impl TryFrom for Vec<[i8; 2]> { fn try_from(value: VertexAttributeValues) -> Result { match value { - VertexAttributeValues::Sint8x2(value) => Ok(value), - VertexAttributeValues::Snorm8x2(value) => Ok(value), + VertexAttributeValues::Sint8x2(value) | VertexAttributeValues::Snorm8x2(value) => { + Ok(value) + } _ => Err(FromVertexAttributeError::new::(value)), } } @@ -177,8 +181,9 @@ impl TryFrom for Vec<[i16; 4]> { fn try_from(value: VertexAttributeValues) -> Result { match value { - VertexAttributeValues::Sint16x4(value) => Ok(value), - VertexAttributeValues::Snorm16x4(value) => Ok(value), + VertexAttributeValues::Sint16x4(value) | VertexAttributeValues::Snorm16x4(value) => { + Ok(value) + } _ => Err(FromVertexAttributeError::new::(value)), } } @@ -189,8 +194,9 @@ impl TryFrom for Vec<[u16; 4]> { fn try_from(value: VertexAttributeValues) -> Result { match value { - VertexAttributeValues::Uint16x4(value) => Ok(value), - VertexAttributeValues::Unorm16x4(value) => Ok(value), + VertexAttributeValues::Uint16x4(value) | VertexAttributeValues::Unorm16x4(value) => { + Ok(value) + } _ => Err(FromVertexAttributeError::new::(value)), } } @@ -201,8 +207,9 @@ impl TryFrom for Vec<[u16; 2]> { fn try_from(value: VertexAttributeValues) -> Result { match value { - VertexAttributeValues::Uint16x2(value) => Ok(value), - VertexAttributeValues::Unorm16x2(value) => Ok(value), + VertexAttributeValues::Uint16x2(value) | VertexAttributeValues::Unorm16x2(value) => { + Ok(value) + } _ => Err(FromVertexAttributeError::new::(value)), } } diff --git a/crates/bevy_render/src/mesh/mesh/mod.rs b/crates/bevy_render/src/mesh/mesh/mod.rs index b21de05112aa4..324e3b2ee9a92 100644 --- a/crates/bevy_render/src/mesh/mesh/mod.rs +++ b/crates/bevy_render/src/mesh/mesh/mod.rs @@ -331,36 +331,30 @@ pub trait VertexFormatSize { impl VertexFormatSize for wgpu::VertexFormat { fn get_size(self) -> u64 { match self { - VertexFormat::Uint8x2 => 2, - VertexFormat::Uint8x4 => 4, - VertexFormat::Sint8x2 => 2, - VertexFormat::Sint8x4 => 4, - VertexFormat::Unorm8x2 => 2, - VertexFormat::Unorm8x4 => 4, - VertexFormat::Snorm8x2 => 2, - VertexFormat::Snorm8x4 => 4, - VertexFormat::Uint16x2 => 2 * 2, - VertexFormat::Uint16x4 => 2 * 4, - VertexFormat::Sint16x2 => 2 * 2, - VertexFormat::Sint16x4 => 2 * 4, - VertexFormat::Unorm16x2 => 2 * 2, - VertexFormat::Unorm16x4 => 2 * 4, - VertexFormat::Snorm16x2 => 2 * 2, - VertexFormat::Snorm16x4 => 2 * 4, - VertexFormat::Float16x2 => 2 * 2, - VertexFormat::Float16x4 => 2 * 4, - VertexFormat::Float32 => 4, - VertexFormat::Float32x2 => 4 * 2, - VertexFormat::Float32x3 => 4 * 3, - VertexFormat::Float32x4 => 4 * 4, - VertexFormat::Uint32 => 4, - VertexFormat::Uint32x2 => 4 * 2, - VertexFormat::Uint32x3 => 4 * 3, - VertexFormat::Uint32x4 => 4 * 4, - VertexFormat::Sint32 => 4, - VertexFormat::Sint32x2 => 4 * 2, - VertexFormat::Sint32x3 => 4 * 3, - VertexFormat::Sint32x4 => 4 * 4, + VertexFormat::Uint8x2 + | VertexFormat::Sint8x2 + | VertexFormat::Unorm8x2 + | VertexFormat::Snorm8x2 => 2, + VertexFormat::Uint8x4 + | VertexFormat::Sint8x4 + | VertexFormat::Unorm8x4 + | VertexFormat::Snorm8x4 + | VertexFormat::Float32 + | VertexFormat::Uint32 + | VertexFormat::Sint32 => 4, + VertexFormat::Uint16x2 + | VertexFormat::Sint16x2 + | VertexFormat::Unorm16x2 + | VertexFormat::Snorm16x2 + | VertexFormat::Float16x2 => 2 * 2, + VertexFormat::Uint16x4 + | VertexFormat::Sint16x4 + | VertexFormat::Unorm16x4 + | VertexFormat::Snorm16x4 + | VertexFormat::Float16x4 => 2 * 4, + VertexFormat::Float32x2 | VertexFormat::Uint32x2 | VertexFormat::Sint32x2 => 4 * 2, + VertexFormat::Float32x3 | VertexFormat::Sint32x3 | VertexFormat::Uint32x3 => 4 * 3, + VertexFormat::Float32x4 | VertexFormat::Uint32x4 | VertexFormat::Sint32x4 => 4 * 4, VertexFormat::Float64 => 8, VertexFormat::Float64x2 => 8 * 2, VertexFormat::Float64x3 => 8 * 3, diff --git a/crates/bevy_ui/src/render/mod.rs b/crates/bevy_ui/src/render/mod.rs index e9ac806434c65..a2f955c24720c 100644 --- a/crates/bevy_ui/src/render/mod.rs +++ b/crates/bevy_ui/src/render/mod.rs @@ -427,8 +427,9 @@ pub fn queue_uinodes( for event in &events.images { match event { AssetEvent::Created { .. } => None, - AssetEvent::Modified { handle } => image_bind_groups.values.remove(handle), - AssetEvent::Removed { handle } => image_bind_groups.values.remove(handle), + AssetEvent::Modified { handle } | AssetEvent::Removed { handle } => { + image_bind_groups.values.remove(handle) + } }; } diff --git a/crates/bevy_ui/src/ui_node.rs b/crates/bevy_ui/src/ui_node.rs index 986f3dd281cb8..fe08ede34c5c5 100644 --- a/crates/bevy_ui/src/ui_node.rs +++ b/crates/bevy_ui/src/ui_node.rs @@ -54,8 +54,7 @@ impl AddAssign for Val { fn add_assign(&mut self, rhs: f32) { match self { Self::Undefined | Self::Auto => {} - Self::Px(value) => *value += rhs, - Self::Percent(value) => *value += rhs, + Self::Px(value) | Self::Percent(value) => *value += rhs, } } } diff --git a/crates/bevy_ui/src/widget/text.rs b/crates/bevy_ui/src/widget/text.rs index 9ba9f71626bbb..023efaf3011f2 100644 --- a/crates/bevy_ui/src/widget/text.rs +++ b/crates/bevy_ui/src/widget/text.rs @@ -28,8 +28,9 @@ pub fn text_constraint(min_size: Val, size: Val, max_size: Val, scale_factor: f6 match (min_size, size, max_size) { (_, _, Val::Px(max)) => scale_value(max, scale_factor), (Val::Px(min), _, _) => scale_value(min, scale_factor), - (Val::Undefined, Val::Px(size), Val::Undefined) => scale_value(size, scale_factor), - (Val::Auto, Val::Px(size), Val::Auto) => scale_value(size, scale_factor), + (Val::Undefined, Val::Px(size), Val::Undefined) | (Val::Auto, Val::Px(size), Val::Auto) => { + scale_value(size, scale_factor) + } _ => f32::MAX, } } diff --git a/crates/bevy_winit/src/winit_windows.rs b/crates/bevy_winit/src/winit_windows.rs index 6a9c484373a62..cab8d282a3f53 100644 --- a/crates/bevy_winit/src/winit_windows.rs +++ b/crates/bevy_winit/src/winit_windows.rs @@ -129,8 +129,7 @@ impl WinitWindows { if window_descriptor.cursor_locked { match winit_window.set_cursor_grab(true) { - Ok(_) => {} - Err(winit::error::ExternalError::NotSupported(_)) => {} + Ok(_) | Err(winit::error::ExternalError::NotSupported(_)) => {} Err(err) => Err(err).unwrap(), } } From cb85153dc03e5f56f579b27d495b53d92fbb1e12 Mon Sep 17 00:00:00 2001 From: Felix de Maneville Date: Tue, 18 Jan 2022 16:17:28 +0100 Subject: [PATCH 04/11] Fixed some redundant else blocks --- .../src/render_phase/draw_state.rs | 31 +++++++++---------- .../bevy_render/src/render_resource/shader.rs | 3 +- .../bevy_render/src/renderer/graph_runner.rs | 3 +- 3 files changed, 17 insertions(+), 20 deletions(-) diff --git a/crates/bevy_render/src/render_phase/draw_state.rs b/crates/bevy_render/src/render_phase/draw_state.rs index 2d0fbb5be52c2..b49707e7b8f7e 100644 --- a/crates/bevy_render/src/render_phase/draw_state.rs +++ b/crates/bevy_render/src/render_phase/draw_state.rs @@ -133,14 +133,14 @@ impl<'a> TrackedRenderPass<'a> { dynamic_uniform_indices ); return; - } else { - trace!( - "set bind_group {}: {:?} ({:?})", - index, - bind_group, - dynamic_uniform_indices - ); } + trace!( + "set bind_group {}: {:?} ({:?})", + index, + bind_group, + dynamic_uniform_indices + ); + self.pass .set_bind_group(index as u32, bind_group, dynamic_uniform_indices); self.state @@ -167,14 +167,14 @@ impl<'a> TrackedRenderPass<'a> { offset ); return; - } else { - trace!( - "set vertex buffer {}: {:?} ({})", - slot_index, - buffer_slice.id(), - offset - ); } + trace!( + "set vertex buffer {}: {:?} ({})", + slot_index, + buffer_slice.id(), + offset + ); + self.pass .set_vertex_buffer(slot_index as u32, *buffer_slice); self.state @@ -201,9 +201,8 @@ impl<'a> TrackedRenderPass<'a> { offset ); return; - } else { - trace!("set index buffer: {:?} ({})", buffer_slice.id(), offset); } + trace!("set index buffer: {:?} ({})", buffer_slice.id(), offset); self.pass.set_index_buffer(*buffer_slice, index_format); self.state .set_index_buffer(buffer_slice.id(), offset, index_format); diff --git a/crates/bevy_render/src/render_resource/shader.rs b/crates/bevy_render/src/render_resource/shader.rs index e8e955d47ceeb..91f5182569284 100644 --- a/crates/bevy_render/src/render_resource/shader.rs +++ b/crates/bevy_render/src/render_resource/shader.rs @@ -357,9 +357,8 @@ impl ShaderProcessor { Source::SpirV(source) => { if shader_defs.is_empty() { return Ok(ProcessedShader::SpirV(source.clone())); - } else { - return Err(ProcessShaderError::ShaderFormatDoesNotSupportShaderDefs); } + return Err(ProcessShaderError::ShaderFormatDoesNotSupportShaderDefs); } }; diff --git a/crates/bevy_render/src/renderer/graph_runner.rs b/crates/bevy_render/src/renderer/graph_runner.rs index 09a7056d76e4f..9ed24c6f5c552 100644 --- a/crates/bevy_render/src/renderer/graph_runner.rs +++ b/crates/bevy_render/src/renderer/graph_runner.rs @@ -102,9 +102,8 @@ impl RenderGraphRunner { expected: input_slot.slot_type, label: input_slot.name.clone().into(), }); - } else { - input_values.push(input_value.clone()); } + input_values.push(input_value.clone()); } else { return Err(RenderGraphRunnerError::MissingInput { slot_index: i, From f7f9cf20457165566598831ecd2dfe3edad10b2e Mon Sep 17 00:00:00 2001 From: Felix de Maneville Date: Tue, 18 Jan 2022 16:25:07 +0100 Subject: [PATCH 05/11] Additional clippy fixes --- .../bevy_reflect/bevy_reflect_derive/src/from_reflect.rs | 2 +- crates/bevy_reflect/bevy_reflect_derive/src/lib.rs | 2 +- crates/bevy_reflect/src/list.rs | 2 +- crates/bevy_tasks/src/iter/adapters.rs | 8 ++++---- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/from_reflect.rs b/crates/bevy_reflect/bevy_reflect_derive/src/from_reflect.rs index 68d18d36a6f4c..55e701d674862 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/from_reflect.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/from_reflect.rs @@ -15,7 +15,7 @@ pub fn impl_struct( field .ident .as_ref() - .map(|i| i.to_string()) + .map(Ident::to_string) .unwrap_or_else(|| index.to_string()) }) .collect::>(); diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index 1cd4feb79b9e1..fe8df06c7d8f5 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -175,7 +175,7 @@ fn impl_struct( field .ident .as_ref() - .map(|i| i.to_string()) + .map(Ident::to_string) .unwrap_or_else(|| index.to_string()) }) .collect::>(); diff --git a/crates/bevy_reflect/src/list.rs b/crates/bevy_reflect/src/list.rs index 6752b9d43861e..576585b6a1734 100644 --- a/crates/bevy_reflect/src/list.rs +++ b/crates/bevy_reflect/src/list.rs @@ -28,7 +28,7 @@ pub trait List: Reflect { fn clone_dynamic(&self) -> DynamicList { DynamicList { name: self.type_name().to_string(), - values: self.iter().map(|value| value.clone_value()).collect(), + values: self.iter().map(Reflect::clone_value).collect(), } } } diff --git a/crates/bevy_tasks/src/iter/adapters.rs b/crates/bevy_tasks/src/iter/adapters.rs index d05da201ad25d..c21d1966f8550 100644 --- a/crates/bevy_tasks/src/iter/adapters.rs +++ b/crates/bevy_tasks/src/iter/adapters.rs @@ -113,7 +113,7 @@ where // This extends each batch using the flatten. The other option is to // turn each IntoIter into its own batch. fn next_batch(&mut self) -> Option> { - self.iter.next_batch().map(|b| b.flatten()) + self.iter.next_batch().map(B::flatten) } } @@ -170,7 +170,7 @@ where T: 'a + Copy, { fn next_batch(&mut self) -> Option> { - self.iter.next_batch().map(|b| b.copied()) + self.iter.next_batch().map(B::copied) } } @@ -186,7 +186,7 @@ where T: 'a + Copy, { fn next_batch(&mut self) -> Option> { - self.iter.next_batch().map(|b| b.cloned()) + self.iter.next_batch().map(B::cloned) } } @@ -202,7 +202,7 @@ where P: ParallelIterator + Clone, { fn next_batch(&mut self) -> Option { - match self.curr.as_mut().and_then(|c| c.next_batch()) { + match self.curr.as_mut().and_then(P::next_batch) { batch @ Some(_) => batch, None => { self.curr = Some(self.iter.clone()); From 43274ee3ac4e7688946e44de523e9990475b1202 Mon Sep 17 00:00:00 2001 From: Felix de Maneville Date: Tue, 18 Jan 2022 16:34:47 +0100 Subject: [PATCH 06/11] Fixed color factoring mix up --- crates/bevy_render/src/color/mod.rs | 35 ++++++++++++++++++----------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/crates/bevy_render/src/color/mod.rs b/crates/bevy_render/src/color/mod.rs index 0a607efeea858..6a0a1e25e6004 100644 --- a/crates/bevy_render/src/color/mod.rs +++ b/crates/bevy_render/src/color/mod.rs @@ -503,14 +503,8 @@ impl AddAssign for Color { green, blue, alpha, - } => { - let rhs = rhs.as_rgba_f32(); - *red += rhs[0]; - *green += rhs[1]; - *blue += rhs[2]; - *alpha += rhs[3]; } - Self::RgbaLinear { + | Self::RgbaLinear { red, green, blue, @@ -813,8 +807,13 @@ impl Mul for Color { green, blue, alpha, - } - | Self::RgbaLinear { + } => Self::Rgba { + red: red * rhs.x, + green: green * rhs.y, + blue: blue * rhs.z, + alpha, + }, + Self::RgbaLinear { red, green, blue, @@ -877,8 +876,13 @@ impl Mul<[f32; 4]> for Color { green, blue, alpha, - } - | Self::RgbaLinear { + } => Self::Rgba { + red: red * rhs[0], + green: green * rhs[1], + blue: blue * rhs[2], + alpha: alpha * rhs[3], + }, + Self::RgbaLinear { red, green, blue, @@ -949,8 +953,13 @@ impl Mul<[f32; 3]> for Color { green, blue, alpha, - } - | Self::RgbaLinear { + } => Self::Rgba { + red: red * rhs[0], + green: green * rhs[1], + blue: blue * rhs[2], + alpha, + }, + Self::RgbaLinear { red, green, blue, From 7e2085da7078960bc74a11a2555d648d7b7fc86f Mon Sep 17 00:00:00 2001 From: Felix de Maneville Date: Wed, 19 Jan 2022 09:57:46 +0100 Subject: [PATCH 07/11] clippy::explicit_iter_loop --- crates/bevy_app/src/plugin_group.rs | 2 +- crates/bevy_asset/src/asset_server.rs | 8 ++++---- crates/bevy_asset/src/io/file_asset_io.rs | 2 +- crates/bevy_asset/src/loader.rs | 2 +- crates/bevy_core_pipeline/src/main_pass_2d.rs | 2 +- crates/bevy_core_pipeline/src/main_pass_3d.rs | 6 +++--- crates/bevy_ecs/src/archetype.rs | 2 +- crates/bevy_ecs/src/query/access.rs | 2 +- crates/bevy_ecs/src/query/state.rs | 8 ++++---- crates/bevy_ecs/src/schedule/executor.rs | 2 +- .../bevy_ecs/src/schedule/executor_parallel.rs | 4 ++-- crates/bevy_ecs/src/schedule/mod.rs | 2 +- crates/bevy_ecs/src/schedule/run_criteria.rs | 4 ++-- crates/bevy_ecs/src/schedule/stage.rs | 8 ++++---- crates/bevy_ecs/src/storage/table.rs | 4 ++-- crates/bevy_ecs/src/system/exclusive_system.rs | 2 +- crates/bevy_ecs/src/system/mod.rs | 4 ++-- crates/bevy_gltf/src/loader.rs | 2 +- crates/bevy_input/src/gamepad.rs | 16 ++++++++-------- crates/bevy_pbr/src/light.rs | 2 +- crates/bevy_pbr/src/render/light.rs | 2 +- crates/bevy_reflect/src/type_registry.rs | 2 +- crates/bevy_render/src/camera/active_cameras.rs | 2 +- crates/bevy_render/src/mesh/mesh/mod.rs | 4 ++-- crates/bevy_render/src/mesh/shape/mod.rs | 4 ++-- crates/bevy_scene/src/dynamic_scene.rs | 4 ++-- crates/bevy_scene/src/serde.rs | 2 +- crates/bevy_sprite/src/render/mod.rs | 12 ++++++------ crates/bevy_text/src/glyph_brush.rs | 2 +- crates/bevy_text/src/pipeline.rs | 2 +- crates/bevy_ui/src/render/mod.rs | 2 +- crates/bevy_ui/src/render/render_pass.rs | 2 +- 32 files changed, 62 insertions(+), 62 deletions(-) diff --git a/crates/bevy_app/src/plugin_group.rs b/crates/bevy_app/src/plugin_group.rs index aecb3dd05acda..30206f365dfa7 100644 --- a/crates/bevy_app/src/plugin_group.rs +++ b/crates/bevy_app/src/plugin_group.rs @@ -111,7 +111,7 @@ impl PluginGroupBuilder { /// Consumes the [`PluginGroupBuilder`] and [builds](Plugin::build) the contained [`Plugin`]s. pub fn finish(self, app: &mut App) { - for ty in self.order.iter() { + for ty in &self.order { if let Some(entry) = self.plugins.get(ty) { if entry.enabled { debug!("added plugin: {}", entry.plugin.name()); diff --git a/crates/bevy_asset/src/asset_server.rs b/crates/bevy_asset/src/asset_server.rs index e80052d0bab94..b6caa4c441d93 100644 --- a/crates/bevy_asset/src/asset_server.rs +++ b/crates/bevy_asset/src/asset_server.rs @@ -106,7 +106,7 @@ impl AssetServer { { let mut loaders = self.server.loaders.write(); let loader_index = loaders.len(); - for extension in loader.extensions().iter() { + for extension in loader.extensions() { self.server .extension_to_loader_index .write() @@ -344,11 +344,11 @@ impl AssetServer { }); // load asset dependencies and prepare asset type hashmap - for (label, loaded_asset) in load_context.labeled_assets.iter_mut() { + for (label, loaded_asset) in &mut load_context.labeled_assets { let label_id = LabelId::from(label.as_ref().map(|label| label.as_str())); let type_uuid = loaded_asset.value.as_ref().unwrap().type_uuid(); source_info.asset_types.insert(label_id, type_uuid); - for dependency in loaded_asset.dependencies.iter() { + for dependency in &loaded_asset.dependencies { self.load_untracked(dependency.clone(), false); } } @@ -473,7 +473,7 @@ impl AssetServer { fn create_assets_in_load_context(&self, load_context: &mut LoadContext) { let asset_lifecycles = self.server.asset_lifecycles.read(); - for (label, asset) in load_context.labeled_assets.iter_mut() { + for (label, asset) in &mut load_context.labeled_assets { let asset_value = asset .value .take() diff --git a/crates/bevy_asset/src/io/file_asset_io.rs b/crates/bevy_asset/src/io/file_asset_io.rs index da19166e6759b..62ddfacd6b11b 100644 --- a/crates/bevy_asset/src/io/file_asset_io.rs +++ b/crates/bevy_asset/src/io/file_asset_io.rs @@ -139,7 +139,7 @@ pub fn filesystem_watcher_system(asset_server: Res) { .. } = event { - for path in paths.iter() { + for path in &paths { if !changed.contains(path) { let relative_path = path.strip_prefix(&asset_io.root_path).unwrap(); let _ = asset_server.load_untracked(relative_path.into(), true); diff --git a/crates/bevy_asset/src/loader.rs b/crates/bevy_asset/src/loader.rs index 3c212ea64a576..2fc3c8ffb5a2a 100644 --- a/crates/bevy_asset/src/loader.rs +++ b/crates/bevy_asset/src/loader.rs @@ -132,7 +132,7 @@ impl<'a> LoadContext<'a> { pub fn get_asset_metas(&self) -> Vec { let mut asset_metas = Vec::new(); - for (label, asset) in self.labeled_assets.iter() { + for (label, asset) in &self.labeled_assets { asset_metas.push(AssetMeta { dependencies: asset.dependencies.clone(), label: label.clone(), diff --git a/crates/bevy_core_pipeline/src/main_pass_2d.rs b/crates/bevy_core_pipeline/src/main_pass_2d.rs index 034327c4b45e5..b0b96642089c4 100644 --- a/crates/bevy_core_pipeline/src/main_pass_2d.rs +++ b/crates/bevy_core_pipeline/src/main_pass_2d.rs @@ -63,7 +63,7 @@ impl Node for MainPass2dNode { let mut draw_functions = draw_functions.write(); let mut tracked_pass = TrackedRenderPass::new(render_pass); - for item in transparent_phase.items.iter() { + for item in &transparent_phase.items { let draw_function = draw_functions.get_mut(item.draw_function).unwrap(); draw_function.draw(world, &mut tracked_pass, view_entity, item); } diff --git a/crates/bevy_core_pipeline/src/main_pass_3d.rs b/crates/bevy_core_pipeline/src/main_pass_3d.rs index e4658ff6c8e3a..d885ef2892bad 100644 --- a/crates/bevy_core_pipeline/src/main_pass_3d.rs +++ b/crates/bevy_core_pipeline/src/main_pass_3d.rs @@ -82,7 +82,7 @@ impl Node for MainPass3dNode { .begin_render_pass(&pass_descriptor); let mut draw_functions = draw_functions.write(); let mut tracked_pass = TrackedRenderPass::new(render_pass); - for item in opaque_phase.items.iter() { + for item in &opaque_phase.items { let draw_function = draw_functions.get_mut(item.draw_function).unwrap(); draw_function.draw(world, &mut tracked_pass, view_entity, item); } @@ -116,7 +116,7 @@ impl Node for MainPass3dNode { .begin_render_pass(&pass_descriptor); let mut draw_functions = draw_functions.write(); let mut tracked_pass = TrackedRenderPass::new(render_pass); - for item in alpha_mask_phase.items.iter() { + for item in &alpha_mask_phase.items { let draw_function = draw_functions.get_mut(item.draw_function).unwrap(); draw_function.draw(world, &mut tracked_pass, view_entity, item); } @@ -154,7 +154,7 @@ impl Node for MainPass3dNode { .begin_render_pass(&pass_descriptor); let mut draw_functions = draw_functions.write(); let mut tracked_pass = TrackedRenderPass::new(render_pass); - for item in transparent_phase.items.iter() { + for item in &transparent_phase.items { let draw_function = draw_functions.get_mut(item.draw_function).unwrap(); draw_function.draw(world, &mut tracked_pass, view_entity, item); } diff --git a/crates/bevy_ecs/src/archetype.rs b/crates/bevy_ecs/src/archetype.rs index 524c22b5b0dac..976f75b4fab81 100644 --- a/crates/bevy_ecs/src/archetype.rs +++ b/crates/bevy_ecs/src/archetype.rs @@ -520,7 +520,7 @@ impl Archetypes { } pub fn clear_entities(&mut self) { - for archetype in self.archetypes.iter_mut() { + for archetype in &mut self.archetypes { archetype.clear_entities(); } } diff --git a/crates/bevy_ecs/src/query/access.rs b/crates/bevy_ecs/src/query/access.rs index 57df955082385..e5a14b393ac3a 100644 --- a/crates/bevy_ecs/src/query/access.rs +++ b/crates/bevy_ecs/src/query/access.rs @@ -208,7 +208,7 @@ impl FilteredAccessSet { // if combined unfiltered access is incompatible, check each filtered access for // compatibility if !filtered_access.access.is_compatible(&self.combined_access) { - for current_filtered_access in self.filtered_accesses.iter() { + for current_filtered_access in &self.filtered_accesses { if !current_filtered_access.is_compatible(filtered_access) { return current_filtered_access .access diff --git a/crates/bevy_ecs/src/query/state.rs b/crates/bevy_ecs/src/query/state.rs index c13b0dc75700b..91e38c6a16368 100644 --- a/crates/bevy_ecs/src/query/state.rs +++ b/crates/bevy_ecs/src/query/state.rs @@ -604,7 +604,7 @@ where ::init(world, &self.filter_state, last_change_tick, change_tick); if Q::Fetch::IS_DENSE && F::Fetch::IS_DENSE { let tables = &world.storages().tables; - for table_id in self.matched_table_ids.iter() { + for table_id in &self.matched_table_ids { let table = &tables[*table_id]; fetch.set_table(&self.fetch_state, table); filter.set_table(&self.filter_state, table); @@ -620,7 +620,7 @@ where } else { let archetypes = &world.archetypes; let tables = &world.storages().tables; - for archetype_id in self.matched_archetype_ids.iter() { + for archetype_id in &self.matched_archetype_ids { let archetype = &archetypes[*archetype_id]; fetch.set_archetype(&self.fetch_state, archetype, tables); filter.set_archetype(&self.filter_state, archetype, tables); @@ -664,7 +664,7 @@ where task_pool.scope(|scope| { if QF::IS_DENSE && F::Fetch::IS_DENSE { let tables = &world.storages().tables; - for table_id in self.matched_table_ids.iter() { + for table_id in &self.matched_table_ids { let table = &tables[*table_id]; let mut offset = 0; while offset < table.len() { @@ -696,7 +696,7 @@ where } } else { let archetypes = &world.archetypes; - for archetype_id in self.matched_archetype_ids.iter() { + for archetype_id in &self.matched_archetype_ids { let mut offset = 0; let archetype = &archetypes[*archetype_id]; while offset < archetype.len() { diff --git a/crates/bevy_ecs/src/schedule/executor.rs b/crates/bevy_ecs/src/schedule/executor.rs index ae746717c25e9..fb920d2967be8 100644 --- a/crates/bevy_ecs/src/schedule/executor.rs +++ b/crates/bevy_ecs/src/schedule/executor.rs @@ -49,7 +49,7 @@ impl SingleThreadedExecutor { let old_generation = std::mem::replace(&mut self.archetype_generation, new_generation); let archetype_index_range = old_generation.value()..new_generation.value(); - for archetype in archetypes.archetypes[archetype_index_range].iter() { + for archetype in &archetypes.archetypes[archetype_index_range] { for container in systems.iter_mut() { let system = container.system_mut(); system.new_archetype(archetype); diff --git a/crates/bevy_ecs/src/schedule/executor_parallel.rs b/crates/bevy_ecs/src/schedule/executor_parallel.rs index c3448f203f2a9..6caa2c7f4425a 100644 --- a/crates/bevy_ecs/src/schedule/executor_parallel.rs +++ b/crates/bevy_ecs/src/schedule/executor_parallel.rs @@ -84,7 +84,7 @@ impl ParallelSystemExecutor for ParallelExecutor { self.should_run.grow(systems.len()); // Construct scheduling data for systems. - for container in systems.iter() { + for container in systems { let dependencies_total = container.dependencies().len(); let system = container.system(); let (start_sender, start_receiver) = async_channel::bounded(1); @@ -166,7 +166,7 @@ impl ParallelExecutor { let old_generation = std::mem::replace(&mut self.archetype_generation, new_generation); let archetype_index_range = old_generation.value()..new_generation.value(); - for archetype in archetypes.archetypes[archetype_index_range].iter() { + for archetype in &archetypes.archetypes[archetype_index_range] { for (index, container) in systems.iter_mut().enumerate() { let meta = &mut self.system_metadata[index]; let system = container.system_mut(); diff --git a/crates/bevy_ecs/src/schedule/mod.rs b/crates/bevy_ecs/src/schedule/mod.rs index 605efe4654a2f..49c7d16d381f5 100644 --- a/crates/bevy_ecs/src/schedule/mod.rs +++ b/crates/bevy_ecs/src/schedule/mod.rs @@ -335,7 +335,7 @@ impl Schedule { /// Executes each [`Stage`] contained in the schedule, one at a time. pub fn run_once(&mut self, world: &mut World) { - for label in self.stage_order.iter() { + for label in &self.stage_order { #[cfg(feature = "trace")] let stage_span = bevy_utils::tracing::info_span!("stage", name = ?label); #[cfg(feature = "trace")] diff --git a/crates/bevy_ecs/src/schedule/run_criteria.rs b/crates/bevy_ecs/src/schedule/run_criteria.rs index b6a6bc7cbf724..8b7591e956791 100644 --- a/crates/bevy_ecs/src/schedule/run_criteria.rs +++ b/crates/bevy_ecs/src/schedule/run_criteria.rs @@ -77,7 +77,7 @@ impl BoxedRunCriteria { let old_generation = std::mem::replace(&mut self.archetype_generation, new_generation); let archetype_index_range = old_generation.value()..new_generation.value(); - for archetype in archetypes.archetypes[archetype_index_range].iter() { + for archetype in &archetypes.archetypes[archetype_index_range] { run_criteria.new_archetype(archetype); } @@ -141,7 +141,7 @@ impl RunCriteriaContainer { let new_generation = archetypes.generation(); let old_generation = std::mem::replace(&mut self.archetype_generation, new_generation); let archetype_index_range = old_generation.value()..new_generation.value(); - for archetype in archetypes.archetypes[archetype_index_range].iter() { + for archetype in &archetypes.archetypes[archetype_index_range] { match &mut self.inner { RunCriteriaInner::Single(system) => { system.new_archetype(archetype); diff --git a/crates/bevy_ecs/src/schedule/stage.rs b/crates/bevy_ecs/src/schedule/stage.rs index 19b3ddeb42c41..3040ea3e322b3 100644 --- a/crates/bevy_ecs/src/schedule/stage.rs +++ b/crates/bevy_ecs/src/schedule/stage.rs @@ -208,7 +208,7 @@ impl SystemStage { } pub fn apply_buffers(&mut self, world: &mut World) { - for container in self.parallel.iter_mut() { + for container in &mut self.parallel { let system = container.system_mut(); #[cfg(feature = "trace")] let span = bevy_utils::tracing::info_span!("system_commands", name = &*system.name()); @@ -261,7 +261,7 @@ impl SystemStage { let (run_criteria, mut systems) = system_set.bake(); let set_run_criteria_index = run_criteria.and_then(|criteria| { // validate that no systems have criteria - for system in systems.iter_mut() { + for system in &mut systems { if let Some(name) = match system { SystemDescriptor::Exclusive(descriptor) => descriptor .run_criteria @@ -285,7 +285,7 @@ impl SystemStage { Some(self.add_run_criteria_internal(descriptor)) } RunCriteriaDescriptorOrLabel::Label(label) => { - for system in systems.iter_mut() { + for system in &mut systems { match system { SystemDescriptor::Exclusive(descriptor) => { descriptor.run_criteria = @@ -611,7 +611,7 @@ impl SystemStage { .map(|label| (label.clone(), order_inverted[index].0)) }) .collect(); - for criteria in self.run_criteria.iter_mut() { + for criteria in &mut self.run_criteria { if let RunCriteriaInner::Piped { input: parent, .. } = &mut criteria.inner { let label = &criteria.after[0]; *parent = *labels.get(label).unwrap_or_else(|| { diff --git a/crates/bevy_ecs/src/storage/table.rs b/crates/bevy_ecs/src/storage/table.rs index 16a5a2bbe1438..e43645399fa5f 100644 --- a/crates/bevy_ecs/src/storage/table.rs +++ b/crates/bevy_ecs/src/storage/table.rs @@ -495,13 +495,13 @@ impl Tables { } pub fn clear(&mut self) { - for table in self.tables.iter_mut() { + for table in &mut self.tables { table.clear(); } } pub(crate) fn check_change_ticks(&mut self, change_tick: u32) { - for table in self.tables.iter_mut() { + for table in &mut self.tables { table.check_change_ticks(change_tick); } } diff --git a/crates/bevy_ecs/src/system/exclusive_system.rs b/crates/bevy_ecs/src/system/exclusive_system.rs index 1d7902650d70e..209ee7c9752bb 100644 --- a/crates/bevy_ecs/src/system/exclusive_system.rs +++ b/crates/bevy_ecs/src/system/exclusive_system.rs @@ -84,7 +84,7 @@ impl ExclusiveSystem for ExclusiveSystemCoerced { let old_generation = std::mem::replace(&mut self.archetype_generation, new_generation); let archetype_index_range = old_generation.value()..new_generation.value(); - for archetype in archetypes.archetypes[archetype_index_range].iter() { + for archetype in &archetypes.archetypes[archetype_index_range] { self.system.new_archetype(archetype); } diff --git a/crates/bevy_ecs/src/system/mod.rs b/crates/bevy_ecs/src/system/mod.rs index a5b4c68bce010..555823b3a6fd9 100644 --- a/crates/bevy_ecs/src/system/mod.rs +++ b/crates/bevy_ecs/src/system/mod.rs @@ -130,7 +130,7 @@ mod tests { world.spawn().insert(A); system.initialize(&mut world); - for archetype in world.archetypes.iter() { + for archetype in &world.archetypes { system.new_archetype(archetype); } system.run((), &mut world); @@ -556,7 +556,7 @@ mod tests { let bundle_info = bundles.get(bundle_id).unwrap(); let mut bundle_components = bundle_info.components().to_vec(); bundle_components.sort(); - for component_id in bundle_components.iter() { + for component_id in &bundle_components { assert!( components.get_info(*component_id).is_some(), "every bundle component exists in Components" diff --git a/crates/bevy_gltf/src/loader.rs b/crates/bevy_gltf/src/loader.rs index 75187f1147b7e..b66d8093d54d8 100644 --- a/crates/bevy_gltf/src/loader.rs +++ b/crates/bevy_gltf/src/loader.rs @@ -760,7 +760,7 @@ fn resolve_node_hierarchy( .into_iter() .enumerate() .map(|(i, (label, node, children))| { - for child in children.iter() { + for child in &children { if let Some(parent) = parents.get_mut(*child) { *parent = Some(i); } else if !has_errored { diff --git a/crates/bevy_input/src/gamepad.rs b/crates/bevy_input/src/gamepad.rs index ad0ce2582aa16..fc6ccc9464f42 100644 --- a/crates/bevy_input/src/gamepad.rs +++ b/crates/bevy_input/src/gamepad.rs @@ -279,24 +279,24 @@ pub fn gamepad_event_system( match event { GamepadEventType::Connected => { events.send(GamepadEvent(gamepad, event.clone())); - for button_type in ALL_BUTTON_TYPES.iter() { - let gamepad_button = GamepadButton(gamepad, *button_type); + for button_type in ALL_BUTTON_TYPES { + let gamepad_button = GamepadButton(gamepad, button_type); button_input.reset(gamepad_button); button_axis.set(gamepad_button, 0.0); } - for axis_type in ALL_AXIS_TYPES.iter() { - axis.set(GamepadAxis(gamepad, *axis_type), 0.0); + for axis_type in ALL_AXIS_TYPES { + axis.set(GamepadAxis(gamepad, axis_type), 0.0); } } GamepadEventType::Disconnected => { events.send(GamepadEvent(gamepad, event.clone())); - for button_type in ALL_BUTTON_TYPES.iter() { - let gamepad_button = GamepadButton(gamepad, *button_type); + for button_type in ALL_BUTTON_TYPES { + let gamepad_button = GamepadButton(gamepad, button_type); button_input.reset(gamepad_button); button_axis.remove(gamepad_button); } - for axis_type in ALL_AXIS_TYPES.iter() { - axis.remove(GamepadAxis(gamepad, *axis_type)); + for axis_type in ALL_AXIS_TYPES { + axis.remove(GamepadAxis(gamepad, axis_type)); } } GamepadEventType::AxisChanged(axis_type, value) => { diff --git a/crates/bevy_pbr/src/light.rs b/crates/bevy_pbr/src/light.rs index 329bfc53c72fa..402a42eb38eaa 100644 --- a/crates/bevy_pbr/src/light.rs +++ b/crates/bevy_pbr/src/light.rs @@ -603,7 +603,7 @@ pub fn assign_lights_to_clusters( } } - for cluster_lights in clusters_lights.iter_mut() { + for cluster_lights in &mut clusters_lights { cluster_lights.entities.shrink_to_fit(); } diff --git a/crates/bevy_pbr/src/render/light.rs b/crates/bevy_pbr/src/render/light.rs index 851e1688233b3..cdd7da44b4bc5 100644 --- a/crates/bevy_pbr/src/render/light.rs +++ b/crates/bevy_pbr/src/render/light.rs @@ -1237,7 +1237,7 @@ impl Node for ShadowPassNode { .begin_render_pass(&pass_descriptor); let mut draw_functions = draw_functions.write(); let mut tracked_pass = TrackedRenderPass::new(render_pass); - for item in shadow_phase.items.iter() { + for item in &shadow_phase.items { let draw_function = draw_functions.get_mut(item.draw_function).unwrap(); draw_function.draw(world, &mut tracked_pass, view_light_entity, item); } diff --git a/crates/bevy_reflect/src/type_registry.rs b/crates/bevy_reflect/src/type_registry.rs index 7ac4c78148ec7..e76fa7699eabc 100644 --- a/crates/bevy_reflect/src/type_registry.rs +++ b/crates/bevy_reflect/src/type_registry.rs @@ -276,7 +276,7 @@ impl TypeRegistration { impl Clone for TypeRegistration { fn clone(&self) -> Self { let mut data = HashMap::default(); - for (id, type_data) in self.data.iter() { + for (id, type_data) in &self.data { data.insert(*id, (*type_data).clone_type_data()); } diff --git a/crates/bevy_render/src/camera/active_cameras.rs b/crates/bevy_render/src/camera/active_cameras.rs index 8f7af81f1279a..42cebc65a67f2 100644 --- a/crates/bevy_render/src/camera/active_cameras.rs +++ b/crates/bevy_render/src/camera/active_cameras.rs @@ -52,7 +52,7 @@ pub fn active_cameras_system( mut active_cameras: ResMut, query: Query<(Entity, &Camera)>, ) { - for (name, active_camera) in active_cameras.cameras.iter_mut() { + for (name, active_camera) in &mut active_cameras.cameras { if active_camera .entity .map_or(false, |entity| query.get(entity).is_err()) diff --git a/crates/bevy_render/src/mesh/mesh/mod.rs b/crates/bevy_render/src/mesh/mesh/mod.rs index 324e3b2ee9a92..b29227d18d8a4 100644 --- a/crates/bevy_render/src/mesh/mesh/mod.rs +++ b/crates/bevy_render/src/mesh/mesh/mod.rs @@ -162,7 +162,7 @@ impl Mesh { /// Panics if the attributes have different vertex counts. pub fn count_vertices(&self) -> usize { let mut vertex_count: Option = None; - for (attribute_name, attribute_data) in self.attributes.iter() { + for (attribute_name, attribute_data) in &self.attributes { let attribute_len = attribute_data.len(); if let Some(previous_vertex_count) = vertex_count { assert_eq!(previous_vertex_count, attribute_len, @@ -230,7 +230,7 @@ impl Mesh { Some(indices) => indices, None => return, }; - for (_, attributes) in self.attributes.iter_mut() { + for attributes in self.attributes.values_mut() { let indices = indices.iter(); match attributes { VertexAttributeValues::Float32(vec) => *vec = duplicate(vec, indices), diff --git a/crates/bevy_render/src/mesh/shape/mod.rs b/crates/bevy_render/src/mesh/shape/mod.rs index f27fda9074f23..d21b693730eb1 100644 --- a/crates/bevy_render/src/mesh/shape/mod.rs +++ b/crates/bevy_render/src/mesh/shape/mod.rs @@ -207,7 +207,7 @@ impl From for Mesh { let mut positions = Vec::<[f32; 3]>::new(); let mut normals = Vec::<[f32; 3]>::new(); let mut uvs = Vec::<[f32; 2]>::new(); - for (position, normal, uv) in vertices.iter() { + for (position, normal, uv) in &vertices { positions.push(*position); normals.push(*normal); uvs.push(*uv); @@ -251,7 +251,7 @@ impl From for Mesh { let mut positions = Vec::new(); let mut normals = Vec::new(); let mut uvs = Vec::new(); - for (position, normal, uv) in vertices.iter() { + for (position, normal, uv) in &vertices { positions.push(*position); normals.push(*normal); uvs.push(*uv); diff --git a/crates/bevy_scene/src/dynamic_scene.rs b/crates/bevy_scene/src/dynamic_scene.rs index 22c4ffe5e614d..0cbf8b688ef59 100644 --- a/crates/bevy_scene/src/dynamic_scene.rs +++ b/crates/bevy_scene/src/dynamic_scene.rs @@ -82,7 +82,7 @@ impl DynamicScene { let registry = world.get_resource::().unwrap().clone(); let type_registry = registry.read(); - for scene_entity in self.entities.iter() { + for scene_entity in &self.entities { // Fetch the entity with the given entity id from the `entity_map` // or spawn a new entity with a transiently unique id if there is // no corresponding entry. @@ -91,7 +91,7 @@ impl DynamicScene { .or_insert_with(|| world.spawn().id()); // Apply/ add each component to the given entity. - for component in scene_entity.components.iter() { + for component in &scene_entity.components { let registration = type_registry .get_with_name(component.type_name()) .ok_or_else(|| SceneSpawnError::UnregisteredType { diff --git a/crates/bevy_scene/src/serde.rs b/crates/bevy_scene/src/serde.rs index a90d1f0ead50c..1358aa4a0d7c2 100644 --- a/crates/bevy_scene/src/serde.rs +++ b/crates/bevy_scene/src/serde.rs @@ -27,7 +27,7 @@ impl<'a> Serialize for SceneSerializer<'a> { S: serde::Serializer, { let mut state = serializer.serialize_seq(Some(self.scene.entities.len()))?; - for entity in self.scene.entities.iter() { + for entity in &self.scene.entities { state.serialize_element(&EntitySerializer { entity, registry: self.registry, diff --git a/crates/bevy_sprite/src/render/mod.rs b/crates/bevy_sprite/src/render/mod.rs index 89d1e729f620f..6ae35e384d48f 100644 --- a/crates/bevy_sprite/src/render/mod.rs +++ b/crates/bevy_sprite/src/render/mod.rs @@ -513,10 +513,10 @@ pub fn queue_sprites( | ((color[1] * 255.0) as u32) << 8 | ((color[2] * 255.0) as u32) << 16 | ((color[3] * 255.0) as u32) << 24; - for i in QUAD_INDICES.iter() { + for i in QUAD_INDICES { sprite_meta.colored_vertices.push(ColoredSpriteVertex { - position: positions[*i], - uv: uvs[*i].into(), + position: positions[i], + uv: uvs[i].into(), color, }); } @@ -532,10 +532,10 @@ pub fn queue_sprites( batch_range: Some(item_start..item_end), }); } else { - for i in QUAD_INDICES.iter() { + for i in QUAD_INDICES { sprite_meta.vertices.push(SpriteVertex { - position: positions[*i], - uv: uvs[*i].into(), + position: positions[i], + uv: uvs[i].into(), }); } let item_start = index; diff --git a/crates/bevy_text/src/glyph_brush.rs b/crates/bevy_text/src/glyph_brush.rs index 37f8e9d9c8050..d4244667172c5 100644 --- a/crates/bevy_text/src/glyph_brush.rs +++ b/crates/bevy_text/src/glyph_brush.rs @@ -73,7 +73,7 @@ impl GlyphBrush { let mut max_y = std::f32::MIN; let mut min_x = std::f32::MAX; - for sg in glyphs.iter() { + for sg in &glyphs { let glyph = &sg.glyph; let scaled_font = sections_data[sg.section_index].3; max_y = max_y.max(glyph.position.y - scaled_font.descent()); diff --git a/crates/bevy_text/src/pipeline.rs b/crates/bevy_text/src/pipeline.rs index 5a4604938f14d..8c13d1a3cec25 100644 --- a/crates/bevy_text/src/pipeline.rs +++ b/crates/bevy_text/src/pipeline.rs @@ -103,7 +103,7 @@ impl TextPipeline { let mut max_x: f32 = std::f32::MIN; let mut max_y: f32 = std::f32::MIN; - for sg in section_glyphs.iter() { + for sg in §ion_glyphs { let scaled_font = scaled_fonts[sg.section_index]; let glyph = &sg.glyph; min_x = min_x.min(glyph.position.x); diff --git a/crates/bevy_ui/src/render/mod.rs b/crates/bevy_ui/src/render/mod.rs index a2f955c24720c..6af6a2ebe3a77 100644 --- a/crates/bevy_ui/src/render/mod.rs +++ b/crates/bevy_ui/src/render/mod.rs @@ -290,7 +290,7 @@ pub fn prepare_uinodes( let mut end = 0; let mut current_batch_handle = Default::default(); let mut last_z = 0.0; - for extracted_uinode in extracted_uinodes.uinodes.iter() { + for extracted_uinode in &extracted_uinodes.uinodes { if current_batch_handle != extracted_uinode.image { if start != end { commands.spawn_bundle((UiBatch { diff --git a/crates/bevy_ui/src/render/render_pass.rs b/crates/bevy_ui/src/render/render_pass.rs index 2ad7357bde8ae..7c1185cc39be1 100644 --- a/crates/bevy_ui/src/render/render_pass.rs +++ b/crates/bevy_ui/src/render/render_pass.rs @@ -92,7 +92,7 @@ impl bevy_render::render_graph::Node for UiPassNode { let mut draw_functions = draw_functions.write(); let mut tracked_pass = TrackedRenderPass::new(render_pass); - for item in transparent_phase.items.iter() { + for item in &transparent_phase.items { let draw_function = draw_functions.get_mut(item.draw_function).unwrap(); draw_function.draw(world, &mut tracked_pass, view_entity, item); } From 7d6d12ba82a91b93fcf988f5186b0a3fd27da2bf Mon Sep 17 00:00:00 2001 From: Felix de Maneville Date: Wed, 19 Jan 2022 10:14:48 +0100 Subject: [PATCH 08/11] clippy::semicolon_if_nothing_is_returned --- crates/bevy_asset/src/assets.rs | 8 ++++---- crates/bevy_asset/src/loader.rs | 2 +- crates/bevy_core/src/float_ord.rs | 4 ++-- crates/bevy_core/src/time/fixed_timestep.rs | 2 +- crates/bevy_core/src/time/timer.rs | 2 +- crates/bevy_core_pipeline/src/lib.rs | 2 +- crates/bevy_diagnostic/src/diagnostic.rs | 2 +- .../bevy_diagnostic/src/log_diagnostics_plugin.rs | 4 ++-- crates/bevy_ecs/src/component.rs | 2 +- crates/bevy_ecs/src/entity/mod.rs | 2 +- crates/bevy_ecs/src/query/fetch.rs | 6 +++--- crates/bevy_ecs/src/schedule/stage.rs | 10 +++++----- crates/bevy_ecs/src/storage/blob_vec.rs | 2 +- crates/bevy_ecs/src/storage/table.rs | 2 +- crates/bevy_ecs/src/system/commands/mod.rs | 6 +++--- crates/bevy_ecs/src/system/query.rs | 8 ++++---- crates/bevy_ecs/src/world/entity_ref.rs | 4 ++-- crates/bevy_gltf/src/loader.rs | 2 +- crates/bevy_input/src/gamepad.rs | 4 ++-- crates/bevy_pbr/src/light.rs | 2 +- crates/bevy_pbr/src/material.rs | 2 +- crates/bevy_pbr/src/pbr_material.rs | 2 +- crates/bevy_reflect/bevy_reflect_derive/src/lib.rs | 6 +++--- crates/bevy_reflect/src/impls/std.rs | 2 +- crates/bevy_reflect/src/map.rs | 2 +- crates/bevy_reflect/src/struct_trait.rs | 2 +- crates/bevy_reflect/src/tuple.rs | 2 +- crates/bevy_reflect/src/tuple_struct.rs | 2 +- crates/bevy_render/src/camera/mod.rs | 2 +- crates/bevy_render/src/color/mod.rs | 2 +- crates/bevy_render/src/render_asset.rs | 2 +- crates/bevy_render/src/render_phase/draw_state.rs | 12 ++++++------ crates/bevy_render/src/render_resource/buffer.rs | 2 +- crates/bevy_render/src/renderer/render_device.rs | 4 ++-- crates/bevy_scene/src/scene_spawner.rs | 4 ++-- crates/bevy_sprite/src/texture_atlas.rs | 2 +- crates/bevy_sprite/src/texture_atlas_builder.rs | 2 +- crates/bevy_tasks/src/iter/mod.rs | 4 ++-- crates/bevy_ui/src/update.rs | 2 +- crates/bevy_window/src/window.rs | 2 +- crates/bevy_winit/src/lib.rs | 13 +++++++------ 41 files changed, 75 insertions(+), 74 deletions(-) diff --git a/crates/bevy_asset/src/assets.rs b/crates/bevy_asset/src/assets.rs index d0120816a28ae..131ea5aff0fe4 100644 --- a/crates/bevy_asset/src/assets.rs +++ b/crates/bevy_asset/src/assets.rs @@ -216,14 +216,14 @@ impl Assets { /// /// Keeps the allocated memory for reuse. pub fn clear(&mut self) { - self.assets.clear() + self.assets.clear(); } /// Reserves capacity for at least additional more elements to be inserted into the assets. /// /// The collection may reserve more space to avoid frequent reallocations. pub fn reserve(&mut self, additional: usize) { - self.assets.reserve(additional) + self.assets.reserve(additional); } /// Shrinks the capacity of the asset map as much as possible. @@ -231,14 +231,14 @@ impl Assets { /// It will drop down as much as possible while maintaining the internal rules and possibly /// leaving some space in accordance with the resize policy. pub fn shrink_to_fit(&mut self) { - self.assets.shrink_to_fit() + self.assets.shrink_to_fit(); } pub fn asset_event_system(mut events: EventWriter>, mut assets: ResMut) { // Check if the events are empty before calling `drain`. // As `drain` triggers change detection. if !assets.events.is_empty() { - events.send_batch(assets.events.drain()) + events.send_batch(assets.events.drain()); } } diff --git a/crates/bevy_asset/src/loader.rs b/crates/bevy_asset/src/loader.rs index 2fc3c8ffb5a2a..c7532f6a6d9cf 100644 --- a/crates/bevy_asset/src/loader.rs +++ b/crates/bevy_asset/src/loader.rs @@ -182,7 +182,7 @@ impl AssetLifecycle for AssetLifecycleChannel { id, version, })) - .unwrap() + .unwrap(); } else { panic!( "Failed to downcast asset to {}.", diff --git a/crates/bevy_core/src/float_ord.rs b/crates/bevy_core/src/float_ord.rs index 42f8987109b27..dc297b4226d56 100644 --- a/crates/bevy_core/src/float_ord.rs +++ b/crates/bevy_core/src/float_ord.rs @@ -41,10 +41,10 @@ impl Hash for FloatOrd { fn hash(&self, state: &mut H) { if self.0.is_nan() { // Ensure all NaN representations hash to the same value - state.write(bytemuck::bytes_of(&f32::NAN)) + state.write(bytemuck::bytes_of(&f32::NAN)); } else if self.0 == 0.0 { // Ensure both zeroes hash to the same value - state.write(bytemuck::bytes_of(&0.0f32)) + state.write(bytemuck::bytes_of(&0.0f32)); } else { state.write(bytemuck::bytes_of(&self.0)); } diff --git a/crates/bevy_core/src/time/fixed_timestep.rs b/crates/bevy_core/src/time/fixed_timestep.rs index 03d9ddf5f52c9..90edd5630f6ff 100644 --- a/crates/bevy_core/src/time/fixed_timestep.rs +++ b/crates/bevy_core/src/time/fixed_timestep.rs @@ -197,7 +197,7 @@ impl System for FixedTimestep { } fn apply_buffers(&mut self, world: &mut World) { - self.internal_system.apply_buffers(world) + self.internal_system.apply_buffers(world); } fn initialize(&mut self, world: &mut World) { diff --git a/crates/bevy_core/src/time/timer.rs b/crates/bevy_core/src/time/timer.rs index 85503fb986cd7..0b4bf67a8f752 100644 --- a/crates/bevy_core/src/time/timer.rs +++ b/crates/bevy_core/src/time/timer.rs @@ -182,7 +182,7 @@ impl Timer { self.stopwatch.reset(); self.finished = self.just_finished(); } - self.repeating = repeating + self.repeating = repeating; } /// Advance the timer by `delta` seconds. diff --git a/crates/bevy_core_pipeline/src/lib.rs b/crates/bevy_core_pipeline/src/lib.rs index 88b06f93cbb75..c705e93c02e81 100644 --- a/crates/bevy_core_pipeline/src/lib.rs +++ b/crates/bevy_core_pipeline/src/lib.rs @@ -331,7 +331,7 @@ pub fn extract_clear_color(clear_color: Res, mut render_world: ResMu // If the clear color has changed if clear_color.is_changed() { // Update the clear color resource in the render world - render_world.insert_resource(clear_color.clone()) + render_world.insert_resource(clear_color.clone()); } } diff --git a/crates/bevy_diagnostic/src/diagnostic.rs b/crates/bevy_diagnostic/src/diagnostic.rs index d38100767ebc5..420901c2d8682 100644 --- a/crates/bevy_diagnostic/src/diagnostic.rs +++ b/crates/bevy_diagnostic/src/diagnostic.rs @@ -65,7 +65,7 @@ impl Diagnostic { "Diagnostic {:?} has name longer than {} characters, and so might overflow in the LogDiagnosticsPlugin\ Consider using a shorter name.", name, MAX_DIAGNOSTIC_NAME_WIDTH - ) + ); } Self { id, diff --git a/crates/bevy_diagnostic/src/log_diagnostics_plugin.rs b/crates/bevy_diagnostic/src/log_diagnostics_plugin.rs index b0f48b2735109..853eb380b1ab8 100644 --- a/crates/bevy_diagnostic/src/log_diagnostics_plugin.rs +++ b/crates/bevy_diagnostic/src/log_diagnostics_plugin.rs @@ -97,7 +97,7 @@ impl LogDiagnosticsPlugin { Self::log_diagnostic(diagnostic); } }, - ) + ); } } @@ -118,7 +118,7 @@ impl LogDiagnosticsPlugin { debug!("{:#?}\n", diagnostic); } }, - ) + ); } } } diff --git a/crates/bevy_ecs/src/component.rs b/crates/bevy_ecs/src/component.rs index a1481f7053159..e046b6d0b48ab 100644 --- a/crates/bevy_ecs/src/component.rs +++ b/crates/bevy_ecs/src/component.rs @@ -180,7 +180,7 @@ pub struct ComponentDescriptor { impl ComponentDescriptor { // SAFETY: The pointer points to a valid value of type `T` and it is safe to drop this value. unsafe fn drop_ptr(x: *mut u8) { - x.cast::().drop_in_place() + x.cast::().drop_in_place(); } pub fn new() -> Self { diff --git a/crates/bevy_ecs/src/entity/mod.rs b/crates/bevy_ecs/src/entity/mod.rs index ddb908b21c13c..6a1a564b30b85 100644 --- a/crates/bevy_ecs/src/entity/mod.rs +++ b/crates/bevy_ecs/src/entity/mod.rs @@ -541,7 +541,7 @@ impl Entities { unsafe { self.flush(|_entity, location| { location.archetype_id = ArchetypeId::INVALID; - }) + }); } } diff --git a/crates/bevy_ecs/src/query/fetch.rs b/crates/bevy_ecs/src/query/fetch.rs index f9963f44d6586..5b541d5171a43 100644 --- a/crates/bevy_ecs/src/query/fetch.rs +++ b/crates/bevy_ecs/src/query/fetch.rs @@ -254,7 +254,7 @@ unsafe impl FetchState for ReadState { panic!("&{} conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.", std::any::type_name::()); } - access.add_read(self.component_id) + access.add_read(self.component_id); } fn update_archetype_component_access( @@ -705,7 +705,7 @@ unsafe impl FetchState for OptionState { ) { if self.state.matches_archetype(archetype) { self.state - .update_archetype_component_access(archetype, access) + .update_archetype_component_access(archetype, access); } } @@ -868,7 +868,7 @@ unsafe impl FetchState for ChangeTrackersState { panic!("ChangeTrackers<{}> conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.", std::any::type_name::()); } - access.add_read(self.component_id) + access.add_read(self.component_id); } fn update_archetype_component_access( diff --git a/crates/bevy_ecs/src/schedule/stage.rs b/crates/bevy_ecs/src/schedule/stage.rs index 3040ea3e322b3..6b652dd13b517 100644 --- a/crates/bevy_ecs/src/schedule/stage.rs +++ b/crates/bevy_ecs/src/schedule/stage.rs @@ -289,11 +289,11 @@ impl SystemStage { match system { SystemDescriptor::Exclusive(descriptor) => { descriptor.run_criteria = - Some(RunCriteriaDescriptorOrLabel::Label(label.clone())) + Some(RunCriteriaDescriptorOrLabel::Label(label.clone())); } SystemDescriptor::Parallel(descriptor) => { descriptor.run_criteria = - Some(RunCriteriaDescriptorOrLabel::Label(label.clone())) + Some(RunCriteriaDescriptorOrLabel::Label(label.clone())); } } } @@ -744,7 +744,7 @@ fn find_ambiguities(systems: &[impl SystemContainer]) -> Vec<(usize, usize, Vec< if let (Some(a), Some(b)) = (a_access, b_access) { let conflicts = a.get_conflicts(b); if !conflicts.is_empty() { - ambiguities.push((index_a, index_b, conflicts)) + ambiguities.push((index_a, index_b, conflicts)); } } else { ambiguities.push((index_a, index_b, Vec::new())); @@ -908,7 +908,7 @@ impl Stage for SystemStage { ShouldRun::YesAndCheckAgain | ShouldRun::NoAndCheckAgain => { match &mut criteria.inner { RunCriteriaInner::Single(system) => { - criteria.should_run = system.run((), world) + criteria.should_run = system.run((), world); } RunCriteriaInner::Piped { input: parent, @@ -916,7 +916,7 @@ impl Stage for SystemStage { .. } => { criteria.should_run = - system.run(run_criteria[*parent].should_run, world) + system.run(run_criteria[*parent].should_run, world); } } match criteria.should_run { diff --git a/crates/bevy_ecs/src/storage/blob_vec.rs b/crates/bevy_ecs/src/storage/blob_vec.rs index f92f3df72866c..8a3a775dbe8f3 100644 --- a/crates/bevy_ecs/src/storage/blob_vec.rs +++ b/crates/bevy_ecs/src/storage/blob_vec.rs @@ -180,7 +180,7 @@ impl BlobVec { pub unsafe fn swap_remove_and_drop_unchecked(&mut self, index: usize) { debug_assert!(index < self.len()); let value = self.swap_remove_and_forget_unchecked(index); - (self.drop)(value) + (self.drop)(value); } /// # Safety diff --git a/crates/bevy_ecs/src/storage/table.rs b/crates/bevy_ecs/src/storage/table.rs index e43645399fa5f..714fb566719ed 100644 --- a/crates/bevy_ecs/src/storage/table.rs +++ b/crates/bevy_ecs/src/storage/table.rs @@ -221,7 +221,7 @@ impl Table { self.columns.insert( component_info.id(), Column::with_capacity(component_info, self.entities.capacity()), - ) + ); } /// Removes the entity at the given row and returns the entity swapped in to replace it (if an diff --git a/crates/bevy_ecs/src/system/commands/mod.rs b/crates/bevy_ecs/src/system/commands/mod.rs index 01b7b5a51ddc0..61eaae0e366ad 100644 --- a/crates/bevy_ecs/src/system/commands/mod.rs +++ b/crates/bevy_ecs/src/system/commands/mod.rs @@ -107,7 +107,7 @@ impl<'w, 's> Commands<'w, 's> { /// Spawns a [`Bundle`] without pre-allocating an [`Entity`]. The [`Entity`] will be allocated /// when this [`Command`] is applied. pub fn spawn_and_forget(&mut self, bundle: impl Bundle) { - self.queue.push(Spawn { bundle }) + self.queue.push(Spawn { bundle }); } /// Creates a new entity with the components contained in `bundle`. @@ -284,7 +284,7 @@ impl<'w, 's> Commands<'w, 's> { /// # system.system(); /// ``` pub fn insert_resource(&mut self, resource: T) { - self.queue.push(InsertResource { resource }) + self.queue.push(InsertResource { resource }); } /// Removes a resource from the [`World`]. @@ -534,7 +534,7 @@ impl<'w, 's, 'a> EntityCommands<'w, 's, 'a> { pub fn despawn(&mut self) { self.commands.add(Despawn { entity: self.entity, - }) + }); } /// Returns the underlying [`Commands`]. diff --git a/crates/bevy_ecs/src/system/query.rs b/crates/bevy_ecs/src/system/query.rs index fa997a0e40dec..c6914e8f34984 100644 --- a/crates/bevy_ecs/src/system/query.rs +++ b/crates/bevy_ecs/src/system/query.rs @@ -464,7 +464,7 @@ where f, self.last_change_tick, self.change_tick, - ) + ); }; } @@ -499,7 +499,7 @@ where f, self.last_change_tick, self.change_tick, - ) + ); }; } @@ -525,7 +525,7 @@ where f, self.last_change_tick, self.change_tick, - ) + ); }; } @@ -547,7 +547,7 @@ where f, self.last_change_tick, self.change_tick, - ) + ); }; } diff --git a/crates/bevy_ecs/src/world/entity_ref.rs b/crates/bevy_ecs/src/world/entity_ref.rs index e7227e3177173..7b7bb6402e7a6 100644 --- a/crates/bevy_ecs/src/world/entity_ref.rs +++ b/crates/bevy_ecs/src/world/entity_ref.rs @@ -389,7 +389,7 @@ impl<'w> EntityMut<'w> { archetypes, storages, new_archetype_id, - ) + ); } } @@ -721,7 +721,7 @@ fn sorted_remove(source: &mut Vec, remove: &[T]) { } else { true } - }) + }); } #[cfg(test)] diff --git a/crates/bevy_gltf/src/loader.rs b/crates/bevy_gltf/src/loader.rs index b66d8093d54d8..3f7ea93148657 100644 --- a/crates/bevy_gltf/src/loader.rs +++ b/crates/bevy_gltf/src/loader.rs @@ -786,7 +786,7 @@ fn resolve_node_hierarchy( assert!(parent_children.remove(&index)); if let Some((_, child_node)) = nodes.get(&index) { - parent_node.children.push(child_node.clone()) + parent_node.children.push(child_node.clone()); } if parent_children.is_empty() { empty_children.push_back(parent_index); diff --git a/crates/bevy_input/src/gamepad.rs b/crates/bevy_input/src/gamepad.rs index fc6ccc9464f42..e995ad41bc652 100644 --- a/crates/bevy_input/src/gamepad.rs +++ b/crates/bevy_input/src/gamepad.rs @@ -309,7 +309,7 @@ pub fn gamepad_event_system( events.send(GamepadEvent( gamepad, GamepadEventType::AxisChanged(*axis_type, filtered_value), - )) + )); } } GamepadEventType::ButtonChanged(button_type, value) => { @@ -322,7 +322,7 @@ pub fn gamepad_event_system( events.send(GamepadEvent( gamepad, GamepadEventType::ButtonChanged(*button_type, filtered_value), - )) + )); } let button_property = settings.get_button_settings(gamepad_button); diff --git a/crates/bevy_pbr/src/light.rs b/crates/bevy_pbr/src/light.rs index 402a42eb38eaa..60b4bffc9928d 100644 --- a/crates/bevy_pbr/src/light.rs +++ b/crates/bevy_pbr/src/light.rs @@ -822,7 +822,7 @@ pub fn check_light_mesh_visibility( } else { computed_visibility.is_visible = true; for visible_entities in cubemap_visible_entities.iter_mut() { - visible_entities.entities.push(entity) + visible_entities.entities.push(entity); } } } diff --git a/crates/bevy_pbr/src/material.rs b/crates/bevy_pbr/src/material.rs index 393bae0692d84..5df5a15656ff9 100644 --- a/crates/bevy_pbr/src/material.rs +++ b/crates/bevy_pbr/src/material.rs @@ -324,7 +324,7 @@ pub fn queue_material_meshes( } let alpha_mode = M::alpha_mode(material); if alpha_mode == AlphaMode::Blend { - mesh_key |= MeshPipelineKey::TRANSPARENT_MAIN_PASS + mesh_key |= MeshPipelineKey::TRANSPARENT_MAIN_PASS; } let specialized_key = M::key(material); diff --git a/crates/bevy_pbr/src/pbr_material.rs b/crates/bevy_pbr/src/pbr_material.rs index 02cf3180bdb5c..b27f080abd08b 100644 --- a/crates/bevy_pbr/src/pbr_material.rs +++ b/crates/bevy_pbr/src/pbr_material.rs @@ -241,7 +241,7 @@ impl RenderAsset for StandardMaterial { AlphaMode::Opaque => flags |= StandardMaterialFlags::ALPHA_MODE_OPAQUE, AlphaMode::Mask(c) => { alpha_cutoff = c; - flags |= StandardMaterialFlags::ALPHA_MODE_MASK + flags |= StandardMaterialFlags::ALPHA_MODE_MASK; } AlphaMode::Blend => flags |= StandardMaterialFlags::ALPHA_MODE_BLEND, }; diff --git a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs index fe8df06c7d8f5..6f61bae1218cb 100644 --- a/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs +++ b/crates/bevy_reflect/bevy_reflect_derive/src/lib.rs @@ -620,15 +620,15 @@ impl ReflectAttrs { match ident.as_str() { "PartialEq" => { attrs.reflect_partial_eq = - TraitImpl::Custom(segment.ident.clone()) + TraitImpl::Custom(segment.ident.clone()); } "Hash" => { attrs.reflect_hash = - TraitImpl::Custom(segment.ident.clone()) + TraitImpl::Custom(segment.ident.clone()); } "Serialize" => { attrs.serialize = - TraitImpl::Custom(segment.ident.clone()) + TraitImpl::Custom(segment.ident.clone()); } _ => {} } diff --git a/crates/bevy_reflect/src/impls/std.rs b/crates/bevy_reflect/src/impls/std.rs index de816eb1c0ddb..c6a09ecd23bc3 100644 --- a/crates/bevy_reflect/src/impls/std.rs +++ b/crates/bevy_reflect/src/impls/std.rs @@ -224,7 +224,7 @@ unsafe impl Reflect for HashMap { if let ReflectRef::Map(map_value) = value.reflect_ref() { for (key, value) in map_value.iter() { if let Some(v) = Map::get_mut(self, key) { - v.apply(value) + v.apply(value); } } } else { diff --git a/crates/bevy_reflect/src/map.rs b/crates/bevy_reflect/src/map.rs index 942fc33277e84..97d06deb9ae42 100644 --- a/crates/bevy_reflect/src/map.rs +++ b/crates/bevy_reflect/src/map.rs @@ -151,7 +151,7 @@ unsafe impl Reflect for DynamicMap { if let ReflectRef::Map(map_value) = value.reflect_ref() { for (key, value) in map_value.iter() { if let Some(v) = self.get_mut(key) { - v.apply(value) + v.apply(value); } } } else { diff --git a/crates/bevy_reflect/src/struct_trait.rs b/crates/bevy_reflect/src/struct_trait.rs index 7771cb25702de..0000d82724ca6 100644 --- a/crates/bevy_reflect/src/struct_trait.rs +++ b/crates/bevy_reflect/src/struct_trait.rs @@ -289,7 +289,7 @@ unsafe impl Reflect for DynamicStruct { for (i, value) in struct_value.iter_fields().enumerate() { let name = struct_value.name_at(i).unwrap(); if let Some(v) = self.field_mut(name) { - v.apply(value) + v.apply(value); } } } else { diff --git a/crates/bevy_reflect/src/tuple.rs b/crates/bevy_reflect/src/tuple.rs index 3c036d26b44db..007507076697d 100644 --- a/crates/bevy_reflect/src/tuple.rs +++ b/crates/bevy_reflect/src/tuple.rs @@ -269,7 +269,7 @@ pub fn tuple_apply(a: &mut T, b: &dyn Reflect) { if let ReflectRef::Tuple(tuple) = b.reflect_ref() { for (i, value) in tuple.iter_fields().enumerate() { if let Some(v) = a.field_mut(i) { - v.apply(value) + v.apply(value); } } } else { diff --git a/crates/bevy_reflect/src/tuple_struct.rs b/crates/bevy_reflect/src/tuple_struct.rs index 432194658e487..2500bce47bf7a 100644 --- a/crates/bevy_reflect/src/tuple_struct.rs +++ b/crates/bevy_reflect/src/tuple_struct.rs @@ -228,7 +228,7 @@ unsafe impl Reflect for DynamicTupleStruct { if let ReflectRef::TupleStruct(tuple_struct) = value.reflect_ref() { for (i, value) in tuple_struct.iter_fields().enumerate() { if let Some(v) = self.field_mut(i) { - v.apply(value) + v.apply(value); } } } else { diff --git a/crates/bevy_render/src/camera/mod.rs b/crates/bevy_render/src/camera/mod.rs index 4df498f0bf34f..5be7298689707 100644 --- a/crates/bevy_render/src/camera/mod.rs +++ b/crates/bevy_render/src/camera/mod.rs @@ -105,5 +105,5 @@ fn extract_cameras( } } - commands.insert_resource(ExtractedCameraNames { entities }) + commands.insert_resource(ExtractedCameraNames { entities }); } diff --git a/crates/bevy_render/src/color/mod.rs b/crates/bevy_render/src/color/mod.rs index 6a0a1e25e6004..684f6e3ec9be3 100644 --- a/crates/bevy_render/src/color/mod.rs +++ b/crates/bevy_render/src/color/mod.rs @@ -586,7 +586,7 @@ impl Add for Color { impl AddAssign for Color { fn add_assign(&mut self, rhs: Vec4) { let rhs: Self = rhs.into(); - *self += rhs + *self += rhs; } } diff --git a/crates/bevy_render/src/render_asset.rs b/crates/bevy_render/src/render_asset.rs index 214036520766c..12861ae6f4e64 100644 --- a/crates/bevy_render/src/render_asset.rs +++ b/crates/bevy_render/src/render_asset.rs @@ -119,7 +119,7 @@ fn extract_render_asset( commands.insert_resource(ExtractedAssets { extracted: extracted_assets, removed, - }) + }); } /// Specifies all ECS data required by [`PrepareAssetSystem`]. diff --git a/crates/bevy_render/src/render_phase/draw_state.rs b/crates/bevy_render/src/render_phase/draw_state.rs index b49707e7b8f7e..fb301b65ce792 100644 --- a/crates/bevy_render/src/render_phase/draw_state.rs +++ b/crates/bevy_render/src/render_phase/draw_state.rs @@ -254,7 +254,7 @@ impl<'a> TrackedRenderPass<'a> { offset, data.len() ); - self.pass.set_push_constants(stages, offset, data) + self.pass.set_push_constants(stages, offset, data); } /// Set the rendering viewport. @@ -279,7 +279,7 @@ impl<'a> TrackedRenderPass<'a> { max_depth ); self.pass - .set_viewport(x, y, width, height, min_depth, max_depth) + .set_viewport(x, y, width, height, min_depth, max_depth); } /// Insert a single debug marker. @@ -287,7 +287,7 @@ impl<'a> TrackedRenderPass<'a> { /// This is a GPU debugging feature. This has no effect on the rendering itself. pub fn insert_debug_marker(&mut self, label: &str) { trace!("insert debug marker: {}", label); - self.pass.insert_debug_marker(label) + self.pass.insert_debug_marker(label); } /// Start a new debug group. @@ -312,7 +312,7 @@ impl<'a> TrackedRenderPass<'a> { /// [`pop_debug_group`]: TrackedRenderPass::pop_debug_group pub fn push_debug_group(&mut self, label: &str) { trace!("push_debug_group marker: {}", label); - self.pass.push_debug_group(label) + self.pass.push_debug_group(label); } /// End the current debug group. @@ -329,11 +329,11 @@ impl<'a> TrackedRenderPass<'a> { /// [`pop_debug_group`]: TrackedRenderPass::pop_debug_group pub fn pop_debug_group(&mut self) { trace!("pop_debug_group"); - self.pass.pop_debug_group() + self.pass.pop_debug_group(); } pub fn set_blend_constant(&mut self, color: Color) { trace!("set blend constant: {:?}", color); - self.pass.set_blend_constant(wgpu::Color::from(color)) + self.pass.set_blend_constant(wgpu::Color::from(color)); } } diff --git a/crates/bevy_render/src/render_resource/buffer.rs b/crates/bevy_render/src/render_resource/buffer.rs index b13b52797ab0f..55e0c8f87a5ac 100644 --- a/crates/bevy_render/src/render_resource/buffer.rs +++ b/crates/bevy_render/src/render_resource/buffer.rs @@ -34,7 +34,7 @@ impl Buffer { #[inline] pub fn unmap(&self) { - self.value.unmap() + self.value.unmap(); } } diff --git a/crates/bevy_render/src/renderer/render_device.rs b/crates/bevy_render/src/renderer/render_device.rs index 004947f0c5ce9..032ffe04a50b9 100644 --- a/crates/bevy_render/src/renderer/render_device.rs +++ b/crates/bevy_render/src/renderer/render_device.rs @@ -46,7 +46,7 @@ impl RenderDevice { /// no-op on the web, device is automatically polled. #[inline] pub fn poll(&self, maintain: wgpu::Maintain) { - self.device.poll(maintain) + self.device.poll(maintain); } /// Creates an empty [`CommandEncoder`](wgpu::CommandEncoder). @@ -144,7 +144,7 @@ impl RenderDevice { /// - A old [`SurfaceTexture`](wgpu::SurfaceTexture) is still alive referencing an old surface. /// - Texture format requested is unsupported on the surface. pub fn configure_surface(&self, surface: &wgpu::Surface, config: &wgpu::SurfaceConfiguration) { - surface.configure(&self.device, config) + surface.configure(&self.device, config); } /// Returns the wgpu [`Device`](wgpu::Device). diff --git a/crates/bevy_scene/src/scene_spawner.rs b/crates/bevy_scene/src/scene_spawner.rs index c951c474b3cb5..94fa1ff2d9fed 100644 --- a/crates/bevy_scene/src/scene_spawner.rs +++ b/crates/bevy_scene/src/scene_spawner.rs @@ -242,7 +242,7 @@ impl SceneSpawner { match self.spawn_dynamic_sync(world, &scene_handle) { Ok(_) => {} Err(SceneSpawnError::NonExistentScene { .. }) => { - self.dynamic_scenes_to_spawn.push(scene_handle) + self.dynamic_scenes_to_spawn.push(scene_handle); } Err(err) => return Err(err), } @@ -254,7 +254,7 @@ impl SceneSpawner { match self.spawn_sync_internal(world, scene_handle, instance_id) { Ok(_) => {} Err(SceneSpawnError::NonExistentRealScene { handle }) => { - self.scenes_to_spawn.push((handle, instance_id)) + self.scenes_to_spawn.push((handle, instance_id)); } Err(err) => return Err(err), } diff --git a/crates/bevy_sprite/src/texture_atlas.rs b/crates/bevy_sprite/src/texture_atlas.rs index 0c62df090a234..a95584a481877 100644 --- a/crates/bevy_sprite/src/texture_atlas.rs +++ b/crates/bevy_sprite/src/texture_atlas.rs @@ -103,7 +103,7 @@ impl TextureAtlas { sprites.push(Rect { min: rect_min, max: Vec2::new(rect_min.x + tile_size.x, rect_min.y + tile_size.y), - }) + }); } } diff --git a/crates/bevy_sprite/src/texture_atlas_builder.rs b/crates/bevy_sprite/src/texture_atlas_builder.rs index 2adcee20f17a8..da6b50a93a946 100644 --- a/crates/bevy_sprite/src/texture_atlas_builder.rs +++ b/crates/bevy_sprite/src/texture_atlas_builder.rs @@ -88,7 +88,7 @@ impl TextureAtlasBuilder { texture.texture_descriptor.size.height, 1, ), - ) + ); } fn copy_texture_to_atlas( diff --git a/crates/bevy_tasks/src/iter/mod.rs b/crates/bevy_tasks/src/iter/mod.rs index 02f6cd8528195..952bc53075551 100644 --- a/crates/bevy_tasks/src/iter/mod.rs +++ b/crates/bevy_tasks/src/iter/mod.rs @@ -36,7 +36,7 @@ where fn count(mut self, pool: &TaskPool) -> usize { pool.scope(|s| { while let Some(batch) = self.next_batch() { - s.spawn(async move { batch.count() }) + s.spawn(async move { batch.count() }); } }) .iter() @@ -219,7 +219,7 @@ where pool.scope(|s| { while let Some(batch) = self.next_batch() { let newf = f.clone(); - s.spawn(async move { batch.partition::, F>(newf) }) + s.spawn(async move { batch.partition::, F>(newf) }); } }) .into_iter() diff --git a/crates/bevy_ui/src/update.rs b/crates/bevy_ui/src/update.rs index 1cd763b1ceedf..76669470cacd1 100644 --- a/crates/bevy_ui/src/update.rs +++ b/crates/bevy_ui/src/update.rs @@ -76,7 +76,7 @@ pub fn update_clipping_system( &mut node_query, root_node, None, - ) + ); } } diff --git a/crates/bevy_window/src/window.rs b/crates/bevy_window/src/window.rs index 71b8269a95b30..3ca7c9f305baf 100644 --- a/crates/bevy_window/src/window.rs +++ b/crates/bevy_window/src/window.rs @@ -332,7 +332,7 @@ impl Window { #[inline] pub fn set_position(&mut self, position: IVec2) { self.command_queue - .push(WindowCommand::SetPosition { position }) + .push(WindowCommand::SetPosition { position }); } /// Modifies the minimum and maximum window bounds for resizing in logical pixels. diff --git a/crates/bevy_winit/src/lib.rs b/crates/bevy_winit/src/lib.rs index a833ecf44b57f..992182740c565 100644 --- a/crates/bevy_winit/src/lib.rs +++ b/crates/bevy_winit/src/lib.rs @@ -57,12 +57,13 @@ fn change_window(world: &mut World) { let window = winit_windows.get_window(id).unwrap(); match mode { bevy_window::WindowMode::BorderlessFullscreen => { - window.set_fullscreen(Some(winit::window::Fullscreen::Borderless(None))) + window + .set_fullscreen(Some(winit::window::Fullscreen::Borderless(None))); } bevy_window::WindowMode::Fullscreen => { window.set_fullscreen(Some(winit::window::Fullscreen::Exclusive( get_best_videomode(&window.current_monitor().unwrap()), - ))) + ))); } bevy_window::WindowMode::SizedFullscreen => window.set_fullscreen(Some( winit::window::Fullscreen::Exclusive(get_fitting_videomode( @@ -129,11 +130,11 @@ fn change_window(world: &mut World) { } bevy_window::WindowCommand::SetMaximized { maximized } => { let window = winit_windows.get_window(id).unwrap(); - window.set_maximized(maximized) + window.set_maximized(maximized); } bevy_window::WindowCommand::SetMinimized { minimized } => { let window = winit_windows.get_window(id).unwrap(); - window.set_minimized(minimized) + window.set_minimized(minimized); } bevy_window::WindowCommand::SetPosition { position } => { let window = winit_windows.get_window(id).unwrap(); @@ -188,7 +189,7 @@ where F: FnMut(Event<'_, ()>, &EventLoopWindowTarget<()>, &mut ControlFlow), { use winit::platform::run_return::EventLoopExtRunReturn; - event_loop.run_return(event_handler) + event_loop.run_return(event_handler); } #[cfg(not(any( @@ -381,7 +382,7 @@ pub fn winit_runner_with(mut app: App) { char_input_events.send(ReceivedCharacter { id: window_id, char: c, - }) + }); } WindowEvent::ScaleFactorChanged { scale_factor, From 36555fdc9f316af8f1feacbe2ac3d07a761abafd Mon Sep 17 00:00:00 2001 From: Felix de Maneville Date: Wed, 19 Jan 2022 10:20:18 +0100 Subject: [PATCH 09/11] Fixed archetypes issue --- crates/bevy_ecs/src/system/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bevy_ecs/src/system/mod.rs b/crates/bevy_ecs/src/system/mod.rs index 555823b3a6fd9..f170c02b1dad7 100644 --- a/crates/bevy_ecs/src/system/mod.rs +++ b/crates/bevy_ecs/src/system/mod.rs @@ -130,7 +130,7 @@ mod tests { world.spawn().insert(A); system.initialize(&mut world); - for archetype in &world.archetypes { + for archetype in world.archetypes.iter() { system.new_archetype(archetype); } system.run((), &mut world); From ea9b9ec056b1282572d99392a7dfba2de9ad0c56 Mon Sep 17 00:00:00 2001 From: Felix de Maneville Date: Wed, 19 Jan 2022 10:38:24 +0100 Subject: [PATCH 10/11] clippy::cloned_instead_of_copied and clippy::map_flatten --- crates/bevy_asset/src/assets.rs | 2 +- crates/bevy_asset/src/info.rs | 2 +- crates/bevy_ecs/src/archetype.rs | 4 ++-- crates/bevy_ecs/src/bundle.rs | 4 ++-- crates/bevy_ecs/src/entity/map_entities.rs | 6 +++--- crates/bevy_ecs/src/schedule/graph_utils.rs | 4 ++-- crates/bevy_ecs/src/storage/sparse_set.rs | 4 ++-- crates/bevy_ecs/src/world/entity_ref.rs | 6 +++--- crates/bevy_ecs/src/world/mod.rs | 2 ++ crates/bevy_input/src/touch.rs | 2 +- crates/bevy_reflect/src/map.rs | 2 +- crates/bevy_reflect/src/type_registry.rs | 2 +- crates/bevy_render/src/render_graph/graph.rs | 2 +- crates/bevy_render/src/render_resource/pipeline_cache.rs | 2 +- crates/bevy_sprite/src/texture_atlas.rs | 2 +- crates/bevy_text/src/font.rs | 3 +-- crates/bevy_transform/src/hierarchy/child_builder.rs | 8 ++++---- crates/bevy_ui/src/focus.rs | 2 +- crates/bevy_ui/src/update.rs | 4 ++-- crates/bevy_winit/src/winit_windows.rs | 2 +- 20 files changed, 33 insertions(+), 32 deletions(-) diff --git a/crates/bevy_asset/src/assets.rs b/crates/bevy_asset/src/assets.rs index 131ea5aff0fe4..55707345516c2 100644 --- a/crates/bevy_asset/src/assets.rs +++ b/crates/bevy_asset/src/assets.rs @@ -192,7 +192,7 @@ impl Assets { /// Get an iterator over all [`HandleId`]'s in the collection. pub fn ids(&self) -> impl Iterator + '_ { - self.assets.keys().cloned() + self.assets.keys().copied() } /// Remove an asset for the given handle. diff --git a/crates/bevy_asset/src/info.rs b/crates/bevy_asset/src/info.rs index 6005e92def189..e1d582781a63d 100644 --- a/crates/bevy_asset/src/info.rs +++ b/crates/bevy_asset/src/info.rs @@ -34,7 +34,7 @@ impl SourceInfo { } pub fn get_asset_type(&self, label_id: LabelId) -> Option { - self.asset_types.get(&label_id).cloned() + self.asset_types.get(&label_id).copied() } } diff --git a/crates/bevy_ecs/src/archetype.rs b/crates/bevy_ecs/src/archetype.rs index 976f75b4fab81..4c80a05e9074d 100644 --- a/crates/bevy_ecs/src/archetype.rs +++ b/crates/bevy_ecs/src/archetype.rs @@ -74,7 +74,7 @@ impl Edges { #[inline] pub fn get_remove_bundle(&self, bundle_id: BundleId) -> Option> { - self.remove_bundle.get(bundle_id).cloned() + self.remove_bundle.get(bundle_id).copied() } #[inline] @@ -87,7 +87,7 @@ impl Edges { &self, bundle_id: BundleId, ) -> Option> { - self.remove_bundle_intersection.get(bundle_id).cloned() + self.remove_bundle_intersection.get(bundle_id).copied() } #[inline] diff --git a/crates/bevy_ecs/src/bundle.rs b/crates/bevy_ecs/src/bundle.rs index d52d09a6e14f9..cc704b7001817 100644 --- a/crates/bevy_ecs/src/bundle.rs +++ b/crates/bevy_ecs/src/bundle.rs @@ -319,7 +319,7 @@ impl BundleInfo { let mut bundle_status = Vec::with_capacity(self.component_ids.len()); let current_archetype = &mut archetypes[archetype_id]; - for component_id in self.component_ids.iter().cloned() { + for component_id in self.component_ids.iter().copied() { if current_archetype.contains(component_id) { bundle_status.push(ComponentStatus::Mutated); } else { @@ -586,7 +586,7 @@ impl Bundles { #[inline] pub fn get_id(&self, type_id: TypeId) -> Option { - self.bundle_ids.get(&type_id).cloned() + self.bundle_ids.get(&type_id).copied() } pub(crate) fn init_info<'a, T: Bundle>( diff --git a/crates/bevy_ecs/src/entity/map_entities.rs b/crates/bevy_ecs/src/entity/map_entities.rs index b6cf162177859..70d8fbca3c238 100644 --- a/crates/bevy_ecs/src/entity/map_entities.rs +++ b/crates/bevy_ecs/src/entity/map_entities.rs @@ -34,15 +34,15 @@ impl EntityMap { pub fn get(&self, entity: Entity) -> Result { self.map .get(&entity) - .cloned() + .copied() .ok_or(MapEntitiesError::EntityNotFound(entity)) } pub fn keys(&self) -> impl Iterator + '_ { - self.map.keys().cloned() + self.map.keys().copied() } pub fn values(&self) -> impl Iterator + '_ { - self.map.values().cloned() + self.map.values().copied() } } diff --git a/crates/bevy_ecs/src/schedule/graph_utils.rs b/crates/bevy_ecs/src/schedule/graph_utils.rs index 88cda8e2042dd..cc172feccaf8f 100644 --- a/crates/bevy_ecs/src/schedule/graph_utils.rs +++ b/crates/bevy_ecs/src/schedule/graph_utils.rs @@ -108,8 +108,8 @@ pub fn topological_order( let mut sorted = Vec::with_capacity(graph.len()); let mut current = Vec::with_capacity(graph.len()); let mut unvisited = HashSet::with_capacity_and_hasher(graph.len(), Default::default()); - unvisited.extend(graph.keys().cloned()); - while let Some(node) = unvisited.iter().next().cloned() { + unvisited.extend(graph.keys().copied()); + while let Some(node) = unvisited.iter().next().copied() { if check_if_cycles_and_visit(&node, graph, &mut sorted, &mut unvisited, &mut current) { let mut cycle = Vec::new(); let last_window = [*current.last().unwrap(), current[0]]; diff --git a/crates/bevy_ecs/src/storage/sparse_set.rs b/crates/bevy_ecs/src/storage/sparse_set.rs index d5e7ae7cabf68..fd80dfb1e8077 100644 --- a/crates/bevy_ecs/src/storage/sparse_set.rs +++ b/crates/bevy_ecs/src/storage/sparse_set.rs @@ -271,7 +271,7 @@ impl SparseSet { } pub fn insert(&mut self, index: I, value: V) { - if let Some(dense_index) = self.sparse.get(index.clone()).cloned() { + if let Some(dense_index) = self.sparse.get(index.clone()).copied() { // SAFE: dense indices stored in self.sparse always exist unsafe { *self.dense.get_unchecked_mut(dense_index) = value; @@ -306,7 +306,7 @@ impl SparseSet { } pub fn get_or_insert_with(&mut self, index: I, func: impl FnOnce() -> V) -> &mut V { - if let Some(dense_index) = self.sparse.get(index.clone()).cloned() { + if let Some(dense_index) = self.sparse.get(index.clone()).copied() { // SAFE: dense indices stored in self.sparse always exist unsafe { self.dense.get_unchecked_mut(dense_index) } } else { diff --git a/crates/bevy_ecs/src/world/entity_ref.rs b/crates/bevy_ecs/src/world/entity_ref.rs index 7b7bb6402e7a6..3d2d6a229ed6f 100644 --- a/crates/bevy_ecs/src/world/entity_ref.rs +++ b/crates/bevy_ecs/src/world/entity_ref.rs @@ -237,7 +237,7 @@ impl<'w> EntityMut<'w> { } let old_archetype = &mut archetypes[old_location.archetype_id]; - let mut bundle_components = bundle_info.component_ids.iter().cloned(); + let mut bundle_components = bundle_info.component_ids.iter().copied(); let entity = self.entity; // SAFE: bundle components are iterated in order, which guarantees that the component type // matches @@ -361,7 +361,7 @@ impl<'w> EntityMut<'w> { let old_archetype = &mut archetypes[old_location.archetype_id]; let entity = self.entity; - for component_id in bundle_info.component_ids.iter().cloned() { + for component_id in bundle_info.component_ids.iter().copied() { if old_archetype.contains(component_id) { removed_components .get_or_insert_with(component_id, Vec::new) @@ -647,7 +647,7 @@ unsafe fn remove_bundle_from_archetype( let current_archetype = &mut archetypes[archetype_id]; let mut removed_table_components = Vec::new(); let mut removed_sparse_set_components = Vec::new(); - for component_id in bundle_info.component_ids.iter().cloned() { + for component_id in bundle_info.component_ids.iter().copied() { if current_archetype.contains(component_id) { // SAFE: bundle components were already initialized by bundles.get_info let component_info = components.get_info_unchecked(component_id); diff --git a/crates/bevy_ecs/src/world/mod.rs b/crates/bevy_ecs/src/world/mod.rs index 4e2c5ca010e0f..53d002a78d737 100644 --- a/crates/bevy_ecs/src/world/mod.rs +++ b/crates/bevy_ecs/src/world/mod.rs @@ -570,6 +570,7 @@ impl World { /// Returns an iterator of entities that had components of type `T` removed /// since the last call to [`World::clear_trackers`]. + // TODO: return `std::iter::Copied` instead pub fn removed(&self) -> std::iter::Cloned> { self.components.get_id(TypeId::of::()).map_or_else( || [].iter().cloned(), @@ -579,6 +580,7 @@ impl World { /// Returns an iterator of entities that had components with the given `component_id` removed /// since the last call to [`World::clear_trackers`]. + // TODO: return `std::iter::Copied` instead pub fn removed_with_id( &self, component_id: ComponentId, diff --git a/crates/bevy_input/src/touch.rs b/crates/bevy_input/src/touch.rs index 0409a948b8891..2f6335cfe7ac4 100644 --- a/crates/bevy_input/src/touch.rs +++ b/crates/bevy_input/src/touch.rs @@ -194,7 +194,7 @@ impl Touches { self.just_pressed.insert(event.id, event.into()); } TouchPhase::Moved => { - if let Some(mut new_touch) = self.pressed.get(&event.id).cloned() { + if let Some(mut new_touch) = self.pressed.get(&event.id).copied() { new_touch.previous_position = new_touch.position; new_touch.previous_force = new_touch.force; new_touch.position = event.position; diff --git a/crates/bevy_reflect/src/map.rs b/crates/bevy_reflect/src/map.rs index 97d06deb9ae42..385121fa2cd1d 100644 --- a/crates/bevy_reflect/src/map.rs +++ b/crates/bevy_reflect/src/map.rs @@ -99,7 +99,7 @@ impl Map for DynamicMap { fn get_mut(&mut self, key: &dyn Reflect) -> Option<&mut dyn Reflect> { self.indices .get(&key.reflect_hash().expect(HASH_ERROR)) - .cloned() + .copied() .map(move |index| &mut *self.values.get_mut(index).unwrap().1) } diff --git a/crates/bevy_reflect/src/type_registry.rs b/crates/bevy_reflect/src/type_registry.rs index e76fa7699eabc..7a0fc8d8bd4d3 100644 --- a/crates/bevy_reflect/src/type_registry.rs +++ b/crates/bevy_reflect/src/type_registry.rs @@ -100,7 +100,7 @@ impl TypeRegistry { pub fn get_with_name_mut(&mut self, type_name: &str) -> Option<&mut TypeRegistration> { self.full_name_to_id .get(type_name) - .cloned() + .copied() .and_then(move |id| self.get_mut(id)) } diff --git a/crates/bevy_render/src/render_graph/graph.rs b/crates/bevy_render/src/render_graph/graph.rs index 7fd7ba8e05485..9bbdd81a4068e 100644 --- a/crates/bevy_render/src/render_graph/graph.rs +++ b/crates/bevy_render/src/render_graph/graph.rs @@ -133,7 +133,7 @@ impl RenderGraph { NodeLabel::Name(ref name) => self .node_names .get(name) - .cloned() + .copied() .ok_or(RenderGraphError::InvalidNode(label)), } } diff --git a/crates/bevy_render/src/render_resource/pipeline_cache.rs b/crates/bevy_render/src/render_resource/pipeline_cache.rs index 9cbb075cf3c6f..9f57e7374173e 100644 --- a/crates/bevy_render/src/render_resource/pipeline_cache.rs +++ b/crates/bevy_render/src/render_resource/pipeline_cache.rs @@ -100,7 +100,7 @@ impl ShaderCache { while let Some(handle) = shaders_to_clear.pop() { if let Some(data) = self.data.get_mut(&handle) { data.processed_shaders.clear(); - pipelines_to_queue.extend(data.pipelines.iter().cloned()); + pipelines_to_queue.extend(data.pipelines.iter().copied()); shaders_to_clear.extend(data.dependents.iter().map(|h| h.clone_weak())); } } diff --git a/crates/bevy_sprite/src/texture_atlas.rs b/crates/bevy_sprite/src/texture_atlas.rs index a95584a481877..10585ac57a2b8 100644 --- a/crates/bevy_sprite/src/texture_atlas.rs +++ b/crates/bevy_sprite/src/texture_atlas.rs @@ -142,6 +142,6 @@ impl TextureAtlas { pub fn get_texture_index(&self, texture: &Handle) -> Option { self.texture_handles .as_ref() - .and_then(|texture_handles| texture_handles.get(texture).cloned()) + .and_then(|texture_handles| texture_handles.get(texture).copied()) } } diff --git a/crates/bevy_text/src/font.rs b/crates/bevy_text/src/font.rs index f12e9d5ff889c..368b8e0dbedd9 100644 --- a/crates/bevy_text/src/font.rs +++ b/crates/bevy_text/src/font.rs @@ -37,8 +37,7 @@ impl Font { TextureDimension::D2, alpha .iter() - .map(|a| vec![255, 255, 255, (*a * 255.0) as u8]) - .flatten() + .flat_map(|a| vec![255, 255, 255, (*a * 255.0) as u8]) .collect::>(), TextureFormat::Rgba8UnormSrgb, ) diff --git a/crates/bevy_transform/src/hierarchy/child_builder.rs b/crates/bevy_transform/src/hierarchy/child_builder.rs index 83f0d75f658cb..c5f11652d0c03 100644 --- a/crates/bevy_transform/src/hierarchy/child_builder.rs +++ b/crates/bevy_transform/src/hierarchy/child_builder.rs @@ -78,7 +78,7 @@ impl Command for PushChildren { { let mut added = false; if let Some(mut children) = world.get_mut::(self.parent) { - children.0.extend(self.children.iter().cloned()); + children.0.extend(self.children.iter().copied()); added = true; } @@ -282,7 +282,7 @@ impl<'w> WorldChildBuilder<'w> { pub fn parent_entity(&self) -> Entity { self.parent_entities .last() - .cloned() + .copied() .expect("There should always be a parent at this point.") } } @@ -332,7 +332,7 @@ impl<'w> BuildWorldChildren for EntityMut<'w> { self.update_location(); } if let Some(mut children_component) = self.get_mut::() { - children_component.0.extend(children.iter().cloned()); + children_component.0.extend(children.iter().copied()); } else { self.insert(Children::with(children)); } @@ -418,7 +418,7 @@ impl<'w> BuildWorldChildren for WorldChildBuilder<'w> { .insert_bundle((Parent(parent), PreviousParent(parent))); } if let Some(mut children_component) = self.world.get_mut::(parent) { - children_component.0.extend(children.iter().cloned()); + children_component.0.extend(children.iter().copied()); } else { self.world .entity_mut(parent) diff --git a/crates/bevy_ui/src/focus.rs b/crates/bevy_ui/src/focus.rs index 251e766efc178..d7e11ae0fa558 100644 --- a/crates/bevy_ui/src/focus.rs +++ b/crates/bevy_ui/src/focus.rs @@ -157,7 +157,7 @@ pub fn ui_focus_system( } } - match focus_policy.cloned().unwrap_or(FocusPolicy::Block) { + match focus_policy.copied().unwrap_or(FocusPolicy::Block) { FocusPolicy::Block => { break; } diff --git a/crates/bevy_ui/src/update.rs b/crates/bevy_ui/src/update.rs index 76669470cacd1..483223060ce55 100644 --- a/crates/bevy_ui/src/update.rs +++ b/crates/bevy_ui/src/update.rs @@ -49,7 +49,7 @@ fn update_hierarchy( } if let Ok(children) = children_query.get(entity) { let current_parent_global_z = current_global_z; - for child in children.iter().cloned() { + for child in children.iter().copied() { current_global_z = update_hierarchy( children_query, node_query, @@ -119,7 +119,7 @@ fn update_clipping( }; if let Ok(children) = children_query.get(entity) { - for child in children.iter().cloned() { + for child in children.iter().copied() { update_clipping(commands, children_query, node_query, child, children_clip); } } diff --git a/crates/bevy_winit/src/winit_windows.rs b/crates/bevy_winit/src/winit_windows.rs index cab8d282a3f53..3f899a7a8a9f4 100644 --- a/crates/bevy_winit/src/winit_windows.rs +++ b/crates/bevy_winit/src/winit_windows.rs @@ -181,7 +181,7 @@ impl WinitWindows { } pub fn get_window_id(&self, id: winit::window::WindowId) -> Option { - self.winit_to_window_id.get(&id).cloned() + self.winit_to_window_id.get(&id).copied() } } From db8190ceaee3893a8f94d6e6916ee9d6bea9cff2 Mon Sep 17 00:00:00 2001 From: Felix de Maneville Date: Wed, 19 Jan 2022 11:00:27 +0100 Subject: [PATCH 11/11] PR requested changes: Rollback most of const methods --- crates/bevy_asset/src/loader.rs | 4 +-- crates/bevy_core/src/time/stopwatch.rs | 4 +-- crates/bevy_core/src/time/time.rs | 14 ++++---- crates/bevy_core/src/time/timer.rs | 14 ++++---- crates/bevy_diagnostic/src/diagnostic.rs | 4 +-- crates/bevy_ecs/src/archetype.rs | 10 +++--- crates/bevy_ecs/src/storage/blob_vec.rs | 8 ++--- crates/bevy_ecs/src/storage/sparse_set.rs | 4 +-- crates/bevy_ecs/src/storage/table.rs | 6 ++-- crates/bevy_ecs/src/system/commands/mod.rs | 2 +- crates/bevy_ecs/src/system/function_system.rs | 2 +- crates/bevy_ecs/src/world/entity_ref.rs | 4 +-- crates/bevy_ecs/src/world/mod.rs | 14 ++++---- crates/bevy_input/src/touch.rs | 12 +++---- crates/bevy_reflect/src/type_registry.rs | 4 +-- crates/bevy_render/src/mesh/mesh/mod.rs | 4 +-- .../bevy_render/src/render_graph/context.rs | 6 ++-- crates/bevy_render/src/render_graph/node.rs | 3 +- .../src/render_resource/bind_group.rs | 2 +- .../src/render_resource/bind_group_layout.rs | 2 +- .../bevy_render/src/render_resource/buffer.rs | 6 ++-- .../src/render_resource/pipeline.rs | 4 +-- .../bevy_render/src/render_resource/shader.rs | 2 +- .../src/render_resource/texture.rs | 6 ++-- .../bevy_render/src/renderer/render_device.rs | 3 +- crates/bevy_tasks/src/task_pool.rs | 4 +-- crates/bevy_text/src/glyph_brush.rs | 2 +- .../src/hierarchy/child_builder.rs | 3 +- crates/bevy_window/src/raw_window_handle.rs | 2 +- crates/bevy_window/src/window.rs | 36 +++++++++---------- 30 files changed, 97 insertions(+), 94 deletions(-) diff --git a/crates/bevy_asset/src/loader.rs b/crates/bevy_asset/src/loader.rs index c7532f6a6d9cf..dff879def8ff5 100644 --- a/crates/bevy_asset/src/loader.rs +++ b/crates/bevy_asset/src/loader.rs @@ -103,7 +103,7 @@ impl<'a> LoadContext<'a> { } } - pub const fn path(&self) -> &Path { + pub fn path(&self) -> &Path { self.path } @@ -142,7 +142,7 @@ impl<'a> LoadContext<'a> { asset_metas } - pub const fn task_pool(&self) -> &TaskPool { + pub fn task_pool(&self) -> &TaskPool { self.task_pool } } diff --git a/crates/bevy_core/src/time/stopwatch.rs b/crates/bevy_core/src/time/stopwatch.rs index d59223c53a554..9fa84cba07a6b 100644 --- a/crates/bevy_core/src/time/stopwatch.rs +++ b/crates/bevy_core/src/time/stopwatch.rs @@ -60,7 +60,7 @@ impl Stopwatch { /// /// [`elapsed_secs`](Stopwatch::elapsed) - if a `f32` value is desirable instead. #[inline] - pub const fn elapsed(&self) -> Duration { + pub fn elapsed(&self) -> Duration { self.elapsed } @@ -168,7 +168,7 @@ impl Stopwatch { /// assert!(!stopwatch.paused()); /// ``` #[inline] - pub const fn paused(&self) -> bool { + pub fn paused(&self) -> bool { self.paused } diff --git a/crates/bevy_core/src/time/time.rs b/crates/bevy_core/src/time/time.rs index 8a18c017fb3eb..d252cabd7b50a 100644 --- a/crates/bevy_core/src/time/time.rs +++ b/crates/bevy_core/src/time/time.rs @@ -47,43 +47,43 @@ impl Time { /// The delta between the current tick and last tick as a [`Duration`] #[inline] - pub const fn delta(&self) -> Duration { + pub fn delta(&self) -> Duration { self.delta } /// The delta between the current and last tick as [`f32`] seconds #[inline] - pub const fn delta_seconds(&self) -> f32 { + pub fn delta_seconds(&self) -> f32 { self.delta_seconds } /// The delta between the current and last tick as [`f64`] seconds #[inline] - pub const fn delta_seconds_f64(&self) -> f64 { + pub fn delta_seconds_f64(&self) -> f64 { self.delta_seconds_f64 } /// The time from startup to the last update in seconds #[inline] - pub const fn seconds_since_startup(&self) -> f64 { + pub fn seconds_since_startup(&self) -> f64 { self.seconds_since_startup } /// The [`Instant`] the app was started #[inline] - pub const fn startup(&self) -> Instant { + pub fn startup(&self) -> Instant { self.startup } /// The ['Instant'] when [`Time::update`] was last called, if it exists #[inline] - pub const fn last_update(&self) -> Option { + pub fn last_update(&self) -> Option { self.last_update } /// The ['Duration'] from startup to the last update #[inline] - pub const fn time_since_startup(&self) -> Duration { + pub fn time_since_startup(&self) -> Duration { self.time_since_startup } } diff --git a/crates/bevy_core/src/time/timer.rs b/crates/bevy_core/src/time/timer.rs index 0b4bf67a8f752..8fe9131246ca8 100644 --- a/crates/bevy_core/src/time/timer.rs +++ b/crates/bevy_core/src/time/timer.rs @@ -60,7 +60,7 @@ impl Timer { /// assert!(timer.finished()); /// ``` #[inline] - pub const fn finished(&self) -> bool { + pub fn finished(&self) -> bool { self.finished } @@ -77,7 +77,7 @@ impl Timer { /// assert!(!timer.just_finished()); /// ``` #[inline] - pub const fn just_finished(&self) -> bool { + pub fn just_finished(&self) -> bool { self.times_finished > 0 } @@ -95,7 +95,7 @@ impl Timer { /// assert_eq!(timer.elapsed(), Duration::from_secs_f32(0.5)); /// ``` #[inline] - pub const fn elapsed(&self) -> Duration { + pub fn elapsed(&self) -> Duration { self.stopwatch.elapsed() } @@ -135,7 +135,7 @@ impl Timer { /// assert_eq!(timer.duration(), Duration::from_secs(1)); /// ``` #[inline] - pub const fn duration(&self) -> Duration { + pub fn duration(&self) -> Duration { self.duration } @@ -163,7 +163,7 @@ impl Timer { /// assert!(timer.repeating()); /// ``` #[inline] - pub const fn repeating(&self) -> bool { + pub fn repeating(&self) -> bool { self.repeating } @@ -285,7 +285,7 @@ impl Timer { /// assert!(!timer.paused()); /// ``` #[inline] - pub const fn paused(&self) -> bool { + pub fn paused(&self) -> bool { self.stopwatch.paused() } @@ -359,7 +359,7 @@ impl Timer { /// assert_eq!(timer.times_finished(), 0); /// ``` #[inline] - pub const fn times_finished(&self) -> u32 { + pub fn times_finished(&self) -> u32 { self.times_finished } } diff --git a/crates/bevy_diagnostic/src/diagnostic.rs b/crates/bevy_diagnostic/src/diagnostic.rs index 420901c2d8682..66d5c98e2edfe 100644 --- a/crates/bevy_diagnostic/src/diagnostic.rs +++ b/crates/bevy_diagnostic/src/diagnostic.rs @@ -86,7 +86,7 @@ impl Diagnostic { self.history.back().map(|measurement| measurement.value) } - pub const fn sum(&self) -> f64 { + pub fn sum(&self) -> f64 { self.sum } @@ -116,7 +116,7 @@ impl Diagnostic { None } - pub const fn get_max_history_length(&self) -> usize { + pub fn get_max_history_length(&self) -> usize { self.max_history_length } diff --git a/crates/bevy_ecs/src/archetype.rs b/crates/bevy_ecs/src/archetype.rs index 4c80a05e9074d..bcc995cf3aa59 100644 --- a/crates/bevy_ecs/src/archetype.rs +++ b/crates/bevy_ecs/src/archetype.rs @@ -178,12 +178,12 @@ impl Archetype { } #[inline] - pub const fn id(&self) -> ArchetypeId { + pub fn id(&self) -> ArchetypeId { self.id } #[inline] - pub const fn table_id(&self) -> TableId { + pub fn table_id(&self) -> TableId { self.table_info.id } @@ -208,7 +208,7 @@ impl Archetype { } #[inline] - pub const fn unique_components(&self) -> &SparseSet { + pub fn unique_components(&self) -> &SparseSet { &self.unique_components } @@ -223,7 +223,7 @@ impl Archetype { } #[inline] - pub const fn edges(&self) -> &Edges { + pub fn edges(&self) -> &Edges { &self.edges } @@ -515,7 +515,7 @@ impl Archetypes { } #[inline] - pub const fn archetype_components_len(&self) -> usize { + pub fn archetype_components_len(&self) -> usize { self.archetype_component_count } diff --git a/crates/bevy_ecs/src/storage/blob_vec.rs b/crates/bevy_ecs/src/storage/blob_vec.rs index 8a3a775dbe8f3..3e82c61f6f405 100644 --- a/crates/bevy_ecs/src/storage/blob_vec.rs +++ b/crates/bevy_ecs/src/storage/blob_vec.rs @@ -44,17 +44,17 @@ impl BlobVec { } #[inline] - pub const fn len(&self) -> usize { + pub fn len(&self) -> usize { self.len } #[inline] - pub const fn is_empty(&self) -> bool { + pub fn is_empty(&self) -> bool { self.len == 0 } #[inline] - pub const fn capacity(&self) -> usize { + pub fn capacity(&self) -> usize { self.capacity } @@ -196,7 +196,7 @@ impl BlobVec { /// # Safety /// must ensure rust mutability rules are not violated #[inline] - pub const unsafe fn get_ptr(&self) -> NonNull { + pub unsafe fn get_ptr(&self) -> NonNull { self.data } diff --git a/crates/bevy_ecs/src/storage/sparse_set.rs b/crates/bevy_ecs/src/storage/sparse_set.rs index fd80dfb1e8077..8756029d213d0 100644 --- a/crates/bevy_ecs/src/storage/sparse_set.rs +++ b/crates/bevy_ecs/src/storage/sparse_set.rs @@ -117,12 +117,12 @@ impl ComponentSparseSet { } #[inline] - pub const fn len(&self) -> usize { + pub fn len(&self) -> usize { self.dense.len() } #[inline] - pub const fn is_empty(&self) -> bool { + pub fn is_empty(&self) -> bool { self.dense.len() == 0 } diff --git a/crates/bevy_ecs/src/storage/table.rs b/crates/bevy_ecs/src/storage/table.rs index 714fb566719ed..099c0434f48f0 100644 --- a/crates/bevy_ecs/src/storage/table.rs +++ b/crates/bevy_ecs/src/storage/table.rs @@ -84,12 +84,12 @@ impl Column { } #[inline] - pub const fn len(&self) -> usize { + pub fn len(&self) -> usize { self.data.len() } #[inline] - pub const fn is_empty(&self) -> bool { + pub fn is_empty(&self) -> bool { self.data.is_empty() } @@ -136,7 +136,7 @@ impl Column { /// # Safety /// must ensure rust mutability rules are not violated #[inline] - pub const unsafe fn get_data_ptr(&self) -> NonNull { + pub unsafe fn get_data_ptr(&self) -> NonNull { self.data.get_ptr() } diff --git a/crates/bevy_ecs/src/system/commands/mod.rs b/crates/bevy_ecs/src/system/commands/mod.rs index 61eaae0e366ad..566e4a95cbc2a 100644 --- a/crates/bevy_ecs/src/system/commands/mod.rs +++ b/crates/bevy_ecs/src/system/commands/mod.rs @@ -372,7 +372,7 @@ impl<'w, 's, 'a> EntityCommands<'w, 's, 'a> { /// # my_system.system(); /// ``` #[inline] - pub const fn id(&self) -> Entity { + pub fn id(&self) -> Entity { self.entity } diff --git a/crates/bevy_ecs/src/system/function_system.rs b/crates/bevy_ecs/src/system/function_system.rs index d7a16b86afc87..3e255423e972e 100644 --- a/crates/bevy_ecs/src/system/function_system.rs +++ b/crates/bevy_ecs/src/system/function_system.rs @@ -35,7 +35,7 @@ impl SystemMeta { /// Returns true if the system is [`Send`]. #[inline] - pub const fn is_send(&self) -> bool { + pub fn is_send(&self) -> bool { self.is_send } diff --git a/crates/bevy_ecs/src/world/entity_ref.rs b/crates/bevy_ecs/src/world/entity_ref.rs index 3d2d6a229ed6f..0f1383e98a8cf 100644 --- a/crates/bevy_ecs/src/world/entity_ref.rs +++ b/crates/bevy_ecs/src/world/entity_ref.rs @@ -113,12 +113,12 @@ impl<'w> EntityMut<'w> { } #[inline] - pub const fn id(&self) -> Entity { + pub fn id(&self) -> Entity { self.entity } #[inline] - pub const fn location(&self) -> EntityLocation { + pub fn location(&self) -> EntityLocation { self.location } diff --git a/crates/bevy_ecs/src/world/mod.rs b/crates/bevy_ecs/src/world/mod.rs index 53d002a78d737..a7e8fb9b98eff 100644 --- a/crates/bevy_ecs/src/world/mod.rs +++ b/crates/bevy_ecs/src/world/mod.rs @@ -117,13 +117,13 @@ impl World { /// Retrieves this [`World`]'s unique ID #[inline] - pub const fn id(&self) -> WorldId { + pub fn id(&self) -> WorldId { self.id } /// Retrieves this world's [Entities] collection #[inline] - pub const fn entities(&self) -> &Entities { + pub fn entities(&self) -> &Entities { &self.entities } @@ -135,13 +135,13 @@ impl World { /// Retrieves this world's [Archetypes] collection #[inline] - pub const fn archetypes(&self) -> &Archetypes { + pub fn archetypes(&self) -> &Archetypes { &self.archetypes } /// Retrieves this world's [Components] collection #[inline] - pub const fn components(&self) -> &Components { + pub fn components(&self) -> &Components { &self.components } @@ -153,13 +153,13 @@ impl World { /// Retrieves this world's [Storages] collection #[inline] - pub const fn storages(&self) -> &Storages { + pub fn storages(&self) -> &Storages { &self.storages } /// Retrieves this world's [Bundles] collection #[inline] - pub const fn bundles(&self) -> &Bundles { + pub fn bundles(&self) -> &Bundles { &self.bundles } @@ -1119,7 +1119,7 @@ impl World { } #[inline] - pub const fn last_change_tick(&self) -> u32 { + pub fn last_change_tick(&self) -> u32 { self.last_change_tick } diff --git a/crates/bevy_input/src/touch.rs b/crates/bevy_input/src/touch.rs index 2f6335cfe7ac4..270c3835c737d 100644 --- a/crates/bevy_input/src/touch.rs +++ b/crates/bevy_input/src/touch.rs @@ -98,32 +98,32 @@ impl Touch { } #[inline] - pub const fn id(&self) -> u64 { + pub fn id(&self) -> u64 { self.id } #[inline] - pub const fn start_position(&self) -> Vec2 { + pub fn start_position(&self) -> Vec2 { self.start_position } #[inline] - pub const fn start_force(&self) -> Option { + pub fn start_force(&self) -> Option { self.start_force } #[inline] - pub const fn previous_position(&self) -> Vec2 { + pub fn previous_position(&self) -> Vec2 { self.previous_position } #[inline] - pub const fn position(&self) -> Vec2 { + pub fn position(&self) -> Vec2 { self.position } #[inline] - pub const fn force(&self) -> Option { + pub fn force(&self) -> Option { self.force } } diff --git a/crates/bevy_reflect/src/type_registry.rs b/crates/bevy_reflect/src/type_registry.rs index 7a0fc8d8bd4d3..c21b7e0f9a14b 100644 --- a/crates/bevy_reflect/src/type_registry.rs +++ b/crates/bevy_reflect/src/type_registry.rs @@ -174,7 +174,7 @@ impl TypeRegistration { /// /// [`TypeId`]: std::any::TypeId #[inline] - pub const fn type_id(&self) -> TypeId { + pub fn type_id(&self) -> TypeId { self.type_id } @@ -225,7 +225,7 @@ impl TypeRegistration { } /// Returns the name of the type. - pub const fn name(&self) -> &'static str { + pub fn name(&self) -> &'static str { self.name } diff --git a/crates/bevy_render/src/mesh/mesh/mod.rs b/crates/bevy_render/src/mesh/mesh/mod.rs index b29227d18d8a4..e3396cc30b70b 100644 --- a/crates/bevy_render/src/mesh/mesh/mod.rs +++ b/crates/bevy_render/src/mesh/mesh/mod.rs @@ -80,7 +80,7 @@ impl Mesh { } /// Returns the topology of the mesh. - pub const fn primitive_topology(&self) -> PrimitiveTopology { + pub fn primitive_topology(&self) -> PrimitiveTopology { self.primitive_topology } @@ -116,7 +116,7 @@ impl Mesh { } /// Retrieves the vertex `indices` of the mesh. - pub const fn indices(&self) -> Option<&Indices> { + pub fn indices(&self) -> Option<&Indices> { self.indices.as_ref() } diff --git a/crates/bevy_render/src/render_graph/context.rs b/crates/bevy_render/src/render_graph/context.rs index a35928d4e9d2b..ec300ac25eb22 100644 --- a/crates/bevy_render/src/render_graph/context.rs +++ b/crates/bevy_render/src/render_graph/context.rs @@ -48,17 +48,17 @@ impl<'a> RenderGraphContext<'a> { /// Returns the input slot values for the node. #[inline] - pub const fn inputs(&self) -> &[SlotValue] { + pub fn inputs(&self) -> &[SlotValue] { self.inputs } /// Returns the [`SlotInfos`] of the inputs. - pub const fn input_info(&self) -> &SlotInfos { + pub fn input_info(&self) -> &SlotInfos { &self.node.input_slots } /// Returns the [`SlotInfos`] of the outputs. - pub const fn output_info(&self) -> &SlotInfos { + pub fn output_info(&self) -> &SlotInfos { &self.node.output_slots } diff --git a/crates/bevy_render/src/render_graph/node.rs b/crates/bevy_render/src/render_graph/node.rs index d3392262eb865..71f178e1e9d60 100644 --- a/crates/bevy_render/src/render_graph/node.rs +++ b/crates/bevy_render/src/render_graph/node.rs @@ -24,7 +24,8 @@ impl NodeId { Self(Uuid::new_v4()) } - pub const fn uuid(&self) -> &Uuid { + #[inline] + pub fn uuid(&self) -> &Uuid { &self.0 } } diff --git a/crates/bevy_render/src/render_resource/bind_group.rs b/crates/bevy_render/src/render_resource/bind_group.rs index 0c449f25e123d..717ebcdecddd2 100644 --- a/crates/bevy_render/src/render_resource/bind_group.rs +++ b/crates/bevy_render/src/render_resource/bind_group.rs @@ -20,7 +20,7 @@ pub struct BindGroup { impl BindGroup { /// Returns the [`BindGroupId`]. #[inline] - pub const fn id(&self) -> BindGroupId { + pub fn id(&self) -> BindGroupId { self.id } } diff --git a/crates/bevy_render/src/render_resource/bind_group_layout.rs b/crates/bevy_render/src/render_resource/bind_group_layout.rs index ded5efc1e23b5..325163c7723d7 100644 --- a/crates/bevy_render/src/render_resource/bind_group_layout.rs +++ b/crates/bevy_render/src/render_resource/bind_group_layout.rs @@ -12,7 +12,7 @@ pub struct BindGroupLayout { impl BindGroupLayout { #[inline] - pub const fn id(&self) -> BindGroupLayoutId { + pub fn id(&self) -> BindGroupLayoutId { self.id } diff --git a/crates/bevy_render/src/render_resource/buffer.rs b/crates/bevy_render/src/render_resource/buffer.rs index 55e0c8f87a5ac..5b93f3ffc6cae 100644 --- a/crates/bevy_render/src/render_resource/buffer.rs +++ b/crates/bevy_render/src/render_resource/buffer.rs @@ -15,7 +15,7 @@ pub struct Buffer { impl Buffer { #[inline] - pub const fn id(&self) -> BufferId { + pub fn id(&self) -> BufferId { self.id } @@ -65,12 +65,12 @@ pub struct BufferSlice<'a> { impl<'a> BufferSlice<'a> { #[inline] - pub const fn id(&self) -> BufferId { + pub fn id(&self) -> BufferId { self.id } #[inline] - pub const fn offset(&self) -> wgpu::BufferAddress { + pub fn offset(&self) -> wgpu::BufferAddress { self.offset } } diff --git a/crates/bevy_render/src/render_resource/pipeline.rs b/crates/bevy_render/src/render_resource/pipeline.rs index b26e0c082c67b..b760937ed0c38 100644 --- a/crates/bevy_render/src/render_resource/pipeline.rs +++ b/crates/bevy_render/src/render_resource/pipeline.rs @@ -23,7 +23,7 @@ pub struct RenderPipeline { impl RenderPipeline { #[inline] - pub const fn id(&self) -> RenderPipelineId { + pub fn id(&self) -> RenderPipelineId { self.id } } @@ -63,7 +63,7 @@ pub struct ComputePipeline { impl ComputePipeline { /// Returns the [`ComputePipelineId`]. #[inline] - pub const fn id(&self) -> ComputePipelineId { + pub fn id(&self) -> ComputePipelineId { self.id } } diff --git a/crates/bevy_render/src/render_resource/shader.rs b/crates/bevy_render/src/render_resource/shader.rs index 91f5182569284..2876eabff16ad 100644 --- a/crates/bevy_render/src/render_resource/shader.rs +++ b/crates/bevy_render/src/render_resource/shader.rs @@ -79,7 +79,7 @@ impl Shader { } #[inline] - pub const fn import_path(&self) -> Option<&ShaderImport> { + pub fn import_path(&self) -> Option<&ShaderImport> { self.import_path.as_ref() } diff --git a/crates/bevy_render/src/render_resource/texture.rs b/crates/bevy_render/src/render_resource/texture.rs index d7630a709966c..7f52c7efe97b8 100644 --- a/crates/bevy_render/src/render_resource/texture.rs +++ b/crates/bevy_render/src/render_resource/texture.rs @@ -18,7 +18,7 @@ pub struct Texture { impl Texture { /// Returns the [`TextureId`]. #[inline] - pub const fn id(&self) -> TextureId { + pub fn id(&self) -> TextureId { self.id } @@ -80,7 +80,7 @@ pub struct TextureView { impl TextureView { /// Returns the [`TextureViewId`]. #[inline] - pub const fn id(&self) -> TextureViewId { + pub fn id(&self) -> TextureViewId { self.id } @@ -145,7 +145,7 @@ pub struct Sampler { impl Sampler { /// Returns the [`SamplerId`]. #[inline] - pub const fn id(&self) -> SamplerId { + pub fn id(&self) -> SamplerId { self.id } } diff --git a/crates/bevy_render/src/renderer/render_device.rs b/crates/bevy_render/src/renderer/render_device.rs index 032ffe04a50b9..0a3a68ebc4efc 100644 --- a/crates/bevy_render/src/renderer/render_device.rs +++ b/crates/bevy_render/src/renderer/render_device.rs @@ -160,7 +160,8 @@ impl RenderDevice { } } - pub const fn align_copy_bytes_per_row(row_bytes: usize) -> usize { + #[inline] + pub fn align_copy_bytes_per_row(row_bytes: usize) -> usize { let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize; let padded_bytes_per_row_padding = (align - row_bytes % align) % align; row_bytes + padded_bytes_per_row_padding diff --git a/crates/bevy_tasks/src/task_pool.rs b/crates/bevy_tasks/src/task_pool.rs index e074e26805cd3..a56464da370ce 100644 --- a/crates/bevy_tasks/src/task_pool.rs +++ b/crates/bevy_tasks/src/task_pool.rs @@ -31,13 +31,13 @@ impl TaskPoolBuilder { /// Override the number of threads created for the pool. If unset, we default to the number /// of logical cores of the system - pub const fn num_threads(mut self, num_threads: usize) -> Self { + pub fn num_threads(mut self, num_threads: usize) -> Self { self.num_threads = Some(num_threads); self } /// Override the stack size of the threads created for the pool - pub const fn stack_size(mut self, stack_size: usize) -> Self { + pub fn stack_size(mut self, stack_size: usize) -> Self { self.stack_size = Some(stack_size); self } diff --git a/crates/bevy_text/src/glyph_brush.rs b/crates/bevy_text/src/glyph_brush.rs index d4244667172c5..dcf8ecb8a99e4 100644 --- a/crates/bevy_text/src/glyph_brush.rs +++ b/crates/bevy_text/src/glyph_brush.rs @@ -156,7 +156,7 @@ impl GlyphPlacementAdjuster { } #[inline(always)] - pub const fn position(&self, p: Vec2) -> Vec2 { + pub fn position(&self, p: Vec2) -> Vec2 { p } } diff --git a/crates/bevy_transform/src/hierarchy/child_builder.rs b/crates/bevy_transform/src/hierarchy/child_builder.rs index c5f11652d0c03..ecdbf29e620f7 100644 --- a/crates/bevy_transform/src/hierarchy/child_builder.rs +++ b/crates/bevy_transform/src/hierarchy/child_builder.rs @@ -151,7 +151,8 @@ impl<'w, 's, 'a> ChildBuilder<'w, 's, 'a> { } /// Returns the parent entity of this [`ChildBuilder`] - pub const fn parent_entity(&self) -> Entity { + #[inline] + pub fn parent_entity(&self) -> Entity { self.push_children.parent } diff --git a/crates/bevy_window/src/raw_window_handle.rs b/crates/bevy_window/src/raw_window_handle.rs index bf6b2cc402c71..831b8352cf6d2 100644 --- a/crates/bevy_window/src/raw_window_handle.rs +++ b/crates/bevy_window/src/raw_window_handle.rs @@ -6,7 +6,7 @@ use raw_window_handle::{HasRawWindowHandle, RawWindowHandle}; pub struct RawWindowHandleWrapper(RawWindowHandle); impl RawWindowHandleWrapper { - pub(crate) const fn new(handle: RawWindowHandle) -> Self { + pub(crate) fn new(handle: RawWindowHandle) -> Self { Self(handle) } diff --git a/crates/bevy_window/src/window.rs b/crates/bevy_window/src/window.rs index 3ca7c9f305baf..10eb3b20bd039 100644 --- a/crates/bevy_window/src/window.rs +++ b/crates/bevy_window/src/window.rs @@ -239,7 +239,7 @@ impl Window { } #[inline] - pub const fn id(&self) -> WindowId { + pub fn id(&self) -> WindowId { self.id } @@ -261,7 +261,7 @@ impl Window { /// This may differ from the actual width depending on OS size limits and /// the scaling factor for high DPI monitors. #[inline] - pub const fn requested_width(&self) -> f32 { + pub fn requested_width(&self) -> f32 { self.requested_width } @@ -271,31 +271,31 @@ impl Window { /// This may differ from the actual width depending on OS size limits and /// the scaling factor for high DPI monitors. #[inline] - pub const fn requested_height(&self) -> f32 { + pub fn requested_height(&self) -> f32 { self.requested_height } /// The window's client area width in physical pixels. #[inline] - pub const fn physical_width(&self) -> u32 { + pub fn physical_width(&self) -> u32 { self.physical_width } /// The window's client area height in physical pixels. #[inline] - pub const fn physical_height(&self) -> u32 { + pub fn physical_height(&self) -> u32 { self.physical_height } /// The window's client resize constraint in logical pixels. #[inline] - pub const fn resize_constraints(&self) -> WindowResizeConstraints { + pub fn resize_constraints(&self) -> WindowResizeConstraints { self.resize_constraints } /// The window's client position in physical pixels. #[inline] - pub const fn position(&self) -> Option { + pub fn position(&self) -> Option { self.position } @@ -405,12 +405,12 @@ impl Window { /// The window scale factor as reported by the window backend. /// This value is unaffected by [`scale_factor_override`](Window::scale_factor_override). #[inline] - pub const fn backend_scale_factor(&self) -> f64 { + pub fn backend_scale_factor(&self) -> f64 { self.backend_scale_factor } #[inline] - pub const fn scale_factor_override(&self) -> Option { + pub fn scale_factor_override(&self) -> Option { self.scale_factor_override } @@ -425,7 +425,7 @@ impl Window { } #[inline] - pub const fn vsync(&self) -> bool { + pub fn vsync(&self) -> bool { self.vsync } @@ -436,7 +436,7 @@ impl Window { } #[inline] - pub const fn resizable(&self) -> bool { + pub fn resizable(&self) -> bool { self.resizable } @@ -447,7 +447,7 @@ impl Window { } #[inline] - pub const fn decorations(&self) -> bool { + pub fn decorations(&self) -> bool { self.decorations } @@ -458,7 +458,7 @@ impl Window { } #[inline] - pub const fn cursor_locked(&self) -> bool { + pub fn cursor_locked(&self) -> bool { self.cursor_locked } @@ -469,7 +469,7 @@ impl Window { } #[inline] - pub const fn cursor_visible(&self) -> bool { + pub fn cursor_visible(&self) -> bool { self.cursor_visible } @@ -481,7 +481,7 @@ impl Window { } #[inline] - pub const fn cursor_icon(&self) -> CursorIcon { + pub fn cursor_icon(&self) -> CursorIcon { self.cursor_icon } @@ -492,7 +492,7 @@ impl Window { /// The current mouse position, in physical pixels. #[inline] - pub const fn physical_cursor_position(&self) -> Option { + pub fn physical_cursor_position(&self) -> Option { self.physical_cursor_position } @@ -522,7 +522,7 @@ impl Window { } #[inline] - pub const fn mode(&self) -> WindowMode { + pub fn mode(&self) -> WindowMode { self.mode } @@ -540,7 +540,7 @@ impl Window { } #[inline] - pub const fn is_focused(&self) -> bool { + pub fn is_focused(&self) -> bool { self.focused }