1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
use crate::private::ArchetypeMetadata;
use smallvec::SmallVec;
use std::alloc;
use std::any::{Any, TypeId};
use std::ops::Deref;

/// Defines archetype objects (entity states) with definite components.
pub trait ArchetypeState: Send + Sync + 'static {
    fn ty(&self) -> TypeId;
    fn as_ptr(&self) -> *const u8;
    fn forget(self);
    fn metadata(&self) -> ArchetypeMetadata;
    fn as_any(&self) -> &dyn Any;
    fn as_any_mut(&mut self) -> &mut dyn Any;
    fn num_components(&self) -> usize;

    fn component_ids(&self) -> SmallVec<[TypeId; 32]> {
        let meta = self.metadata();
        (meta.component_type_ids)()
    }
}

/// Defines archetype objects (entity states).
pub trait StaticArchetype: Sized + ArchetypeState {
    const N_COMPONENTS: usize;

    fn metadata() -> ArchetypeMetadata;

    fn into_any(self) -> AnyState {
        AnyState(Box::new(self))
    }
}

pub struct AnyState(Box<dyn ArchetypeState>);

/// Entity state with arbitrary components.
impl AnyState {
    /// Returns `&dyn` reference to the contained state.
    pub fn downcast_ref<T: ArchetypeState>(&self) -> Option<&T> {
        self.0.as_any().downcast_ref()
    }

    /// Returns `&mut dyn` reference to the contained state.
    pub fn downcast_mut<T: ArchetypeState>(&mut self) -> Option<&mut T> {
        self.0.as_any_mut().downcast_mut()
    }

    /// Returns the contained state.
    pub fn downcast<T: ArchetypeState>(self) -> Option<T> {
        if let Some(val) = self.downcast_ref::<T>() {
            let val = unsafe { (val as *const T).read() };
            self.forget();
            Some(val)
        } else {
            None
        }
    }
}

impl<T: StaticArchetype> From<T> for AnyState {
    fn from(state: T) -> Self {
        state.into_any()
    }
}

impl ArchetypeState for AnyState {
    fn ty(&self) -> TypeId {
        self.0.ty()
    }

    fn as_ptr(&self) -> *const u8 {
        self.0.as_ptr()
    }

    fn forget(self) {
        let val: &dyn ArchetypeState = self.0.deref();
        let layout = alloc::Layout::for_value(val);
        let ptr = Box::into_raw(self.0);

        // Deallocate `Box` without dropping the state itself.
        if layout.size() != 0 {
            unsafe {
                assert!(!ptr.is_null());
                alloc::dealloc(ptr as *mut u8, layout);
            };
        }
    }

    fn metadata(&self) -> ArchetypeMetadata {
        self.0.metadata()
    }

    fn as_any(&self) -> &dyn Any {
        self.0.as_any()
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self.0.as_any_mut()
    }

    fn num_components(&self) -> usize {
        self.0.num_components()
    }
}

impl ArchetypeState for () {
    fn ty(&self) -> TypeId {
        TypeId::of::<()>()
    }

    fn as_ptr(&self) -> *const u8 {
        self as *const _ as *const u8
    }

    fn forget(self) {}

    fn metadata(&self) -> ArchetypeMetadata {
        ArchetypeMetadata {
            type_id: TypeId::of::<Self>(),
            component_type_ids: || Default::default(),
            component_infos: || Default::default(),
            size: 0,
            needs_drop: false,
            drop_fn: |_| {},
        }
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn num_components(&self) -> usize {
        0
    }
}

impl StaticArchetype for () {
    const N_COMPONENTS: usize = 0;

    fn metadata() -> ArchetypeMetadata {
        ArchetypeMetadata {
            type_id: TypeId::of::<Self>(),
            component_type_ids: || Default::default(),
            component_infos: || Default::default(),
            size: 0,
            needs_drop: false,
            drop_fn: |_| {},
        }
    }
}