diff --git a/Cargo.toml b/Cargo.toml index 978c1b754f9fb..e80d7de677e5e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,22 +34,23 @@ members = [ type_complexity = "allow" doc_markdown = "warn" manual_let_else = "warn" -undocumented_unsafe_blocks = "warn" -redundant_else = "warn" match_same_arms = "warn" -semicolon_if_nothing_returned = "warn" redundant_closure_for_method_calls = "warn" +redundant_else = "warn" +semicolon_if_nothing_returned = "warn" +undocumented_unsafe_blocks = "warn" unwrap_or_default = "warn" +use_self = "warn" ptr_as_ptr = "warn" ptr_cast_constness = "warn" ref_as_ptr = "warn" [workspace.lints.rust] -unsafe_op_in_unsafe_fn = "warn" missing_docs = "warn" -unsafe_code = "deny" unexpected_cfgs = { level = "warn", check-cfg = ['cfg(docsrs_dep)'] } +unsafe_code = "deny" +unsafe_op_in_unsafe_fn = "warn" [lints] workspace = true diff --git a/crates/bevy_animation/src/lib.rs b/crates/bevy_animation/src/lib.rs index e8e394b957df6..d887750bab7c1 100755 --- a/crates/bevy_animation/src/lib.rs +++ b/crates/bevy_animation/src/lib.rs @@ -82,9 +82,9 @@ impl Keyframes { /// Returns the number of keyframes. pub fn len(&self) -> usize { match self { - Keyframes::Weights(vec) => vec.len(), - Keyframes::Translation(vec) | Keyframes::Scale(vec) => vec.len(), - Keyframes::Rotation(vec) => vec.len(), + Self::Weights(vec) => vec.len(), + Self::Translation(vec) | Self::Scale(vec) => vec.len(), + Self::Rotation(vec) => vec.len(), } } @@ -1233,7 +1233,7 @@ impl AnimationTargetId { impl From<&Name> for AnimationTargetId { fn from(name: &Name) -> Self { - AnimationTargetId::from_name(name) + Self::from_name(name) } } diff --git a/crates/bevy_animation/src/transition.rs b/crates/bevy_animation/src/transition.rs index 77e8fdfef5ca3..95961448a45a4 100644 --- a/crates/bevy_animation/src/transition.rs +++ b/crates/bevy_animation/src/transition.rs @@ -64,8 +64,8 @@ pub struct AnimationTransition { impl AnimationTransitions { /// Creates a new [`AnimationTransitions`] component, ready to be added to /// an entity with an [`AnimationPlayer`]. - pub fn new() -> AnimationTransitions { - AnimationTransitions::default() + pub fn new() -> Self { + Self::default() } /// Plays a new animation on the given [`AnimationPlayer`], fading out any diff --git a/crates/bevy_app/src/app.rs b/crates/bevy_app/src/app.rs index d1fa331a23101..54045daa51784 100644 --- a/crates/bevy_app/src/app.rs +++ b/crates/bevy_app/src/app.rs @@ -91,7 +91,7 @@ impl Debug for App { impl Default for App { fn default() -> Self { - let mut app = App::empty(); + let mut app = Self::empty(); app.sub_apps.main.update_schedule = Some(Main.intern()); #[cfg(feature = "bevy_reflect")] @@ -116,14 +116,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. /// /// Use this constructor if you want to customize scheduling, exit handling, cleanup, etc. - pub fn empty() -> App { + pub fn empty() -> Self { Self { sub_apps: SubApps { main: SubApp::new(), @@ -169,7 +169,7 @@ impl App { } let runner = std::mem::replace(&mut self.runner, Box::new(run_once)); - let app = std::mem::replace(self, App::empty()); + let app = std::mem::replace(self, Self::empty()); (runner)(app) } @@ -200,7 +200,7 @@ impl App { /// App::new() /// .set_runner(my_runner); /// ``` - pub fn set_runner(&mut self, f: impl FnOnce(App) -> AppExit + 'static) -> &mut Self { + pub fn set_runner(&mut self, f: impl FnOnce(Self) -> AppExit + 'static) -> &mut Self { self.runner = Box::new(f); self } @@ -1044,13 +1044,13 @@ impl AppExit { /// Returns `true` if `self` is a [`AppExit::Success`]. #[must_use] pub const fn is_success(&self) -> bool { - matches!(self, AppExit::Success) + matches!(self, Self::Success) } /// Returns `true` if `self` is a [`AppExit::Error`]. #[must_use] pub const fn is_error(&self) -> bool { - matches!(self, AppExit::Error(_)) + matches!(self, Self::Error(_)) } /// Creates a [`AppExit`] from a code. @@ -1076,9 +1076,9 @@ impl From for AppExit { impl Termination for AppExit { fn report(self) -> std::process::ExitCode { match self { - AppExit::Success => ExitCode::SUCCESS, + Self::Success => ExitCode::SUCCESS, // We leave logging an error to our users - AppExit::Error(value) => ExitCode::from(value.get()), + Self::Error(value) => ExitCode::from(value.get()), } } } @@ -1420,7 +1420,7 @@ mod tests { struct TestResource; impl FromWorld for TestResource { fn from_world(_world: &mut World) -> Self { - TestResource + Self } } @@ -1430,7 +1430,7 @@ mod tests { } impl FromWorld for NonSendTestResource { fn from_world(_world: &mut World) -> Self { - NonSendTestResource { + Self { _marker: PhantomData, } } diff --git a/crates/bevy_app/src/schedule_runner.rs b/crates/bevy_app/src/schedule_runner.rs index 1d697ca00eb37..6c566cc3e7d0f 100644 --- a/crates/bevy_app/src/schedule_runner.rs +++ b/crates/bevy_app/src/schedule_runner.rs @@ -27,7 +27,7 @@ pub enum RunMode { impl Default for RunMode { fn default() -> Self { - RunMode::Loop { wait: None } + Self::Loop { wait: None } } } @@ -52,14 +52,14 @@ pub struct ScheduleRunnerPlugin { impl ScheduleRunnerPlugin { /// See [`RunMode::Once`]. pub fn run_once() -> Self { - ScheduleRunnerPlugin { + Self { run_mode: RunMode::Once, } } /// See [`RunMode::Loop`]. pub fn run_loop(wait_duration: Duration) -> Self { - ScheduleRunnerPlugin { + Self { run_mode: RunMode::Loop { wait: Some(wait_duration), }, diff --git a/crates/bevy_app/src/terminal_ctrl_c_handler.rs b/crates/bevy_app/src/terminal_ctrl_c_handler.rs index 54e0bc5338ee2..0c81e0d21828e 100644 --- a/crates/bevy_app/src/terminal_ctrl_c_handler.rs +++ b/crates/bevy_app/src/terminal_ctrl_c_handler.rs @@ -67,7 +67,6 @@ impl Plugin for TerminalCtrlCHandlerPlugin { } Err(err) => bevy_utils::tracing::warn!("Failed to set `Ctrl+C` handler: {err}"), } - - app.add_systems(Update, TerminalCtrlCHandlerPlugin::exit_on_flag); + app.add_systems(Update, Self::exit_on_flag); } } diff --git a/crates/bevy_asset/src/event.rs b/crates/bevy_asset/src/event.rs index f049751bb79c3..ef81e3f9713ff 100644 --- a/crates/bevy_asset/src/event.rs +++ b/crates/bevy_asset/src/event.rs @@ -33,7 +33,7 @@ pub struct UntypedAssetLoadFailedEvent { impl From<&AssetLoadFailedEvent> for UntypedAssetLoadFailedEvent { fn from(value: &AssetLoadFailedEvent) -> Self { - UntypedAssetLoadFailedEvent { + Self { id: value.id.untyped(), path: value.path.clone(), error: value.error.clone(), @@ -59,27 +59,27 @@ pub enum AssetEvent { impl AssetEvent { /// Returns `true` if this event is [`AssetEvent::LoadedWithDependencies`] and matches the given `id`. pub fn is_loaded_with_dependencies(&self, asset_id: impl Into>) -> bool { - matches!(self, AssetEvent::LoadedWithDependencies { id } if *id == asset_id.into()) + matches!(self, Self::LoadedWithDependencies { id } if *id == asset_id.into()) } /// Returns `true` if this event is [`AssetEvent::Added`] and matches the given `id`. pub fn is_added(&self, asset_id: impl Into>) -> bool { - matches!(self, AssetEvent::Added { id } if *id == asset_id.into()) + matches!(self, Self::Added { id } if *id == asset_id.into()) } /// Returns `true` if this event is [`AssetEvent::Modified`] and matches the given `id`. pub fn is_modified(&self, asset_id: impl Into>) -> bool { - matches!(self, AssetEvent::Modified { id } if *id == asset_id.into()) + matches!(self, Self::Modified { id } if *id == asset_id.into()) } /// Returns `true` if this event is [`AssetEvent::Removed`] and matches the given `id`. pub fn is_removed(&self, asset_id: impl Into>) -> bool { - matches!(self, AssetEvent::Removed { id } if *id == asset_id.into()) + matches!(self, Self::Removed { id } if *id == asset_id.into()) } /// Returns `true` if this event is [`AssetEvent::Unused`] and matches the given `id`. pub fn is_unused(&self, asset_id: impl Into>) -> bool { - matches!(self, AssetEvent::Unused { id } if *id == asset_id.into()) + matches!(self, Self::Unused { id } if *id == asset_id.into()) } } diff --git a/crates/bevy_asset/src/handle.rs b/crates/bevy_asset/src/handle.rs index 95e480493a4c4..13da9a2da86b4 100644 --- a/crates/bevy_asset/src/handle.rs +++ b/crates/bevy_asset/src/handle.rs @@ -136,8 +136,8 @@ pub enum Handle { impl Clone for Handle { fn clone(&self) -> Self { match self { - Handle::Strong(handle) => Handle::Strong(handle.clone()), - Handle::Weak(id) => Handle::Weak(*id), + Self::Strong(handle) => Self::Strong(handle.clone()), + Self::Weak(id) => Self::Weak(*id), } } } @@ -145,7 +145,7 @@ impl Clone for Handle { impl Handle { /// Create a new [`Handle::Weak`] with the given [`u128`] encoding of a [`Uuid`]. pub const fn weak_from_u128(value: u128) -> Self { - Handle::Weak(AssetId::Uuid { + Self::Weak(AssetId::Uuid { uuid: Uuid::from_u128(value), }) } @@ -154,8 +154,8 @@ impl Handle { #[inline] pub fn id(&self) -> AssetId { match self { - Handle::Strong(handle) => handle.id.typed_unchecked(), - Handle::Weak(id) => *id, + Self::Strong(handle) => handle.id.typed_unchecked(), + Self::Weak(id) => *id, } } @@ -163,29 +163,29 @@ impl Handle { #[inline] pub fn path(&self) -> Option<&AssetPath<'static>> { match self { - Handle::Strong(handle) => handle.path.as_ref(), - Handle::Weak(_) => None, + Self::Strong(handle) => handle.path.as_ref(), + Self::Weak(_) => None, } } /// Returns `true` if this is a weak handle. #[inline] pub fn is_weak(&self) -> bool { - matches!(self, Handle::Weak(_)) + matches!(self, Self::Weak(_)) } /// Returns `true` if this is a strong handle. #[inline] pub fn is_strong(&self) -> bool { - matches!(self, Handle::Strong(_)) + matches!(self, Self::Strong(_)) } /// Creates a [`Handle::Weak`] clone of this [`Handle`], which will not keep the referenced [`Asset`] alive. #[inline] pub fn clone_weak(&self) -> Self { match self { - Handle::Strong(handle) => Handle::Weak(handle.id.typed_unchecked::()), - Handle::Weak(id) => Handle::Weak(*id), + Self::Strong(handle) => Self::Weak(handle.id.typed_unchecked::()), + Self::Weak(id) => Self::Weak(*id), } } @@ -200,7 +200,7 @@ impl Handle { impl Default for Handle { fn default() -> Self { - Handle::Weak(AssetId::default()) + Self::Weak(AssetId::default()) } } @@ -208,7 +208,7 @@ impl std::fmt::Debug for Handle { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let name = get_short_name(std::any::type_name::()); match self { - Handle::Strong(handle) => { + Self::Strong(handle) => { write!( f, "StrongHandle<{name}>{{ id: {:?}, path: {:?} }}", @@ -216,7 +216,7 @@ impl std::fmt::Debug for Handle { handle.path ) } - Handle::Weak(id) => write!(f, "WeakHandle<{name}>({:?})", id.internal()), + Self::Weak(id) => write!(f, "WeakHandle<{name}>({:?})", id.internal()), } } } @@ -293,8 +293,8 @@ impl UntypedHandle { #[inline] pub fn id(&self) -> UntypedAssetId { match self { - UntypedHandle::Strong(handle) => handle.id, - UntypedHandle::Weak(id) => *id, + Self::Strong(handle) => handle.id, + Self::Weak(id) => *id, } } @@ -302,17 +302,17 @@ impl UntypedHandle { #[inline] pub fn path(&self) -> Option<&AssetPath<'static>> { match self { - UntypedHandle::Strong(handle) => handle.path.as_ref(), - UntypedHandle::Weak(_) => None, + Self::Strong(handle) => handle.path.as_ref(), + Self::Weak(_) => None, } } /// Creates an [`UntypedHandle::Weak`] clone of this [`UntypedHandle`], which will not keep the referenced [`Asset`] alive. #[inline] - pub fn clone_weak(&self) -> UntypedHandle { + pub fn clone_weak(&self) -> Self { match self { - UntypedHandle::Strong(handle) => UntypedHandle::Weak(handle.id), - UntypedHandle::Weak(id) => UntypedHandle::Weak(*id), + Self::Strong(handle) => Self::Weak(handle.id), + Self::Weak(id) => Self::Weak(*id), } } @@ -320,8 +320,8 @@ impl UntypedHandle { #[inline] pub fn type_id(&self) -> TypeId { match self { - UntypedHandle::Strong(handle) => handle.id.type_id(), - UntypedHandle::Weak(id) => id.type_id(), + Self::Strong(handle) => handle.id.type_id(), + Self::Weak(id) => id.type_id(), } } @@ -329,8 +329,8 @@ impl UntypedHandle { #[inline] pub fn typed_unchecked(self) -> Handle { match self { - UntypedHandle::Strong(handle) => Handle::Strong(handle), - UntypedHandle::Weak(id) => Handle::Weak(id.typed_unchecked::()), + Self::Strong(handle) => Handle::Strong(handle), + Self::Weak(id) => Handle::Weak(id.typed_unchecked::()), } } @@ -346,8 +346,8 @@ impl UntypedHandle { "The target Handle's TypeId does not match the TypeId of this UntypedHandle" ); match self { - UntypedHandle::Strong(handle) => Handle::Strong(handle), - UntypedHandle::Weak(id) => Handle::Weak(id.typed_unchecked::()), + Self::Strong(handle) => Handle::Strong(handle), + Self::Weak(id) => Handle::Weak(id.typed_unchecked::()), } } @@ -375,8 +375,8 @@ impl UntypedHandle { #[inline] pub fn meta_transform(&self) -> Option<&MetaTransform> { match self { - UntypedHandle::Strong(handle) => handle.meta_transform.as_ref(), - UntypedHandle::Weak(_) => None, + Self::Strong(handle) => handle.meta_transform.as_ref(), + Self::Weak(_) => None, } } } @@ -400,7 +400,7 @@ impl Hash for UntypedHandle { impl std::fmt::Debug for UntypedHandle { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - UntypedHandle::Strong(handle) => { + Self::Strong(handle) => { write!( f, "StrongHandle{{ type_id: {:?}, id: {:?}, path: {:?} }}", @@ -409,7 +409,7 @@ impl std::fmt::Debug for UntypedHandle { handle.path ) } - UntypedHandle::Weak(id) => write!( + Self::Weak(id) => write!( f, "WeakHandle{{ type_id: {:?}, id: {:?} }}", id.type_id(), @@ -473,8 +473,8 @@ impl PartialOrd> for UntypedHandle { impl From> for UntypedHandle { fn from(value: Handle) -> Self { match value { - Handle::Strong(handle) => UntypedHandle::Strong(handle), - Handle::Weak(id) => UntypedHandle::Weak(id.into()), + Handle::Strong(handle) => Self::Strong(handle), + Handle::Weak(id) => Self::Weak(id.into()), } } } @@ -491,12 +491,12 @@ impl TryFrom for Handle { } match value { - UntypedHandle::Strong(handle) => Ok(Handle::Strong(handle)), + UntypedHandle::Strong(handle) => Ok(Self::Strong(handle)), UntypedHandle::Weak(id) => { let Ok(id) = id.try_into() else { return Err(UntypedAssetConversionError::TypeIdMismatch { expected, found }); }; - Ok(Handle::Weak(id)) + Ok(Self::Weak(id)) } } } diff --git a/crates/bevy_asset/src/id.rs b/crates/bevy_asset/src/id.rs index c4b48a06d6cee..4d2dc1a64a358 100644 --- a/crates/bevy_asset/src/id.rs +++ b/crates/bevy_asset/src/id.rs @@ -63,15 +63,15 @@ impl AssetId { #[inline] pub(crate) fn internal(self) -> InternalAssetId { match self { - AssetId::Index { index, .. } => InternalAssetId::Index(index), - AssetId::Uuid { uuid } => InternalAssetId::Uuid(uuid), + Self::Index { index, .. } => InternalAssetId::Index(index), + Self::Uuid { uuid } => InternalAssetId::Uuid(uuid), } } } impl Default for AssetId { fn default() -> Self { - AssetId::Uuid { + Self::Uuid { uuid: Self::DEFAULT_UUID, } } @@ -94,7 +94,7 @@ impl Display for AssetId { impl Debug for AssetId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - AssetId::Index { index, .. } => { + Self::Index { index, .. } => { write!( f, "AssetId<{}>{{ index: {}, generation: {}}}", @@ -103,7 +103,7 @@ impl Debug for AssetId { index.generation ) } - AssetId::Uuid { uuid } => { + Self::Uuid { uuid } => { write!( f, "AssetId<{}>{{uuid: {}}}", @@ -186,11 +186,11 @@ impl UntypedAssetId { #[inline] pub fn typed_unchecked(self) -> AssetId { match self { - UntypedAssetId::Index { index, .. } => AssetId::Index { + Self::Index { index, .. } => AssetId::Index { index, marker: PhantomData, }, - UntypedAssetId::Uuid { uuid, .. } => AssetId::Uuid { uuid }, + Self::Uuid { uuid, .. } => AssetId::Uuid { uuid }, } } @@ -238,17 +238,15 @@ impl UntypedAssetId { #[inline] pub fn type_id(&self) -> TypeId { match self { - UntypedAssetId::Index { type_id, .. } | UntypedAssetId::Uuid { type_id, .. } => { - *type_id - } + Self::Index { type_id, .. } | Self::Uuid { type_id, .. } => *type_id, } } #[inline] pub(crate) fn internal(self) -> InternalAssetId { match self { - UntypedAssetId::Index { index, .. } => InternalAssetId::Index(index), - UntypedAssetId::Uuid { uuid, .. } => InternalAssetId::Uuid(uuid), + Self::Index { index, .. } => InternalAssetId::Index(index), + Self::Uuid { uuid, .. } => InternalAssetId::Uuid(uuid), } } } @@ -257,13 +255,13 @@ impl Display for UntypedAssetId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut writer = f.debug_struct("UntypedAssetId"); match self { - UntypedAssetId::Index { index, type_id } => { + Self::Index { index, type_id } => { writer .field("type_id", type_id) .field("index", &index.index) .field("generation", &index.generation); } - UntypedAssetId::Uuid { uuid, type_id } => { + Self::Uuid { uuid, type_id } => { writer.field("type_id", type_id).field("uuid", uuid); } } @@ -319,19 +317,19 @@ impl InternalAssetId { #[inline] pub(crate) fn typed(self) -> AssetId { match self { - InternalAssetId::Index(index) => AssetId::Index { + Self::Index(index) => AssetId::Index { index, marker: PhantomData, }, - InternalAssetId::Uuid(uuid) => AssetId::Uuid { uuid }, + Self::Uuid(uuid) => AssetId::Uuid { uuid }, } } #[inline] pub(crate) fn untyped(self, type_id: TypeId) -> UntypedAssetId { match self { - InternalAssetId::Index(index) => UntypedAssetId::Index { index, type_id }, - InternalAssetId::Uuid(uuid) => UntypedAssetId::Uuid { uuid, type_id }, + Self::Index(index) => UntypedAssetId::Index { index, type_id }, + Self::Uuid(uuid) => UntypedAssetId::Uuid { uuid, type_id }, } } } @@ -388,8 +386,8 @@ impl From> for UntypedAssetId { let type_id = TypeId::of::(); match value { - AssetId::Index { index, .. } => UntypedAssetId::Index { type_id, index }, - AssetId::Uuid { uuid } => UntypedAssetId::Uuid { type_id, uuid }, + AssetId::Index { index, .. } => Self::Index { type_id, index }, + AssetId::Uuid { uuid } => Self::Uuid { type_id, uuid }, } } } @@ -403,12 +401,12 @@ impl TryFrom for AssetId { let expected = TypeId::of::(); match value { - UntypedAssetId::Index { index, type_id } if type_id == expected => Ok(AssetId::Index { + UntypedAssetId::Index { index, type_id } if type_id == expected => Ok(Self::Index { index, marker: PhantomData, }), UntypedAssetId::Uuid { uuid, type_id } if type_id == expected => { - Ok(AssetId::Uuid { uuid }) + Ok(Self::Uuid { uuid }) } _ => Err(UntypedAssetIdConversionError::TypeIdMismatch { expected, found }), } diff --git a/crates/bevy_asset/src/io/file/file_watcher.rs b/crates/bevy_asset/src/io/file/file_watcher.rs index 12793b738b93c..272edc264647c 100644 --- a/crates/bevy_asset/src/io/file/file_watcher.rs +++ b/crates/bevy_asset/src/io/file/file_watcher.rs @@ -39,7 +39,7 @@ impl FileWatcher { last_event: None, }, )?; - Ok(FileWatcher { _watcher: watcher }) + Ok(Self { _watcher: watcher }) } } diff --git a/crates/bevy_asset/src/io/memory.rs b/crates/bevy_asset/src/io/memory.rs index 03edf58d1feca..2673b8ec0ffa4 100644 --- a/crates/bevy_asset/src/io/memory.rs +++ b/crates/bevy_asset/src/io/memory.rs @@ -69,7 +69,7 @@ impl Dir { ); } - pub fn get_or_insert_dir(&self, path: &Path) -> Dir { + pub fn get_or_insert_dir(&self, path: &Path) -> Self { let mut dir = self.clone(); let mut full_path = PathBuf::new(); for c in path.components() { @@ -78,7 +78,7 @@ impl Dir { dir = { let dirs = &mut dir.0.write().dirs; dirs.entry(name) - .or_insert_with(|| Dir::new(full_path.clone())) + .or_insert_with(|| Self::new(full_path.clone())) .clone() }; } @@ -86,7 +86,7 @@ impl Dir { dir } - pub fn get_dir(&self, path: &Path) -> Option { + pub fn get_dir(&self, path: &Path) -> Option { let mut dir = self.clone(); for p in path.components() { let component = p.as_os_str().to_str().unwrap(); diff --git a/crates/bevy_asset/src/io/source.rs b/crates/bevy_asset/src/io/source.rs index 1ac6b65c22dd0..e505137e5a3e9 100644 --- a/crates/bevy_asset/src/io/source.rs +++ b/crates/bevy_asset/src/io/source.rs @@ -38,7 +38,7 @@ impl<'a> Display for AssetSourceId<'a> { impl<'a> AssetSourceId<'a> { /// Creates a new [`AssetSourceId`] - pub fn new(source: Option>>) -> AssetSourceId<'a> { + pub fn new(source: Option>>) -> Self { match source { Some(source) => AssetSourceId::Name(source.into()), None => AssetSourceId::Default, @@ -76,8 +76,8 @@ impl From<&'static str> for AssetSourceId<'static> { } } -impl<'a, 'b> From<&'a AssetSourceId<'b>> for AssetSourceId<'b> { - fn from(value: &'a AssetSourceId<'b>) -> Self { +impl<'a, 'b> From<&'a Self> for AssetSourceId<'b> { + fn from(value: &'a Self) -> Self { value.clone() } } diff --git a/crates/bevy_asset/src/loader.rs b/crates/bevy_asset/src/loader.rs index bd7dda474ebad..d2ff809fa618c 100644 --- a/crates/bevy_asset/src/loader.rs +++ b/crates/bevy_asset/src/loader.rs @@ -154,7 +154,7 @@ impl LoadedAsset { value.visit_dependencies(&mut |id| { dependencies.insert(id); }); - LoadedAsset { + Self { value, dependencies, loader_dependencies: HashMap::default(), @@ -189,7 +189,7 @@ impl LoadedAsset { impl From for LoadedAsset { fn from(asset: A) -> Self { - LoadedAsset::new_with_dependencies(asset, None) + Self::new_with_dependencies(asset, None) } } @@ -204,7 +204,7 @@ pub struct ErasedLoadedAsset { impl From> for ErasedLoadedAsset { fn from(asset: LoadedAsset) -> Self { - ErasedLoadedAsset { + Self { value: Box::new(asset.value), dependencies: asset.dependencies, loader_dependencies: asset.loader_dependencies, @@ -237,10 +237,7 @@ impl ErasedLoadedAsset { } /// Returns the [`ErasedLoadedAsset`] for the given label, if it exists. - pub fn get_labeled( - &self, - label: impl Into>, - ) -> Option<&ErasedLoadedAsset> { + pub fn get_labeled(&self, label: impl Into>) -> Option<&Self> { self.labeled_assets.get(&label.into()).map(|a| &a.asset) } @@ -252,7 +249,7 @@ impl ErasedLoadedAsset { /// Cast this loaded asset as the given type. If the type does not match, /// the original type-erased asset is returned. #[allow(clippy::result_large_err)] - pub fn downcast(mut self) -> Result, ErasedLoadedAsset> { + pub fn downcast(mut self) -> Result, Self> { match self.value.downcast::() { Ok(value) => Ok(LoadedAsset { value: *value, diff --git a/crates/bevy_asset/src/loader_builders.rs b/crates/bevy_asset/src/loader_builders.rs index 27609a411e4cb..72f281d1fe1dc 100644 --- a/crates/bevy_asset/src/loader_builders.rs +++ b/crates/bevy_asset/src/loader_builders.rs @@ -37,9 +37,7 @@ pub struct NestedLoader<'ctx, 'builder> { } impl<'ctx, 'builder> NestedLoader<'ctx, 'builder> { - pub(crate) fn new( - load_context: &'builder mut LoadContext<'ctx>, - ) -> NestedLoader<'ctx, 'builder> { + pub(crate) fn new(load_context: &'builder mut LoadContext<'ctx>) -> Self { NestedLoader { load_context, meta_transform: None, diff --git a/crates/bevy_asset/src/path.rs b/crates/bevy_asset/src/path.rs index 3c23fff5ad712..1f4131f76f020 100644 --- a/crates/bevy_asset/src/path.rs +++ b/crates/bevy_asset/src/path.rs @@ -103,7 +103,7 @@ impl<'a> AssetPath<'a> { /// /// # Panics /// Panics if the asset path is in an invalid format. Use [`AssetPath::try_parse`] for a fallible variant - pub fn parse(asset_path: &'a str) -> AssetPath<'a> { + pub fn parse(asset_path: &'a str) -> Self { Self::try_parse(asset_path).unwrap() } @@ -117,7 +117,7 @@ impl<'a> AssetPath<'a> { /// and reference counting for [`AssetPath::into_owned`]. /// /// This will return a [`ParseAssetPathError`] if `asset_path` is in an invalid format. - pub fn try_parse(asset_path: &'a str) -> Result, ParseAssetPathError> { + pub fn try_parse(asset_path: &'a str) -> Result { let (source, path, label) = Self::parse_internal(asset_path)?; Ok(Self { source: match source { @@ -220,7 +220,7 @@ impl<'a> AssetPath<'a> { /// Creates a new [`AssetPath`] from a [`Path`]. #[inline] - pub fn from_path(path: &'a Path) -> AssetPath<'a> { + pub fn from_path(path: &'a Path) -> Self { AssetPath { path: CowArc::Borrowed(path), source: AssetSourceId::Default, @@ -278,7 +278,7 @@ impl<'a> AssetPath<'a> { /// Returns this asset path with the given label. This will replace the previous /// label if it exists. #[inline] - pub fn with_label(self, label: impl Into>) -> AssetPath<'a> { + pub fn with_label(self, label: impl Into>) -> Self { AssetPath { source: self.source, path: self.path, @@ -289,7 +289,7 @@ impl<'a> AssetPath<'a> { /// Returns this asset path with the given asset source. This will replace the previous asset /// source if it exists. #[inline] - pub fn with_source(self, source: impl Into>) -> AssetPath<'a> { + pub fn with_source(self, source: impl Into>) -> Self { AssetPath { source: source.into(), path: self.path, @@ -298,7 +298,7 @@ impl<'a> AssetPath<'a> { } /// Returns an [`AssetPath`] for the parent folder of this path, if there is a parent folder in the path. - pub fn parent(&self) -> Option> { + pub fn parent(&self) -> Option { let path = match &self.path { CowArc::Borrowed(path) => CowArc::Borrowed(path.parent()?), CowArc::Static(path) => CowArc::Static(path.parent()?), @@ -523,8 +523,8 @@ impl From for AssetPath<'static> { } } -impl<'a, 'b> From<&'a AssetPath<'b>> for AssetPath<'b> { - fn from(value: &'a AssetPath<'b>) -> Self { +impl<'a, 'b> From<&'a Self> for AssetPath<'b> { + fn from(value: &'a Self) -> Self { value.clone() } } diff --git a/crates/bevy_asset/src/processor/mod.rs b/crates/bevy_asset/src/processor/mod.rs index 15acdbdc8d55d..55ad986511353 100644 --- a/crates/bevy_asset/src/processor/mod.rs +++ b/crates/bevy_asset/src/processor/mod.rs @@ -973,7 +973,7 @@ impl AssetProcessorData { finished_sender.set_overflow(true); initialized_sender.set_overflow(true); - AssetProcessorData { + Self { sources: source, finished_sender, finished_receiver, diff --git a/crates/bevy_asset/src/processor/process.rs b/crates/bevy_asset/src/processor/process.rs index 349c047005586..58083464cd15e 100644 --- a/crates/bevy_asset/src/processor/process.rs +++ b/crates/bevy_asset/src/processor/process.rs @@ -81,7 +81,7 @@ impl< > LoadTransformAndSave { pub fn new(transformer: T, saver: S) -> Self { - LoadTransformAndSave { + Self { transformer, saver, marker: PhantomData, @@ -105,7 +105,7 @@ pub struct LoadAndSave> { impl> From for LoadAndSave { fn from(value: S) -> Self { - LoadAndSave { + Self { saver: value, marker: PhantomData, } diff --git a/crates/bevy_asset/src/reflect.rs b/crates/bevy_asset/src/reflect.rs index a74a8b7fa5a0f..4f254d7c5a4a6 100644 --- a/crates/bevy_asset/src/reflect.rs +++ b/crates/bevy_asset/src/reflect.rs @@ -126,7 +126,7 @@ impl ReflectAsset { impl FromType for ReflectAsset { fn from_type() -> Self { - ReflectAsset { + Self { handle_type_id: TypeId::of::>(), assets_resource_type_id: TypeId::of::>(), get: |world, handle| { @@ -222,7 +222,7 @@ impl ReflectHandle { impl FromType> for ReflectHandle { fn from_type() -> Self { - ReflectHandle { + Self { asset_type_id: TypeId::of::(), downcast_handle_untyped: |handle: &dyn Any| { handle diff --git a/crates/bevy_asset/src/server/info.rs b/crates/bevy_asset/src/server/info.rs index 98d92702077c7..422ee07505e59 100644 --- a/crates/bevy_asset/src/server/info.rs +++ b/crates/bevy_asset/src/server/info.rs @@ -305,8 +305,8 @@ impl AssetInfos { fn next(&mut self) -> Option { match self { - HandlesByPathIterator::None => None, - HandlesByPathIterator::Some(iter) => iter.next(), + Self::None => None, + Self::Some(iter) => iter.next(), } } } @@ -531,7 +531,7 @@ impl AssetInfos { /// Recursively propagates loaded state up the dependency tree. fn propagate_loaded_state( - infos: &mut AssetInfos, + infos: &mut Self, loaded_id: UntypedAssetId, waiting_id: UntypedAssetId, sender: &Sender, @@ -564,7 +564,7 @@ impl AssetInfos { /// Recursively propagates failed state up the dependency tree fn propagate_failed_state( - infos: &mut AssetInfos, + infos: &mut Self, failed_id: UntypedAssetId, waiting_id: UntypedAssetId, ) { diff --git a/crates/bevy_asset/src/server/loaders.rs b/crates/bevy_asset/src/server/loaders.rs index b0ecba7ae3f1d..67f970bd5217e 100644 --- a/crates/bevy_asset/src/server/loaders.rs +++ b/crates/bevy_asset/src/server/loaders.rs @@ -293,8 +293,8 @@ pub(crate) enum MaybeAssetLoader { impl MaybeAssetLoader { pub(crate) async fn get(self) -> Result, GetLoaderError> { match self { - MaybeAssetLoader::Ready(loader) => Ok(loader), - MaybeAssetLoader::Pending { mut receiver, .. } => Ok(receiver.recv().await?), + Self::Ready(loader) => Ok(loader), + Self::Pending { mut receiver, .. } => Ok(receiver.recv().await?), } } } diff --git a/crates/bevy_asset/src/transformer.rs b/crates/bevy_asset/src/transformer.rs index 0ffddc4658a43..6372b1b13c071 100644 --- a/crates/bevy_asset/src/transformer.rs +++ b/crates/bevy_asset/src/transformer.rs @@ -51,7 +51,7 @@ impl TransformedAsset { /// Creates a new [`TransformedAsset`] from `asset` if its internal value matches `A`. pub fn from_loaded(asset: ErasedLoadedAsset) -> Option { if let Ok(value) = asset.value.downcast::() { - return Some(TransformedAsset { + return Some(Self { value: *value, labeled_assets: asset.labeled_assets, }); diff --git a/crates/bevy_audio/src/audio.rs b/crates/bevy_audio/src/audio.rs index 497adfcdba9a5..2ff3a31cba872 100644 --- a/crates/bevy_audio/src/audio.rs +++ b/crates/bevy_audio/src/audio.rs @@ -27,7 +27,7 @@ impl Volume { } /// Zero (silent) volume level - pub const ZERO: Self = Volume(0.0); + pub const ZERO: Self = Self(0.0); } /// The way Bevy manages the sound playback. @@ -81,7 +81,7 @@ impl Default for PlaybackSettings { impl PlaybackSettings { /// Will play the associated audio source once. - pub const ONCE: PlaybackSettings = PlaybackSettings { + pub const ONCE: Self = Self { mode: PlaybackMode::Once, volume: Volume(1.0), speed: 1.0, @@ -91,21 +91,21 @@ impl PlaybackSettings { }; /// Will play the associated audio source in a loop. - pub const LOOP: PlaybackSettings = PlaybackSettings { + pub const LOOP: Self = Self { mode: PlaybackMode::Loop, - ..PlaybackSettings::ONCE + ..Self::ONCE }; /// Will play the associated audio source once and despawn the entity afterwards. - pub const DESPAWN: PlaybackSettings = PlaybackSettings { + pub const DESPAWN: Self = Self { mode: PlaybackMode::Despawn, - ..PlaybackSettings::ONCE + ..Self::ONCE }; /// Will play the associated audio source once and remove the audio components afterwards. - pub const REMOVE: PlaybackSettings = PlaybackSettings { + pub const REMOVE: Self = Self { mode: PlaybackMode::Remove, - ..PlaybackSettings::ONCE + ..Self::ONCE }; /// Helper to start in a paused state. @@ -164,7 +164,7 @@ impl SpatialListener { /// `gap` is the distance between the left and right "ears" of the listener. Ears are /// positioned on the x axis. pub fn new(gap: f32) -> Self { - SpatialListener { + Self { left_ear_offset: Vec3::X * gap / -2.0, right_ear_offset: Vec3::X * gap / 2.0, } diff --git a/crates/bevy_audio/src/audio_source.rs b/crates/bevy_audio/src/audio_source.rs index 64a481b32852b..a10d4affcd4f2 100644 --- a/crates/bevy_audio/src/audio_source.rs +++ b/crates/bevy_audio/src/audio_source.rs @@ -93,8 +93,8 @@ pub trait Decodable: Send + Sync + 'static { } impl Decodable for AudioSource { - type DecoderItem = > as Iterator>::Item; - type Decoder = rodio::Decoder>; + type DecoderItem = > as Iterator>::Item; + type Decoder = rodio::Decoder>; fn decoder(&self) -> Self::Decoder { rodio::Decoder::new(Cursor::new(self.clone())).unwrap() diff --git a/crates/bevy_audio/src/pitch.rs b/crates/bevy_audio/src/pitch.rs index 3cc913b66fbcd..7e56282554c8b 100644 --- a/crates/bevy_audio/src/pitch.rs +++ b/crates/bevy_audio/src/pitch.rs @@ -15,7 +15,7 @@ pub struct Pitch { impl Pitch { /// Creates a new note pub fn new(frequency: f32, duration: std::time::Duration) -> Self { - Pitch { + Self { frequency, duration, } diff --git a/crates/bevy_color/src/color.rs b/crates/bevy_color/src/color.rs index 92fa2b98fd559..43191ce9837f5 100644 --- a/crates/bevy_color/src/color.rs +++ b/crates/bevy_color/src/color.rs @@ -371,7 +371,7 @@ impl Color { impl Default for Color { /// A fully white [`Color::LinearRgba`] color with an alpha of 1.0. fn default() -> Self { - Color::WHITE + Self::WHITE } } @@ -380,16 +380,16 @@ impl Alpha for Color { let mut new = *self; match &mut new { - Color::Srgba(x) => *x = x.with_alpha(alpha), - Color::LinearRgba(x) => *x = x.with_alpha(alpha), - Color::Hsla(x) => *x = x.with_alpha(alpha), - Color::Hsva(x) => *x = x.with_alpha(alpha), - Color::Hwba(x) => *x = x.with_alpha(alpha), - Color::Laba(x) => *x = x.with_alpha(alpha), - Color::Lcha(x) => *x = x.with_alpha(alpha), - Color::Oklaba(x) => *x = x.with_alpha(alpha), - Color::Oklcha(x) => *x = x.with_alpha(alpha), - Color::Xyza(x) => *x = x.with_alpha(alpha), + Self::Srgba(x) => *x = x.with_alpha(alpha), + Self::LinearRgba(x) => *x = x.with_alpha(alpha), + Self::Hsla(x) => *x = x.with_alpha(alpha), + Self::Hsva(x) => *x = x.with_alpha(alpha), + Self::Hwba(x) => *x = x.with_alpha(alpha), + Self::Laba(x) => *x = x.with_alpha(alpha), + Self::Lcha(x) => *x = x.with_alpha(alpha), + Self::Oklaba(x) => *x = x.with_alpha(alpha), + Self::Oklcha(x) => *x = x.with_alpha(alpha), + Self::Xyza(x) => *x = x.with_alpha(alpha), } new @@ -397,31 +397,31 @@ impl Alpha for Color { fn alpha(&self) -> f32 { match self { - Color::Srgba(x) => x.alpha(), - Color::LinearRgba(x) => x.alpha(), - Color::Hsla(x) => x.alpha(), - Color::Hsva(x) => x.alpha(), - Color::Hwba(x) => x.alpha(), - Color::Laba(x) => x.alpha(), - Color::Lcha(x) => x.alpha(), - Color::Oklaba(x) => x.alpha(), - Color::Oklcha(x) => x.alpha(), - Color::Xyza(x) => x.alpha(), + Self::Srgba(x) => x.alpha(), + Self::LinearRgba(x) => x.alpha(), + Self::Hsla(x) => x.alpha(), + Self::Hsva(x) => x.alpha(), + Self::Hwba(x) => x.alpha(), + Self::Laba(x) => x.alpha(), + Self::Lcha(x) => x.alpha(), + Self::Oklaba(x) => x.alpha(), + Self::Oklcha(x) => x.alpha(), + Self::Xyza(x) => x.alpha(), } } fn set_alpha(&mut self, alpha: f32) { match self { - Color::Srgba(x) => x.set_alpha(alpha), - Color::LinearRgba(x) => x.set_alpha(alpha), - Color::Hsla(x) => x.set_alpha(alpha), - Color::Hsva(x) => x.set_alpha(alpha), - Color::Hwba(x) => x.set_alpha(alpha), - Color::Laba(x) => x.set_alpha(alpha), - Color::Lcha(x) => x.set_alpha(alpha), - Color::Oklaba(x) => x.set_alpha(alpha), - Color::Oklcha(x) => x.set_alpha(alpha), - Color::Xyza(x) => x.set_alpha(alpha), + Self::Srgba(x) => x.set_alpha(alpha), + Self::LinearRgba(x) => x.set_alpha(alpha), + Self::Hsla(x) => x.set_alpha(alpha), + Self::Hsva(x) => x.set_alpha(alpha), + Self::Hwba(x) => x.set_alpha(alpha), + Self::Laba(x) => x.set_alpha(alpha), + Self::Lcha(x) => x.set_alpha(alpha), + Self::Oklaba(x) => x.set_alpha(alpha), + Self::Oklcha(x) => x.set_alpha(alpha), + Self::Xyza(x) => x.set_alpha(alpha), } } } @@ -662,16 +662,16 @@ type ChosenColorSpace = Oklcha; impl Luminance for Color { fn luminance(&self) -> f32 { match self { - Color::Srgba(x) => x.luminance(), - Color::LinearRgba(x) => x.luminance(), - Color::Hsla(x) => x.luminance(), - Color::Hsva(x) => ChosenColorSpace::from(*x).luminance(), - Color::Hwba(x) => ChosenColorSpace::from(*x).luminance(), - Color::Laba(x) => x.luminance(), - Color::Lcha(x) => x.luminance(), - Color::Oklaba(x) => x.luminance(), - Color::Oklcha(x) => x.luminance(), - Color::Xyza(x) => x.luminance(), + Self::Srgba(x) => x.luminance(), + Self::LinearRgba(x) => x.luminance(), + Self::Hsla(x) => x.luminance(), + Self::Hsva(x) => ChosenColorSpace::from(*x).luminance(), + Self::Hwba(x) => ChosenColorSpace::from(*x).luminance(), + Self::Laba(x) => x.luminance(), + Self::Lcha(x) => x.luminance(), + Self::Oklaba(x) => x.luminance(), + Self::Oklcha(x) => x.luminance(), + Self::Xyza(x) => x.luminance(), } } @@ -679,16 +679,16 @@ impl Luminance for Color { let mut new = *self; match &mut new { - Color::Srgba(x) => *x = x.with_luminance(value), - Color::LinearRgba(x) => *x = x.with_luminance(value), - Color::Hsla(x) => *x = x.with_luminance(value), - Color::Hsva(x) => *x = ChosenColorSpace::from(*x).with_luminance(value).into(), - Color::Hwba(x) => *x = ChosenColorSpace::from(*x).with_luminance(value).into(), - Color::Laba(x) => *x = x.with_luminance(value), - Color::Lcha(x) => *x = x.with_luminance(value), - Color::Oklaba(x) => *x = x.with_luminance(value), - Color::Oklcha(x) => *x = x.with_luminance(value), - Color::Xyza(x) => *x = x.with_luminance(value), + Self::Srgba(x) => *x = x.with_luminance(value), + Self::LinearRgba(x) => *x = x.with_luminance(value), + Self::Hsla(x) => *x = x.with_luminance(value), + Self::Hsva(x) => *x = ChosenColorSpace::from(*x).with_luminance(value).into(), + Self::Hwba(x) => *x = ChosenColorSpace::from(*x).with_luminance(value).into(), + Self::Laba(x) => *x = x.with_luminance(value), + Self::Lcha(x) => *x = x.with_luminance(value), + Self::Oklaba(x) => *x = x.with_luminance(value), + Self::Oklcha(x) => *x = x.with_luminance(value), + Self::Xyza(x) => *x = x.with_luminance(value), } new @@ -698,16 +698,16 @@ impl Luminance for Color { let mut new = *self; match &mut new { - Color::Srgba(x) => *x = x.darker(amount), - Color::LinearRgba(x) => *x = x.darker(amount), - Color::Hsla(x) => *x = x.darker(amount), - Color::Hsva(x) => *x = ChosenColorSpace::from(*x).darker(amount).into(), - Color::Hwba(x) => *x = ChosenColorSpace::from(*x).darker(amount).into(), - Color::Laba(x) => *x = x.darker(amount), - Color::Lcha(x) => *x = x.darker(amount), - Color::Oklaba(x) => *x = x.darker(amount), - Color::Oklcha(x) => *x = x.darker(amount), - Color::Xyza(x) => *x = x.darker(amount), + Self::Srgba(x) => *x = x.darker(amount), + Self::LinearRgba(x) => *x = x.darker(amount), + Self::Hsla(x) => *x = x.darker(amount), + Self::Hsva(x) => *x = ChosenColorSpace::from(*x).darker(amount).into(), + Self::Hwba(x) => *x = ChosenColorSpace::from(*x).darker(amount).into(), + Self::Laba(x) => *x = x.darker(amount), + Self::Lcha(x) => *x = x.darker(amount), + Self::Oklaba(x) => *x = x.darker(amount), + Self::Oklcha(x) => *x = x.darker(amount), + Self::Xyza(x) => *x = x.darker(amount), } new @@ -717,16 +717,16 @@ impl Luminance for Color { let mut new = *self; match &mut new { - Color::Srgba(x) => *x = x.lighter(amount), - Color::LinearRgba(x) => *x = x.lighter(amount), - Color::Hsla(x) => *x = x.lighter(amount), - Color::Hsva(x) => *x = ChosenColorSpace::from(*x).lighter(amount).into(), - Color::Hwba(x) => *x = ChosenColorSpace::from(*x).lighter(amount).into(), - Color::Laba(x) => *x = x.lighter(amount), - Color::Lcha(x) => *x = x.lighter(amount), - Color::Oklaba(x) => *x = x.lighter(amount), - Color::Oklcha(x) => *x = x.lighter(amount), - Color::Xyza(x) => *x = x.lighter(amount), + Self::Srgba(x) => *x = x.lighter(amount), + Self::LinearRgba(x) => *x = x.lighter(amount), + Self::Hsla(x) => *x = x.lighter(amount), + Self::Hsva(x) => *x = ChosenColorSpace::from(*x).lighter(amount).into(), + Self::Hwba(x) => *x = ChosenColorSpace::from(*x).lighter(amount).into(), + Self::Laba(x) => *x = x.lighter(amount), + Self::Lcha(x) => *x = x.lighter(amount), + Self::Oklaba(x) => *x = x.lighter(amount), + Self::Oklcha(x) => *x = x.lighter(amount), + Self::Xyza(x) => *x = x.lighter(amount), } new @@ -738,16 +738,16 @@ impl Hue for Color { let mut new = *self; match &mut new { - Color::Srgba(x) => *x = ChosenColorSpace::from(*x).with_hue(hue).into(), - Color::LinearRgba(x) => *x = ChosenColorSpace::from(*x).with_hue(hue).into(), - Color::Hsla(x) => *x = x.with_hue(hue), - Color::Hsva(x) => *x = x.with_hue(hue), - Color::Hwba(x) => *x = x.with_hue(hue), - Color::Laba(x) => *x = ChosenColorSpace::from(*x).with_hue(hue).into(), - Color::Lcha(x) => *x = x.with_hue(hue), - Color::Oklaba(x) => *x = ChosenColorSpace::from(*x).with_hue(hue).into(), - Color::Oklcha(x) => *x = x.with_hue(hue), - Color::Xyza(x) => *x = ChosenColorSpace::from(*x).with_hue(hue).into(), + Self::Srgba(x) => *x = ChosenColorSpace::from(*x).with_hue(hue).into(), + Self::LinearRgba(x) => *x = ChosenColorSpace::from(*x).with_hue(hue).into(), + Self::Hsla(x) => *x = x.with_hue(hue), + Self::Hsva(x) => *x = x.with_hue(hue), + Self::Hwba(x) => *x = x.with_hue(hue), + Self::Laba(x) => *x = ChosenColorSpace::from(*x).with_hue(hue).into(), + Self::Lcha(x) => *x = x.with_hue(hue), + Self::Oklaba(x) => *x = ChosenColorSpace::from(*x).with_hue(hue).into(), + Self::Oklcha(x) => *x = x.with_hue(hue), + Self::Xyza(x) => *x = ChosenColorSpace::from(*x).with_hue(hue).into(), } new @@ -755,16 +755,16 @@ impl Hue for Color { fn hue(&self) -> f32 { match self { - Color::Srgba(x) => ChosenColorSpace::from(*x).hue(), - Color::LinearRgba(x) => ChosenColorSpace::from(*x).hue(), - Color::Hsla(x) => x.hue(), - Color::Hsva(x) => x.hue(), - Color::Hwba(x) => x.hue(), - Color::Laba(x) => ChosenColorSpace::from(*x).hue(), - Color::Lcha(x) => x.hue(), - Color::Oklaba(x) => ChosenColorSpace::from(*x).hue(), - Color::Oklcha(x) => x.hue(), - Color::Xyza(x) => ChosenColorSpace::from(*x).hue(), + Self::Srgba(x) => ChosenColorSpace::from(*x).hue(), + Self::LinearRgba(x) => ChosenColorSpace::from(*x).hue(), + Self::Hsla(x) => x.hue(), + Self::Hsva(x) => x.hue(), + Self::Hwba(x) => x.hue(), + Self::Laba(x) => ChosenColorSpace::from(*x).hue(), + Self::Lcha(x) => x.hue(), + Self::Oklaba(x) => ChosenColorSpace::from(*x).hue(), + Self::Oklcha(x) => x.hue(), + Self::Xyza(x) => ChosenColorSpace::from(*x).hue(), } } @@ -778,16 +778,16 @@ impl Mix for Color { let mut new = *self; match &mut new { - Color::Srgba(x) => *x = x.mix(&(*other).into(), factor), - Color::LinearRgba(x) => *x = x.mix(&(*other).into(), factor), - Color::Hsla(x) => *x = x.mix(&(*other).into(), factor), - Color::Hsva(x) => *x = x.mix(&(*other).into(), factor), - Color::Hwba(x) => *x = x.mix(&(*other).into(), factor), - Color::Laba(x) => *x = x.mix(&(*other).into(), factor), - Color::Lcha(x) => *x = x.mix(&(*other).into(), factor), - Color::Oklaba(x) => *x = x.mix(&(*other).into(), factor), - Color::Oklcha(x) => *x = x.mix(&(*other).into(), factor), - Color::Xyza(x) => *x = x.mix(&(*other).into(), factor), + Self::Srgba(x) => *x = x.mix(&(*other).into(), factor), + Self::LinearRgba(x) => *x = x.mix(&(*other).into(), factor), + Self::Hsla(x) => *x = x.mix(&(*other).into(), factor), + Self::Hsva(x) => *x = x.mix(&(*other).into(), factor), + Self::Hwba(x) => *x = x.mix(&(*other).into(), factor), + Self::Laba(x) => *x = x.mix(&(*other).into(), factor), + Self::Lcha(x) => *x = x.mix(&(*other).into(), factor), + Self::Oklaba(x) => *x = x.mix(&(*other).into(), factor), + Self::Oklcha(x) => *x = x.mix(&(*other).into(), factor), + Self::Xyza(x) => *x = x.mix(&(*other).into(), factor), } new @@ -797,16 +797,16 @@ impl Mix for Color { impl EuclideanDistance for Color { fn distance_squared(&self, other: &Self) -> f32 { match self { - Color::Srgba(x) => x.distance_squared(&(*other).into()), - Color::LinearRgba(x) => x.distance_squared(&(*other).into()), - Color::Hsla(x) => ChosenColorSpace::from(*x).distance_squared(&(*other).into()), - Color::Hsva(x) => ChosenColorSpace::from(*x).distance_squared(&(*other).into()), - Color::Hwba(x) => ChosenColorSpace::from(*x).distance_squared(&(*other).into()), - Color::Laba(x) => ChosenColorSpace::from(*x).distance_squared(&(*other).into()), - Color::Lcha(x) => ChosenColorSpace::from(*x).distance_squared(&(*other).into()), - Color::Oklaba(x) => x.distance_squared(&(*other).into()), - Color::Oklcha(x) => x.distance_squared(&(*other).into()), - Color::Xyza(x) => ChosenColorSpace::from(*x).distance_squared(&(*other).into()), + Self::Srgba(x) => x.distance_squared(&(*other).into()), + Self::LinearRgba(x) => x.distance_squared(&(*other).into()), + Self::Hsla(x) => ChosenColorSpace::from(*x).distance_squared(&(*other).into()), + Self::Hsva(x) => ChosenColorSpace::from(*x).distance_squared(&(*other).into()), + Self::Hwba(x) => ChosenColorSpace::from(*x).distance_squared(&(*other).into()), + Self::Laba(x) => ChosenColorSpace::from(*x).distance_squared(&(*other).into()), + Self::Lcha(x) => ChosenColorSpace::from(*x).distance_squared(&(*other).into()), + Self::Oklaba(x) => x.distance_squared(&(*other).into()), + Self::Oklcha(x) => x.distance_squared(&(*other).into()), + Self::Xyza(x) => ChosenColorSpace::from(*x).distance_squared(&(*other).into()), } } } diff --git a/crates/bevy_color/src/hsla.rs b/crates/bevy_color/src/hsla.rs index 6b26fbff8de34..f2512bca8288f 100644 --- a/crates/bevy_color/src/hsla.rs +++ b/crates/bevy_color/src/hsla.rs @@ -254,8 +254,7 @@ impl From for Hsva { } else { 2. * (1. - (lightness / value)) }; - - Hsva::new(hue, saturation, value, alpha) + Self::new(hue, saturation, value, alpha) } } @@ -275,8 +274,7 @@ impl From for Hsla { } else { (value - lightness) / lightness.min(1. - lightness) }; - - Hsla::new(hue, saturation, lightness, alpha) + Self::new(hue, saturation, lightness, alpha) } } diff --git a/crates/bevy_color/src/hsva.rs b/crates/bevy_color/src/hsva.rs index e708ccf67e5b0..bee398910ccde 100644 --- a/crates/bevy_color/src/hsva.rs +++ b/crates/bevy_color/src/hsva.rs @@ -141,8 +141,7 @@ impl From for Hwba { // Based on https://en.wikipedia.org/wiki/HWB_color_model#Conversion let whiteness = (1. - saturation) * value; let blackness = 1. - value; - - Hwba::new(hue, whiteness, blackness, alpha) + Self::new(hue, whiteness, blackness, alpha) } } @@ -162,8 +161,7 @@ impl From for Hsva { } else { 0. }; - - Hsva::new(hue, saturation, value, alpha) + Self::new(hue, saturation, value, alpha) } } diff --git a/crates/bevy_color/src/hwba.rs b/crates/bevy_color/src/hwba.rs index 078f56cfb7c9a..1411c4f613619 100644 --- a/crates/bevy_color/src/hwba.rs +++ b/crates/bevy_color/src/hwba.rs @@ -216,7 +216,7 @@ impl From for Hwba { let whiteness = x_min; let blackness = 1.0 - x_max; - Hwba { + Self { hue, whiteness, blackness, @@ -258,7 +258,7 @@ impl From for Srgba { _ => unreachable!("i is bounded in [0, 6)"), }; - Srgba::new(red, green, blue, alpha) + Self::new(red, green, blue, alpha) } } diff --git a/crates/bevy_color/src/laba.rs b/crates/bevy_color/src/laba.rs index 391bb9b4fe86f..3bce8c37a986c 100644 --- a/crates/bevy_color/src/laba.rs +++ b/crates/bevy_color/src/laba.rs @@ -247,11 +247,10 @@ impl From for Xyza { (116.0 * fz - 16.0) / Laba::CIE_KAPPA } }; - let x = xr * Xyza::D65_WHITE.x; - let y = yr * Xyza::D65_WHITE.y; - let z = zr * Xyza::D65_WHITE.z; - - Xyza::new(x, y, z, alpha) + let x = xr * Self::D65_WHITE.x; + let y = yr * Self::D65_WHITE.y; + let z = zr * Self::D65_WHITE.z; + Self::new(x, y, z, alpha) } } @@ -261,26 +260,25 @@ impl From for Laba { let xr = x / Xyza::D65_WHITE.x; let yr = y / Xyza::D65_WHITE.y; let zr = z / Xyza::D65_WHITE.z; - let fx = if xr > Laba::CIE_EPSILON { + let fx = if xr > Self::CIE_EPSILON { xr.cbrt() } else { - (Laba::CIE_KAPPA * xr + 16.0) / 116.0 + (Self::CIE_KAPPA * xr + 16.0) / 116.0 }; - let fy = if yr > Laba::CIE_EPSILON { + let fy = if yr > Self::CIE_EPSILON { yr.cbrt() } else { - (Laba::CIE_KAPPA * yr + 16.0) / 116.0 + (Self::CIE_KAPPA * yr + 16.0) / 116.0 }; - let fz = if yr > Laba::CIE_EPSILON { + let fz = if yr > Self::CIE_EPSILON { zr.cbrt() } else { - (Laba::CIE_KAPPA * zr + 16.0) / 116.0 + (Self::CIE_KAPPA * zr + 16.0) / 116.0 }; let l = 1.16 * fy - 0.16; let a = 5.00 * (fx - fy); let b = 2.00 * (fy - fz); - - Laba::new(l, a, b, alpha) + Self::new(l, a, b, alpha) } } diff --git a/crates/bevy_color/src/lcha.rs b/crates/bevy_color/src/lcha.rs index e372ff492afcc..24df3665ebdc0 100644 --- a/crates/bevy_color/src/lcha.rs +++ b/crates/bevy_color/src/lcha.rs @@ -259,8 +259,7 @@ impl From for Laba { let l = lightness; let a = chroma * hue.to_radians().cos(); let b = chroma * hue.to_radians().sin(); - - Laba::new(l, a, b, alpha) + Self::new(l, a, b, alpha) } } @@ -284,11 +283,9 @@ impl From for Lcha { h } }; - let chroma = c.clamp(0.0, 1.5); let hue = h; - - Lcha::new(lightness, chroma, hue, alpha) + Self::new(lightness, chroma, hue, alpha) } } diff --git a/crates/bevy_color/src/linear_rgba.rs b/crates/bevy_color/src/linear_rgba.rs index 3a9a0fd5d2641..f0b67d07ca484 100644 --- a/crates/bevy_color/src/linear_rgba.rs +++ b/crates/bevy_color/src/linear_rgba.rs @@ -321,7 +321,7 @@ impl ColorToPacked for LinearRgba { #[cfg(feature = "wgpu-types")] impl From for wgpu_types::Color { fn from(color: LinearRgba) -> Self { - wgpu_types::Color { + Self { r: color.red as f64, g: color.green as f64, b: color.blue as f64, @@ -370,8 +370,7 @@ impl encase::private::ReadFrom for LinearRgba { for el in &mut buffer { encase::private::ReadFrom::read_from(el, reader); } - - *self = LinearRgba { + *self = Self { red: buffer[0], green: buffer[1], blue: buffer[2], @@ -391,7 +390,7 @@ impl encase::private::CreateFrom for LinearRgba { let green: f32 = encase::private::CreateFrom::create_from(reader); let blue: f32 = encase::private::CreateFrom::create_from(reader); let alpha: f32 = encase::private::CreateFrom::create_from(reader); - LinearRgba { + Self { red, green, blue, diff --git a/crates/bevy_color/src/oklaba.rs b/crates/bevy_color/src/oklaba.rs index bf0ffdba1620f..96585b0728d4b 100644 --- a/crates/bevy_color/src/oklaba.rs +++ b/crates/bevy_color/src/oklaba.rs @@ -235,7 +235,7 @@ impl From for Oklaba { let l = 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_; let a = 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_; let b = 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_; - Oklaba::new(l, a, b, alpha) + Self::new(l, a, b, alpha) } } diff --git a/crates/bevy_color/src/oklcha.rs b/crates/bevy_color/src/oklcha.rs index 165fa0af95a24..1e137ac1a563b 100644 --- a/crates/bevy_color/src/oklcha.rs +++ b/crates/bevy_color/src/oklcha.rs @@ -262,10 +262,8 @@ impl From for Oklcha { ) -> Self { let chroma = a.hypot(b); let hue = b.atan2(a).to_degrees(); - let hue = if hue < 0.0 { hue + 360.0 } else { hue }; - - Oklcha::new(lightness, chroma, hue, alpha) + Self::new(lightness, chroma, hue, alpha) } } @@ -281,8 +279,7 @@ impl From for Oklaba { let l = lightness; let a = chroma * hue.to_radians().cos(); let b = chroma * hue.to_radians().sin(); - - Oklaba::new(l, a, b, alpha) + Self::new(l, a, b, alpha) } } diff --git a/crates/bevy_color/src/srgba.rs b/crates/bevy_color/src/srgba.rs index 100d35632d085..ffb3870c9a92b 100644 --- a/crates/bevy_color/src/srgba.rs +++ b/crates/bevy_color/src/srgba.rs @@ -40,12 +40,12 @@ impl Srgba { // https://en.wikipedia.org/wiki/Web_colors#Basic_colors ///
- pub const BLACK: Srgba = Srgba::new(0.0, 0.0, 0.0, 1.0); + pub const BLACK: Self = Self::new(0.0, 0.0, 0.0, 1.0); ///
#[doc(alias = "transparent")] - pub const NONE: Srgba = Srgba::new(0.0, 0.0, 0.0, 0.0); + pub const NONE: Self = Self::new(0.0, 0.0, 0.0, 0.0); ///
- pub const WHITE: Srgba = Srgba::new(1.0, 1.0, 1.0, 1.0); + pub const WHITE: Self = Self::new(1.0, 1.0, 1.0, 1.0); /// A fully red color with full alpha. pub const RED: Self = Self { @@ -250,7 +250,7 @@ impl Luminance for Srgba { fn with_luminance(&self, luminance: f32) -> Self { let linear: LinearRgba = (*self).into(); linear - .with_luminance(Srgba::gamma_function(luminance)) + .with_luminance(Self::gamma_function(luminance)) .into() } @@ -389,9 +389,9 @@ impl From for Srgba { #[inline] fn from(value: LinearRgba) -> Self { Self { - red: Srgba::gamma_function_inverse(value.red), - green: Srgba::gamma_function_inverse(value.green), - blue: Srgba::gamma_function_inverse(value.blue), + red: Self::gamma_function_inverse(value.red), + green: Self::gamma_function_inverse(value.green), + blue: Self::gamma_function_inverse(value.blue), alpha: value.alpha, } } diff --git a/crates/bevy_color/src/xyza.rs b/crates/bevy_color/src/xyza.rs index a9fb422bef110..fc5b5420a651f 100644 --- a/crates/bevy_color/src/xyza.rs +++ b/crates/bevy_color/src/xyza.rs @@ -219,12 +219,10 @@ impl From for Xyza { let r = red; let g = green; let b = blue; - let x = r * 0.4124564 + g * 0.3575761 + b * 0.1804375; let y = r * 0.2126729 + g * 0.7151522 + b * 0.072175; let z = r * 0.0193339 + g * 0.119192 + b * 0.9503041; - - Xyza::new(x, y, z, alpha) + Self::new(x, y, z, alpha) } } @@ -236,8 +234,7 @@ impl From for LinearRgba { let r = x * 3.2404542 + y * -1.5371385 + z * -0.4985314; let g = x * -0.969266 + y * 1.8760108 + z * 0.041556; let b = x * 0.0556434 + y * -0.2040259 + z * 1.0572252; - - LinearRgba::new(r, g, b, alpha) + Self::new(r, g, b, alpha) } } diff --git a/crates/bevy_core/src/name.rs b/crates/bevy_core/src/name.rs index 9f858cf96e09c..8bb93db80ec1b 100644 --- a/crates/bevy_core/src/name.rs +++ b/crates/bevy_core/src/name.rs @@ -41,7 +41,7 @@ pub struct Name { impl Default for Name { fn default() -> Self { - Name::new("") + Self::new("") } } @@ -51,7 +51,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 } @@ -61,7 +61,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. @@ -146,13 +146,13 @@ impl<'a> std::fmt::Display for NameOrEntityItem<'a> { impl From<&str> for Name { #[inline(always)] fn from(name: &str) -> Self { - Name::new(name.to_owned()) + Self::new(name.to_owned()) } } impl From for Name { #[inline(always)] fn from(name: String) -> Self { - Name::new(name) + Self::new(name) } } @@ -166,13 +166,13 @@ impl AsRef for Name { } impl From<&Name> for String { #[inline(always)] - fn from(val: &Name) -> String { + fn from(val: &Name) -> Self { val.as_str().to_owned() } } impl From for String { #[inline(always)] - fn from(val: Name) -> String { + fn from(val: Name) -> Self { val.name.into_owned() } } diff --git a/crates/bevy_core/src/task_pool_options.rs b/crates/bevy_core/src/task_pool_options.rs index 276902fb499da..a7429866134a0 100644 --- a/crates/bevy_core/src/task_pool_options.rs +++ b/crates/bevy_core/src/task_pool_options.rs @@ -51,7 +51,7 @@ pub struct TaskPoolOptions { impl Default for TaskPoolOptions { fn default() -> Self { - TaskPoolOptions { + Self { // By default, use however many cores are available on the system min_total_threads: 1, max_total_threads: usize::MAX, @@ -83,7 +83,7 @@ impl Default for TaskPoolOptions { impl TaskPoolOptions { /// Create a configuration that forces using the given number of threads. pub fn with_num_threads(thread_count: usize) -> Self { - TaskPoolOptions { + Self { min_total_threads: thread_count, max_total_threads: thread_count, ..Default::default() diff --git a/crates/bevy_core_pipeline/src/auto_exposure/compensation_curve.rs b/crates/bevy_core_pipeline/src/auto_exposure/compensation_curve.rs index 67dcead57a834..d0699214221d9 100644 --- a/crates/bevy_core_pipeline/src/auto_exposure/compensation_curve.rs +++ b/crates/bevy_core_pipeline/src/auto_exposure/compensation_curve.rs @@ -212,19 +212,15 @@ impl RenderAsset for GpuAutoExposureCompensationCurve { Default::default(), &source.lut, ); - let texture_view = texture.create_view(&Default::default()); - let mut extents = UniformBuffer::from(AutoExposureCompensationCurveUniform { min_log_lum: source.min_log_lum, inv_log_lum_range: 1.0 / (source.max_log_lum - source.min_log_lum), min_compensation: source.min_compensation, compensation_range: source.max_compensation - source.min_compensation, }); - extents.write_buffer(render_device, render_queue); - - Ok(GpuAutoExposureCompensationCurve { + Ok(Self { texture_view, extents, }) diff --git a/crates/bevy_core_pipeline/src/blit/mod.rs b/crates/bevy_core_pipeline/src/blit/mod.rs index d11a99cbb329d..a94e743128209 100644 --- a/crates/bevy_core_pipeline/src/blit/mod.rs +++ b/crates/bevy_core_pipeline/src/blit/mod.rs @@ -59,7 +59,7 @@ impl FromWorld for BlitPipeline { let sampler = render_device.create_sampler(&SamplerDescriptor::default()); - BlitPipeline { + Self { texture_bind_group, sampler, } diff --git a/crates/bevy_core_pipeline/src/bloom/downsampling_pipeline.rs b/crates/bevy_core_pipeline/src/bloom/downsampling_pipeline.rs index ba48e4b0fe78b..128ec8145f8da 100644 --- a/crates/bevy_core_pipeline/src/bloom/downsampling_pipeline.rs +++ b/crates/bevy_core_pipeline/src/bloom/downsampling_pipeline.rs @@ -73,7 +73,7 @@ impl FromWorld for BloomDownsamplingPipeline { ..Default::default() }); - BloomDownsamplingPipeline { + Self { bind_group_layout, sampler, } diff --git a/crates/bevy_core_pipeline/src/bloom/upsampling_pipeline.rs b/crates/bevy_core_pipeline/src/bloom/upsampling_pipeline.rs index 161c251e36d4d..ad878e6ab17bb 100644 --- a/crates/bevy_core_pipeline/src/bloom/upsampling_pipeline.rs +++ b/crates/bevy_core_pipeline/src/bloom/upsampling_pipeline.rs @@ -37,7 +37,6 @@ pub struct BloomUpsamplingPipelineKeys { impl FromWorld for BloomUpsamplingPipeline { fn from_world(world: &mut World) -> Self { let render_device = world.resource::(); - let bind_group_layout = render_device.create_bind_group_layout( "bloom_upsampling_bind_group_layout", &BindGroupLayoutEntries::sequential( @@ -52,8 +51,7 @@ impl FromWorld for BloomUpsamplingPipeline { ), ), ); - - BloomUpsamplingPipeline { bind_group_layout } + Self { bind_group_layout } } } diff --git a/crates/bevy_core_pipeline/src/contrast_adaptive_sharpening/mod.rs b/crates/bevy_core_pipeline/src/contrast_adaptive_sharpening/mod.rs index f76e06367231e..ba06984016dfb 100644 --- a/crates/bevy_core_pipeline/src/contrast_adaptive_sharpening/mod.rs +++ b/crates/bevy_core_pipeline/src/contrast_adaptive_sharpening/mod.rs @@ -56,7 +56,7 @@ pub struct ContrastAdaptiveSharpeningSettings { impl Default for ContrastAdaptiveSharpeningSettings { fn default() -> Self { - ContrastAdaptiveSharpeningSettings { + Self { enabled: true, sharpening_strength: 0.6, denoise: false, @@ -191,7 +191,7 @@ impl FromWorld for CasPipeline { let sampler = render_device.create_sampler(&SamplerDescriptor::default()); - CasPipeline { + Self { texture_bind_group, sampler, } diff --git a/crates/bevy_core_pipeline/src/core_2d/mod.rs b/crates/bevy_core_pipeline/src/core_2d/mod.rs index 7bd6bea38cb58..936e54e65f727 100644 --- a/crates/bevy_core_pipeline/src/core_2d/mod.rs +++ b/crates/bevy_core_pipeline/src/core_2d/mod.rs @@ -191,7 +191,7 @@ impl BinnedPhaseItem for Opaque2d { batch_range: Range, extra_index: PhaseItemExtraIndex, ) -> Self { - Opaque2d { + Self { key, representative_entity, batch_range, @@ -276,7 +276,7 @@ impl BinnedPhaseItem for AlphaMask2d { batch_range: Range, extra_index: PhaseItemExtraIndex, ) -> Self { - AlphaMask2d { + Self { key, representative_entity, batch_range, diff --git a/crates/bevy_core_pipeline/src/core_3d/camera_3d.rs b/crates/bevy_core_pipeline/src/core_3d/camera_3d.rs index 697d9df64b339..7374986bdda20 100644 --- a/crates/bevy_core_pipeline/src/core_3d/camera_3d.rs +++ b/crates/bevy_core_pipeline/src/core_3d/camera_3d.rs @@ -92,15 +92,15 @@ pub enum Camera3dDepthLoadOp { impl Default for Camera3dDepthLoadOp { fn default() -> Self { - Camera3dDepthLoadOp::Clear(0.0) + Self::Clear(0.0) } } impl From for LoadOp { fn from(config: Camera3dDepthLoadOp) -> Self { match config { - Camera3dDepthLoadOp::Clear(x) => LoadOp::Clear(x), - Camera3dDepthLoadOp::Load => LoadOp::Load, + Camera3dDepthLoadOp::Clear(x) => Self::Clear(x), + Camera3dDepthLoadOp::Load => Self::Load, } } } diff --git a/crates/bevy_core_pipeline/src/core_3d/mod.rs b/crates/bevy_core_pipeline/src/core_3d/mod.rs index bf38e1deb2159..572233fb0df0b 100644 --- a/crates/bevy_core_pipeline/src/core_3d/mod.rs +++ b/crates/bevy_core_pipeline/src/core_3d/mod.rs @@ -285,7 +285,7 @@ impl BinnedPhaseItem for Opaque3d { batch_range: Range, extra_index: PhaseItemExtraIndex, ) -> Self { - Opaque3d { + Self { key, representative_entity, batch_range, diff --git a/crates/bevy_core_pipeline/src/dof/mod.rs b/crates/bevy_core_pipeline/src/dof/mod.rs index a35bdc0723d8a..4f4b775f3aced 100644 --- a/crates/bevy_core_pipeline/src/dof/mod.rs +++ b/crates/bevy_core_pipeline/src/dof/mod.rs @@ -474,8 +474,8 @@ impl DepthOfFieldSettings { /// /// All fields of the returned [`DepthOfFieldSettings`] other than /// `focal_length` and `aperture_f_stops` are set to their default values. - pub fn from_physical_camera(camera: &PhysicalCameraParameters) -> DepthOfFieldSettings { - DepthOfFieldSettings { + pub fn from_physical_camera(camera: &PhysicalCameraParameters) -> Self { + Self { sensor_height: camera.sensor_height, aperture_f_stops: camera.aperture_f_stops, ..default() @@ -510,7 +510,7 @@ impl FromWorld for DepthOfFieldGlobalBindGroupLayout { ..default() }); - DepthOfFieldGlobalBindGroupLayout { + Self { color_texture_sampler: sampler, layout, } @@ -846,7 +846,7 @@ impl DepthOfFieldPipelines { /// depth of field render passes. fn pipeline_render_info(&self) -> [DepthOfFieldPipelineRenderInfo; 2] { match *self { - DepthOfFieldPipelines::Gaussian { + Self::Gaussian { horizontal: horizontal_pipeline, vertical: vertical_pipeline, } => [ @@ -866,7 +866,7 @@ impl DepthOfFieldPipelines { }, ], - DepthOfFieldPipelines::Bokeh { + Self::Bokeh { pass_0: pass_0_pipeline, pass_1: pass_1_pipeline, } => [ diff --git a/crates/bevy_core_pipeline/src/fxaa/mod.rs b/crates/bevy_core_pipeline/src/fxaa/mod.rs index f338a564375d0..25e11cb38e0ce 100644 --- a/crates/bevy_core_pipeline/src/fxaa/mod.rs +++ b/crates/bevy_core_pipeline/src/fxaa/mod.rs @@ -40,11 +40,11 @@ pub enum Sensitivity { impl Sensitivity { pub fn get_str(&self) -> &str { match self { - Sensitivity::Low => "LOW", - Sensitivity::Medium => "MEDIUM", - Sensitivity::High => "HIGH", - Sensitivity::Ultra => "ULTRA", - Sensitivity::Extreme => "EXTREME", + Self::Low => "LOW", + Self::Medium => "MEDIUM", + Self::High => "HIGH", + Self::Ultra => "ULTRA", + Self::Extreme => "EXTREME", } } } @@ -70,7 +70,7 @@ pub struct Fxaa { impl Default for Fxaa { fn default() -> Self { - Fxaa { + Self { enabled: true, edge_threshold: Sensitivity::High, edge_threshold_min: Sensitivity::High, @@ -150,7 +150,7 @@ impl FromWorld for FxaaPipeline { ..default() }); - FxaaPipeline { + Self { texture_bind_group, sampler, } diff --git a/crates/bevy_core_pipeline/src/motion_blur/pipeline.rs b/crates/bevy_core_pipeline/src/motion_blur/pipeline.rs index cff26a9e22f17..39a4deb65ca2a 100644 --- a/crates/bevy_core_pipeline/src/motion_blur/pipeline.rs +++ b/crates/bevy_core_pipeline/src/motion_blur/pipeline.rs @@ -88,7 +88,7 @@ impl MotionBlurPipeline { impl FromWorld for MotionBlurPipeline { fn from_world(render_world: &mut bevy_ecs::world::World) -> Self { let render_device = render_world.resource::().clone(); - MotionBlurPipeline::new(&render_device) + Self::new(&render_device) } } diff --git a/crates/bevy_core_pipeline/src/post_process/mod.rs b/crates/bevy_core_pipeline/src/post_process/mod.rs index 79c41f990b33c..0c3365aee6e7a 100644 --- a/crates/bevy_core_pipeline/src/post_process/mod.rs +++ b/crates/bevy_core_pipeline/src/post_process/mod.rs @@ -314,7 +314,7 @@ impl FromWorld for PostProcessingPipeline { ..default() }); - PostProcessingPipeline { + Self { bind_group_layout, source_sampler, chromatic_aberration_lut_sampler, @@ -486,11 +486,9 @@ pub fn prepare_post_processing_uniforms( } impl ExtractComponent for ChromaticAberration { - type QueryData = Read; - + type QueryData = Read; type QueryFilter = With; - - type Out = ChromaticAberration; + type Out = Self; fn extract_component( chromatic_aberration: QueryItem<'_, Self::QueryData>, diff --git a/crates/bevy_core_pipeline/src/prepass/mod.rs b/crates/bevy_core_pipeline/src/prepass/mod.rs index 1f03eb8220f39..73cd6971e4dbf 100644 --- a/crates/bevy_core_pipeline/src/prepass/mod.rs +++ b/crates/bevy_core_pipeline/src/prepass/mod.rs @@ -206,7 +206,7 @@ impl BinnedPhaseItem for Opaque3dPrepass { batch_range: Range, extra_index: PhaseItemExtraIndex, ) -> Self { - Opaque3dPrepass { + Self { key, representative_entity, batch_range, diff --git a/crates/bevy_core_pipeline/src/skybox/mod.rs b/crates/bevy_core_pipeline/src/skybox/mod.rs index 59cfa908863c2..571ff3965e400 100644 --- a/crates/bevy_core_pipeline/src/skybox/mod.rs +++ b/crates/bevy_core_pipeline/src/skybox/mod.rs @@ -101,7 +101,7 @@ pub struct Skybox { impl Default for Skybox { fn default() -> Self { - Skybox { + Self { image: Handle::default(), brightness: 0.0, rotation: Quat::IDENTITY, diff --git a/crates/bevy_core_pipeline/src/smaa/mod.rs b/crates/bevy_core_pipeline/src/smaa/mod.rs index e6e00e54b06d0..59545a66cb25a 100644 --- a/crates/bevy_core_pipeline/src/smaa/mod.rs +++ b/crates/bevy_core_pipeline/src/smaa/mod.rs @@ -437,7 +437,7 @@ impl FromWorld for SmaaPipelines { ), ); - SmaaPipelines { + Self { edge_detection: SmaaEdgeDetectionPipeline { postprocess_bind_group_layout: postprocess_bind_group_layout.clone(), edge_detection_bind_group_layout, @@ -1079,10 +1079,10 @@ impl SmaaPreset { /// preset. fn shader_def(&self) -> ShaderDefVal { match *self { - SmaaPreset::Low => "SMAA_PRESET_LOW".into(), - SmaaPreset::Medium => "SMAA_PRESET_MEDIUM".into(), - SmaaPreset::High => "SMAA_PRESET_HIGH".into(), - SmaaPreset::Ultra => "SMAA_PRESET_ULTRA".into(), + Self::Low => "SMAA_PRESET_LOW".into(), + Self::Medium => "SMAA_PRESET_MEDIUM".into(), + Self::High => "SMAA_PRESET_HIGH".into(), + Self::Ultra => "SMAA_PRESET_ULTRA".into(), } } } diff --git a/crates/bevy_core_pipeline/src/taa/mod.rs b/crates/bevy_core_pipeline/src/taa/mod.rs index 4a78af178e503..42e5c6059f019 100644 --- a/crates/bevy_core_pipeline/src/taa/mod.rs +++ b/crates/bevy_core_pipeline/src/taa/mod.rs @@ -285,7 +285,7 @@ impl FromWorld for TaaPipeline { ), ); - TaaPipeline { + Self { taa_bind_group_layout, nearest_sampler, linear_sampler, diff --git a/crates/bevy_core_pipeline/src/tonemapping/mod.rs b/crates/bevy_core_pipeline/src/tonemapping/mod.rs index f734bfcf6ed47..389ad61df91c4 100644 --- a/crates/bevy_core_pipeline/src/tonemapping/mod.rs +++ b/crates/bevy_core_pipeline/src/tonemapping/mod.rs @@ -185,7 +185,7 @@ pub enum Tonemapping { impl Tonemapping { pub fn is_enabled(&self) -> bool { - *self != Tonemapping::None + *self != Self::None } } @@ -331,7 +331,7 @@ impl FromWorld for TonemappingPipeline { let sampler = render_device.create_sampler(&SamplerDescriptor::default()); - TonemappingPipeline { + Self { texture_bind_group: tonemap_texture_bind_group, sampler, } diff --git a/crates/bevy_dev_tools/src/fps_overlay.rs b/crates/bevy_dev_tools/src/fps_overlay.rs index 069882cb4e3c6..0ce7dfc7ff5ca 100644 --- a/crates/bevy_dev_tools/src/fps_overlay.rs +++ b/crates/bevy_dev_tools/src/fps_overlay.rs @@ -63,7 +63,7 @@ pub struct FpsOverlayConfig { impl Default for FpsOverlayConfig { fn default() -> Self { - FpsOverlayConfig { + Self { text_config: TextStyle { font: Handle::::default(), font_size: 32.0, diff --git a/crates/bevy_dev_tools/src/ui_debug_overlay/inset.rs b/crates/bevy_dev_tools/src/ui_debug_overlay/inset.rs index 86be2146c73d7..c9aa757dd9e47 100644 --- a/crates/bevy_dev_tools/src/ui_debug_overlay/inset.rs +++ b/crates/bevy_dev_tools/src/ui_debug_overlay/inset.rs @@ -27,17 +27,17 @@ enum Dir { impl Dir { const fn increments(self) -> i64 { match self { - Dir::Start => 1, - Dir::End => -1, + Self::Start => 1, + Self::End => -1, } } } impl From for Dir { fn from(value: i64) -> Self { if value.is_positive() { - Dir::Start + Self::Start } else { - Dir::End + Self::End } } } @@ -51,7 +51,7 @@ struct DrawnLines { #[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)] impl DrawnLines { fn new(width: f32) -> Self { - DrawnLines { + Self { lines: HashMap::new(), width, } diff --git a/crates/bevy_diagnostic/src/diagnostic.rs b/crates/bevy_diagnostic/src/diagnostic.rs index b45ee593cfab3..0780ee4a18104 100644 --- a/crates/bevy_diagnostic/src/diagnostic.rs +++ b/crates/bevy_diagnostic/src/diagnostic.rs @@ -24,15 +24,15 @@ impl DiagnosticPath { /// Create a new `DiagnosticPath`. Usable in const contexts. /// /// **Note**: path is not validated, so make sure it follows all the requirements. - pub const fn const_new(path: &'static str) -> DiagnosticPath { - DiagnosticPath { + pub const fn const_new(path: &'static str) -> Self { + Self { path: Cow::Borrowed(path), hash: fnv1a_hash_str_64(path), } } /// Create a new `DiagnosticPath` from the specified string. - pub fn new(path: impl Into>) -> DiagnosticPath { + pub fn new(path: impl Into>) -> Self { let path = path.into(); debug_assert!(!path.is_empty(), "diagnostic path can't be empty"); @@ -49,24 +49,22 @@ impl DiagnosticPath { "diagnostic path can't contain empty components" ); - DiagnosticPath { + Self { hash: fnv1a_hash_str_64(&path), path, } } /// Create a new `DiagnosticPath` from an iterator over components. - pub fn from_components<'a>(components: impl IntoIterator) -> DiagnosticPath { + pub fn from_components<'a>(components: impl IntoIterator) -> Self { let mut buf = String::new(); - for (i, component) in components.into_iter().enumerate() { if i > 0 { buf.push('/'); } buf.push_str(component); } - - DiagnosticPath::new(buf) + Self::new(buf) } /// Returns full path, joined by `/` @@ -165,8 +163,8 @@ impl Diagnostic { } /// Create a new diagnostic with the given path. - pub fn new(path: DiagnosticPath) -> Diagnostic { - Diagnostic { + pub fn new(path: DiagnosticPath) -> Self { + Self { path, suffix: Cow::Borrowed(""), history: VecDeque::with_capacity(DEFAULT_MAX_HISTORY_LENGTH), diff --git a/crates/bevy_diagnostic/src/log_diagnostics_plugin.rs b/crates/bevy_diagnostic/src/log_diagnostics_plugin.rs index 2f007edcaaf50..8f8686be6b701 100644 --- a/crates/bevy_diagnostic/src/log_diagnostics_plugin.rs +++ b/crates/bevy_diagnostic/src/log_diagnostics_plugin.rs @@ -27,7 +27,7 @@ struct LogDiagnosticsState { impl Default for LogDiagnosticsPlugin { fn default() -> Self { - LogDiagnosticsPlugin { + Self { debug: false, wait_duration: Duration::from_secs(1), filter: None, @@ -52,7 +52,7 @@ impl Plugin for LogDiagnosticsPlugin { impl LogDiagnosticsPlugin { pub fn filtered(filter: Vec) -> Self { - LogDiagnosticsPlugin { + Self { filter: Some(filter), ..Default::default() } diff --git a/crates/bevy_diagnostic/src/system_information_diagnostics_plugin.rs b/crates/bevy_diagnostic/src/system_information_diagnostics_plugin.rs index 9037c6a8f82e9..91852b33aab60 100644 --- a/crates/bevy_diagnostic/src/system_information_diagnostics_plugin.rs +++ b/crates/bevy_diagnostic/src/system_information_diagnostics_plugin.rs @@ -173,7 +173,7 @@ pub mod internal { .with_memory(MemoryRefreshKind::new().with_ram()), ); - let system_info = SystemInfo { + let system_info = Self { os: System::long_os_version().unwrap_or_else(|| String::from("not available")), kernel: System::kernel_version().unwrap_or_else(|| String::from("not available")), cpu: sys diff --git a/crates/bevy_ecs/src/archetype.rs b/crates/bevy_ecs/src/archetype.rs index baafd514db30c..de938ccc704e6 100644 --- a/crates/bevy_ecs/src/archetype.rs +++ b/crates/bevy_ecs/src/archetype.rs @@ -48,7 +48,7 @@ pub struct ArchetypeRow(u32); impl ArchetypeRow { /// Index indicating an invalid archetype row. /// This is meant to be used as a placeholder. - pub const INVALID: ArchetypeRow = ArchetypeRow(u32::MAX); + pub const INVALID: Self = Self(u32::MAX); /// Creates a `ArchetypeRow`. #[inline] @@ -79,11 +79,11 @@ pub struct ArchetypeId(u32); impl ArchetypeId { /// The ID for the [`Archetype`] without any components. - pub const EMPTY: ArchetypeId = ArchetypeId(0); + pub const EMPTY: Self = Self(0); /// # Safety: /// /// This must always have an all-1s bit pattern to ensure soundness in fast entity id space allocation. - pub const INVALID: ArchetypeId = ArchetypeId(u32::MAX); + pub const INVALID: Self = Self(u32::MAX); /// Create an `ArchetypeId` from a plain value. /// @@ -95,7 +95,7 @@ impl ArchetypeId { /// to avoid panics and other unexpected behaviors. #[inline] pub const fn new(index: usize) -> Self { - ArchetypeId(index as u32) + Self(index as u32) } /// The plain value of this `ArchetypeId`. @@ -677,7 +677,7 @@ impl ArchetypeGeneration { /// The first archetype. #[inline] pub const fn initial() -> Self { - ArchetypeGeneration(ArchetypeId::EMPTY) + Self(ArchetypeId::EMPTY) } } @@ -756,7 +756,7 @@ pub struct ArchetypeRecord { impl Archetypes { pub(crate) fn new() -> Self { - let mut archetypes = Archetypes { + let mut archetypes = Self { archetypes: Vec::new(), by_components: Default::default(), by_component: Default::default(), diff --git a/crates/bevy_ecs/src/bundle.rs b/crates/bevy_ecs/src/bundle.rs index 6d3f04949a6c7..6b8307e6be4fa 100644 --- a/crates/bevy_ecs/src/bundle.rs +++ b/crates/bevy_ecs/src/bundle.rs @@ -340,7 +340,7 @@ impl BundleInfo { components: &Components, component_ids: Vec, id: BundleId, - ) -> BundleInfo { + ) -> Self { let mut deduped = component_ids.clone(); deduped.sort_unstable(); deduped.dedup(); @@ -371,7 +371,7 @@ impl BundleInfo { // - is valid for the associated world // - has had its storage initialized // - is in the same order as the source bundle type - BundleInfo { id, component_ids } + Self { id, component_ids } } /// Returns a value identifying the associated [`Bundle`] type. diff --git a/crates/bevy_ecs/src/change_detection.rs b/crates/bevy_ecs/src/change_detection.rs index cb6f3a72d7cca..27181488f14ff 100644 --- a/crates/bevy_ecs/src/change_detection.rs +++ b/crates/bevy_ecs/src/change_detection.rs @@ -638,8 +638,8 @@ impl_debug!(ResMut<'w, T>, Resource); impl<'w, T: Resource> From> for Mut<'w, T> { /// Convert this `ResMut` into a `Mut`. This allows keeping the change-detection feature of `Mut` /// while losing the specificity of `ResMut` for resources. - fn from(other: ResMut<'w, T>) -> Mut<'w, T> { - Mut { + fn from(other: ResMut<'w, T>) -> Self { + Self { value: other.value, ticks: other.ticks, #[cfg(feature = "track_change_detection")] @@ -675,8 +675,8 @@ impl_debug!(NonSendMut<'w, T>,); impl<'w, T: 'static> From> for Mut<'w, T> { /// Convert this `NonSendMut` into a `Mut`. This allows keeping the change-detection feature of `Mut` /// while losing the specificity of `NonSendMut`. - fn from(other: NonSendMut<'w, T>) -> Mut<'w, T> { - Mut { + fn from(other: NonSendMut<'w, T>) -> Self { + Self { value: other.value, ticks: other.ticks, #[cfg(feature = "track_change_detection")] @@ -753,8 +753,8 @@ impl<'w, T: ?Sized> Ref<'w, T> { last_run: Tick, this_run: Tick, #[cfg(feature = "track_change_detection")] caller: &'static Location<'static>, - ) -> Ref<'w, T> { - Ref { + ) -> Self { + Self { value, ticks: Ticks { added, diff --git a/crates/bevy_ecs/src/component.rs b/crates/bevy_ecs/src/component.rs index 161db19b9a0e9..b46a6994d69c4 100644 --- a/crates/bevy_ecs/src/component.rs +++ b/crates/bevy_ecs/src/component.rs @@ -463,7 +463,7 @@ impl ComponentInfo { /// Create a new [`ComponentInfo`]. pub(crate) fn new(id: ComponentId, descriptor: ComponentDescriptor) -> Self { - ComponentInfo { + Self { id, descriptor, hooks: ComponentHooks::default(), @@ -528,8 +528,8 @@ impl ComponentId { /// The `index` is a unique value associated with each type of component in a given world. /// Usually, this value is taken from a counter incremented for each type of component registered with the world. #[inline] - pub const fn new(index: usize) -> ComponentId { - ComponentId(index) + pub const fn new(index: usize) -> Self { + Self(index) } /// Returns the index of the current component. @@ -694,17 +694,14 @@ impl Components { pub fn init_component(&mut self, storages: &mut Storages) -> ComponentId { let type_id = TypeId::of::(); - let Components { + let Self { indices, components, .. } = self; *indices.entry(type_id).or_insert_with(|| { - let index = Components::init_component_inner( - components, - storages, - ComponentDescriptor::new::(), - ); + let index = + Self::init_component_inner(components, storages, ComponentDescriptor::new::()); T::register_component_hooks(&mut components[index.index()].hooks); index }) @@ -726,7 +723,7 @@ impl Components { storages: &mut Storages, descriptor: ComponentDescriptor, ) -> ComponentId { - Components::init_component_inner(&mut self.components, storages, descriptor) + Self::init_component_inner(&mut self.components, storages, descriptor) } #[inline] @@ -961,7 +958,7 @@ impl Tick { /// /// `this_run` is the current tick of the system, used as a reference to help deal with wraparound. #[inline] - pub fn is_newer_than(self, last_run: Tick, this_run: Tick) -> bool { + pub fn is_newer_than(self, last_run: Self, this_run: Self) -> bool { // This works even with wraparound because the world tick (`this_run`) is always "newer" than // `last_run` and `self.tick`, and we scan periodically to clamp `ComponentTicks` values // so they never get older than `u32::MAX` (the difference would overflow). @@ -984,7 +981,7 @@ impl Tick { /// /// Returns `true` if wrapping was performed. Otherwise, returns `false`. #[inline] - pub(crate) fn check_tick(&mut self, tick: Tick) -> bool { + pub(crate) fn check_tick(&mut self, tick: Self) -> bool { let age = tick.relative_to(*self); // This comparison assumes that `age` has not overflowed `u32::MAX` before, which will be true // so long as this check always runs before that can happen. @@ -1114,7 +1111,7 @@ impl std::ops::Deref for ComponentIdFor<'_, T> { impl From> for ComponentId { #[inline] - fn from(to_component_id: ComponentIdFor) -> ComponentId { + fn from(to_component_id: ComponentIdFor) -> Self { *to_component_id } } diff --git a/crates/bevy_ecs/src/entity/mod.rs b/crates/bevy_ecs/src/entity/mod.rs index 4250058ed8cda..80373236b6368 100644 --- a/crates/bevy_ecs/src/entity/mod.rs +++ b/crates/bevy_ecs/src/entity/mod.rs @@ -166,7 +166,7 @@ pub struct Entity { // See impl PartialEq for Entity { #[inline] - fn eq(&self, other: &Entity) -> bool { + fn eq(&self, other: &Self) -> bool { // By using `to_bits`, the codegen can be optimised out even // further potentially. Relies on the correct alignment/field // order of `Entity`. @@ -223,9 +223,8 @@ impl Entity { /// Construct an [`Entity`] from a raw `index` value and a non-zero `generation` value. /// Ensure that the generation value is never greater than `0x7FFF_FFFF`. #[inline(always)] - pub(crate) const fn from_raw_and_generation(index: u32, generation: NonZeroU32) -> Entity { + pub(crate) const fn from_raw_and_generation(index: u32, generation: NonZeroU32) -> Self { debug_assert!(generation.get() <= HIGH_MASK); - Self { index, generation } } @@ -278,7 +277,7 @@ impl Entity { /// `Entity` lines up between instances, but instead insert a secondary identifier as /// a component. #[inline(always)] - pub const fn from_raw(index: u32) -> Entity { + pub const fn from_raw(index: u32) -> Self { Self::from_raw_and_generation(index, NonZeroU32::MIN) } @@ -364,7 +363,7 @@ impl TryFrom for Entity { impl From for Identifier { #[inline] fn from(value: Entity) -> Self { - Identifier::from_bits(value.to_bits()) + Self::from_bits(value.to_bits()) } } @@ -386,7 +385,7 @@ impl<'de> Deserialize<'de> for Entity { { use serde::de::Error; let id: u64 = serde::de::Deserialize::deserialize(deserializer)?; - Entity::try_from_bits(id).map_err(D::Error::custom) + Self::try_from_bits(id).map_err(D::Error::custom) } } @@ -440,7 +439,7 @@ impl SparseSetIndex for Entity { #[inline] fn get_sparse_set_index(value: usize) -> Self { - Entity::from_raw(value as u32) + Self::from_raw(value as u32) } } @@ -537,7 +536,7 @@ pub struct Entities { impl Entities { pub(crate) const fn new() -> Self { - Entities { + Self { meta: Vec::new(), pending: Vec::new(), free_cursor: AtomicIdCursor::new(0), @@ -956,7 +955,7 @@ struct EntityMeta { impl EntityMeta { /// meta for **pending entity** - const EMPTY: EntityMeta = EntityMeta { + const EMPTY: Self = Self { generation: NonZeroU32::MIN, location: EntityLocation::INVALID, }; @@ -993,7 +992,7 @@ pub struct EntityLocation { impl EntityLocation { /// location for **pending entity** and **invalid entity** - const INVALID: EntityLocation = EntityLocation { + const INVALID: Self = Self { archetype_id: ArchetypeId::INVALID, archetype_row: ArchetypeRow::INVALID, table_id: TableId::INVALID, diff --git a/crates/bevy_ecs/src/event/event_cursor.rs b/crates/bevy_ecs/src/event/event_cursor.rs index 4868197712a6e..d14bbdc47a5e1 100644 --- a/crates/bevy_ecs/src/event/event_cursor.rs +++ b/crates/bevy_ecs/src/event/event_cursor.rs @@ -69,7 +69,7 @@ pub struct EventCursor { impl Default for EventCursor { fn default() -> Self { - EventCursor { + Self { last_event_count: 0, _marker: Default::default(), } @@ -78,7 +78,7 @@ impl Default for EventCursor { impl Clone for EventCursor { fn clone(&self) -> Self { - EventCursor { + Self { last_event_count: self.last_event_count, _marker: PhantomData, } diff --git a/crates/bevy_ecs/src/intern.rs b/crates/bevy_ecs/src/intern.rs index 54ea4e32071bc..2272b85649be8 100644 --- a/crates/bevy_ecs/src/intern.rs +++ b/crates/bevy_ecs/src/intern.rs @@ -82,8 +82,8 @@ impl Debug for Interned { } } -impl From<&Interned> for Interned { - fn from(value: &Interned) -> Self { +impl From<&Self> for Interned { + fn from(value: &Self) -> Self { *value } } @@ -183,7 +183,7 @@ mod tests { impl Internable for A { fn leak(&self) -> &'static Self { - &A + &Self } fn ref_eq(&self, other: &Self) -> bool { @@ -212,8 +212,8 @@ mod tests { impl Internable for A { fn leak(&self) -> &'static Self { match self { - A::X => &A::X, - A::Y => &A::Y, + Self::X => &Self::X, + Self::Y => &Self::Y, } } diff --git a/crates/bevy_ecs/src/lib.rs b/crates/bevy_ecs/src/lib.rs index a08a62053e107..fcd562c429e2e 100644 --- a/crates/bevy_ecs/src/lib.rs +++ b/crates/bevy_ecs/src/lib.rs @@ -114,7 +114,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/observer/entity_observer.rs b/crates/bevy_ecs/src/observer/entity_observer.rs index ce30201785758..e4aac91123bf1 100644 --- a/crates/bevy_ecs/src/observer/entity_observer.rs +++ b/crates/bevy_ecs/src/observer/entity_observer.rs @@ -14,7 +14,7 @@ impl Component for ObservedBy { fn register_component_hooks(hooks: &mut ComponentHooks) { hooks.on_remove(|mut world, entity, _| { let observed_by = { - let mut component = world.get_mut::(entity).unwrap(); + let mut component = world.get_mut::(entity).unwrap(); std::mem::take(&mut component.0) }; for e in observed_by { diff --git a/crates/bevy_ecs/src/observer/mod.rs b/crates/bevy_ecs/src/observer/mod.rs index 600384d478438..7c8dd0e8baa3e 100644 --- a/crates/bevy_ecs/src/observer/mod.rs +++ b/crates/bevy_ecs/src/observer/mod.rs @@ -119,7 +119,7 @@ impl ObserverDescriptor { self } - pub(crate) fn merge(&mut self, descriptor: &ObserverDescriptor) { + pub(crate) fn merge(&mut self, descriptor: &Self) { self.events.extend(descriptor.events.iter().copied()); self.components .extend(descriptor.components.iter().copied()); diff --git a/crates/bevy_ecs/src/observer/runner.rs b/crates/bevy_ecs/src/observer/runner.rs index 1706ead914e0e..f439b55382aa9 100644 --- a/crates/bevy_ecs/src/observer/runner.rs +++ b/crates/bevy_ecs/src/observer/runner.rs @@ -71,7 +71,7 @@ impl Component for ObserverState { let descriptor = std::mem::take( &mut world .entity_mut(entity) - .get_mut::() + .get_mut::() .unwrap() .as_mut() .descriptor, diff --git a/crates/bevy_ecs/src/query/access.rs b/crates/bevy_ecs/src/query/access.rs index 5f2b405973c73..692f9f4626f57 100644 --- a/crates/bevy_ecs/src/query/access.rs +++ b/crates/bevy_ecs/src/query/access.rs @@ -350,7 +350,7 @@ impl Access { } /// Adds all access from `other`. - pub fn extend(&mut self, other: &Access) { + pub fn extend(&mut self, other: &Self) { self.reads_all_resources = self.reads_all_resources || other.reads_all_resources; self.writes_all_resources = self.writes_all_resources || other.writes_all_resources; self.reads_all_components = self.reads_all_components || other.reads_all_components; @@ -368,7 +368,7 @@ impl Access { /// /// [`Access`] instances are incompatible if one can write /// an element that the other can read or write. - pub fn is_components_compatible(&self, other: &Access) -> bool { + pub fn is_components_compatible(&self, other: &Self) -> bool { if self.writes_all_components { return !other.has_any_component_read(); } @@ -397,7 +397,7 @@ impl Access { /// /// [`Access`] instances are incompatible if one can write /// an element that the other can read or write. - pub fn is_resources_compatible(&self, other: &Access) -> bool { + pub fn is_resources_compatible(&self, other: &Self) -> bool { if self.writes_all_resources { return !other.has_any_resource_read(); } @@ -425,13 +425,13 @@ impl Access { /// /// [`Access`] instances are incompatible if one can write /// an element that the other can read or write. - pub fn is_compatible(&self, other: &Access) -> bool { + pub fn is_compatible(&self, other: &Self) -> bool { self.is_components_compatible(other) && self.is_resources_compatible(other) } /// Returns `true` if the set's component access is a subset of another, i.e. `other`'s component access /// contains at least all the values in `self`. - pub fn is_subset_components(&self, other: &Access) -> bool { + pub fn is_subset_components(&self, other: &Self) -> bool { if self.writes_all_components { return other.writes_all_components; } @@ -455,7 +455,7 @@ impl Access { /// Returns `true` if the set's resource access is a subset of another, i.e. `other`'s resource access /// contains at least all the values in `self`. - pub fn is_subset_resources(&self, other: &Access) -> bool { + pub fn is_subset_resources(&self, other: &Self) -> bool { if self.writes_all_resources { return other.writes_all_resources; } @@ -479,12 +479,12 @@ impl Access { /// Returns `true` if the set is a subset of another, i.e. `other` contains /// at least all the values in `self`. - pub fn is_subset(&self, other: &Access) -> bool { + pub fn is_subset(&self, other: &Self) -> bool { self.is_subset_components(other) && self.is_subset_resources(other) } /// Returns a vector of elements that the access and `other` cannot access at the same time. - pub fn get_conflicts(&self, other: &Access) -> AccessConflicts { + pub fn get_conflicts(&self, other: &Self) -> AccessConflicts { let mut conflicts = FixedBitSet::new(); if self.reads_all_components { if other.writes_all_components { @@ -633,7 +633,7 @@ impl Default for FilteredAccess { impl From> for FilteredAccessSet { fn from(filtered_access: FilteredAccess) -> Self { - let mut base = FilteredAccessSet::::default(); + let mut base = Self::default(); base.add(filtered_access); base } @@ -651,12 +651,8 @@ pub enum AccessConflicts { impl AccessConflicts { fn add(&mut self, other: &Self) { match (self, other) { - (s, AccessConflicts::All) => { - *s = AccessConflicts::All; - } - (AccessConflicts::Individual(this), AccessConflicts::Individual(other)) => { - this.extend(other.ones()); - } + (s, Self::All) => *s = Self::All, + (Self::Individual(this), Self::Individual(other)) => this.extend(other.ones()), _ => {} } } @@ -772,17 +768,17 @@ impl FilteredAccess { /// As the underlying array of filters represents a disjunction, /// where each element (`AccessFilters`) represents a conjunction, /// we can simply append to the array. - pub fn append_or(&mut self, other: &FilteredAccess) { + pub fn append_or(&mut self, other: &Self) { self.filter_sets.append(&mut other.filter_sets.clone()); } /// Adds all of the accesses from `other` to `self`. - pub fn extend_access(&mut self, other: &FilteredAccess) { + pub fn extend_access(&mut self, other: &Self) { self.access.extend(&other.access); } /// Returns `true` if this and `other` can be active at the same time. - pub fn is_compatible(&self, other: &FilteredAccess) -> bool { + pub fn is_compatible(&self, other: &Self) -> bool { if self.access.is_compatible(&other.access) { return true; } @@ -803,7 +799,7 @@ impl FilteredAccess { } /// Returns a vector of elements that this and `other` cannot access at the same time. - pub fn get_conflicts(&self, other: &FilteredAccess) -> AccessConflicts { + pub fn get_conflicts(&self, other: &Self) -> AccessConflicts { if !self.is_compatible(other) { // filters are disjoint, so we can just look at the unfiltered intersection return self.access.get_conflicts(&other.access); @@ -817,7 +813,7 @@ impl FilteredAccess { /// /// Extending `Or<(With
, Without)>` with `Or<(With, Without)>` will result in /// `Or<((With, With), (With, Without), (Without, With), (Without, Without))>`. - pub fn extend(&mut self, other: &FilteredAccess) { + pub fn extend(&mut self, other: &Self) { self.access.extend(&other.access); self.required.union_with(&other.required); @@ -865,7 +861,7 @@ impl FilteredAccess { /// Returns `true` if the set is a subset of another, i.e. `other` contains /// at least all the values in `self`. - pub fn is_subset(&self, other: &FilteredAccess) -> bool { + pub fn is_subset(&self, other: &Self) -> bool { self.required.is_subset(&other.required) && self.access().is_subset(other.access()) } @@ -984,7 +980,7 @@ impl FilteredAccessSet { /// mutually exclusive. The fine grained phase iterates over all filters in /// the `self` set and compares it to all the filters in the `other` set, /// making sure they are all mutually compatible. - pub fn is_compatible(&self, other: &FilteredAccessSet) -> bool { + pub fn is_compatible(&self, other: &Self) -> bool { if self.combined_access.is_compatible(other.combined_access()) { return true; } @@ -999,7 +995,7 @@ impl FilteredAccessSet { } /// Returns a vector of elements that this set and `other` cannot access at the same time. - pub fn get_conflicts(&self, other: &FilteredAccessSet) -> AccessConflicts { + pub fn get_conflicts(&self, other: &Self) -> AccessConflicts { // if the unfiltered access is incompatible, must check each pair let mut conflicts = AccessConflicts::empty(); if !self.combined_access.is_compatible(other.combined_access()) { @@ -1045,7 +1041,7 @@ impl FilteredAccessSet { } /// Adds all of the accesses from the passed set to `self`. - pub fn extend(&mut self, filtered_access_set: FilteredAccessSet) { + pub fn extend(&mut self, filtered_access_set: Self) { self.combined_access .extend(&filtered_access_set.combined_access); self.filtered_accesses diff --git a/crates/bevy_ecs/src/query/fetch.rs b/crates/bevy_ecs/src/query/fetch.rs index 8e522b61a2a7a..9068b9b74788c 100644 --- a/crates/bevy_ecs/src/query/fetch.rs +++ b/crates/bevy_ecs/src/query/fetch.rs @@ -293,7 +293,7 @@ pub type ROQueryItem<'w, D> = QueryItem<'w, ::ReadOnly>; /// `update_component_access` and `update_archetype_component_access` do nothing. /// This is sound because `fetch` does not access components. unsafe impl WorldQuery for Entity { - type Item<'w> = Entity; + type Item<'w> = Self; type Fetch<'w> = (); type State = (); @@ -363,7 +363,7 @@ unsafe impl ReadOnlyQueryData for Entity {} /// `update_component_access` and `update_archetype_component_access` do nothing. /// This is sound because `fetch` does not access components. unsafe impl WorldQuery for EntityLocation { - type Item<'w> = EntityLocation; + type Item<'w> = Self; type Fetch<'w> = &'w Entities; type State = (); diff --git a/crates/bevy_ecs/src/query/iter.rs b/crates/bevy_ecs/src/query/iter.rs index f8564025aa15c..e6eb2cdb42c39 100644 --- a/crates/bevy_ecs/src/query/iter.rs +++ b/crates/bevy_ecs/src/query/iter.rs @@ -75,11 +75,11 @@ impl<'w, 's, D: QueryData, F: QueryFilter> QueryIter<'w, 's, D, F> { /// } /// } /// ``` - pub fn remaining(&self) -> QueryIter<'w, 's, D, F> + pub fn remaining(&self) -> Self where D: ReadOnlyQueryData, { - QueryIter { + Self { world: self.world, tables: self.tables, archetypes: self.archetypes, @@ -1112,9 +1112,9 @@ where entity_list: EntityList, last_run: Tick, this_run: Tick, - ) -> QuerySortedIter<'w, 's, D, F, I> { + ) -> Self { let fetch = D::init_fetch(world, &query_state.fetch_state, last_run, this_run); - QuerySortedIter { + Self { query_state, entities: world.entities(), archetypes: world.archetypes(), @@ -1245,10 +1245,10 @@ impl<'w, 's, D: QueryData, F: QueryFilter, I: Iterator>> entity_list: EntityList, last_run: Tick, this_run: Tick, - ) -> QueryManyIter<'w, 's, D, F, I> { + ) -> Self { let fetch = D::init_fetch(world, &query_state.fetch_state, last_run, this_run); let filter = F::init_fetch(world, &query_state.filter_state, last_run, this_run); - QueryManyIter { + Self { query_state, entities: world.entities(), archetypes: world.archetypes(), @@ -2051,7 +2051,7 @@ mod tests { let mut query = world.query::<&Sparse>(); let mut iter = query.iter(&world); println!( - "before_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", + "before_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", iter.cursor.archetype_entities.len(), iter.cursor.table_entities.len(), iter.cursor.current_len, @@ -2059,7 +2059,7 @@ mod tests { ); _ = iter.next(); println!( - "after_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", + "after_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", iter.cursor.archetype_entities.len(), iter.cursor.table_entities.len(), iter.cursor.current_len, @@ -2076,7 +2076,7 @@ mod tests { let mut query = world.query::<(&A, &Sparse)>(); let mut iter = query.iter(&world); println!( - "before_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", + "before_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", iter.cursor.archetype_entities.len(), iter.cursor.table_entities.len(), iter.cursor.current_len, @@ -2084,7 +2084,7 @@ mod tests { ); _ = iter.next(); println!( - "after_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", + "after_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", iter.cursor.archetype_entities.len(), iter.cursor.table_entities.len(), iter.cursor.current_len, @@ -2104,7 +2104,7 @@ mod tests { let mut query = world.query::<(&A, &Sparse)>(); let mut iter = query.iter(&world); println!( - "before_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", + "before_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", iter.cursor.archetype_entities.len(), iter.cursor.table_entities.len(), iter.cursor.current_len, @@ -2113,7 +2113,7 @@ mod tests { assert!(iter.cursor.table_entities.len() | iter.cursor.archetype_entities.len() == 0); _ = iter.next(); println!( - "after_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", + "after_next_call: archetype_entities: {} table_entities: {} current_len: {} current_row: {}", iter.cursor.archetype_entities.len(), iter.cursor.table_entities.len(), iter.cursor.current_len, diff --git a/crates/bevy_ecs/src/query/state.rs b/crates/bevy_ecs/src/query/state.rs index 2d2a85e014b3a..c21ba57b7a4f3 100644 --- a/crates/bevy_ecs/src/query/state.rs +++ b/crates/bevy_ecs/src/query/state.rs @@ -1706,7 +1706,7 @@ impl QueryState { impl From> for QueryState { fn from(mut value: QueryBuilder) -> Self { - QueryState::from_builder(&mut value) + Self::from_builder(&mut value) } } diff --git a/crates/bevy_ecs/src/reflect/bundle.rs b/crates/bevy_ecs/src/reflect/bundle.rs index b594506c7a824..d30b3b37969ca 100644 --- a/crates/bevy_ecs/src/reflect/bundle.rs +++ b/crates/bevy_ecs/src/reflect/bundle.rs @@ -126,7 +126,7 @@ impl ReflectBundle { impl FromType for ReflectBundle { fn from_type() -> Self { - ReflectBundle(ReflectBundleFns { + Self(ReflectBundleFns { insert: |entity, reflected_bundle, registry| { let bundle = entity.world_scope(|world| { from_reflect_with_fallback::(reflected_bundle, world, registry) diff --git a/crates/bevy_ecs/src/reflect/component.rs b/crates/bevy_ecs/src/reflect/component.rs index b3422208d1f4b..4ba57ced133db 100644 --- a/crates/bevy_ecs/src/reflect/component.rs +++ b/crates/bevy_ecs/src/reflect/component.rs @@ -258,7 +258,7 @@ impl ReflectComponent { impl FromType for ReflectComponent { fn from_type() -> Self { - ReflectComponent(ReflectComponentFns { + Self(ReflectComponentFns { insert: |entity, reflected_component, registry| { let component = entity.world_scope(|world| { from_reflect_with_fallback::(reflected_component, world, registry) diff --git a/crates/bevy_ecs/src/reflect/from_world.rs b/crates/bevy_ecs/src/reflect/from_world.rs index fb9ffc8939ccd..92ce4bbbf31ea 100644 --- a/crates/bevy_ecs/src/reflect/from_world.rs +++ b/crates/bevy_ecs/src/reflect/from_world.rs @@ -79,7 +79,7 @@ impl ReflectFromWorld { impl FromType for ReflectFromWorld { fn from_type() -> Self { - ReflectFromWorld(ReflectFromWorldFns { + Self(ReflectFromWorldFns { from_world: |world| Box::new(B::from_world(world)), }) } diff --git a/crates/bevy_ecs/src/reflect/map_entities.rs b/crates/bevy_ecs/src/reflect/map_entities.rs index 4bc70acc3e55e..e86a669b8cc50 100644 --- a/crates/bevy_ecs/src/reflect/map_entities.rs +++ b/crates/bevy_ecs/src/reflect/map_entities.rs @@ -50,7 +50,7 @@ impl ReflectMapEntities { impl FromType for ReflectMapEntities { fn from_type() -> Self { - ReflectMapEntities { + Self { map_entities: |world, entity_mapper, entities| { for &entity in entities { if let Some(mut component) = world.get_mut::(entity) { @@ -95,7 +95,7 @@ impl ReflectMapEntitiesResource { impl FromType for ReflectMapEntitiesResource { fn from_type() -> Self { - ReflectMapEntitiesResource { + Self { map_entities: |world, entity_mapper| { if let Some(mut resource) = world.get_resource_mut::() { resource.map_entities(entity_mapper); diff --git a/crates/bevy_ecs/src/reflect/resource.rs b/crates/bevy_ecs/src/reflect/resource.rs index e55ffb964a97c..b050652048e51 100644 --- a/crates/bevy_ecs/src/reflect/resource.rs +++ b/crates/bevy_ecs/src/reflect/resource.rs @@ -183,7 +183,7 @@ impl ReflectResource { impl FromType for ReflectResource { fn from_type() -> Self { - ReflectResource(ReflectResourceFns { + Self(ReflectResourceFns { insert: |world, reflected_resource, registry| { let resource = from_reflect_with_fallback::(reflected_resource, world, registry); world.insert_resource(resource); diff --git a/crates/bevy_ecs/src/schedule/executor/multi_threaded.rs b/crates/bevy_ecs/src/schedule/executor/multi_threaded.rs index 39606d998e3a2..9726572572914 100644 --- a/crates/bevy_ecs/src/schedule/executor/multi_threaded.rs +++ b/crates/bevy_ecs/src/schedule/executor/multi_threaded.rs @@ -748,7 +748,7 @@ impl Default for MainThreadExecutor { impl MainThreadExecutor { /// Creates a new executor that can be used to run systems on the main thread. pub fn new() -> Self { - MainThreadExecutor(TaskPool::get_thread_executor()) + Self(TaskPool::get_thread_executor()) } } diff --git a/crates/bevy_ecs/src/schedule/graph_utils.rs b/crates/bevy_ecs/src/schedule/graph_utils.rs index 2fcbb6df90f2b..f3ca3fbaeba46 100644 --- a/crates/bevy_ecs/src/schedule/graph_utils.rs +++ b/crates/bevy_ecs/src/schedule/graph_utils.rs @@ -21,18 +21,18 @@ impl NodeId { /// Returns the internal integer value. pub(crate) fn index(&self) -> usize { match self { - NodeId::System(index) | NodeId::Set(index) => *index, + Self::System(index) | Self::Set(index) => *index, } } /// Returns `true` if the identified node is a system. pub const fn is_system(&self) -> bool { - matches!(self, NodeId::System(_)) + matches!(self, Self::System(_)) } /// Returns `true` if the identified node is a system set. pub const fn is_set(&self) -> bool { - matches!(self, NodeId::Set(_)) + matches!(self, Self::Set(_)) } } diff --git a/crates/bevy_ecs/src/schedule/stepping.rs b/crates/bevy_ecs/src/schedule/stepping.rs index 822e69f16d882..fb65f7c1eb60a 100644 --- a/crates/bevy_ecs/src/schedule/stepping.rs +++ b/crates/bevy_ecs/src/schedule/stepping.rs @@ -136,7 +136,7 @@ impl std::fmt::Debug for Stepping { impl Stepping { /// Create a new instance of the `Stepping` resource. pub fn new() -> Self { - Stepping::default() + Self::default() } /// System to call denoting that a new render frame has begun diff --git a/crates/bevy_ecs/src/storage/blob_vec.rs b/crates/bevy_ecs/src/storage/blob_vec.rs index c64ccd5a0aca6..29c74554e7f2a 100644 --- a/crates/bevy_ecs/src/storage/blob_vec.rs +++ b/crates/bevy_ecs/src/storage/blob_vec.rs @@ -55,11 +55,11 @@ impl BlobVec { item_layout: Layout, drop: Option)>, capacity: usize, - ) -> BlobVec { + ) -> Self { let align = NonZeroUsize::new(item_layout.align()).expect("alignment must be > 0"); let data = bevy_ptr::dangling_with_align(align); if item_layout.size() == 0 { - BlobVec { + Self { data, // ZST `BlobVec` max size is `usize::MAX`, and `reserve_exact` for ZST assumes // the capacity is always `usize::MAX` and panics if it overflows. @@ -69,7 +69,7 @@ impl BlobVec { drop, } } else { - let mut blob_vec = BlobVec { + let mut blob_vec = Self { data, capacity: 0, len: 0, diff --git a/crates/bevy_ecs/src/storage/table.rs b/crates/bevy_ecs/src/storage/table.rs index d525cebe210bd..46a46e118e90b 100644 --- a/crates/bevy_ecs/src/storage/table.rs +++ b/crates/bevy_ecs/src/storage/table.rs @@ -34,7 +34,7 @@ use std::{ pub struct TableId(u32); impl TableId { - pub(crate) const INVALID: TableId = TableId(u32::MAX); + pub(crate) const INVALID: Self = Self(u32::MAX); /// Creates a new [`TableId`]. /// @@ -104,7 +104,7 @@ impl TableId { pub struct TableRow(u32); impl TableRow { - pub(crate) const INVALID: TableRow = TableRow(u32::MAX); + pub(crate) const INVALID: Self = Self(u32::MAX); /// Creates a `TableRow`. #[inline] @@ -163,7 +163,7 @@ impl Column { /// Constructs a new [`Column`], configured with a component's layout and an initial `capacity`. #[inline] pub(crate) fn with_capacity(component_info: &ComponentInfo, capacity: usize) -> Self { - Column { + Self { // SAFETY: component_info.drop() is valid for the types that will be inserted. data: unsafe { BlobVec::new(component_info.layout(), component_info.drop(), capacity) }, added_ticks: Vec::with_capacity(capacity), @@ -318,7 +318,7 @@ impl Column { #[inline] pub(crate) unsafe fn initialize_from_unchecked( &mut self, - other: &mut Column, + other: &mut Self, src_row: TableRow, dst_row: TableRow, ) { @@ -709,7 +709,7 @@ impl Table { pub(crate) unsafe fn move_to_and_forget_missing_unchecked( &mut self, row: TableRow, - new_table: &mut Table, + new_table: &mut Self, ) -> TableMoveResult { debug_assert!(row.as_usize() < self.entity_count()); let is_last = row.as_usize() == self.entities.len() - 1; @@ -741,7 +741,7 @@ impl Table { pub(crate) unsafe fn move_to_and_drop_missing_unchecked( &mut self, row: TableRow, - new_table: &mut Table, + new_table: &mut Self, ) -> TableMoveResult { debug_assert!(row.as_usize() < self.entity_count()); let is_last = row.as_usize() == self.entities.len() - 1; @@ -772,7 +772,7 @@ impl Table { pub(crate) unsafe fn move_to_superset_unchecked( &mut self, row: TableRow, - new_table: &mut Table, + new_table: &mut Self, ) -> TableMoveResult { debug_assert!(row.as_usize() < self.entity_count()); let is_last = row.as_usize() == self.entities.len() - 1; @@ -915,7 +915,7 @@ pub struct Tables { impl Default for Tables { fn default() -> Self { let empty_table = TableBuilder::with_capacity(0, 0).build(); - Tables { + Self { tables: vec![empty_table], table_ids: HashMap::default(), } diff --git a/crates/bevy_ecs/src/system/builder.rs b/crates/bevy_ecs/src/system/builder.rs index 520d73f4e9cdc..5625129e98988 100644 --- a/crates/bevy_ecs/src/system/builder.rs +++ b/crates/bevy_ecs/src/system/builder.rs @@ -145,7 +145,7 @@ impl ParamBuilder { unsafe impl<'w, 's, D: QueryData + 'static, F: QueryFilter + 'static> SystemParamBuilder> for QueryState { - fn build(self, world: &mut World, system_meta: &mut SystemMeta) -> QueryState { + fn build(self, world: &mut World, system_meta: &mut SystemMeta) -> Self { self.validate_world(world.id()); init_query_param(world, system_meta, &self); self diff --git a/crates/bevy_ecs/src/system/combinator.rs b/crates/bevy_ecs/src/system/combinator.rs index cec961ea0abdc..f89f37b6a4dc2 100644 --- a/crates/bevy_ecs/src/system/combinator.rs +++ b/crates/bevy_ecs/src/system/combinator.rs @@ -258,7 +258,7 @@ where { /// Clone the combined system. The cloned instance must be `.initialize()`d before it can run. fn clone(&self) -> Self { - CombinatorSystem::new(self.a.clone(), self.b.clone(), self.name.clone()) + Self::new(self.a.clone(), self.b.clone(), self.name.clone()) } } diff --git a/crates/bevy_ecs/src/system/commands/mod.rs b/crates/bevy_ecs/src/system/commands/mod.rs index 292a28ebe12cb..424c79e3d1a0f 100644 --- a/crates/bevy_ecs/src/system/commands/mod.rs +++ b/crates/bevy_ecs/src/system/commands/mod.rs @@ -1523,7 +1523,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/exclusive_system_param.rs b/crates/bevy_ecs/src/system/exclusive_system_param.rs index 255da95fec682..e6e3b624b6d01 100644 --- a/crates/bevy_ecs/src/system/exclusive_system_param.rs +++ b/crates/bevy_ecs/src/system/exclusive_system_param.rs @@ -77,12 +77,12 @@ impl<'_s, T: FromWorld + Send + 'static> ExclusiveSystemParam for Local<'_s, T> impl ExclusiveSystemParam for PhantomData { type State = (); - type Item<'s> = PhantomData; + type Item<'s> = Self; fn init(_world: &mut World, _system_meta: &mut SystemMeta) -> Self::State {} fn get_param<'s>(_state: &'s mut Self::State, _system_meta: &SystemMeta) -> Self::Item<'s> { - PhantomData + Self } } diff --git a/crates/bevy_ecs/src/system/mod.rs b/crates/bevy_ecs/src/system/mod.rs index bfb2dcd396cce..770cf44bc6245 100644 --- a/crates/bevy_ecs/src/system/mod.rs +++ b/crates/bevy_ecs/src/system/mod.rs @@ -900,7 +900,7 @@ mod tests { impl FromWorld for Foo { fn from_world(world: &mut World) -> Self { - Foo { + Self { value: world.resource::().value + 1, } } diff --git a/crates/bevy_ecs/src/system/query.rs b/crates/bevy_ecs/src/system/query.rs index ffe595b2cfd01..05ea9f028cc97 100644 --- a/crates/bevy_ecs/src/system/query.rs +++ b/crates/bevy_ecs/src/system/query.rs @@ -1380,7 +1380,7 @@ impl<'w, 's, D: QueryData, F: QueryFilter> Query<'w, 's, D, F> { /// * `&mut T` -> `&T` /// * `&mut T` -> `Ref` /// * [`EntityMut`](crate::world::EntityMut) -> [`EntityRef`](crate::world::EntityRef) - /// + /// /// [`EntityLocation`]: crate::entity::EntityLocation /// [`&Archetype`]: crate::archetype::Archetype #[track_caller] @@ -1626,7 +1626,7 @@ impl<'w, Q: QueryData, F: QueryFilter> QueryLens<'w, Q, F> { impl<'w, 's, Q: QueryData, F: QueryFilter> From<&'s mut QueryLens<'w, Q, F>> for Query<'w, 's, Q, F> { - fn from(value: &'s mut QueryLens<'w, Q, F>) -> Query<'w, 's, Q, F> { + fn from(value: &'s mut QueryLens<'w, Q, F>) -> Self { value.query() } } @@ -1634,7 +1634,7 @@ impl<'w, 's, Q: QueryData, F: QueryFilter> From<&'s mut QueryLens<'w, Q, F>> impl<'w, 'q, Q: QueryData, F: QueryFilter> From<&'q mut Query<'w, '_, Q, F>> for QueryLens<'q, Q, F> { - fn from(value: &'q mut Query<'w, '_, Q, F>) -> QueryLens<'q, Q, F> { + fn from(value: &'q mut Query<'w, '_, Q, F>) -> Self { value.transmute_lens_filtered() } } diff --git a/crates/bevy_ecs/src/system/system_param.rs b/crates/bevy_ecs/src/system/system_param.rs index 3bf032590aa8d..fc450bbf5800c 100644 --- a/crates/bevy_ecs/src/system/system_param.rs +++ b/crates/bevy_ecs/src/system/system_param.rs @@ -534,6 +534,7 @@ unsafe impl<'a, T: Resource> ReadOnlySystemParam for Option> {} // SAFETY: this impl defers to `Res`, which initializes and validates the correct world access. unsafe impl<'a, T: Resource> SystemParam for Option> { type State = ComponentId; + #[allow(clippy::use_self)] // False positive: https://github.com/rust-lang/rust-clippy/issues/13277 type Item<'w, 's> = Option>; fn init_state(world: &mut World, system_meta: &mut SystemMeta) -> Self::State { @@ -627,6 +628,7 @@ unsafe impl<'a, T: Resource> SystemParam for ResMut<'a, T> { // SAFETY: this impl defers to `ResMut`, which initializes and validates the correct world access. unsafe impl<'a, T: Resource> SystemParam for Option> { type State = ComponentId; + #[allow(clippy::use_self)] // False positive: https://github.com/rust-lang/rust-clippy/issues/13277 type Item<'w, 's> = Option>; fn init_state(world: &mut World, system_meta: &mut SystemMeta) -> Self::State { @@ -1161,6 +1163,7 @@ unsafe impl ReadOnlySystemParam for Option> {} // SAFETY: this impl defers to `NonSend`, which initializes and validates the correct world access. unsafe impl SystemParam for Option> { type State = ComponentId; + #[allow(clippy::use_self)] // False positive: https://github.com/rust-lang/rust-clippy/issues/13277 type Item<'w, 's> = Option>; fn init_state(world: &mut World, system_meta: &mut SystemMeta) -> Self::State { @@ -1249,6 +1252,7 @@ unsafe impl<'a, T: 'static> SystemParam for NonSendMut<'a, T> { // SAFETY: this impl defers to `NonSendMut`, which initializes and validates the correct world access. unsafe impl<'a, T: 'static> SystemParam for Option> { type State = ComponentId; + #[allow(clippy::use_self)] // False positive: https://github.com/rust-lang/rust-clippy/issues/13277 type Item<'w, 's> = Option>; fn init_state(world: &mut World, system_meta: &mut SystemMeta) -> Self::State { @@ -1392,7 +1396,7 @@ unsafe impl ReadOnlySystemParam for SystemChangeTick {} // SAFETY: `SystemChangeTick` doesn't require any world access unsafe impl SystemParam for SystemChangeTick { type State = (); - type Item<'w, 's> = SystemChangeTick; + type Item<'w, 's> = Self; fn init_state(_world: &mut World, _system_meta: &mut SystemMeta) -> Self::State {} @@ -1402,7 +1406,7 @@ unsafe impl SystemParam for SystemChangeTick { _world: UnsafeWorldCell<'w>, change_tick: Tick, ) -> Self::Item<'w, 's> { - SystemChangeTick { + Self { last_run: system_meta.last_run, this_run: change_tick, } @@ -1627,7 +1631,7 @@ unsafe impl SystemParam for PhantomData { _world: UnsafeWorldCell<'world>, _change_tick: Tick, ) -> Self::Item<'world, 'state> { - PhantomData + Self } } diff --git a/crates/bevy_ecs/src/world/command_queue.rs b/crates/bevy_ecs/src/world/command_queue.rs index a682443a4670a..59811d843a729 100644 --- a/crates/bevy_ecs/src/world/command_queue.rs +++ b/crates/bevy_ecs/src/world/command_queue.rs @@ -102,7 +102,7 @@ impl CommandQueue { } /// Take all commands from `other` and append them to `self`, leaving `other` empty - pub fn append(&mut self, other: &mut CommandQueue) { + pub fn append(&mut self, other: &mut Self) { self.bytes.append(&mut other.bytes); } diff --git a/crates/bevy_ecs/src/world/deferred_world.rs b/crates/bevy_ecs/src/world/deferred_world.rs index 90205b2ed4360..30b80c746d961 100644 --- a/crates/bevy_ecs/src/world/deferred_world.rs +++ b/crates/bevy_ecs/src/world/deferred_world.rs @@ -47,8 +47,8 @@ impl<'w> UnsafeWorldCell<'w> { } impl<'w> From<&'w mut World> for DeferredWorld<'w> { - fn from(world: &'w mut World) -> DeferredWorld<'w> { - DeferredWorld { + fn from(world: &'w mut World) -> Self { + Self { world: world.as_unsafe_world_cell(), } } @@ -57,8 +57,8 @@ impl<'w> From<&'w mut World> for DeferredWorld<'w> { impl<'w> DeferredWorld<'w> { /// Reborrow self as a new instance of [`DeferredWorld`] #[inline] - pub fn reborrow(&mut self) -> DeferredWorld { - DeferredWorld { world: self.world } + pub fn reborrow(&mut self) -> Self { + Self { world: self.world } } /// Creates a [`Commands`] instance that pushes to the world's command queue diff --git a/crates/bevy_ecs/src/world/entity_ref.rs b/crates/bevy_ecs/src/world/entity_ref.rs index 0aa28241557e7..8dbe4435b66ee 100644 --- a/crates/bevy_ecs/src/world/entity_ref.rs +++ b/crates/bevy_ecs/src/world/entity_ref.rs @@ -159,10 +159,10 @@ impl<'w> EntityRef<'w> { } impl<'w> From> for EntityRef<'w> { - fn from(entity_mut: EntityWorldMut<'w>) -> EntityRef<'w> { + fn from(entity_mut: EntityWorldMut<'w>) -> Self { // SAFETY: // - `EntityWorldMut` guarantees exclusive access to the entire world. - unsafe { EntityRef::new(entity_mut.into_unsafe_entity_cell()) } + unsafe { Self::new(entity_mut.into_unsafe_entity_cell()) } } } @@ -171,7 +171,7 @@ impl<'a> From<&'a EntityWorldMut<'_>> for EntityRef<'a> { // SAFETY: // - `EntityWorldMut` guarantees exclusive access to the entire world. // - `&value` ensures no mutable accesses are active. - unsafe { EntityRef::new(value.as_unsafe_entity_cell_readonly()) } + unsafe { Self::new(value.as_unsafe_entity_cell_readonly()) } } } @@ -179,7 +179,7 @@ impl<'w> From> for EntityRef<'w> { fn from(value: EntityMut<'w>) -> Self { // SAFETY: // - `EntityMut` guarantees exclusive access to all of the entity's components. - unsafe { EntityRef::new(value.0) } + unsafe { Self::new(value.0) } } } @@ -188,7 +188,7 @@ impl<'a> From<&'a EntityMut<'_>> for EntityRef<'a> { // SAFETY: // - `EntityMut` guarantees exclusive access to all of the entity's components. // - `&value` ensures there are no mutable accesses. - unsafe { EntityRef::new(value.0) } + unsafe { Self::new(value.0) } } } @@ -200,7 +200,7 @@ impl<'a> TryFrom> for EntityRef<'a> { Err(TryFromFilteredError::MissingReadAllAccess) } else { // SAFETY: check above guarantees read-only access to all components of the entity. - Ok(unsafe { EntityRef::new(value.entity) }) + Ok(unsafe { Self::new(value.entity) }) } } } @@ -213,7 +213,7 @@ impl<'a> TryFrom<&'a FilteredEntityRef<'_>> for EntityRef<'a> { Err(TryFromFilteredError::MissingReadAllAccess) } else { // SAFETY: check above guarantees read-only access to all components of the entity. - Ok(unsafe { EntityRef::new(value.entity) }) + Ok(unsafe { Self::new(value.entity) }) } } } @@ -226,7 +226,7 @@ impl<'a> TryFrom> for EntityRef<'a> { Err(TryFromFilteredError::MissingReadAllAccess) } else { // SAFETY: check above guarantees read-only access to all components of the entity. - Ok(unsafe { EntityRef::new(value.entity) }) + Ok(unsafe { Self::new(value.entity) }) } } } @@ -239,7 +239,7 @@ impl<'a> TryFrom<&'a FilteredEntityMut<'_>> for EntityRef<'a> { Err(TryFromFilteredError::MissingReadAllAccess) } else { // SAFETY: check above guarantees read-only access to all components of the entity. - Ok(unsafe { EntityRef::new(value.entity) }) + Ok(unsafe { Self::new(value.entity) }) } } } diff --git a/crates/bevy_ecs/src/world/identifier.rs b/crates/bevy_ecs/src/world/identifier.rs index b075205818d69..bca37d6192906 100644 --- a/crates/bevy_ecs/src/world/identifier.rs +++ b/crates/bevy_ecs/src/world/identifier.rs @@ -51,8 +51,7 @@ unsafe impl ReadOnlySystemParam for WorldId {} // SAFETY: No world data is accessed. unsafe impl SystemParam for WorldId { type State = (); - - type Item<'world, 'state> = WorldId; + type Item<'world, 'state> = Self; fn init_state(_: &mut World, _: &mut crate::system::SystemMeta) -> Self::State {} @@ -67,8 +66,8 @@ unsafe impl SystemParam for WorldId { } impl ExclusiveSystemParam for WorldId { - type State = WorldId; - type Item<'s> = WorldId; + type State = Self; + type Item<'s> = Self; fn init(world: &mut World, _system_meta: &mut SystemMeta) -> Self::State { world.id() diff --git a/crates/bevy_ecs/src/world/mod.rs b/crates/bevy_ecs/src/world/mod.rs index faf832b7d33fa..0e18c4ab7ca75 100644 --- a/crates/bevy_ecs/src/world/mod.rs +++ b/crates/bevy_ecs/src/world/mod.rs @@ -183,8 +183,8 @@ 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 @@ -1976,7 +1976,7 @@ impl World { /// assert_eq!(world.get_resource::().unwrap().0, 2); /// ``` #[track_caller] - 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 last_change_tick = self.last_change_tick(); let change_tick = self.change_tick(); @@ -2339,7 +2339,7 @@ impl World { pub fn last_change_tick_scope( &mut self, last_change_tick: Tick, - f: impl FnOnce(&mut World) -> T, + f: impl FnOnce(&mut Self) -> T, ) -> T { struct LastTickGuard<'a> { world: &'a mut World, @@ -2817,7 +2817,7 @@ impl World { pub fn try_schedule_scope( &mut self, label: impl ScheduleLabel, - f: impl FnOnce(&mut World, &mut Schedule) -> R, + f: impl FnOnce(&mut Self, &mut Schedule) -> R, ) -> Result { let label = label.intern(); let Some(mut schedule) = self @@ -2877,7 +2877,7 @@ impl World { pub fn schedule_scope( &mut self, label: impl ScheduleLabel, - f: impl FnOnce(&mut World, &mut Schedule) -> R, + f: impl FnOnce(&mut Self, &mut Schedule) -> R, ) -> R { self.try_schedule_scope(label, f) .unwrap_or_else(|e| panic!("{e}")) diff --git a/crates/bevy_gizmos/src/config.rs b/crates/bevy_gizmos/src/config.rs index 7f2dba96dff16..7753a9c4ccb58 100644 --- a/crates/bevy_gizmos/src/config.rs +++ b/crates/bevy_gizmos/src/config.rs @@ -197,7 +197,7 @@ pub(crate) struct GizmoMeshConfig { #[cfg(feature = "bevy_render")] impl From<&GizmoConfig> for GizmoMeshConfig { fn from(item: &GizmoConfig) -> Self { - GizmoMeshConfig { + Self { line_perspective: item.line_perspective, line_style: item.line_style, render_layers: item.render_layers.clone(), diff --git a/crates/bevy_gizmos/src/lib.rs b/crates/bevy_gizmos/src/lib.rs index 9d5f533d713cd..34eacf4788824 100644 --- a/crates/bevy_gizmos/src/lib.rs +++ b/crates/bevy_gizmos/src/lib.rs @@ -501,7 +501,7 @@ impl RenderAsset for GpuLineGizmo { contents: color_buffer_data, }); - Ok(GpuLineGizmo { + Ok(Self { position_buffer, color_buffer, vertex_count: gizmo.positions.len() as u32, diff --git a/crates/bevy_gizmos/src/pipeline_2d.rs b/crates/bevy_gizmos/src/pipeline_2d.rs index 0f6552f787406..2bd69b5f17b89 100644 --- a/crates/bevy_gizmos/src/pipeline_2d.rs +++ b/crates/bevy_gizmos/src/pipeline_2d.rs @@ -78,7 +78,7 @@ struct LineGizmoPipeline { impl FromWorld for LineGizmoPipeline { fn from_world(render_world: &mut World) -> Self { - LineGizmoPipeline { + Self { mesh_pipeline: render_world.resource::().clone(), uniform_layout: render_world .resource::() @@ -174,7 +174,7 @@ struct LineJointGizmoPipeline { impl FromWorld for LineJointGizmoPipeline { fn from_world(render_world: &mut World) -> Self { - LineJointGizmoPipeline { + Self { mesh_pipeline: render_world.resource::().clone(), uniform_layout: render_world .resource::() diff --git a/crates/bevy_gizmos/src/pipeline_3d.rs b/crates/bevy_gizmos/src/pipeline_3d.rs index 8197623b3618c..7229356546073 100644 --- a/crates/bevy_gizmos/src/pipeline_3d.rs +++ b/crates/bevy_gizmos/src/pipeline_3d.rs @@ -77,7 +77,7 @@ struct LineGizmoPipeline { impl FromWorld for LineGizmoPipeline { fn from_world(render_world: &mut World) -> Self { - LineGizmoPipeline { + Self { mesh_pipeline: render_world.resource::().clone(), uniform_layout: render_world .resource::() @@ -171,7 +171,7 @@ struct LineJointGizmoPipeline { impl FromWorld for LineJointGizmoPipeline { fn from_world(render_world: &mut World) -> Self { - LineJointGizmoPipeline { + Self { mesh_pipeline: render_world.resource::().clone(), uniform_layout: render_world .resource::() diff --git a/crates/bevy_gltf/src/lib.rs b/crates/bevy_gltf/src/lib.rs index 722dde2150d59..88bb57b3f204c 100644 --- a/crates/bevy_gltf/src/lib.rs +++ b/crates/bevy_gltf/src/lib.rs @@ -234,7 +234,7 @@ impl GltfNode { /// Create a node extracting name and index from glTF def pub fn new( node: &gltf::Node, - children: Vec>, + children: Vec>, mesh: Option>, transform: bevy_transform::prelude::Transform, skin: Option>, @@ -389,7 +389,7 @@ impl GltfPrimitive { extras: Option, material_extras: Option, ) -> Self { - GltfPrimitive { + Self { index: gltf_primitive.index(), parent_mesh_index: gltf_mesh.index(), name: { @@ -527,17 +527,17 @@ pub enum GltfAssetLabel { impl std::fmt::Display for GltfAssetLabel { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - GltfAssetLabel::Scene(index) => f.write_str(&format!("Scene{index}")), - GltfAssetLabel::Node(index) => f.write_str(&format!("Node{index}")), - GltfAssetLabel::Mesh(index) => f.write_str(&format!("Mesh{index}")), - GltfAssetLabel::Primitive { mesh, primitive } => { + Self::Scene(index) => f.write_str(&format!("Scene{index}")), + Self::Node(index) => f.write_str(&format!("Node{index}")), + Self::Mesh(index) => f.write_str(&format!("Mesh{index}")), + Self::Primitive { mesh, primitive } => { f.write_str(&format!("Mesh{mesh}/Primitive{primitive}")) } - GltfAssetLabel::MorphTarget { mesh, primitive } => { + Self::MorphTarget { mesh, primitive } => { f.write_str(&format!("Mesh{mesh}/Primitive{primitive}/MorphTargets")) } - GltfAssetLabel::Texture(index) => f.write_str(&format!("Texture{index}")), - GltfAssetLabel::Material { + Self::Texture(index) => f.write_str(&format!("Texture{index}")), + Self::Material { index, is_scale_inverted, } => f.write_str(&format!( @@ -548,10 +548,10 @@ impl std::fmt::Display for GltfAssetLabel { "" } )), - GltfAssetLabel::DefaultMaterial => f.write_str("DefaultMaterial"), - GltfAssetLabel::Animation(index) => f.write_str(&format!("Animation{index}")), - GltfAssetLabel::Skin(index) => f.write_str(&format!("Skin{index}")), - GltfAssetLabel::InverseBindMatrices(index) => { + Self::DefaultMaterial => f.write_str("DefaultMaterial"), + Self::Animation(index) => f.write_str(&format!("Animation{index}")), + Self::Skin(index) => f.write_str(&format!("Skin{index}")), + Self::InverseBindMatrices(index) => { f.write_str(&format!("Skin{index}/InverseBindMatrices")) } } diff --git a/crates/bevy_gltf/src/loader.rs b/crates/bevy_gltf/src/loader.rs index 3ae1c6957927a..112f527f806f4 100644 --- a/crates/bevy_gltf/src/loader.rs +++ b/crates/bevy_gltf/src/loader.rs @@ -1821,7 +1821,7 @@ fn split_once(input: &str, delimiter: char) -> Option<(&str, &str)> { } impl<'a> DataUri<'a> { - fn parse(uri: &'a str) -> Result, ()> { + fn parse(uri: &'a str) -> Result { let uri = uri.strip_prefix("data:").ok_or(())?; let (mime_type, data) = split_once(uri, ',').ok_or(())?; @@ -1918,7 +1918,7 @@ impl ClearcoatExtension { load_context: &mut LoadContext, document: &Document, material: &Material, - ) -> Option { + ) -> Option { let extension = material .extensions()? .get("KHR_materials_clearcoat")? @@ -1960,7 +1960,7 @@ impl ClearcoatExtension { }) .unzip(); - Some(ClearcoatExtension { + Some(Self { clearcoat_factor: extension.get("clearcoatFactor").and_then(Value::as_f64), clearcoat_roughness_factor: extension .get("clearcoatRoughnessFactor") @@ -2001,7 +2001,7 @@ impl AnisotropyExtension { load_context: &mut LoadContext, document: &Document, material: &Material, - ) -> Option { + ) -> Option { let extension = material .extensions()? .get("KHR_materials_anisotropy")? @@ -2019,7 +2019,7 @@ impl AnisotropyExtension { }) .unzip(); - Some(AnisotropyExtension { + Some(Self { anisotropy_strength: extension.get("anisotropyStrength").and_then(Value::as_f64), anisotropy_rotation: extension.get("anisotropyRotation").and_then(Value::as_f64), #[cfg(feature = "pbr_anisotropy_texture")] diff --git a/crates/bevy_gltf/src/vertex_attributes.rs b/crates/bevy_gltf/src/vertex_attributes.rs index d42ecbf397771..aa5bd7f5dd7c2 100644 --- a/crates/bevy_gltf/src/vertex_attributes.rs +++ b/crates/bevy_gltf/src/vertex_attributes.rs @@ -104,7 +104,7 @@ impl<'a> VertexAttributeIter<'a> { fn from_accessor( accessor: gltf::Accessor<'a>, buffer_data: &'a Vec>, - ) -> Result, AccessFailed> { + ) -> Result { let normalization = Normalization(accessor.normalized()); let format = (accessor.data_type(), accessor.dimensions()); let acc = BufferAccessor { diff --git a/crates/bevy_hierarchy/src/components/children.rs b/crates/bevy_hierarchy/src/components/children.rs index 5a53462d82c58..6cca4a302c01c 100644 --- a/crates/bevy_hierarchy/src/components/children.rs +++ b/crates/bevy_hierarchy/src/components/children.rs @@ -43,7 +43,7 @@ impl MapEntities for Children { impl FromWorld for Children { #[inline] fn from_world(_world: &mut World) -> Self { - Children(SmallVec::new()) + Self(SmallVec::new()) } } diff --git a/crates/bevy_hierarchy/src/components/parent.rs b/crates/bevy_hierarchy/src/components/parent.rs index 99d8e45460a8d..ca814b94c954d 100644 --- a/crates/bevy_hierarchy/src/components/parent.rs +++ b/crates/bevy_hierarchy/src/components/parent.rs @@ -52,7 +52,7 @@ impl Parent { impl FromWorld for Parent { #[inline(always)] fn from_world(_world: &mut World) -> Self { - Parent(Entity::PLACEHOLDER) + Self(Entity::PLACEHOLDER) } } diff --git a/crates/bevy_hierarchy/src/valid_parent_check_plugin.rs b/crates/bevy_hierarchy/src/valid_parent_check_plugin.rs index 21cde05f52865..a510156e2700d 100644 --- a/crates/bevy_hierarchy/src/valid_parent_check_plugin.rs +++ b/crates/bevy_hierarchy/src/valid_parent_check_plugin.rs @@ -21,7 +21,7 @@ pub struct ReportHierarchyIssue { impl ReportHierarchyIssue { /// Constructs a new object pub fn new(enabled: bool) -> Self { - ReportHierarchyIssue { + Self { enabled, _comp: Default::default(), } diff --git a/crates/bevy_input/src/axis.rs b/crates/bevy_input/src/axis.rs index 21e4b7165b444..44ccf2f50b6c5 100644 --- a/crates/bevy_input/src/axis.rs +++ b/crates/bevy_input/src/axis.rs @@ -20,7 +20,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 5e8c78a54c3b5..6af1ec8eb8760 100644 --- a/crates/bevy_input/src/gamepad.rs +++ b/crates/bevy_input/src/gamepad.rs @@ -476,7 +476,7 @@ pub struct ButtonSettings { impl Default for ButtonSettings { fn default() -> Self { - ButtonSettings { + Self { press_threshold: 0.75, release_threshold: 0.65, } @@ -500,10 +500,7 @@ impl ButtonSettings { /// `GamepadSettingsError::ButtonReleaseThresholdOutOfRange`, /// `GamepadSettingsError::ButtonPressThresholdOutOfRange`, or /// `GamepadSettingsError::ButtonReleaseThresholdGreaterThanPressThreshold`. - pub fn new( - press_threshold: f32, - release_threshold: f32, - ) -> Result { + pub fn new(press_threshold: f32, release_threshold: f32) -> Result { if !(0.0..=1.0).contains(&release_threshold) { Err(ButtonSettingsError::ReleaseThresholdOutOfRange( release_threshold, @@ -520,7 +517,7 @@ impl ButtonSettings { }, ) } else { - Ok(ButtonSettings { + Ok(Self { press_threshold, release_threshold, }) @@ -644,7 +641,7 @@ pub struct AxisSettings { impl Default for AxisSettings { fn default() -> Self { - AxisSettings { + Self { livezone_upperbound: 1.0, deadzone_upperbound: 0.05, deadzone_lowerbound: -0.05, @@ -682,7 +679,7 @@ impl AxisSettings { deadzone_upperbound: f32, livezone_upperbound: f32, threshold: f32, - ) -> Result { + ) -> Result { if !(-1.0..=0.0).contains(&livezone_lowerbound) { Err(AxisSettingsError::LiveZoneLowerBoundOutOfRange( livezone_lowerbound, @@ -972,7 +969,7 @@ pub struct ButtonAxisSettings { impl Default for ButtonAxisSettings { fn default() -> Self { - ButtonAxisSettings { + Self { high: 0.95, low: 0.05, threshold: 0.01, @@ -1341,19 +1338,19 @@ pub struct GamepadRumbleIntensity { impl GamepadRumbleIntensity { /// Rumble both gamepad motors at maximum intensity. - pub const MAX: Self = GamepadRumbleIntensity { + pub const MAX: Self = Self { strong_motor: 1.0, weak_motor: 1.0, }; /// Rumble the weak motor at maximum intensity. - pub const WEAK_MAX: Self = GamepadRumbleIntensity { + pub const WEAK_MAX: Self = Self { strong_motor: 0.0, weak_motor: 1.0, }; /// Rumble the strong motor at maximum intensity. - pub const STRONG_MAX: Self = GamepadRumbleIntensity { + pub const STRONG_MAX: Self = Self { strong_motor: 1.0, weak_motor: 0.0, }; diff --git a/crates/bevy_input/src/lib.rs b/crates/bevy_input/src/lib.rs index 83984af1e69fd..3779118995d55 100644 --- a/crates/bevy_input/src/lib.rs +++ b/crates/bevy_input/src/lib.rs @@ -170,6 +170,6 @@ pub enum ButtonState { impl ButtonState { /// Is this button pressed? pub fn is_pressed(&self) -> bool { - matches!(self, ButtonState::Pressed) + matches!(self, Self::Pressed) } } diff --git a/crates/bevy_input/src/touch.rs b/crates/bevy_input/src/touch.rs index 89c749b7e3fce..d3a76aac6a1e3 100644 --- a/crates/bevy_input/src/touch.rs +++ b/crates/bevy_input/src/touch.rs @@ -209,8 +209,8 @@ impl Touch { } 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_macro_utils/src/bevy_manifest.rs b/crates/bevy_macro_utils/src/bevy_manifest.rs index f06b46abacc5a..c35e04c40f4b5 100644 --- a/crates/bevy_macro_utils/src/bevy_manifest.rs +++ b/crates/bevy_macro_utils/src/bevy_manifest.rs @@ -115,7 +115,7 @@ impl BevyManifest { self.maybe_get_path(BEVY) .map(|bevy_path| { let mut segments = bevy_path.segments; - segments.push(BevyManifest::parse_str(subcrate)); + segments.push(Self::parse_str(subcrate)); syn::Path { leading_colon: None, segments, diff --git a/crates/bevy_math/src/bounding/bounded2d/mod.rs b/crates/bevy_math/src/bounding/bounded2d/mod.rs index 1fdf6c75b0ca7..22f086d92bdfc 100644 --- a/crates/bevy_math/src/bounding/bounded2d/mod.rs +++ b/crates/bevy_math/src/bounding/bounded2d/mod.rs @@ -59,7 +59,7 @@ impl Aabb2d { /// /// Panics if the given set of points is empty. #[inline(always)] - pub fn from_point_cloud(isometry: Isometry2d, points: &[Vec2]) -> Aabb2d { + pub fn from_point_cloud(isometry: Isometry2d, points: &[Vec2]) -> Self { // Transform all points by rotation let mut iter = points.iter().map(|point| isometry.rotation * *point); @@ -71,7 +71,7 @@ impl Aabb2d { (point.min(prev_min), point.max(prev_max)) }); - Aabb2d { + Self { min: min + isometry.translation, max: max + isometry.translation, } @@ -473,7 +473,7 @@ impl BoundingCircle { /// /// The bounding circle is not guaranteed to be the smallest possible. #[inline(always)] - pub fn from_point_cloud(isometry: Isometry2d, points: &[Vec2]) -> BoundingCircle { + pub fn from_point_cloud(isometry: Isometry2d, points: &[Vec2]) -> Self { let center = point_cloud_2d_center(points); let mut radius_squared = 0.0; @@ -485,7 +485,7 @@ impl BoundingCircle { } } - BoundingCircle::new(isometry * center, radius_squared.sqrt()) + Self::new(isometry * center, radius_squared.sqrt()) } /// Get the radius of the bounding circle diff --git a/crates/bevy_math/src/bounding/bounded3d/mod.rs b/crates/bevy_math/src/bounding/bounded3d/mod.rs index 60822fa3fe4cd..1eb673acd8f90 100644 --- a/crates/bevy_math/src/bounding/bounded3d/mod.rs +++ b/crates/bevy_math/src/bounding/bounded3d/mod.rs @@ -64,7 +64,7 @@ impl Aabb3d { pub fn from_point_cloud( isometry: Isometry3d, points: impl Iterator>, - ) -> Aabb3d { + ) -> Self { // Transform all points by rotation let mut iter = points.map(|point| isometry.rotation * point.into()); @@ -76,7 +76,7 @@ impl Aabb3d { (point.min(prev_min), point.max(prev_max)) }); - Aabb3d { + Self { min: min + isometry.translation, max: max + isometry.translation, } @@ -475,10 +475,7 @@ impl BoundingSphere { /// /// The bounding sphere is not guaranteed to be the smallest possible. #[inline(always)] - pub fn from_point_cloud( - isometry: Isometry3d, - points: &[impl Copy + Into], - ) -> BoundingSphere { + pub fn from_point_cloud(isometry: Isometry3d, points: &[impl Copy + Into]) -> Self { let center = point_cloud_3d_center(points.iter().map(|v| Into::::into(*v))); let mut radius_squared: f32 = 0.0; @@ -490,7 +487,7 @@ impl BoundingSphere { } } - BoundingSphere::new(isometry * center, radius_squared.sqrt()) + Self::new(isometry * center, radius_squared.sqrt()) } /// Get the radius of the bounding sphere diff --git a/crates/bevy_math/src/common_traits.rs b/crates/bevy_math/src/common_traits.rs index 525d8e403524e..1ace6f037f97d 100644 --- a/crates/bevy_math/src/common_traits.rs +++ b/crates/bevy_math/src/common_traits.rs @@ -50,19 +50,19 @@ pub trait VectorSpace: } impl VectorSpace for Vec4 { - const ZERO: Self = Vec4::ZERO; + const ZERO: Self = Self::ZERO; } impl VectorSpace for Vec3 { - const ZERO: Self = Vec3::ZERO; + const ZERO: Self = Self::ZERO; } impl VectorSpace for Vec3A { - const ZERO: Self = Vec3A::ZERO; + const ZERO: Self = Self::ZERO; } impl VectorSpace for Vec2 { - const ZERO: Self = Vec2::ZERO; + const ZERO: Self = Self::ZERO; } impl VectorSpace for f32 { diff --git a/crates/bevy_math/src/compass.rs b/crates/bevy_math/src/compass.rs index 244c37962eb4d..6f6343ce17fe9 100644 --- a/crates/bevy_math/src/compass.rs +++ b/crates/bevy_math/src/compass.rs @@ -75,10 +75,10 @@ pub enum CompassOctant { impl From for Dir2 { fn from(q: CompassQuadrant) -> Self { match q { - CompassQuadrant::North => Dir2::NORTH, - CompassQuadrant::East => Dir2::EAST, - CompassQuadrant::South => Dir2::SOUTH, - CompassQuadrant::West => Dir2::WEST, + CompassQuadrant::North => Self::NORTH, + CompassQuadrant::East => Self::EAST, + CompassQuadrant::South => Self::SOUTH, + CompassQuadrant::West => Self::WEST, } } } @@ -102,14 +102,14 @@ impl From for CompassQuadrant { impl From for Dir2 { fn from(o: CompassOctant) -> Self { match o { - CompassOctant::North => Dir2::NORTH, - CompassOctant::NorthEast => Dir2::NORTH_EAST, - CompassOctant::East => Dir2::EAST, - CompassOctant::SouthEast => Dir2::SOUTH_EAST, - CompassOctant::South => Dir2::SOUTH, - CompassOctant::SouthWest => Dir2::SOUTH_WEST, - CompassOctant::West => Dir2::WEST, - CompassOctant::NorthWest => Dir2::NORTH_WEST, + CompassOctant::North => Self::NORTH, + CompassOctant::NorthEast => Self::NORTH_EAST, + CompassOctant::East => Self::EAST, + CompassOctant::SouthEast => Self::SOUTH_EAST, + CompassOctant::South => Self::SOUTH, + CompassOctant::SouthWest => Self::SOUTH_WEST, + CompassOctant::West => Self::WEST, + CompassOctant::NorthWest => Self::NORTH_WEST, } } } diff --git a/crates/bevy_math/src/curve/cores.rs b/crates/bevy_math/src/curve/cores.rs index 92ad2fdc71a3c..f7e48643a1771 100644 --- a/crates/bevy_math/src/curve/cores.rs +++ b/crates/bevy_math/src/curve/cores.rs @@ -42,10 +42,10 @@ impl InterpolationDatum { #[must_use] pub fn map(self, f: impl Fn(T) -> S) -> InterpolationDatum { match self { - InterpolationDatum::Exact(v) => InterpolationDatum::Exact(f(v)), - InterpolationDatum::LeftTail(v) => InterpolationDatum::LeftTail(f(v)), - InterpolationDatum::RightTail(v) => InterpolationDatum::RightTail(f(v)), - InterpolationDatum::Between(u, v, s) => InterpolationDatum::Between(f(u), f(v), s), + Self::Exact(v) => InterpolationDatum::Exact(f(v)), + Self::LeftTail(v) => InterpolationDatum::LeftTail(f(v)), + Self::RightTail(v) => InterpolationDatum::RightTail(f(v)), + Self::Between(u, v, s) => InterpolationDatum::Between(f(u), f(v), s), } } } @@ -102,7 +102,7 @@ impl InterpolationDatum { /// fn domain(&self) -> Interval { /// self.core.domain() /// } -/// +/// /// fn sample_unchecked(&self, t: f32) -> T { /// // To sample this curve, check the interpolation mode and dispatch accordingly. /// match self.interpolation_mode { @@ -165,8 +165,7 @@ impl EvenCore { if !domain.is_bounded() { return Err(EvenCoreError::UnboundedDomain); } - - Ok(EvenCore { domain, samples }) + Ok(Self { domain, samples }) } /// The domain of the curve derived from this core. @@ -297,7 +296,7 @@ pub fn even_interp(domain: Interval, samples: usize, t: f32) -> InterpolationDat /// fn domain(&self) -> Interval { /// self.core.domain() /// } -/// +/// /// fn sample_unchecked(&self, t: f32) -> T { /// // To sample the curve, we just look at the interpolation mode and /// // dispatch accordingly. @@ -369,7 +368,7 @@ impl UnevenCore { } let (times, samples): (Vec, Vec) = timed_samples.into_iter().unzip(); - Ok(UnevenCore { times, samples }) + Ok(Self { times, samples }) } /// The domain of the curve derived from this core. @@ -433,7 +432,7 @@ impl UnevenCore { /// /// [`Curve::reparametrize`]: crate::curve::Curve::reparametrize #[must_use] - pub fn map_sample_times(mut self, f: impl Fn(f32) -> f32) -> UnevenCore { + pub fn map_sample_times(mut self, f: impl Fn(f32) -> f32) -> Self { let mut timed_samples = self .times .into_iter() diff --git a/crates/bevy_math/src/curve/interval.rs b/crates/bevy_math/src/curve/interval.rs index 3ac30de4a6aac..b5893c2c9d52b 100644 --- a/crates/bevy_math/src/curve/interval.rs +++ b/crates/bevy_math/src/curve/interval.rs @@ -85,7 +85,7 @@ impl Interval { /// Create an [`Interval`] by intersecting this interval with another. Returns an error if the /// intersection would be empty (hence an invalid interval). - pub fn intersect(self, other: Interval) -> Result { + pub fn intersect(self, other: Self) -> Result { let lower = max_by(self.start, other.start, f32::total_cmp); let upper = min_by(self.end, other.end, f32::total_cmp); Self::new(lower, upper) @@ -180,7 +180,7 @@ impl Interval { impl TryFrom> for Interval { type Error = InvalidIntervalError; fn try_from(range: RangeInclusive) -> Result { - Interval::new(*range.start(), *range.end()) + Self::new(*range.start(), *range.end()) } } diff --git a/crates/bevy_math/src/curve/mod.rs b/crates/bevy_math/src/curve/mod.rs index 03cfd7c74c07f..dd821e99b76ef 100644 --- a/crates/bevy_math/src/curve/mod.rs +++ b/crates/bevy_math/src/curve/mod.rs @@ -523,7 +523,7 @@ where /// Create a new curve with the given `domain` from the given `function`. When sampled, the /// `function` is evaluated at the sample time to compute the output. pub fn new(domain: Interval, function: F) -> Self { - FunctionCurve { + Self { domain, f: function, _phantom: PhantomData, @@ -894,7 +894,7 @@ impl UnevenSampleCurve { /// /// The samples are re-sorted by time after mapping and deduplicated by output time, so /// the function `f` should generally be injective over the sample times of the curve. - pub fn map_sample_times(self, f: impl Fn(f32) -> f32) -> UnevenSampleCurve { + pub fn map_sample_times(self, f: impl Fn(f32) -> f32) -> Self { Self { core: self.core.map_sample_times(f), interpolation: self.interpolation, @@ -943,7 +943,7 @@ impl UnevenSampleAutoCurve { /// /// The samples are re-sorted by time after mapping and deduplicated by output time, so /// the function `f` should generally be injective over the sample times of the curve. - pub fn map_sample_times(self, f: impl Fn(f32) -> f32) -> UnevenSampleAutoCurve { + pub fn map_sample_times(self, f: impl Fn(f32) -> f32) -> Self { Self { core: self.core.map_sample_times(f), } diff --git a/crates/bevy_math/src/direction.rs b/crates/bevy_math/src/direction.rs index 8f4cf7d9eabab..0cb727f7f9de7 100644 --- a/crates/bevy_math/src/direction.rs +++ b/crates/bevy_math/src/direction.rs @@ -25,13 +25,13 @@ impl InvalidDirectionError { /// Creates an [`InvalidDirectionError`] from the length of an invalid direction vector. pub fn from_length(length: f32) -> Self { if length.is_nan() { - InvalidDirectionError::NaN + Self::NaN } else if !length.is_finite() { // If the direction is non-finite but also not NaN, it must be infinite - InvalidDirectionError::Infinite + Self::Infinite } else { // If the direction is invalid but neither NaN nor infinite, it must be zero - InvalidDirectionError::Zero + Self::Zero } } } @@ -472,7 +472,7 @@ impl Dir3 { #[inline] pub fn slerp(self, rhs: Self, s: f32) -> Self { let quat = Quat::IDENTITY.slerp(Quat::from_rotation_arc(self.0, rhs.0), s); - Dir3(quat.mul_vec3(self.0)) + Self(quat.mul_vec3(self.0)) } /// Returns `self` after an approximate normalization, assuming the value is already nearly normalized. @@ -740,7 +740,7 @@ impl Dir3A { Quat::from_rotation_arc(Vec3::from(self.0), Vec3::from(rhs.0)), s, ); - Dir3A(quat.mul_vec3a(self.0)) + Self(quat.mul_vec3a(self.0)) } /// Returns `self` after an approximate normalization, assuming the value is already nearly normalized. diff --git a/crates/bevy_math/src/float_ord.rs b/crates/bevy_math/src/float_ord.rs index 63360449258d3..d05d00adeceab 100644 --- a/crates/bevy_math/src/float_ord.rs +++ b/crates/bevy_math/src/float_ord.rs @@ -86,10 +86,10 @@ 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_math/src/isometry.rs b/crates/bevy_math/src/isometry.rs index a6505eb846c5d..2f7653df6f736 100644 --- a/crates/bevy_math/src/isometry.rs +++ b/crates/bevy_math/src/isometry.rs @@ -103,7 +103,7 @@ pub struct Isometry2d { impl Isometry2d { /// The identity isometry which represents the rigid motion of not doing anything. - pub const IDENTITY: Self = Isometry2d { + pub const IDENTITY: Self = Self { rotation: Rot2::IDENTITY, translation: Vec2::ZERO, }; @@ -111,7 +111,7 @@ impl Isometry2d { /// Create a two-dimensional isometry from a rotation and a translation. #[inline] pub fn new(translation: Vec2, rotation: Rot2) -> Self { - Isometry2d { + Self { rotation, translation, } @@ -120,7 +120,7 @@ impl Isometry2d { /// Create a two-dimensional isometry from a rotation. #[inline] pub fn from_rotation(rotation: Rot2) -> Self { - Isometry2d { + Self { rotation, translation: Vec2::ZERO, } @@ -129,7 +129,7 @@ impl Isometry2d { /// Create a two-dimensional isometry from a translation. #[inline] pub fn from_translation(translation: Vec2) -> Self { - Isometry2d { + Self { rotation: Rot2::IDENTITY, translation, } @@ -138,7 +138,7 @@ impl Isometry2d { /// Create a two-dimensional isometry from a translation with the given `x` and `y` components. #[inline] pub fn from_xy(x: f32, y: f32) -> Self { - Isometry2d { + Self { rotation: Rot2::IDENTITY, translation: Vec2::new(x, y), } @@ -148,7 +148,7 @@ impl Isometry2d { #[inline] pub fn inverse(&self) -> Self { let inv_rot = self.rotation.inverse(); - Isometry2d { + Self { rotation: inv_rot, translation: inv_rot * -self.translation, } @@ -185,7 +185,7 @@ impl Isometry2d { impl From for Affine2 { #[inline] fn from(iso: Isometry2d) -> Self { - Affine2 { + Self { matrix2: iso.rotation.into(), translation: iso.translation, } @@ -197,7 +197,7 @@ impl Mul for Isometry2d { #[inline] fn mul(self, rhs: Self) -> Self::Output { - Isometry2d { + Self { rotation: self.rotation * rhs.rotation, translation: self.rotation * rhs.translation + self.translation, } @@ -367,7 +367,7 @@ pub struct Isometry3d { impl Isometry3d { /// The identity isometry which represents the rigid motion of not doing anything. - pub const IDENTITY: Self = Isometry3d { + pub const IDENTITY: Self = Self { rotation: Quat::IDENTITY, translation: Vec3A::ZERO, }; @@ -375,7 +375,7 @@ impl Isometry3d { /// Create a three-dimensional isometry from a rotation and a translation. #[inline] pub fn new(translation: impl Into, rotation: Quat) -> Self { - Isometry3d { + Self { rotation, translation: translation.into(), } @@ -384,7 +384,7 @@ impl Isometry3d { /// Create a three-dimensional isometry from a rotation. #[inline] pub fn from_rotation(rotation: Quat) -> Self { - Isometry3d { + Self { rotation, translation: Vec3A::ZERO, } @@ -393,7 +393,7 @@ impl Isometry3d { /// Create a three-dimensional isometry from a translation. #[inline] pub fn from_translation(translation: impl Into) -> Self { - Isometry3d { + Self { rotation: Quat::IDENTITY, translation: translation.into(), } @@ -402,7 +402,7 @@ impl Isometry3d { /// Create a three-dimensional isometry from a translation with the given `x`, `y`, and `z` components. #[inline] pub fn from_xyz(x: f32, y: f32, z: f32) -> Self { - Isometry3d { + Self { rotation: Quat::IDENTITY, translation: Vec3A::new(x, y, z), } @@ -412,7 +412,7 @@ impl Isometry3d { #[inline] pub fn inverse(&self) -> Self { let inv_rot = self.rotation.inverse(); - Isometry3d { + Self { rotation: inv_rot, translation: inv_rot * -self.translation, } @@ -449,7 +449,7 @@ impl Isometry3d { impl From for Affine3 { #[inline] fn from(iso: Isometry3d) -> Self { - Affine3 { + Self { matrix3: Mat3::from_quat(iso.rotation), translation: iso.translation.into(), } @@ -459,7 +459,7 @@ impl From for Affine3 { impl From for Affine3A { #[inline] fn from(iso: Isometry3d) -> Self { - Affine3A { + Self { matrix3: Mat3A::from_quat(iso.rotation), translation: iso.translation, } @@ -471,7 +471,7 @@ impl Mul for Isometry3d { #[inline] fn mul(self, rhs: Self) -> Self::Output { - Isometry3d { + Self { rotation: self.rotation * rhs.rotation, translation: self.rotation * rhs.translation + self.translation, } diff --git a/crates/bevy_math/src/primitives/dim3.rs b/crates/bevy_math/src/primitives/dim3.rs index ed692d7eadbc1..fac52c1b640c5 100644 --- a/crates/bevy_math/src/primitives/dim3.rs +++ b/crates/bevy_math/src/primitives/dim3.rs @@ -954,7 +954,7 @@ impl Triangle3d { /// This triangle but reversed. #[inline(always)] #[must_use] - pub fn reversed(mut self) -> Triangle3d { + pub fn reversed(mut self) -> Self { self.reverse(); self } diff --git a/crates/bevy_math/src/rotation2d.rs b/crates/bevy_math/src/rotation2d.rs index e9fd1f7f13280..33e846ba6ef6c 100644 --- a/crates/bevy_math/src/rotation2d.rs +++ b/crates/bevy_math/src/rotation2d.rs @@ -223,7 +223,7 @@ impl Rot2 { let length_squared = self.length_squared(); // Based on a Taylor approximation of the inverse square root, see [`Dir3::fast_renormalize`](crate::Dir3::fast_renormalize) for more details. let length_recip_approx = 0.5 * (3.0 - length_squared); - Rot2 { + Self { sin: self.sin * length_recip_approx, cos: self.cos * length_recip_approx, } @@ -369,7 +369,7 @@ impl From for Rot2 { impl From for Mat2 { /// Creates a [`Mat2`] rotation matrix from a [`Rot2`]. fn from(rot: Rot2) -> Self { - Mat2::from_cols_array(&[rot.cos, -rot.sin, rot.sin, rot.cos]) + Self::from_cols_array(&[rot.cos, -rot.sin, rot.sin, rot.cos]) } } diff --git a/crates/bevy_pbr/src/cluster/mod.rs b/crates/bevy_pbr/src/cluster/mod.rs index fe913a1d196bb..fa84af7ae1844 100644 --- a/crates/bevy_pbr/src/cluster/mod.rs +++ b/crates/bevy_pbr/src/cluster/mod.rs @@ -251,10 +251,10 @@ impl Default for ClusterConfig { impl ClusterConfig { fn dimensions_for_screen_size(&self, screen_size: UVec2) -> UVec3 { match &self { - ClusterConfig::None => UVec3::ZERO, - ClusterConfig::Single => UVec3::ONE, - ClusterConfig::XYZ { dimensions, .. } => *dimensions, - ClusterConfig::FixedZ { + Self::None => UVec3::ZERO, + Self::Single => UVec3::ONE, + Self::XYZ { dimensions, .. } => *dimensions, + Self::FixedZ { total, z_slices, .. } => { let aspect_ratio: f32 = @@ -288,8 +288,8 @@ impl ClusterConfig { fn first_slice_depth(&self) -> f32 { match self { - ClusterConfig::None | ClusterConfig::Single => 0.0, - ClusterConfig::XYZ { z_config, .. } | ClusterConfig::FixedZ { z_config, .. } => { + Self::None | Self::Single => 0.0, + Self::XYZ { z_config, .. } | Self::FixedZ { z_config, .. } => { z_config.first_slice_depth } } @@ -297,21 +297,19 @@ impl ClusterConfig { fn far_z_mode(&self) -> ClusterFarZMode { match self { - ClusterConfig::None => ClusterFarZMode::Constant(0.0), - ClusterConfig::Single => ClusterFarZMode::MaxClusterableObjectRange, - ClusterConfig::XYZ { z_config, .. } | ClusterConfig::FixedZ { z_config, .. } => { - z_config.far_z_mode - } + Self::None => ClusterFarZMode::Constant(0.0), + Self::Single => ClusterFarZMode::MaxClusterableObjectRange, + Self::XYZ { z_config, .. } | Self::FixedZ { z_config, .. } => z_config.far_z_mode, } } fn dynamic_resizing(&self) -> bool { match self { - ClusterConfig::None | ClusterConfig::Single => false, - ClusterConfig::XYZ { + Self::None | Self::Single => false, + Self::XYZ { dynamic_resizing, .. } - | ClusterConfig::FixedZ { + | Self::FixedZ { dynamic_resizing, .. } => *dynamic_resizing, } @@ -431,7 +429,7 @@ impl GpuClusterableObjects { pub(crate) fn set(&mut self, mut clusterable_objects: Vec) { match self { - GpuClusterableObjects::Uniform(buffer) => { + Self::Uniform(buffer) => { let len = clusterable_objects .len() .min(MAX_UNIFORM_BUFFER_CLUSTERABLE_OBJECTS); @@ -439,7 +437,7 @@ impl GpuClusterableObjects { let dst = &mut buffer.get_mut().data[..len]; dst.copy_from_slice(src); } - GpuClusterableObjects::Storage(buffer) => { + Self::Storage(buffer) => { buffer.get_mut().data.clear(); buffer.get_mut().data.append(&mut clusterable_objects); } @@ -452,10 +450,10 @@ impl GpuClusterableObjects { render_queue: &RenderQueue, ) { match self { - GpuClusterableObjects::Uniform(buffer) => { + Self::Uniform(buffer) => { buffer.write_buffer(render_device, render_queue); } - GpuClusterableObjects::Storage(buffer) => { + Self::Storage(buffer) => { buffer.write_buffer(render_device, render_queue); } } @@ -463,8 +461,8 @@ impl GpuClusterableObjects { pub fn binding(&self) -> Option { match self { - GpuClusterableObjects::Uniform(buffer) => buffer.binding(), - GpuClusterableObjects::Storage(buffer) => buffer.binding(), + Self::Uniform(buffer) => buffer.binding(), + Self::Storage(buffer) => buffer.binding(), } } @@ -775,14 +773,14 @@ impl ViewClusterBuffers { } fn uniform() -> Self { - ViewClusterBuffers::Uniform { + Self::Uniform { clusterable_object_index_lists: UniformBuffer::default(), cluster_offsets_and_counts: UniformBuffer::default(), } } fn storage() -> Self { - ViewClusterBuffers::Storage { + Self::Storage { clusterable_object_index_lists: StorageBuffer::default(), cluster_offsets_and_counts: StorageBuffer::default(), } diff --git a/crates/bevy_pbr/src/deferred/mod.rs b/crates/bevy_pbr/src/deferred/mod.rs index eb4ba66cf0998..62b452d052e6e 100644 --- a/crates/bevy_pbr/src/deferred/mod.rs +++ b/crates/bevy_pbr/src/deferred/mod.rs @@ -54,8 +54,8 @@ pub struct PbrDeferredLightingDepthId { } impl PbrDeferredLightingDepthId { - pub fn new(value: u8) -> PbrDeferredLightingDepthId { - PbrDeferredLightingDepthId { + pub fn new(value: u8) -> Self { + Self { depth_id: value as u32, #[cfg(all(feature = "webgl", target_arch = "wasm32", not(feature = "webgpu")))] @@ -78,7 +78,7 @@ impl PbrDeferredLightingDepthId { impl Default for PbrDeferredLightingDepthId { fn default() -> Self { - PbrDeferredLightingDepthId { + Self { depth_id: DEFAULT_PBR_DEFERRED_LIGHTING_PASS_ID as u32, #[cfg(all(feature = "webgl", target_arch = "wasm32", not(feature = "webgpu")))] diff --git a/crates/bevy_pbr/src/fog.rs b/crates/bevy_pbr/src/fog.rs index 894ced95a4d09..86495e64460c6 100644 --- a/crates/bevy_pbr/src/fog.rs +++ b/crates/bevy_pbr/src/fog.rs @@ -307,51 +307,42 @@ pub enum FogFalloff { impl FogFalloff { /// Creates a [`FogFalloff::Exponential`] value from the given visibility distance in world units, /// using the revised Koschmieder contrast threshold, [`FogFalloff::REVISED_KOSCHMIEDER_CONTRAST_THRESHOLD`]. - pub fn from_visibility(visibility: f32) -> FogFalloff { - FogFalloff::from_visibility_contrast( - visibility, - FogFalloff::REVISED_KOSCHMIEDER_CONTRAST_THRESHOLD, - ) + pub fn from_visibility(visibility: f32) -> Self { + Self::from_visibility_contrast(visibility, Self::REVISED_KOSCHMIEDER_CONTRAST_THRESHOLD) } /// Creates a [`FogFalloff::Exponential`] value from the given visibility distance in world units, /// and a given contrast threshold in the range of `0.0` to `1.0`. - pub fn from_visibility_contrast(visibility: f32, contrast_threshold: f32) -> FogFalloff { - FogFalloff::Exponential { - density: FogFalloff::koschmieder(visibility, contrast_threshold), + pub fn from_visibility_contrast(visibility: f32, contrast_threshold: f32) -> Self { + Self::Exponential { + density: Self::koschmieder(visibility, contrast_threshold), } } /// Creates a [`FogFalloff::ExponentialSquared`] value from the given visibility distance in world units, /// using the revised Koschmieder contrast threshold, [`FogFalloff::REVISED_KOSCHMIEDER_CONTRAST_THRESHOLD`]. - pub fn from_visibility_squared(visibility: f32) -> FogFalloff { - FogFalloff::from_visibility_contrast_squared( + pub fn from_visibility_squared(visibility: f32) -> Self { + Self::from_visibility_contrast_squared( visibility, - FogFalloff::REVISED_KOSCHMIEDER_CONTRAST_THRESHOLD, + Self::REVISED_KOSCHMIEDER_CONTRAST_THRESHOLD, ) } /// Creates a [`FogFalloff::ExponentialSquared`] value from the given visibility distance in world units, /// and a given contrast threshold in the range of `0.0` to `1.0`. - pub fn from_visibility_contrast_squared( - visibility: f32, - contrast_threshold: f32, - ) -> FogFalloff { - FogFalloff::ExponentialSquared { - density: (FogFalloff::koschmieder(visibility, contrast_threshold) / visibility).sqrt(), + pub fn from_visibility_contrast_squared(visibility: f32, contrast_threshold: f32) -> Self { + Self::ExponentialSquared { + density: (Self::koschmieder(visibility, contrast_threshold) / visibility).sqrt(), } } /// Creates a [`FogFalloff::Atmospheric`] value from the given visibility distance in world units, /// and a shared color for both extinction and inscattering, using the revised Koschmieder contrast threshold, /// [`FogFalloff::REVISED_KOSCHMIEDER_CONTRAST_THRESHOLD`]. - pub fn from_visibility_color( - visibility: f32, - extinction_inscattering_color: Color, - ) -> FogFalloff { - FogFalloff::from_visibility_contrast_colors( + pub fn from_visibility_color(visibility: f32, extinction_inscattering_color: Color) -> Self { + Self::from_visibility_contrast_colors( visibility, - FogFalloff::REVISED_KOSCHMIEDER_CONTRAST_THRESHOLD, + Self::REVISED_KOSCHMIEDER_CONTRAST_THRESHOLD, extinction_inscattering_color, extinction_inscattering_color, ) @@ -369,10 +360,10 @@ impl FogFalloff { visibility: f32, extinction_color: Color, inscattering_color: Color, - ) -> FogFalloff { - FogFalloff::from_visibility_contrast_colors( + ) -> Self { + Self::from_visibility_contrast_colors( visibility, - FogFalloff::REVISED_KOSCHMIEDER_CONTRAST_THRESHOLD, + Self::REVISED_KOSCHMIEDER_CONTRAST_THRESHOLD, extinction_color, inscattering_color, ) @@ -384,8 +375,8 @@ impl FogFalloff { visibility: f32, contrast_threshold: f32, extinction_inscattering_color: Color, - ) -> FogFalloff { - FogFalloff::from_visibility_contrast_colors( + ) -> Self { + Self::from_visibility_contrast_colors( visibility, contrast_threshold, extinction_inscattering_color, @@ -405,13 +396,13 @@ impl FogFalloff { contrast_threshold: f32, extinction_color: Color, inscattering_color: Color, - ) -> FogFalloff { + ) -> Self { use std::f32::consts::E; let [r_e, g_e, b_e, a_e] = LinearRgba::from(extinction_color).to_f32_array(); let [r_i, g_i, b_i, a_i] = LinearRgba::from(inscattering_color).to_f32_array(); - FogFalloff::Atmospheric { + Self::Atmospheric { extinction: Vec3::new( // Values are subtracted from 1.0 here to preserve the intuitive/artistic meaning of // colors, since they're later subtracted. (e.g. by giving a blue extinction color, you @@ -419,11 +410,11 @@ impl FogFalloff { (1.0 - r_e).powf(E), (1.0 - g_e).powf(E), (1.0 - b_e).powf(E), - ) * FogFalloff::koschmieder(visibility, contrast_threshold) + ) * Self::koschmieder(visibility, contrast_threshold) * a_e.powf(E), inscattering: Vec3::new(r_i.powf(E), g_i.powf(E), b_i.powf(E)) - * FogFalloff::koschmieder(visibility, contrast_threshold) + * Self::koschmieder(visibility, contrast_threshold) * a_i.powf(E), } } @@ -465,7 +456,7 @@ impl FogFalloff { impl Default for FogSettings { fn default() -> Self { - FogSettings { + Self { color: Color::WHITE, falloff: FogFalloff::Linear { start: 0.0, diff --git a/crates/bevy_pbr/src/light/ambient_light.rs b/crates/bevy_pbr/src/light/ambient_light.rs index 9bff67d5f836d..88f99b627a5b3 100644 --- a/crates/bevy_pbr/src/light/ambient_light.rs +++ b/crates/bevy_pbr/src/light/ambient_light.rs @@ -36,7 +36,7 @@ impl Default for AmbientLight { } } impl AmbientLight { - pub const NONE: AmbientLight = AmbientLight { + pub const NONE: Self = Self { color: Color::WHITE, brightness: 0.0, }; diff --git a/crates/bevy_pbr/src/light/directional_light.rs b/crates/bevy_pbr/src/light/directional_light.rs index 9c74971ca15a5..e3552d2772321 100644 --- a/crates/bevy_pbr/src/light/directional_light.rs +++ b/crates/bevy_pbr/src/light/directional_light.rs @@ -67,7 +67,7 @@ pub struct DirectionalLight { impl Default for DirectionalLight { fn default() -> Self { - DirectionalLight { + Self { color: Color::WHITE, illuminance: light_consts::lux::AMBIENT_DAYLIGHT, shadows_enabled: false, diff --git a/crates/bevy_pbr/src/light/point_light.rs b/crates/bevy_pbr/src/light/point_light.rs index 9ca85cd4db167..b372065719c51 100644 --- a/crates/bevy_pbr/src/light/point_light.rs +++ b/crates/bevy_pbr/src/light/point_light.rs @@ -49,7 +49,7 @@ pub struct PointLight { impl Default for PointLight { fn default() -> Self { - PointLight { + Self { color: Color::WHITE, // 1,000,000 lumens is a very large "cinema light" capable of registering brightly at Bevy's // default "very overcast day" exposure level. For "indoor lighting" with a lower exposure, diff --git a/crates/bevy_pbr/src/light_probe/environment_map.rs b/crates/bevy_pbr/src/light_probe/environment_map.rs index 8a78e93083024..3f4fe7692665b 100644 --- a/crates/bevy_pbr/src/light_probe/environment_map.rs +++ b/crates/bevy_pbr/src/light_probe/environment_map.rs @@ -108,7 +108,7 @@ pub struct EnvironmentMapLight { impl Default for EnvironmentMapLight { fn default() -> Self { - EnvironmentMapLight { + Self { diffuse_map: Handle::default(), specular_map: Handle::default(), intensity: 0.0, @@ -201,7 +201,7 @@ impl ExtractInstance for EnvironmentMapIds { type QueryFilter = (); fn extract(item: QueryItem<'_, Self::QueryData>) -> Option { - Some(EnvironmentMapIds { + Some(Self { diffuse: item.diffuse_map.id(), specular: item.specular_map.id(), }) @@ -236,7 +236,7 @@ impl<'a> RenderViewEnvironmentMapBindGroupEntries<'a> { images: &'a RenderAssets, fallback_image: &'a FallbackImage, render_device: &RenderDevice, - ) -> RenderViewEnvironmentMapBindGroupEntries<'a> { + ) -> Self { if binding_arrays_are_usable(render_device) { let mut diffuse_texture_views = vec![]; let mut specular_texture_views = vec![]; @@ -321,14 +321,14 @@ impl LightProbeComponent for EnvironmentMapLight { } fn create_render_view_light_probes( - view_component: Option<&EnvironmentMapLight>, + view_component: Option<&Self>, image_assets: &RenderAssets, ) -> RenderViewLightProbes { let mut render_view_light_probes = RenderViewLightProbes::new(); // Find the index of the cubemap associated with the view, and determine // its smallest mip level. - if let Some(EnvironmentMapLight { + if let Some(Self { diffuse_map: diffuse_map_handle, specular_map: specular_map_handle, intensity, diff --git a/crates/bevy_pbr/src/light_probe/irradiance_volume.rs b/crates/bevy_pbr/src/light_probe/irradiance_volume.rs index 618da04fa4490..7dc29af39f91d 100644 --- a/crates/bevy_pbr/src/light_probe/irradiance_volume.rs +++ b/crates/bevy_pbr/src/light_probe/irradiance_volume.rs @@ -215,7 +215,7 @@ impl<'a> RenderViewIrradianceVolumeBindGroupEntries<'a> { images: &'a RenderAssets, fallback_image: &'a FallbackImage, render_device: &RenderDevice, - ) -> RenderViewIrradianceVolumeBindGroupEntries<'a> { + ) -> Self { if binding_arrays_are_usable(render_device) { RenderViewIrradianceVolumeBindGroupEntries::get_multiple( render_view_irradiance_volumes, @@ -238,7 +238,7 @@ impl<'a> RenderViewIrradianceVolumeBindGroupEntries<'a> { render_view_irradiance_volumes: Option<&RenderViewLightProbes>, images: &'a RenderAssets, fallback_image: &'a FallbackImage, - ) -> RenderViewIrradianceVolumeBindGroupEntries<'a> { + ) -> Self { let mut texture_views = vec![]; let mut sampler = None; @@ -271,7 +271,7 @@ impl<'a> RenderViewIrradianceVolumeBindGroupEntries<'a> { render_view_irradiance_volumes: Option<&RenderViewLightProbes>, images: &'a RenderAssets, fallback_image: &'a FallbackImage, - ) -> RenderViewIrradianceVolumeBindGroupEntries<'a> { + ) -> Self { if let Some(irradiance_volumes) = render_view_irradiance_volumes { if let Some(irradiance_volume) = irradiance_volumes.render_light_probes.first() { if irradiance_volume.texture_index >= 0 { diff --git a/crates/bevy_pbr/src/light_probe/mod.rs b/crates/bevy_pbr/src/light_probe/mod.rs index dbcdd680d9fdb..246a8c6484a87 100644 --- a/crates/bevy_pbr/src/light_probe/mod.rs +++ b/crates/bevy_pbr/src/light_probe/mod.rs @@ -306,7 +306,7 @@ pub struct EnvironmentMapUniform { impl Default for EnvironmentMapUniform { fn default() -> Self { - EnvironmentMapUniform { + Self { transform: Mat4::IDENTITY, } } @@ -583,8 +583,8 @@ where fn new( (light_probe_transform, environment_map): (&GlobalTransform, &C), image_assets: &RenderAssets, - ) -> Option> { - environment_map.id(image_assets).map(|id| LightProbeInfo { + ) -> Option { + environment_map.id(image_assets).map(|id| Self { world_from_light: light_probe_transform.affine(), light_from_world: light_probe_transform.compute_matrix().inverse(), asset_id: id, @@ -621,8 +621,8 @@ where C: LightProbeComponent, { /// Creates a new empty list of light probes. - fn new() -> RenderViewLightProbes { - RenderViewLightProbes { + fn new() -> Self { + Self { binding_index_to_textures: vec![], cubemap_to_binding_index: HashMap::new(), render_light_probes: vec![], diff --git a/crates/bevy_pbr/src/material.rs b/crates/bevy_pbr/src/material.rs index ce55b93d3ec68..96469e120ac1e 100644 --- a/crates/bevy_pbr/src/material.rs +++ b/crates/bevy_pbr/src/material.rs @@ -407,8 +407,7 @@ impl FromWorld for MaterialPipeline { fn from_world(world: &mut World) -> Self { let asset_server = world.resource::(); let render_device = world.resource::(); - - MaterialPipeline { + Self { mesh_pipeline: world.resource::().clone(), material_layout: M::bind_group_layout(render_device), vertex_shader: match M::vertex_shader() { @@ -830,11 +829,11 @@ pub struct DefaultOpaqueRendererMethod(OpaqueRendererMethod); impl DefaultOpaqueRendererMethod { pub fn forward() -> Self { - DefaultOpaqueRendererMethod(OpaqueRendererMethod::Forward) + Self(OpaqueRendererMethod::Forward) } pub fn deferred() -> Self { - DefaultOpaqueRendererMethod(OpaqueRendererMethod::Deferred) + Self(OpaqueRendererMethod::Deferred) } pub fn set_to_forward(&mut self) { @@ -935,8 +934,7 @@ impl RenderAsset for PreparedMaterial { MeshPipelineKey::READS_VIEW_TRANSMISSION_TEXTURE, material.reads_view_transmission_texture(), ); - - Ok(PreparedMaterial { + Ok(Self { bindings: prepared.bindings, bind_group: prepared.bind_group, key: prepared.data, diff --git a/crates/bevy_pbr/src/parallax.rs b/crates/bevy_pbr/src/parallax.rs index e458f88146701..fdb102ca14daa 100644 --- a/crates/bevy_pbr/src/parallax.rs +++ b/crates/bevy_pbr/src/parallax.rs @@ -34,12 +34,12 @@ pub enum ParallaxMappingMethod { } impl ParallaxMappingMethod { /// [`ParallaxMappingMethod::Relief`] with a 5 steps, a reasonable default. - pub const DEFAULT_RELIEF_MAPPING: Self = ParallaxMappingMethod::Relief { max_steps: 5 }; + pub const DEFAULT_RELIEF_MAPPING: Self = Self::Relief { max_steps: 5 }; pub(crate) fn max_steps(&self) -> u32 { match self { - ParallaxMappingMethod::Occlusion => 0, - ParallaxMappingMethod::Relief { max_steps } => *max_steps, + Self::Occlusion => 0, + Self::Relief { max_steps } => *max_steps, } } } diff --git a/crates/bevy_pbr/src/pbr_material.rs b/crates/bevy_pbr/src/pbr_material.rs index 916a1f098ccd2..e6a5611df61df 100644 --- a/crates/bevy_pbr/src/pbr_material.rs +++ b/crates/bevy_pbr/src/pbr_material.rs @@ -759,7 +759,7 @@ impl StandardMaterial { impl Default for StandardMaterial { fn default() -> Self { - StandardMaterial { + Self { // White because it gets multiplied with texture values if someone uses // a texture. base_color: Color::WHITE, @@ -842,7 +842,7 @@ impl Default for StandardMaterial { impl From for StandardMaterial { fn from(color: Color) -> Self { - StandardMaterial { + Self { base_color: color, alpha_mode: if color.alpha() < 1.0 { AlphaMode::Blend @@ -856,7 +856,7 @@ impl From for StandardMaterial { impl From> for StandardMaterial { fn from(texture: Handle) -> Self { - StandardMaterial { + Self { base_color_texture: Some(texture), ..Default::default() } @@ -1136,90 +1136,78 @@ const STANDARD_MATERIAL_KEY_DEPTH_BIAS_SHIFT: u64 = 32; impl From<&StandardMaterial> for StandardMaterialKey { fn from(material: &StandardMaterial) -> Self { - let mut key = StandardMaterialKey::empty(); + let mut key = Self::empty(); + key.set(Self::CULL_FRONT, material.cull_mode == Some(Face::Front)); + key.set(Self::CULL_BACK, material.cull_mode == Some(Face::Back)); + key.set(Self::NORMAL_MAP, material.normal_map_texture.is_some()); key.set( - StandardMaterialKey::CULL_FRONT, - material.cull_mode == Some(Face::Front), - ); - key.set( - StandardMaterialKey::CULL_BACK, - material.cull_mode == Some(Face::Back), - ); - key.set( - StandardMaterialKey::NORMAL_MAP, - material.normal_map_texture.is_some(), - ); - key.set( - StandardMaterialKey::RELIEF_MAPPING, + Self::RELIEF_MAPPING, matches!( material.parallax_mapping_method, ParallaxMappingMethod::Relief { .. } ), ); key.set( - StandardMaterialKey::DIFFUSE_TRANSMISSION, + Self::DIFFUSE_TRANSMISSION, material.diffuse_transmission > 0.0, ); key.set( - StandardMaterialKey::SPECULAR_TRANSMISSION, + Self::SPECULAR_TRANSMISSION, material.specular_transmission > 0.0, ); - key.set(StandardMaterialKey::CLEARCOAT, material.clearcoat > 0.0); + key.set(Self::CLEARCOAT, material.clearcoat > 0.0); #[cfg(feature = "pbr_multi_layer_material_textures")] key.set( - StandardMaterialKey::CLEARCOAT_NORMAL_MAP, + Self::CLEARCOAT_NORMAL_MAP, material.clearcoat > 0.0 && material.clearcoat_normal_texture.is_some(), ); - key.set( - StandardMaterialKey::ANISOTROPY, - material.anisotropy_strength > 0.0, - ); + key.set(Self::ANISOTROPY, material.anisotropy_strength > 0.0); key.set( - StandardMaterialKey::BASE_COLOR_UV, + Self::BASE_COLOR_UV, material.base_color_channel != UvChannel::Uv0, ); key.set( - StandardMaterialKey::EMISSIVE_UV, + Self::EMISSIVE_UV, material.emissive_channel != UvChannel::Uv0, ); key.set( - StandardMaterialKey::METALLIC_ROUGHNESS_UV, + Self::METALLIC_ROUGHNESS_UV, material.metallic_roughness_channel != UvChannel::Uv0, ); key.set( - StandardMaterialKey::OCCLUSION_UV, + Self::OCCLUSION_UV, material.occlusion_channel != UvChannel::Uv0, ); #[cfg(feature = "pbr_transmission_textures")] { key.set( - StandardMaterialKey::SPECULAR_TRANSMISSION_UV, + Self::SPECULAR_TRANSMISSION_UV, material.specular_transmission_channel != UvChannel::Uv0, ); key.set( - StandardMaterialKey::THICKNESS_UV, + Self::THICKNESS_UV, material.thickness_channel != UvChannel::Uv0, ); key.set( - StandardMaterialKey::DIFFUSE_TRANSMISSION_UV, + Self::DIFFUSE_TRANSMISSION_UV, material.diffuse_transmission_channel != UvChannel::Uv0, ); } key.set( - StandardMaterialKey::NORMAL_MAP_UV, + Self::NORMAL_MAP_UV, material.normal_map_channel != UvChannel::Uv0, ); #[cfg(feature = "pbr_anisotropy_texture")] { key.set( - StandardMaterialKey::ANISOTROPY_UV, + Self::ANISOTROPY_UV, material.anisotropy_channel != UvChannel::Uv0, ); } @@ -1227,20 +1215,20 @@ impl From<&StandardMaterial> for StandardMaterialKey { #[cfg(feature = "pbr_multi_layer_material_textures")] { key.set( - StandardMaterialKey::CLEARCOAT_UV, + Self::CLEARCOAT_UV, material.clearcoat_channel != UvChannel::Uv0, ); key.set( - StandardMaterialKey::CLEARCOAT_ROUGHNESS_UV, + Self::CLEARCOAT_ROUGHNESS_UV, material.clearcoat_roughness_channel != UvChannel::Uv0, ); key.set( - StandardMaterialKey::CLEARCOAT_NORMAL_UV, + Self::CLEARCOAT_NORMAL_UV, material.clearcoat_normal_channel != UvChannel::Uv0, ); } - key.insert(StandardMaterialKey::from_bits_retain( + key.insert(Self::from_bits_retain( (material.depth_bias as u64) << STANDARD_MATERIAL_KEY_DEPTH_BIAS_SHIFT, )); key diff --git a/crates/bevy_pbr/src/prepass/mod.rs b/crates/bevy_pbr/src/prepass/mod.rs index a8ca69a41f176..cdde98b64943a 100644 --- a/crates/bevy_pbr/src/prepass/mod.rs +++ b/crates/bevy_pbr/src/prepass/mod.rs @@ -285,7 +285,7 @@ impl FromWorld for PrepassPipeline { let mesh_pipeline = world.resource::(); - PrepassPipeline { + Self { view_layout_motion_vectors, view_layout_no_motion_vectors, mesh_layouts: mesh_pipeline.mesh_layouts.clone(), diff --git a/crates/bevy_pbr/src/render/gpu_preprocess.rs b/crates/bevy_pbr/src/render/gpu_preprocess.rs index 67eca5df5e13d..3d7a259e1146e 100644 --- a/crates/bevy_pbr/src/render/gpu_preprocess.rs +++ b/crates/bevy_pbr/src/render/gpu_preprocess.rs @@ -310,7 +310,7 @@ impl FromWorld for PreprocessPipelines { &gpu_culling_bind_group_layout_entries, ); - PreprocessPipelines { + Self { direct: PreprocessPipeline { bind_group_layout: direct_bind_group_layout, pipeline_id: None, @@ -361,7 +361,7 @@ impl PreprocessPipeline { fn prepare( &mut self, pipeline_cache: &PipelineCache, - pipelines: &mut SpecializedComputePipelines, + pipelines: &mut SpecializedComputePipelines, key: PreprocessPipelineKey, ) { if self.pipeline_id.is_some() { diff --git a/crates/bevy_pbr/src/render/light.rs b/crates/bevy_pbr/src/render/light.rs index 9ecf1b3616be4..c32d409f819e9 100644 --- a/crates/bevy_pbr/src/render/light.rs +++ b/crates/bevy_pbr/src/render/light.rs @@ -142,8 +142,7 @@ pub struct ShadowSamplers { impl FromWorld for ShadowSamplers { fn from_world(world: &mut World) -> Self { let render_device = world.resource::(); - - ShadowSamplers { + Self { point_light_sampler: render_device.create_sampler(&SamplerDescriptor { address_mode_u: AddressMode::ClampToEdge, address_mode_v: AddressMode::ClampToEdge, @@ -1360,7 +1359,7 @@ impl BinnedPhaseItem for Shadow { batch_range: Range, extra_index: PhaseItemExtraIndex, ) -> Self { - Shadow { + Self { key, representative_entity, batch_range, diff --git a/crates/bevy_pbr/src/render/mesh.rs b/crates/bevy_pbr/src/render/mesh.rs index f3e52b3780640..3dcc948429998 100644 --- a/crates/bevy_pbr/src/render/mesh.rs +++ b/crates/bevy_pbr/src/render/mesh.rs @@ -408,25 +408,24 @@ impl MeshFlags { lod_index: Option, not_shadow_receiver: bool, transmitted_receiver: bool, - ) -> MeshFlags { + ) -> Self { let mut mesh_flags = if not_shadow_receiver { - MeshFlags::empty() + Self::empty() } else { - MeshFlags::SHADOW_RECEIVER + Self::SHADOW_RECEIVER }; if transmitted_receiver { - mesh_flags |= MeshFlags::TRANSMITTED_SHADOW_RECEIVER; + mesh_flags |= Self::TRANSMITTED_SHADOW_RECEIVER; } if transform.affine().matrix3.determinant().is_sign_positive() { - mesh_flags |= MeshFlags::SIGN_DETERMINANT_MODEL_3X3; + mesh_flags |= Self::SIGN_DETERMINANT_MODEL_3X3; } let lod_index_bits = match lod_index { None => u16::MAX, Some(lod_index) => u16::from(lod_index), }; - mesh_flags |= - MeshFlags::from_bits_retain((lod_index_bits as u32) << MeshFlags::LOD_INDEX_SHIFT); + mesh_flags |= Self::from_bits_retain((lod_index_bits as u32) << Self::LOD_INDEX_SHIFT); mesh_flags } @@ -576,7 +575,7 @@ impl RenderMeshInstanceShared { previous_transform.is_some(), ); - RenderMeshInstanceShared { + Self { mesh_asset_id: handle.id(), flags: mesh_instance_flags, @@ -619,19 +618,19 @@ pub struct RenderMeshInstancesGpu(EntityHashMap); impl RenderMeshInstances { /// Creates a new [`RenderMeshInstances`] instance. - fn new(use_gpu_instance_buffer_builder: bool) -> RenderMeshInstances { + fn new(use_gpu_instance_buffer_builder: bool) -> Self { if use_gpu_instance_buffer_builder { - RenderMeshInstances::GpuBuilding(RenderMeshInstancesGpu::default()) + Self::GpuBuilding(RenderMeshInstancesGpu::default()) } else { - RenderMeshInstances::CpuBuilding(RenderMeshInstancesCpu::default()) + Self::CpuBuilding(RenderMeshInstancesCpu::default()) } } /// Returns the ID of the mesh asset attached to the given entity, if any. pub(crate) fn mesh_asset_id(&self, entity: Entity) -> Option> { match *self { - RenderMeshInstances::CpuBuilding(ref instances) => instances.mesh_asset_id(entity), - RenderMeshInstances::GpuBuilding(ref instances) => instances.mesh_asset_id(entity), + Self::CpuBuilding(ref instances) => instances.mesh_asset_id(entity), + Self::GpuBuilding(ref instances) => instances.mesh_asset_id(entity), } } @@ -639,12 +638,8 @@ impl RenderMeshInstances { /// mesh attached. pub fn render_mesh_queue_data(&self, entity: Entity) -> Option { match *self { - RenderMeshInstances::CpuBuilding(ref instances) => { - instances.render_mesh_queue_data(entity) - } - RenderMeshInstances::GpuBuilding(ref instances) => { - instances.render_mesh_queue_data(entity) - } + Self::CpuBuilding(ref instances) => instances.render_mesh_queue_data(entity), + Self::GpuBuilding(ref instances) => instances.render_mesh_queue_data(entity), } } @@ -652,10 +647,10 @@ impl RenderMeshInstances { /// for the given mesh as appropriate. fn insert_mesh_instance_flags(&mut self, entity: Entity, flags: RenderMeshInstanceFlags) { match *self { - RenderMeshInstances::CpuBuilding(ref mut instances) => { + Self::CpuBuilding(ref mut instances) => { instances.insert_mesh_instance_flags(entity, flags); } - RenderMeshInstances::GpuBuilding(ref mut instances) => { + Self::GpuBuilding(ref mut instances) => { instances.insert_mesh_instance_flags(entity, flags); } } @@ -716,10 +711,10 @@ impl RenderMeshInstanceGpuQueue { /// enabled. fn init(&mut self, any_gpu_culling: bool) { match (any_gpu_culling, &mut *self) { - (true, RenderMeshInstanceGpuQueue::GpuCulling(queue)) => queue.clear(), - (true, _) => *self = RenderMeshInstanceGpuQueue::GpuCulling(vec![]), - (false, RenderMeshInstanceGpuQueue::CpuCulling(queue)) => queue.clear(), - (false, _) => *self = RenderMeshInstanceGpuQueue::CpuCulling(vec![]), + (true, Self::GpuCulling(queue)) => queue.clear(), + (true, _) => *self = Self::GpuCulling(vec![]), + (false, Self::CpuCulling(queue)) => queue.clear(), + (false, _) => *self = Self::CpuCulling(vec![]), } } @@ -731,24 +726,17 @@ impl RenderMeshInstanceGpuQueue { culling_data_builder: Option, ) { match (&mut *self, culling_data_builder) { - (&mut RenderMeshInstanceGpuQueue::CpuCulling(ref mut queue), None) => { + (&mut Self::CpuCulling(ref mut queue), None) => { queue.push((entity, instance_builder)); } - ( - &mut RenderMeshInstanceGpuQueue::GpuCulling(ref mut queue), - Some(culling_data_builder), - ) => { + (&mut Self::GpuCulling(ref mut queue), Some(culling_data_builder)) => { queue.push((entity, instance_builder, culling_data_builder)); } (_, None) => { - *self = RenderMeshInstanceGpuQueue::CpuCulling(vec![(entity, instance_builder)]); + *self = Self::CpuCulling(vec![(entity, instance_builder)]); } (_, Some(culling_data_builder)) => { - *self = RenderMeshInstanceGpuQueue::GpuCulling(vec![( - entity, - instance_builder, - culling_data_builder, - )]); + *self = Self::GpuCulling(vec![(entity, instance_builder, culling_data_builder)]); } } } @@ -808,11 +796,11 @@ impl MeshCullingData { /// chosen. fn new(aabb: Option<&Aabb>) -> Self { match aabb { - Some(aabb) => MeshCullingData { + Some(aabb) => Self { aabb_center: aabb.center.extend(0.0), aabb_half_extents: aabb.half_extents.extend(0.0), }, - None => MeshCullingData { + None => Self { aabb_center: Vec3::ZERO.extend(0.0), aabb_half_extents: Vec3::INFINITY.extend(0.0), }, @@ -1225,7 +1213,7 @@ impl FromWorld for MeshPipeline { } }; - MeshPipeline { + Self { view_layouts: view_layouts.clone(), clustered_forward_buffer_binding_type, dummy_white_gpu_image, @@ -1557,9 +1545,9 @@ impl MeshPipelineKey { pub fn from_hdr(hdr: bool) -> Self { if hdr { - MeshPipelineKey::HDR + Self::HDR } else { - MeshPipelineKey::NONE + Self::NONE } } diff --git a/crates/bevy_pbr/src/render/mesh_bindings.rs b/crates/bevy_pbr/src/render/mesh_bindings.rs index 0ba7eb5de28b2..aed17ac49c471 100644 --- a/crates/bevy_pbr/src/render/mesh_bindings.rs +++ b/crates/bevy_pbr/src/render/mesh_bindings.rs @@ -136,7 +136,7 @@ impl MeshLayouts { /// /// [`Mesh`]: bevy_render::prelude::Mesh pub fn new(render_device: &RenderDevice) -> Self { - MeshLayouts { + Self { model_only: Self::model_only_layout(render_device), lightmapped: Self::lightmapped_layout(render_device), skinned: Self::skinned_layout(render_device), diff --git a/crates/bevy_pbr/src/render/mesh_view_bindings.rs b/crates/bevy_pbr/src/render/mesh_view_bindings.rs index 36c5d7bfe044f..b00844fa57b66 100644 --- a/crates/bevy_pbr/src/render/mesh_view_bindings.rs +++ b/crates/bevy_pbr/src/render/mesh_view_bindings.rs @@ -79,23 +79,21 @@ impl MeshPipelineViewLayoutKey { /// Builds a unique label for each layout based on the flags pub fn label(&self) -> String { - use MeshPipelineViewLayoutKey as Key; - format!( "mesh_view_layout{}{}{}{}{}", - self.contains(Key::MULTISAMPLED) + self.contains(Self::MULTISAMPLED) .then_some("_multisampled") .unwrap_or_default(), - self.contains(Key::DEPTH_PREPASS) + self.contains(Self::DEPTH_PREPASS) .then_some("_depth") .unwrap_or_default(), - self.contains(Key::NORMAL_PREPASS) + self.contains(Self::NORMAL_PREPASS) .then_some("_normal") .unwrap_or_default(), - self.contains(Key::MOTION_VECTOR_PREPASS) + self.contains(Self::MOTION_VECTOR_PREPASS) .then_some("_motion") .unwrap_or_default(), - self.contains(Key::DEFERRED_PREPASS) + self.contains(Self::DEFERRED_PREPASS) .then_some("_deferred") .unwrap_or_default(), ) @@ -104,22 +102,22 @@ impl MeshPipelineViewLayoutKey { impl From for MeshPipelineViewLayoutKey { fn from(value: MeshPipelineKey) -> Self { - let mut result = MeshPipelineViewLayoutKey::empty(); + let mut result = Self::empty(); if value.msaa_samples() > 1 { - result |= MeshPipelineViewLayoutKey::MULTISAMPLED; + result |= Self::MULTISAMPLED; } if value.contains(MeshPipelineKey::DEPTH_PREPASS) { - result |= MeshPipelineViewLayoutKey::DEPTH_PREPASS; + result |= Self::DEPTH_PREPASS; } if value.contains(MeshPipelineKey::NORMAL_PREPASS) { - result |= MeshPipelineViewLayoutKey::NORMAL_PREPASS; + result |= Self::NORMAL_PREPASS; } if value.contains(MeshPipelineKey::MOTION_VECTOR_PREPASS) { - result |= MeshPipelineViewLayoutKey::MOTION_VECTOR_PREPASS; + result |= Self::MOTION_VECTOR_PREPASS; } if value.contains(MeshPipelineKey::DEFERRED_PREPASS) { - result |= MeshPipelineViewLayoutKey::DEFERRED_PREPASS; + result |= Self::DEFERRED_PREPASS; } result @@ -128,10 +126,10 @@ impl From for MeshPipelineViewLayoutKey { impl From for MeshPipelineViewLayoutKey { fn from(value: Msaa) -> Self { - let mut result = MeshPipelineViewLayoutKey::empty(); + let mut result = Self::empty(); if value.samples() > 1 { - result |= MeshPipelineViewLayoutKey::MULTISAMPLED; + result |= Self::MULTISAMPLED; } result @@ -140,20 +138,20 @@ impl From for MeshPipelineViewLayoutKey { impl From> for MeshPipelineViewLayoutKey { fn from(value: Option<&ViewPrepassTextures>) -> Self { - let mut result = MeshPipelineViewLayoutKey::empty(); + let mut result = Self::empty(); if let Some(prepass_textures) = value { if prepass_textures.depth.is_some() { - result |= MeshPipelineViewLayoutKey::DEPTH_PREPASS; + result |= Self::DEPTH_PREPASS; } if prepass_textures.normal.is_some() { - result |= MeshPipelineViewLayoutKey::NORMAL_PREPASS; + result |= Self::NORMAL_PREPASS; } if prepass_textures.motion_vectors.is_some() { - result |= MeshPipelineViewLayoutKey::MOTION_VECTOR_PREPASS; + result |= Self::MOTION_VECTOR_PREPASS; } if prepass_textures.deferred.is_some() { - result |= MeshPipelineViewLayoutKey::DEFERRED_PREPASS; + result |= Self::DEFERRED_PREPASS; } } diff --git a/crates/bevy_pbr/src/render/skin.rs b/crates/bevy_pbr/src/render/skin.rs index 86f702ea491d3..bf6bf5a5fccec 100644 --- a/crates/bevy_pbr/src/render/skin.rs +++ b/crates/bevy_pbr/src/render/skin.rs @@ -25,7 +25,7 @@ pub struct SkinIndex { impl SkinIndex { /// Index to be in address space based on the size of a skin uniform. const fn new(start: usize) -> Self { - SkinIndex { + Self { index: (start * std::mem::size_of::()) as u32, } } diff --git a/crates/bevy_pbr/src/ssr/mod.rs b/crates/bevy_pbr/src/ssr/mod.rs index 1ae86b10a1aca..14d003aaf1717 100644 --- a/crates/bevy_pbr/src/ssr/mod.rs +++ b/crates/bevy_pbr/src/ssr/mod.rs @@ -486,10 +486,8 @@ pub fn prepare_ssr_settings( } impl ExtractComponent for ScreenSpaceReflectionsSettings { - type QueryData = Read; - + type QueryData = Read; type QueryFilter = (); - type Out = ScreenSpaceReflectionsUniform; fn extract_component(settings: QueryItem<'_, Self::QueryData>) -> Option { diff --git a/crates/bevy_pbr/src/volumetric_fog/render.rs b/crates/bevy_pbr/src/volumetric_fog/render.rs index de158762d5301..6a8ac2099fbe9 100644 --- a/crates/bevy_pbr/src/volumetric_fog/render.rs +++ b/crates/bevy_pbr/src/volumetric_fog/render.rs @@ -258,7 +258,7 @@ impl FromWorld for VolumetricFogPipeline { render_device.create_bind_group_layout(&*description, &bind_group_layout_entries) }); - VolumetricFogPipeline { + Self { mesh_view_layouts: mesh_view_layouts.clone(), volumetric_view_bind_group_layouts: bind_group_layouts, } @@ -804,9 +804,9 @@ impl VolumetricFogBindGroupLayoutKey { "volumetric lighting view bind group layout ({})", self.iter() .filter_map(|flag| { - if flag == VolumetricFogBindGroupLayoutKey::DENSITY_TEXTURE { + if flag == Self::DENSITY_TEXTURE { Some("density texture") - } else if flag == VolumetricFogBindGroupLayoutKey::MULTISAMPLED { + } else if flag == Self::MULTISAMPLED { Some("multisampled") } else { None diff --git a/crates/bevy_picking/src/input/mod.rs b/crates/bevy_picking/src/input/mod.rs index e3dd9e3695e6d..bc79ee4ef9d38 100644 --- a/crates/bevy_picking/src/input/mod.rs +++ b/crates/bevy_picking/src/input/mod.rs @@ -66,8 +66,8 @@ impl Plugin for InputPlugin { .add_systems( First, ( - mouse::mouse_pick_events.run_if(InputPlugin::is_mouse_enabled), - touch::touch_pick_events.run_if(InputPlugin::is_touch_enabled), + mouse::mouse_pick_events.run_if(Self::is_mouse_enabled), + touch::touch_pick_events.run_if(Self::is_touch_enabled), // IMPORTANT: the commands must be flushed after `touch_pick_events` is run // because we need pointer spawning to happen immediately to prevent issues with // missed events during drag and drop. @@ -78,9 +78,9 @@ impl Plugin for InputPlugin { ) .add_systems( Last, - touch::deactivate_touch_pointers.run_if(InputPlugin::is_touch_enabled), + touch::deactivate_touch_pointers.run_if(Self::is_touch_enabled), ) .register_type::() - .register_type::(); + .register_type::(); } } diff --git a/crates/bevy_picking/src/lib.rs b/crates/bevy_picking/src/lib.rs index ba0ef8eee98fa..908c78a9c324c 100644 --- a/crates/bevy_picking/src/lib.rs +++ b/crates/bevy_picking/src/lib.rs @@ -139,7 +139,7 @@ pub struct PointerBundle { impl PointerBundle { /// Create a new pointer with the provided [`PointerId`](pointer::PointerId). pub fn new(id: pointer::PointerId) -> Self { - PointerBundle { + Self { id, location: pointer::PointerLocation::default(), click: pointer::PointerPress::default(), diff --git a/crates/bevy_picking/src/pointer.rs b/crates/bevy_picking/src/pointer.rs index 3d1991c1ec246..ccf27d57f00f1 100644 --- a/crates/bevy_picking/src/pointer.rs +++ b/crates/bevy_picking/src/pointer.rs @@ -34,19 +34,19 @@ pub enum PointerId { impl PointerId { /// Returns true if the pointer is a touch input. pub fn is_touch(&self) -> bool { - matches!(self, PointerId::Touch(_)) + matches!(self, Self::Touch(_)) } /// Returns true if the pointer is the mouse. pub fn is_mouse(&self) -> bool { - matches!(self, PointerId::Mouse) + matches!(self, Self::Mouse) } /// Returns true if the pointer is a custom input. pub fn is_custom(&self) -> bool { - matches!(self, PointerId::Custom(_)) + matches!(self, Self::Custom(_)) } /// Returns the touch id if the pointer is a touch input. pub fn get_touch_id(&self) -> Option { - if let PointerId::Touch(id) = self { + if let Self::Touch(id) = self { Some(*id) } else { None @@ -131,7 +131,7 @@ pub struct InputPress { impl InputPress { /// Create a new pointer button down event. - pub fn new_down(id: PointerId, button: PointerButton) -> InputPress { + pub fn new_down(id: PointerId, button: PointerButton) -> Self { Self { pointer_id: id, direction: PressDirection::Down, @@ -140,7 +140,7 @@ impl InputPress { } /// Create a new pointer button up event. - pub fn new_up(id: PointerId, button: PointerButton) -> InputPress { + pub fn new_up(id: PointerId, button: PointerButton) -> Self { Self { pointer_id: id, direction: PressDirection::Up, @@ -162,7 +162,7 @@ impl InputPress { /// Receives [`InputPress`] events and updates corresponding [`PointerPress`] components. pub fn receive( - mut events: EventReader, + mut events: EventReader, mut pointers: Query<(&PointerId, &mut PointerPress)>, ) { for input_press_event in events.read() { @@ -202,7 +202,7 @@ pub enum PointerButton { impl PointerButton { /// Iterator over all buttons that a pointer can have. - pub fn iter() -> impl Iterator { + pub fn iter() -> impl Iterator { [Self::Primary, Self::Secondary, Self::Middle].into_iter() } } @@ -238,7 +238,7 @@ pub struct InputMove { impl InputMove { /// Create a new [`InputMove`] event. - pub fn new(id: PointerId, location: Location, delta: Vec2) -> InputMove { + pub fn new(id: PointerId, location: Location, delta: Vec2) -> Self { Self { pointer_id: id, location, @@ -248,7 +248,7 @@ impl InputMove { /// Receives [`InputMove`] events and updates corresponding [`PointerLocation`] components. pub fn receive( - mut events: EventReader, + mut events: EventReader, mut pointers: Query<(&PointerId, &mut PointerLocation)>, ) { for event_pointer in events.read() { diff --git a/crates/bevy_ptr/src/lib.rs b/crates/bevy_ptr/src/lib.rs index 5010c931355b5..92a3628413e15 100644 --- a/crates/bevy_ptr/src/lib.rs +++ b/crates/bevy_ptr/src/lib.rs @@ -129,20 +129,20 @@ impl ConstNonNull { } impl From> for ConstNonNull { - fn from(value: NonNull) -> ConstNonNull { - ConstNonNull(value) + fn from(value: NonNull) -> Self { + Self(value) } } impl<'a, T: ?Sized> From<&'a T> for ConstNonNull { - fn from(value: &'a T) -> ConstNonNull { - ConstNonNull(NonNull::from(value)) + fn from(value: &'a T) -> Self { + Self(NonNull::from(value)) } } impl<'a, T: ?Sized> From<&'a mut T> for ConstNonNull { - fn from(value: &'a mut T) -> ConstNonNull { - ConstNonNull(NonNull::from(value)) + fn from(value: &'a mut T) -> Self { + Self(NonNull::from(value)) } } /// Type-erased borrow of some unknown type chosen when constructing this type. diff --git a/crates/bevy_reflect/derive/src/container_attributes.rs b/crates/bevy_reflect/derive/src/container_attributes.rs index b5f0f906b3bcc..c2114a7560fa3 100644 --- a/crates/bevy_reflect/derive/src/container_attributes.rs +++ b/crates/bevy_reflect/derive/src/container_attributes.rs @@ -65,14 +65,14 @@ impl TraitImpl { /// Update `self` with whichever value is not [`TraitImpl::NotImplemented`]. /// If `other` is [`TraitImpl::NotImplemented`], then `self` is not modified. /// An error is returned if neither value is [`TraitImpl::NotImplemented`]. - pub fn merge(&mut self, other: TraitImpl) -> Result<(), syn::Error> { + pub fn merge(&mut self, other: Self) -> Result<(), syn::Error> { match (&self, other) { - (TraitImpl::NotImplemented, value) => { + (Self::NotImplemented, value) => { *self = value; Ok(()) } - (_, TraitImpl::NotImplemented) => Ok(()), - (_, TraitImpl::Implemented(span) | TraitImpl::Custom(_, span)) => { + (_, Self::NotImplemented) => Ok(()), + (_, Self::Implemented(span) | Self::Custom(_, span)) => { Err(syn::Error::new(span, CONFLICTING_TYPE_DATA_MESSAGE)) } } diff --git a/crates/bevy_reflect/derive/src/field_attributes.rs b/crates/bevy_reflect/derive/src/field_attributes.rs index 5228f80a67cdf..560b6d73435ff 100644 --- a/crates/bevy_reflect/derive/src/field_attributes.rs +++ b/crates/bevy_reflect/derive/src/field_attributes.rs @@ -43,8 +43,8 @@ impl ReflectIgnoreBehavior { /// Returns `true` if the ignoring behavior implies member is included in the reflection API, and false otherwise. pub fn is_active(self) -> bool { match self { - ReflectIgnoreBehavior::None | ReflectIgnoreBehavior::IgnoreSerialization => true, - ReflectIgnoreBehavior::IgnoreAlways => false, + Self::None | Self::IgnoreSerialization => true, + Self::IgnoreAlways => false, } } @@ -85,8 +85,7 @@ pub(crate) struct FieldAttributes { impl FieldAttributes { /// Parse all field attributes marked "reflect" (such as `#[reflect(ignore)]`). pub fn parse_attributes(attrs: &[Attribute]) -> syn::Result { - let mut args = FieldAttributes::default(); - + let mut args = Self::default(); attrs .iter() .filter_map(|attr| { diff --git a/crates/bevy_reflect/derive/src/reflect_value.rs b/crates/bevy_reflect/derive/src/reflect_value.rs index 6faa0e8752d45..ef697be8aa398 100644 --- a/crates/bevy_reflect/derive/src/reflect_value.rs +++ b/crates/bevy_reflect/derive/src/reflect_value.rs @@ -61,7 +61,7 @@ impl ReflectValueDef { attrs }); } - Ok(ReflectValueDef { + Ok(Self { attrs, type_path, generics, diff --git a/crates/bevy_reflect/derive/src/trait_reflection.rs b/crates/bevy_reflect/derive/src/trait_reflection.rs index b8ea651b88492..3ece861a5e168 100644 --- a/crates/bevy_reflect/derive/src/trait_reflection.rs +++ b/crates/bevy_reflect/derive/src/trait_reflection.rs @@ -17,7 +17,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/derive/src/type_path.rs b/crates/bevy_reflect/derive/src/type_path.rs index 3ef92981a33d9..5bd78ef8587e1 100644 --- a/crates/bevy_reflect/derive/src/type_path.rs +++ b/crates/bevy_reflect/derive/src/type_path.rs @@ -87,12 +87,12 @@ impl Parse for NamedTypePathDef { if path.leading_colon.is_none() && custom_path.is_none() { if path.segments.len() == 1 { let ident = path.segments.into_iter().next().unwrap().ident; - Ok(NamedTypePathDef::Primitive(ident)) + Ok(Self::Primitive(ident)) } else { Err(input.error("non-customized paths must start with a double colon (`::`)")) } } else { - Ok(NamedTypePathDef::External { + Ok(Self::External { path, generics, custom_path, diff --git a/crates/bevy_reflect/derive/src/utility.rs b/crates/bevy_reflect/derive/src/utility.rs index 231dc18f2bbbc..43fbc3c321477 100644 --- a/crates/bevy_reflect/derive/src/utility.rs +++ b/crates/bevy_reflect/derive/src/utility.rs @@ -379,7 +379,7 @@ impl StringExpr { /// Appends a [`StringExpr`] to another. /// /// If both expressions are [`StringExpr::Const`] this will use [`concat`] to merge them. - pub fn appended_by(mut self, other: StringExpr) -> Self { + pub fn appended_by(mut self, other: Self) -> Self { if let Self::Const(tokens) = self { if let Self::Const(more) = other { return Self::Const(quote! { @@ -399,12 +399,12 @@ impl StringExpr { impl Default for StringExpr { fn default() -> Self { - StringExpr::from_str("") + Self::from_str("") } } -impl FromIterator for StringExpr { - fn from_iter>(iter: T) -> Self { +impl FromIterator for StringExpr { + fn from_iter>(iter: T) -> Self { let mut iter = iter.into_iter(); match iter.next() { Some(mut expr) => { diff --git a/crates/bevy_reflect/src/array.rs b/crates/bevy_reflect/src/array.rs index 3377a60cd2162..33f8c1354ba1b 100644 --- a/crates/bevy_reflect/src/array.rs +++ b/crates/bevy_reflect/src/array.rs @@ -343,7 +343,7 @@ impl Array for DynamicArray { #[inline] fn clone_dynamic(&self) -> DynamicArray { - DynamicArray { + Self { represented_type: self.represented_type, values: self .values @@ -401,8 +401,8 @@ pub struct ArrayIter<'a> { impl<'a> ArrayIter<'a> { /// Creates a new [`ArrayIter`]. #[inline] - pub const fn new(array: &'a dyn Array) -> ArrayIter { - ArrayIter { array, index: 0 } + pub const fn new(array: &'a dyn Array) -> Self { + Self { array, index: 0 } } } diff --git a/crates/bevy_reflect/src/enums/dynamic_enum.rs b/crates/bevy_reflect/src/enums/dynamic_enum.rs index bf1c1fa6ddb20..91e433a5181c2 100644 --- a/crates/bevy_reflect/src/enums/dynamic_enum.rs +++ b/crates/bevy_reflect/src/enums/dynamic_enum.rs @@ -20,9 +20,9 @@ pub enum DynamicVariant { impl Clone for DynamicVariant { fn clone(&self) -> Self { match self { - DynamicVariant::Unit => DynamicVariant::Unit, - DynamicVariant::Tuple(data) => DynamicVariant::Tuple(data.clone_dynamic()), - DynamicVariant::Struct(data) => DynamicVariant::Struct(data.clone_dynamic()), + Self::Unit => Self::Unit, + Self::Tuple(data) => Self::Tuple(data.clone_dynamic()), + Self::Struct(data) => Self::Struct(data.clone_dynamic()), } } } @@ -165,7 +165,7 @@ impl DynamicEnum { pub fn from_ref(value: &TEnum) -> Self { let type_info = value.get_represented_type_info(); let mut dyn_enum = match value.variant_type() { - VariantType::Unit => DynamicEnum::new_with_index( + VariantType::Unit => Self::new_with_index( value.variant_index(), value.variant_name(), DynamicVariant::Unit, @@ -175,7 +175,7 @@ impl DynamicEnum { for field in value.iter_fields() { data.insert_boxed(field.value().clone_value()); } - DynamicEnum::new_with_index( + Self::new_with_index( value.variant_index(), value.variant_name(), DynamicVariant::Tuple(data), @@ -187,7 +187,7 @@ impl DynamicEnum { let name = field.name().unwrap(); data.insert_boxed(name, field.value().clone_value()); } - DynamicEnum::new_with_index( + Self::new_with_index( value.variant_index(), value.variant_name(), DynamicVariant::Struct(data), diff --git a/crates/bevy_reflect/src/func/closures/dynamic_closure.rs b/crates/bevy_reflect/src/func/closures/dynamic_closure.rs index f49645f70f4a7..e41d40a34c83b 100644 --- a/crates/bevy_reflect/src/func/closures/dynamic_closure.rs +++ b/crates/bevy_reflect/src/func/closures/dynamic_closure.rs @@ -180,7 +180,7 @@ impl From for DynamicClosure<'static> { impl<'env> IntoClosure<'env, ()> for DynamicClosure<'env> { #[inline] - fn into_closure(self) -> DynamicClosure<'env> { + fn into_closure(self) -> Self { self } } diff --git a/crates/bevy_reflect/src/func/closures/dynamic_closure_mut.rs b/crates/bevy_reflect/src/func/closures/dynamic_closure_mut.rs index b85521d939ba1..50e1042bd21f7 100644 --- a/crates/bevy_reflect/src/func/closures/dynamic_closure_mut.rs +++ b/crates/bevy_reflect/src/func/closures/dynamic_closure_mut.rs @@ -221,7 +221,7 @@ impl<'env> From> for DynamicClosureMut<'env> { impl<'env> IntoClosureMut<'env, ()> for DynamicClosureMut<'env> { #[inline] - fn into_closure_mut(self) -> DynamicClosureMut<'env> { + fn into_closure_mut(self) -> Self { self } } diff --git a/crates/bevy_reflect/src/func/into_function.rs b/crates/bevy_reflect/src/func/into_function.rs index 965661aa7ac9a..6d3802a7cba6e 100644 --- a/crates/bevy_reflect/src/func/into_function.rs +++ b/crates/bevy_reflect/src/func/into_function.rs @@ -96,8 +96,8 @@ mod tests { struct Foo(i32); impl Foo { - pub fn add(&self, other: &Foo) -> Foo { - Foo(self.0 + other.0) + pub fn add(&self, other: &Self) -> Self { + Self(self.0 + other.0) } } diff --git a/crates/bevy_reflect/src/impls/smallvec.rs b/crates/bevy_reflect/src/impls/smallvec.rs index 6addd3a9468e7..e556a1f88818c 100644 --- a/crates/bevy_reflect/src/impls/smallvec.rs +++ b/crates/bevy_reflect/src/impls/smallvec.rs @@ -15,7 +15,7 @@ where T::Item: FromReflect + MaybeTyped + TypePath, { fn get(&self, index: usize) -> Option<&dyn PartialReflect> { - if index < SmallVec::len(self) { + if index < Self::len(self) { Some(&self[index] as &dyn PartialReflect) } else { None @@ -23,7 +23,7 @@ where } fn get_mut(&mut self, index: usize) -> Option<&mut dyn PartialReflect> { - if index < SmallVec::len(self) { + if index < Self::len(self) { Some(&mut self[index] as &mut dyn PartialReflect) } else { None @@ -39,7 +39,7 @@ where ) }) }); - SmallVec::insert(self, index, value); + Self::insert(self, index, value); } fn remove(&mut self, index: usize) -> Box { @@ -55,7 +55,7 @@ where ) }) }); - SmallVec::push(self, value); + Self::push(self, value); } fn pop(&mut self) -> Option> { @@ -64,7 +64,7 @@ where } fn len(&self) -> usize { - >::len(self) + ::len(self) } fn iter(&self) -> ListIter { @@ -211,8 +211,8 @@ where T::Item: FromReflect + MaybeTyped + TypePath, { 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 } } diff --git a/crates/bevy_reflect/src/lib.rs b/crates/bevy_reflect/src/lib.rs index 87e770483529e..78aa9cdf57297 100644 --- a/crates/bevy_reflect/src/lib.rs +++ b/crates/bevy_reflect/src/lib.rs @@ -1833,7 +1833,7 @@ mod tests { impl Default for TestStruct { fn default() -> Self { - TestStruct { + Self { _hrl: |input| input, } } diff --git a/crates/bevy_reflect/src/list.rs b/crates/bevy_reflect/src/list.rs index 3a29c5733e659..88bc0435f2136 100644 --- a/crates/bevy_reflect/src/list.rs +++ b/crates/bevy_reflect/src/list.rs @@ -251,7 +251,7 @@ impl List for DynamicList { } fn push(&mut self, value: Box) { - DynamicList::push_box(self, value); + Self::push_box(self, value); } fn pop(&mut self) -> Option> { @@ -271,7 +271,7 @@ impl List for DynamicList { } fn clone_dynamic(&self) -> DynamicList { - DynamicList { + Self { represented_type: self.represented_type, values: self .values @@ -422,7 +422,7 @@ pub struct ListIter<'a> { impl<'a> ListIter<'a> { /// Creates a new [`ListIter`]. #[inline] - pub const fn new(list: &'a dyn List) -> ListIter { + pub const fn new(list: &'a dyn List) -> Self { ListIter { list, index: 0 } } } diff --git a/crates/bevy_reflect/src/map.rs b/crates/bevy_reflect/src/map.rs index b619a091eff2c..0dd19ffd5577c 100644 --- a/crates/bevy_reflect/src/map.rs +++ b/crates/bevy_reflect/src/map.rs @@ -321,7 +321,7 @@ impl Map for DynamicMap { } fn clone_dynamic(&self) -> DynamicMap { - DynamicMap { + Self { represented_type: self.represented_type, values: self .values @@ -457,8 +457,8 @@ pub struct MapIter<'a> { impl<'a> MapIter<'a> { /// Creates a new [`MapIter`]. #[inline] - pub const fn new(map: &'a dyn Map) -> MapIter { - MapIter { map, index: 0 } + pub const fn new(map: &'a dyn Map) -> Self { + Self { map, index: 0 } } } diff --git a/crates/bevy_reflect/src/path/mod.rs b/crates/bevy_reflect/src/path/mod.rs index c3d8ccfa2de21..d7a37337c6986 100644 --- a/crates/bevy_reflect/src/path/mod.rs +++ b/crates/bevy_reflect/src/path/mod.rs @@ -297,7 +297,7 @@ pub struct OffsetAccess { impl From> for OffsetAccess { fn from(access: Access<'static>) -> Self { - OffsetAccess { + Self { access, offset: None, } @@ -451,17 +451,17 @@ impl<'a> ReflectPath<'a> for &'a ParsedPath { } impl From> for ParsedPath { fn from(value: Vec) -> Self { - ParsedPath(value) + Self(value) } } impl From<[OffsetAccess; N]> for ParsedPath { fn from(value: [OffsetAccess; N]) -> Self { - ParsedPath(value.to_vec()) + Self(value.to_vec()) } } impl From>> for ParsedPath { fn from(value: Vec>) -> Self { - ParsedPath( + Self( value .into_iter() .map(|access| OffsetAccess { diff --git a/crates/bevy_reflect/src/reflect.rs b/crates/bevy_reflect/src/reflect.rs index 0456d209c7ad9..44a87980606c7 100644 --- a/crates/bevy_reflect/src/reflect.rs +++ b/crates/bevy_reflect/src/reflect.rs @@ -162,15 +162,15 @@ pub enum ReflectKind { impl std::fmt::Display for ReflectKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - ReflectKind::Struct => f.pad("struct"), - ReflectKind::TupleStruct => f.pad("tuple struct"), - ReflectKind::Tuple => f.pad("tuple"), - ReflectKind::List => f.pad("list"), - ReflectKind::Array => f.pad("array"), - ReflectKind::Map => f.pad("map"), - ReflectKind::Set => f.pad("set"), - ReflectKind::Enum => f.pad("enum"), - ReflectKind::Value => f.pad("value"), + Self::Struct => f.pad("struct"), + Self::TupleStruct => f.pad("tuple struct"), + Self::Tuple => f.pad("tuple"), + Self::List => f.pad("list"), + Self::Array => f.pad("array"), + Self::Map => f.pad("map"), + Self::Set => f.pad("set"), + Self::Enum => f.pad("enum"), + Self::Value => f.pad("value"), } } } diff --git a/crates/bevy_reflect/src/set.rs b/crates/bevy_reflect/src/set.rs index 08bcf4c163ece..6286f04057225 100644 --- a/crates/bevy_reflect/src/set.rs +++ b/crates/bevy_reflect/src/set.rs @@ -237,8 +237,7 @@ impl Set for DynamicSet { Self::internal_hash(boxed.as_ref()) }); }); - - DynamicSet { + Self { represented_type: self.represented_type, hash_table, } diff --git a/crates/bevy_reflect/src/std_traits.rs b/crates/bevy_reflect/src/std_traits.rs index 2f9b84735e758..ac33b68b7bd7e 100644 --- a/crates/bevy_reflect/src/std_traits.rs +++ b/crates/bevy_reflect/src/std_traits.rs @@ -16,7 +16,7 @@ impl ReflectDefault { impl FromType for ReflectDefault { fn from_type() -> Self { - ReflectDefault { + Self { default: || Box::::default(), } } diff --git a/crates/bevy_reflect/src/struct_trait.rs b/crates/bevy_reflect/src/struct_trait.rs index 52dce37f91b94..e0dd4cba41288 100644 --- a/crates/bevy_reflect/src/struct_trait.rs +++ b/crates/bevy_reflect/src/struct_trait.rs @@ -391,7 +391,7 @@ impl Struct for DynamicStruct { } fn clone_dynamic(&self) -> DynamicStruct { - DynamicStruct { + Self { represented_type: self.get_represented_type_info(), 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 b63a5f6c777e8..a2e4d44527ef4 100644 --- a/crates/bevy_reflect/src/tuple.rs +++ b/crates/bevy_reflect/src/tuple.rs @@ -288,7 +288,7 @@ impl Tuple for DynamicTuple { #[inline] fn clone_dynamic(&self) -> DynamicTuple { - DynamicTuple { + Self { represented_type: self.represented_type, fields: self .fields diff --git a/crates/bevy_reflect/src/tuple_struct.rs b/crates/bevy_reflect/src/tuple_struct.rs index dd923e47be795..e275cd65c7d91 100644 --- a/crates/bevy_reflect/src/tuple_struct.rs +++ b/crates/bevy_reflect/src/tuple_struct.rs @@ -296,7 +296,7 @@ impl TupleStruct for DynamicTupleStruct { } fn clone_dynamic(&self) -> DynamicTupleStruct { - DynamicTupleStruct { + Self { represented_type: self.represented_type, fields: self .fields diff --git a/crates/bevy_reflect/src/type_registry.rs b/crates/bevy_reflect/src/type_registry.rs index 1263b0bbed523..f164b7c8ffb04 100644 --- a/crates/bevy_reflect/src/type_registry.rs +++ b/crates/bevy_reflect/src/type_registry.rs @@ -527,8 +527,7 @@ impl Clone for TypeRegistration { for (id, type_data) in &self.data { data.insert(*id, (*type_data).clone_type_data()); } - - TypeRegistration { + Self { data, type_info: self.type_info, } @@ -579,7 +578,7 @@ pub struct ReflectSerialize { impl FromType for ReflectSerialize { fn from_type() -> Self { - ReflectSerialize { + Self { get_serializable: |value| { value .downcast_ref::() @@ -632,7 +631,7 @@ impl ReflectDeserialize { impl Deserialize<'a> + Reflect> FromType for ReflectDeserialize { fn from_type() -> Self { - ReflectDeserialize { + Self { func: |deserializer| Ok(Box::new(T::deserialize(deserializer)?)), } } @@ -730,7 +729,7 @@ impl ReflectFromPtr { #[allow(unsafe_code)] impl FromType for ReflectFromPtr { fn from_type() -> Self { - ReflectFromPtr { + Self { type_id: TypeId::of::(), from_ptr: |ptr| { // SAFETY: `from_ptr_mut` is either called in `ReflectFromPtr::as_reflect` diff --git a/crates/bevy_render/macros/src/as_bind_group.rs b/crates/bevy_render/macros/src/as_bind_group.rs index 25887495f41bf..b9c4b9363611f 100644 --- a/crates/bevy_render/macros/src/as_bind_group.rs +++ b/crates/bevy_render/macros/src/as_bind_group.rs @@ -657,9 +657,9 @@ impl VisibilityFlags { impl ShaderStageVisibility { fn hygienic_quote(&self, path: &proc_macro2::TokenStream) -> proc_macro2::TokenStream { match self { - ShaderStageVisibility::All => quote! { #path::ShaderStages::all() }, - ShaderStageVisibility::None => quote! { #path::ShaderStages::NONE }, - ShaderStageVisibility::Flags(flags) => { + Self::All => quote! { #path::ShaderStages::all() }, + Self::None => quote! { #path::ShaderStages::NONE }, + Self::Flags(flags) => { let mut quoted = Vec::new(); if flags.vertex { @@ -751,12 +751,12 @@ enum BindingTextureSampleType { impl ToTokens for BindingTextureDimension { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { tokens.extend(match self { - BindingTextureDimension::D1 => quote! { TextureViewDimension::D1 }, - BindingTextureDimension::D2 => quote! { TextureViewDimension::D2 }, - BindingTextureDimension::D2Array => quote! { TextureViewDimension::D2Array }, - BindingTextureDimension::Cube => quote! { TextureViewDimension::Cube }, - BindingTextureDimension::CubeArray => quote! { TextureViewDimension::CubeArray }, - BindingTextureDimension::D3 => quote! { TextureViewDimension::D3 }, + Self::D1 => quote! { TextureViewDimension::D1 }, + Self::D2 => quote! { TextureViewDimension::D2 }, + Self::D2Array => quote! { TextureViewDimension::D2Array }, + Self::Cube => quote! { TextureViewDimension::Cube }, + Self::CubeArray => quote! { TextureViewDimension::CubeArray }, + Self::D3 => quote! { TextureViewDimension::D3 }, }); } } @@ -764,12 +764,12 @@ impl ToTokens for BindingTextureDimension { impl ToTokens for BindingTextureSampleType { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { tokens.extend(match self { - BindingTextureSampleType::Float { filterable } => { + Self::Float { filterable } => { quote! { TextureSampleType::Float { filterable: #filterable } } } - BindingTextureSampleType::Depth => quote! { TextureSampleType::Depth }, - BindingTextureSampleType::Sint => quote! { TextureSampleType::Sint }, - BindingTextureSampleType::Uint => quote! { TextureSampleType::Uint }, + Self::Depth => quote! { TextureSampleType::Depth }, + Self::Sint => quote! { TextureSampleType::Sint }, + Self::Uint => quote! { TextureSampleType::Uint }, }); } } @@ -783,7 +783,7 @@ struct TextureAttrs { impl Default for BindingTextureSampleType { fn default() -> Self { - BindingTextureSampleType::Float { filterable: true } + Self::Float { filterable: true } } } @@ -1004,9 +1004,9 @@ enum SamplerBindingType { impl ToTokens for SamplerBindingType { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { tokens.extend(match self { - SamplerBindingType::Filtering => quote! { SamplerBindingType::Filtering }, - SamplerBindingType::NonFiltering => quote! { SamplerBindingType::NonFiltering }, - SamplerBindingType::Comparison => quote! { SamplerBindingType::Comparison }, + Self::Filtering => quote! { SamplerBindingType::Filtering }, + Self::NonFiltering => quote! { SamplerBindingType::NonFiltering }, + Self::Comparison => quote! { SamplerBindingType::Comparison }, }); } } diff --git a/crates/bevy_render/src/batching/gpu_preprocessing.rs b/crates/bevy_render/src/batching/gpu_preprocessing.rs index b03f4ba1843ad..533c5eef32c6d 100644 --- a/crates/bevy_render/src/batching/gpu_preprocessing.rs +++ b/crates/bevy_render/src/batching/gpu_preprocessing.rs @@ -208,8 +208,8 @@ pub struct IndirectParametersBuffer(pub BufferVec); impl IndirectParametersBuffer { /// Creates the indirect parameters buffer. - pub fn new() -> IndirectParametersBuffer { - IndirectParametersBuffer(BufferVec::new( + pub fn new() -> Self { + Self(BufferVec::new( BufferUsages::STORAGE | BufferUsages::INDIRECT, )) } @@ -236,16 +236,16 @@ impl FromWorld for GpuPreprocessingSupport { ) }) { - GpuPreprocessingSupport::None + Self::None } else if !device .features() .contains(Features::INDIRECT_FIRST_INSTANCE) || !adapter.get_downlevel_capabilities().flags.contains( DownlevelFlags::VERTEX_AND_INSTANCE_INDEX_RESPECTS_RESPECTIVE_FIRST_VALUE_IN_INDIRECT_DRAW) { - GpuPreprocessingSupport::PreprocessingOnly + Self::PreprocessingOnly } else { - GpuPreprocessingSupport::Culling + Self::Culling } } } @@ -257,7 +257,7 @@ where { /// Creates new buffers. pub fn new() -> Self { - BatchedInstanceBuffers { + Self { data_buffer: UninitBufferVec::new(BufferUsages::STORAGE), work_item_buffers: EntityHashMap::default(), current_input_buffer: RawBufferVec::new(BufferUsages::STORAGE), diff --git a/crates/bevy_render/src/batching/mod.rs b/crates/bevy_render/src/batching/mod.rs index 6287911e06249..6afad6e5ed7c2 100644 --- a/crates/bevy_render/src/batching/mod.rs +++ b/crates/bevy_render/src/batching/mod.rs @@ -51,7 +51,7 @@ struct BatchMeta { impl BatchMeta { fn new(item: &impl CachedRenderPipelinePhaseItem, user_data: T) -> Self { - BatchMeta { + Self { pipeline_id: item.cached_pipeline(), draw_function_id: item.draw_function(), dynamic_offset: item.extra_index().as_dynamic_offset(), diff --git a/crates/bevy_render/src/batching/no_gpu_preprocessing.rs b/crates/bevy_render/src/batching/no_gpu_preprocessing.rs index 51176cb42b240..cb12202b56ab0 100644 --- a/crates/bevy_render/src/batching/no_gpu_preprocessing.rs +++ b/crates/bevy_render/src/batching/no_gpu_preprocessing.rs @@ -31,7 +31,7 @@ where { /// Creates a new buffer. pub fn new(render_device: &RenderDevice) -> Self { - BatchedInstanceBuffer(GpuArrayBuffer::new(render_device)) + Self(GpuArrayBuffer::new(render_device)) } /// Returns the binding of the buffer that contains the per-instance data. diff --git a/crates/bevy_render/src/camera/camera.rs b/crates/bevy_render/src/camera/camera.rs index 4f533345b94f7..13d3e52b54bc1 100644 --- a/crates/bevy_render/src/camera/camera.rs +++ b/crates/bevy_render/src/camera/camera.rs @@ -552,7 +552,7 @@ pub enum CameraOutputMode { impl Default for CameraOutputMode { fn default() -> Self { - CameraOutputMode::Write { + Self::Write { blend_state: None, clear_color: ClearColorConfig::Default, } @@ -621,11 +621,11 @@ impl RenderTarget { /// Normalize the render target down to a more concrete value, mostly used for equality comparisons. pub fn normalize(&self, primary_window: Option) -> Option { match self { - RenderTarget::Window(window_ref) => window_ref + Self::Window(window_ref) => window_ref .normalize(primary_window) .map(NormalizedRenderTarget::Window), - RenderTarget::Image(handle) => Some(NormalizedRenderTarget::Image(handle.clone())), - RenderTarget::TextureView(id) => Some(NormalizedRenderTarget::TextureView(*id)), + Self::Image(handle) => Some(NormalizedRenderTarget::Image(handle.clone())), + Self::TextureView(id) => Some(NormalizedRenderTarget::TextureView(*id)), } } @@ -648,15 +648,11 @@ impl NormalizedRenderTarget { manual_texture_views: &'a ManualTextureViews, ) -> Option<&'a TextureView> { match self { - NormalizedRenderTarget::Window(window_ref) => windows + Self::Window(window_ref) => windows .get(&window_ref.entity()) .and_then(|window| window.swap_chain_texture_view.as_ref()), - NormalizedRenderTarget::Image(image_handle) => { - images.get(image_handle).map(|image| &image.texture_view) - } - NormalizedRenderTarget::TextureView(id) => { - manual_texture_views.get(id).map(|tex| &tex.texture_view) - } + Self::Image(image_handle) => images.get(image_handle).map(|image| &image.texture_view), + Self::TextureView(id) => manual_texture_views.get(id).map(|tex| &tex.texture_view), } } @@ -668,15 +664,11 @@ impl NormalizedRenderTarget { manual_texture_views: &'a ManualTextureViews, ) -> Option { match self { - NormalizedRenderTarget::Window(window_ref) => windows + Self::Window(window_ref) => windows .get(&window_ref.entity()) .and_then(|window| window.swap_chain_texture_format), - NormalizedRenderTarget::Image(image_handle) => { - images.get(image_handle).map(|image| image.texture_format) - } - NormalizedRenderTarget::TextureView(id) => { - manual_texture_views.get(id).map(|tex| tex.format) - } + Self::Image(image_handle) => images.get(image_handle).map(|image| image.texture_format), + Self::TextureView(id) => manual_texture_views.get(id).map(|tex| tex.format), } } @@ -687,26 +679,24 @@ impl NormalizedRenderTarget { manual_texture_views: &ManualTextureViews, ) -> Option { match self { - NormalizedRenderTarget::Window(window_ref) => resolutions + Self::Window(window_ref) => resolutions .into_iter() .find(|(entity, _)| *entity == window_ref.entity()) .map(|(_, window)| RenderTargetInfo { physical_size: window.physical_size(), scale_factor: window.resolution.scale_factor(), }), - NormalizedRenderTarget::Image(image_handle) => { + Self::Image(image_handle) => { let image = images.get(image_handle)?; Some(RenderTargetInfo { physical_size: image.size(), scale_factor: 1.0, }) } - NormalizedRenderTarget::TextureView(id) => { - manual_texture_views.get(id).map(|tex| RenderTargetInfo { - physical_size: tex.size, - scale_factor: 1.0, - }) - } + Self::TextureView(id) => manual_texture_views.get(id).map(|tex| RenderTargetInfo { + physical_size: tex.size, + scale_factor: 1.0, + }), } } @@ -717,13 +707,9 @@ impl NormalizedRenderTarget { changed_image_handles: &HashSet<&AssetId>, ) -> bool { match self { - NormalizedRenderTarget::Window(window_ref) => { - changed_window_ids.contains(&window_ref.entity()) - } - NormalizedRenderTarget::Image(image_handle) => { - changed_image_handles.contains(&image_handle.id()) - } - NormalizedRenderTarget::TextureView(_) => true, + Self::Window(window_ref) => changed_window_ids.contains(&window_ref.entity()), + Self::Image(image_handle) => changed_image_handles.contains(&image_handle.id()), + Self::TextureView(_) => true, } } } diff --git a/crates/bevy_render/src/camera/projection.rs b/crates/bevy_render/src/camera/projection.rs index 0a6c3ca00afab..d04d320bc5507 100644 --- a/crates/bevy_render/src/camera/projection.rs +++ b/crates/bevy_render/src/camera/projection.rs @@ -119,36 +119,36 @@ impl From for Projection { impl CameraProjection for Projection { fn get_clip_from_view(&self) -> Mat4 { match self { - Projection::Perspective(projection) => projection.get_clip_from_view(), - Projection::Orthographic(projection) => projection.get_clip_from_view(), + Self::Perspective(projection) => projection.get_clip_from_view(), + Self::Orthographic(projection) => projection.get_clip_from_view(), } } fn update(&mut self, width: f32, height: f32) { match self { - Projection::Perspective(projection) => projection.update(width, height), - Projection::Orthographic(projection) => projection.update(width, height), + Self::Perspective(projection) => projection.update(width, height), + Self::Orthographic(projection) => projection.update(width, height), } } fn far(&self) -> f32 { match self { - Projection::Perspective(projection) => projection.far(), - Projection::Orthographic(projection) => projection.far(), + Self::Perspective(projection) => projection.far(), + Self::Orthographic(projection) => projection.far(), } } fn get_frustum_corners(&self, z_near: f32, z_far: f32) -> [Vec3A; 8] { match self { - Projection::Perspective(projection) => projection.get_frustum_corners(z_near, z_far), - Projection::Orthographic(projection) => projection.get_frustum_corners(z_near, z_far), + Self::Perspective(projection) => projection.get_frustum_corners(z_near, z_far), + Self::Orthographic(projection) => projection.get_frustum_corners(z_near, z_far), } } } impl Default for Projection { fn default() -> Self { - Projection::Perspective(Default::default()) + Self::Perspective(Default::default()) } } @@ -218,7 +218,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, @@ -264,34 +264,34 @@ pub enum ScalingMode { } impl Mul for ScalingMode { - type Output = ScalingMode; + type Output = Self; /// Scale the `ScalingMode`. For example, multiplying by 2 makes the viewport twice as large. - fn mul(self, rhs: f32) -> ScalingMode { + fn mul(self, rhs: f32) -> Self { match self { - ScalingMode::Fixed { width, height } => ScalingMode::Fixed { + Self::Fixed { width, height } => Self::Fixed { width: width * rhs, height: height * rhs, }, - ScalingMode::WindowSize(pixels_per_world_unit) => { - ScalingMode::WindowSize(pixels_per_world_unit / rhs) + Self::WindowSize(pixels_per_world_unit) => { + Self::WindowSize(pixels_per_world_unit / rhs) } - ScalingMode::AutoMin { + Self::AutoMin { min_width, min_height, - } => ScalingMode::AutoMin { + } => Self::AutoMin { min_width: min_width * rhs, min_height: min_height * rhs, }, - ScalingMode::AutoMax { + Self::AutoMax { max_width, max_height, - } => ScalingMode::AutoMax { + } => Self::AutoMax { max_width: max_width * rhs, max_height: max_height * rhs, }, - ScalingMode::FixedVertical(size) => ScalingMode::FixedVertical(size * rhs), - ScalingMode::FixedHorizontal(size) => ScalingMode::FixedHorizontal(size * rhs), + Self::FixedVertical(size) => Self::FixedVertical(size * rhs), + Self::FixedHorizontal(size) => Self::FixedHorizontal(size * rhs), } } } @@ -303,10 +303,10 @@ impl MulAssign for ScalingMode { } impl Div for ScalingMode { - type Output = ScalingMode; + type Output = Self; /// Scale the `ScalingMode`. For example, dividing by 2 makes the viewport half as large. - fn div(self, rhs: f32) -> ScalingMode { + fn div(self, rhs: f32) -> Self { self * (1.0 / rhs) } } @@ -481,7 +481,7 @@ impl CameraProjection for OrthographicProjection { impl Default for OrthographicProjection { fn default() -> Self { - OrthographicProjection { + Self { scale: 1.0, near: 0.0, far: 1000.0, diff --git a/crates/bevy_render/src/diagnostic/internal.rs b/crates/bevy_render/src/diagnostic/internal.rs index 297e09863101b..0b55e29b12404 100644 --- a/crates/bevy_render/src/diagnostic/internal.rs +++ b/crates/bevy_render/src/diagnostic/internal.rs @@ -43,16 +43,14 @@ pub struct DiagnosticsRecorder(WgpuWrapper); impl DiagnosticsRecorder { /// Creates the new `DiagnosticsRecorder`. - pub fn new(device: &RenderDevice, queue: &Queue) -> DiagnosticsRecorder { + pub fn new(device: &RenderDevice, queue: &Queue) -> Self { let features = device.features(); - let timestamp_period_ns = if features.contains(Features::TIMESTAMP_QUERY) { queue.get_timestamp_period() } else { 0.0 }; - - DiagnosticsRecorder(WgpuWrapper::new(DiagnosticsRecorderInternal { + Self(WgpuWrapper::new(DiagnosticsRecorderInternal { timestamp_period_ns, features, current_frame: Mutex::new(FrameData::new(device, features)), @@ -174,7 +172,7 @@ struct FrameData { } impl FrameData { - fn new(device: &RenderDevice, features: Features) -> FrameData { + fn new(device: &RenderDevice, features: Features) -> Self { let wgpu_device = device.wgpu_device(); let mut buffer_size = 0; @@ -221,7 +219,7 @@ impl FrameData { (None, None) }; - FrameData { + Self { timestamps_query_set, num_timestamps: 0, supports_timestamps_inside_passes: features @@ -609,7 +607,7 @@ pub trait WriteTimestamp { impl WriteTimestamp for CommandEncoder { fn write_timestamp(&mut self, query_set: &QuerySet, index: u32) { - CommandEncoder::write_timestamp(self, query_set, index); + Self::write_timestamp(self, query_set, index); } } diff --git a/crates/bevy_render/src/extract_component.rs b/crates/bevy_render/src/extract_component.rs index 4b327cf6af3e8..f99610e902f7d 100644 --- a/crates/bevy_render/src/extract_component.rs +++ b/crates/bevy_render/src/extract_component.rs @@ -195,9 +195,9 @@ impl Plugin for ExtractComponentPlugin { } impl ExtractComponent for Handle { - type QueryData = Read>; + type QueryData = Read; type QueryFilter = (); - type Out = Handle; + type Out = Self; #[inline] fn extract_component(handle: QueryItem<'_, Self::QueryData>) -> Option { diff --git a/crates/bevy_render/src/mesh/allocator.rs b/crates/bevy_render/src/mesh/allocator.rs index 218e19c475a7b..e7b9d6c2c625a 100644 --- a/crates/bevy_render/src/mesh/allocator.rs +++ b/crates/bevy_render/src/mesh/allocator.rs @@ -845,11 +845,11 @@ impl GeneralSlab { settings: &MeshAllocatorSettings, layout: ElementLayout, data_slot_count: u32, - ) -> GeneralSlab { + ) -> Self { let slab_slot_capacity = (settings.min_slab_size.div_ceil(layout.slot_size()) as u32) .max(offset_allocator::ext::min_allocator_size(data_slot_count)); - let mut new_slab = GeneralSlab { + let mut new_slab = Self { allocator: Allocator::new(slab_slot_capacity), buffer: None, resident_allocations: HashMap::new(), @@ -940,8 +940,8 @@ impl GeneralSlab { impl ElementLayout { /// Creates an [`ElementLayout`] for mesh data of the given class (vertex or /// index) with the given byte size. - fn new(class: ElementClass, size: u64) -> ElementLayout { - ElementLayout { + fn new(class: ElementClass, size: u64) -> Self { + Self { class, size, // Make sure that slot boundaries begin and end on @@ -956,13 +956,10 @@ impl ElementLayout { /// Creates the appropriate [`ElementLayout`] for the given mesh's vertex /// data. - fn vertex( - mesh_vertex_buffer_layouts: &mut MeshVertexBufferLayouts, - mesh: &Mesh, - ) -> ElementLayout { + fn vertex(mesh_vertex_buffer_layouts: &mut MeshVertexBufferLayouts, mesh: &Mesh) -> Self { let mesh_vertex_buffer_layout = mesh.get_mesh_vertex_buffer_layout(mesh_vertex_buffer_layouts); - ElementLayout::new( + Self::new( ElementClass::Vertex, mesh_vertex_buffer_layout.0.layout().array_stride, ) @@ -970,12 +967,12 @@ impl ElementLayout { /// Creates the appropriate [`ElementLayout`] for the given mesh's index /// data. - fn index(mesh: &Mesh) -> Option { + fn index(mesh: &Mesh) -> Option { let size = match mesh.indices()? { Indices::U16(_) => 2, Indices::U32(_) => 4, }; - Some(ElementLayout::new(ElementClass::Index, size)) + Some(Self::new(ElementClass::Index, size)) } } diff --git a/crates/bevy_render/src/mesh/mesh/mod.rs b/crates/bevy_render/src/mesh/mesh/mod.rs index 507084df1517a..3cec50f3c44f2 100644 --- a/crates/bevy_render/src/mesh/mesh/mod.rs +++ b/crates/bevy_render/src/mesh/mesh/mod.rs @@ -206,7 +206,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, asset_usage: RenderAssetUsages) -> Self { - Mesh { + Self { primitive_topology, attributes: Default::default(), indices: None, @@ -649,7 +649,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`"); @@ -660,7 +660,7 @@ impl Mesh { .flat_map(|normal| [normal; 3]) .collect(); - self.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normals); + self.insert_attribute(Self::ATTRIBUTE_NORMAL, normals); } /// Calculates the [`Mesh::ATTRIBUTE_NORMAL`] of an indexed mesh, smoothing normals for shared @@ -685,7 +685,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`"); @@ -716,7 +716,7 @@ impl Mesh { } } - self.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normals); + self.insert_attribute(Self::ATTRIBUTE_NORMAL, normals); } /// Consumes the mesh and returns a mesh with calculated [`Mesh::ATTRIBUTE_NORMAL`]. @@ -768,7 +768,7 @@ impl Mesh { /// Requires a [`PrimitiveTopology::TriangleList`] topology and the [`Mesh::ATTRIBUTE_POSITION`], [`Mesh::ATTRIBUTE_NORMAL`] and [`Mesh::ATTRIBUTE_UV_0`] attributes set. pub fn generate_tangents(&mut self) -> Result<(), GenerateTangentsError> { let tangents = generate_tangents_for_mesh(self)?; - self.insert_attribute(Mesh::ATTRIBUTE_TANGENT, tangents); + self.insert_attribute(Self::ATTRIBUTE_TANGENT, tangents); Ok(()) } @@ -779,7 +779,7 @@ impl Mesh { /// (Alternatively, you can use [`Mesh::generate_tangents`] to mutate an existing mesh in-place) /// /// Requires a [`PrimitiveTopology::TriangleList`] topology and the [`Mesh::ATTRIBUTE_POSITION`], [`Mesh::ATTRIBUTE_NORMAL`] and [`Mesh::ATTRIBUTE_UV_0`] attributes set. - pub fn with_generated_tangents(mut self) -> Result { + pub fn with_generated_tangents(mut self) -> Result { self.generate_tangents()?; Ok(self) } @@ -795,12 +795,12 @@ impl Mesh { /// Panics if the vertex attribute values of `other` are incompatible with `self`. /// For example, [`VertexAttributeValues::Float32`] is incompatible with [`VertexAttributeValues::Float32x3`]. #[allow(clippy::match_same_arms)] - pub fn merge(&mut self, other: &Mesh) { + pub fn merge(&mut self, other: &Self) { use VertexAttributeValues::*; // The indices of `other` should start after the last vertex of `self`. let index_offset = self - .attribute(Mesh::ATTRIBUTE_POSITION) + .attribute(Self::ATTRIBUTE_POSITION) .get_or_insert(&VertexAttributeValues::Float32x3(Vec::default())) .len(); @@ -885,7 +885,7 @@ impl Mesh { ); if let Some(VertexAttributeValues::Float32x3(ref mut positions)) = - self.attribute_mut(Mesh::ATTRIBUTE_POSITION) + self.attribute_mut(Self::ATTRIBUTE_POSITION) { // Apply scale, rotation, and translation to vertex positions positions @@ -902,7 +902,7 @@ impl Mesh { } if let Some(VertexAttributeValues::Float32x3(ref mut normals)) = - self.attribute_mut(Mesh::ATTRIBUTE_NORMAL) + self.attribute_mut(Self::ATTRIBUTE_NORMAL) { // Transform normals, taking into account non-uniform scaling and rotation normals.iter_mut().for_each(|normal| { @@ -913,7 +913,7 @@ impl Mesh { } if let Some(VertexAttributeValues::Float32x3(ref mut tangents)) = - self.attribute_mut(Mesh::ATTRIBUTE_TANGENT) + self.attribute_mut(Self::ATTRIBUTE_TANGENT) { // Transform tangents, taking into account non-uniform scaling and rotation tangents.iter_mut().for_each(|tangent| { @@ -940,7 +940,7 @@ impl Mesh { } if let Some(VertexAttributeValues::Float32x3(ref mut positions)) = - self.attribute_mut(Mesh::ATTRIBUTE_POSITION) + self.attribute_mut(Self::ATTRIBUTE_POSITION) { // Apply translation to vertex positions positions @@ -962,7 +962,7 @@ impl Mesh { /// [`Aabb`] of entities with modified mesh are not updated automatically. pub fn rotate_by(&mut self, rotation: Quat) { if let Some(VertexAttributeValues::Float32x3(ref mut positions)) = - self.attribute_mut(Mesh::ATTRIBUTE_POSITION) + self.attribute_mut(Self::ATTRIBUTE_POSITION) { // Apply rotation to vertex positions positions @@ -976,7 +976,7 @@ impl Mesh { } if let Some(VertexAttributeValues::Float32x3(ref mut normals)) = - self.attribute_mut(Mesh::ATTRIBUTE_NORMAL) + self.attribute_mut(Self::ATTRIBUTE_NORMAL) { // Transform normals normals.iter_mut().for_each(|normal| { @@ -985,7 +985,7 @@ impl Mesh { } if let Some(VertexAttributeValues::Float32x3(ref mut tangents)) = - self.attribute_mut(Mesh::ATTRIBUTE_TANGENT) + self.attribute_mut(Self::ATTRIBUTE_TANGENT) { // Transform tangents tangents.iter_mut().for_each(|tangent| { @@ -1014,7 +1014,7 @@ impl Mesh { ); if let Some(VertexAttributeValues::Float32x3(ref mut positions)) = - self.attribute_mut(Mesh::ATTRIBUTE_POSITION) + self.attribute_mut(Self::ATTRIBUTE_POSITION) { // Apply scale to vertex positions positions @@ -1028,7 +1028,7 @@ impl Mesh { } if let Some(VertexAttributeValues::Float32x3(ref mut normals)) = - self.attribute_mut(Mesh::ATTRIBUTE_NORMAL) + self.attribute_mut(Self::ATTRIBUTE_NORMAL) { // Transform normals, taking into account non-uniform scaling normals.iter_mut().for_each(|normal| { @@ -1037,7 +1037,7 @@ impl Mesh { } if let Some(VertexAttributeValues::Float32x3(ref mut tangents)) = - self.attribute_mut(Mesh::ATTRIBUTE_TANGENT) + self.attribute_mut(Self::ATTRIBUTE_TANGENT) { // Transform tangents, taking into account non-uniform scaling tangents.iter_mut().for_each(|tangent| { @@ -1053,7 +1053,7 @@ impl Mesh { /// type [`VertexAttributeValues::Float32x3`], or if `self` doesn't have any vertices. pub fn compute_aabb(&self) -> Option { let Some(VertexAttributeValues::Float32x3(values)) = - self.attribute(Mesh::ATTRIBUTE_POSITION) + self.attribute(Self::ATTRIBUTE_POSITION) else { return None; }; @@ -1141,7 +1141,7 @@ impl Mesh { /// [primitive topology]: PrimitiveTopology /// [triangles]: Triangle3d pub fn triangles(&self) -> Result + '_, MeshTrianglesError> { - let Some(position_data) = self.attribute(Mesh::ATTRIBUTE_POSITION) else { + let Some(position_data) = self.attribute(Self::ATTRIBUTE_POSITION) else { return Err(MeshTrianglesError::MissingPositions); }; @@ -1233,10 +1233,10 @@ where fn next(&mut self) -> Option { match self { - FourIterators::First(iter) => iter.next(), - FourIterators::Second(iter) => iter.next(), - FourIterators::Third(iter) => iter.next(), - FourIterators::Fourth(iter) => iter.next(), + Self::First(iter) => iter.next(), + Self::Second(iter) => iter.next(), + Self::Third(iter) => iter.next(), + Self::Fourth(iter) => iter.next(), } } } @@ -1425,41 +1425,41 @@ impl VertexFormatSize for VertexFormat { #[allow(clippy::match_same_arms)] 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::Unorm10_10_10_2 => 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::Float64 => 8, - VertexFormat::Float64x2 => 8 * 2, - VertexFormat::Float64x3 => 8 * 3, - VertexFormat::Float64x4 => 8 * 4, + Self::Uint8x2 => 2, + Self::Uint8x4 => 4, + Self::Sint8x2 => 2, + Self::Sint8x4 => 4, + Self::Unorm8x2 => 2, + Self::Unorm8x4 => 4, + Self::Snorm8x2 => 2, + Self::Snorm8x4 => 4, + Self::Unorm10_10_10_2 => 4, + Self::Uint16x2 => 2 * 2, + Self::Uint16x4 => 2 * 4, + Self::Sint16x2 => 2 * 2, + Self::Sint16x4 => 2 * 4, + Self::Unorm16x2 => 2 * 2, + Self::Unorm16x4 => 2 * 4, + Self::Snorm16x2 => 2 * 2, + Self::Snorm16x4 => 2 * 4, + Self::Float16x2 => 2 * 2, + Self::Float16x4 => 2 * 4, + Self::Float32 => 4, + Self::Float32x2 => 4 * 2, + Self::Float32x3 => 4 * 3, + Self::Float32x4 => 4 * 4, + Self::Uint32 => 4, + Self::Uint32x2 => 4 * 2, + Self::Uint32x3 => 4 * 3, + Self::Uint32x4 => 4 * 4, + Self::Sint32 => 4, + Self::Sint32x2 => 4 * 2, + Self::Sint32x3 => 4 * 3, + Self::Sint32x4 => 4 * 4, + Self::Float64 => 8, + Self::Float64x2 => 8 * 2, + Self::Float64x3 => 8 * 3, + Self::Float64x4 => 8 * 4, } } } @@ -1504,34 +1504,34 @@ impl VertexAttributeValues { #[allow(clippy::match_same_arms)] pub fn len(&self) -> usize { match self { - VertexAttributeValues::Float32(values) => values.len(), - VertexAttributeValues::Sint32(values) => values.len(), - VertexAttributeValues::Uint32(values) => values.len(), - VertexAttributeValues::Float32x2(values) => values.len(), - VertexAttributeValues::Sint32x2(values) => values.len(), - VertexAttributeValues::Uint32x2(values) => values.len(), - VertexAttributeValues::Float32x3(values) => values.len(), - VertexAttributeValues::Sint32x3(values) => values.len(), - VertexAttributeValues::Uint32x3(values) => values.len(), - VertexAttributeValues::Float32x4(values) => values.len(), - VertexAttributeValues::Sint32x4(values) => values.len(), - VertexAttributeValues::Uint32x4(values) => values.len(), - VertexAttributeValues::Sint16x2(values) => values.len(), - VertexAttributeValues::Snorm16x2(values) => values.len(), - VertexAttributeValues::Uint16x2(values) => values.len(), - VertexAttributeValues::Unorm16x2(values) => values.len(), - VertexAttributeValues::Sint16x4(values) => values.len(), - VertexAttributeValues::Snorm16x4(values) => values.len(), - VertexAttributeValues::Uint16x4(values) => values.len(), - VertexAttributeValues::Unorm16x4(values) => values.len(), - VertexAttributeValues::Sint8x2(values) => values.len(), - VertexAttributeValues::Snorm8x2(values) => values.len(), - VertexAttributeValues::Uint8x2(values) => values.len(), - VertexAttributeValues::Unorm8x2(values) => values.len(), - VertexAttributeValues::Sint8x4(values) => values.len(), - VertexAttributeValues::Snorm8x4(values) => values.len(), - VertexAttributeValues::Uint8x4(values) => values.len(), - VertexAttributeValues::Unorm8x4(values) => values.len(), + Self::Float32(values) => values.len(), + Self::Sint32(values) => values.len(), + Self::Uint32(values) => values.len(), + Self::Float32x2(values) => values.len(), + Self::Sint32x2(values) => values.len(), + Self::Uint32x2(values) => values.len(), + Self::Float32x3(values) => values.len(), + Self::Sint32x3(values) => values.len(), + Self::Uint32x3(values) => values.len(), + Self::Float32x4(values) => values.len(), + Self::Sint32x4(values) => values.len(), + Self::Uint32x4(values) => values.len(), + Self::Sint16x2(values) => values.len(), + Self::Snorm16x2(values) => values.len(), + Self::Uint16x2(values) => values.len(), + Self::Unorm16x2(values) => values.len(), + Self::Sint16x4(values) => values.len(), + Self::Snorm16x4(values) => values.len(), + Self::Uint16x4(values) => values.len(), + Self::Unorm16x4(values) => values.len(), + Self::Sint8x2(values) => values.len(), + Self::Snorm8x2(values) => values.len(), + Self::Uint8x2(values) => values.len(), + Self::Unorm8x2(values) => values.len(), + Self::Sint8x4(values) => values.len(), + Self::Snorm8x4(values) => values.len(), + Self::Uint8x4(values) => values.len(), + Self::Unorm8x4(values) => values.len(), } } @@ -1543,7 +1543,7 @@ impl VertexAttributeValues { /// Returns the values as float triples if possible. pub fn as_float3(&self) -> Option<&[[f32; 3]]> { match self { - VertexAttributeValues::Float32x3(values) => Some(values), + Self::Float32x3(values) => Some(values), _ => None, } } @@ -1554,34 +1554,34 @@ impl VertexAttributeValues { #[allow(clippy::match_same_arms)] 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), } } } @@ -1589,34 +1589,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, } } } @@ -1633,24 +1633,24 @@ impl Indices { /// Returns an iterator over the indices. pub fn iter(&self) -> impl Iterator + '_ { match self { - Indices::U16(vec) => IndicesIter::U16(vec.iter()), - Indices::U32(vec) => IndicesIter::U32(vec.iter()), + Self::U16(vec) => IndicesIter::U16(vec.iter()), + Self::U32(vec) => IndicesIter::U32(vec.iter()), } } /// Returns the number of indices. pub fn len(&self) -> usize { match self { - Indices::U16(vec) => vec.len(), - Indices::U32(vec) => vec.len(), + Self::U16(vec) => vec.len(), + Self::U32(vec) => vec.len(), } } /// Returns `true` if there are no indices. pub fn is_empty(&self) -> bool { match self { - Indices::U16(vec) => vec.is_empty(), - Indices::U32(vec) => vec.is_empty(), + Self::U16(vec) => vec.is_empty(), + Self::U32(vec) => vec.is_empty(), } } } @@ -1685,8 +1685,8 @@ impl<'a> FusedIterator for IndicesIter<'a> {} 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, } } } @@ -1826,7 +1826,7 @@ impl RenderAsset for RenderMesh { mesh.morph_targets.is_some(), ); - Ok(RenderMesh { + Ok(Self { vertex_count: mesh.count_vertices() as u32, buffer_info, key_bits, diff --git a/crates/bevy_render/src/mesh/morph.rs b/crates/bevy_render/src/mesh/morph.rs index b5eac7cdfec63..89dd69ef6158b 100644 --- a/crates/bevy_render/src/mesh/morph.rs +++ b/crates/bevy_render/src/mesh/morph.rs @@ -110,7 +110,7 @@ impl MorphTargetImage { TextureFormat::R32Float, asset_usage, ); - Ok(MorphTargetImage(image)) + Ok(Self(image)) } } @@ -143,7 +143,7 @@ impl MorphWeights { let target_count = weights.len(); return Err(MorphBuildError::TooManyTargets { target_count }); } - Ok(MorphWeights { + Ok(Self { weights, first_mesh, }) @@ -183,7 +183,7 @@ impl MeshMorphWeights { let target_count = weights.len(); return Err(MorphBuildError::TooManyTargets { target_count }); } - Ok(MeshMorphWeights { weights }) + Ok(Self { weights }) } pub fn weights(&self) -> &[f32] { &self.weights @@ -228,7 +228,7 @@ pub struct MorphAttributes { } impl From<[Vec3; 3]> for MorphAttributes { fn from([position, normal, tangent]: [Vec3; 3]) -> Self { - MorphAttributes { + Self { position, normal, tangent, @@ -242,7 +242,7 @@ impl MorphAttributes { pub const COMPONENT_COUNT: usize = 9; pub fn new(position: Vec3, normal: Vec3, tangent: Vec3) -> Self { - MorphAttributes { + Self { position, normal, tangent, diff --git a/crates/bevy_render/src/mesh/primitives/dim2.rs b/crates/bevy_render/src/mesh/primitives/dim2.rs index 282e59b351808..220033b4dc315 100644 --- a/crates/bevy_render/src/mesh/primitives/dim2.rs +++ b/crates/bevy_render/src/mesh/primitives/dim2.rs @@ -112,7 +112,7 @@ pub enum CircularMeshUvMode { impl Default for CircularMeshUvMode { fn default() -> Self { - CircularMeshUvMode::Mask { angle: 0.0 } + Self::Mask { angle: 0.0 } } } diff --git a/crates/bevy_render/src/mesh/primitives/dim3/capsule.rs b/crates/bevy_render/src/mesh/primitives/dim3/capsule.rs index 3c85fc629b03b..45589fac5a65b 100644 --- a/crates/bevy_render/src/mesh/primitives/dim3/capsule.rs +++ b/crates/bevy_render/src/mesh/primitives/dim3/capsule.rs @@ -96,7 +96,7 @@ impl Capsule3dMeshBuilder { impl MeshBuilder for Capsule3dMeshBuilder { fn build(&self) -> Mesh { // code adapted from https://behreajj.medium.com/making-a-capsule-mesh-via-script-in-five-3d-environments-c2214abf02db - let Capsule3dMeshBuilder { + let Self { capsule, rings, longitudes, diff --git a/crates/bevy_render/src/mesh/primitives/extrusion.rs b/crates/bevy_render/src/mesh/primitives/extrusion.rs index 123026524a83e..1f7455fcb1d09 100644 --- a/crates/bevy_render/src/mesh/primitives/extrusion.rs +++ b/crates/bevy_render/src/mesh/primitives/extrusion.rs @@ -51,8 +51,8 @@ impl PerimeterSegment { /// A layer is the set of vertices sharing a common Z value or depth. fn vertices_per_layer(&self) -> u32 { match self { - PerimeterSegment::Smooth { indices, .. } => indices.len() as u32, - PerimeterSegment::Flat { indices } => 2 * (indices.len() as u32 - 1), + Self::Smooth { indices, .. } => indices.len() as u32, + Self::Flat { indices } => 2 * (indices.len() as u32 - 1), } } @@ -61,9 +61,7 @@ impl PerimeterSegment { /// A segment is the set of faces on the mantel of the extrusion between two layers of vertices. fn indices_per_segment(&self) -> usize { match self { - PerimeterSegment::Smooth { indices, .. } | PerimeterSegment::Flat { indices } => { - 6 * (indices.len() - 1) - } + Self::Smooth { indices, .. } | Self::Flat { indices } => 6 * (indices.len() - 1), } } } diff --git a/crates/bevy_render/src/primitives/mod.rs b/crates/bevy_render/src/primitives/mod.rs index 921a2cbc44315..51353871a1c7c 100644 --- a/crates/bevy_render/src/primitives/mod.rs +++ b/crates/bevy_render/src/primitives/mod.rs @@ -222,7 +222,7 @@ impl Frustum { /// Returns a frustum derived from `clip_from_world`. #[inline] pub fn from_clip_from_world(clip_from_world: &Mat4) -> Self { - let mut frustum = Frustum::from_clip_from_world_no_far(clip_from_world); + let mut frustum = Self::from_clip_from_world_no_far(clip_from_world); frustum.half_spaces[5] = HalfSpace::new(clip_from_world.row(2)); frustum } @@ -236,7 +236,7 @@ impl Frustum { view_backward: &Vec3, far: f32, ) -> Self { - let mut frustum = Frustum::from_clip_from_world_no_far(clip_from_world); + let mut frustum = Self::from_clip_from_world_no_far(clip_from_world); let far_center = *view_translation - far * *view_backward; frustum.half_spaces[5] = HalfSpace::new(view_backward.extend(-view_backward.dot(far_center))); diff --git a/crates/bevy_render/src/render_asset.rs b/crates/bevy_render/src/render_asset.rs index 5c9be59de3dd6..ae74972fcd70f 100644 --- a/crates/bevy_render/src/render_asset.rs +++ b/crates/bevy_render/src/render_asset.rs @@ -101,7 +101,7 @@ impl Default for RenderAssetUsages { /// the asset to be unloaded from the main world once it has been prepared for rendering. If the asset does not need /// to reach the render world at all, use `RenderAssetUsages::MAIN_WORLD` exclusively. fn default() -> Self { - RenderAssetUsages::MAIN_WORLD | RenderAssetUsages::RENDER_WORLD + Self::MAIN_WORLD | Self::RENDER_WORLD } } diff --git a/crates/bevy_render/src/render_graph/edge.rs b/crates/bevy_render/src/render_graph/edge.rs index 199b7e8abbd96..ea87f57d178f8 100644 --- a/crates/bevy_render/src/render_graph/edge.rs +++ b/crates/bevy_render/src/render_graph/edge.rs @@ -38,14 +38,14 @@ impl Edge { /// Returns the id of the `input_node`. pub fn get_input_node(&self) -> InternedRenderLabel { match self { - Edge::SlotEdge { input_node, .. } | Edge::NodeEdge { input_node, .. } => *input_node, + Self::SlotEdge { input_node, .. } | Self::NodeEdge { input_node, .. } => *input_node, } } /// Returns the id of the `output_node`. pub fn get_output_node(&self) -> InternedRenderLabel { match self { - Edge::SlotEdge { output_node, .. } | Edge::NodeEdge { output_node, .. } => *output_node, + Self::SlotEdge { 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 9779e4a75ccee..3e8faba7967c8 100644 --- a/crates/bevy_render/src/render_graph/graph.rs +++ b/crates/bevy_render/src/render_graph/graph.rs @@ -527,14 +527,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, graph)) } /// Returns an iterator over the sub graphs, that allows modifying each value. pub fn iter_sub_graphs_mut( &mut self, - ) -> impl Iterator { + ) -> impl Iterator { self.sub_graphs .iter_mut() .map(|(name, graph)| (*name, graph)) @@ -572,7 +572,7 @@ impl RenderGraph { /// Adds the `sub_graph` with the `label` to the graph. /// If the label is already present replaces it instead. - pub fn add_sub_graph(&mut self, label: impl RenderSubGraph, sub_graph: RenderGraph) { + pub fn add_sub_graph(&mut self, label: impl RenderSubGraph, sub_graph: Self) { self.sub_graphs.insert(label.intern(), sub_graph); } @@ -583,12 +583,12 @@ impl RenderGraph { } /// Retrieves the sub graph corresponding to the `label`. - pub fn get_sub_graph(&self, label: impl RenderSubGraph) -> Option<&RenderGraph> { + pub fn get_sub_graph(&self, label: impl RenderSubGraph) -> Option<&Self> { self.sub_graphs.get(&label.intern()) } /// Retrieves the sub graph corresponding to the `label` mutably. - pub fn get_sub_graph_mut(&mut self, label: impl RenderSubGraph) -> Option<&mut RenderGraph> { + pub fn get_sub_graph_mut(&mut self, label: impl RenderSubGraph) -> Option<&mut Self> { self.sub_graphs.get_mut(&label.intern()) } @@ -601,7 +601,7 @@ impl RenderGraph { /// # See also /// /// - [`get_sub_graph`](Self::get_sub_graph) for a fallible version. - pub fn sub_graph(&self, label: impl RenderSubGraph) -> &RenderGraph { + pub fn sub_graph(&self, label: impl RenderSubGraph) -> &Self { let label = label.intern(); self.sub_graphs .get(&label) @@ -617,7 +617,7 @@ impl RenderGraph { /// # See also /// /// - [`get_sub_graph_mut`](Self::get_sub_graph_mut) for a fallible version. - pub fn sub_graph_mut(&mut self, label: impl RenderSubGraph) -> &mut RenderGraph { + pub fn sub_graph_mut(&mut self, label: impl RenderSubGraph) -> &mut Self { let label = label.intern(); self.sub_graphs .get_mut(&label) @@ -694,7 +694,7 @@ mod tests { impl TestNode { pub fn new(inputs: usize, outputs: usize) -> Self { - TestNode { + Self { inputs: (0..inputs) .map(|i| SlotInfo::new(format!("in_{i}"), SlotType::TextureView)) .collect(), diff --git a/crates/bevy_render/src/render_graph/node.rs b/crates/bevy_render/src/render_graph/node.rs index 8528457d420a1..e9800b6f5644b 100644 --- a/crates/bevy_render/src/render_graph/node.rs +++ b/crates/bevy_render/src/render_graph/node.rs @@ -241,7 +241,7 @@ impl NodeState { where T: Node, { - NodeState { + Self { label, input_slots: node.input().into(), output_slots: node.output().into(), diff --git a/crates/bevy_render/src/render_graph/node_slot.rs b/crates/bevy_render/src/render_graph/node_slot.rs index fd5dc388d3812..0b327876fdcf0 100644 --- a/crates/bevy_render/src/render_graph/node_slot.rs +++ b/crates/bevy_render/src/render_graph/node_slot.rs @@ -26,35 +26,35 @@ impl SlotValue { /// Returns the [`SlotType`] of this value. pub 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) } } @@ -77,10 +77,10 @@ pub enum SlotType { impl fmt::Display for SlotType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let s = match self { - SlotType::Buffer => "Buffer", - SlotType::TextureView => "TextureView", - SlotType::Sampler => "Sampler", - SlotType::Entity => "Entity", + Self::Buffer => "Buffer", + Self::TextureView => "TextureView", + Self::Sampler => "Sampler", + Self::Entity => "Entity", }; f.write_str(s) @@ -95,33 +95,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) + Self::Name(value) } } impl From for SlotLabel { fn from(value: usize) -> Self { - SlotLabel::Index(value) + Self::Index(value) } } @@ -134,7 +134,7 @@ pub struct SlotInfo { impl SlotInfo { pub fn new(name: impl Into>, slot_type: SlotType) -> Self { - SlotInfo { + Self { name: name.into(), slot_type, } @@ -150,7 +150,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/mod.rs b/crates/bevy_render/src/render_phase/mod.rs index 1bc1ee52ca687..124906456a675 100644 --- a/crates/bevy_render/src/render_phase/mod.rs +++ b/crates/bevy_render/src/render_phase/mod.rs @@ -237,7 +237,7 @@ where T: Clone + ShaderSize + WriteInto, { fn from(value: GpuArrayBufferIndex) -> Self { - UnbatchableBinnedEntityIndices { + Self { instance_index: value.index, extra_index: PhaseItemExtraIndex::maybe_dynamic_offset(value.dynamic_offset), } @@ -489,20 +489,18 @@ impl UnbatchableBinnedEntityIndexSet { entity_index: u32, ) -> Option { match self { - UnbatchableBinnedEntityIndexSet::NoEntities => None, - UnbatchableBinnedEntityIndexSet::Sparse { instance_range, .. } - if entity_index >= instance_range.len() as u32 => - { + Self::NoEntities => None, + Self::Sparse { instance_range, .. } if entity_index >= instance_range.len() as u32 => { None } - UnbatchableBinnedEntityIndexSet::Sparse { + Self::Sparse { instance_range, first_indirect_parameters_index: None, } => Some(UnbatchableBinnedEntityIndices { instance_index: instance_range.start + entity_index, extra_index: PhaseItemExtraIndex::NONE, }), - UnbatchableBinnedEntityIndexSet::Sparse { + Self::Sparse { instance_range, first_indirect_parameters_index: Some(first_indirect_parameters_index), } => Some(UnbatchableBinnedEntityIndices { @@ -511,9 +509,7 @@ impl UnbatchableBinnedEntityIndexSet { u32::from(*first_indirect_parameters_index) + entity_index, ), }), - UnbatchableBinnedEntityIndexSet::Dense(ref indices) => { - indices.get(entity_index as usize).copied() - } + Self::Dense(ref indices) => indices.get(entity_index as usize).copied(), } } } @@ -655,15 +651,15 @@ impl UnbatchableBinnedEntityIndexSet { /// Adds a new entity to the list of unbatchable binned entities. pub fn add(&mut self, indices: UnbatchableBinnedEntityIndices) { match self { - UnbatchableBinnedEntityIndexSet::NoEntities => { + Self::NoEntities => { if indices.extra_index.is_dynamic_offset() { // This is the first entity we've seen, and we don't have // compute shaders. Initialize an array. - *self = UnbatchableBinnedEntityIndexSet::Dense(vec![indices]); + *self = Self::Dense(vec![indices]); } else { // This is the first entity we've seen, and we have compute // shaders. Initialize the fast path. - *self = UnbatchableBinnedEntityIndexSet::Sparse { + *self = Self::Sparse { instance_range: indices.instance_index..indices.instance_index + 1, first_indirect_parameters_index: indices .extra_index @@ -672,8 +668,7 @@ impl UnbatchableBinnedEntityIndexSet { } } } - - UnbatchableBinnedEntityIndexSet::Sparse { + Self::Sparse { ref mut instance_range, first_indirect_parameters_index, } if instance_range.end == indices.instance_index @@ -691,8 +686,7 @@ impl UnbatchableBinnedEntityIndexSet { // This is the normal case on non-WebGL 2. instance_range.end += 1; } - - UnbatchableBinnedEntityIndexSet::Sparse { instance_range, .. } => { + Self::Sparse { instance_range, .. } => { // We thought we were in non-WebGL 2 mode, but we got a dynamic // offset or non-contiguous index anyway. This shouldn't happen, // but let's go ahead and do the sensible thing anyhow: demote @@ -702,10 +696,9 @@ impl UnbatchableBinnedEntityIndexSet { .flat_map(|entity_index| self.indices_for_entity_index(entity_index)) .chain(iter::once(indices)) .collect(); - *self = UnbatchableBinnedEntityIndexSet::Dense(new_dynamic_offsets); + *self = Self::Dense(new_dynamic_offsets); } - - UnbatchableBinnedEntityIndexSet::Dense(ref mut dense_indices) => { + Self::Dense(ref mut dense_indices) => { dense_indices.push(indices); } } @@ -910,7 +903,7 @@ impl PhaseItemExtraIndex { pub const FLAGS_MASK: u32 = !Self::OFFSET_MASK; /// The special value that indicates that no extra index is present. - pub const NONE: PhaseItemExtraIndex = PhaseItemExtraIndex(u32::MAX); + pub const NONE: Self = Self(u32::MAX); /// Returns either the indirect parameters index or the dynamic offset, /// depending on which is in use. @@ -933,10 +926,10 @@ impl PhaseItemExtraIndex { /// Packs a indirect parameters index into this extra index. #[inline] - pub fn indirect_parameters_index(indirect_parameter_index: u32) -> PhaseItemExtraIndex { + pub fn indirect_parameters_index(indirect_parameter_index: u32) -> Self { // Make sure we didn't overflow. debug_assert_eq!(indirect_parameter_index & Self::FLAGS_MASK, 0); - PhaseItemExtraIndex(indirect_parameter_index | Self::INDIRECT_PARAMETER_INDEX) + Self(indirect_parameter_index | Self::INDIRECT_PARAMETER_INDEX) } /// Returns either an indirect parameters index or @@ -944,31 +937,31 @@ impl PhaseItemExtraIndex { #[inline] pub fn maybe_indirect_parameters_index( maybe_indirect_parameters_index: Option, - ) -> PhaseItemExtraIndex { + ) -> Self { match maybe_indirect_parameters_index { Some(indirect_parameters_index) => { Self::indirect_parameters_index(indirect_parameters_index.into()) } - None => PhaseItemExtraIndex::NONE, + None => Self::NONE, } } /// Packs a dynamic offset into this extra index. #[inline] - pub fn dynamic_offset(dynamic_offset: u32) -> PhaseItemExtraIndex { + pub fn dynamic_offset(dynamic_offset: u32) -> Self { // Make sure we didn't overflow. debug_assert_eq!(dynamic_offset & Self::FLAGS_MASK, 0); - PhaseItemExtraIndex(dynamic_offset) + Self(dynamic_offset) } /// Returns either a dynamic offset or [`PhaseItemExtraIndex::NONE`], as /// appropriate. #[inline] - pub fn maybe_dynamic_offset(maybe_dynamic_offset: Option) -> PhaseItemExtraIndex { + pub fn maybe_dynamic_offset(maybe_dynamic_offset: Option) -> Self { match maybe_dynamic_offset { Some(dynamic_offset) => Self::dynamic_offset(dynamic_offset.into()), - None => PhaseItemExtraIndex::NONE, + None => Self::NONE, } } @@ -1108,11 +1101,11 @@ where impl BinnedRenderPhaseType { /// Creates the appropriate [`BinnedRenderPhaseType`] for a mesh, given its /// batchability. - pub fn mesh(batchable: bool) -> BinnedRenderPhaseType { + pub fn mesh(batchable: bool) -> Self { if batchable { - BinnedRenderPhaseType::BatchableMesh + Self::BatchableMesh } else { - BinnedRenderPhaseType::UnbatchableMesh + Self::UnbatchableMesh } } } diff --git a/crates/bevy_render/src/render_phase/rangefinder.rs b/crates/bevy_render/src/render_phase/rangefinder.rs index 4222ee134b02f..95985a82dfbdd 100644 --- a/crates/bevy_render/src/render_phase/rangefinder.rs +++ b/crates/bevy_render/src/render_phase/rangefinder.rs @@ -7,10 +7,9 @@ pub struct ViewRangefinder3d { impl ViewRangefinder3d { /// Creates a 3D rangefinder for a view matrix. - pub fn from_world_from_view(world_from_view: &Mat4) -> ViewRangefinder3d { + pub fn from_world_from_view(world_from_view: &Mat4) -> Self { let view_from_world = world_from_view.inverse(); - - ViewRangefinder3d { + Self { view_from_world_row_2: view_from_world.row(2), } } diff --git a/crates/bevy_render/src/render_resource/bind_group.rs b/crates/bevy_render/src/render_resource/bind_group.rs index 39704525b780f..e0430b57c0746 100644 --- a/crates/bevy_render/src/render_resource/bind_group.rs +++ b/crates/bevy_render/src/render_resource/bind_group.rs @@ -36,7 +36,7 @@ impl BindGroup { impl From for BindGroup { fn from(value: wgpu::BindGroup) -> Self { - BindGroup { + Self { id: BindGroupId::new(), value: ErasedBindGroup::new(value), } @@ -380,9 +380,9 @@ pub enum OwnedBindingResource { impl OwnedBindingResource { pub fn get_binding(&self) -> BindingResource { match self { - OwnedBindingResource::Buffer(buffer) => buffer.as_entire_binding(), - OwnedBindingResource::TextureView(view) => BindingResource::TextureView(view), - OwnedBindingResource::Sampler(sampler) => BindingResource::Sampler(sampler), + Self::Buffer(buffer) => buffer.as_entire_binding(), + Self::TextureView(view) => BindingResource::TextureView(view), + Self::Sampler(sampler) => BindingResource::Sampler(sampler), } } } diff --git a/crates/bevy_render/src/render_resource/bind_group_entries.rs b/crates/bevy_render/src/render_resource/bind_group_entries.rs index 33260f985067d..a918e28609028 100644 --- a/crates/bevy_render/src/render_resource/bind_group_entries.rs +++ b/crates/bevy_render/src/render_resource/bind_group_entries.rs @@ -164,7 +164,7 @@ impl<'a> IntoBinding<'a> for &'a Sampler { impl<'a> IntoBinding<'a> for BindingResource<'a> { #[inline] - fn into_binding(self) -> BindingResource<'a> { + fn into_binding(self) -> Self { self } } 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 9793f1391d188..0cd6f7898f12d 100644 --- a/crates/bevy_render/src/render_resource/bind_group_layout.rs +++ b/crates/bevy_render/src/render_resource/bind_group_layout.rs @@ -30,7 +30,7 @@ impl BindGroupLayout { impl From for BindGroupLayout { fn from(value: wgpu::BindGroupLayout) -> Self { - BindGroupLayout { + Self { id: BindGroupLayoutId::new(), value: ErasedBindGroupLayout::new(value), } diff --git a/crates/bevy_render/src/render_resource/buffer.rs b/crates/bevy_render/src/render_resource/buffer.rs index 9867945673efb..b8d023bc6c6d9 100644 --- a/crates/bevy_render/src/render_resource/buffer.rs +++ b/crates/bevy_render/src/render_resource/buffer.rs @@ -37,7 +37,7 @@ impl Buffer { impl From for Buffer { fn from(value: wgpu::Buffer) -> Self { - Buffer { + Self { id: BufferId::new(), value: ErasedBuffer::new(value), } diff --git a/crates/bevy_render/src/render_resource/buffer_vec.rs b/crates/bevy_render/src/render_resource/buffer_vec.rs index 49be061aa9848..24d66d9016e5e 100644 --- a/crates/bevy_render/src/render_resource/buffer_vec.rs +++ b/crates/bevy_render/src/render_resource/buffer_vec.rs @@ -99,7 +99,7 @@ impl RawBufferVec { index } - pub fn append(&mut self, other: &mut RawBufferVec) { + pub fn append(&mut self, other: &mut Self) { self.values.append(&mut other.values); } diff --git a/crates/bevy_render/src/render_resource/gpu_array_buffer.rs b/crates/bevy_render/src/render_resource/gpu_array_buffer.rs index f1980062bd2b5..ce50e7f77c470 100644 --- a/crates/bevy_render/src/render_resource/gpu_array_buffer.rs +++ b/crates/bevy_render/src/render_resource/gpu_array_buffer.rs @@ -41,23 +41,23 @@ impl GpuArrayBuffer { pub fn new(device: &RenderDevice) -> Self { let limits = device.limits(); if limits.max_storage_buffers_per_shader_stage == 0 { - GpuArrayBuffer::Uniform(BatchedUniformBuffer::new(&limits)) + Self::Uniform(BatchedUniformBuffer::new(&limits)) } else { - GpuArrayBuffer::Storage(BufferVec::new(BufferUsages::STORAGE)) + Self::Storage(BufferVec::new(BufferUsages::STORAGE)) } } pub fn clear(&mut self) { match self { - GpuArrayBuffer::Uniform(buffer) => buffer.clear(), - GpuArrayBuffer::Storage(buffer) => buffer.clear(), + Self::Uniform(buffer) => buffer.clear(), + Self::Storage(buffer) => buffer.clear(), } } pub fn push(&mut self, value: T) -> GpuArrayBufferIndex { match self { - GpuArrayBuffer::Uniform(buffer) => buffer.push(value), - GpuArrayBuffer::Storage(buffer) => { + Self::Uniform(buffer) => buffer.push(value), + Self::Storage(buffer) => { let index = buffer.push(value) as u32; GpuArrayBufferIndex { index, @@ -70,8 +70,8 @@ impl GpuArrayBuffer { pub fn write_buffer(&mut self, device: &RenderDevice, queue: &RenderQueue) { match self { - GpuArrayBuffer::Uniform(buffer) => buffer.write_buffer(device, queue), - GpuArrayBuffer::Storage(buffer) => buffer.write_buffer(device, queue), + Self::Uniform(buffer) => buffer.write_buffer(device, queue), + Self::Storage(buffer) => buffer.write_buffer(device, queue), } } @@ -90,8 +90,8 @@ impl GpuArrayBuffer { pub fn binding(&self) -> Option { match self { - GpuArrayBuffer::Uniform(buffer) => buffer.binding(), - GpuArrayBuffer::Storage(buffer) => buffer.binding(), + Self::Uniform(buffer) => buffer.binding(), + Self::Storage(buffer) => buffer.binding(), } } diff --git a/crates/bevy_render/src/render_resource/pipeline.rs b/crates/bevy_render/src/render_resource/pipeline.rs index 8eafdaf2892a9..ed42e0b69829f 100644 --- a/crates/bevy_render/src/render_resource/pipeline.rs +++ b/crates/bevy_render/src/render_resource/pipeline.rs @@ -32,7 +32,7 @@ impl RenderPipeline { impl From for RenderPipeline { fn from(value: wgpu::RenderPipeline) -> Self { - RenderPipeline { + Self { id: RenderPipelineId::new(), value: ErasedRenderPipeline::new(value), } @@ -71,7 +71,7 @@ impl ComputePipeline { impl From for ComputePipeline { fn from(value: wgpu::ComputePipeline) -> Self { - ComputePipeline { + Self { id: ComputePipelineId::new(), value: ErasedComputePipeline::new(value), } @@ -151,8 +151,7 @@ impl VertexBufferLayout { }); offset += format.size(); } - - VertexBufferLayout { + Self { array_stride: offset, step_mode, attributes, diff --git a/crates/bevy_render/src/render_resource/pipeline_cache.rs b/crates/bevy_render/src/render_resource/pipeline_cache.rs index be0a8577272a3..5585df73eb851 100644 --- a/crates/bevy_render/src/render_resource/pipeline_cache.rs +++ b/crates/bevy_render/src/render_resource/pipeline_cache.rs @@ -61,7 +61,7 @@ pub struct CachedRenderPipelineId(CachedPipelineId); impl CachedRenderPipelineId { /// An invalid cached render pipeline index, often used to initialize a variable. - pub const INVALID: Self = CachedRenderPipelineId(usize::MAX); + pub const INVALID: Self = Self(usize::MAX); #[inline] pub fn id(&self) -> usize { @@ -75,7 +75,7 @@ pub struct CachedComputePipelineId(CachedPipelineId); impl CachedComputePipelineId { /// An invalid cached compute pipeline index, often used to initialize a variable. - pub const INVALID: Self = CachedComputePipelineId(usize::MAX); + pub const INVALID: Self = Self(usize::MAX); #[inline] pub fn id(&self) -> usize { @@ -114,14 +114,14 @@ impl CachedPipelineState { /// pending creation or because an error occurred while attempting to create GPU object. pub fn unwrap(&self) -> &Pipeline { match self { - CachedPipelineState::Ok(pipeline) => pipeline, - CachedPipelineState::Queued => { + Self::Ok(pipeline) => pipeline, + Self::Queued => { panic!("Pipeline has not been compiled yet. It is still in the 'Queued' state.") } - CachedPipelineState::Creating(..) => { + Self::Creating(..) => { panic!("Pipeline has not been compiled yet. It is still in the 'Creating' state.") } - CachedPipelineState::Err(err) => panic!("{}", err), + Self::Err(err) => panic!("{}", err), } } } @@ -151,22 +151,22 @@ pub enum ShaderDefVal { impl From<&str> for ShaderDefVal { fn from(key: &str) -> Self { - ShaderDefVal::Bool(key.to_string(), true) + Self::Bool(key.to_string(), true) } } impl From for ShaderDefVal { fn from(key: String) -> Self { - ShaderDefVal::Bool(key, true) + Self::Bool(key, true) } } impl ShaderDefVal { pub fn value_as_string(&self) -> String { match self { - ShaderDefVal::Bool(_, def) => def.to_string(), - ShaderDefVal::Int(_, def) => def.to_string(), - ShaderDefVal::UInt(_, def) => def.to_string(), + Self::Bool(_, def) => def.to_string(), + Self::Int(_, def) => def.to_string(), + Self::UInt(_, def) => def.to_string(), } } } diff --git a/crates/bevy_render/src/render_resource/shader.rs b/crates/bevy_render/src/render_resource/shader.rs index 33055de58ccb9..0dd00d0fc3d0a 100644 --- a/crates/bevy_render/src/render_resource/shader.rs +++ b/crates/bevy_render/src/render_resource/shader.rs @@ -66,11 +66,11 @@ impl Shader { (import_path, imports) } - pub fn from_wgsl(source: impl Into>, path: impl Into) -> Shader { + pub fn from_wgsl(source: impl Into>, path: impl Into) -> Self { let source = source.into(); let path = path.into(); - let (import_path, imports) = Shader::preprocess(&source, &path); - Shader { + let (import_path, imports) = Self::preprocess(&source, &path); + Self { path, imports, import_path, @@ -85,7 +85,7 @@ impl Shader { source: impl Into>, path: impl Into, shader_defs: Vec, - ) -> Shader { + ) -> Self { Self { shader_defs, ..Self::from_wgsl(source, path) @@ -96,11 +96,11 @@ impl Shader { source: impl Into>, stage: naga::ShaderStage, path: impl Into, - ) -> Shader { + ) -> Self { let source = source.into(); let path = path.into(); - let (import_path, imports) = Shader::preprocess(&source, &path); - Shader { + let (import_path, imports) = Self::preprocess(&source, &path); + Self { path, imports, import_path, @@ -111,9 +111,9 @@ impl Shader { } } - pub fn from_spirv(source: impl Into>, path: impl Into) -> Shader { + pub fn from_spirv(source: impl Into>, path: impl Into) -> Self { let path = path.into(); - Shader { + Self { path: path.clone(), imports: Vec::new(), import_path: ShaderImport::AssetPath(path), @@ -202,8 +202,8 @@ pub enum Source { impl Source { pub fn as_str(&self) -> &str { match self { - Source::Wgsl(s) | Source::Glsl(s, _) => s, - Source::SpirV(_) => panic!("spirv not yet implemented"), + Self::Wgsl(s) | Self::Glsl(s, _) => s, + Self::SpirV(_) => panic!("spirv not yet implemented"), } } } @@ -211,9 +211,9 @@ impl Source { impl From<&Source> for naga_oil::compose::ShaderLanguage { fn from(value: &Source) -> Self { match value { - Source::Wgsl(_) => naga_oil::compose::ShaderLanguage::Wgsl, + Source::Wgsl(_) => Self::Wgsl, #[cfg(any(feature = "shader_format_glsl", target_arch = "wasm32"))] - Source::Glsl(_, _) => naga_oil::compose::ShaderLanguage::Glsl, + Source::Glsl(_, _) => Self::Glsl, #[cfg(all(not(feature = "shader_format_glsl"), not(target_arch = "wasm32")))] Source::Glsl(_, _) => panic!( "GLSL is not supported in this configuration; use the feature `shader_format_glsl`" @@ -226,11 +226,11 @@ impl From<&Source> for naga_oil::compose::ShaderLanguage { impl From<&Source> for naga_oil::compose::ShaderType { fn from(value: &Source) -> Self { match value { - Source::Wgsl(_) => naga_oil::compose::ShaderType::Wgsl, + Source::Wgsl(_) => Self::Wgsl, #[cfg(any(feature = "shader_format_glsl", target_arch = "wasm32"))] Source::Glsl(_, shader_stage) => match shader_stage { - naga::ShaderStage::Vertex => naga_oil::compose::ShaderType::GlslVertex, - naga::ShaderStage::Fragment => naga_oil::compose::ShaderType::GlslFragment, + naga::ShaderStage::Vertex => Self::GlslVertex, + naga::ShaderStage::Fragment => Self::GlslFragment, naga::ShaderStage::Compute => panic!("glsl compute not yet implemented"), }, #[cfg(all(not(feature = "shader_format_glsl"), not(target_arch = "wasm32")))] @@ -307,8 +307,8 @@ pub enum ShaderImport { impl ShaderImport { pub fn module_name(&self) -> Cow<'_, String> { match self { - ShaderImport::AssetPath(s) => Cow::Owned(format!("\"{s}\"")), - ShaderImport::Custom(s) => Cow::Borrowed(s), + Self::AssetPath(s) => Cow::Owned(format!("\"{s}\"")), + Self::Custom(s) => Cow::Borrowed(s), } } } diff --git a/crates/bevy_render/src/render_resource/texture.rs b/crates/bevy_render/src/render_resource/texture.rs index df0df616a6f6c..a1c70e9524537 100644 --- a/crates/bevy_render/src/render_resource/texture.rs +++ b/crates/bevy_render/src/render_resource/texture.rs @@ -31,7 +31,7 @@ impl Texture { impl From for Texture { fn from(value: wgpu::Texture) -> Self { - Texture { + Self { id: TextureId::new(), value: ErasedTexture::new(value), } @@ -78,7 +78,7 @@ impl TextureView { impl From for TextureView { fn from(value: wgpu::TextureView) -> Self { - TextureView { + Self { id: TextureViewId::new(), value: ErasedTextureView::new(value), } @@ -87,7 +87,7 @@ impl From for TextureView { impl From for SurfaceTexture { fn from(value: wgpu::SurfaceTexture) -> Self { - SurfaceTexture { + Self { value: ErasedSurfaceTexture::new(value), } } @@ -135,7 +135,7 @@ impl Sampler { impl From for Sampler { fn from(value: wgpu::Sampler) -> Self { - Sampler { + Self { id: SamplerId::new(), value: ErasedSampler::new(value), } diff --git a/crates/bevy_render/src/spatial_bundle.rs b/crates/bevy_render/src/spatial_bundle.rs index e84f765a27fe8..d649c41bab598 100644 --- a/crates/bevy_render/src/spatial_bundle.rs +++ b/crates/bevy_render/src/spatial_bundle.rs @@ -35,14 +35,14 @@ impl SpatialBundle { /// This initializes [`GlobalTransform`] as identity, and visibility as visible #[inline] pub const fn from_transform(transform: Transform) -> Self { - SpatialBundle { + Self { transform, ..Self::INHERITED_IDENTITY } } /// A [`SpatialBundle`] with inherited visibility and identity transform. - pub const INHERITED_IDENTITY: Self = SpatialBundle { + pub const INHERITED_IDENTITY: Self = Self { visibility: Visibility::Inherited, inherited_visibility: InheritedVisibility::HIDDEN, view_visibility: ViewVisibility::HIDDEN, @@ -51,7 +51,7 @@ impl SpatialBundle { }; /// An invisible [`SpatialBundle`] with identity transform. - pub const HIDDEN_IDENTITY: Self = SpatialBundle { + pub const HIDDEN_IDENTITY: Self = Self { visibility: Visibility::Hidden, ..Self::INHERITED_IDENTITY }; diff --git a/crates/bevy_render/src/texture/image.rs b/crates/bevy_render/src/texture/image.rs index 4eca33b20fa62..e2df4a6a1d533 100644 --- a/crates/bevy_render/src/texture/image.rs +++ b/crates/bevy_render/src/texture/image.rs @@ -70,12 +70,12 @@ macro_rules! feature_gate { impl ImageFormat { pub fn from_mime_type(mime_type: &str) -> Option { Some(match mime_type.to_ascii_lowercase().as_str() { - "image/avif" => ImageFormat::Avif, + "image/avif" => Self::Avif, "image/bmp" | "image/x-bmp" => feature_gate!("bmp", Bmp), "image/vnd-ms.dds" => feature_gate!("dds", Dds), "image/vnd.radiance" => feature_gate!("hdr", Hdr), - "image/gif" => ImageFormat::Gif, - "image/x-icon" => ImageFormat::Ico, + "image/gif" => Self::Gif, + "image/x-icon" => Self::Ico, "image/jpeg" => feature_gate!("jpeg", Jpeg), "image/ktx2" => feature_gate!("ktx2", Ktx2), "image/png" => feature_gate!("png", Png), @@ -85,7 +85,7 @@ impl ImageFormat { | "image/x-portable-pixmap" | "image/x-portable-anymap" => feature_gate!("pnm", Pnm), "image/x-targa" | "image/x-tga" => feature_gate!("tga", Tga), - "image/tiff" => ImageFormat::Tiff, + "image/tiff" => Self::Tiff, "image/webp" => feature_gate!("webp", WebP), _ => return None, }) @@ -93,21 +93,21 @@ impl ImageFormat { pub fn from_extension(extension: &str) -> Option { Some(match extension.to_ascii_lowercase().as_str() { - "avif" => ImageFormat::Avif, + "avif" => Self::Avif, "basis" => feature_gate!("basis-universal", Basis), "bmp" => feature_gate!("bmp", Bmp), "dds" => feature_gate!("dds", Dds), - "ff" | "farbfeld" => ImageFormat::Farbfeld, - "gif" => ImageFormat::Gif, + "ff" | "farbfeld" => Self::Farbfeld, + "gif" => Self::Gif, "exr" => feature_gate!("exr", OpenExr), "hdr" => feature_gate!("hdr", Hdr), - "ico" => ImageFormat::Ico, + "ico" => Self::Ico, "jpg" | "jpeg" => feature_gate!("jpeg", Jpeg), "ktx2" => feature_gate!("ktx2", Ktx2), "pbm" | "pam" | "ppm" | "pgm" => feature_gate!("pnm", Pnm), "png" => feature_gate!("png", Png), "tga" => feature_gate!("tga", Tga), - "tif" | "tiff" => ImageFormat::Tiff, + "tif" | "tiff" => Self::Tiff, "webp" => feature_gate!("webp", WebP), _ => return None, }) @@ -115,51 +115,51 @@ impl ImageFormat { pub fn as_image_crate_format(&self) -> Option { Some(match self { - ImageFormat::Avif => image::ImageFormat::Avif, + Self::Avif => image::ImageFormat::Avif, #[cfg(feature = "bmp")] - ImageFormat::Bmp => image::ImageFormat::Bmp, + Self::Bmp => image::ImageFormat::Bmp, #[cfg(feature = "dds")] - ImageFormat::Dds => image::ImageFormat::Dds, - ImageFormat::Farbfeld => image::ImageFormat::Farbfeld, - ImageFormat::Gif => image::ImageFormat::Gif, + Self::Dds => image::ImageFormat::Dds, + Self::Farbfeld => image::ImageFormat::Farbfeld, + Self::Gif => image::ImageFormat::Gif, #[cfg(feature = "exr")] - ImageFormat::OpenExr => image::ImageFormat::OpenExr, + Self::OpenExr => image::ImageFormat::OpenExr, #[cfg(feature = "hdr")] - ImageFormat::Hdr => image::ImageFormat::Hdr, - ImageFormat::Ico => image::ImageFormat::Ico, + Self::Hdr => image::ImageFormat::Hdr, + Self::Ico => image::ImageFormat::Ico, #[cfg(feature = "jpeg")] - ImageFormat::Jpeg => image::ImageFormat::Jpeg, + Self::Jpeg => image::ImageFormat::Jpeg, #[cfg(feature = "png")] - ImageFormat::Png => image::ImageFormat::Png, + Self::Png => image::ImageFormat::Png, #[cfg(feature = "pnm")] - ImageFormat::Pnm => image::ImageFormat::Pnm, + Self::Pnm => image::ImageFormat::Pnm, #[cfg(feature = "tga")] - ImageFormat::Tga => image::ImageFormat::Tga, - ImageFormat::Tiff => image::ImageFormat::Tiff, + Self::Tga => image::ImageFormat::Tga, + Self::Tiff => image::ImageFormat::Tiff, #[cfg(feature = "webp")] - ImageFormat::WebP => image::ImageFormat::WebP, + Self::WebP => image::ImageFormat::WebP, #[cfg(feature = "basis-universal")] - ImageFormat::Basis => return None, + Self::Basis => return None, #[cfg(feature = "ktx2")] - ImageFormat::Ktx2 => return None, + Self::Ktx2 => return None, }) } - pub fn from_image_crate_format(format: image::ImageFormat) -> Option { + pub fn from_image_crate_format(format: image::ImageFormat) -> Option { Some(match format { - image::ImageFormat::Avif => ImageFormat::Avif, + image::ImageFormat::Avif => Self::Avif, image::ImageFormat::Bmp => feature_gate!("bmp", Bmp), image::ImageFormat::Dds => feature_gate!("dds", Dds), - image::ImageFormat::Farbfeld => ImageFormat::Farbfeld, - image::ImageFormat::Gif => ImageFormat::Gif, + image::ImageFormat::Farbfeld => Self::Farbfeld, + image::ImageFormat::Gif => Self::Gif, image::ImageFormat::OpenExr => feature_gate!("exr", OpenExr), image::ImageFormat::Hdr => feature_gate!("hdr", Hdr), - image::ImageFormat::Ico => ImageFormat::Ico, + image::ImageFormat::Ico => Self::Ico, image::ImageFormat::Jpeg => feature_gate!("jpeg", Jpeg), image::ImageFormat::Png => feature_gate!("png", Png), image::ImageFormat::Pnm => feature_gate!("pnm", Pnm), image::ImageFormat::Tga => feature_gate!("tga", Tga), - image::ImageFormat::Tiff => ImageFormat::Tiff, + image::ImageFormat::Tiff => Self::Tiff, image::ImageFormat::WebP => feature_gate!("webp", WebP), _ => return None, }) @@ -193,14 +193,14 @@ pub enum ImageSampler { impl ImageSampler { /// Returns an image sampler with [`ImageFilterMode::Linear`] min and mag filters #[inline] - pub fn linear() -> ImageSampler { - ImageSampler::Descriptor(ImageSamplerDescriptor::linear()) + pub fn linear() -> Self { + Self::Descriptor(ImageSamplerDescriptor::linear()) } /// Returns an image sampler with [`ImageFilterMode::Nearest`] min and mag filters #[inline] - pub fn nearest() -> ImageSampler { - ImageSampler::Descriptor(ImageSamplerDescriptor::nearest()) + pub fn nearest() -> Self { + Self::Descriptor(ImageSamplerDescriptor::nearest()) } } @@ -360,8 +360,8 @@ impl Default for ImageSamplerDescriptor { impl ImageSamplerDescriptor { /// Returns a sampler descriptor with [`Linear`](crate::render_resource::FilterMode::Linear) min and mag filters #[inline] - pub fn linear() -> ImageSamplerDescriptor { - ImageSamplerDescriptor { + pub fn linear() -> Self { + Self { mag_filter: ImageFilterMode::Linear, min_filter: ImageFilterMode::Linear, mipmap_filter: ImageFilterMode::Linear, @@ -371,8 +371,8 @@ impl ImageSamplerDescriptor { /// Returns a sampler descriptor with [`Nearest`](crate::render_resource::FilterMode::Nearest) min and mag filters #[inline] - pub fn nearest() -> ImageSamplerDescriptor { - ImageSamplerDescriptor { + pub fn nearest() -> Self { + Self { mag_filter: ImageFilterMode::Nearest, min_filter: ImageFilterMode::Nearest, mipmap_filter: ImageFilterMode::Nearest, @@ -401,10 +401,10 @@ impl ImageSamplerDescriptor { impl From for wgpu::AddressMode { fn from(value: ImageAddressMode) -> Self { match value { - ImageAddressMode::ClampToEdge => wgpu::AddressMode::ClampToEdge, - ImageAddressMode::Repeat => wgpu::AddressMode::Repeat, - ImageAddressMode::MirrorRepeat => wgpu::AddressMode::MirrorRepeat, - ImageAddressMode::ClampToBorder => wgpu::AddressMode::ClampToBorder, + ImageAddressMode::ClampToEdge => Self::ClampToEdge, + ImageAddressMode::Repeat => Self::Repeat, + ImageAddressMode::MirrorRepeat => Self::MirrorRepeat, + ImageAddressMode::ClampToBorder => Self::ClampToBorder, } } } @@ -412,8 +412,8 @@ impl From for wgpu::AddressMode { impl From for wgpu::FilterMode { fn from(value: ImageFilterMode) -> Self { match value { - ImageFilterMode::Nearest => wgpu::FilterMode::Nearest, - ImageFilterMode::Linear => wgpu::FilterMode::Linear, + ImageFilterMode::Nearest => Self::Nearest, + ImageFilterMode::Linear => Self::Linear, } } } @@ -421,14 +421,14 @@ impl From for wgpu::FilterMode { impl From for wgpu::CompareFunction { fn from(value: ImageCompareFunction) -> Self { match value { - ImageCompareFunction::Never => wgpu::CompareFunction::Never, - ImageCompareFunction::Less => wgpu::CompareFunction::Less, - ImageCompareFunction::Equal => wgpu::CompareFunction::Equal, - ImageCompareFunction::LessEqual => wgpu::CompareFunction::LessEqual, - ImageCompareFunction::Greater => wgpu::CompareFunction::Greater, - ImageCompareFunction::NotEqual => wgpu::CompareFunction::NotEqual, - ImageCompareFunction::GreaterEqual => wgpu::CompareFunction::GreaterEqual, - ImageCompareFunction::Always => wgpu::CompareFunction::Always, + ImageCompareFunction::Never => Self::Never, + ImageCompareFunction::Less => Self::Less, + ImageCompareFunction::Equal => Self::Equal, + ImageCompareFunction::LessEqual => Self::LessEqual, + ImageCompareFunction::Greater => Self::Greater, + ImageCompareFunction::NotEqual => Self::NotEqual, + ImageCompareFunction::GreaterEqual => Self::GreaterEqual, + ImageCompareFunction::Always => Self::Always, } } } @@ -436,10 +436,10 @@ impl From for wgpu::CompareFunction { impl From for wgpu::SamplerBorderColor { fn from(value: ImageSamplerBorderColor) -> Self { match value { - ImageSamplerBorderColor::TransparentBlack => wgpu::SamplerBorderColor::TransparentBlack, - ImageSamplerBorderColor::OpaqueBlack => wgpu::SamplerBorderColor::OpaqueBlack, - ImageSamplerBorderColor::OpaqueWhite => wgpu::SamplerBorderColor::OpaqueWhite, - ImageSamplerBorderColor::Zero => wgpu::SamplerBorderColor::Zero, + ImageSamplerBorderColor::TransparentBlack => Self::TransparentBlack, + ImageSamplerBorderColor::OpaqueBlack => Self::OpaqueBlack, + ImageSamplerBorderColor::OpaqueWhite => Self::OpaqueWhite, + ImageSamplerBorderColor::Zero => Self::Zero, } } } @@ -447,10 +447,10 @@ impl From for wgpu::SamplerBorderColor { impl From for ImageAddressMode { fn from(value: wgpu::AddressMode) -> Self { match value { - wgpu::AddressMode::ClampToEdge => ImageAddressMode::ClampToEdge, - wgpu::AddressMode::Repeat => ImageAddressMode::Repeat, - wgpu::AddressMode::MirrorRepeat => ImageAddressMode::MirrorRepeat, - wgpu::AddressMode::ClampToBorder => ImageAddressMode::ClampToBorder, + wgpu::AddressMode::ClampToEdge => Self::ClampToEdge, + wgpu::AddressMode::Repeat => Self::Repeat, + wgpu::AddressMode::MirrorRepeat => Self::MirrorRepeat, + wgpu::AddressMode::ClampToBorder => Self::ClampToBorder, } } } @@ -458,8 +458,8 @@ impl From for ImageAddressMode { impl From for ImageFilterMode { fn from(value: wgpu::FilterMode) -> Self { match value { - wgpu::FilterMode::Nearest => ImageFilterMode::Nearest, - wgpu::FilterMode::Linear => ImageFilterMode::Linear, + wgpu::FilterMode::Nearest => Self::Nearest, + wgpu::FilterMode::Linear => Self::Linear, } } } @@ -467,14 +467,14 @@ impl From for ImageFilterMode { impl From for ImageCompareFunction { fn from(value: wgpu::CompareFunction) -> Self { match value { - wgpu::CompareFunction::Never => ImageCompareFunction::Never, - wgpu::CompareFunction::Less => ImageCompareFunction::Less, - wgpu::CompareFunction::Equal => ImageCompareFunction::Equal, - wgpu::CompareFunction::LessEqual => ImageCompareFunction::LessEqual, - wgpu::CompareFunction::Greater => ImageCompareFunction::Greater, - wgpu::CompareFunction::NotEqual => ImageCompareFunction::NotEqual, - wgpu::CompareFunction::GreaterEqual => ImageCompareFunction::GreaterEqual, - wgpu::CompareFunction::Always => ImageCompareFunction::Always, + wgpu::CompareFunction::Never => Self::Never, + wgpu::CompareFunction::Less => Self::Less, + wgpu::CompareFunction::Equal => Self::Equal, + wgpu::CompareFunction::LessEqual => Self::LessEqual, + wgpu::CompareFunction::Greater => Self::Greater, + wgpu::CompareFunction::NotEqual => Self::NotEqual, + wgpu::CompareFunction::GreaterEqual => Self::GreaterEqual, + wgpu::CompareFunction::Always => Self::Always, } } } @@ -482,17 +482,17 @@ impl From for ImageCompareFunction { impl From for ImageSamplerBorderColor { fn from(value: wgpu::SamplerBorderColor) -> Self { match value { - wgpu::SamplerBorderColor::TransparentBlack => ImageSamplerBorderColor::TransparentBlack, - wgpu::SamplerBorderColor::OpaqueBlack => ImageSamplerBorderColor::OpaqueBlack, - wgpu::SamplerBorderColor::OpaqueWhite => ImageSamplerBorderColor::OpaqueWhite, - wgpu::SamplerBorderColor::Zero => ImageSamplerBorderColor::Zero, + wgpu::SamplerBorderColor::TransparentBlack => Self::TransparentBlack, + wgpu::SamplerBorderColor::OpaqueBlack => Self::OpaqueBlack, + wgpu::SamplerBorderColor::OpaqueWhite => Self::OpaqueWhite, + wgpu::SamplerBorderColor::Zero => Self::Zero, } } } impl<'a> From> for ImageSamplerDescriptor { fn from(value: wgpu::SamplerDescriptor) -> Self { - ImageSamplerDescriptor { + Self { label: value.label.map(ToString::to_string), address_mode_u: value.address_mode_u.into(), address_mode_v: value.address_mode_v.into(), @@ -514,7 +514,7 @@ impl Default for Image { fn default() -> Self { let format = TextureFormat::bevy_default(); let data = vec![255; format.pixel_size()]; - Image { + Self { data, texture_descriptor: wgpu::TextureDescriptor { size: Extent3d { @@ -569,14 +569,14 @@ impl Image { /// A transparent white 1x1x1 image. /// /// Contrast to [`Image::default`], which is opaque. - pub fn transparent() -> Image { + pub fn transparent() -> Self { // We rely on the default texture format being RGBA8UnormSrgb // when constructing a transparent color from bytes. // If this changes, this function will need to be updated. let format = TextureFormat::bevy_default(); debug_assert!(format.pixel_size() == 4); let data = vec![255, 255, 255, 0]; - Image { + Self { data, texture_descriptor: wgpu::TextureDescriptor { size: Extent3d { @@ -610,7 +610,7 @@ impl Image { format: TextureFormat, asset_usage: RenderAssetUsages, ) -> Self { - let mut value = Image::default(); + let mut value = Self::default(); value.texture_descriptor.format = format; value.texture_descriptor.dimension = dimension; value.asset_usage = asset_usage; @@ -749,7 +749,7 @@ impl Image { is_srgb: bool, image_sampler: ImageSampler, asset_usage: RenderAssetUsages, - ) -> Result { + ) -> Result { let format = image_type.to_image_format()?; // Load the image in the expected format. @@ -961,7 +961,7 @@ impl RenderAsset for GpuImage { } }; - Ok(GpuImage { + Ok(Self { texture, texture_view, texture_format: image.texture_descriptor.format, @@ -1013,7 +1013,7 @@ impl CompressedImageFormats { | TextureFormat::Bc6hRgbUfloat | TextureFormat::Bc6hRgbFloat | TextureFormat::Bc7RgbaUnorm - | TextureFormat::Bc7RgbaUnormSrgb => self.contains(CompressedImageFormats::BC), + | TextureFormat::Bc7RgbaUnormSrgb => self.contains(Self::BC), TextureFormat::Etc2Rgb8Unorm | TextureFormat::Etc2Rgb8UnormSrgb | TextureFormat::Etc2Rgb8A1Unorm @@ -1023,8 +1023,8 @@ impl CompressedImageFormats { | TextureFormat::EacR11Unorm | TextureFormat::EacR11Snorm | TextureFormat::EacRg11Unorm - | TextureFormat::EacRg11Snorm => self.contains(CompressedImageFormats::ETC2), - TextureFormat::Astc { .. } => self.contains(CompressedImageFormats::ASTC_LDR), + | TextureFormat::EacRg11Snorm => self.contains(Self::ETC2), + TextureFormat::Astc { .. } => self.contains(Self::ASTC_LDR), _ => true, } } diff --git a/crates/bevy_render/src/texture/image_texture_conversion.rs b/crates/bevy_render/src/texture/image_texture_conversion.rs index 5284c0adcca10..d6fe2e3200bc4 100644 --- a/crates/bevy_render/src/texture/image_texture_conversion.rs +++ b/crates/bevy_render/src/texture/image_texture_conversion.rs @@ -12,7 +12,7 @@ impl Image { dyn_img: DynamicImage, is_srgb: bool, asset_usage: RenderAssetUsages, - ) -> Image { + ) -> Self { use bytemuck::cast_slice; let width; let height; @@ -149,7 +149,7 @@ impl Image { } } - Image::new( + Self::new( Extent3d { width, height, diff --git a/crates/bevy_render/src/texture/mod.rs b/crates/bevy_render/src/texture/mod.rs index 9b1a592773409..8489c8cea2682 100644 --- a/crates/bevy_render/src/texture/mod.rs +++ b/crates/bevy_render/src/texture/mod.rs @@ -60,21 +60,21 @@ pub struct ImagePlugin { impl Default for ImagePlugin { fn default() -> Self { - ImagePlugin::default_linear() + Self::default_linear() } } impl ImagePlugin { /// Creates image settings with linear sampling by default. - pub fn default_linear() -> ImagePlugin { - ImagePlugin { + pub fn default_linear() -> Self { + Self { default_sampler: ImageSamplerDescriptor::linear(), } } /// Creates image settings with nearest sampling by default. - pub fn default_nearest() -> ImagePlugin { - ImagePlugin { + pub fn default_nearest() -> Self { + Self { default_sampler: ImageSamplerDescriptor::nearest(), } } @@ -172,6 +172,6 @@ pub trait BevyDefault { impl BevyDefault for wgpu::TextureFormat { fn bevy_default() -> Self { - wgpu::TextureFormat::Rgba8UnormSrgb + Self::Rgba8UnormSrgb } } diff --git a/crates/bevy_render/src/view/mod.rs b/crates/bevy_render/src/view/mod.rs index f9c4a5c59b4d7..d70139de9b784 100644 --- a/crates/bevy_render/src/view/mod.rs +++ b/crates/bevy_render/src/view/mod.rs @@ -381,8 +381,8 @@ impl ColorGrading { pub fn with_identical_sections( global: ColorGradingGlobal, section: ColorGradingSection, - ) -> ColorGrading { - ColorGrading { + ) -> Self { + Self { global, highlights: section, midtones: section, @@ -641,7 +641,7 @@ impl ViewTarget { /// Returns `true` if and only if the main texture is [`Self::TEXTURE_FORMAT_HDR`] #[inline] pub fn is_hdr(&self) -> bool { - self.main_texture_format == ViewTarget::TEXTURE_FORMAT_HDR + self.main_texture_format == Self::TEXTURE_FORMAT_HDR } /// The final texture this view will render to. diff --git a/crates/bevy_render/src/view/visibility/mod.rs b/crates/bevy_render/src/view/visibility/mod.rs index 341404d189fdb..a966bdcdac549 100644 --- a/crates/bevy_render/src/view/visibility/mod.rs +++ b/crates/bevy_render/src/view/visibility/mod.rs @@ -57,11 +57,11 @@ impl PartialEq for &Visibility { } // Allows `Visibility == &Visibility` -impl PartialEq<&Visibility> for Visibility { +impl PartialEq<&Self> for Visibility { #[inline] - fn eq(&self, other: &&Visibility) -> bool { + fn eq(&self, other: &&Self) -> bool { // Use the base Visibility == Visibility implementation. - >::eq(self, *other) + >::eq(self, *other) } } diff --git a/crates/bevy_render/src/view/visibility/render_layers.rs b/crates/bevy_render/src/view/visibility/render_layers.rs index 9c2f5a258de52..e162b33057394 100644 --- a/crates/bevy_render/src/view/visibility/render_layers.rs +++ b/crates/bevy_render/src/view/visibility/render_layers.rs @@ -43,7 +43,7 @@ impl std::fmt::Debug for RenderLayers { impl FromIterator for RenderLayers { fn from_iter>(i: T) -> Self { - i.into_iter().fold(Self::none(), RenderLayers::with) + i.into_iter().fold(Self::none(), Self::with) } } @@ -66,14 +66,14 @@ impl RenderLayers { ); let mut buffer = [0; INLINE_BLOCKS]; buffer[buffer_index] = bit; - RenderLayers(SmallVec::from_const(buffer)) + Self(SmallVec::from_const(buffer)) } /// Create a new `RenderLayers` that belongs to no layers. /// /// This is distinct from [`RenderLayers::default`], which belongs to the first layer. pub const fn none() -> Self { - RenderLayers(SmallVec::from_const([0; INLINE_BLOCKS])) + Self(SmallVec::from_const([0; INLINE_BLOCKS])) } /// Create a `RenderLayers` from a list of layers. @@ -119,7 +119,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 fn intersects(&self, other: &Self) -> bool { // Check for the common case where the view layer and entity layer // both point towards our default layer. if self.0.as_ptr() == other.0.as_ptr() { diff --git a/crates/bevy_render/src/view/window/cursor.rs b/crates/bevy_render/src/view/window/cursor.rs index eed41cec114be..5b2c7083f7d3f 100644 --- a/crates/bevy_render/src/view/window/cursor.rs +++ b/crates/bevy_render/src/view/window/cursor.rs @@ -31,19 +31,19 @@ pub enum CursorIcon { impl Default for CursorIcon { fn default() -> Self { - CursorIcon::System(Default::default()) + Self::System(Default::default()) } } impl From for CursorIcon { fn from(icon: SystemCursorIcon) -> Self { - CursorIcon::System(icon) + Self::System(icon) } } impl From for CursorIcon { fn from(cursor: CustomCursor) -> Self { - CursorIcon::Custom(cursor) + Self::Custom(cursor) } } diff --git a/crates/bevy_scene/src/scene.rs b/crates/bevy_scene/src/scene.rs index f852d356b390b..a6d1c1f157f67 100644 --- a/crates/bevy_scene/src/scene.rs +++ b/crates/bevy_scene/src/scene.rs @@ -29,11 +29,10 @@ impl Scene { pub fn from_dynamic_scene( dynamic_scene: &DynamicScene, type_registry: &AppTypeRegistry, - ) -> Result { + ) -> Result { let mut world = World::new(); let mut entity_map = EntityHashMap::default(); dynamic_scene.write_to_world_with(&mut world, &mut entity_map, type_registry)?; - Ok(Self { world }) } @@ -41,7 +40,7 @@ impl Scene { /// /// This method will return a [`SceneSpawnError`] if a type either is not registered in the /// provided [`AppTypeRegistry`] or doesn't reflect the [`Component`](bevy_ecs::component::Component) trait. - pub fn clone_with(&self, type_registry: &AppTypeRegistry) -> Result { + pub fn clone_with(&self, type_registry: &AppTypeRegistry) -> Result { let mut new_world = World::new(); let mut entity_map = EntityHashMap::default(); self.write_to_world_with(&mut new_world, &mut entity_map, type_registry)?; diff --git a/crates/bevy_scene/src/scene_loader.rs b/crates/bevy_scene/src/scene_loader.rs index 566a573560d0f..60b7d44a1e1bd 100644 --- a/crates/bevy_scene/src/scene_loader.rs +++ b/crates/bevy_scene/src/scene_loader.rs @@ -21,7 +21,7 @@ pub struct SceneLoader { impl FromWorld for SceneLoader { fn from_world(world: &mut World) -> Self { let type_registry = world.resource::(); - SceneLoader { + Self { type_registry: type_registry.0.clone(), } } diff --git a/crates/bevy_scene/src/scene_spawner.rs b/crates/bevy_scene/src/scene_spawner.rs index 9aa59bb6fd8ed..063edb834285d 100644 --- a/crates/bevy_scene/src/scene_spawner.rs +++ b/crates/bevy_scene/src/scene_spawner.rs @@ -37,7 +37,7 @@ pub struct InstanceId(Uuid); impl InstanceId { fn new() -> Self { - InstanceId(Uuid::new_v4()) + Self(Uuid::new_v4()) } } diff --git a/crates/bevy_sprite/src/lib.rs b/crates/bevy_sprite/src/lib.rs index 77a31f505e0b8..ad4e6108c1c2f 100644 --- a/crates/bevy_sprite/src/lib.rs +++ b/crates/bevy_sprite/src/lib.rs @@ -219,13 +219,11 @@ pub fn calculate_bounds_2d( impl ExtractComponent for SpriteSource { type QueryData = (); - - type QueryFilter = With; - - type Out = SpriteSource; + type QueryFilter = With; + type Out = Self; fn extract_component(_: QueryItem<'_, Self::QueryData>) -> Option { - Some(SpriteSource) + Some(Self) } } diff --git a/crates/bevy_sprite/src/mesh2d/color_material.rs b/crates/bevy_sprite/src/mesh2d/color_material.rs index 2df333539a2b5..c0ea59163e241 100644 --- a/crates/bevy_sprite/src/mesh2d/color_material.rs +++ b/crates/bevy_sprite/src/mesh2d/color_material.rs @@ -61,7 +61,7 @@ impl ColorMaterial { impl Default for ColorMaterial { fn default() -> Self { - ColorMaterial { + Self { color: Color::WHITE, texture: None, // TODO should probably default to AlphaMask once supported? @@ -72,7 +72,7 @@ impl Default for ColorMaterial { impl From for ColorMaterial { fn from(color: Color) -> Self { - ColorMaterial { + Self { color, alpha_mode: if color.alpha() < 1.0 { AlphaMode2d::Blend @@ -86,7 +86,7 @@ impl From for ColorMaterial { impl From> for ColorMaterial { fn from(texture: Handle) -> Self { - ColorMaterial { + Self { texture: Some(texture), ..Default::default() } diff --git a/crates/bevy_sprite/src/mesh2d/material.rs b/crates/bevy_sprite/src/mesh2d/material.rs index 58a02ba13048c..1c30241acfb4d 100644 --- a/crates/bevy_sprite/src/mesh2d/material.rs +++ b/crates/bevy_sprite/src/mesh2d/material.rs @@ -322,8 +322,7 @@ impl FromWorld for Material2dPipeline { let asset_server = world.resource::(); let render_device = world.resource::(); let material2d_layout = M::bind_group_layout(render_device); - - Material2dPipeline { + Self { mesh2d_pipeline: world.resource::().clone(), material2d_layout, vertex_shader: match M::vertex_shader() { @@ -601,7 +600,7 @@ impl RenderAsset for PreparedMaterial2d { Ok(prepared) => { let mut mesh_pipeline_key_bits = Mesh2dPipelineKey::empty(); mesh_pipeline_key_bits.insert(alpha_mode_pipeline_key(material.alpha_mode())); - Ok(PreparedMaterial2d { + Ok(Self { bindings: prepared.bindings, bind_group: prepared.bind_group, key: prepared.data, diff --git a/crates/bevy_sprite/src/mesh2d/mesh.rs b/crates/bevy_sprite/src/mesh2d/mesh.rs index 8bce6f1cb6529..a7db650bb70ee 100644 --- a/crates/bevy_sprite/src/mesh2d/mesh.rs +++ b/crates/bevy_sprite/src/mesh2d/mesh.rs @@ -339,7 +339,7 @@ impl FromWorld for Mesh2dPipeline { mip_level_count: image.texture_descriptor.mip_level_count, } }; - Mesh2dPipeline { + Self { view_layout, mesh_layout, dummy_white_gpu_image, @@ -511,9 +511,9 @@ impl Mesh2dPipelineKey { pub fn from_hdr(hdr: bool) -> Self { if hdr { - Mesh2dPipelineKey::HDR + Self::HDR } else { - Mesh2dPipelineKey::NONE + Self::NONE } } diff --git a/crates/bevy_sprite/src/render/mod.rs b/crates/bevy_sprite/src/render/mod.rs index 60c64131fe12b..902392b999881 100644 --- a/crates/bevy_sprite/src/render/mod.rs +++ b/crates/bevy_sprite/src/render/mod.rs @@ -122,7 +122,7 @@ impl FromWorld for SpritePipeline { } }; - SpritePipeline { + Self { view_layout, material_layout, dummy_white_gpu_image, @@ -175,9 +175,9 @@ impl SpritePipelineKey { #[inline] pub const fn from_hdr(hdr: bool) -> Self { if hdr { - SpritePipelineKey::HDR + Self::HDR } else { - SpritePipelineKey::NONE + Self::NONE } } } diff --git a/crates/bevy_sprite/src/sprite.rs b/crates/bevy_sprite/src/sprite.rs index ae57eb760c091..cde61d1caec62 100644 --- a/crates/bevy_sprite/src/sprite.rs +++ b/crates/bevy_sprite/src/sprite.rs @@ -72,16 +72,16 @@ pub enum Anchor { impl Anchor { pub fn as_vec(&self) -> Vec2 { match self { - Anchor::Center => Vec2::ZERO, - Anchor::BottomLeft => Vec2::new(-0.5, -0.5), - Anchor::BottomCenter => Vec2::new(0.0, -0.5), - Anchor::BottomRight => Vec2::new(0.5, -0.5), - Anchor::CenterLeft => Vec2::new(-0.5, 0.0), - Anchor::CenterRight => Vec2::new(0.5, 0.0), - Anchor::TopLeft => Vec2::new(-0.5, 0.5), - Anchor::TopCenter => Vec2::new(0.0, 0.5), - Anchor::TopRight => Vec2::new(0.5, 0.5), - Anchor::Custom(point) => *point, + Self::Center => Vec2::ZERO, + Self::BottomLeft => Vec2::new(-0.5, -0.5), + Self::BottomCenter => Vec2::new(0.0, -0.5), + Self::BottomRight => Vec2::new(0.5, -0.5), + Self::CenterLeft => Vec2::new(-0.5, 0.0), + Self::CenterRight => Vec2::new(0.5, 0.0), + Self::TopLeft => Vec2::new(-0.5, 0.5), + Self::TopCenter => Vec2::new(0.0, 0.5), + Self::TopRight => Vec2::new(0.5, 0.5), + Self::Custom(point) => *point, } } } diff --git a/crates/bevy_state/src/reflect.rs b/crates/bevy_state/src/reflect.rs index 422d4aff1a341..74a20079992d0 100644 --- a/crates/bevy_state/src/reflect.rs +++ b/crates/bevy_state/src/reflect.rs @@ -38,7 +38,7 @@ impl ReflectState { impl FromType for ReflectState { fn from_type() -> Self { - ReflectState(ReflectStateFns { + Self(ReflectStateFns { reflect: |world| { world .get_resource::>() @@ -82,7 +82,7 @@ impl ReflectFreelyMutableState { impl FromType for ReflectFreelyMutableState { fn from_type() -> Self { - ReflectFreelyMutableState(ReflectFreelyMutableStateFns { + Self(ReflectFreelyMutableStateFns { set_next_state: |world, reflected_state, registry| { let new_state: S = from_reflect_with_fallback( reflected_state.as_partial_reflect(), diff --git a/crates/bevy_state/src/state/mod.rs b/crates/bevy_state/src/state/mod.rs index 5e5ea005df0d7..428cd5361ef59 100644 --- a/crates/bevy_state/src/state/mod.rs +++ b/crates/bevy_state/src/state/mod.rs @@ -242,9 +242,9 @@ mod tests { if simple == SimpleState::A && (complex.a_flexible_value == "bob" || complex.a_flexible_value == "jane") { - Some(ComplexComputedState::InAAndStrIsBobOrJane) + Some(Self::InAAndStrIsBobOrJane) } else if simple == SimpleState::B(true) && complex.another_value > 8 { - Some(ComplexComputedState::InTrueBAndUsizeAbove8) + Some(Self::InTrueBAndUsizeAbove8) } else { None } @@ -343,11 +343,9 @@ mod tests { fn compute((s1, s2): (Option, Option)) -> Option { match (s1, s2) { - (Some(SimpleState::A), Some(SimpleState2::A1)) => Some(TestNewcomputedState::A1), - (Some(SimpleState::B(true)), Some(SimpleState2::B2)) => { - Some(TestNewcomputedState::B2) - } - (Some(SimpleState::B(true)), _) => Some(TestNewcomputedState::B1), + (Some(SimpleState::A), Some(SimpleState2::A1)) => Some(Self::A1), + (Some(SimpleState::B(true)), Some(SimpleState2::B2)) => Some(Self::B2), + (Some(SimpleState::B(true)), _) => Some(Self::B1), _ => None, } } diff --git a/crates/bevy_tasks/src/task_pool.rs b/crates/bevy_tasks/src/task_pool.rs index dd892e7decc77..9832755b8dcc8 100644 --- a/crates/bevy_tasks/src/task_pool.rs +++ b/crates/bevy_tasks/src/task_pool.rs @@ -160,7 +160,7 @@ impl TaskPool { thread_builder .spawn(move || { - TaskPool::LOCAL_EXECUTOR.with(|local_executor| { + Self::LOCAL_EXECUTOR.with(|local_executor| { if let Some(on_thread_spawn) = on_thread_spawn { on_thread_spawn(); drop(on_thread_spawn); @@ -551,7 +551,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))) } /// Runs a function with the local executor. Typically used to tick diff --git a/crates/bevy_text/src/font_atlas.rs b/crates/bevy_text/src/font_atlas.rs index b5e0dfb575f7e..b67c1877dde6e 100644 --- a/crates/bevy_text/src/font_atlas.rs +++ b/crates/bevy_text/src/font_atlas.rs @@ -39,7 +39,7 @@ impl FontAtlas { textures: &mut Assets, texture_atlases_layout: &mut Assets, size: UVec2, - ) -> FontAtlas { + ) -> Self { let texture = textures.add(Image::new_fill( Extent3d { width: size.x, diff --git a/crates/bevy_text/src/font_atlas_set.rs b/crates/bevy_text/src/font_atlas_set.rs index e4d11b60c0617..356e7529683cc 100644 --- a/crates/bevy_text/src/font_atlas_set.rs +++ b/crates/bevy_text/src/font_atlas_set.rs @@ -54,7 +54,7 @@ pub fn remove_dropped_font_atlas_sets( pub struct FontSizeKey(pub u32); impl From for FontSizeKey { - fn from(val: u32) -> FontSizeKey { + fn from(val: u32) -> Self { Self(val) } } @@ -82,7 +82,7 @@ pub struct FontAtlasSet { 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/text.rs b/crates/bevy_text/src/text.rs index 9172b6896e96b..337ffb640b067 100644 --- a/crates/bevy_text/src/text.rs +++ b/crates/bevy_text/src/text.rs @@ -199,10 +199,10 @@ pub enum JustifyText { impl From for cosmic_text::Align { fn from(justify: JustifyText) -> Self { match justify { - JustifyText::Left => cosmic_text::Align::Left, - JustifyText::Center => cosmic_text::Align::Center, - JustifyText::Right => cosmic_text::Align::Right, - JustifyText::Justified => cosmic_text::Align::Justified, + JustifyText::Left => Self::Left, + JustifyText::Center => Self::Center, + JustifyText::Right => Self::Right, + JustifyText::Justified => Self::Justified, } } } diff --git a/crates/bevy_time/src/fixed.rs b/crates/bevy_time/src/fixed.rs index a49763905577a..d7637975590fb 100644 --- a/crates/bevy_time/src/fixed.rs +++ b/crates/bevy_time/src/fixed.rs @@ -226,7 +226,7 @@ impl Time { impl Default for Fixed { fn default() -> Self { Self { - timestep: Time::::DEFAULT_TIMESTEP, + timestep: Time::::DEFAULT_TIMESTEP, overstep: Duration::ZERO, } } diff --git a/crates/bevy_time/src/virt.rs b/crates/bevy_time/src/virt.rs index 58eade3333d49..808e4f265bf07 100644 --- a/crates/bevy_time/src/virt.rs +++ b/crates/bevy_time/src/virt.rs @@ -258,7 +258,7 @@ impl Time { impl Default for Virtual { fn default() -> Self { Self { - max_delta: Time::::DEFAULT_MAX_DELTA, + max_delta: Time::::DEFAULT_MAX_DELTA, paused: false, relative_speed: 1.0, effective_speed: 1.0, diff --git a/crates/bevy_transform/src/bundles.rs b/crates/bevy_transform/src/bundles.rs index dc8931824a7fd..feae968f6551b 100644 --- a/crates/bevy_transform/src/bundles.rs +++ b/crates/bevy_transform/src/bundles.rs @@ -33,7 +33,7 @@ pub struct TransformBundle { impl TransformBundle { /// An identity [`TransformBundle`] with no translation, rotation, and a scale of 1 on all axes. - pub const IDENTITY: Self = TransformBundle { + pub const IDENTITY: Self = Self { local: Transform::IDENTITY, global: GlobalTransform::IDENTITY, }; @@ -44,7 +44,7 @@ impl TransformBundle { /// [`bevy_app::PostUpdate`] schedule. #[inline] pub const fn from_transform(transform: Transform) -> Self { - TransformBundle { + Self { local: transform, ..Self::IDENTITY } diff --git a/crates/bevy_transform/src/components/global_transform.rs b/crates/bevy_transform/src/components/global_transform.rs index dd8f4ca08f5a3..ecbc19d981cbd 100644 --- a/crates/bevy_transform/src/components/global_transform.rs +++ b/crates/bevy_transform/src/components/global_transform.rs @@ -72,19 +72,19 @@ impl GlobalTransform { #[doc(hidden)] #[inline] pub fn from_translation(translation: Vec3) -> Self { - GlobalTransform(Affine3A::from_translation(translation)) + Self(Affine3A::from_translation(translation)) } #[doc(hidden)] #[inline] pub fn from_rotation(rotation: Quat) -> Self { - GlobalTransform(Affine3A::from_rotation_translation(rotation, Vec3::ZERO)) + Self(Affine3A::from_rotation_translation(rotation, Vec3::ZERO)) } #[doc(hidden)] #[inline] pub fn from_scale(scale: Vec3) -> Self { - GlobalTransform(Affine3A::from_scale(scale)) + Self(Affine3A::from_scale(scale)) } #[doc(hidden)] @@ -166,7 +166,7 @@ impl GlobalTransform { /// The transform is expected to be non-degenerate and without shearing, or the output /// will be invalid. #[inline] - pub fn reparented_to(&self, parent: &GlobalTransform) -> Transform { + pub fn reparented_to(&self, parent: &Self) -> Transform { let relative_affine = parent.affine().inverse() * self.affine(); let (scale, rotation, translation) = relative_affine.to_scale_rotation_translation(); Transform { @@ -277,17 +277,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 { - GlobalTransform(self.0 * global_transform.0) + fn mul(self, global_transform: Self) -> Self::Output { + Self(self.0 * global_transform.0) } } 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/transform.rs b/crates/bevy_transform/src/components/transform.rs index f0d89017454d3..f214c8588f851 100644 --- a/crates/bevy_transform/src/components/transform.rs +++ b/crates/bevy_transform/src/components/transform.rs @@ -63,7 +63,7 @@ pub struct Transform { impl Transform { /// An identity [`Transform`] with no translation, rotation, and a scale of 1 on all axes. - pub const IDENTITY: Self = Transform { + pub const IDENTITY: Self = Self { translation: Vec3::ZERO, rotation: Quat::IDENTITY, scale: Vec3::ONE, @@ -82,8 +82,7 @@ impl Transform { #[inline] pub fn from_matrix(world_from_local: Mat4) -> Self { let (scale, rotation, translation) = world_from_local.to_scale_rotation_translation(); - - Transform { + Self { translation, rotation, scale, @@ -94,7 +93,7 @@ impl Transform { /// all axes. #[inline] pub const fn from_translation(translation: Vec3) -> Self { - Transform { + Self { translation, ..Self::IDENTITY } @@ -104,7 +103,7 @@ impl Transform { /// all axes. #[inline] pub const fn from_rotation(rotation: Quat) -> Self { - Transform { + Self { rotation, ..Self::IDENTITY } @@ -114,7 +113,7 @@ impl Transform { /// all axes. #[inline] pub const fn from_scale(scale: Vec3) -> Self { - Transform { + Self { scale, ..Self::IDENTITY } @@ -125,7 +124,7 @@ impl Transform { /// [isometry]: Isometry3d #[inline] pub fn from_isometry(iso: Isometry3d) -> Self { - Transform { + Self { translation: iso.translation.into(), rotation: iso.rotation, ..Self::IDENTITY @@ -499,11 +498,11 @@ impl Transform { /// resulting [`Transform`] #[inline] #[must_use] - pub fn mul_transform(&self, transform: Transform) -> Self { + pub fn mul_transform(&self, transform: Self) -> Self { let translation = self.transform_point(transform.translation); let rotation = self.rotation * transform.rotation; let scale = self.scale * transform.scale; - Transform { + Self { translation, rotation, scale, @@ -561,10 +560,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_ui/src/geometry.rs b/crates/bevy_ui/src/geometry.rs index 610fc8fb7a39c..504dc90ba9a69 100644 --- a/crates/bevy_ui/src/geometry.rs +++ b/crates/bevy_ui/src/geometry.rs @@ -102,17 +102,17 @@ impl Default for Val { } impl Mul for Val { - type Output = Val; + type Output = Self; fn mul(self, rhs: f32) -> Self::Output { match self { - Val::Auto => Val::Auto, - Val::Px(value) => Val::Px(value * rhs), - Val::Percent(value) => Val::Percent(value * rhs), - Val::Vw(value) => Val::Vw(value * rhs), - Val::Vh(value) => Val::Vh(value * rhs), - Val::VMin(value) => Val::VMin(value * rhs), - Val::VMax(value) => Val::VMax(value * rhs), + Self::Auto => Self::Auto, + Self::Px(value) => Self::Px(value * rhs), + Self::Percent(value) => Self::Percent(value * rhs), + Self::Vw(value) => Self::Vw(value * rhs), + Self::Vh(value) => Self::Vh(value * rhs), + Self::VMin(value) => Self::VMin(value * rhs), + Self::VMax(value) => Self::VMax(value * rhs), } } } @@ -120,29 +120,29 @@ impl Mul for Val { impl MulAssign for Val { fn mul_assign(&mut self, rhs: f32) { match self { - Val::Auto => {} - Val::Px(value) - | Val::Percent(value) - | Val::Vw(value) - | Val::Vh(value) - | Val::VMin(value) - | Val::VMax(value) => *value *= rhs, + Self::Auto => {} + Self::Px(value) + | Self::Percent(value) + | Self::Vw(value) + | Self::Vh(value) + | Self::VMin(value) + | Self::VMax(value) => *value *= rhs, } } } impl Div for Val { - type Output = Val; + type Output = Self; fn div(self, rhs: f32) -> Self::Output { match self { - Val::Auto => Val::Auto, - Val::Px(value) => Val::Px(value / rhs), - Val::Percent(value) => Val::Percent(value / rhs), - Val::Vw(value) => Val::Vw(value / rhs), - Val::Vh(value) => Val::Vh(value / rhs), - Val::VMin(value) => Val::VMin(value / rhs), - Val::VMax(value) => Val::VMax(value / rhs), + Self::Auto => Self::Auto, + Self::Px(value) => Self::Px(value / rhs), + Self::Percent(value) => Self::Percent(value / rhs), + Self::Vw(value) => Self::Vw(value / rhs), + Self::Vh(value) => Self::Vh(value / rhs), + Self::VMin(value) => Self::VMin(value / rhs), + Self::VMax(value) => Self::VMax(value / rhs), } } } @@ -150,28 +150,28 @@ impl Div for Val { impl DivAssign for Val { fn div_assign(&mut self, rhs: f32) { match self { - Val::Auto => {} - Val::Px(value) - | Val::Percent(value) - | Val::Vw(value) - | Val::Vh(value) - | Val::VMin(value) - | Val::VMax(value) => *value /= rhs, + Self::Auto => {} + Self::Px(value) + | Self::Percent(value) + | Self::Vw(value) + | Self::Vh(value) + | Self::VMin(value) + | Self::VMax(value) => *value /= rhs, } } } impl Neg for Val { - type Output = Val; + type Output = Self; fn neg(self) -> Self::Output { match self { - Val::Px(value) => Val::Px(-value), - Val::Percent(value) => Val::Percent(-value), - Val::Vw(value) => Val::Vw(-value), - Val::Vh(value) => Val::Vh(-value), - Val::VMin(value) => Val::VMin(-value), - Val::VMax(value) => Val::VMax(-value), + Self::Px(value) => Self::Px(-value), + Self::Percent(value) => Self::Percent(-value), + Self::Vw(value) => Self::Vw(-value), + Self::Vh(value) => Self::Vh(-value), + Self::VMin(value) => Self::VMin(-value), + Self::VMax(value) => Self::VMax(-value), _ => self, } } @@ -192,13 +192,13 @@ impl Val { /// **Note:** If a [`Val::Px`] is resolved, its inner value is returned unchanged. pub fn resolve(self, parent_size: f32, viewport_size: Vec2) -> Result { match self { - Val::Percent(value) => Ok(parent_size * value / 100.0), - Val::Px(value) => Ok(value), - Val::Vw(value) => Ok(viewport_size.x * value / 100.0), - Val::Vh(value) => Ok(viewport_size.y * value / 100.0), - Val::VMin(value) => Ok(viewport_size.min_element() * value / 100.0), - Val::VMax(value) => Ok(viewport_size.max_element() * value / 100.0), - Val::Auto => Err(ValArithmeticError::NonEvaluateable), + Self::Percent(value) => Ok(parent_size * value / 100.0), + Self::Px(value) => Ok(value), + Self::Vw(value) => Ok(viewport_size.x * value / 100.0), + Self::Vh(value) => Ok(viewport_size.y * value / 100.0), + Self::VMin(value) => Ok(viewport_size.min_element() * value / 100.0), + Self::VMax(value) => Ok(viewport_size.max_element() * value / 100.0), + Self::Auto => Err(ValArithmeticError::NonEvaluateable), } } } @@ -301,7 +301,7 @@ impl UiRect { /// assert_eq!(ui_rect.bottom, Val::Px(40.0)); /// ``` pub const fn new(left: Val, right: Val, top: Val, bottom: Val) -> Self { - UiRect { + Self { left, right, top, @@ -324,7 +324,7 @@ impl UiRect { /// assert_eq!(ui_rect.bottom, Val::Px(10.0)); /// ``` pub const fn all(value: Val) -> Self { - UiRect { + Self { left: value, right: value, top: value, @@ -348,7 +348,7 @@ impl UiRect { /// assert_eq!(ui_rect.bottom, Val::Px(40.)); /// ``` pub const fn px(left: f32, right: f32, top: f32, bottom: f32) -> Self { - UiRect { + Self { left: Val::Px(left), right: Val::Px(right), top: Val::Px(top), @@ -372,7 +372,7 @@ impl UiRect { /// assert_eq!(ui_rect.bottom, Val::Percent(1.)); /// ``` pub const fn percent(left: f32, right: f32, top: f32, bottom: f32) -> Self { - UiRect { + Self { left: Val::Percent(left), right: Val::Percent(right), top: Val::Percent(top), @@ -396,7 +396,7 @@ impl UiRect { /// assert_eq!(ui_rect.bottom, Val::ZERO); /// ``` pub fn horizontal(value: Val) -> Self { - UiRect { + Self { left: value, right: value, ..Default::default() @@ -419,7 +419,7 @@ impl UiRect { /// assert_eq!(ui_rect.bottom, Val::Px(10.0)); /// ``` pub fn vertical(value: Val) -> Self { - UiRect { + Self { top: value, bottom: value, ..Default::default() @@ -441,7 +441,7 @@ impl UiRect { /// assert_eq!(ui_rect.bottom, Val::Percent(15.0)); /// ``` pub fn axes(horizontal: Val, vertical: Val) -> Self { - UiRect { + Self { left: horizontal, right: horizontal, top: vertical, @@ -465,7 +465,7 @@ impl UiRect { /// assert_eq!(ui_rect.bottom, Val::ZERO); /// ``` pub fn left(value: Val) -> Self { - UiRect { + Self { left: value, ..Default::default() } @@ -487,7 +487,7 @@ impl UiRect { /// assert_eq!(ui_rect.bottom, Val::ZERO); /// ``` pub fn right(value: Val) -> Self { - UiRect { + Self { right: value, ..Default::default() } @@ -509,7 +509,7 @@ impl UiRect { /// assert_eq!(ui_rect.bottom, Val::ZERO); /// ``` pub fn top(value: Val) -> Self { - UiRect { + Self { top: value, ..Default::default() } @@ -531,7 +531,7 @@ impl UiRect { /// assert_eq!(ui_rect.bottom, Val::Px(10.0)); /// ``` pub fn bottom(value: Val) -> Self { - UiRect { + Self { bottom: value, ..Default::default() } diff --git a/crates/bevy_ui/src/layout/convert.rs b/crates/bevy_ui/src/layout/convert.rs index 8a4a1ae95e449..bf814335dccca 100644 --- a/crates/bevy_ui/src/layout/convert.rs +++ b/crates/bevy_ui/src/layout/convert.rs @@ -15,21 +15,21 @@ impl Val { context: &LayoutContext, ) -> taffy::style::LengthPercentageAuto { match self { - Val::Auto => taffy::style::LengthPercentageAuto::Auto, - Val::Percent(value) => taffy::style::LengthPercentageAuto::Percent(value / 100.), - Val::Px(value) => { + Self::Auto => taffy::style::LengthPercentageAuto::Auto, + Self::Percent(value) => taffy::style::LengthPercentageAuto::Percent(value / 100.), + Self::Px(value) => { taffy::style::LengthPercentageAuto::Length(context.scale_factor * value) } - Val::VMin(value) => { + Self::VMin(value) => { taffy::style::LengthPercentageAuto::Length(context.min_size * value / 100.) } - Val::VMax(value) => { + Self::VMax(value) => { taffy::style::LengthPercentageAuto::Length(context.max_size * value / 100.) } - Val::Vw(value) => { + Self::Vw(value) => { taffy::style::LengthPercentageAuto::Length(context.physical_size.x * value / 100.) } - Val::Vh(value) => { + Self::Vh(value) => { taffy::style::LengthPercentageAuto::Length(context.physical_size.y * value / 100.) } } @@ -244,10 +244,10 @@ impl From for Option { impl From for taffy::style::Display { fn from(value: Display) -> Self { match value { - Display::Flex => taffy::style::Display::Flex, - Display::Grid => taffy::style::Display::Grid, - Display::Block => taffy::style::Display::Block, - Display::None => taffy::style::Display::None, + Display::Flex => Self::Flex, + Display::Grid => Self::Grid, + Display::Block => Self::Block, + Display::None => Self::None, } } } @@ -255,9 +255,9 @@ impl From for taffy::style::Display { impl From for taffy::style::Overflow { fn from(value: OverflowAxis) -> Self { match value { - OverflowAxis::Visible => taffy::style::Overflow::Visible, - OverflowAxis::Clip => taffy::style::Overflow::Clip, - OverflowAxis::Hidden => taffy::style::Overflow::Hidden, + OverflowAxis::Visible => Self::Visible, + OverflowAxis::Clip => Self::Clip, + OverflowAxis::Hidden => Self::Hidden, } } } @@ -265,10 +265,10 @@ impl From for taffy::style::Overflow { impl From for taffy::style::FlexDirection { fn from(value: FlexDirection) -> Self { match value { - FlexDirection::Row => taffy::style::FlexDirection::Row, - FlexDirection::Column => taffy::style::FlexDirection::Column, - FlexDirection::RowReverse => taffy::style::FlexDirection::RowReverse, - FlexDirection::ColumnReverse => taffy::style::FlexDirection::ColumnReverse, + FlexDirection::Row => Self::Row, + FlexDirection::Column => Self::Column, + FlexDirection::RowReverse => Self::RowReverse, + FlexDirection::ColumnReverse => Self::ColumnReverse, } } } @@ -276,8 +276,8 @@ impl From for taffy::style::FlexDirection { impl From for taffy::style::Position { fn from(value: PositionType) -> Self { match value { - PositionType::Relative => taffy::style::Position::Relative, - PositionType::Absolute => taffy::style::Position::Absolute, + PositionType::Relative => Self::Relative, + PositionType::Absolute => Self::Absolute, } } } @@ -285,9 +285,9 @@ impl From for taffy::style::Position { impl From for taffy::style::FlexWrap { fn from(value: FlexWrap) -> Self { match value { - FlexWrap::NoWrap => taffy::style::FlexWrap::NoWrap, - FlexWrap::Wrap => taffy::style::FlexWrap::Wrap, - FlexWrap::WrapReverse => taffy::style::FlexWrap::WrapReverse, + FlexWrap::NoWrap => Self::NoWrap, + FlexWrap::Wrap => Self::Wrap, + FlexWrap::WrapReverse => Self::WrapReverse, } } } @@ -295,10 +295,10 @@ impl From for taffy::style::FlexWrap { impl From for taffy::style::GridAutoFlow { fn from(value: GridAutoFlow) -> Self { match value { - GridAutoFlow::Row => taffy::style::GridAutoFlow::Row, - GridAutoFlow::RowDense => taffy::style::GridAutoFlow::RowDense, - GridAutoFlow::Column => taffy::style::GridAutoFlow::Column, - GridAutoFlow::ColumnDense => taffy::style::GridAutoFlow::ColumnDense, + GridAutoFlow::Row => Self::Row, + GridAutoFlow::RowDense => Self::RowDense, + GridAutoFlow::Column => Self::Column, + GridAutoFlow::ColumnDense => Self::ColumnDense, } } } @@ -307,15 +307,15 @@ impl From for taffy::geometry::Line fn from(value: GridPlacement) -> Self { let span = value.get_span().unwrap_or(1); match (value.get_start(), value.get_end()) { - (Some(start), Some(end)) => taffy::geometry::Line { + (Some(start), Some(end)) => Self { start: style_helpers::line(start), end: style_helpers::line(end), }, - (Some(start), None) => taffy::geometry::Line { + (Some(start), None) => Self { start: style_helpers::line(start), end: style_helpers::span(span), }, - (None, Some(end)) => taffy::geometry::Line { + (None, Some(end)) => Self { start: style_helpers::span(span), end: style_helpers::line(end), }, @@ -327,25 +327,25 @@ impl From for taffy::geometry::Line impl MinTrackSizingFunction { fn into_taffy(self, context: &LayoutContext) -> taffy::style::MinTrackSizingFunction { match self { - MinTrackSizingFunction::Px(val) => taffy::style::MinTrackSizingFunction::Fixed( + Self::Px(val) => taffy::style::MinTrackSizingFunction::Fixed( Val::Px(val).into_length_percentage(context), ), - MinTrackSizingFunction::Percent(val) => taffy::style::MinTrackSizingFunction::Fixed( + Self::Percent(val) => taffy::style::MinTrackSizingFunction::Fixed( Val::Percent(val).into_length_percentage(context), ), - MinTrackSizingFunction::Auto => taffy::style::MinTrackSizingFunction::Auto, - MinTrackSizingFunction::MinContent => taffy::style::MinTrackSizingFunction::MinContent, - MinTrackSizingFunction::MaxContent => taffy::style::MinTrackSizingFunction::MaxContent, - MinTrackSizingFunction::VMin(val) => taffy::style::MinTrackSizingFunction::Fixed( + Self::Auto => taffy::style::MinTrackSizingFunction::Auto, + Self::MinContent => taffy::style::MinTrackSizingFunction::MinContent, + Self::MaxContent => taffy::style::MinTrackSizingFunction::MaxContent, + Self::VMin(val) => taffy::style::MinTrackSizingFunction::Fixed( Val::VMin(val).into_length_percentage(context), ), - MinTrackSizingFunction::VMax(val) => taffy::style::MinTrackSizingFunction::Fixed( + Self::VMax(val) => taffy::style::MinTrackSizingFunction::Fixed( Val::VMax(val).into_length_percentage(context), ), - MinTrackSizingFunction::Vh(val) => taffy::style::MinTrackSizingFunction::Fixed( + Self::Vh(val) => taffy::style::MinTrackSizingFunction::Fixed( Val::Vh(val).into_length_percentage(context), ), - MinTrackSizingFunction::Vw(val) => taffy::style::MinTrackSizingFunction::Fixed( + Self::Vw(val) => taffy::style::MinTrackSizingFunction::Fixed( Val::Vw(val).into_length_percentage(context), ), } @@ -355,38 +355,32 @@ impl MinTrackSizingFunction { impl MaxTrackSizingFunction { fn into_taffy(self, context: &LayoutContext) -> taffy::style::MaxTrackSizingFunction { match self { - MaxTrackSizingFunction::Px(val) => taffy::style::MaxTrackSizingFunction::Fixed( + Self::Px(val) => taffy::style::MaxTrackSizingFunction::Fixed( Val::Px(val).into_length_percentage(context), ), - MaxTrackSizingFunction::Percent(val) => taffy::style::MaxTrackSizingFunction::Fixed( + Self::Percent(val) => taffy::style::MaxTrackSizingFunction::Fixed( Val::Percent(val).into_length_percentage(context), ), - MaxTrackSizingFunction::Auto => taffy::style::MaxTrackSizingFunction::Auto, - MaxTrackSizingFunction::MinContent => taffy::style::MaxTrackSizingFunction::MinContent, - MaxTrackSizingFunction::MaxContent => taffy::style::MaxTrackSizingFunction::MaxContent, - MaxTrackSizingFunction::FitContentPx(val) => { - taffy::style::MaxTrackSizingFunction::FitContent( - Val::Px(val).into_length_percentage(context), - ) - } - MaxTrackSizingFunction::FitContentPercent(val) => { - taffy::style::MaxTrackSizingFunction::FitContent( - Val::Percent(val).into_length_percentage(context), - ) - } - MaxTrackSizingFunction::Fraction(fraction) => { - taffy::style::MaxTrackSizingFunction::Fraction(fraction) - } - MaxTrackSizingFunction::VMin(val) => taffy::style::MaxTrackSizingFunction::Fixed( + Self::Auto => taffy::style::MaxTrackSizingFunction::Auto, + Self::MinContent => taffy::style::MaxTrackSizingFunction::MinContent, + Self::MaxContent => taffy::style::MaxTrackSizingFunction::MaxContent, + Self::FitContentPx(val) => taffy::style::MaxTrackSizingFunction::FitContent( + Val::Px(val).into_length_percentage(context), + ), + Self::FitContentPercent(val) => taffy::style::MaxTrackSizingFunction::FitContent( + Val::Percent(val).into_length_percentage(context), + ), + Self::Fraction(fraction) => taffy::style::MaxTrackSizingFunction::Fraction(fraction), + Self::VMin(val) => taffy::style::MaxTrackSizingFunction::Fixed( Val::VMin(val).into_length_percentage(context), ), - MaxTrackSizingFunction::VMax(val) => taffy::style::MaxTrackSizingFunction::Fixed( + Self::VMax(val) => taffy::style::MaxTrackSizingFunction::Fixed( Val::VMax(val).into_length_percentage(context), ), - MaxTrackSizingFunction::Vh(val) => taffy::style::MaxTrackSizingFunction::Fixed( + Self::Vh(val) => taffy::style::MaxTrackSizingFunction::Fixed( Val::Vh(val).into_length_percentage(context), ), - MaxTrackSizingFunction::Vw(val) => taffy::style::MaxTrackSizingFunction::Fixed( + Self::Vw(val) => taffy::style::MaxTrackSizingFunction::Fixed( Val::Vw(val).into_length_percentage(context), ), } diff --git a/crates/bevy_ui/src/measurement.rs b/crates/bevy_ui/src/measurement.rs index 5c565930f53d0..0de941e4a4fe7 100644 --- a/crates/bevy_ui/src/measurement.rs +++ b/crates/bevy_ui/src/measurement.rs @@ -50,11 +50,11 @@ pub enum NodeMeasure { impl Measure for NodeMeasure { fn measure(&mut self, measure_args: MeasureArgs, style: &taffy::Style) -> Vec2 { match self { - NodeMeasure::Fixed(fixed) => fixed.measure(measure_args, style), + Self::Fixed(fixed) => fixed.measure(measure_args, style), #[cfg(feature = "bevy_text")] - NodeMeasure::Text(text) => text.measure(measure_args, style), - NodeMeasure::Image(image) => image.measure(measure_args, style), - NodeMeasure::Custom(custom) => custom.measure(measure_args, style), + Self::Text(text) => text.measure(measure_args, style), + Self::Image(image) => image.measure(measure_args, style), + Self::Custom(custom) => custom.measure(measure_args, style), } } } @@ -89,7 +89,7 @@ impl ContentSize { } /// Creates a `ContentSize` with a `Measure` that always returns given `size` argument, regardless of the UI layout's constraints. - pub fn fixed_size(size: Vec2) -> ContentSize { + pub fn fixed_size(size: Vec2) -> Self { let mut content_size = Self::default(); content_size.set(NodeMeasure::Fixed(FixedMeasure { size })); content_size diff --git a/crates/bevy_ui/src/render/pipeline.rs b/crates/bevy_ui/src/render/pipeline.rs index e31dc3bcfbba9..5f184dc79eece 100644 --- a/crates/bevy_ui/src/render/pipeline.rs +++ b/crates/bevy_ui/src/render/pipeline.rs @@ -38,7 +38,7 @@ impl FromWorld for UiPipeline { ), ); - UiPipeline { + Self { view_layout, image_layout, } diff --git a/crates/bevy_ui/src/render/ui_material_pipeline.rs b/crates/bevy_ui/src/render/ui_material_pipeline.rs index e15dc4223e456..ace4e6db2b231 100644 --- a/crates/bevy_ui/src/render/ui_material_pipeline.rs +++ b/crates/bevy_ui/src/render/ui_material_pipeline.rs @@ -217,7 +217,6 @@ impl FromWorld for UiMaterialPipeline { let asset_server = world.resource::(); let render_device = world.resource::(); let ui_layout = M::bind_group_layout(render_device); - let view_layout = render_device.create_bind_group_layout( "ui_view_layout", &BindGroupLayoutEntries::sequential( @@ -228,8 +227,7 @@ impl FromWorld for UiMaterialPipeline { ), ), ); - - UiMaterialPipeline { + Self { ui_layout, view_layout, vertex_shader: match M::vertex_shader() { @@ -616,7 +614,7 @@ impl RenderAsset for PreparedUiMaterial { (render_device, images, fallback_image, pipeline): &mut SystemParamItem, ) -> Result> { match material.as_bind_group(&pipeline.ui_layout, render_device, images, fallback_image) { - Ok(prepared) => Ok(PreparedUiMaterial { + Ok(prepared) => Ok(Self { bindings: prepared.bindings, bind_group: prepared.bind_group, key: prepared.data, diff --git a/crates/bevy_ui/src/ui_node.rs b/crates/bevy_ui/src/ui_node.rs index 766b86e4338cc..7e3275ca54012 100644 --- a/crates/bevy_ui/src/ui_node.rs +++ b/crates/bevy_ui/src/ui_node.rs @@ -1741,7 +1741,7 @@ impl> From for BorderColor { impl BorderColor { /// Border color is transparent by default. - pub const DEFAULT: Self = BorderColor(Color::NONE); + pub const DEFAULT: Self = Self(Color::NONE); } impl Default for BorderColor { @@ -1862,7 +1862,7 @@ impl Default for UiImage { /// To set this to a visible image, you need to set the `texture` field to a valid image handle, /// or use [`Handle`]'s default 1x1 solid white texture (as is done in [`UiImage::solid_color`]). fn default() -> Self { - UiImage { + Self { // This should be white because the tint is multiplied with the image, // so if you set an actual image with default tint you'd want its original colors color: Color::WHITE, diff --git a/crates/bevy_utils/macros/src/lib.rs b/crates/bevy_utils/macros/src/lib.rs index 199be4755b571..56d1723f922fe 100644 --- a/crates/bevy_utils/macros/src/lib.rs +++ b/crates/bevy_utils/macros/src/lib.rs @@ -33,15 +33,13 @@ impl Parse for AllTuples { while input.parse::().is_ok() { idents.push(input.parse::()?); } - if start > 1 && fake_variadic { return Err(Error::new( input.span(), "#[doc(fake_variadic)] only works when the tuple with length one is included", )); } - - Ok(AllTuples { + Ok(Self { fake_variadic, macro_ident, start, diff --git a/crates/bevy_utils/src/synccell.rs b/crates/bevy_utils/src/synccell.rs index e99c97b7d3838..af7c55cff0258 100644 --- a/crates/bevy_utils/src/synccell.rs +++ b/crates/bevy_utils/src/synccell.rs @@ -41,9 +41,9 @@ impl SyncCell { /// Build a mutable reference to a `SyncCell` from a mutable reference /// to its inner value, to skip constructing with [`new()`](SyncCell::new()). - pub fn from_mut(r: &'_ mut T) -> &'_ mut SyncCell { + pub fn from_mut(r: &'_ mut T) -> &'_ mut Self { // SAFETY: repr is transparent, so refs have the same layout; and `SyncCell` properties are `&mut`-agnostic - unsafe { &mut *(ptr::from_mut(r) as *mut SyncCell) } + unsafe { &mut *(ptr::from_mut(r) as *mut Self) } } } diff --git a/crates/bevy_utils/src/syncunsafecell.rs b/crates/bevy_utils/src/syncunsafecell.rs index e447f7122619c..040017652eb03 100644 --- a/crates/bevy_utils/src/syncunsafecell.rs +++ b/crates/bevy_utils/src/syncunsafecell.rs @@ -78,8 +78,8 @@ impl SyncUnsafeCell { #[inline] /// Returns a `&mut SyncUnsafeCell` from a `&mut T`. - pub fn from_mut(t: &mut T) -> &mut SyncUnsafeCell { - let ptr = ptr::from_mut(t) as *mut SyncUnsafeCell; + pub fn from_mut(t: &mut T) -> &mut Self { + let ptr = ptr::from_mut(t) as *mut Self; // SAFETY: `ptr` must be safe to mutably dereference, since it was originally // obtained from a mutable reference. `SyncUnsafeCell` has the same representation // as the original type `T`, since the former is annotated with #[repr(transparent)]. @@ -101,7 +101,7 @@ impl SyncUnsafeCell<[T]> { /// assert_eq!(slice_cell.len(), 3); /// ``` pub fn as_slice_of_cells(&self) -> &[SyncUnsafeCell] { - let self_ptr: *const SyncUnsafeCell<[T]> = ptr::from_ref(self); + let self_ptr: *const Self = ptr::from_ref(self); let slice_ptr = self_ptr as *const [SyncUnsafeCell]; // SAFETY: `UnsafeCell` and `SyncUnsafeCell` have #[repr(transparent)] // therefore: @@ -114,14 +114,14 @@ impl SyncUnsafeCell<[T]> { impl Default for SyncUnsafeCell { /// Creates an `SyncUnsafeCell`, with the `Default` value for T. - fn default() -> SyncUnsafeCell { - SyncUnsafeCell::new(Default::default()) + fn default() -> Self { + Self::new(Default::default()) } } impl From for SyncUnsafeCell { /// Creates a new `SyncUnsafeCell` containing the given value. - fn from(t: T) -> SyncUnsafeCell { - SyncUnsafeCell::new(t) + fn from(t: T) -> Self { + Self::new(t) } } diff --git a/crates/bevy_window/src/lib.rs b/crates/bevy_window/src/lib.rs index f27af26699424..d908eaf06b1c2 100644 --- a/crates/bevy_window/src/lib.rs +++ b/crates/bevy_window/src/lib.rs @@ -45,7 +45,7 @@ use bevy_app::prelude::*; impl Default for WindowPlugin { fn default() -> Self { - WindowPlugin { + Self { primary_window: Some(Window::default()), exit_condition: ExitCondition::OnAllClosed, close_when_requested: true, diff --git a/crates/bevy_window/src/raw_handle.rs b/crates/bevy_window/src/raw_handle.rs index 81b9a37096a83..bd20220143997 100644 --- a/crates/bevy_window/src/raw_handle.rs +++ b/crates/bevy_window/src/raw_handle.rs @@ -27,8 +27,8 @@ pub struct WindowWrapper { impl WindowWrapper { /// Creates a `WindowWrapper` from a window. - pub fn new(window: W) -> WindowWrapper { - WindowWrapper { + pub fn new(window: W) -> Self { + Self { reference: Arc::new(window), ty: PhantomData, } @@ -61,8 +61,8 @@ impl RawHandleWrapper { /// Creates a `RawHandleWrapper` from a `WindowWrapper`. pub fn new( window: &WindowWrapper, - ) -> Result { - Ok(RawHandleWrapper { + ) -> Result { + Ok(Self { _window: window.reference.clone(), window_handle: window.window_handle()?.as_raw(), display_handle: window.display_handle()?.as_raw(), diff --git a/crates/bevy_window/src/window.rs b/crates/bevy_window/src/window.rs index f578658cdf451..6c1f0095ae843 100644 --- a/crates/bevy_window/src/window.rs +++ b/crates/bevy_window/src/window.rs @@ -510,7 +510,7 @@ impl WindowResizeConstraints { /// Will output warnings if it isn't. #[must_use] pub fn check_constraints(&self) -> Self { - let WindowResizeConstraints { + let Self { mut min_width, mut min_height, mut max_width, @@ -532,7 +532,7 @@ impl WindowResizeConstraints { ); max_height = min_height; } - WindowResizeConstraints { + Self { min_width, min_height, max_width, @@ -581,7 +581,7 @@ pub struct CursorOptions { impl Default for CursorOptions { fn default() -> Self { - CursorOptions { + Self { visible: true, grab_mode: CursorGrabMode::None, hit_test: true, @@ -624,12 +624,12 @@ impl WindowPosition { /// Set the position to a specific point. pub fn set(&mut self, position: IVec2) { - *self = WindowPosition::At(position); + *self = Self::At(position); } /// Set the window to a specific monitor. pub fn center(&mut self, monitor: MonitorSelection) { - *self = WindowPosition::Centered(monitor); + *self = Self::Centered(monitor); } } @@ -703,7 +703,7 @@ pub struct WindowResolution { impl Default for WindowResolution { fn default() -> Self { - WindowResolution { + Self { physical_width: 1280, physical_height: 720, scale_factor_override: None, @@ -839,8 +839,8 @@ impl From<(I, I)> for WindowResolution where I: Into, { - fn from((width, height): (I, I)) -> WindowResolution { - WindowResolution::new(width.into(), height.into()) + fn from((width, height): (I, I)) -> Self { + Self::new(width.into(), height.into()) } } @@ -848,20 +848,20 @@ impl From<[I; 2]> for WindowResolution where I: Into, { - fn from([width, height]: [I; 2]) -> WindowResolution { - WindowResolution::new(width.into(), height.into()) + fn from([width, height]: [I; 2]) -> Self { + Self::new(width.into(), height.into()) } } impl From for WindowResolution { - fn from(res: Vec2) -> WindowResolution { - WindowResolution::new(res.x, res.y) + fn from(res: Vec2) -> Self { + Self::new(res.x, res.y) } } impl From for WindowResolution { - fn from(res: DVec2) -> WindowResolution { - WindowResolution::new(res.x as f32, res.y as f32) + fn from(res: DVec2) -> Self { + Self::new(res.x as f32, res.y as f32) } } diff --git a/crates/bevy_winit/src/winit_config.rs b/crates/bevy_winit/src/winit_config.rs index e97831bb3867a..a753e5ff7a29f 100644 --- a/crates/bevy_winit/src/winit_config.rs +++ b/crates/bevy_winit/src/winit_config.rs @@ -16,7 +16,7 @@ impl WinitSettings { /// [`Continuous`](UpdateMode::Continuous) if windows have focus, /// [`reactive_low_power`](UpdateMode::reactive_low_power) otherwise. pub fn game() -> Self { - WinitSettings { + Self { focused_mode: UpdateMode::Continuous, unfocused_mode: UpdateMode::reactive_low_power(Duration::from_secs_f64(1.0 / 60.0)), // 60Hz, } @@ -29,7 +29,7 @@ impl WinitSettings { /// /// Use the [`EventLoopProxy`](crate::EventLoopProxy) to request a redraw from outside bevy. pub fn desktop_app() -> Self { - WinitSettings { + Self { focused_mode: UpdateMode::reactive(Duration::from_secs(5)), unfocused_mode: UpdateMode::reactive_low_power(Duration::from_secs(60)), } @@ -48,7 +48,7 @@ impl WinitSettings { impl Default for WinitSettings { fn default() -> Self { - WinitSettings::game() + Self::game() } } diff --git a/examples/3d/blend_modes.rs b/examples/3d/blend_modes.rs index 521494446c6e7..258331ce42565 100644 --- a/examples/3d/blend_modes.rs +++ b/examples/3d/blend_modes.rs @@ -270,7 +270,7 @@ struct ExampleDisplay; impl Default for ExampleState { fn default() -> Self { - ExampleState { + Self { alpha: 0.9, unlit: false, } diff --git a/examples/3d/clearcoat.rs b/examples/3d/clearcoat.rs index 69aaa3071795b..2c2387d46a0f9 100644 --- a/examples/3d/clearcoat.rs +++ b/examples/3d/clearcoat.rs @@ -335,8 +335,8 @@ impl LightMode { /// Creates the help text at the bottom of the screen. fn create_help_text(&self) -> Text { let help_text = match *self { - LightMode::Point => "Press Space to switch to a directional light", - LightMode::Directional => "Press Space to switch to a point light", + Self::Point => "Press Space to switch to a directional light", + Self::Directional => "Press Space to switch to a point light", }; Text::from_section(help_text, TextStyle::default()) diff --git a/examples/3d/color_grading.rs b/examples/3d/color_grading.rs index 6ed6d12d8a48e..a02c98ed2ec6a 100644 --- a/examples/3d/color_grading.rs +++ b/examples/3d/color_grading.rs @@ -423,10 +423,10 @@ fn add_basic_scene(commands: &mut Commands, asset_server: &AssetServer) { impl Display for SelectedGlobalColorGradingOption { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let name = match *self { - SelectedGlobalColorGradingOption::Exposure => "Exposure", - SelectedGlobalColorGradingOption::Temperature => "Temperature", - SelectedGlobalColorGradingOption::Tint => "Tint", - SelectedGlobalColorGradingOption::Hue => "Hue", + Self::Exposure => "Exposure", + Self::Temperature => "Temperature", + Self::Tint => "Tint", + Self::Hue => "Hue", }; f.write_str(name) } @@ -435,9 +435,9 @@ impl Display for SelectedGlobalColorGradingOption { impl Display for SelectedColorGradingSection { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let name = match *self { - SelectedColorGradingSection::Highlights => "Highlights", - SelectedColorGradingSection::Midtones => "Midtones", - SelectedColorGradingSection::Shadows => "Shadows", + Self::Highlights => "Highlights", + Self::Midtones => "Midtones", + Self::Shadows => "Shadows", }; f.write_str(name) } @@ -446,11 +446,11 @@ impl Display for SelectedColorGradingSection { impl Display for SelectedSectionColorGradingOption { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let name = match *self { - SelectedSectionColorGradingOption::Saturation => "Saturation", - SelectedSectionColorGradingOption::Contrast => "Contrast", - SelectedSectionColorGradingOption::Gamma => "Gamma", - SelectedSectionColorGradingOption::Gain => "Gain", - SelectedSectionColorGradingOption::Lift => "Lift", + Self::Saturation => "Saturation", + Self::Contrast => "Contrast", + Self::Gamma => "Gamma", + Self::Gain => "Gain", + Self::Lift => "Lift", }; f.write_str(name) } @@ -459,8 +459,8 @@ impl Display for SelectedSectionColorGradingOption { impl Display for SelectedColorGradingOption { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { - SelectedColorGradingOption::Global(option) => write!(f, "\"{}\"", option), - SelectedColorGradingOption::Section(section, option) => { + Self::Global(option) => write!(f, "\"{}\"", option), + Self::Section(section, option) => { write!(f, "\"{}\" for \"{}\"", option, section) } } @@ -471,21 +471,21 @@ impl SelectedSectionColorGradingOption { /// Returns the appropriate value in the given color grading section. fn get(&self, section: &ColorGradingSection) -> f32 { match *self { - SelectedSectionColorGradingOption::Saturation => section.saturation, - SelectedSectionColorGradingOption::Contrast => section.contrast, - SelectedSectionColorGradingOption::Gamma => section.gamma, - SelectedSectionColorGradingOption::Gain => section.gain, - SelectedSectionColorGradingOption::Lift => section.lift, + Self::Saturation => section.saturation, + Self::Contrast => section.contrast, + Self::Gamma => section.gamma, + Self::Gain => section.gain, + Self::Lift => section.lift, } } fn set(&self, section: &mut ColorGradingSection, value: f32) { match *self { - SelectedSectionColorGradingOption::Saturation => section.saturation = value, - SelectedSectionColorGradingOption::Contrast => section.contrast = value, - SelectedSectionColorGradingOption::Gamma => section.gamma = value, - SelectedSectionColorGradingOption::Gain => section.gain = value, - SelectedSectionColorGradingOption::Lift => section.lift = value, + Self::Saturation => section.saturation = value, + Self::Contrast => section.contrast = value, + Self::Gamma => section.gamma = value, + Self::Gain => section.gain = value, + Self::Lift => section.lift = value, } } } @@ -495,10 +495,10 @@ impl SelectedGlobalColorGradingOption { /// values. fn get(&self, global: &ColorGradingGlobal) -> f32 { match *self { - SelectedGlobalColorGradingOption::Exposure => global.exposure, - SelectedGlobalColorGradingOption::Temperature => global.temperature, - SelectedGlobalColorGradingOption::Tint => global.tint, - SelectedGlobalColorGradingOption::Hue => global.hue, + Self::Exposure => global.exposure, + Self::Temperature => global.temperature, + Self::Tint => global.tint, + Self::Hue => global.hue, } } @@ -506,10 +506,10 @@ impl SelectedGlobalColorGradingOption { /// values. fn set(&self, global: &mut ColorGradingGlobal, value: f32) { match *self { - SelectedGlobalColorGradingOption::Exposure => global.exposure = value, - SelectedGlobalColorGradingOption::Temperature => global.temperature = value, - SelectedGlobalColorGradingOption::Tint => global.tint = value, - SelectedGlobalColorGradingOption::Hue => global.hue = value, + Self::Exposure => global.exposure = value, + Self::Temperature => global.temperature = value, + Self::Tint => global.tint = value, + Self::Hue => global.hue = value, } } } @@ -518,15 +518,14 @@ impl SelectedColorGradingOption { /// Returns the appropriate value in the given set of color grading values. fn get(&self, color_grading: &ColorGrading) -> f32 { match self { - SelectedColorGradingOption::Global(option) => option.get(&color_grading.global), - SelectedColorGradingOption::Section( - SelectedColorGradingSection::Highlights, - option, - ) => option.get(&color_grading.highlights), - SelectedColorGradingOption::Section(SelectedColorGradingSection::Midtones, option) => { + Self::Global(option) => option.get(&color_grading.global), + Self::Section(SelectedColorGradingSection::Highlights, option) => { + option.get(&color_grading.highlights) + } + Self::Section(SelectedColorGradingSection::Midtones, option) => { option.get(&color_grading.midtones) } - SelectedColorGradingOption::Section(SelectedColorGradingSection::Shadows, option) => { + Self::Section(SelectedColorGradingSection::Shadows, option) => { option.get(&color_grading.shadows) } } @@ -535,17 +534,16 @@ impl SelectedColorGradingOption { /// Sets the appropriate value in the given set of color grading values. fn set(&self, color_grading: &mut ColorGrading, value: f32) { match self { - SelectedColorGradingOption::Global(option) => { + Self::Global(option) => { option.set(&mut color_grading.global, value); } - SelectedColorGradingOption::Section( - SelectedColorGradingSection::Highlights, - option, - ) => option.set(&mut color_grading.highlights, value), - SelectedColorGradingOption::Section(SelectedColorGradingSection::Midtones, option) => { + Self::Section(SelectedColorGradingSection::Highlights, option) => { + option.set(&mut color_grading.highlights, value); + } + Self::Section(SelectedColorGradingSection::Midtones, option) => { option.set(&mut color_grading.midtones, value); } - SelectedColorGradingOption::Section(SelectedColorGradingSection::Shadows, option) => { + Self::Section(SelectedColorGradingSection::Shadows, option) => { option.set(&mut color_grading.shadows, value); } } diff --git a/examples/3d/irradiance_volumes.rs b/examples/3d/irradiance_volumes.rs index 0c4c44f00bf60..270530a68509c 100644 --- a/examples/3d/irradiance_volumes.rs +++ b/examples/3d/irradiance_volumes.rs @@ -507,8 +507,7 @@ impl FromWorld for ExampleAssets { world.load_asset(GltfAssetLabel::Animation(1).from_asset("models/animated/Fox.glb")); let (fox_animation_graph, fox_animation_node) = AnimationGraph::from_clip(fox_animation.clone()); - - ExampleAssets { + Self { main_sphere: world.add_asset(Sphere::default().mesh().uv(32, 18)), fox: world.load_asset(GltfAssetLabel::Scene(0).from_asset("models/animated/Fox.glb")), main_sphere_material: world.add_asset(Color::from(SILVER)), diff --git a/examples/3d/lines.rs b/examples/3d/lines.rs index bae99c445aa95..97a69d75f61e8 100644 --- a/examples/3d/lines.rs +++ b/examples/3d/lines.rs @@ -99,15 +99,14 @@ struct LineList { impl From for Mesh { fn from(line: LineList) -> Self { let vertices: Vec<_> = line.lines.into_iter().flat_map(|(a, b)| [a, b]).collect(); - - Mesh::new( + Self::new( // This tells wgpu that the positions are list of lines // where every pair is a start and end point PrimitiveTopology::LineList, RenderAssetUsages::RENDER_WORLD, ) // Add the vertices positions as an attribute - .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, vertices) + .with_inserted_attribute(Self::ATTRIBUTE_POSITION, vertices) } } @@ -119,13 +118,13 @@ struct LineStrip { impl From for Mesh { fn from(line: LineStrip) -> Self { - Mesh::new( + Self::new( // This tells wgpu that the positions are a list of points // where a line will be drawn between each consecutive point PrimitiveTopology::LineStrip, RenderAssetUsages::RENDER_WORLD, ) // Add the point positions as an attribute - .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, line.points) + .with_inserted_attribute(Self::ATTRIBUTE_POSITION, line.points) } } diff --git a/examples/3d/parallax_mapping.rs b/examples/3d/parallax_mapping.rs index 08fa84f75c3d2..903c05b978ef3 100644 --- a/examples/3d/parallax_mapping.rs +++ b/examples/3d/parallax_mapping.rs @@ -38,19 +38,19 @@ const MAX_DEPTH: f32 = 0.3; struct TargetDepth(f32); impl Default for TargetDepth { fn default() -> Self { - TargetDepth(0.09) + Self(0.09) } } struct TargetLayers(f32); impl Default for TargetLayers { fn default() -> Self { - TargetLayers(5.0) + Self(5.0) } } struct CurrentMethod(ParallaxMappingMethod); impl Default for CurrentMethod { fn default() -> Self { - CurrentMethod(ParallaxMappingMethod::Relief { max_steps: 4 }) + Self(ParallaxMappingMethod::Relief { max_steps: 4 }) } } impl fmt::Display for CurrentMethod { diff --git a/examples/3d/reflection_probes.rs b/examples/3d/reflection_probes.rs index ca8f02441dd25..48c99768cb125 100644 --- a/examples/3d/reflection_probes.rs +++ b/examples/3d/reflection_probes.rs @@ -254,9 +254,9 @@ impl TryFrom for ReflectionMode { fn try_from(value: u32) -> Result { match value { - 0 => Ok(ReflectionMode::None), - 1 => Ok(ReflectionMode::EnvironmentMap), - 2 => Ok(ReflectionMode::ReflectionProbe), + 0 => Ok(Self::None), + 1 => Ok(Self::EnvironmentMap), + 2 => Ok(Self::ReflectionProbe), _ => Err(()), } } @@ -265,9 +265,9 @@ impl TryFrom for ReflectionMode { impl Display for ReflectionMode { fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult { let text = match *self { - ReflectionMode::None => "No reflections", - ReflectionMode::EnvironmentMap => "Environment map", - ReflectionMode::ReflectionProbe => "Reflection probe", + Self::None => "No reflections", + Self::EnvironmentMap => "Environment map", + Self::ReflectionProbe => "Reflection probe", }; formatter.write_str(text) } @@ -330,8 +330,7 @@ impl FromWorld for Cubemaps { // In reality you wouldn't do this--you'd use a real skybox texture--but // reusing the textures like this saves space in the Bevy repository. let specular_map = world.load_asset("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"); - - Cubemaps { + Self { diffuse: world.load_asset("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"), specular_reflection_probe: world .load_asset("environment_maps/cubes_reflection_probe_specular_rgb9e5_zstd.ktx2"), diff --git a/examples/3d/tonemapping.rs b/examples/3d/tonemapping.rs index cc3d8d140bda7..e2dd62413c1a7 100644 --- a/examples/3d/tonemapping.rs +++ b/examples/3d/tonemapping.rs @@ -593,7 +593,6 @@ impl PerMethodSettings { impl Default for PerMethodSettings { fn default() -> Self { let mut settings = HashMap::new(); - for method in [ Tonemapping::None, Tonemapping::Reinhard, @@ -604,12 +603,8 @@ impl Default for PerMethodSettings { Tonemapping::TonyMcMapface, Tonemapping::BlenderFilmic, ] { - settings.insert( - method, - PerMethodSettings::basic_scene_recommendation(method), - ); + settings.insert(method, Self::basic_scene_recommendation(method)); } - Self { settings } } } diff --git a/examples/3d/transmission.rs b/examples/3d/transmission.rs index b796f95704c6d..5d24eee946c3d 100644 --- a/examples/3d/transmission.rs +++ b/examples/3d/transmission.rs @@ -405,7 +405,7 @@ struct ExampleDisplay; impl Default for ExampleState { fn default() -> Self { - ExampleState { + Self { diffuse_transmission: 0.5, specular_transmission: 0.9, thickness: 1.8, diff --git a/examples/animation/animation_graph.rs b/examples/animation/animation_graph.rs index bfb9b663712dd..da9f6850871ec 100644 --- a/examples/animation/animation_graph.rs +++ b/examples/animation/animation_graph.rs @@ -545,8 +545,8 @@ impl NodeRect { /// Note that node rectangles are anchored in the *lower*-left corner. The /// `bottom` parameter specifies vertical distance from the *bottom* of the /// window. - const fn new(left: f32, bottom: f32, width: f32, height: f32) -> NodeRect { - NodeRect { + const fn new(left: f32, bottom: f32, width: f32, height: f32) -> Self { + Self { left, bottom, width, diff --git a/examples/app/headless_renderer.rs b/examples/app/headless_renderer.rs index 2a882063d9abf..d15450d78e311 100644 --- a/examples/app/headless_renderer.rs +++ b/examples/app/headless_renderer.rs @@ -111,8 +111,8 @@ struct SceneController { } impl SceneController { - pub fn new(width: u32, height: u32, single_image: bool) -> SceneController { - SceneController { + pub fn new(width: u32, height: u32, single_image: bool) -> Self { + Self { state: SceneState::BuildScene, name: String::from(""), width, @@ -291,22 +291,16 @@ struct ImageCopier { } impl ImageCopier { - pub fn new( - src_image: Handle, - size: Extent3d, - render_device: &RenderDevice, - ) -> ImageCopier { + pub fn new(src_image: Handle, size: Extent3d, render_device: &RenderDevice) -> Self { let padded_bytes_per_row = RenderDevice::align_copy_bytes_per_row((size.width) as usize) * 4; - let cpu_buffer = render_device.create_buffer(&BufferDescriptor { label: None, size: padded_bytes_per_row as u64 * size.height as u64, usage: BufferUsages::MAP_READ | BufferUsages::COPY_DST, mapped_at_creation: false, }); - - ImageCopier { + Self { buffer: cpu_buffer, src_image, enabled: Arc::new(AtomicBool::new(true)), diff --git a/examples/asset/multi_asset_sync.rs b/examples/asset/multi_asset_sync.rs index 2b2386dad36ce..5b906950b3dc3 100644 --- a/examples/asset/multi_asset_sync.rs +++ b/examples/asset/multi_asset_sync.rs @@ -90,12 +90,12 @@ pub struct LoadingText; impl AssetBarrier { /// Create an [`AssetBarrier`] with a [`AssetBarrierGuard`]. - pub fn new() -> (AssetBarrier, AssetBarrierGuard) { + pub fn new() -> (Self, AssetBarrierGuard) { let inner = Arc::new(AssetBarrierInner { count: AtomicU32::new(1), notify: Event::new(), }); - (AssetBarrier(inner.clone()), AssetBarrierGuard(inner)) + (Self(inner.clone()), AssetBarrierGuard(inner)) } /// Returns true if all [`AssetBarrierGuard`] is dropped. @@ -125,7 +125,7 @@ impl AssetBarrier { impl Clone for AssetBarrierGuard { fn clone(&self) -> Self { self.count.fetch_add(1, Ordering::AcqRel); - AssetBarrierGuard(self.0.clone()) + Self(self.0.clone()) } } diff --git a/examples/audio/decodable.rs b/examples/audio/decodable.rs index 6edd43ae861a4..15c31934f25df 100644 --- a/examples/audio/decodable.rs +++ b/examples/audio/decodable.rs @@ -29,7 +29,7 @@ impl SineDecoder { fn new(frequency: f32) -> Self { // standard sample rate for most recordings let sample_rate = 44_100; - SineDecoder { + Self { current_progress: 0., progress_per_frame: frequency / sample_rate as f32, period: std::f32::consts::PI * 2., diff --git a/examples/ecs/ecs_guide.rs b/examples/ecs/ecs_guide.rs index 76fc719141cc9..2ee9341f88625 100644 --- a/examples/ecs/ecs_guide.rs +++ b/examples/ecs/ecs_guide.rs @@ -59,9 +59,9 @@ enum PlayerStreak { impl fmt::Display for PlayerStreak { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - PlayerStreak::Hot(n) => write!(f, "{n} round hot streak"), - PlayerStreak::None => write!(f, "0 round streak"), - PlayerStreak::Cold(n) => write!(f, "{n} round cold streak"), + Self::Hot(n) => write!(f, "{n} round hot streak"), + Self::None => write!(f, "0 round streak"), + Self::Cold(n) => write!(f, "{n} round cold streak"), } } } diff --git a/examples/ecs/event.rs b/examples/ecs/event.rs index e085a874cb570..b0288387e7890 100644 --- a/examples/ecs/event.rs +++ b/examples/ecs/event.rs @@ -26,7 +26,7 @@ struct DamageTimer(pub Timer); impl Default for DamageTimer { fn default() -> Self { - DamageTimer(Timer::from_seconds(1.0, TimerMode::Repeating)) + Self(Timer::from_seconds(1.0, TimerMode::Repeating)) } } diff --git a/examples/ecs/observers.rs b/examples/ecs/observers.rs index aae7d446e96f4..b03c45324e85e 100644 --- a/examples/ecs/observers.rs +++ b/examples/ecs/observers.rs @@ -50,7 +50,7 @@ struct Mine { impl Mine { fn random(rand: &mut ChaCha8Rng) -> Self { - Mine { + Self { pos: Vec2::new( (rand.gen::() - 0.5) * 1200.0, (rand.gen::() - 0.5) * 600.0, diff --git a/examples/games/breakout.rs b/examples/games/breakout.rs index 1fe1cb17c3346..a39c61e54dbb0 100644 --- a/examples/games/breakout.rs +++ b/examples/games/breakout.rs @@ -123,10 +123,10 @@ impl WallLocation { /// Location of the *center* of the wall, used in `transform.translation()` fn position(&self) -> Vec2 { match self { - WallLocation::Left => Vec2::new(LEFT_WALL, 0.), - WallLocation::Right => Vec2::new(RIGHT_WALL, 0.), - WallLocation::Bottom => Vec2::new(0., BOTTOM_WALL), - WallLocation::Top => Vec2::new(0., TOP_WALL), + Self::Left => Vec2::new(LEFT_WALL, 0.), + Self::Right => Vec2::new(RIGHT_WALL, 0.), + Self::Bottom => Vec2::new(0., BOTTOM_WALL), + Self::Top => Vec2::new(0., TOP_WALL), } } @@ -139,12 +139,8 @@ impl WallLocation { assert!(arena_width > 0.0); match self { - WallLocation::Left | WallLocation::Right => { - Vec2::new(WALL_THICKNESS, arena_height + WALL_THICKNESS) - } - WallLocation::Bottom | WallLocation::Top => { - Vec2::new(arena_width + WALL_THICKNESS, WALL_THICKNESS) - } + Self::Left | Self::Right => Vec2::new(WALL_THICKNESS, arena_height + WALL_THICKNESS), + Self::Bottom | Self::Top => Vec2::new(arena_width + WALL_THICKNESS, WALL_THICKNESS), } } } @@ -152,8 +148,8 @@ impl WallLocation { impl WallBundle { // This "builder method" allows us to reuse logic across our wall entities, // making our code easier to read and less prone to bugs when we change the logic - fn new(location: WallLocation) -> WallBundle { - WallBundle { + fn new(location: WallLocation) -> Self { + Self { sprite_bundle: SpriteBundle { transform: Transform { // We need to convert our Vec2 into a Vec3, by giving it a z-coordinate diff --git a/examples/games/stepping.rs b/examples/games/stepping.rs index f0d5593c03998..201cc5d48a8df 100644 --- a/examples/games/stepping.rs +++ b/examples/games/stepping.rs @@ -19,14 +19,14 @@ pub struct SteppingPlugin { impl SteppingPlugin { /// add a schedule to be stepped when stepping is enabled - pub fn add_schedule(mut self, label: impl ScheduleLabel) -> SteppingPlugin { + pub fn add_schedule(mut self, label: impl ScheduleLabel) -> Self { self.schedule_labels.push(label.intern()); self } /// Set the location of the stepping UI when activated - pub fn at(self, left: Val, top: Val) -> SteppingPlugin { - SteppingPlugin { top, left, ..self } + pub fn at(self, left: Val, top: Val) -> Self { + Self { top, left, ..self } } } diff --git a/examples/math/cubic_splines.rs b/examples/math/cubic_splines.rs index 7167d85ef7814..fbb2894796432 100644 --- a/examples/math/cubic_splines.rs +++ b/examples/math/cubic_splines.rs @@ -119,9 +119,9 @@ enum SplineMode { impl std::fmt::Display for SplineMode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - SplineMode::Hermite => f.write_str("Hermite"), - SplineMode::Cardinal => f.write_str("Cardinal"), - SplineMode::B => f.write_str("B"), + Self::Hermite => f.write_str("Hermite"), + Self::Cardinal => f.write_str("Cardinal"), + Self::B => f.write_str("B"), } } } @@ -138,8 +138,8 @@ enum CyclingMode { impl std::fmt::Display for CyclingMode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - CyclingMode::NotCyclic => f.write_str("Not Cyclic"), - CyclingMode::Cyclic => f.write_str("Cyclic"), + Self::NotCyclic => f.write_str("Not Cyclic"), + Self::Cyclic => f.write_str("Cyclic"), } } } diff --git a/examples/math/render_primitives.rs b/examples/math/render_primitives.rs index 0d34d4ad7c379..ee06178ba7d28 100644 --- a/examples/math/render_primitives.rs +++ b/examples/math/render_primitives.rs @@ -92,8 +92,8 @@ enum PrimitiveSelected { impl std::fmt::Display for PrimitiveSelected { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let name = match self { - PrimitiveSelected::RectangleAndCuboid => String::from("Rectangle/Cuboid"), - PrimitiveSelected::CircleAndSphere => String::from("Circle/Sphere"), + Self::RectangleAndCuboid => String::from("Rectangle/Cuboid"), + Self::CircleAndSphere => String::from("Circle/Sphere"), other => format!("{other:?}"), }; write!(f, "{name}") diff --git a/examples/math/sampling_primitives.rs b/examples/math/sampling_primitives.rs index 6aa6feece5c3c..695136ff88bc2 100644 --- a/examples/math/sampling_primitives.rs +++ b/examples/math/sampling_primitives.rs @@ -140,7 +140,7 @@ impl SampledShapes { let translations = (0..n_shapes).map(|i| (i as f32 - n_shapes as f32 / 2.0) * DISTANCE_BETWEEN_SHAPES); - SampledShapes(shapes.into_iter().zip(translations).collect()) + Self(shapes.into_iter().zip(translations).collect()) } } @@ -160,14 +160,14 @@ struct ShapeMeshBuilder { impl Shape { /// Return a vector containing all implemented shapes - fn list_all_shapes() -> Vec { + fn list_all_shapes() -> Vec { vec![ - Shape::Cuboid, - Shape::Sphere, - Shape::Capsule, - Shape::Cylinder, - Shape::Tetrahedron, - Shape::Triangle, + Self::Cuboid, + Self::Sphere, + Self::Capsule, + Self::Cylinder, + Self::Tetrahedron, + Self::Triangle, ] } } @@ -176,23 +176,23 @@ impl ShapeSample for Shape { type Output = Vec3; fn sample_interior(&self, rng: &mut R) -> Vec3 { match self { - Shape::Cuboid => CUBOID.sample_interior(rng), - Shape::Sphere => SPHERE.sample_interior(rng), - Shape::Capsule => CAPSULE_3D.sample_interior(rng), - Shape::Cylinder => CYLINDER.sample_interior(rng), - Shape::Tetrahedron => TETRAHEDRON.sample_interior(rng), - Shape::Triangle => TRIANGLE_3D.sample_interior(rng), + Self::Cuboid => CUBOID.sample_interior(rng), + Self::Sphere => SPHERE.sample_interior(rng), + Self::Capsule => CAPSULE_3D.sample_interior(rng), + Self::Cylinder => CYLINDER.sample_interior(rng), + Self::Tetrahedron => TETRAHEDRON.sample_interior(rng), + Self::Triangle => TRIANGLE_3D.sample_interior(rng), } } fn sample_boundary(&self, rng: &mut R) -> Self::Output { match self { - Shape::Cuboid => CUBOID.sample_boundary(rng), - Shape::Sphere => SPHERE.sample_boundary(rng), - Shape::Capsule => CAPSULE_3D.sample_boundary(rng), - Shape::Cylinder => CYLINDER.sample_boundary(rng), - Shape::Tetrahedron => TETRAHEDRON.sample_boundary(rng), - Shape::Triangle => TRIANGLE_3D.sample_boundary(rng), + Self::Cuboid => CUBOID.sample_boundary(rng), + Self::Sphere => SPHERE.sample_boundary(rng), + Self::Capsule => CAPSULE_3D.sample_boundary(rng), + Self::Cylinder => CYLINDER.sample_boundary(rng), + Self::Tetrahedron => TETRAHEDRON.sample_boundary(rng), + Self::Triangle => TRIANGLE_3D.sample_boundary(rng), } } } diff --git a/examples/scene/scene.rs b/examples/scene/scene.rs index e5f18d1bdd4ad..c80e3b212d676 100644 --- a/examples/scene/scene.rs +++ b/examples/scene/scene.rs @@ -44,7 +44,7 @@ struct ComponentB { impl FromWorld for ComponentB { fn from_world(world: &mut World) -> Self { let time = world.resource::