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.

feat(ecs): every component carries the tick of its last write, and an audit finds a write that left none - Registry::patch, markChanged, changedSince and anyChangedSince over stamps kept beside the components, the reader's tick from beginChangeRead, and setChangeAudit, which reports each component type written without a stamp; the first step toward a renderer that walks only what changed

yhh7c54c1e42b41
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index fd4452aa9..592bec951 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -39,7 +39,7 @@ env:
test_touch_stream
test_frame_lifecycle
test_particle_stretch test_particle_speed_limit test_particle_bursts
- test_record_table
+ test_record_table test_change_stamps
jobs:
playable-runtime:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ef33c6ee9..5fbb51a7d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,7 @@ published separately; it ships inside the editor.
### Added
+- **Components carry the tick of their last write.** Each component pool keeps, beside every component, the tick at which it was last written, added or replaced, and the latest such tick of the pool. `Registry::patch<T>()` is mutable access that stamps the write, `markChanged<T>()` stamps a write made through a reference held from before, and adding or replacing a component stamps it; `get<T>()` stamps nothing. A reader asks `beginChangeRead()` for the tick it looks at, and next time `changedSince<T>(entity, tick)` and `anyChangedSince<T>(tick)` say what was written after that look, including what was written later in the same frame. Stamps travel with their components through a removal and a re-sort, and are kept within half the counter's range so none reads as new after the tick wraps. `Registry::setChangeAudit` (`World.setChangeAudit` from script) keeps a copy of every component each frame and reports each type written without a stamp, which is what a consumer of changes would never see; `render-submit-cost.mjs --audit` runs it on an example. Nothing reads the stamps yet: this is the ground for a renderer that walks only what changed, and the audit lists what still writes without saying so (an animated rig's bones, the platformer's and the 3D physics example's moving bodies).
- **A playable opens on a start screen.** A single-file playable showed an empty page until its first frame: the engine inflated and compiled, the scene loaded, and with `quality.prewarmShaders` its shaders warmed, twenty-five seconds for one lake scene in a headless browser. It now carries the web export's start screen (the game's title, a bar, what the boot is doing), in markup that is on screen before any script runs, and announces the same `esengine:bootprogress` and `esengine:firstframe` events. `initPlayableRuntime` takes `onBeforeRun`, called once everything is loaded and warmed, and `prewarmShaders.onProgress`. A stretch of a boot nothing measures (shaders compiling, then a ground or a field still being made) runs a light along the bar and says which it is, where the bar used to sit still on "Ready"; a web export's start screen does the same.
- **A terrain layer and a field of plants each say how much of the sky reaches them.** A `.esterrainlayer`'s `occlusion` (0 to 1) scales the occlusion its mask holds, and the Foliage material's `u_rootOcclusion` is the sky's light at a plant's root, rising to all of it at the tip. Both dim only the environment's light, as a material's ambient occlusion does; the sun and other lights are as they were. Left out (1), nothing changes. The terrain layer editor has the field.
- **An ambient light's diffuse has its own scale and tint.** `diffuseScale` and `diffuseTint` on an Ambient light multiply the light its environment gives surfaces, and leave the reflections and the sky drawn behind them as they were: a sky whose irradiance is too dark or too blue for a look is lifted without brightening every reflection. At 1 and white (the defaults) nothing changes.
diff --git a/pipeline/src/runtime/gameHost.ts b/pipeline/src/runtime/gameHost.ts
index 9b41e4676..08492e1c3 100644
--- a/pipeline/src/runtime/gameHost.ts
+++ b/pipeline/src/runtime/gameHost.ts
@@ -694,6 +694,14 @@ async function boot(): Promise<void> {
quiet(): void {
module.engine_setCpuProfiling?.(false);
},
+ /** The change audit (World.setChangeAudit): on, every frame counts component writes made without a change stamp. */
+ changeAudit(enabled: boolean): void {
+ app.world.setChangeAudit(enabled);
+ },
+ /** Component writes found without a change stamp since the audit was turned on. */
+ changeAuditTotal(): number {
+ return app.world.changeAuditTotal();
+ },
/**
* What the last frame's renderer counted — the work a picture cannot show.
* A field of props drawn at three levels and one drawn at one look alike
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index a58201928..15ddcb875 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -14151,6 +14151,7 @@ Generator<number, T, void>
@internal beginIteration: () => void
@internal bufferedWriteRows: (component: AnyComponentDef) => number
@internal builtin: BuiltinBridge
+@internal changeAuditTotal: () => number
@internal changes_: ChangeTracker
@internal closeSpeculation: () => void
@internal commitReservedSpawn: (entity: Entity, name?: string) => void
@@ -14221,6 +14222,7 @@ Generator<number, T, void>
@internal scriptLayoutEpoch: () => number
@internal scriptSpanOf: (component: AnyComponentDef) => { rows: number; stride: number; sparse: number; sparseCount: number; owners: number; ownerCount: number; } | undefined
@internal setAssetFieldResolver: (resolver: AssetFieldResolver | null) => void
+@internal setChangeAudit: (enabled: boolean) => void
@internal setQueryCostEnabled: (enabled: boolean) => void
@internal setTransformChangeTracking: (on: boolean) => boolean
@internal speculating: boolean
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 993d5786e..adae15776 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -9056,7 +9056,7 @@ TextureUploadDecision
## REGISTRY_OPS — const @experimental
```
-{ readonly create: "es_registry_create"; readonly destroy: "es_registry_destroy"; readonly valid: "es_registry_valid"; readonly entityCount: "es_registry_entityCount"; readonly reserveDestruction: "es_registry_reserveDestruction"; readonly releaseDestruction: "es_registry_releaseDestruction"; readonly destructionPending: "es_registry_destructionPending"; readonly setEntityEnabled: "es_registry_setEntityEnabled"; readonly isEntityActive: "es_registry_isEntityActive"; readonly isEntityEnabled: "es_registry_isEntityEnabled"; readonly hasInactiveEntities: "es_registry_hasInactiveEntities"; readonly activityEpoch: "es_registry_activityEpoch"; readonly setParent: "es_registry_setParent"; }
+{ readonly create: "es_registry_create"; readonly destroy: "es_registry_destroy"; readonly valid: "es_registry_valid"; readonly entityCount: "es_registry_entityCount"; readonly reserveDestruction: "es_registry_reserveDestruction"; readonly releaseDestruction: "es_registry_releaseDestruction"; readonly destructionPending: "es_registry_destructionPending"; readonly setEntityEnabled: "es_registry_setEntityEnabled"; readonly isEntityActive: "es_registry_isEntityActive"; readonly isEntityEnabled: "es_registry_isEntityEnabled"; readonly hasInactiveEntities: "es_registry_hasInactiveEntities"; readonly activityEpoch: "es_registry_activityEpoch"; readonly changeTick: "es_registry_changeTick"; readonly beginChangeRead: "es_registry_beginChangeRead"; readonly setChangeAudit: "es_registry_setChangeAudit"; readonly auditChanges: "es_registry_auditChanges"; readonly changeAuditTotal: "es_registry_changeAuditTotal"; readonly setParent: "es_registry_setParent"; }
```
## RENAMED_COMPONENT_TYPES — const @experimental
@@ -14380,6 +14380,7 @@ Generator<number, T, void>
@internal beginIteration: () => void
@internal bufferedWriteRows: (component: AnyComponentDef) => number
@internal builtin: BuiltinBridge
+@internal changeAuditTotal: () => number
@internal changes_: ChangeTracker
@internal closeSpeculation: () => void
@internal commitReservedSpawn: (entity: Entity, name?: string) => void
@@ -14450,6 +14451,7 @@ Generator<number, T, void>
@internal scriptLayoutEpoch: () => number
@internal scriptSpanOf: (component: AnyComponentDef) => { rows: number; stride: number; sparse: number; sparseCount: number; owners: number; ownerCount: number; } | undefined
@internal setAssetFieldResolver: (resolver: AssetFieldResolver | null) => void
+@internal setChangeAudit: (enabled: boolean) => void
@internal setQueryCostEnabled: (enabled: boolean) => void
@internal setTransformChangeTracking: (on: boolean) => boolean
@internal speculating: boolean
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 8d80b50d5..7ecc7b922 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -14146,6 +14146,7 @@ Generator<number, T, void>
@internal beginIteration: () => void
@internal bufferedWriteRows: (component: AnyComponentDef) => number
@internal builtin: BuiltinBridge
+@internal changeAuditTotal: () => number
@internal changes_: ChangeTracker
@internal closeSpeculation: () => void
@internal commitReservedSpawn: (entity: Entity, name?: string) => void
@@ -14216,6 +14217,7 @@ Generator<number, T, void>
@internal scriptLayoutEpoch: () => number
@internal scriptSpanOf: (component: AnyComponentDef) => { rows: number; stride: number; sparse: number; sparseCount: number; owners: number; ownerCount: number; } | undefined
@internal setAssetFieldResolver: (resolver: AssetFieldResolver | null) => void
+@internal setChangeAudit: (enabled: boolean) => void
@internal setQueryCostEnabled: (enabled: boolean) => void
@internal setTransformChangeTracking: (on: boolean) => boolean
@internal speculating: boolean
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index e75509e8e..4b3873dc6 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -14449,6 +14449,7 @@ Generator<number, T, void>
@internal beginIteration: () => void
@internal bufferedWriteRows: (component: AnyComponentDef) => number
@internal builtin: BuiltinBridge
+@internal changeAuditTotal: () => number
@internal changes_: ChangeTracker
@internal closeSpeculation: () => void
@internal commitReservedSpawn: (entity: Entity, name?: string) => void
@@ -14519,6 +14520,7 @@ Generator<number, T, void>
@internal scriptLayoutEpoch: () => number
@internal scriptSpanOf: (component: AnyComponentDef) => { rows: number; stride: number; sparse: number; sparseCount: number; owners: number; ownerCount: number; } | undefined
@internal setAssetFieldResolver: (resolver: AssetFieldResolver | null) => void
+@internal setChangeAudit: (enabled: boolean) => void
@internal setQueryCostEnabled: (enabled: boolean) => void
@internal setTransformChangeTracking: (on: boolean) => boolean
@internal speculating: boolean
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index a0fa5df8c..b746eb34e 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -70,6 +70,10 @@ addUINode: (entity: Entity, component: UINode) => void
addUIScroll: (entity: Entity, component: UIScroll) => void
addUIVisual: (entity: Entity, component: UIVisual) => void
addVelocity: (entity: Entity, component: Velocity) => void
+auditChanges: () => number
+beginChangeRead: () => number
+changeAuditTotal: () => number
+changeTick: () => number
componentTypeId: ((name: string) => number) | undefined
create: () => Entity
delete: () => void
@@ -251,6 +255,7 @@ removeUIScroll: (entity: Entity) => void
removeUIVisual: (entity: Entity) => void
removeVelocity: (entity: Entity) => void
reserveDestruction: (entity: Entity) => boolean
+setChangeAudit: (enabled: boolean) => void
setEntityEnabled: (entity: Entity, enabled: boolean) => boolean
setParent: (child: Entity, parent: Entity) => boolean
valid: (entity: Entity) => boolean
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 340f51311..4378795ab 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -14180,6 +14180,7 @@ Generator<number, T, void>
@internal beginIteration: () => void
@internal bufferedWriteRows: (component: AnyComponentDef) => number
@internal builtin: BuiltinBridge
+@internal changeAuditTotal: () => number
@internal changes_: ChangeTracker
@internal closeSpeculation: () => void
@internal commitReservedSpawn: (entity: Entity, name?: string) => void
@@ -14250,6 +14251,7 @@ Generator<number, T, void>
@internal scriptLayoutEpoch: () => number
@internal scriptSpanOf: (component: AnyComponentDef) => { rows: number; stride: number; sparse: number; sparseCount: number; owners: number; ownerCount: number; } | undefined
@internal setAssetFieldResolver: (resolver: AssetFieldResolver | null) => void
+@internal setChangeAudit: (enabled: boolean) => void
@internal setQueryCostEnabled: (enabled: boolean) => void
@internal setTransformChangeTracking: (on: boolean) => boolean
@internal speculating: boolean
diff --git a/sdk/src/ecs/bridge/registryOps.generated.ts b/sdk/src/ecs/bridge/registryOps.generated.ts
index 7dfe1ac51..589605d6b 100644
--- a/sdk/src/ecs/bridge/registryOps.generated.ts
+++ b/sdk/src/ecs/bridge/registryOps.generated.ts
@@ -19,6 +19,11 @@ export const REGISTRY_OPS = {
isEntityEnabled: 'es_registry_isEntityEnabled',
hasInactiveEntities: 'es_registry_hasInactiveEntities',
activityEpoch: 'es_registry_activityEpoch',
+ changeTick: 'es_registry_changeTick',
+ beginChangeRead: 'es_registry_beginChangeRead',
+ setChangeAudit: 'es_registry_setChangeAudit',
+ auditChanges: 'es_registry_auditChanges',
+ changeAuditTotal: 'es_registry_changeAuditTotal',
setParent: 'es_registry_setParent',
} as const satisfies { readonly [K in keyof Registry]?: string };
diff --git a/sdk/src/ecs/world.ts b/sdk/src/ecs/world.ts
index 74aae6231..41227d537 100644
--- a/sdk/src/ecs/world.ts
+++ b/sdk/src/ecs/world.ts
@@ -1485,6 +1485,26 @@ export class World {
/** @internal The frame runner's clock for change detection. */
advanceTick(): void {
this.changes_.advanceTick();
+ // Once a frame, while the audit is on: the engine compares its components with the copy it kept and counts each one
+ // whose bytes changed without a change stamp (Registry::auditChanges).
+ if (this.changeAudit_) this.builtin_.getCppRegistry()?.auditChanges?.();
+ }
+
+ private changeAudit_ = false;
+
+ /**
+ * @internal Turns on the engine's change audit, for tests and gates: every frame from here on, a component written without
+ * a change stamp is counted, and its type named in the log the first time. It copies every component once a frame.
+ */
+ setChangeAudit(enabled: boolean): void {
+ const registry = this.builtin_.getCppRegistry();
+ registry?.setChangeAudit?.(enabled);
+ this.changeAudit_ = enabled && typeof registry?.auditChanges === 'function';
+ }
+
+ /** @internal Component writes the audit has found without a change stamp since it was turned on. */
+ changeAuditTotal(): number {
+ return this.builtin_.getCppRegistry()?.changeAuditTotal?.() ?? 0;
}
/** @internal */
diff --git a/sdk/src/wasm/wasm.generated.ts b/sdk/src/wasm/wasm.generated.ts
index f7b1451f7..d2c790718 100644
--- a/sdk/src/wasm/wasm.generated.ts
+++ b/sdk/src/wasm/wasm.generated.ts
@@ -1165,6 +1165,16 @@ export interface Registry {
hasInactiveEntities(): boolean;
/** Bumped by every activity change. */
activityEpoch(): number;
+ /** The tick a component write made now is stamped with. */
+ changeTick(): number;
+ /** For a reader about to look for changes: the tick it looks at; the clock then moves on. */
+ beginChangeRead(): number;
+ /** Turns on the audit that finds component writes made without a change stamp. */
+ setChangeAudit(enabled: boolean): void;
+ /** Unstamped component writes since the last audit (0 while the audit is off). */
+ auditChanges(): number;
+ /** Unstamped component writes the audit has found since it was turned on. */
+ changeAuditTotal(): number;
/** Re-parents child; false when refused (a cycle, an invalid entity). */
setParent(child: Entity, parent: Entity): boolean;
/** All generated builtin names, separated by |; absent on older cores. */
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index 60bb9dc0f..9704b1fe8 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -2505,6 +2505,11 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
.function("isEntityEnabled", optional_override([](Registry& r, u32 entity) { return r.isEntityEnabled(static_cast<Entity>(entity)); }))
.function("hasInactiveEntities", optional_override([](Registry& r) { return r.hasInactiveEntities(); }))
.function("activityEpoch", optional_override([](Registry& r) { return r.activityEpoch(); }))
+ .function("changeTick", optional_override([](Registry& r) { return r.changeTick(); }))
+ .function("beginChangeRead", optional_override([](Registry& r) { return r.beginChangeRead(); }))
+ .function("setChangeAudit", optional_override([](Registry& r, bool enabled) { r.setChangeAudit(enabled); }))
+ .function("auditChanges", optional_override([](Registry& r) { return r.auditChanges(); }))
+ .function("changeAuditTotal", optional_override([](Registry& r) { return r.changeAuditTotal(); }))
.function("setParent", optional_override([](Registry& r, u32 child, u32 parent) { return esengine::ecs::setParent(r, static_cast<Entity>(child), static_cast<Entity>(parent)); }))
.function("getBuiltinComponentNames", optional_override([](Registry& r, u32 e) {
diff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hpp
index 456a1ccae..d3ef9565a 100644
--- a/src/esengine/ecs/Registry.hpp
+++ b/src/esengine/ecs/Registry.hpp
@@ -140,6 +140,126 @@ public:
entity_changes_.record(entity.id(), flags, component);
}
+ // =========================================================================
+ // Change Detection
+ // =========================================================================
+ //
+ // Every component carries the tick of its last write. A write stamps the tick that is current; a reader asks
+ // beginChangeRead(), which hands back the tick it read at and moves the clock on, and next time takes as changed whatever is
+ // stamped after that. A write made after a reader looked is stamped later than what it read at, so it is seen the next time,
+ // whichever frame it happened in.
+ //
+ // What writes says so: patch<T>() (a mutable reference that stamps), markChanged<T>() (after writing through a reference
+ // already held), add, replace and remove. get<T>() announces nothing; setChangeAudit() reports what changed without saying.
+
+ /** @brief The tick a write made now is stamped with. */
+ u32 changeTick() const { return change_tick_; }
+
+ /**
+ * @brief For a reader about to look: the tick it is looking at, after which the clock moves on.
+ * @details Keep the answer; next time, changedSince(it) is what was written since this look. Stamps older than half the
+ * counter's range are lifted on the way, so an untouched component never reads as newer once the tick wraps.
+ */
+ u32 beginChangeRead() {
+ const u32 seen = change_tick_;
+ ++change_tick_;
+ if (change_tick_ == 0) change_tick_ = 1;
+ if ((change_tick_ & ((1u << 20) - 1)) == 0) {
+ const u32 floor = change_tick_ - (1u << 30);
+ for (auto& pool : pools_) if (pool) pool->clampStamps(floor);
+ }
+ return seen;
+ }
+
+ /** @brief Mutable access that says it writes: @p entity's T, stamped. Fatal where it has none, as get<T>() is. */
+ template<typename T>
+ T& patch(Entity entity) {
+ auto* pool = getPool<T>();
+ ES_VERIFY_FATAL(pool != nullptr, noPoolMessage(entity));
+ T& component = pool->get(entity);
+ pool->markChanged(entity, change_tick_);
+ return component;
+ }
+
+ /** @brief Says @p entity's T was written, through a reference held from before. */
+ template<typename T>
+ void markChanged(Entity entity) {
+ if (auto* pool = getPool<T>()) pool->markChanged(entity, change_tick_);
+ }
+
+ /** @brief Whether @p entity's T was written, added or replaced after @p tick (an answer of beginChangeRead). */
+ template<typename T>
+ bool changedSince(Entity entity, u32 tick) const {
+ const auto* pool = getPool<T>();
+ return pool && tickAfter(pool->changedTick(entity), tick);
+ }
+
+ /** @brief Whether any T was written, added or removed after @p tick: the question a frame that may skip its walk asks first. */
+ template<typename T>
+ bool anyChangedSince(u32 tick) const {
+ const auto* pool = getPool<T>();
+ return pool && tickAfter(pool->lastChangedTick(), tick);
+ }
+
+ /**
+ * @brief Turns the change audit on or off. On, auditChanges() compares every auditable component with the copy it kept and
+ * reports each one whose bytes changed with no stamp to say so — a write some consumer will never see.
+ * @details A check for tests and gates: it copies every component once per audit.
+ */
+ void setChangeAudit(bool enabled) {
+ change_audit_ = enabled;
+ audit_copies_.clear();
+ audit_reported_.clear();
+ if (enabled) auditChanges();
+ }
+ bool changeAuditEnabled() const { return change_audit_; }
+
+ /**
+ * @brief Compares, reports, and keeps a new copy. @return The unstamped writes found since the last call (0 while off).
+ * @details Each component type is named in the log the first time one of its writes goes unstamped, with the entity; every
+ * one is counted. A type that can be neither copied as bytes nor compared is named once, at the first audit, as unchecked.
+ */
+ u32 auditChanges() {
+ if (!change_audit_) return 0;
+ u32 found = 0;
+ if (audit_copies_.size() < pools_.size()) audit_copies_.resize(pools_.size());
+ if (audit_reported_.size() < pools_.size()) audit_reported_.resize(pools_.size(), 0);
+ for (usize id = 0; id < pools_.size(); ++id) {
+ const auto& pool = pools_[id];
+ if (!pool) continue;
+ if (!pool->auditable()) {
+ if (!audit_reported_[id]) {
+ audit_reported_[id] = 2;
+ ES_LOG_INFO("change audit: {} can be neither copied as bytes nor compared with ==, and is not checked", std::string(pool->typeName()));
+ }
+ continue;
+ }
+ auto& copy = audit_copies_[id];
+ if (!copy.entities.empty() || copy.tick != 0) {
+ struct Sink { Registry* self; usize id; Entity first = INVALID_ENTITY; };
+ Sink sink{this, id};
+ const u32 here = pool->auditCompare(copy, [](void* user, Entity entity) {
+ auto* s = static_cast<Sink*>(user);
+ if (s->first == INVALID_ENTITY) s->first = entity;
+ }, &sink);
+ if (here && audit_reported_[id] != 1) {
+ audit_reported_[id] = 1;
+ ES_LOG_WARN("change audit: {} was written without a stamp (entity {}, {} this frame) - a consumer of changes "
+ "will not see it", std::string(pool->typeName()), sink.first.index(), here);
+ }
+ found += here;
+ audit_unstamped_total_ += here;
+ }
+ pool->auditKeep(copy, change_tick_);
+ }
+ // The copies were taken at this tick: a write from here on has to be stamped later than it to count as said.
+ beginChangeRead();
+ return found;
+ }
+
+ /** @brief Unstamped writes the audit has found since it was turned on. */
+ u32 changeAuditTotal() const { return audit_unstamped_total_; }
+
template<class... C> auto activeView() {
return ActiveView<View<C...>, Registry>(view<C...>(), *this);
}
@@ -263,6 +383,7 @@ public:
component_masks_[idx].forEachSet([&](u32 bit) {
if (bit < pools_.size() && pools_[bit]) {
pools_[bit]->remove(entity);
+ pools_[bit]->noteStructural(change_tick_);
}
});
@@ -357,6 +478,7 @@ public:
auto& pool = assurePool<T>();
auto& result = pool.emplace(entity, std::forward<Args>(args)...);
component_masks_[entity.index()].set(componentTypeId<T>());
+ pool.markChanged(entity, change_tick_);
recordComponentChange<T>(entity);
return result;
}
@@ -379,11 +501,13 @@ public:
if (pool.contains(entity)) {
auto& comp = pool.get(entity);
comp = T(std::forward<Args>(args)...);
+ pool.markChanged(entity, change_tick_);
recordComponentChange<T>(entity, ENTITY_CHANGE_REPLACED);
return comp;
}
auto& result = pool.emplace(entity, std::forward<Args>(args)...);
component_masks_[entity.index()].set(componentTypeId<T>());
+ pool.markChanged(entity, change_tick_);
recordComponentChange<T>(entity);
return result;
}
@@ -400,6 +524,7 @@ public:
auto* pool = getPool<T>();
if (pool && pool->contains(entity)) {
pool->remove(entity);
+ pool->noteStructural(change_tick_);
recordComponentChange<T>(entity);
const u32 idx = entity.index();
if (idx < component_masks_.size()) {
@@ -469,6 +594,7 @@ public:
ES_VERIFY_FATAL(valid(entity), invalidEntityMessage("getOrEmplace", entity));
auto& result = pool.emplace(entity, std::forward<Args>(args)...);
component_masks_[entity.index()].set(componentTypeId<T>());
+ pool.markChanged(entity, change_tick_);
recordComponentChange<T>(entity);
return result;
}
@@ -676,9 +802,8 @@ public:
auto* pool = getPool<T>();
if (!pool) return;
- auto& entities = pool->entities();
- auto& components = pool->components();
- usize n = entities.size();
+ const auto& components = pool->components();
+ const usize n = components.size();
if (n <= 1) return;
std::vector<usize> perm(n);
@@ -687,27 +812,8 @@ public:
std::sort(perm.begin(), perm.end(), [&](usize a, usize b) {
return compare(components[a], components[b]);
});
-
- for (usize i = 0; i < n; ++i) {
- if (perm[i] == i) continue;
-
- usize j = i;
- Entity tmpEntity = std::move(entities[i]);
- T tmpComponent = std::move(components[i]);
-
- while (perm[j] != i) {
- usize src = perm[j];
- entities[j] = std::move(entities[src]);
- components[j] = std::move(components[src]);
- perm[j] = j;
- j = src;
- }
-
- entities[j] = std::move(tmpEntity);
- components[j] = std::move(tmpComponent);
- perm[j] = j;
- }
- pool->rebuildSparse();
+ // The entity, its component and its stamp move together.
+ pool->permute(perm);
}
/**
@@ -885,6 +991,13 @@ private:
/** @brief Type-erased component pools indexed by TypeId */
std::vector<Unique<SparseSetBase>> pools_;
+ /// The tick a write is stamped with (see beginChangeRead). Starts at 1: 0 is "never written".
+ u32 change_tick_ = 1;
+ bool change_audit_ = false;
+ std::vector<SparseSetBase::AuditCopy> audit_copies_;
+ std::vector<u8> audit_reported_;
+ u32 audit_unstamped_total_ = 0;
+
Signal<void(Entity)> on_destroy_signal_;
// Indexed by the canonical entity slot/generation. Grow during activation,
// never allocate one hash node per teardown or a whole-world array on the
diff --git a/src/esengine/ecs/SparseSet.hpp b/src/esengine/ecs/SparseSet.hpp
index 4efda245b..3af1a473b 100644
--- a/src/esengine/ecs/SparseSet.hpp
+++ b/src/esengine/ecs/SparseSet.hpp
@@ -27,8 +27,12 @@
// Standard library
#include <algorithm>
#include <array>
+#include <concepts>
+#include <cstring>
#include <memory>
#include <string>
+#include <string_view>
+#include <type_traits>
#include <vector>
namespace esengine::ecs {
@@ -114,6 +118,41 @@ public:
/** @brief Rank for an entity the caller did not order — sorts last, stably. */
static constexpr u32 UNRANKED = 0xFFFFFFFFu;
+ // ---- Change stamps --------------------------------------------------------------------------------------------------------
+ // Every component carries the tick of its last write beside it (see Registry::changeTick for what a tick is). Written by
+ // whoever writes the component: Registry::patch and markChanged here, the generated setters from script.
+
+ /** @brief The tick of the last write to any component of this pool, or of the last add or remove: "anything since?" in O(1). */
+ virtual u32 lastChangedTick() const = 0;
+ /** @brief Notes an add or a remove at @p tick, which no stamp of a component that is still there records. */
+ virtual void noteStructural(u32 tick) = 0;
+ /** @brief Lifts every stamp older than @p floor to it, so a stamp never reads as newer after the tick wraps. */
+ virtual void clampStamps(u32 floor) = 0;
+ /** @brief The component type's name, for what the audit says. */
+ virtual std::string_view typeName() const = 0;
+
+ // ---- The audit -------------------------------------------------------------------------------------------------------------
+ // A write that left no stamp is a consumer that will never see it (a renderer drawing the old state). The audit keeps a copy
+ // of every component and reports each one that changed since the copy while its stamp did not move: by its bytes where they
+ // are its value (trivially copyable), by == where it says what equal is; a component that is neither is listed as unchecked.
+
+ /** @brief What the audit kept of a pool: its entities and their components' bytes, as they were at @p tick. */
+ struct AuditCopy {
+ std::vector<Entity> entities;
+ std::vector<u8> bytes; ///< a trivially copyable component's bytes
+ std::shared_ptr<void> values; ///< otherwise a copy of the components, compared with ==
+ u32 tick = 0;
+ };
+ /** @brief Whether this pool's components can be audited (see above). */
+ virtual bool auditable() const = 0;
+ /** @brief Keeps the pool's state as it is at @p tick. */
+ virtual void auditKeep(AuditCopy& copy, u32 tick) const = 0;
+ /**
+ * @brief Calls @p report for each entity whose component changed since @p copy without a stamp after copy.tick.
+ * @return How many did.
+ */
+ virtual u32 auditCompare(const AuditCopy& copy, void (*report)(void* user, Entity entity), void* user) const = 0;
+
/**
* @brief Which current slot belongs at each position when `dense` is put in `rank` order (stable).
* @details Not a member of the template: the sort does not depend on the component type, and a copy of `std::stable_sort` and its
@@ -133,6 +172,37 @@ public:
}
};
+/** @brief T's name as the compiler spells it, without a namespace: what an audit report says. */
+template<typename T>
+std::string_view componentTypeName() {
+#if defined(_MSC_VER) && !defined(__clang__)
+ constexpr std::string_view full = __FUNCSIG__;
+ constexpr std::string_view open = "componentTypeName<";
+ constexpr std::string_view close = ">(void)";
+#else
+ constexpr std::string_view full = __PRETTY_FUNCTION__;
+ constexpr std::string_view open = "T = ";
+ constexpr std::string_view close = "]";
+#endif
+ const usize start = full.find(open);
+ if (start == std::string_view::npos) return full;
+ std::string_view name = full.substr(start + open.size());
+ const usize end = name.rfind(close);
+ if (end != std::string_view::npos) name = name.substr(0, end);
+ const usize colon = name.rfind("::");
+ if (colon != std::string_view::npos) name = name.substr(colon + 2);
+ // MSVC writes "struct X" / "class X".
+ for (std::string_view tag : {std::string_view("struct "), std::string_view("class ")}) {
+ if (name.substr(0, tag.size()) == tag) name = name.substr(tag.size());
+ }
+ return name;
+}
+
+/** @brief Whether stamp @p a is later than tick @p b, across a wrap of the counter (stamps are kept within half its range). */
+inline bool tickAfter(u32 a, u32 b) {
+ return static_cast<i32>(a - b) > 0;
+}
+
// =============================================================================
// SparseSet
// =============================================================================
@@ -270,6 +340,82 @@ public:
return &components_[di];
}
+ // =========================================================================
+ // Change Stamps
+ // =========================================================================
+
+ /** @brief The tick of @p entity's last write, 0 when it has none here. */
+ u32 changedTick(Entity entity) const {
+ const u32 di = denseIndexOf(entity);
+ return di != INVALID_INDEX && dense_[di] == entity ? changed_[di] : 0;
+ }
+
+ /** @brief Stamps @p entity's component with @p tick: it was written. No-op for an entity without one. */
+ void markChanged(Entity entity, u32 tick) {
+ const u32 di = denseIndexOf(entity);
+ if (di == INVALID_INDEX || dense_[di] != entity) return;
+ changed_[di] = tick;
+ if (tickAfter(tick, last_changed_)) last_changed_ = tick;
+ }
+
+ /** @brief The stamps, parallel to components(): where a writer that holds a component's place stamps it. */
+ u32* changeTicks() { return changed_.data(); }
+ const u32* changeTicks() const { return changed_.data(); }
+
+ /** @brief Where the pool's last-change tick lives, for a writer that stamps through changeTicks() to lift with it. */
+ u32* lastChangedSlot() { return &last_changed_; }
+
+ u32 lastChangedTick() const override { return last_changed_; }
+ void noteStructural(u32 tick) override {
+ if (tickAfter(tick, last_changed_)) last_changed_ = tick;
+ }
+ void clampStamps(u32 floor) override {
+ for (u32& t : changed_) if (tickAfter(floor, t)) t = floor;
+ if (tickAfter(floor, last_changed_)) last_changed_ = floor;
+ }
+ std::string_view typeName() const override { return componentTypeName<T>(); }
+
+ static constexpr bool kAuditBytes = std::is_trivially_copyable_v<T>;
+ static constexpr bool kAuditValues = !kAuditBytes && std::is_copy_constructible_v<T> && std::equality_comparable<T>;
+ bool auditable() const override { return kAuditBytes || kAuditValues; }
+ void auditKeep(AuditCopy& copy, u32 tick) const override {
+ copy.tick = tick;
+ copy.entities = dense_;
+ copy.bytes.clear();
+ copy.values.reset();
+ if constexpr (kAuditBytes) {
+ copy.bytes.resize(components_.size() * sizeof(T));
+ if (!components_.empty()) std::memcpy(copy.bytes.data(), components_.data(), copy.bytes.size());
+ } else if constexpr (kAuditValues) {
+ copy.values = std::make_shared<std::vector<T>>(components_);
+ }
+ }
+ u32 auditCompare(const AuditCopy& copy, void (*report)(void*, Entity), void* user) const override {
+ if constexpr (!kAuditBytes && !kAuditValues) {
+ return 0;
+ } else {
+ const auto* values = kAuditValues ? static_cast<const std::vector<T>*>(copy.values.get()) : nullptr;
+ if (kAuditValues && !values) return 0;
+ u32 found = 0;
+ for (usize k = 0; k < copy.entities.size(); ++k) {
+ const Entity entity = copy.entities[k];
+ const u32 di = denseIndexOf(entity);
+ if (di == INVALID_INDEX || dense_[di] != entity) continue; // removed since: the journal says so
+ if (tickAfter(changed_[di], copy.tick)) continue; // written, and said so
+ bool same = false;
+ if constexpr (kAuditBytes) {
+ same = std::memcmp(&components_[di], copy.bytes.data() + k * sizeof(T), sizeof(T)) == 0;
+ } else {
+ same = components_[di] == (*values)[k];
+ }
+ if (same) continue;
+ ++found;
+ if (report) report(user, entity);
+ }
+ return found;
+ }
+ }
+
// =========================================================================
// Modification Operations
// =========================================================================
@@ -315,8 +461,11 @@ public:
// pointers into components_ become stale. A non-reallocating append
// leaves existing component addresses intact, so no bump is needed.
const T* before = components_.data();
+ const u32* stampsBefore = changed_.data();
components_.emplace_back(std::forward<Args>(args)...);
- if (components_.data() != before) ++version_;
+ // Unstamped: whoever adds it stamps it with the tick it belongs to (Registry::emplace).
+ changed_.push_back(0);
+ if (components_.data() != before || changed_.data() != stampsBefore) ++version_;
return components_.back();
}
@@ -344,6 +493,7 @@ public:
if (denseIdx == static_cast<u32>(dense_.size()) - 1) {
dense_.pop_back();
components_.pop_back();
+ changed_.pop_back();
(*pages_[pageIndex])[offset] = INVALID_INDEX;
return;
}
@@ -352,6 +502,8 @@ public:
dense_[denseIdx] = last;
components_[denseIdx] = std::move(components_.back());
+ changed_[denseIdx] = changed_.back();
+ changed_.pop_back();
const u32 lastIdx = last.index();
(*pages_[lastIdx / SPARSE_PAGE_SIZE])[lastIdx % SPARSE_PAGE_SIZE] = denseIdx;
@@ -385,6 +537,7 @@ public:
pages_.clear();
dense_.clear();
components_.clear();
+ changed_.clear();
}
/** @copydoc SparseSetBase::version() */
@@ -400,34 +553,47 @@ public:
// one function for every component type (see stablePermutation).
std::vector<usize> perm = stablePermutation(dense_, rank);
+ permute(perm);
+ }
+
+ /**
+ * @brief Puts slot perm[i] at position i, for every i: the entity, its component and its stamp together.
+ * @details The one way storage is reordered (reorderBy, Registry::sort). A permutation that moves nothing leaves storage, and
+ * every handed-out pointer, alone. Consumes @p perm.
+ */
+ void permute(std::vector<usize>& perm) {
+ const usize n = dense_.size();
bool moved = false;
for (usize i = 0; i < n; ++i) {
if (perm[i] != i) { moved = true; break; }
}
- if (!moved) return; // already in order — no version bump, no stale pointers
+ if (!moved) return;
- // Cycle-walk the permutation in place (same idiom as Registry::sort).
+ // Cycle-walk the permutation in place.
for (usize i = 0; i < n; ++i) {
if (perm[i] == i) continue;
usize j = i;
Entity tmpEntity = std::move(dense_[i]);
T tmpComponent = std::move(components_[i]);
+ const u32 tmpStamp = changed_[i];
while (perm[j] != i) {
const usize src = perm[j];
dense_[j] = std::move(dense_[src]);
components_[j] = std::move(components_[src]);
+ changed_[j] = changed_[src];
perm[j] = j;
j = src;
}
dense_[j] = std::move(tmpEntity);
components_[j] = std::move(tmpComponent);
+ changed_[j] = tmpStamp;
perm[j] = j;
}
rebuildSparse();
}
void rebuildSparse() {
- // Called after Registry::sort permutes dense_/components_ in place —
+ // Called after permute() moves dense_/components_ in place —
// component addresses changed, so any handed-out raw pointer is stale.
++version_;
pages_.clear();
@@ -468,14 +634,6 @@ public:
*/
const std::vector<Entity>& entities() const override { return dense_; }
- /**
- * @brief Gets the dense entity array (non-const)
- * @return Reference to entity vector
- *
- * @details Allows direct modification of entity order (e.g., for sorting).
- * Use with caution - must maintain correspondence with components().
- */
- std::vector<Entity>& entities() { return dense_; }
/**
* @brief Gets the component array for direct iteration
@@ -550,6 +708,12 @@ private:
*/
std::vector<T> components_;
+ /** @brief Change stamps, parallel to components_: changed_[i] is the tick of components_[i]'s last write. */
+ std::vector<u32> changed_;
+
+ /** @brief The latest tick any component here was written, added or removed at. */
+ u32 last_changed_ = 0;
+
/** @brief Pointer-staleness generation; see SparseSetBase::version(). */
u32 version_ = 0;
};
diff --git a/src/esengine/ecs/components/BitmapText.hpp b/src/esengine/ecs/components/BitmapText.hpp
index a137591de..466f60e2c 100644
--- a/src/esengine/ecs/components/BitmapText.hpp
+++ b/src/esengine/ecs/components/BitmapText.hpp
@@ -50,6 +50,9 @@ struct BitmapText {
ES_PROPERTY()
bool enabled{true};
+
+ /// Compared member by member: what the change audit checks a write of this component against (Registry::auditChanges).
+ bool operator==(const BitmapText&) const = default;
};
} // namespace esengine::ecs
diff --git a/src/esengine/ecs/components/MeshRenderer.hpp b/src/esengine/ecs/components/MeshRenderer.hpp
index fc4fb2007..21948a396 100644
--- a/src/esengine/ecs/components/MeshRenderer.hpp
+++ b/src/esengine/ecs/components/MeshRenderer.hpp
@@ -36,6 +36,8 @@ struct MeshVertex2D {
glm::vec2 position{0.0f, 0.0f};
glm::vec2 uv{0.0f, 0.0f};
u32 color = 0xFFFFFFFFu;
+
+ bool operator==(const MeshVertex2D&) const = default;
};
// =============================================================================
@@ -123,6 +125,9 @@ struct MeshRenderer {
glm::vec2 localMax{0.0f, 0.0f};
MeshRenderer() = default;
+
+ /// Compared member by member: what the change audit checks a write of this component against (Registry::auditChanges).
+ bool operator==(const MeshRenderer&) const = default;
};
// =============================================================================
diff --git a/src/esengine/ecs/components/ShadowCaster2D.hpp b/src/esengine/ecs/components/ShadowCaster2D.hpp
index dc8d83f38..ee53ec9a2 100644
--- a/src/esengine/ecs/components/ShadowCaster2D.hpp
+++ b/src/esengine/ecs/components/ShadowCaster2D.hpp
@@ -47,6 +47,9 @@ struct ShadowCaster2D {
/** @brief Disabled casters are skipped during collection. */
ES_PROPERTY()
bool enabled{true};
+
+ /// Compared member by member: what the change audit checks a write of this component against (Registry::auditChanges).
+ bool operator==(const ShadowCaster2D&) const = default;
};
} // namespace esengine::ecs
diff --git a/src/esengine/ecs/components/SpringBone.hpp b/src/esengine/ecs/components/SpringBone.hpp
index 9455cb27a..2fc40cfb0 100644
--- a/src/esengine/ecs/components/SpringBone.hpp
+++ b/src/esengine/ecs/components/SpringBone.hpp
@@ -80,6 +80,9 @@ struct SpringBone {
std::vector<Entity> colliders;
SpringBone() = default;
+
+ /// Compared member by member: what the change audit checks a write of this component against (Registry::auditChanges).
+ bool operator==(const SpringBone&) const = default;
};
/**
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 64d825b07..2fdc3fdb5 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -825,6 +825,15 @@ target_compile_options(test_registry_safety PRIVATE $<${_es_safety_asan}:-fsanit
target_link_options(test_registry_safety PRIVATE $<${_es_safety_asan}:-fsanitize=address>)
add_test(NAME test_registry_safety COMMAND test_registry_safety)
+# Change stamps: a write is seen once by the reader that looked before it, a stamp moves with its component, and the audit
+# finds a write that left none. Header-only against Registry.hpp.
+add_executable(test_change_stamps
+ ecs/test_change_stamps.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp
+)
+target_include_directories(test_change_stamps PRIVATE ${CMAKE_SOURCE_DIR}/src)
+add_test(NAME test_change_stamps COMMAND test_change_stamps)
+
# onDestroy RAII Connection / dual-order teardown safety (RC12 B1, fixes A12).
# Built with AddressSanitizer so the use-after-free the old bare-`this` callback
# caused (in either teardown order) is actually caught, not just "didn't crash".
diff --git a/tests/ecs/test_change_stamps.cpp b/tests/ecs/test_change_stamps.cpp
new file mode 100644
index 000000000..a83544e0b
--- /dev/null
+++ b/tests/ecs/test_change_stamps.cpp
@@ -0,0 +1,147 @@
+// Change stamps on the ECS: every component carries the tick of its last write, a reader asks what changed since it last
+// looked, and the audit finds a write that left no stamp. Header-only against Registry.hpp, like test_registry_safety.
+
+#include "esengine/ecs/Registry.hpp"
+
+#include <cstdio>
+#include <string>
+
+using esengine::Entity;
+using esengine::u32;
+using esengine::ecs::Registry;
+using esengine::ecs::tickAfter;
+
+namespace {
+struct Pos { float x = 1.0f; float y = 2.0f; };
+struct Rank { int value = 0; };
+struct Named { std::string name; }; // neither trivially copyable nor comparable: the audit cannot check it
+struct Listed { // not trivially copyable, but says what equal is: checked by value
+ std::vector<int> values;
+ bool operator==(const Listed&) const = default;
+};
+}
+
+static int g_failures = 0;
+#define CHECK(cond, msg) \
+ do { \
+ if (!(cond)) { std::printf("FAIL: %s\n", msg); ++g_failures; } \
+ else { std::printf("ok: %s\n", msg); } \
+ } while (0)
+
+int main() {
+ // --- A write is seen once, by the reader that looked before it ---
+ {
+ Registry r;
+ const u32 start = r.beginChangeRead();
+ const Entity a = r.create();
+ r.emplace<Pos>(a);
+ CHECK(r.changedSince<Pos>(a, start), "an added component reads as changed since a look before it");
+ CHECK(r.anyChangedSince<Pos>(start), "and the pool says something changed");
+
+ const u32 seen = r.beginChangeRead();
+ CHECK(!r.changedSince<Pos>(a, seen), "a look after the add sees nothing new");
+ CHECK(!r.anyChangedSince<Pos>(seen), "nor does the pool");
+
+ r.get<Pos>(a).x = 5.0f;
+ CHECK(!r.changedSince<Pos>(a, seen), "get<T>() announces nothing");
+
+ r.patch<Pos>(a).x = 6.0f;
+ CHECK(r.changedSince<Pos>(a, seen), "patch<T>() stamps the write");
+ CHECK(r.anyChangedSince<Pos>(seen), "and lifts the pool's last change");
+
+ const u32 again = r.beginChangeRead();
+ r.get<Pos>(a).y = 3.0f;
+ r.markChanged<Pos>(a);
+ CHECK(r.changedSince<Pos>(a, again), "markChanged<T>() says a write made through a held reference");
+
+ const u32 before = r.beginChangeRead();
+ r.remove<Pos>(a);
+ CHECK(r.anyChangedSince<Pos>(before), "a remove reads as a change of the pool");
+ CHECK(!r.changedSince<Pos>(a, before), "while the entity has no stamp left to ask");
+
+ const u32 later = r.beginChangeRead();
+ r.emplaceOrReplace<Pos>(a);
+ r.emplaceOrReplace<Pos>(a);
+ CHECK(r.changedSince<Pos>(a, later), "a replace stamps");
+ }
+
+ // --- A stamp moves with its component ---
+ {
+ Registry r;
+ const Entity a = r.create(), b = r.create(), c = r.create();
+ r.emplace<Rank>(a, Rank{3});
+ r.emplace<Rank>(b, Rank{1});
+ r.emplace<Rank>(c, Rank{2});
+ const u32 seen = r.beginChangeRead();
+ r.patch<Rank>(c); // only c is written after the look
+
+ r.remove<Rank>(a); // swap-and-pop puts c where a was
+ CHECK(r.changedSince<Rank>(c, seen), "a swap-and-pop keeps the moved component's stamp with it");
+ CHECK(!r.changedSince<Rank>(b, seen), "and leaves the others' alone");
+
+ r.emplace<Rank>(a, Rank{0});
+ const u32 sorted = r.beginChangeRead();
+ r.patch<Rank>(b);
+ r.sort<Rank>([](const Rank& x, const Rank& y) { return x.value < y.value; });
+ CHECK(r.changedSince<Rank>(b, sorted) && !r.changedSince<Rank>(c, sorted) && !r.changedSince<Rank>(a, sorted),
+ "sort carries every stamp to where its component went");
+ CHECK(r.get<Rank>(a).value == 0 && r.get<Rank>(b).value == 1 && r.get<Rank>(c).value == 2, "and sorts");
+ }
+
+ // --- The tick wraps without an old stamp reading as new ---
+ {
+ CHECK(tickAfter(1u, 0xFFFFFFF0u), "a stamp after a wrap is later than one before it");
+ CHECK(!tickAfter(0xFFFFFFF0u, 1u), "and not the other way round");
+ }
+
+ // --- The audit finds writes that left no stamp, and only those ---
+ {
+ Registry r;
+ const Entity a = r.create(), b = r.create();
+ r.emplace<Pos>(a);
+ r.emplace<Pos>(b);
+ r.emplace<Named>(a);
+ r.emplace<Listed>(b);
+ r.setChangeAudit(true);
+
+ CHECK(r.auditChanges() == 0, "nothing written, nothing found");
+
+ r.get<Pos>(a).x = 9.0f;
+ CHECK(r.auditChanges() == 1, "a write through get<T>() with no stamp is found");
+
+ r.patch<Pos>(a).x = 10.0f;
+ r.get<Pos>(b).x = 11.0f;
+ r.markChanged<Pos>(b);
+ CHECK(r.auditChanges() == 0, "writes through patch or followed by markChanged are not");
+
+ r.get<Named>(a).name = "changed";
+ CHECK(r.auditChanges() == 0, "a component neither trivially copyable nor comparable is not checked (and is named as such)");
+
+ r.get<Listed>(b).values.push_back(1);
+ CHECK(r.auditChanges() == 1, "one that says what equal is is checked by value");
+ r.patch<Listed>(b).values.push_back(2);
+ CHECK(r.auditChanges() == 0, "and a stamped write of it is not reported");
+
+ r.remove<Pos>(b);
+ const Entity c = r.create();
+ r.emplace<Pos>(c);
+ CHECK(r.auditChanges() == 0, "adds and removes are not unstamped writes");
+
+ r.get<Pos>(c).y = 4.0f;
+ r.get<Pos>(a).y = 4.0f;
+ CHECK(r.auditChanges() == 2 && r.changeAuditTotal() == 4, "every unstamped write is counted");
+
+ r.setChangeAudit(false);
+ r.get<Pos>(a).x = 1.0f;
+ CHECK(r.auditChanges() == 0, "and nothing is checked while it is off");
+ }
+
+ // --- The audit names a type as the code spells it ---
+ {
+ const std::string_view name = esengine::ecs::componentTypeName<Pos>();
+ CHECK(name == "Pos", "componentTypeName drops the namespace");
+ }
+
+ std::printf(g_failures ? "\n%d FAILURE(S)\n" : "\nall passed\n", g_failures);
+ return g_failures ? 1 : 0;
+}
diff --git a/tools/eht/registry_ops.py b/tools/eht/registry_ops.py
index 0fb2f6e3c..2fd17a0ce 100644
--- a/tools/eht/registry_ops.py
+++ b/tools/eht/registry_ops.py
@@ -68,6 +68,16 @@ REGISTRY_OPS: Tuple[RegistryOp, ...] = (
RegistryOp('hasInactiveEntities', (), 'bool', 'r.hasInactiveEntities()',
'Whether any entity is inactive (lets a query skip the activity check).'),
RegistryOp('activityEpoch', (), 'number', 'r.activityEpoch()', 'Bumped by every activity change.'),
+ RegistryOp('changeTick', (), 'number', 'r.changeTick()',
+ 'The tick a component write made now is stamped with.'),
+ RegistryOp('beginChangeRead', (), 'number', 'r.beginChangeRead()',
+ 'For a reader about to look for changes: the tick it looks at; the clock then moves on.'),
+ RegistryOp('setChangeAudit', (('enabled', 'bool'),), 'void', 'r.setChangeAudit({0})',
+ 'Turns on the audit that finds component writes made without a change stamp.'),
+ RegistryOp('auditChanges', (), 'number', 'r.auditChanges()',
+ 'Unstamped component writes since the last audit (0 while the audit is off).'),
+ RegistryOp('changeAuditTotal', (), 'number', 'r.changeAuditTotal()',
+ 'Unstamped component writes the audit has found since it was turned on.'),
RegistryOp('setParent', (_e('child'), _e('parent')), 'bool',
'esengine::ecs::setParent(r, {0}, {1})',
'Re-parents child; false when refused (a cycle, an invalid entity).'),
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 49f140523..30f56ad65 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -4818,4 +4818,6 @@ export const NOTED = {
{"internal": "The transform cache this restores was made lazy after the last release; no release kept a child in its old place."},
"perf(render): a run of mesh draws that differ only by their geometry and records is one call - with WEBGL_multi_draw, each draw reads its record base and probe offset by gl_DrawID from one block staged for the run, so a run binds its blocks once and draws once":
{"note": "A run of mesh draws is one call on WebGL2."},
+ "feat(ecs): every component carries the tick of its last write, and an audit finds a write that left none - Registry::patch, markChanged, changedSince and anyChangedSince over stamps kept beside the components, the reader's tick from beginChangeRead, and setChangeAudit, which reports each component type written without a stamp; the first step toward a renderer that walks only what changed":
+ {"note": "Components carry the tick of their last write."},
};
diff --git a/tools/render-submit-cost.mjs b/tools/render-submit-cost.mjs
index 35859944d..50fb310ec 100644
--- a/tools/render-submit-cost.mjs
+++ b/tools/render-submit-cost.mjs
@@ -47,6 +47,9 @@ const PROFILE = argv.includes('--profile');
const GLCALLS = argv.includes('--glcalls');
/** Time frames with the engine's profiler left off: what a frame costs a player, not a profiled one. No scopes are read. */
const WALL = argv.includes('--wall');
+// --audit: after the scene settles, turn on the engine's change audit, play two seconds, and list the component types written
+// without a change stamp (World.setChangeAudit) - the census of what a consumer of changes would not see.
+const AUDIT = argv.includes('--audit');
const NO_EXPORT = argv.includes('--no-export');
const ONLY = flag('only', '') ? new Set(flag('only', '').split(',')) : null;
/** A png of the last measured frame, to compare two builds' pictures. */
@@ -122,6 +125,8 @@ async function measure(browser, dir) {
}
const errors = [];
page.on('pageerror', (e) => errors.push(String(e).slice(0, 200)));
+ const audit = [];
+ if (AUDIT) page.on('console', (m) => { if (m.text().includes('change audit:')) audit.push(m.text().replace(/^.*change audit: /, '')); });
if (argv.includes('--logs')) {
page.on('console', (m) => { if (['warning', 'error'].includes(m.type())) console.log(` [${m.type()}] ${m.text().slice(0, 300)}`); });
page.on('pageerror', (e) => console.log(` [pageerror] ${String(e).slice(0, 300)}`));
@@ -148,6 +153,18 @@ async function measure(browser, dir) {
}
return -1;
});
+ let auditTotal = null;
+ if (AUDIT) {
+ auditTotal = await page.evaluate(async () => {
+ const c = window.__estellaCooked;
+ if (!c.changeAudit) throw new Error('this package has no change audit (no changeAudit()): re-export it');
+ c.changeAudit(true);
+ for (let i = 0; i < 12; i++) { await c.step(10, 1 / 60); await new Promise((r) => setTimeout(r, 10)); }
+ const total = c.changeAuditTotal();
+ c.changeAudit(false);
+ return total;
+ });
+ }
let cdp = null;
if (PROFILE) {
cdp = await context.newCDPSession(page);
@@ -188,7 +205,8 @@ async function measure(browser, dir) {
const keys = new Set(result.scopes.flatMap((s) => Object.keys(s ?? {})));
const native = {};
for (const k of keys) native[k] = median(result.scopes.map((s) => s?.[k] ?? 0));
- return { ms: median(result.ms), native, counters: result.counters, systems: result.systems, settled, errors, profile, gl: result.gl };
+ return { ms: median(result.ms), native, counters: result.counters, systems: result.systems, settled, errors, profile, gl: result.gl,
+ audit: AUDIT ? { total: auditTotal, lines: audit } : null };
} finally {
await context.close();
await new Promise((r) => server.close(r));
@@ -243,12 +261,16 @@ try {
const r = await measure(browser, dir);
const n = r.native, c = r.counters;
const renderCpu = (n['render.collect'] ?? 0) + (n['render.finalize'] ?? 0) + (n['render.submit'] ?? 0) + (n['render.graph'] ?? 0);
- table[spread] = { ms: r.ms, renderCpu, native: n, counters: c, settled: r.settled, errors: r.errors, gl: r.gl };
+ table[spread] = { ms: r.ms, renderCpu, native: n, counters: c, settled: r.settled, errors: r.errors, gl: r.gl, audit: r.audit };
console.log(`${spread.padEnd(8)} frame ${r.ms.toFixed(2)} ms collect ${(n['render.collect'] ?? 0).toFixed(2)} finalize ${(n['render.finalize'] ?? 0).toFixed(2)} submit ${(n['render.submit'] ?? 0).toFixed(2)} graph ${(n['render.graph'] ?? 0).toFixed(2)} -> render CPU ${renderCpu.toFixed(2)} ms draws ${c['batch.draws'] ?? '?'} (gpu ${c['render.gpu.draws'] ?? '?'}, merged ${c['batch.merged'] ?? '?'}, shadow ${c['render.shadow.draws'] ?? '?'}) tris ${((c['render.triangles'] ?? 0) / 1e6).toFixed(2)}M settled ${r.settled}${r.errors.length ? ' ERRORS ' + r.errors[0] : ''}`);
const breaks = Object.entries(c).filter(([k]) => k.startsWith('batch.break.')).map(([k, v]) => `${k.slice(12)}=${v}`).join(' ');
if (breaks) console.log(` merge breaks: ${breaks}`);
const sys = (r.systems ?? []).slice().sort((a, b) => b.ms - a.ms).slice(0, 6).map((s) => `${s.name} ${s.ms.toFixed(2)}`).join(', ');
if (sys) console.log(` top systems: ${sys}`);
+ if (r.audit) {
+ console.log(` change audit: ${r.audit.total} unstamped write(s) in 120 frames`);
+ for (const line of r.audit.lines) console.log(` ${line}`);
+ }
if (r.gl) {
const rows = Object.entries(r.gl).sort((a, b) => b[1] - a[1]);
const total = rows.reduce((t, [, v]) => t + v, 0);