Crimson Engine 1.0.0
A high-performance C++20 game engine prototype showcasing a custom ECS, Vulkan renderer, and ImGui editor.
Loading...
Searching...
No Matches
Registry.hpp
Go to the documentation of this file.
1#pragma once
2#include "EntityManager.hpp"
4#include <unordered_map>
5#include <typeindex>
6#include <functional>
7#include <vector>
8#include <memory>
9
10#include "core/EngineAPI.hpp"
11
12// Simple runtime component type id registry
17ENGINE_API std::unordered_map<std::type_index, std::size_t>& g_componentTypeMap();
18
24ENGINE_API std::size_t registerComponentType(std::type_index idx);
25
30class Registry {
31public:
35 Registry() = default;
36
38 using ComponentAddedCallback = std::function<void(Entity)>;
40 using ComponentRemovedCallback = std::function<void(Entity)>;
41
46 Entity create() { return entities.create(); }
47
52 void destroy(Entity e) {
53 if (e.getId() == Entity::INVALID_ENTITY) {
54 return;
55 }
56
57 ComponentMask mask = entities.getMask(e);
58 for (auto& [id, storage] : storages) {
59 if (!mask.test(id)) {
60 continue;
61 }
62
63 storage->removeEntity(e);
64
65 auto callbacksIt = componentRemovedCallbacks.find(id);
66 if (callbacksIt != componentRemovedCallbacks.end()) {
67 for (auto& cb : callbacksIt->second) {
68 cb(e);
69 }
70 }
71 }
72
73 entities.destroy(e);
74 }
75
79 void clear() {
80 auto aliveCopy = entities.getAlive();
81 for (auto id : aliveCopy) {
82 destroy(Entity(id));
83 }
84 storages.clear();
85 }
86
92 bool isValid(Entity e) const {
93 if (e.getId() == Entity::INVALID_ENTITY) return false;
94 const auto& alive = entities.getAlive();
95 return std::find(alive.begin(), alive.end(), e.getId()) != alive.end();
96 }
97
105 template<typename T>
106 T& emplace(Entity e, T&& comp) {
108 getStorage<T>()->add(e, std::forward<T>(comp));
109
110 auto id = registerComponentType(typeid(T));
111 entities.getMask(e).set(id);
112
113 if (componentAddedCallbacks.find(id) != componentAddedCallbacks.end()) {
114 for (auto& cb : componentAddedCallbacks[id]) cb(e);
115 }
116
117 return getStorage<T>()->get(e);
118 }
119
125 template<typename T>
126 void remove(Entity e) {
127 auto* storage = getStorage<T>();
128 if (storage && storage->has(e)) {
129 storage->remove(e);
130 auto id = registerComponentType(typeid(T));
131 entities.getMask(e).reset(id);
132
134 for (auto& cb : componentRemovedCallbacks[id]) cb(e);
135 }
136 }
137 }
138
145 template<typename T>
146 T* get(Entity e) {
147 auto* storage = getStorage<T>();
148 if (!storage || !storage->has(e)) return nullptr;
149 return &storage->get(e);
150 }
151
158 template<typename T>
160 T* ptr = get<T>(e);
161 if (!ptr) throw std::runtime_error("Component missing!");
162 return *ptr;
163 }
164
171 template<typename T>
172 bool has(Entity e) {
173 auto* storage = getStorage<T>();
174 return storage && storage->has(e);
175 }
176
182 template<typename T>
184 auto id = registerComponentType(typeid(T));
185 componentAddedCallbacks[id].push_back(cb);
186 }
187
193 template<typename T>
195 auto id = registerComponentType(typeid(T));
196 componentRemovedCallbacks[id].push_back(cb);
197 }
198
204 template<typename... Components>
205 class View {
206 public:
212 View(Registry& reg, IStorage* sm) : registry(reg), smallest(sm) {}
213
218 struct Iterator {
220 const std::vector<Entity>& entities;
221 size_t index;
222
224 void advance() {
225 while (index < entities.size()) {
226 Entity e = entities[index];
227 if (e.getId() != Entity::INVALID_ENTITY && (registry.has<Components>(e) && ...)) {
228 break;
229 }
230 index++;
231 }
232 }
233
235 bool operator!=(const Iterator& other) const { return index != other.index; }
236
238 void operator++() {
239 index++;
240 advance();
241 }
242
247 auto operator*() const {
248 Entity e = entities[index];
249 return std::tuple_cat(std::make_tuple(e), std::forward_as_tuple(*registry.get<Components>(e)...));
250 }
251 };
252
255 if (!smallest) return end();
256 Iterator it{ registry, smallest->getEntities(), 0 };
257 it.advance();
258 return it;
259 }
260
263 static const std::vector<Entity> empty;
264 const std::vector<Entity>& ents = smallest ? smallest->getEntities() : empty;
265 return Iterator{ registry, ents, ents.size() };
266 }
267
268 private:
271 };
272
278 template<typename... Components>
279 auto view() {
280 ensureStorages<Components...>();
281 IStorage* smallest = getSmallestStorage<Components...>();
282 return View<Components...>(*this, smallest);
283 }
284
285private:
289 std::unordered_map<std::size_t, std::unique_ptr<IStorage>> storages;
291 std::unordered_map<std::size_t, std::vector<ComponentAddedCallback>> componentAddedCallbacks;
293 std::unordered_map<std::size_t, std::vector<ComponentRemovedCallback>> componentRemovedCallbacks;
294
299 template<typename T>
301 std::size_t id = registerComponentType(typeid(T));
302 if (storages.find(id) == storages.end()) {
303 storages[id] = std::make_unique<ComponentStorage<T>>();
304 }
305 }
306
312 template<typename T>
314 std::size_t id = registerComponentType(typeid(T));
315 auto it = storages.find(id);
316 if (it == storages.end()) return nullptr;
317 return static_cast<ComponentStorage<T>*>(it->second.get());
318 }
319
324 template<typename... Components>
326
332 template<typename T>
334
342 template<typename First, typename Second, typename... Rest>
345 IStorage* b = getSmallestStorage<Second, Rest...>();
346 if (!a) return b;
347 if (!b) return a;
348 return (a->size() < b->size()) ? a : b;
349 }
350};
#define ENGINE_API
Definition EngineAPI.hpp:10
std::bitset< MAX_COMPONENTS > ComponentMask
Bitmask representing component registration status.
Definition Entity.hpp:55
ENGINE_API std::unordered_map< std::type_index, std::size_t > & g_componentTypeMap()
Retrieves the global map of component types to unique numeric IDs.
Definition Registry.cpp:3
ENGINE_API std::size_t registerComponentType(std::type_index idx)
Registers or retrieves the unique ID for a component type.
Definition Registry.cpp:8
Template class storing components contiguously in memory for optimal cache usage.
Definition ComponentStorage.hpp:41
Lightweight identifier representing a game object in the Entity Component System.
Definition Entity.hpp:11
static constexpr IdType INVALID_ENTITY
Constant representing a null or invalid entity.
Definition Entity.hpp:16
IdType getId() const
Retrieve the raw identifier of the entity.
Definition Entity.hpp:32
Manages entity allocation, deallocation, component masks, and lifetime tracking.
Definition EntityManager.hpp:13
Zero-allocation filtered view over entities containing a specific set of components.
Definition Registry.hpp:205
IStorage * smallest
Definition Registry.hpp:270
Iterator end()
Returns ending view iterator.
Definition Registry.hpp:262
View(Registry &reg, IStorage *sm)
Construct a new View object.
Definition Registry.hpp:212
Registry & registry
Definition Registry.hpp:269
Iterator begin()
Returns beginning view iterator.
Definition Registry.hpp:254
ComponentStorage< T > * getStorage()
Retrieves storage class for component type.
Definition Registry.hpp:313
std::function< void(Entity)> ComponentAddedCallback
Callback function type invoked when a component is added.
Definition Registry.hpp:38
bool isValid(Entity e) const
Checks if an entity is alive and valid.
Definition Registry.hpp:92
bool has(Entity e)
Checks if an entity possesses a component of type T.
Definition Registry.hpp:172
T * get(Entity e)
Retrieves a pointer to a component of type T on an entity.
Definition Registry.hpp:146
std::unordered_map< std::size_t, std::vector< ComponentAddedCallback > > componentAddedCallbacks
Callbacks for component insertions.
Definition Registry.hpp:291
void remove(Entity e)
Removes a component of type T from an entity.
Definition Registry.hpp:126
T & getRef(Entity e)
Retrieves a reference to a component of type T on an entity. Throws if missing.
Definition Registry.hpp:159
void ensureStorage()
Ensures a component storage exists.
Definition Registry.hpp:300
std::unordered_map< std::size_t, std::vector< ComponentRemovedCallback > > componentRemovedCallbacks
Callbacks for component removals.
Definition Registry.hpp:293
EntityManager entities
Entity lifetime manager.
Definition Registry.hpp:287
void subscribeToAdded(ComponentAddedCallback cb)
Subscribes a callback to when a component of type T is added.
Definition Registry.hpp:183
void ensureStorages()
Ensures all given component type storages exist.
Definition Registry.hpp:325
std::unordered_map< std::size_t, std::unique_ptr< IStorage > > storages
Map of component storage classes keyed by type ID.
Definition Registry.hpp:289
std::function< void(Entity)> ComponentRemovedCallback
Callback function type invoked when a component is removed.
Definition Registry.hpp:40
void clear()
Destroys all entities and clears all component storages.
Definition Registry.hpp:79
Entity create()
Creates a new entity.
Definition Registry.hpp:46
auto view()
Generates a filtered view of entities containing the requested components.
Definition Registry.hpp:279
Registry()=default
Construct a new Registry object.
IStorage * getSmallestStorage()
Base case for retrieving smallest storage from parameter pack.
Definition Registry.hpp:333
void destroy(Entity e)
Destroys an entity, removing all its components.
Definition Registry.hpp:52
T & emplace(Entity e, T &&comp)
Emplaces a component on an entity.
Definition Registry.hpp:106
void subscribeToRemoved(ComponentRemovedCallback cb)
Subscribes a callback to when a component of type T is removed.
Definition Registry.hpp:194
IStorage * getSmallestStorage()
Recursively determines smallest storage among requested components.
Definition Registry.hpp:343
Polymorphic base interface for all component storage types, allowing untyped manipulation of componen...
Definition ComponentStorage.hpp:12
virtual size_t size() const =0
Returns the number of component instances stored.
Iterator over the entities matching the View filters.
Definition Registry.hpp:218
auto operator*() const
Dereferences the iterator to a tuple containing the entity and its component references.
Definition Registry.hpp:247
void advance()
Helper to advance iterator to next matching entity.
Definition Registry.hpp:224
void operator++()
Move iterator forward.
Definition Registry.hpp:238
size_t index
Definition Registry.hpp:221
Registry & registry
Definition Registry.hpp:219
const std::vector< Entity > & entities
Definition Registry.hpp:220
bool operator!=(const Iterator &other) const
Check iterator inequality.
Definition Registry.hpp:235