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
fix(ecs): the ordering a system declares is the ordering it gets
yhh8fa11666a0e6
diff --git a/docs/astro/src/content/docs/core-concepts/app-lifecycle.mdx b/docs/astro/src/content/docs/core-concepts/app-lifecycle.mdxindex 455db72a7..3efe207b1 100644--- a/docs/astro/src/content/docs/core-concepts/app-lifecycle.mdx+++ b/docs/astro/src/content/docs/core-concepts/app-lifecycle.mdx@@ -191,7 +191,7 @@ The members exported for users, grouped:|---|---|| `app.addSystem(sys)` | Register on `Schedule.Update`. || `app.addStartupSystem(sys)` | Register on `Schedule.Startup` (runs once, before the first frame's schedules). |-| `app.addSystemToSchedule(schedule, sys, { runBefore?, runAfter?, runIf? })` | Any schedule, with ordering edges and a run condition. |+| `app.addSystemToSchedule(schedule, sys, { runBefore?, runAfter?, runIf? })` | Any schedule, with a run condition and ordering edges — added to any the definition already declared. || `app.addSystemSet(set)` / `app.addSystemSetToSchedule(schedule, set)` | Register a whole `SystemSet`; members inherit the set's `runIf` and ordering, and other systems can order against the set's name. || `app.removeSystem(systemId)` | Remove by the def's `_id` symbol. || `app.addEvent(eventDef)` | Register an event channel (double-buffered; swapped each frame). |diff --git a/docs/astro/src/content/docs/core-concepts/systems.mdx b/docs/astro/src/content/docs/core-concepts/systems.mdxindex 868ee946c..93d6530d2 100644--- a/docs/astro/src/content/docs/core-concepts/systems.mdx+++ b/docs/astro/src/content/docs/core-concepts/systems.mdx@@ -61,30 +61,103 @@ or into any phase with `addSystemToSchedule(Schedule.X, system)`:| `First` → `PreUpdate` → `Update` → `PostUpdate` → `Last` | Every frame, in this order. || `FixedPreUpdate` → `FixedUpdate` → `FixedPostUpdate` | On the fixed timestep (physics / replication cadence) — 0..n times per frame. |-Within a phase, systems run in registration order. To constrain that, register on-the **`App`** with ordering options — these reference system **names**, so name the-systems you want to order:+Within a phase, systems run in **registration order** — a straight-line flow needs+no annotations at all. Beyond that, reach for the coarsest lever that expresses+what you mean.-```typescript-import { Schedule } from 'esengine';+### Phases first++Most "run this after that" is really "this belongs in the next phase". Order+across phases is fixed, so it costs no edges: read input in `PreUpdate`, move in+`Update`, follow with the camera in `PostUpdate`.++### Ordering edges+Where one system genuinely depends on another inside the same phase, say so.+Edges reference system **names**, so name the systems you want to order. Ordering+declared on `defineSystem` travels with the definition — which is how the+top-level `addSystem`, which takes no options of its own, gets ordered:++```typescriptconst move = defineSystem([...], moveFn, { name: 'move' });-const camera = defineSystem([...], cameraFn, { name: 'camera' });+const camera = defineSystem([...], cameraFn, {+ name: 'camera',+ runAfter: ['move'], // camera follows movement+});++addSystem(move);+addSystem(camera);+```++Registering on the **`App`** takes the same edges plus `runIf`, and **adds** to+whatever the definition declared rather than replacing it:++```typescript+import { Schedule } from 'esengine';-app.addSystemToSchedule(Schedule.Update, move);app.addSystemToSchedule(Schedule.Update, camera, {- runAfter: ['move'], // camera follows movement+ runAfter: ['input'], // on top of the 'move' edge aboverunIf: () => isPlaying, // skip this system when the condition is false});```+An edge naming a system that isn't in that phase is ignored, and if the edges ever+form a loop the scheduler throws with the offending path —+`Circular system dependency: move → camera → move`.++### System sets++Naming a dependency once per system gets old. `defineSystemSet` gives a **group**+one name: the set's `runIf` and edges apply to every member, and any other system+can constrain the whole group by referring to that name.++```typescript+import { Schedule, defineSystemSet } from 'esengine';++const physics = defineSystemSet('physics', {+ systems: [applyForces, integrateVelocity, resolveContacts],+ runBefore: ['render'], // all three run before 'render'+ runIf: () => !paused, // ...and none of them run while paused+});++app.addSystemSetToSchedule(Schedule.FixedUpdate, physics);++// One edge waits for the entire set:+app.addSystemToSchedule(Schedule.FixedUpdate, debugDraw, { runAfter: ['physics'] });+```++Members keep the order they are listed in. `app.addSystemSet(set)` is the shortcut+for the `Update` phase.++### Priority numbers++There is no `order: 100` option, and none is needed: registration order *is* the+default order, so a numeric scheme is a sort at the call site.++```typescript+const ordered = [+ { order: 100, system: input },+ { order: 200, system: move },+ { order: 300, system: camera },+];+for (const { system } of ordered.sort((a, b) => a.order - b.order)) {+ app.addSystemToSchedule(Schedule.Update, system);+}+```++The engine does not build this in because a number is an implicit global protocol:+values collide, inserting between neighbours needs a magic gap, and deleting a+system quietly takes an implied dependency with it. `runAfter: ['move']` states the+dependency itself — local, composable across plugins, and checkable.+Scene systems only run while their scene is active, so multiple scenes can coexistin one world without interfering.<Aside type="note">- The top-level `addSystem` / `addSystemToSchedule` take **no** options, and- `defineSystem`'s options keep only `name` — so ordering (`runBefore` / `runAfter`- / `runIf`) is applied through `app.addSystemToSchedule(schedule, system, options)`.+ The top-level `addSystem` / `addSystemToSchedule` take **no** options — put `name`,+ `runBefore` and `runAfter` in `defineSystem`. A run condition (`runIf`) has no+ definition-site form, so it comes from `app.addSystemToSchedule(schedule, system,+ options)` or from the enclosing `SystemSet`.</Aside>## Filtering & change detectiondiff --git a/docs/astro/src/content/docs/zh-cn/core-concepts/app-lifecycle.mdx b/docs/astro/src/content/docs/zh-cn/core-concepts/app-lifecycle.mdxindex f05703eda..bf34e7533 100644--- a/docs/astro/src/content/docs/zh-cn/core-concepts/app-lifecycle.mdx+++ b/docs/astro/src/content/docs/zh-cn/core-concepts/app-lifecycle.mdx@@ -178,7 +178,7 @@ export const scorePlugin: Plugin = {|---|---|| `app.addSystem(sys)` | 注册到 `Schedule.Update`。 || `app.addStartupSystem(sys)` | 注册到 `Schedule.Startup`(只跑一次,在首帧各调度之前)。 |-| `app.addSystemToSchedule(schedule, sys, { runBefore?, runAfter?, runIf? })` | 任意调度,带排序边和运行条件。 |+| `app.addSystemToSchedule(schedule, sys, { runBefore?, runAfter?, runIf? })` | 任意调度,带运行条件和排序边——排序边追加在定义处已声明的边之上。 || `app.addSystemSet(set)` / `app.addSystemSetToSchedule(schedule, set)` | 注册整个 `SystemSet`;成员继承集合的 `runIf` 与排序,其他系统可用集合名对其排序。 || `app.removeSystem(systemId)` | 按系统定义的 `_id` symbol 移除。 || `app.addEvent(eventDef)` | 注册事件通道(双缓冲;每帧交换)。 |diff --git a/docs/astro/src/content/docs/zh-cn/core-concepts/systems.mdx b/docs/astro/src/content/docs/zh-cn/core-concepts/systems.mdxindex 660dffd85..474bcff3e 100644--- a/docs/astro/src/content/docs/zh-cn/core-concepts/systems.mdx+++ b/docs/astro/src/content/docs/zh-cn/core-concepts/systems.mdx@@ -54,28 +54,94 @@ addSystem(defineSystem(| `First` → `PreUpdate` → `Update` → `PostUpdate` → `Last` | 每帧,按此顺序。 || `FixedPreUpdate` → `FixedUpdate` → `FixedPostUpdate` | 固定步长(物理 / 复制节拍)——每帧 0..n 次。 |-同一阶段内,系统按注册顺序运行。要约束顺序,在 **`App`** 上带排序选项注册——它们按系统-**名字**引用,所以给要排序的系统起名:+同一阶段内,系统**按注册顺序**运行——线性流程一个标注都不用写。再往上,按"能表达你的+意思的最粗那一层"来选工具。-```typescript-import { Schedule } from 'esengine';+### 先用阶段++大多数"我要跑在它之后"其实是"我属于下一个阶段"。跨阶段的先后是固定的,不用任何依赖边:+`PreUpdate` 收输入,`Update` 移动,`PostUpdate` 跟相机。++### 排序边+同一阶段内确实存在依赖时,把它写出来。依赖边按系统**名字**引用,所以要给参与排序的系统+起名。写在 `defineSystem` 上的排序会**跟着定义走**——顶层的 `addSystem` 自身不收选项,靠+的就是这条:++```typescriptconst move = defineSystem([...], moveFn, { name: 'move' });-const camera = defineSystem([...], cameraFn, { name: 'camera' });+const camera = defineSystem([...], cameraFn, {+ name: 'camera',+ runAfter: ['move'], // 相机跟在移动之后+});++addSystem(move);+addSystem(camera);+```++在 **`App`** 上注册可以写同样的边,外加 `runIf`;它是在定义处已声明的边之上**追加**,而不是+覆盖:++```typescript+import { Schedule } from 'esengine';-app.addSystemToSchedule(Schedule.Update, move);app.addSystemToSchedule(Schedule.Update, camera, {- runAfter: ['move'], // 相机跟在移动之后+ runAfter: ['input'], // 叠加在上面那条 'move' 边之上runIf: () => isPlaying, // 条件为 false 时跳过该系统});```+指向本阶段内不存在的系统的边会被忽略;依赖边一旦成环,调度器会带着成环路径抛错——+`Circular system dependency: move → camera → move`。++### 系统集(System Set)++一条条给每个系统写依赖很快就烦了。`defineSystemSet` 给**一组**系统起一个名字:集合的+`runIf` 和依赖边对每个成员生效,别的系统也只要引用这个名字就能一次约束整组。++```typescript+import { Schedule, defineSystemSet } from 'esengine';++const physics = defineSystemSet('physics', {+ systems: [applyForces, integrateVelocity, resolveContacts],+ runBefore: ['render'], // 三个成员都跑在 'render' 之前+ runIf: () => !paused, // ……暂停时三个都不跑+});++app.addSystemSetToSchedule(Schedule.FixedUpdate, physics);++// 一条边就等整组:+app.addSystemToSchedule(Schedule.FixedUpdate, debugDraw, { runAfter: ['physics'] });+```++成员按列出的顺序运行。`app.addSystemSet(set)` 是注册进 `Update` 阶段的快捷方式。++### 数值优先级++没有 `order: 100` 这种选项,也不需要:注册顺序**就是**默认顺序,所以数值方案就是调用处+的一次排序。++```typescript+const ordered = [+ { order: 100, system: input },+ { order: 200, system: move },+ { order: 300, system: camera },+];+for (const { system } of ordered.sort((a, b) => a.order - b.order)) {+ app.addSystemToSchedule(Schedule.Update, system);+}+```++引擎不内建它,是因为数值是一份隐式的全局协议:数字会撞车,想往两者之间插入就得靠魔法+间隔,删掉一个系统还会悄悄带走一条隐含依赖。而 `runAfter: ['move']` 陈述的是依赖本身+——局部、可跨插件组合、且可校验。+场景系统只在其所属场景处于激活状态时运行,因此多个场景可以共存于同一个世界而互不干扰。<Aside type="note">- 顶层的 `addSystem` / `addSystemToSchedule` **不**收选项,`defineSystem` 的选项只保留- `name`——所以排序(`runBefore` / `runAfter` / `runIf`)要经- `app.addSystemToSchedule(schedule, system, options)` 施加。+ 顶层的 `addSystem` / `addSystemToSchedule` **不**收选项——`name` / `runBefore` /+ `runAfter` 写在 `defineSystem` 里。运行条件 `runIf` 没有定义处的写法,只能经+ `app.addSystemToSchedule(schedule, system, options)` 或所属的 `SystemSet` 施加。</Aside>## 过滤与变更检测diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 5fd459072..7f48353e5 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: 1369 stable · 17 beta · 1 deprecated+Symbols: 1372 stable · 17 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -6542,6 +6542,8 @@ _fn: (...args: never[]) => void | Promise<void>_id: symbol_name: string_params: readonly SystemParam[]+_runAfter: readonly string[] | undefined+_runBefore: readonly string[] | undefined```## SystemOptions — interface@@ -6575,6 +6577,24 @@ static new (world: World, resources: ResourceStorage, eventRegistry?: EventRegisstatic prototype: SystemRunner```+## SystemSet — interface+```+_kind: "set"+_name: string+_runAfter: readonly string[] | undefined+_runBefore: readonly string[] | undefined+_runIf: RunCondition | undefined+_systems: readonly SystemDef[]+```++## SystemSetOptions — interface+```+runAfter: string[] | undefined+runBefore: string[] | undefined+runIf: RunCondition | undefined+systems: SystemDef[]+```+## TB_E — const```2@@ -8756,6 +8776,11 @@ PluralSelector<P extends readonly SystemParam[]>(params: [...P], fn: (...args: InferParams<P>) => void | Promise<void>, options?: SystemOptions): SystemDef```+## defineSystemSet — function+```+(name: string, options: SystemSetOptions): SystemSet+```+## defineTag — function```(name: string): ComponentDef<{}>diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex e9a6b85f5..78be57fe1 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: 1388 stable · 22 beta · 1 deprecated+Symbols: 1391 stable · 22 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -6706,6 +6706,8 @@ _fn: (...args: never[]) => void | Promise<void>_id: symbol_name: string_params: readonly SystemParam[]+_runAfter: readonly string[] | undefined+_runBefore: readonly string[] | undefined```## SystemOptions — interface@@ -6739,6 +6741,24 @@ static new (world: World, resources: ResourceStorage, eventRegistry?: EventRegisstatic prototype: SystemRunner```+## SystemSet — interface+```+_kind: "set"+_name: string+_runAfter: readonly string[] | undefined+_runBefore: readonly string[] | undefined+_runIf: RunCondition | undefined+_systems: readonly SystemDef[]+```++## SystemSetOptions — interface+```+runAfter: string[] | undefined+runBefore: string[] | undefined+runIf: RunCondition | undefined+systems: SystemDef[]+```+## TB_E — const```2@@ -8960,6 +8980,11 @@ PluralSelector<P extends readonly SystemParam[]>(params: [...P], fn: (...args: InferParams<P>) => void | Promise<void>, options?: SystemOptions): SystemDef```+## defineSystemSet — function+```+(name: string, options: SystemSetOptions): SystemSet+```+## defineTag — function```(name: string): ComponentDef<{}>diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 89ea22ad6..175df4919 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: 1368 stable · 19 beta · 1 deprecated+Symbols: 1371 stable · 19 beta · 1 deprecated## ANCHOR_AXES — const```@@ -6537,6 +6537,8 @@ _fn: (...args: never[]) => void | Promise<void>_id: symbol_name: string_params: readonly SystemParam[]+_runAfter: readonly string[] | undefined+_runBefore: readonly string[] | undefined```## SystemOptions — interface@@ -6570,6 +6572,24 @@ static new (world: World, resources: ResourceStorage, eventRegistry?: EventRegisstatic prototype: SystemRunner```+## SystemSet — interface+```+_kind: "set"+_name: string+_runAfter: readonly string[] | undefined+_runBefore: readonly string[] | undefined+_runIf: RunCondition | undefined+_systems: readonly SystemDef[]+```++## SystemSetOptions — interface+```+runAfter: string[] | undefined+runBefore: string[] | undefined+runIf: RunCondition | undefined+systems: SystemDef[]+```+## TB_E — const```2@@ -8751,6 +8771,11 @@ PluralSelector<P extends readonly SystemParam[]>(params: [...P], fn: (...args: InferParams<P>) => void | Promise<void>, options?: SystemOptions): SystemDef```+## defineSystemSet — function+```+(name: string, options: SystemSetOptions): SystemSet+```+## defineTag — function```(name: string): ComponentDef<{}>diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex dfc33bbfe..d3ad48a01 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: 1389 stable · 17 beta · 1 deprecated+Symbols: 1392 stable · 17 beta · 1 deprecated## ANCHOR_AXES — const```@@ -6752,6 +6752,8 @@ _fn: (...args: never[]) => void | Promise<void>_id: symbol_name: string_params: readonly SystemParam[]+_runAfter: readonly string[] | undefined+_runBefore: readonly string[] | undefined```## SystemOptions — interface@@ -6785,6 +6787,24 @@ static new (world: World, resources: ResourceStorage, eventRegistry?: EventRegisstatic prototype: SystemRunner```+## SystemSet — interface+```+_kind: "set"+_name: string+_runAfter: readonly string[] | undefined+_runBefore: readonly string[] | undefined+_runIf: RunCondition | undefined+_systems: readonly SystemDef[]+```++## SystemSetOptions — interface+```+runAfter: string[] | undefined+runBefore: string[] | undefined+runIf: RunCondition | undefined+systems: SystemDef[]+```+## TB_E — const```2@@ -8971,6 +8991,11 @@ PluralSelector<P extends readonly SystemParam[]>(params: [...P], fn: (...args: InferParams<P>) => void | Promise<void>, options?: SystemOptions): SystemDef```+## defineSystemSet — function+```+(name: string, options: SystemSetOptions): SystemSet+```+## defineTag — function```(name: string): ComponentDef<{}>diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 763ba1a5b..19af6df94 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: 1379 stable · 17 beta · 1 deprecated+Symbols: 1382 stable · 17 beta · 1 deprecated## ANCHOR_AXES — const```@@ -6544,6 +6544,8 @@ _fn: (...args: never[]) => void | Promise<void>_id: symbol_name: string_params: readonly SystemParam[]+_runAfter: readonly string[] | undefined+_runBefore: readonly string[] | undefined```## SystemOptions — interface@@ -6577,6 +6579,24 @@ static new (world: World, resources: ResourceStorage, eventRegistry?: EventRegisstatic prototype: SystemRunner```+## SystemSet — interface+```+_kind: "set"+_name: string+_runAfter: readonly string[] | undefined+_runBefore: readonly string[] | undefined+_runIf: RunCondition | undefined+_systems: readonly SystemDef[]+```++## SystemSetOptions — interface+```+runAfter: string[] | undefined+runBefore: string[] | undefined+runIf: RunCondition | undefined+systems: SystemDef[]+```+## TB_E — const```2@@ -8775,6 +8795,11 @@ PluralSelector<P extends readonly SystemParam[]>(params: [...P], fn: (...args: InferParams<P>) => void | Promise<void>, options?: SystemOptions): SystemDef```+## defineSystemSet — function+```+(name: string, options: SystemSetOptions): SystemSet+```+## defineTag — function```(name: string): ComponentDef<{}>diff --git a/sdk/src/app/app.ts b/sdk/src/app/app.tsindex 803c9f80f..c1e8bc0fc 100644--- a/sdk/src/app/app.ts+++ b/sdk/src/app/app.ts@@ -6,7 +6,7 @@*/import { World } from '../ecs/world';-import { Schedule, SystemDef, SystemRunner, SystemSet, type RunCondition } from '../ecs/system';+import { Schedule, SystemDef, SystemRunner, SystemSet, mergeOrderingEdges, type RunCondition } from '../ecs/system';import { ResourceStorage, Time, TimeData, type ResourceDef } from '../ecs/resource';import { EventRegistry, type EventDef } from '../ecs/event';import type { ESEngineModule, CppRegistry } from '../wasm';@@ -234,6 +234,11 @@ export class App {// Systems// =========================================================================+ /**+ * Register `system` onto `schedule`. Ordering given here is added to+ * whatever the definition already declared, so a system can carry its own+ * edges and still be constrained further at the registration site.+ */addSystemToSchedule(schedule: Schedule,system: SystemDef,@@ -245,13 +250,15 @@ export class App {_params: system._params,_fn: system._fn,_name: name,+ _runBefore: system._runBefore,+ _runAfter: system._runAfter,};this.templateToRuntime_.set(system._id, scoped._id);this.systems_.get(schedule)!.push({system: scoped,- runBefore: options?.runBefore,- runAfter: options?.runAfter,+ runBefore: mergeOrderingEdges(system._runBefore, options?.runBefore),+ runAfter: mergeOrderingEdges(system._runAfter, options?.runAfter),runIf: options?.runIf,subsystem: this.buildingPlugin_ ?? undefined,});@@ -321,11 +328,11 @@ export class App {}/**- * 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.+ * Register every system in `set` onto `schedule`. Each member gets the set's+ * `runIf`, and the set's `runBefore` / `runAfter` edges on top of any it+ * declared itself; members keep the order they were listed in. Other systems+ * may reference the set's name in their own ordering, and the scheduler+ * expands those references to every member.*/addSystemSetToSchedule(schedule: Schedule, set: SystemSet): this {const members: string[] = [];@@ -333,8 +340,8 @@ export class App {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 mergedRunBefore = mergeOrderingEdges(sys._runBefore, set._runBefore);+ const mergedRunAfter = mergeOrderingEdges(sys._runAfter, set._runAfter);const setCondition = set._runIf;const runIf: RunCondition | undefined = setCondition ? (() => setCondition()) : undefined;@@ -345,6 +352,8 @@ export class App {_params: sys._params,_fn: sys._fn,_name: name,+ _runBefore: sys._runBefore,+ _runAfter: sys._runAfter,};this.templateToRuntime_.set(sys._id, scoped._id);diff --git a/sdk/src/core-runtime.ts b/sdk/src/core-runtime.tsindex c73292c0e..cdbd532a4 100644--- a/sdk/src/core-runtime.ts+++ b/sdk/src/core-runtime.ts@@ -339,6 +339,7 @@ export {export {Schedule,defineSystem,+ defineSystemSet,addSystem,addStartupSystem,addSystemToSchedule,@@ -348,6 +349,8 @@ export {type SystemDef,type SystemParam,type SystemOptions,+ type SystemSet,+ type SystemSetOptions,type InferParam,type InferParams,} from './ecs/system';diff --git a/sdk/src/ecs/system.ts b/sdk/src/ecs/system.tsindex 31ac63b9c..f069b1508 100644--- a/sdk/src/ecs/system.ts+++ b/sdk/src/ecs/system.ts@@ -90,16 +90,29 @@ export interface SystemDef {readonly _params: readonly SystemParam[];readonly _fn: (...args: never[]) => void | Promise<void>;readonly _name: string;+ readonly _runBefore?: readonly string[];+ readonly _runAfter?: readonly string[];}let templateCounter_ = 0;export interface SystemOptions {+ /** Name other systems reference in their ordering edges. */name?: string;+ /** This system runs before each of these names (a system or a set). */runBefore?: string[];+ /** This system runs after each of these names (a system or a set). */runAfter?: string[];}+/**+ * Declare a system: what it reads and writes, and the function to run.+ *+ * Ordering declared here travels with the definition, so it applies wherever+ * the system is registered — including the top-level {@link addSystem}, which+ * takes no options of its own. Edges given again at the registration site (or+ * on the enclosing {@link SystemSet}) are added to these, not replaced.+ */export function defineSystem<P extends readonly SystemParam[]>(params: [...P],fn: (...args: InferParams<P>) => void | Promise<void>,@@ -111,20 +124,39 @@ export function defineSystem<P extends readonly SystemParam[]>(_id: Symbol(`SystemTemplate_${tid}`),_params: params,_fn: fn as (...args: never[]) => void,- _name: options?.name ?? ''+ _name: options?.name ?? '',+ _runBefore: options?.runBefore,+ _runAfter: options?.runAfter,};}+/** Union of ordering edges from two sources, preserving first-seen order. */+export function mergeOrderingEdges(+ a: readonly string[] | undefined,+ b: readonly string[] | undefined+): string[] | undefined {+ if (!a?.length) return b?.length ? [...b] : undefined;+ if (!b?.length) return [...a];+ const out = [...a];+ for (const name of b) {+ if (!out.includes(name)) out.push(name);+ }+ return out;+}+// =============================================================================// 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.+ * A named group of systems. When registered via `App.addSystemSet`, every+ * member gets the set's `runIf` and its `runBefore` / `runAfter` edges — the+ * group's ordering written once instead of per system. Other+ * systems or sets may also reference the set's *name* in their own edges; the+ * scheduler expands such a reference to every member of the set.+ *+ * Build one with {@link defineSystemSet}; the underscore-prefixed fields are+ * the scheduler's, not an authoring surface.*/export interface SystemSet {readonly _kind: 'set';@@ -146,6 +178,21 @@ export interface SystemSetOptions {runAfter?: string[];}+/**+ * Group systems under one name so ordering and run conditions are written once.+ *+ * ```ts+ * const physics = defineSystemSet('physics', {+ * systems: [applyForces, integrateVelocity],+ * runBefore: ['render'],+ * runIf: () => !paused,+ * });+ * app.addSystemSetToSchedule(Schedule.FixedUpdate, physics);+ * ```+ *+ * Members keep the order they are listed in; anything constraining `'physics'`+ * constrains all of them.+ */export function defineSystemSet(name: string, options: SystemSetOptions): SystemSet {if (!name) throw new Error('SystemSet requires a name');return {diff --git a/sdk/tests/system-ordering.test.ts b/sdk/tests/system-ordering.test.tsindex 8ae3dce8d..2cf95cf44 100644--- a/sdk/tests/system-ordering.test.ts+++ b/sdk/tests/system-ordering.test.ts@@ -1,8 +1,8 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { describe, it, expect, beforeEach } from 'vitest';-import { App } from '../src/app/app';-import { defineSystem, Schedule } from '../src/ecs/system';+import { App, flushPendingSystems } from '../src/app/app';+import { addSystem, defineSystem, Schedule } from '../src/ecs/system';describe('System Dependency Ordering', () => {let app: App;@@ -192,6 +192,93 @@ describe('System Dependency Ordering', () => {});});+ describe('ordering declared on defineSystem', () => {+ it('travels with the definition to the registration site', async () => {+ const move = defineSystem([], () => {+ executionOrder.push('move');+ }, { name: 'MoveSystem' });++ const camera = defineSystem([], () => {+ executionOrder.push('camera');+ }, { name: 'CameraSystem', runAfter: ['MoveSystem'] });++ app.addSystemToSchedule(Schedule.Update, camera);+ app.addSystemToSchedule(Schedule.Update, move);++ (app as any).runner_ = { run: (sys: any) => sys._fn() };+ await (app as any).runSchedule(Schedule.Update);++ expect(executionOrder).toEqual(['move', 'camera']);+ });++ it('applies through the top-level addSystem path, which takes no options', async () => {+ const move = defineSystem([], () => {+ executionOrder.push('move');+ }, { name: 'MoveSystem' });++ const camera = defineSystem([], () => {+ executionOrder.push('camera');+ }, { name: 'CameraSystem', runAfter: ['MoveSystem'] });++ addSystem(camera);+ addSystem(move);+ flushPendingSystems(app);++ (app as any).runner_ = { run: (sys: any) => sys._fn() };+ await (app as any).runSchedule(Schedule.Update);++ expect(executionOrder).toEqual(['move', 'camera']);+ });++ it('adds to the registration site edges rather than being replaced by them', async () => {+ const input = defineSystem([], () => {+ executionOrder.push('input');+ }, { name: 'InputSystem' });++ const move = defineSystem([], () => {+ executionOrder.push('move');+ }, { name: 'MoveSystem' });++ // Declares one edge itself, gets another at registration.+ const camera = defineSystem([], () => {+ executionOrder.push('camera');+ }, { name: 'CameraSystem', runAfter: ['MoveSystem'] });++ app.addSystemToSchedule(Schedule.Update, camera, { runAfter: ['InputSystem'] });+ app.addSystemToSchedule(Schedule.Update, move);+ app.addSystemToSchedule(Schedule.Update, input);++ (app as any).runner_ = { run: (sys: any) => sys._fn() };+ await (app as any).runSchedule(Schedule.Update);++ const cameraIdx = executionOrder.indexOf('camera');+ expect(executionOrder.indexOf('move')).toBeLessThan(cameraIdx);+ expect(executionOrder.indexOf('input')).toBeLessThan(cameraIdx);+ });++ it('survives repeated registration of the same definition', async () => {+ const move = defineSystem([], () => {+ executionOrder.push('move');+ }, { name: 'MoveSystem' });++ const camera = defineSystem([], () => {+ executionOrder.push('camera');+ }, { name: 'CameraSystem', runAfter: ['MoveSystem'] });++ const other = App.new();+ other.addSystemToSchedule(Schedule.Update, camera);+ other.addSystemToSchedule(Schedule.Update, move);++ app.addSystemToSchedule(Schedule.Update, camera);+ app.addSystemToSchedule(Schedule.Update, move);++ (app as any).runner_ = { run: (sys: any) => sys._fn() };+ await (app as any).runSchedule(Schedule.Update);++ expect(executionOrder).toEqual(['move', 'camera']);+ });+ });+describe('non-existent dependencies', () => {it('should ignore dependencies on non-existent systems', async () => {const systemA = defineSystem([], () => {