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(scheduler): SystemSet — group systems with shared run conditions and ordering
esengine79f1eb4e1b94
diff --git a/sdk/src/app.ts b/sdk/src/app.tsindex 0fabe131c..03d8919d6 100644--- a/sdk/src/app.ts+++ b/sdk/src/app.ts@@ -4,7 +4,7 @@*/import { World } from './world';-import { Schedule, SystemDef, SystemRunner } from './system';+import { Schedule, SystemDef, SystemRunner, SystemSet, type RunCondition } from './system';import { ResourceStorage, Time, TimeData, type ResourceDef } from './resource';import { EventRegistry, type EventDef } from './event';import type { ESEngineModule, CppRegistry } from './wasm';@@ -45,7 +45,7 @@ export interface Plugin {// System Entry// =============================================================================-export type RunCondition = () => boolean;+export type { RunCondition };interface SystemEntry {system: SystemDef;@@ -65,6 +65,8 @@ export class App {private runner_: SystemRunner | null = null;private systemCounter_ = 0;private readonly templateToRuntime_ = new Map<symbol, symbol>();+ /** Set name -> runtime system names registered under that set, for dep expansion. */+ private readonly setMembership_ = new Map<string, string[]>();private running_ = false;private lastTime_ = 0;@@ -201,6 +203,53 @@ export class App {return this.addSystemToSchedule(Schedule.Startup, system);}+ /**+ * Register every system in `set` onto `schedule`. Each member inherits+ * the set's `runIf` (AND-combined with its own if supplied per-system+ * here), and its `runBefore` / `runAfter` lists are prepended to the+ * member's edges. Other systems may reference the set's name in their+ * own ordering; the scheduler expands those references to every member.+ */+ addSystemSetToSchedule(schedule: Schedule, set: SystemSet): this {+ const members: string[] = [];+ for (const sys of set._systems) {+ const name = sys._name || `System_${String(++this.systemCounter_)}`;+ members.push(name);++ const mergedRunBefore = set._runBefore ? [...set._runBefore] : undefined;+ const mergedRunAfter = set._runAfter ? [...set._runAfter] : undefined;+ const setCondition = set._runIf;+ const runIf: RunCondition | undefined = setCondition ? (() => setCondition()) : undefined;++ // Use the scoped system name the App would generate so ordering+ // lookups match. Mirrors addSystemToSchedule's naming path.+ const scoped: SystemDef = {+ _id: Symbol(`System_${name}`),+ _params: sys._params,+ _fn: sys._fn,+ _name: name,+ };+ this.templateToRuntime_.set(sys._id, scoped._id);++ this.systems_.get(schedule)!.push({+ system: scoped,+ runBefore: mergedRunBefore,+ runAfter: mergedRunAfter,+ runIf,+ });+ }+ this.sortedSystemsCache_.delete(schedule);++ const existing = this.setMembership_.get(set._name);+ this.setMembership_.set(set._name, existing ? [...existing, ...members] : members);+ return this;+ }++ /** Shortcut for `addSystemSetToSchedule(Schedule.Update, set)`. */+ addSystemSet(set: SystemSet): this {+ return this.addSystemSetToSchedule(Schedule.Update, set);+ }+removeSystem(systemId: symbol): boolean {const runtimeId = this.templateToRuntime_.get(systemId) ?? systemId;let removed = false;@@ -647,11 +696,26 @@ export class App {nameToIndex.set(systems[i].system._name, i);}+ // Expand a name that may refer to a SystemSet into the indices of+ // every member of the set that is also in this schedule. Returns+ // empty when the name matches neither a system nor a known set.+ const resolveTargets = (name: string): number[] => {+ const direct = nameToIndex.get(name);+ if (direct !== undefined) return [direct];+ const members = this.setMembership_.get(name);+ if (!members) return [];+ const out: number[] = [];+ for (const m of members) {+ const idx = nameToIndex.get(m);+ if (idx !== undefined) out.push(idx);+ }+ return out;+ };+for (const entry of systems) {if (entry.runBefore) {for (const targetName of entry.runBefore) {- const targetIndex = nameToIndex.get(targetName);- if (targetIndex !== undefined) {+ for (const targetIndex of resolveTargets(targetName)) {const targetEntry = systems[targetIndex];if (!targetEntry.runAfter) {targetEntry.runAfter = [];@@ -680,8 +744,7 @@ export class App {if (entry.runAfter) {for (const depName of entry.runAfter) {- const depIndex = nameToIndex.get(depName);- if (depIndex !== undefined) {+ for (const depIndex of resolveTargets(depName)) {visit(depIndex);}}diff --git a/sdk/src/system.ts b/sdk/src/system.tsindex f7c92f39e..b0f944e26 100644--- a/sdk/src/system.ts+++ b/sdk/src/system.ts@@ -82,6 +82,9 @@ export type InferParams<P extends readonly SystemParam[]> = {// System Definition// =============================================================================+/** Predicate evaluated per-frame; returning false skips the system for that tick. */+export type RunCondition = () => boolean;+export interface SystemDef {readonly _id: symbol;readonly _params: readonly SystemParam[];@@ -112,6 +115,49 @@ export function defineSystem<P extends readonly SystemParam[]>(};}+// =============================================================================+// System Set — group of systems sharing a run condition and ordering edges+// =============================================================================++/**+ * A named group of systems. When registered via `App.addSystemSet`, each+ * contained system inherits the set's `runIf` (AND-combined with its own)+ * and `runBefore`/`runAfter` edges. Other systems or sets may also reference+ * the set's *name* in their own `runBefore`/`runAfter` lists; the scheduler+ * expands such references to every member of the set.+ */+export interface SystemSet {+ readonly _kind: 'set';+ readonly _name: string;+ readonly _systems: readonly SystemDef[];+ readonly _runIf?: RunCondition;+ readonly _runBefore?: readonly string[];+ readonly _runAfter?: readonly string[];+}++export interface SystemSetOptions {+ /** Systems contained in the set. */+ systems: SystemDef[];+ /** Predicate checked per-frame; false skips every member. */+ runIf?: RunCondition;+ /** Member systems run before each of these names (may reference a set). */+ runBefore?: string[];+ /** Member systems run after each of these names (may reference a set). */+ runAfter?: string[];+}++export function defineSystemSet(name: string, options: SystemSetOptions): SystemSet {+ if (!name) throw new Error('SystemSet requires a name');+ return {+ _kind: 'set',+ _name: name,+ _systems: options.systems,+ _runIf: options.runIf,+ _runBefore: options.runBefore,+ _runAfter: options.runAfter,+ };+}+// =============================================================================// Global System Registration// =============================================================================diff --git a/sdk/tests/system-set.test.ts b/sdk/tests/system-set.test.tsnew file mode 100644index 000000000..77ad753f9--- /dev/null+++ b/sdk/tests/system-set.test.ts@@ -0,0 +1,119 @@+/**+ * @file system-set.test.ts+ * @brief SystemSet grouping, shared runIf, and set-name dep expansion.+ */+import { describe, expect, it } from 'vitest';+import { App } from '../src/app';+import { Schedule, defineSystem, defineSystemSet } from '../src/system';++function namedSystem(name: string, trace: string[]) {+ return defineSystem([], () => { trace.push(name); }, { name });+}++describe('SystemSet', () => {+ it('runs every member system in the set', async () => {+ const app = App.new();+ const trace: string[] = [];++ app.addSystemSetToSchedule(Schedule.Update, defineSystemSet('physics', {+ systems: [+ namedSystem('ApplyForces', trace),+ namedSystem('IntegrateVelocity', trace),+ ],+ }));++ await app.tick(1 / 60);+ expect(trace.sort()).toEqual(['ApplyForces', 'IntegrateVelocity']);+ });++ it('runIf on the set gates every member', async () => {+ const app = App.new();+ const trace: string[] = [];+ let enabled = false;++ app.addSystemSetToSchedule(Schedule.Update, defineSystemSet('physics', {+ systems: [+ namedSystem('ApplyForces', trace),+ namedSystem('IntegrateVelocity', trace),+ ],+ runIf: () => enabled,+ }));++ await app.tick(1 / 60);+ expect(trace).toEqual([]);++ enabled = true;+ await app.tick(1 / 60);+ expect(trace.sort()).toEqual(['ApplyForces', 'IntegrateVelocity']);+ });++ it('other systems can reference the set name in runAfter', async () => {+ const app = App.new();+ const trace: string[] = [];++ app.addSystemSetToSchedule(Schedule.Update, defineSystemSet('physics', {+ systems: [+ namedSystem('ApplyForces', trace),+ namedSystem('IntegrateVelocity', trace),+ ],+ }));++ app.addSystemToSchedule(Schedule.Update, namedSystem('RenderSync', trace), {+ runAfter: ['physics'],+ });++ await app.tick(1 / 60);++ // Both set members must have run before RenderSync.+ const renderIdx = trace.indexOf('RenderSync');+ expect(trace.indexOf('ApplyForces')).toBeLessThan(renderIdx);+ expect(trace.indexOf('IntegrateVelocity')).toBeLessThan(renderIdx);+ });++ it('other systems can reference the set name in runBefore', async () => {+ const app = App.new();+ const trace: string[] = [];++ app.addSystemSetToSchedule(Schedule.Update, defineSystemSet('physics', {+ systems: [+ namedSystem('ApplyForces', trace),+ namedSystem('IntegrateVelocity', trace),+ ],+ }));++ app.addSystemToSchedule(Schedule.Update, namedSystem('Input', trace), {+ runBefore: ['physics'],+ });++ await app.tick(1 / 60);++ const inputIdx = trace.indexOf('Input');+ expect(inputIdx).toBeLessThan(trace.indexOf('ApplyForces'));+ expect(inputIdx).toBeLessThan(trace.indexOf('IntegrateVelocity'));+ });++ it('set runBefore makes every member run before the external target', async () => {+ const app = App.new();+ const trace: string[] = [];++ app.addSystemToSchedule(Schedule.Update, namedSystem('Render', trace));++ app.addSystemSetToSchedule(Schedule.Update, defineSystemSet('physics', {+ systems: [+ namedSystem('ApplyForces', trace),+ namedSystem('IntegrateVelocity', trace),+ ],+ runBefore: ['Render'],+ }));++ await app.tick(1 / 60);++ const renderIdx = trace.indexOf('Render');+ expect(trace.indexOf('ApplyForces')).toBeLessThan(renderIdx);+ expect(trace.indexOf('IntegrateVelocity')).toBeLessThan(renderIdx);+ });++ it('defineSystemSet rejects empty names', () => {+ expect(() => defineSystemSet('', { systems: [] })).toThrow(/name/i);+ });+});