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 system that waits no longer holds the ones it has nothing to do with
esengined9b65e2982b2
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex c858c1b2c..473d8b61b 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -8678,7 +8678,9 @@ tabIndex: number | undefined@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+@internal resumeIteration: (depth: number) => void@internal setQueryCostEnabled: (enabled: boolean) => void+@internal suspendIteration: () => numberdespawn: (entity: Entity) => voidentityCount: () => numberfindEntityByName: (name: string) => Entity | nulldiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex d760b8a38..23343a08a 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -8871,7 +8871,9 @@ tabIndex: number | undefined@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+@internal resumeIteration: (depth: number) => void@internal setQueryCostEnabled: (enabled: boolean) => void+@internal suspendIteration: () => numberdespawn: (entity: Entity) => voidentityCount: () => numberfindEntityByName: (name: string) => Entity | nulldiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 6a423fb93..50f3ae974 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -8673,7 +8673,9 @@ tabIndex: number | undefined@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+@internal resumeIteration: (depth: number) => void@internal setQueryCostEnabled: (enabled: boolean) => void+@internal suspendIteration: () => numberdespawn: (entity: Entity) => voidentityCount: () => numberfindEntityByName: (name: string) => Entity | nulldiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 93acf379b..f84688f98 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -8918,7 +8918,9 @@ tabIndex: number | undefined@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+@internal resumeIteration: (depth: number) => void@internal setQueryCostEnabled: (enabled: boolean) => void+@internal suspendIteration: () => numberdespawn: (entity: Entity) => voidentityCount: () => numberfindEntityByName: (name: string) => Entity | nulldiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 1774d1139..653ea48a6 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -8700,7 +8700,9 @@ tabIndex: number | undefined@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+@internal resumeIteration: (depth: number) => void@internal setQueryCostEnabled: (enabled: boolean) => void+@internal suspendIteration: () => numberdespawn: (entity: Entity) => voidentityCount: () => numberfindEntityByName: (name: string) => Entity | nulldiff --git a/sdk/src/app/ambiguity.ts b/sdk/src/app/ambiguity.tsindex 268520201..77efb71f9 100644--- a/sdk/src/app/ambiguity.ts+++ b/sdk/src/app/ambiguity.ts@@ -60,8 +60,14 @@ export interface Ambiguity {over: string[];}-/** Everything that must run before each index, transitively. */-function ancestors(edges: readonly number[][]): Set<number>[] {+/**+ * Everything that must run before each index, transitively.+ *+ * Exported because the schedule needs it for a second reason: a system may only+ * start beside an unfinished one if it does not depend on it, and "depends on"+ * has to include the edge it inherited rather than declared.+ */+export function ancestors(edges: readonly number[][]): Set<number>[] {const out: Set<number>[] = edges.map(() => new Set<number>());const done = new Uint8Array(edges.length);const visit = (i: number, stack: Set<number>): void => {@@ -112,8 +118,11 @@ export function detectAmbiguities(/*** Systems grouped into batches that could run at the same time: a batch is free* of conflicts within itself and its dependencies are met by the batches before- * it. The schedule still runs them one after another — this measures how much of- * one is inherently sequential.+ * it.+ *+ * A measurement, not the plan: the schedule starts systems in sorted order and+ * overlaps by this same rule, which shows on the clock only where a system+ * awaits — a synchronous one finishes before the next can start.*/export function parallelBatches(systems: readonly OrderedSystem[],diff --git a/sdk/src/app/app.ts b/sdk/src/app/app.tsindex 984ab488d..438cd009b 100644--- a/sdk/src/app/app.ts+++ b/sdk/src/app/app.ts@@ -18,12 +18,14 @@ import { prefabsPlugin } from '../prefab/prefabServer';import { setWasmErrorHandler } from '../wasm/wasmError';import { corePlugin, DEFAULT_UI_CAMERA_INFO } from './corePlugin';import {+ ancestors,dependencyEdges,detectAmbiguities,parallelBatches,type Ambiguity,type ResolveTargets,} from './ambiguity';+import { accessOf, conflicts, type SystemAccess } from './access';import { platformNow } from '../platform';import { RenderPipeline } from '../render/renderPipeline';import type { SceneConfig } from '../scene/sceneManager';@@ -72,6 +74,14 @@ export interface FrameCosts {scopes: ScopeCost[];}+/** A system still running, and what decides who may start beside it. */+interface InflightSystem {+ /** Its position in the sorted list — how a dependant recognises it. */+ index: number;+ access: SystemAccess;+ done: Promise<void>;+}+interface SystemEntry {system: SystemDef;runBefore?: string[];@@ -152,6 +162,8 @@ export class App {private pluginsFinished_ = false;private readonly eventRegistry_ = new EventRegistry();private readonly sortedSystemsCache_ = new Map<Schedule, SystemEntry[]>();+ /** Transitive ordering, per schedule. Invalidated with the sort it follows. */+ private readonly dependencyCache_ = new Map<Schedule, Set<number>[]>();private error_handler_: ((error: unknown, systemName: string) => void) | null = null;private system_error_handler_: ((error: Error, systemName?: string) => 'continue' | 'pause') | null = null;private statsEnabled_ = false;@@ -342,6 +354,7 @@ export class App {domain: this.registeringDomain_(),});this.sortedSystemsCache_.delete(schedule);+ this.dependencyCache_.delete(schedule);return this;}@@ -442,6 +455,7 @@ export class App {live[i].system = { _id: cur._id, _params: defs[i]._params, _fn: defs[i]._fn, _name: cur._name };}this.sortedSystemsCache_.delete(schedule);+ this.dependencyCache_.delete(schedule);}return true;}@@ -486,6 +500,7 @@ export class App {});}this.sortedSystemsCache_.delete(schedule);+ this.dependencyCache_.delete(schedule);const existing = this.setMembership_.get(set._name);this.setMembership_.set(set._name, existing ? [...existing, ...members] : members);@@ -505,6 +520,7 @@ export class App {if (filtered.length !== entries.length) {this.systems_.set(schedule, filtered);this.sortedSystemsCache_.delete(schedule);+ this.dependencyCache_.delete(schedule);removed = true;}}@@ -927,6 +943,7 @@ export class App {entries.length = 0;}this.sortedSystemsCache_.clear();+ this.dependencyCache_.clear();this.templateToRuntime_.clear();this.systemCounter_ = 0;@@ -1152,7 +1169,8 @@ export class App {/*** `schedule` grouped into batches that could run at the same time — how much- * of it is inherently sequential. The schedule still runs them in order.+ * of it is inherently sequential. A measurement: the schedule starts systems+ * in sorted order, overlapping only what awaits. See {@link parallelBatches}.** @beta*/@@ -1211,6 +1229,7 @@ export class App {await this.runSchedule(Schedule.Startup);startup.length = 0;this.sortedSystemsCache_.delete(Schedule.Startup);+ this.dependencyCache_.delete(Schedule.Startup);} finally {this.flushing_startup_ = false;}@@ -1234,40 +1253,103 @@ export class App {const t0 = this.phaseTimings_ ? performance.now() : 0;- for (const entry of systems) {+ // Systems that returned a promise and have not settled. A synchronous+ // system runs to completion the moment it starts, so this is empty for a+ // schedule of synchronous systems and the loop below is the old one.+ const inflight: InflightSystem[] = [];+ const settle = async (): Promise<void> => {+ const waiting = inflight.map((f) => f.done);+ inflight.length = 0;+ await Promise.all(waiting);+ };++ for (let i = 0; i < systems.length; i++) {+ const entry = systems[i];+ if (this.frame_paused_) break;if (entry.runIf && !entry.runIf()) continue;++ // Where the declarations are spent rather than reported: a system+ // starts beside an unfinished one only when it neither depends on it+ // nor touches what it touches — undeclared conflicts with everything.+ if (inflight.length > 0) {+ const dependsOn = this.dependenciesFor(schedule, systems)[i];+ const access = accessOf(entry.system);+ const blocked = inflight.some(+ (f) => dependsOn.has(f.index) || conflicts(access, f.access),+ );+ if (blocked) await settle();+ }+try {this.currentSystem_ = entry.system._name;const result = this.runner_.run(entry.system);if (result instanceof Promise) {- await result;+ inflight.push({+ index: i,+ access: accessOf(entry.system),+ done: result.then(+ () => { this.markSystemStepped(entry); },+ (e) => { this.reportSystemError(e, entry.system._name); },+ ),+ });+ } else {+ this.markSystemStepped(entry);}- // Liveness: a system ran, so its owning subsystem stepped this frame.- if (entry.subsystem) this.subsystems_.markStepped(entry.subsystem);} catch (e) {- const name = entry.system._name;- log.error('app', `System "${name}" threw an error`, e);- if (this.error_handler_) {- this.error_handler_(e, name);- }- if (this.system_error_handler_) {- const err = e instanceof Error ? e : new Error(String(e));- const action = this.system_error_handler_(err, name);- if (action === 'pause') {- this.frame_paused_ = true;- return;- }- }+ this.reportSystemError(e, entry.system._name);} finally {+ // Only meaningful for the synchronous stretch: a system parked at+ // an await has no claim on it while someone else runs.this.currentSystem_ = '';}}+ await settle();+if (this.phaseTimings_) {this.phaseTimings_.set(Schedule[schedule], performance.now() - t0);}}+ /**+ * What must finish before each system of `systems` may start, transitively.+ *+ * Ordering edges are a stronger statement than access: two systems that touch+ * nothing in common may still have been ordered on purpose, and starting the+ * second beside the first would silently ignore that.+ */+ private dependenciesFor(schedule: Schedule, systems: readonly SystemEntry[]): Set<number>[] {+ let deps = this.dependencyCache_.get(schedule);+ if (!deps) {+ deps = ancestors(dependencyEdges(systems, this.resolverFor(systems)));+ this.dependencyCache_.set(schedule, deps);+ }+ return deps;+ }++ /** Liveness: a system ran, so its owning subsystem stepped this frame. */+ private markSystemStepped(entry: SystemEntry): void {+ if (entry.subsystem) this.subsystems_.markStepped(entry.subsystem);+ }++ /**+ * Report one system's failure. Pausing stops the schedule from STARTING+ * anything else; what is already in flight still has to be waited for, since+ * a promise cannot be taken back.+ */+ private reportSystemError(e: unknown, name: string): void {+ log.error('app', `System "${name}" threw an error`, e);+ if (this.error_handler_) {+ this.error_handler_(e, name);+ }+ if (this.system_error_handler_) {+ const err = e instanceof Error ? e : new Error(String(e));+ if (this.system_error_handler_(err, name) === 'pause') {+ this.frame_paused_ = true;+ }+ }+ }+private updateTime(delta: number): void {const time = this.resources_.get(Time);const scale = time.scale >= 0 ? time.scale : 0;diff --git a/sdk/src/ecs/system.ts b/sdk/src/ecs/system.tsindex 2c8724c3f..cd4dd3913 100644--- a/sdk/src/ecs/system.ts+++ b/sdk/src/ecs/system.ts@@ -517,10 +517,15 @@ export class SystemRunner {}if (result instanceof Promise) {- return result.then(() => {- this.flushSystem_(system, args, t0);- }, (e) => {+ // Parked here, another system may run. The iteration guard belongs to+ // the world, so this one's share of it is set aside until it resumes.+ const suspended = this.world_.suspendIteration();+ const resume = (): void => {+ this.world_.resumeIteration(suspended);this.flushSystem_(system, args, t0);+ };+ return result.then(resume, (e) => {+ resume();throw e;});}diff --git a/sdk/src/ecs/world.ts b/sdk/src/ecs/world.tsindex 5c5ec8338..e35554b7c 100644--- a/sdk/src/ecs/world.ts+++ b/sdk/src/ecs/world.ts@@ -439,6 +439,25 @@ export class World {this.iterationDepth_ = 0;}+ /**+ * @internal Set the guard aside for a system suspended at an `await`, and+ * give it back when that system resumes.+ *+ * The depth is the WORLD's, and a system parked mid-query would otherwise+ * lend its iteration to whoever runs next: their spawn is refused for an+ * iteration that is not theirs, and their reset frees a query still walking.+ */+ suspendIteration(): number {+ const depth = this.iterationDepth_;+ this.iterationDepth_ = 0;+ return depth;+ }++ /** @internal Pairs with {@link suspendIteration}. */+ resumeIteration(depth: number): void {+ this.iterationDepth_ = depth;+ }+/** @internal */isIterating(): boolean {return this.iterationDepth_ > 0;diff --git a/sdk/tests/async-system.test.ts b/sdk/tests/async-system.test.tsindex e9cdaf63a..5e3a8d0d2 100644--- a/sdk/tests/async-system.test.ts+++ b/sdk/tests/async-system.test.ts@@ -35,6 +35,10 @@ function createMockWorld() {beginIteration: vi.fn(),endIteration: vi.fn(),resetIterationDepth: vi.fn(),+ // A system parked at an await hands its share of the world's iteration+ // guard back, so whoever runs next is not refused for it.+ suspendIteration: vi.fn(() => 0),+ resumeIteration: vi.fn(),getWorldTick: vi.fn(() => worldTick.value),isAddedSince: vi.fn(() => false),isChangedSince: vi.fn(() => false),@@ -172,7 +176,10 @@ describe('App async systems', () => {expect(order).toEqual(['async-start', 'async-end', 'post-update']);});- it('should await async systems in sequence within same schedule', async () => {+ // Systems that declare nothing they touch declare nothing about their order+ // either, so their waits may overlap and the shorter one lands first.+ // Ordering is something you say — see the next test.+ it('lets unordered async systems overlap, so the shorter one lands first', async () => {const app = App.new();const order: string[] = [];@@ -192,9 +199,35 @@ describe('App async systems', () => {await app.tick(1 / 60);+ expect(order).toEqual(['B', 'A']);+ });++ it('keeps async systems in order when the order was declared', async () => {+ const app = App.new();+ const order: string[] = [];++ app.addSystemToSchedule(Schedule.Update, defineSystem(+ [], async () => {+ await new Promise(r => setTimeout(r, 10));+ order.push('A');+ }, { name: 'AsyncA' }+ ));++ app.addSystemToSchedule(Schedule.Update, defineSystem(+ [], async () => {+ await new Promise(r => setTimeout(r, 5));+ order.push('B');+ }, { name: 'AsyncB' }+ ), { runAfter: ['AsyncA'] });++ await app.tick(1 / 60);+expect(order).toEqual(['A', 'B']);});+ // The point of overlapping: a synchronous system no longer queues behind an+ // await it has nothing to do with. `sync-2` runs while `async` is parked, and+ // every one of them still runs before the tick returns.it('should handle mix of sync and async systems', async () => {const app = App.new();const order: string[] = [];@@ -216,7 +249,7 @@ describe('App async systems', () => {await app.tick(1 / 60);- expect(order).toEqual(['sync-1', 'async', 'sync-2']);+ expect(order).toEqual(['sync-1', 'sync-2', 'async']);});it('should handle async system with resource access', async () => {diff --git a/sdk/tests/schedule-concurrency.test.ts b/sdk/tests/schedule-concurrency.test.tsnew file mode 100644index 000000000..8872711c4--- /dev/null+++ b/sdk/tests/schedule-concurrency.test.ts@@ -0,0 +1,140 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Systems that wait, waiting at the same time.+ *+ * A synchronous system runs to completion the moment it starts, so on one+ * thread only the WAITING can overlap. Who may start beside a system+ * parked on an `await` is exactly what the access declarations answer —+ * these are the tests where those declarations are spent, not reported.+ */+import { describe, it, expect } from 'vitest';+import { App } from '../src/app/app';+import { Schedule, defineSystem, GetWorld } from '../src/ecs/system';+import { Query, Mut } from '../src/ecs/query';+import { defineComponent } from '../src/ecs/component';+import { Commands, type CommandsInstance } from '../src/ecs/commands';++const Position = defineComponent('ConcPosition', { x: 0, y: 0 });+const Health = defineComponent('ConcHealth', { hp: 100 });++const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));++/** Wall time one tick takes, which is the only thing overlap can be seen in. */+async function tickMs(app: App): Promise<number> {+ const t0 = performance.now();+ await app.tick(1 / 60);+ return performance.now() - t0;+}++describe('two systems that wait', () => {+ it('wait at the same time when neither touches what the other does', async () => {+ const app = App.new();+ app.addSystemToSchedule(Schedule.Update,+ defineSystem([Query(Mut(Position))], async () => { await sleep(60); }, { name: 'SlowA' }));+ app.addSystemToSchedule(Schedule.Update,+ defineSystem([Query(Mut(Health))], async () => { await sleep(60); }, { name: 'SlowB' }));++ // Serial would be ~120ms; the margin is generous because a loaded CI box+ // is slow, and 120 vs 60 survives any amount of that.+ expect(await tickMs(app)).toBeLessThan(100);+ });++ it('wait one after another when one writes what the other reads', async () => {+ const app = App.new();+ app.addSystemToSchedule(Schedule.Update,+ defineSystem([Query(Mut(Position))], async () => { await sleep(60); }, { name: 'Writer' }));+ app.addSystemToSchedule(Schedule.Update,+ defineSystem([Query(Position)], async () => { await sleep(60); }, { name: 'Reader' }));++ expect(await tickMs(app)).toBeGreaterThan(110);+ });++ // The escape hatch keeps its price: a system that never said what it reaches+ // for cannot be run beside anything, because anything is what it might touch.+ it('wait one after another when one declares nothing', async () => {+ const app = App.new();+ app.addSystemToSchedule(Schedule.Update,+ defineSystem([GetWorld()], async () => { await sleep(60); }, { name: 'Opaque' }));+ app.addSystemToSchedule(Schedule.Update,+ defineSystem([Query(Mut(Health))], async () => { await sleep(60); }, { name: 'Declared' }));++ expect(await tickMs(app)).toBeGreaterThan(110);+ });++ it('overlap once that same system declares its reach', async () => {+ const app = App.new();+ app.addSystemToSchedule(Schedule.Update, defineSystem([GetWorld()], async () => { await sleep(60); },+ { name: 'Declared1', touches: { writes: ['ConcPosition'] } }));+ app.addSystemToSchedule(Schedule.Update,+ defineSystem([Query(Mut(Health))], async () => { await sleep(60); }, { name: 'Declared2' }));++ expect(await tickMs(app)).toBeLessThan(100);+ });+});++describe('a schedule that overlaps', () => {+ it('still runs every system, and an ordering edge still holds', async () => {+ const app = App.new();+ const order: string[] = [];+ app.addSystemToSchedule(Schedule.Update, defineSystem([Query(Mut(Position))], async () => {+ await sleep(40);+ order.push('slow');+ }, { name: 'Slow' }));+ app.addSystemToSchedule(Schedule.Update, defineSystem([Query(Mut(Health))], () => {+ order.push('fast');+ }, { name: 'Fast' }));+ app.addSystemToSchedule(Schedule.Update, defineSystem([Query(Health)], () => {+ order.push('after');+ }, { name: 'After' }), { runAfter: ['Fast'] });++ await app.tick(1 / 60);+ // 'fast' beat 'slow' — that IS the overlap — and 'after' still followed it.+ expect(order).toEqual(['fast', 'after', 'slow']);+ });++ // The iteration guard is the world's, not the system's: a system parked+ // mid-query must not leave it standing, or the next system's spawn is+ // refused for an iteration that is not its own.+ it('does not lend a parked query iteration to the next system', async () => {+ const app = App.new();+ const subject = app.world.spawn('subject');+ app.world.insert(subject, Position, { x: 0, y: 0 });+ let spawnError: unknown = null;++ // Parked INSIDE the loop: a for-of that has run to the end already gave+ // the guard back, and a system suspended after that lends nothing. The+ // depth only outlives an await when the iterator is still open.+ app.addSystemToSchedule(Schedule.Update, defineSystem([Query(Mut(Position))],+ async (q: Iterable<unknown>) => {+ for (const _ of q) await sleep(40);+ }, { name: 'Iterating', touches: { writes: ['ConcPosition'] } }));++ app.addSystemToSchedule(Schedule.Update, defineSystem([GetWorld()], (world) => {+ try {+ world.spawn('from-the-other-system');+ } catch (e) {+ spawnError = e;+ }+ }, { name: 'Spawner', touches: { writes: ['ConcHealth'] } }));++ await app.tick(1 / 60);+ expect(spawnError).toBeNull();+ });++ it('applies a deferred command from the system that returned first', async () => {+ const app = App.new();+ let spawned = 0;+ app.addSystemToSchedule(Schedule.Update, defineSystem([Query(Mut(Position))],+ async () => { await sleep(40); }, { name: 'Slow' }));+ app.addSystemToSchedule(Schedule.Update, defineSystem([Commands(), Query(Mut(Health))],+ (commands: CommandsInstance) => {+ commands.spawn();+ spawned++;+ }, { name: 'Spawner' }));++ await app.tick(1 / 60);+ expect(spawned).toBe(1);+ expect(app.world.entityCount()).toBeGreaterThan(0);+ });+});