wecs_core/component/
component.rs

1use std::any::{Any, TypeId};
2
3use crate::query::QueryComponent;
4
5pub trait Component {}
6
7pub type ComponentId = TypeId;
8
9pub trait ComponentList {
10    fn get_ids() -> Vec<ComponentId>;
11    fn get_component_values(self) -> Vec<Box<dyn Any>>;
12}
13
14impl<T1> ComponentList for T1
15where
16    T1: Component + 'static,
17{
18    fn get_ids() -> Vec<ComponentId> {
19        vec![TypeId::of::<T1>()]
20    }
21
22    fn get_component_values(self) -> Vec<Box<dyn Any>> {
23        vec![Box::new(self)]
24    }
25}
26
27macro_rules! impl_cl_for {
28    ( $($n:ident),* ) => {
29        #[allow(non_snake_case)]
30        impl<$($n,)*> ComponentList for ($($n,)*)
31        where
32        $($n: Component + 'static,)*
33        {
34            fn get_ids() -> Vec<ComponentId> {
35                vec![$(TypeId::of::<$n>(),)*]
36            }
37
38            fn get_component_values(self) -> Vec<Box<dyn Any>> {
39                let ($($n,)*) = self;
40                vec![$(Box::new($n)),*]
41            }
42        }
43    };
44}
45
46impl_cl_for!(T1);
47impl_cl_for!(T1, T2);
48impl_cl_for!(T1, T2, T3);
49impl_cl_for!(T1, T2, T3, T4);
50impl_cl_for!(T1, T2, T3, T4, T5);
51impl_cl_for!(T1, T2, T3, T4, T5, T6);
52impl_cl_for!(T1, T2, T3, T4, T5, T6, T7);
53impl_cl_for!(T1, T2, T3, T4, T5, T6, T7, T8);
54impl_cl_for!(T1, T2, T3, T4, T5, T6, T7, T8, T9);
55impl_cl_for!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
56impl_cl_for!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
57impl_cl_for!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
58impl_cl_for!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13);
59impl_cl_for!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14);
60impl_cl_for!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15);
61impl_cl_for!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16);
62
63impl<C> QueryComponent for &C
64where
65    C: Component + 'static,
66{
67    type Item<'world> = &'world C;
68
69    fn get_component_ids() -> Vec<ComponentId> {
70        vec![TypeId::of::<C>()]
71    }
72
73    #[inline]
74    fn get_component<'world>(
75        world: crate::world::UnsafeWorldCell<'world>,
76        entity_id: crate::entity::EntityId,
77    ) -> Self::Item<'world> {
78        world.world().get_entity_component_unchecked::<C>(entity_id)
79    }
80}
81
82impl<C> QueryComponent for &mut C
83where
84    C: Component + 'static,
85{
86    type Item<'world> = &'world mut C;
87
88    fn get_component_ids() -> Vec<ComponentId> {
89        vec![TypeId::of::<C>()]
90    }
91
92    #[inline]
93    fn get_component<'world>(
94        world: crate::world::UnsafeWorldCell<'world>,
95        entity_id: crate::entity::EntityId,
96    ) -> Self::Item<'world> {
97        world
98            .world_mut()
99            .get_entity_component_mut_unchecked::<C>(entity_id)
100    }
101}