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): a step of gameplay nobody has seen yet, and can take back

esengine4391c661a25e
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index d45a8f4fc..ae454b70e 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -3328,6 +3328,8 @@ static prototype: EventReaderInstance<any>
## EventRegistry — class @experimental
```
+@internal rewindWrites: (marks: Map<symbol, number>) => void
+@internal writeMarks: () => Map<symbol, number>
busNamed: (name: string) => EventBus<unknown> | undefined
getBus: <T>(event: EventDef<T>) => EventBus<T>
register: <T>(event: EventDef<T>) => void
@@ -10265,6 +10267,7 @@ tabIndex: number | undefined
@internal bufferedWriteRows: (component: AnyComponentDef) => number
@internal builtin: BuiltinBridge
@internal changes_: ChangeTracker
+@internal closeSpeculation: () => void
@internal compositionChanges: () => CompositionDelta | null
@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => void
@internal disconnectCpp: () => void
@@ -10291,6 +10294,7 @@ tabIndex: number | undefined
@internal isIterating: () => boolean
@internal layoutEpoch: () => number | null
@internal markChanged: (entity: Entity, component: AnyComponentDef) => void
+@internal openSpeculation: (log: { record(world: World, entity: Entity, component: AnyComponentDef): void; }) => void
@internal queries_: QueryCache
@internal queryCostEnabled: boolean
@internal queryEntities: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]
@@ -10310,6 +10314,7 @@ tabIndex: number | undefined
@internal scriptSpanOf: (component: AnyComponentDef) => { rows: number; stride: number; sparse: number; sparseCount: number; owners: number; ownerCount: number; } | undefined
@internal setQueryCostEnabled: (enabled: boolean) => void
@internal setTransformChangeTracking: (on: boolean) => boolean
+@internal speculating: boolean
@internal suspendIteration: () => number
@internal takeCompositionChanges: () => void
@internal topologyReaderCount: (component: AnyComponentDef) => number
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index be39e1a2b..02500f721 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -3336,6 +3336,8 @@ static prototype: EventReaderInstance<any>
## EventRegistry — class @experimental
```
+@internal rewindWrites: (marks: Map<symbol, number>) => void
+@internal writeMarks: () => Map<symbol, number>
busNamed: (name: string) => EventBus<unknown> | undefined
getBus: <T>(event: EventDef<T>) => EventBus<T>
register: <T>(event: EventDef<T>) => void
@@ -10458,6 +10460,7 @@ tabIndex: number | undefined
@internal bufferedWriteRows: (component: AnyComponentDef) => number
@internal builtin: BuiltinBridge
@internal changes_: ChangeTracker
+@internal closeSpeculation: () => void
@internal compositionChanges: () => CompositionDelta | null
@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => void
@internal disconnectCpp: () => void
@@ -10484,6 +10487,7 @@ tabIndex: number | undefined
@internal isIterating: () => boolean
@internal layoutEpoch: () => number | null
@internal markChanged: (entity: Entity, component: AnyComponentDef) => void
+@internal openSpeculation: (log: { record(world: World, entity: Entity, component: AnyComponentDef): void; }) => void
@internal queries_: QueryCache
@internal queryCostEnabled: boolean
@internal queryEntities: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]
@@ -10503,6 +10507,7 @@ tabIndex: number | undefined
@internal scriptSpanOf: (component: AnyComponentDef) => { rows: number; stride: number; sparse: number; sparseCount: number; owners: number; ownerCount: number; } | undefined
@internal setQueryCostEnabled: (enabled: boolean) => void
@internal setTransformChangeTracking: (on: boolean) => boolean
+@internal speculating: boolean
@internal suspendIteration: () => number
@internal takeCompositionChanges: () => void
@internal topologyReaderCount: (component: AnyComponentDef) => number
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 97c03ce10..dd4d1f149 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -3323,6 +3323,8 @@ static prototype: EventReaderInstance<any>
## EventRegistry — class @experimental
```
+@internal rewindWrites: (marks: Map<symbol, number>) => void
+@internal writeMarks: () => Map<symbol, number>
busNamed: (name: string) => EventBus<unknown> | undefined
getBus: <T>(event: EventDef<T>) => EventBus<T>
register: <T>(event: EventDef<T>) => void
@@ -10260,6 +10262,7 @@ tabIndex: number | undefined
@internal bufferedWriteRows: (component: AnyComponentDef) => number
@internal builtin: BuiltinBridge
@internal changes_: ChangeTracker
+@internal closeSpeculation: () => void
@internal compositionChanges: () => CompositionDelta | null
@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => void
@internal disconnectCpp: () => void
@@ -10286,6 +10289,7 @@ tabIndex: number | undefined
@internal isIterating: () => boolean
@internal layoutEpoch: () => number | null
@internal markChanged: (entity: Entity, component: AnyComponentDef) => void
+@internal openSpeculation: (log: { record(world: World, entity: Entity, component: AnyComponentDef): void; }) => void
@internal queries_: QueryCache
@internal queryCostEnabled: boolean
@internal queryEntities: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]
@@ -10305,6 +10309,7 @@ tabIndex: number | undefined
@internal scriptSpanOf: (component: AnyComponentDef) => { rows: number; stride: number; sparse: number; sparseCount: number; owners: number; ownerCount: number; } | undefined
@internal setQueryCostEnabled: (enabled: boolean) => void
@internal setTransformChangeTracking: (on: boolean) => boolean
+@internal speculating: boolean
@internal suspendIteration: () => number
@internal takeCompositionChanges: () => void
@internal topologyReaderCount: (component: AnyComponentDef) => number
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index dcc75cdb7..9d01f8e12 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -3323,6 +3323,8 @@ static prototype: EventReaderInstance<any>
## EventRegistry — class @experimental
```
+@internal rewindWrites: (marks: Map<symbol, number>) => void
+@internal writeMarks: () => Map<symbol, number>
busNamed: (name: string) => EventBus<unknown> | undefined
getBus: <T>(event: EventDef<T>) => EventBus<T>
register: <T>(event: EventDef<T>) => void
@@ -10514,6 +10516,7 @@ tabIndex: number | undefined
@internal bufferedWriteRows: (component: AnyComponentDef) => number
@internal builtin: BuiltinBridge
@internal changes_: ChangeTracker
+@internal closeSpeculation: () => void
@internal compositionChanges: () => CompositionDelta | null
@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => void
@internal disconnectCpp: () => void
@@ -10540,6 +10543,7 @@ tabIndex: number | undefined
@internal isIterating: () => boolean
@internal layoutEpoch: () => number | null
@internal markChanged: (entity: Entity, component: AnyComponentDef) => void
+@internal openSpeculation: (log: { record(world: World, entity: Entity, component: AnyComponentDef): void; }) => void
@internal queries_: QueryCache
@internal queryCostEnabled: boolean
@internal queryEntities: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]
@@ -10559,6 +10563,7 @@ tabIndex: number | undefined
@internal scriptSpanOf: (component: AnyComponentDef) => { rows: number; stride: number; sparse: number; sparseCount: number; owners: number; ownerCount: number; } | undefined
@internal setQueryCostEnabled: (enabled: boolean) => void
@internal setTransformChangeTracking: (on: boolean) => boolean
+@internal speculating: boolean
@internal suspendIteration: () => number
@internal takeCompositionChanges: () => void
@internal topologyReaderCount: (component: AnyComponentDef) => number
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index b7a6350f2..1d7d689a1 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -3323,6 +3323,8 @@ static prototype: EventReaderInstance<any>
## EventRegistry — class @experimental
```
+@internal rewindWrites: (marks: Map<symbol, number>) => void
+@internal writeMarks: () => Map<symbol, number>
busNamed: (name: string) => EventBus<unknown> | undefined
getBus: <T>(event: EventDef<T>) => EventBus<T>
register: <T>(event: EventDef<T>) => void
@@ -10288,6 +10290,7 @@ tabIndex: number | undefined
@internal bufferedWriteRows: (component: AnyComponentDef) => number
@internal builtin: BuiltinBridge
@internal changes_: ChangeTracker
+@internal closeSpeculation: () => void
@internal compositionChanges: () => CompositionDelta | null
@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => void
@internal disconnectCpp: () => void
@@ -10314,6 +10317,7 @@ tabIndex: number | undefined
@internal isIterating: () => boolean
@internal layoutEpoch: () => number | null
@internal markChanged: (entity: Entity, component: AnyComponentDef) => void
+@internal openSpeculation: (log: { record(world: World, entity: Entity, component: AnyComponentDef): void; }) => void
@internal queries_: QueryCache
@internal queryCostEnabled: boolean
@internal queryEntities: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string, filter?: QueryFilter, precomputedDepIds?: symbol[]) => readonly Entity[]
@@ -10333,6 +10337,7 @@ tabIndex: number | undefined
@internal scriptSpanOf: (component: AnyComponentDef) => { rows: number; stride: number; sparse: number; sparseCount: number; owners: number; ownerCount: number; } | undefined
@internal setQueryCostEnabled: (enabled: boolean) => void
@internal setTransformChangeTracking: (on: boolean) => boolean
+@internal speculating: boolean
@internal suspendIteration: () => number
@internal takeCompositionChanges: () => void
@internal topologyReaderCount: (component: AnyComponentDef) => number
diff --git a/sdk/src/ecs/event.ts b/sdk/src/ecs/event.ts
index 2c22141b6..2b2d0fb75 100644
--- a/sdk/src/ecs/event.ts
+++ b/sdk/src/ecs/event.ts
@@ -113,6 +113,17 @@ export class EventBus<T> {
this.writeBuffer_ = tmp;
this.writeBuffer_.length = 0;
}
+
+ /** @internal How much has been written since the last swap — a speculation
+ * takes this before it runs and un-writes back to it if it is abandoned. */
+ writeMark(): number {
+ return this.writeBuffer_.length;
+ }
+
+ /** @internal */
+ rewindWrite(mark: number): void {
+ if (mark < this.writeBuffer_.length) this.writeBuffer_.length = mark;
+ }
}
// =============================================================================
@@ -154,6 +165,19 @@ export class EventRegistry {
bus.swap();
}
}
+
+ /** @internal Where every bus's write half stands right now. */
+ writeMarks(): Map<symbol, number> {
+ const marks = new Map<symbol, number>();
+ for (const [id, bus] of this.buses_) marks.set(id, bus.writeMark());
+ return marks;
+ }
+
+ /** @internal Un-write back to `marks`. A bus made DURING the speculation is
+ * absent from them, so it rewinds to empty rather than being left alone. */
+ rewindWrites(marks: Map<symbol, number>): void {
+ for (const [id, bus] of this.buses_) bus.rewindWrite(marks.get(id) ?? 0);
+ }
}
// =============================================================================
diff --git a/sdk/src/ecs/speculation.ts b/sdk/src/ecs/speculation.ts
new file mode 100644
index 000000000..3a2baa78a
--- /dev/null
+++ b/sdk/src/ecs/speculation.ts
@@ -0,0 +1,138 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file speculation.ts
+ * @brief A step of gameplay nobody has seen yet, and can take back
+ *
+ * Not a fifth deferral mechanism: a boundary the three the engine already has
+ * agree on. Structural change goes to a `CommandsInstance` this scope owns and
+ * flushes only on commit; events written inside it sit in each bus's write half
+ * until the next swap, so a watermark un-writes them; component values are
+ * copied on first touch — and the touch that counts is the HANDLE LEAVING, not
+ * the write arriving, because script storage hands out the stored object itself
+ * and by the time `set` is called the old value is already gone.
+ *
+ * `Transaction` in this directory is the EDITOR's undo/redo of an authoring
+ * gesture, built from forward/reverse closure pairs. This is the runtime's, and
+ * the two must not be confused: closures per mutation cannot be resimulated.
+ */
+
+import { Entity } from '../types';
+import { AnyComponentDef } from './component';
+import { CommandsInstance } from './commands';
+import { EventRegistry } from './event';
+import { ResourceStorage } from './resource';
+import { deepClone } from '../util/deepClone';
+import type { World } from './world';
+
+/** What the body decided. `abandon` must leave nothing a reader could see. */
+export type SpeculationOutcome = 'commit' | 'abandon';
+
+/** Everything the scope has to reach. Explicit rather than global: resources
+ * and the event registry belong to the app, and a kernel that guessed which
+ * one would be a second authority over both. */
+export interface SpeculationScope {
+ world: World;
+ resources: ResourceStorage;
+ /** Omit when the step writes no events — then there is no watermark to take. */
+ events?: EventRegistry;
+}
+
+/** One component's value as it stood before the scope touched it; `absent`
+ * when the entity did not have it, so undoing means removing it again. */
+interface Before {
+ entity: Entity;
+ component: AnyComponentDef;
+ value: unknown | undefined;
+}
+
+/**
+ * The undo log a World writes into while a speculation is open.
+ *
+ * First touch wins: a component written five times in one step still has one
+ * pre-scope value, and restoring it is what "before" means.
+ */
+export class SpeculationLog {
+ private readonly before_ = new Map<string, Before>();
+ private restoring_ = false;
+ private capturing_ = false;
+
+ /** @internal Called by World wherever a handle leaves or a value lands. */
+ record(world: World, entity: Entity, component: AnyComponentDef): void {
+ // Reading the pre-image goes back through `tryGet`, which asks here.
+ if (this.restoring_ || this.capturing_) return;
+ const key = `${entity}:${String(component._id.description ?? component._id.toString())}`;
+ if (this.before_.has(key)) return;
+ this.capturing_ = true;
+ try {
+ const held = world.has(entity, component) ? world.tryGet(entity, component) : undefined;
+ this.before_.set(key, {
+ entity,
+ component,
+ value: held === undefined || held === null ? undefined : deepClone(held),
+ });
+ } finally {
+ this.capturing_ = false;
+ }
+ }
+
+ /** @internal Put every touched component back, without recording the undo. */
+ undo(world: World): void {
+ this.restoring_ = true;
+ try {
+ for (const { entity, component, value } of this.before_.values()) {
+ if (value === undefined) {
+ if (world.has(entity, component)) world.remove(entity, component);
+ } else {
+ world.set(entity, component, value as never);
+ }
+ }
+ } finally {
+ this.restoring_ = false;
+ this.before_.clear();
+ }
+ }
+
+ /** @internal */
+ forget(): void {
+ this.before_.clear();
+ }
+}
+
+/**
+ * Run `body` as a step that has not happened yet.
+ *
+ * It gets the scope's own command queue, and that is what keeps an abandoned
+ * step from consuming an identity: `EntityCommands` allocates none until the
+ * queue is flushed. Spawning on the World itself throws inside the scope.
+ */
+export function speculate(
+ scope: SpeculationScope,
+ body: (commands: CommandsInstance) => SpeculationOutcome,
+): SpeculationOutcome {
+ 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);
+ } catch (e) {
+ world.closeSpeculation();
+ log.undo(world);
+ if (marks && events) events.rewindWrites(marks);
+ throw e;
+ }
+ world.closeSpeculation();
+
+ if (outcome === 'commit') {
+ log.forget();
+ commands.flush();
+ return 'commit';
+ }
+ log.undo(world);
+ if (marks && events) events.rewindWrites(marks);
+ return 'abandon';
+}
diff --git a/sdk/src/ecs/world.ts b/sdk/src/ecs/world.ts
index 5c809d23a..7f974badc 100644
--- a/sdk/src/ecs/world.ts
+++ b/sdk/src/ecs/world.ts
@@ -219,6 +219,12 @@ export class World {
* mutating the set a query is walking is what `Commands` exists to defer.
*/
spawn(name?: string): Entity {
+ if (this.speculation_) {
+ throw new Error(
+ 'Cannot spawn entity inside a speculation. ' +
+ 'Use its Commands, which allocate no identity until the step commits.'
+ );
+ }
if (this.isIterating()) {
throw new Error(
'Cannot spawn entity during query iteration. ' +
@@ -277,6 +283,12 @@ export class World {
* as with {@link spawn} this throws during query iteration.
*/
despawn(entity: Entity): void {
+ if (this.speculation_) {
+ throw new Error(
+ 'Cannot despawn entity inside a speculation. ' +
+ 'Use its Commands, which apply only if the step commits.'
+ );
+ }
if (this.isIterating()) {
throw new Error(
'Cannot despawn entity during query iteration. ' +
@@ -667,6 +679,7 @@ export class World {
* replaces it.
*/
insert<C extends AnyComponentDef>(entity: Entity, component: C, data?: Partial<ComponentData<C>>): ComponentData<C> {
+ this.speculation_?.record(this, entity, component);
if (this.isHierarchyComponent_(component)) {
return this.insertHierarchy_(entity, component, data) as ComponentData<C>;
}
@@ -681,6 +694,7 @@ export class World {
* reads. Insert-or-replace: an entity that lacks the component gets it.
*/
set<C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentData<C>): void {
+ this.speculation_?.record(this, entity, component);
if (this.isHierarchyComponent_(component)) {
this.insertHierarchy_(entity, component, data);
return;
@@ -785,6 +799,7 @@ export class World {
* Asking for a component the entity lacks throws; {@link tryGet} allows it.
*/
get<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C> {
+ this.speculation_?.record(this, entity, component);
if (isBuiltinComponent(component)) {
return this.builtin_.get(entity, component) as ComponentData<C>;
}
@@ -807,6 +822,7 @@ export class World {
* absent. Reading only, on the same terms — writing to the result is
* deprecated; {@link update} is the edit. */
tryGet<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C> | null {
+ this.speculation_?.record(this, entity, component);
if (isBuiltinComponent(component)) {
if (!this.builtin_.hasCpp) return null;
const bset = this.builtin_.getEntitySet(component._cppName);
@@ -832,6 +848,7 @@ export class World {
/** Take `component` off `entity`. Throws during query iteration, as
* {@link spawn} does. */
remove(entity: Entity, component: AnyComponentDef): void {
+ this.speculation_?.record(this, entity, component);
if (this.isIterating()) {
throw new Error(
'Cannot remove component during query iteration. ' +
@@ -1402,6 +1419,32 @@ export class World {
this.recordComponentWrite_(entity, component);
}
+ /**
+ * @internal The open speculation's undo log, or null.
+ *
+ * The pre-image is taken where the HANDLE leaves, not where the write
+ * arrives: script storage hands out the stored object itself, so by `set`
+ * the old value is gone (docs/MUTATION_CONTRACT.md). Hence `get`/`tryGet`
+ * ask here too, and only a component's first touch is kept.
+ */
+ private speculation_: { record(world: World, entity: Entity, component: AnyComponentDef): void } | null = null;
+
+ /** @internal */
+ openSpeculation(log: { record(world: World, entity: Entity, component: AnyComponentDef): void }): void {
+ if (this.speculation_) throw new Error('A speculation is already open on this World — nesting is not supported.');
+ this.speculation_ = log;
+ }
+
+ /** @internal */
+ closeSpeculation(): void {
+ this.speculation_ = null;
+ }
+
+ /** @internal Whether a step that can be taken back is running. */
+ get speculating(): boolean {
+ return this.speculation_ !== null;
+ }
+
/** @internal Whether any query is asking about `component`'s changes. */
isChangeTracked(component: AnyComponentDef): boolean {
return this.changes_.isTracked(component);
diff --git a/sdk/tests/speculation.test.ts b/sdk/tests/speculation.test.ts
new file mode 100644
index 000000000..42565edd2
--- /dev/null
+++ b/sdk/tests/speculation.test.ts
@@ -0,0 +1,112 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file speculation.test.ts
+ * @brief A step nobody has seen yet leaves nothing behind when it is taken back
+ *
+ * Three ways a step can leak, and they fail differently: the value it
+ * wrote, the identity it consumed, and the event it delivered. The
+ * shape is the flagship's damage resolution — hurt something, spawn the
+ * effect, announce the death — because that is the smallest gameplay
+ * act that touches all three.
+ */
+import { describe, it, expect } from 'vitest';
+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';
+
+const Health = defineComponent('SpecHealth', { hp: 100 });
+const Effect = defineComponent('SpecEffect', { kind: '' });
+const Died = defineEvent<{ entity: number }>('SpecDied', { entity: 0 });
+
+function scene() {
+ const world = new World();
+ const resources = new ResourceStorage();
+ const events = new EventRegistry();
+ const victim = world.spawn();
+ world.insert(victim, Health, { hp: 100 });
+ return { world, resources, events, victim };
+}
+
+/** What a reader would see: events are readable only after the swap. */
+function delivered(events: EventRegistry): Array<{ entity: number }> {
+ events.swapAll();
+ return [...events.getBus(Died).getReadBuffer()] as Array<{ entity: number }>;
+}
+
+describe('a speculated step', () => {
+ it('abandoned, leaves no value, no identity and no event', () => {
+ const { world, resources, events, victim } = scene();
+ const before = world.spawn(); // the identity the effect would take
+ world.despawn(before);
+
+ const outcome = speculate({ world, resources, events }, (commands) => {
+ const hp = world.get(victim, Health);
+ world.set(victim, Health, { ...hp, hp: hp.hp - 40 });
+ commands.spawn().insert(Effect, { kind: 'death' });
+ events.getBus(Died).send({ entity: victim });
+ return 'abandon';
+ });
+
+ expect(outcome).toBe('abandon');
+ expect(world.get(victim, Health).hp).toBe(100);
+ expect(world.getEntitiesWithComponents([Effect]).length).toBe(0);
+ expect(delivered(events)).toEqual([]);
+ });
+
+ it('committed, leaves all three', () => {
+ const { world, resources, events, victim } = scene();
+
+ const outcome = speculate({ world, resources, events }, (commands) => {
+ const hp = world.get(victim, Health);
+ world.set(victim, Health, { ...hp, hp: hp.hp - 40 });
+ commands.spawn().insert(Effect, { kind: 'death' });
+ events.getBus(Died).send({ entity: victim });
+ return 'commit';
+ });
+
+ expect(outcome).toBe('commit');
+ expect(world.get(victim, Health).hp).toBe(60);
+ expect(world.getEntitiesWithComponents([Effect]).length).toBe(1);
+ expect(delivered(events)).toEqual([{ entity: victim }]);
+ });
+
+ // The identity clause on its own: an abandoned step must not have COST one.
+ // What this holds is that the queue allocates nothing until it commits, not
+ // merely that the entity is gone afterwards.
+ it('abandoned, hands the next spawn the identity it would have had', () => {
+ const dry = scene();
+ const untouched = dry.world.spawn();
+
+ const { world, resources, events, victim } = scene();
+ speculate({ world, resources, events }, (commands) => {
+ commands.spawn().insert(Effect, { kind: 'death' });
+ world.set(victim, Health, { hp: 1 });
+ return 'abandon';
+ });
+ expect(world.spawn()).toBe(untouched);
+ });
+
+ it('refuses a structural change it could not take back', () => {
+ const { world, resources, events } = scene();
+ expect(() => speculate({ world, resources, events }, () => {
+ world.spawn();
+ return 'commit';
+ })).toThrow(/speculation/i);
+ });
+
+ // A value written through the live handle and never announced: the pre-image
+ // has to come from the hand-out, or this restores whatever `set` saw.
+ it('restores a value that was written through the handle', () => {
+ const { world, resources, events, victim } = scene();
+ speculate({ world, resources, events }, () => {
+ const hp = world.get(victim, Health);
+ hp.hp = 3;
+ world.markChanged(victim, Health);
+ return 'abandon';
+ });
+ expect(world.get(victim, Health).hp).toBe(100);
+ });
+});