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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
|
use std::any::type_name;
use std::collections::{HashMap, HashSet};
use std::hash::{DefaultHasher, Hash, Hasher};
use std::slice::Iter as SliceIter;
use crate::component::{Component, Id as ComponentId, IsOptional as ComponentIsOptional};
use crate::lock::Lock;
use crate::type_name::TypeName;
use crate::EntityComponent;
#[derive(Debug, Default)]
pub struct ComponentStorage
{
archetypes: Vec<Archetype>,
archetype_lookup: HashMap<ArchetypeComponentsHash, Vec<usize>>,
pending_archetype_lookup_entries: Vec<Vec<ComponentId>>,
}
#[derive(Debug)]
pub struct ArchetypeRefIter<'component_storage>
{
inner: SliceIter<'component_storage, usize>,
archetypes: &'component_storage Vec<Archetype>,
}
impl<'component_storage> Iterator for ArchetypeRefIter<'component_storage>
{
type Item = &'component_storage Archetype;
fn next(&mut self) -> Option<Self::Item>
{
let archetype_index = *self.inner.next()?;
Some(
self.archetypes
.get(archetype_index)
.expect("Archetype index in archetype lookup entry was not found"),
)
}
}
impl ComponentStorage
{
pub fn find_entities(
&self,
component_ids: &[(ComponentId, ComponentIsOptional)],
) -> Option<ArchetypeRefIter<'_>>
{
let ids = component_ids
.iter()
.filter_map(|(component_id, is_optional)| {
if *is_optional == ComponentIsOptional::Yes {
return None;
}
Some(*component_id)
});
self.archetype_lookup
.get(&ArchetypeComponentsHash::new(ids))
.map(|archetypes_indices| ArchetypeRefIter {
inner: archetypes_indices.iter(),
archetypes: &self.archetypes,
})
}
#[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
pub fn push_entity(&mut self, components: Vec<Box<dyn Component>>)
{
#[cfg(feature = "debug")]
tracing::debug!(
"Pushing entity with components: ({})",
components
.iter()
.map(|component| component.type_name())
.collect::<Vec<_>>()
.join(", ")
);
let archetype_indices = self
.archetype_lookup
.entry(ArchetypeComponentsHash::new(
components
.iter()
.filter(|component| !component.is_optional())
.map(|component| component.id()),
))
.or_insert_with(|| {
self.archetypes.push(Archetype::default());
vec![self.archetypes.len() - 1]
});
if archetype_indices.is_empty() {
self.archetypes.push(Archetype::default());
archetype_indices.push(self.archetypes.len() - 1);
}
let archetype = self
.archetypes
.get_mut(
archetype_indices
.first()
.copied()
.expect("No archetype index found"),
)
.expect("Archetype is gone");
archetype
.component_ids
.extend(components.iter().map(|component| component.id()));
archetype.components.push(
components
.into_iter()
.map(|component| EntityComponent {
id: component.id(),
name: component.type_name(),
component: Lock::new(component),
})
.collect(),
);
}
pub fn add_archetype_lookup_entry(&mut self, component_ids: &[ComponentId])
{
self.pending_archetype_lookup_entries
.push(component_ids.to_vec());
}
pub fn make_archetype_lookup_entries(&mut self)
{
for pending_entry in &self.pending_archetype_lookup_entries {
let components_set: HashSet<_> = pending_entry
.into_iter()
.map(|component_id| *component_id)
.collect();
let matching_archetype_indices = self
.archetypes
.iter()
.enumerate()
.filter_map(|(index, archetype)| {
if archetype.component_ids.is_superset(&components_set) {
return Some(index);
}
None
});
let archetype_indices = self
.archetype_lookup
.entry(ArchetypeComponentsHash::new(
pending_entry.into_iter().copied().clone(),
))
.or_default();
archetype_indices.extend(matching_archetype_indices);
}
}
}
impl TypeName for ComponentStorage
{
fn type_name(&self) -> &'static str
{
type_name::<Self>()
}
}
#[derive(Debug, Default)]
pub struct Archetype
{
component_ids: HashSet<ComponentId>,
pub components: Vec<Vec<EntityComponent>>,
}
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
struct ArchetypeComponentsHash
{
hash: u64,
}
impl ArchetypeComponentsHash
{
fn new(component_ids: impl IntoIterator<Item = ComponentId>) -> Self
{
let mut hasher = DefaultHasher::new();
for component_id in component_ids {
component_id.hash(&mut hasher);
}
let hash = hasher.finish();
Self { hash }
}
}
#[cfg(test)]
mod tests
{
use std::collections::HashSet;
use ecs_macros::Component;
use super::{Archetype, ArchetypeComponentsHash, ComponentStorage};
use crate::component::Id as ComponentId;
use crate::lock::Lock;
use crate::{self as ecs, EntityComponent};
#[derive(Debug, Component)]
struct HealthPotion
{
_hp_restoration: u32,
}
#[derive(Debug, Component)]
struct Hookshot
{
_range: u32,
}
#[derive(Debug, Component)]
struct DekuNut
{
_throwing_damage: u32,
}
#[derive(Debug, Component)]
struct Bow
{
_damage: u32,
}
#[derive(Debug, Component)]
struct IronBoots;
#[test]
fn push_entity_works()
{
let mut component_storage = ComponentStorage::default();
component_storage.push_entity(vec![
Box::new(HealthPotion { _hp_restoration: 12 }),
Box::new(Hookshot { _range: 50 }),
]);
assert_eq!(component_storage.archetypes.len(), 1);
let archetype = component_storage
.archetypes
.first()
.expect("Expected a archetype in archetypes Vec");
assert_eq!(archetype.component_ids.len(), 2);
// One entity
assert_eq!(archetype.components.len(), 1);
let entity_components = archetype
.components
.first()
.expect("Expected a entity in archetype");
assert_eq!(entity_components.len(), 2);
assert_eq!(component_storage.archetype_lookup.len(), 1);
let lookup = component_storage
.archetype_lookup
.get(&ArchetypeComponentsHash::new([
ComponentId::of::<HealthPotion>(),
ComponentId::of::<Hookshot>(),
]))
.expect("Expected entry in archetype lookup map");
let first_archetype_index = lookup
.first()
.expect("Expected archetype lookup to contain a archetype reference");
assert_eq!(*first_archetype_index, 0);
}
#[test]
fn lookup_works()
{
let mut component_storage = ComponentStorage::default();
component_storage.archetypes.push(Archetype {
component_ids: HashSet::from([
ComponentId::of::<IronBoots>(),
ComponentId::of::<HealthPotion>(),
ComponentId::of::<Hookshot>(),
]),
components: vec![
vec![EntityComponent {
id: ComponentId::of::<IronBoots>(),
name: "Iron boots",
component: Lock::new(Box::new(IronBoots)),
}],
vec![EntityComponent {
id: ComponentId::of::<HealthPotion>(),
name: "Health potion",
component: Lock::new(Box::new(HealthPotion { _hp_restoration: 20 })),
}],
vec![EntityComponent {
id: ComponentId::of::<Hookshot>(),
name: "Hookshot",
component: Lock::new(Box::new(Hookshot { _range: 67 })),
}],
],
});
component_storage.archetypes.push(Archetype {
component_ids: HashSet::from([
ComponentId::of::<DekuNut>(),
ComponentId::of::<IronBoots>(),
ComponentId::of::<Bow>(),
ComponentId::of::<Hookshot>(),
]),
components: vec![
vec![EntityComponent {
id: ComponentId::of::<DekuNut>(),
name: "Deku nut",
component: Lock::new(Box::new(DekuNut { _throwing_damage: 5 })),
}],
vec![EntityComponent {
id: ComponentId::of::<IronBoots>(),
name: "Iron boots",
component: Lock::new(Box::new(IronBoots)),
}],
vec![EntityComponent {
id: ComponentId::of::<Bow>(),
name: "Bow",
component: Lock::new(Box::new(Bow { _damage: 20 })),
}],
vec![EntityComponent {
id: ComponentId::of::<Hookshot>(),
name: "Hookshot",
component: Lock::new(Box::new(Hookshot { _range: 67 })),
}],
],
});
component_storage.add_archetype_lookup_entry(&[
ComponentId::of::<IronBoots>(),
ComponentId::of::<Hookshot>(),
]);
assert_eq!(component_storage.pending_archetype_lookup_entries.len(), 1);
component_storage.make_archetype_lookup_entries();
assert_eq!(component_storage.archetype_lookup.len(), 1);
let archetypes = component_storage
.archetype_lookup
.get(&ArchetypeComponentsHash::new([
ComponentId::of::<IronBoots>(),
ComponentId::of::<Hookshot>(),
]))
.expect(concat!(
"Expected a archetype for IronBoots & Hookshot to be found in the ",
"archetype lookup map"
));
assert_eq!(archetypes.len(), 2);
}
}
|