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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
refactor(ecs): unify SDK and native mutation cursors
yhhb337116af076
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex bd5e61c3b..53fd26f0d 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -10002,6 +10002,7 @@ tabIndex: number | undefined```@internal addressOfComponent: (component: AnyComponentDef, entity: Entity) => number | undefined@internal addressResolver: (component: AnyComponentDef) => (entity: Entity) => number | undefined+@internal advanceMutationCursor: (component: AnyComponentDef, kind: "write" | "topology", reader: number, through: number) => void@internal advanceRemovedCursorReader: (component: AnyComponentDef, readerId: number, through: number) => void@internal advanceRemovedReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void@internal advanceTick: () => void@@ -10019,6 +10020,7 @@ tabIndex: number | undefined@internal compositionChanges: () => CompositionDelta | null@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => void@internal disconnectCpp: () => void+@internal disposeMutationCursor: (component: AnyComponentDef, kind: "write" | "topology", reader: number) => void@internal disposeRemovedReader: (component: AnyComponentDef, readerId: number) => void@internal disposeTopologyReader: (component: AnyComponentDef, readerId: number) => void@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void@@ -10035,7 +10037,7 @@ tabIndex: number | undefined@internal getRemovalSequence: () => number@internal getRemovedEntitiesForReader: (component: AnyComponentDef, readerId: number) => Entity[]@internal getRemovedEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]-@internal getStorageSizes: () => { entities: number; indexSlots: number; spawnCallbacks: number; despawnCallbacks: number; names: ReturnType<NameIndex["sizes"]>; scripts: ReturnType<ScriptStorage["sizes"]>; changes: ReturnType<ChangeTracker["sizes"]>; queryCacheEntries: number; }+@internal getStorageSizes: () => { entities: number; indexSlots: number; spawnCallbacks: number; despawnCallbacks: number; coreDisconnectCallbacks: number; names: ReturnType<NameIndex["sizes"]>; scripts: ReturnType<ScriptStorage["sizes"]>; changes: ReturnType<ChangeTracker["sizes"]>; queryCacheEntries: number; }@internal getTopologyChangedEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@internal getWasmModule: () => ESEngineModule | null@internal getWorldTick: () => number@@ -10053,10 +10055,15 @@ tabIndex: number | undefined@internal isIterating: () => boolean@internal layoutEpoch: () => number | null@internal markChanged: (entity: Entity, component: AnyComponentDef) => void+@internal mutationSequence: (kind: "write" | "topology") => number+@internal mutationsForCursor: (component: AnyComponentDef, kind: "write" | "topology", reader: number) => Entity[]+@internal onCoreDisconnect: (dispose: () => void) => () => void@internal openSpeculation: (log: { record(world: World, entity: Entity, component: AnyComponentDef): void; }) => void@internal queries_: QueryCache@internal queryCostEnabled: boolean@internal queryEntities: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]+@internal refreshBuiltinMembership: (entity: Entity, component: AnyComponentDef) => void+@internal registerMutationCursor: (component: AnyComponentDef, kind: "write" | "topology") => number@internal registerRemovedCursorReader: (component: AnyComponentDef) => number@internal registerRemovedReader: (component: AnyComponentDef) => number@internal registerRemovedReaderFrom: (component: AnyComponentDef, retainFromTick: number) => numberdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex e088c073e..eb675dd4b 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -10215,6 +10215,7 @@ tabIndex: number | undefined```@internal addressOfComponent: (component: AnyComponentDef, entity: Entity) => number | undefined@internal addressResolver: (component: AnyComponentDef) => (entity: Entity) => number | undefined+@internal advanceMutationCursor: (component: AnyComponentDef, kind: "write" | "topology", reader: number, through: number) => void@internal advanceRemovedCursorReader: (component: AnyComponentDef, readerId: number, through: number) => void@internal advanceRemovedReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void@internal advanceTick: () => void@@ -10232,6 +10233,7 @@ tabIndex: number | undefined@internal compositionChanges: () => CompositionDelta | null@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => void@internal disconnectCpp: () => void+@internal disposeMutationCursor: (component: AnyComponentDef, kind: "write" | "topology", reader: number) => void@internal disposeRemovedReader: (component: AnyComponentDef, readerId: number) => void@internal disposeTopologyReader: (component: AnyComponentDef, readerId: number) => void@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void@@ -10248,7 +10250,7 @@ tabIndex: number | undefined@internal getRemovalSequence: () => number@internal getRemovedEntitiesForReader: (component: AnyComponentDef, readerId: number) => Entity[]@internal getRemovedEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]-@internal getStorageSizes: () => { entities: number; indexSlots: number; spawnCallbacks: number; despawnCallbacks: number; names: ReturnType<NameIndex["sizes"]>; scripts: ReturnType<ScriptStorage["sizes"]>; changes: ReturnType<ChangeTracker["sizes"]>; queryCacheEntries: number; }+@internal getStorageSizes: () => { entities: number; indexSlots: number; spawnCallbacks: number; despawnCallbacks: number; coreDisconnectCallbacks: number; names: ReturnType<NameIndex["sizes"]>; scripts: ReturnType<ScriptStorage["sizes"]>; changes: ReturnType<ChangeTracker["sizes"]>; queryCacheEntries: number; }@internal getTopologyChangedEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@internal getWasmModule: () => ESEngineModule | null@internal getWorldTick: () => number@@ -10266,10 +10268,15 @@ tabIndex: number | undefined@internal isIterating: () => boolean@internal layoutEpoch: () => number | null@internal markChanged: (entity: Entity, component: AnyComponentDef) => void+@internal mutationSequence: (kind: "write" | "topology") => number+@internal mutationsForCursor: (component: AnyComponentDef, kind: "write" | "topology", reader: number) => Entity[]+@internal onCoreDisconnect: (dispose: () => void) => () => void@internal openSpeculation: (log: { record(world: World, entity: Entity, component: AnyComponentDef): void; }) => void@internal queries_: QueryCache@internal queryCostEnabled: boolean@internal queryEntities: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]+@internal refreshBuiltinMembership: (entity: Entity, component: AnyComponentDef) => void+@internal registerMutationCursor: (component: AnyComponentDef, kind: "write" | "topology") => number@internal registerRemovedCursorReader: (component: AnyComponentDef) => number@internal registerRemovedReader: (component: AnyComponentDef) => number@internal registerRemovedReaderFrom: (component: AnyComponentDef, retainFromTick: number) => numberdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex e901abd71..756b3cb70 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -9997,6 +9997,7 @@ tabIndex: number | undefined```@internal addressOfComponent: (component: AnyComponentDef, entity: Entity) => number | undefined@internal addressResolver: (component: AnyComponentDef) => (entity: Entity) => number | undefined+@internal advanceMutationCursor: (component: AnyComponentDef, kind: "write" | "topology", reader: number, through: number) => void@internal advanceRemovedCursorReader: (component: AnyComponentDef, readerId: number, through: number) => void@internal advanceRemovedReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void@internal advanceTick: () => void@@ -10014,6 +10015,7 @@ tabIndex: number | undefined@internal compositionChanges: () => CompositionDelta | null@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => void@internal disconnectCpp: () => void+@internal disposeMutationCursor: (component: AnyComponentDef, kind: "write" | "topology", reader: number) => void@internal disposeRemovedReader: (component: AnyComponentDef, readerId: number) => void@internal disposeTopologyReader: (component: AnyComponentDef, readerId: number) => void@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void@@ -10030,7 +10032,7 @@ tabIndex: number | undefined@internal getRemovalSequence: () => number@internal getRemovedEntitiesForReader: (component: AnyComponentDef, readerId: number) => Entity[]@internal getRemovedEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]-@internal getStorageSizes: () => { entities: number; indexSlots: number; spawnCallbacks: number; despawnCallbacks: number; names: ReturnType<NameIndex["sizes"]>; scripts: ReturnType<ScriptStorage["sizes"]>; changes: ReturnType<ChangeTracker["sizes"]>; queryCacheEntries: number; }+@internal getStorageSizes: () => { entities: number; indexSlots: number; spawnCallbacks: number; despawnCallbacks: number; coreDisconnectCallbacks: number; names: ReturnType<NameIndex["sizes"]>; scripts: ReturnType<ScriptStorage["sizes"]>; changes: ReturnType<ChangeTracker["sizes"]>; queryCacheEntries: number; }@internal getTopologyChangedEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@internal getWasmModule: () => ESEngineModule | null@internal getWorldTick: () => number@@ -10048,10 +10050,15 @@ tabIndex: number | undefined@internal isIterating: () => boolean@internal layoutEpoch: () => number | null@internal markChanged: (entity: Entity, component: AnyComponentDef) => void+@internal mutationSequence: (kind: "write" | "topology") => number+@internal mutationsForCursor: (component: AnyComponentDef, kind: "write" | "topology", reader: number) => Entity[]+@internal onCoreDisconnect: (dispose: () => void) => () => void@internal openSpeculation: (log: { record(world: World, entity: Entity, component: AnyComponentDef): void; }) => void@internal queries_: QueryCache@internal queryCostEnabled: boolean@internal queryEntities: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]+@internal refreshBuiltinMembership: (entity: Entity, component: AnyComponentDef) => void+@internal registerMutationCursor: (component: AnyComponentDef, kind: "write" | "topology") => number@internal registerRemovedCursorReader: (component: AnyComponentDef) => number@internal registerRemovedReader: (component: AnyComponentDef) => number@internal registerRemovedReaderFrom: (component: AnyComponentDef, retainFromTick: number) => numberdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 918ee3970..29e5302d5 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -10296,6 +10296,7 @@ tabIndex: number | undefined```@internal addressOfComponent: (component: AnyComponentDef, entity: Entity) => number | undefined@internal addressResolver: (component: AnyComponentDef) => (entity: Entity) => number | undefined+@internal advanceMutationCursor: (component: AnyComponentDef, kind: "write" | "topology", reader: number, through: number) => void@internal advanceRemovedCursorReader: (component: AnyComponentDef, readerId: number, through: number) => void@internal advanceRemovedReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void@internal advanceTick: () => void@@ -10313,6 +10314,7 @@ tabIndex: number | undefined@internal compositionChanges: () => CompositionDelta | null@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => void@internal disconnectCpp: () => void+@internal disposeMutationCursor: (component: AnyComponentDef, kind: "write" | "topology", reader: number) => void@internal disposeRemovedReader: (component: AnyComponentDef, readerId: number) => void@internal disposeTopologyReader: (component: AnyComponentDef, readerId: number) => void@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void@@ -10329,7 +10331,7 @@ tabIndex: number | undefined@internal getRemovalSequence: () => number@internal getRemovedEntitiesForReader: (component: AnyComponentDef, readerId: number) => Entity[]@internal getRemovedEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]-@internal getStorageSizes: () => { entities: number; indexSlots: number; spawnCallbacks: number; despawnCallbacks: number; names: ReturnType<NameIndex["sizes"]>; scripts: ReturnType<ScriptStorage["sizes"]>; changes: ReturnType<ChangeTracker["sizes"]>; queryCacheEntries: number; }+@internal getStorageSizes: () => { entities: number; indexSlots: number; spawnCallbacks: number; despawnCallbacks: number; coreDisconnectCallbacks: number; names: ReturnType<NameIndex["sizes"]>; scripts: ReturnType<ScriptStorage["sizes"]>; changes: ReturnType<ChangeTracker["sizes"]>; queryCacheEntries: number; }@internal getTopologyChangedEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@internal getWasmModule: () => ESEngineModule | null@internal getWorldTick: () => number@@ -10347,10 +10349,15 @@ tabIndex: number | undefined@internal isIterating: () => boolean@internal layoutEpoch: () => number | null@internal markChanged: (entity: Entity, component: AnyComponentDef) => void+@internal mutationSequence: (kind: "write" | "topology") => number+@internal mutationsForCursor: (component: AnyComponentDef, kind: "write" | "topology", reader: number) => Entity[]+@internal onCoreDisconnect: (dispose: () => void) => () => void@internal openSpeculation: (log: { record(world: World, entity: Entity, component: AnyComponentDef): void; }) => void@internal queries_: QueryCache@internal queryCostEnabled: boolean@internal queryEntities: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]+@internal refreshBuiltinMembership: (entity: Entity, component: AnyComponentDef) => void+@internal registerMutationCursor: (component: AnyComponentDef, kind: "write" | "topology") => number@internal registerRemovedCursorReader: (component: AnyComponentDef) => number@internal registerRemovedReader: (component: AnyComponentDef) => number@internal registerRemovedReaderFrom: (component: AnyComponentDef, retainFromTick: number) => numberdiff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.mdindex 7eb22f7e6..b23a35314 100644--- a/sdk/etc/wasm.api.md+++ b/sdk/etc/wasm.api.md@@ -61,6 +61,7 @@ addUINode: (entity: Entity, component: UINode) => voidaddUIScroll: (entity: Entity, component: UIScroll) => voidaddUIVisual: (entity: Entity, component: UIVisual) => voidaddVelocity: (entity: Entity, component: Velocity) => void+componentTypeId: ((name: string) => number) | undefinedcreate: () => Entitydelete: () => voiddestroy: (entity: Entity) => void@@ -404,6 +405,7 @@ provideReplacementDevice: (() => boolean) | undefinedrecoverDevice: (() => boolean) | undefinedregistryLayoutEpoch: (registry: CppRegistry) => numberregistry_batchSyncPhysicsTransforms: (registry: CppRegistry, bufferPtr: number, count: number, ppu: number) => void+registry_entityChangeResetEpoch: ((registry: CppRegistry) => number) | undefinedregistry_entityChangeSequence: ((registry: CppRegistry) => number) | undefinedregistry_getCameraEntities: (registry: CppRegistry) => number[]registry_getCanvasEntities: ((registry: CppRegistry) => number[]) | undefineddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 45bf4ab07..0af6577c3 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -10028,6 +10028,7 @@ tabIndex: number | undefined```@internal addressOfComponent: (component: AnyComponentDef, entity: Entity) => number | undefined@internal addressResolver: (component: AnyComponentDef) => (entity: Entity) => number | undefined+@internal advanceMutationCursor: (component: AnyComponentDef, kind: "write" | "topology", reader: number, through: number) => void@internal advanceRemovedCursorReader: (component: AnyComponentDef, readerId: number, through: number) => void@internal advanceRemovedReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void@internal advanceTick: () => void@@ -10045,6 +10046,7 @@ tabIndex: number | undefined@internal compositionChanges: () => CompositionDelta | null@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => void@internal disconnectCpp: () => void+@internal disposeMutationCursor: (component: AnyComponentDef, kind: "write" | "topology", reader: number) => void@internal disposeRemovedReader: (component: AnyComponentDef, readerId: number) => void@internal disposeTopologyReader: (component: AnyComponentDef, readerId: number) => void@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void@@ -10061,7 +10063,7 @@ tabIndex: number | undefined@internal getRemovalSequence: () => number@internal getRemovedEntitiesForReader: (component: AnyComponentDef, readerId: number) => Entity[]@internal getRemovedEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]-@internal getStorageSizes: () => { entities: number; indexSlots: number; spawnCallbacks: number; despawnCallbacks: number; names: ReturnType<NameIndex["sizes"]>; scripts: ReturnType<ScriptStorage["sizes"]>; changes: ReturnType<ChangeTracker["sizes"]>; queryCacheEntries: number; }+@internal getStorageSizes: () => { entities: number; indexSlots: number; spawnCallbacks: number; despawnCallbacks: number; coreDisconnectCallbacks: number; names: ReturnType<NameIndex["sizes"]>; scripts: ReturnType<ScriptStorage["sizes"]>; changes: ReturnType<ChangeTracker["sizes"]>; queryCacheEntries: number; }@internal getTopologyChangedEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@internal getWasmModule: () => ESEngineModule | null@internal getWorldTick: () => number@@ -10079,10 +10081,15 @@ tabIndex: number | undefined@internal isIterating: () => boolean@internal layoutEpoch: () => number | null@internal markChanged: (entity: Entity, component: AnyComponentDef) => void+@internal mutationSequence: (kind: "write" | "topology") => number+@internal mutationsForCursor: (component: AnyComponentDef, kind: "write" | "topology", reader: number) => Entity[]+@internal onCoreDisconnect: (dispose: () => void) => () => void@internal openSpeculation: (log: { record(world: World, entity: Entity, component: AnyComponentDef): void; }) => void@internal queries_: QueryCache@internal queryCostEnabled: boolean@internal queryEntities: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]+@internal refreshBuiltinMembership: (entity: Entity, component: AnyComponentDef) => void+@internal registerMutationCursor: (component: AnyComponentDef, kind: "write" | "topology") => number@internal registerRemovedCursorReader: (component: AnyComponentDef) => number@internal registerRemovedReader: (component: AnyComponentDef) => number@internal registerRemovedReaderFrom: (component: AnyComponentDef, retainFromTick: number) => numberdiff --git a/sdk/src/ecs/ChangeTracker.ts b/sdk/src/ecs/ChangeTracker.tsindex 02a939ff0..ec0841441 100644--- a/sdk/src/ecs/ChangeTracker.ts+++ b/sdk/src/ecs/ChangeTracker.ts@@ -171,14 +171,14 @@ export class ChangeTracker {private changeSequence_ = 0;private readonly removals_ = new ReaderOwnedJournal(true);/** Membership moves, independent of ordinary change tracking. */- private readonly topology_ = new ReaderOwnedJournal();+ private readonly topology_ = new ReaderOwnedJournal(true);/*** Components WRITTEN, for a consumer that needs to enumerate them sparsely.* `isChangedSince` answers about one entity at a time; finding which entities* changed through it means walking the per-entity map, which is the O(E) a* candidate consumer is trying to avoid.*/- private readonly writes_ = new ReaderOwnedJournal();+ private readonly writes_ = new ReaderOwnedJournal(true);private trackedComponents_ = new Set<symbol>();// The most recent worldTick at which ANY entity changed each component — an// O(1) "did anything change since tick T" gate (vs scanning the per-entity map).@@ -282,6 +282,30 @@ export class ChangeTracker {return this.topology_.since(component._id, sinceTick);}+ registerMutationCursor(component: AnyComponentDef, kind: 'write' | 'topology'): number {+ const id = this.nextReaderId_++;+ this.mutationJournal_(kind).registerCursor(component._id, id);+ return id;+ }++ mutationSequence(kind: 'write' | 'topology'): number { return this.mutationJournal_(kind).sequence(); }++ mutationsForCursor(component: AnyComponentDef, kind: 'write' | 'topology', reader: number): Entity[] {+ return this.mutationJournal_(kind).sinceCursor(component._id, reader);+ }++ advanceMutationCursor(component: AnyComponentDef, kind: 'write' | 'topology', reader: number, through: number): void {+ this.mutationJournal_(kind).advanceCursor(component._id, reader, through);+ }++ disposeMutationCursor(component: AnyComponentDef, kind: 'write' | 'topology', reader: number): void {+ this.mutationJournal_(kind).dispose(component._id, reader);+ }++ private mutationJournal_(kind: 'write' | 'topology'): ReaderOwnedJournal {+ return kind === 'write' ? this.writes_ : this.topology_;+ }+registerTopologyReaderFrom(component: AnyComponentDef, retainFromTick: number): number {const id = this.nextReaderId_++;this.topology_.register(component._id, id, retainFromTick);diff --git a/sdk/src/ecs/ComponentMutationReader.ts b/sdk/src/ecs/ComponentMutationReader.tsnew file mode 100644index 000000000..4e0649115--- /dev/null+++ b/sdk/src/ecs/ComponentMutationReader.ts@@ -0,0 +1,159 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import type { Entity } from '../types';+import type { World } from './world';+import type { CppRegistry } from '../wasm';+import { Children, Transform, isBuiltinComponent, type AnyComponentDef } from './component';+import { worldEngineApi, type EngineApi } from './bridge/engineApi';+import { withMalloc } from '../wasm/wasmScratch';+import { ENTITY_CHANGE_CAPACITY, ENTITY_CHANGE_WORDS, ENTITY_CHANGE_SUBTREE,+ ENTITY_CHANGE_RESET, ENTITY_CHANGE_REPLACED, ENTITY_CHANGE_NO_COMPONENT } from '../wasm/constants.generated';++export interface ComponentMutationBatch {+ readonly full: boolean;+ readonly reset: boolean;+ readonly entities: Set<Entity>;+ readonly changed: Map<AnyComponentDef, Set<Entity>>;+ readonly nativeSequence: number;+ readonly resetEpoch: number;+ readonly writeSequence: number;+ readonly topologySequence: number;+}++/** Projects SDK and native mutation cursors onto World-owned entities. Readers+ * acknowledge only successful runs and release history while their consumer stops. */+export class ComponentMutationReader {+ private api: EngineApi | null = null;+ private registry: CppRegistry | null = null;+ private lease: number | null = null;+ private cursor = 0;+ private first = true;+ private resetEpoch: number | null = null;+ private lastRegistry: CppRegistry | null = null;+ private readonly nativeTypes = new Map<number, AnyComponentDef>();+ private readonly writes = new Map<AnyComponentDef, number>();+ private readonly topology = new Map<AnyComponentDef, number>();+ private readonly offDisconnect: () => void;+ private readonly members: Set<AnyComponentDef>;+ private readonly values: Set<AnyComponentDef>;++ constructor(private readonly world: World, components: readonly AnyComponentDef[],+ topologyOnly: readonly AnyComponentDef[], private readonly subtree: readonly AnyComponentDef[]) {+ this.values = new Set([...components, ...subtree]);+ this.members = new Set([...this.values, ...topologyOnly]);+ this.offDisconnect = world.onCoreDisconnect(() => {+ try { this.pause(); } finally { this.lastRegistry = null; this.resetEpoch = null; }+ });+ }++ private open(): boolean {+ if (this.lease !== null) return true;+ const api = worldEngineApi(this.world), registry = this.world.getCppRegistry();+ if (!registry?.componentTypeId || !api?.registry_watchEntityChanges || !api.registry_unwatchEntityChanges+ || !api.registry_entityChangeSequence || !api.registry_entityChangeResetEpoch || !api.registry_readEntityChanges+ || !api._malloc || !api._free || !api.HEAPU32) return false;+ for (const component of this.members) {+ if (!isBuiltinComponent(component)) continue;+ const id = registry.componentTypeId(component._cppName);+ if (!Number.isInteger(id) || id < 0) { this.nativeTypes.clear(); return false; }+ this.nativeTypes.set(id, component);+ }+ this.api = api; this.registry = registry;+ if (this.lastRegistry !== registry) {+ this.lastRegistry = registry;+ this.resetEpoch = api.registry_entityChangeResetEpoch(registry);+ }+ this.lease = api.registry_watchEntityChanges(registry);+ for (const component of this.values) this.writes.set(component, this.world.registerMutationCursor(component, 'write'));+ for (const component of this.members) this.topology.set(component, this.world.registerMutationCursor(component, 'topology'));+ return true;+ }++ read(): ComponentMutationBatch | null {+ if (!this.open()) return null;+ const world = this.world, api = this.api!, registry = this.registry!;+ const nativeSequence = api.registry_entityChangeSequence!(registry);+ const resetEpoch = api.registry_entityChangeResetEpoch!(registry);+ const writeSequence = world.mutationSequence('write'), topologySequence = world.mutationSequence('topology');+ const entities = new Set<Entity>(), roots = new Set<Entity>();+ const changed = new Map<AnyComponentDef, Set<Entity>>();+ const note = (component: AnyComponentDef, entity: Entity, membership: boolean) => {+ let ids = changed.get(component);+ if (!ids) { ids = new Set(); changed.set(component, ids); }+ ids.add(entity);+ if (membership || this.values.has(component)) entities.add(entity);+ if (this.subtree.includes(component)) roots.add(entity);+ };+ for (const [component, reader] of this.writes) {+ for (const entity of world.mutationsForCursor(component, 'write', reader)) note(component, entity, false);+ }+ for (const [component, reader] of this.topology) {+ for (const entity of world.mutationsForCursor(component, 'topology', reader)) note(component, entity, true);+ }+ let reset = resetEpoch < 0 || resetEpoch !== this.resetEpoch;+ let full = this.first || reset;+ if (nativeSequence !== this.cursor) {+ withMalloc({ _malloc: api._malloc!.bind(api), _free: api._free!.bind(api) },+ ENTITY_CHANGE_CAPACITY * ENTITY_CHANGE_WORDS * 4, ptr => {+ if (!ptr) { full = true; return; }+ const count = api.registry_readEntityChanges!(registry, this.cursor, ptr, ENTITY_CHANGE_CAPACITY);+ if (count < 0) { full = true; return; }+ if (!Number.isInteger(count) || count > ENTITY_CHANGE_CAPACITY) throw new Error('Invalid native mutation batch length');+ const heap = api.HEAPU32!;+ for (let i = 0; i < count; ++i) {+ const at = (ptr >>> 2) + i * ENTITY_CHANGE_WORDS;+ const entity = heap[at] as Entity, flags = heap[at + 1], type = heap[at + 2];+ if (flags & ENTITY_CHANGE_RESET) { full = true; reset = true; continue; }+ if (flags & ENTITY_CHANGE_SUBTREE) roots.add(entity);+ if (type === ENTITY_CHANGE_NO_COMPONENT) entities.add(entity);+ const component = this.nativeTypes.get(type);+ if (!component) continue;+ const membership = !(flags & ENTITY_CHANGE_REPLACED);+ note(component, entity, membership);+ world.refreshBuiltinMembership(entity, component);+ }+ });+ }+ if (full) {+ for (const entity of world.getAllEntities()) {+ entities.add(entity);+ for (const component of this.nativeTypes.values()) world.refreshBuiltinMembership(entity, component);+ }+ } else if (roots.size) {+ const hasChildren = world.resolveHas(Children);+ const pending = [...roots], visited = new Set<Entity>();+ while (pending.length) {+ const entity = pending.pop()!;+ if (visited.has(entity) || !world.valid(entity)) continue;+ visited.add(entity); entities.add(entity);+ if (hasChildren?.(entity)) for (const child of world.get(entity, Children).entities) pending.push(child);+ }+ }+ if (roots.size) world.invalidateTransformComposition();+ // Native Transform replacement is a value write, independent of body membership.+ if (changed.has(Transform)) world.invalidateTransformComposition();+ return { full, reset, entities, changed, nativeSequence, resetEpoch, writeSequence, topologySequence };+ }++ commit(batch: ComponentMutationBatch): void {+ this.cursor = batch.nativeSequence; this.first = false;+ this.resetEpoch = batch.resetEpoch;+ for (const [component, reader] of this.writes) this.world.advanceMutationCursor(component, 'write', reader, batch.writeSequence);+ for (const [component, reader] of this.topology) this.world.advanceMutationCursor(component, 'topology', reader, batch.topologySequence);+ }++ pause(): void {+ for (const [component, reader] of this.writes) this.world.disposeMutationCursor(component, 'write', reader);+ for (const [component, reader] of this.topology) this.world.disposeMutationCursor(component, 'topology', reader);+ this.writes.clear(); this.topology.clear(); this.nativeTypes.clear();+ try {+ if (this.lease !== null) this.api!.registry_unwatchEntityChanges!(this.registry, this.lease);+ } finally {+ this.lease = null; this.registry = null; this.api = null; this.cursor = 0; this.first = true;+ }+ }++ dispose(): void {+ try { this.pause(); } finally { this.lastRegistry = null; this.offDisconnect(); }+ }+}diff --git a/sdk/src/ecs/bridge/nativeBindings.ts b/sdk/src/ecs/bridge/nativeBindings.tsindex 6e520dc7e..abdb790ae 100644--- a/sdk/src/ecs/bridge/nativeBindings.ts+++ b/sdk/src/ecs/bridge/nativeBindings.ts@@ -222,6 +222,7 @@ export function hasRendererBindings(/** Optional bulk inspection; older hosts retain individual component checks. */export const INSPECTION_BINDINGS = {getBuiltinComponentNames: 'es_getBuiltinComponentNames',+ componentTypeId: 'es_componentTypeId',} as const;/**diff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.tsindex b102a3493..9089bcf8c 100644--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts@@ -123,6 +123,7 @@ export interface NativeEngineApi {probe_volume_create?(resX: number, resY: number, resZ: number, shPtr: number): number;probe_volume_release?(volumeHandle: number): void;registry_batchSyncPhysicsTransforms?(registry: unknown, bufferPtr: number, count: number, ppu: number): void;+ registry_entityChangeResetEpoch?(registry: unknown): number;registry_entityChangeSequence?(registry: unknown): number;registry_getCanvasEntity?(registry: unknown): number;registry_getGeneration?(registry: unknown, entity: number): number;@@ -419,6 +420,7 @@ export function createNativeEngineApi(bind('probe_volume_create', 'es_probe_volume_create', false);bind('probe_volume_release', 'es_probe_volume_release', false);bind('registry_batchSyncPhysicsTransforms', 'es_registry_batchSyncPhysicsTransforms', true);+ bind('registry_entityChangeResetEpoch', 'es_registry_entityChangeResetEpoch', true);bind('registry_entityChangeSequence', 'es_registry_entityChangeSequence', true);bind('registry_getCanvasEntity', 'es_registry_getCanvasEntity', true);bind('registry_getGeneration', 'es_registry_getGeneration', true);diff --git a/sdk/src/ecs/bridge/nativeRegistry.ts b/sdk/src/ecs/bridge/nativeRegistry.tsindex 766b074b3..583ddc8d0 100644--- a/sdk/src/ecs/bridge/nativeRegistry.ts+++ b/sdk/src/ecs/bridge/nativeRegistry.ts@@ -89,7 +89,7 @@ export function createNativeRegistry(): CppRegistry {const reg: Record<string, unknown> = {};for (const [method, binding] of Object.entries(INSPECTION_BINDINGS)) {- if (typeof scope[binding] === 'function') reg[method] = (entity: Entity) => hostCall(scope, binding, [entity]);+ if (typeof scope[binding] === 'function') reg[method] = (...args: unknown[]) => hostCall(scope, binding, args);}for (const [method, binding] of Object.entries(ACTIVITY_BINDINGS)) {if (typeof scope[binding] === 'function') reg[method] = (...args: unknown[]) => hostCall(scope, binding, args);diff --git a/sdk/src/ecs/world.ts b/sdk/src/ecs/world.tsindex 159cf6648..ff3c0e3e8 100644--- a/sdk/src/ecs/world.ts+++ b/sdk/src/ecs/world.ts@@ -162,6 +162,7 @@ export class World {private inactive_: { set: Set<Entity> } | null = null;private inactiveVersion_ = -1;private coreActivityEpoch_ = -1;+ private readonly coreDisconnect_ = new Set<() => void>();private entities_ = new Map<Entity, number>();private indexGeneration_ = new Map<number, number>(); // index -> current generation (for isStale detection)private iterationDepth_ = 0;@@ -189,6 +190,7 @@ export class World {module?: ESEngineModule,options?: BridgeConnectOptions,): void {+ if (this.getCppRegistry()) this.notifyCoreDisconnect_();this.addressOf_.clear();this.builtin_.connect(cppRegistry, module, options);for (const e of this.scripts_.getStorageById(Disabled._id)?.keys() ?? []) cppRegistry.setEntityEnabled?.(e, false);@@ -198,6 +200,7 @@ export class World {/** @internal */disconnectCpp(): void {+ this.notifyCoreDisconnect_();this.addressOf_.clear();this.builtin_.disconnect();this.coreActivityEpoch_ = -1;@@ -214,6 +217,30 @@ export class World {return this.builtin_.getCppRegistry();}+ /** @internal Release native leases before the owning core is disconnected. */+ onCoreDisconnect(dispose: () => void): () => void {+ this.coreDisconnect_.add(dispose);+ return () => { this.coreDisconnect_.delete(dispose); };+ }++ private notifyCoreDisconnect_(): void {+ for (const dispose of [...this.coreDisconnect_]) {+ try { dispose(); } catch (error) { log.warn('world', 'Core disconnect callback error', error); }+ }+ }++ /** @internal Refresh membership mirrors after an observed native mutation. */+ refreshBuiltinMembership(entity: Entity, component: AnyComponentDef): void {+ if (!isBuiltinComponent(component)) return;+ const set = this.builtin_.getEntitySet(component._cppName);+ const present = this.builtin_.getBuiltinMethods(component._cppName).has(entity);+ if (set && set.has(entity) !== present) {+ if (present) set.add(entity); else set.delete(entity);+ this.queries_.markStructuralChange();+ }+ this.queries_.markComponentDirty(component._id);+ }+/** @internal */getWasmModule(): ESEngineModule | null {return this.builtin_.getWasmModule();@@ -473,6 +500,7 @@ export class World {indexSlots: number;spawnCallbacks: number;despawnCallbacks: number;+ coreDisconnectCallbacks: number;names: ReturnType<NameIndex['sizes']>;scripts: ReturnType<ScriptStorage['sizes']>;changes: ReturnType<ChangeTracker['sizes']>;@@ -483,6 +511,7 @@ export class World {indexSlots: this.indexGeneration_.size,spawnCallbacks: this.spawnCallbacks_.length,despawnCallbacks: this.despawnCallbacks_.length,+ coreDisconnectCallbacks: this.coreDisconnect_.size,names: this.names_.sizes(),scripts: this.scripts_.sizes(),changes: this.changes_.sizes(),@@ -1476,6 +1505,29 @@ export class World {return this.changes_.registerTopologyReaderFrom(component, retainFromTick);}+ /** @internal A mutation cursor distinguishes writes within one world tick. */+ registerMutationCursor(component: AnyComponentDef, kind: 'write' | 'topology'): number {+ return this.changes_.registerMutationCursor(component, kind);+ }++ /** @internal Current boundary to acknowledge after a successful read. */+ mutationSequence(kind: 'write' | 'topology'): number { return this.changes_.mutationSequence(kind); }++ /** @internal Unacknowledged component mutations for this reader. */+ mutationsForCursor(component: AnyComponentDef, kind: 'write' | 'topology', reader: number): Entity[] {+ return this.changes_.mutationsForCursor(component, kind, reader);+ }++ /** @internal Preserve mutations that arrived after the read's boundary. */+ advanceMutationCursor(component: AnyComponentDef, kind: 'write' | 'topology', reader: number, through: number): void {+ this.changes_.advanceMutationCursor(component, kind, reader, through);+ }++ /** @internal Release this reader's history claim. */+ disposeMutationCursor(component: AnyComponentDef, kind: 'write' | 'topology', reader: number): void {+ this.changes_.disposeMutationCursor(component, kind, reader);+ }+/** @internal Entities worth re-reading because their membership moved. */getTopologyChangedEntitiesSince(component: AnyComponentDef, sinceTick: number): Entity[] {return this.changes_.getTopologyChangedEntitiesSince(component, sinceTick);diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex 7db46f0fe..fcc408d86 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -688,6 +688,7 @@ export interface ESEngineModule {registry_watchEntityChanges?(registry: CppRegistry): number;registry_unwatchEntityChanges?(registry: CppRegistry, reader: number): void;registry_entityChangeSequence?(registry: CppRegistry): number;+ registry_entityChangeResetEpoch?(registry: CppRegistry): number;registry_readEntityChanges?(registry: CppRegistry, after: number, outputPtr: number, capacity: number): number;registry_batchSyncPhysicsTransforms(registry: CppRegistry, bufferPtr: number, count: number, ppu: number): void;registry_readWorldPoses2D?(registry: CppRegistry, entitiesPtr: number, count: number, outputPtr: number): number;diff --git a/sdk/src/wasm/wasm.generated.ts b/sdk/src/wasm/wasm.generated.tsindex bbc8230a1..2b382c237 100644--- a/sdk/src/wasm/wasm.generated.ts+++ b/sdk/src/wasm/wasm.generated.ts@@ -939,6 +939,8 @@ export interface Registry {entityCount(): number;/** All generated builtin names, separated by |; absent on older cores. */getBuiltinComponentNames?(entity: Entity): string;+ /** Host-local component ID; -1 for an unknown name. */+ componentTypeId?(name: string): number;hasBitmapText(entity: Entity): boolean;getBitmapText(entity: Entity): BitmapText;diff --git a/sdk/tests/component-mutation-cursor.test.ts b/sdk/tests/component-mutation-cursor.test.tsnew file mode 100644index 000000000..1a1f9d1e1--- /dev/null+++ b/sdk/tests/component-mutation-cursor.test.ts@@ -0,0 +1,77 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { expect, it } from 'vitest';+import { World } from '../src/ecs/world';+import { defineComponent } from '../src/ecs/component';+import { ComponentMutationReader } from '../src/ecs/ComponentMutationReader';+import { createNativeRegistry } from '../src/ecs/bridge/nativeRegistry';++it('acknowledges only sampled writes, including subsequent writes in the same tick', () => {+ const world = new World(), component = defineComponent('CursorWrite', { value: 0 });+ const reader = world.registerMutationCursor(component, 'write');+ const entity = world.spawn(); world.insert(entity, component);+ const through = world.mutationSequence('write');+ expect(world.mutationsForCursor(component, 'write', reader)).toEqual([entity]);+ world.update(entity, component, value => { value.value = 1; });+ world.advanceMutationCursor(component, 'write', reader, through);+ expect(world.mutationsForCursor(component, 'write', reader)).toEqual([entity]);+ world.advanceMutationCursor(component, 'write', reader, world.mutationSequence('write'));+ expect(world.mutationsForCursor(component, 'write', reader)).toEqual([]);+ expect(world.bufferedWriteRows(component)).toBe(0);+ world.disposeMutationCursor(component, 'write', reader);+ expect(world.writeReaderCount(component)).toBe(0);+});++it('retains topology changes for independent readers through remove and reinsert', () => {+ const world = new World(), component = defineComponent('CursorMembership', { value: 0 });+ const fast = world.registerMutationCursor(component, 'topology');+ const slow = world.registerMutationCursor(component, 'topology');+ const entity = world.spawn(); world.insert(entity, component);+ world.advanceMutationCursor(component, 'topology', fast, world.mutationSequence('topology'));+ world.remove(entity, component); world.insert(entity, component, { value: 3 });+ expect(world.mutationsForCursor(component, 'topology', fast)).toEqual([entity, entity]);+ expect(world.mutationsForCursor(component, 'topology', slow)).toEqual([entity, entity, entity]);+ world.disposeMutationCursor(component, 'topology', slow);+ expect(world.mutationsForCursor(component, 'topology', fast)).toEqual([entity, entity]);+ world.disposeMutationCursor(component, 'topology', fast);+ expect(world.topologyReaderCount(component)).toBe(0);+});++it('lets tick samplers and cursor readers retain different windows', () => {+ const world = new World(), component = defineComponent('CursorMixed', { value: 0 });+ const cursor = world.registerMutationCursor(component, 'write');+ const ticks = world.registerWriteReaderFrom(component, 0);+ const entity = world.spawn(); world.insert(entity, component);+ world.advanceTick(); world.update(entity, component, value => { value.value++; });+ world.advanceMutationCursor(component, 'write', cursor, world.mutationSequence('write'));+ expect(world.mutationsForCursor(component, 'write', cursor)).toEqual([]);+ expect(world.getWrittenEntitiesSince(component, -1)).toEqual([entity, entity]);+ world.disposeWriteReader(component, ticks);+ expect(world.bufferedWriteRows(component)).toBe(0);+ world.disposeMutationCursor(component, 'write', cursor);+});++it('keeps older or logic-only hosts on the existing reconciliation path', () => {+ const world = new World(), component = defineComponent('CursorLegacy', { value: 0 });+ const reader = new ComponentMutationReader(world, [component], [], []);+ expect(reader.read()).toBeNull();+ expect(world.writeReaderCount(component)).toBe(0);+ expect(world.topologyReaderCount(component)).toBe(0);+ reader.dispose(); world.disconnectCpp();+});++it('resolves component IDs through the native host without treating names as entities', () => {+ const registry = createNativeRegistry({ es_componentTypeId: (name: string) => name === 'RigidBody2D' ? 17 : -1 });+ expect(registry.componentTypeId?.('RigidBody2D')).toBe(17);+ expect(registry.componentTypeId?.('unknown')).toBe(-1);+});++it('continues disconnect cleanup when another native observer fails', () => {+ const world = new World(); let cleaned = false;+ const first = world.onCoreDisconnect(() => { throw new Error('native core is unavailable'); });+ const second = world.onCoreDisconnect(() => { cleaned = true; });+ expect(() => world.disconnectCpp()).not.toThrow();+ expect(cleaned).toBe(true);+ first(); second();+ expect(world.getStorageSizes().coreDisconnectCallbacks).toBe(0);+});diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cppindex db6c14968..7f2b9198f 100644--- a/src/esengine/bindings/RendererBindings.cpp+++ b/src/esengine/bindings/RendererBindings.cpp@@ -1218,6 +1218,7 @@ u32 registry_getGeneration(ecs::Registry& registry, u32 entity) {u32 registry_watchEntityChanges(ecs::Registry& registry) { return registry.watchEntityChanges(); }void registry_unwatchEntityChanges(ecs::Registry& registry, u32 reader) { registry.unwatchEntityChanges(reader); }double registry_entityChangeSequence(ecs::Registry& registry) { return registry.entityChangeSequence(); }+double registry_entityChangeResetEpoch(ecs::Registry& registry) { return registry.entityChangeResetEpoch(); }int registry_readEntityChanges(ecs::Registry& registry, double after, uintptr_t outputPtr, int capacity) {if (capacity < 0 || capacity > static_cast<int>(ecs::ENTITY_CHANGE_CAPACITY)|| outputPtr % alignof(ecs::EntityChangeRow)) return -1;diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hppindex 9cf1f1d30..428fd341f 100644--- a/src/esengine/bindings/RendererBindings.hpp+++ b/src/esengine/bindings/RendererBindings.hpp@@ -322,6 +322,7 @@ u32 registry_getGeneration(ecs::Registry& registry, u32 entity);u32 registry_watchEntityChanges(ecs::Registry& registry);void registry_unwatchEntityChanges(ecs::Registry& registry, u32 reader);double registry_entityChangeSequence(ecs::Registry& registry);+double registry_entityChangeResetEpoch(ecs::Registry& registry);// Output contains entity/flags/component-type rows. Returns -1 when the cursor or capacity// cannot cover the retained history; the caller must perform a full refresh.int registry_readEntityChanges(ecs::Registry& registry, double after, uintptr_t outputPtr, int capacity);diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cppindex d4973a5e1..c31c44138 100644--- a/src/esengine/bindings/WebBindings.generated.cpp+++ b/src/esengine/bindings/WebBindings.generated.cpp@@ -2130,6 +2130,57 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {return names;}))+ .function("componentTypeId", optional_override([](Registry&, const std::string& name) {+ if (name == "BitmapText") return static_cast<int>(componentTypeId<esengine::ecs::BitmapText>());+ if (name == "BoxCollider2D") return static_cast<int>(componentTypeId<esengine::ecs::BoxCollider2D>());+ if (name == "BoxCollider3D") return static_cast<int>(componentTypeId<esengine::ecs::BoxCollider3D>());+ if (name == "Camera") return static_cast<int>(componentTypeId<esengine::ecs::Camera>());+ if (name == "Canvas") return static_cast<int>(componentTypeId<esengine::ecs::Canvas>());+ if (name == "CapsuleCollider2D") return static_cast<int>(componentTypeId<esengine::ecs::CapsuleCollider2D>());+ if (name == "CapsuleCollider3D") return static_cast<int>(componentTypeId<esengine::ecs::CapsuleCollider3D>());+ if (name == "CharacterController3D") return static_cast<int>(componentTypeId<esengine::ecs::CharacterController3D>());+ if (name == "Children") return static_cast<int>(componentTypeId<esengine::ecs::Children>());+ if (name == "CircleCollider2D") return static_cast<int>(componentTypeId<esengine::ecs::CircleCollider2D>());+ if (name == "ConvexCollider3D") return static_cast<int>(componentTypeId<esengine::ecs::ConvexCollider3D>());+ if (name == "Draggable") return static_cast<int>(componentTypeId<esengine::ecs::Draggable>());+ if (name == "DragonBonesAnimation") return static_cast<int>(componentTypeId<esengine::ecs::DragonBonesAnimation>());+ if (name == "FlexContainer") return static_cast<int>(componentTypeId<esengine::ecs::FlexContainer>());+ if (name == "Interactable") return static_cast<int>(componentTypeId<esengine::ecs::Interactable>());+ if (name == "LODGroup") return static_cast<int>(componentTypeId<esengine::ecs::LODGroup>());+ if (name == "Light") return static_cast<int>(componentTypeId<esengine::ecs::Light>());+ if (name == "LightProbeVolume") return static_cast<int>(componentTypeId<esengine::ecs::LightProbeVolume>());+ if (name == "MeshCollider3D") return static_cast<int>(componentTypeId<esengine::ecs::MeshCollider3D>());+ if (name == "MeshLightmap") return static_cast<int>(componentTypeId<esengine::ecs::MeshLightmap>());+ if (name == "MeshMorph") return static_cast<int>(componentTypeId<esengine::ecs::MeshMorph>());+ if (name == "MeshRenderer") return static_cast<int>(componentTypeId<esengine::ecs::MeshRenderer>());+ if (name == "MeshSkin") return static_cast<int>(componentTypeId<esengine::ecs::MeshSkin>());+ if (name == "Occluder") return static_cast<int>(componentTypeId<esengine::ecs::Occluder>());+ if (name == "Parent") return static_cast<int>(componentTypeId<esengine::ecs::Parent>());+ if (name == "ParticleEmitter") return static_cast<int>(componentTypeId<esengine::ecs::ParticleEmitter>());+ if (name == "ParticleForceField") return static_cast<int>(componentTypeId<esengine::ecs::ParticleForceField>());+ if (name == "ReflectionProbe") return static_cast<int>(componentTypeId<esengine::ecs::ReflectionProbe>());+ if (name == "RigidBody2D") return static_cast<int>(componentTypeId<esengine::ecs::RigidBody2D>());+ if (name == "RigidBody3D") return static_cast<int>(componentTypeId<esengine::ecs::RigidBody3D>());+ if (name == "SegmentCollider2D") return static_cast<int>(componentTypeId<esengine::ecs::SegmentCollider2D>());+ if (name == "ShadowCaster2D") return static_cast<int>(componentTypeId<esengine::ecs::ShadowCaster2D>());+ if (name == "ShapeRenderer") return static_cast<int>(componentTypeId<esengine::ecs::ShapeRenderer>());+ if (name == "SortingGroup") return static_cast<int>(componentTypeId<esengine::ecs::SortingGroup>());+ if (name == "SphereCollider3D") return static_cast<int>(componentTypeId<esengine::ecs::SphereCollider3D>());+ if (name == "SpineAnimation") return static_cast<int>(componentTypeId<esengine::ecs::SpineAnimation>());+ if (name == "Sprite") return static_cast<int>(componentTypeId<esengine::ecs::Sprite>());+ if (name == "SpriteMask") return static_cast<int>(componentTypeId<esengine::ecs::SpriteMask>());+ if (name == "TilemapLayer") return static_cast<int>(componentTypeId<esengine::ecs::TilemapLayer>());+ if (name == "TrailRenderer") return static_cast<int>(componentTypeId<esengine::ecs::TrailRenderer>());+ if (name == "Transform") return static_cast<int>(componentTypeId<esengine::ecs::Transform>());+ if (name == "UIInteraction") return static_cast<int>(componentTypeId<esengine::ecs::UIInteraction>());+ if (name == "UIMask") return static_cast<int>(componentTypeId<esengine::ecs::UIMask>());+ if (name == "UINode") return static_cast<int>(componentTypeId<esengine::ecs::UINode>());+ if (name == "UIScroll") return static_cast<int>(componentTypeId<esengine::ecs::UIScroll>());+ if (name == "UIVisual") return static_cast<int>(componentTypeId<esengine::ecs::UIVisual>());+ if (name == "Velocity") return static_cast<int>(componentTypeId<esengine::ecs::Velocity>());+ return -1;+ }))+// BitmapText.function("hasBitmapText", optional_override([](Registry& r, u32 e) {return r.has<esengine::ecs::BitmapText>(static_cast<Entity>(e));diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex 8fb09fc44..279bf51f3 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -785,6 +785,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {emscripten::function("registry_watchEntityChanges", &esengine::registry_watchEntityChanges);emscripten::function("registry_unwatchEntityChanges", &esengine::registry_unwatchEntityChanges);emscripten::function("registry_entityChangeSequence", &esengine::registry_entityChangeSequence);+ emscripten::function("registry_entityChangeResetEpoch", &esengine::registry_entityChangeResetEpoch);emscripten::function("registry_readEntityChanges", &esengine::registry_readEntityChanges);emscripten::function("gl_enableErrorCheck", &esengine::gl_enableErrorCheck);diff --git a/src/esengine/ecs/EntityChangeJournal.hpp b/src/esengine/ecs/EntityChangeJournal.hppindex 0ec1b547b..4bcf597ab 100644--- a/src/esengine/ecs/EntityChangeJournal.hpp+++ b/src/esengine/ecs/EntityChangeJournal.hpp@@ -48,10 +48,12 @@ public:if (readers_.empty()) std::vector<EntityChangeRow>().swap(rows_);}double sequence() const { return static_cast<double>(sequence_); }+ double resetEpoch() const { return reset_epoch_ == MAX_SEQUENCE ? -1 : static_cast<double>(reset_epoch_); }usize readerCount() const { return readers_.size(); }usize retainedRows() const { return rows_.empty() ? 0 : std::min<u64>(sequence_, ENTITY_CHANGE_CAPACITY); }void record(u32 entity, u32 flags = 0, u32 component = ENTITY_CHANGE_NO_COMPONENT) {+ if ((flags & ENTITY_CHANGE_RESET) && reset_epoch_ < MAX_SEQUENCE) ++reset_epoch_;if (readers_.empty()) return;// Saturation preserves the JS number contract by requiring a rescan.if (sequence_ == MAX_SEQUENCE) { exhausted_ = true; return; }@@ -74,6 +76,7 @@ private:std::vector<EntityChangeRow> rows_;std::unordered_set<u32> readers_;u64 sequence_ = 0;+ u64 reset_epoch_ = 0;u32 next_reader_ = 0;bool exhausted_ = false;};diff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hppindex fecaa8898..abc4f6b04 100644--- a/src/esengine/ecs/Registry.hpp+++ b/src/esengine/ecs/Registry.hpp@@ -125,6 +125,7 @@ public:u32 watchEntityChanges() { return entity_changes_.watch(); }void unwatchEntityChanges(u32 reader) { entity_changes_.unwatch(reader); }double entityChangeSequence() const { return entity_changes_.sequence(); }+ double entityChangeResetEpoch() const { return entity_changes_.resetEpoch(); }i32 readEntityChanges(double after, std::span<EntityChangeRow> output) const {return entity_changes_.read(after, output);}diff --git a/tests/ecs/test_entity_activity.cpp b/tests/ecs/test_entity_activity.cppindex 73d7d94d6..dde9ce5df 100644--- a/tests/ecs/test_entity_activity.cpp+++ b/tests/ecs/test_entity_activity.cpp@@ -94,9 +94,12 @@ TEST_CASE("entity change history is bounded and owned by independent readers") {EntityChangeJournal journal;journal.record(1);CHECK(journal.retainedRows() == 0);+ journal.record(1, ENTITY_CHANGE_RESET);+ CHECK(journal.resetEpoch() == 1);std::array<EntityChangeRow, ENTITY_CHANGE_CAPACITY> rows{};CHECK(journal.read(0, rows) == -1);const auto first = journal.watch();+ CHECK(journal.resetEpoch() == 1);journal.record(10);const auto second = journal.watch();const auto cursor = journal.sequence();@@ -166,6 +169,7 @@ TEST_CASE("registry history covers component lifetime and explicit native writesCHECK(rows[5].component == componentTypeId<JournalPosition>());const auto cursor = registry.entityChangeSequence();registry.clear();+ CHECK(registry.entityChangeResetEpoch() == 1);REQUIRE(registry.readEntityChanges(cursor, rows) == 1);CHECK(rows[0].flags == ENTITY_CHANGE_RESET);registry.unwatchEntityChanges(reader);diff --git a/tools/eht/generators/embind.py b/tools/eht/generators/embind.pyindex d73211583..77755fc11 100644--- a/tools/eht/generators/embind.py+++ b/tools/eht/generators/embind.py@@ -390,6 +390,11 @@ class EmbindGenerator:full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.namelines.append(f' if (r.has<{full}>(entity)) {{ if (!names.empty()) names += "|"; names += "{comp.name}"; }}')lines.extend([' return names;', ' }))', ''])+ lines.append(' .function("componentTypeId", optional_override([](Registry&, const std::string& name) {')+ for comp in self.components:+ full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name+ lines.append(f' if (name == "{comp.name}") return static_cast<int>(componentTypeId<{full}>());')+ lines.extend([' return -1;', ' }))', ''])for comp in self.components:full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.namediff --git a/tools/eht/generators/native_bindings.py b/tools/eht/generators/native_bindings.pyindex aa4af45b2..707d603b0 100644--- a/tools/eht/generators/native_bindings.py+++ b/tools/eht/generators/native_bindings.py@@ -273,7 +273,21 @@ class NativeBindingsGenerator:' return JS_NewStringLen(ctx, names.data(), names.size());','}', '',])+ lines.extend([+ 'static JSValue es_componentTypeId(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {',+ ' if (argc < 1) return JS_NewInt32(ctx, -1);',+ ' const char* raw = JS_ToCString(ctx, argv[0]);',+ ' if (!raw) return JS_EXCEPTION;',+ ' const std::string name(raw);',+ ' JS_FreeCString(ctx, raw);',+ ])+ for comp in components:+ full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name+ lines.append(f' if (name == "{comp.name}") return JS_NewInt64(ctx, esengine::componentTypeId<{full}>());')+ lines.extend([' return JS_NewInt32(ctx, -1);', '}', ''])lines.append('void esn_register(JSContext* ctx, JSValue global) {')+ lines.append(' JS_SetPropertyStr(ctx, global, "es_componentTypeId", '+ 'JS_NewCFunction(ctx, es_componentTypeId, "es_componentTypeId", 1));')lines.append(' JS_SetPropertyStr(ctx, global, "es_getBuiltinComponentNames", ''JS_NewCFunction(ctx, es_getBuiltinComponentNames, "es_getBuiltinComponentNames", 1));')for comp in components:diff --git a/tools/eht/generators/typescript.py b/tools/eht/generators/typescript.pyindex cda84718e..cd61ff2c9 100644--- a/tools/eht/generators/typescript.py+++ b/tools/eht/generators/typescript.py@@ -98,6 +98,8 @@ class TypeScriptGenerator:' entityCount(): number;',' /** All generated builtin names, separated by |; absent on older cores. */',' getBuiltinComponentNames?(entity: Entity): string;',+ ' /** Host-local component ID; -1 for an unknown name. */',+ ' componentTypeId?(name: string): number;','',]for comp in self.components:diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex e1e85d236..18505c298 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'refactor(ecs): unify SDK and native mutation cursors':+ { internal: 'Provides same-tick SDK mutation cursors, generated host component IDs, native reset epochs and owned core-disconnect leases for shared sparse runtime synchronization.' },'refactor(ecs): expose bounded native entity change history':{ internal: 'Adds opt-in native entity and component mutation history as infrastructure for sparse synchronization, with independent cursors, bounded storage, hierarchy roots and overflow/reset signals; no user-facing synchronization policy changes in this commit.' },'perf(tilemap): synchronize collision by changed chunk':