This repository has been archived by the owner on Feb 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 56
/
ECS.h
1198 lines (996 loc) · 29.4 KB
/
ECS.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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#pragma once
/*
Copyright (c) 2016 Sam Bloomberg
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <unordered_map>
#include <functional>
#include <vector>
#include <algorithm>
#include <stdint.h>
#include <type_traits>
//////////////////////////////////////////////////////////////////////////
// SETTINGS //
//////////////////////////////////////////////////////////////////////////
// Define what you want to pass to the tick() function by defining ECS_TICK_TYPE before including this header,
// or leave it as default (float).
// This is really messy to do but the alternative is some sort of slow custom event setup for ticks, which is silly.
// Add this before including this header if you don't want to pass anything to tick()
//#define ECS_TICK_TYPE_VOID
#ifndef ECS_TICK_TYPE
#define ECS_TICK_TYPE ECS::DefaultTickData
#endif
// Define what kind of allocator you want the world to use. It should have a default constructor.
#ifndef ECS_ALLOCATOR_TYPE
#define ECS_ALLOCATOR_TYPE std::allocator<ECS::Entity>
#endif
// Define ECS_TICK_NO_CLEANUP if you don't want the world to automatically cleanup dead entities
// at the beginning of each tick. This will require you to call cleanup() manually to prevent memory
// leaks.
//#define ECS_TICK_NO_CLEANUP
// Define ECS_NO_RTTI to turn off RTTI. This requires using the ECS_DEFINE_TYPE and ECS_DECLARE_TYPE macros on all types
// that you wish to use as components or events. If you use ECS_NO_RTTI, also place ECS_TYPE_IMPLEMENTATION in a single cpp file.
//#define ECS_NO_RTTI
#ifndef ECS_NO_RTTI
#include <typeindex>
#include <typeinfo>
#define ECS_TYPE_IMPLEMENTATION
#else
#define ECS_TYPE_IMPLEMENTATION \
ECS::TypeIndex ECS::Internal::TypeRegistry::nextIndex = 1; \
\
ECS_DEFINE_TYPE(ECS::Events::OnEntityCreated);\
ECS_DEFINE_TYPE(ECS::Events::OnEntityDestroyed); \
#endif
//////////////////////////////////////////////////////////////////////////
// CODE //
//////////////////////////////////////////////////////////////////////////
namespace ECS
{
#ifndef ECS_NO_RTTI
typedef std::type_index TypeIndex;
#define ECS_DECLARE_TYPE
#define ECS_DEFINE_TYPE(name)
template<typename T>
TypeIndex getTypeIndex()
{
return std::type_index(typeid(T));
}
#else
typedef uint32_t TypeIndex;
namespace Internal
{
class TypeRegistry
{
public:
TypeRegistry()
{
index = nextIndex;
++nextIndex;
}
TypeIndex getIndex() const
{
return index;
}
private:
static TypeIndex nextIndex;
TypeIndex index;
};
}
#define ECS_DECLARE_TYPE public: static ECS::Internal::TypeRegistry __ecs_type_reg
#define ECS_DEFINE_TYPE(name) ECS::Internal::TypeRegistry name::__ecs_type_reg
template<typename T>
TypeIndex getTypeIndex()
{
return T::__ecs_type_reg.getIndex();
}
#endif
class World;
class Entity;
typedef float DefaultTickData;
typedef ECS_ALLOCATOR_TYPE Allocator;
// Do not use anything in the Internal namespace yourself.
namespace Internal
{
template<typename... Types>
class EntityComponentView;
class EntityView;
struct BaseComponentContainer
{
public:
virtual ~BaseComponentContainer() { }
// This should only ever be called by the entity itself.
virtual void destroy(World* world) = 0;
// This will be called by the entity itself
virtual void removed(Entity* ent) = 0;
};
class BaseEventSubscriber
{
public:
virtual ~BaseEventSubscriber() {};
};
template<typename... Types>
class EntityComponentIterator
{
public:
EntityComponentIterator(World* world, size_t index, bool bIsEnd, bool bIncludePendingDestroy);
size_t getIndex() const
{
return index;
}
bool isEnd() const;
bool includePendingDestroy() const
{
return bIncludePendingDestroy;
}
World* getWorld() const
{
return world;
}
Entity* get() const;
Entity* operator*() const
{
return get();
}
bool operator==(const EntityComponentIterator<Types...>& other) const
{
if (world != other.world)
return false;
if (isEnd())
return other.isEnd();
return index == other.index;
}
bool operator!=(const EntityComponentIterator<Types...>& other) const
{
if (world != other.world)
return true;
if (isEnd())
return !other.isEnd();
return index != other.index;
}
EntityComponentIterator<Types...>& operator++();
private:
bool bIsEnd = false;
size_t index;
class ECS::World* world;
bool bIncludePendingDestroy;
};
template<typename... Types>
class EntityComponentView
{
public:
EntityComponentView(const EntityComponentIterator<Types...>& first, const EntityComponentIterator<Types...>& last);
const EntityComponentIterator<Types...>& begin() const
{
return firstItr;
}
const EntityComponentIterator<Types...>& end() const
{
return lastItr;
}
private:
EntityComponentIterator<Types...> firstItr;
EntityComponentIterator<Types...> lastItr;
};
}
/**
* Think of this as a pointer to a component. Whenever you get a component from the world or an entity,
* it'll be wrapped in a ComponentHandle.
*/
template<typename T>
class ComponentHandle
{
public:
ComponentHandle()
: component(nullptr)
{
}
ComponentHandle(T* component)
: component(component)
{
}
T* operator->() const
{
return component;
}
operator bool() const
{
return isValid();
}
T& get()
{
return *component;
}
bool isValid() const
{
return component != nullptr;
}
private:
T* component;
};
/**
* A system that acts on entities. Generally, this will act on a subset of entities using World::each().
*
* Systems often will respond to events by subclassing EventSubscriber. You may use configure() to subscribe to events,
* but remember to unsubscribe in unconfigure().
*/
class EntitySystem
{
public:
virtual ~EntitySystem() {}
/**
* Called when this system is added to a world.
*/
virtual void configure(World* world)
{
}
/**
* Called when this system is being removed from a world.
*/
virtual void unconfigure(World* world)
{
}
/**
* Called when World::tick() is called. See ECS_TICK_TYPE at the top of this file for more
* information about passing data to tick.
*/
#ifdef ECS_TICK_TYPE_VOID
virtual void tick(World* world)
#else
virtual void tick(World* world, ECS_TICK_TYPE data)
#endif
{
}
};
/**
* Subclass this as EventSubscriber<EventType> and then call World::subscribe() in order to subscribe to events. Make sure
* to call World::unsubscribe() or World::unsubscribeAll() when your subscriber is deleted!
*/
template<typename T>
class EventSubscriber : public Internal::BaseEventSubscriber
{
public:
virtual ~EventSubscriber() {}
/**
* Called when an event is emitted by the world.
*/
virtual void receive(World* world, const T& event) = 0;
};
namespace Events
{
// Called when a new entity is created.
struct OnEntityCreated
{
ECS_DECLARE_TYPE;
Entity* entity;
};
// Called when an entity is about to be destroyed.
struct OnEntityDestroyed
{
ECS_DECLARE_TYPE;
Entity* entity;
};
// Called when a component is assigned (not necessarily created).
template<typename T>
struct OnComponentAssigned
{
ECS_DECLARE_TYPE;
Entity* entity;
ComponentHandle<T> component;
};
// Called when a component is removed
template<typename T>
struct OnComponentRemoved
{
ECS_DECLARE_TYPE;
Entity* entity;
ComponentHandle<T> component;
};
#ifdef ECS_NO_RTTI
template<typename T>
ECS_DEFINE_TYPE(ECS::Events::OnComponentAssigned<T>);
template<typename T>
ECS_DEFINE_TYPE(ECS::Events::OnComponentRemoved<T>);
#endif
}
/**
* A container for components. Entities do not have any logic of their own, except of that which to manage
* components. Components themselves are generally structs that contain data with which EntitySystems can
* act upon, but technically any data type may be used as a component, though only one of each data type
* may be on a single Entity at a time.
*/
class Entity
{
public:
friend class World;
const static size_t InvalidEntityId = 0;
// Do not create entities yourself, use World::create().
Entity(World* world, size_t id)
: world(world), id(id)
{
}
// Do not delete entities yourself, use World::destroy().
~Entity()
{
removeAll();
}
/**
* Get the world associated with this entity.
*/
World* getWorld() const
{
return world;
}
/**
* Does this entity have a component?
*/
template<typename T>
bool has() const
{
auto index = getTypeIndex<T>();
return components.find(index) != components.end();
}
/**
* Does this entity have this list of components? The order of components does not matter.
*/
template<typename T, typename V, typename... Types>
bool has() const
{
return has<T>() && has<V, Types...>();
}
/**
* Assign a new component (or replace an old one). All components must have a default constructor, though they
* may have additional constructors. You may pass arguments to this function the same way you would to a constructor.
*
* It is recommended that components be simple types (not const, not references, not pointers). If you need to store
* any of the above, wrap it in a struct.
*/
template<typename T, typename... Args>
ComponentHandle<T> assign(Args&&... args);
/**
* Remove a component of a specific type. Returns whether a component was removed.
*/
template<typename T>
bool remove()
{
auto found = components.find(getTypeIndex<T>());
if (found != components.end())
{
found->second->removed(this);
found->second->destroy(world);
components.erase(found);
return true;
}
return false;
}
/**
* Remove all components from this entity.
*/
void removeAll()
{
for (auto pair : components)
{
pair.second->removed(this);
pair.second->destroy(world);
}
components.clear();
}
/**
* Get a component from this entity.
*/
template<typename T>
ComponentHandle<T> get();
/**
* Call a function with components from this entity as arguments. This will return true if this entity has
* all specified components attached, and false if otherwise.
*/
template<typename... Types>
bool with(typename std::common_type<std::function<void(ComponentHandle<Types>...)>>::type view)
{
if (!has<Types...>())
return false;
view(get<Types>()...); // variadic template expansion is fun
return true;
}
/**
* Get this entity's id. Entity ids aren't too useful at the moment, but can be used to tell the difference between entities when debugging.
*/
size_t getEntityId() const
{
return id;
}
bool isPendingDestroy() const
{
return bPendingDestroy;
}
private:
std::unordered_map<TypeIndex, Internal::BaseComponentContainer*> components;
World* world;
size_t id;
bool bPendingDestroy = false;
};
/**
* The world creates, destroys, and manages entities. The lifetime of entities and _registered_ systems are handled by the world
* (don't delete a system without unregistering it from the world first!), while event subscribers have their own lifetimes
* (the world doesn't delete them automatically when the world is deleted).
*/
class World
{
public:
using WorldAllocator = std::allocator_traits<Allocator>::template rebind_alloc<World>;
using EntityAllocator = std::allocator_traits<Allocator>::template rebind_alloc<Entity>;
using SystemAllocator = std::allocator_traits<Allocator>::template rebind_alloc<EntitySystem>;
using EntityPtrAllocator = std::allocator_traits<Allocator>::template rebind_alloc<Entity*>;
using SystemPtrAllocator = std::allocator_traits<Allocator>::template rebind_alloc<EntitySystem*>;
using SubscriberPtrAllocator = std::allocator_traits<Allocator>::template rebind_alloc<Internal::BaseEventSubscriber*>;
using SubscriberPairAllocator = std::allocator_traits<Allocator>::template rebind_alloc<std::pair<const TypeIndex, std::vector<Internal::BaseEventSubscriber*, SubscriberPtrAllocator>>>;
/**
* Use this function to construct the world with a custom allocator.
*/
static World* createWorld(Allocator alloc)
{
WorldAllocator worldAlloc(alloc);
World* world = std::allocator_traits<WorldAllocator>::allocate(worldAlloc, 1);
std::allocator_traits<WorldAllocator>::construct(worldAlloc, world, alloc);
return world;
}
/**
* Use this function to construct the world with the default allocator.
*/
static World* createWorld()
{
return createWorld(Allocator());
}
// Use this to destroy the world instead of calling delete.
// This will emit OnEntityDestroyed events and call EntitySystem::unconfigure as appropriate.
void destroyWorld()
{
WorldAllocator alloc(entAlloc);
std::allocator_traits<WorldAllocator>::destroy(alloc, this);
std::allocator_traits<WorldAllocator>::deallocate(alloc, this, 1);
}
World(Allocator alloc)
: entAlloc(alloc), systemAlloc(alloc),
entities({}, EntityPtrAllocator(alloc)),
systems({}, SystemPtrAllocator(alloc)),
subscribers({}, 0, std::hash<TypeIndex>(), std::equal_to<TypeIndex>(), SubscriberPtrAllocator(alloc))
{
}
/**
* Destroying the world will emit OnEntityDestroyed events and call EntitySystem::unconfigure() as appropriate.
*
* Use World::destroyWorld to destroy and deallocate the world, do not manually delete the world!
*/
~World();
/**
* Create a new entity. This will emit the OnEntityCreated event.
*/
Entity* create()
{
++lastEntityId;
Entity* ent = std::allocator_traits<EntityAllocator>::allocate(entAlloc, 1);
std::allocator_traits<EntityAllocator>::construct(entAlloc, ent, this, lastEntityId);
entities.push_back(ent);
emit<Events::OnEntityCreated>({ ent });
return ent;
}
/**
* Destroy an entity. This will emit the OnEntityDestroy event.
*
* If immediate is false (recommended), then the entity won't be immediately
* deleted but instead will be removed at the beginning of the next tick() or
* when cleanup() is called. OnEntityDestroyed will still be called immediately.
*
* This function is safe to call multiple times on a single entity. Note that calling
* this once with immediate = false and then calling it with immediate = true will
* remove the entity from the pending destroy queue and will immediately destroy it
* _without_ emitting a second OnEntityDestroyed event.
*
* A warning: Do not set immediate to true if you are currently iterating through entities!
*/
void destroy(Entity* ent, bool immediate = false);
/**
* Delete all entities in the pending destroy queue. Returns true if any entities were cleaned up,
* false if there were no entities to clean up.
*/
bool cleanup();
/**
* Reset the world, destroying all entities. Entity ids will be reset as well.
*/
void reset();
/**
* Register a system. The world will manage the memory of the system unless you unregister the system.
*/
EntitySystem* registerSystem(EntitySystem* system)
{
systems.push_back(system);
system->configure(this);
return system;
}
/**
* Unregister a system.
*/
void unregisterSystem(EntitySystem* system)
{
systems.erase(std::remove(systems.begin(), systems.end(), system), systems.end());
system->unconfigure(this);
}
void enableSystem(EntitySystem* system)
{
auto it = std::find(disabledSystems.begin(), disabledSystems.end(), system);
if (it != disabledSystems.end())
{
disabledSystems.erase(it);
systems.push_back(system);
}
}
void disableSystem(EntitySystem* system)
{
auto it = std::find(systems.begin(), systems.end(), system);
if (it != systems.end())
{
systems.erase(it);
disabledSystems.push_back(system);
}
}
/**
* Subscribe to an event.
*/
template<typename T>
void subscribe(EventSubscriber<T>* subscriber)
{
auto index = getTypeIndex<T>();
auto found = subscribers.find(index);
if (found == subscribers.end())
{
std::vector<Internal::BaseEventSubscriber*, SubscriberPtrAllocator> subList(entAlloc);
subList.push_back(subscriber);
subscribers.insert({ index, subList });
}
else
{
found->second.push_back(subscriber);
}
}
/**
* Unsubscribe from an event.
*/
template<typename T>
void unsubscribe(EventSubscriber<T>* subscriber)
{
auto index = getTypeIndex<T>();
auto found = subscribers.find(index);
if (found != subscribers.end())
{
found->second.erase(std::remove(found->second.begin(), found->second.end(), subscriber), found->second.end());
if (found->second.size() == 0)
{
subscribers.erase(found);
}
}
}
/**
* Unsubscribe from all events. Don't be afraid of the void pointer, just pass in your subscriber as normal.
*/
void unsubscribeAll(void* subscriber)
{
for (auto kv : subscribers)
{
kv.second.erase(std::remove(kv.second.begin(), kv.second.end(), subscriber), kv.second.end());
if (kv.second.size() == 0)
{
subscribers.erase(kv.first);
}
}
}
/**
* Emit an event. This will do nothing if there are no subscribers for the event type.
*/
template<typename T>
void emit(const T& event)
{
auto found = subscribers.find(getTypeIndex<T>());
if (found != subscribers.end())
{
for (auto* base : found->second)
{
auto* sub = reinterpret_cast<EventSubscriber<T>*>(base);
sub->receive(this, event);
}
}
}
/**
* Run a function on each entity with a specific set of components. This is useful for implementing an EntitySystem.
*
* If you want to include entities that are pending destruction, set includePendingDestroy to true.
*/
template<typename... Types>
void each(typename std::common_type<std::function<void(Entity*, ComponentHandle<Types>...)>>::type viewFunc, bool bIncludePendingDestroy = false);
/**
* Run a function on all entities.
*/
void all(std::function<void(Entity*)> viewFunc, bool bIncludePendingDestroy = false);
/**
* Get a view for entities with a specific set of components. The list of entities is calculated on the fly, so this method itself
* has little overhead. This is mostly useful with a range based for loop.
*/
template<typename... Types>
Internal::EntityComponentView<Types...> each(bool bIncludePendingDestroy = false)
{
Internal::EntityComponentIterator<Types...> first(this, 0, false, bIncludePendingDestroy);
Internal::EntityComponentIterator<Types...> last(this, getCount(), true, bIncludePendingDestroy);
return Internal::EntityComponentView<Types...>(first, last);
}
Internal::EntityView all(bool bIncludePendingDestroy = false);
size_t getCount() const
{
return entities.size();
}
Entity* getByIndex(size_t idx)
{
if (idx >= getCount())
return nullptr;
return entities[idx];
}
/**
* Get an entity by an id. This is a slow process.
*/
Entity* getById(size_t id) const;
/**
* Tick the world. See the definition for ECS_TICK_TYPE at the top of this file for more information on
* passing data through tick().
*/
#ifdef ECS_TICK_TYPE_VOID
void tick()
#else
void tick(ECS_TICK_TYPE data)
#endif
{
#ifndef ECS_TICK_NO_CLEANUP
cleanup();
#endif
for (auto* system : systems)
{
#ifdef ECS_TICK_TYPE_VOID
system->tick(this);
#else
system->tick(this, data);
#endif
}
}
EntityAllocator& getPrimaryAllocator()
{
return entAlloc;
}
private:
EntityAllocator entAlloc;
SystemAllocator systemAlloc;
std::vector<Entity*, EntityPtrAllocator> entities;
std::vector<EntitySystem*, SystemPtrAllocator> systems;
std::vector<EntitySystem*> disabledSystems;
std::unordered_map<TypeIndex,
std::vector<Internal::BaseEventSubscriber*, SubscriberPtrAllocator>,
std::hash<TypeIndex>,
std::equal_to<TypeIndex>,
SubscriberPairAllocator> subscribers;
size_t lastEntityId = 0;
};
namespace Internal
{
class EntityIterator
{
public:
EntityIterator(World* world, size_t index, bool bIsEnd, bool bIncludePendingDestroy);
size_t getIndex() const
{
return index;
}
bool isEnd() const;
bool includePendingDestroy() const
{
return bIncludePendingDestroy;
}
World* getWorld() const
{
return world;
}
Entity* get() const;
Entity* operator*() const
{
return get();
}
bool operator==(const EntityIterator& other) const
{
if (world != other.world)
return false;
if (isEnd())
return other.isEnd();
return index == other.index;
}
bool operator!=(const EntityIterator& other) const
{
if (world != other.world)
return true;
if (isEnd())
return !other.isEnd();
return index != other.index;
}
EntityIterator& operator++();
private:
bool bIsEnd = false;
size_t index;
class ECS::World* world;
bool bIncludePendingDestroy;
};
class EntityView
{
public:
EntityView(const EntityIterator& first, const EntityIterator& last)
: firstItr(first), lastItr(last)
{
if (firstItr.get() == nullptr || (firstItr.get()->isPendingDestroy() && !firstItr.includePendingDestroy()))
{
++firstItr;
}
}
const EntityIterator& begin() const
{
return firstItr;
}
const EntityIterator& end() const
{
return lastItr;
}
private:
EntityIterator firstItr;
EntityIterator lastItr;
};
template<typename T>
struct ComponentContainer : public BaseComponentContainer
{
ComponentContainer() {}
ComponentContainer(const T& data) : data(data) {}
T data;
protected:
virtual void destroy(World* world)
{
using ComponentAllocator = std::allocator_traits<World::EntityAllocator>::template rebind_alloc<ComponentContainer<T>>;
ComponentAllocator alloc(world->getPrimaryAllocator());
std::allocator_traits<ComponentAllocator>::destroy(alloc, this);
std::allocator_traits<ComponentAllocator>::deallocate(alloc, this, 1);
}
virtual void removed(Entity* ent)
{
auto handle = ComponentHandle<T>(&data);
ent->getWorld()->emit<Events::OnComponentRemoved<T>>({ ent, handle });
}
};
}
inline World::~World()
{
for (auto* system : systems)
{
system->unconfigure(this);
}
for (auto* ent : entities)
{
if (!ent->isPendingDestroy())
{
ent->bPendingDestroy = true;
emit<Events::OnEntityDestroyed>({ ent });
}
std::allocator_traits<EntityAllocator>::destroy(entAlloc, ent);
std::allocator_traits<EntityAllocator>::deallocate(entAlloc, ent, 1);
}
for (auto* system : systems)
{
std::allocator_traits<SystemAllocator>::destroy(systemAlloc, system);
std::allocator_traits<SystemAllocator>::deallocate(systemAlloc, system, 1);
}
}
inline void World::destroy(Entity* ent, bool immediate)
{
if (ent == nullptr)
return;
if (ent->isPendingDestroy())
{
if (immediate)
{
entities.erase(std::remove(entities.begin(), entities.end(), ent), entities.end());
std::allocator_traits<EntityAllocator>::destroy(entAlloc, ent);
std::allocator_traits<EntityAllocator>::deallocate(entAlloc, ent, 1);
}
return;
}
ent->bPendingDestroy = true;
emit<Events::OnEntityDestroyed>({ ent });
if (immediate)
{
entities.erase(std::remove(entities.begin(), entities.end(), ent), entities.end());
std::allocator_traits<EntityAllocator>::destroy(entAlloc, ent);
std::allocator_traits<EntityAllocator>::deallocate(entAlloc, ent, 1);
}
}
inline bool World::cleanup()
{
size_t count = 0;
entities.erase(std::remove_if(entities.begin(), entities.end(), [&, this](Entity* ent) {