Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
Relation.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
29#pragma once
30
31#include "../core/Types.hpp"
32
33#include <algorithm>
34#include <vector>
35
36namespace esengine::ecs {
37
39public:
40 static constexpr u32 NONE = Entity::INVALID_RAW;
41
43 Entity target(Entity source) const { return Entity::fromRaw(read(target_, source)); }
44 bool hasTarget(Entity source) const { return read(target_, source) != NONE; }
46 Entity first(Entity target) const { return Entity::fromRaw(read(first_, target)); }
47 Entity last(Entity target) const { return Entity::fromRaw(read(last_, target)); }
49 Entity next(Entity source) const { return Entity::fromRaw(read(next_, source)); }
50 Entity prev(Entity source) const { return Entity::fromRaw(read(prev_, source)); }
52 u32 count(Entity target) const { return target.index() < count_.size() ? count_[target.index()] : 0; }
53 bool hasSources(Entity target) const { return count(target) != 0; }
55 u32 depth(Entity entity) const { return entity.index() < depth_.size() ? depth_[entity.index()] : 0; }
57 u32 linkCount() const { return links_; }
59 u32 epoch() const { return epoch_; }
60
62 template<typename Visit>
63 void eachSource(Entity target, Visit&& visit) const {
64 for (u32 at = read(first_, target); at != NONE; at = next_[Entity::fromRaw(at).index()]) {
65 visit(Entity::fromRaw(at));
66 }
67 }
68
70 std::vector<Entity> sources(Entity target) const {
71 std::vector<Entity> out;
72 out.reserve(count(target));
73 eachSource(target, [&out](Entity e) { out.push_back(e); });
74 return out;
75 }
76
78 bool isDescendantOf(Entity entity, Entity ancestor) const {
79 for (u32 at = read(target_, entity); at != NONE; at = read(target_, Entity::fromRaw(at))) {
80 if (at == ancestor.raw) return true;
81 }
82 return false;
83 }
84
86 Entity root(Entity entity) const {
87 while (hasTarget(entity)) entity = target(entity);
88 return entity;
89 }
90
96 void link(Entity source, Entity target, Entity before = INVALID_ENTITY) {
97 markTree(source);
98 if (hasTarget(source)) detach(source);
99 grow(std::max(source.index(), target.index()));
100 const u32 s = source.index(), t = target.index();
101 if (before.isValid() && read(target_, before) == target.raw) {
102 const u32 b = before.index();
103 const u32 p = prev_[b];
104 prev_[s] = p;
105 next_[s] = before.raw;
106 prev_[b] = source.raw;
107 if (p == NONE) first_[t] = source.raw; else next_[Entity::fromRaw(p).index()] = source.raw;
108 } else {
109 const u32 l = last_[t];
110 prev_[s] = l;
111 next_[s] = NONE;
112 if (l == NONE) first_[t] = source.raw; else next_[Entity::fromRaw(l).index()] = source.raw;
113 last_[t] = source.raw;
114 }
115 target_[s] = target.raw;
116 ++count_[t];
117 ++links_;
118 setSubtreeDepth(source, depth_[t] + 1);
119 noteRetargeted(source.raw);
120 markTree(target);
121 ++epoch_;
122 }
123
125 void unlink(Entity source) {
126 if (!hasTarget(source)) return;
127 markTree(source);
128 detach(source);
129 setSubtreeDepth(source, 0);
130 noteRetargeted(source.raw);
131 markTree(source);
132 ++epoch_;
133 }
134
139 bool sortSources(Entity target, const std::vector<u32>& rank) {
140 if (count(target) <= 1) return false;
141 scratch_ = sources(target);
142 const auto rankOf = [&rank](Entity e) { return e.index() < rank.size() ? rank[e.index()] : NONE; };
143 if (std::is_sorted(scratch_.begin(), scratch_.end(), [&](Entity a, Entity b) { return rankOf(a) < rankOf(b); })) return false;
144 std::stable_sort(scratch_.begin(), scratch_.end(), [&](Entity a, Entity b) { return rankOf(a) < rankOf(b); });
145 const u32 t = target.index();
146 u32 prev = NONE;
147 for (const Entity e : scratch_) {
148 prev_[e.index()] = prev;
149 if (prev == NONE) first_[t] = e.raw; else next_[Entity::fromRaw(prev).index()] = e.raw;
150 prev = e.raw;
151 }
152 next_[Entity::fromRaw(prev).index()] = NONE;
153 last_[t] = prev;
154 markTree(target);
155 ++epoch_;
156 return true;
157 }
158
165 void onDestroy(Entity entity) {
166 const u32 i = entity.index();
167 if (i >= target_.size()) return;
168 if (target_[i] != NONE || first_[i] != NONE) markTree(entity);
169 bool changed = false;
170 if (target_[i] != NONE) { detach(entity); changed = true; }
171 for (u32 at = first_[i]; at != NONE;) {
172 const u32 c = Entity::fromRaw(at).index();
173 const u32 following = next_[c];
174 target_[c] = prev_[c] = next_[c] = NONE;
175 --links_;
176 setSubtreeDepth(Entity::fromRaw(at), 0);
177 noteRetargeted(at);
178 markTree(Entity::fromRaw(at));
179 at = following;
180 changed = true;
181 }
182 first_[i] = last_[i] = NONE;
183 count_[i] = 0;
184 depth_[i] = 0;
185 if (changed) ++epoch_;
186 }
187
188 void clear() {
189 target_.clear(); first_.clear(); last_.clear(); next_.clear(); prev_.clear(); count_.clear(); depth_.clear();
190 links_ = 0;
191 retargeted_.clear();
192 retargetedOverflow_ = true;
193 all_dirty_ = true;
194 dirty_roots_.clear();
195 ++epoch_;
196 }
197
203 bool takeRetargeted(std::vector<Entity>& out) {
204 out.clear();
205 const bool listed = !retargetedOverflow_;
206 if (listed) for (const u32 raw : retargeted_) out.push_back(Entity::fromRaw(raw));
207 retargeted_.clear();
208 retargetedOverflow_ = false;
209 return listed;
210 }
211
220
222 struct CascadeTree {
224 std::vector<CascadeEntry> entries;
226 bool alive = false;
227 };
228
230 struct CascadeAt {
233 };
234
242 const std::vector<CascadeTree>& cascade() const {
243 refreshCascade();
244 return trees_;
245 }
246
248 CascadeAt cascadeAt(Entity entity) const {
249 const u32 i = entity.index();
250 if (i >= tree_of_.size() || tree_of_[i] == NONE) return {NONE, NONE};
251 return {tree_of_[i], slot_of_[i]};
252 }
253
255 const u32* targets() const { return target_.data(); }
256 const u32* firsts() const { return first_.data(); }
257 const u32* nexts() const { return next_.data(); }
258 usize capacity() const { return target_.size(); }
259
260private:
261 std::vector<u32> target_, first_, last_, next_, prev_, count_, depth_;
262 std::vector<Entity> scratch_;
263 std::vector<u32> walk_;
264 u32 links_ = 0;
265 u32 epoch_ = 1;
267 std::vector<u32> retargeted_;
268 bool retargetedOverflow_ = false;
269 static constexpr usize RETARGETED_CAP = 4096;
270
271 void noteRetargeted(u32 raw) {
272 if (retargetedOverflow_) return;
273 if (retargeted_.size() >= RETARGETED_CAP) { retargeted_.clear(); retargetedOverflow_ = true; return; }
274 retargeted_.push_back(raw);
275 }
276
277 mutable std::vector<CascadeTree> trees_;
278 mutable std::vector<u32> free_trees_;
280 mutable std::vector<u32> tree_of_, slot_of_;
282 mutable std::vector<u32> dirty_roots_;
283 mutable bool all_dirty_ = true;
284 mutable std::vector<std::pair<u32, u32>> pending_;
285 static constexpr usize DIRTY_ROOTS_CAP = 1024;
286
288 void markTree(Entity entity) {
289 if (all_dirty_ || !entity.isValid()) return;
290 if (dirty_roots_.size() >= DIRTY_ROOTS_CAP) { all_dirty_ = true; dirty_roots_.clear(); return; }
291 dirty_roots_.push_back(root(entity).raw);
292 }
293
295 u32 rootAt(u32 index) const {
296 if (index >= target_.size() || target_[index] != NONE || first_[index] == NONE) return NONE;
297 // A root's own id is not stored at its slot; its first child names it.
298 return target_[Entity::fromRaw(first_[index]).index()];
299 }
300
301 void refreshCascade() const {
302 if (all_dirty_) {
303 for (auto& tree : trees_) for (const auto& e : tree.entries) forget(e.entity);
304 trees_.clear();
305 free_trees_.clear();
306 tree_of_.assign(target_.size(), NONE);
307 slot_of_.assign(target_.size(), NONE);
308 for (u32 i = 0, n = static_cast<u32>(target_.size()); i < n; ++i) {
309 const u32 r = rootAt(i);
310 if (r != NONE) buildTree(Entity::fromRaw(r));
311 }
312 all_dirty_ = false;
313 dirty_roots_.clear();
314 return;
315 }
316 if (dirty_roots_.empty()) return;
317 if (tree_of_.size() < target_.size()) {
318 tree_of_.resize(target_.size(), NONE);
319 slot_of_.resize(target_.size(), NONE);
320 }
321 std::sort(dirty_roots_.begin(), dirty_roots_.end());
322 dirty_roots_.erase(std::unique(dirty_roots_.begin(), dirty_roots_.end()), dirty_roots_.end());
323 // First every touched tree lets go of its entities, then the trees that still have a root are built again: an entity
324 // that moved from one touched tree to another ends up in the one built last only if no clearing comes after it.
325 for (const u32 raw : dirty_roots_) {
326 const u32 t = treeRootedAt(Entity::fromRaw(raw));
327 if (t == NONE) continue;
328 for (const auto& e : trees_[t].entries) forget(e.entity);
329 trees_[t].entries.clear();
330 trees_[t].alive = false;
331 free_trees_.push_back(t);
332 }
333 for (const u32 raw : dirty_roots_) {
334 const u32 i = Entity::fromRaw(raw).index();
335 if (rootAt(i) == raw) buildTree(Entity::fromRaw(raw));
336 }
337 dirty_roots_.clear();
338 }
339
341 u32 treeRootedAt(Entity root) const {
342 const u32 i = root.index();
343 if (i >= tree_of_.size() || tree_of_[i] == NONE || slot_of_[i] != 0) return NONE;
344 const u32 t = tree_of_[i];
345 return trees_[t].alive && trees_[t].root == root ? t : NONE;
346 }
347
348 void forget(Entity entity) const {
349 const u32 i = entity.index();
350 if (i < tree_of_.size()) tree_of_[i] = slot_of_[i] = NONE;
351 }
352
353 void buildTree(Entity root) const {
354 u32 t;
355 if (!free_trees_.empty()) { t = free_trees_.back(); free_trees_.pop_back(); }
356 else { t = static_cast<u32>(trees_.size()); trees_.emplace_back(); }
357 auto& tree = trees_[t];
358 tree.root = root;
359 tree.alive = true;
360 auto& out = tree.entries;
361 out.clear();
362 out.push_back({root, NONE, 0});
363 pushSources(root.index(), 0);
364 while (!pending_.empty()) {
365 const auto [raw, parent] = pending_.back();
366 pending_.pop_back();
367 out.push_back({Entity::fromRaw(raw), parent, 0});
368 pushSources(Entity::fromRaw(raw).index(), static_cast<u32>(out.size() - 1));
369 }
370 // Each entry's subtree ends where its last descendant's does: walked back to front, a child has its end before its
371 // parent takes the larger of the two.
372 const u32 n = static_cast<u32>(out.size());
373 for (u32 i = 0; i < n; ++i) {
374 out[i].end = i + 1;
375 const u32 e = out[i].entity.index();
376 if (e >= tree_of_.size()) { tree_of_.resize(e + 1, NONE); slot_of_.resize(e + 1, NONE); }
377 tree_of_[e] = t;
378 slot_of_[e] = i;
379 }
380 for (u32 i = n; i-- > 0;) {
381 const u32 p = out[i].parent;
382 if (p != NONE && out[i].end > out[p].end) out[p].end = out[i].end;
383 }
384 }
385
387 void pushSources(u32 index, u32 slot) const {
388 for (u32 at = last_[index]; at != NONE; at = prev_[Entity::fromRaw(at).index()]) pending_.emplace_back(at, slot);
389 }
390
391 static u32 read(const std::vector<u32>& slots, Entity entity) {
392 const u32 i = entity.index();
393 return i < slots.size() ? slots[i] : NONE;
394 }
395
396 void grow(u32 index) {
397 if (index < target_.size()) return;
398 // Doubling: an entity count that grows one at a time costs amortised O(1) per link.
399 const usize size = std::max<usize>(static_cast<usize>(index) + 1, target_.size() * 2);
400 target_.resize(size, NONE); first_.resize(size, NONE); last_.resize(size, NONE);
401 next_.resize(size, NONE); prev_.resize(size, NONE); count_.resize(size, 0); depth_.resize(size, 0);
402 }
403
405 void detach(Entity source) {
406 const u32 s = source.index();
407 const u32 t = Entity::fromRaw(target_[s]).index();
408 const u32 p = prev_[s], n = next_[s];
409 if (p == NONE) first_[t] = n; else next_[Entity::fromRaw(p).index()] = n;
410 if (n == NONE) last_[t] = p; else prev_[Entity::fromRaw(n).index()] = p;
411 target_[s] = prev_[s] = next_[s] = NONE;
412 --count_[t];
413 --links_;
414 }
415
417 void setSubtreeDepth(Entity root, u32 depth) {
418 const u32 r = root.index();
419 if (r >= depth_.size() || depth_[r] == depth) return;
420 const i64 delta = static_cast<i64>(depth) - static_cast<i64>(depth_[r]);
421 walk_.clear();
422 walk_.push_back(root.raw);
423 while (!walk_.empty()) {
424 const u32 at = walk_.back();
425 walk_.pop_back();
426 const u32 i = Entity::fromRaw(at).index();
427 depth_[i] = static_cast<u32>(static_cast<i64>(depth_[i]) + delta);
428 for (u32 c = first_[i]; c != NONE; c = next_[Entity::fromRaw(c).index()]) walk_.push_back(c);
429 }
430 }
431};
432
433} // namespace esengine::ecs
Core type definitions and utilities for ESEngine.
u32 depth(Entity entity) const
Links between entity and the root of its tree: 0 for a root.
Definition Relation.hpp:55
void unlink(Entity source)
Takes source's target away; its own sources stay with it.
Definition Relation.hpp:125
static constexpr u32 NONE
Definition Relation.hpp:40
u32 linkCount() const
How many entities have a target: the size of (Relation, *).
Definition Relation.hpp:57
Entity target(Entity source) const
The entity's target (its parent), or INVALID_ENTITY.
Definition Relation.hpp:43
bool takeRetargeted(std::vector< Entity > &out)
Hands over the entities whose target changed since the last call (moved, detached,...
Definition Relation.hpp:203
CascadeAt cascadeAt(Entity entity) const
Where entity sits in cascade(), or tree NONE when it is in no tree. Current as of the last cascade() ...
Definition Relation.hpp:248
Entity last(Entity target) const
Definition Relation.hpp:47
bool hasTarget(Entity source) const
Definition Relation.hpp:44
Entity first(Entity target) const
The first / last entity naming target (first and last child), or INVALID_ENTITY.
Definition Relation.hpp:46
void onDestroy(Entity entity)
Forgets entity, which is being destroyed: it leaves its target, and its sources become roots.
Definition Relation.hpp:165
u32 epoch() const
Bumped by every edit to the relation's shape, so a cache built from it can tell it is stale.
Definition Relation.hpp:59
u32 count(Entity target) const
How many entities name target.
Definition Relation.hpp:52
bool isDescendantOf(Entity entity, Entity ancestor) const
Whether ancestor is entity's target, or its target's, and so on up. Bounded: no cycle can form here.
Definition Relation.hpp:78
std::vector< Entity > sources(Entity target) const
The entities naming target, in order: for a caller that edits the relation while it walks them.
Definition Relation.hpp:70
void link(Entity source, Entity target, Entity before=INVALID_ENTITY)
Gives source the target target, placed before before among its sources (last when before is none).
Definition Relation.hpp:96
Entity root(Entity entity) const
The top of entity's tree (itself when it has no target).
Definition Relation.hpp:86
bool hasSources(Entity target) const
Definition Relation.hpp:53
void eachSource(Entity target, Visit &&visit) const
Calls visit(source) for each entity naming target, in order. visit must not edit the relation.
Definition Relation.hpp:63
Entity prev(Entity source) const
Definition Relation.hpp:50
bool sortSources(Entity target, const std::vector< u32 > &rank)
Puts target's sources in the order of rank (per entity index, lower first; stable; past the end last)...
Definition Relation.hpp:139
const u32 * targets() const
The arrays themselves, for a reader across the wasm boundary; valid until the next edit that grows th...
Definition Relation.hpp:255
const std::vector< CascadeTree > & cascade() const
Every tree of the relation, each in cascade order: Flecs' cascade, one array per tree.
Definition Relation.hpp:242
Entity next(Entity source) const
The entity after / before source among those naming the same target (siblings), or INVALID_ENTITY.
Definition Relation.hpp:49
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
constexpr Entity INVALID_ENTITY
Invalid entity sentinel value.
Definition Types.hpp:174
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
std::int64_t i64
Signed 64-bit integer.
Definition Types.hpp:56
Entity identifier with packed index + generation.
Definition Types.hpp:135
static constexpr u32 INVALID_RAW
Definition Types.hpp:143
static constexpr Entity fromRaw(u32 v)
Reconstructs an Entity from a raw packed value.
Definition Types.hpp:162
constexpr u32 index() const
Gets the entity index.
Definition Types.hpp:150
Where an entity sits in the cascade: which tree, and where in it.
Definition Relation.hpp:230
One entity of a tree, in cascade order.
Definition Relation.hpp:213
One tree, root first, every entity after its target and in its siblings' order (preorder).
Definition Relation.hpp:222