Implement disjoint mut for resource

This commit is contained in:
hodasemi 2025-04-04 17:32:27 +02:00
parent bdaedab819
commit 5b152f9919
5 changed files with 133 additions and 45 deletions

View file

@ -0,0 +1,5 @@
pub trait GetDisjointMut<'a, T: 'a> {
type Error;
fn get_mut(&'a mut self) -> std::result::Result<T, Self::Error>;
}

View file

@ -1,6 +1,7 @@
mod entity; mod entity;
mod entity_object_manager; mod entity_object_manager;
mod events; mod events;
pub mod get_disjoint_mut;
mod resources; mod resources;
mod type_map; mod type_map;
mod unsafe_component_store; mod unsafe_component_store;
@ -16,3 +17,4 @@ pub use crate::type_map::{
pub use crate::unsafe_component_store::UnsafeComponentStore; pub use crate::unsafe_component_store::UnsafeComponentStore;
pub use crate::updates::*; pub use crate::updates::*;
pub use crate::world::{World, WorldBuilder}; pub use crate::world::{World, WorldBuilder};
pub use update_macros::Resource;

View file

@ -3,94 +3,162 @@ use std::{
collections::HashMap, collections::HashMap,
}; };
use anyhow::{Error, anyhow};
use utilities::prelude::{remove_life_time, remove_life_time_mut}; use utilities::prelude::{remove_life_time, remove_life_time_mut};
type Untyped = dyn Any + Send + Sync; use crate::get_disjoint_mut::GetDisjointMut;
pub trait Resource: Any + Send + Sync {}
impl dyn Resource {
pub fn downcast_owned<T: Resource + 'static>(mut self: Box<Self>) -> Option<T> {
self.downcast_mut()
.map(|raw| unsafe { *Box::from_raw(raw as *mut T) })
}
pub fn downcast_ref<T: Resource + 'static>(&self) -> Option<&T> {
(self as &dyn Any).downcast_ref()
}
pub fn downcast_mut<T: Resource + 'static>(&mut self) -> Option<&mut T> {
(self as &mut dyn Any).downcast_mut()
}
}
#[derive(Default)] #[derive(Default)]
pub struct Resources { pub struct Resources {
map: HashMap<TypeId, Box<Untyped>>, map: HashMap<TypeId, Box<dyn Resource>>,
} }
impl Resources { impl Resources {
pub fn insert<T: Any + Send + Sync>(&mut self, value: T) -> Option<T> { pub fn insert<T: Resource>(&mut self, value: T) -> Option<T> {
self.map self.map
.insert(TypeId::of::<T>(), Box::new(value)) .insert(TypeId::of::<T>(), Box::new(value))
.map(|any| *Self::downcast_unchecked(any)) .map(|any| any.downcast_owned())
.flatten()
} }
pub fn insert_if_not_exists<T: Default + Any + Send + Sync>(&mut self) { pub fn insert_if_not_exists<T: Resource + Default>(&mut self) {
if !self.contains::<T>() { if !self.contains::<T>() {
self.insert(T::default()); self.insert(T::default());
} }
} }
pub fn remove<T: Any + Send + Sync>(&mut self) -> Option<T> { pub fn remove<T: Resource>(&mut self) -> Option<T> {
self.map self.map
.remove(&TypeId::of::<T>()) .remove(&TypeId::of::<T>())
.map(|any| *Self::downcast_unchecked(any)) .map(|any| any.downcast_owned())
.flatten()
} }
pub fn get<T: Any + Send + Sync>(&self) -> &T { pub fn get<T: Resource>(&self) -> &T {
self.get_opt::<T>().unwrap() self.get_opt::<T>().unwrap()
} }
pub fn get_by_type_id<T: Any + Send + Sync>(&self, type_id: TypeId) -> &T { pub fn get_by_type_id<T: Resource>(&self, type_id: TypeId) -> &T {
self.get_opt_by_type_id(type_id).unwrap() self.get_opt_by_type_id(type_id).unwrap()
} }
pub fn get_unchecked<'a, T: Any + Send + Sync>(&self) -> &'a T { pub fn get_unchecked<'a, T: Resource>(&self) -> &'a T {
unsafe { remove_life_time(self.get::<T>()) } unsafe { remove_life_time(self.get::<T>()) }
} }
pub fn get_opt<T: Any + Send + Sync>(&self) -> Option<&T> { pub fn get_opt<T: Resource>(&self) -> Option<&T> {
self.get_opt_by_type_id(TypeId::of::<T>()) self.get_opt_by_type_id(TypeId::of::<T>())
} }
pub fn get_opt_by_type_id<T: Any + Send + Sync>(&self, type_id: TypeId) -> Option<&T> { pub fn get_opt_by_type_id<T: Resource>(&self, type_id: TypeId) -> Option<&T> {
debug_assert_eq!(type_id, TypeId::of::<T>()); debug_assert_eq!(type_id, TypeId::of::<T>());
self.map self.map
.get(&type_id) .get(&type_id)
.map(|any| Self::downcast_ref_unchecked(any)) .map(|any| any.downcast_ref())
.flatten()
} }
pub fn get_mut<T: Any + Send + Sync>(&mut self) -> &mut T { pub fn get_mut<T: Resource>(&mut self) -> &mut T {
self.get_mut_opt::<T>().unwrap() self.get_mut_opt::<T>().unwrap()
} }
pub fn get_mut_by_type_id<T: Any + Send + Sync>(&mut self, type_id: TypeId) -> &mut T { pub fn get_mut_by_type_id<T: Resource>(&mut self, type_id: TypeId) -> &mut T {
self.get_mut_opt_by_type_id(type_id).unwrap() self.get_mut_opt_by_type_id(type_id).unwrap()
} }
pub fn get_mut_by_type_id_untyped(&mut self, type_id: TypeId) -> &mut Untyped { pub fn get_mut_by_type_id_untyped(&mut self, type_id: TypeId) -> &mut dyn Resource {
self.get_mut_opt_by_type_id_untyped(type_id).unwrap() self.get_mut_opt_by_type_id_untyped(type_id).unwrap()
} }
pub fn get_mut_unchecked<'a, T: Any + Send + Sync>(&mut self) -> &'a mut T { pub fn get_mut_unchecked<'a, T: Resource>(&mut self) -> &'a mut T {
unsafe { remove_life_time_mut(self.get_mut::<T>()) } unsafe { remove_life_time_mut(self.get_mut::<T>()) }
} }
pub fn get_mut_opt<T: Any + Send + Sync>(&mut self) -> Option<&mut T> { pub fn get_mut_opt<T: Resource>(&mut self) -> Option<&mut T> {
self.get_mut_opt_by_type_id(TypeId::of::<T>()) self.get_mut_opt_by_type_id(TypeId::of::<T>())
} }
pub fn get_mut_opt_by_type_id<T: Any + Send + Sync>( pub fn get_mut_opt_by_type_id<T: Resource>(&mut self, type_id: TypeId) -> Option<&mut T> {
&mut self,
type_id: TypeId,
) -> Option<&mut T> {
debug_assert_eq!(type_id, TypeId::of::<T>()); debug_assert_eq!(type_id, TypeId::of::<T>());
self.map self.map
.get_mut(&type_id) .get_mut(&type_id)
.map(|any| Self::downcast_mut_unchecked(any)) .map(|any| any.downcast_mut())
.flatten()
} }
pub fn get_mut_opt_by_type_id_untyped(&mut self, type_id: TypeId) -> Option<&mut Untyped> { pub fn get_mut_opt_by_type_id_untyped(&mut self, type_id: TypeId) -> Option<&mut dyn Resource> {
self.map.get_mut(&type_id).map(|any| any.as_mut()) self.map.get_mut(&type_id).map(|any| any.as_mut())
} }
pub fn contains<T: Any + Send + Sync>(&self) -> bool { pub fn contains<T: Resource>(&self) -> bool {
self.map.contains_key(&TypeId::of::<T>()) self.map.contains_key(&TypeId::of::<T>())
} }
} }
impl<'a, T> GetDisjointMut<'a, &'a mut T> for Resources
where
T: Resource,
{
type Error = Error;
fn get_mut(&'a mut self) -> std::result::Result<&'a mut T, Self::Error> {
self.map
.get_mut(&TypeId::of::<T>())
.map(|any| any.downcast_mut().unwrap())
.ok_or_else(|| anyhow!("failed downcasting {}", stringify!(T)))
}
}
macro_rules! impl_get_disjoint_mut {
($struct:ident<$($t:ident$(,)?)+>{$error:ident}) => {
impl<'a, $($t,)+> GetDisjointMut<'a, ($(&'a mut $t,)+)> for $struct
where
$(
$t: Resource + 'static,
)+
{
type Error = $error;
fn get_mut(&'a mut self) -> std::result::Result<($(&'a mut $t,)+), Self::Error> {
let mut types: std::collections::VecDeque<_>
= self.map.get_disjoint_mut([$(&TypeId::of::<$t>(),)+]).into_iter().collect();
Ok(($(
types
.pop_front()
.flatten()
.map(|any| any.downcast_mut().unwrap())
.ok_or_else(|| anyhow!("failed downcasting {}", stringify!($t)))?,
)+))
}
}
};
}
impl_get_disjoint_mut!(Resources < T, U > { Error });
impl_get_disjoint_mut!(Resources < T, U, V > { Error });
impl_get_disjoint_mut!(Resources < T, U, V, W > { Error });
impl_get_disjoint_mut!(Resources < T, U, V, W, X > { Error });
impl_get_disjoint_mut!(Resources < T, U, V, W, X, Y > { Error });
impl_get_disjoint_mut!(Resources < T, U, V, W, X, Y, Z > { Error });
impl_get_disjoint_mut!(Resources < T, U, V, W, X, Y, Z, A > { Error });
impl_get_disjoint_mut!(Resources < T, U, V, W, X, Y, Z, A, B > { Error });

View file

@ -10,7 +10,7 @@ use std::{
use anyhow::Result; use anyhow::Result;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::World; use crate::{World, get_disjoint_mut::GetDisjointMut};
pub trait EntityComponent: Any + Send + Sync { pub trait EntityComponent: Any + Send + Sync {
fn enable(&mut self, _world: &mut World) -> Result<()> { fn enable(&mut self, _world: &mut World) -> Result<()> {
@ -151,15 +151,13 @@ impl TypeMap {
} }
} }
pub trait GetTypeMap<'a, T: 'a> { impl<'a, T> GetDisjointMut<'a, &'a mut T> for TypeMap
fn get_mut(&'a mut self) -> std::result::Result<T, ComponentNotFoundError>;
}
impl<'a, T> GetTypeMap<'a, &'a mut T> for TypeMap
where where
T: EntityComponent + ComponentDebug, T: EntityComponent + ComponentDebug,
{ {
fn get_mut(&'a mut self) -> std::result::Result<&'a mut T, ComponentNotFoundError> { type Error = ComponentNotFoundError;
fn get_mut(&'a mut self) -> std::result::Result<&'a mut T, Self::Error> {
self.map self.map
.get_mut(&TypeId::of::<T>()) .get_mut(&TypeId::of::<T>())
.map(|any| any.downcast_mut().unwrap()) .map(|any| any.downcast_mut().unwrap())
@ -167,15 +165,17 @@ where
} }
} }
macro_rules! impl_get_type_map { macro_rules! impl_get_disjoint_mut {
(<$($t:ident$(,)?)+>) => { ($struct:ident<$($t:ident$(,)?)+>{$error:ident}) => {
impl<'a, $($t,)+> GetTypeMap<'a, ($(&'a mut $t,)+)> for TypeMap impl<'a, $($t,)+> GetDisjointMut<'a, ($(&'a mut $t,)+)> for $struct
where where
$( $(
$t: EntityComponent + ComponentDebug + 'static, $t: EntityComponent + ComponentDebug + 'static,
)+ )+
{ {
fn get_mut(&'a mut self) -> std::result::Result<($(&'a mut $t,)+), ComponentNotFoundError> { type Error = $error;
fn get_mut(&'a mut self) -> std::result::Result<($(&'a mut $t,)+), Self::Error> {
let mut types: std::collections::VecDeque<_> let mut types: std::collections::VecDeque<_>
= self.map.get_disjoint_mut([$(&TypeId::of::<$t>(),)+]).into_iter().collect(); = self.map.get_disjoint_mut([$(&TypeId::of::<$t>(),)+]).into_iter().collect();
@ -191,14 +191,16 @@ macro_rules! impl_get_type_map {
}; };
} }
impl_get_type_map!(<T, U>); impl_get_disjoint_mut!(TypeMap < T, U > { ComponentNotFoundError });
impl_get_type_map!(<T, U, V>); impl_get_disjoint_mut!(TypeMap < T, U, V > { ComponentNotFoundError });
impl_get_type_map!(<T, U, V, W>); impl_get_disjoint_mut!(TypeMap < T, U, V, W > { ComponentNotFoundError });
impl_get_type_map!(<T, U, V, W, X>); impl_get_disjoint_mut!(TypeMap < T, U, V, W, X > { ComponentNotFoundError });
impl_get_type_map!(<T, U, V, W, X, Y>); impl_get_disjoint_mut!(TypeMap < T, U, V, W, X, Y > { ComponentNotFoundError });
impl_get_type_map!(<T, U, V, W, X, Y, Z>); impl_get_disjoint_mut!(TypeMap < T, U, V, W, X, Y, Z > { ComponentNotFoundError });
impl_get_type_map!(<T, U, V, W, X, Y, Z, A>); #[rustfmt::skip]
impl_get_type_map!(<T, U, V, W, X, Y, Z, A, B>); impl_get_disjoint_mut!(TypeMap < T, U, V, W, X, Y, Z, A > { ComponentNotFoundError });
#[rustfmt::skip]
impl_get_disjoint_mut!(TypeMap < T, U, V, W, X, Y, Z, A, B > { ComponentNotFoundError });
#[derive(Debug)] #[derive(Debug)]
pub enum ComponentRequestType { pub enum ComponentRequestType {

View file

@ -2,10 +2,10 @@ use proc_macro::TokenStream;
use proc_macro2::{Span, TokenStream as TokenStream2}; use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::{format_ident, quote}; use quote::{format_ident, quote};
use syn::{ use syn::{
DeriveInput, Ident, LitInt, Result,
parse::{Parse, ParseStream}, parse::{Parse, ParseStream},
parse_macro_input, parse_macro_input,
token::Comma, token::Comma,
Ident, LitInt, Result,
}; };
struct InputInfo { struct InputInfo {
@ -115,3 +115,14 @@ pub fn implement_pair_update(input: TokenStream) -> TokenStream {
)* )*
}) })
} }
#[proc_macro_derive(Resource)]
pub fn derive_resource(input: TokenStream) -> TokenStream {
let ast = parse_macro_input!(input as DeriveInput);
let implementor = ast.ident;
TokenStream::from(quote! {
impl Resource for #implementor {}
})
}