Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

perf(engine): the UI layout keeps Yoga's work, not just its allocations

esengine77266888b2b5
diff --git a/sdk/benchmarks/ui-layout.bench.ts b/sdk/benchmarks/ui-layout.bench.ts
new file mode 100644
index 000000000..87023ac84
--- /dev/null
+++ b/sdk/benchmarks/ui-layout.bench.ts
@@ -0,0 +1,123 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file What a UI tree costs per frame, split by what actually changed.
+ *
+ * Three cases, because the layout pass treats them very differently and only
+ * one of them is rare:
+ *
+ * STATIC — nothing changed. The gate should skip the solve entirely, so
+ * this measures the floor: the DFS rebuild + structure signature
+ * that runs unconditionally to detect change in the first place.
+ * ONE FIELD— a single node's width moved. This is the common case in a real
+ * UI (a label retypes, a bar fills) and the one worth watching:
+ * the difference between it and STATIC is what one edit costs.
+ * STRUCTURE— a node was added. A full resolve is legitimately required.
+ *
+ * Runs against the real engine wasm, so the numbers are the shipped ones.
+ */
+import { describe, bench, beforeAll } from 'vitest';
+import path from 'path';
+import type { ESEngineModule, Registry, Entity } from '../src/wasm/wasm.generated';
+
+let wasm: ESEngineModule;
+
+const WASM_DIR = path.resolve(__dirname, '../../desktop/public/wasm');
+
+beforeAll(async () => {
+ const engineMod = await import(path.join(WASM_DIR, 'esengine.js'));
+ wasm = await engineMod.default({ locateFile: (p: string) => path.join(WASM_DIR, p) });
+});
+
+const TRANSFORM = {
+ position: { x: 0, y: 0, z: 0 },
+ rotation: { x: 0, y: 0, z: 0, w: 1 },
+ scale: { x: 1, y: 1, z: 1 },
+ worldPosition: { x: 0, y: 0, z: 0 },
+ worldRotation: { x: 0, y: 0, z: 0, w: 1 },
+ worldScale: { x: 1, y: 1, z: 1 },
+};
+
+const px = (v: number) => ({ value: v, unit: 0 });
+const auto = () => ({ value: 0, unit: 2 });
+
+const uiNode = (w: number, h: number) => ({
+ position: 0, display: 0, opacity: 1, pointerEvents: 0,
+ width: px(w), height: px(h),
+ minWidth: auto(), minHeight: auto(), maxWidth: auto(), maxHeight: auto(),
+ flexGrow: 0, flexShrink: 1, flexBasis: auto(), alignSelf: 0,
+ marginLeft: px(0), marginTop: px(0), marginRight: px(0), marginBottom: px(0),
+ insetLeft: auto(), insetTop: auto(), insetRight: auto(), insetBottom: auto(),
+});
+
+/**
+ * A Canvas root with `count` UINodes under it, in a realistic shape: rows of
+ * children rather than one flat list, so the solve has depth to walk.
+ */
+function buildTree(reg: Registry, count: number): { root: Entity; leaves: Entity[] } {
+ const root = reg.create();
+ reg.addTransform(root, TRANSFORM);
+ reg.addUINode(root, uiNode(800, 600));
+ reg.addCanvas(root, {
+ designResolution: { x: 800, y: 600 },
+ pixelsPerUnit: 1, scaleMode: 0, matchWidthOrHeight: 0,
+ backgroundColor: { x: 0, y: 0, z: 0, w: 1 },
+ });
+
+ const leaves: Entity[] = [];
+ const PER_ROW = 10;
+ let row: Entity | null = null;
+ for (let i = 0; i < count; i++) {
+ if (i % PER_ROW === 0) {
+ row = reg.create();
+ reg.addTransform(row, TRANSFORM);
+ reg.addUINode(row, uiNode(800, 40));
+ reg.setParent(row, root);
+ }
+ const leaf = reg.create();
+ reg.addTransform(leaf, TRANSFORM);
+ reg.addUINode(leaf, uiNode(60, 30));
+ reg.setParent(leaf, row!);
+ leaves.push(leaf);
+ }
+ return { root, leaves };
+}
+
+const CAM = { l: -400, b: -300, r: 400, t: 300 };
+const solve = (reg: Registry, propertyDirty: boolean) =>
+ wasm.uiLayout_update(reg as never, CAM.l, CAM.b, CAM.r, CAM.t, propertyDirty);
+
+for (const size of [100, 500, 2000]) {
+ describe(`UI layout — ${size} nodes`, () => {
+ let reg: Registry;
+ let leaves: Entity[];
+
+ const setup = () => {
+ reg = new wasm.Registry();
+ ({ leaves } = buildTree(reg, size));
+ solve(reg, true); // prime: the first pass always solves
+ };
+
+ // The floor. Everything here runs whether or not anything changed.
+ bench('static frame (nothing changed)', () => {
+ solve(reg, false);
+ }, { setup });
+
+ // The common case, and the one the dirty granularity is about.
+ bench('one node resized', () => {
+ const node = reg.getUINode(leaves[(leaves.length / 2) | 0]);
+ node.width = px(60 + (Math.random() * 8 | 0));
+ reg.addUINode(leaves[(leaves.length / 2) | 0], node);
+ solve(reg, true);
+ }, { setup });
+
+ // A resolve is genuinely required here — this is the honest upper bound.
+ bench('one node added', () => {
+ const e = reg.create();
+ reg.addTransform(e, TRANSFORM);
+ reg.addUINode(e, uiNode(60, 30));
+ reg.setParent(e, leaves[0]);
+ solve(reg, false);
+ }, { setup });
+ });
+}
diff --git a/sdk/tests/ui-layout-incremental.test.ts b/sdk/tests/ui-layout-incremental.test.ts
new file mode 100644
index 000000000..66fdd6514
--- /dev/null
+++ b/sdk/tests/ui-layout-incremental.test.ts
@@ -0,0 +1,305 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui-layout-incremental.test.ts
+ * @brief An incrementally solved layout equals the same layout solved from
+ * scratch — for every node, not just the one that changed.
+ *
+ * The layout pass keeps its Yoga nodes, their styles AND their hierarchy between
+ * frames, and re-applies styles so Yoga's own value-diffing decides what to
+ * resolve. That is what makes editing one field cost one subtree instead of the
+ * tree. Its failure mode is silent and invisible to a screenshot of a static
+ * scene: a node that SHOULD have been recomputed is skipped and keeps last
+ * frame's box, which looks perfectly plausible.
+ *
+ * So every case here is a differential: drive the change incrementally, then
+ * build the same end state in a FRESH registry (which resets the retained
+ * cache — Registry::instanceId) and require the two to agree exactly.
+ *
+ * Needs pre-built WASM at desktop/public/wasm (`node build-tools/cli.js build -t web`).
+ */
+import { describe, it, expect, beforeAll } from 'vitest';
+import { UIPositionType, UINode, type UINodeData } from '../src/ui/core/ui-node';
+import { px, auto } from '../src/ui/core/dimension';
+import { App } from '../src/app/app';
+import { Canvas, Transform } from '../src/ecs/component';
+import { FlexContainer } from '../src/ui/layout/flex';
+import { UICameraInfo } from '../src/ui/core/ui-camera-info';
+import { uiLayoutPlugin } from '../src/ui/layout/layout';
+import type { ESEngineModule, CppRegistry } from '../src/wasm';
+import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';
+
+const node = (over: Partial<UINodeData> = {}): UINodeData => ({
+ position: 0,
+ width: auto(), height: auto(),
+ minWidth: auto(), minHeight: auto(),
+ maxWidth: auto(), maxHeight: auto(),
+ flexGrow: 0, flexShrink: 1, flexBasis: auto(),
+ alignSelf: 0,
+ marginLeft: px(0), marginTop: px(0), marginRight: px(0), marginBottom: px(0),
+ insetLeft: auto(), insetTop: auto(), insetRight: auto(), insetBottom: auto(),
+ ...over,
+});
+
+const TRANSFORM = {
+ position: { x: 0, y: 0, z: 0 },
+ rotation: { x: 0, y: 0, z: 0, w: 1 },
+ scale: { x: 1, y: 1, z: 1 },
+};
+
+/** Every laid-out node's box, keyed by the caller's own label for it. */
+type Boxes = Record<string, { w: number; h: number; x: number; y: number }>;
+
+describe.skipIf(!HAS_WASM)('incremental layout equals a fresh solve', () => {
+ let module: ESEngineModule;
+ beforeAll(async () => { module = await loadWasmModule(); });
+
+ function createApp(camW = 800, camH = 600) {
+ const app = App.new();
+ const registry = new module.Registry() as unknown as CppRegistry;
+ app.connectCpp(registry, module);
+ app.insertResource(UICameraInfo, {
+ viewProjection: new Float32Array(16),
+ vpX: 0, vpY: 0, vpW: 0, vpH: 0, screenW: 0, screenH: 0,
+ worldLeft: -camW / 2, worldBottom: -camH / 2,
+ worldRight: camW / 2, worldTop: camH / 2,
+ worldMouseX: 0, worldMouseY: 0, valid: true,
+ });
+ app.addPlugin(uiLayoutPlugin);
+ return { app, registry };
+ }
+
+ function dispose(app: App, registry: CppRegistry): void {
+ for (const e of app.world.getAllEntities()) { try { app.world.despawn(e); } catch { /* gone */ } }
+ app.world.disconnectCpp();
+ (registry as unknown as { delete(): void }).delete();
+ }
+
+ /**
+ * A row of `count` boxes inside a flex container inside a canvas. Returns the
+ * entities by label so a case can perturb one and read them all back.
+ */
+ function build(app: App, count: number, leafWidth = 60) {
+ const world = app.world;
+ const root = world.spawn();
+ world.insert(root, Canvas, {});
+ world.insert(root, UINode, node({
+ position: UIPositionType.Absolute,
+ insetLeft: px(0), insetTop: px(0), insetRight: px(0), insetBottom: px(0),
+ }));
+ world.insert(root, Transform, TRANSFORM);
+
+ const row = world.spawn();
+ world.setParent(row, root);
+ world.insert(row, UINode, node({ width: px(600), height: px(200) }));
+ world.insert(row, FlexContainer, {
+ direction: 0, wrap: 0, justifyContent: 0, alignItems: 0, alignContent: 0,
+ gap: { x: 10, y: 10 },
+ padding: { left: 8, top: 8, right: 8, bottom: 8 },
+ });
+ world.insert(row, Transform, TRANSFORM);
+
+ const leaves: number[] = [];
+ for (let i = 0; i < count; i++) {
+ const leaf = world.spawn();
+ world.setParent(leaf, row);
+ world.insert(leaf, UINode, node({ width: px(leafWidth), height: px(40) }));
+ world.insert(leaf, Transform, TRANSFORM);
+ leaves.push(leaf);
+ }
+ return { root, row, leaves };
+ }
+
+ const read = (registry: CppRegistry, labelled: Record<string, number>): Boxes => {
+ const out: Boxes = {};
+ for (const [label, e] of Object.entries(labelled)) {
+ const p = registry.getTransform(e).position;
+ out[label] = {
+ w: module.getUINodeComputedWidth!(registry, e),
+ h: module.getUINodeComputedHeight!(registry, e),
+ x: p.x, y: p.y,
+ };
+ }
+ return out;
+ };
+
+ const label = (ids: { root: number; row: number; leaves: number[] }) => ({
+ root: ids.root, row: ids.row,
+ ...Object.fromEntries(ids.leaves.map((e, i) => [`leaf${i}`, e])),
+ });
+
+ /**
+ * The comparison this file exists for, and the one thing it must not get
+ * wrong: the two runs have to reach the same end state by DIFFERENT routes.
+ *
+ * live — solve, then perturb, then solve again. The second solve is the
+ * incremental one under test.
+ * fresh — perturb BEFORE the first solve, so the end state is resolved
+ * from nothing in a registry that has no retained anything.
+ *
+ * `settle` is how a case asks for a frame mid-perturbation: real for the
+ * live run, a no-op for the fresh one, which must reach the end state
+ * without ever solving an intermediate.
+ */
+ async function differential(
+ setup: (app: App) => { root: number; row: number; leaves: number[] },
+ perturb: (
+ app: App,
+ ids: { root: number; row: number; leaves: number[] },
+ settle: () => Promise<void>,
+ ) => void | Promise<void>,
+ camAfter?: { w: number; h: number },
+ ): Promise<[Boxes, Boxes]> {
+ const live = createApp();
+ const liveIds = setup(live.app);
+ await live.app.tick(1 / 60);
+ await perturb(live.app, liveIds, () => live.app.tick(1 / 60));
+ if (camAfter) {
+ const cam = live.app.getResource(UICameraInfo);
+ cam.worldLeft = -camAfter.w / 2; cam.worldRight = camAfter.w / 2;
+ cam.worldBottom = -camAfter.h / 2; cam.worldTop = camAfter.h / 2;
+ }
+ await live.app.tick(1 / 60);
+ const incremental = read(live.registry, label(liveIds));
+ dispose(live.app, live.registry);
+
+ const fresh = createApp(camAfter?.w, camAfter?.h);
+ const freshIds = setup(fresh.app);
+ await perturb(fresh.app, freshIds, async () => { /* no intermediate solve */ });
+ await fresh.app.tick(1 / 60);
+ const scratch = read(fresh.registry, label(freshIds));
+ dispose(fresh.app, fresh.registry);
+
+ return [incremental, scratch];
+ }
+
+ it('resizing one leaf moves its siblings exactly as a fresh solve would', async () => {
+ const [inc, fresh] = await differential(
+ (app) => build(app, 5),
+ (app, ids) => {
+ const n = app.world.get(ids.leaves[2], UINode) as UINodeData;
+ app.world.insert(ids.leaves[2], UINode, { ...n, width: px(160) });
+ },
+ );
+ expect(inc).toEqual(fresh);
+ // And the change actually took, so this is not two identical no-ops.
+ expect(inc.leaf2.w).toBeCloseTo(160, 3);
+ });
+
+ it('changing the container re-places every child', async () => {
+ const [inc, fresh] = await differential(
+ (app) => build(app, 5),
+ (app, ids) => {
+ const fc = app.world.get(ids.row, FlexContainer) as Record<string, unknown>;
+ app.world.insert(ids.row, FlexContainer, { ...fc, justifyContent: 2, gap: { x: 40, y: 10 } });
+ },
+ );
+ expect(inc).toEqual(fresh);
+ });
+
+ // The retained node keeps whatever style it was last given, so "no
+ // FlexContainer" has to actively restore Yoga's defaults rather than leave
+ // the removed container's padding and justify in place.
+ it('removing the container clears the style it had applied', async () => {
+ const [inc, fresh] = await differential(
+ (app) => build(app, 4),
+ (app, ids) => { app.world.remove(ids.row, FlexContainer); },
+ );
+ expect(inc).toEqual(fresh);
+ });
+
+ it('adding a node lays out the new sibling and re-places the old ones', async () => {
+ const [inc, fresh] = await differential(
+ (app) => build(app, 4),
+ (app, ids) => {
+ const extra = app.world.spawn();
+ app.world.setParent(extra, ids.row);
+ app.world.insert(extra, UINode, node({ width: px(50), height: px(40) }));
+ app.world.insert(extra, Transform, TRANSFORM);
+ },
+ );
+ expect(inc).toEqual(fresh);
+ });
+
+ it('removing a node re-places the survivors', async () => {
+ const [inc, fresh] = await differential(
+ (app) => build(app, 5),
+ (app, ids) => { app.world.despawn(ids.leaves[1]); },
+ );
+ // leaf1 is gone in both; compare what is left.
+ delete inc.leaf1; delete fresh.leaf1;
+ expect(inc).toEqual(fresh);
+ });
+
+ // A subtree root positions itself against the camera box, so a resize moves
+ // every node even though Yoga may report no new layout for any of them.
+ it('resizing the camera re-places the whole tree', async () => {
+ const [inc, fresh] = await differential(
+ (app) => build(app, 5),
+ () => { /* only the camera changes */ },
+ { w: 1200, h: 400 },
+ );
+ expect(inc).toEqual(fresh);
+ });
+
+ // The case the parent-resize propagation exists for, and the only shape that
+ // exercises it: a child pinned to its parent's top-left keeps the exact same
+ // Yoga box when the parent resizes — same left, top, width, height — so Yoga
+ // rightly reports no new layout for it. Its WORLD position still moved,
+ // because that is measured from the parent's centre. Skip it and the child
+ // silently stays where the smaller parent had put it.
+ it('re-places a corner-pinned child when only its parent resized', async () => {
+ const buildPinned = (app: App) => {
+ const world = app.world;
+ const root = world.spawn();
+ world.insert(root, Canvas, {});
+ world.insert(root, UINode, node({
+ position: UIPositionType.Absolute,
+ insetLeft: px(0), insetTop: px(0), insetRight: px(0), insetBottom: px(0),
+ }));
+ world.insert(root, Transform, TRANSFORM);
+
+ const box = world.spawn();
+ world.setParent(box, root);
+ world.insert(box, UINode, node({ width: px(300), height: px(200) }));
+ world.insert(box, Transform, TRANSFORM);
+
+ const pinned = world.spawn();
+ world.setParent(pinned, box);
+ world.insert(pinned, UINode, node({
+ position: UIPositionType.Absolute,
+ insetLeft: px(0), insetTop: px(0),
+ width: px(50), height: px(30),
+ }));
+ world.insert(pinned, Transform, TRANSFORM);
+ return { root, row: box, leaves: [pinned] };
+ };
+
+ const [inc, fresh] = await differential(
+ buildPinned,
+ (app, ids) => {
+ const n = app.world.get(ids.row, UINode) as UINodeData;
+ app.world.insert(ids.row, UINode, { ...n, width: px(500) });
+ },
+ );
+ expect(inc).toEqual(fresh);
+ // The pinned child's own box is unchanged — which is exactly why Yoga
+ // reports nothing for it and the propagation has to carry the move.
+ expect(inc.leaf0.w).toBeCloseTo(50, 3);
+ expect(inc.leaf0.x).not.toBeCloseTo(fresh.row.x, 3);
+ });
+
+ it('a run of edits ends where one fresh solve of the end state does', async () => {
+ const [inc, fresh] = await differential(
+ (app) => build(app, 6),
+ async (app, ids, settle) => {
+ for (const [i, w] of [[0, 30], [3, 90], [5, 120], [0, 45]] as const) {
+ const n = app.world.get(ids.leaves[i], UINode) as UINodeData;
+ app.world.insert(ids.leaves[i], UINode, { ...n, width: px(w) });
+ await settle();
+ }
+ },
+ );
+ expect(inc).toEqual(fresh);
+ });
+});
diff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hpp
index 6c174d36e..de9c34012 100644
--- a/src/esengine/ecs/Registry.hpp
+++ b/src/esengine/ecs/Registry.hpp
@@ -73,6 +73,20 @@ public:
Registry(Registry&&) noexcept = default;
Registry& operator=(Registry&&) noexcept = default;
+ /**
+ * @brief Which registry this is — unique for the process, never reused.
+ *
+ * @details Entity ids are only meaningful WITHIN a registry: a fresh one
+ * hands out 1, 2, 3 again, so anything caching per entity across
+ * registries (a scene reload, an editor play/stop) would silently
+ * serve the previous world's data for the new world's entities.
+ * Comparing addresses cannot answer this — a destroyed registry's
+ * storage is routinely reused by the next one. Systems that keep
+ * per-entity state hold this alongside it and drop the lot when it
+ * changes; see UISystem's retained Yoga nodes.
+ */
+ u64 instanceId() const { return instance_id_; }
+
// =========================================================================
// Entity Management
// =========================================================================
@@ -601,6 +615,11 @@ public:
}
private:
+ // Handed out once per registry and never recycled, so it survives one being
+ // destroyed and the next taking its address. See instanceId().
+ static inline u64 next_instance_id_{0};
+ u64 instance_id_{++next_instance_id_};
+
// =========================================================================
// Private Helpers
// =========================================================================
diff --git a/src/esengine/ui/UILayoutSystem.cpp b/src/esengine/ui/UILayoutSystem.cpp
index fe525a51a..c5a1cc3af 100644
--- a/src/esengine/ui/UILayoutSystem.cpp
+++ b/src/esengine/ui/UILayoutSystem.cpp
@@ -206,6 +206,12 @@ void applyUINodeStyle(Registry& registry, Entity entity, YGNodeRef yg) {
applyMargin(yg, YGEdgeBottom, n.marginBottom);
// Container properties still come from FlexContainer (folded into UILayout in F4).
+ //
+ // The absent case is written out rather than skipped: this runs against a
+ // node that KEEPS its style between frames, so "no FlexContainer" has to
+ // actively say Yoga's defaults. Leaving them alone would let a removed
+ // FlexContainer's padding and justify go on laying the node out forever —
+ // the one thing a total style application must not do.
if (auto* fc = registry.tryGet<FlexContainer>(entity)) {
YGNodeStyleSetFlexDirection(yg, toYGFlexDirection(fc->direction));
YGNodeStyleSetFlexWrap(yg, toYGWrap(fc->wrap));
@@ -218,6 +224,18 @@ void applyUINodeStyle(Registry& registry, Entity entity, YGNodeRef yg) {
YGNodeStyleSetPadding(yg, YGEdgeTop, fc->padding.top);
YGNodeStyleSetPadding(yg, YGEdgeRight, fc->padding.right);
YGNodeStyleSetPadding(yg, YGEdgeBottom, fc->padding.bottom);
+ } else {
+ YGNodeStyleSetFlexDirection(yg, YGFlexDirectionColumn);
+ YGNodeStyleSetFlexWrap(yg, YGWrapNoWrap);
+ YGNodeStyleSetJustifyContent(yg, YGJustifyFlexStart);
+ YGNodeStyleSetAlignItems(yg, YGAlignStretch);
+ YGNodeStyleSetAlignContent(yg, YGAlignFlexStart);
+ YGNodeStyleSetGap(yg, YGGutterColumn, 0.0f);
+ YGNodeStyleSetGap(yg, YGGutterRow, 0.0f);
+ YGNodeStyleSetPadding(yg, YGEdgeLeft, 0.0f);
+ YGNodeStyleSetPadding(yg, YGEdgeTop, 0.0f);
+ YGNodeStyleSetPadding(yg, YGEdgeRight, 0.0f);
+ YGNodeStyleSetPadding(yg, YGEdgeBottom, 0.0f);
}
}
@@ -225,21 +243,24 @@ void applyUINodeStyle(Registry& registry, Entity entity, YGNodeRef yg) {
// `availW/H` + `parentPivot*` describe the available box the root sits in.
void layoutUINodeSubtree(
Registry& registry, UITree& tree, LayoutCache& cache, i32 rootIdx,
- f32 availW, f32 availH, f32 parentPivotX, f32 parentPivotY
+ f32 availW, f32 availH, f32 parentPivotX, f32 parentPivotY,
+ bool structureChanged, bool forceWriteback
) {
i32 begin = rootIdx;
i32 end = rootIdx + tree.nodes_[rootIdx].subtree_size;
std::vector<YGNodeRef> yg(static_cast<usize>(end - begin), nullptr);
std::unordered_map<Entity, i32> slotOf; // entity → local slot index
- // Reuse the retained YGNode per entity. layoutUpdate orphaned the whole
- // forest first, so every node here is childless + owner-less; resetting it
- // to Yoga defaults makes reuse identical to a fresh YGNodeNew.
+ // The retained YGNode KEEPS its style between frames, and re-applying it is
+ // how Yoga is told what moved: every YGNodeStyleSet* is `if (old != new)
+ // { set; markDirtyAndPropagate(); }`, so a field that did not change costs
+ // one comparison and dirties nothing. Resetting first (as this used to) made
+ // every field look changed, which dirtied every node and threw away the
+ // incremental solve the retained nodes exist for.
for (i32 k = begin; k < end; ++k) {
Entity e = tree.nodes_[k].entity;
if (!registry.has<UINode>(e)) continue; // tree is homogeneously UINode
YGNodeRef node = cache.getOrCreate(e);
- YGNodeReset(node);
applyUINodeStyle(registry, e, node);
yg[static_cast<usize>(k - begin)] = node;
slotOf[e] = k - begin;
@@ -247,13 +268,22 @@ void layoutUINodeSubtree(
YGNodeRef rootYG = yg[0];
if (!rootYG) return;
- for (i32 k = begin + 1; k < end; ++k) {
- YGNodeRef child = yg[static_cast<usize>(k - begin)];
- if (!child) continue;
- auto it = slotOf.find(tree.nodes_[k].parent);
- if (it == slotOf.end()) continue;
- YGNodeRef parentYG = yg[static_cast<usize>(it->second)];
- YGNodeInsertChild(parentYG, child, YGNodeGetChildCount(parentYG));
+ // Parenting is rebuilt only when the tree's shape actually changed. Yoga's
+ // own child list is the retained hierarchy the rest of the time — and
+ // re-inserting an unchanged child would dirty it for nothing.
+ if (structureChanged) {
+ for (i32 k = begin; k < end; ++k) {
+ YGNodeRef node = yg[static_cast<usize>(k - begin)];
+ if (node) YGNodeRemoveAllChildren(node);
+ }
+ for (i32 k = begin + 1; k < end; ++k) {
+ YGNodeRef child = yg[static_cast<usize>(k - begin)];
+ if (!child) continue;
+ auto it = slotOf.find(tree.nodes_[k].parent);
+ if (it == slotOf.end()) continue;
+ YGNodeRef parentYG = yg[static_cast<usize>(it->second)];
+ YGNodeInsertChild(parentYG, child, YGNodeGetChildCount(parentYG));
+ }
}
// The root fills the available box on axes it leaves auto.
@@ -263,13 +293,36 @@ void layoutUINodeSubtree(
YGNodeCalculateLayout(rootYG, availW, availH, YGDirectionLTR);
+ // Which nodes' own box changed, by local slot. A node whose PARENT resized
+ // has to be written even when Yoga left its own box alone: the local
+ // position below is expressed against the parent's computed size, so the
+ // same Yoga offset inside a resized parent is a different world position.
+ // DFS order guarantees a parent's entry is filled before its children read it.
+ std::vector<u8> resized(static_cast<usize>(end - begin), 0);
+
for (i32 k = begin; k < end; ++k) {
YGNodeRef node = yg[static_cast<usize>(k - begin)];
if (!node) continue;
Entity e = tree.nodes_[k].entity;
+
+ bool parentResized = false;
+ if (k != begin) {
+ auto it = slotOf.find(tree.nodes_[k].parent);
+ if (it != slotOf.end()) parentResized = resized[static_cast<usize>(it->second)] != 0;
+ }
+ // Yoga tells us what it recomputed; everything else still holds the
+ // output of the last solve, which is still correct.
+ if (!forceWriteback && !YGNodeGetHasNewLayout(node) && !parentResized) {
+ tree.nodes_[k].flags &= ~(LAYOUT_DIRTY | HAS_DIRTY_CHILD);
+ continue;
+ }
+ YGNodeSetHasNewLayout(node, false);
+
auto& un = registry.get<UINode>(e);
f32 fw = YGNodeLayoutGetWidth(node);
f32 fh = YGNodeLayoutGetHeight(node);
+ resized[static_cast<usize>(k - begin)] =
+ (un.computed_size_.x != fw || un.computed_size_.y != fh) ? 1 : 0;
un.computed_size_.x = fw;
un.computed_size_.y = fh;
@@ -387,7 +440,9 @@ bool anyUIAnimActive(Registry& registry) {
return active;
}
-void unifiedLayoutPass(Registry& registry, UITree& tree, LayoutCache& cache, const LayoutRect& cameraRect) {
+void unifiedLayoutPass(Registry& registry, UITree& tree, LayoutCache& cache,
+ const LayoutRect& cameraRect, bool structureChanged,
+ bool forceWriteback) {
for (i32 i = 0; i < static_cast<i32>(tree.nodes_.size()); ) {
auto& node = tree.nodes_[i];
@@ -403,7 +458,8 @@ void unifiedLayoutPass(Registry& registry, UITree& tree, LayoutCache& cache, con
if (!parentIsUINode) {
f32 availW = cameraRect.right - cameraRect.left;
f32 availH = cameraRect.top - cameraRect.bottom;
- layoutUINodeSubtree(registry, tree, cache, i, availW, availH, 0.5f, 0.5f);
+ layoutUINodeSubtree(registry, tree, cache, i, availW, availH, 0.5f, 0.5f,
+ structureChanged, forceWriteback);
}
i += node.subtree_size;
}
@@ -420,7 +476,17 @@ void UISystem::layoutUpdate(
f32 camLeft, f32 camBottom, f32 camRight, f32 camTop,
bool tsPropertyDirty
) {
- if (!layoutCache_) layoutCache_ = std::make_unique<LayoutCache>();
+ // The retained nodes are keyed by entity, and entity ids restart with each
+ // registry — so a scene reload or an editor play/stop would otherwise hand
+ // the new world the previous world's layout. This is only load-bearing now
+ // that styles persist between frames: the old pass reset every node it
+ // touched, which hid the aliasing by throwing the stale state away.
+ if (layoutCache_ && lastRegistryId_ != registry.instanceId()) layoutCache_.reset();
+ lastRegistryId_ = registry.instanceId();
+ if (!layoutCache_) {
+ layoutCache_ = std::make_unique<LayoutCache>();
+ layoutPrimed_ = false; // a fresh cache has no hierarchy to reuse
+ }
// Rebuild the DFS node list every pass: it is O(N) pointer-walking (no Yoga)
// and yields the structure signature that detects spawn/despawn/reparent —
@@ -442,30 +508,38 @@ void UISystem::layoutUpdate(
// the last solve — leaves the retained YGNodes and every UINode's computed
// output valid, so the whole solve is safely skipped. `wasAnimActive` forces
// one more solve on the frame a tween just ended (see anyUIAnimActive).
- bool dirty = !layoutPrimed_ || sigChanged || rectChanged || tsPropertyDirty
+ bool first = !layoutPrimed_;
+ bool dirty = first || sigChanged || rectChanged || tsPropertyDirty
|| animNow || wasAnimActive;
layoutPrimed_ = true;
if (!dirty) return;
- // Orphan the entire retained forest up front. Each subtree then rebuilds its
- // own hierarchy from childless nodes, so an entity that moved between Canvas
- // roots since last frame is never still owned by its old parent on re-insert.
- for (auto& node : tree.nodes_) {
- if (registry.has<UINode>(node.entity)) {
- YGNodeRemoveAllChildren(layoutCache_->getOrCreate(node.entity));
- }
- }
-
+ // Two signals, because they answer different questions. The hierarchy has to
+ // be rebuilt when the tree's SHAPE changed. Output has to be written for
+ // every node when the ROOT'S FRAME changed — a subtree root positions itself
+ // against the camera box, so the same Yoga result inside a resized box is a
+ // different world position, and Yoga would rightly report no new layout.
+ bool structureChanged = first || sigChanged;
+ bool forceWriteback = structureChanged || rectChanged;
+
+ // The retained hierarchy is rebuilt only when the tree's shape changed —
+ // which is exactly when an entity may still be owned by the parent it had
+ // last frame. Orphaning unconditionally (as this used to) dirtied every
+ // Yoga node on every pass, so no solve could ever be partial.
propagateHiddenInTree(registry, tree);
propagateInheritedUIState(registry, tree);
LayoutRect cameraRect{ camLeft, camBottom, camRight, camTop };
- unifiedLayoutPass(registry, tree, *layoutCache_, cameraRect);
-
- // Reap YGNodes whose entity left the tree this frame.
- std::unordered_set<Entity> live;
- live.reserve(tree.nodes_.size());
- for (auto& node : tree.nodes_) live.insert(node.entity);
- layoutCache_->reap(live);
+ unifiedLayoutPass(registry, tree, *layoutCache_, cameraRect, structureChanged, forceWriteback);
+
+ // Reaping is likewise a structural concern: with the same set of entities in
+ // the tree there is nothing to free, and building the live set is a hash
+ // insert per node.
+ if (structureChanged) {
+ std::unordered_set<Entity> live;
+ live.reserve(tree.nodes_.size());
+ for (auto& node : tree.nodes_) live.insert(node.entity);
+ layoutCache_->reap(live);
+ }
}
// Out-of-line so LayoutCache is complete here (it holds Yoga types kept out of
diff --git a/src/esengine/ui/UISystem.hpp b/src/esengine/ui/UISystem.hpp
index 498a4c0ba..e59cb931c 100644
--- a/src/esengine/ui/UISystem.hpp
+++ b/src/esengine/ui/UISystem.hpp
@@ -115,6 +115,9 @@ private:
f32 lastCamL_{0}, lastCamB_{0}, lastCamR_{0}, lastCamT_{0};
bool lastAnimActive_{false};
bool layoutPrimed_{false}; // force a solve on the very first pass
+ // Which registry the retained Yoga nodes belong to — entity ids restart with
+ // each one, so they mean nothing across registries (Registry::instanceId).
+ u64 lastRegistryId_{0};
};
} // namespace esengine::ecs