Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
View.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
15#pragma once
16
17// =============================================================================
18// Includes
19// =============================================================================
20
21// Project includes
22#include "../core/Types.hpp"
23#include "../core/Log.hpp"
24#include "Entity.hpp"
25#include "SparseSet.hpp"
26
27// Standard library
28#include <tuple>
29
30namespace esengine::ecs {
31
32// Forward declaration
33class Registry;
34
35// =============================================================================
36// ViewIterator
37// =============================================================================
38
48template<typename... Components>
50public:
52 using PoolsTuple = std::tuple<SparseSet<Components>*...>;
53
60 ViewIterator(const std::vector<Entity>* entities, usize index, PoolsTuple pools)
61 : entities_(entities), index_(index), pools_(pools) {
62 // Skip to first valid entity
63 if (entities_ && index_ < entities_->size()) {
64 skipInvalid();
65 }
66 }
67
72 Entity operator*() const {
73 // Kept as ES_ASSERT (not ES_VERIFY) deliberately: this is the ECS query
74 // hot path, and entities_ is structurally non-null for any iterator the
75 // View API hands out (begin()/end() always pass a live pointer). Only a
76 // manually default-constructed iterator violates it — a pure-logic
77 // misuse, not a runtime-data boundary — so no per-deref branch here.
78 ES_ASSERT(entities_ != nullptr, "Dereferencing null ViewIterator");
79 return (*entities_)[index_];
80 }
81
87 ++index_;
88 skipInvalid();
89 return *this;
90 }
91
97 bool operator!=(const ViewIterator& other) const {
98 return index_ != other.index_;
99 }
100
106 bool operator==(const ViewIterator& other) const {
107 return index_ == other.index_;
108 }
109
110private:
117 void skipInvalid() {
118 if (!entities_) return;
119 while (index_ < entities_->size()) {
120 Entity entity = (*entities_)[index_];
121 if (allHave(entity)) {
122 break;
123 }
124 ++index_;
125 }
126 }
127
133 bool allHave(Entity entity) const {
134 return allHaveImpl(entity, std::index_sequence_for<Components...>{});
135 }
136
143 template<usize... Is>
144 bool allHaveImpl(Entity entity, std::index_sequence<Is...>) const {
145 return (std::get<Is>(pools_)->contains(entity) && ...);
146 }
147
148 const std::vector<Entity>* entities_;
149 usize index_;
150 PoolsTuple pools_;
151};
152
153// =============================================================================
154// Multi-Component View
155// =============================================================================
156
183template<typename... Components>
184class View {
185public:
187 using Iterator = ViewIterator<Components...>;
189 using PoolsTuple = std::tuple<SparseSet<Components>*...>;
190
195 View(PoolsTuple pools) : pools_(pools) {
196 // Find the smallest pool to iterate over
197 findSmallestPool();
198 }
199
204 Iterator begin() const {
205 if (!smallest_) return end();
206 return Iterator(&smallest_->entities(), 0, pools_);
207 }
208
213 Iterator end() const {
214 if (!smallest_) return Iterator(nullptr, 0, pools_);
215 return Iterator(&smallest_->entities(), smallest_->size(), pools_);
216 }
217
218 // =========================================================================
219 // Component Access
220 // =========================================================================
221
228 template<typename T>
229 T& get(Entity entity) {
230 return std::get<SparseSet<T>*>(pools_)->get(entity);
231 }
232
234 template<typename T>
235 const T& get(Entity entity) const {
236 return std::get<SparseSet<T>*>(pools_)->get(entity);
237 }
238
244 std::tuple<Components&...> getAll(Entity entity) {
245 return std::tuple<Components&...>(
246 std::get<SparseSet<Components>*>(pools_)->get(entity)...);
247 }
248
249 // =========================================================================
250 // View Properties
251 // =========================================================================
252
257 bool empty() const {
258 return !smallest_ || smallest_->empty();
259 }
260
268 usize sizeHint() const {
269 return smallest_ ? smallest_->size() : 0;
270 }
271
272 // =========================================================================
273 // Functional Iteration
274 // =========================================================================
275
276 template<typename Func>
277 void each(Func&& func) {
278 if (!smallest_) return;
279
280 // Snapshot tolerates emplace/remove on the smallest pool during the callback.
281 std::vector<Entity> entities = smallest_->entities();
282
283 for (Entity entity : entities) {
284 if (!smallest_->contains(entity)) continue;
285 if (!allHaveExceptSmallest(entity)) continue;
286
287 if constexpr (std::is_invocable_v<Func, Entity, Components&...>) {
288 func(entity, getByEntity<Components>(entity)...);
289 } else if constexpr (std::is_invocable_v<Func, Components&...>) {
290 func(getByEntity<Components>(entity)...);
291 } else {
292 func(entity);
293 }
294 }
295 }
296
303 template<typename Func>
304 void eachLive(Func&& func) {
305 if (!smallest_) return;
306
307 const std::vector<Entity>& dense = smallest_->entities();
308 for (usize i = 0; i < dense.size(); ++i) {
309 Entity entity = dense[i];
310 if (!allHaveExceptSmallest(entity)) continue;
311
312 if constexpr (std::is_invocable_v<Func, Entity, Components&...>) {
313 func(entity, getByEntity<Components>(entity)...);
314 } else if constexpr (std::is_invocable_v<Func, Components&...>) {
315 func(getByEntity<Components>(entity)...);
316 } else {
317 func(entity);
318 }
319 }
320 }
321
322private:
323 template<typename T>
324 T& getByEntity(Entity entity) {
325 return std::get<SparseSet<T>*>(pools_)->getUnchecked(entity);
326 }
327
328 bool allHaveExceptSmallest(Entity entity) const {
329 return allHaveExceptSmallestImpl(entity, std::index_sequence_for<Components...>{});
330 }
331
332 template<usize... Is>
333 bool allHaveExceptSmallestImpl(Entity entity, std::index_sequence<Is...>) const {
334 return ((static_cast<SparseSetBase*>(std::get<Is>(pools_)) == smallest_ ||
335 std::get<Is>(pools_)->contains(entity)) && ...);
336 }
337
344 void findSmallestPool() {
345 smallest_ = nullptr;
346 usize minSize = std::numeric_limits<usize>::max();
347
348 findSmallestImpl(minSize, std::index_sequence_for<Components...>{});
349 }
350
351 template<usize... Is>
352 void findSmallestImpl(usize& minSize, std::index_sequence<Is...>) {
353 ((checkPool<Is>(minSize)), ...);
354 }
355
356 template<usize I>
357 void checkPool(usize& minSize) {
358 auto* pool = std::get<I>(pools_);
359 if (pool && pool->size() < minSize) {
360 minSize = pool->size();
361 smallest_ = static_cast<SparseSetBase*>(pool);
362 }
363 }
364
366 PoolsTuple pools_;
368 SparseSetBase* smallest_ = nullptr;
369};
370
371// =============================================================================
372// Single-Component View Specialization
373// =============================================================================
374
396template<typename T>
397class View<T> {
398public:
400 using Iterator = typename std::vector<Entity>::const_iterator;
401
406 explicit View(SparseSet<T>* pool) : pool_(pool) {}
407
412 Iterator begin() const { return pool_ ? pool_->begin() : Iterator{}; }
413
418 Iterator end() const { return pool_ ? pool_->end() : Iterator{}; }
419
425 T& get(Entity entity) { return pool_->get(entity); }
426
428 const T& get(Entity entity) const { return pool_->get(entity); }
429
435 std::tuple<T&> getAll(Entity entity) { return std::tuple<T&>(pool_->get(entity)); }
436
441 bool empty() const { return !pool_ || pool_->empty(); }
442
447 usize size() const { return pool_ ? pool_->size() : 0; }
448
453 usize sizeHint() const { return size(); }
454
466 template<typename Func>
467 void each(Func&& func) {
468 if (!pool_) return;
469
470 // Snapshot tolerates emplace/remove on the pool during the callback — the
471 // same contract as the multi-component view's each. Live forward iteration
472 // would re-visit mid-iteration emplaces and skip swap-popped removals.
473 std::vector<Entity> entities = pool_->entities();
474
475 for (Entity entity : entities) {
476 if (!pool_->contains(entity)) continue;
477 if constexpr (std::is_invocable_v<Func, Entity, T&>) {
478 func(entity, pool_->getUnchecked(entity));
479 } else if constexpr (std::is_invocable_v<Func, T&>) {
480 func(pool_->getUnchecked(entity));
481 } else {
482 func(entity);
483 }
484 }
485 }
486
493 template<typename Func>
494 void eachLive(Func&& func) {
495 if (!pool_) return;
496
497 const std::vector<Entity>& dense = pool_->entities();
498 for (usize i = 0; i < dense.size(); ++i) {
499 Entity entity = dense[i];
500 if constexpr (std::is_invocable_v<Func, Entity, T&>) {
501 func(entity, pool_->getUnchecked(entity));
502 } else if constexpr (std::is_invocable_v<Func, T&>) {
503 func(pool_->getUnchecked(entity));
504 } else {
505 func(entity);
506 }
507 }
508 }
509
510private:
512 SparseSet<T>* pool_;
513};
514
515} // namespace esengine::ecs
Entity utilities for the ECS system.
Logging utilities for ESEngine.
#define ES_ASSERT(condition, message)
Assert macro (debug builds only).
Definition Log.hpp:328
Sparse set data structure for efficient ECS component storage.
Core type definitions and utilities for ESEngine.
Central container for all entities and components.
Definition Registry.hpp:73
Sparse set container for efficient entity-component storage.
Iterator for multi-component views.
Definition View.hpp:49
bool operator==(const ViewIterator &other) const
Equality comparison.
Definition View.hpp:106
Entity operator*() const
Dereferences to get the current entity.
Definition View.hpp:72
bool operator!=(const ViewIterator &other) const
Inequality comparison.
Definition View.hpp:97
ViewIterator(const std::vector< Entity > *entities, usize index, PoolsTuple pools)
Constructs an iterator.
Definition View.hpp:60
std::tuple< SparseSet< Components > *... > PoolsTuple
Tuple type holding pointers to all component pools.
Definition View.hpp:52
ViewIterator & operator++()
Advances to the next matching entity.
Definition View.hpp:86
const T & get(Entity entity) const
Gets the component for an entity.
Definition View.hpp:428
void each(Func &&func)
Executes a function for each entity.
Definition View.hpp:467
typename std::vector< Entity >::const_iterator Iterator
Iterator type (directly iterates pool).
Definition View.hpp:400
usize size() const
Gets the exact number of entities in the view.
Definition View.hpp:447
void eachLive(Func &&func)
Like each(), but iterates the live dense array with no defensive copy.
Definition View.hpp:494
Iterator end() const
Returns iterator past the last entity.
Definition View.hpp:418
View(SparseSet< T > *pool)
Constructs a single-component view.
Definition View.hpp:406
usize sizeHint() const
Upper bound on matching entities — exact here, since nothing filters.
Definition View.hpp:453
bool empty() const
Checks if the view is empty.
Definition View.hpp:441
T & get(Entity entity)
Gets the component for an entity.
Definition View.hpp:425
std::tuple< T & > getAll(Entity entity)
Gets all components for an entity as a tuple.
Definition View.hpp:435
Iterator begin() const
Returns iterator to the first entity.
Definition View.hpp:412
ViewIterator< Components... > Iterator
Iterator type.
Definition View.hpp:187
Iterator begin() const
Returns iterator to the first matching entity.
Definition View.hpp:204
T & get(Entity entity)
Gets a specific component from an entity.
Definition View.hpp:229
void each(Func &&func)
Definition View.hpp:277
std::tuple< Components &... > getAll(Entity entity)
Gets all components for an entity as a tuple.
Definition View.hpp:244
std::tuple< SparseSet< Components > *... > PoolsTuple
Tuple type for pool pointers.
Definition View.hpp:189
void eachLive(Func &&func)
Like each(), but iterates the live dense array with no defensive copy.
Definition View.hpp:304
View(PoolsTuple pools)
Constructs a view from component pools.
Definition View.hpp:195
const T & get(Entity entity) const
Gets a specific component from an entity.
Definition View.hpp:235
usize sizeHint() const
Gets the estimated number of matching entities.
Definition View.hpp:268
bool empty() const
Checks if the view is empty.
Definition View.hpp:257
Iterator end() const
Returns iterator past the last entity.
Definition View.hpp:213
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
Entity identifier with packed index + generation.
Definition Types.hpp:135