Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(render): material subgraphs — a graph used as one node of another, inlined at compile time

yhh3dfd21f6cabe
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3b30a1a2f..86f85d3d2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,7 +16,7 @@ published separately; it ships inside the editor.
### Changed
-- **Gizmos are redrawn.** The transform handles are larger and clearer: arrows have filled heads, rings dim on their far side, the scale handles are solid cubes, and the part under the cursor turns yellow while the others fall back as you drag. A chip beside the cursor reads the offset, angle or factor being applied (`X +120.0`, `Y 42.5°`, `X ×1.35`), a rotate drag fills the swept angle, a move leaves a ghost where it started and, with snapping on, ticks at each increment. The entity under the cursor is outlined faintly before you click it, and a selected entity's outline is a little heavier. A selected mesh shows corner brackets with the length of three edges and its triangle and vertex count in the readout, the Show menu can draw its wireframe and normals, and a skinned mesh or one of its bones shows the skeleton as bones with the chosen joint in yellow. A decal projector shows its box and the line it projects along, a light probe volume the grid of probes a bake would lay, a LOD group the level it is showing and the share of the screen it takes, and the Gizmo menu has a handle-size slider. A selected UI node shows its margin and padding as bands, the pinned insets of an absolutely placed node as dashed lines with their values, and a flex container's direction and the gaps between its children. The six faces of a light probe volume, reflection probe or decal projector are handles: drag one and that half of the box follows the cursor. A selected mesh is outlined along its own silhouette rather than a box, up to 80,000 triangles. The Show menu can draw wireframe on every mesh at once, and choosing a bone paints the surface it moves from blue to red, the rest left grey; convex colliders now draw with the other 3D colliders. A Hunter's attack range is drawn as a red ball, a Perceiver's sight as the cone it actually tests (a ball when its field of view is all round), and a ThirdPersonCamera's boom as a line from the point it looks at to where it ends up, with the probe swept along it as a ball at the end. A UI element drawn as 9-slice shows its picture under its Slice Border field with four guides to drag, as the texture inspector does; while the texture carries a border of its own, which the renderer prefers, it says so instead. A selected Spine or DragonBones entity shows its bones over the artwork as the 3D rigs do, laid where the runtime posed them this frame, with the entity's scale and flips applied; the Spine and DragonBones modules gained a call that lists the bone tree, so a module built before it still draws the skeleton and only the bones are absent. A selected tilemap layer reports its tile count and the size of the area its tiles cover in the viewport readout (`172 tiles · 32×17`), and on a square grid outlines that area, so an infinite layer's edge can be seen. The profiler is laid out as a module rail (Frame, CPU / GPU, Render, Counters, Memory, Systems, Spine) beside the module chosen: its timeline plots what the CPU was busy with and no longer the wait for the next frame, so a healthy window is no longer one flat block and a hitch is a tall column; clicking a column pins that frame and the strip beneath says in a sentence how far over budget it ran and where; the cost tree is a table of total, own cost and share of the frame, in columns; the toolbar is icon buttons with the live state as a pill. The frame debugger's draw list has column headers, a header per pass with its draw count, a swatch for each draw's type, a break-reason filter that starts with All, and the position of the selected draw in the capture. The sequencer's keyframes take the shape of how the curve leaves them (round smooth, diamond linear, square held, round with an arc eased) in the colour of their track, a group's row sums up the keys beneath it, each channel row shows its value at the playhead beside a swatch that is its curve's colour, the ruler marks seconds as well as frames, the playhead's flag carries the frame, the record button is red and the snap toggle says what it is; the curve view marks its grid and names the selected key's frame, value and interpolation. The sound event editor lists its variants as a table with each clip's waveform and the share of the draw its weight takes, groups its settings (playback, level and pitch, voices, space), draws volume and rate as ranges, plots the attenuation curve with the function the runtime uses, and leads its preview bar with the Trigger action. The Show menu also picks how the viewport shades meshes: as authored, as neutral clay (shape, without anyone's colours) or as flat albedo (base colour, no light); the engine takes it as per-view state, so a camera preview in the same frame keeps the authored look. A fourth shading, wireframe, draws every triangle edge on a dark surface with the hidden ones hidden; the engine's pipelines now carry a primitive topology, WebGL2 and WebGPU alike, and each mesh the editor loads keeps a line list of its distinct edges. Script graphs, material graphs and behavior trees share one node look: a header in the colour of what the node is for, an icon and a plain name with the stored id small beside it, round pins that are solid when wired and hollow when not (control pins are triangles), and wires coloured by the type they carry. A graph with no saved positions is laid out left to right when it opens and opens no smaller than half size, and an Arrange button lays any graph out again. A script graph's inputs, outputs and variables are a searchable list beside the canvas that shows how often each variable is read and written, lights the nodes that use the selected one, and lets you drag a variable onto the canvas to get or set it. The Lighting panel folds into groups with a short state beside each title, shows its warnings as a plain row with an amber edge rather than an amber box, and keeps the bake state, counts and the Bake button pinned at the bottom. The History panel draws a rule at the present, with undone steps below it. The scatter brush draws one real sample of itself to scale. The Plugins panel is a list grouped by origin, with search, beside the details of the plugin picked: its actions, declared capabilities, what it contributes and its health. The string table numbers its rows, marks a missing translation with an amber edge and totals its problems in a status bar. The Spine preview in the asset inspector uses the editor's own dropdowns and icon buttons, shows the time against the animation's length, and names the bounds drawn over it (fixed, unsaved, last scan). While a running game is inspected, the selected entity's outline carries its name, the move handles have arrowheads, and a chip beside the handle reads the position, turn or scale being applied. The Game panel says it is idle, starting or failed with an icon, and a failure shows its reason in a block that can be selected. The World panel is a short panel beside the Content Browser: a toolbar with the cell count and size, the persistent entities as a count that opens their list, and — while the game runs — what is in each residency state, the hit rate and the last demand-to-resident time; below it a table of cells with their entity count and, at runtime, state, prefetch result and demand-to-resident time, and the entities of the picked cell beside it. Picking a cell frames its entities in the viewport. The UI Widgets palette is a searchable list in groups (layout, display, input, popup, touch controls) with the Chinese name and the widget's own name on each row, instead of a grid of tiles. The UI debugger's four views are laid out alike: the Elements tree shows each element's main component and its picked element's size and components sit beside it; Text and Focus order are tables with a state dot per row and select on a click of the row; Events draws each dispatch's bubbling path as a chain from its target. Project Health's three counts filter the list, its findings are grouped by severity under folding headings, and the checks that could not run are listed with their reasons instead of in a tooltip. In the Agent panel each run's header carries a dot for how it came out (running, held, not held, stopped early, never checked), a run's steps hang on a rail with a dot each, the acceptance line is ruled off like the change set instead of boxed, and the key hints under the input show while you are typing. The Plugins panel lists the ids a plugin and another owner both claimed and who got them, filters the list to failed, awaiting-trust, incompatible or shadowed plugins, no longer offers a built-in plugin a trust withdrawal that cannot hold, and says what a plugin contributes before disabling it.
+- **Gizmos are redrawn.** The transform handles are larger and clearer: arrows have filled heads, rings dim on their far side, the scale handles are solid cubes, and the part under the cursor turns yellow while the others fall back as you drag. A chip beside the cursor reads the offset, angle or factor being applied (`X +120.0`, `Y 42.5°`, `X ×1.35`), a rotate drag fills the swept angle, a move leaves a ghost where it started and, with snapping on, ticks at each increment. The entity under the cursor is outlined faintly before you click it, and a selected entity's outline is a little heavier. A selected mesh shows corner brackets with the length of three edges and its triangle and vertex count in the readout, the Show menu can draw its wireframe and normals, and a skinned mesh or one of its bones shows the skeleton as bones with the chosen joint in yellow. A decal projector shows its box and the line it projects along, a light probe volume the grid of probes a bake would lay, a LOD group the level it is showing and the share of the screen it takes, and the Gizmo menu has a handle-size slider. A selected UI node shows its margin and padding as bands, the pinned insets of an absolutely placed node as dashed lines with their values, and a flex container's direction and the gaps between its children. The six faces of a light probe volume, reflection probe or decal projector are handles: drag one and that half of the box follows the cursor. A selected mesh is outlined along its own silhouette rather than a box, up to 80,000 triangles. The Show menu can draw wireframe on every mesh at once, and choosing a bone paints the surface it moves from blue to red, the rest left grey; convex colliders now draw with the other 3D colliders. A Hunter's attack range is drawn as a red ball, a Perceiver's sight as the cone it actually tests (a ball when its field of view is all round), and a ThirdPersonCamera's boom as a line from the point it looks at to where it ends up, with the probe swept along it as a ball at the end. A UI element drawn as 9-slice shows its picture under its Slice Border field with four guides to drag, as the texture inspector does; while the texture carries a border of its own, which the renderer prefers, it says so instead. A selected Spine or DragonBones entity shows its bones over the artwork as the 3D rigs do, laid where the runtime posed them this frame, with the entity's scale and flips applied; the Spine and DragonBones modules gained a call that lists the bone tree, so a module built before it still draws the skeleton and only the bones are absent. A selected tilemap layer reports its tile count and the size of the area its tiles cover in the viewport readout (`172 tiles · 32×17`), and on a square grid outlines that area, so an infinite layer's edge can be seen. The profiler is laid out as a module rail (Frame, CPU / GPU, Render, Counters, Memory, Systems, Spine) beside the module chosen: its timeline plots what the CPU was busy with and no longer the wait for the next frame, so a healthy window is no longer one flat block and a hitch is a tall column; clicking a column pins that frame and the strip beneath says in a sentence how far over budget it ran and where; the cost tree is a table of total, own cost and share of the frame, in columns; the toolbar is icon buttons with the live state as a pill. The frame debugger's draw list has column headers, a header per pass with its draw count, a swatch for each draw's type, a break-reason filter that starts with All, and the position of the selected draw in the capture. The sequencer's keyframes take the shape of how the curve leaves them (round smooth, diamond linear, square held, round with an arc eased) in the colour of their track, a group's row sums up the keys beneath it, each channel row shows its value at the playhead beside a swatch that is its curve's colour, the ruler marks seconds as well as frames, the playhead's flag carries the frame, the record button is red and the snap toggle says what it is; the curve view marks its grid and names the selected key's frame, value and interpolation. The sound event editor lists its variants as a table with each clip's waveform and the share of the draw its weight takes, groups its settings (playback, level and pitch, voices, space), draws volume and rate as ranges, plots the attenuation curve with the function the runtime uses, and leads its preview bar with the Trigger action. The Show menu also picks how the viewport shades meshes: as authored, as neutral clay (shape, without anyone's colours) or as flat albedo (base colour, no light); the engine takes it as per-view state, so a camera preview in the same frame keeps the authored look. A fourth shading, wireframe, draws every triangle edge on a dark surface with the hidden ones hidden; the engine's pipelines now carry a primitive topology, WebGL2 and WebGPU alike, and each mesh the editor loads keeps a line list of its distinct edges. Script graphs, material graphs and behavior trees share one node look: a header in the colour of what the node is for, an icon and a plain name with the stored id small beside it, round pins that are solid when wired and hollow when not (control pins are triangles), and wires coloured by the type they carry. A graph with no saved positions is laid out left to right when it opens and opens no smaller than half size, and an Arrange button lays any graph out again. A script graph's inputs, outputs and variables are a searchable list beside the canvas that shows how often each variable is read and written, lights the nodes that use the selected one, and lets you drag a variable onto the canvas to get or set it. The Lighting panel folds into groups with a short state beside each title, shows its warnings as a plain row with an amber edge rather than an amber box, and keeps the bake state, counts and the Bake button pinned at the bottom. The History panel draws a rule at the present, with undone steps below it. The scatter brush draws one real sample of itself to scale. The Plugins panel is a list grouped by origin, with search, beside the details of the plugin picked: its actions, declared capabilities, what it contributes and its health. The string table numbers its rows, marks a missing translation with an amber edge and totals its problems in a status bar. The Spine preview in the asset inspector uses the editor's own dropdowns and icon buttons, shows the time against the animation's length, and names the bounds drawn over it (fixed, unsaved, last scan). While a running game is inspected, the selected entity's outline carries its name, the move handles have arrowheads, and a chip beside the handle reads the position, turn or scale being applied. The Game panel says it is idle, starting or failed with an icon, and a failure shows its reason in a block that can be selected. The World panel is a short panel beside the Content Browser: a toolbar with the cell count and size, the persistent entities as a count that opens their list, and — while the game runs — what is in each residency state, the hit rate and the last demand-to-resident time; below it a table of cells with their entity count and, at runtime, state, prefetch result and demand-to-resident time, and the entities of the picked cell beside it. Picking a cell frames its entities in the viewport. The UI Widgets palette is a searchable list in groups (layout, display, input, popup, touch controls) with the Chinese name and the widget's own name on each row, instead of a grid of tiles. The UI debugger's four views are laid out alike: the Elements tree shows each element's main component and its picked element's size and components sit beside it; Text and Focus order are tables with a state dot per row and select on a click of the row; Events draws each dispatch's bubbling path as a chain from its target. Project Health's three counts filter the list, its findings are grouped by severity under folding headings, and the checks that could not run are listed with their reasons instead of in a tooltip. In the Agent panel each run's header carries a dot for how it came out (running, held, not held, stopped early, never checked), a run's steps hang on a rail with a dot each, the acceptance line is ruled off like the change set instead of boxed, and the key hints under the input show while you are typing. The Plugins panel lists the ids a plugin and another owner both claimed and who got them, filters the list to failed, awaiting-trust, incompatible or shadowed plugins, no longer offers a built-in plugin a trust withdrawal that cannot hold, and says what a plugin contributes before disabling it. A material graph can now use another graph as one node: a `.esmatsub` material subgraph has inputs (a name, a type and a default each) and one result, a graph that uses it fills the inputs by wire or by typing a number on the node, and the compiler inlines it, so one subgraph used twice makes two independent copies and saving a subgraph recompiles the shaders of the graphs that use it. New ones come from the Content Browser's New menu; the subgraph's own header says how many graphs use it.
- **A material's preview is a real shape.** Selecting a material shows it on a sphere, cube or plane (lit materials open on the sphere, sprite shaders on the plane), over a dark, checker or light background, with a sample image for shaders that sample a texture; the choice is remembered per kind. The header carries the ball as its icon and the name with a faint extension, the shader is a plain section with a link to make it unique, and the Content Browser's material thumbnails use the same preview. The engine's offscreen preview target now has a depth buffer, so a mesh drawn there is no longer drawn inside out.
- **The 2D animation editors are redrawn.** In the sprite animation editor the view's tools float over its corner, playback and the timeline are one panel, frame events are flags on an event track (click one to rename, move or remove it), the frame source folds into a strip that opens on an empty clip, and frame rate, loop and Save no longer appear a second time in the inspector. The animator controller shows states as cards with their clip and speed, wires between a pair of states run side by side with a pill for the condition (dashed when it waits for the exit time), and its inspector puts the selected state or transition first, with the controller's layers, typed parameters and a folded constraints section below.
- **The tile editor matches its design.** The layer and tileset menus sit on the raised surface, a picked tile has a 2px frame and shows its id on hover, the brush column shows the tile id, the replace dialog's button says Replace, and the tileset inspector shows one-way and trigger as switches, the layer opacity is a slim slider, and a collision layer's friction and bounce fields are flat with their own heading.
diff --git a/desktop b/desktop
index 9476179c6..efa604a29 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 9476179c6173b098a6bda4d9cc8dde0663704d7f
+Subproject commit efa604a290fe0552fd7e102d135dd06282c8b3dc
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 564dca413..711395d58 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: 115 public · 109 beta · 1604 experimental · 3 deprecated
+Symbols: 115 public · 116 beta · 1604 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -4230,6 +4230,10 @@ PlatformImage | PlatformCanvas | ImageBitmap
## GraphNodeType — type @beta
```
| 'output' // the root: its `color` input becomes fragColor
+ | 'subgraph' // another graph used as one node (inlined before compile)
+ | 'subInput' // inside a subgraph: one of its inputs, read by the nodes that use it
+ | 'subOutput' // inside a subgraph: its result
+ | 'literal' // a constant the compiler makes when a subgraph input is left unconnected
| 'uv' // v_texCoord
| 'vertexColor' // v_color (the sprite's per-instance tint)
| 'time' // u_time.x — the injected engine frame clock (seconds)
@@ -5172,6 +5176,7 @@ uniforms: Map<string, UniformValue>
## MaterialGraph — interface @beta
```
domain: string | undefined
+kind: "subgraph" | undefined
name: string | undefined
nodes: MaterialGraphNode[]
output: string
@@ -8628,6 +8633,18 @@ Birth = 1
Death = 0
```
+## SubgraphInput — interface @beta
+```
+default: number
+name: string
+type: GraphType
+```
+
+## SubgraphResolver — type @beta
+```
+(ref: string) => MaterialGraph | null
+```
+
## SubsystemActivity — type @experimental
```
'stepping' | 'idle' | 'inactive'
@@ -11059,7 +11076,7 @@ MotionDriver<AnimatorBlend2DMotion>
## compileMaterialGraph — function @beta
```
-(graph: MaterialGraph): string
+(source: MaterialGraph, resolve?: SubgraphResolver): string
```
## composeTRS — function @experimental
@@ -11662,6 +11679,11 @@ EventBindingPlugin
(prefab: PrefabData, overrides: PrefabOverride[], ctx: FlattenContext): FlattenResult
```
+## flattenSubgraphs — function @beta
+```
+(graph: MaterialGraph, resolve: SubgraphResolver, stack?: readonly string[]): MaterialGraph
+```
+
## flushPendingRegistrations — function @experimental
```
(app: App): void
@@ -12322,6 +12344,11 @@ MeshRendererPlugin
(): MaterialGraph
```
+## newMaterialSubgraph — function @beta
+```
+(): MaterialGraph
+```
+
## noInput — const @experimental
```
() => InputState
@@ -13377,6 +13404,16 @@ StatsPlugin
(entities: readonly EnvironmentLightEntity[], exists: (ref: string) => boolean): StudioPreviewReport
```
+## subgraphInputs — function @beta
+```
+(sub: MaterialGraph): SubgraphInput[]
+```
+
+## subgraphRefs — function @beta
+```
+(graph: MaterialGraph): string[]
+```
+
## summarizeCapture — function @experimental
```
(capture: ProfileCapture): CaptureSummary
@@ -13612,6 +13649,11 @@ UIVisibilityPlugin
(scene: SceneData): DocumentDiagnostic[]
```
+## validateSubgraph — function @beta
+```
+(sub: MaterialGraph, resolve: SubgraphResolver): void
+```
+
## vec2 — const @experimental
```
(x?: number, y?: number) => Vec2
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 439f5a47e..54c32eb44 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: 115 public · 114 beta · 1623 experimental · 3 deprecated
+Symbols: 115 public · 121 beta · 1623 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -4238,6 +4238,10 @@ PlatformImage | PlatformCanvas | ImageBitmap
## GraphNodeType — type @beta
```
| 'output' // the root: its `color` input becomes fragColor
+ | 'subgraph' // another graph used as one node (inlined before compile)
+ | 'subInput' // inside a subgraph: one of its inputs, read by the nodes that use it
+ | 'subOutput' // inside a subgraph: its result
+ | 'literal' // a constant the compiler makes when a subgraph input is left unconnected
| 'uv' // v_texCoord
| 'vertexColor' // v_color (the sprite's per-instance tint)
| 'time' // u_time.x — the injected engine frame clock (seconds)
@@ -5180,6 +5184,7 @@ uniforms: Map<string, UniformValue>
## MaterialGraph — interface @beta
```
domain: string | undefined
+kind: "subgraph" | undefined
name: string | undefined
nodes: MaterialGraphNode[]
output: string
@@ -8841,6 +8846,18 @@ Birth = 1
Death = 0
```
+## SubgraphInput — interface @beta
+```
+default: number
+name: string
+type: GraphType
+```
+
+## SubgraphResolver — type @beta
+```
+(ref: string) => MaterialGraph | null
+```
+
## SubsystemActivity — type @experimental
```
'stepping' | 'idle' | 'inactive'
@@ -11287,7 +11304,7 @@ MotionDriver<AnimatorBlend2DMotion>
## compileMaterialGraph — function @beta
```
-(graph: MaterialGraph): string
+(source: MaterialGraph, resolve?: SubgraphResolver): string
```
## composeTRS — function @experimental
@@ -11915,6 +11932,11 @@ EventBindingPlugin
(prefab: PrefabData, overrides: PrefabOverride[], ctx: FlattenContext): FlattenResult
```
+## flattenSubgraphs — function @beta
+```
+(graph: MaterialGraph, resolve: SubgraphResolver, stack?: readonly string[]): MaterialGraph
+```
+
## flushPendingRegistrations — function @experimental
```
(app: App): void
@@ -12585,6 +12607,11 @@ MeshRendererPlugin
(): MaterialGraph
```
+## newMaterialSubgraph — function @beta
+```
+(): MaterialGraph
+```
+
## noInput — const @experimental
```
() => InputState
@@ -13640,6 +13667,16 @@ StatsPlugin
(entities: readonly EnvironmentLightEntity[], exists: (ref: string) => boolean): StudioPreviewReport
```
+## subgraphInputs — function @beta
+```
+(sub: MaterialGraph): SubgraphInput[]
+```
+
+## subgraphRefs — function @beta
+```
+(graph: MaterialGraph): string[]
+```
+
## summarizeCapture — function @experimental
```
(capture: ProfileCapture): CaptureSummary
@@ -13875,6 +13912,11 @@ UIVisibilityPlugin
(scene: SceneData): DocumentDiagnostic[]
```
+## validateSubgraph — function @beta
+```
+(sub: MaterialGraph, resolve: SubgraphResolver): void
+```
+
## vec2 — const @experimental
```
(x?: number, y?: number) => Vec2
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index b777dcd7f..d6d005b4e 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: 115 public · 111 beta · 1603 experimental · 3 deprecated
+Symbols: 115 public · 118 beta · 1603 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -4225,6 +4225,10 @@ PlatformImage | PlatformCanvas | ImageBitmap
## GraphNodeType — type @beta
```
| 'output' // the root: its `color` input becomes fragColor
+ | 'subgraph' // another graph used as one node (inlined before compile)
+ | 'subInput' // inside a subgraph: one of its inputs, read by the nodes that use it
+ | 'subOutput' // inside a subgraph: its result
+ | 'literal' // a constant the compiler makes when a subgraph input is left unconnected
| 'uv' // v_texCoord
| 'vertexColor' // v_color (the sprite's per-instance tint)
| 'time' // u_time.x — the injected engine frame clock (seconds)
@@ -5167,6 +5171,7 @@ uniforms: Map<string, UniformValue>
## MaterialGraph — interface @beta
```
domain: string | undefined
+kind: "subgraph" | undefined
name: string | undefined
nodes: MaterialGraphNode[]
output: string
@@ -8623,6 +8628,18 @@ Birth = 1
Death = 0
```
+## SubgraphInput — interface @beta
+```
+default: number
+name: string
+type: GraphType
+```
+
+## SubgraphResolver — type @beta
+```
+(ref: string) => MaterialGraph | null
+```
+
## SubsystemActivity — type @experimental
```
'stepping' | 'idle' | 'inactive'
@@ -11054,7 +11071,7 @@ MotionDriver<AnimatorBlend2DMotion>
## compileMaterialGraph — function @beta
```
-(graph: MaterialGraph): string
+(source: MaterialGraph, resolve?: SubgraphResolver): string
```
## composeTRS — function @experimental
@@ -11657,6 +11674,11 @@ EventBindingPlugin
(prefab: PrefabData, overrides: PrefabOverride[], ctx: FlattenContext): FlattenResult
```
+## flattenSubgraphs — function @beta
+```
+(graph: MaterialGraph, resolve: SubgraphResolver, stack?: readonly string[]): MaterialGraph
+```
+
## flushPendingRegistrations — function @experimental
```
(app: App): void
@@ -12322,6 +12344,11 @@ MeshRendererPlugin
(): MaterialGraph
```
+## newMaterialSubgraph — function @beta
+```
+(): MaterialGraph
+```
+
## noInput — const @experimental
```
() => InputState
@@ -13382,6 +13409,16 @@ StatsPlugin
(entities: readonly EnvironmentLightEntity[], exists: (ref: string) => boolean): StudioPreviewReport
```
+## subgraphInputs — function @beta
+```
+(sub: MaterialGraph): SubgraphInput[]
+```
+
+## subgraphRefs — function @beta
+```
+(graph: MaterialGraph): string[]
+```
+
## summarizeCapture — function @experimental
```
(capture: ProfileCapture): CaptureSummary
@@ -13617,6 +13654,11 @@ UIVisibilityPlugin
(scene: SceneData): DocumentDiagnostic[]
```
+## validateSubgraph — function @beta
+```
+(sub: MaterialGraph, resolve: SubgraphResolver): void
+```
+
## vec2 — const @experimental
```
(x?: number, y?: number) => Vec2
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index d59c0ec88..542d2428a 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: 115 public · 109 beta · 1625 experimental · 3 deprecated
+Symbols: 115 public · 116 beta · 1625 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -4225,6 +4225,10 @@ PlatformImage | PlatformCanvas | ImageBitmap
## GraphNodeType — type @beta
```
| 'output' // the root: its `color` input becomes fragColor
+ | 'subgraph' // another graph used as one node (inlined before compile)
+ | 'subInput' // inside a subgraph: one of its inputs, read by the nodes that use it
+ | 'subOutput' // inside a subgraph: its result
+ | 'literal' // a constant the compiler makes when a subgraph input is left unconnected
| 'uv' // v_texCoord
| 'vertexColor' // v_color (the sprite's per-instance tint)
| 'time' // u_time.x — the injected engine frame clock (seconds)
@@ -5167,6 +5171,7 @@ uniforms: Map<string, UniformValue>
## MaterialGraph — interface @beta
```
domain: string | undefined
+kind: "subgraph" | undefined
name: string | undefined
nodes: MaterialGraphNode[]
output: string
@@ -8916,6 +8921,18 @@ Birth = 1
Death = 0
```
+## SubgraphInput — interface @beta
+```
+default: number
+name: string
+type: GraphType
+```
+
+## SubgraphResolver — type @beta
+```
+(ref: string) => MaterialGraph | null
+```
+
## SubsystemActivity — type @experimental
```
'stepping' | 'idle' | 'inactive'
@@ -11353,7 +11370,7 @@ MotionDriver<AnimatorBlend2DMotion>
## compileMaterialGraph — function @beta
```
-(graph: MaterialGraph): string
+(source: MaterialGraph, resolve?: SubgraphResolver): string
```
## composeTRS — function @experimental
@@ -11961,6 +11978,11 @@ EventBindingPlugin
(prefab: PrefabData, overrides: PrefabOverride[], ctx: FlattenContext): FlattenResult
```
+## flattenSubgraphs — function @beta
+```
+(graph: MaterialGraph, resolve: SubgraphResolver, stack?: readonly string[]): MaterialGraph
+```
+
## flushPendingRegistrations — function @experimental
```
(app: App): void
@@ -12631,6 +12653,11 @@ MeshRendererPlugin
(): MaterialGraph
```
+## newMaterialSubgraph — function @beta
+```
+(): MaterialGraph
+```
+
## noInput — const @experimental
```
() => InputState
@@ -13686,6 +13713,16 @@ StatsPlugin
(entities: readonly EnvironmentLightEntity[], exists: (ref: string) => boolean): StudioPreviewReport
```
+## subgraphInputs — function @beta
+```
+(sub: MaterialGraph): SubgraphInput[]
+```
+
+## subgraphRefs — function @beta
+```
+(graph: MaterialGraph): string[]
+```
+
## summarizeCapture — function @experimental
```
(capture: ProfileCapture): CaptureSummary
@@ -13921,6 +13958,11 @@ UIVisibilityPlugin
(scene: SceneData): DocumentDiagnostic[]
```
+## validateSubgraph — function @beta
+```
+(sub: MaterialGraph, resolve: SubgraphResolver): void
+```
+
## vec2 — const @experimental
```
(x?: number, y?: number) => Vec2
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 3e3e43a3e..f1ce33415 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: 115 public · 109 beta · 1616 experimental · 3 deprecated
+Symbols: 115 public · 116 beta · 1616 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -4225,6 +4225,10 @@ PlatformImage | PlatformCanvas | ImageBitmap
## GraphNodeType — type @beta
```
| 'output' // the root: its `color` input becomes fragColor
+ | 'subgraph' // another graph used as one node (inlined before compile)
+ | 'subInput' // inside a subgraph: one of its inputs, read by the nodes that use it
+ | 'subOutput' // inside a subgraph: its result
+ | 'literal' // a constant the compiler makes when a subgraph input is left unconnected
| 'uv' // v_texCoord
| 'vertexColor' // v_color (the sprite's per-instance tint)
| 'time' // u_time.x — the injected engine frame clock (seconds)
@@ -5174,6 +5178,7 @@ uniforms: Map<string, UniformValue>
## MaterialGraph — interface @beta
```
domain: string | undefined
+kind: "subgraph" | undefined
name: string | undefined
nodes: MaterialGraphNode[]
output: string
@@ -8630,6 +8635,18 @@ Birth = 1
Death = 0
```
+## SubgraphInput — interface @beta
+```
+default: number
+name: string
+type: GraphType
+```
+
+## SubgraphResolver — type @beta
+```
+(ref: string) => MaterialGraph | null
+```
+
## SubsystemActivity — type @experimental
```
'stepping' | 'idle' | 'inactive'
@@ -11085,7 +11102,7 @@ MotionDriver<AnimatorBlend2DMotion>
## compileMaterialGraph — function @beta
```
-(graph: MaterialGraph): string
+(source: MaterialGraph, resolve?: SubgraphResolver): string
```
## composeTRS — function @experimental
@@ -11688,6 +11705,11 @@ EventBindingPlugin
(prefab: PrefabData, overrides: PrefabOverride[], ctx: FlattenContext): FlattenResult
```
+## flattenSubgraphs — function @beta
+```
+(graph: MaterialGraph, resolve: SubgraphResolver, stack?: readonly string[]): MaterialGraph
+```
+
## flushPendingRegistrations — function @experimental
```
(app: App): void
@@ -12358,6 +12380,11 @@ MeshRendererPlugin
(): MaterialGraph
```
+## newMaterialSubgraph — function @beta
+```
+(): MaterialGraph
+```
+
## noInput — const @experimental
```
() => InputState
@@ -13413,6 +13440,16 @@ StatsPlugin
(entities: readonly EnvironmentLightEntity[], exists: (ref: string) => boolean): StudioPreviewReport
```
+## subgraphInputs — function @beta
+```
+(sub: MaterialGraph): SubgraphInput[]
+```
+
+## subgraphRefs — function @beta
+```
+(graph: MaterialGraph): string[]
+```
+
## summarizeCapture — function @experimental
```
(capture: ProfileCapture): CaptureSummary
@@ -13648,6 +13685,11 @@ UIVisibilityPlugin
(scene: SceneData): DocumentDiagnostic[]
```
+## validateSubgraph — function @beta
+```
+(sub: MaterialGraph, resolve: SubgraphResolver): void
+```
+
## vec2 — const @experimental
```
(x?: number, y?: number) => Vec2
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index da37dc93f..4faeb4e7f 100644
--- a/sdk/src/core-render.ts
+++ b/sdk/src/core-render.ts
@@ -121,6 +121,11 @@ export {
export {
compileMaterialGraph,
newMaterialGraph,
+ newMaterialSubgraph,
+ flattenSubgraphs,
+ subgraphInputs,
+ subgraphRefs,
+ validateSubgraph,
addNode,
moveNode,
connect,
@@ -129,6 +134,8 @@ export {
NODE_SPECS,
type MaterialGraph,
type MaterialGraphNode,
+ type SubgraphResolver,
+ type SubgraphInput,
type GraphNodeType,
type GraphType,
type NodeSpec,
diff --git a/sdk/src/render/materialGraph.ts b/sdk/src/render/materialGraph.ts
index 8927a177a..3104b401c 100644
--- a/sdk/src/render/materialGraph.ts
+++ b/sdk/src/render/materialGraph.ts
@@ -22,6 +22,10 @@ import { RENAMED_DOMAINS } from './shaderReflect';
export type GraphNodeType =
| 'output' // the root: its `color` input becomes fragColor
+ | 'subgraph' // another graph used as one node (inlined before compile)
+ | 'subInput' // inside a subgraph: one of its inputs, read by the nodes that use it
+ | 'subOutput' // inside a subgraph: its result
+ | 'literal' // a constant the compiler makes when a subgraph input is left unconnected
| 'uv' // v_texCoord
| 'vertexColor' // v_color (the sprite's per-instance tint)
| 'time' // u_time.x — the injected engine frame clock (seconds)
@@ -52,6 +56,8 @@ export interface MaterialGraphNode {
}
export interface MaterialGraph {
+ /** `'subgraph'` for a `.esmatsub` — a graph meant to be used as a node, ending in a `subOutput`. */
+ kind?: 'subgraph';
name?: string;
/** Material domain (Unlit default; Lit etc. flow through unchanged, under its current name). */
domain?: string;
@@ -104,7 +110,9 @@ interface Emitted {
* either backend. Throws on a missing node/input, a cycle, an unknown node type, or an
* output root that isn't an `output` node.
*/
-export function compileMaterialGraph(graph: MaterialGraph): string {
+export function compileMaterialGraph(source: MaterialGraph, resolve?: SubgraphResolver): string {
+ const graph = resolve ? flattenSubgraphs(source, resolve) : source;
+ if (graph.nodes.some((n) => n.type === 'subgraph')) throw new Error('material graph: a subgraph node needs a resolver to compile');
const nodes = new Map(graph.nodes.map((n) => [n.id, n] as const));
const memo = new Map<string, Emitted>();
const visiting = new Set<string>();
@@ -255,6 +263,24 @@ export function compileMaterialGraph(graph: MaterialGraph): string {
`fract(${uv.wexpr} + tc.u_time.x * vec2f(${sx}, ${sy}))`);
break;
}
+ case 'literal': {
+ const v = typeof n.params?.value === 'number' && Number.isFinite(n.params.value) ? n.params.value : 0;
+ const ty = (['float', 'vec2', 'vec3', 'vec4'] as const).find((t) => t === n.params?.type) ?? 'float';
+ const f = v.toFixed(4);
+ out = ty === 'float'
+ ? { expr: f, wexpr: f, type: 'float' }
+ : { expr: `${ty}(${f})`, wexpr: `${WGSL_TYPE[ty]}(${f})`, type: ty };
+ break;
+ }
+ case 'subInput': {
+ // Only reached compiling a subgraph on its own (validation): it reads as its default.
+ const inp = subgraphInputs({ nodes: [n], output: n.id })[0]!;
+ const f = inp.default.toFixed(4);
+ out = inp.type === 'float'
+ ? { expr: f, wexpr: f, type: 'float' }
+ : { expr: `${inp.type}(${f})`, wexpr: `${WGSL_TYPE[inp.type]}(${f})`, type: inp.type };
+ break;
+ }
case 'output': {
const c = input('color');
out = { expr: toVec4(c.expr, c.type), wexpr: toVec4W(c.wexpr, c.type), type: 'vec4' };
@@ -360,6 +386,11 @@ export interface NodeSpec {
}
export const NODE_SPECS: Record<GraphNodeType, NodeSpec> = {
+ // The ports of these three come from the subgraph a node names, so their specs are placeholders.
+ subgraph: { label: 'Subgraph', inputs: [], output: 'float', params: [], addable: false },
+ subInput: { label: 'Subgraph Input', inputs: [], output: 'float', params: [], addable: false },
+ subOutput: { label: 'Subgraph Output', inputs: [{ name: 'value', type: 'float' }], output: null, params: [], addable: false },
+ literal: { label: 'Literal', inputs: [], output: 'float', params: [], addable: false },
output: { label: 'Output', inputs: [{ name: 'color', type: 'vec4' }], output: null, params: [], addable: false },
uv: { label: 'UV', inputs: [], output: 'vec2', params: [], addable: true },
vertexColor: { label: 'Vertex Color', inputs: [], output: 'vec4', params: [], addable: true },
@@ -434,6 +465,124 @@ export function moveNode(g: MaterialGraph, id: string, x: number, y: number): Ma
return next;
}
+// =============================================================================
+// Subgraphs: a graph used as one node, inlined before compile
+// =============================================================================
+
+/** How a graph finds a subgraph it names: by the `ref` its `subgraph` node carries. Null = not found. */
+export type SubgraphResolver = (ref: string) => MaterialGraph | null;
+
+/** One input a subgraph takes, read from its `subInput` nodes — what a node using it shows as ports. */
+export interface SubgraphInput {
+ /** The node id inside the subgraph, and the slot name on a `subgraph` node that uses it. */
+ name: string;
+ type: GraphType;
+ /** What an unconnected input reads as, unless the using node overrides it with `params["in_<name>"]`. */
+ default: number;
+}
+
+const MAX_SUBGRAPH_DEPTH = 8;
+
+/** The inputs a subgraph exposes, in the order its nodes list them. */
+export function subgraphInputs(sub: MaterialGraph): SubgraphInput[] {
+ const out: SubgraphInput[] = [];
+ for (const n of sub.nodes) {
+ if (n.type !== 'subInput') continue;
+ const name = typeof n.params?.name === 'string' && n.params.name ? n.params.name : n.id;
+ const type = (['float', 'vec2', 'vec3', 'vec4'] as const).find((t) => t === n.params?.type) ?? 'float';
+ out.push({ name, type, default: typeof n.params?.default === 'number' ? n.params.default : 0 });
+ }
+ return out;
+}
+
+/** The `ref`s a graph names, directly (not through the subgraphs those name). */
+export function subgraphRefs(graph: MaterialGraph): string[] {
+ return [...new Set(graph.nodes.filter((n) => n.type === 'subgraph').map((n) => String(n.params?.ref ?? '')).filter(Boolean))];
+}
+
+/**
+ * Replace every `subgraph` node with the nodes of the graph it names, so the compiler only ever sees
+ * plain nodes. An unconnected input becomes a literal (the subgraph's default, or the using node's
+ * `in_<name>`); a connected one is the wire itself. Ids and explicit param names are prefixed with the
+ * using node's id, so one subgraph used twice makes two independent copies — not one shared param.
+ * Throws on a missing subgraph, a subgraph that contains itself, or nesting past 8 levels.
+ */
+export function flattenSubgraphs(graph: MaterialGraph, resolve: SubgraphResolver, stack: readonly string[] = []): MaterialGraph {
+ if (!graph.nodes.some((n) => n.type === 'subgraph')) return graph;
+ const nodes: MaterialGraphNode[] = [];
+ const alias = new Map<string, string>();
+ for (const n of graph.nodes) {
+ if (n.type !== 'subgraph') {
+ nodes.push({ ...n, inputs: n.inputs ? { ...n.inputs } : undefined });
+ continue;
+ }
+ const ref = typeof n.params?.ref === 'string' ? n.params.ref : '';
+ if (!ref) throw new Error(`material graph: subgraph node "${n.id}" names no subgraph`);
+ if (stack.includes(ref)) throw new Error(`material graph: subgraph "${ref}" contains itself`);
+ if (stack.length >= MAX_SUBGRAPH_DEPTH) throw new Error(`material graph: subgraphs nested deeper than ${MAX_SUBGRAPH_DEPTH}`);
+ const sub = resolve(ref);
+ if (!sub) throw new Error(`material graph: subgraph "${ref}" (node "${n.id}") not found`);
+ const flat = flattenSubgraphs(sub, resolve, [...stack, ref]);
+ const pre = (id: string): string => `${n.id}__${id}`;
+ for (const sn of flat.nodes) {
+ if (sn.type === 'subInput') {
+ const inp = subgraphInputs({ ...flat, nodes: [sn] })[0]!;
+ const src = n.inputs?.[inp.name];
+ if (src) alias.set(pre(sn.id), src);
+ else {
+ const over = n.params?.[`in_${inp.name}`];
+ nodes.push({ id: pre(sn.id), type: 'literal', params: { value: typeof over === 'number' ? over : inp.default, type: inp.type } });
+ }
+ } else if (sn.type === 'subOutput') {
+ const value = sn.inputs?.value;
+ if (!value) throw new Error(`material graph: subgraph "${ref}" has no value connected to its output`);
+ alias.set(n.id, pre(value));
+ } else {
+ const params = sn.params ? { ...sn.params } : undefined;
+ if (params && typeof params.name === 'string' && params.name) params.name = `${n.id}_${params.name}`;
+ const inputs = sn.inputs ? Object.fromEntries(Object.entries(sn.inputs).map(([k, v]) => [k, pre(v)])) : undefined;
+ nodes.push({ ...sn, id: pre(sn.id), params, inputs });
+ }
+ }
+ }
+ const settle = (id: string): string => {
+ for (let i = 0; i < 64 && alias.has(id); i++) id = alias.get(id)!;
+ return id;
+ };
+ for (const n of nodes) {
+ if (!n.inputs) continue;
+ for (const [k, v] of Object.entries(n.inputs)) n.inputs[k] = settle(v);
+ }
+ // A subgraph used inside another is expanded in the recursive call, so none remain here.
+ return flattenSubgraphs({ ...graph, output: settle(graph.output), nodes }, resolve, stack);
+}
+
+/** A starter subgraph: one input, passed straight through. */
+export function newMaterialSubgraph(): MaterialGraph {
+ return {
+ kind: 'subgraph',
+ name: 'Subgraph',
+ output: 'out',
+ nodes: [
+ { id: 'in1', type: 'subInput', x: 60, y: 80, params: { name: 'value', type: 'float', default: 0 } },
+ { id: 'out', type: 'subOutput', x: 360, y: 80, inputs: { value: 'in1' } },
+ ],
+ };
+}
+
+/** Whether @p sub compiles when used — checked by wrapping its output in a throwaway material output. */
+export function validateSubgraph(sub: MaterialGraph, resolve: SubgraphResolver): void {
+ const probe: MaterialGraph = {
+ name: 'probe', output: 'probe_out',
+ nodes: [...sub.nodes.map((n) => ({ ...n })), { id: 'probe_out', type: 'output', inputs: { color: sub.output } }],
+ };
+ // The subOutput is a pass-through of its `value`; point the probe at that value directly.
+ const so = sub.nodes.find((n) => n.id === sub.output && n.type === 'subOutput');
+ if (!so) throw new Error('material graph: a subgraph\'s `output` must reference a "subOutput" node');
+ probe.nodes[probe.nodes.length - 1]!.inputs = { color: so.inputs?.value ?? '' };
+ compileMaterialGraph(probe, resolve);
+}
+
/** Whether a path from @p fromId back to @p toId exists (so connecting them would loop). */
function reaches(g: MaterialGraph, fromId: string, toId: string): boolean {
const byId = new Map(g.nodes.map((n) => [n.id, n] as const));
@@ -458,7 +607,8 @@ function reaches(g: MaterialGraph, fromId: string, toId: string): boolean {
export function connect(g: MaterialGraph, fromId: string, toId: string, toSlot: string): MaterialGraph {
if (fromId === toId) return g;
const to = g.nodes.find((n) => n.id === toId);
- if (!to || !NODE_SPECS[to.type].inputs.some((p) => p.name === toSlot)) return g;
+ // A subgraph node's slots are the inputs of the graph it names — checked when it compiles.
+ if (!to || (to.type !== 'subgraph' && !NODE_SPECS[to.type].inputs.some((p) => p.name === toSlot))) return g;
if (reaches(g, fromId, toId)) return g; // the source already depends on the target → cycle
const next = clone(g);
const n = next.nodes.find((m) => m.id === toId)!;
diff --git a/sdk/tests/materialSubgraph.test.ts b/sdk/tests/materialSubgraph.test.ts
new file mode 100644
index 000000000..073065e73
--- /dev/null
+++ b/sdk/tests/materialSubgraph.test.ts
@@ -0,0 +1,105 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import {
+ compileMaterialGraph, flattenSubgraphs, subgraphInputs, subgraphRefs, validateSubgraph, newMaterialSubgraph, connect,
+ type MaterialGraph, type SubgraphResolver,
+} from '../src/render/materialGraph';
+
+// wind(time, strength) = sin(time) * strength
+const wind: MaterialGraph = {
+ kind: 'subgraph', name: 'Wind', output: 'out',
+ nodes: [
+ { id: 'time', type: 'subInput', params: { name: 'time', type: 'float', default: 0 } },
+ { id: 'strength', type: 'subInput', params: { name: 'strength', type: 'float', default: 0.5 } },
+ { id: 'sin', type: 'sin', inputs: { x: 'time' } },
+ { id: 'mul', type: 'multiply', inputs: { a: 'sin', b: 'strength' } },
+ { id: 'out', type: 'subOutput', inputs: { value: 'mul' } },
+ ],
+};
+const libs: Record<string, MaterialGraph> = { 'wind.esmatsub': wind };
+const resolve: SubgraphResolver = (ref) => libs[ref] ?? null;
+
+const user = (over: Partial<MaterialGraph['nodes'][number]> = {}): MaterialGraph => ({
+ name: 'Leaf', output: 'out',
+ nodes: [
+ { id: 't', type: 'time' },
+ { id: 'w', type: 'subgraph', params: { ref: 'wind.esmatsub' }, inputs: { time: 't' }, ...over },
+ { id: 'out', type: 'output', inputs: { color: 'w' } },
+ ],
+});
+
+describe('subgraphs', () => {
+ it('lists a subgraph\'s inputs with their defaults', () => {
+ expect(subgraphInputs(wind)).toEqual([
+ { name: 'time', type: 'float', default: 0 }, { name: 'strength', type: 'float', default: 0.5 },
+ ]);
+ });
+
+ it('inlines the subgraph: a connected input is the wire, an unconnected one its default', () => {
+ const src = compileMaterialGraph(user(), resolve);
+ expect(src).toContain('sin(u_time.x)');
+ expect(src).toContain('0.5000');
+ });
+
+ it('lets the using node override an unconnected input', () => {
+ const src = compileMaterialGraph(user({ params: { ref: 'wind.esmatsub', in_strength: 0.9 } }), resolve);
+ expect(src).toContain('0.9000');
+ expect(src).not.toContain('0.5000');
+ });
+
+ it('makes independent copies when used twice — their param names do not collide', () => {
+ const tex: MaterialGraph = { kind: 'subgraph', output: 'out', nodes: [
+ { id: 'c', type: 'constFloat', params: { name: 'u_amount', value: 1 } },
+ { id: 'out', type: 'subOutput', inputs: { value: 'c' } },
+ ] };
+ const g: MaterialGraph = { output: 'out', nodes: [
+ { id: 'a', type: 'subgraph', params: { ref: 'amount.esmatsub' } },
+ { id: 'b', type: 'subgraph', params: { ref: 'amount.esmatsub' } },
+ { id: 'm', type: 'multiply', inputs: { a: 'a', b: 'b' } },
+ { id: 'out', type: 'output', inputs: { color: 'm' } },
+ ] };
+ const src = compileMaterialGraph(g, (r) => (r === 'amount.esmatsub' ? tex : null));
+ expect(src).toContain('#pragma param a_u_amount float');
+ expect(src).toContain('#pragma param b_u_amount float');
+ });
+
+ it('flattens nested subgraphs', () => {
+ const outer: MaterialGraph = { kind: 'subgraph', output: 'out', nodes: [
+ { id: 'in', type: 'subInput', params: { name: 'time', type: 'float', default: 0 } },
+ { id: 'inner', type: 'subgraph', params: { ref: 'wind.esmatsub' }, inputs: { time: 'in' } },
+ { id: 'out', type: 'subOutput', inputs: { value: 'inner' } },
+ ] };
+ const g: MaterialGraph = { output: 'out', nodes: [
+ { id: 't', type: 'time' },
+ { id: 'o', type: 'subgraph', params: { ref: 'outer.esmatsub' }, inputs: { time: 't' } },
+ { id: 'out', type: 'output', inputs: { color: 'o' } },
+ ] };
+ const flat = flattenSubgraphs(g, (r) => (r === 'outer.esmatsub' ? outer : libs[r] ?? null));
+ expect(flat.nodes.some((n) => n.type === 'subgraph')).toBe(false);
+ expect(compileMaterialGraph(g, (r) => (r === 'outer.esmatsub' ? outer : libs[r] ?? null))).toContain('sin(u_time.x)');
+ });
+
+ it('refuses a subgraph that contains itself, a missing one, and a graph compiled without a resolver', () => {
+ const self: MaterialGraph = { kind: 'subgraph', output: 'out', nodes: [
+ { id: 's', type: 'subgraph', params: { ref: 'self.esmatsub' } }, { id: 'out', type: 'subOutput', inputs: { value: 's' } },
+ ] };
+ const g: MaterialGraph = { output: 'out', nodes: [{ id: 's', type: 'subgraph', params: { ref: 'self.esmatsub' } }, { id: 'out', type: 'output', inputs: { color: 's' } }] };
+ expect(() => compileMaterialGraph(g, (r) => (r === 'self.esmatsub' ? self : null))).toThrow(/contains itself/);
+ expect(() => compileMaterialGraph(user(), () => null)).toThrow(/not found/);
+ expect(() => compileMaterialGraph(user())).toThrow(/needs a resolver/);
+ });
+
+ it('validates a subgraph on its own, and rejects one with no value on its output', () => {
+ expect(() => validateSubgraph(wind, resolve)).not.toThrow();
+ expect(() => validateSubgraph(newMaterialSubgraph(), resolve)).not.toThrow();
+ const broken: MaterialGraph = { ...wind, nodes: wind.nodes.map((n) => (n.id === 'out' ? { ...n, inputs: {} } : n)) };
+ expect(() => validateSubgraph(broken, resolve)).toThrow();
+ });
+
+ it('lists the refs a graph names and connects into a subgraph node by any slot', () => {
+ expect(subgraphRefs(user())).toEqual(['wind.esmatsub']);
+ const g = connect(user(), 't', 'w', 'strength');
+ expect(g.nodes.find((n) => n.id === 'w')!.inputs).toEqual({ time: 't', strength: 't' });
+ });
+});
diff --git a/tools/assetMetaTable.js b/tools/assetMetaTable.js
index 617f297d1..cd0f287e1 100644
--- a/tools/assetMetaTable.js
+++ b/tools/assetMetaTable.js
@@ -61,6 +61,8 @@ export const EXT_TO_TYPE = Object.freeze({
// only be made by the Content Browser's own button) and a graph written by
// any other hand is never adopted by the scan, which types orphans by name.
'.esmatgraph': 'materialgraph',
+ // A material graph used as a node of another; inlined at compile time, never shipped itself.
+ '.esmatsub': 'materialgraph',
// Import-only sources: importing one writes .esmesh (+ images + a prefab)
// beside it, and THOSE are what a scene references. Typed apart from the
// products for that reason — the engine loads no model format.
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 4053a1d18..b583e9167 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -148,6 +148,8 @@ export const NOTED = {
{ note: 'The Agent panel is redrawn.' },
'feat(editor): the Plugins panel shows id conflicts, filters by phase, previews what disabling removes and drops the built-ins trust withdrawal':
{ note: 'The Plugins panel shows conflicts and what disabling removes.' },
+ 'feat(render): material subgraphs — a graph used as one node of another, inlined at compile time':
+ { note: 'Material graphs can use other graphs as nodes.' },
'feat(editor): an asset header names its kind and size, and a segmented switch is used only when its words fit':
{ note: "An asset's header names its kind and size." },
"feat(editor): asset inspectors take the board's finish — a card preview, ruled key-value rows, tinted actions, a kind icon in the header":