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(logic): an entity can carry a graph, and the graph can reach the world
esenginece98d44b7790
diff --git a/desktop b/desktopindex f8269406a..db35feb00 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit f8269406a89222269b28193dbc6bc248bfb1da21+Subproject commit db35feb009ae30f5b91acad220b026c98fffe092diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex d2afe2cc0..2031b27aa 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": 1938,+ "experimental": 1950,"deprecated": 3},- "total": 2153,+ "total": 2165,"subsystems": [{"id": "ecs",@@ -298,10 +298,10 @@"why": "the node vocabulary is still growing: a name that gains an output changes what an authored graph can read, so the shape is not one to freeze yet","whyZh": "节点词汇表还在长:一个名字多一个输出就改变了已画好的图能读到什么,形状还不到冻结的时候","entry": [- "compileScriptGraph",- "stepScriptGraph",- "describeNode",- "canConnect"+ "ScriptGraphAgent",+ "registerScriptGraph",+ "registerValue",+ "scriptGraphPlugin"]},{diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.tsindex f3ad4184b..5a4f10edb 100644--- a/docs/astro/src/data/componentDocs.ts+++ b/docs/astro/src/data/componentDocs.ts@@ -169,6 +169,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {PerceptionTarget: { category: 'gameplay', summary: 'Tag: perceivers can see this entity.', doc: 'gameplay/ai/perception' },StateMachineAgent: { category: 'gameplay', summary: 'Runs a gameplay state machine asset, calling registry actions as states enter, update and exit.', doc: 'gameplay/ai/state-machines' },BehaviorTreeAgent: { category: 'gameplay', summary: 'Ticks a behavior tree asset against a blackboard, calling registry actions at its leaves.', doc: 'gameplay/ai/behavior-trees' },+ ScriptGraphAgent: { category: 'gameplay', summary: 'Runs a script graph asset on this entity — events, an exec wire, and data wires between registered names.', doc: null },EventBinding: { category: 'gameplay', summary: 'Wires an event on this entity to named actions — gameplay authored in the inspector, with no script.', doc: 'scripting/events', anchor: 'the-data', anchorZh: '数据本身' },AudioSource: { category: 'gameplay', summary: 'Declarative playback attached to an entity, attenuated by distance when spatial.', doc: 'assets/audio', anchor: 'declarative-playback--audiosource', anchorZh: '声明式播放--audiosource' },AudioListener: { category: 'gameplay', summary: 'The ear spatial audio is mixed relative to — usually the camera or the player.', doc: 'assets/audio', anchor: 'spatial-audio', anchorZh: '空间音频' },diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 3b796e62c..20002bacb 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -3583,6 +3583,17 @@}]},+ {+ "name": "ScriptGraphAgent",+ "source": "ts",+ "fields": [+ {+ "key": "graph",+ "type": "Asset<scriptgraph>",+ "default": "none"+ }+ ]+ },{"name": "SegmentCollider2D","source": "cpp",diff --git a/pipeline/src/assets/assetDb.ts b/pipeline/src/assets/assetDb.tsindex dd19711fb..c9a7e38ac 100644--- a/pipeline/src/assets/assetDb.ts+++ b/pipeline/src/assets/assetDb.ts@@ -232,6 +232,7 @@ const BITMAP_FONT = 'bitmapfont';// inside a document, so an unscanned type 404s what the document needs.const JSON_REF_TYPES = new Set(['scene', 'prefab', 'material', 'tileset', 'tilemap', 'animclip', 'animation', 'statemachine', 'behaviortree',+ 'scriptgraph','environment', 'animatorcontroller', 'avatar','json',]);diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex f0907bd58..5d5735d7e 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 · 1777 experimental · 3 deprecated+Symbols: 114 public · 94 beta · 1789 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -277,6 +277,11 @@ static new <Ctx = unknown>(): AiRegistry<Ctx>static prototype: AiRegistry<any>```+## AiScriptGraphs — const @experimental+```+ResourceDef<ScriptGraphs>+```+## AiValueSpec — interface @experimental```evaluate: (ctx: Ctx, bb: Blackboard, params: AiParams, out: AiOutputs) => void@@ -850,7 +855,7 @@ type: AssetFieldType## AssetFieldType — type @public```-'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume'+'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'scriptgraph' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume'```## AssetGroupDef — interface @experimental@@ -8027,6 +8032,16 @@ variables: ScriptGraphVariable[] | undefinedversion: string```+## ScriptGraphAgent — const @experimental+```+ComponentDef<ScriptGraphAgentData>+```++## ScriptGraphAgentData — interface @experimental+```+graph: string+```+## ScriptGraphEdge — interface @experimental```from: string@@ -8046,6 +8061,14 @@ x: number | undefinedy: number | undefined```+## ScriptGraphPlugin — class @experimental+```+build: (app: App) => void+name: string+static new (): ScriptGraphPlugin+static prototype: ScriptGraphPlugin+```+## ScriptGraphVariable — interface @experimental```default: ScriptValue | undefined@@ -8053,6 +8076,16 @@ name: stringtype: "string" | "number" | "bool" | "entity"```+## ScriptGraphs — class @experimental+```+blackboard: (entity: Entity) => Blackboard+halted: (entity: Entity) => boolean+setVariable: (entity: Entity, name: string, value: ScriptValue) => void+variable: (entity: Entity, name: string) => ScriptValue+static new (states: Map<Entity, AgentState>): ScriptGraphs+static prototype: ScriptGraphs+```+## ScriptNodeShape — interface @experimental```entry: "start" | "update" | "destroy" | "event" | undefined@@ -11478,6 +11511,11 @@ BtPlugin(): void```+## clearScriptGraphStore — function @experimental+```+(): void+```+## clearUserComponents — function @experimental```(): void@@ -12128,6 +12166,11 @@ DragPlugin(def: BtDefinition): BtDefinition```+## ensureBuiltinScriptNodes — function @experimental+```+(): void+```+## enterStatePath — function @experimental```(scope: AnimatorScope, name: string): string[]@@ -12523,6 +12566,11 @@ GameplayPlugin(): ResourceStats | null```+## getScriptGraph — function @experimental+```+(key: string): CompiledScriptGraph | undefined+```+## getTextureDimensions — function @experimental```(handle: number): TextureDimensions | null@@ -13513,6 +13561,11 @@ PrefabsPlugin(type: string, codec: SceneComponentCodec): void```+## registerScriptGraph — function @experimental+```+(key: string, graph: ScriptGraph): CompiledScriptGraph+```+## registerSideModule — function @experimental```(id: string, descriptor: SideModuleDescriptor): void@@ -13813,6 +13866,16 @@ Plugin(view: EditorViewData): { right: { axis: WorldAxis; sign: number; }; up: { axis: WorldAxis; sign: number; }; }```+## scriptGraphPlugin — const @experimental+```+ScriptGraphPlugin+```++## scriptGraphTouches — function @experimental+```+(app: App): SystemTouches+```+## selectBlendClip — function @experimental```(blend: AnimatorBlend1D, value: number): AnimatorBlendThreshold@@ -14173,6 +14236,11 @@ StatsPlugin<Ctx>(compiled: CompiledScriptGraph, run: ScriptRunState, tick: ScriptTickContext<Ctx>): void```+## stepScriptGraphs — function @experimental+```+(world: ScriptGraphWorldView, commands: CommandsInstance, dt: number, states: Map<Entity, AgentState>, resolveGraph?: (ref: string) => CompiledScriptGraph | undefined, onProblem?: (entity: Entity, message: string) => void): void+```+## stopNavAgent — function @experimental```(world: World, entity: Entity): voiddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 4e6f64d88..7f447c676 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 · 1796 experimental · 3 deprecated+Symbols: 114 public · 99 beta · 1808 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -277,6 +277,11 @@ static new <Ctx = unknown>(): AiRegistry<Ctx>static prototype: AiRegistry<any>```+## AiScriptGraphs — const @experimental+```+ResourceDef<ScriptGraphs>+```+## AiValueSpec — interface @experimental```evaluate: (ctx: Ctx, bb: Blackboard, params: AiParams, out: AiOutputs) => void@@ -850,7 +855,7 @@ type: AssetFieldType## AssetFieldType — type @public```-'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume'+'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'scriptgraph' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume'```## AssetGroupDef — interface @experimental@@ -8220,6 +8225,16 @@ variables: ScriptGraphVariable[] | undefinedversion: string```+## ScriptGraphAgent — const @experimental+```+ComponentDef<ScriptGraphAgentData>+```++## ScriptGraphAgentData — interface @experimental+```+graph: string+```+## ScriptGraphEdge — interface @experimental```from: string@@ -8239,6 +8254,14 @@ x: number | undefinedy: number | undefined```+## ScriptGraphPlugin — class @experimental+```+build: (app: App) => void+name: string+static new (): ScriptGraphPlugin+static prototype: ScriptGraphPlugin+```+## ScriptGraphVariable — interface @experimental```default: ScriptValue | undefined@@ -8246,6 +8269,16 @@ name: stringtype: "string" | "number" | "bool" | "entity"```+## ScriptGraphs — class @experimental+```+blackboard: (entity: Entity) => Blackboard+halted: (entity: Entity) => boolean+setVariable: (entity: Entity, name: string, value: ScriptValue) => void+variable: (entity: Entity, name: string) => ScriptValue+static new (states: Map<Entity, AgentState>): ScriptGraphs+static prototype: ScriptGraphs+```+## ScriptNodeShape — interface @experimental```entry: "start" | "update" | "destroy" | "event" | undefined@@ -11686,6 +11719,11 @@ BtPlugin(): void```+## clearScriptGraphStore — function @experimental+```+(): void+```+## clearUserComponents — function @experimental```(): void@@ -12361,6 +12399,11 @@ DragPlugin(def: BtDefinition): BtDefinition```+## ensureBuiltinScriptNodes — function @experimental+```+(): void+```+## enterStatePath — function @experimental```(scope: AnimatorScope, name: string): string[]@@ -12756,6 +12799,11 @@ GameplayPlugin(): ResourceStats | null```+## getScriptGraph — function @experimental+```+(key: string): CompiledScriptGraph | undefined+```+## getTextureDimensions — function @experimental```(handle: number): TextureDimensions | null@@ -13756,6 +13804,11 @@ PrefabsPlugin(type: string, codec: SceneComponentCodec): void```+## registerScriptGraph — function @experimental+```+(key: string, graph: ScriptGraph): CompiledScriptGraph+```+## registerSideModule — function @experimental```(id: string, descriptor: SideModuleDescriptor): void@@ -14056,6 +14109,16 @@ Plugin(view: EditorViewData): { right: { axis: WorldAxis; sign: number; }; up: { axis: WorldAxis; sign: number; }; }```+## scriptGraphPlugin — const @experimental+```+ScriptGraphPlugin+```++## scriptGraphTouches — function @experimental+```+(app: App): SystemTouches+```+## selectBlendClip — function @experimental```(blend: AnimatorBlend1D, value: number): AnimatorBlendThreshold@@ -14416,6 +14479,11 @@ StatsPlugin<Ctx>(compiled: CompiledScriptGraph, run: ScriptRunState, tick: ScriptTickContext<Ctx>): void```+## stepScriptGraphs — function @experimental+```+(world: ScriptGraphWorldView, commands: CommandsInstance, dt: number, states: Map<Entity, AgentState>, resolveGraph?: (ref: string) => CompiledScriptGraph | undefined, onProblem?: (entity: Entity, message: string) => void): void+```+## stopNavAgent — function @experimental```(world: World, entity: Entity): voiddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 4aa22f665..ed3d92952 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 · 1776 experimental · 3 deprecated+Symbols: 114 public · 96 beta · 1788 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -272,6 +272,11 @@ static new <Ctx = unknown>(): AiRegistry<Ctx>static prototype: AiRegistry<any>```+## AiScriptGraphs — const @experimental+```+ResourceDef<ScriptGraphs>+```+## AiValueSpec — interface @experimental```evaluate: (ctx: Ctx, bb: Blackboard, params: AiParams, out: AiOutputs) => void@@ -845,7 +850,7 @@ type: AssetFieldType## AssetFieldType — type @public```-'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume'+'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'scriptgraph' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume'```## AssetGroupDef — interface @experimental@@ -8022,6 +8027,16 @@ variables: ScriptGraphVariable[] | undefinedversion: string```+## ScriptGraphAgent — const @experimental+```+ComponentDef<ScriptGraphAgentData>+```++## ScriptGraphAgentData — interface @experimental+```+graph: string+```+## ScriptGraphEdge — interface @experimental```from: string@@ -8041,6 +8056,14 @@ x: number | undefinedy: number | undefined```+## ScriptGraphPlugin — class @experimental+```+build: (app: App) => void+name: string+static new (): ScriptGraphPlugin+static prototype: ScriptGraphPlugin+```+## ScriptGraphVariable — interface @experimental```default: ScriptValue | undefined@@ -8048,6 +8071,16 @@ name: stringtype: "string" | "number" | "bool" | "entity"```+## ScriptGraphs — class @experimental+```+blackboard: (entity: Entity) => Blackboard+halted: (entity: Entity) => boolean+setVariable: (entity: Entity, name: string, value: ScriptValue) => void+variable: (entity: Entity, name: string) => ScriptValue+static new (states: Map<Entity, AgentState>): ScriptGraphs+static prototype: ScriptGraphs+```+## ScriptNodeShape — interface @experimental```entry: "start" | "update" | "destroy" | "event" | undefined@@ -11473,6 +11506,11 @@ BtPlugin(): void```+## clearScriptGraphStore — function @experimental+```+(): void+```+## clearUserComponents — function @experimental```(): void@@ -12123,6 +12161,11 @@ DragPlugin(def: BtDefinition): BtDefinition```+## ensureBuiltinScriptNodes — function @experimental+```+(): void+```+## enterStatePath — function @experimental```(scope: AnimatorScope, name: string): string[]@@ -12518,6 +12561,11 @@ GameplayPlugin(): ResourceStats | null```+## getScriptGraph — function @experimental+```+(key: string): CompiledScriptGraph | undefined+```+## getTextureDimensions — function @experimental```(handle: number): TextureDimensions | null@@ -13518,6 +13566,11 @@ PrefabsPlugin(type: string, codec: SceneComponentCodec): void```+## registerScriptGraph — function @experimental+```+(key: string, graph: ScriptGraph): CompiledScriptGraph+```+## registerSideModule — function @experimental```(id: string, descriptor: SideModuleDescriptor): void@@ -13818,6 +13871,16 @@ Plugin(view: EditorViewData): { right: { axis: WorldAxis; sign: number; }; up: { axis: WorldAxis; sign: number; }; }```+## scriptGraphPlugin — const @experimental+```+ScriptGraphPlugin+```++## scriptGraphTouches — function @experimental+```+(app: App): SystemTouches+```+## selectBlendClip — function @experimental```(blend: AnimatorBlend1D, value: number): AnimatorBlendThreshold@@ -14178,6 +14241,11 @@ StatsPlugin<Ctx>(compiled: CompiledScriptGraph, run: ScriptRunState, tick: ScriptTickContext<Ctx>): void```+## stepScriptGraphs — function @experimental+```+(world: ScriptGraphWorldView, commands: CommandsInstance, dt: number, states: Map<Entity, AgentState>, resolveGraph?: (ref: string) => CompiledScriptGraph | undefined, onProblem?: (entity: Entity, message: string) => void): void+```+## stopNavAgent — function @experimental```(world: World, entity: Entity): voiddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 0d4b44ac8..7c1f0bd88 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 · 1798 experimental · 3 deprecated+Symbols: 114 public · 94 beta · 1810 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -272,6 +272,11 @@ static new <Ctx = unknown>(): AiRegistry<Ctx>static prototype: AiRegistry<any>```+## AiScriptGraphs — const @experimental+```+ResourceDef<ScriptGraphs>+```+## AiValueSpec — interface @experimental```evaluate: (ctx: Ctx, bb: Blackboard, params: AiParams, out: AiOutputs) => void@@ -845,7 +850,7 @@ type: AssetFieldType## AssetFieldType — type @public```-'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume'+'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'scriptgraph' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume'```## AssetGroupDef — interface @experimental@@ -8270,6 +8275,16 @@ variables: ScriptGraphVariable[] | undefinedversion: string```+## ScriptGraphAgent — const @experimental+```+ComponentDef<ScriptGraphAgentData>+```++## ScriptGraphAgentData — interface @experimental+```+graph: string+```+## ScriptGraphEdge — interface @experimental```from: string@@ -8289,6 +8304,14 @@ x: number | undefinedy: number | undefined```+## ScriptGraphPlugin — class @experimental+```+build: (app: App) => void+name: string+static new (): ScriptGraphPlugin+static prototype: ScriptGraphPlugin+```+## ScriptGraphVariable — interface @experimental```default: ScriptValue | undefined@@ -8296,6 +8319,16 @@ name: stringtype: "string" | "number" | "bool" | "entity"```+## ScriptGraphs — class @experimental+```+blackboard: (entity: Entity) => Blackboard+halted: (entity: Entity) => boolean+setVariable: (entity: Entity, name: string, value: ScriptValue) => void+variable: (entity: Entity, name: string) => ScriptValue+static new (states: Map<Entity, AgentState>): ScriptGraphs+static prototype: ScriptGraphs+```+## ScriptNodeShape — interface @experimental```entry: "start" | "update" | "destroy" | "event" | undefined@@ -11727,6 +11760,11 @@ BtPlugin(): void```+## clearScriptGraphStore — function @experimental+```+(): void+```+## clearUserComponents — function @experimental```(): void@@ -12382,6 +12420,11 @@ DragPlugin(def: BtDefinition): BtDefinition```+## ensureBuiltinScriptNodes — function @experimental+```+(): void+```+## enterStatePath — function @experimental```(scope: AnimatorScope, name: string): string[]@@ -12777,6 +12820,11 @@ GameplayPlugin(): ResourceStats | null```+## getScriptGraph — function @experimental+```+(key: string): CompiledScriptGraph | undefined+```+## getTextureDimensions — function @experimental```(handle: number): TextureDimensions | null@@ -13777,6 +13825,11 @@ PrefabsPlugin(type: string, codec: SceneComponentCodec): void```+## registerScriptGraph — function @experimental+```+(key: string, graph: ScriptGraph): CompiledScriptGraph+```+## registerSideModule — function @experimental```(id: string, descriptor: SideModuleDescriptor): void@@ -14077,6 +14130,16 @@ Plugin(view: EditorViewData): { right: { axis: WorldAxis; sign: number; }; up: { axis: WorldAxis; sign: number; }; }```+## scriptGraphPlugin — const @experimental+```+ScriptGraphPlugin+```++## scriptGraphTouches — function @experimental+```+(app: App): SystemTouches+```+## selectBlendClip — function @experimental```(blend: AnimatorBlend1D, value: number): AnimatorBlendThreshold@@ -14437,6 +14500,11 @@ StatsPlugin<Ctx>(compiled: CompiledScriptGraph, run: ScriptRunState, tick: ScriptTickContext<Ctx>): void```+## stepScriptGraphs — function @experimental+```+(world: ScriptGraphWorldView, commands: CommandsInstance, dt: number, states: Map<Entity, AgentState>, resolveGraph?: (ref: string) => CompiledScriptGraph | undefined, onProblem?: (entity: Entity, message: string) => void): void+```+## stopNavAgent — function @experimental```(world: World, entity: Entity): voiddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex a3d4547c2..c170483b5 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 · 1788 experimental · 3 deprecated+Symbols: 114 public · 94 beta · 1800 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -272,6 +272,11 @@ static new <Ctx = unknown>(): AiRegistry<Ctx>static prototype: AiRegistry<any>```+## AiScriptGraphs — const @experimental+```+ResourceDef<ScriptGraphs>+```+## AiValueSpec — interface @experimental```evaluate: (ctx: Ctx, bb: Blackboard, params: AiParams, out: AiOutputs) => void@@ -845,7 +850,7 @@ type: AssetFieldType## AssetFieldType — type @public```-'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume'+'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'scriptgraph' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume'```## AssetGroupDef — interface @experimental@@ -8029,6 +8034,16 @@ variables: ScriptGraphVariable[] | undefinedversion: string```+## ScriptGraphAgent — const @experimental+```+ComponentDef<ScriptGraphAgentData>+```++## ScriptGraphAgentData — interface @experimental+```+graph: string+```+## ScriptGraphEdge — interface @experimental```from: string@@ -8048,6 +8063,14 @@ x: number | undefinedy: number | undefined```+## ScriptGraphPlugin — class @experimental+```+build: (app: App) => void+name: string+static new (): ScriptGraphPlugin+static prototype: ScriptGraphPlugin+```+## ScriptGraphVariable — interface @experimental```default: ScriptValue | undefined@@ -8055,6 +8078,16 @@ name: stringtype: "string" | "number" | "bool" | "entity"```+## ScriptGraphs — class @experimental+```+blackboard: (entity: Entity) => Blackboard+halted: (entity: Entity) => boolean+setVariable: (entity: Entity, name: string, value: ScriptValue) => void+variable: (entity: Entity, name: string) => ScriptValue+static new (states: Map<Entity, AgentState>): ScriptGraphs+static prototype: ScriptGraphs+```+## ScriptNodeShape — interface @experimental```entry: "start" | "update" | "destroy" | "event" | undefined@@ -11501,6 +11534,11 @@ BtPlugin(): void```+## clearScriptGraphStore — function @experimental+```+(): void+```+## clearUserComponents — function @experimental```(): void@@ -12151,6 +12189,11 @@ DragPlugin(def: BtDefinition): BtDefinition```+## ensureBuiltinScriptNodes — function @experimental+```+(): void+```+## enterStatePath — function @experimental```(scope: AnimatorScope, name: string): string[]@@ -12546,6 +12589,11 @@ GameplayPlugin(): ResourceStats | null```+## getScriptGraph — function @experimental+```+(key: string): CompiledScriptGraph | undefined+```+## getTextureDimensions — function @experimental```(handle: number): TextureDimensions | null@@ -13541,6 +13589,11 @@ PrefabsPlugin(type: string, codec: SceneComponentCodec): void```+## registerScriptGraph — function @experimental+```+(key: string, graph: ScriptGraph): CompiledScriptGraph+```+## registerSideModule — function @experimental```(id: string, descriptor: SideModuleDescriptor): void@@ -13841,6 +13894,16 @@ Plugin(view: EditorViewData): { right: { axis: WorldAxis; sign: number; }; up: { axis: WorldAxis; sign: number; }; }```+## scriptGraphPlugin — const @experimental+```+ScriptGraphPlugin+```++## scriptGraphTouches — function @experimental+```+(app: App): SystemTouches+```+## selectBlendClip — function @experimental```(blend: AnimatorBlend1D, value: number): AnimatorBlendThreshold@@ -14201,6 +14264,11 @@ StatsPlugin<Ctx>(compiled: CompiledScriptGraph, run: ScriptRunState, tick: ScriptTickContext<Ctx>): void```+## stepScriptGraphs — function @experimental+```+(world: ScriptGraphWorldView, commands: CommandsInstance, dt: number, states: Map<Entity, AgentState>, resolveGraph?: (ref: string) => CompiledScriptGraph | undefined, onProblem?: (entity: Entity, message: string) => void): void+```+## stopNavAgent — function @experimental```(world: World, entity: Entity): voiddiff --git a/sdk/src/app/pluginSets.ts b/sdk/src/app/pluginSets.tsindex a6e189cd2..f5aa567f3 100644--- a/sdk/src/app/pluginSets.ts+++ b/sdk/src/app/pluginSets.ts@@ -35,6 +35,7 @@ import { timerPlugin } from '../ecs/timer';import { velocityPlugin } from '../velocity';import { lifecyclePlugin } from '../ecs/lifecycle';import { navPlugin, fsmPlugin, btPlugin, perceptionPlugin } from '../ai';+import { scriptGraphPlugin } from '../logic';import { eventBindingPlugin } from '../eventBinding';import { replicationPlugin } from '../net/replication';import { servicesPlugin } from '../services';@@ -54,7 +55,7 @@ import { diagnosticsPlugin } from '../diagnostics';export const simulationBasePlugins = (): Plugin[] => [diagnosticsPlugin,timerPlugin, velocityPlugin, lifecyclePlugin, audioPlugin,- perceptionPlugin, fsmPlugin, btPlugin, navPlugin, eventBindingPlugin, replicationPlugin,+ perceptionPlugin, fsmPlugin, btPlugin, scriptGraphPlugin, navPlugin, eventBindingPlugin, replicationPlugin,servicesPlugin,];@@ -74,6 +75,6 @@ export const webBasePlugins = (): Plugin[] => [timerPlugin, velocityPlugin, lifecyclePlugin, animationPlugin, audioPlugin, videoPlugin,particlePlugin, trailPlugin, meshRendererPlugin, tilemapPlugin, postProcessPlugin, timelinePlugin,gameplayPlugin,- perceptionPlugin, fsmPlugin, btPlugin, navPlugin, eventBindingPlugin, replicationPlugin,+ perceptionPlugin, fsmPlugin, btPlugin, scriptGraphPlugin, navPlugin, eventBindingPlugin, replicationPlugin,servicesPlugin,];diff --git a/sdk/src/asset/AssetLoader.ts b/sdk/src/asset/AssetLoader.tsindex 7e5ca76ea..4c85ce06e 100644--- a/sdk/src/asset/AssetLoader.ts+++ b/sdk/src/asset/AssetLoader.ts@@ -85,6 +85,10 @@ export interface BtResult {btId: string;}+export interface ScriptGraphResult {+ graphId: string;+}+export interface PrefabResult {data: unknown;}diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex f4ca6d3fe..7c23fd383 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -44,6 +44,7 @@ import { FsmAssetLoader } from './loaders/FsmAssetLoader';import { AnimatorControllerAssetLoader } from './loaders/AnimatorControllerAssetLoader';import { AvatarAssetLoader } from './loaders/AvatarAssetLoader';import { BtAssetLoader } from './loaders/BtAssetLoader';+import { ScriptGraphAssetLoader } from './loaders/ScriptGraphAssetLoader';import { LocaleAssetLoader } from './loaders/LocaleAssetLoader';import { JsonAssetLoader } from './loaders/JsonAssetLoader';import { getComponentDefaults } from '../ecs/component';@@ -1302,6 +1303,7 @@ export class Assets {const timelinePaths = discovered.byType.get('timeline') ?? new Set<string>();const fsmPaths = discovered.byType.get('statemachine') ?? new Set<string>();const btPaths = discovered.byType.get('behaviortree') ?? new Set<string>();+ const graphPaths = discovered.byType.get('scriptgraph') ?? new Set<string>();const animatorPaths = discovered.byType.get('animatorcontroller') ?? new Set<string>();const avatarPaths = discovered.byType.get('avatar') ?? new Set<string>();const meshPaths = discovered.byType.get('mesh') ?? new Set<string>();@@ -1409,6 +1411,7 @@ export class Assets {// fsm/bt is that path resolves once the scene finishes preloading.pushAcquire(fsmPaths, p => this.acquireTyped('statemachine', p), 'statemachine');pushAcquire(btPaths, p => this.acquireTyped('behaviortree', p), 'behaviortree');+ pushAcquire(graphPaths, p => this.acquireTyped('scriptgraph', p), 'scriptgraph');pushAcquire(animatorPaths, p => this.acquireTyped('animatorcontroller', p), 'animatorcontroller');pushAcquire(avatarPaths, p => this.acquireTyped('avatar', p), 'avatar');@@ -2241,6 +2244,7 @@ export class Assets {this.register(new AnimatorControllerAssetLoader());this.register(new AvatarAssetLoader());this.register(new BtAssetLoader());+ this.register(new ScriptGraphAssetLoader());this.register(new LocaleAssetLoader());this.register(new JsonAssetLoader());}diff --git a/sdk/src/asset/loaders/ScriptGraphAssetLoader.ts b/sdk/src/asset/loaders/ScriptGraphAssetLoader.tsnew file mode 100644index 000000000..553dd0a29--- /dev/null+++ b/sdk/src/asset/loaders/ScriptGraphAssetLoader.ts@@ -0,0 +1,28 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file ScriptGraphAssetLoader.ts+ * @brief Loads a `.esgraph` and publishes the compiled graph on its slot, so a+ * ScriptGraphAgent naming it resolves at runtime.+ *+ * The payload IS the runtime definition — the compile here only indexes it (pins+ * resolved, wires turned into lookups), which is why it happens once per era and+ * not once per name.+ */+import type { AssetLoader, LoadContext, RegistryAssetLoader, ScriptGraphResult } from '../AssetLoader';+import type { RegistryEra } from '../registryAssets';+import { compileAgainstRegistry } from '../../logic/ScriptGraphAgent';+import type { ScriptGraph } from '../../logic/types';++export class ScriptGraphAssetLoader implements AssetLoader<ScriptGraphResult> {+ readonly type = 'scriptgraph';+ readonly extensions = ['.esgraph'];++ readonly registry: RegistryAssetLoader<ScriptGraphResult> = {+ prepare: async (path: string, ctx: LoadContext): Promise<RegistryEra<ScriptGraphResult>> => {+ const text = await ctx.loadText(ctx.catalog.getBuildPath(path));+ const graph = JSON.parse(text) as ScriptGraph;+ return { published: compileAgainstRegistry(graph), value: { graphId: path } };+ },+ };+}diff --git a/sdk/src/assetTypes.ts b/sdk/src/assetTypes.tsindex 5ebf791d2..103a5e0d0 100644--- a/sdk/src/assetTypes.ts+++ b/sdk/src/assetTypes.ts@@ -85,6 +85,8 @@ const ASSET_TYPE_REGISTRY: readonly AssetTypeEntry[] = [{ extensions: ['esanimator'], contentType: 'json', editorType: 'json', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: false },// Behavior tree (registerBt / BtAssetLoader) — data-driven BT definition.{ extensions: ['esbt'], contentType: 'json', editorType: 'json', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: false },+ // Script graph (registerScriptGraph / ScriptGraphAssetLoader) — visual logic.+ { extensions: ['esgraph'], contentType: 'json', editorType: 'json', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: false },// Prefiltered environment: nine irradiance coefficients inline, plus the path// of the octahedral atlas they were baked beside — hence the transitive dep,// without which the cook ships the document and culls the image it is half of.diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex bfad94650..148df5a4b 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -1024,6 +1024,18 @@ export {type CompiledScriptGraph,type ScriptRunState,type ScriptTickContext,+ ScriptGraphAgent,+ registerScriptGraph,+ getScriptGraph,+ clearScriptGraphStore,+ ScriptGraphPlugin,+ scriptGraphPlugin,+ ScriptGraphs,+ AiScriptGraphs,+ stepScriptGraphs,+ scriptGraphTouches,+ ensureBuiltinScriptNodes,+ type ScriptGraphAgentData,} from './logic';// =============================================================================diff --git a/sdk/src/logic/ScriptGraphAgent.ts b/sdk/src/logic/ScriptGraphAgent.tsnew file mode 100644index 000000000..4cf7c4cb2--- /dev/null+++ b/sdk/src/logic/ScriptGraphAgent.ts@@ -0,0 +1,77 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file ScriptGraphAgent.ts+ * @brief ScriptGraphAgent component + the compiled-graph store.+ *+ * The authorable half: which graph to run (a registered name or a `.esgraph`+ * asset key). Mirrors StateMachineAgent — an entity carries the reference and+ * the plugin does the ticking, so the component stays serializable.+ */++import { defineComponent } from '../ecs/component';+import { isUuidRef } from '../asset/AssetRegistry';+import { aiRegistry } from '../ai/fsm/AiContext';+import { ensureBuiltinAiRegistrations } from '../ai/builtins';+import { ensureBuiltinScriptNodes } from './builtinNodes';+import { compileScriptGraph, type CompiledScriptGraph } from './ScriptGraphRunner';+import type { ScriptGraph } from './types';++export interface ScriptGraphAgentData {+ /** Key of the graph to run: a `registerScriptGraph` name or a `.esgraph` path. */+ graph: string;+}++export const ScriptGraphAgent = defineComponent<ScriptGraphAgentData>('ScriptGraphAgent', {+ graph: '',+}, {+ assetFields: [{ field: 'graph', type: 'scriptgraph' }],+ // Preload a `.esgraph` path or an editor-serialized uuid ref with the scene,+ // so the graph is registered before the agent first ticks. A plain code name+ // is left alone — this callback is the discovery authority.+ discoverAssets: data => {+ const graph = data.graph;+ return typeof graph === 'string' && (graph.endsWith('.esgraph') || isUuidRef(graph))+ ? [{ type: 'scriptgraph', path: graph }]+ : [];+ },+});++/**+ * Compile against the shared registry, having made sure the engine's own verbs+ * are in it. A graph compiled before they registered would carry a problem for+ * every built-in name it calls — and the compile happens at asset prepare, which+ * can precede any plugin's build.+ */+export function compileAgainstRegistry(graph: ScriptGraph): CompiledScriptGraph {+ ensureBuiltinAiRegistrations();+ ensureBuiltinScriptNodes();+ return compileScriptGraph(graph, aiRegistry);+}++/**+ * Graphs a game registered in CODE, process-wide. A `.esgraph` does not land+ * here — it belongs to the realm that loaded it, which a lookup asks first.+ */+const graphStore = new Map<string, CompiledScriptGraph>();++/** Register (compile) a graph under `key` — the code half of the registry. */+export function registerScriptGraph(key: string, graph: ScriptGraph): CompiledScriptGraph {+ const compiled = compileAgainstRegistry(graph);+ graphStore.set(key, compiled);+ return compiled;+}++export function getScriptGraph(key: string): CompiledScriptGraph | undefined {+ return graphStore.get(key);+}++/** Every registered graph — what the schedule reads to learn this system's reach. */+export function allScriptGraphs(): Iterable<CompiledScriptGraph> {+ return graphStore.values();+}++/** Drop all registered graphs (tests / hot-reload). */+export function clearScriptGraphStore(): void {+ graphStore.clear();+}diff --git a/sdk/src/logic/ScriptGraphPlugin.ts b/sdk/src/logic/ScriptGraphPlugin.tsnew file mode 100644index 000000000..9378c8a04--- /dev/null+++ b/sdk/src/logic/ScriptGraphPlugin.ts@@ -0,0 +1,279 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file ScriptGraphPlugin.ts+ * @brief Ticks ScriptGraphAgents against the shared runtime + registry.+ *+ * Per-entity run state and blackboard live in a closure Map (the `defineBehavior`+ * pattern), so the component stays serializable. The per-frame body is+ * `stepScriptGraphs`, extracted to unit-test against a fake world. Gated to play+ * mode and run in `Update` beside the FSM, which is the schedule slot the other+ * authored-graph interpreters already hold.+ */++import type { App, Plugin } from '../app/app';+import type { Entity } from '../types';+import type { World } from '../ecs/world';+import { defineSystem, Schedule, GetWorld, type SystemTouches } from '../ecs/system';+import { Res, Time, defineResource, type TimeData } from '../ecs/resource';+import { Commands, type CommandsInstance } from '../ecs/commands';+import { playModeOnly } from '../ecs/env';+import type { AnyComponentDef, ComponentData } from '../ecs/component';+import { log } from '../util/logger';+import { Blackboard } from '../ai/fsm/Blackboard';+import { aiRegistry, type AiContext } from '../ai/fsm/AiContext';+import { ensureBuiltinAiRegistrations } from '../ai/builtins';+import { ensureBuiltinScriptNodes } from './builtinNodes';+import { TouchesBuilder, touchesOfLeaves, type LeafRef } from '../ai/worldView';+import { appRegistryAsset, appRegistryAssets } from '../asset/registryLookup';+import { ensureEntityEvents, type EntityEvent, type EntityEventQueue, type Unsubscribe } from '../ecs/entityEvents';+import { ScriptGraphAgent, getScriptGraph, allScriptGraphs } from './ScriptGraphAgent';+import {+ createScriptRunState, stepScriptGraph, destroyScriptGraph, fireScriptGraphEvent,+ type CompiledScriptGraph, type ScriptRunState, type ScriptTickContext,+} from './ScriptGraphRunner';+import type { ScriptValue } from './types';++/** Per-entity graph runtime: blackboard persists; run rebuilds when the key changes. */+interface AgentState {+ bb: Blackboard;+ run: ScriptRunState | null;+ graphKey: string | null;+ compiled: CompiledScriptGraph | null;+}++/** The slice of `World` the step needs — lets tests inject a fake. */+export interface ScriptGraphWorldView {+ getEntitiesWithComponents(components: readonly AnyComponentDef[]): readonly Entity[];+ get<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C>;+ set<C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentData<C>): void;+ has(entity: Entity, component: AnyComponentDef): boolean;+}++type MutableAiContext = { -readonly [K in keyof AiContext]: AiContext[K] };++/** Get (creating if needed) an agent's blackboard — lets game code seed data early. */+export function agentGraphBlackboard(states: Map<Entity, AgentState>, entity: Entity): Blackboard {+ let st = states.get(entity);+ if (!st) {+ st = { bb: new Blackboard(), run: null, graphKey: null, compiled: null };+ states.set(entity, st);+ }+ return st.bb;+}++function contextFor(world: ScriptGraphWorldView, commands: CommandsInstance): MutableAiContext {+ const ctx: MutableAiContext = {+ entity: 0 as Entity,+ dt: 0,+ blackboard: null as unknown as Blackboard,+ world: world as unknown as World,+ commands,+ get: c => world.get(ctx.entity, c),+ set: (c, d) => world.set(ctx.entity, c, d),+ has: c => world.has(ctx.entity, c),+ };+ return ctx;+}++/**+ * Advance every ScriptGraphAgent one tick, and run `event.destroy` for the ones+ * that left. Presence is diffed against the live query rather than watching for+ * removals, so a graph's teardown fires the frame its entity drops out however+ * it left — the `defineBehavior` lifecycle contract.+ */+export function stepScriptGraphs(+ world: ScriptGraphWorldView,+ commands: CommandsInstance,+ dt: number,+ states: Map<Entity, AgentState>,+ resolveGraph?: (ref: string) => CompiledScriptGraph | undefined,+ onProblem?: (entity: Entity, message: string) => void,+): void {+ const ctx = contextFor(world, commands);+ const tick = (entity: Entity, st: AgentState, delta: number): ScriptTickContext<AiContext> => {+ ctx.entity = entity;+ ctx.dt = delta;+ ctx.blackboard = st.bb;+ return {+ ctx: ctx as AiContext, bb: st.bb, registry: aiRegistry, dt: delta,+ onProblem: message => onProblem?.(entity, message),+ };+ };++ const present = new Set<Entity>();+ for (const entity of world.getEntitiesWithComponents([ScriptGraphAgent])) {+ present.add(entity);+ const agent = world.get(entity, ScriptGraphAgent);+ if (!agent.graph) continue;+ const compiled = resolveGraph?.(agent.graph) ?? getScriptGraph(agent.graph);+ if (!compiled) continue;++ let st = states.get(entity);+ if (!st) {+ st = { bb: new Blackboard(), run: null, graphKey: null, compiled: null };+ states.set(entity, st);+ }+ if (st.run === null || st.graphKey !== agent.graph) {+ st.run = createScriptRunState(compiled);+ st.graphKey = agent.graph;+ st.compiled = compiled;+ for (const problem of compiled.problems) onProblem?.(entity, problem);+ }+ stepScriptGraph(compiled, st.run, tick(entity, st, dt));+ }++ if (states.size === present.size) return;+ for (const [entity, st] of states) {+ if (present.has(entity)) continue;+ if (st.compiled && st.run) destroyScriptGraph(st.compiled, st.run, tick(entity, st, 0));+ states.delete(entity);+ }+}++/** Every leaf a compiled graph names — one per `call` node. */+export function* scriptGraphLeaves(compiled: CompiledScriptGraph): Iterable<LeafRef> {+ for (const node of compiled.graph.nodes) {+ if (node.kind === 'call' && node.ref) yield { kind: 'action', name: node.ref };+ }+}++/**+ * What the script-graph system reaches for: the union over the graphs THIS app+ * has. Read per app, because a schedule is per app.+ */+export function scriptGraphTouches(app: App): SystemTouches {+ const builder = new TouchesBuilder().reading(ScriptGraphAgent._name);+ const loaded = [+ ...appRegistryAssets<CompiledScriptGraph>(app, 'scriptgraph'),+ ...allScriptGraphs(),+ ];+ for (const compiled of loaded) touchesOfLeaves(aiRegistry, scriptGraphLeaves(compiled), builder);+ return builder.build();+}++/**+ * Keeps the subscribed event types equal to the union the loaded graphs listen+ * for. One handler per TYPE rather than per (entity, type): a graph swapped at+ * runtime then needs no re-subscription, and a bubbled event still reaches an+ * ancestor's graph because it dispatches with `currentTarget` set to it.+ */+function createEventBridge(+ world: ScriptGraphWorldView,+ events: EntityEventQueue,+ states: Map<Entity, AgentState>,+ tickOf: (entity: Entity, st: AgentState) => ScriptTickContext<AiContext>,+): { sync(): void; dispose(): void } {+ const subscriptions = new Map<string, Unsubscribe>();++ const handle = (event: EntityEvent): void => {+ const self = event.currentTarget;+ const st = states.get(self);+ if (!st?.compiled || !st.run) return;+ fireScriptGraphEvent(st.compiled, st.run, tickOf(self, st), event.type, event.target as number);+ };++ return {+ sync(): void {+ const wanted = new Set<string>();+ for (const st of states.values()) {+ if (!st.compiled) continue;+ for (const type of st.compiled.events.keys()) wanted.add(type);+ }+ for (const [type, off] of subscriptions) {+ if (!wanted.has(type)) { off(); subscriptions.delete(type); }+ }+ for (const type of wanted) {+ if (!subscriptions.has(type)) subscriptions.set(type, events.on(type, handle));+ }+ },+ dispose(): void {+ for (const off of subscriptions.values()) off();+ subscriptions.clear();+ },+ };+}++/** Resource for game code to reach an agent's variables and blackboard. */+export class ScriptGraphs {+ constructor(private states: Map<Entity, AgentState>) {}++ blackboard(entity: Entity): Blackboard {+ return agentGraphBlackboard(this.states, entity);+ }++ /** A graph variable's value, or null before the instance has started. */+ variable(entity: Entity, name: string): ScriptValue {+ return this.states.get(entity)?.run?.vars.get(name) ?? null;+ }++ /** Write a graph variable — how game code hands a running graph its input. */+ setVariable(entity: Entity, name: string, value: ScriptValue): void {+ this.states.get(entity)?.run?.vars.set(name, value);+ }++ /** Whether the instance spent its step budget and stopped. */+ halted(entity: Entity): boolean {+ return this.states.get(entity)?.run?.halted ?? false;+ }+}++export const AiScriptGraphs = defineResource<ScriptGraphs>(null!, 'AiScriptGraphs');++export class ScriptGraphPlugin implements Plugin {+ name = 'scriptGraph';++ build(app: App): void {+ ensureBuiltinAiRegistrations();+ ensureBuiltinScriptNodes();+ const states = new Map<Entity, AgentState>();+ app.world.onDespawn((entity: Entity) => states.delete(entity));+ app.insertResource(AiScriptGraphs, new ScriptGraphs(states));++ const world = app.world as unknown as ScriptGraphWorldView;+ const events = ensureEntityEvents(app);+ let commands_: CommandsInstance | null = null;+ let dt_ = 0;++ const onProblem = (entity: Entity, message: string): void => {+ log.warn('logic', `ScriptGraphAgent on entity ${entity as number}: ${message}`);+ };++ // An event arrives outside the system body, so the context it runs on is+ // built from the frame's last known commands and delta.+ const ctx = contextFor(world, null as unknown as CommandsInstance);+ const bridge = createEventBridge(world, events, states, (entity, st) => {+ ctx.entity = entity;+ ctx.dt = dt_;+ ctx.blackboard = st.bb;+ ctx.commands = commands_ as CommandsInstance;+ return {+ ctx: ctx as AiContext, bb: st.bb, registry: aiRegistry, dt: dt_,+ onProblem: message => onProblem(entity, message),+ };+ });++ const resolveGraph = (ref: string): CompiledScriptGraph | undefined =>+ appRegistryAsset<CompiledScriptGraph>(app, 'scriptgraph', ref);++ app.addSystemToSchedule(+ Schedule.Update,+ defineSystem(+ [Res(Time), Commands(), GetWorld()],+ (time: TimeData, commands: CommandsInstance, w) => {+ commands_ = commands;+ dt_ = time.delta;+ stepScriptGraphs(w as ScriptGraphWorldView, commands, time.delta, states, resolveGraph, onProblem);+ bridge.sync();+ },+ // Asked per analysis, not once: a graph loaded later changes the+ // answer, and no graph at all means this system touches only the+ // agent component.+ { name: 'ScriptGraphSystem', touches: () => scriptGraphTouches(app) },+ ),+ { runIf: playModeOnly },+ );+ }+}++export const scriptGraphPlugin = new ScriptGraphPlugin();diff --git a/sdk/src/logic/builtinNodes.ts b/sdk/src/logic/builtinNodes.tsnew file mode 100644index 000000000..6e32ae489--- /dev/null+++ b/sdk/src/logic/builtinNodes.ts@@ -0,0 +1,120 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file builtinNodes.ts+ * @brief The engine's own value vocabulary — maths, comparison, logic, reading+ * the world — registered as ordinary names.+ *+ * Deliberately not built into the interpreter: an addition node reaches the+ * graph through the same door a project's own `registerValue` does, so there is+ * no privileged set to imitate. Namespaced to stay clear of game names, and a+ * name already present is never overwritten, so game code wins whatever the+ * registration order was.+ *+ * Everything here is `pure`: it answers a question and changes nothing. That is+ * also what keeps it out of the FSM and behaviour-tree palettes, where a name+ * that changes nothing would be a hook that does nothing.+ */++import { aiRegistry, type AiContext } from '../ai/fsm/AiContext';+import type { AiOutputDef, AiOutputs, AiParamDef, AiParams, AiTouches } from '../ai/fsm/registry';+import { getEntityProperty } from '../ecs/propertyPath';+import { log } from '../util/logger';++const num = (v: unknown): number => (typeof v === 'number' ? v : Number(v) || 0);+const str = (v: unknown): string => (v === undefined || v === null ? '' : String(v));++const N = (name: string): AiParamDef => ({ name, type: 'number' });+const B = (name: string): AiParamDef => ({ name, type: 'bool' });+const OUT_N: AiOutputDef[] = [{ name: 'result', type: 'number' }];+const OUT_B: AiOutputDef[] = [{ name: 'result', type: 'bool' }];+const OUT_S: AiOutputDef[] = [{ name: 'result', type: 'string' }];++function value(+ name: string,+ params: readonly AiParamDef[],+ outputs: readonly AiOutputDef[],+ evaluate: (ctx: AiContext, params: AiParams, out: AiOutputs) => void,+ touches?: AiTouches,+): void {+ if (aiRegistry.hasAction(name)) return;+ aiRegistry.registerValue(name, {+ params, outputs, touches,+ evaluate: (ctx, _bb, p, out) => evaluate(ctx, p, out),+ });+}++/**+ * Register the engine's built-in graph vocabulary. Idempotent (and safe after an+ * `aiRegistry.clear()`): each name registers only if absent.+ */+export function ensureBuiltinScriptNodes(): void {+ value('math.add', [N('a'), N('b')], OUT_N, (_c, p, out) => { out.result = num(p.a) + num(p.b); });+ value('math.subtract', [N('a'), N('b')], OUT_N, (_c, p, out) => { out.result = num(p.a) - num(p.b); });+ value('math.multiply', [N('a'), N('b')], OUT_N, (_c, p, out) => { out.result = num(p.a) * num(p.b); });+ value('math.divide', [N('a'), N('b')], OUT_N, (_c, p, out) => {+ // Division by zero is an authoring mistake with no right answer; zero at+ // least keeps the rest of the graph running on a number.+ const b = num(p.b);+ out.result = b === 0 ? 0 : num(p.a) / b;+ });+ value('math.min', [N('a'), N('b')], OUT_N, (_c, p, out) => { out.result = Math.min(num(p.a), num(p.b)); });+ value('math.max', [N('a'), N('b')], OUT_N, (_c, p, out) => { out.result = Math.max(num(p.a), num(p.b)); });+ value('math.abs', [N('a')], OUT_N, (_c, p, out) => { out.result = Math.abs(num(p.a)); });+ value('math.clamp', [N('value'), N('min'), N('max')], OUT_N, (_c, p, out) => {+ out.result = Math.min(Math.max(num(p.value), num(p.min)), num(p.max));+ });+ value('math.lerp', [N('a'), N('b'), N('t')], OUT_N, (_c, p, out) => {+ const t = num(p.t);+ out.result = num(p.a) + (num(p.b) - num(p.a)) * t;+ });+ // A fresh number per activation of the node reading it — the memo makes one+ // wire one value, which is the only guarantee a random node can honour.+ value('math.random', [N('min'), N('max')], OUT_N, (_c, p, out) => {+ const min = num(p.min);+ const max = num(p.max);+ out.result = min + Math.random() * (max - min);+ });++ value('compare.equal', [N('a'), N('b')], OUT_B, (_c, p, out) => { out.result = num(p.a) === num(p.b); });+ value('compare.less', [N('a'), N('b')], OUT_B, (_c, p, out) => { out.result = num(p.a) < num(p.b); });+ value('compare.greater', [N('a'), N('b')], OUT_B, (_c, p, out) => { out.result = num(p.a) > num(p.b); });++ value('logic.and', [B('a'), B('b')], OUT_B, (_c, p, out) => { out.result = Boolean(p.a) && Boolean(p.b); });+ value('logic.or', [B('a'), B('b')], OUT_B, (_c, p, out) => { out.result = Boolean(p.a) || Boolean(p.b); });+ value('logic.not', [B('a')], OUT_B, (_c, p, out) => { out.result = !p.a; });++ value('string.concat',+ [{ name: 'a', type: 'string' }, { name: 'b', type: 'string' }], OUT_S,+ (_c, p, out) => { out.result = str(p.a) + str(p.b); });++ // The read half of `property.set`, and the same addressing: "Component" plus+ // a dot path. Numbers come back as numbers, everything else as its string, so+ // one node serves every field without a type per node.+ value('property.get',+ [{ name: 'path', type: 'string', tooltip: 'Component.field, e.g. Transform.position.x' }],+ [{ name: 'value', type: 'number' }, { name: 'text', type: 'string' }],+ (ctx, p, out) => {+ const path = str(p.path).trim();+ const raw = path ? getEntityProperty(ctx.world, ctx.entity, path) : undefined;+ out.value = typeof raw === 'number' ? raw : Number(raw) || 0;+ out.text = str(raw);+ },+ // Which component it reads is the first segment of the authored path;+ // with no readable path it admits it cannot say.+ { opaque: true },+ );++ value('entity.self', [], [{ name: 'entity', type: 'entity' }],+ (ctx, _p, out) => { out.entity = ctx.entity as number; });++ // An effectful name, so it carries an exec pin and sequences like any other+ // statement — a log line that ran "somewhere in the data" would be useless.+ if (!aiRegistry.hasAction('debug.log')) {+ aiRegistry.registerAction('debug.log', {+ params: [{ name: 'message', type: 'string' }],+ touches: {},+ run: (_ctx, _bb, _arg, params) => { log.info('logic', str(params?.message)); },+ });+ }+}diff --git a/sdk/src/logic/index.ts b/sdk/src/logic/index.tsindex ddc18c973..ce4930ffa 100644--- a/sdk/src/logic/index.ts+++ b/sdk/src/logic/index.ts@@ -45,3 +45,27 @@ export {type ScriptRunState,type ScriptTickContext,} from './ScriptGraphRunner';++export {+ ScriptGraphAgent,+ registerScriptGraph,+ getScriptGraph,+ allScriptGraphs,+ clearScriptGraphStore,+ compileAgainstRegistry,+ type ScriptGraphAgentData,+} from './ScriptGraphAgent';++export {+ ScriptGraphPlugin,+ scriptGraphPlugin,+ ScriptGraphs,+ AiScriptGraphs,+ stepScriptGraphs,+ scriptGraphLeaves,+ scriptGraphTouches,+ agentGraphBlackboard,+ type ScriptGraphWorldView,+} from './ScriptGraphPlugin';++export { ensureBuiltinScriptNodes } from './builtinNodes';diff --git a/sdk/src/scene/scene.ts b/sdk/src/scene/scene.tsindex fb798b996..083a76772 100644--- a/sdk/src/scene/scene.ts+++ b/sdk/src/scene/scene.ts@@ -151,7 +151,7 @@ export class MissingAssetsError extends Error {** @public*/-export type AssetFieldType = 'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume';+export type AssetFieldType = 'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'scriptgraph' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume';// =============================================================================// Component Query Helpers (read from self-describing ComponentDef)diff --git a/sdk/tests/script-graph-agent.test.ts b/sdk/tests/script-graph-agent.test.tsnew file mode 100644index 000000000..238d75886--- /dev/null+++ b/sdk/tests/script-graph-agent.test.ts@@ -0,0 +1,250 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file script-graph-agent.test.ts+ * @brief A graph attached to an entity: it ticks, it reaches the world through+ * the shared context, it tears down when the entity leaves, and the+ * schedule can be told what it touches before it has run.+ */+import { describe, it, expect, beforeEach } from 'vitest';+import type { Entity } from '../src/types';+import type { CommandsInstance } from '../src/ecs/commands';+import { aiRegistry, registerAction } from '../src/ai/fsm/AiContext';+import { defineComponent } from '../src/ecs/component';+import {+ ScriptGraphAgent, registerScriptGraph, clearScriptGraphStore,+} from '../src/logic/ScriptGraphAgent';+import {+ stepScriptGraphs, scriptGraphLeaves, ScriptGraphs, type ScriptGraphWorldView,+} from '../src/logic/ScriptGraphPlugin';+import { ensureBuiltinScriptNodes } from '../src/logic/builtinNodes';+import { SCRIPT_GRAPH_VERSION, type ScriptGraph } from '../src/logic/types';+import { compileScriptGraph } from '../src/logic/ScriptGraphRunner';++interface HealthData { value: number }+const Health = defineComponent<HealthData>('TestHealth', { value: 0 });++/** Minimal in-memory world satisfying what stepScriptGraphs calls. */+class FakeWorld implements ScriptGraphWorldView {+ private store = new Map<string, unknown>();+ private next = 1;+ private entities: Entity[] = [];++ spawn(graph: string, health = 0): Entity {+ const e = this.next++ as Entity;+ this.store.set(`${e}:ScriptGraphAgent`, ScriptGraphAgent.create({ graph }));+ this.store.set(`${e}:TestHealth`, Health.create({ value: health }));+ this.entities.push(e);+ return e;+ }+ despawn(entity: Entity): void {+ this.entities = this.entities.filter((e) => e !== entity);+ }+ getEntitiesWithComponents(): Entity[] { return this.entities; }+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ get(entity: Entity, component: { _name: string }): any {+ return this.store.get(`${entity}:${component._name}`);+ }+ set(entity: Entity, component: { _name: string }, data: unknown): void {+ this.store.set(`${entity}:${component._name}`, data);+ }+ has(entity: Entity, component: { _name: string }): boolean {+ return this.store.has(`${entity}:${component._name}`);+ }+}++const NO_COMMANDS = {} as CommandsInstance;++const graph = (nodes: ScriptGraph['nodes'], edges: ScriptGraph['edges'], variables?: ScriptGraph['variables']): ScriptGraph =>+ ({ version: SCRIPT_GRAPH_VERSION, nodes, edges, ...(variables ? { variables } : {}) });++const wire = (from: string, fromPort: string, to: string, toPort: string) =>+ ({ id: `${from}.${fromPort}->${to}.${toPort}`, from, fromPort, to, toPort });++describe('a graph on an entity', () => {+ let log: string[];++ beforeEach(() => {+ aiRegistry.clear();+ clearScriptGraphStore();+ ensureBuiltinScriptNodes();+ log = [];+ registerAction('test.note', {+ params: [{ name: 'text', type: 'string' }],+ touches: { reads: ['TestHealth'] },+ run: (ctx, _bb, _arg, params) => { log.push(`${params?.text}:${ctx.entity}`); },+ });+ });++ it('ticks each agent with its own entity in the context', () => {+ registerScriptGraph('note', graph(+ [+ { id: 'u', kind: 'event.update' },+ { id: 'n', kind: 'call', ref: 'test.note', literals: { text: 'hi' } },+ ],+ [wire('u', 'then', 'n', '')],+ ));+ const world = new FakeWorld();+ const a = world.spawn('note');+ const b = world.spawn('note');++ stepScriptGraphs(world, NO_COMMANDS, 0.1, new Map());+ expect(log).toEqual([`hi:${a}`, `hi:${b}`]);+ });++ it('reads the entity it is attached to, through the shared context', () => {+ registerScriptGraph('read', graph(+ [+ { id: 'u', kind: 'event.update' },+ { id: 'p', kind: 'call', ref: 'property.get', literals: { path: 'TestHealth.value' } },+ { id: 'n', kind: 'call', ref: 'test.note' },+ ],+ [wire('u', 'then', 'n', ''), wire('p', 'value', 'n', 'text')],+ ));+ const world = new FakeWorld();+ const e = world.spawn('read', 42);++ stepScriptGraphs(world, NO_COMMANDS, 0.1, new Map());+ expect(log).toEqual([`42:${e}`]);+ });++ it('keeps one instance of state per entity', () => {+ registerScriptGraph('count', graph(+ [+ { id: 'u', kind: 'event.update' },+ { id: 'g', kind: 'var.get', literals: { name: 'n' } },+ { id: 'a', kind: 'call', ref: 'math.add', literals: { b: 1 } },+ { id: 's', kind: 'var.set', literals: { name: 'n' } },+ { id: 'note', kind: 'call', ref: 'test.note' },+ ],+ [+ wire('u', 'then', 's', ''),+ wire('g', 'value', 'a', 'a'),+ wire('a', 'result', 's', 'value'),+ wire('s', 'then', 'note', ''),+ wire('g', 'value', 'note', 'text'),+ ],+ [{ name: 'n', type: 'number', default: 0 }],+ ));+ const world = new FakeWorld();+ const a = world.spawn('count');+ const b = world.spawn('count');+ const states = new Map();++ stepScriptGraphs(world, NO_COMMANDS, 0.1, states);+ stepScriptGraphs(world, NO_COMMANDS, 0.1, states);+ expect(log).toEqual([`1:${a}`, `1:${b}`, `2:${a}`, `2:${b}`]);+ });++ it('runs event.destroy the tick the entity drops out of the query', () => {+ registerScriptGraph('bye', graph(+ [+ { id: 'd', kind: 'event.destroy' },+ { id: 'n', kind: 'call', ref: 'test.note', literals: { text: 'bye' } },+ ],+ [wire('d', 'then', 'n', '')],+ ));+ const world = new FakeWorld();+ const e = world.spawn('bye');+ const states = new Map();++ stepScriptGraphs(world, NO_COMMANDS, 0.1, states);+ expect(log).toEqual([]);++ world.despawn(e);+ stepScriptGraphs(world, NO_COMMANDS, 0.1, states);+ expect(log).toEqual([`bye:${e}`]);+ expect(states.size).toBe(0);++ // …and only once: the state is gone, so a later tick has nothing to end.+ stepScriptGraphs(world, NO_COMMANDS, 0.1, states);+ expect(log).toEqual([`bye:${e}`]);+ });++ it('rebuilds the instance when the agent is pointed at another graph', () => {+ registerScriptGraph('one', graph(+ [{ id: 'u', kind: 'event.start' }, { id: 'n', kind: 'call', ref: 'test.note', literals: { text: 'one' } }],+ [wire('u', 'then', 'n', '')],+ ));+ registerScriptGraph('two', graph(+ [{ id: 'u', kind: 'event.start' }, { id: 'n', kind: 'call', ref: 'test.note', literals: { text: 'two' } }],+ [wire('u', 'then', 'n', '')],+ ));+ const world = new FakeWorld();+ const e = world.spawn('one');+ const states = new Map();++ stepScriptGraphs(world, NO_COMMANDS, 0.1, states);+ world.set(e, ScriptGraphAgent, { graph: 'two' });+ stepScriptGraphs(world, NO_COMMANDS, 0.1, states);+ expect(log).toEqual([`one:${e}`, `two:${e}`]);+ });++ it('reports a graph that names something unregistered, once', () => {+ registerScriptGraph('broken', graph(+ [{ id: 'u', kind: 'event.update' }, { id: 'n', kind: 'call', ref: 'nope.missing' }],+ [wire('u', 'then', 'n', '')],+ ));+ const world = new FakeWorld();+ world.spawn('broken');+ const problems: string[] = [];+ const states = new Map();++ stepScriptGraphs(world, NO_COMMANDS, 0.1, states, undefined, (_e, m) => problems.push(m));+ stepScriptGraphs(world, NO_COMMANDS, 0.1, states, undefined, (_e, m) => problems.push(m));+ expect(problems).toHaveLength(1);+ expect(problems[0]).toContain('nope.missing');+ });+});++describe('what the system reaches for comes from the graphs, not the system', () => {+ beforeEach(() => {+ aiRegistry.clear();+ clearScriptGraphStore();+ registerAction('test.hit', { touches: { writes: ['TestHealth'] }, run: () => {} });+ });++ it('names one leaf per call node', () => {+ const compiled = compileScriptGraph(graph(+ [+ { id: 'u', kind: 'event.update' },+ { id: 'a', kind: 'call', ref: 'test.hit' },+ { id: 'b', kind: 'flow.branch' },+ ],+ [],+ ), aiRegistry);+ expect([...scriptGraphLeaves(compiled)]).toEqual([{ kind: 'action', name: 'test.hit' }]);+ });+});++describe('the ScriptGraphs resource', () => {+ beforeEach(() => {+ aiRegistry.clear();+ clearScriptGraphStore();+ ensureBuiltinScriptNodes();+ });++ it('hands a running graph its input and reads a variable back', () => {+ registerScriptGraph('vars', graph(+ [+ { id: 'u', kind: 'event.update' },+ { id: 'g', kind: 'var.get', literals: { name: 'in' } },+ { id: 's', kind: 'var.set', literals: { name: 'out' } },+ ],+ [wire('u', 'then', 's', ''), wire('g', 'value', 's', 'value')],+ [{ name: 'in', type: 'number', default: 1 }, { name: 'out', type: 'number', default: 0 }],+ ));+ const world = new FakeWorld();+ const e = world.spawn('vars');+ const states = new Map();+ const api = new ScriptGraphs(states);++ stepScriptGraphs(world, NO_COMMANDS, 0.1, states);+ expect(api.variable(e, 'out')).toBe(1);++ api.setVariable(e, 'in', 9);+ stepScriptGraphs(world, NO_COMMANDS, 0.1, states);+ expect(api.variable(e, 'out')).toBe(9);+ expect(api.halted(e)).toBe(false);+ });+});diff --git a/tools/apiSubsystems.mjs b/tools/apiSubsystems.mjsindex 4cd3ea4f3..ba0f1af65 100644--- a/tools/apiSubsystems.mjs+++ b/tools/apiSubsystems.mjs@@ -260,7 +260,7 @@ export const SUBSYSTEMS = [tier: 'experimental',why: 'the node vocabulary is still growing: a name that gains an output changes what an authored graph can read, so the shape is not one to freeze yet',whyZh: '节点词汇表还在长:一个名字多一个输出就改变了已画好的图能读到什么,形状还不到冻结的时候',- entry: ['compileScriptGraph', 'stepScriptGraph', 'describeNode', 'canConnect'],+ entry: ['ScriptGraphAgent', 'registerScriptGraph', 'registerValue', 'scriptGraphPlugin'],},{id: 'networking',diff --git a/tools/assetMetaTable.js b/tools/assetMetaTable.jsindex 2ae9d4a67..49fa31912 100644--- a/tools/assetMetaTable.js+++ b/tools/assetMetaTable.js@@ -87,6 +87,7 @@ export const EXT_TO_TYPE = Object.freeze({'.estileset': 'tileset','.esfsm': 'statemachine','.esbt': 'behaviortree',+ '.esgraph': 'scriptgraph','.esanimator': 'animatorcontroller','.esavatar': 'avatar','.eslocale': 'locale',diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjsindex 7afd76361..f0c0e2955 100644--- a/tools/check-corpus-authoring.mjs+++ b/tools/check-corpus-authoring.mjs@@ -120,6 +120,7 @@ const DISPOSITION = {// — owed: a creator-facing component nothing in the shipped corpus authors.// Each reason names where the coverage belongs. —+ ScriptGraphAgent: ['owed', 'the script-graph editor is not landed yet, so no example can hold a `.esgraph` an author made; the coverage belongs in an example whose logic is a graph rather than a script'],};diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex fe7914463..f3f2868ff 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,15 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'feat(assets): a script graph is a live asset like the other authored graphs':+ { internal: 'The .esgraph asset slot. Nothing authors one yet — no panel, no new-asset entry.' },++ 'feat(assets): the Content Browser knows a .esgraph when it sees one':+ { internal: 'Badge and icon for an asset type nothing can create yet.' },++ 'feat(logic): an entity can carry a graph, and the graph can reach the world':+ { internal: 'The engine binding and the built-in value vocabulary. Still nothing authors a graph — the asset has no editor yet.' },+'feat(logic): a graph is nodes, wires, and one vocabulary it shares':{ internal: 'The script-graph core and the registry half it needs. Nothing authors one yet — no asset type, no component, no panel.' },