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:
1 parent
ce42d16657
commit
e7d82bd1a9
60 files changed
+1269
-213
No files matched your search
@@ -34,6 +34,8 @@ export function buildAsset(type: AssetType, name: string, id = newId()): Asset {
|
||||
return { ...base, type: 'container', objects: [] };
|
||||
case 'animation':
|
||||
return { ...base, type: 'animation', frames: [] };
|
||||
case 'statemachine':
|
||||
return { ...base, type: 'statemachine', graph: createEmptyGraph() };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,14 +8,14 @@ import {
|
||||
} from '../graph/Graph';
|
||||
import { isTerminalType, resolveDef, terminalNode } from '../graph/nested';
|
||||
import { nodeDef } from '../graph/NodeRegistry';
|
||||
import { behaviorLookup } from '../model/behaviorPrograms';
|
||||
import { graphLookup } from '../model/graphLookup';
|
||||
import { newId } from '../ids';
|
||||
import type { PropertyBag, PropertyValue } from '../model/Properties';
|
||||
import type { Project } from '../model/Project';
|
||||
import { coerceValue, defaultsOf } from '../properties/PropertySchema';
|
||||
import { type Removed, removeById, removeFirst, removeWhere, restoreAt } from '../util/list';
|
||||
import { type Command, CommandError } from './Command';
|
||||
import { requireBehavior, requireNode, requireNodeDef } from './require';
|
||||
import { requireGraph, requireNode, requireNodeDef } from './require';
|
||||
import { SetBagValueCommand } from './SetBagValueCommand';
|
||||
|
||||
export class AddNodeCommand implements Command {
|
||||
@@ -44,16 +44,16 @@ export class AddNodeCommand implements Command {
|
||||
|
||||
execute(project: Project): void {
|
||||
requireNodeDef(this.node.type);
|
||||
const graph = requireBehavior(project, this.assetId).graph;
|
||||
const graph = requireGraph(project, this.assetId);
|
||||
// The two terminals give the behavior its signature; a second one of either would make
|
||||
// "which ports does this behavior have" ambiguous.
|
||||
if (isTerminalType(this.node.type) && terminalNode(graph, this.node.type))
|
||||
throw new CommandError(`This behavior already has a ${nodeDef(this.node.type)?.label} node`);
|
||||
throw new CommandError(`This graph already has a ${nodeDef(this.node.type)?.label} node`);
|
||||
graph.nodes.push(this.node);
|
||||
}
|
||||
|
||||
undo(project: Project): void {
|
||||
const graph = requireBehavior(project, this.assetId).graph;
|
||||
const graph = requireGraph(project, this.assetId);
|
||||
graph.nodes = removeById(graph.nodes, this.node.id);
|
||||
}
|
||||
}
|
||||
@@ -69,7 +69,7 @@ export class RemoveNodeCommand implements Command {
|
||||
) {}
|
||||
|
||||
execute(project: Project): void {
|
||||
const graph = requireBehavior(project, this.assetId).graph;
|
||||
const graph = requireGraph(project, this.assetId);
|
||||
const node = removeFirst(graph.nodes, (n) => n.id === this.nodeId);
|
||||
if (!node) throw new CommandError(`Node ${this.nodeId} not found`);
|
||||
// `edgesOfNode` reads the edge list only, so it still finds them after the node is gone.
|
||||
@@ -79,7 +79,7 @@ export class RemoveNodeCommand implements Command {
|
||||
|
||||
undo(project: Project): void {
|
||||
if (!this.removed) return;
|
||||
const graph = requireBehavior(project, this.assetId).graph;
|
||||
const graph = requireGraph(project, this.assetId);
|
||||
restoreAt(graph.nodes, [this.removed.node]);
|
||||
restoreAt(graph.edges, this.removed.edges);
|
||||
}
|
||||
@@ -134,9 +134,9 @@ export class SetNodeParamCommand extends SetBagValueCommand<GraphNode> {
|
||||
|
||||
override execute(project: Project): void {
|
||||
super.execute(project);
|
||||
const graph = requireBehavior(project, this.assetId).graph;
|
||||
const graph = requireGraph(project, this.assetId);
|
||||
const node = requireNode(project, this.assetId, this.nodeId);
|
||||
const def = resolveDef(node, graph, behaviorLookup(project));
|
||||
const def = resolveDef(node, graph, graphLookup(project));
|
||||
if (!def) return;
|
||||
const outputs = new Set(def.outputs.map((p) => p.key));
|
||||
const inputs = new Set(def.inputs.map((p) => p.key));
|
||||
@@ -150,7 +150,7 @@ export class SetNodeParamCommand extends SetBagValueCommand<GraphNode> {
|
||||
|
||||
override undo(project: Project): void {
|
||||
super.undo(project);
|
||||
restoreAt(requireBehavior(project, this.assetId).graph.edges, this.orphans);
|
||||
restoreAt(requireGraph(project, this.assetId).edges, this.orphans);
|
||||
}
|
||||
|
||||
protected override resolveTarget(project: Project): GraphNode {
|
||||
@@ -183,12 +183,12 @@ export class ConnectCommand implements Command {
|
||||
}
|
||||
|
||||
execute(project: Project): void {
|
||||
const graph = requireBehavior(project, this.assetId).graph;
|
||||
const graph = requireGraph(project, this.assetId);
|
||||
const fromNode = findNode(graph, this.edge.from.node);
|
||||
const toNode = findNode(graph, this.edge.to.node);
|
||||
if (!fromNode || !toNode) throw new CommandError('Node not found');
|
||||
if (fromNode === toNode) throw new CommandError('A node cannot connect to itself');
|
||||
const lookup = behaviorLookup(project);
|
||||
const lookup = graphLookup(project);
|
||||
const out = resolveDef(fromNode, graph, lookup)?.outputs.find((p) => p.key === this.edge.from.port);
|
||||
const inp = resolveDef(toNode, graph, lookup)?.inputs.find((p) => p.key === this.edge.to.port);
|
||||
if (!out || !inp) throw new CommandError('Port not found');
|
||||
@@ -201,7 +201,7 @@ export class ConnectCommand implements Command {
|
||||
}
|
||||
|
||||
undo(project: Project): void {
|
||||
const graph = requireBehavior(project, this.assetId).graph;
|
||||
const graph = requireGraph(project, this.assetId);
|
||||
graph.edges = removeById(graph.edges, this.edge.id);
|
||||
restoreAt(graph.edges, this.replaced);
|
||||
}
|
||||
@@ -231,7 +231,7 @@ export class FoldEdgeCommand implements Command {
|
||||
}
|
||||
|
||||
private edge(project: Project): GraphEdge {
|
||||
const edge = requireBehavior(project, this.assetId).graph.edges.find((e) => e.id === this.edgeId);
|
||||
const edge = requireGraph(project, this.assetId).edges.find((e) => e.id === this.edgeId);
|
||||
if (!edge) throw new CommandError(`Edge ${this.edgeId} not found`);
|
||||
return edge;
|
||||
}
|
||||
@@ -282,13 +282,13 @@ export class DisconnectCommand implements Command {
|
||||
) {}
|
||||
|
||||
execute(project: Project): void {
|
||||
const graph = requireBehavior(project, this.assetId).graph;
|
||||
const graph = requireGraph(project, this.assetId);
|
||||
this.removed = removeWhere(graph.edges, (e) => e.id === this.edgeId);
|
||||
if (this.removed.length === 0) throw new CommandError(`Edge ${this.edgeId} not found`);
|
||||
}
|
||||
|
||||
undo(project: Project): void {
|
||||
restoreAt(requireBehavior(project, this.assetId).graph.edges, this.removed);
|
||||
restoreAt(requireGraph(project, this.assetId).edges, this.removed);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
/** Lookups that throw a `CommandError` when the target does not exist. */
|
||||
import { findNode, type GraphNode } from '../graph/Graph';
|
||||
import { findNode, type Graph, type GraphNode } from '../graph/Graph';
|
||||
import { type NodeDef, nodeDef } from '../graph/NodeRegistry';
|
||||
import type { Asset, BehaviorAsset } from '../model/Asset';
|
||||
import { findObject, type ObjectTree } from '../model/hierarchy';
|
||||
import { isTemplateContent, objectRef, type ObjectRef } from '../model/instance';
|
||||
import { findAsset, findAssetOf, findObjectHolder, type ObjectHolder, type Project } from '../model/Project';
|
||||
import {
|
||||
findAsset,
|
||||
findAssetOf,
|
||||
findGraphAsset,
|
||||
findObjectHolder,
|
||||
type ObjectHolder,
|
||||
type Project,
|
||||
} from '../model/Project';
|
||||
import type { SceneObject } from '../model/SceneObject';
|
||||
import { propDef, type PropertyDef } from '../properties/PropertySchema';
|
||||
import { CommandError } from './Command';
|
||||
@@ -64,8 +71,15 @@ export function requireBehavior(project: Project, assetId: string): BehaviorAsse
|
||||
return asset;
|
||||
}
|
||||
|
||||
/** The graph of a behavior or of a state machine – what every graph command edits. */
|
||||
export function requireGraph(project: Project, assetId: string): Graph {
|
||||
const asset = findGraphAsset(project, assetId);
|
||||
if (!asset) throw new CommandError(`Behavior or state machine ${assetId} not found`);
|
||||
return asset.graph;
|
||||
}
|
||||
|
||||
export function requireNode(project: Project, assetId: string, nodeId: string): GraphNode {
|
||||
const node = findNode(requireBehavior(project, assetId).graph, nodeId);
|
||||
const node = findNode(requireGraph(project, assetId), nodeId);
|
||||
if (!node) throw new CommandError(`Node ${nodeId} not found`);
|
||||
return node;
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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>();
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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';
|
||||
@@ -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 };
|
||||
@@ -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(',');
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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' };
|
||||
},
|
||||
};
|
||||
@@ -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 } : {};
|
||||
},
|
||||
};
|
||||
@@ -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);
|
||||
@@ -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' }));
|
||||
}
|
||||
+18
-1
@@ -82,6 +82,15 @@ export interface AnimationAsset extends AssetBase {
|
||||
frames: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The graph holds one `State` node per state and nothing else; a behavior reads the machine's
|
||||
* current state through `State branch` and moves it through `Set state`.
|
||||
*/
|
||||
export interface StateMachineAsset extends AssetBase {
|
||||
type: 'statemachine';
|
||||
graph: Graph;
|
||||
}
|
||||
|
||||
export type Asset =
|
||||
| SpriteAsset
|
||||
| CameraAsset
|
||||
@@ -91,7 +100,15 @@ export type Asset =
|
||||
| ColliderAsset
|
||||
| ContainerAsset
|
||||
| TextureAsset
|
||||
| AnimationAsset;
|
||||
| AnimationAsset
|
||||
| StateMachineAsset;
|
||||
|
||||
/** The assets edited as a node graph – what the graph canvas and the graph commands work on. */
|
||||
export type GraphAsset = BehaviorAsset | StateMachineAsset;
|
||||
|
||||
export function isGraphAsset(asset: Asset): asset is GraphAsset {
|
||||
return asset.type === 'behavior' || asset.type === 'statemachine';
|
||||
}
|
||||
|
||||
export function isSceneAsset(asset: Asset): asset is SceneAsset {
|
||||
return asset.type === 'scene';
|
||||
|
||||
@@ -8,6 +8,7 @@ export const ASSET_TYPES = [
|
||||
'container',
|
||||
'texture',
|
||||
'animation',
|
||||
'statemachine',
|
||||
] as const;
|
||||
|
||||
export type AssetType = (typeof ASSET_TYPES)[number];
|
||||
@@ -22,13 +23,17 @@ export const ASSET_TYPE_LABELS: Record<AssetType, string> = {
|
||||
container: 'Container',
|
||||
texture: 'Texture',
|
||||
animation: 'Animation',
|
||||
statemachine: 'State machine',
|
||||
};
|
||||
|
||||
/** Textures and animations are not placeable: they are pictures a sprite wears through `texture`. */
|
||||
export type PlaceableAssetType = Exclude<AssetType, 'scene' | 'texture' | 'animation'>;
|
||||
/**
|
||||
* Textures and animations are not placeable: they are pictures a sprite wears through `texture`.
|
||||
* A state machine is not either: a behavior refers to it by id.
|
||||
*/
|
||||
export type PlaceableAssetType = Exclude<AssetType, 'scene' | 'texture' | 'animation' | 'statemachine'>;
|
||||
|
||||
export function isPlaceableType(type: AssetType): type is PlaceableAssetType {
|
||||
return type !== 'scene' && type !== 'texture' && type !== 'animation';
|
||||
return type !== 'scene' && type !== 'texture' && type !== 'animation' && type !== 'statemachine';
|
||||
}
|
||||
|
||||
export function isAssetType(value: unknown): value is AssetType {
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
import { type Asset, type ContainerAsset, isSceneAsset, type SceneAsset } from './Asset';
|
||||
import {
|
||||
type Asset,
|
||||
type ContainerAsset,
|
||||
type GraphAsset,
|
||||
isGraphAsset,
|
||||
isSceneAsset,
|
||||
type SceneAsset,
|
||||
} from './Asset';
|
||||
|
||||
/** 2: a placed container carries no copy of its template. */
|
||||
export const PROJECT_FORMAT_VERSION = 2;
|
||||
@@ -38,6 +45,11 @@ export function listScenes(project: Project): SceneAsset[] {
|
||||
return project.assets.filter(isSceneAsset);
|
||||
}
|
||||
|
||||
export function findGraphAsset(project: Project, assetId: string): GraphAsset | undefined {
|
||||
const asset = findAsset(project, assetId);
|
||||
return asset && isGraphAsset(asset) ? asset : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything that holds placed objects. A container's `objects` are a template, so anything
|
||||
* walking "all placed objects" must cover both or it silently skips the templates.
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
import type { BehaviorLookup } from '../graph/lookup';
|
||||
import { resolveAssetProps } from '../properties/resolve';
|
||||
import { findAssetOf, type Project } from './Project';
|
||||
|
||||
/**
|
||||
* What a `Run behavior` node needs from the project. `defaults` are the asset's variable values;
|
||||
* every call copies them, so a nested behavior never carries state from one call to the next.
|
||||
*/
|
||||
export function behaviorLookup(project: Project): BehaviorLookup {
|
||||
return (assetId) => {
|
||||
const asset = findAssetOf(project, assetId, 'behavior');
|
||||
if (!asset) return null;
|
||||
return { name: asset.name, graph: asset.graph, defaults: resolveAssetProps(asset) };
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { GraphLookup } from '../graph/lookup';
|
||||
import { statesOf } from '../graph/stateMachine';
|
||||
import { resolveAssetProps } from '../properties/resolve';
|
||||
import { findAssetOf, type Project } from './Project';
|
||||
|
||||
/**
|
||||
* What a graph may see of the project around it. A behavior's `defaults` are its variable values;
|
||||
* every call copies them, so a nested behavior never carries state from one call to the next.
|
||||
*/
|
||||
export function graphLookup(project: Project): GraphLookup {
|
||||
return {
|
||||
behavior: (assetId) => {
|
||||
const asset = findAssetOf(project, assetId, 'behavior');
|
||||
if (!asset) return null;
|
||||
return { name: asset.name, graph: asset.graph, defaults: resolveAssetProps(asset) };
|
||||
},
|
||||
machine: (assetId) => {
|
||||
const asset = findAssetOf(project, assetId, 'statemachine');
|
||||
return asset ? { name: asset.name, states: statesOf(asset.graph) } : null;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -155,6 +155,8 @@ const ASSET_SCHEMAS: Record<AssetType, PropertySchema> = {
|
||||
],
|
||||
// Behaviors declare their own properties (variables) per asset too – see `schemaForAsset`.
|
||||
behavior: [{ key: 'runInEditor', label: 'Run in editor', kind: 'boolean', default: false }],
|
||||
// The states are the asset's graph (see StateMachineAsset), not a property.
|
||||
statemachine: [],
|
||||
collider: [
|
||||
{
|
||||
key: 'shape',
|
||||
|
||||
@@ -92,6 +92,20 @@ export const KINDS = [
|
||||
field: true,
|
||||
port: true,
|
||||
},
|
||||
/** A state machine asset's id – a text, so it is tagged in a list like a texture. */
|
||||
{
|
||||
kind: 'statemachine',
|
||||
label: 'State machine',
|
||||
mark: '◈',
|
||||
travels: 'string',
|
||||
empty: '',
|
||||
coerce: text,
|
||||
tagged: true,
|
||||
reference: true,
|
||||
variable: true,
|
||||
field: true,
|
||||
port: true,
|
||||
},
|
||||
{ kind: 'object', label: 'Object', mark: '◇', travels: 'object', port: true },
|
||||
{ kind: 'list', label: 'List', mark: '≡', travels: 'list', variable: true, port: true },
|
||||
{ kind: 'struct', label: 'Struct', mark: '⊞', travels: 'struct', variable: true, port: true },
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
isValidPortName,
|
||||
fixedPortKeys,
|
||||
nodeDef,
|
||||
STATE,
|
||||
} from '../graph';
|
||||
import type { Asset, TextureFrame } from '../model/Asset';
|
||||
import { isAssetType } from '../model/AssetTypes';
|
||||
@@ -89,6 +90,8 @@ export function deserializeProject(raw: unknown, fallbackId = ''): Project {
|
||||
variables: variables.get(id) ?? [],
|
||||
graph: normalizeGraph(a.graph),
|
||||
});
|
||||
} else if (type === 'statemachine') {
|
||||
assets.push({ id, type, name, props, graph: normalizeGraph(a.graph, STATE) });
|
||||
} else if (type === 'texture') {
|
||||
assets.push({ id, type, name, props, ...normalizeTexture(a, takenIds) });
|
||||
} else if (type === 'animation') {
|
||||
@@ -242,7 +245,8 @@ function normalizePorts(raw: unknown, fixed: readonly string[], writable: boolea
|
||||
return ports;
|
||||
}
|
||||
|
||||
function normalizeGraph(raw: unknown): Graph {
|
||||
/** `only` restricts the node types kept: a state machine's graph holds states and nothing else. */
|
||||
function normalizeGraph(raw: unknown, only?: string): Graph {
|
||||
const g = asRecord(raw);
|
||||
const graph = createEmptyGraph();
|
||||
const nodeIds = new Set<string>();
|
||||
@@ -251,7 +255,7 @@ function normalizeGraph(raw: unknown): Graph {
|
||||
const id = typeof n.id === 'string' ? n.id : '';
|
||||
const type = typeof n.type === 'string' ? n.type : '';
|
||||
const def = nodeDef(type);
|
||||
if (!id || nodeIds.has(id) || !def) continue;
|
||||
if (!id || nodeIds.has(id) || !def || (only !== undefined && type !== only)) continue;
|
||||
nodeIds.add(id);
|
||||
// Params carry both settings and inline input values, so there is no schema to coerce against.
|
||||
const params: PropertyBag = {};
|
||||
|
||||
Reference in new issue
Block a user