Skip to content

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

perf(sdk): decouple the query cache from the global structural version

esengine8db0da248ac7
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 2d0090f74..ce931d21b 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -937,7 +937,7 @@ width: number
## BuiltinBridge — class
```
connect: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => void
-deleteFromEntitySets: (entity: Entity) => void
+deleteFromEntitySets: (entity: Entity) => string[]
disconnect: () => void
get: <T>(entity: Entity, component: BuiltinComponentDef<T>) => T
getBuiltinMethods: (cppName: string) => BuiltinMethods
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 7b6ace18d..b11a1b852 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -932,7 +932,7 @@ width: number
## BuiltinBridge — class
```
connect: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => void
-deleteFromEntitySets: (entity: Entity) => void
+deleteFromEntitySets: (entity: Entity) => string[]
disconnect: () => void
get: <T>(entity: Entity, component: BuiltinComponentDef<T>) => T
getBuiltinMethods: (cppName: string) => BuiltinMethods
diff --git a/sdk/src/ecs/BuiltinBridge.ts b/sdk/src/ecs/BuiltinBridge.ts
index a93286854..ccd94e5d9 100644
--- a/sdk/src/ecs/BuiltinBridge.ts
+++ b/sdk/src/ecs/BuiltinBridge.ts
@@ -512,10 +512,13 @@ export class BuiltinBridge {
return set;
}
- deleteFromEntitySets(entity: Entity): void {
- for (const [, set] of this.builtinEntitySets_) {
- set.delete(entity);
+ /** Removes the entity from every builtin set; returns the cppNames it was in. */
+ deleteFromEntitySets(entity: Entity): string[] {
+ const removed: string[] = [];
+ for (const [cppName, set] of this.builtinEntitySets_) {
+ if (set.delete(entity)) removed.push(cppName);
}
+ return removed;
}
insert<T>(entity: Entity, component: BuiltinComponentDef<T>, data?: Partial<T>): { merged: T; isNew: boolean } {
diff --git a/sdk/src/ecs/QueryCache.ts b/sdk/src/ecs/QueryCache.ts
index 2357ba7ad..17373d777 100644
--- a/sdk/src/ecs/QueryCache.ts
+++ b/sdk/src/ecs/QueryCache.ts
@@ -8,7 +8,6 @@
import { Entity } from '../types';
interface CacheEntry {
- structuralVersion: number;
componentVersions: Map<symbol, number>;
result: Entity[];
}
@@ -41,6 +40,10 @@ export class QueryCache {
return this.structuralVersion_;
}
+ // A monotonic "something structural happened" counter exposed as the world
+ // version for coarse external gates (e.g. physics reconcile). It deliberately
+ // does NOT invalidate cached queries — invalidation is per-component below, so
+ // churn of unrelated entities never drops an unrelated query's result.
markStructuralChange(): void {
this.structuralVersion_++;
}
@@ -61,14 +64,11 @@ export class QueryCache {
): Entity[] {
const cached = this.cache_.get(cacheKey);
if (cached) {
- const validity = this.checkValidity_(cached, dependentComponentIds);
- if (validity === 0) {
+ if (this.checkValidity_(cached, dependentComponentIds)) {
this.hits_++;
return cached.result;
}
- // 1 = structural, 2 = component — classify the miss for stats.
- if (validity === 1) this.structuralInvalidations_++;
- else this.componentInvalidations_++;
+ this.componentInvalidations_++;
}
this.misses_++;
@@ -79,7 +79,6 @@ export class QueryCache {
compVersions.set(id, this.componentVersions_.get(id) ?? 0);
}
this.cache_.set(cacheKey, {
- structuralVersion: this.structuralVersion_,
componentVersions: compVersions,
result,
});
@@ -106,17 +105,13 @@ export class QueryCache {
this.componentInvalidations_ = 0;
}
- /**
- * Returns 0 when the entry is still valid, 1 when structural version moved,
- * 2 when a dependent component changed.
- */
- private checkValidity_(entry: CacheEntry, dependentComponentIds: symbol[]): 0 | 1 | 2 {
- if (entry.structuralVersion !== this.structuralVersion_) return 1;
+ /** True when every dependent component is unchanged since the entry was cached. */
+ private checkValidity_(entry: CacheEntry, dependentComponentIds: symbol[]): boolean {
for (const id of dependentComponentIds) {
const current = this.componentVersions_.get(id) ?? 0;
const cached = entry.componentVersions.get(id) ?? 0;
- if (current !== cached) return 2;
+ if (current !== cached) return false;
}
- return 0;
+ return true;
}
}
diff --git a/sdk/src/world.ts b/sdk/src/world.ts
index 34b68311e..0db323018 100644
--- a/sdk/src/world.ts
+++ b/sdk/src/world.ts
@@ -6,7 +6,7 @@
*/
import { Entity, entityGeneration, entityIndex, makeEntity, INVALID_ENTITY } from './types';
-import { AnyComponentDef, ComponentDef, ComponentData, BuiltinComponentDef, isBuiltinComponent, getAllRegisteredComponents, getUserComponents, Name } from './component';
+import { AnyComponentDef, ComponentDef, ComponentData, BuiltinComponentDef, isBuiltinComponent, getAllRegisteredComponents, getUserComponents, getComponent, Name, Parent, Children } from './component';
import type { CppRegistry, ESEngineModule } from './wasm';
import { handleWasmError } from './wasmError';
import { BuiltinBridge, convertFromWasm, convertForWasm, type BridgeConnectOptions, type BuiltinMethods } from './ecs/BuiltinBridge';
@@ -253,11 +253,20 @@ export class World {
this.entities_.delete(entity);
this.queries_.markStructuralChange();
- this.builtin_.deleteFromEntitySets(entity);
+ // Dirty exactly the component versions this entity carried so its
+ // membership leaves the relevant cached queries — unrelated queries stay
+ // valid (the query cache no longer honors the global structural version).
+ for (const cppName of this.builtin_.deleteFromEntitySets(entity)) {
+ const def = getComponent(cppName);
+ if (def) this.queries_.markComponentDirty(def._id);
+ }
+ this.queries_.markComponentDirty(Parent._id);
+ this.queries_.markComponentDirty(Children._id);
const removedIds = this.scripts_.removeEntity(entity);
for (const id of removedIds) {
this.changes_.recordRemovedById(id, entity);
+ this.queries_.markComponentDirty(id);
}
}
@@ -346,6 +355,8 @@ export class World {
}
}
this.queries_.markStructuralChange();
+ this.queries_.markComponentDirty(Parent._id);
+ this.queries_.markComponentDirty(Children._id);
notifyBridge('onParentChanged', child, parent);
}
@@ -359,6 +370,8 @@ export class World {
}
}
this.queries_.markStructuralChange();
+ this.queries_.markComponentDirty(Parent._id);
+ this.queries_.markComponentDirty(Children._id);
notifyBridge('onParentChanged', entity, null);
}
diff --git a/sdk/tests/query-cache-stats.test.ts b/sdk/tests/query-cache-stats.test.ts
index bc0de9ffb..4e2854575 100644
--- a/sdk/tests/query-cache-stats.test.ts
+++ b/sdk/tests/query-cache-stats.test.ts
@@ -34,12 +34,18 @@ describe('QueryCache.getStats', () => {
expect(s.misses).toBe(1);
});
- it('attributes a structural-change miss to structuralInvalidations', () => {
- cache.getOrCompute('q1', [], () => []);
+ it('does not invalidate a cached query on a bare structural change', () => {
+ // markStructuralChange only advances the world version for coarse external
+ // gates (physics); query invalidation is per-component. A query whose
+ // dependent components are untouched must survive structural churn.
+ let computed = 0;
+ cache.getOrCompute('q1', [], () => { computed++; return []; });
cache.markStructuralChange();
- cache.getOrCompute('q1', [], () => []);
+ cache.getOrCompute('q1', [], () => { computed++; return []; });
+ expect(computed).toBe(1);
const s = cache.getStats();
- expect(s.structuralInvalidations).toBe(1);
+ expect(s.hits).toBe(1);
+ expect(s.structuralInvalidations).toBe(0);
expect(s.componentInvalidations).toBe(0);
});
diff --git a/sdk/tests/world.test.ts b/sdk/tests/world.test.ts
index 314889f88..669b85245 100644
--- a/sdk/tests/world.test.ts
+++ b/sdk/tests/world.test.ts
@@ -330,6 +330,27 @@ describe('World', () => {
const entities2 = world.getEntitiesWithComponents([Position]);
expect(entities2).toHaveLength(0);
});
+
+ it('keeps an unrelated query cached across churn of other components', () => {
+ const a = world.spawn();
+ world.insert(a, Position);
+
+ // Prime the [Position] query, then watch it survive unrelated churn.
+ expect(world.getEntitiesWithComponents([Position])).toHaveLength(1);
+ world.resetQueryCacheStats();
+
+ for (let i = 0; i < 20; i++) {
+ const e = world.spawn();
+ world.insert(e, Velocity);
+ world.despawn(e);
+ }
+
+ const result = world.getEntitiesWithComponents([Position]);
+ expect(result).toHaveLength(1);
+ const stats = world.getQueryCacheStats();
+ expect(stats.hits).toBe(1);
+ expect(stats.misses).toBe(0);
+ });
});
describe('complex scenarios', () => {