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.

bench(ecs): what a composition costs when it also says which transforms moved

esenginef6225596ebaf
diff --git a/bench/replication-interest/README.md b/bench/replication-interest/README.md
index cc801902f..f84995478 100644
--- a/bench/replication-interest/README.md
+++ b/bench/replication-interest/README.md
@@ -146,6 +146,14 @@ Three things are asserted rather than assumed:
- The per-connection dirty and removal filters are timed and counted but stay
tiny at these rates. If a provider removes the interest query, `C × (D + R)`
is the next thing to look at — measured, not guessed.
+- **The composed output has a second author, and an incremental provider is not
+ production-complete until that is resolved.** `registry_batchSyncPhysics-
+ Transforms` writes `worldPosition`/`worldRotation`/`worldScale` itself, marks
+ the transform decomposed, and bypasses `TransformSystem` — so a provider fed by
+ what the COMPOSITION says changed would silently not contain any physics-driven
+ entity. Composition has a canonical author now, which is what turns that into a
+ question with an answer; it is not this one. See
+ `bench/transform-composition/README.md` for what the composition can hand over.
- Custom `position()` readers are why a provider cannot simply index everything:
the server has no way to know when a caller's arbitrary function would return
something new. That is a design constraint on any provider, not a cost measured here.
diff --git a/bench/transform-composition/README.md b/bench/transform-composition/README.md
new file mode 100644
index 000000000..44d409176
--- /dev/null
+++ b/bench/transform-composition/README.md
@@ -0,0 +1,109 @@
+# What it costs for a composition to say which world transforms moved
+
+The interest path's remaining cost is rebuilding its spatial grid every sample —
+181% of a core at 100k × 32, against 9% for the queries it answers. An index that
+kept itself would spend the build column on the entities that actually moved
+instead, and the only place that knows which those are is the composition itself.
+
+So before designing that index: **given the composition already walks every
+transform, what does it cost to also hand back the entities whose output
+differs?**
+
+## Two sets, and they are not the same size
+
+| | what it is |
+|---|---|
+| **visited** | entities `TransformSystem` wrote this pass |
+| **changed** | entities whose composed OUTPUT differs from what it was |
+
+`visited` is not a useful answer. A non-static root is recomposed
+unconditionally, so on a flat world the walk writes all 100,000 of them whatever
+moved — a consumer told "100,000 composed" learns nothing it did not already
+know. `changed` is the set an incremental index would maintain itself from.
+
+## The output does not have one representation
+
+A **root** publishes decomposed world TRS (`worldPosition`/`worldRotation`/
+`worldScale`, `decomposed_ = true`). A **child** publishes `cachedMatrix_` and is
+decomposed lazily, by whoever reads it. So the comparison is against whichever
+one the entity actually publishes — and an entity arriving from the child path
+with no decomposed TRS has nothing to compare, so it counts as changed.
+
+`decomposed_` itself is **not** part of the output. A READ flips it: the pointer
+accessor decomposes on the way out, so an entity anyone looked at would be
+reported as having moved. The first version of this did test it, and reported
+every child the bench had read — 198 of 200 — as changed in a workload where
+nothing moved at all.
+
+## The arms
+
+| | |
+|---|---|
+| **A** | compose, as it ships |
+| **B** | the same compose, collecting the entities whose output differs |
+
+Both run in **one process, alternating passes** over the same world. Measured in
+separate processes they differed by more than the thing being measured: B came
+out *faster* than A on the tree shape, by 33%.
+
+## What it costs
+
+`node bench/transform-composition/run.mjs`, 100,000 entities, one compose per
+pass. The tree is 1,000 roots of 99 children each.
+
+| workload | A µs | B µs | B/A | visited | changed |
+|---|---|---|---|---|---|
+| flat, nothing writes | 0.3 | 1.8 | — | — | — |
+| flat, 1% written, none of it moved | 638 | 847 | 1.33 | 100,000 | **0** |
+| flat, 1% moved | 634 | 848 | 1.34 | 100,000 | **1,000** |
+| flat, everything moved | 651 | 908 | 1.40 | 100,000 | 100,000 |
+| tree, 1% moved | 1,944 | 2,085 | 1.07 | 100,000 | **1,000** |
+| tree, 1% of roots moved, subtrees follow | 1,868 | 1,959 | 1.05 | 100,000 | **1,000** |
+| tree, one subtree changes parent | 1,871 | 1,970 | 1.05 | 100,000 | **1** |
+
+The `nothing writes` row is the epoch gate, not a composition: neither arm walks
+anything, and B's 1.8 µs is the probe binding allocating a JS object to answer
+with. It is in the table to show the gate holds, not as a cost.
+
+**The collection is 1.3% of a core.** 213 µs on top of a compose, at 60 composes
+per second, is 12,800 µs per simulated second. The grid rebuild it could replace
+is 1,810,169 — **0.7% of the cost of the thing it would let us stop doing**.
+
+Three results decide the shape of the index rather than its price:
+
+- **1,000 of 100,000.** At 1% movement the changed set is 1% of the visited one,
+ in both shapes. A grid that touched only those entries would do 1% of the
+ rebuild's work.
+- **Writing without moving costs nothing extra to detect.** 1% of entities
+ written back unchanged produces `changed = 0` — the epoch cannot tell that case
+ from real movement, and the comparison can. A tween finishing on its final
+ value, a physics body asleep, an editor drag that snapped back: all free.
+- **A reparent that does not move anything changes one entity.** The subtree
+ keeps its world positions, so only the entity whose published representation
+ flipped is in the set.
+
+The tree pays proportionally less (1.05 against 1.34) because a child's compose
+is a mat4 multiply and the comparison is 16 floats beside it, where a root's
+compose is three copies.
+
+Both arms read back the world position the probe should have composed, and the
+tree's probe is a child — the path that publishes a matrix rather than a TRS. An
+arm that stops composing turns four of the seven points red; the other three
+never move their probe, so the check is live where movement is.
+
+## What this does not cover
+
+- **Physics is a second author of the composed output.** `registry_batchSync-
+ PhysicsTransforms` writes the world fields itself, `decomposed_ = true`,
+ without going through `TransformSystem`. A journal built on this collection
+ would not contain those entities. **Not production-complete until that
+ ownership is resolved** — the composition has a canonical author now, which is
+ what makes it a question with an answer, but it is not this one.
+- Nothing ships. `composeCollecting` has one caller and it is this bench; the
+ shipped `ensureComposed` path collects nothing and pays one predictable branch
+ per entity, which the A column is what says is affordable.
+- The set is COUNTED here, not consumed. What an index costs to update from it —
+ cell removal, reinsertion, and the ownership of entities that left the world
+ entirely — is the next measurement, not this one.
+- One compose per pass. A frame that runs several fixed steps composes several
+ times, and the changed sets would have to be unioned or consumed per step.
diff --git a/bench/transform-composition/arm.mjs b/bench/transform-composition/arm.mjs
new file mode 100644
index 000000000..06096a45b
--- /dev/null
+++ b/bench/transform-composition/arm.mjs
@@ -0,0 +1,155 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file What it costs for a composition to say which world transforms moved.
+ *
+ * The composition already walks every transform when anything is stale. A
+ * consumer keyed on world position — a spatial index, a replication journal —
+ * wants the entities whose OUTPUT differs, which is a strictly smaller set than
+ * the one the walk visits: on a flat world the walk visits all of them whatever
+ * moved. This times the same compose with and without producing that set.
+ *
+ * node bench/transform-composition/arm.mjs --arm B --shape flat --mutate local
+ */
+import path from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
+const argv = process.argv.slice(2);
+const flag = (name, fallback) => {
+ const i = argv.indexOf(`--${name}`);
+ return i >= 0 && argv[i + 1] !== undefined ? argv[i + 1] : fallback;
+};
+
+const SHAPE = flag('shape', 'flat');
+const MUTATE = flag('mutate', 'local');
+const ENTITIES = Number(flag('entities', '100000'));
+const CHILDREN = Number(flag('children', '99'));
+const RATE = Number(flag('rate', '0.01'));
+const WARMUP = Number(flag('warmup', '10'));
+const MEASURE = Number(flag('measure', '40'));
+
+const sdk = await import(pathToFileURL(path.join(ROOT, 'sdk', 'dist', 'index.node.js')).href);
+const wasmDir = process.env.ESENGINE_WASM_DIR ?? path.join(ROOT, 'build', 'wasm', 'web');
+const factory = (await import(pathToFileURL(path.join(wasmDir, 'esengine.js')).href)).default;
+const module = await factory({ locateFile: (f) => path.join(wasmDir, f) });
+
+const app = sdk.App.new();
+app.connectCpp(new module.Registry(), module, { strict: false });
+const world = app.world;
+const registry = world.getCppRegistry();
+
+/** Every entity, and the roots among them — a mutation picks from one or other. */
+const all = [];
+const roots = [];
+if (SHAPE === 'flat') {
+ for (let i = 0; i < ENTITIES; i++) {
+ const e = world.spawn();
+ world.insert(e, sdk.Transform, { position: { x: i, y: 0, z: 0 } });
+ all.push(e); roots.push(e);
+ }
+} else {
+ for (let i = 0; all.length < ENTITIES; i++) {
+ const r = world.spawn();
+ world.insert(r, sdk.Transform, { position: { x: i, y: 0, z: 0 } });
+ all.push(r); roots.push(r);
+ for (let c = 0; c < CHILDREN && all.length < ENTITIES; c++) {
+ const kid = world.spawn();
+ world.insert(kid, sdk.Transform, { position: { x: c, y: 0, z: 0 } });
+ world.setParent(kid, r);
+ all.push(kid);
+ }
+ }
+}
+
+const setter = world.resolveSetter(sdk.Transform);
+const getter = world.resolveGetter(sdk.Transform, 'borrowed');
+const K = Math.max(1, Math.round(all.length * RATE));
+const R = Math.max(1, Math.round(roots.length * RATE));
+
+/** One producer's worth of work, timed separately from the compose it makes stale. */
+function mutate(tick) {
+ switch (MUTATE) {
+ case 'none': return;
+ case 'still': {
+ // Every write happens; none of them moves anything. The epoch cannot
+ // tell the difference — comparing the output is the only thing that can.
+ for (let i = 0; i < K; i++) { const t = getter(all[i]); setter(all[i], t); }
+ break;
+ }
+ case 'parent': {
+ // A share of the ROOTS, so what the subtree costs is visible: 1% of
+ // all entities would be every root in this shape.
+ for (let i = 0; i < R; i++) {
+ const t = getter(roots[i]); t.position.x += 1; setter(roots[i], t);
+ }
+ break;
+ }
+ case 'reparent': {
+ // One subtree changes parent and comes back, so the shape is steady.
+ if (tick % 2 === 0) world.setParent(roots[1], roots[0]);
+ else world.removeParent(roots[1]);
+ return; // setParent is a producer already; it announces for itself
+ }
+ default: {
+ for (let i = 0; i < K; i++) {
+ const t = getter(all[i]); t.position.x += 1; setter(all[i], t);
+ }
+ }
+ }
+ // The ptr setter writes the component heap and calls no C++, which is exactly
+ // why a producer has to say so. One notification per pass, as a system does.
+ world.invalidateTransformComposition();
+}
+
+const collecting = module.transform_composeCollecting;
+let visitedSum = 0;
+let changedSum = 0;
+let ran = 0;
+
+// Both arms in one process, alternating passes. Run apart they disagreed by more
+// than the thing being measured — two node processes differ by more than a
+// hundred microseconds of compose, and B came out FASTER than A on the tree.
+function composeA() { world.ensureTransformsComposed(); }
+function composeB() {
+ const r = collecting(registry);
+ if (r.ran) { ran++; visitedSum += r.visited; changedSum += r.changed; }
+}
+
+for (let t = 0; t < WARMUP; t++) { mutate(t); (t % 2 ? composeB : composeA)(); }
+ran = 0; visitedSum = 0; changedSum = 0;
+let nsA = 0;
+let nsB = 0;
+let passesA = 0;
+let passesB = 0;
+for (let t = 0; t < MEASURE; t++) {
+ mutate(t);
+ const collect = t % 2 === 1;
+ const t0 = process.hrtime.bigint();
+ if (collect) composeB(); else composeA();
+ const dt = Number(process.hrtime.bigint() - t0);
+ if (collect) { nsB += dt; passesB++; } else { nsA += dt; passesA++; }
+}
+
+// The world the two arms produced between them, against what it should be: an
+// arm that composed nothing would time beautifully and mean nothing. For the
+// tree the probe is a CHILD, which is the path that publishes a matrix.
+const probe = SHAPE === 'flat' ? all[0] : all[1];
+const composed = world.get(probe, sdk.Transform).worldPosition;
+const localX = world.get(probe, sdk.Transform).position.x;
+const parentX = SHAPE === 'flat' ? 0 : world.get(roots[0], sdk.Transform).position.x;
+const expectedX = localX + parentX;
+
+process.stdout.write(`${JSON.stringify({
+ shape: SHAPE, mutate: MUTATE, entities: all.length, roots: roots.length,
+ mutated: MUTATE === 'none' ? 0 : MUTATE === 'reparent' ? 1 : MUTATE === 'parent' ? R : K,
+ passes: MEASURE, composedPasses: ran,
+ usA: nsA / 1000 / passesA,
+ usB: nsB / 1000 / passesB,
+ oneCorePercentA: (nsA / 1000 / passesA) * 60 / 1e4,
+ // Per COMPOSED pass: a workload that never goes stale composed none, and
+ // averaging over the passes it skipped would report a fraction of a set.
+ visited: ran ? Math.round(visitedSum / ran) : null,
+ changed: ran ? Math.round(changedSum / ran) : null,
+ composedX: composed.x, expectedX, agrees: composed.x === expectedX,
+})}\n`);
diff --git a/bench/transform-composition/run.mjs b/bench/transform-composition/run.mjs
new file mode 100644
index 000000000..9dac1348c
--- /dev/null
+++ b/bench/transform-composition/run.mjs
@@ -0,0 +1,78 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file What it costs for a composition to say which world transforms moved.
+ *
+ * node bench/transform-composition/run.mjs
+ *
+ * Ships nothing: no production path asks for the changed set yet.
+ */
+import { spawnSync } from 'node:child_process';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { sdkIdentity } from '../replication-dirty/workload.mjs';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const ROOT = path.resolve(HERE, '..', '..');
+const ARM = path.join(HERE, 'arm.mjs');
+const ENTITIES = Number(process.env.BENCH_ENTITIES ?? 100000);
+
+/** Each point says what moved, which is what makes the two set sizes mean something. */
+const POINTS = [
+ { shape: 'flat', mutate: 'none', rate: 0, says: 'nothing writes' },
+ { shape: 'flat', mutate: 'still', rate: 0.01, says: '1% written, none of it moved' },
+ { shape: 'flat', mutate: 'local', rate: 0.01, says: '1% moved' },
+ { shape: 'flat', mutate: 'local', rate: 1, says: 'everything moved' },
+ { shape: 'tree', mutate: 'local', rate: 0.01, says: '1% moved, in a 1000-root tree' },
+ { shape: 'tree', mutate: 'parent', rate: 0.01, says: '1% of roots moved, subtrees follow' },
+ { shape: 'tree', mutate: 'reparent', rate: 0, says: 'one subtree changes parent' },
+];
+
+function run(p) {
+ const out = spawnSync(process.execPath, [
+ ARM, '--shape', p.shape, '--mutate', p.mutate,
+ '--entities', String(ENTITIES), '--rate', String(p.rate),
+ '--warmup', '10', '--measure', '120',
+ ], { encoding: 'utf8', cwd: ROOT, maxBuffer: 1 << 24 });
+ if (out.status !== 0) {
+ console.error(out.stderr || out.stdout);
+ throw new Error(`${p.shape}/${p.mutate} exited ${out.status}`);
+ }
+ return JSON.parse(out.stdout);
+}
+
+const rows = POINTS.map((p) => ({ p, r: run(p) }));
+
+const say = (s = '') => console.log(s);
+const pad = (v, w) => String(v).padStart(w);
+say('');
+say(`=== what it costs to also say WHICH world transforms moved (${ENTITIES} entities) ===`);
+say('');
+say(' A compose, as it ships');
+say(' B the same compose, collecting the entities whose OUTPUT differs');
+say('');
+// Both arms drove the same mutation sequence, so they must have composed the
+// same world. An arm that composed nothing would be the fastest one here.
+// Measured apart, the two arms differed by more than the thing being measured.
+say(' Both arms ran in one process, alternating passes over the same world.');
+const wrong = rows.filter(({ r }) => !r.agrees);
+say(wrong.length === 0
+ ? ' Every point read back the world position it should have composed.'
+ : ` WRONG WORLD at ${wrong.length} point(s) — the numbers mean nothing.`);
+say('');
+say(' workload A us B us B/A visited changed');
+for (const { p, r } of rows) {
+ const name = `${p.shape}/${p.mutate} — ${p.says}`;
+ const ratio = r.usA > 0 ? (r.usB / r.usA).toFixed(2) : '—';
+ const visited = r.visited === null ? '—' : r.visited;
+ const changed = r.changed === null ? '—' : r.changed;
+ say(` ${name.padEnd(46)} ${pad(r.usA.toFixed(1), 6)} ${pad(r.usB.toFixed(1), 6)} ${pad(ratio, 5)} ${pad(visited, 8)} ${pad(changed, 8)}`);
+}
+say('');
+const flat1 = rows.find(({ p }) => p.shape === 'flat' && p.mutate === 'local' && p.rate === 0.01).r;
+say(` At 1% movement the walk writes ${flat1.visited} and ${flat1.changed} of them actually moved:`);
+say(' the set a consumer keyed on world position wants is the second one, and');
+say(' nothing outside the composition can tell them apart without reading all of it.');
+say('');
+say(` ${JSON.stringify({ ...sdkIdentity(ROOT), cpu: os.cpus()[0]?.model })}`);
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index c6a2b9e17..99ba245b3 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -648,6 +648,20 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
ts->ensureComposed(registry);
}
}), emscripten::allow_raw_pointers());
+ // The same composition, asked to also say WHICH entities' output moved — the
+ // set an incremental spatial index would maintain itself from. Costed in
+ // bench/transform-composition; no shipped path calls it.
+ emscripten::function("transform_composeCollecting", emscripten::optional_override(
+ [](esengine::ecs::Registry& registry) -> emscripten::val {
+ static std::vector<esengine::Entity> changed;
+ auto* ts = esengine::ctx().tryGet<esengine::ecs::TransformSystem>();
+ auto out = emscripten::val::object();
+ const bool ran = ts && ts->composeCollecting(registry, changed);
+ out.set("ran", ran);
+ out.set("visited", ts ? ts->visited() : 0u);
+ out.set("changed", static_cast<esengine::u32>(ran ? changed.size() : 0));
+ return out;
+ }), emscripten::allow_raw_pointers());
emscripten::function("renderer_setEntityDrawOrder", &esengine::renderer_setEntityDrawOrder);
emscripten::function("renderer_submitAll", &esengine::renderer_submitAll);
#ifdef ES_ENABLE_PARTICLES
diff --git a/src/esengine/ecs/TransformSystem.hpp b/src/esengine/ecs/TransformSystem.hpp
index e00a28477..313510aec 100644
--- a/src/esengine/ecs/TransformSystem.hpp
+++ b/src/esengine/ecs/TransformSystem.hpp
@@ -76,6 +76,30 @@ public:
u32 composedEpoch() const { return composedEpoch_; }
+ /**
+ * @brief Compose, and answer which entities' composed OUTPUT actually moved
+ * @param changed Receives those entities; cleared first
+ * @return Whether it composed at all (false = nothing was stale)
+ * @details Not the set the walk VISITED: a non-static root is recomposed
+ * unconditionally. Costed in bench/transform-composition.
+ * @note A root publishes decomposed world TRS and a child publishes
+ * `cachedMatrix_`, so each is compared against the one it publishes.
+ */
+ bool composeCollecting(Registry& registry, std::vector<Entity>& changed) {
+ changed.clear();
+ visited_ = 0;
+ if (registry.instanceId() == composedRegistry_
+ && transformMutationEpoch() == composedEpoch_) return false;
+ changed_ = &changed;
+ updateDirtyTransforms(registry);
+ changed_ = nullptr;
+ markComposed(registry);
+ return true;
+ }
+
+ /** How many entities the last collecting compose actually wrote. */
+ u32 visited() const { return visited_; }
+
private:
// Zero, while the epoch starts at one: nothing has been composed yet, so the
// first ensure runs rather than believing a world it has never looked at.
@@ -89,6 +113,11 @@ private:
std::vector<Entity> dirty_to_clear_;
+ // Null on the shipped path: composition answers "are they stale", and only a
+ // caller building an incremental structure pays for "which ones moved".
+ std::vector<Entity>* changed_ = nullptr;
+ u32 visited_ = 0;
+
void updateDirtyTransforms(Registry& registry) {
dirty_to_clear_.clear();
@@ -127,6 +156,15 @@ private:
}
void updateRootTransform(Registry& registry, Entity entity, Transform& transform) {
+ if (changed_) {
+ ++visited_;
+ if (!transform.decomposed_
+ || transform.worldPosition != transform.position
+ || transform.worldRotation != transform.rotation
+ || transform.worldScale != transform.scale) {
+ changed_->push_back(entity);
+ }
+ }
transform.worldPosition = transform.position;
transform.worldRotation = transform.rotation;
transform.worldScale = transform.scale;
@@ -183,6 +221,13 @@ private:
glm::mat4 localMatrix = math::compose(transform.position, transform.rotation, transform.scale);
glm::mat4 worldMatrix = parentWorldMatrix * localMatrix;
+ if (changed_) {
+ ++visited_;
+ // `decomposed_` is not part of the output: a READ flips it (the ptr
+ // accessor decomposes on the way out), so testing it here reports
+ // every child anyone looked at as having moved.
+ if (worldMatrix != transform.cachedMatrix_) changed_->push_back(entity);
+ }
transform.cachedMatrix_ = worldMatrix;
transform.decomposed_ = false;
diff --git a/tools/check-engine-exports.mjs b/tools/check-engine-exports.mjs
index eaee8a805..14eb6289a 100644
--- a/tools/check-engine-exports.mjs
+++ b/tools/check-engine-exports.mjs
@@ -30,7 +30,10 @@ const byName = new Set([...layouts.matchAll(/ptrFn:\s*'(\w+)'/g)].map((m) => m[1
// read back through another binding. `wasm.ts` declares the surface rather than
// calling it, and generated files name every entry by construction.
const { files, missing } = listTrackedSources(
- ['sdk/src', 'sdk/tests', 'desktop/src', 'desktop/electron', 'desktop/tests', 'tools', 'pipeline/src']);
+ ['sdk/src', 'sdk/tests', 'desktop/src', 'desktop/electron', 'desktop/tests', 'tools', 'pipeline/src',
+ // A bench is a host too, and some entry points exist to be measured
+ // before anything is designed around them. Exercised is exercised.
+ 'bench']);
if (missing.length) {
console.log(`check-engine-exports: no editor checkout — ${missing.join(', ')} not scanned for callers.`);
}