State machines: asset, tab, State branch and Set state nodes (#51)

A state machine is an asset whose graph holds one `State` node per state
(no ports, name as title), edited in a new "State machine" tab that reuses
the graph canvas: right-click places "State n", snap toggle shared with the
Behavior tab via SnapToggle. `statemachine` is a value kind like texture
(port, literal node, variable, struct field, tagged list item).

Behaviors use it through `State branch` (one exec output per state) and
`Set state` (one exec input per state; the interpreter now hands `run` the
entry port). States live per behavior instance in NodeContext.states, with
no initial state. Ports derive from the inline picker or a wired
`State machine` literal; BehaviorLookup became GraphLookup with
behavior(id) and machine(id).

The Graph tab is labelled "Behavior" (key unchanged). Unit tests
(state-machine, kinds, catalog, ports), e2e step 26 and README added.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
rootandClaude Fable 5.1 committed 2026-09-12 18:00:23 +02:00
1 parent ce42d16657
commit e7d82bd1a9
60 files changed
+1269 -213

No files matched your search

+10 -9
View File
@@ -1,5 +1,5 @@
import { edgesInto, edgesOutOf, type Graph, type GraphNode } from './Graph';
import { type BehaviorLookup, NO_BEHAVIORS } from './lookup';
import { type GraphLookup, NO_LOOKUP } from './lookup';
import { BEHAVIOR_END, BEHAVIOR_START, resolveDef, terminalNode } from './nested';
import type { NodeContext } from './NodeContext';
import {
@@ -58,7 +58,7 @@ export class GraphInterpreter {
constructor(
readonly graph: Graph,
private readonly behaviors: BehaviorLookup = NO_BEHAVIORS,
private readonly lookup: GraphLookup = NO_LOOKUP,
) {
this.frame = emptyFrame(graph);
}
@@ -93,11 +93,11 @@ export class GraphInterpreter {
const target = this.node(edge.to.node);
if (!target) continue;
this.trace?.onEdge(edge.id);
this.execute(target, ctx, depth + 1);
this.execute(target, ctx, depth + 1, edge.to.port);
}
}
private execute(node: GraphNode, ctx: NodeContext, depth: number): void {
private execute(node: GraphNode, ctx: NodeContext, depth: number, entry: string): void {
if (++this.steps > MAX_STEPS_PER_FIRE)
throw new Error('Behavior graph exceeded the step limit (endless loop?)');
if (depth > MAX_DEPTH)
@@ -105,7 +105,7 @@ export class GraphInterpreter {
const def = this.def(node);
if (!def?.run) return;
const inputs = this.collectInputs(node, ctx);
const result = def.run(ctx, inputs, node.params, def);
const result = def.run(ctx, inputs, node.params, def, entry);
const returned = result.call ? this.call(result.call, ctx, depth) : {};
const produced = { ...result.outputs, ...returned };
if (!def.read) this.frame.outputCache.set(node.id, produced);
@@ -122,7 +122,7 @@ export class GraphInterpreter {
* a call and not an inlining: nothing of it survives the return but the values it hands back.
*/
private call(call: CallResult, ctx: NodeContext, depth: number): Record<string, Value> {
const program = this.behaviors(call.behaviorId);
const program = this.lookup.behavior(call.behaviorId);
if (!program) return {};
if (this.callStack.includes(call.behaviorId)) throw new Error(`Behavior "${program.name}" runs itself`);
const start = terminalNode(program.graph, BEHAVIOR_START);
@@ -135,7 +135,8 @@ export class GraphInterpreter {
this.calledBehaviors.add(call.behaviorId);
try {
this.trace?.onNode(start.id);
this.follow(start, 'exec', { ...ctx, variables: { ...program.defaults } }, depth + 1);
// Fresh variables and fresh states alike: a call keeps nothing, and sees nothing of the caller's.
this.follow(start, 'exec', { ...ctx, variables: { ...program.defaults }, states: {} }, depth + 1);
const end = terminalNode(program.graph, BEHAVIOR_END);
return (end && this.frame.outputCache.get(end.id)) ?? {};
} finally {
@@ -196,7 +197,7 @@ export class GraphInterpreter {
throw new Error('Behavior graph exceeded the step limit (data cycle?)');
// Mark before evaluating so a data cycle reads null instead of recursing forever.
this.frame.dataCache.set(nodeId, {});
const outputs = def.run(ctx, this.collectInputs(source, ctx), source.params, def).outputs ?? {};
const outputs = def.run(ctx, this.collectInputs(source, ctx), source.params, def, '').outputs ?? {};
this.frame.dataCache.set(nodeId, outputs);
this.trace?.onNode(nodeId);
this.record(nodeId, outputs);
@@ -220,7 +221,7 @@ export class GraphInterpreter {
}
private def(node: GraphNode) {
return resolveDef(node, this.frame.graph, this.behaviors);
return resolveDef(node, this.frame.graph, this.lookup);
}
private node(id: string): GraphNode | undefined {
+5
View File
@@ -62,6 +62,11 @@ export interface NodeContext {
/** The behavior's parent object – the one the graph acts on. */
owner: EntityHandle | null;
variables: PropertyBag;
/**
* The current state of each state machine this instance has set, keyed by machine asset id,
* as the state node's id. A machine not in here is in no state: `State branch` follows nothing.
*/
states: Record<string, string>;
/** Seconds since the world started and since the last tick. */
time: number;
dt: number;
+14 -6
View File
@@ -2,7 +2,7 @@ import type { PropertyBag, PropertyValue } from '../model/Properties';
import { isKindWith, plainKindOf } from '../properties/kinds';
import { flatDef, type PropertyDef } from '../properties/PropertySchema';
import type { DeclaredPort, Graph, GraphNode, PortType } from './Graph';
import type { BehaviorLookup } from './lookup';
import type { GraphLookup } from './lookup';
import type { NodeContext } from './NodeContext';
import { asList, type Value } from './values';
@@ -16,7 +16,8 @@ export interface PortDef {
field?: PropertyDef;
}
export type NodeCategory = 'event' | 'flow' | 'data' | 'variable' | 'action';
/** `state` is the one category no behavior graph offers: its nodes are the states of a state machine. */
export type NodeCategory = 'event' | 'flow' | 'data' | 'variable' | 'action' | 'state';
/**
* How a loop node asks for one of its exec outputs to be run repeatedly: `port` carries the body,
@@ -45,11 +46,11 @@ export interface RunResult {
call?: CallResult;
}
/** What a node may compute its ports from: itself, the graph it sits in, and the behaviors around it. */
/** What a node may compute its ports from: itself, the graph it sits in, and the project around it. */
export interface PortSource {
node: GraphNode;
graph: Graph;
behaviors: BehaviorLookup;
lookup: GraphLookup;
}
/** Ports a single node has on top of the fixed ones of its type, and a label naming what it does. */
@@ -95,9 +96,16 @@ export interface NodeDef {
read?(ctx: NodeContext, params: PropertyBag, input: (key: string) => Value): Record<string, Value>;
/**
* Event nodes have no `run` – the interpreter seeds their outputs. `def` is resolved for the node at
* hand, the only way a node with derived ports knows how many it has.
* hand, the only way a node with derived ports knows how many it has. `entry` is the exec input
* the pulse arrived through – what a node with one exec input per meaning reads.
*/
run?(ctx: NodeContext, inputs: Record<string, Value>, params: PropertyBag, def: NodeDef): RunResult;
run?(
ctx: NodeContext,
inputs: Record<string, Value>,
params: PropertyBag,
def: NodeDef,
entry: string,
): RunResult;
}
const defs = new Map<string, NodeDef>();
+4 -4
View File
@@ -1,5 +1,5 @@
import { edgesInto, findNode, type Graph, type PortType, portsCompatible } from './Graph';
import type { BehaviorLookup } from './lookup';
import type { GraphLookup } from './lookup';
import { resolveDef } from './nested';
import type { NodeDef } from './NodeRegistry';
@@ -10,7 +10,7 @@ export interface PortSide {
isOutput: boolean;
}
export function portTypeOf(graph: Graph, side: PortSide, lookup: BehaviorLookup): PortType | undefined {
export function portTypeOf(graph: Graph, side: PortSide, lookup: GraphLookup): PortType | undefined {
const node = findNode(graph, side.nodeId);
const def = node && resolveDef(node, graph, lookup);
const list = side.isOutput ? def?.outputs : def?.inputs;
@@ -18,7 +18,7 @@ export function portTypeOf(graph: Graph, side: PortSide, lookup: BehaviorLookup)
}
/** Whether a drag from `from` may land on `to`, i.e. whether ConnectCommand would accept it. */
export function canConnect(graph: Graph, from: PortSide, to: PortSide, lookup: BehaviorLookup): boolean {
export function canConnect(graph: Graph, from: PortSide, to: PortSide, lookup: GraphLookup): boolean {
if (from.isOutput === to.isOutput || from.nodeId === to.nodeId) return false;
const fromType = portTypeOf(graph, from, lookup);
const toType = portTypeOf(graph, to, lookup);
@@ -36,7 +36,7 @@ export function dropTargetPort(
graph: Graph,
from: PortSide,
nodeId: string,
lookup: BehaviorLookup,
lookup: GraphLookup,
): PortSide | null {
if (nodeId === from.nodeId) return null;
const node = findNode(graph, nodeId);
+1
View File
@@ -8,6 +8,7 @@ export * from './nested';
export * from './NodeContext';
export * from './NodeRegistry';
export * from './propertyPorts';
export * from './stateMachine';
export * from './values';
export * from './variablePorts';
export { GraphInterpreter, type TraceListener } from './GraphInterpreter';
+20 -2
View File
@@ -8,6 +8,24 @@ export interface BehaviorProgram {
defaults: PropertyBag;
}
export type BehaviorLookup = (assetId: string) => BehaviorProgram | null;
/** One state of a machine: the node id is what a port and the runtime hold, the name is the label. */
export interface MachineState {
id: string;
name: string;
}
export const NO_BEHAVIORS: BehaviorLookup = () => null;
export interface StateMachine {
name: string;
states: MachineState[];
}
/**
* What a node may look up in the project around its graph: the behaviors it can run and the
* state machines it can read. One handle, so no caller can resolve a node with half of it.
*/
export interface GraphLookup {
behavior(assetId: string): BehaviorProgram | null;
machine(assetId: string): StateMachine | null;
}
export const NO_LOOKUP: GraphLookup = { behavior: () => null, machine: () => null };
+6 -6
View File
@@ -2,7 +2,7 @@ import { textOf } from '../model/Properties';
import { isTaggedKind } from '../properties/kinds';
import { flatDef, isValidFieldName } from '../properties/PropertySchema';
import { type DeclaredPort, declaredPortType, type Graph, type GraphNode } from './Graph';
import type { BehaviorLookup } from './lookup';
import type { GraphLookup } from './lookup';
import { nodeDef, type NodeDef, type PortDef } from './NodeRegistry';
export const BEHAVIOR_START = 'BehaviorStart';
@@ -92,14 +92,14 @@ export function declaredPorts(graph: Graph | undefined, type: string): PortDef[]
* The node definition as it applies to *this* node: identical to the registered one, unless the
* type declares ports per node (`declaresPorts`) or computes them (`derivePorts`).
*/
export function resolveDef(node: GraphNode, graph: Graph, lookup: BehaviorLookup): NodeDef | undefined {
export function resolveDef(node: GraphNode, graph: Graph, lookup: GraphLookup): NodeDef | undefined {
const def = nodeDef(node.type);
if (!def || (!def.declaresPorts && !def.derivePorts)) return def;
const own = (side: 'inputs' | 'outputs') =>
declaredOn(def, node.ports ?? [], side).map((p) =>
def.declaredPort ? def.declaredPort(p, node) : portDefOf(p),
);
const grown = def.derivePorts?.({ node, graph, behaviors: lookup }) ?? {};
const grown = def.derivePorts?.({ node, graph, lookup }) ?? {};
const side = (key: 'inputs' | 'outputs') => execFirst([...def[key], ...(grown[key] ?? []), ...own(key)]);
return { ...def, label: grown.label ?? def.label, inputs: side('inputs'), outputs: side('outputs') };
}
@@ -113,12 +113,12 @@ function execFirst(ports: PortDef[]): PortDef[] {
* Why this call cannot do anything, or null if it can. A call is the one node that depends on a
* *different* graph, so it is the one node that can look perfectly healthy and still be dead.
*/
export function callProblem(node: GraphNode, lookup: BehaviorLookup, ownerId = ''): string | null {
export function callProblem(node: GraphNode, lookup: GraphLookup, ownerId = ''): string | null {
if (node.type !== RUN_BEHAVIOR) return null;
const id = textOf(node.params[BEHAVIOR_PARAM] ?? '');
if (!id) return 'No behavior picked';
if (id === ownerId) return 'A behavior cannot run itself';
const program = lookup(id);
const program = lookup.behavior(id);
if (!program) return 'That behavior is gone';
if (!terminalNode(program.graph, BEHAVIOR_START)) return 'No start node – does nothing';
return null;
@@ -128,7 +128,7 @@ export function callProblem(node: GraphNode, lookup: BehaviorLookup, ownerId = '
* Everything that changes how a node looks, as one string. Views and the inspector rebuild when it
* changes – a port list that is derived rather than fixed has no other way of being noticed.
*/
export function portSignature(node: GraphNode, graph: Graph, lookup: BehaviorLookup, ownerId = ''): string {
export function portSignature(node: GraphNode, graph: Graph, lookup: GraphLookup, ownerId = ''): string {
const def = resolveDef(node, graph, lookup);
if (!def) return 'missing';
const list = (ports: PortDef[]) => ports.map((p) => `${p.key}:${p.type}`).join(',');
+5
View File
@@ -30,6 +30,11 @@ export const TextureLiteral = literal(
'texture',
'A constant picture: a texture, one of its frames or an animation, as a sprite wears it.',
);
export const StateMachineLiteral = literal(
'StateMachine',
'statemachine',
'A constant state machine, for a "State branch" or a "Set state" to work on.',
);
export const ListLiteral = literal(
'List',
'list',
+2 -2
View File
@@ -18,8 +18,8 @@ export const RunBehavior: NodeDef = {
inputs: [exec()],
outputs: [exec()],
params: [{ key: BEHAVIOR_PARAM, label: 'Behavior', kind: 'asset', default: '', assetTypes: ['behavior'] }],
derivePorts: ({ node, behaviors }) => {
const program = behaviors(textOf(node.params[BEHAVIOR_PARAM] ?? ''));
derivePorts: ({ node, lookup }) => {
const program = lookup.behavior(textOf(node.params[BEHAVIOR_PARAM] ?? ''));
return {
// The graph reads as what it does, not as a row of identical "Run behavior" boxes.
label: program?.name,
+23
View File
@@ -0,0 +1,23 @@
import type { NodeDef } from '../../NodeRegistry';
import { machineOf, machinePort, statePorts } from '../../stateMachine';
import { asString } from '../../values';
import { exec } from '../shared';
/** The mirror image of `State branch`: the input the flow arrives through names the new state. */
export const SetState: NodeDef = {
type: 'SetState',
label: 'Set state',
category: 'action',
description:
'Puts the machine into the state whose input the flow arrived through, then continues. Each ' +
'behavior instance keeps its own states.',
inputs: [machinePort()],
outputs: [exec()],
params: [],
derivePorts: (source) => ({ inputs: statePorts(machineOf(source)) }),
run: (ctx, inputs, _params, def, entry) => {
const machine = asString(inputs.machine);
if (machine && def.inputs.some((p) => p.type === 'exec' && p.key === entry)) ctx.states[machine] = entry;
return { next: 'exec' };
},
};
+22
View File
@@ -0,0 +1,22 @@
import type { NodeDef } from '../../NodeRegistry';
import { machineOf, machinePort, statePorts } from '../../stateMachine';
import { asString } from '../../values';
import { exec } from '../shared';
/** No state set yet, or a state of another machine: the flow ends here, along no output. */
export const StateBranch: NodeDef = {
type: 'StateBranch',
label: 'State branch',
category: 'flow',
description:
'Continues along the output of the state the machine is in. Before "Set state" has run, the ' +
'machine is in no state and nothing continues.',
inputs: [exec(), machinePort()],
outputs: [],
params: [],
derivePorts: (source) => ({ outputs: statePorts(machineOf(source)) }),
run: (ctx, inputs, _params, def) => {
const current = ctx.states[asString(inputs.machine)];
return def.outputs.some((p) => p.key === current) ? { next: current } : {};
},
};
+16 -1
View File
@@ -26,7 +26,14 @@ import { IsTouching } from './data/IsTouching';
import { Join } from './data/Join';
import { KeyIsDown } from './data/KeyIsDown';
import { Length } from './data/Length';
import { BooleanLiteral, ListLiteral, NumberLiteral, StringLiteral, TextureLiteral } from './data/literals';
import {
BooleanLiteral,
ListLiteral,
NumberLiteral,
StateMachineLiteral,
StringLiteral,
TextureLiteral,
} from './data/literals';
import { Max } from './data/Max';
import { Min } from './data/Min';
import { Modulo } from './data/Modulo';
@@ -76,6 +83,9 @@ import { Branch } from './flow/Branch';
import { Repeat } from './flow/Repeat';
import { RunBehavior } from './flow/RunBehavior';
import { Sequence } from './flow/Sequence';
import { SetState } from './flow/SetState';
import { StateBranch } from './flow/StateBranch';
import { State } from '../stateMachine';
import { Variables } from './variable/Variables';
/**
@@ -99,6 +109,8 @@ export const BUILT_IN_NODES: readonly NodeDef[] = [
Sequence,
Repeat,
RunBehavior,
StateBranch,
SetState,
BehaviorEnd,
Variables,
Self,
@@ -114,6 +126,7 @@ export const BUILT_IN_NODES: readonly NodeDef[] = [
BooleanLiteral,
StringLiteral,
TextureLiteral,
StateMachineLiteral,
Add,
Subtract,
Multiply,
@@ -168,3 +181,5 @@ export const BUILT_IN_NODES: readonly NodeDef[] = [
];
for (const def of BUILT_IN_NODES) registerNode(def);
// Registered so a machine's graph loads and draws, but not built in: no behavior graph offers it.
registerNode(State);
+73
View File
@@ -0,0 +1,73 @@
import { textOf } from '../model/Properties';
import { flatDef } from '../properties/PropertySchema';
import { edgesInto, type Graph, type GraphNode } from './Graph';
import type { MachineState, StateMachine } from './lookup';
import type { NodeDef, PortDef, PortSource } from './NodeRegistry';
export const STATE = 'State';
export const STATE_MACHINE = 'StateMachine';
export const STATE_NAME_PARAM = 'name';
/** The input naming the machine on `State branch` and `Set state`. */
export const MACHINE_PORT = 'machine';
/**
* One state of a state machine: a node with no ports whose name is its title. Its graph is the
* machine asset's, never a behavior's – the palette leaves the `state` category out.
*/
export const State: NodeDef = {
type: STATE,
label: 'State',
category: 'state',
description: 'One state of a state machine.',
inputs: [],
outputs: [],
params: [flatDef(STATE_NAME_PARAM, 'text', { label: 'Name', value: 'State' })],
derivePorts: ({ node }) => ({ label: stateName(node) }),
};
export function isStateNode(node: GraphNode): boolean {
return node.type === STATE;
}
export function stateName(node: GraphNode): string {
return textOf(node.params[STATE_NAME_PARAM] ?? '') || State.label;
}
/** The states of a machine's graph in node order – what its ports and the runtime name. */
export function statesOf(graph: Graph): MachineState[] {
return graph.nodes.filter(isStateNode).map((node) => ({ id: node.id, name: stateName(node) }));
}
/** What a state placed from the palette is called: "State 3" for the third. */
export function nextStateName(graph: Graph): string {
return `${State.label} ${statesOf(graph).length + 1}`;
}
/** The `machine` input; unconnected, it shows the machine picker. */
export const machinePort = (): PortDef => ({
key: MACHINE_PORT,
label: 'machine',
type: 'string',
field: flatDef(MACHINE_PORT, 'statemachine', { label: 'Machine' }),
});
/**
* The machine a node's `machine` input names while the graph is drawn: the inline pick, or the
* `State machine` literal an edge brings in. A port is derived from the graph, not from a running
* value, so a variable or a list item feeding the input yields no state ports.
*/
export function machineOf({ node, graph, lookup }: PortSource): StateMachine | null {
const edge = edgesInto(graph, node.id, MACHINE_PORT)[0];
const source = edge && graph.nodes.find((n) => n.id === edge.from.node);
const id = edge
? source?.type === STATE_MACHINE
? textOf(source.params.value ?? '')
: ''
: textOf(node.params[MACHINE_PORT] ?? '');
return id ? lookup.machine(id) : null;
}
/** One exec port per state, keyed by the state's id – a rename keeps every edge. */
export function statePorts(machine: StateMachine | null): PortDef[] {
return (machine?.states ?? []).map((state) => ({ key: state.id, label: state.name, type: 'exec' }));
}