-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmonkeroecs.hh
2510 lines (2220 loc) · 74.2 KB
/
monkeroecs.hh
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
/*
The MIT License (MIT)
Copyright (c) 2020, 2021, 2022 Julius Ikkala
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.
*/
/** \mainpage MonkeroECS
*
* \section intro_sec Introduction
*
* MonkeroECS is a fairly small, header-only Entity Component System rescued
* from a game engine. It aims for simple and terse usage and also contains an
* event system.
*
* MonkeroECS is written in C++17 and the only dependency is the standard
* library. Note that the code isn't pretty and has to do some pretty gnarly
* trickery to make the usable as terse as it is.
*
* While performance is one of the goals of this ECS, it was more written with
* flexibility in mind. Particularly, random access and multi-component
* iteration should be quite fast. All components have stable storage, that is,
* they will not get moved around after their creation. Therefore, the ECS also
* works with components that are not copyable or movable and pointers to them
* will not be invalidated until the component is removed.
*
* Adding the ECS to your project is simple; just copy the monkeroecs.hh yo
* your codebase and include it!
*
* The name is a reference to the game the ECS was originally created for, but
* it was unfortunately never finished or released in any form despite the
* engine being in a finished state.
*/
#ifndef MONKERO_ECS_HH
#define MONKERO_ECS_HH
//#define MONKERO_CONTAINER_DEALLOCATE_BUCKETS
//#define MONKERO_CONTAINER_DEBUG_UTILS
#include <cstdint>
#include <map>
#include <functional>
#include <memory>
#include <vector>
#include <limits>
#include <utility>
#include <type_traits>
#include <algorithm>
#include <tuple>
#include <map>
#include <cstring>
#ifdef MONKERO_CONTAINER_DEBUG_UTILS
#include <iostream>
#include <bitset>
#endif
// Thanks, MSVC -.-
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
/** This namespace contains all of MonkeroECS. */
namespace monkero
{
/** The entity type, it's just an ID.
* An entity alone will not take up memory in the ECS, only once components are
* added does the entity truly use memory. You can change this to uint64_t if
* you truly need over 4 billion entities and have tons of memory.
*/
using entity = std::uint32_t;
// You are not allowed to use this entity ID.
inline constexpr entity INVALID_ENTITY = 0;
class scene;
/** A built-in event emitted when a component is added to the ECS. */
template<typename Component>
struct add_component
{
entity id; /**< The entity that got the component */
Component* data; /**< A pointer to the component */
};
/** A built-in event emitted when a component is removed from the ECS.
* The destructor of class scene will emit remove_component events for all
* components still left at that point.
*/
template<typename Component>
struct remove_component
{
entity id; /**< The entity that lost the component */
Component* data; /**< A pointer to the component (it's not destroyed quite yet) */
};
/** This class is used to receive events of the specified type(s).
* Once it is destructed, no events will be delivered to the associated
* callback function anymore.
* \note Due to the callback nature, event subscriptions are immovable.
* \see receiver
*/
class event_subscription
{
friend class scene;
public:
inline event_subscription(scene* ctx = nullptr, std::size_t subscription_id = 0);
inline explicit event_subscription(event_subscription&& other);
event_subscription(const event_subscription& other) = delete;
inline ~event_subscription();
event_subscription& operator=(event_subscription&& other) = delete;
event_subscription& operator=(const event_subscription& other) = delete;
private:
scene* ctx;
std::size_t subscription_id;
};
// Provides event receiving facilities for one type alone. Derive
// from class receiver instead in your own code.
template<typename EventType>
class event_receiver
{
public:
virtual ~event_receiver() = default;
/** Receivers must implement this for each received event type.
* It's called by emitters when an event of EventType is emitted.
* \param ctx The ECS this receiver is part of.
* \param event The event that occurred.
*/
virtual void handle(scene& ctx, const EventType& event) = 0;
};
/** Deriving from this class allows systems to receive events of the specified
* type(s). Just give a list of the desired event types in the template
* parameters and the system will start receiving them from all other systems
* automatically.
*/
template<typename... ReceiveEvents>
class receiver: public event_receiver<ReceiveEvents>...
{
friend class scene;
private:
event_subscription sub;
};
/** Specializing this class for your component type and implementing the given
* functions allows for accelerated entity searching based on any parameter you
* want to define. The default does not define any searching operations.
*/
template<typename Component>
class search_index
{
public:
// It's up to you how you want to do this searching. You should return
// INVALID_ENTITY if there was no entity matching the search parameters.
// You can also have multiple find() overloads for the same component type.
// entity find(some parameters here) const;
/** Called automatically when an entity of this component type is added.
* \param id ID of the entity whose component is being added.
* \param data the component data itself.
*/
void add_entity(entity id, const Component& data);
/** Called automatically when an entity of this component type is removed.
* \param id ID of the entity whose component is being removed.
* \param data the component data itself.
*/
void remove_entity(entity id, const Component& data);
/** Manual full search index refresh.
* Never called automatically, the ECS has a refresh_search_index() function
* that the user must call that then calls this.
* \param e the ECS context.
*/
void update(scene& e);
// Don't copy this one though, or else you won't get some add_entity or
// remove_entity calls.
using empty_default_impl = void;
};
template<typename T, typename=void>
struct has_bucket_exp_hint: std::false_type { };
template<typename T>
struct has_bucket_exp_hint<
T,
decltype((void)
T::bucket_exp_hint, void()
)
> : std::is_integral<decltype(T::bucket_exp_hint)> { };
/** Provides bucket size choice for the component container.
* To change the number of entries in a bucket for your component type, you have
* two options:
* A (preferred when you can modify the component type):
* Add a `static constexpr std::uint32_t bucket_exp_hint = N;`
* B (needed when you cannot modify the component type):
* Specialize component_bucket_exp_hint for your type and provide a
* `static constexpr std::uint32_t value = N;`
* Where the bucket size will then be 2**N.
*/
template<typename T>
struct component_bucket_exp_hint
{
static constexpr std::uint32_t value = []{
if constexpr (has_bucket_exp_hint<T>::value)
{
return T::bucket_exp_hint;
}
else
{
uint32_t i = 6;
// Aim for 65kb buckets
while((std::max(sizeof(T), std::uint64_t(4))<<i) < std::uint64_t(65536))
++i;
return i;
}
}();
};
class component_container_base
{
public:
virtual ~component_container_base() = default;
inline virtual void start_batch() = 0;
inline virtual void finish_batch() = 0;
inline virtual void erase(entity id) = 0;
inline virtual void clear() = 0;
inline virtual std::size_t size() const = 0;
inline virtual void update_search_index() = 0;
inline virtual void list_entities(
std::map<entity, entity>& translation_table
) = 0;
inline virtual void concat(
scene& target,
const std::map<entity, entity>& translation_table
) = 0;
inline virtual void copy(
scene& target,
entity result_id,
entity original_id
) = 0;
};
struct component_container_entity_advancer
{
public:
inline void advance();
std::uint32_t bucket_mask;
std::uint32_t bucket_exp;
entity*** bucket_jump_table;
std::uint32_t current_bucket;
entity current_entity;
entity* current_jump_table;
};
template<typename T>
class component_container: public component_container_base
{
public:
using bitmask_type = std::uint64_t;
static constexpr uint32_t bitmask_bits = 64;
static constexpr uint32_t bitmask_shift = 6; // 64 = 2**6
static constexpr uint32_t bitmask_mask = 0x3F;
static constexpr uint32_t initial_bucket_count = 16u;
static constexpr bool tag_component = std::is_empty_v<T>;
static constexpr std::uint32_t bucket_exp =
component_bucket_exp_hint<T>::value;
static constexpr std::uint32_t bucket_mask = (1u<<bucket_exp)-1;
static constexpr std::uint32_t bucket_bitmask_units =
std::max(1u, (1u<<bucket_exp)>>bitmask_shift);
component_container(scene& ctx);
component_container(component_container&& other) = delete;
component_container(const component_container& other) = delete;
~component_container();
T* operator[](entity e);
const T* operator[](entity e) const;
void insert(entity id, T&& value);
template<typename... Args>
void emplace(entity id, Args&&... value);
void erase(entity id) override;
void clear() override;
bool contains(entity id) const;
void start_batch() override;
void finish_batch() override;
class iterator
{
friend class component_container<T>;
public:
using component_type = T;
iterator() = delete;
iterator(const iterator& other) = default;
iterator& operator++();
iterator operator++(int);
std::pair<entity, T*> operator*();
std::pair<entity, const T*> operator*() const;
bool operator==(const iterator& other) const;
bool operator!=(const iterator& other) const;
bool try_advance(entity id);
operator bool() const;
entity get_id() const;
component_container<T>* get_container() const;
component_container_entity_advancer get_advancer();
private:
iterator(component_container& from, entity e);
component_container* from;
entity current_entity;
std::uint32_t current_bucket;
entity* current_jump_table;
T* current_components;
};
iterator begin();
iterator end();
std::size_t size() const override;
void update_search_index() override;
void list_entities(
std::map<entity, entity>& translation_table
) override;
void concat(
scene& target,
const std::map<entity, entity>& translation_table
) override;
void copy(
scene& target,
entity result_id,
entity original_id
) override;
template<typename... Args>
entity find_entity(Args&&... args) const;
#ifdef MONKERO_CONTAINER_DEBUG_UTILS
bool test_invariant() const;
void print_bitmask() const;
void print_jump_table() const;
#endif
private:
T* get_unsafe(entity e);
void destroy();
void jump_table_insert(entity id);
void jump_table_erase(entity id);
std::size_t get_top_bitmask_size() const;
bool bitmask_empty(std::uint32_t bucket_index) const;
void bitmask_insert(entity id);
// Returns a hint to whether the whole bucket should be removed or not.
bool bitmask_erase(entity id);
template<typename... Args>
void bucket_insert(entity id, Args&&... args);
void bucket_erase(entity id, bool signal);
void bucket_self_erase(std::uint32_t bucket_index);
void try_jump_table_bucket_erase(std::uint32_t bucket_index);
void ensure_bucket_space(entity id);
void ensure_bitmask(std::uint32_t bucket_index);
void ensure_jump_table(std::uint32_t bucket_index);
bool batch_change(entity id);
entity find_previous_entity(entity id);
void signal_add(entity id, T* data);
void signal_remove(entity id, T* data);
static unsigned bitscan_reverse(std::uint64_t mt);
static bool find_bitmask_top(
bitmask_type* bitmask,
std::uint32_t count,
std::uint32_t& top_index
);
static bool find_bitmask_previous_index(
bitmask_type* bitmask,
std::uint32_t index,
std::uint32_t& prev_index
);
struct alignas(T) t_mimicker { std::uint8_t pad[sizeof(T)]; };
// Bucket data
std::uint32_t entity_count;
std::uint32_t bucket_count;
bitmask_type** bucket_bitmask;
bitmask_type* top_bitmask;
entity** bucket_jump_table;
T** bucket_components;
// Batching data
bool batching;
std::uint32_t batch_checklist_size;
std::uint32_t batch_checklist_capacity;
entity* batch_checklist;
bitmask_type** bucket_batch_bitmask;
// Search index (kinda separate, but handy to keep around here.)
scene* ctx;
search_index<T> search;
};
/** The primary class of the ECS.
* Entities are created by it, components are attached throught it and events
* are routed through it.
*/
class scene
{
friend class event_subscription;
public:
/** The constructor. */
inline scene();
/** The destructor.
* It ensures that all remove_component events are sent for the remainder
* of the components before event handlers are cleared.
*/
inline ~scene();
/** Calls a given function for all suitable entities.
* The parameters of the function mandate how it is called. Batching is
* enabled automatically so that removing and adding entities and components
* during iteration is safe.
* \param f The iteration callback.
* The first parameter of \p f must be #entity (the entity that the
* iteration concerns.) After that, further parameters must be either
* references or pointers to components. The function is only called when
* all referenced components are present for the entity; pointer
* parameters are optional and can be null if the component is not
* present.
*/
template<typename F>
inline void foreach(F&& f);
/** Same as foreach(), just syntactic sugar.
* \see foreach()
*/
template<typename F>
inline void operator()(F&& f);
/** Adds an entity without components.
* \return The new entity ID.
*/
inline entity add();
/** Adds an entity with initial components.
* Takes a list of component instances. Note that they must be moved in, so
* you should create them during the call or use std::move().
* \param components All components that should be included.
* \return The new entity ID.
*/
template<typename... Components>
entity add(Components&&... components);
/** Adds a component to an existing entity, building it in-place.
* \param id The entity that components are added to.
* \param args Parameters for the constructor of the Component type.
*/
template<typename Component, typename... Args>
void emplace(entity id, Args&&... args);
/** Adds components to an existing entity.
* Takes a list of component instances. Note that they must be moved in, so
* you should create them during the call or use std::move().
* \param id The entity that components are added to.
* \param components All components that should be attached.
*/
template<typename... Components>
void attach(entity id, Components&&... components);
/** Removes all components related to the entity.
* Unlike the component-specific remove() call, this also releases the ID to
* be reused by another entity.
* \param id The entity whose components to remove.
*/
inline void remove(entity id);
/** Removes a component of an entity.
* \tparam Component The type of component to remove from the entity.
* \param id The entity whose component to remove.
*/
template<typename Component>
void remove(entity id);
/** Removes all components of all entities.
* It also resets the entity counter, so this truly invalidates all
* previous entities!
*/
inline void clear_entities();
/** Copies entities from another ECS to this one.
* \param other the other ECS whose entities and components to copy to this.
* \param translation_table if not nullptr, will be filled in with the
* entity ID correspondence from the old ECS to the new.
* \warn event handlers are not copied, only entities and components. Entity
* IDs will also change.
* \warn You should finish batching on the other ECS before calling this.
*/
inline void concat(
scene& other,
std::map<entity, entity>* translation_table = nullptr
);
/** Copies one entity from another ECS to this one.
* \param other the other ECS whose entity to copy to this.
* \param other_id the ID of the entity to copy in the other ECS.
* \return entity ID of the created entity.
* \warn You should finish batching on the other ECS before calling this.
*/
inline entity copy(scene& other, entity other_id);
/** Starts batching behaviour for add/remove.
* Batching allows you to safely add and remove components while you iterate
* over them, but comes with no performance benefit.
*/
inline void start_batch();
/** Finishes batching behaviour for add/remove and applies the changes.
*/
inline void finish_batch();
/** Counts instances of entities with a specified component.
* \tparam Component the component type to count instances of.
* \return The number of entities with the specified component.
*/
template<typename Component>
size_t count() const;
/** Checks if an entity has the given component.
* \tparam Component the component type to check.
* \param id The id of the entity whose component is checked.
* \return true if the entity has the given component, false otherwise.
*/
template<typename Component>
bool has(entity id) const;
/** Returns the desired component of an entity.
* Const version.
* \tparam Component the component type to get.
* \param id The id of the entity whose component to fetch.
* \return A pointer to the component if present, null otherwise.
*/
template<typename Component>
const Component* get(entity id) const;
/** Returns the desired component of an entity.
* \tparam Component the component type to get.
* \param id The id of the entity whose component to fetch.
* \return A pointer to the component if present, null otherwise.
*/
template<typename Component>
Component* get(entity id);
/** Uses search_index<Component> to find the desired component.
* \tparam Component the component type to search for.
* \tparam Args search argument types.
* \param args arguments for search_index<Component>::find().
* \return A pointer to the component if present, null otherwise.
* \see update_search_index()
*/
template<typename Component, typename... Args>
Component* find_component(Args&&... args);
/** Uses search_index<Component> to find the desired component.
* Const version.
* \tparam Component the component type to search for.
* \tparam Args search argument types.
* \param args arguments for search_index<Component>::find().
* \return A pointer to the component if present, null otherwise.
* \see update_search_index()
*/
template<typename Component, typename... Args>
const Component* find_component(Args&&... args) const;
/** Uses search_index<Component> to find the desired entity.
* \tparam Component the component type to search for.
* \tparam Args search argument types.
* \param args arguments for search_index<Component>::find().
* \return An entity id if found, INVALID_ENTITY otherwise.
* \see update_search_index()
*/
template<typename Component, typename... Args>
entity find(Args&&... args) const;
/** Calls search_index<Component>::update() for the component type.
* \tparam Component the component type whose search index to update.
*/
template<typename Component>
void update_search_index();
/** Updates search indices of all component types.
*/
inline void update_search_indices();
/** Calls all handlers of the given event type.
* \tparam EventType the type of the event to emit.
* \param event The event to emit.
*/
template<typename EventType>
void emit(const EventType& event);
/** Returns how many handlers are present for the given event type.
* \tparam EventType the type of the event to check.
* \return the number of event handlers for this EventType.
*/
template<typename EventType>
size_t get_handler_count() const;
/** Adds event handler(s) to the ECS.
* \tparam F Callable types, with signature void(scene& ctx, const EventType& e).
* \param callbacks The event handler callbacks.
* \return ID of the "subscription"
* \see subscribe() for RAII handler lifetime.
* \see bind_event_handler() for binding to member functions.
*/
template<typename... F>
size_t add_event_handler(F&&... callbacks);
/** Adds member functions of an object as event handler(s) to the ECS.
* \tparam T Type of the object whose members are being bound.
* \tparam F Member function types, with signature
* void(scene& ctx, const EventType& e).
* \param userdata The class to bind to each callback.
* \param callbacks The event handler callbacks.
* \return ID of the "subscription"
* \see subscribe() for RAII handler lifetime.
* \see add_event_handler() for free-standing functions.
*/
template<class T, typename... F>
size_t bind_event_handler(T* userdata, F&&... callbacks);
/** Removes event handler(s) from the ECS
* \param id ID of the "subscription"
* \see subscribe() for RAII handler lifetime.
*/
inline void remove_event_handler(size_t id);
/** Adds event handlers for a receiver object.
* \tparam EventTypes Event types that are being received.
* \param r The receiver to add handlers for.
*/
template<typename... EventTypes>
void add_receiver(receiver<EventTypes...>& r);
/** Adds event handlers with a subscription object that tracks lifetime.
* \tparam F Callable types, with signature void(scene& ctx, const EventType& e).
* \param callbacks The event handler callbacks.
* \return The subscription object that removes the event handler on its
* destruction.
*/
template<typename... F>
event_subscription subscribe(F&&... callbacks);
private:
template<bool pass_id, typename... Components>
struct foreach_impl
{
template<typename F>
static void foreach(scene& ctx, F&& f);
template<typename Component>
struct iterator_wrapper
{
static constexpr bool required = true;
typename component_container<std::decay_t<std::remove_pointer_t<std::decay_t<Component>>>>::iterator iter;
};
template<typename Component>
static inline auto make_iterator(scene& ctx)
{
return iterator_wrapper<Component>{
ctx.get_container<std::decay_t<std::remove_pointer_t<std::decay_t<Component>>>>().begin()
};
}
template<typename Component>
struct converter
{
template<typename T>
static inline T& convert(T*);
};
template<typename F>
static void call(
F&& f,
entity id,
std::decay_t<std::remove_pointer_t<std::decay_t<Components>>>*... args
);
};
template<typename... Components>
foreach_impl<true, Components...>
foreach_redirector(const std::function<void(entity id, Components...)>&);
template<typename... Components>
foreach_impl<false, Components...>
foreach_redirector(const std::function<void(Components...)>&);
template<typename T>
T event_handler_type_detector(const std::function<void(scene&, const T&)>&);
template<typename T>
T event_handler_type_detector(void (*)(scene&, const T&));
template<typename T, typename U>
U event_handler_type_detector(void (T::*)(scene&, const U&));
template<typename Component>
void try_attach_dependencies(entity id);
template<typename Component>
component_container<Component>& get_container() const;
template<typename Component>
static size_t get_component_type_key();
inline static size_t component_type_key_counter = 0;
template<typename Event>
static size_t get_event_type_key();
inline static size_t event_type_key_counter = 0;
template<typename F>
void internal_add_handler(size_t id, F&& f);
template<class C, typename F>
void internal_bind_handler(size_t id, C* c, F&& f);
entity id_counter;
std::vector<entity> reusable_ids;
std::vector<entity> post_batch_reusable_ids;
size_t subscriber_counter;
int defer_batch;
mutable std::vector<std::unique_ptr<component_container_base>> components;
struct event_handler
{
size_t subscription_id;
// TODO: Once we have std::function_ref, see if this can be optimized.
// The main difficulty we have to handle are pointers to member
// functions, which have been made unnecessarily unusable in C++.
std::function<void(scene& ctx, const void* event)> callback;
};
std::vector<std::vector<event_handler>> event_handlers;
};
/** Components may derive from this class to require other components.
* The other components are added to the entity along with this one if they
* are not yet present.
*/
template<typename... DependencyComponents>
class dependency_components
{
friend class scene;
public:
static void ensure_dependency_components_exist(entity id, scene& ctx);
};
//==============================================================================
// Implementation
//==============================================================================
event_subscription::event_subscription(scene* ctx, std::size_t subscription_id)
: ctx(ctx), subscription_id(subscription_id)
{
}
event_subscription::event_subscription(event_subscription&& other)
: ctx(other.ctx), subscription_id(other.subscription_id)
{
other.ctx = nullptr;
}
event_subscription::~event_subscription()
{
if(ctx)
ctx->remove_event_handler(subscription_id);
}
template<typename T>
constexpr bool search_index_is_empty_default(
int,
typename T::empty_default_impl const * = nullptr
){ return true; }
template<typename T>
constexpr bool search_index_is_empty_default(long)
{ return false; }
template<typename T>
constexpr bool search_index_is_empty_default()
{ return search_index_is_empty_default<T>(0); }
template<typename Component>
void search_index<Component>::add_entity(entity, const Component&) {}
template<typename Component>
void search_index<Component>::update(scene&) {}
template<typename Component>
void search_index<Component>::remove_entity(entity, const Component&) {}
template<typename T>
component_container<T>::component_container(scene& ctx)
: entity_count(0), bucket_count(0),
bucket_bitmask(nullptr), top_bitmask(nullptr),
bucket_jump_table(nullptr), bucket_components(nullptr), batching(false),
batch_checklist_size(0), batch_checklist_capacity(0),
batch_checklist(nullptr), bucket_batch_bitmask(nullptr), ctx(&ctx)
{
}
template<typename T>
component_container<T>::~component_container()
{
destroy();
}
template<typename T>
T* component_container<T>::operator[](entity e)
{
if(!contains(e)) return nullptr;
return get_unsafe(e);
}
template<typename T>
const T* component_container<T>::operator[](entity e) const
{
return const_cast<component_container<T>*>(this)->operator[](e);
}
template<typename T>
void component_container<T>::insert(entity id, T&& value)
{
emplace(id, std::move(value));
}
template<typename T>
template<typename... Args>
void component_container<T>::emplace(entity id, Args&&... args)
{
if(id == INVALID_ENTITY)
return;
ensure_bucket_space(id);
if(contains(id))
{ // If we just replace something that exists, life is easy.
bucket_erase(id, true);
bucket_insert(id, std::forward<Args>(args)...);
}
else if(batching)
{
entity_count++;
if(!batch_change(id))
{
// If there was already a change, that means that there was an
// existing batched erase. That means that we can replace an
// existing object instead.
bucket_erase(id, true);
}
bucket_insert(id, std::forward<Args>(args)...);
}
else
{
entity_count++;
bitmask_insert(id);
jump_table_insert(id);
bucket_insert(id, std::forward<Args>(args)...);
}
}
template<typename T>
void component_container<T>::erase(entity id)
{
if(!contains(id))
return;
entity_count--;
if(batching)
{
if(!batch_change(id))
{
// If there was already a change, that means that there was an
// existing batched add. Because it's not being iterated, we can
// just destroy it here.
bucket_erase(id, true);
}
else signal_remove(id, get_unsafe(id));
}
else
{
bool erase_bucket = bitmask_erase(id);
jump_table_erase(id);
bucket_erase(id, true);
if(erase_bucket)
{
bucket_self_erase(id >> bucket_exp);
try_jump_table_bucket_erase(id >> bucket_exp);
}
}
}
template<typename T>
void component_container<T>::clear()
{
if(batching)
{ // Uh oh, this is super suboptimal :/ pls don't clear while iterating.
for(auto it = begin(); it != end(); ++it)
{
erase((*it).first);
}
}
else
{
// Clear top bitmask
std::uint32_t top_bitmask_count = get_top_bitmask_size();
for(std::uint32_t i = 0; i< top_bitmask_count; ++i)
top_bitmask[i] = 0;
// Destroy all existing objects
if(
ctx->get_handler_count<remove_component<T>>() ||
!search_index_is_empty_default<decltype(search)>()
){
for(auto it = begin(); it != end(); ++it)
{
auto pair = *it;
signal_remove(pair.first, pair.second);
pair.second->~T();
}
}
else
{
for(auto it = begin(); it != end(); ++it)
(*it).second->~T();
}
// Release all bucket pointers
for(std::uint32_t i = 0; i < bucket_count; ++i)
{
if(bucket_bitmask[i])
{
delete [] bucket_bitmask[i];
bucket_bitmask[i] = nullptr;
}
if(bucket_batch_bitmask[i])
{
delete [] bucket_batch_bitmask[i];
bucket_batch_bitmask[i] = nullptr;
}
if(bucket_jump_table[i])
{
delete [] bucket_jump_table[i];
bucket_jump_table[i] = nullptr;
}
if constexpr(!tag_component)
{
if(bucket_components[i])
{
delete [] reinterpret_cast<t_mimicker*>(bucket_components[i]);
bucket_components[i] = nullptr;
}
}
}