forked from turanszkij/WickedEngine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwiECS.h
638 lines (572 loc) · 18.2 KB
/
wiECS.h
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
#ifndef WI_ENTITY_COMPONENT_SYSTEM_H
#define WI_ENTITY_COMPONENT_SYSTEM_H
#include "wiArchive.h"
#include "wiJobSystem.h"
#include "wiUnorderedMap.h"
#include "wiUnorderedSet.h"
#include "wiVector.h"
#include <cstdint>
#include <cassert>
#include <atomic>
#include <memory>
#include <string>
// Entity-Component System
namespace wi::ecs
{
// The Entity is a global unique persistent identifier within the entity-component system
// It can be stored and used for the duration of the application
// The entity can be a different value on a different run of the application, if it was serialized
// It must be only serialized with the SerializeEntity() function. It will ensure that entities still match with their components correctly after serialization
using Entity = uint32_t;
inline constexpr Entity INVALID_ENTITY = 0;
// Runtime can create a new entity with this
inline Entity CreateEntity()
{
static std::atomic<Entity> next{ INVALID_ENTITY + 1 };
return next.fetch_add(1);
}
class ComponentLibrary;
struct EntitySerializer
{
wi::jobsystem::context ctx; // allow components to spawn serialization subtasks
wi::unordered_map<uint64_t, Entity> remap;
bool allow_remap = true;
uint64_t version = 0; // The ComponentLibrary serialization will modify this by the registered component's version number
wi::unordered_set<std::string> resource_registration; // register for resource manager serialization
ComponentLibrary* componentlibrary = nullptr;
wi::unordered_map<std::string, uint64_t> library_versions;
~EntitySerializer()
{
wi::jobsystem::Wait(ctx); // automatically wait for all subtasks after serialization
}
// Returns the library version of the currently serializing Component
// If not using ComponentLibrary, it returns version set by the user.
uint64_t GetVersion() const
{
return version;
}
uint64_t GetVersion(const std::string& name) const
{
auto it = library_versions.find(name);
if (it != library_versions.end())
{
return it->second;
}
return 0;
}
void RegisterResource(const std::string& resource_name)
{
if (resource_name.empty())
return;
resource_registration.insert(resource_name);
}
};
// This is the safe way to serialize an entity
inline void SerializeEntity(wi::Archive& archive, Entity& entity, EntitySerializer& seri)
{
if (archive.IsReadMode())
{
// Entities are always serialized as uint64_t for back-compat
uint64_t mem;
archive >> mem;
if (mem != INVALID_ENTITY && seri.allow_remap)
{
auto it = seri.remap.find(mem);
if (it == seri.remap.end())
{
entity = CreateEntity();
seri.remap[mem] = entity;
}
else
{
entity = it->second;
}
}
else
{
entity = (Entity)mem;
}
}
else
{
#if defined(__GNUC__) && !defined(__SCE__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
#endif // __GNUC__ && !__SCE__
archive << entity;
#if defined(__GNUC__) && !defined(__SCE__)
#pragma GCC diagnostic pop
#endif // __GNUC__ && !__SCE__
}
}
// This is an interface class to implement a ComponentManager,
// inherit this class if you want to work with ComponentLibrary
class ComponentManager_Interface
{
public:
virtual ~ComponentManager_Interface() = default;
virtual void Copy(const ComponentManager_Interface& other) = 0;
virtual void Merge(ComponentManager_Interface& other) = 0;
virtual void Clear() = 0;
virtual void Serialize(wi::Archive& archive, EntitySerializer& seri) = 0;
virtual void Component_Serialize(Entity entity, wi::Archive& archive, EntitySerializer& seri) = 0;
virtual void Remove(Entity entity) = 0;
virtual void Remove_KeepSorted(Entity entity) = 0;
virtual void MoveItem(size_t index_from, size_t index_to) = 0;
virtual bool Contains(Entity entity) const = 0;
virtual size_t GetIndex(Entity entity) const = 0;
virtual size_t GetCount() const = 0;
virtual Entity GetEntity(size_t index) const = 0;
virtual const wi::vector<Entity>& GetEntityArray() const = 0;
};
// The ComponentManager is a container that stores components and matches them with entities
// Note: final keyword is used to indicate this is a final implementation.
// This allows function inlining and avoid calls, improves performance considerably
template<typename Component>
class ComponentManager final : public ComponentManager_Interface
{
public:
// reservedCount : how much components can be held initially before growing the container
ComponentManager(size_t reservedCount = 0)
{
components.reserve(reservedCount);
entities.reserve(reservedCount);
lookup.reserve(reservedCount);
}
// Clear the whole container
inline void Clear()
{
components.clear();
entities.clear();
lookup.clear();
}
// Perform deep copy of all the contents of "other" into this
inline void Copy(const ComponentManager<Component>& other)
{
Clear();
components = other.components;
entities = other.entities;
lookup = other.lookup;
}
// Merge in an other component manager of the same type to this.
// The other component manager MUST NOT contain any of the same entities!
// The other component manager is not retained after this operation!
inline void Merge(ComponentManager<Component>& other)
{
components.reserve(GetCount() + other.GetCount());
entities.reserve(GetCount() + other.GetCount());
lookup.reserve(GetCount() + other.GetCount());
for (size_t i = 0; i < other.GetCount(); ++i)
{
Entity entity = other.entities[i];
assert(!Contains(entity));
entities.push_back(entity);
lookup[entity] = components.size();
components.push_back(std::move(other.components[i]));
}
other.Clear();
}
inline void Copy(const ComponentManager_Interface& other)
{
Copy((ComponentManager<Component>&)other);
}
inline void Merge(ComponentManager_Interface& other)
{
Merge((ComponentManager<Component>&)other);
}
// Read/Write everything to an archive depending on the archive state
inline void Serialize(wi::Archive& archive, EntitySerializer& seri)
{
if (archive.IsReadMode())
{
const size_t prev_count = components.size();
size_t count;
archive >> count;
components.resize(prev_count + count);
for (size_t i = 0; i < count; ++i)
{
components[prev_count + i].Serialize(archive, seri);
}
entities.resize(prev_count + count);
for (size_t i = 0; i < count; ++i)
{
Entity entity;
SerializeEntity(archive, entity, seri);
entities[prev_count + i] = entity;
lookup[entity] = prev_count + i;
}
}
else
{
archive << components.size();
for (Component& component : components)
{
component.Serialize(archive, seri);
}
for (Entity entity : entities)
{
SerializeEntity(archive, entity, seri);
}
}
}
//Read one single component onto an archive, make sure entity are serialized first
inline void Component_Serialize(Entity entity, wi::Archive& archive, EntitySerializer& seri)
{
if(archive.IsReadMode())
{
bool component_exists;
archive >> component_exists;
if (component_exists)
{
auto& component = this->Create(entity);
component.Serialize(archive, seri);
}
}
else
{
auto component = this->GetComponent(entity);
if (component != nullptr)
{
archive << true;
component->Serialize(archive, seri);
}
else
{
archive << false;
}
}
}
// Create a new component and retrieve a reference to it
inline Component& Create(Entity entity)
{
// INVALID_ENTITY is not allowed!
assert(entity != INVALID_ENTITY);
// Only one of this component type per entity is allowed!
assert(lookup.find(entity) == lookup.end());
// Entity count must always be the same as the number of coponents!
assert(entities.size() == components.size());
assert(lookup.size() == components.size());
// Update the entity lookup table:
lookup[entity] = components.size();
// New components are always pushed to the end:
components.emplace_back();
// Also push corresponding entity:
entities.push_back(entity);
return components.back();
}
// Remove a component of a certain entity if it exists
inline void Remove(Entity entity)
{
auto it = lookup.find(entity);
if (it != lookup.end())
{
// Directly index into components and entities array:
const size_t index = it->second;
const Entity entity = entities[index];
if (index < components.size() - 1)
{
// Swap out the dead element with the last one:
components[index] = std::move(components.back()); // try to use move instead of copy
entities[index] = entities.back();
// Update the lookup table:
lookup[entities[index]] = index;
}
// Shrink the container:
components.pop_back();
entities.pop_back();
lookup.erase(entity);
}
}
// Remove a component of a certain entity if it exists while keeping the current ordering
inline void Remove_KeepSorted(Entity entity)
{
auto it = lookup.find(entity);
if (it != lookup.end())
{
// Directly index into components and entities array:
const size_t index = it->second;
const Entity entity = entities[index];
if (index < components.size() - 1)
{
// Move every component left by one that is after this element:
for (size_t i = index + 1; i < components.size(); ++i)
{
components[i - 1] = std::move(components[i]);
}
// Move every entity left by one that is after this element and update lut:
for (size_t i = index + 1; i < entities.size(); ++i)
{
entities[i - 1] = entities[i];
lookup[entities[i - 1]] = i - 1;
}
}
// Shrink the container:
components.pop_back();
entities.pop_back();
lookup.erase(entity);
}
}
// Place an entity-component to the specified index position while keeping the ordering intact
inline void MoveItem(size_t index_from, size_t index_to)
{
assert(index_from < GetCount());
assert(index_to < GetCount());
if (index_from == index_to)
{
return;
}
// Save the moved component and entity:
Component component = std::move(components[index_from]);
Entity entity = entities[index_from];
// Every other entity-component that's in the way gets moved by one and lut is kept updated:
const int direction = index_from < index_to ? 1 : -1;
for (size_t i = index_from; i != index_to; i += direction)
{
const size_t next = i + direction;
components[i] = std::move(components[next]);
entities[i] = entities[next];
lookup[entities[i]] = i;
}
// Saved entity-component moved to the required position:
components[index_to] = std::move(component);
entities[index_to] = entity;
lookup[entity] = index_to;
}
// Check if a component exists for a given entity or not
inline bool Contains(Entity entity) const
{
if (lookup.empty())
return false;
return lookup.find(entity) != lookup.end();
}
// Retrieve a [read/write] component specified by an entity (if it exists, otherwise nullptr)
inline Component* GetComponent(Entity entity)
{
if (lookup.empty())
return nullptr;
auto it = lookup.find(entity);
if (it != lookup.end())
{
return &components[it->second];
}
return nullptr;
}
// Retrieve a [read only] component specified by an entity (if it exists, otherwise nullptr)
inline const Component* GetComponent(Entity entity) const
{
if (lookup.empty())
return nullptr;
const auto it = lookup.find(entity);
if (it != lookup.end())
{
return &components[it->second];
}
return nullptr;
}
// Retrieve component index by entity handle (if not exists, returns ~0ull value)
inline size_t GetIndex(Entity entity) const
{
if (lookup.empty())
return ~0ull;
const auto it = lookup.find(entity);
if (it != lookup.end())
{
return it->second;
}
return ~0ull;
}
// Retrieve the number of existing entries
inline size_t GetCount() const { return components.size(); }
// Directly index a specific component without indirection
// 0 <= index < GetCount()
inline Entity GetEntity(size_t index) const { return entities[index]; }
// Directly index a specific [read/write] component without indirection
// 0 <= index < GetCount()
inline Component& operator[](size_t index) { return components[index]; }
// Directly index a specific [read only] component without indirection
// 0 <= index < GetCount()
inline const Component& operator[](size_t index) const { return components[index]; }
// Returns the tightly packed [read only] entity array
inline const wi::vector<Entity>& GetEntityArray() const { return entities; }
// Returns the tightly packed [read only] component array
inline const wi::vector<Component>& GetComponentArray() const { return components; }
private:
// This is a linear array of alive components
wi::vector<Component> components;
// This is a linear array of entities corresponding to each alive component
wi::vector<Entity> entities;
// This is a lookup table for entities
wi::unordered_map<Entity, size_t> lookup;
// Disallow this to be copied by mistake
ComponentManager(const ComponentManager&) = delete;
};
// This is the class to store all component managers,
// this is useful for bulk operation of all attached components within an entity
class ComponentLibrary
{
public:
struct LibraryEntry
{
std::unique_ptr<ComponentManager_Interface> component_manager;
uint64_t version = 0;
};
wi::unordered_map<std::string, LibraryEntry> entries;
// Create an instance of ComponentManager of a certain data type
// The name must be unique, it will be used in serialization
// version is optional, it will be propagated to ComponentManager::Serialize() inside the EntitySerializer parameter
template<typename T>
inline ComponentManager<T>& Register(const std::string& name, uint64_t version = 0)
{
entries[name].component_manager = std::make_unique<ComponentManager<T>>();
entries[name].version = version;
return static_cast<ComponentManager<T>&>(*entries[name].component_manager);
}
template<typename T>
inline ComponentManager<T>* Get(const std::string& name)
{
auto it = entries.find(name);
if (it == entries.end())
return nullptr;
return static_cast<ComponentManager<T>*>(it->second.component_manager.get());
}
template<typename T>
inline const ComponentManager<T>* Get(const std::string& name) const
{
auto it = entries.find(name);
if (it == entries.end())
return nullptr;
return static_cast<const ComponentManager<T>*>(it->second.component_manager.get());
}
inline uint64_t GetVersion(std::string name) const
{
auto it = entries.find(name);
if (it == entries.end())
return 0;
return it->second.version;
}
// Serialize all registered component managers
inline void Serialize(wi::Archive& archive, EntitySerializer& seri)
{
seri.componentlibrary = this;
if(archive.IsReadMode())
{
bool has_next = false;
size_t begin = archive.GetPos();
// First pass, gather component type versions and jump over all data:
// This is so that we can look up other component versions within component serialization if needed
do
{
archive >> has_next;
if (has_next)
{
std::string name;
archive >> name;
uint64_t jump_pos = 0;
archive >> jump_pos;
auto it = entries.find(name);
if (it != entries.end())
{
archive >> seri.version;
seri.library_versions[name] = seri.version;
}
archive.Jump(jump_pos);
}
} while (has_next);
// Jump back to beginning of component library data
archive.Jump(begin);
// Second pass, read all component data:
// At this point, all existing component type versions are available
do
{
archive >> has_next;
if(has_next)
{
std::string name;
archive >> name;
uint64_t jump_pos = 0;
archive >> jump_pos;
auto it = entries.find(name);
if(it != entries.end())
{
archive >> seri.version;
it->second.component_manager->Serialize(archive, seri);
}
else
{
// component manager of this name was not registered, skip serialization by jumping over the data
archive.Jump(jump_pos);
}
}
}
while(has_next);
}
else
{
// Save all component type versions:
for (auto& it : entries)
{
seri.library_versions[it.first] = it.second.version;
}
// Serialize all component data, at this point component type version lookup is also complete
for(auto& it : entries)
{
archive << true;
archive << it.first; // name
size_t offset = archive.WriteUnknownJumpPosition(); // we will be able to jump from here...
archive << it.second.version;
seri.version = it.second.version;
it.second.component_manager->Serialize(archive, seri);
archive.PatchUnknownJumpPosition(offset); // ...to here, if this component manager was not registered
}
archive << false;
}
}
// Serialize all components for one entity
inline void Entity_Serialize(Entity entity, wi::Archive& archive, EntitySerializer& seri)
{
seri.componentlibrary = this;
if(archive.IsReadMode())
{
bool has_next = false;
do
{
archive >> has_next;
if(has_next)
{
std::string name;
archive >> name;
uint64_t jump_size = 0;
archive >> jump_size;
auto it = entries.find(name);
if (it != entries.end())
{
archive >> seri.version;
it->second.component_manager->Component_Serialize(entity, archive, seri);
}
else
{
// component manager of this name was not registered, skip serialization by jumping over the data
archive.Jump(jump_size);
}
}
}
while(has_next);
}
else
{
for(auto& it : entries)
{
archive << true;
archive << it.first; // name
size_t offset = archive.WriteUnknownJumpPosition(); // we will be able to jump from here...
archive << it.second.version;
seri.version = it.second.version;
it.second.component_manager->Component_Serialize(entity, archive, seri);
archive.PatchUnknownJumpPosition(offset); // ...to here, if this component manager was not registered
}
archive << false;
}
}
};
}
#endif // WI_ENTITY_COMPONENT_SYSTEM_H