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
feat(ecs): a step can be asked whether it is a function of the world
esenginec001b10c7019
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 98b4e07db..0728c8e8a 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 114,"beta": 101,- "experimental": 1838,+ "experimental": 1840,"deprecated": 3},- "total": 2053,+ "total": 2055,"subsystems": [{"id": "ecs",diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex d84d3aee2..54d22ee5c 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: 114 public · 94 beta · 1677 experimental · 3 deprecated+Symbols: 114 public · 94 beta · 1679 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -2271,6 +2271,7 @@ keyof ThemeColors## CommandsInstance — class @public```+@internal describe: () => string@internal spawnImmediate: (components: SpawnComponentEntry[], entityRef: { entity: Entity; }, name?: string, parent?: Entity | null) => voiddespawn: (entity: Entity) => CommandsInstanceentity: (entity: Entity) => EntityCommands@@ -3213,6 +3214,7 @@ iconHalf: number | ((at: Vec3) => number) | undefined## EntityCommands — class @public```+@internal describe: () => stringchildOf: (parent: Entity) => EntityCommandsfinalize: () => voidid: () => Entity@@ -3330,6 +3332,7 @@ static prototype: EventReaderInstance<any>```@internal rewindWrites: (marks: Map<symbol, number>) => void@internal writeMarks: () => Map<symbol, number>+@internal writtenSince: (marks: Map<symbol, number>) => stringbusNamed: (name: string) => EventBus<unknown> | undefinedgetBus: <T>(event: EventDef<T>) => EventBus<T>register: <T>(event: EventDef<T>) => void@@ -6997,6 +7000,12 @@ UIElement = 7{ init(width: number, height: number): void; resize(width: number, height: number): void; beginFrame(elapsedSec?: number): void; updateTransforms(registry: { _cpp: CppRegistry; }): void; begin(viewProjection: Float32Array, target?: RenderTargetHandle, clearFlags?: number, clearColor?: { x: number; y: number; z: number; w: number; }, clearRect?: { x: number; y: number; w: number; h: number; }): void; flush(): void; end(): void; endFrame(): void; hasScreenOverlay(): boolean; beginScreenOverlay(projection: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): void; submitScreenOverlay(registry: { _cpp: CppRegistry; }): void; endScreenOverlay(target?: RenderTargetHandle): void; submitAll(registry: { _cpp: CppRegistry; }, vpX: number, vpY: number, vpW: number, vpH: number): void; setStage(stage: RenderStage): void; createRenderTarget(width: number, height: number, flags?: number): RenderTargetHandle; releaseRenderTarget(handle: RenderTargetHandle): void; getTargetTexture(handle: RenderTargetHandle): number; getTargetDepthTexture(handle: RenderTargetHandle): number; setClearColor(r: number, g: number, b: number, a: number): void; setViewport(x: number, y: number, w: number, h: number): void; setYSortLayers(mask: number): void; setDepthLayers(mask: number): void; setCullingMask(mask: number): void; setViewId(view: number): void; lodInspect(view: number, entity: number): LodDecision | null; setLodPreview(view: number, entity: number, level: number | null): void; lightStatus(entity: number): LightStatus | null; shadowStatus(entity: number): ShadowStatus | null; setTextureParams(textureId: number, minFilter: number, magFilter: number, wrapS: number, wrapT: number): void; measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): { width: number; height: number; }; getStats(): RenderStats; captureNextFrame(): void; getCapturedData(): FrameCaptureData | null; hasCapturedData(): boolean; replayToDrawCall(drawCallIndex: number): void; getSnapshotImageData(): Promise<ImageData | null>; }```+## ReplayReport — interface @experimental+```+stable: boolean+why: string+```+## Replicated — const @experimental```ComponentDef<ReplicatedData>@@ -8046,6 +8055,7 @@ ResourceDef<SpeculationInstance>## SpeculationInstance — class @experimental```+replay: (body: (commands: CommandsInstance) => SpeculationOutcome) => ReplayReportrun: (body: (commands: CommandsInstance) => SpeculationOutcome) => SpeculationOutcomestatic new (world: World, resources: ResourceStorage, events: EventRegistry | null): SpeculationInstancestatic prototype: SpeculationInstance@@ -12999,6 +13009,11 @@ PrefabsPlugin(def: BtDefinition, id: string, newParentId: string): BtDefinition```+## replay — function @experimental+```+(scope: SpeculationScope, body: (commands: CommandsInstance) => SpeculationOutcome): ReplayReport+```+## replicationPlugin — const @experimental```ReplicationPlugindiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex c8779168d..4a9a8049a 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: 114 public · 99 beta · 1696 experimental · 3 deprecated+Symbols: 114 public · 99 beta · 1698 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -2271,6 +2271,7 @@ keyof ThemeColors## CommandsInstance — class @public```+@internal describe: () => string@internal spawnImmediate: (components: SpawnComponentEntry[], entityRef: { entity: Entity; }, name?: string, parent?: Entity | null) => voiddespawn: (entity: Entity) => CommandsInstanceentity: (entity: Entity) => EntityCommands@@ -3221,6 +3222,7 @@ iconHalf: number | ((at: Vec3) => number) | undefined## EntityCommands — class @public```+@internal describe: () => stringchildOf: (parent: Entity) => EntityCommandsfinalize: () => voidid: () => Entity@@ -3338,6 +3340,7 @@ static prototype: EventReaderInstance<any>```@internal rewindWrites: (marks: Map<symbol, number>) => void@internal writeMarks: () => Map<symbol, number>+@internal writtenSince: (marks: Map<symbol, number>) => stringbusNamed: (name: string) => EventBus<unknown> | undefinedgetBus: <T>(event: EventDef<T>) => EventBus<T>register: <T>(event: EventDef<T>) => void@@ -7190,6 +7193,12 @@ UIElement = 7{ init(width: number, height: number): void; resize(width: number, height: number): void; beginFrame(elapsedSec?: number): void; updateTransforms(registry: { _cpp: CppRegistry; }): void; begin(viewProjection: Float32Array, target?: RenderTargetHandle, clearFlags?: number, clearColor?: { x: number; y: number; z: number; w: number; }, clearRect?: { x: number; y: number; w: number; h: number; }): void; flush(): void; end(): void; endFrame(): void; hasScreenOverlay(): boolean; beginScreenOverlay(projection: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): void; submitScreenOverlay(registry: { _cpp: CppRegistry; }): void; endScreenOverlay(target?: RenderTargetHandle): void; submitAll(registry: { _cpp: CppRegistry; }, vpX: number, vpY: number, vpW: number, vpH: number): void; setStage(stage: RenderStage): void; createRenderTarget(width: number, height: number, flags?: number): RenderTargetHandle; releaseRenderTarget(handle: RenderTargetHandle): void; getTargetTexture(handle: RenderTargetHandle): number; getTargetDepthTexture(handle: RenderTargetHandle): number; setClearColor(r: number, g: number, b: number, a: number): void; setViewport(x: number, y: number, w: number, h: number): void; setYSortLayers(mask: number): void; setDepthLayers(mask: number): void; setCullingMask(mask: number): void; setViewId(view: number): void; lodInspect(view: number, entity: number): LodDecision | null; setLodPreview(view: number, entity: number, level: number | null): void; lightStatus(entity: number): LightStatus | null; shadowStatus(entity: number): ShadowStatus | null; setTextureParams(textureId: number, minFilter: number, magFilter: number, wrapS: number, wrapT: number): void; measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): { width: number; height: number; }; getStats(): RenderStats; captureNextFrame(): void; getCapturedData(): FrameCaptureData | null; hasCapturedData(): boolean; replayToDrawCall(drawCallIndex: number): void; getSnapshotImageData(): Promise<ImageData | null>; }```+## ReplayReport — interface @experimental+```+stable: boolean+why: string+```+## Replicated — const @experimental```ComponentDef<ReplicatedData>@@ -8239,6 +8248,7 @@ ResourceDef<SpeculationInstance>## SpeculationInstance — class @experimental```+replay: (body: (commands: CommandsInstance) => SpeculationOutcome) => ReplayReportrun: (body: (commands: CommandsInstance) => SpeculationOutcome) => SpeculationOutcomestatic new (world: World, resources: ResourceStorage, events: EventRegistry | null): SpeculationInstancestatic prototype: SpeculationInstance@@ -13242,6 +13252,11 @@ PrefabsPlugin(def: BtDefinition, id: string, newParentId: string): BtDefinition```+## replay — function @experimental+```+(scope: SpeculationScope, body: (commands: CommandsInstance) => SpeculationOutcome): ReplayReport+```+## replicationPlugin — const @experimental```ReplicationPlugindiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 7de099af7..155c9f158 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: 114 public · 96 beta · 1676 experimental · 3 deprecated+Symbols: 114 public · 96 beta · 1678 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -2266,6 +2266,7 @@ keyof ThemeColors## CommandsInstance — class @public```+@internal describe: () => string@internal spawnImmediate: (components: SpawnComponentEntry[], entityRef: { entity: Entity; }, name?: string, parent?: Entity | null) => voiddespawn: (entity: Entity) => CommandsInstanceentity: (entity: Entity) => EntityCommands@@ -3208,6 +3209,7 @@ iconHalf: number | ((at: Vec3) => number) | undefined## EntityCommands — class @public```+@internal describe: () => stringchildOf: (parent: Entity) => EntityCommandsfinalize: () => voidid: () => Entity@@ -3325,6 +3327,7 @@ static prototype: EventReaderInstance<any>```@internal rewindWrites: (marks: Map<symbol, number>) => void@internal writeMarks: () => Map<symbol, number>+@internal writtenSince: (marks: Map<symbol, number>) => stringbusNamed: (name: string) => EventBus<unknown> | undefinedgetBus: <T>(event: EventDef<T>) => EventBus<T>register: <T>(event: EventDef<T>) => void@@ -6992,6 +6995,12 @@ UIElement = 7{ init(width: number, height: number): void; resize(width: number, height: number): void; beginFrame(elapsedSec?: number): void; updateTransforms(registry: { _cpp: CppRegistry; }): void; begin(viewProjection: Float32Array, target?: RenderTargetHandle, clearFlags?: number, clearColor?: { x: number; y: number; z: number; w: number; }, clearRect?: { x: number; y: number; w: number; h: number; }): void; flush(): void; end(): void; endFrame(): void; hasScreenOverlay(): boolean; beginScreenOverlay(projection: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): void; submitScreenOverlay(registry: { _cpp: CppRegistry; }): void; endScreenOverlay(target?: RenderTargetHandle): void; submitAll(registry: { _cpp: CppRegistry; }, vpX: number, vpY: number, vpW: number, vpH: number): void; setStage(stage: RenderStage): void; createRenderTarget(width: number, height: number, flags?: number): RenderTargetHandle; releaseRenderTarget(handle: RenderTargetHandle): void; getTargetTexture(handle: RenderTargetHandle): number; getTargetDepthTexture(handle: RenderTargetHandle): number; setClearColor(r: number, g: number, b: number, a: number): void; setViewport(x: number, y: number, w: number, h: number): void; setYSortLayers(mask: number): void; setDepthLayers(mask: number): void; setCullingMask(mask: number): void; setViewId(view: number): void; lodInspect(view: number, entity: number): LodDecision | null; setLodPreview(view: number, entity: number, level: number | null): void; lightStatus(entity: number): LightStatus | null; shadowStatus(entity: number): ShadowStatus | null; setTextureParams(textureId: number, minFilter: number, magFilter: number, wrapS: number, wrapT: number): void; measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): { width: number; height: number; }; getStats(): RenderStats; captureNextFrame(): void; getCapturedData(): FrameCaptureData | null; hasCapturedData(): boolean; replayToDrawCall(drawCallIndex: number): void; getSnapshotImageData(): Promise<ImageData | null>; }```+## ReplayReport — interface @experimental+```+stable: boolean+why: string+```+## Replicated — const @experimental```ComponentDef<ReplicatedData>@@ -8041,6 +8050,7 @@ ResourceDef<SpeculationInstance>## SpeculationInstance — class @experimental```+replay: (body: (commands: CommandsInstance) => SpeculationOutcome) => ReplayReportrun: (body: (commands: CommandsInstance) => SpeculationOutcome) => SpeculationOutcomestatic new (world: World, resources: ResourceStorage, events: EventRegistry | null): SpeculationInstancestatic prototype: SpeculationInstance@@ -13004,6 +13014,11 @@ PrefabsPlugin(def: BtDefinition, id: string, newParentId: string): BtDefinition```+## replay — function @experimental+```+(scope: SpeculationScope, body: (commands: CommandsInstance) => SpeculationOutcome): ReplayReport+```+## replicationPlugin — const @experimental```ReplicationPlugindiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 5e416a0cf..5c5726e77 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: 114 public · 94 beta · 1698 experimental · 3 deprecated+Symbols: 114 public · 94 beta · 1700 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -2266,6 +2266,7 @@ keyof ThemeColors## CommandsInstance — class @public```+@internal describe: () => string@internal spawnImmediate: (components: SpawnComponentEntry[], entityRef: { entity: Entity; }, name?: string, parent?: Entity | null) => voiddespawn: (entity: Entity) => CommandsInstanceentity: (entity: Entity) => EntityCommands@@ -3208,6 +3209,7 @@ iconHalf: number | ((at: Vec3) => number) | undefined## EntityCommands — class @public```+@internal describe: () => stringchildOf: (parent: Entity) => EntityCommandsfinalize: () => voidid: () => Entity@@ -3325,6 +3327,7 @@ static prototype: EventReaderInstance<any>```@internal rewindWrites: (marks: Map<symbol, number>) => void@internal writeMarks: () => Map<symbol, number>+@internal writtenSince: (marks: Map<symbol, number>) => stringbusNamed: (name: string) => EventBus<unknown> | undefinedgetBus: <T>(event: EventDef<T>) => EventBus<T>register: <T>(event: EventDef<T>) => void@@ -7240,6 +7243,12 @@ UIElement = 7{ init(width: number, height: number): void; resize(width: number, height: number): void; beginFrame(elapsedSec?: number): void; updateTransforms(registry: { _cpp: CppRegistry; }): void; begin(viewProjection: Float32Array, target?: RenderTargetHandle, clearFlags?: number, clearColor?: { x: number; y: number; z: number; w: number; }, clearRect?: { x: number; y: number; w: number; h: number; }): void; flush(): void; end(): void; endFrame(): void; hasScreenOverlay(): boolean; beginScreenOverlay(projection: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): void; submitScreenOverlay(registry: { _cpp: CppRegistry; }): void; endScreenOverlay(target?: RenderTargetHandle): void; submitAll(registry: { _cpp: CppRegistry; }, vpX: number, vpY: number, vpW: number, vpH: number): void; setStage(stage: RenderStage): void; createRenderTarget(width: number, height: number, flags?: number): RenderTargetHandle; releaseRenderTarget(handle: RenderTargetHandle): void; getTargetTexture(handle: RenderTargetHandle): number; getTargetDepthTexture(handle: RenderTargetHandle): number; setClearColor(r: number, g: number, b: number, a: number): void; setViewport(x: number, y: number, w: number, h: number): void; setYSortLayers(mask: number): void; setDepthLayers(mask: number): void; setCullingMask(mask: number): void; setViewId(view: number): void; lodInspect(view: number, entity: number): LodDecision | null; setLodPreview(view: number, entity: number, level: number | null): void; lightStatus(entity: number): LightStatus | null; shadowStatus(entity: number): ShadowStatus | null; setTextureParams(textureId: number, minFilter: number, magFilter: number, wrapS: number, wrapT: number): void; measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): { width: number; height: number; }; getStats(): RenderStats; captureNextFrame(): void; getCapturedData(): FrameCaptureData | null; hasCapturedData(): boolean; replayToDrawCall(drawCallIndex: number): void; getSnapshotImageData(): Promise<ImageData | null>; }```+## ReplayReport — interface @experimental+```+stable: boolean+why: string+```+## Replicated — const @experimental```ComponentDef<ReplicatedData>@@ -8289,6 +8298,7 @@ ResourceDef<SpeculationInstance>## SpeculationInstance — class @experimental```+replay: (body: (commands: CommandsInstance) => SpeculationOutcome) => ReplayReportrun: (body: (commands: CommandsInstance) => SpeculationOutcome) => SpeculationOutcomestatic new (world: World, resources: ResourceStorage, events: EventRegistry | null): SpeculationInstancestatic prototype: SpeculationInstance@@ -13263,6 +13273,11 @@ PrefabsPlugin(def: BtDefinition, id: string, newParentId: string): BtDefinition```+## replay — function @experimental+```+(scope: SpeculationScope, body: (commands: CommandsInstance) => SpeculationOutcome): ReplayReport+```+## replicationPlugin — const @experimental```ReplicationPlugindiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex ad564150f..7cd253edb 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: 114 public · 94 beta · 1688 experimental · 3 deprecated+Symbols: 114 public · 94 beta · 1690 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -2266,6 +2266,7 @@ keyof ThemeColors## CommandsInstance — class @public```+@internal describe: () => string@internal spawnImmediate: (components: SpawnComponentEntry[], entityRef: { entity: Entity; }, name?: string, parent?: Entity | null) => voiddespawn: (entity: Entity) => CommandsInstanceentity: (entity: Entity) => EntityCommands@@ -3208,6 +3209,7 @@ iconHalf: number | ((at: Vec3) => number) | undefined## EntityCommands — class @public```+@internal describe: () => stringchildOf: (parent: Entity) => EntityCommandsfinalize: () => voidid: () => Entity@@ -3325,6 +3327,7 @@ static prototype: EventReaderInstance<any>```@internal rewindWrites: (marks: Map<symbol, number>) => void@internal writeMarks: () => Map<symbol, number>+@internal writtenSince: (marks: Map<symbol, number>) => stringbusNamed: (name: string) => EventBus<unknown> | undefinedgetBus: <T>(event: EventDef<T>) => EventBus<T>register: <T>(event: EventDef<T>) => void@@ -6999,6 +7002,12 @@ UIElement = 7{ init(width: number, height: number): void; resize(width: number, height: number): void; beginFrame(elapsedSec?: number): void; updateTransforms(registry: { _cpp: CppRegistry; }): void; begin(viewProjection: Float32Array, target?: RenderTargetHandle, clearFlags?: number, clearColor?: { x: number; y: number; z: number; w: number; }, clearRect?: { x: number; y: number; w: number; h: number; }): void; flush(): void; end(): void; endFrame(): void; hasScreenOverlay(): boolean; beginScreenOverlay(projection: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number): void; submitScreenOverlay(registry: { _cpp: CppRegistry; }): void; endScreenOverlay(target?: RenderTargetHandle): void; submitAll(registry: { _cpp: CppRegistry; }, vpX: number, vpY: number, vpW: number, vpH: number): void; setStage(stage: RenderStage): void; createRenderTarget(width: number, height: number, flags?: number): RenderTargetHandle; releaseRenderTarget(handle: RenderTargetHandle): void; getTargetTexture(handle: RenderTargetHandle): number; getTargetDepthTexture(handle: RenderTargetHandle): number; setClearColor(r: number, g: number, b: number, a: number): void; setViewport(x: number, y: number, w: number, h: number): void; setYSortLayers(mask: number): void; setDepthLayers(mask: number): void; setCullingMask(mask: number): void; setViewId(view: number): void; lodInspect(view: number, entity: number): LodDecision | null; setLodPreview(view: number, entity: number, level: number | null): void; lightStatus(entity: number): LightStatus | null; shadowStatus(entity: number): ShadowStatus | null; setTextureParams(textureId: number, minFilter: number, magFilter: number, wrapS: number, wrapT: number): void; measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): { width: number; height: number; }; getStats(): RenderStats; captureNextFrame(): void; getCapturedData(): FrameCaptureData | null; hasCapturedData(): boolean; replayToDrawCall(drawCallIndex: number): void; getSnapshotImageData(): Promise<ImageData | null>; }```+## ReplayReport — interface @experimental+```+stable: boolean+why: string+```+## Replicated — const @experimental```ComponentDef<ReplicatedData>@@ -8048,6 +8057,7 @@ ResourceDef<SpeculationInstance>## SpeculationInstance — class @experimental```+replay: (body: (commands: CommandsInstance) => SpeculationOutcome) => ReplayReportrun: (body: (commands: CommandsInstance) => SpeculationOutcome) => SpeculationOutcomestatic new (world: World, resources: ResourceStorage, events: EventRegistry | null): SpeculationInstancestatic prototype: SpeculationInstance@@ -13027,6 +13037,11 @@ PrefabsPlugin(def: BtDefinition, id: string, newParentId: string): BtDefinition```+## replay — function @experimental+```+(scope: SpeculationScope, body: (commands: CommandsInstance) => SpeculationOutcome): ReplayReport+```+## replicationPlugin — const @experimental```ReplicationPlugindiff --git a/sdk/src/core-runtime.ts b/sdk/src/core-runtime.tsindex aebf5646b..8e469fcd6 100644--- a/sdk/src/core-runtime.ts+++ b/sdk/src/core-runtime.ts@@ -406,7 +406,9 @@ export {export {Speculation,SpeculationInstance,+ replay,type SpeculationOutcome,+ type ReplayReport,} from './ecs/speculation';// =============================================================================diff --git a/sdk/src/ecs/commands.ts b/sdk/src/ecs/commands.tsindex 7b8e2fcb2..324a21cf6 100644--- a/sdk/src/ecs/commands.ts+++ b/sdk/src/ecs/commands.ts@@ -11,6 +11,14 @@ import type { World } from './world';import { ResourceDef, ResourceStorage } from './resource';import { log } from '../util/logger';+/** Key order is not a difference a replay should report, so sort it away. */+function stableText(value: unknown): string {+ if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'undefined';+ if (Array.isArray(value)) return `[${value.map(stableText).join(',')}]`;+ const rec = value as Record<string, unknown>;+ return `{${Object.keys(rec).sort().map((k) => `${k}:${stableText(rec[k])}`).join(',')}}`;+}+// =============================================================================// Commands Descriptor (for system parameters)// =============================================================================@@ -118,6 +126,16 @@ export class EntityCommands {}}+ /** @internal What this spawn or edit WOULD do, as text a second run can be+ * compared against — a queued spawn has no entity yet, so identity cannot+ * be part of the comparison and the composition is. */+ describe(): string {+ const parts = this.components_.map((c) => `${c.component._name}=${stableText(c.data)}`).sort();+ return `${this.isNew_ ? 'spawn' : `edit#${this.entityRef_.entity}`}`+ + `${this.spawnName_ ? `:${this.spawnName_}` : ''}`+ + `(${parts.join(',')})${this.parent_ === null ? '' : `<-${this.parent_}`}`;+ }+insert<T extends object>(component: AnyComponentDef, data?: Partial<T>): this {let instance: unknown;@@ -251,6 +269,18 @@ export class CommandsInstance {}}+ /** @internal Everything queued and not yet applied, as comparable text. */+ describe(): string {+ const spawned = this.spawned_.map((ec) => ec.describe());+ const pending = this.pending_.map((c) => {+ const anyCmd = c as { type: string; entity?: Entity; component?: { _name: string }; data?: unknown };+ return `${anyCmd.type}#${anyCmd.entity ?? '-'}`+ + `${anyCmd.component ? `:${anyCmd.component._name}` : ''}`+ + `${anyCmd.data === undefined ? '' : `=${stableText(anyCmd.data)}`}`;+ });+ return [...spawned, ...pending].join('|');+ }+flush(): void {for (const ec of this.spawned_) {ec.finalize();diff --git a/sdk/src/ecs/event.ts b/sdk/src/ecs/event.tsindex 2b2d0fb75..b8f127230 100644--- a/sdk/src/ecs/event.ts+++ b/sdk/src/ecs/event.ts@@ -124,6 +124,11 @@ export class EventBus<T> {rewindWrite(mark: number): void {if (mark < this.writeBuffer_.length) this.writeBuffer_.length = mark;}++ /** @internal Payloads written past `mark`, oldest first, as text. */+ writtenSince(mark: number): string[] {+ return this.writeBuffer_.slice(mark).map((e) => JSON.stringify(e) ?? 'undefined');+ }}// =============================================================================@@ -178,6 +183,18 @@ export class EventRegistry {rewindWrites(marks: Map<symbol, number>): void {for (const [id, bus] of this.buses_) bus.rewindWrite(marks.get(id) ?? 0);}++ /** @internal What has been written since `marks`, as comparable text: a+ * replay asks whether the same step announces the same things. */+ writtenSince(marks: Map<symbol, number>): string {+ const out: string[] = [];+ for (const [id, bus] of this.buses_) {+ const from = marks.get(id) ?? 0;+ const wrote = bus.writtenSince(from);+ if (wrote.length > 0) out.push(`${String(id.description ?? id.toString())}:${wrote.join(',')}`);+ }+ return out.sort().join('|');+ }}// =============================================================================diff --git a/sdk/src/ecs/speculation.ts b/sdk/src/ecs/speculation.tsindex a8528bd40..1f54faef3 100644--- a/sdk/src/ecs/speculation.ts+++ b/sdk/src/ecs/speculation.ts@@ -97,6 +97,87 @@ export class SpeculationLog {forget(): void {this.before_.clear();}++ /** @internal Where the step LEFT every component it touched. Read with the+ * speculation already closed, so looking does not record. */+ postImage(world: World): string {+ const rows: string[] = [];+ for (const [key, { entity, component }] of this.before_) {+ const held = world.has(entity, component) ? world.tryGet(entity, component) : undefined;+ rows.push(`${key}=${held === undefined || held === null ? 'absent' : stableText(held)}`);+ }+ return rows.sort().join('|');+ }+}++/** Key order is not a difference a replay should report, so sort it away. */+function stableText(value: unknown): string {+ if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'undefined';+ if (Array.isArray(value)) return `[${value.map(stableText).join(',')}]`;+ const rec = value as Record<string, unknown>;+ return `{${Object.keys(rec).sort().map((k) => `${k}:${stableText(rec[k])}`).join(',')}}`;+}++/** What one run of a step did, on the three surfaces the scope owns. */+interface Trace {+ outcome: SpeculationOutcome;+ values: string;+ commands: string;+ events: string;+}++/** Run the step and take it back, keeping an account of what it did. */+function trace(scope: SpeculationScope, body: (commands: CommandsInstance) => SpeculationOutcome): Trace {+ const { world, resources, events } = scope;+ const log = new SpeculationLog();+ const commands = new CommandsInstance(world, resources);+ const marks = events?.writeMarks();++ world.openSpeculation(log);+ let outcome: SpeculationOutcome;+ try {+ outcome = body(commands);+ } finally {+ world.closeSpeculation();+ }+ const taken: Trace = {+ outcome,+ values: log.postImage(world),+ commands: commands.describe(),+ events: marks && events ? events.writtenSince(marks) : '',+ };+ log.undo(world);+ if (marks && events) events.rewindWrites(marks);+ return taken;+}++/** Whether a step reached the same place twice, and what differed if not. */+export interface ReplayReport {+ stable: boolean;+ why: string;+}++/**+ * Run the same step twice from the same state, over the three surfaces this+ * scope aligns; both runs are taken back. A predicted step already promises to+ * depend "only on world state + actions + dt" (replication/client.ts), and+ * nothing held it to that — a clock or a random source reads green until desync.+ */+export function replay(+ scope: SpeculationScope,+ body: (commands: CommandsInstance) => SpeculationOutcome,+): ReplayReport {+ const first = trace(scope, body);+ const second = trace(scope, body);+ for (const surface of ['outcome', 'values', 'commands', 'events'] as const) {+ if (first[surface] !== second[surface]) {+ return {+ stable: false,+ why: `${surface} differed between runs: ${String(first[surface])} then ${String(second[surface])}`,+ };+ }+ }+ return { stable: true, why: '' };}/**@@ -159,10 +240,17 @@ export class SpeculationInstance {}run(body: (commands: CommandsInstance) => SpeculationOutcome): SpeculationOutcome {- return speculate(- { world: this.world_, resources: this.resources_, events: this.events_ ?? undefined },- body,- );+ return speculate(this.scope_(), body);+ }++ /** Ask whether the step is a function of the world alone. Takes both runs+ * back, so asking costs the world nothing. */+ replay(body: (commands: CommandsInstance) => SpeculationOutcome): ReplayReport {+ return replay(this.scope_(), body);+ }++ private scope_(): SpeculationScope {+ return { world: this.world_, resources: this.resources_, events: this.events_ ?? undefined };}}diff --git a/sdk/tests/speculation.test.ts b/sdk/tests/speculation.test.tsindex 97b00ed99..f280f620b 100644--- a/sdk/tests/speculation.test.ts+++ b/sdk/tests/speculation.test.ts@@ -15,7 +15,7 @@ import { World } from '../src/ecs/world';import { defineComponent } from '../src/ecs/component';import { defineEvent, EventRegistry } from '../src/ecs/event';import { ResourceStorage } from '../src/ecs/resource';-import { speculate } from '../src/ecs/speculation';+import { speculate, replay } from '../src/ecs/speculation';import { App } from '../src/app/app';import { Schedule } from '../src/ecs/system';import { defineSystem } from '../src/ecs/system';@@ -182,3 +182,66 @@ describe('a speculation a system asked for', () => {expect(world.getEntitiesWithComponents([Effect]).length).toBe(0);});});++// The contract the replication client already depends on — a predicted step+// "depends only on world state + actions + dt" — with something holding it.+describe('replaying a step', () => {+ it('says so when the same step lands in the same place', () => {+ const { world, resources, events, victim } = scene();+ const report = replay({ world, resources, events }, (commands) => {+ const hp = world.get(victim, Health);+ world.set(victim, Health, { ...hp, hp: hp.hp - 10 });+ commands.spawn().insert(Effect, { kind: 'hit' });+ events.getBus(Died).send({ entity: victim });+ return 'commit';+ });+ expect(report).toEqual({ stable: true, why: '' });+ });++ it('names the surface when the step is not a function of the world', () => {+ const { world, resources, events, victim } = scene();+ const report = replay({ world, resources, events }, () => {+ const hp = world.get(victim, Health);+ world.set(victim, Health, { ...hp, hp: Math.random() });+ return 'commit';+ });+ expect(report.stable).toBe(false);+ expect(report.why).toMatch(/^values differed between runs/);+ });++ it('catches a step whose STRUCTURE wanders, not just its values', () => {+ const { world, resources, events } = scene();+ let n = 0;+ const report = replay({ world, resources, events }, (commands) => {+ for (let i = 0; i <= n; i++) commands.spawn().insert(Effect, { kind: 'hit' });+ n++;+ return 'commit';+ });+ expect(report.stable).toBe(false);+ expect(report.why).toMatch(/^commands differed between runs/);+ });++ it('and an announcement that wanders', () => {+ const { world, resources, events, victim } = scene();+ let n = 0;+ const report = replay({ world, resources, events }, () => {+ events.getBus(Died).send({ entity: victim + n++ });+ return 'commit';+ });+ expect(report.stable).toBe(false);+ expect(report.why).toMatch(/^events differed between runs/);+ });++ it('leaves the world where it found it, whatever it asked', () => {+ const { world, resources, events, victim } = scene();+ replay({ world, resources, events }, (commands) => {+ world.set(victim, Health, { hp: 7 });+ commands.spawn().insert(Effect, { kind: 'hit' });+ events.getBus(Died).send({ entity: victim });+ return 'commit';+ });+ expect(world.get(victim, Health).hp).toBe(100);+ expect(world.getEntitiesWithComponents([Effect]).length).toBe(0);+ expect(delivered(events)).toEqual([]);+ });+});