Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
UILayoutSystem.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
5#include "./UISystem.hpp"
6
11#include "../ecs/components/UINode.hpp" // UINode + AlignSelf
12
13#include <yoga/Yoga.h>
14#include <unordered_map>
15#include <unordered_set>
16#include <vector>
17#include <algorithm>
18
19namespace esengine::ecs {
20
21// Reused across frames so the per-frame inherited walk allocates nothing.
22static std::vector<f32> inherited_alpha_stack_;
23static std::vector<u8> inherited_block_stack_;
24
25// Retained Yoga node cache: one YGNode per UI entity, kept alive across frames.
26// A stable UI tree reuses its allocations instead of YGNodeNew/FreeRecursive
27// every solve; entities that leave the tree are reaped. The hierarchy + style
28// are still rebuilt each frame here (Stage 1) — dirty-gating that avoids the
29// rebuild/solve when nothing changed is layered on top separately.
31 std::unordered_map<Entity, YGNodeRef> nodes;
32
34 for (auto& [entity, node] : nodes) YGNodeFree(node);
35 }
36
37 YGNodeRef getOrCreate(Entity entity) {
38 auto it = nodes.find(entity);
39 if (it != nodes.end()) return it->second;
40 YGNodeRef node = YGNodeNew();
41 nodes.emplace(entity, node);
42 return node;
43 }
44
45 // Free the YGNodes of entities no longer in the tree. YGNodeFree disconnects
46 // each from its owner/children, so order is irrelevant (live nodes hold only
47 // live children after the pass, so none point at a reaped node).
48 void reap(const std::unordered_set<Entity>& live) {
49 for (auto it = nodes.begin(); it != nodes.end();) {
50 if (live.find(it->first) == live.end()) {
51 YGNodeFree(it->second);
52 it = nodes.erase(it);
53 } else {
54 ++it;
55 }
56 }
57 }
58};
59
60namespace {
61
62// =============================================================================
63// Flex enum → Yoga mappers (shared by the UINode container + item styling)
64// =============================================================================
65
66YGFlexDirection toYGFlexDirection(FlexDirection dir) {
67 switch (dir) {
68 case FlexDirection::Row: return YGFlexDirectionRow;
69 case FlexDirection::Column: return YGFlexDirectionColumn;
70 case FlexDirection::RowReverse: return YGFlexDirectionRowReverse;
71 case FlexDirection::ColumnReverse: return YGFlexDirectionColumnReverse;
72 }
73 return YGFlexDirectionRow;
74}
75
76YGWrap toYGWrap(FlexWrap wrap) {
77 switch (wrap) {
78 case FlexWrap::NoWrap: return YGWrapNoWrap;
79 case FlexWrap::Wrap: return YGWrapWrap;
80 }
81 return YGWrapNoWrap;
82}
83
84YGJustify toYGJustify(JustifyContent jc) {
85 switch (jc) {
86 case JustifyContent::Start: return YGJustifyFlexStart;
87 case JustifyContent::Center: return YGJustifyCenter;
88 case JustifyContent::End: return YGJustifyFlexEnd;
89 case JustifyContent::SpaceBetween: return YGJustifySpaceBetween;
90 case JustifyContent::SpaceAround: return YGJustifySpaceAround;
91 case JustifyContent::SpaceEvenly: return YGJustifySpaceEvenly;
92 }
93 return YGJustifyFlexStart;
94}
95
96YGAlign toYGAlign(AlignItems ai) {
97 switch (ai) {
98 case AlignItems::Start: return YGAlignFlexStart;
99 case AlignItems::Center: return YGAlignCenter;
100 case AlignItems::End: return YGAlignFlexEnd;
101 case AlignItems::Stretch: return YGAlignStretch;
102 }
103 return YGAlignStretch;
104}
105
106YGAlign toYGAlignContent(AlignContent ac) {
107 switch (ac) {
108 case AlignContent::Start: return YGAlignFlexStart;
109 case AlignContent::Center: return YGAlignCenter;
110 case AlignContent::End: return YGAlignFlexEnd;
111 case AlignContent::Stretch: return YGAlignStretch;
112 case AlignContent::SpaceBetween: return YGAlignSpaceBetween;
113 case AlignContent::SpaceAround: return YGAlignSpaceAround;
114 }
115 return YGAlignFlexStart;
116}
117
118YGAlign toYGAlignSelf(AlignSelf as) {
119 switch (as) {
120 case AlignSelf::Auto: return YGAlignAuto;
121 case AlignSelf::Start: return YGAlignFlexStart;
122 case AlignSelf::Center: return YGAlignCenter;
123 case AlignSelf::End: return YGAlignFlexEnd;
124 case AlignSelf::Stretch: return YGAlignStretch;
125 }
126 return YGAlignAuto;
127}
128
129// =============================================================================
130// UINode (CSS box) → single-pass Yoga (the single layout model)
131// =============================================================================
132//
133// A UINode subtree is laid out by ONE Yoga solve: each entity becomes a YGNode,
134// the hierarchy is mirrored, the root is sized to its available box, and one
135// YGNodeCalculateLayout resolves the whole subtree. Output is written as the
136// engine's center-based, y-up local Transform (implicit pivot 0.5, matching
137// UIElementPlugin) plus UINode.computed_size_ (read by the renderer/hit-test).
138
139// Dimension.unit codes — mirror the TS DimensionUnit enum.
140constexpr u8 DIM_PX = 0, DIM_PERCENT = 1, DIM_AUTO = 2;
141
142void applyWidth(YGNodeRef n, const Dimension& d) {
143 if (d.unit == DIM_PERCENT) YGNodeStyleSetWidthPercent(n, d.value);
144 else if (d.unit == DIM_AUTO) YGNodeStyleSetWidthAuto(n);
145 else YGNodeStyleSetWidth(n, d.value);
146}
147void applyHeight(YGNodeRef n, const Dimension& d) {
148 if (d.unit == DIM_PERCENT) YGNodeStyleSetHeightPercent(n, d.value);
149 else if (d.unit == DIM_AUTO) YGNodeStyleSetHeightAuto(n);
150 else YGNodeStyleSetHeight(n, d.value);
151}
152// min/max have no Yoga "auto"; Auto means "no constraint" → leave unset.
153void applyMinWidth(YGNodeRef n, const Dimension& d) {
154 if (d.unit == DIM_PERCENT) YGNodeStyleSetMinWidthPercent(n, d.value);
155 else if (d.unit == DIM_PX) YGNodeStyleSetMinWidth(n, d.value);
156}
157void applyMinHeight(YGNodeRef n, const Dimension& d) {
158 if (d.unit == DIM_PERCENT) YGNodeStyleSetMinHeightPercent(n, d.value);
159 else if (d.unit == DIM_PX) YGNodeStyleSetMinHeight(n, d.value);
160}
161void applyMaxWidth(YGNodeRef n, const Dimension& d) {
162 if (d.unit == DIM_PERCENT) YGNodeStyleSetMaxWidthPercent(n, d.value);
163 else if (d.unit == DIM_PX) YGNodeStyleSetMaxWidth(n, d.value);
164}
165void applyMaxHeight(YGNodeRef n, const Dimension& d) {
166 if (d.unit == DIM_PERCENT) YGNodeStyleSetMaxHeightPercent(n, d.value);
167 else if (d.unit == DIM_PX) YGNodeStyleSetMaxHeight(n, d.value);
168}
169void applyFlexBasis(YGNodeRef n, const Dimension& d) {
170 if (d.unit == DIM_PERCENT) YGNodeStyleSetFlexBasisPercent(n, d.value);
171 else if (d.unit == DIM_AUTO) YGNodeStyleSetFlexBasisAuto(n);
172 else YGNodeStyleSetFlexBasis(n, d.value);
173}
174void applyMargin(YGNodeRef n, YGEdge edge, const Dimension& d) {
175 if (d.unit == DIM_PERCENT) YGNodeStyleSetMarginPercent(n, edge, d.value);
176 else if (d.unit == DIM_AUTO) YGNodeStyleSetMarginAuto(n, edge);
177 else YGNodeStyleSetMargin(n, edge, d.value);
178}
179void applyInset(YGNodeRef n, YGEdge edge, const Dimension& d) {
180 // Auto = that edge is unconstrained; leave it unset so size/flow decides.
181 if (d.unit == DIM_PERCENT) YGNodeStyleSetPositionPercent(n, edge, d.value);
182 else if (d.unit == DIM_PX) YGNodeStyleSetPosition(n, edge, d.value);
183}
184
185void applyUINodeStyle(Registry& registry, Entity entity, YGNodeRef yg) {
186 auto& n = registry.get<UINode>(entity);
187 YGNodeStyleSetDisplay(yg, n.display == UIDisplay::None
188 ? YGDisplayNone : YGDisplayFlex);
189 YGNodeStyleSetPositionType(yg, n.position == UIPositionType::Absolute
190 ? YGPositionTypeAbsolute : YGPositionTypeRelative);
191 applyInset(yg, YGEdgeLeft, n.insetLeft);
192 applyInset(yg, YGEdgeTop, n.insetTop);
193 applyInset(yg, YGEdgeRight, n.insetRight);
194 applyInset(yg, YGEdgeBottom, n.insetBottom);
195 applyWidth(yg, n.width);
196 applyHeight(yg, n.height);
197 applyMinWidth(yg, n.minWidth);
198 applyMinHeight(yg, n.minHeight);
199 applyMaxWidth(yg, n.maxWidth);
200 applyMaxHeight(yg, n.maxHeight);
201 YGNodeStyleSetFlexGrow(yg, n.flexGrow);
202 YGNodeStyleSetFlexShrink(yg, n.flexShrink);
203 applyFlexBasis(yg, n.flexBasis);
204 YGNodeStyleSetAlignSelf(yg, toYGAlignSelf(n.alignSelf));
205 applyMargin(yg, YGEdgeLeft, n.marginLeft);
206 applyMargin(yg, YGEdgeTop, n.marginTop);
207 applyMargin(yg, YGEdgeRight, n.marginRight);
208 applyMargin(yg, YGEdgeBottom, n.marginBottom);
209
210 // Container properties still come from FlexContainer (folded into UILayout in F4).
211 //
212 // The absent case is written out rather than skipped: this runs against a
213 // node that KEEPS its style between frames, so "no FlexContainer" has to
214 // actively say Yoga's defaults. Leaving them alone would let a removed
215 // FlexContainer's padding and justify go on laying the node out forever —
216 // the one thing a total style application must not do.
217 if (auto* fc = registry.tryGet<FlexContainer>(entity)) {
218 YGNodeStyleSetFlexDirection(yg, toYGFlexDirection(fc->direction));
219 YGNodeStyleSetFlexWrap(yg, toYGWrap(fc->wrap));
220 YGNodeStyleSetJustifyContent(yg, toYGJustify(fc->justifyContent));
221 YGNodeStyleSetAlignItems(yg, toYGAlign(fc->alignItems));
222 YGNodeStyleSetAlignContent(yg, toYGAlignContent(fc->alignContent));
223 YGNodeStyleSetGap(yg, YGGutterColumn, fc->gap.x);
224 YGNodeStyleSetGap(yg, YGGutterRow, fc->gap.y);
225 YGNodeStyleSetPadding(yg, YGEdgeLeft, fc->padding.left);
226 YGNodeStyleSetPadding(yg, YGEdgeTop, fc->padding.top);
227 YGNodeStyleSetPadding(yg, YGEdgeRight, fc->padding.right);
228 YGNodeStyleSetPadding(yg, YGEdgeBottom, fc->padding.bottom);
229 } else {
230 YGNodeStyleSetFlexDirection(yg, YGFlexDirectionColumn);
231 YGNodeStyleSetFlexWrap(yg, YGWrapNoWrap);
232 YGNodeStyleSetJustifyContent(yg, YGJustifyFlexStart);
233 YGNodeStyleSetAlignItems(yg, YGAlignStretch);
234 YGNodeStyleSetAlignContent(yg, YGAlignFlexStart);
235 YGNodeStyleSetGap(yg, YGGutterColumn, 0.0f);
236 YGNodeStyleSetGap(yg, YGGutterRow, 0.0f);
237 YGNodeStyleSetPadding(yg, YGEdgeLeft, 0.0f);
238 YGNodeStyleSetPadding(yg, YGEdgeTop, 0.0f);
239 YGNodeStyleSetPadding(yg, YGEdgeRight, 0.0f);
240 YGNodeStyleSetPadding(yg, YGEdgeBottom, 0.0f);
241 }
242}
243
244// Lay out the UINode subtree rooted at tree index `rootIdx` in one Yoga solve.
245// `availW/H` + `parentPivot*` describe the available box the root sits in.
246void layoutUINodeSubtree(
247 Registry& registry, UITree& tree, LayoutCache& cache, i32 rootIdx,
248 f32 availW, f32 availH, f32 parentPivotX, f32 parentPivotY,
249 bool structureChanged, bool forceWriteback
250) {
251 i32 begin = rootIdx;
252 i32 end = rootIdx + tree.nodes_[rootIdx].subtree_size;
253
254 std::vector<YGNodeRef> yg(static_cast<usize>(end - begin), nullptr);
255 std::unordered_map<Entity, i32> slotOf; // entity → local slot index
256 // The retained YGNode KEEPS its style between frames, and re-applying it is
257 // how Yoga is told what moved: every YGNodeStyleSet* is `if (old != new)
258 // { set; markDirtyAndPropagate(); }`, so a field that did not change costs
259 // one comparison and dirties nothing. Resetting first (as this used to) made
260 // every field look changed, which dirtied every node and threw away the
261 // incremental solve the retained nodes exist for.
262 for (i32 k = begin; k < end; ++k) {
263 Entity e = tree.nodes_[k].entity;
264 if (!registry.has<UINode>(e)) continue; // tree is homogeneously UINode
265 YGNodeRef node = cache.getOrCreate(e);
266 applyUINodeStyle(registry, e, node);
267 yg[static_cast<usize>(k - begin)] = node;
268 slotOf[e] = k - begin;
269 }
270 YGNodeRef rootYG = yg[0];
271 if (!rootYG) return;
272
273 // Parenting is rebuilt only when the tree's shape actually changed. Yoga's
274 // own child list is the retained hierarchy the rest of the time — and
275 // re-inserting an unchanged child would dirty it for nothing.
276 if (structureChanged) {
277 for (i32 k = begin; k < end; ++k) {
278 YGNodeRef node = yg[static_cast<usize>(k - begin)];
279 if (node) YGNodeRemoveAllChildren(node);
280 }
281 for (i32 k = begin + 1; k < end; ++k) {
282 YGNodeRef child = yg[static_cast<usize>(k - begin)];
283 if (!child) continue;
284 auto it = slotOf.find(tree.nodes_[k].parent);
285 if (it == slotOf.end()) continue;
286 YGNodeRef parentYG = yg[static_cast<usize>(it->second)];
287 YGNodeInsertChild(parentYG, child, YGNodeGetChildCount(parentYG));
288 }
289 }
290
291 // The root fills the available box on axes it leaves auto.
292 auto& rootNode = registry.get<UINode>(tree.nodes_[begin].entity);
293 if (rootNode.width.unit == DIM_AUTO) YGNodeStyleSetWidth(rootYG, availW);
294 if (rootNode.height.unit == DIM_AUTO) YGNodeStyleSetHeight(rootYG, availH);
295
296 YGNodeCalculateLayout(rootYG, availW, availH, YGDirectionLTR);
297
298 // Which nodes' own box changed, by local slot. A node whose PARENT resized
299 // has to be written even when Yoga left its own box alone: the local
300 // position below is expressed against the parent's computed size, so the
301 // same Yoga offset inside a resized parent is a different world position.
302 // DFS order guarantees a parent's entry is filled before its children read it.
303 std::vector<u8> resized(static_cast<usize>(end - begin), 0);
304
305 for (i32 k = begin; k < end; ++k) {
306 YGNodeRef node = yg[static_cast<usize>(k - begin)];
307 if (!node) continue;
308 Entity e = tree.nodes_[k].entity;
309
310 bool parentResized = false;
311 if (k != begin) {
312 auto it = slotOf.find(tree.nodes_[k].parent);
313 if (it != slotOf.end()) parentResized = resized[static_cast<usize>(it->second)] != 0;
314 }
315 // Yoga tells us what it recomputed; everything else still holds the
316 // output of the last solve, which is still correct.
317 if (!forceWriteback && !YGNodeGetHasNewLayout(node) && !parentResized) continue;
318 YGNodeSetHasNewLayout(node, false);
319
320 auto& un = registry.get<UINode>(e);
321 f32 fw = YGNodeLayoutGetWidth(node);
322 f32 fh = YGNodeLayoutGetHeight(node);
323 resized[static_cast<usize>(k - begin)] =
324 (un.computed_size_.x != fw || un.computed_size_.y != fh) ? 1 : 0;
325 un.computed_size_.x = fw;
326 un.computed_size_.y = fh;
327
328 // Position frame = the parent box (root's available box, else the parent
329 // UINode whose computed_size_ is already set — DFS order guarantees it).
330 f32 pw, ph, ppx, ppy;
331 if (k == begin) {
332 pw = availW; ph = availH; ppx = parentPivotX; ppy = parentPivotY;
333 } else {
334 auto& pn = registry.get<UINode>(tree.nodes_[k].parent);
335 pw = pn.computed_size_.x; ph = pn.computed_size_.y; ppx = 0.5f; ppy = 0.5f;
336 }
337 f32 yl = YGNodeLayoutGetLeft(node);
338 f32 yt = YGNodeLayoutGetTop(node);
339
340 // An absolute child centres an axis when both its insets AND both its
341 // margins on that axis are `auto`. A pivot-less CSS box can't otherwise
342 // centre an out-of-flow node: Yoga's abspos centring keys off the
343 // parent's justifyContent, so it can't differ per sibling under one
344 // Canvas. Overriding the Yoga offset makes centring a self-contained
345 // per-node anchor, independent of the parent and of which axis is main.
346 if (k != begin && un.position == UIPositionType::Absolute) {
347 auto axisCentred = [](const Dimension& a, const Dimension& b,
348 const Dimension& m0, const Dimension& m1) {
349 return a.unit == DIM_AUTO && b.unit == DIM_AUTO &&
350 m0.unit == DIM_AUTO && m1.unit == DIM_AUTO;
351 };
352 if (axisCentred(un.insetLeft, un.insetRight, un.marginLeft, un.marginRight))
353 yl = 0.5f * (pw - fw);
354 if (axisCentred(un.insetTop, un.insetBottom, un.marginTop, un.marginBottom))
355 yt = 0.5f * (ph - fh);
356 }
357
358 // Center-based, y-up local position (implicit pivot 0.5).
359 f32 localX = -ppx * pw + yl + 0.5f * fw;
360 f32 localY = (1.0f - ppy) * ph - yt - 0.5f * fh;
361
362 if (auto* t = registry.tryGet<Transform>(e)) {
363 // Leave tween-driven position axes alone (see TweenSystem anim_override_). Stamped where it moved: composition
364 // recomposes the written entities, and a layout pass that places every node where it already was moves none.
365 const glm::vec3 before = t->position;
366 if (!(un.anim_override_ & UINode::ANIM_POS_X)) t->position.x = localX;
367 if (!(un.anim_override_ & UINode::ANIM_POS_Y)) t->position.y = localY;
368 if (t->position != before) registry.markChanged<Transform>(e);
369 }
370 }
371
372 // Retained nodes are not freed here — layoutUpdate reaps entities that left
373 // the tree and the LayoutCache frees the rest on teardown.
374}
375
376// Resolve display:none hierarchically over the DFS-ordered tree: a node with
377// display None hides its whole subtree. Rendering, text and hit-testing read
378// the resulting UINode.hidden_in_tree_ bit so they never need tree knowledge.
379void propagateHiddenInTree(Registry& registry, UITree& tree) {
380 auto& nodes = tree.nodes_;
381 for (i32 i = 0; i < static_cast<i32>(nodes.size()); ) {
382 auto* n = registry.tryGet<UINode>(nodes[i].entity);
383 if (n && n->display == UIDisplay::None) {
384 i32 end = i + nodes[i].subtree_size;
385 for (i32 k = i; k < end; ++k) {
386 if (auto* c = registry.tryGet<UINode>(nodes[k].entity)) c->hidden_in_tree_ = true;
387 }
388 i = end;
389 } else {
390 if (n) n->hidden_in_tree_ = false;
391 ++i;
392 }
393 }
394}
395
396// Resolve opacity and pointer-events hierarchically over the same DFS-ordered
397// tree: opacity multiplies down (CSS `opacity`), pointer-events latches off
398// (CSS `pointer-events: none` on an ancestor is not overridable by a child).
399// Rendering and hit-testing read the resulting UINode bits, so neither needs
400// tree knowledge — the contract propagateHiddenInTree already established.
401//
402// `depth` is monotonic in DFS order, so one running stack indexed by depth
403// carries each node's inherited value to its children without a second walk.
404void propagateInheritedUIState(Registry& registry, UITree& tree) {
405 auto& nodes = tree.nodes_;
406 if (nodes.empty()) return;
407
408 inherited_alpha_stack_.assign(nodes.size() + 1, 1.0f);
409 inherited_block_stack_.assign(nodes.size() + 1, static_cast<u8>(0));
410
411 for (usize i = 0; i < nodes.size(); ++i) {
412 const u32 depth = nodes[i].depth;
413 const f32 parentAlpha = depth == 0 ? 1.0f : inherited_alpha_stack_[depth - 1];
414 const bool parentBlocked = depth == 0 ? false : inherited_block_stack_[depth - 1] != 0;
415
416 auto* n = registry.tryGet<UINode>(nodes[i].entity);
417 if (!n) {
418 inherited_alpha_stack_[depth] = parentAlpha;
419 inherited_block_stack_[depth] = static_cast<u8>(parentBlocked);
420 continue;
421 }
422 const f32 alpha = parentAlpha * std::clamp(n->opacity, 0.0f, 1.0f);
423 const bool blocked = n->pointerEvents == UIPointerEvents::None
424 || (parentBlocked && n->pointerEvents != UIPointerEvents::Receive);
425 n->alpha_in_tree_ = alpha;
426 n->pointer_blocked_in_tree_ = blocked;
427 inherited_alpha_stack_[depth] = alpha;
428 inherited_block_stack_[depth] = static_cast<u8>(blocked);
429 }
430}
431
432// A tween drives Transform fields directly in C++ (TweenSystem), invisible to the
433// TS change-tracking that feeds tsPropertyDirty. Scan the UINode anim_override_
434// bits so the gate keeps solving while any tween is active — and, via the caller's
435// lastAnimActive_, once more on the frame a tween ends (override already cleared)
436// so layout reclaims the position it had ceded.
437bool anyUIAnimActive(Registry& registry) {
438 bool active = false;
439 registry.eachLive<UINode>([&](Entity, UINode& n) {
440 if (n.anim_override_ != 0) active = true;
441 });
442 return active;
443}
444
447bool isScreenRoot(Registry& registry, Entity e) {
448 auto* p = registry.tryGet<Parent>(e);
449 return !p || p->entity == INVALID_ENTITY || !registry.valid(p->entity);
450}
451
454void placeScreenRoots(Registry& registry, UITree& tree, LayoutCache& cache,
455 const LayoutRect& box) {
456 const f32 availW = box.width();
457 const f32 availH = box.height();
458 const f32 cx = box.centerX();
459 const f32 cy = box.centerY();
460 for (i32 i = 0; i < static_cast<i32>(tree.nodes_.size()); ) {
461 auto& node = tree.nodes_[i];
462 bool parentIsUINode = node.parent != INVALID_ENTITY && registry.has<UINode>(node.parent);
463 if (!parentIsUINode && isScreenRoot(registry, node.entity)) {
464 auto it = cache.nodes.find(node.entity);
465 auto* t = registry.tryGet<Transform>(node.entity);
466 auto* un = registry.tryGet<UINode>(node.entity);
467 if (it != cache.nodes.end() && t && un) {
468 const f32 fw = YGNodeLayoutGetWidth(it->second);
469 const f32 fh = YGNodeLayoutGetHeight(it->second);
470 const f32 localX = -0.5f * availW + YGNodeLayoutGetLeft(it->second) + 0.5f * fw;
471 const f32 localY = 0.5f * availH - YGNodeLayoutGetTop(it->second) - 0.5f * fh;
472 const glm::vec3 before = t->position;
473 if (!(un->anim_override_ & UINode::ANIM_POS_X)) t->position.x = cx + localX;
474 if (!(un->anim_override_ & UINode::ANIM_POS_Y)) t->position.y = cy + localY;
475 if (t->position != before) registry.markChanged<Transform>(node.entity);
476 }
477 }
478 i += node.subtree_size;
479 }
480}
481
483void addSubtree(Registry& registry, Entity entity, std::unordered_set<u32>& out, std::vector<u32>& rootByIndex) {
484 std::vector<Entity> pending{entity};
485 while (!pending.empty()) {
486 const Entity current = pending.back();
487 pending.pop_back();
488 if (!registry.valid(current) || !out.insert(current.id()).second) continue;
489 if (current.index() >= rootByIndex.size()) rootByIndex.resize(current.index() + 1, 0);
490 rootByIndex[current.index()] = entity.id();
491 auto* children = registry.tryGet<Children>(current);
492 if (!children) continue;
493 for (Entity child : children->entities) pending.push_back(child);
494 }
495}
496
505void collectScreenDomain(Registry& registry, std::unordered_set<u32>& out, std::vector<u32>& roots, std::vector<u32>& rootByIndex) {
506 out.clear();
507 roots.clear();
508 registry.each<Canvas>([&](Entity entity, Canvas&) {
509 if (!registry.has<UINode>(entity) || !registry.has<Transform>(entity)) return;
510 if (!isScreenRoot(registry, entity)) return;
511 roots.push_back(entity.id());
512 addSubtree(registry, entity, out, rootByIndex);
513 });
514}
515
516void unifiedLayoutPass(Registry& registry, UITree& tree, LayoutCache& cache,
517 const LayoutRect& box, bool structureChanged,
518 bool forceWriteback) {
519 for (i32 i = 0; i < static_cast<i32>(tree.nodes_.size()); ) {
520 auto& node = tree.nodes_[i];
521
522 // Every node is a UINode. A subtree root (its parent is not a UINode —
523 // a top-level UI element / Canvas) is resolved in one Yoga solve over its
524 // whole subtree; skip past it. The available box is the layout box's size;
525 // where that box sits is applied by placeScreenRoots.
526 bool parentIsUINode = node.parent != INVALID_ENTITY && registry.has<UINode>(node.parent);
527 if (!parentIsUINode) {
528 layoutUINodeSubtree(registry, tree, cache, i, box.width(), box.height(), 0.5f, 0.5f,
529 structureChanged, forceWriteback);
530 }
531 i += node.subtree_size;
532 }
533}
534
535} // anonymous namespace
536
537// =============================================================================
538// UISystem layout entry (defined here to share the anon-namespace helpers)
539// =============================================================================
540
541void UISystem::propagateDetachedUIState(Registry& registry) {
542 if (++inherited_stamp_ == 0) {
543 inherited_cache_.clear();
544 ++inherited_stamp_;
545 }
546 registry.each<UINode>([&](Entity entity, UINode&) {
547 inherited_path_.clear();
548 InheritedState state;
549 Entity current = entity;
550 while (registry.valid(current)) {
551 auto& memo = inherited_cache_[current];
552 if (memo.stamp == inherited_stamp_) {
553 state = memo.resolving ? InheritedState{true, 0.0f, true} : memo.state;
554 break;
555 }
556 memo.stamp = inherited_stamp_;
557 memo.resolving = true;
558 inherited_path_.push_back(current);
559 const auto* parent = registry.tryGet<Parent>(current);
560 current = parent ? parent->entity : INVALID_ENTITY;
561 }
562 for (auto it = inherited_path_.rbegin(); it != inherited_path_.rend(); ++it) {
563 if (auto* node = registry.tryGet<UINode>(*it)) {
564 state.hidden = state.hidden || node->display == UIDisplay::None;
565 state.alpha *= std::clamp(node->opacity, 0.0f, 1.0f);
566 state.blocked = node->pointerEvents == UIPointerEvents::None
567 || (state.blocked && node->pointerEvents != UIPointerEvents::Receive);
568 node->hidden_in_tree_ = state.hidden;
569 node->alpha_in_tree_ = state.alpha;
570 node->pointer_blocked_in_tree_ = state.blocked;
571 }
572 auto& memo = inherited_cache_.at(*it);
573 memo.state = state;
574 memo.resolving = false;
575 }
576 });
577 // Keep live ancestry entries for reuse, but do not retain removed trees.
578 for (auto it = inherited_cache_.begin(); it != inherited_cache_.end();) {
579 if (it->second.stamp != inherited_stamp_) it = inherited_cache_.erase(it);
580 else ++it;
581 }
582}
583
585 Registry& registry,
586 f32 boxLeft, f32 boxBottom, f32 boxRight, f32 boxTop,
587 bool tsPropertyDirty
588) {
589 // The retained nodes are keyed by entity, and entity ids restart with each
590 // registry — so a scene reload or an editor play/stop would otherwise hand
591 // the new world the previous world's layout. This is only load-bearing now
592 // that styles persist between frames: the old pass reset every node it
593 // touched, which hid the aliasing by throwing the stale state away.
594 if (lastRegistryId_ != registry.instanceId()) {
595 layoutCache_.reset();
596 inherited_cache_.clear();
597 }
598 lastRegistryId_ = registry.instanceId();
599 if (!layoutCache_) {
600 layoutCache_ = std::make_unique<LayoutCache>();
601 layoutPrimed_ = false; // a fresh cache has no hierarchy to reuse
602 }
603
604 // Rebuild the DFS node list every pass: it is O(N) pointer-walking (no Yoga)
605 // and yields the structure signature that detects spawn/despawn/reparent —
606 // the reliable structural signal we don't otherwise have. The expensive part
607 // (orphan + propagateHidden + Yoga solve + reap) is what the gate below skips.
608 tree.rebuild(registry);
609 // Beside the rebuild and never behind the skip gate below: a frame that needs
610 // no re-solve can still have reparented something, and a renderer reading a
611 // stale set would draw it in the wrong domain rather than in the wrong place.
612 collectScreenDomain(registry, screen_domain_, screen_roots_, screen_root_by_index_);
613
614 // Layout belongs to Canvas; visibility and input inheritance belong to the
615 // whole UI hierarchy, including nodes that just left their Canvas.
616 const bool detached = registry.view<UINode>().size() != tree.nodes_.size();
617 if (detached) propagateDetachedUIState(registry);
618 else if (!inherited_cache_.empty()) inherited_cache_.clear();
619
620 LayoutRect box{ boxLeft, boxBottom, boxRight, boxTop };
621
622 bool animNow = anyUIAnimActive(registry);
623 bool sigChanged = tree.structure_sig_ != lastSig_;
624 // A resized box invalidates the solve; a box that merely MOVED does not —
625 // Yoga solves against the size alone, and only the screen roots' world
626 // placement depends on where the box sits. Keeping these apart is what stops
627 // a panning camera from rewriting the whole UI tree every frame.
628 bool sizeChanged = box.width() != lastBoxW_ || box.height() != lastBoxH_;
629 bool centerChanged = box.centerX() != lastBoxCX_ || box.centerY() != lastBoxCY_;
630 bool wasAnimActive = lastAnimActive_;
631
632 lastSig_ = tree.structure_sig_;
633 lastBoxW_ = box.width(); lastBoxH_ = box.height();
634 lastBoxCX_ = box.centerX(); lastBoxCY_ = box.centerY();
635 lastAnimActive_ = animNow;
636
637 // A fully static frame — no structural, box-size, property, or tween change
638 // since the last solve — leaves the retained YGNodes and every UINode's
639 // computed output valid, so the whole solve is safely skipped. `wasAnimActive`
640 // forces one more solve on the frame a tween just ended (see anyUIAnimActive).
641 bool first = !layoutPrimed_;
642 bool dirty = first || sigChanged || sizeChanged || tsPropertyDirty
643 || animNow || wasAnimActive;
644 layoutPrimed_ = true;
645 if (!dirty) {
646 if (centerChanged) {
648 placeScreenRoots(registry, tree, *layoutCache_, box);
649 }
650 return centerChanged;
651 }
652
653 // Only a pass that may write local transforms invalidates their composition.
655
656 // Two signals, because they answer different questions. The hierarchy has to
657 // be rebuilt when the tree's SHAPE changed. Output has to be written for
658 // every node when the ROOT'S FRAME changed — a subtree root positions itself
659 // against the box, so the same Yoga result inside a resized box is a
660 // different world position, and Yoga would rightly report no new layout.
661 bool structureChanged = first || sigChanged;
662 bool forceWriteback = structureChanged || sizeChanged;
663
664 // The retained hierarchy is rebuilt only when the tree's shape changed —
665 // which is exactly when an entity may still be owned by the parent it had
666 // last frame. Orphaning unconditionally (as this used to) dirtied every
667 // Yoga node on every pass, so no solve could ever be partial.
668 if (!detached) {
669 propagateHiddenInTree(registry, tree);
670 propagateInheritedUIState(registry, tree);
671 }
672 unifiedLayoutPass(registry, tree, *layoutCache_, box, structureChanged, forceWriteback);
673 placeScreenRoots(registry, tree, *layoutCache_, box);
674
675 // Reaping is likewise a structural concern: with the same set of entities in
676 // the tree there is nothing to free, and building the live set is a hash
677 // insert per node.
678 if (structureChanged) {
679 std::unordered_set<Entity> live;
680 live.reserve(tree.nodes_.size());
681 for (auto& node : tree.nodes_) live.insert(node.entity);
682 layoutCache_->reap(live);
683 }
684 return true;
685}
686
687// Out-of-line so LayoutCache is complete here (it holds Yoga types kept out of
688// the header). Defaulted — the unique_ptr frees the cache, whose destructor
689// frees the retained YGNodes.
690UISystem::UISystem() = default;
691UISystem::~UISystem() = default;
692
693
694} // namespace esengine::ecs
Canvas component for 2D game resolution management.
Hierarchy components for parent-child relationships.
System for computing hierarchical world transforms.
Unified Transform component with local and world-space data.
UI subsystem owning layout tree and hit-test state.
Central container for all entities and components.
Definition Registry.hpp:73
u64 instanceId() const
Which registry this is — unique for the process, never reused.
Definition Registry.hpp:96
View< Components... > view()
Creates a view for iterating entities with specific components.
Definition Registry.hpp:761
bool layoutUpdate(Registry &registry, f32 boxLeft, f32 boxBottom, f32 boxRight, f32 boxTop, bool tsPropertyDirty)
Rebuild layout tree and apply layout to all dirty nodes. The four bounds are the world-space box UI i...
std::unique_ptr< LayoutCache > layoutCache_
Definition UISystem.hpp:68
static std::vector< f32 > inherited_alpha_stack_
AlignSelf
Per-item cross-axis alignment override (CSS align-self). Lives on UINode since UINode carries the fle...
Definition UINode.hpp:18
static std::vector< u8 > inherited_block_stack_
void invalidateTransformComposition()
Say that composed world transforms are stale.
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
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::uint8_t u8
Unsigned 8-bit integer.
Definition Types.hpp:41
float f32
32-bit floating point
Definition Types.hpp:59
Entity identifier with packed index + generation.
Definition Types.hpp:135
Canvas component for 2D game resolution management.
Definition Canvas.hpp:71
Children list component.
Definition Hierarchy.hpp:66
void reap(const std::unordered_set< Entity > &live)
std::unordered_map< Entity, YGNodeRef > nodes
YGNodeRef getOrCreate(Entity entity)
Parent reference component.
Definition Hierarchy.hpp:46
Entity entity
Parent entity ID.
Definition Hierarchy.hpp:49
Unified transform component.
Definition Transform.hpp:45
UINode — the CSS box-model layout input (the CSS/Flex primary layout model).
Definition UINode.hpp:79
glm::vec2 computed_size_
Definition UINode.hpp:147
static constexpr u8 ANIM_POS_X
Definition UINode.hpp:164
static constexpr u8 ANIM_POS_Y
Definition UINode.hpp:165