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): World is frozen, and the leak list is empty

esengine427df0fd5633
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 21bafa3c9..5ca21cc05 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -1,9 +1,9 @@
{
"note": "Generated by tools/api-stability.mjs from sdk/etc/*.api.md — do not edit.",
"counts": {
- "public": 71,
+ "public": 74,
"beta": 24,
- "experimental": 1530,
+ "experimental": 1527,
"deprecated": 3
},
"total": 1625,
@@ -128,6 +128,18 @@
"minigame"
]
},
+ {
+ "name": "ComponentData",
+ "kind": "type",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
{
"name": "ComponentDef",
"kind": "interface",
@@ -284,6 +296,18 @@
"minigame"
]
},
+ {
+ "name": "GetWorld",
+ "kind": "function",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
{
"name": "GetWorldDescriptor",
"kind": "interface",
@@ -752,6 +776,18 @@
"minigame"
]
},
+ {
+ "name": "World",
+ "kind": "class",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
{
"name": "addStartupSystem",
"kind": "function",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 2751856d5..c2bd92e73 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 71 public · 17 beta · 1415 experimental · 3 deprecated
+Symbols: 74 public · 17 beta · 1412 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -1791,7 +1791,7 @@ resume: () => void
state: TweenState
```
-## ComponentData — type @experimental
+## ComponentData — type @public
```
C extends BuiltinComponentDef<infer T> ? T :
C extends ComponentDef<infer T> ? T :
@@ -3025,7 +3025,7 @@ static new (input: InputState): GestureDetector
static prototype: GestureDetector
```
-## GetWorld — function @experimental
+## GetWorld — function @public
```
(): GetWorldDescriptor
```
@@ -8300,52 +8300,53 @@ tabIndex: number | undefined
(component: AnyComponentDef): FilterExpr
```
-## World — class @experimental
+## World — class @public
```
+@internal advanceTick: () => void
+@internal anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean
+@internal applyEntityOrder: (entities: readonly Entity[]) => void
+@internal beginIteration: () => void
@internal builtin: BuiltinBridge
+@internal changes_: ChangeTracker
+@internal cleanRemovedBuffer: (beforeTick: number) => void
@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => void
@internal disconnectCpp: () => void
+@internal enableChangeTracking: (component: AnyComponentDef) => void
+@internal endIteration: () => void
@internal getCppRegistry: () => CppRegistry | null
+@internal getQueryCacheStats: () => QueryCacheStats
+@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 getWasmModule: () => ESEngineModule | null
+@internal getWorldTick: () => number
+@internal getWorldVersion: () => number
+@internal hasCpp: boolean
+@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
+@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
+@internal isIterating: () => boolean
@internal markChanged: (entity: Entity, component: AnyComponentDef) => void
+@internal queries_: QueryCache
+@internal queryEntities: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]
+@internal resetIterationDepth: () => void
+@internal resetQueryCacheStats: () => void
+@internal resetQueryPool: () => void
@internal resolveGetter: (component: AnyComponentDef) => ((entity: Entity) => unknown) | null
@internal resolveHas: (component: AnyComponentDef) => ((entity: Entity) => boolean) | null
@internal resolveSetter: (component: AnyComponentDef) => ((entity: Entity, data: unknown) => void) | null
-advanceTick: () => void
-anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean
-applyEntityOrder: (entities: readonly Entity[]) => void
-beginIteration: () => void
-changes_: ChangeTracker
-cleanRemovedBuffer: (beforeTick: number) => void
despawn: (entity: Entity) => void
-enableChangeTracking: (component: AnyComponentDef) => void
-endIteration: () => void
entityCount: () => number
findEntityByName: (name: string) => Entity | null
get: <C extends AnyComponentDef>(entity: Entity, component: C) => ComponentData<C>
getAllEntities: () => Entity[]
getComponentTypes: (entity: Entity) => string[]
-getEntitiesWithComponents: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]
-getQueryCacheStats: () => QueryCacheStats
-getRemovedEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]
-getWorldTick: () => number
-getWorldVersion: () => number
+getEntitiesWithComponents: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[]) => readonly Entity[]
has: (entity: Entity, component: AnyComponentDef) => boolean
-hasCpp: boolean
insert: <C extends AnyComponentDef>(entity: Entity, component: C, data?: Partial<ComponentData<C>>) => ComponentData<C>
-isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
-isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
-isIterating: () => boolean
isStale: (entity: Entity) => boolean
onDespawn: (callback: (entity: Entity) => void) => () => void
onSpawn: (callback: (entity: Entity) => void) => () => void
-queries_: QueryCache
remove: (entity: Entity, component: AnyComponentDef) => void
removeParent: (entity: Entity) => void
-resetIterationDepth: () => void
-resetQueryCacheStats: () => void
-resetQueryPool: () => void
set: <C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentData<C>) => void
setParent: (child: Entity, parent: Entity) => void
spawn: (name?: string) => Entity
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 6a046e5a6..cf16459fa 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 71 public · 22 beta · 1434 experimental · 3 deprecated
+Symbols: 74 public · 22 beta · 1431 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -1791,7 +1791,7 @@ resume: () => void
state: TweenState
```
-## ComponentData — type @experimental
+## ComponentData — type @public
```
C extends BuiltinComponentDef<infer T> ? T :
C extends ComponentDef<infer T> ? T :
@@ -3033,7 +3033,7 @@ static new (input: InputState): GestureDetector
static prototype: GestureDetector
```
-## GetWorld — function @experimental
+## GetWorld — function @public
```
(): GetWorldDescriptor
```
@@ -8493,52 +8493,53 @@ tabIndex: number | undefined
(component: AnyComponentDef): FilterExpr
```
-## World — class @experimental
+## World — class @public
```
+@internal advanceTick: () => void
+@internal anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean
+@internal applyEntityOrder: (entities: readonly Entity[]) => void
+@internal beginIteration: () => void
@internal builtin: BuiltinBridge
+@internal changes_: ChangeTracker
+@internal cleanRemovedBuffer: (beforeTick: number) => void
@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => void
@internal disconnectCpp: () => void
+@internal enableChangeTracking: (component: AnyComponentDef) => void
+@internal endIteration: () => void
@internal getCppRegistry: () => CppRegistry | null
+@internal getQueryCacheStats: () => QueryCacheStats
+@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 getWasmModule: () => ESEngineModule | null
+@internal getWorldTick: () => number
+@internal getWorldVersion: () => number
+@internal hasCpp: boolean
+@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
+@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
+@internal isIterating: () => boolean
@internal markChanged: (entity: Entity, component: AnyComponentDef) => void
+@internal queries_: QueryCache
+@internal queryEntities: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]
+@internal resetIterationDepth: () => void
+@internal resetQueryCacheStats: () => void
+@internal resetQueryPool: () => void
@internal resolveGetter: (component: AnyComponentDef) => ((entity: Entity) => unknown) | null
@internal resolveHas: (component: AnyComponentDef) => ((entity: Entity) => boolean) | null
@internal resolveSetter: (component: AnyComponentDef) => ((entity: Entity, data: unknown) => void) | null
-advanceTick: () => void
-anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean
-applyEntityOrder: (entities: readonly Entity[]) => void
-beginIteration: () => void
-changes_: ChangeTracker
-cleanRemovedBuffer: (beforeTick: number) => void
despawn: (entity: Entity) => void
-enableChangeTracking: (component: AnyComponentDef) => void
-endIteration: () => void
entityCount: () => number
findEntityByName: (name: string) => Entity | null
get: <C extends AnyComponentDef>(entity: Entity, component: C) => ComponentData<C>
getAllEntities: () => Entity[]
getComponentTypes: (entity: Entity) => string[]
-getEntitiesWithComponents: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]
-getQueryCacheStats: () => QueryCacheStats
-getRemovedEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]
-getWorldTick: () => number
-getWorldVersion: () => number
+getEntitiesWithComponents: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[]) => readonly Entity[]
has: (entity: Entity, component: AnyComponentDef) => boolean
-hasCpp: boolean
insert: <C extends AnyComponentDef>(entity: Entity, component: C, data?: Partial<ComponentData<C>>) => ComponentData<C>
-isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
-isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
-isIterating: () => boolean
isStale: (entity: Entity) => boolean
onDespawn: (callback: (entity: Entity) => void) => () => void
onSpawn: (callback: (entity: Entity) => void) => () => void
-queries_: QueryCache
remove: (entity: Entity, component: AnyComponentDef) => void
removeParent: (entity: Entity) => void
-resetIterationDepth: () => void
-resetQueryCacheStats: () => void
-resetQueryPool: () => void
set: <C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentData<C>) => void
setParent: (child: Entity, parent: Entity) => void
spawn: (name?: string) => Entity
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 4744a437b..e5bf4927a 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 71 public · 19 beta · 1414 experimental · 3 deprecated
+Symbols: 74 public · 19 beta · 1411 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1786,7 +1786,7 @@ resume: () => void
state: TweenState
```
-## ComponentData — type @experimental
+## ComponentData — type @public
```
C extends BuiltinComponentDef<infer T> ? T :
C extends ComponentDef<infer T> ? T :
@@ -3020,7 +3020,7 @@ static new (input: InputState): GestureDetector
static prototype: GestureDetector
```
-## GetWorld — function @experimental
+## GetWorld — function @public
```
(): GetWorldDescriptor
```
@@ -8295,52 +8295,53 @@ tabIndex: number | undefined
(component: AnyComponentDef): FilterExpr
```
-## World — class @experimental
+## World — class @public
```
+@internal advanceTick: () => void
+@internal anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean
+@internal applyEntityOrder: (entities: readonly Entity[]) => void
+@internal beginIteration: () => void
@internal builtin: BuiltinBridge
+@internal changes_: ChangeTracker
+@internal cleanRemovedBuffer: (beforeTick: number) => void
@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => void
@internal disconnectCpp: () => void
+@internal enableChangeTracking: (component: AnyComponentDef) => void
+@internal endIteration: () => void
@internal getCppRegistry: () => CppRegistry | null
+@internal getQueryCacheStats: () => QueryCacheStats
+@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 getWasmModule: () => ESEngineModule | null
+@internal getWorldTick: () => number
+@internal getWorldVersion: () => number
+@internal hasCpp: boolean
+@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
+@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
+@internal isIterating: () => boolean
@internal markChanged: (entity: Entity, component: AnyComponentDef) => void
+@internal queries_: QueryCache
+@internal queryEntities: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]
+@internal resetIterationDepth: () => void
+@internal resetQueryCacheStats: () => void
+@internal resetQueryPool: () => void
@internal resolveGetter: (component: AnyComponentDef) => ((entity: Entity) => unknown) | null
@internal resolveHas: (component: AnyComponentDef) => ((entity: Entity) => boolean) | null
@internal resolveSetter: (component: AnyComponentDef) => ((entity: Entity, data: unknown) => void) | null
-advanceTick: () => void
-anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean
-applyEntityOrder: (entities: readonly Entity[]) => void
-beginIteration: () => void
-changes_: ChangeTracker
-cleanRemovedBuffer: (beforeTick: number) => void
despawn: (entity: Entity) => void
-enableChangeTracking: (component: AnyComponentDef) => void
-endIteration: () => void
entityCount: () => number
findEntityByName: (name: string) => Entity | null
get: <C extends AnyComponentDef>(entity: Entity, component: C) => ComponentData<C>
getAllEntities: () => Entity[]
getComponentTypes: (entity: Entity) => string[]
-getEntitiesWithComponents: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]
-getQueryCacheStats: () => QueryCacheStats
-getRemovedEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]
-getWorldTick: () => number
-getWorldVersion: () => number
+getEntitiesWithComponents: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[]) => readonly Entity[]
has: (entity: Entity, component: AnyComponentDef) => boolean
-hasCpp: boolean
insert: <C extends AnyComponentDef>(entity: Entity, component: C, data?: Partial<ComponentData<C>>) => ComponentData<C>
-isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
-isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
-isIterating: () => boolean
isStale: (entity: Entity) => boolean
onDespawn: (callback: (entity: Entity) => void) => () => void
onSpawn: (callback: (entity: Entity) => void) => () => void
-queries_: QueryCache
remove: (entity: Entity, component: AnyComponentDef) => void
removeParent: (entity: Entity) => void
-resetIterationDepth: () => void
-resetQueryCacheStats: () => void
-resetQueryPool: () => void
set: <C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentData<C>) => void
setParent: (child: Entity, parent: Entity) => void
spawn: (name?: string) => Entity
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index da4d28309..7afbedc7b 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 71 public · 17 beta · 1435 experimental · 3 deprecated
+Symbols: 74 public · 17 beta · 1432 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1786,7 +1786,7 @@ resume: () => void
state: TweenState
```
-## ComponentData — type @experimental
+## ComponentData — type @public
```
C extends BuiltinComponentDef<infer T> ? T :
C extends ComponentDef<infer T> ? T :
@@ -3020,7 +3020,7 @@ static new (input: InputState): GestureDetector
static prototype: GestureDetector
```
-## GetWorld — function @experimental
+## GetWorld — function @public
```
(): GetWorldDescriptor
```
@@ -8540,52 +8540,53 @@ tabIndex: number | undefined
(component: AnyComponentDef): FilterExpr
```
-## World — class @experimental
+## World — class @public
```
+@internal advanceTick: () => void
+@internal anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean
+@internal applyEntityOrder: (entities: readonly Entity[]) => void
+@internal beginIteration: () => void
@internal builtin: BuiltinBridge
+@internal changes_: ChangeTracker
+@internal cleanRemovedBuffer: (beforeTick: number) => void
@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => void
@internal disconnectCpp: () => void
+@internal enableChangeTracking: (component: AnyComponentDef) => void
+@internal endIteration: () => void
@internal getCppRegistry: () => CppRegistry | null
+@internal getQueryCacheStats: () => QueryCacheStats
+@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 getWasmModule: () => ESEngineModule | null
+@internal getWorldTick: () => number
+@internal getWorldVersion: () => number
+@internal hasCpp: boolean
+@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
+@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
+@internal isIterating: () => boolean
@internal markChanged: (entity: Entity, component: AnyComponentDef) => void
+@internal queries_: QueryCache
+@internal queryEntities: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]
+@internal resetIterationDepth: () => void
+@internal resetQueryCacheStats: () => void
+@internal resetQueryPool: () => void
@internal resolveGetter: (component: AnyComponentDef) => ((entity: Entity) => unknown) | null
@internal resolveHas: (component: AnyComponentDef) => ((entity: Entity) => boolean) | null
@internal resolveSetter: (component: AnyComponentDef) => ((entity: Entity, data: unknown) => void) | null
-advanceTick: () => void
-anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean
-applyEntityOrder: (entities: readonly Entity[]) => void
-beginIteration: () => void
-changes_: ChangeTracker
-cleanRemovedBuffer: (beforeTick: number) => void
despawn: (entity: Entity) => void
-enableChangeTracking: (component: AnyComponentDef) => void
-endIteration: () => void
entityCount: () => number
findEntityByName: (name: string) => Entity | null
get: <C extends AnyComponentDef>(entity: Entity, component: C) => ComponentData<C>
getAllEntities: () => Entity[]
getComponentTypes: (entity: Entity) => string[]
-getEntitiesWithComponents: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]
-getQueryCacheStats: () => QueryCacheStats
-getRemovedEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]
-getWorldTick: () => number
-getWorldVersion: () => number
+getEntitiesWithComponents: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[]) => readonly Entity[]
has: (entity: Entity, component: AnyComponentDef) => boolean
-hasCpp: boolean
insert: <C extends AnyComponentDef>(entity: Entity, component: C, data?: Partial<ComponentData<C>>) => ComponentData<C>
-isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
-isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
-isIterating: () => boolean
isStale: (entity: Entity) => boolean
onDespawn: (callback: (entity: Entity) => void) => () => void
onSpawn: (callback: (entity: Entity) => void) => () => void
-queries_: QueryCache
remove: (entity: Entity, component: AnyComponentDef) => void
removeParent: (entity: Entity) => void
-resetIterationDepth: () => void
-resetQueryCacheStats: () => void
-resetQueryPool: () => void
set: <C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentData<C>) => void
setParent: (child: Entity, parent: Entity) => void
spawn: (name?: string) => Entity
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index e52f86238..73203a790 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 71 public · 17 beta · 1425 experimental · 3 deprecated
+Symbols: 74 public · 17 beta · 1422 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1786,7 +1786,7 @@ resume: () => void
state: TweenState
```
-## ComponentData — type @experimental
+## ComponentData — type @public
```
C extends BuiltinComponentDef<infer T> ? T :
C extends ComponentDef<infer T> ? T :
@@ -3020,7 +3020,7 @@ static new (input: InputState): GestureDetector
static prototype: GestureDetector
```
-## GetWorld — function @experimental
+## GetWorld — function @public
```
(): GetWorldDescriptor
```
@@ -8322,52 +8322,53 @@ tabIndex: number | undefined
(component: AnyComponentDef): FilterExpr
```
-## World — class @experimental
+## World — class @public
```
+@internal advanceTick: () => void
+@internal anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean
+@internal applyEntityOrder: (entities: readonly Entity[]) => void
+@internal beginIteration: () => void
@internal builtin: BuiltinBridge
+@internal changes_: ChangeTracker
+@internal cleanRemovedBuffer: (beforeTick: number) => void
@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => void
@internal disconnectCpp: () => void
+@internal enableChangeTracking: (component: AnyComponentDef) => void
+@internal endIteration: () => void
@internal getCppRegistry: () => CppRegistry | null
+@internal getQueryCacheStats: () => QueryCacheStats
+@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 getWasmModule: () => ESEngineModule | null
+@internal getWorldTick: () => number
+@internal getWorldVersion: () => number
+@internal hasCpp: boolean
+@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
+@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
+@internal isIterating: () => boolean
@internal markChanged: (entity: Entity, component: AnyComponentDef) => void
+@internal queries_: QueryCache
+@internal queryEntities: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]
+@internal resetIterationDepth: () => void
+@internal resetQueryCacheStats: () => void
+@internal resetQueryPool: () => void
@internal resolveGetter: (component: AnyComponentDef) => ((entity: Entity) => unknown) | null
@internal resolveHas: (component: AnyComponentDef) => ((entity: Entity) => boolean) | null
@internal resolveSetter: (component: AnyComponentDef) => ((entity: Entity, data: unknown) => void) | null
-advanceTick: () => void
-anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean
-applyEntityOrder: (entities: readonly Entity[]) => void
-beginIteration: () => void
-changes_: ChangeTracker
-cleanRemovedBuffer: (beforeTick: number) => void
despawn: (entity: Entity) => void
-enableChangeTracking: (component: AnyComponentDef) => void
-endIteration: () => void
entityCount: () => number
findEntityByName: (name: string) => Entity | null
get: <C extends AnyComponentDef>(entity: Entity, component: C) => ComponentData<C>
getAllEntities: () => Entity[]
getComponentTypes: (entity: Entity) => string[]
-getEntitiesWithComponents: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]
-getQueryCacheStats: () => QueryCacheStats
-getRemovedEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]
-getWorldTick: () => number
-getWorldVersion: () => number
+getEntitiesWithComponents: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[]) => readonly Entity[]
has: (entity: Entity, component: AnyComponentDef) => boolean
-hasCpp: boolean
insert: <C extends AnyComponentDef>(entity: Entity, component: C, data?: Partial<ComponentData<C>>) => ComponentData<C>
-isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
-isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean
-isIterating: () => boolean
isStale: (entity: Entity) => boolean
onDespawn: (callback: (entity: Entity) => void) => () => void
onSpawn: (callback: (entity: Entity) => void) => () => void
-queries_: QueryCache
remove: (entity: Entity, component: AnyComponentDef) => void
removeParent: (entity: Entity) => void
-resetIterationDepth: () => void
-resetQueryCacheStats: () => void
-resetQueryPool: () => void
set: <C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentData<C>) => void
setParent: (child: Entity, parent: Entity) => void
spawn: (name?: string) => Entity
diff --git a/sdk/src/ecs/ScriptStorage.ts b/sdk/src/ecs/ScriptStorage.ts
index f85fec41a..16d523eb4 100644
--- a/sdk/src/ecs/ScriptStorage.ts
+++ b/sdk/src/ecs/ScriptStorage.ts
@@ -45,13 +45,22 @@ export class ScriptStorage {
const storage = this.getStorage(component);
const isNew = !storage.has(entity);
storage.set(entity, value);
+ this.note_(entity, component);
+ return { value, isNew };
+ }
+
+ /**
+ * Record that `entity` carries `component`. The index and the per-component
+ * maps are one membership fact, so every write that adds a component has to
+ * come through here or `getEntityComponentIds` starts answering a subset.
+ */
+ private note_(entity: Entity, component: ComponentDef<any>): void {
let ids = this.entityComponents_.get(entity);
if (!ids) {
ids = new Set();
this.entityComponents_.set(entity, ids);
}
ids.add(component._id);
- return { value, isNew };
}
get<T>(entity: Entity, component: ComponentDef<T>): T {
@@ -76,7 +85,13 @@ export class ScriptStorage {
}
}
- set(entity: Entity, component: ComponentDef<any>, data: unknown): void {
+ /**
+ * Store a whole value, answering whether the entity lacked the component —
+ * the caller owns the structural bookkeeping an addition needs. Invalid data
+ * warns rather than throwing as `insert` does: a scene load and the reconciler
+ * write through here, where one bad field must not take a frame down.
+ */
+ set(entity: Entity, component: ComponentDef<any>, data: unknown): { isNew: boolean } {
if (data !== null && data !== undefined && typeof data === 'object') {
const errors = validateComponentData(
component._name,
@@ -88,7 +103,11 @@ export class ScriptStorage {
log.warn('ecs', formatValidationErrors(component._name, errors));
}
}
- this.getStorage(component).set(entity, data);
+ const storage = this.getStorage(component);
+ const isNew = !storage.has(entity);
+ storage.set(entity, data);
+ this.note_(entity, component);
+ return { isNew };
}
getStorage(component: ComponentDef<any>): Map<Entity, unknown> {
diff --git a/sdk/src/ecs/component.ts b/sdk/src/ecs/component.ts
index 3fb648456..d6330f747 100644
--- a/sdk/src/ecs/component.ts
+++ b/sdk/src/ecs/component.ts
@@ -1124,6 +1124,13 @@ export type {
// Type Helpers
// =============================================================================
+/**
+ * The value shape a component definition holds — `ComponentData<typeof Transform>`
+ * is `TransformData`. This is what `world.get` answers and `world.set` takes, so a
+ * helper generic over a component writes its own signature with it.
+ *
+ * @public
+ */
export type ComponentData<C> =
C extends BuiltinComponentDef<infer T> ? T :
C extends ComponentDef<infer T> ? T :
diff --git a/sdk/src/ecs/query.ts b/sdk/src/ecs/query.ts
index c0054da13..9ca9c99cb 100644
--- a/sdk/src/ecs/query.ts
+++ b/sdk/src/ecs/query.ts
@@ -443,7 +443,7 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu
* so none of them can disagree about the cache key or the dep set.
*/
private candidates_(): readonly Entity[] {
- return this.world_.getEntitiesWithComponents(
+ return this.world_.queryEntities(
this.allRequired_,
this.descriptor_._with,
this.descriptor_._without,
diff --git a/sdk/src/ecs/system.ts b/sdk/src/ecs/system.ts
index 6233369a2..6ce9848ad 100644
--- a/sdk/src/ecs/system.ts
+++ b/sdk/src/ecs/system.ts
@@ -56,6 +56,13 @@ export interface GetWorldDescriptor {
readonly _type: 'get_world';
}
+/**
+ * Ask a system for the {@link World} itself. The escape hatch: it declares no
+ * access, so the scheduler cannot see what the system touches and the query cache
+ * cannot serve it. Reach for `Query`/`Res`/`Commands` first.
+ *
+ * @public
+ */
export function GetWorld(): GetWorldDescriptor {
return { _type: 'get_world' };
}
diff --git a/sdk/src/ecs/world.ts b/sdk/src/ecs/world.ts
index 6413eca69..6a183e35b 100644
--- a/sdk/src/ecs/world.ts
+++ b/sdk/src/ecs/world.ts
@@ -114,11 +114,22 @@ export interface QueryFilter {
// World
// =============================================================================
+/**
+ * The entity store, as `GetWorld()` hands it to a system — the escape hatch for
+ * work the declared parameters cannot express. Prefer `Query`/`Res`/`Commands`:
+ * those declare their access, so the scheduler can see it and the cache can serve
+ * them. The frozen surface here is what a game does with entities; what the frame
+ * runner, the query cache and the editor's projection need is `@internal`.
+ *
+ * @public
+ */
export class World {
private readonly builtin_ = new BuiltinBridge();
private readonly scripts_ = new ScriptStorage();
private readonly names_ = new NameIndex();
+ /** @internal */
readonly changes_ = new ChangeTracker();
+ /** @internal */
readonly queries_ = new QueryCache();
private entities_ = new Map<Entity, number>();
private indexGeneration_ = new Map<number, number>(); // index -> current generation (for isStale detection)
@@ -153,7 +164,7 @@ export class World {
this.builtin_.disconnect();
}
- /** Whether an engine core is bound — false in a pure-JS world. */
+ /** @internal Whether an engine core is bound — false in a pure-JS world. */
get hasCpp(): boolean {
return this.builtin_.hasCpp;
}
@@ -172,6 +183,10 @@ export class World {
// Entity Management
// =========================================================================
+ /**
+ * Create an entity with no components. Throws during query iteration —
+ * mutating the set a query is walking is what `Commands` exists to defer.
+ */
spawn(name?: string): Entity {
if (this.isIterating()) {
throw new Error(
@@ -225,6 +240,11 @@ export class World {
return entity;
}
+ /**
+ * Destroy `entity` and its whole subtree — children before parents, so none
+ * is left orphaned and still drawing. Already-gone entities are ignored, and
+ * as with {@link spawn} this throws during query iteration.
+ */
despawn(entity: Entity): void {
if (this.isIterating()) {
throw new Error(
@@ -300,6 +320,11 @@ export class World {
}
}
+ /**
+ * Run `callback` whenever an entity is created; the returned function
+ * unsubscribes. A throw is logged and swallowed, so one bad listener cannot
+ * stop the others or the spawn itself.
+ */
onSpawn(callback: (entity: Entity) => void): () => void {
this.spawnCallbacks_.push(callback);
return () => {
@@ -308,6 +333,11 @@ export class World {
};
}
+ /**
+ * Run `callback` whenever an entity is destroyed, once per entity in a
+ * subtree teardown; the returned function unsubscribes. This is the hook a
+ * per-entity side table is cleaned up from.
+ */
onDespawn(callback: (entity: Entity) => void): () => void {
this.despawnCallbacks_.push(callback);
return () => {
@@ -316,6 +346,8 @@ export class World {
};
}
+ /** Whether `entity` currently exists. False for one never spawned and for a
+ * despawned one alike — {@link isStale} tells the two apart. */
valid(entity: Entity): boolean {
return this.entities_.has(entity);
}
@@ -333,6 +365,7 @@ export class World {
return currentGen !== undefined && currentGen !== entityGeneration(entity);
}
+ /** How many entities exist. */
entityCount(): number {
return this.entities_.size;
}
@@ -366,24 +399,27 @@ export class World {
};
}
+ /** @internal Structural version the query cache invalidates against. */
getWorldVersion(): number {
return this.queries_.structuralVersion;
}
- /** Cumulative query-cache counters (hits, misses, invalidation causes). */
+ /** @internal Cumulative query-cache counters (hits, misses, invalidation causes). */
getQueryCacheStats(): QueryCacheStats {
return this.queries_.getStats();
}
- /** Reset the query-cache counters. Entries themselves are kept. */
+ /** @internal Reset the query-cache counters. Entries themselves are kept. */
resetQueryCacheStats(): void {
this.queries_.resetStats();
}
+ /** @internal Iteration depth is what makes spawn/despawn refuse mid-query. */
beginIteration(): void {
this.iterationDepth_++;
}
+ /** @internal */
endIteration(): void {
this.iterationDepth_--;
if (this.iterationDepth_ < 0) {
@@ -392,14 +428,18 @@ export class World {
}
}
+ /** @internal Depth is reset rather than unwound when a frame aborts. */
resetIterationDepth(): void {
this.iterationDepth_ = 0;
}
+ /** @internal */
isIterating(): boolean {
return this.iterationDepth_ > 0;
}
+ /** Every entity, in storage order — which is the order queries walk and,
+ * within a sorting layer, the order the renderer draws. A fresh array. */
getAllEntities(): Entity[] {
return Array.from(this.entities_.keys());
}
@@ -421,6 +461,7 @@ export class World {
*
* @param entities the desired iteration order (first iterates first, draws first)
*/
+ /** @internal */
applyEntityOrder(entities: readonly Entity[]): void {
if (entities.length === 0) return;
if (this.isIterating()) {
@@ -461,6 +502,11 @@ export class World {
}
}
+ /**
+ * Make `child` a child of `parent`. This is the side to write — the engine
+ * keeps {@link Parent} and {@link Children} in step from here, and a transform
+ * composes against whatever this names.
+ */
setParent(child: Entity, parent: Entity): void {
const cppRegistry = this.builtin_.getCppRegistry();
if (cppRegistry) {
@@ -476,6 +522,7 @@ export class World {
notifyBridge('onParentChanged', child, parent);
}
+ /** Detach `entity` from its parent, leaving its own children attached to it. */
removeParent(entity: Entity): void {
const cppRegistry = this.builtin_.getCppRegistry();
if (cppRegistry) {
@@ -495,6 +542,11 @@ export class World {
// Component Management
// =========================================================================
+ /**
+ * Add `component` to `entity`, with `data` merged over the component's
+ * defaults, and answer the stored value. Adding one that is already there
+ * replaces it.
+ */
insert<C extends AnyComponentDef>(entity: Entity, component: C, data?: Partial<ComponentData<C>>): ComponentData<C> {
if (isBuiltinComponent(component)) {
return this.insertBuiltin_(entity, component, data) as ComponentData<C>;
@@ -502,6 +554,10 @@ export class World {
return this.insertScript_(entity, component as ComponentDef<any>, data) as ComponentData<C>;
}
+ /**
+ * Store a whole component value and stamp the change tick a `Changed` filter
+ * reads. Insert-or-replace: an entity that lacks the component gets it.
+ */
set<C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentData<C>): void {
if (isBuiltinComponent(component)) {
// `set` is insert-or-replace: adding a builtin the entity LACKS must run
@@ -535,7 +591,16 @@ export class World {
notifyBridge('onComponentChanged', entity, component._name);
return;
}
- this.scripts_.set(entity, component as ComponentDef<any>, data);
+ // Insert-or-replace means the ADD case owes the same bookkeeping insert
+ // does, or a warmed query never learns the entity matched. The builtin
+ // branch above says so; this one did not.
+ const { isNew } = this.scripts_.set(entity, component as ComponentDef<any>, data);
+ if (isNew) {
+ this.queries_.markComponentDirty(component._id);
+ this.queries_.markStructuralChange();
+ this.changes_.recordAdded(component, entity);
+ notifyBridge('onComponentAdded', entity, component._name);
+ }
this.changes_.recordChanged(component, entity);
if ((component as ComponentDef<any>)._id === Name._id) {
this.names_.update(entity, (data as { value: string }).value);
@@ -543,6 +608,12 @@ export class World {
notifyBridge('onComponentChanged', entity, component._name);
}
+ /**
+ * The component's value. Asking for one the entity does not have is a
+ * programming error, not a case to handle — use {@link tryGet} where absence
+ * is expected. Engine-backed components answer a fresh object each call;
+ * writing to it does not store anything, {@link set} does.
+ */
get<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C> {
if (isBuiltinComponent(component)) {
return this.builtin_.get(entity, component) as ComponentData<C>;
@@ -550,6 +621,7 @@ export class World {
return this.scripts_.get(entity, component as ComponentDef<any>) as ComponentData<C>;
}
+ /** Whether `entity` carries `component`. */
has(entity: Entity, component: AnyComponentDef): boolean {
if (component._builtin) {
if (!this.builtin_.hasCpp) return false;
@@ -561,6 +633,7 @@ export class World {
return this.scripts_.has(entity, component as ComponentDef<any>);
}
+ /** {@link get}, answering null instead of throwing when the component is absent. */
tryGet<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C> | null {
if (isBuiltinComponent(component)) {
if (!this.builtin_.hasCpp) return null;
@@ -584,6 +657,8 @@ export class World {
return val !== undefined ? val as ComponentData<C> : null;
}
+ /** Take `component` off `entity`. Throws during query iteration, as
+ * {@link spawn} does. */
remove(entity: Entity, component: AnyComponentDef): void {
if (this.isIterating()) {
throw new Error(
@@ -655,6 +730,8 @@ export class World {
// Name Index
// =========================================================================
+ /** The entity with this {@link Name}, or null. Names are not identities —
+ * with two matches, which one comes back is not defined. */
findEntityByName(name: string): Entity | null {
return this.names_.findByName(name);
}
@@ -719,10 +796,13 @@ export class World {
// Query Support
// =========================================================================
+ /** @internal Per-frame reuse of the query instance pool. */
resetQueryPool(): void {
// No-op: query pool removed, results stored directly in cache
}
+ /** The names of every component on `entity` — for inspectors and diagnostics;
+ * a system asks {@link has} about the definitions it knows. */
getComponentTypes(entity: Entity): string[] {
const types = new Set<string>();
for (const [name, methods] of this.builtin_.getMethodCache()) {
@@ -783,10 +863,32 @@ export class World {
return ids;
}
+ /**
+ * Entities carrying every component in `components`, narrowed by `with` and
+ * `without`. Answered from the query cache, so calling it every frame is the
+ * intended use; the array is the cache's own and must not be mutated.
+ *
+ * @public
+ */
getEntitiesWithComponents(
components: AnyComponentDef[],
withFilters: AnyComponentDef[] = [],
withoutFilters: AnyComponentDef[] = [],
+ ): readonly Entity[] {
+ return this.queryEntities(components, withFilters, withoutFilters);
+ }
+
+ /**
+ * @internal The same walk, with the cache key, dependency ids and predicate
+ * filter supplied by the caller. `QueryInstance` computes those once per
+ * query so a cache hit allocates nothing — which is why they are not
+ * parameters of the frozen door above: they are the cache's shape, and
+ * freezing them would freeze it.
+ */
+ queryEntities(
+ components: AnyComponentDef[],
+ withFilters: AnyComponentDef[] = [],
+ withoutFilters: AnyComponentDef[] = [],
precomputedKey?: string,
filter?: QueryFilter,
precomputedDepIds?: symbol[],
@@ -907,35 +1009,43 @@ export class World {
// Change Detection (delegates to ChangeTracker)
// =========================================================================
+ /** @internal The frame runner's clock for change detection. */
advanceTick(): void {
this.changes_.advanceTick();
}
+ /** @internal */
getWorldTick(): number {
return this.changes_.getWorldTick();
}
+ /** @internal Opted into by a query that declares an Added/Changed filter;
+ * tracking every component would cost every write. */
enableChangeTracking(component: AnyComponentDef): void {
this.changes_.enableChangeTracking(component);
}
+ /** @internal What `Added`/`Changed` filters are implemented in terms of. */
isAddedSince(entity: Entity, component: AnyComponentDef, sinceTick: number): boolean {
return this.changes_.isAddedSince(entity, component, sinceTick);
}
+ /** @internal */
isChangedSince(entity: Entity, component: AnyComponentDef, sinceTick: number): boolean {
return this.changes_.isChangedSince(entity, component, sinceTick);
}
- /** True if ANY entity changed `component` after `sinceTick` (O(1) gate). */
+ /** @internal True if ANY entity changed `component` after `sinceTick` (O(1) gate). */
anyChangedSince(component: AnyComponentDef, sinceTick: number): boolean {
return this.changes_.anyChangedSince(component, sinceTick);
}
+ /** @internal What a `Removed` query reads. */
getRemovedEntitiesSince(component: AnyComponentDef, sinceTick: number): Entity[] {
return this.changes_.getRemovedEntitiesSince(component, sinceTick);
}
+ /** @internal */
cleanRemovedBuffer(beforeTick: number): void {
this.changes_.cleanRemovedBuffer(beforeTick);
}
diff --git a/sdk/tests/async-system.test.ts b/sdk/tests/async-system.test.ts
index aaa8ce965..e9cdaf63a 100644
--- a/sdk/tests/async-system.test.ts
+++ b/sdk/tests/async-system.test.ts
@@ -30,6 +30,8 @@ function createMockWorld() {
set: vi.fn(),
valid: vi.fn((e: Entity) => entities.has(e)),
getEntitiesWithComponents: vi.fn(() => [] as Entity[]),
+ // What QueryInstance actually calls: the precomputed-key path.
+ queryEntities: vi.fn(() => [] as Entity[]),
beginIteration: vi.fn(),
endIteration: vi.fn(),
resetIterationDepth: vi.fn(),
diff --git a/sdk/tests/ecs-vocabulary.test.ts b/sdk/tests/ecs-vocabulary.test.ts
index 707da14df..f3df14968 100644
--- a/sdk/tests/ecs-vocabulary.test.ts
+++ b/sdk/tests/ecs-vocabulary.test.ts
@@ -21,7 +21,7 @@ import type {
FilterExpr, RemovedQueryDescriptor,
ResourceDef, ResDescriptor, ResMutDescriptor, CommandsDescriptor, QueryArg,
EventDef, EventReaderDescriptor, EventWriterDescriptor, GetWorldDescriptor,
- SystemDef, SystemOptions, SystemParam, InferParam, InferParams,
+ SystemDef, SystemOptions, SystemParam, InferParam, InferParams, ComponentData,
Entity, QueryResult, ChildrenData, ParentData, NameData, TransformData,
Vec2, Vec3, Vec4, Quat, Color,
} from '../src/core';
@@ -194,6 +194,134 @@ describe('resource vocabulary', () => {
});
});
+describe('world vocabulary', () => {
+ it('spawn, valid and despawn are the entity lifecycle', () => {
+ const world = new World();
+ const e = world.spawn('vocab-entity');
+ expect(world.valid(e)).toBe(true);
+ expect(world.entityCount()).toBe(1);
+ world.despawn(e);
+ expect(world.valid(e)).toBe(false);
+ expect(world.entityCount()).toBe(0);
+ });
+
+ it('isStale answers about the slot, not the entity', () => {
+ // Both are invalid; isStale is the one that says WHY. It reports on the
+ // index, and a pure-JS world never reuses one — the recycled case needs an
+ // engine core, so what is pinned here is that neither false is a throw.
+ const world = new World();
+ const e = world.spawn();
+ world.despawn(e);
+ expect(world.valid(e)).toBe(false);
+ expect(world.isStale(e)).toBe(false);
+ expect(world.isStale(9999 as typeof e)).toBe(false);
+ });
+
+ it('insert merges over the component defaults, and get answers the stored value', () => {
+ const world = new World();
+ const e = world.spawn();
+ const data: ComponentData<typeof Position> = world.insert(e, Position, { x: 5 });
+ expect(data).toEqual({ x: 5, y: 0 });
+ expect(world.get(e, Position)).toEqual({ x: 5, y: 0 });
+ expect(world.has(e, Position)).toBe(true);
+ });
+
+ it('tryGet answers null where get is a programming error', () => {
+ const world = new World();
+ const e = world.spawn();
+ expect(world.tryGet(e, Position)).toBeNull();
+ world.insert(e, Position);
+ expect(world.tryGet(e, Position)).toEqual({ x: 0, y: 0 });
+ });
+
+ it('set is insert-or-replace and remove takes it off again', () => {
+ const world = new World();
+ const e = world.spawn();
+ world.set(e, Position, { x: 1, y: 2 });
+ expect(world.has(e, Position)).toBe(true);
+ expect(world.get(e, Position)).toEqual({ x: 1, y: 2 });
+ world.remove(e, Position);
+ expect(world.has(e, Position)).toBe(false);
+ });
+
+ it('set on a component the entity lacked reaches a query that already ran', () => {
+ // "Insert-or-replace" is the whole claim: an add through set owes the same
+ // structural bookkeeping insert does, or a warmed cache answers the old set
+ // forever. It did not, until freezing the method made the claim explicit.
+ const world = new World();
+ const e = world.spawn();
+ expect(world.getEntitiesWithComponents([Position])).toEqual([]);
+ world.set(e, Position, { x: 1, y: 2 });
+ expect(world.getEntitiesWithComponents([Position])).toEqual([e]);
+ });
+
+ it('getComponentTypes lists a component however it was added', () => {
+ // Defined here rather than at module scope: the name lookup reads the
+ // context's registry, which the suite's setup resets.
+ const Local = defineComponent('VocabLocal', { v: 0 });
+ const world = new World();
+ const viaSet = world.spawn();
+ const viaInsert = world.spawn();
+ world.set(viaSet, Local, { v: 1 });
+ world.insert(viaInsert, Local, { v: 2 });
+ expect(world.getComponentTypes(viaSet)).toContain('VocabLocal');
+ expect(world.getComponentTypes(viaInsert)).toContain('VocabLocal');
+ });
+
+ it('getEntitiesWithComponents narrows by with and without', () => {
+ const world = new World();
+ const both = world.spawn();
+ world.insert(both, Position);
+ world.insert(both, Health);
+ const positionOnly = world.spawn();
+ world.insert(positionOnly, Position);
+
+ expect([...world.getEntitiesWithComponents([Position])].sort()).toEqual([both, positionOnly].sort());
+ expect(world.getEntitiesWithComponents([Position], [Health])).toEqual([both]);
+ expect(world.getEntitiesWithComponents([Position], [], [Health])).toEqual([positionOnly]);
+ });
+
+ it('findEntityByName reads the name spawn was given', () => {
+ const world = new World();
+ const e = world.spawn('vocab-findable');
+ expect(world.findEntityByName('vocab-findable')).toBe(e);
+ expect(world.findEntityByName('nobody')).toBeNull();
+ });
+
+ it('onSpawn and onDespawn fire until their unsubscribe is called', () => {
+ const world = new World();
+ const spawned: number[] = [];
+ const despawned: number[] = [];
+ const offSpawn = world.onSpawn((e) => spawned.push(e));
+ const offDespawn = world.onDespawn((e) => despawned.push(e));
+
+ const first = world.spawn();
+ world.despawn(first);
+ offSpawn();
+ offDespawn();
+ world.despawn(world.spawn());
+
+ expect(spawned).toEqual([first]);
+ expect(despawned).toEqual([first]);
+ });
+
+ it('mutating an entity while a query iterates is refused, not tolerated', () => {
+ // The contract Commands exists to satisfy — asserted because a throw is
+ // the promise, and silently corrupting the walk would also "work".
+ const world = new World();
+ const e = world.spawn();
+ world.insert(e, Position);
+ world.beginIteration();
+ try {
+ expect(() => world.spawn()).toThrow(/Commands/);
+ expect(() => world.despawn(e)).toThrow(/Commands/);
+ expect(() => world.remove(e, Position)).toThrow(/Commands/);
+ } finally {
+ world.endIteration();
+ }
+ });
+});
+
describe('event vocabulary', () => {
it('defineEvent answers an EventDef both descriptors are built over', () => {
const Hit: EventDef<{ damage: number }> = defineEvent('VocabHit');
diff --git a/sdk/tests/system.test.ts b/sdk/tests/system.test.ts
index e506d2e36..d89b00e60 100644
--- a/sdk/tests/system.test.ts
+++ b/sdk/tests/system.test.ts
@@ -52,6 +52,8 @@ function createMockWorld() {
set: vi.fn(),
valid: vi.fn((e: Entity) => entities.has(e)),
getEntitiesWithComponents: vi.fn(() => [] as Entity[]),
+ // What QueryInstance actually calls: the precomputed-key path.
+ queryEntities: vi.fn(() => [] as Entity[]),
beginIteration: vi.fn(),
endIteration: vi.fn(),
resetIterationDepth: vi.fn(),
diff --git a/tools/check-tier-leaks.mjs b/tools/check-tier-leaks.mjs
index 7ce411a8e..d8152aa8a 100644
--- a/tools/check-tier-leaks.mjs
+++ b/tools/check-tier-leaks.mjs
@@ -9,10 +9,11 @@
* 1.0 and the type it hands you does not. So a frozen symbol may only name
* frozen types.
*
- * Wave 1 froze six symbols whose signatures are spelled in a vocabulary nobody
- * has frozen yet, so this starts as a ratchet rather than a wall: the leaks that
- * exist are named in {@link ACCEPTED} and a new one fails. Each line deleted
- * from that list is a promise that got real.
+ * It began as a ratchet — the leaks that existed were named in {@link ACCEPTED}
+ * and a new one failed — because Wave 1 froze six symbols spelled in a vocabulary
+ * nobody had frozen yet. That list is now empty, so this is a wall: every frozen
+ * signature names only frozen types, and any new leak has to be answered rather
+ * than recorded.
*
* node tools/check-tier-leaks.mjs exit 1 on an undeclared leak
* node tools/check-tier-leaks.mjs --report print what freezing would cost
@@ -23,20 +24,11 @@ import { ETC, ENTRIES } from './lib/sdkProgram.mjs';
import { parseSnapshot } from './lib/apiSnapshot.mjs';
/**
- * Frozen symbols known to name unfrozen types, and what is still missing. Every
- * one is the ECS vocabulary the six Wave 1 symbols are written in — descriptors,
- * defs and the parameter union — none of which has been through the freeze bar.
+ * Frozen symbols known to name unfrozen types, and what is still missing. Empty
+ * is the goal state, not an oversight: the ECS vocabulary the frozen calls are
+ * spelled in has all been through the freeze bar, World included.
*/
-// World carries the host's binding seam (connectCpp, getCppRegistry), so
-// freezing it would freeze that too, and 0.50 deliberately does not.
-const WORLD = 'names World, which is not frozen while it carries the host binding seam';
-
-export const ACCEPTED = {
- CommandsInstance: WORLD,
- InferParam: WORLD,
- QueryInstance: WORLD,
- RemovedQueryInstance: WORLD,
-};
+export const ACCEPTED = {};
/** Every symbol across every entry, keeping the strongest tier any entry gives it. */
function surface() {
@@ -57,13 +49,22 @@ function surface() {
const api = surface();
+/**
+ * A member's own name, which is not a type reference. World declares
+ * `findEntityByName` and so does scene.ts, and without this the class read as
+ * leaking a reference to the free function that merely shares its name.
+ */
+const MEMBER_NAME = /^(?:static\s+|readonly\s+)*[A-Za-z_$][\w$]*\??\s*:/;
+
/**
* Exported symbols a body names. A type not in the surface is a built-in or
* private; an `@internal` member carries no promise, so what it names does not
* constrain the promise its type makes.
*/
function referenced(name) {
- const lines = (api.get(name)?.body ?? '').split('\n').filter((l) => !l.startsWith('@internal '));
+ const lines = (api.get(name)?.body ?? '').split('\n')
+ .filter((l) => !l.startsWith('@internal '))
+ .map((l) => l.replace(MEMBER_NAME, ''));
const out = new Set();
for (const id of lines.join('\n').match(/[A-Za-z_$][\w$]*/g) ?? []) {
if (id !== name && api.has(id)) out.add(id);