GREM 3.12.0
Game/Rendering Engine Modules for C++
Loading...
Searching...
No Matches
EntityRegistry.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Ivar Härnqvist
2// SPDX-License-Identifier: MIT
3
4#ifndef GREM_EXECUTION_ENTITY_REGISTRY_HPP
5#define GREM_EXECUTION_ENTITY_REGISTRY_HPP
6
8
23#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
25#endif
26
27#include <algorithm> // std::fill, std::copy_n, std::min
28#include <compare> // std::strong_ordering
29#include <cstddef> // std::size_t
30#include <functional> // std::hash
31#include <iterator> // std::forward_iterator_tag, std::random_access_iterator_tag
32#include <memory> // std::allocator, std::uninitialized_..., std::destroy_n, std::destroy_at, std::construct_at
33#include <stdexcept> // std::invalid_argument, std::out_of_range, std::length_error, std::logic_error
34#include <type_traits> // std::is_const_v, std::is_empty_v, std::remove_..._t, std::conditional_t, std::true_type
35#include <typeindex> // std::type_index
36#include <typeinfo> // IWYU pragma: keep // typeid
37#include <utility> // std::move, std::forward, std::exchange, std::...index_sequence, std::in_place_type...
38
39namespace grem::execution {
40
41template <typename... KnownComponents>
42class EntityRegistry; // Forward declaration.
43
44template <typename... ComponentsAndExclusions>
45class Entities; // Forward declaration.
46
48// Mark Entities as an entity range type.
49template <typename... ComponentsAndExclusions>
50struct is_entity_range<Entities<ComponentsAndExclusions...>> : std::true_type {};
51
52// Define how to extract the components and exclusions of an Entities type.
53template <typename... ComponentsAndExclusions>
54struct entity_range_components_and_exclusions<Entities<ComponentsAndExclusions...>> {
55 using type = meta::TypeList<ComponentsAndExclusions...>;
56};
58
59template <typename Component>
60class ComponentPool; // Forward declaration.
61
63// Mark ComponentPool as a component pool type.
64template <typename Component>
65struct is_component_pool<ComponentPool<Component>> : std::true_type {};
67
71class EntityID {
72public:
73 using Identifier = uint64_t;
74 using Index = uint32_t;
75 using Generation = uint16_t;
76 using Flags = uint16_t;
77
79 static constexpr Index MAX_INDEX = Limits<Index>::MAX - 1;
81 static constexpr Flags ALL_FLAGS = Limits<Flags>::MAX;
82
86 GREM_ALWAYS_INLINE constexpr EntityID() noexcept = default;
87
97 GREM_ALWAYS_INLINE constexpr EntityID(Index index, Generation generation, Flags flags)
98 : value((uint64_t{flags} << 48) | (uint64_t{generation} << 32) | uint64_t{index}) {}
99
106 GREM_ALWAYS_INLINE constexpr explicit operator bool() const noexcept {
107 return *this != EntityID{};
108 }
109
116 [[nodiscard]] GREM_ALWAYS_INLINE constexpr Identifier getIdentifier() const noexcept {
117 return value;
118 }
119
125 [[nodiscard]] GREM_ALWAYS_INLINE constexpr Index getIndex() const noexcept {
126 return static_cast<Index>(value & uint64_t{Limits<Index>::MAX});
127 }
128
134 [[nodiscard]] GREM_ALWAYS_INLINE constexpr Generation getGeneration() const noexcept {
135 return static_cast<Generation>((value >> 32) & uint64_t{Limits<Generation>::MAX});
136 }
137
143 [[nodiscard]] GREM_ALWAYS_INLINE constexpr Flags getFlags() const noexcept {
144 return static_cast<Flags>((value >> 48) & uint64_t{Limits<Flags>::MAX});
145 }
146
154 [[nodiscard]] GREM_ALWAYS_INLINE constexpr bool operator==(const EntityID& other) const noexcept = default;
155
163 [[nodiscard]] GREM_ALWAYS_INLINE constexpr std::strong_ordering operator<=>(const EntityID& other) const noexcept = default;
164
165private:
166 uint64_t value = Limits<uint64_t>::MAX;
167};
168
169namespace detail {
170
171struct EntitySlot {
172 struct Active {
173 EntityID::Index idIndex;
174 EntityID::Flags flags;
175 };
176
177 struct Inactive {
178 EntityID::Index previousAvailableSlotIndex;
179 EntityID::Index nextAvailableSlotIndex;
180 };
181
182 EntityID::Generation generation;
183 union {
184 Active active;
185 Inactive inactive;
186 };
187};
188
189template <typename ComponentOrExclusion>
190struct entities_extract_components {
191 static_assert(component<ComponentOrExclusion>,
192 "The template arguments to grem::execution::Entities may only contain valid component types and/or exclusions of valid component types. See the definition of the "
193 "grem::execution::component concept for what constitutes a valid component type.");
194};
195
196template <component Component>
197struct entities_extract_components<Component> {
198 using MutableComponents = meta::TypeList<Component>;
199 using ImmutableComponents = meta::TypeList<>;
200 using IncludedComponents = meta::TypeList<Component>;
201 using ExcludedComponents = meta::TypeList<>;
202};
203
204template <component Component>
205struct entities_extract_components<const Component> {
206 using MutableComponents = meta::TypeList<>;
207 using ImmutableComponents = meta::TypeList<Component>;
208 using IncludedComponents = meta::TypeList<const Component>;
209 using ExcludedComponents = meta::TypeList<>;
210};
211
212template <component Component>
213struct entities_extract_components<Exclude<Component>> {
214 using MutableComponents = meta::TypeList<>;
215 using ImmutableComponents = meta::TypeList<>;
216 using IncludedComponents = meta::TypeList<>;
217 using ExcludedComponents = meta::TypeList<Component>;
218};
219
220template <typename T>
221concept empty_component = std::is_empty_v<std::remove_cv_t<T>>;
222
223template <empty_component Component>
224inline constinit Component DUMMY_COMPONENT{};
225
226template <typename... Components>
227inline constexpr size_t NON_EMPTY_COMPONENT_COUNT = (static_cast<size_t>(!empty_component<Components>) + ... + 0);
228
229template <typename... Components>
230static constexpr auto NON_EMPTY_COMPONENT_INDEX_MAP = [] {
231 Array<size_t, sizeof...(Components)> result{};
232 [&]<size_t... Indices>(std::index_sequence<Indices...>) {
233 size_t i = 0;
234 ((result[Indices] = (empty_component<Components>) ? size_t{} : i++), ...);
235 }(std::make_index_sequence<sizeof...(Components)>{});
236 return result;
237}();
238
239template <typename FirstComponent, typename... OtherComponents>
240struct first_non_empty_component : first_non_empty_component<OtherComponents...> {};
241
242template <typename FirstComponent>
243struct first_non_empty_component<FirstComponent> {
244 using type = FirstComponent;
245};
246
247template <typename FirstComponent, typename... OtherComponents>
248requires(!empty_component<FirstComponent>) struct first_non_empty_component<FirstComponent, OtherComponents...> {
249 using type = FirstComponent;
250};
251
252template <typename List>
253struct non_empty_component_count_of_type_list;
254
255template <typename... Ts>
256struct non_empty_component_count_of_type_list<meta::TypeList<Ts...>> : std::integral_constant<size_t, NON_EMPTY_COMPONENT_COUNT<Ts...>> {};
257
258template <typename List>
259struct first_non_empty_component_of_type_list;
260
261template <typename... Ts>
262struct first_non_empty_component_of_type_list<meta::TypeList<Ts...>> : first_non_empty_component<Ts...> {};
263
264template <typename... ComponentsAndExclusions>
265concept entities_is_single_component =
266 (meta::type_list_size_v<typename detail::entities_extract_components<ComponentsAndExclusions>::IncludedComponents> + ...) == 1 &&
267 (meta::type_list_empty_v<typename detail::entities_extract_components<ComponentsAndExclusions>::ExcludedComponents> && ...);
268
269struct EmptyComponentPointer {};
270
271#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
272struct IteratorValidity {
273 SharedPointer<Atomic<size_t>> validGeneration{};
274 size_t iteratorGeneration = Limits<size_t>::MAX;
275
276 constexpr IteratorValidity() noexcept = default;
277
278 IteratorValidity(SharedPointer<Atomic<size_t>> validGeneration) noexcept
279 : validGeneration(std::move(validGeneration)) {
280 if (this->validGeneration) {
281 iteratorGeneration = this->validGeneration->load();
282 }
283 }
284
285 [[nodiscard]] bool operator==(const IteratorValidity&) const noexcept = default;
286
287 void assertValid() const {
288 [[maybe_unused]] const bool iteratorValidity = validGeneration && iteratorGeneration == validGeneration->load();
289 GREM_ASSERT(iteratorValidity && R"(
290
291Error: Detected use of invalidated iterator to grem::execution::Entities.
292Note: Iterators may be invalidated by calls to createEntity(), destroyEntity(), clear(), addComponent(), etc. on the EntityRegistry.
293Tip: If entities need to be destroyed as a result of iteration, either use erase_if(), or build a list of EntityIDs while iterating and destroy them afterwards.
294Tip: If new entities need to be created as a result of iteration, build a list of configurations while iterating, and create entities from them afterwards.
295Tip: If only one entity needs to be created/destroyed as a result of searching the entities, create/destroy it and then immediately break from the loop.
296
297)");
298 }
299};
300#endif
301
302struct MultiComponentSentinel {};
303
304template <typename IncludedComponentsList, typename ExcludedComponentsList>
305class MultiComponentIterator;
306
307template <typename... IncludedComponents, typename... ExcludedComponents>
308class MultiComponentIterator<meta::TypeList<IncludedComponents...>, meta::TypeList<ExcludedComponents...>> {
309private:
310 static constexpr size_t EXCLUDED_COMPONENT_COUNT = sizeof...(ExcludedComponents);
311 static constexpr size_t INCLUDED_COMPONENT_COUNT = sizeof...(IncludedComponents);
312 static constexpr size_t NON_EMPTY_INCLUDED_COMPONENT_COUNT = NON_EMPTY_COMPONENT_COUNT<IncludedComponents...>;
313 static constexpr auto NON_EMPTY_INCLUDED_COMPONENT_INDEX_MAP = NON_EMPTY_COMPONENT_INDEX_MAP<IncludedComponents...>;
314
315public:
316 using difference_type = ptrdiff_t;
317 using value_type = Tuple<const EntityID, IncludedComponents...>;
318 using reference = Tuple<const EntityID, IncludedComponents&...>;
319 using iterator_category = std::forward_iterator_tag;
320
321 struct pointer {
322 reference ref;
323
324 [[nodiscard]] GREM_ALWAYS_INLINE constexpr reference* operator->() noexcept {
325 return &ref;
326 }
327 };
328
329 GREM_ALWAYS_INLINE MultiComponentIterator() noexcept = default;
330
331#if defined(NDEBUG) && !defined(GREM_USE_RELEASE_ASSERTIONS)
332 GREM_ALWAYS_INLINE constexpr MultiComponentIterator(const EntityID* candidateEntity, const EntityID* candidateEntitiesEnd,
333 const Array<const EntityID::Index*, EXCLUDED_COMPONENT_COUNT>& excludedIndexArrays, const Array<const EntityID::Index*, INCLUDED_COMPONENT_COUNT>& componentIndexArrays,
334 const Array<void*, NON_EMPTY_INCLUDED_COMPONENT_COUNT>& componentArrays, Span<const EntitySlot> slots) noexcept
335 : candidateEntity(candidateEntity)
336 , candidateEntitiesEnd(candidateEntitiesEnd)
337 , excludedIndexArrays(excludedIndexArrays)
338 , componentIndexArrays(componentIndexArrays)
339 , componentArrays(componentArrays)
340 , slots(slots) {
341 findNextEntity();
342 }
343#else
344 GREM_ALWAYS_INLINE constexpr MultiComponentIterator(const EntityID* candidateEntity, const EntityID* candidateEntitiesEnd,
345 const Array<const EntityID::Index*, EXCLUDED_COMPONENT_COUNT>& excludedIndexArrays, const Array<const EntityID::Index*, INCLUDED_COMPONENT_COUNT>& componentIndexArrays,
346 const Array<void*, NON_EMPTY_INCLUDED_COMPONENT_COUNT>& componentArrays, Span<const EntitySlot> slots,
347 const Array<IteratorValidity, EXCLUDED_COMPONENT_COUNT>& excludedIteratorValidity,
348 const Array<IteratorValidity, max(INCLUDED_COMPONENT_COUNT, size_t{1})>& componentIteratorValidity) noexcept
349 : candidateEntity(candidateEntity)
350 , candidateEntitiesEnd(candidateEntitiesEnd)
351 , excludedIndexArrays(excludedIndexArrays)
352 , componentIndexArrays(componentIndexArrays)
353 , componentArrays(componentArrays)
354 , slots(slots)
355 , excludedIteratorValidity(excludedIteratorValidity)
356 , componentIteratorValidity(componentIteratorValidity) {
357 findNextEntity();
358 }
359#endif
360
361 [[nodiscard]] GREM_ALWAYS_INLINE constexpr reference operator*() const {
362#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
363 assertValid();
364#endif
365 GREM_ASSERT(containsEntity(excludedIndexArrays, componentIndexArrays, slots, *candidateEntity));
366 return dereference(componentIndexArrays, componentArrays, *candidateEntity);
367 }
368
369 [[nodiscard]] GREM_ALWAYS_INLINE constexpr pointer operator->() const {
370 return pointer{**this};
371 }
372
373 GREM_ALWAYS_INLINE constexpr MultiComponentIterator& operator++() {
374#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
375 assertValid();
376#endif
377 ++candidateEntity;
378 findNextEntity();
379 return *this;
380 }
381
382 GREM_ALWAYS_INLINE constexpr MultiComponentIterator operator++(int) {
383 MultiComponentIterator old = *this;
384 ++*this;
385 return old;
386 }
387
388 [[nodiscard]] GREM_ALWAYS_INLINE constexpr bool operator==(const MultiComponentIterator& other) const {
389#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
390 GREM_ASSERT(excludedIteratorValidity == other.excludedIteratorValidity);
391 GREM_ASSERT(componentIteratorValidity == other.componentIteratorValidity);
392#endif
393 return candidateEntity == other.candidateEntity;
394 }
395
396 [[nodiscard]] GREM_ALWAYS_INLINE constexpr bool operator==(const MultiComponentSentinel&) const {
397 return candidateEntity == candidateEntitiesEnd;
398 }
399
400private:
401 template <typename... ComponentsAndExclusions>
402 friend class grem::execution::Entities;
403
404 template <typename Component, size_t I>
405 [[nodiscard]] GREM_ALWAYS_INLINE static Component& getComponentUnsafe(const Array<const EntityID::Index*, INCLUDED_COMPONENT_COUNT>& componentIndexArrays,
406 const Array<void*, NON_EMPTY_INCLUDED_COMPONENT_COUNT>& componentArrays, size_t slotIndex) {
407 if constexpr (empty_component<Component>) {
408 return DUMMY_COMPONENT<Component>;
409 } else {
410 return static_cast<Component*>(componentArrays[NON_EMPTY_INCLUDED_COMPONENT_INDEX_MAP[I]])[componentIndexArrays[I][slotIndex]];
411 }
412 }
413
414 [[nodiscard]] GREM_ALWAYS_INLINE static bool passesFilter(const Array<const EntityID::Index*, EXCLUDED_COMPONENT_COUNT>& excludedIndexArrays,
415 const Array<const EntityID::Index*, INCLUDED_COMPONENT_COUNT>& componentIndexArrays, EntityID id) {
416 const size_t slotIndex = id.getIndex();
417 const bool notExcluded = [&]<size_t... Indices>(std::index_sequence<Indices...>) -> bool {
418 return ((!excludedIndexArrays[Indices] || excludedIndexArrays[Indices][slotIndex] == EntityID::INVALID_INDEX) && ... && true);
419 }(std::make_index_sequence<EXCLUDED_COMPONENT_COUNT>{});
420 if (!notExcluded) {
421 return false;
422 }
423 const bool included = [&]<size_t... Indices>(std::index_sequence<Indices...>) -> bool {
424 return ((componentIndexArrays[Indices][slotIndex] != EntityID::INVALID_INDEX) && ... && true);
425 }(std::make_index_sequence<INCLUDED_COMPONENT_COUNT>{});
426 return included;
427 }
428
429 [[nodiscard]] GREM_ALWAYS_INLINE static bool containsEntity(const Array<const EntityID::Index*, EXCLUDED_COMPONENT_COUNT>& excludedIndexArrays,
430 const Array<const EntityID::Index*, INCLUDED_COMPONENT_COUNT>& componentIndexArrays, Span<const EntitySlot> slots, EntityID id) {
431 return id.getIndex() < slots.size() && (id.getGeneration() & 1) != 0 && slots[id.getIndex()].generation == id.getGeneration() &&
432 passesFilter(excludedIndexArrays, componentIndexArrays, id);
433 }
434
435 [[nodiscard]] GREM_ALWAYS_INLINE static reference dereference(const Array<const EntityID::Index*, INCLUDED_COMPONENT_COUNT>& componentIndexArrays,
436 const Array<void*, NON_EMPTY_INCLUDED_COMPONENT_COUNT>& componentArrays, EntityID id) {
437 return [&]<size_t... Indices>(std::index_sequence<Indices...>) -> reference {
438 const size_t slotIndex = id.getIndex();
439 return reference{id, getComponentUnsafe<IncludedComponents, Indices>(componentIndexArrays, componentArrays, slotIndex)...};
440 }(std::make_index_sequence<INCLUDED_COMPONENT_COUNT>{});
441 }
442
443 GREM_ALWAYS_INLINE void findNextEntity() {
444 while (candidateEntity != candidateEntitiesEnd && !passesFilter(excludedIndexArrays, componentIndexArrays, *candidateEntity)) {
445 ++candidateEntity;
446 }
447 }
448
449 const EntityID* candidateEntity;
450 const EntityID* candidateEntitiesEnd;
451 [[no_unique_address]] Array<const EntityID::Index*, EXCLUDED_COMPONENT_COUNT> excludedIndexArrays;
452 [[no_unique_address]] Array<const EntityID::Index*, INCLUDED_COMPONENT_COUNT> componentIndexArrays;
453 [[no_unique_address]] Array<void*, NON_EMPTY_INCLUDED_COMPONENT_COUNT> componentArrays;
455#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
456 Array<IteratorValidity, EXCLUDED_COMPONENT_COUNT> excludedIteratorValidity{};
457 Array<IteratorValidity, max(INCLUDED_COMPONENT_COUNT, size_t{1})> componentIteratorValidity{};
458
459 void assertValid() const {
460 for (size_t i = 0; i < EXCLUDED_COMPONENT_COUNT; ++i) {
461 if (excludedIndexArrays[i]) {
462 excludedIteratorValidity[i].assertValid();
463 }
464 }
465 for (const IteratorValidity& validity : componentIteratorValidity) {
466 validity.assertValid();
467 }
468 }
469#endif
470};
471
472struct SingleComponentSentinel {
473 const EntityID* entitiesEnd;
474};
475
476template <typename Component>
477class SingleComponentIterator {
478public:
479 using difference_type = ptrdiff_t;
480 using value_type = Tuple<const EntityID, Component>;
481 using reference = Tuple<const EntityID, Component&>;
482 using iterator_category = std::random_access_iterator_tag;
483
484 struct pointer {
485 reference ref;
486
487 [[nodiscard]] GREM_ALWAYS_INLINE constexpr reference* operator->() noexcept {
488 return &ref;
489 }
490 };
491
492 GREM_ALWAYS_INLINE SingleComponentIterator() noexcept = default;
493
494#if defined(NDEBUG) && !defined(GREM_USE_RELEASE_ASSERTIONS)
495 GREM_ALWAYS_INLINE constexpr SingleComponentIterator(const EntityID* entity, Component* component, const EntityID::Index* componentIndexArray, void* componentArray,
496 Span<const EntitySlot> slots) noexcept
497 : entity(entity)
498 , component(component)
499 , componentIndexArray(componentIndexArray)
500 , componentArray(componentArray)
501 , slots(slots) {}
502#else
503 GREM_ALWAYS_INLINE constexpr SingleComponentIterator(const EntityID* entity, Component* component, const EntityID::Index* componentIndexArray, void* componentArray,
505 const IteratorValidity& validity) noexcept // NOLINT(modernize-pass-by-value)
506 : entity(entity)
507 , component(component)
508 , componentIndexArray(componentIndexArray)
509 , componentArray(componentArray)
510 , slots(slots)
511 , validity(validity) {}
512#endif
513
514 GREM_ALWAYS_INLINE constexpr operator SingleComponentIterator<const Component>() const noexcept {
515#if defined(NDEBUG) && !defined(GREM_USE_RELEASE_ASSERTIONS)
516 return SingleComponentIterator<const Component>{entity, component, componentIndexArray, componentArray, slots};
517#else
518 return SingleComponentIterator<const Component>{entity, component, componentIndexArray, componentArray, slots, validity};
519#endif
520 }
521
522 [[nodiscard]] GREM_ALWAYS_INLINE constexpr reference operator*() const {
523#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
524 assertValid();
525#endif
526 return reference{*entity, *component};
527 }
528
529 [[nodiscard]] GREM_ALWAYS_INLINE constexpr pointer operator->() const {
530 return pointer{**this};
531 }
532
533 [[nodiscard]] GREM_ALWAYS_INLINE constexpr reference operator[](difference_type n) const {
534 return *(*this + n);
535 }
536
537 GREM_ALWAYS_INLINE constexpr SingleComponentIterator& operator++() {
538#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
539 assertValid();
540#endif
541 ++entity;
542 ++component;
543 return *this;
544 }
545
546 GREM_ALWAYS_INLINE constexpr SingleComponentIterator& operator--() {
547#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
548 assertValid();
549#endif
550 --entity;
551 --component;
552 return *this;
553 }
554
555 GREM_ALWAYS_INLINE constexpr SingleComponentIterator operator++(int) {
556 SingleComponentIterator old = *this;
557 ++*this;
558 return old;
559 }
560
561 GREM_ALWAYS_INLINE constexpr SingleComponentIterator operator--(int) {
562 SingleComponentIterator old = *this;
563 --*this;
564 return old;
565 }
566
567 GREM_ALWAYS_INLINE constexpr SingleComponentIterator& operator+=(difference_type n) {
568#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
569 if (n != 0) {
570 assertValid();
571 }
572#endif
573 entity += n;
574 component += n;
575 return *this;
576 }
577
578 GREM_ALWAYS_INLINE constexpr SingleComponentIterator& operator-=(difference_type n) {
579#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
580 if (n != 0) {
581 assertValid();
582 }
583#endif
584 entity -= n;
585 component -= n;
586 return *this;
587 }
588
589 [[nodiscard]] GREM_ALWAYS_INLINE constexpr bool operator==(const SingleComponentSentinel& sentinel) const {
590 return entity == sentinel.entitiesEnd;
591 }
592
593 [[nodiscard]] GREM_ALWAYS_INLINE friend constexpr SingleComponentIterator operator+(SingleComponentIterator a, difference_type b) {
594 return a += b;
595 }
596
597 [[nodiscard]] GREM_ALWAYS_INLINE friend constexpr SingleComponentIterator operator+(difference_type a, SingleComponentIterator b) {
598 return b += a;
599 }
600
601 [[nodiscard]] GREM_ALWAYS_INLINE friend constexpr SingleComponentIterator operator-(SingleComponentIterator a, difference_type b) {
602 return a -= b;
603 }
604
605 [[nodiscard]] GREM_ALWAYS_INLINE friend constexpr difference_type operator-(SingleComponentIterator a, SingleComponentIterator b) {
606#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
607 GREM_ASSERT(a.validity == b.validity);
608#endif
609 GREM_ASSERT(a.entity - b.entity == a.component - b.component);
610 return static_cast<difference_type>(a.entity - b.entity);
611 }
612
613 [[nodiscard]] GREM_ALWAYS_INLINE friend constexpr bool operator==(SingleComponentIterator a, SingleComponentIterator b) {
614#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
615 GREM_ASSERT(a.validity == b.validity);
616#endif
617 GREM_ASSERT(a.entity - b.entity == a.component - b.component);
618 return a.entity == b.entity;
619 }
620
621 [[nodiscard]] GREM_ALWAYS_INLINE friend constexpr auto operator<=>(SingleComponentIterator a, SingleComponentIterator b) {
622#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
623 GREM_ASSERT(a.validity == b.validity);
624#endif
625 GREM_ASSERT(a.entity - b.entity == a.component - b.component);
626 return a.entity <=> b.entity;
627 }
628
629private:
630 template <typename... ComponentsAndExclusions>
631 friend class Entities;
632
633 const EntityID* entity;
634 Component* component;
635 const EntityID::Index* componentIndexArray;
636 void* componentArray;
638#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
639 IteratorValidity validity{};
640
641 void assertValid() const {
642 validity.assertValid();
643 }
644#endif
645};
646
647template <empty_component Component>
648class SingleComponentIterator<Component> {
649public:
650 using difference_type = ptrdiff_t;
651 using value_type = Tuple<const EntityID, Component>;
652 using reference = Tuple<const EntityID, Component&>;
653 using iterator_category = std::random_access_iterator_tag;
654
655 struct pointer {
656 reference ref;
657
658 [[nodiscard]] GREM_ALWAYS_INLINE constexpr reference* operator->() noexcept {
659 return &ref;
660 }
661 };
662
663 GREM_ALWAYS_INLINE SingleComponentIterator() noexcept = default;
664
665#if defined(NDEBUG) && !defined(GREM_USE_RELEASE_ASSERTIONS)
666 GREM_ALWAYS_INLINE constexpr SingleComponentIterator(const EntityID* entity, Component*, const EntityID::Index* componentIndexArray, void*,
667 Span<const EntitySlot> slots) noexcept
668 : entity(entity)
669 , componentIndexArray(componentIndexArray)
670 , slots(slots) {}
671#else
672 GREM_ALWAYS_INLINE constexpr SingleComponentIterator(const EntityID* entity, Component*, const EntityID::Index* componentIndexArray, void*, Span<const EntitySlot> slots,
673 const IteratorValidity& validity) noexcept // NOLINT(modernize-pass-by-value)
674 : entity(entity)
675 , componentIndexArray(componentIndexArray)
676 , slots(slots)
677 , validity(validity) {}
678#endif
679
680 GREM_ALWAYS_INLINE constexpr operator SingleComponentIterator<const Component>() const noexcept {
681#if defined(NDEBUG) && !defined(GREM_USE_RELEASE_ASSERTIONS)
682 return SingleComponentIterator<const Component>{entity, nullptr, componentIndexArray, nullptr, slots};
683#else
684 return SingleComponentIterator<const Component>{entity, nullptr, componentIndexArray, nullptr, slots, validity};
685#endif
686 }
687
688 [[nodiscard]] GREM_ALWAYS_INLINE constexpr reference operator*() const {
689#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
690 assertValid();
691#endif
692 return reference{*entity, DUMMY_COMPONENT<Component>};
693 }
694
695 [[nodiscard]] GREM_ALWAYS_INLINE constexpr pointer operator->() const {
696 return pointer{**this};
697 }
698
699 [[nodiscard]] GREM_ALWAYS_INLINE constexpr reference operator[](difference_type n) const {
700 return *(*this + n);
701 }
702
703 GREM_ALWAYS_INLINE constexpr SingleComponentIterator& operator++() {
704#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
705 assertValid();
706#endif
707 ++entity;
708 return *this;
709 }
710
711 GREM_ALWAYS_INLINE constexpr SingleComponentIterator& operator--() {
712#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
713 assertValid();
714#endif
715 --entity;
716 return *this;
717 }
718
719 GREM_ALWAYS_INLINE constexpr SingleComponentIterator operator++(int) {
720 SingleComponentIterator old = *this;
721 ++*this;
722 return old;
723 }
724
725 GREM_ALWAYS_INLINE constexpr SingleComponentIterator operator--(int) {
726 SingleComponentIterator old = *this;
727 --*this;
728 return old;
729 }
730
731 GREM_ALWAYS_INLINE constexpr SingleComponentIterator& operator+=(difference_type n) {
732#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
733 if (n != 0) {
734 assertValid();
735 }
736#endif
737 entity += n;
738 return *this;
739 }
740
741 GREM_ALWAYS_INLINE constexpr SingleComponentIterator& operator-=(difference_type n) {
742#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
743 if (n != 0) {
744 assertValid();
745 }
746#endif
747 entity -= n;
748 return *this;
749 }
750
751 [[nodiscard]] GREM_ALWAYS_INLINE constexpr bool operator==(const SingleComponentSentinel& sentinel) const {
752 return entity == sentinel.entitiesEnd;
753 }
754
755 [[nodiscard]] GREM_ALWAYS_INLINE friend constexpr SingleComponentIterator operator+(SingleComponentIterator a, difference_type b) {
756 return a += b;
757 }
758
759 [[nodiscard]] GREM_ALWAYS_INLINE friend constexpr SingleComponentIterator operator+(difference_type a, SingleComponentIterator b) {
760 return b += a;
761 }
762
763 [[nodiscard]] GREM_ALWAYS_INLINE friend constexpr SingleComponentIterator operator-(SingleComponentIterator a, difference_type b) {
764 return a -= b;
765 }
766
767 [[nodiscard]] GREM_ALWAYS_INLINE friend constexpr difference_type operator-(SingleComponentIterator a, SingleComponentIterator b) {
768#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
769 GREM_ASSERT(a.validity == b.validity);
770#endif
771 return static_cast<difference_type>(a.entity - b.entity);
772 }
773
774 [[nodiscard]] GREM_ALWAYS_INLINE friend constexpr bool operator==(SingleComponentIterator a, SingleComponentIterator b) {
775#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
776 GREM_ASSERT(a.validity == b.validity);
777#endif
778 return a.entity == b.entity;
779 }
780
781 [[nodiscard]] GREM_ALWAYS_INLINE friend constexpr auto operator<=>(SingleComponentIterator a, SingleComponentIterator b) {
782#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
783 GREM_ASSERT(a.validity == b.validity);
784#endif
785 return a.entity <=> b.entity;
786 }
787
788private:
789 template <typename... ComponentsAndExclusions>
790 friend class Entities;
791
792 const EntityID* entity;
793 const EntityID::Index* componentIndexArray;
795#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
796 IteratorValidity validity{};
797
798 void assertValid() const {
799 validity.assertValid();
800 }
801#endif
802};
803
804} // namespace detail
805
814template <typename... ComponentsAndExclusions>
815class Entities {
816public:
819
822
825
828
829private:
830 static constexpr size_t EXCLUDED_COMPONENT_COUNT = meta::type_list_size_v<ExcludedComponents>;
831 static constexpr size_t INCLUDED_COMPONENT_COUNT = meta::type_list_size_v<IncludedComponents>;
832 static constexpr size_t NON_EMPTY_INCLUDED_COMPONENT_COUNT = detail::non_empty_component_count_of_type_list<IncludedComponents>::value;
833
834public:
835 using iterator = detail::MultiComponentIterator<IncludedComponents, ExcludedComponents>;
836 using sentinel = detail::MultiComponentSentinel;
837 using value_type = typename iterator::value_type;
838 using reference = typename iterator::reference;
839 using size_type = size_t;
840 using difference_type = ptrdiff_t;
841
845 GREM_ALWAYS_INLINE constexpr Entities() noexcept = default;
846
855 GREM_ALWAYS_INLINE constexpr Entities(const iterator& first, const iterator& last) noexcept
856 : candidateEntities(first.candidateEntities.data(), static_cast<size_t>(last.candidateEntities.data() - first.candidateEntities.data()))
857 , excludedIndexArrays(first.excludedIndexArrays)
858 , componentIndexArrays(first.componentIndexArrays)
859 , componentArrays(first.componentArrays)
860 , slots(first.slots) {
861#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
862 GREM_ASSERT(first.excludedIteratorValidity == last.excludedIteratorValidity);
863 GREM_ASSERT(first.componentIteratorValidity == last.componentIteratorValidity);
864 excludedIteratorValidity = first.excludedIteratorValidity;
865 componentIteratorValidity = first.componentIteratorValidity;
866#endif
867 }
868
869 [[nodiscard]] GREM_ALWAYS_INLINE constexpr iterator begin() const noexcept {
870#if defined(NDEBUG) && !defined(GREM_USE_RELEASE_ASSERTIONS)
871 return iterator{candidateEntities.data(), candidateEntities.data() + candidateEntities.size(), excludedIndexArrays, componentIndexArrays, componentArrays, slots};
872#else
873 return iterator{candidateEntities.data(), candidateEntities.data() + candidateEntities.size(), excludedIndexArrays, componentIndexArrays, componentArrays, slots,
874 excludedIteratorValidity, componentIteratorValidity};
875#endif
876 }
877
878 [[nodiscard]] GREM_ALWAYS_INLINE constexpr sentinel end() const noexcept {
879 return sentinel{};
880 }
881
888 [[nodiscard]] GREM_ALWAYS_INLINE constexpr size_type getCandidateCount() const noexcept {
889 return candidateEntities.size();
890 }
891
900 [[nodiscard]] GREM_ALWAYS_INLINE constexpr bool containsEntity(EntityID id) const {
901 for (const EntityID::Index* const componentIndexArray : componentIndexArrays) {
902 if (!componentIndexArray) {
903 return false;
904 }
905 }
906#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
907 assertValid();
908#endif
909 return iterator::containsEntity(excludedIndexArrays, componentIndexArrays, slots, id);
910 }
911
912 [[nodiscard]] GREM_ALWAYS_INLINE constexpr reference operator[](EntityID id) const {
913#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
914 assertValid();
915#endif
916 GREM_ASSERT(iterator::containsEntity(excludedIndexArrays, componentIndexArrays, slots, id));
917 return iterator::dereference(componentIndexArrays, componentArrays, id);
918 }
919
931 template <component T>
932 [[nodiscard]] GREM_ALWAYS_INLINE bool hasComponent(EntityID id) const noexcept {
933 return findComponent<T>(id) != nullptr;
934 }
935
949 template <component T>
950 [[nodiscard]] GREM_ALWAYS_INLINE auto& getComponent(EntityID id) const {
951 auto* const result = findComponent<T>(id);
952 if (!result) {
953 throw std::out_of_range{("Component \"" + meta::unqualified_type_name_v<T> + "\" not found for the specified entity.").c_str()};
954 }
955 return *result;
956 }
957
974 template <component T, typename U>
975 [[nodiscard]] GREM_ALWAYS_INLINE auto getComponentOr(EntityID id, U&& defaultValue) const {
976 auto* const result = findComponent<T>(id);
977 if (!result) {
978 return std::forward<U>(defaultValue);
979 }
980 return *result;
981 }
982
995 template <component T>
996 [[nodiscard]] GREM_ALWAYS_INLINE auto* findComponent(EntityID id) const noexcept {
997 if (containsEntity(id)) {
998 return &getComponentAtEntityIndexUnsafe<T>(id.getIndex());
999 }
1000 return decltype(&getComponentAtEntityIndexUnsafe<T>(id.getIndex())){nullptr};
1001 }
1002
1016 GREM_ASSERT((slots[slotIndex].generation & 1) != 0);
1017 return EntityID{slotIndex, slots[slotIndex].generation, slots[slotIndex].active.flags};
1018 }
1019
1037 template <component T>
1039 constexpr bool CONTAINS_CONST_COMPONENT = meta::type_list_contains_v<IncludedComponents, const T>;
1040 constexpr bool CONTAINS_NON_CONST_COMPONENT = meta::type_list_contains_v<IncludedComponents, T>;
1041 static_assert(CONTAINS_CONST_COMPONENT || CONTAINS_NON_CONST_COMPONENT, "The specified component type must be included in the entity range type.");
1042#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
1043 assertValid();
1044#endif
1045 if constexpr (CONTAINS_CONST_COMPONENT) {
1046 return iterator::template getComponentUnsafe<const T, meta::type_list_index_v<IncludedComponents, const T>>(componentIndexArrays, componentArrays, slotIndex);
1047 } else {
1048 return iterator::template getComponentUnsafe<T, meta::type_list_index_v<IncludedComponents, T>>(componentIndexArrays, componentArrays, slotIndex);
1049 }
1050 }
1051
1052private:
1053 template <typename... KnownComponents>
1054 friend class EntityRegistry;
1055
1056#if defined(NDEBUG) && !defined(GREM_USE_RELEASE_ASSERTIONS)
1059 Span<const detail::EntitySlot> slots) noexcept
1060 : candidateEntities(candidateEntities)
1061 , excludedIndexArrays(excludedIndexArrays)
1062 , componentIndexArrays(componentIndexArrays)
1063 , componentArrays(componentArrays)
1064 , slots(slots) {}
1065#else
1069 const Array<detail::IteratorValidity, max(INCLUDED_COMPONENT_COUNT, size_t{1})>& componentIteratorValidity) noexcept
1070 : candidateEntities(candidateEntities)
1071 , excludedIndexArrays(excludedIndexArrays)
1072 , componentIndexArrays(componentIndexArrays)
1073 , componentArrays(componentArrays)
1074 , slots(slots)
1075 , excludedIteratorValidity(excludedIteratorValidity)
1076 , componentIteratorValidity(componentIteratorValidity) {}
1077#endif
1078
1079 GREM_ALWAYS_INLINE void chunkCandidates(size_t begin, size_t end) noexcept {
1080 candidateEntities = candidateEntities.subspan(begin, end - begin);
1081 }
1082
1083 Span<const EntityID> candidateEntities{};
1084 [[no_unique_address]] Array<const EntityID::Index*, EXCLUDED_COMPONENT_COUNT> excludedIndexArrays{};
1085 [[no_unique_address]] Array<const EntityID::Index*, INCLUDED_COMPONENT_COUNT> componentIndexArrays{};
1086 [[no_unique_address]] Array<void*, NON_EMPTY_INCLUDED_COMPONENT_COUNT> componentArrays{};
1087 Span<const detail::EntitySlot> slots{};
1088#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
1089 Array<detail::IteratorValidity, EXCLUDED_COMPONENT_COUNT> excludedIteratorValidity{};
1090 Array<detail::IteratorValidity, max(INCLUDED_COMPONENT_COUNT, size_t{1})> componentIteratorValidity{};
1091
1092 void assertValid() const {
1093 for (size_t i = 0; i < EXCLUDED_COMPONENT_COUNT; ++i) {
1094 if (excludedIndexArrays[i]) {
1095 excludedIteratorValidity[i].assertValid();
1096 }
1097 }
1098 for (const detail::IteratorValidity& validity : componentIteratorValidity) {
1099 validity.assertValid();
1100 }
1101 }
1102#endif
1103};
1104
1113template <typename... ComponentsAndExclusions>
1114requires(detail::entities_is_single_component<ComponentsAndExclusions...>) class Entities<ComponentsAndExclusions...> {
1115public:
1118
1121
1124
1127
1128private:
1129 using Component = typename detail::first_non_empty_component_of_type_list<IncludedComponents>::type;
1130
1131 static constexpr bool IS_COMPONENT_EMPTY = detail::empty_component<Component>;
1132
1133public:
1134 using iterator = detail::SingleComponentIterator<Component>;
1135 using sentinel = detail::SingleComponentSentinel;
1136 using value_type = typename iterator::value_type;
1137 using reference = typename iterator::reference;
1138 using size_type = size_t;
1139 using difference_type = ptrdiff_t;
1140
1144 GREM_ALWAYS_INLINE constexpr Entities() noexcept = default;
1145
1154 GREM_ALWAYS_INLINE constexpr Entities(const iterator& first, const iterator& last) noexcept requires(IS_COMPONENT_EMPTY)
1155 : candidateEntities(first.entity, static_cast<size_t>(last.entity - first.entity))
1156 , componentIndexArray(first.componentIndexArray)
1157 , slots(first.slots) {
1158#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
1159 GREM_ASSERT(first.validity == last.validity);
1160 validity = first.validity;
1161#endif
1162 }
1163
1172 GREM_ALWAYS_INLINE constexpr Entities(const iterator& first, const iterator& last) noexcept requires(!IS_COMPONENT_EMPTY)
1173 : candidateEntities(first.entity, static_cast<size_t>(last.entity - first.entity))
1174 , candidateComponents(first.component)
1175 , componentIndexArray(first.componentIndexArray)
1176 , componentArray(first.componentArray)
1177 , slots(first.slots) {
1178#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
1179 GREM_ASSERT(first.validity == last.validity);
1180 validity = first.validity;
1181#endif
1182 }
1183
1184 [[nodiscard]] GREM_ALWAYS_INLINE constexpr iterator begin() const noexcept {
1185 Component* component = nullptr;
1186 void* componentArrayElement = nullptr;
1187 if constexpr (!IS_COMPONENT_EMPTY) {
1188 component = candidateComponents;
1189 componentArrayElement = componentArray;
1190 }
1191#if defined(NDEBUG) && !defined(GREM_USE_RELEASE_ASSERTIONS)
1192 return iterator{candidateEntities.data(), component, componentIndexArray, componentArrayElement, slots};
1193#else
1194 return iterator{candidateEntities.data(), component, componentIndexArray, componentArrayElement, slots, validity};
1195#endif
1196 }
1197
1198 [[nodiscard]] GREM_ALWAYS_INLINE constexpr sentinel end() const noexcept {
1199 return sentinel{candidateEntities.data() + candidateEntities.size()};
1200 }
1201
1202 [[nodiscard]] GREM_ALWAYS_INLINE constexpr Component* data() const noexcept requires(!IS_COMPONENT_EMPTY) {
1203 return candidateComponents;
1204 }
1205
1206 [[nodiscard]] GREM_ALWAYS_INLINE constexpr size_type size() const noexcept {
1207 return candidateEntities.size();
1208 }
1209
1210 [[nodiscard]] GREM_ALWAYS_INLINE constexpr bool empty() const noexcept {
1211 return candidateEntities.empty();
1212 }
1213
1220 [[nodiscard]] GREM_ALWAYS_INLINE constexpr size_t getCandidateCount() const noexcept {
1221 return candidateEntities.size();
1222 }
1223
1232 [[nodiscard]] GREM_ALWAYS_INLINE constexpr bool containsEntity(EntityID id) const {
1233 if (!componentIndexArray) {
1234 return false;
1235 }
1236#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
1237 assertValid();
1238#endif
1239 return id.getIndex() < slots.size() && (id.getGeneration() & 1) != 0 && slots[id.getIndex()].generation == id.getGeneration() &&
1240 componentIndexArray[id.getIndex()] != EntityID::INVALID_INDEX;
1241 }
1242
1243 [[nodiscard]] GREM_ALWAYS_INLINE constexpr reference operator[](EntityID id) const {
1246 }
1247
1259 template <component T>
1260 [[nodiscard]] GREM_ALWAYS_INLINE bool hasComponent(EntityID id) const noexcept {
1261 return findComponent<T>(id) != nullptr;
1262 }
1263
1277 template <component T>
1278 [[nodiscard]] GREM_ALWAYS_INLINE auto& getComponent(EntityID id) const {
1279 auto* const result = findComponent<T>(id);
1280 if (!result) {
1281 throw std::out_of_range{("Component \"" + meta::unqualified_type_name_v<T> + "\" not found for the specified entity.").c_str()};
1282 }
1283 return *result;
1284 }
1285
1302 template <component T, typename U>
1303 [[nodiscard]] GREM_ALWAYS_INLINE auto getComponentOr(EntityID id, U&& defaultValue) const {
1304 auto* const result = findComponent<T>(id);
1305 if (!result) {
1306 return std::forward<U>(defaultValue);
1307 }
1308 return *result;
1309 }
1310
1323 template <component T>
1324 [[nodiscard]] GREM_ALWAYS_INLINE auto* findComponent(EntityID id) const noexcept {
1325 if (containsEntity(id)) {
1326 return &getComponentAtEntityIndexUnsafe<T>(id.getIndex());
1327 }
1328 return decltype(&getComponentAtEntityIndexUnsafe<T>(id.getIndex())){nullptr};
1329 }
1330
1344 GREM_ASSERT((slots[slotIndex].generation & 1) != 0);
1345 return EntityID{slotIndex, slots[slotIndex].generation, slots[slotIndex].active.flags};
1346 }
1347
1365 template <component T>
1367 static_assert(same_as<T, std::remove_const_t<Component>>, "The specified component type must be included in the entity range type.");
1368#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
1369 assertValid();
1370#endif
1371 if constexpr (IS_COMPONENT_EMPTY) {
1372 return detail::DUMMY_COMPONENT<Component>;
1373 } else {
1374 return static_cast<Component*>(componentArray)[componentIndexArray[slotIndex]];
1375 }
1376 }
1377
1378private:
1379 template <typename... KnownComponents>
1380 friend class EntityRegistry;
1381
1382#if defined(NDEBUG) && !defined(GREM_USE_RELEASE_ASSERTIONS)
1384 const Array<const EntityID::Index*, 1>& componentIndexArrays, const Array<void*, 0>&, Span<const detail::EntitySlot> slots) noexcept requires(IS_COMPONENT_EMPTY)
1385 : candidateEntities(candidateEntities)
1386 , componentIndexArray(componentIndexArrays[0])
1387 , slots(slots) {}
1388
1390 const Array<const EntityID::Index*, 1>& componentIndexArrays, const Array<void*, 1>& componentArrays, Span<const detail::EntitySlot> slots) noexcept
1391 requires(!IS_COMPONENT_EMPTY)
1392 : candidateEntities(candidateEntities)
1393 , candidateComponents(static_cast<Component*>(componentArrays[0]))
1394 , componentIndexArray(componentIndexArrays[0])
1395 , componentArray(componentArrays[0])
1396 , slots(slots) {}
1397#else
1398 GREM_ALWAYS_INLINE constexpr Entities(Span<const EntityID> candidateEntities, const Array<const EntityID::Index*, 0>&,
1400 const Array<detail::IteratorValidity, 1>& componentIteratorValidity) noexcept requires(IS_COMPONENT_EMPTY)
1401 : candidateEntities(candidateEntities)
1402 , componentIndexArray(componentIndexArrays[0])
1403 , slots(slots)
1404 , validity(componentIteratorValidity[0]) {
1405 if (!candidateEntities.empty()) {
1406 validity.assertValid();
1407 }
1408 }
1409
1410 GREM_ALWAYS_INLINE constexpr Entities(Span<const EntityID> candidateEntities, const Array<const EntityID::Index*, 0>&,
1411 const Array<const EntityID::Index*, 1>& componentIndexArrays, const Array<void*, 1>& componentArrays, Span<const detail::EntitySlot> slots,
1412 const Array<detail::IteratorValidity, 0>&, const Array<detail::IteratorValidity, 1>& componentIteratorValidity) noexcept requires(!IS_COMPONENT_EMPTY)
1413 : candidateEntities(candidateEntities)
1414 , candidateComponents(static_cast<Component*>(componentArrays[0]))
1415 , componentIndexArray(componentIndexArrays[0])
1416 , componentArray(componentArrays[0])
1417 , slots(slots)
1418 , validity(componentIteratorValidity[0]) {
1419 if (!candidateEntities.empty()) {
1420 validity.assertValid();
1421 }
1422 }
1423#endif
1424
1425 GREM_ALWAYS_INLINE void chunkCandidates(size_t begin, size_t end) noexcept {
1426 candidateEntities = candidateEntities.subspan(begin, end - begin);
1427 if constexpr (!IS_COMPONENT_EMPTY) {
1428 candidateComponents += begin;
1429 }
1430 }
1431
1432 Span<const EntityID> candidateEntities{};
1433 [[no_unique_address]] std::conditional_t<IS_COMPONENT_EMPTY, detail::EmptyComponentPointer, Component*> candidateComponents{};
1434 [[no_unique_address]] const EntityID::Index* componentIndexArray = nullptr;
1435 [[no_unique_address]] std::conditional_t<IS_COMPONENT_EMPTY, detail::EmptyComponentPointer, void*> componentArray{};
1436 Span<const detail::EntitySlot> slots{};
1437#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
1438 detail::IteratorValidity validity{};
1439
1440 void assertValid() const {
1441 validity.assertValid();
1442 }
1443#endif
1444};
1445
1446namespace detail {
1447
1448struct ComponentStorage {
1449 using Destroy = void (*)(void* array, EntityID::Index count, EntityID::Index capacity) noexcept;
1450 using DestructiveMove = void (*)(void* array, EntityID::Index destinationIndex, EntityID::Index sourceIndex) noexcept;
1451 using CopyOrClone = void* (*)(void* output, EntityID::Index outputCount, EntityID::Index outputCapacity, const void* input, EntityID::Index inputCount,
1452 EntityID::Index inputCapacity);
1453
1454 template <component T>
1455 static void destroyImplementation(void* array, EntityID::Index count, EntityID::Index capacity) noexcept {
1456 if constexpr (!detail::empty_component<T>) {
1457 T* const components = static_cast<T*>(array);
1458 std::destroy_n(components, static_cast<size_t>(count));
1459 if (capacity > 0) {
1460 std::allocator<T>{}.deallocate(components, static_cast<size_t>(capacity));
1461 }
1462 }
1463 }
1464
1465 template <component T>
1466 static void destructiveMoveImplementation(void* array, EntityID::Index destinationIndex, EntityID::Index sourceIndex) noexcept {
1467 if constexpr (!detail::empty_component<T>) {
1468 T* const components = static_cast<T*>(array);
1469 if (destinationIndex != sourceIndex) {
1470 components[destinationIndex] = std::move(components[sourceIndex]);
1471 }
1472 std::destroy_at(components + sourceIndex);
1473 }
1474 }
1475
1476 template <component T>
1477 static void* copyOrCloneImplementation(void* output, EntityID::Index outputCount, EntityID::Index outputCapacity, const void* input, EntityID::Index inputCount,
1478 EntityID::Index inputCapacity) {
1479 if constexpr (!copyable<T>) {
1480 if (inputCount > 0) {
1481 throw std::logic_error{("Attempted to copy uncopyable entity component \"" + meta::unqualified_type_name_v<T> + "\".").c_str()};
1482 }
1483 T* const outputComponents = static_cast<T*>(output);
1484 std::destroy_n(outputComponents, static_cast<size_t>(outputCount));
1485 return nullptr;
1486 } else if constexpr (!detail::empty_component<T>) {
1487 T* const outputComponents = static_cast<T*>(output);
1488 const T* const inputComponents = static_cast<const T*>(input);
1489 if (outputCount >= inputCount) {
1490 std::copy_n(inputComponents, static_cast<size_t>(inputCount), outputComponents);
1491 std::destroy_n(outputComponents + inputCount, static_cast<size_t>(outputCount - inputCount));
1492 } else if (outputCapacity >= inputCount) {
1493 std::copy_n(inputComponents, static_cast<size_t>(outputCount), outputComponents);
1494 std::uninitialized_copy_n(inputComponents + outputCount, static_cast<size_t>(inputCount - outputCount), outputComponents + outputCount);
1495 } else {
1496 T* const newArray = std::allocator<T>{}.allocate(static_cast<size_t>(inputCapacity));
1497 try {
1498 std::uninitialized_copy_n(inputComponents, static_cast<size_t>(inputCount), newArray);
1499 } catch (...) {
1500 std::allocator<T>{}.deallocate(newArray, static_cast<size_t>(inputCapacity));
1501 throw;
1502 }
1503 return newArray;
1504 }
1505 return nullptr;
1506 } else {
1507 return nullptr;
1508 }
1509 }
1510
1511 Buffer<EntityID::Index> indices{};
1512 Buffer<EntityID> entityIDs{};
1513 EntityID::Index componentCapacity = 0;
1514 void* array = nullptr;
1515 Destroy destroy = nullptr;
1516 DestructiveMove destructiveMove = nullptr;
1517 CopyOrClone copyOrClone = nullptr;
1518#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
1519 SharedPointer<Atomic<size_t>> currentIteratorGeneration = SharedPointer<Atomic<size_t>>::create();
1520#endif
1521
1522 GREM_ALWAYS_INLINE ComponentStorage() = default;
1523
1524 template <component T>
1525 GREM_ALWAYS_INLINE ComponentStorage(size_t slotCount, std::in_place_type_t<T>)
1526 : indices(slotCount, EntityID::INVALID_INDEX)
1527 , destroy(destroyImplementation<T>)
1528 , destructiveMove(destructiveMoveImplementation<T>)
1529 , copyOrClone(copyOrCloneImplementation<T>) {}
1530
1531 GREM_ALWAYS_INLINE ComponentStorage(size_t slotCount, const ComponentStorage& other)
1532 : indices(slotCount, EntityID::INVALID_INDEX)
1533 , destroy(other.destroy)
1534 , destructiveMove(other.destructiveMove)
1535 , copyOrClone(other.copyOrClone) {}
1536
1537 GREM_ALWAYS_INLINE ~ComponentStorage() {
1538 if (array) {
1539 destroy(array, static_cast<EntityID::Index>(entityIDs.size()), componentCapacity);
1540 }
1541#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
1542 currentIteratorGeneration->fetch_add(1);
1543#endif
1544 }
1545
1546 GREM_ALWAYS_INLINE ComponentStorage(const ComponentStorage& other) {
1547 *this = other;
1548 }
1549
1550 GREM_ALWAYS_INLINE ComponentStorage(ComponentStorage&& other) noexcept {
1551 *this = std::move(other);
1552 }
1553
1554 ComponentStorage& operator=(const ComponentStorage& other) {
1555 if (this == &other) {
1556 return *this;
1557 }
1558#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
1559 currentIteratorGeneration->fetch_add(1);
1560#endif
1561 if (destroy != other.destroy) {
1562 if (array) {
1563 destroy(array, static_cast<EntityID::Index>(entityIDs.size()), componentCapacity);
1564 }
1565 indices.clear();
1566 entityIDs.clear();
1567 componentCapacity = 0;
1568 array = nullptr;
1569 destroy = other.destroy;
1570 destructiveMove = other.destructiveMove;
1571 copyOrClone = other.copyOrClone;
1572 }
1573 if (other.copyOrClone) {
1574 const EntityID::Index count = static_cast<EntityID::Index>(entityIDs.size());
1575 const EntityID::Index capacity = componentCapacity;
1576 const EntityID::Index otherCount = static_cast<EntityID::Index>(other.entityIDs.size());
1577 const EntityID::Index otherCapacity = other.componentCapacity;
1578 void* const newArray = other.copyOrClone(array, count, capacity, other.array, otherCount, otherCapacity);
1579 if (newArray) {
1580 if (array) {
1581 destroy(array, count, capacity);
1582 }
1583 array = newArray;
1584 componentCapacity = other.componentCapacity;
1585 }
1586 try {
1587 entityIDs = other.entityIDs;
1588 indices = other.indices;
1589 } catch (...) {
1590 destroy(array, otherCount, 0);
1591 entityIDs.clear();
1592 throw;
1593 }
1594 }
1595 return *this;
1596 }
1597
1598 ComponentStorage& operator=(ComponentStorage&& other) noexcept {
1599 if (this == &other) {
1600 return *this;
1601 }
1602 if (array) {
1603 destroy(array, static_cast<EntityID::Index>(entityIDs.size()), componentCapacity);
1604 }
1605 indices = std::move(other.indices);
1606 entityIDs = std::move(other.entityIDs);
1607 componentCapacity = std::exchange(other.componentCapacity, EntityID::Index{0});
1608 array = std::exchange(other.array, nullptr);
1609 destroy = other.destroy;
1610 destructiveMove = other.destructiveMove;
1611 copyOrClone = other.copyOrClone;
1612#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
1613 currentIteratorGeneration->fetch_add(1);
1614 std::swap(currentIteratorGeneration, other.currentIteratorGeneration);
1615#endif
1616 return *this;
1617 }
1618
1619 void clear() noexcept {
1620 destroy(array, static_cast<EntityID::Index>(entityIDs.size()), 0);
1621 entityIDs.clear();
1622 std::fill(indices.begin(), indices.end(), EntityID::INVALID_INDEX);
1623#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
1624 currentIteratorGeneration->fetch_add(1);
1625#endif
1626 }
1627
1628 template <component T, typename... Args>
1629 T& add(EntityID id, Args&&... args) {
1630 T* const result = addIfMissing<T>(id, std::forward<Args>(args)...);
1631 if (!result) {
1632 throw std::logic_error{"Component was already added to entity."};
1633 }
1634 return *result;
1635 }
1636
1637 template <component T, typename... Args>
1638 T* addIfMissing(EntityID id, Args&&... args) {
1639 const EntityID::Index slotIndex = id.getIndex();
1640 if (indices[slotIndex] != EntityID::INVALID_INDEX) {
1641 return nullptr;
1642 }
1643 const size_t oldCount = entityIDs.size();
1644 if constexpr (detail::empty_component<T>) {
1645 entityIDs.push_back(id);
1646 indices[slotIndex] = static_cast<EntityID::Index>(oldCount);
1647#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
1648 currentIteratorGeneration->fetch_add(1);
1649#endif
1650 return &detail::DUMMY_COMPONENT<T>;
1651 } else {
1652 const size_t oldCapacity = static_cast<size_t>(componentCapacity);
1653 if (oldCount >= oldCapacity) {
1654 GREM_ASSERT(oldCount == oldCapacity);
1655 const size_t newCapacity = clamp(oldCapacity + oldCapacity / 2, size_t{8}, static_cast<size_t>(static_cast<size_t>(EntityID::MAX_INDEX) + 1));
1656 GREM_ASSERT(newCapacity > oldCapacity);
1657 const T* const oldArray = static_cast<const T*>(array);
1658 T* const newArray = std::allocator<T>{}.allocate(newCapacity);
1659 try {
1660 std::uninitialized_move_n(oldArray, oldCount, newArray);
1661 } catch (...) {
1662 std::allocator<T>{}.deallocate(newArray, newCapacity);
1663 throw;
1664 }
1665 if (array) {
1666 destroy(array, static_cast<EntityID::Index>(oldCount), static_cast<EntityID::Index>(oldCapacity));
1667 }
1668 array = newArray;
1669 componentCapacity = static_cast<EntityID::Index>(newCapacity);
1670 }
1671 T* const newComponent = std::construct_at(static_cast<T*>(array) + oldCount, std::forward<Args>(args)...);
1672 try {
1673 entityIDs.push_back(id);
1674 } catch (...) {
1675 std::destroy_at(newComponent);
1676 throw;
1677 }
1678 indices[slotIndex] = static_cast<EntityID::Index>(oldCount);
1679#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
1680 currentIteratorGeneration->fetch_add(1);
1681#endif
1682 return newComponent;
1683 }
1684 }
1685
1686 void remove(EntityID::Index slotIndex) noexcept {
1687 const EntityID::Index componentIndex = indices[slotIndex];
1688 if (componentIndex != EntityID::INVALID_INDEX) {
1689 const EntityID::Index lastComponentIndex = static_cast<EntityID::Index>(entityIDs.size() - 1);
1690 const EntityID lastComponentEntityID = entityIDs[lastComponentIndex];
1691 indices[lastComponentEntityID.getIndex()] = componentIndex;
1692 entityIDs[componentIndex] = lastComponentEntityID;
1693 destructiveMove(array, componentIndex, lastComponentIndex);
1694 entityIDs.pop_back();
1695 indices[slotIndex] = EntityID::INVALID_INDEX;
1696#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
1697 currentIteratorGeneration->fetch_add(1);
1698#endif
1699 }
1700 }
1701};
1702
1703} // namespace detail
1704
1712template <typename Component>
1714public:
1715 using iterator = detail::SingleComponentIterator<Component>;
1716 using sentinel = detail::SingleComponentSentinel;
1717 using value_type = typename iterator::value_type;
1718 using reference = typename iterator::reference;
1719 using size_type = size_t;
1720 using difference_type = typename iterator::difference_type;
1721 using component_type = Component;
1722
1726 GREM_ALWAYS_INLINE constexpr ComponentPool() noexcept = default;
1727
1734 GREM_ALWAYS_INLINE operator ComponentPool<const Component>() const noexcept requires(!std::is_const_v<Component>) {
1735 return ComponentPool<const Component>{storage, slots};
1736 }
1737
1738 [[nodiscard]] GREM_ALWAYS_INLINE constexpr iterator begin() const noexcept {
1739#if defined(NDEBUG) && !defined(GREM_USE_RELEASE_ASSERTIONS)
1740 return (storage) ? iterator{storage->entityIDs.data(), static_cast<Component*>(storage->array), storage->indices.data(), storage->array, storage->indices.size()}
1741 : iterator{nullptr, nullptr, nullptr, nullptr, 0};
1742#else
1743 return (storage)
1744 ? iterator{storage->entityIDs.data(), static_cast<Component*>(storage->array), storage->indices.data(), storage->array, storage->indices.size(), validGeneration}
1745 : iterator{nullptr, nullptr, nullptr, nullptr, 0, validGeneration};
1746#endif
1747 }
1748
1749 [[nodiscard]] GREM_ALWAYS_INLINE constexpr sentinel end() const noexcept {
1750 return (storage) ? sentinel{storage->entityIDs.data() + storage->entityIDs.size()} : sentinel{nullptr};
1751 }
1752
1753 [[nodiscard]] GREM_ALWAYS_INLINE constexpr reference operator[](EntityID id) const {
1754 GREM_ASSERT(storage);
1755 GREM_ASSERT(has(id));
1756 if constexpr (detail::empty_component<Component>) {
1757 return {id, detail::DUMMY_COMPONENT<Component>};
1758 } else {
1759 return {id, static_cast<Component*>(storage->array)[storage->indices[id.getIndex()]]};
1760 }
1761 }
1762
1772 [[nodiscard]] GREM_ALWAYS_INLINE constexpr bool has(EntityID id) const {
1773 if (!storage) {
1774 return false;
1775 }
1776 GREM_ASSERT(storage->indices.size() == slots.size());
1777 return isValidEntity(id) && storage->indices[id.getIndex()] != EntityID::INVALID_INDEX;
1778 }
1779
1791 GREM_ALWAYS_INLINE Component& get(EntityID id) const {
1792 Component* const result = find(id);
1793 if (!result) {
1794 throw std::out_of_range{("Component \"" + meta::unqualified_type_name_v<std::remove_const_t<Component>> + "\" not found for the specified entity.").c_str()};
1795 }
1796 return *result;
1797 }
1798
1814 template <typename U>
1815 GREM_ALWAYS_INLINE Component getOr(EntityID id, U&& defaultValue) const {
1816 Component* const result = find(id);
1817 if (!result) {
1818 return std::forward<U>(defaultValue);
1819 }
1820 return *result;
1821 }
1822
1832 [[nodiscard]] GREM_ALWAYS_INLINE Component* find(EntityID id) const {
1833 if (!storage) {
1834 return nullptr;
1835 }
1836 GREM_ASSERT(storage->indices.size() == slots.size());
1837 if (isValidEntity(id)) {
1838 const EntityID::Index componentIndex = storage->indices[id.getIndex()];
1839 if (componentIndex != EntityID::INVALID_INDEX) {
1840 if constexpr (detail::empty_component<Component>) {
1841 return &detail::DUMMY_COMPONENT<Component>;
1842 } else {
1843 return static_cast<Component*>(storage->array) + componentIndex;
1844 }
1845 }
1846 }
1847 return nullptr;
1848 }
1849
1868 template <typename... Args>
1869 GREM_ALWAYS_INLINE Component& add(EntityID id, Args&&... args) requires(!std::is_const_v<Component>) {
1870 if (!storage) {
1871 throw std::logic_error{("The component pool required to add component \"" + meta::unqualified_type_name_v<Component> + "\" does not exist.").c_str()};
1872 }
1873 if (!isValidEntity(id)) {
1874 throw std::out_of_range{"Invalid entity handle."};
1875 }
1876 return storage->template add<Component>(id, std::forward<Args>(args)...);
1877 }
1878
1898 template <typename... Args>
1899 GREM_ALWAYS_INLINE Component* addIfMissing(EntityID id, Args&&... args) requires(!std::is_const_v<Component>) {
1900 if (!storage) {
1901 throw std::logic_error{("The component pool required to add component \"" + meta::unqualified_type_name_v<Component> + "\" does not exist.").c_str()};
1902 }
1903 if (!isValidEntity(id)) {
1904 throw std::out_of_range{"Invalid entity handle."};
1905 }
1906 return storage->template addIfMissing<Component>(id, std::forward<Args>(args)...);
1907 }
1908
1929 GREM_ALWAYS_INLINE Component& addOrAssign(EntityID id, Component&& value) requires(!std::is_const_v<Component>) {
1930 if (Component* const result = find(id)) {
1931 return *result = std::move(value);
1932 }
1933 return add(id, std::move(value));
1934 }
1935
1956 GREM_ALWAYS_INLINE Component& addOrAssign(EntityID id, const Component& value) requires(!std::is_const_v<Component>) {
1957 if (Component* const result = find(id)) {
1958 return *result = value;
1959 }
1960 return add(id, value);
1961 }
1962
1972 GREM_ALWAYS_INLINE bool remove(EntityID id) noexcept requires(!std::is_const_v<Component>) {
1973 if (!has(id)) {
1974 return false;
1975 }
1976 storage->remove(id.getIndex());
1977 return true;
1978 }
1979
1986 GREM_ALWAYS_INLINE size_type removeFromAllEntities() noexcept requires(!std::is_const_v<Component>) {
1987 if (storage) {
1988 const size_type result = storage->entityIDs.size();
1989 storage->clear();
1990 return result;
1991 }
1992 return 0;
1993 }
1994
1995private:
1996 template <typename... KnownComponents>
1997 friend class EntityRegistry;
1998
1999 template <typename U>
2000 friend class ComponentPool;
2001
2002 GREM_ALWAYS_INLINE constexpr ComponentPool(std::conditional_t<std::is_const_v<Component>, const detail::ComponentStorage, detail::ComponentStorage>* storage,
2003 Span<const detail::EntitySlot> slots) noexcept
2004 : storage(storage)
2005 , slots(slots) {
2006#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
2007 if (storage) {
2008 validGeneration = storage->currentIteratorGeneration;
2009 }
2010#endif
2011 }
2012
2013 [[nodiscard]] GREM_ALWAYS_INLINE bool isValidEntity(EntityID id) const {
2014 return id.getIndex() < slots.size() && (id.getGeneration() & 1) != 0 && slots[id.getIndex()].generation == id.getGeneration();
2015 }
2016
2017 std::conditional_t<std::is_const_v<Component>, const detail::ComponentStorage, detail::ComponentStorage>* storage = nullptr;
2018 Span<const detail::EntitySlot> slots{};
2019#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
2020 SharedPointer<Atomic<size_t>> validGeneration{};
2021#endif
2022};
2023
2032template <typename EntReg>
2034public:
2041 [[nodiscard]] GREM_ALWAYS_INLINE constexpr EntityBuilder(EntReg& registry, EntityID entityID) noexcept
2042 : registry(registry)
2043 , entityID(entityID) {}
2044
2047
2050
2053 : registry(other.registry)
2054 , entityID(std::exchange(other.entityID, {})) {}
2055
2058
2061
2072
2078 [[nodiscard]] GREM_ALWAYS_INLINE EntReg& getRegistry() noexcept {
2079 return registry;
2080 }
2081
2087 [[nodiscard]] GREM_ALWAYS_INLINE const EntReg& getRegistry() const noexcept {
2088 return registry;
2089 }
2090
2096 [[nodiscard]] GREM_ALWAYS_INLINE EntityID getEntityID() const noexcept {
2097 return entityID;
2098 }
2099
2118 template <component T, typename... Args>
2119 T& addComponent(Args&&... args);
2120
2138 template <component T, typename... Args>
2139 T* addComponentIfMissing(Args&&... args);
2140
2160 template <component T>
2162
2182 template <component T>
2183 T& addOrAssignComponent(const T& value);
2184
2194 template <component T>
2195 bool removeComponent() noexcept;
2196
2203 bool removeAllComponents() noexcept;
2204
2213 template <component T>
2214 [[nodiscard]] bool hasComponent() const noexcept;
2215
2226 template <component T>
2227 [[nodiscard]] T& getComponent();
2228
2239 template <component T>
2240 [[nodiscard]] const T& getComponent() const;
2241
2256 template <component T, typename U>
2257 [[nodiscard]] T getComponentOr(U&& defaultValue) const;
2258
2268 template <component T>
2269 [[nodiscard]] T* findComponent() noexcept;
2270
2280 template <component T>
2281 [[nodiscard]] const T* findComponent() const noexcept;
2282
2294 return std::exchange(entityID, EntityID{});
2295 }
2296
2297private:
2298 EntReg& registry;
2299 EntityID entityID;
2300};
2301
2302// Deduction guide for EntityBuilder.
2303template <typename Registry>
2305
2322template <typename... KnownComponents>
2324private:
2325 using KnownComponentTypeList = meta::TypeList<KnownComponents...>;
2326
2327public:
2328 static_assert((component<KnownComponents> && ...));
2329
2334 using const_pointer = const EntityID*;
2335 using size_type = size_t;
2336 using difference_type = ptrdiff_t;
2339
2341 EntityRegistry() noexcept = default;
2342
2343#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
2346 currentIteratorGeneration->fetch_add(1);
2347 }
2348#else
2350 ~EntityRegistry() = default;
2351#endif
2352
2355 *this = other;
2356 }
2357
2359 EntityRegistry(EntityRegistry&& other) noexcept {
2360 *this = std::move(other);
2361 }
2362
2365 if (this == &other) {
2366 return *this;
2367 }
2368 try {
2369 slots = other.slots;
2370 entityIDs = other.entityIDs;
2371 firstAvailableSlotIndex = other.firstAvailableSlotIndex;
2372 for (auto&& [typeIndex, storage] : componentPools) {
2373 if (!other.componentPools.contains(typeIndex)) {
2374 storage.clear();
2375 storage.indices.resize(slots.size(), EntityID::INVALID_INDEX);
2376 }
2377 }
2378 for (const auto& [typeIndex, otherStorage] : other.componentPools) {
2379 componentPools[typeIndex] = otherStorage;
2380 }
2381 for (size_t i = 0; i < sizeof...(KnownComponents); ++i) {
2382 knownComponentPools[i] = other.knownComponentPools[i];
2383 }
2384 } catch (...) {
2385 slots.clear();
2386 entityIDs.clear();
2387 firstAvailableSlotIndex = EntityID::INVALID_INDEX;
2388 componentPools.clear();
2389 for (Optional<detail::ComponentStorage>& storage : knownComponentPools) {
2390 if (storage) {
2391 storage->clear();
2392 }
2393 }
2394#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
2395 currentIteratorGeneration->fetch_add(1);
2396#endif
2397 throw;
2398 }
2399#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
2400 currentIteratorGeneration->fetch_add(1);
2401#endif
2402 return *this;
2403 }
2404
2407 if (this == &other) {
2408 return *this;
2409 }
2410 slots = std::exchange(other.slots, {});
2411 entityIDs = std::exchange(other.entityIDs, {});
2412 firstAvailableSlotIndex = std::exchange(other.firstAvailableSlotIndex, EntityID::Index{0});
2413 componentPools = std::exchange(other.componentPools, {});
2414 knownComponentPools = std::exchange(other.knownComponentPools, {});
2415#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
2416 currentIteratorGeneration->fetch_add(1);
2417 std::swap(currentIteratorGeneration, other.currentIteratorGeneration);
2418#endif
2419 return *this;
2420 }
2421
2426 void clear() noexcept {
2427 entityIDs.clear();
2428
2429 // Make all generation entries available for reuse.
2430 for (EntityID::Index slotIndex = 0; slotIndex < slots.size(); ++slotIndex) {
2431 const EntityID::Generation generation = slots[slotIndex].generation;
2432 const EntityID::Generation destroyedGeneration = generation + (generation & 1); // Make sure that the generation counter is even (marking invalid).
2433 const EntityID::Index previousAvailableSlotIndex = (slotIndex == 0) ? EntityID::INVALID_INDEX : static_cast<EntityID::Index>(slotIndex - 1);
2434 const EntityID::Index nextAvailableSlotIndex = (slotIndex == slots.size() - 1) ? EntityID::INVALID_INDEX : static_cast<EntityID::Index>(slotIndex + 1);
2435 slots[slotIndex] = detail::EntitySlot{
2436 .generation = destroyedGeneration,
2437 .inactive{.previousAvailableSlotIndex = previousAvailableSlotIndex, .nextAvailableSlotIndex = nextAvailableSlotIndex},
2438 };
2439 }
2440 firstAvailableSlotIndex = (slots.empty()) ? EntityID::INVALID_INDEX : EntityID::Index{0};
2441
2442 for (auto&& [typeIndex, storage] : componentPools) {
2443 storage.clear();
2444 }
2445 for (Optional<detail::ComponentStorage>& storage : knownComponentPools) {
2446 if (storage) {
2447 storage->clear();
2448 }
2449 }
2450
2451#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
2452 currentIteratorGeneration->fetch_add(1);
2453#endif
2454 }
2455
2471 if (size() >= max_size()) {
2472 throw std::length_error{"Maximum entity count exceeded."};
2473 }
2474
2475 const EntityID::Index idIndex = static_cast<EntityID::Index>(entityIDs.size());
2476 EntityID& id = entityIDs.push_back_unspecified_value();
2477
2478 if (firstAvailableSlotIndex == EntityID::INVALID_INDEX) {
2479 const EntityID::Index slotIndex = static_cast<EntityID::Index>(slots.size());
2480 GREM_ASSERT(slotIndex == idIndex);
2481 try {
2482 const size_t oldSlotCount = slots.size();
2483 slots.push_back(detail::EntitySlot{.generation = 1, .active{.idIndex = idIndex, .flags = flags}});
2484 try {
2485 for (auto&& [typeIndex, storage] : componentPools) {
2486 storage.indices.push_back(EntityID::INVALID_INDEX);
2487#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
2488 storage.currentIteratorGeneration->fetch_add(1);
2489#endif
2490 }
2491 for (Optional<detail::ComponentStorage>& storage : knownComponentPools) {
2492 if (storage) {
2493 storage->indices.push_back(EntityID::INVALID_INDEX);
2494#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
2495 storage->currentIteratorGeneration->fetch_add(1);
2496#endif
2497 }
2498 }
2499 } catch (...) {
2500 for (auto&& [typeIndex, storage] : componentPools) {
2501 storage.indices.resize(oldSlotCount);
2502 }
2503 for (Optional<detail::ComponentStorage>& storage : knownComponentPools) {
2504 if (storage) {
2505 storage->indices.resize(oldSlotCount);
2506 }
2507 }
2508 slots.pop_back();
2509 throw;
2510 }
2511 } catch (...) {
2512 entityIDs.pop_back();
2513 throw;
2514 }
2515 id = EntityID{slotIndex, 1, flags};
2516 } else {
2517 const EntityID::Index slotIndex = firstAvailableSlotIndex;
2518 const EntityID::Index nextAvailableSlotIndex = slots[slotIndex].inactive.nextAvailableSlotIndex;
2519 if (nextAvailableSlotIndex != EntityID::INVALID_INDEX) {
2520 slots[nextAvailableSlotIndex].inactive.previousAvailableSlotIndex = slotIndex;
2521 }
2522 firstAvailableSlotIndex = nextAvailableSlotIndex;
2523 const EntityID::Generation generation = slots[slotIndex].generation + 1;
2524 slots[slotIndex] = detail::EntitySlot{.generation = generation, .active{.idIndex = idIndex, .flags = flags}};
2525 id = EntityID{slotIndex, generation, flags};
2526 }
2527#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
2528 currentIteratorGeneration->fetch_add(1);
2529#endif
2530 return EntityBuilder{*this, id};
2531 }
2532
2552 if (id.getIndex() == EntityID::INVALID_INDEX || (id.getGeneration() & 1) == 0) {
2553 throw std::invalid_argument{"Invalid entity handle."};
2554 }
2555
2556 if (containsEntityAtIndex(id.getIndex())) {
2557 throw std::logic_error{"An entity already exists at the index of the given ID."};
2558 }
2559
2560 if (size() >= max_size()) {
2561 throw std::length_error{"Maximum entity count exceeded."};
2562 }
2563
2564 const EntityID::Index idIndex = static_cast<EntityID::Index>(entityIDs.size());
2565 entityIDs.push_back(id);
2566
2567 const EntityID::Index slotIndex = id.getIndex();
2568 const EntityID::Generation generation = id.getGeneration();
2569 const EntityID::Flags flags = id.getFlags();
2570 if (slotIndex >= slots.size()) {
2571 try {
2572 const size_t oldSlotCount = slots.size();
2573 const size_t newSlotCount = static_cast<size_t>(slotIndex + 1);
2574 slots.reserve(newSlotCount);
2575 for (size_t newSlotIndex = oldSlotCount; newSlotIndex < newSlotCount - 1; ++newSlotIndex) {
2576 const EntityID::Index previousAvailableSlotIndex = (newSlotIndex == oldSlotCount) ? EntityID::INVALID_INDEX : static_cast<EntityID::Index>(newSlotIndex - 1);
2577 const EntityID::Index nextAvailableSlotIndex = (newSlotIndex == newSlotCount - 2) ? EntityID::INVALID_INDEX : static_cast<EntityID::Index>(newSlotIndex + 1);
2578 slots.push_back(detail::EntitySlot{
2579 .generation = 0,
2580 .inactive{.previousAvailableSlotIndex = previousAvailableSlotIndex, .nextAvailableSlotIndex = nextAvailableSlotIndex},
2581 });
2582 }
2583 if (newSlotCount - oldSlotCount >= 2) {
2584 if (firstAvailableSlotIndex != EntityID::INVALID_INDEX) {
2585 slots.back().inactive.nextAvailableSlotIndex = firstAvailableSlotIndex;
2586 }
2587 firstAvailableSlotIndex = static_cast<EntityID::Index>(oldSlotCount);
2588 }
2589 slots.push_back(detail::EntitySlot{.generation = generation, .active{.idIndex = idIndex, .flags = flags}});
2590 try {
2591 for (auto&& [typeIndex, storage] : componentPools) {
2592 storage.indices.resize(newSlotCount, EntityID::INVALID_INDEX);
2593#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
2594 storage.currentIteratorGeneration->fetch_add(1);
2595#endif
2596 }
2597 for (Optional<detail::ComponentStorage>& storage : knownComponentPools) {
2598 if (storage) {
2599 storage->indices.resize(newSlotCount, EntityID::INVALID_INDEX);
2600#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
2601 storage->currentIteratorGeneration->fetch_add(1);
2602#endif
2603 }
2604 }
2605 } catch (...) {
2606 for (auto&& [typeIndex, storage] : componentPools) {
2607 storage.indices.resize(oldSlotCount);
2608 }
2609 for (Optional<detail::ComponentStorage>& storage : knownComponentPools) {
2610 if (storage) {
2611 storage->indices.resize(oldSlotCount);
2612 }
2613 }
2614 slots.resize(oldSlotCount);
2615 throw;
2616 }
2617 } catch (...) {
2618 entityIDs.pop_back();
2619 throw;
2620 }
2621 } else {
2622 const EntityID::Index previousAvailableSlotIndex = slots[slotIndex].inactive.previousAvailableSlotIndex;
2623 const EntityID::Index nextAvailableSlotIndex = slots[slotIndex].inactive.nextAvailableSlotIndex;
2624 if (previousAvailableSlotIndex == EntityID::INVALID_INDEX) {
2625 firstAvailableSlotIndex = nextAvailableSlotIndex;
2626 } else {
2627 slots[previousAvailableSlotIndex].inactive.nextAvailableSlotIndex = nextAvailableSlotIndex;
2628 }
2629 if (nextAvailableSlotIndex != EntityID::INVALID_INDEX) {
2630 slots[nextAvailableSlotIndex].inactive.previousAvailableSlotIndex = previousAvailableSlotIndex;
2631 }
2632 slots[slotIndex] = detail::EntitySlot{.generation = generation, .active{.idIndex = idIndex, .flags = flags}};
2633 }
2634#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
2635 currentIteratorGeneration->fetch_add(1);
2636#endif
2637 return EntityBuilder{*this, id};
2638 }
2639
2651 const EntityID::Index slotIndex = id.getIndex();
2652 if (slotIndex < slots.size() && (id.getGeneration() & 1) != 0) {
2653 detail::EntitySlot& slot = slots[slotIndex];
2654 if (slot.generation == id.getGeneration()) {
2655 const EntityID::Index idIndex = slot.active.idIndex;
2656 slot.active.flags = newFlags;
2657 const EntityID newEntityID{slotIndex, id.getGeneration(), newFlags};
2658 GREM_ASSERT(entityIDs[idIndex].getGeneration() == id.getGeneration());
2659 entityIDs[idIndex] = newEntityID;
2660 for (auto&& [typeIndex, storage] : componentPools) {
2661 const EntityID::Index componentIndex = storage.indices[slotIndex];
2662 if (componentIndex != EntityID::INVALID_INDEX) {
2663 GREM_ASSERT(storage.entityIDs[componentIndex].getGeneration() == id.getGeneration());
2664 storage.entityIDs[componentIndex] = newEntityID;
2665#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
2666 storage.currentIteratorGeneration->fetch_add(1);
2667#endif
2668 }
2669 }
2670 for (Optional<detail::ComponentStorage>& storage : knownComponentPools) {
2671 if (storage) {
2672 const EntityID::Index componentIndex = storage->indices[slotIndex];
2673 if (componentIndex != EntityID::INVALID_INDEX) {
2674 GREM_ASSERT(storage->entityIDs[componentIndex].getGeneration() == id.getGeneration());
2675 storage->entityIDs[componentIndex] = newEntityID;
2676#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
2677 storage->currentIteratorGeneration->fetch_add(1);
2678#endif
2679 }
2680 }
2681 }
2682#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
2683 currentIteratorGeneration->fetch_add(1);
2684#endif
2685 return newEntityID;
2686 }
2687 }
2688 return {};
2689 }
2690
2700 if (!containsEntity(id)) {
2701 return false;
2702 }
2703 const bool result = destroyEntityAtIndex(id.getIndex());
2704 GREM_ASSERT(result);
2705 return result;
2706 }
2707
2718 bool destroyEntityAtIndex(EntityID::Index slotIndex) noexcept {
2719 if (!containsEntityAtIndex(slotIndex)) {
2720 return false;
2721 }
2722
2723 GREM_ASSERT(!entityIDs.empty());
2724
2725 // Move the last entity's data to the destroyed entity's index.
2726 const EntityID::Index idIndex = slots[slotIndex].active.idIndex;
2727 const EntityID::Generation generation = slots[slotIndex].generation;
2728 const EntityID lastEntityID = entityIDs.back();
2729 const EntityID::Index lastSlotIndex = lastEntityID.getIndex();
2730 if (lastSlotIndex != slotIndex) {
2731 slots[lastSlotIndex] = detail::EntitySlot{.generation = lastEntityID.getGeneration(),
2732 .active{.idIndex = idIndex, .flags = lastEntityID.getFlags()}}; // Repoint the last entity's slot to its new index.
2733 entityIDs[idIndex] = lastEntityID;
2734 }
2735 for (auto&& [typeIndex, storage] : componentPools) {
2736 storage.remove(slotIndex);
2737 }
2738 for (Optional<detail::ComponentStorage>& storage : knownComponentPools) {
2739 if (storage) {
2740 storage->remove(slotIndex);
2741 }
2742 }
2743 entityIDs.pop_back();
2744
2745 // Make the destroyed entity's slot available for reuse.
2746 slots[slotIndex] = detail::EntitySlot{.generation = static_cast<EntityID::Generation>(generation + 1),
2747 .inactive{.previousAvailableSlotIndex = EntityID::INVALID_INDEX, .nextAvailableSlotIndex = firstAvailableSlotIndex}};
2748 firstAvailableSlotIndex = slotIndex;
2749
2750#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
2751 currentIteratorGeneration->fetch_add(1);
2752#endif
2753 return true;
2754 }
2755
2756 [[nodiscard]] GREM_ALWAYS_INLINE iterator begin() noexcept {
2757 return entityIDs.begin();
2758 }
2759
2760 [[nodiscard]] GREM_ALWAYS_INLINE const_iterator begin() const noexcept {
2761 return entityIDs.begin();
2762 }
2763
2764 [[nodiscard]] GREM_ALWAYS_INLINE const_iterator cbegin() const noexcept {
2765 return begin();
2766 }
2767
2768 [[nodiscard]] GREM_ALWAYS_INLINE iterator end() noexcept {
2769 return entityIDs.end();
2770 }
2771
2772 [[nodiscard]] GREM_ALWAYS_INLINE const_iterator end() const noexcept {
2773 return entityIDs.end();
2774 }
2775
2776 [[nodiscard]] GREM_ALWAYS_INLINE const_iterator cend() const noexcept {
2777 return end();
2778 }
2779
2788 [[nodiscard]] GREM_ALWAYS_INLINE bool containsEntity(EntityID id) const noexcept {
2789 const EntityID::Index slotIndex = id.getIndex();
2790 return slotIndex < slots.size() && (id.getGeneration() & 1) != 0 && slots[slotIndex].generation == id.getGeneration();
2791 }
2792
2801 [[nodiscard]] GREM_ALWAYS_INLINE bool containsEntityAtIndex(EntityID::Index slotIndex) const {
2802 return slotIndex < slots.size() && (slots[slotIndex].generation & 1) != 0;
2803 }
2804
2810 [[nodiscard]] GREM_ALWAYS_INLINE size_type size() const noexcept {
2811 return entityIDs.size();
2812 }
2813
2820 [[nodiscard]] GREM_ALWAYS_INLINE bool empty() const noexcept {
2821 return entityIDs.empty();
2822 }
2823
2830 [[nodiscard]] GREM_ALWAYS_INLINE size_type max_size() const noexcept {
2831 return std::min({
2832 static_cast<size_type>(slots.max_size()),
2833 static_cast<size_type>(entityIDs.max_size()),
2834 size_type{static_cast<size_type>(EntityID::MAX_INDEX) + 1},
2835 });
2836 }
2837
2860 template <component T, typename... Args>
2862 return createComponentPool<T>().add(id, std::forward<Args>(args)...);
2863 }
2864
2886 template <component T, typename... Args>
2888 return createComponentPool<T>().addIfMissing(id, std::forward<Args>(args)...);
2889 }
2890
2913 template <component T>
2915 return createComponentPool<std::decay_t<T>>().addOrAssign(id, std::forward<T>(value));
2916 }
2917
2940 template <component T>
2942 return createComponentPool<T>().addOrAssign(id, value);
2943 }
2944
2959 template <component T>
2961 return getComponentPool<T>().remove(id);
2962 }
2963
2976 if (!containsEntity(id)) {
2977 return false;
2978 }
2979 for (auto&& [typeIndex, storage] : componentPools) {
2980 storage.remove(id.getIndex());
2981 }
2982 for (Optional<detail::ComponentStorage>& storage : knownComponentPools) {
2983 if (storage) {
2984 storage->remove(id.getIndex());
2985 }
2986 }
2987 return true;
2988 }
2989
3001 template <component T>
3003 return getComponentPool<T>().removeFromAllEntities();
3004 }
3005
3016 template <component T>
3017 [[nodiscard]] GREM_ALWAYS_INLINE bool hasComponent(EntityID id) const noexcept {
3018 return findComponent<T>(id) != nullptr;
3019 }
3020
3033 template <component T>
3035 T* const result = findComponent<T>(id);
3036 if (!result) {
3037 throw std::out_of_range{("Component \"" + meta::unqualified_type_name_v<T> + "\" not found for the specified entity.").c_str()};
3038 }
3039 return *result;
3040 }
3041
3054 template <component T>
3055 [[nodiscard]] GREM_ALWAYS_INLINE const T& getComponent(EntityID id) const {
3056 const T* const result = findComponent<T>(id);
3057 if (!result) {
3058 throw std::out_of_range{("Component \"" + meta::unqualified_type_name_v<T> + "\" not found for the specified entity.").c_str()};
3059 }
3060 return *result;
3061 }
3062
3077 template <component T, typename U>
3078 [[nodiscard]] GREM_ALWAYS_INLINE T getComponentOr(EntityID id, U&& defaultValue) const {
3079 const T* const result = findComponent<T>(id);
3080 if (!result) {
3081 return std::forward<U>(defaultValue);
3082 }
3083 return *result;
3084 }
3085
3097 template <component T>
3098 [[nodiscard]] GREM_ALWAYS_INLINE T* findComponent(EntityID id) noexcept {
3099 if (containsEntity(id)) {
3102 GREM_ASSERT(storage->indices.size() == slots.size());
3103 const EntityID::Index componentIndex = storage->indices[id.getIndex()];
3104 if (componentIndex != EntityID::INVALID_INDEX) {
3105 if constexpr (detail::empty_component<T>) {
3106 return &detail::DUMMY_COMPONENT<T>;
3107 } else {
3108 return static_cast<T*>(storage->array) + componentIndex;
3109 }
3110 }
3111 }
3112 } else {
3113 if (const auto it = componentPools.find(typeid(T)); it != componentPools.end()) {
3114 detail::ComponentStorage& storage = it->second;
3115 GREM_ASSERT(storage.indices.size() == slots.size());
3116 const EntityID::Index componentIndex = storage.indices[id.getIndex()];
3117 if (componentIndex != EntityID::INVALID_INDEX) {
3118 if constexpr (detail::empty_component<T>) {
3119 return &detail::DUMMY_COMPONENT<T>;
3120 } else {
3121 return static_cast<T*>(storage.array) + componentIndex;
3122 }
3123 }
3124 }
3125 }
3126 }
3127 return nullptr;
3128 }
3129
3141 template <component T>
3142 [[nodiscard]] GREM_ALWAYS_INLINE const T* findComponent(EntityID id) const noexcept {
3143 if (containsEntity(id)) {
3146 GREM_ASSERT(storage->indices.size() == slots.size());
3147 const EntityID::Index componentIndex = storage->indices[id.getIndex()];
3148 if (componentIndex != EntityID::INVALID_INDEX) {
3149 if constexpr (detail::empty_component<T>) {
3150 return &detail::DUMMY_COMPONENT<const T>;
3151 } else {
3152 return static_cast<const T*>(storage->array) + componentIndex;
3153 }
3154 }
3155 }
3156 } else {
3157 if (const auto it = componentPools.find(typeid(T)); it != componentPools.end()) {
3158 const detail::ComponentStorage& storage = it->second;
3159 GREM_ASSERT(storage.indices.size() == slots.size());
3160 const EntityID::Index componentIndex = storage.indices[id.getIndex()];
3161 if (componentIndex != EntityID::INVALID_INDEX) {
3162 if constexpr (detail::empty_component<T>) {
3163 return &detail::DUMMY_COMPONENT<const T>;
3164 } else {
3165 return static_cast<const T*>(storage.array) + componentIndex;
3166 }
3167 }
3168 }
3169 }
3170 }
3171 return nullptr;
3172 }
3173
3186 GREM_ASSERT((slots[slotIndex].generation & 1) != 0);
3187 return EntityID{slotIndex, slots[slotIndex].generation, slots[slotIndex].active.flags};
3188 }
3189
3205 template <component T>
3207 if constexpr (detail::empty_component<T>) {
3208 return detail::DUMMY_COMPONENT<T>;
3210 detail::ComponentStorage& storage = *knownComponentPools[meta::type_list_index_v<KnownComponentTypeList, T>];
3211 GREM_ASSERT(slotIndex < storage.indices.size());
3212 const EntityID::Index componentIndex = storage.indices[slotIndex];
3213 GREM_ASSERT(componentIndex != EntityID::INVALID_INDEX);
3214 return static_cast<T*>(storage.array)[componentIndex];
3215 } else {
3216 const auto it = componentPools.find(typeid(T));
3217 GREM_ASSERT(it != componentPools.end());
3218 detail::ComponentStorage& storage = it->second;
3219 GREM_ASSERT(slotIndex < storage.indices.size());
3220 const EntityID::Index componentIndex = storage.indices[slotIndex];
3221 GREM_ASSERT(componentIndex != EntityID::INVALID_INDEX);
3222 return static_cast<T*>(storage.array)[componentIndex];
3223 }
3224 }
3225
3241 template <component T>
3243 if constexpr (detail::empty_component<T>) {
3244 return detail::DUMMY_COMPONENT<const T>;
3246 const detail::ComponentStorage& storage = *knownComponentPools[meta::type_list_index_v<KnownComponentTypeList, T>];
3247 GREM_ASSERT(slotIndex < storage.indices.size());
3248 const EntityID::Index componentIndex = storage.indices[slotIndex];
3249 GREM_ASSERT(componentIndex != EntityID::INVALID_INDEX);
3250 return static_cast<const T*>(storage.array)[componentIndex];
3251 } else {
3252 const auto it = componentPools.find(typeid(T));
3253 GREM_ASSERT(it != componentPools.end());
3254 const detail::ComponentStorage& storage = it->second;
3255 GREM_ASSERT(slotIndex < storage.indices.size());
3256 const EntityID::Index componentIndex = storage.indices[slotIndex];
3257 GREM_ASSERT(componentIndex != EntityID::INVALID_INDEX);
3258 return static_cast<const T*>(storage.array)[componentIndex];
3259 }
3260 }
3261
3283 template <typename... ComponentsAndExclusions>
3284 [[nodiscard]] GREM_ALWAYS_INLINE Entities<ComponentsAndExclusions...> getEntities() noexcept
3285 requires(!meta::type_list_empty_v<typename Entities<ComponentsAndExclusions...>::MutableComponents>) {
3286 using EntityRange = Entities<ComponentsAndExclusions...>;
3287 return getEntitiesImplementation<EntityRange>(typename EntityRange::IncludedComponents{}, typename EntityRange::ExcludedComponents{});
3288 }
3289
3311 template <typename... ComponentsAndExclusions>
3312 [[nodiscard]] GREM_ALWAYS_INLINE Entities<ComponentsAndExclusions...> getEntities() const noexcept
3313 requires(meta::type_list_empty_v<typename Entities<ComponentsAndExclusions...>::MutableComponents>) {
3314 using EntityRange = Entities<ComponentsAndExclusions...>;
3315 return const_cast<EntityRegistry*>(this)->getEntitiesImplementation<EntityRange>(typename EntityRange::IncludedComponents{}, typename EntityRange::ExcludedComponents{});
3316 }
3317
3325 template <typename... ComponentsAndExclusions>
3326 [[nodiscard]] GREM_ALWAYS_INLINE operator Entities<ComponentsAndExclusions...>() noexcept
3327 requires(!meta::type_list_empty_v<typename Entities<ComponentsAndExclusions...>::MutableComponents>) {
3328 return getEntities<ComponentsAndExclusions...>();
3329 }
3330
3338 template <typename... ComponentsAndExclusions>
3339 [[nodiscard]] GREM_ALWAYS_INLINE operator Entities<ComponentsAndExclusions...>() const noexcept
3340 requires(meta::type_list_empty_v<typename Entities<ComponentsAndExclusions...>::MutableComponents>) {
3341 return getEntities<ComponentsAndExclusions...>();
3342 }
3343
3372 template <typename... ComponentsAndExclusions>
3373 [[nodiscard]] GREM_ALWAYS_INLINE Entities<ComponentsAndExclusions...> getEntitiesChunk(size_t chunkIndex, size_t chunkCount) noexcept
3374 requires(!meta::type_list_empty_v<typename Entities<ComponentsAndExclusions...>::MutableComponents>) {
3375 using EntityRange = Entities<ComponentsAndExclusions...>;
3376 return getEntitiesChunkImplementation<EntityRange>(chunkIndex, chunkCount, typename EntityRange::IncludedComponents{}, typename EntityRange::ExcludedComponents{});
3377 }
3378
3407 template <typename... ComponentsAndExclusions>
3408 [[nodiscard]] GREM_ALWAYS_INLINE Entities<ComponentsAndExclusions...> getEntitiesChunk(size_t chunkIndex, size_t chunkCount) const noexcept
3409 requires(meta::type_list_empty_v<typename Entities<ComponentsAndExclusions...>::MutableComponents>) {
3410 using EntityRange = Entities<ComponentsAndExclusions...>;
3411 return const_cast<EntityRegistry*>(this)->getEntitiesChunkImplementation<EntityRange>(chunkIndex, chunkCount, typename EntityRange::IncludedComponents{},
3412 typename EntityRange::ExcludedComponents{});
3413 }
3414
3430 template <component T>
3434 if (!storage) {
3435 storage.emplace(slots.size(), std::in_place_type<T>);
3436 }
3437 return ComponentPool<T>{&*storage, slots};
3438 } else {
3439 detail::ComponentStorage& storage = componentPools.try_emplace(typeid(T), slots.size(), std::in_place_type<T>).first->second;
3440 return ComponentPool<T>{&storage, slots};
3441 }
3442 }
3443
3459 template <component T>
3463 return ComponentPool<T>{&*storage, slots};
3464 }
3465 return ComponentPool<T>{};
3466 } else {
3467 if (const auto it = componentPools.find(typeid(T)); it != componentPools.end()) {
3468 return ComponentPool<T>{&it->second, slots};
3469 }
3470 return ComponentPool<T>{};
3471 }
3472 }
3473
3489 template <component T>
3493 return ComponentPool<const T>{&*storage, slots};
3494 }
3495 return ComponentPool<const T>{};
3496 } else {
3497 if (const auto it = componentPools.find(typeid(T)); it != componentPools.end()) {
3498 return ComponentPool<const T>{&it->second, slots};
3499 }
3500 return ComponentPool<const T>{};
3501 }
3502 }
3503
3512 template <typename... ComponentsAndExclusions>
3514 size_type result = 0;
3515 while (true) {
3516 const auto entities = getEntities<ComponentsAndExclusions...>();
3517 const auto first = entities.begin();
3518 const auto last = entities.end();
3519 if (first == last) {
3520 break;
3521 }
3523 ++result;
3524 }
3525 return result;
3526 }
3527
3541 template <typename Predicate>
3542 friend size_type erase_if(EntityRegistry& c, Predicate predicate) {
3543 size_type result = 0;
3544 size_type i = 0;
3545 while (i < c.entityIDs.size()) {
3546 const EntityID id = c.entityIDs[i];
3547 if (predicate(id)) {
3548 c.destroyEntity(id);
3549 ++result;
3550 } else {
3551 ++i;
3552 }
3553 }
3554 return result;
3555 }
3556
3557private:
3558 template <typename EntityRange, typename... IncludedComponents, typename... ExcludedComponents>
3559 [[nodiscard]] EntityRange getEntitiesImplementation(meta::TypeList<IncludedComponents...>, meta::TypeList<ExcludedComponents...>) noexcept {
3560 Optional<Span<const EntityID>> candidateEntities{};
3561 Array<const EntityID::Index*, sizeof...(ExcludedComponents)> excludedIndexArrays{};
3562 Array<const EntityID::Index*, sizeof...(IncludedComponents)> componentIndexArrays{};
3563 Array<void*, detail::NON_EMPTY_COMPONENT_COUNT<IncludedComponents...>> componentArrays{};
3564#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
3565 Array<detail::IteratorValidity, sizeof...(ExcludedComponents)> excludedIteratorValidity{};
3566 Array<detail::IteratorValidity, max(sizeof...(IncludedComponents), size_t{1})> componentIteratorValidity{};
3567#endif
3568
3569 [[maybe_unused]] size_t excludedComponentIndex = 0;
3570 (([&]<typename Component>(meta::Type<Component>) -> void {
3571 static_assert(!std::is_const_v<Component>);
3572 using T = Component;
3574 if (Optional<detail::ComponentStorage>& storage = knownComponentPools[meta::type_list_index_v<KnownComponentTypeList, T>]) {
3575 excludedIndexArrays[excludedComponentIndex] = storage->indices.data();
3576#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
3577 excludedIteratorValidity[excludedComponentIndex] = storage->currentIteratorGeneration;
3578#endif
3579 }
3580 } else {
3581 if (const auto it = componentPools.find(typeid(T)); it != componentPools.end()) {
3582 excludedIndexArrays[excludedComponentIndex] = it->second.indices.data();
3583#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
3584 excludedIteratorValidity[excludedComponentIndex] = it->second.currentIteratorGeneration;
3585#endif
3586 }
3587 }
3588 ++excludedComponentIndex;
3590 ...);
3591
3592 [[maybe_unused]] size_t includedComponentIndex = 0;
3593 [[maybe_unused]] size_t nonEmptyIncludedComponentIndex = 0;
3594 if constexpr (sizeof...(IncludedComponents) == 0) {
3595 candidateEntities = entityIDs;
3596#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
3597 componentIteratorValidity.front() = currentIteratorGeneration;
3598#endif
3599 } else {
3600 (([&]<typename Component>(meta::Type<Component>) -> void {
3601 using T = std::remove_const_t<Component>;
3603 if (Optional<detail::ComponentStorage>& storage = knownComponentPools[meta::type_list_index_v<KnownComponentTypeList, T>]) {
3604 componentIndexArrays[includedComponentIndex] = storage->indices.data();
3605#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
3606 componentIteratorValidity[includedComponentIndex] = storage->currentIteratorGeneration;
3607#endif
3608 if constexpr (!detail::empty_component<Component>) {
3609 componentArrays[nonEmptyIncludedComponentIndex] = storage->array;
3610 }
3611 const Span<const EntityID> componentEntityIDs = storage->entityIDs;
3612 if (!candidateEntities || componentEntityIDs.size() < candidateEntities->size()) {
3613 candidateEntities = componentEntityIDs;
3614 }
3615 } else {
3616 candidateEntities.emplace();
3617 }
3618 } else {
3619 if (const auto it = componentPools.find(typeid(T)); it != componentPools.end()) {
3620 componentIndexArrays[includedComponentIndex] = it->second.indices.data();
3621#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
3622 componentIteratorValidity[includedComponentIndex] = it->second.currentIteratorGeneration;
3623#endif
3624 if constexpr (!detail::empty_component<Component>) {
3625 componentArrays[nonEmptyIncludedComponentIndex] = it->second.array;
3626 }
3627 const Span<const EntityID> componentEntityIDs = it->second.entityIDs;
3628 if (!candidateEntities || componentEntityIDs.size() < candidateEntities->size()) {
3629 candidateEntities = componentEntityIDs;
3630 }
3631 } else {
3632 candidateEntities.emplace();
3633 }
3634 }
3635 ++includedComponentIndex;
3636 if constexpr (!detail::empty_component<Component>) {
3637 ++nonEmptyIncludedComponentIndex;
3638 }
3640 ...);
3641 }
3642
3643#if defined(NDEBUG) && !defined(GREM_USE_RELEASE_ASSERTIONS)
3644 return EntityRange{candidateEntities.value_or(Span<const EntityID>{}), excludedIndexArrays, componentIndexArrays, componentArrays, slots};
3645#else
3646 return EntityRange{candidateEntities.value_or(Span<const EntityID>{}), excludedIndexArrays, componentIndexArrays, componentArrays, slots, excludedIteratorValidity,
3647 componentIteratorValidity};
3648#endif
3649 }
3650
3651 template <typename EntityRange, typename... IncludedComponents, typename... ExcludedComponents>
3652 [[nodiscard]] EntityRange getEntitiesChunkImplementation(size_t chunkIndex, size_t chunkCount, meta::TypeList<IncludedComponents...>,
3653 meta::TypeList<ExcludedComponents...>) noexcept {
3654 EntityRange result = getEntitiesImplementation<EntityRange>(meta::TYPE_LIST<IncludedComponents...>, meta::TYPE_LIST<ExcludedComponents...>);
3655 const size_t candidateCount = result.getCandidateCount();
3656 GREM_ASSERT(chunkIndex < chunkCount);
3657 const size_t chunkSize = (candidateCount + chunkCount - 1) / chunkCount;
3658 const size_t chunkBegin = min(chunkIndex * chunkSize, candidateCount);
3659 const size_t chunkEnd = min(chunkBegin + chunkSize, candidateCount);
3660 result.chunkCandidates(chunkBegin, chunkEnd);
3661 return result;
3662 }
3663
3664 Buffer<detail::EntitySlot> slots{};
3665 Buffer<EntityID> entityIDs{};
3666 EntityID::Index firstAvailableSlotIndex = EntityID::INVALID_INDEX;
3667 HashMap<std::type_index, detail::ComponentStorage> componentPools{};
3668 Array<Optional<detail::ComponentStorage>, sizeof...(KnownComponents)> knownComponentPools{};
3669#if !defined(NDEBUG) || defined(GREM_USE_RELEASE_ASSERTIONS)
3670 SharedPointer<Atomic<size_t>> currentIteratorGeneration = SharedPointer<Atomic<size_t>>::create();
3671#endif
3672};
3673
3674template <typename EntReg>
3676 if (entityID) {
3677 registry.destroyEntity(entityID);
3678 }
3679}
3680
3681template <typename EntReg>
3683 entityID = registry.setEntityFlags(entityID, newFlags);
3684 return entityID;
3685}
3686
3687template <typename EntReg>
3688template <component T, typename... Args>
3689inline T& EntityBuilder<EntReg>::addComponent(Args&&... args) {
3690 return registry.template addComponent<T>(entityID, std::forward<Args>(args)...);
3691}
3692
3693template <typename EntReg>
3694template <component T, typename... Args>
3696 return registry.template addComponentIfMissing<T>(entityID, std::forward<Args>(args)...);
3697}
3698
3699template <typename EntReg>
3700template <component T>
3702 return registry.template addOrAssignComponent<std::decay_t<T>>(entityID, std::forward<T>(value));
3703}
3704
3705template <typename EntReg>
3706template <component T>
3708 return registry.template addOrAssignComponent<T>(entityID, value);
3709}
3710
3711template <typename EntReg>
3712template <component T>
3714 return registry.template removeComponent<T>(entityID);
3715}
3716
3717template <typename EntReg>
3719 return registry.removeAllComponents(entityID);
3720}
3721
3722template <typename EntReg>
3723template <component T>
3724inline bool EntityBuilder<EntReg>::hasComponent() const noexcept {
3725 return registry.template hasComponent<T>(entityID);
3726}
3727
3728template <typename EntReg>
3729template <component T>
3731 return registry.template getComponent<T>(entityID);
3732}
3733
3734template <typename EntReg>
3735template <component T>
3737 return registry.template getComponent<T>(entityID);
3738}
3739
3740template <typename EntReg>
3741template <component T, typename U>
3742inline T EntityBuilder<EntReg>::getComponentOr(U&& defaultValue) const {
3743 return registry.template getComponentOr<T>(entityID, std::forward<U>(defaultValue));
3744}
3745
3746template <typename EntReg>
3747template <component T>
3749 return registry.template findComponent<T>(entityID);
3750}
3751
3752template <typename EntReg>
3753template <component T>
3754inline const T* EntityBuilder<EntReg>::findComponent() const noexcept {
3755 return registry.template findComponent<T>(entityID);
3756}
3757
3758} // namespace grem::execution
3759
3760template <>
3761struct std::hash<grem::execution::EntityID> {
3762 [[nodiscard]] std::size_t operator()(const grem::execution::EntityID& entityID) const {
3763 return hasher(entityID.getIdentifier());
3764 }
3765
3766private:
3767 [[no_unique_address]] std::hash<typename grem::execution::EntityID::Identifier> hasher;
3768};
3769
3770#endif
#define GREM_ASSERT(expression)
Definition assertions.hpp:77
#define GREM_ALWAYS_INLINE
Definition attributes.hpp:10
const_pointer const_iterator
Definition Buffer.hpp:43
pointer iterator
Definition Buffer.hpp:42
Optional value type that holds either a value or no value.
Definition Optional.hpp:58
constexpr T value_or(U &&defaultValue) const &
Get the underlying value, or a fallback value in case the optional is empty.
Definition Optional.hpp:453
constexpr T & emplace(Args &&... args)
Construct a new underlying value, destroying the old value if present.
Definition Optional.hpp:706
Tightly packed set of elements with stable IDs, supporting fast iteration as well as amortized O(1) i...
Definition Registry.hpp:175
Definition Span.hpp:146
constexpr detail::subspan_type_t< T, EXTENT, Offset, N > subspan() const
Definition Span.hpp:284
Reference to an EntityRegistry's pool of instances of a specific component type.
Definition EntityRegistry.hpp:1713
typename iterator::difference_type difference_type
Definition EntityRegistry.hpp:1720
GREM_ALWAYS_INLINE bool remove(EntityID id) noexcept
Erase the component instance associated with a specific entity.
Definition EntityRegistry.hpp:1972
detail::SingleComponentIterator< Component > iterator
Definition EntityRegistry.hpp:1715
typename iterator::reference reference
Definition EntityRegistry.hpp:1718
GREM_ALWAYS_INLINE size_type removeFromAllEntities() noexcept
Erase all associated component instances.
Definition EntityRegistry.hpp:1986
friend class ComponentPool
Definition EntityRegistry.hpp:2000
GREM_ALWAYS_INLINE constexpr reference operator[](EntityID id) const
Definition EntityRegistry.hpp:1753
typename iterator::value_type value_type
Definition EntityRegistry.hpp:1717
GREM_ALWAYS_INLINE constexpr ComponentPool() noexcept=default
Construct an invalid component pool reference.
GREM_ALWAYS_INLINE Component & get(EntityID id) const
Get the component instance associated with a specific entity.
Definition EntityRegistry.hpp:1791
GREM_ALWAYS_INLINE Component & addOrAssign(EntityID id, Component &&value)
Add a component instance associated with a specific entity, or assign to it if it already has one.
Definition EntityRegistry.hpp:1929
size_t size_type
Definition EntityRegistry.hpp:1719
GREM_ALWAYS_INLINE constexpr sentinel end() const noexcept
Definition EntityRegistry.hpp:1749
GREM_ALWAYS_INLINE Component * addIfMissing(EntityID id, Args &&... args)
Add a component instance associated with a specific entity if it doesn't already have one.
Definition EntityRegistry.hpp:1899
Component component_type
Definition EntityRegistry.hpp:1721
GREM_ALWAYS_INLINE Component & addOrAssign(EntityID id, const Component &value)
Add a component instance associated with a specific entity, or assign to it if it already has one.
Definition EntityRegistry.hpp:1956
GREM_ALWAYS_INLINE constexpr bool has(EntityID id) const
Check if the referenced pool has a component instance associated with a specific entity.
Definition EntityRegistry.hpp:1772
detail::SingleComponentSentinel sentinel
Definition EntityRegistry.hpp:1716
GREM_ALWAYS_INLINE Component & add(EntityID id, Args &&... args)
Add a component instance associated with a specific entity.
Definition EntityRegistry.hpp:1869
GREM_ALWAYS_INLINE Component * find(EntityID id) const
Try to get the component instance associated with a specific entity.
Definition EntityRegistry.hpp:1832
GREM_ALWAYS_INLINE Component getOr(EntityID id, U &&defaultValue) const
Get the component instance associated with a specific entity, or a default value in case the entity d...
Definition EntityRegistry.hpp:1815
GREM_ALWAYS_INLINE constexpr iterator begin() const noexcept
Definition EntityRegistry.hpp:1738
friend class EntityRegistry
Entity registry used by a Simulation.
Definition EntityRegistry.hpp:1997
ptrdiff_t difference_type
Definition EntityRegistry.hpp:1139
GREM_ALWAYS_INLINE constexpr size_t getCandidateCount() const noexcept
Get an upper bound estimate on the number of entities in the range, which is equal to the exact numbe...
Definition EntityRegistry.hpp:1220
typename iterator::reference reference
Definition EntityRegistry.hpp:1137
GREM_ALWAYS_INLINE constexpr reference operator[](EntityID id) const
Definition EntityRegistry.hpp:1243
GREM_ALWAYS_INLINE auto & getComponent(EntityID id) const
Get a specific component of a specific entity in the range.
Definition EntityRegistry.hpp:1278
detail::SingleComponentIterator< Component > iterator
Definition EntityRegistry.hpp:1134
meta::type_list_concat_t< typename detail::entities_extract_components< ComponentsAndExclusions >::ExcludedComponents... > ExcludedComponents
List of components excluded by the range, provided as a meta::TypeList.
Definition EntityRegistry.hpp:1126
GREM_ALWAYS_INLINE constexpr Entities() noexcept=default
Construct an empty entity range.
GREM_ALWAYS_INLINE bool hasComponent(EntityID id) const noexcept
Check if the range contains a specific entity with a specific component.
Definition EntityRegistry.hpp:1260
GREM_ALWAYS_INLINE constexpr bool empty() const noexcept
Definition EntityRegistry.hpp:1210
typename iterator::value_type value_type
Definition EntityRegistry.hpp:1136
GREM_ALWAYS_INLINE constexpr size_type size() const noexcept
Definition EntityRegistry.hpp:1206
GREM_ALWAYS_INLINE constexpr Component * data() const noexcept
Definition EntityRegistry.hpp:1202
GREM_ALWAYS_INLINE auto & getComponentAtEntityIndexUnsafe(EntityID::Index slotIndex) const
Get a specific component of the entity in a specific slot of the underlying EntityRegistry.
Definition EntityRegistry.hpp:1366
GREM_ALWAYS_INLINE constexpr Entities(const iterator &first, const iterator &last) noexcept
Construct an entity subrange from an iterator pair.
Definition EntityRegistry.hpp:1172
GREM_ALWAYS_INLINE EntityID getEntityIDAtEntityIndexUnsafe(EntityID::Index slotIndex) const
Get the entity handle of the entity in a specific slot of the underlying EntityRegistry.
Definition EntityRegistry.hpp:1343
size_t size_type
Definition EntityRegistry.hpp:1138
GREM_ALWAYS_INLINE auto * findComponent(EntityID id) const noexcept
Try to get a specific component of a specific entity in the range.
Definition EntityRegistry.hpp:1324
detail::SingleComponentSentinel sentinel
Definition EntityRegistry.hpp:1135
GREM_ALWAYS_INLINE constexpr sentinel end() const noexcept
Definition EntityRegistry.hpp:1198
meta::type_list_concat_t< typename detail::entities_extract_components< ComponentsAndExclusions >::IncludedComponents... > IncludedComponents
List of components required by the range, provided as a meta::TypeList.
Definition EntityRegistry.hpp:1123
GREM_ALWAYS_INLINE constexpr bool containsEntity(EntityID id) const
Check if the range contains a specific entity.
Definition EntityRegistry.hpp:1232
GREM_ALWAYS_INLINE constexpr iterator begin() const noexcept
Definition EntityRegistry.hpp:1184
meta::type_list_concat_t< typename detail::entities_extract_components< ComponentsAndExclusions >::MutableComponents... > MutableComponents
List of non-const components required by the range, provided as a meta::TypeList.
Definition EntityRegistry.hpp:1117
meta::type_list_concat_t< typename detail::entities_extract_components< ComponentsAndExclusions >::ImmutableComponents... > ImmutableComponents
List of const components required by the range, provided as a meta::TypeList.
Definition EntityRegistry.hpp:1120
GREM_ALWAYS_INLINE auto getComponentOr(EntityID id, U &&defaultValue) const
Get a specific component of a specific entity in the range, with a default value in case the entity d...
Definition EntityRegistry.hpp:1303
friend class EntityRegistry
Entity registry used by a Simulation.
Definition EntityRegistry.hpp:1380
View of entities in an EntityRegistry that have all of the required components and none of the exclud...
Definition EntityRegistry.hpp:815
detail::MultiComponentIterator< IncludedComponents, ExcludedComponents > iterator
Definition EntityRegistry.hpp:835
typename iterator::reference reference
Definition EntityRegistry.hpp:838
GREM_ALWAYS_INLINE constexpr bool containsEntity(EntityID id) const
Check if the range contains a specific entity.
Definition EntityRegistry.hpp:900
GREM_ALWAYS_INLINE constexpr size_type getCandidateCount() const noexcept
Get an upper bound estimate on the number of entities in the range.
Definition EntityRegistry.hpp:888
ptrdiff_t difference_type
Definition EntityRegistry.hpp:840
GREM_ALWAYS_INLINE constexpr Entities() noexcept=default
Construct an empty entity range.
typename iterator::value_type value_type
Definition EntityRegistry.hpp:837
meta::type_list_concat_t< typename detail::entities_extract_components< ComponentsAndExclusions >::ExcludedComponents... > ExcludedComponents
List of components excluded by the range, provided as a meta::TypeList.
Definition EntityRegistry.hpp:827
GREM_ALWAYS_INLINE constexpr iterator begin() const noexcept
Definition EntityRegistry.hpp:869
GREM_ALWAYS_INLINE auto getComponentOr(EntityID id, U &&defaultValue) const
Get a specific component of a specific entity in the range, or a default value in case the entity doe...
Definition EntityRegistry.hpp:975
GREM_ALWAYS_INLINE auto * findComponent(EntityID id) const noexcept
Try to get a specific component of a specific entity in the range.
Definition EntityRegistry.hpp:996
meta::type_list_concat_t< typename detail::entities_extract_components< ComponentsAndExclusions >::MutableComponents... > MutableComponents
List of non-const components required by the range, provided as a meta::TypeList.
Definition EntityRegistry.hpp:818
GREM_ALWAYS_INLINE constexpr reference operator[](EntityID id) const
Definition EntityRegistry.hpp:912
GREM_ALWAYS_INLINE bool hasComponent(EntityID id) const noexcept
Check if the range contains a specific entity with a specific component.
Definition EntityRegistry.hpp:932
GREM_ALWAYS_INLINE EntityID getEntityIDAtEntityIndexUnsafe(EntityID::Index slotIndex) const
Get the entity handle of the entity in a specific slot of the underlying EntityRegistry.
Definition EntityRegistry.hpp:1015
meta::type_list_concat_t< typename detail::entities_extract_components< ComponentsAndExclusions >::IncludedComponents... > IncludedComponents
List of components required by the range, provided as a meta::TypeList.
Definition EntityRegistry.hpp:824
meta::type_list_concat_t< typename detail::entities_extract_components< ComponentsAndExclusions >::ImmutableComponents... > ImmutableComponents
List of const components required by the range, provided as a meta::TypeList.
Definition EntityRegistry.hpp:821
GREM_ALWAYS_INLINE auto & getComponent(EntityID id) const
Get a specific component of a specific entity in the range.
Definition EntityRegistry.hpp:950
detail::MultiComponentSentinel sentinel
Definition EntityRegistry.hpp:836
GREM_ALWAYS_INLINE auto & getComponentAtEntityIndexUnsafe(EntityID::Index slotIndex) const
Get a specific component of the entity in a specific slot of the underlying EntityRegistry.
Definition EntityRegistry.hpp:1038
GREM_ALWAYS_INLINE constexpr sentinel end() const noexcept
Definition EntityRegistry.hpp:878
size_t size_type
Definition EntityRegistry.hpp:839
friend class EntityRegistry
Entity registry used by a Simulation.
Definition EntityRegistry.hpp:1054
Temporary reference to an incomplete entity that is currently being built inside of an EntityRegistry...
Definition EntityRegistry.hpp:2033
GREM_ALWAYS_INLINE constexpr EntityBuilder(EntReg &registry, EntityID entityID) noexcept
Construct an entity builder.
Definition EntityRegistry.hpp:2041
GREM_ALWAYS_INLINE EntityID build()
Definition EntityRegistry.hpp:2293
GREM_ALWAYS_INLINE EntityID getEntityID() const noexcept
Definition EntityRegistry.hpp:2096
GREM_ALWAYS_INLINE const EntityRegistry< N > & getRegistry() const noexcept
Definition EntityRegistry.hpp:2087
EntityBuilder & operator=(EntityBuilder &&)=delete
EntityID setEntityFlags(EntityID::Flags newFlags)
GREM_ALWAYS_INLINE EntityRegistry< N > & getRegistry() noexcept
Definition EntityRegistry.hpp:2078
EntityBuilder(EntityBuilder &&other) noexcept
Definition EntityRegistry.hpp:2052
EntityBuilder & operator=(const EntityBuilder &)=delete
Handle to a specific entity in a registry.
Definition EntityRegistry.hpp:71
static constexpr Index INVALID_INDEX
Reserved index value for an invalid entity handle.
Definition EntityRegistry.hpp:78
GREM_ALWAYS_INLINE constexpr Generation getGeneration() const noexcept
Get the generation counter value of the entity.
Definition EntityRegistry.hpp:134
GREM_ALWAYS_INLINE constexpr Index getIndex() const noexcept
Get the index of the entity's generation slot.
Definition EntityRegistry.hpp:125
uint64_t Identifier
Underlying value type.
Definition EntityRegistry.hpp:73
GREM_ALWAYS_INLINE constexpr Identifier getIdentifier() const noexcept
Get a unique identifier for the underlying representation of the entity handle.
Definition EntityRegistry.hpp:116
static constexpr Flags ALL_FLAGS
Maximum valid set of user-defined flags.
Definition EntityRegistry.hpp:81
GREM_ALWAYS_INLINE constexpr Flags getFlags() const noexcept
Get the user-defined flags of the entity.
Definition EntityRegistry.hpp:143
static constexpr Index MAX_INDEX
Maximum valid index value.
Definition EntityRegistry.hpp:79
uint16_t Flags
User-defined flags type.
Definition EntityRegistry.hpp:76
GREM_ALWAYS_INLINE constexpr std::strong_ordering operator<=>(const EntityID &other) const noexcept=default
Compare this handle to another.
uint16_t Generation
Generation counter type.
Definition EntityRegistry.hpp:75
GREM_ALWAYS_INLINE constexpr bool operator==(const EntityID &other) const noexcept=default
Compare this handle to another for equality.
GREM_ALWAYS_INLINE constexpr EntityID() noexcept=default
Construct an invalid entity handle.
static constexpr Generation MAX_GENERATION
Maximum valid generation counter value.
Definition EntityRegistry.hpp:80
uint32_t Index
Index type.
Definition EntityRegistry.hpp:74
Dynamic container of entities with stable EntityID handles and associated component instances,...
Definition EntityRegistry.hpp:2323
GREM_ALWAYS_INLINE const_iterator cend() const noexcept
Definition EntityRegistry.hpp:2776
GREM_ALWAYS_INLINE const T * findComponent(EntityID id) const noexcept
Try to get a specific component of an entity.
Definition EntityRegistry.hpp:3142
EntityRegistry & operator=(const EntityRegistry &other)
Copy assignment.
Definition EntityRegistry.hpp:2364
EntityRegistry(EntityRegistry &&other) noexcept
Move constructor.
Definition EntityRegistry.hpp:2359
GREM_ALWAYS_INLINE const_iterator cbegin() const noexcept
Definition EntityRegistry.hpp:2764
EntityID & reference
Definition EntityRegistry.hpp:2331
GREM_ALWAYS_INLINE bool containsEntityAtIndex(EntityID::Index slotIndex) const
Check if the registry contains an entity in a specific slot.
Definition EntityRegistry.hpp:2801
GREM_ALWAYS_INLINE T & addOrAssignComponent(EntityID id, T &&value)
Add a component to an entity, or assign to it if it already has one.
Definition EntityRegistry.hpp:2914
GREM_ALWAYS_INLINE bool removeComponent(EntityID id) noexcept
Erase a component from an entity.
Definition EntityRegistry.hpp:2960
GREM_ALWAYS_INLINE T * findComponent(EntityID id) noexcept
Try to get a specific component of an entity.
Definition EntityRegistry.hpp:3098
GREM_ALWAYS_INLINE const_iterator end() const noexcept
Definition EntityRegistry.hpp:2772
EntityBuilder< EntityRegistry > createEntity(EntityID::Flags flags={})
Create a new entity.
Definition EntityRegistry.hpp:2470
EntityRegistry() noexcept=default
Construct an empty entity registry.
GREM_ALWAYS_INLINE T * addComponentIfMissing(EntityID id, Args &&... args)
Add a component to an entity if it doesn't already have it.
Definition EntityRegistry.hpp:2887
size_type GREM_ALWAYS_INLINE removeComponentFromAllEntities() noexcept
Erase a specific component from all entities.
Definition EntityRegistry.hpp:3002
GREM_ALWAYS_INLINE iterator end() noexcept
Definition EntityRegistry.hpp:2768
friend size_type erase_if(EntityRegistry &c, Predicate predicate)
Destroy all entities in an entity registry whose entity handles match a predicate,...
Definition EntityRegistry.hpp:3542
GREM_ALWAYS_INLINE const T & getComponent(EntityID id) const
Get a specific component of an entity.
Definition EntityRegistry.hpp:3055
typename Buffer< EntityID >::const_iterator const_iterator
Definition EntityRegistry.hpp:2338
size_type destroyEntities() noexcept
Destroy all entities that have all of the required components and none of the excluded components,...
Definition EntityRegistry.hpp:3513
GREM_ALWAYS_INLINE T & addComponent(EntityID id, Args &&... args)
Add a component to an entity.
Definition EntityRegistry.hpp:2861
size_t size_type
Definition EntityRegistry.hpp:2335
GREM_ALWAYS_INLINE Entities< ComponentsAndExclusions... > getEntitiesChunk(size_t chunkIndex, size_t chunkCount) const noexcept
Get a specific chunk of the entites in the registry that have all of the required components and none...
Definition EntityRegistry.hpp:3408
GREM_ALWAYS_INLINE bool empty() const noexcept
Check if the registry is empty.
Definition EntityRegistry.hpp:2820
ptrdiff_t difference_type
Definition EntityRegistry.hpp:2336
EntityID setEntityFlags(EntityID id, EntityID::Flags newFlags)
Update the flags embedded in an entity's handle.
Definition EntityRegistry.hpp:2650
void clear() noexcept
Destroy all entities and erase all of their associated components from the registry.
Definition EntityRegistry.hpp:2426
GREM_ALWAYS_INLINE const T & getComponentAtEntityIndexUnsafe(EntityID::Index slotIndex) const
Get a specific component of the entity in a specific slot.
Definition EntityRegistry.hpp:3242
GREM_ALWAYS_INLINE EntityID getEntityIDAtEntityIndexUnsafe(EntityID::Index slotIndex) const
Get the entity handle of the entity in a specific slot.
Definition EntityRegistry.hpp:3185
const EntityID & const_reference
Definition EntityRegistry.hpp:2332
GREM_ALWAYS_INLINE iterator begin() noexcept
Definition EntityRegistry.hpp:2756
GREM_ALWAYS_INLINE T & getComponentAtEntityIndexUnsafe(EntityID::Index slotIndex)
Get a specific component of the entity in a specific slot.
Definition EntityRegistry.hpp:3206
GREM_ALWAYS_INLINE size_type size() const noexcept
Get the number of valid entity handles currently in the registry.
Definition EntityRegistry.hpp:2810
~EntityRegistry()
Destructor.
Definition EntityRegistry.hpp:2345
GREM_ALWAYS_INLINE ComponentPool< T > getComponentPool() noexcept
Get a reference to a specific component pool if it exists.
Definition EntityRegistry.hpp:3460
GREM_ALWAYS_INLINE T & addOrAssignComponent(EntityID id, const T &value)
Add a component to an entity, or assign to it if it already has one.
Definition EntityRegistry.hpp:2941
GREM_ALWAYS_INLINE const_iterator begin() const noexcept
Definition EntityRegistry.hpp:2760
const EntityID * const_pointer
Definition EntityRegistry.hpp:2334
EntityRegistry & operator=(EntityRegistry &&other) noexcept
Move assignment.
Definition EntityRegistry.hpp:2406
GREM_ALWAYS_INLINE bool hasComponent(EntityID id) const noexcept
Check if an entity has a specific component.
Definition EntityRegistry.hpp:3017
EntityID value_type
Definition EntityRegistry.hpp:2330
EntityRegistry(const EntityRegistry &other)
Copy constructor.
Definition EntityRegistry.hpp:2354
GREM_ALWAYS_INLINE Entities< ComponentsAndExclusions... > getEntities() const noexcept
Get a view of all entites in the registry that have all of the required components and none of the ex...
Definition EntityRegistry.hpp:3312
GREM_ALWAYS_INLINE bool destroyEntity(EntityID id) noexcept
Destroy an entity and all of its associated components.
Definition EntityRegistry.hpp:2699
GREM_ALWAYS_INLINE T getComponentOr(EntityID id, U &&defaultValue) const
Get a specific component of an entity, or a default value in case the entity doesn't exist or doesn't...
Definition EntityRegistry.hpp:3078
GREM_ALWAYS_INLINE bool containsEntity(EntityID id) const noexcept
Check if the registry contains a specific entity.
Definition EntityRegistry.hpp:2788
GREM_ALWAYS_INLINE Entities< ComponentsAndExclusions... > getEntities() noexcept
Get a view of all entites in the registry that have all of the required components and none of the ex...
Definition EntityRegistry.hpp:3284
GREM_ALWAYS_INLINE Entities< ComponentsAndExclusions... > getEntitiesChunk(size_t chunkIndex, size_t chunkCount) noexcept
Get a specific chunk of the entites in the registry that have all of the required components and none...
Definition EntityRegistry.hpp:3373
EntityBuilder< EntityRegistry > createEntityAtID(EntityID id)
Create a new entity with a specific entity handle.
Definition EntityRegistry.hpp:2551
GREM_ALWAYS_INLINE size_type max_size() const noexcept
Get the maximum number of simultaneous valid entity handles that the registry can contain.
Definition EntityRegistry.hpp:2830
typename Buffer< EntityID >::iterator iterator
Definition EntityRegistry.hpp:2337
GREM_ALWAYS_INLINE T & getComponent(EntityID id)
Get a specific component of an entity.
Definition EntityRegistry.hpp:3034
GREM_ALWAYS_INLINE ComponentPool< const T > getComponentPool() const noexcept
Get a reference to a specific component pool if it exists.
Definition EntityRegistry.hpp:3490
GREM_ALWAYS_INLINE bool removeAllComponents(EntityID id) noexcept
Erase all components from an entity.
Definition EntityRegistry.hpp:2975
GREM_ALWAYS_INLINE ComponentPool< T > createComponentPool()
Ensure that the component pool for a specific component type has been created, and get a reference to...
Definition EntityRegistry.hpp:3431
bool destroyEntityAtIndex(EntityID::Index slotIndex) noexcept
Destroy the entity in a specific slot and all of its associated components.
Definition EntityRegistry.hpp:2718
Concept that checks if a given type is a valid component type that can be stored and associated with ...
Definition component.hpp:21
Definition concepts.hpp:106
Definition concepts.hpp:35
@ T
't'
Definition keyboard.hpp:90
@ I
'i'
Definition keyboard.hpp:79
Definition Chunk.hpp:19
EntityBuilder(Registry &, EntityID) -> EntityBuilder< Registry >
constexpr decltype(auto) get(EntityTable< Row, Allocator > &t, std::size_t rowIndex)
Definition EntityTable.hpp:518
Definition aliases.hpp:16
typename type_list_concat< Lists... >::type type_list_concat_t
Concatenation of a sequence of specializations of meta::TypeList into a single meta::TypeList.
Definition metaprogramming.hpp:604
constexpr std::size_t type_list_index_v
Index of the first occurence of a specific type in a specialization of meta::TypeList.
Definition metaprogramming.hpp:509
constexpr std::size_t type_list_size_v
Number of types in a specialization of meta::TypeList.
Definition metaprogramming.hpp:399
constexpr bool type_list_empty_v
Whether a specialization of meta::TypeList is empty or not.
Definition metaprogramming.hpp:418
constexpr Type< T > TYPE
Wrapper value for a type identity wrapper.
Definition metaprogramming.hpp:339
constexpr TypeList< Ts... > TYPE_LIST
Wrapper value for a compile-time list of types.
Definition metaprogramming.hpp:357
constexpr auto unqualified_type_name_v
Unqualified name of a type.
Definition metaprogramming.hpp:1526
constexpr bool type_list_contains_v
Whether a specialization of meta::TypeList contains a specific type.
Definition metaprogramming.hpp:475
execution::EntityID EntityID
Opaque handle to a specific entity in a Simulation's EntityRegistry.
Definition EntityID.hpp:16
Definition aliases.hpp:9
Array(T, Us...) -> Array< T, 1+sizeof...(Us)>
constexpr auto count(input_range auto &&range, const auto &value)
Definition algorithms.hpp:234
GREM_ALWAYS_INLINE constexpr decltype(auto) clamp(T &&value, Low &&minValue, High &&maxValue)
Clamp a value to a specific interval.
Definition fundamentals.hpp:630
constexpr bool operator==(const Indirect< A, AllocatorA > &a, const Indirect< B, AllocatorB > &b)
Definition Indirect.hpp:246
constexpr auto move(input_range auto &&range, auto outputIterator)
Definition algorithms.hpp:669
Tuple(Ts...) -> Tuple< Ts... >
constexpr Offset2D operator*(Offset2D a, int32_t b) noexcept
Definition extents.hpp:692
Span(R &&range) -> Span< std::remove_reference_t< decltype(*std::data(range))> >
GREM_ALWAYS_INLINE constexpr decltype(auto) max(A &&a, B &&b)
Get the greater of two values, or the first value if they are equivalent.
Definition fundamentals.hpp:598
GREM_ALWAYS_INLINE constexpr decltype(auto) min(A &&a, B &&b)
Get the smaller of two values, or the first value if they are equivalent.
Definition fundamentals.hpp:585
Definition Array.hpp:20
static constexpr T MAX
Definition fundamentals.hpp:29
Compile-time list of types.
Definition metaprogramming.hpp:347
std::size_t operator()(const grem::execution::EntityID &entityID) const
Definition EntityRegistry.hpp:3762