From d50a2f6e63c25adf3b64652310c423717bd3966f Mon Sep 17 00:00:00 2001 From: HampusM Date: Sun, 16 Jun 2024 13:17:57 +0200 Subject: refactor(ecs): add component ID struct --- ecs/src/component.rs | 37 +++++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-) (limited to 'ecs/src/component.rs') diff --git a/ecs/src/component.rs b/ecs/src/component.rs index 5c0b9ce..512c60d 100644 --- a/ecs/src/component.rs +++ b/ecs/src/component.rs @@ -15,7 +15,7 @@ pub(crate) mod storage; pub trait Component: SystemInput + Any + TypeName { /// The component type in question. Will usually be `Self` - type Component + type Component: Component where Self: Sized; @@ -23,6 +23,9 @@ pub trait Component: SystemInput + Any + TypeName where Self: Sized; + /// Returns the ID of this component's type. + fn id(&self) -> Id; + #[doc(hidden)] fn as_any_mut(&mut self) -> &mut dyn Any; @@ -76,6 +79,11 @@ where type Component = ComponentT; type RefMut<'component> = Option>; + fn id(&self) -> Id + { + Id::of::() + } + fn as_any_mut(&mut self) -> &mut dyn Any { self @@ -104,6 +112,23 @@ where impl SystemInput for Option where ComponentT: Component {} +/// The ID of a [`Component`] type. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Id +{ + inner: TypeId, +} + +impl Id +{ + pub fn of() -> Self + where + ComponentT: Component, + { + Self { inner: TypeId::of::() } + } +} + /// A sequence of components. pub trait Sequence { @@ -113,7 +138,7 @@ pub trait Sequence fn into_vec(self) -> Vec>; - fn type_ids() -> Vec<(TypeId, IsOptional)>; + fn ids() -> Vec<(Id, IsOptional)>; fn from_components<'component>( components: impl Iterator, @@ -145,7 +170,7 @@ impl From for IsOptional /// Will return `true` if the component is a [`Option`]. pub fn is_optional() -> bool { - if TypeId::of::() == TypeId::of::>() { + if Id::of::() == Id::of::>() { return true; } @@ -174,11 +199,11 @@ macro_rules! inner { Vec::from_iter([#(Box::new(self.I) as Box,)*]) } - fn type_ids() -> Vec<(TypeId, IsOptional)> + fn ids() -> Vec<(Id, IsOptional)> { vec![ #( - (TypeId::of::(), is_optional::().into()), + (Id::of::(), is_optional::().into()), )* ] } @@ -193,7 +218,7 @@ macro_rules! inner { for comp in components { #( - if comp.id == TypeId::of::() { + if comp.id == Id::of::() { comp_~I = Some(lock_component(comp)); continue; } -- cgit v1.2.3-18-g5258