Give a behavior more ways in and out, and hear it as an event (#294)
A behavior run by another one had a single flow port at its Start and at its End, so it could not branch for its caller. And it could not be used as an event: a call needs a pulse at its flow input, and the events of a called graph never fire. An input like "Confirm" (Space or Enter) had to be built again in every graph. - A declared port of a Start or an End node can be of the kind Flow. It sits above the values and shares their names, exec stays reserved. Only these two nodes declare one, a struct does not. - Run behavior shows a flow port of the Start as a further flow input. A call arriving through it leaves the Start through the output of that name and not through exec. - Run behavior shows a flow port of the End as a further flow output. The call goes on through the one the End was reached by last, and then through exec. exec fires always, as before. - On behavior is a new event node without a flow input. The behavior it names runs at the node for as long as the behavior around it runs, with all of its own events and one set of variables per node. - Its outputs are those of the End. It fires once the inner pulse is through, by the output the End was reached by last, exec only for End.exec. A pulse that never reaches the End is not seen. - The value ports of the Start are its inputs, read anew for each inner pulse. The Start itself never fires there. - It nests to any depth. Under a Run behavior it stays silent. A behavior hearing itself, however far round, is not started and the node says "A behavior cannot listen to itself". - The palette offers every other behavior with an End once more as "On <name>". A node naming one without End says so. - An On node removed while the game runs ends its behavior with On disable and On destroy. The sounds of the entity end only with the behavior placed on it. - Renaming and deleting a declared port follows the edges at On behavior nodes as it does at Run behavior nodes. - The flow outputs of the Start of a behavior placed on an object never fire, like its exec. - The engine prompt of the benchmark names flow ports and On behavior. Tests: - Gate on melektaus-atx right before this commit: 215 files, 3319 tests (3278 + 41), exit 0. - e2e 19 on melektaus-atx: 39 checks (+4), all pass. e2e 1-6,17-24,26,36,51: 628 checks, all pass. - 19 unit tests in flow-ports.test.ts, 19 in on-behavior.test.ts on a real world, the rest in the node catalog. - Four new e2e checks in module 19: a flow port declared by mouse at the End, On Confirm in the graph, the call leaving through the further output while playing, Enter and Space on a real keyboard. - 19 unit counter-probes all fail their tests. One did not at first (a removed node kept its instance), a test was added. Two browser counter-probes fail their checks. - One screenshot looked at: On Confirm with exec and pressed, the second flow pin at the calling node. - The e2e sum of 1680 is counted (1676 + 4), the full suite and the smokes did not run. - Not seen in the browser: flow inputs at the Start, nesting, the ring, values through On behavior, the palette entry. No test holds that the sounds of the entity go on when a heard behavior ends. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b5339b96c2
commit
46c620ae3b
26 files changed
+1211
-42
No files matched your search
@@ -9,11 +9,12 @@ import {
|
||||
type Graph,
|
||||
type GraphEdge,
|
||||
type GraphNode,
|
||||
isFlowPort,
|
||||
isTerminalNode,
|
||||
isValidPortName,
|
||||
namesBehavior,
|
||||
OBJECT_BEHAVIOR_PARAM,
|
||||
propertyTargetOf,
|
||||
RUN_BEHAVIOR,
|
||||
variablesSourceOf,
|
||||
} from '../graph';
|
||||
import type { PropertyValue } from '../model/Properties';
|
||||
@@ -32,8 +33,9 @@ interface PortSite {
|
||||
|
||||
/**
|
||||
* Where a change to `node`'s declaration has to be mirrored. For most nodes that is the node
|
||||
* itself. A behavior's terminal is the exception: its ports are also ports of every node calling
|
||||
* the behavior – facing the other way, because what a start node hands out the caller passes in.
|
||||
* itself. A behavior's terminal is the exception: its ports are also ports of every node running or
|
||||
* hearing the behavior – facing the other way, because what a start node hands out the caller passes in.
|
||||
* A node that has no such port (an `On behavior` and a flow port of the start) has no edges on it either.
|
||||
*/
|
||||
function portSites(project: Project, assetId: string, node: GraphNode): PortSite[] {
|
||||
const sites = ownSites(requireBehavior(project, assetId).graph, node);
|
||||
@@ -41,7 +43,7 @@ function portSites(project: Project, assetId: string, node: GraphNode): PortSite
|
||||
for (const other of project.assets) {
|
||||
if (other.type !== 'behavior') continue;
|
||||
for (const caller of other.graph.nodes) {
|
||||
if (caller.type !== RUN_BEHAVIOR || caller.params[BEHAVIOR_PARAM] !== assetId) continue;
|
||||
if (!namesBehavior(caller.type) || caller.params[BEHAVIOR_PARAM] !== assetId) continue;
|
||||
sites.push({ graph: other.graph, nodeId: caller.id, asInput: node.type === BEHAVIOR_START });
|
||||
}
|
||||
}
|
||||
@@ -135,6 +137,8 @@ export class AddPortsCommand implements Command {
|
||||
const keys = new Set((node.ports ?? []).map((p) => p.key));
|
||||
for (const port of this.ports) {
|
||||
checkPortName(node, port.key);
|
||||
if (isFlowPort(port) && !isTerminalNode(node))
|
||||
throw new CommandError('Only a start or an end node declares a flow port');
|
||||
if (keys.has(port.key)) throw new CommandError(`"${port.key}" already exists`);
|
||||
keys.add(port.key);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { blockProblem, findMode, MATCH_INPUT, matchOf, searchOutcome, stopsAtHit
|
||||
import type { Graph, GraphNode } from './Graph';
|
||||
import { type GraphCache, type GraphIndex, searchingIndex } from './graphIndex';
|
||||
import { type GraphLookup, NO_LOOKUP } from './lookup';
|
||||
import { BEHAVIOR_END, callEntries, terminalNode } from './nested';
|
||||
import { BEHAVIOR_END, BEHAVIOR_START, callEntries } from './nested';
|
||||
import { fieldValue, splitField, withSplitValues } from './portSplits';
|
||||
import type { PropertyBag, PropertyValue } from '../model/Properties';
|
||||
import type { NodeContext } from './NodeContext';
|
||||
@@ -41,6 +41,14 @@ interface Frame {
|
||||
index: GraphIndex;
|
||||
outputCache: Map<string, Record<string, Value>>;
|
||||
dataCache: Map<string, Record<string, Value>>;
|
||||
/** The flow input this graph's end node was reached by last, once it was reached at all (#294). */
|
||||
ended?: string;
|
||||
}
|
||||
|
||||
/** How a graph was left: through which flow input of its end node, and with what. */
|
||||
export interface Ending {
|
||||
port: string;
|
||||
values: Record<string, Value>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -83,6 +91,11 @@ export class GraphInterpreter {
|
||||
private callSites: string[] = [];
|
||||
private steps = 0;
|
||||
trace: TraceListener | null = null;
|
||||
/**
|
||||
* What the start node hands out while this graph runs on its own events and not as a call: the
|
||||
* inputs of the `On behavior` node listening to it (#294). Set by whoever sends the pulses.
|
||||
*/
|
||||
given: Record<string, Value> | null = null;
|
||||
|
||||
constructor(
|
||||
readonly graph: Graph,
|
||||
@@ -101,6 +114,14 @@ export class GraphInterpreter {
|
||||
return { graph, index: this.indexOf(graph), outputCache: new Map(), dataCache: new Map() };
|
||||
}
|
||||
|
||||
/** A frame of the graph itself, its start node holding what was given from outside. */
|
||||
private ownFrame(): Frame {
|
||||
const frame = this.emptyFrame(this.graph);
|
||||
const start = this.given ? frame.index.ofType(BEHAVIOR_START)[0] : undefined;
|
||||
if (start && this.given) frame.outputCache.set(start.id, { ...this.given });
|
||||
return frame;
|
||||
}
|
||||
|
||||
eventNodes(type: string): readonly GraphNode[] {
|
||||
return this.indexOf(this.graph).ofType(type);
|
||||
}
|
||||
@@ -110,7 +131,7 @@ export class GraphInterpreter {
|
||||
* through – a state event names one.
|
||||
*/
|
||||
pulse(node: GraphNode, ctx: NodeContext, outputs: Record<string, Value> = {}, port = 'exec'): void {
|
||||
this.frame = this.emptyFrame(this.graph);
|
||||
this.frame = this.ownFrame();
|
||||
this.callStack = [];
|
||||
this.callSites = [];
|
||||
this.steps = 0;
|
||||
@@ -125,12 +146,30 @@ export class GraphInterpreter {
|
||||
* the node at all (#160). Null for an input the node does not have.
|
||||
*/
|
||||
eventInput(node: GraphNode, key: string, ctx: NodeContext): Value {
|
||||
this.frame = this.emptyFrame(this.graph);
|
||||
this.frame = this.ownFrame();
|
||||
this.steps = 0;
|
||||
const port = this.def(node)?.inputs.find((p) => p.key === key);
|
||||
return port ? this.inputValue(node, port, ctx) : null;
|
||||
}
|
||||
|
||||
/** Every data input of an event node, read ahead of a pulse like `eventInput`. */
|
||||
eventInputs(node: GraphNode, ctx: NodeContext): Record<string, Value> {
|
||||
this.frame = this.ownFrame();
|
||||
this.steps = 0;
|
||||
return this.collectInputs(node, ctx);
|
||||
}
|
||||
|
||||
/** How the last pulse left this graph, or null when it never reached the end node. */
|
||||
get ending(): Ending | null {
|
||||
return this.endingOf(this.frame);
|
||||
}
|
||||
|
||||
private endingOf(frame: Frame): Ending | null {
|
||||
if (frame.ended === undefined) return null;
|
||||
const end = frame.index.ofType(BEHAVIOR_END)[0];
|
||||
return { port: frame.ended, values: (end && frame.outputCache.get(end.id)) ?? {} };
|
||||
}
|
||||
|
||||
/**
|
||||
* The `On state entered` / `On state exited` nodes watching one machine. A node whose machine
|
||||
* input carries a running value rather than a pick has no state outputs at all, so it is never
|
||||
@@ -161,30 +200,33 @@ export class GraphInterpreter {
|
||||
if (!def?.run) return;
|
||||
const inputs = this.collectInputs(node, ctx);
|
||||
const result = def.run(ctx, inputs, node.params, def, entry, this.lookup);
|
||||
const returned = result.call ? this.call(result.call, node.id, ctx, depth) : {};
|
||||
const produced = { ...result.outputs, ...returned };
|
||||
const returned = result.call ? this.call(result.call, node.id, ctx, depth) : null;
|
||||
const produced = { ...result.outputs, ...returned?.values };
|
||||
if (node.type === BEHAVIOR_END) this.frame.ended = entry;
|
||||
if (!def.read) this.frame.outputCache.set(node.id, produced);
|
||||
this.trace?.onNode(node.id);
|
||||
if (this.trace?.onValues) this.record(node.id, def.read ? this.readAll(node, def, ctx) : produced);
|
||||
if (result.repeat) this.loop(node, result.repeat, ctx, depth);
|
||||
if (result.find) this.search(node, result.find, ctx, depth);
|
||||
const next = result.next === undefined ? [] : Array.isArray(result.next) ? result.next : [result.next];
|
||||
for (const port of next) this.follow(node, port, ctx, depth);
|
||||
// The way out the called graph took comes first, so `exec` reads as "and then" (#294).
|
||||
const ways = returned && returned.port !== 'exec' ? [returned.port, ...next] : next;
|
||||
for (const port of ways) this.follow(node, port, ctx, depth);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs another behavior from its start node (or, lacking one, its `On start` nodes) to its end
|
||||
* node and returns what the end node was handed. The nested graph gets its own frame and a fresh
|
||||
* node and returns how it was left; null when it never got there. The nested graph gets its own frame and a fresh
|
||||
* copy of its variable defaults, so it is a call and not an inlining: nothing of it survives the
|
||||
* return but the values it hands back – and the variables it keeps, which wait for the next call
|
||||
* from the same site.
|
||||
*/
|
||||
private call(call: CallResult, site: string, ctx: NodeContext, depth: number): Record<string, Value> {
|
||||
private call(call: CallResult, site: string, ctx: NodeContext, depth: number): Ending | null {
|
||||
const program = this.lookup.behavior(call.behaviorId);
|
||||
if (!program) return {};
|
||||
if (!program) return null;
|
||||
if (this.callStack.includes(call.behaviorId)) throw new Error(`Behavior "${program.name}" runs itself`);
|
||||
const entries = callEntries(program.graph);
|
||||
if (entries.length === 0) return {};
|
||||
if (entries.length === 0) return null;
|
||||
const sites = [...this.callSites, site].join('/');
|
||||
const kept = program.kept ?? [];
|
||||
const variables = resumedVariables(program.defaults, this.keptCalls.get(sites), kept);
|
||||
@@ -212,10 +254,9 @@ export class GraphInterpreter {
|
||||
try {
|
||||
for (const entry of entries) {
|
||||
this.trace?.onNode(entry.id);
|
||||
this.follow(entry, 'exec', inner, depth + 1);
|
||||
this.follow(entry, call.entry, inner, depth + 1);
|
||||
}
|
||||
const end = terminalNode(program.graph, BEHAVIOR_END);
|
||||
return (end && this.frame.outputCache.get(end.id)) ?? {};
|
||||
return this.endingOf(this.frame);
|
||||
} finally {
|
||||
this.callStack.pop();
|
||||
this.callSites.pop();
|
||||
|
||||
@@ -61,6 +61,8 @@ export interface RepeatResult {
|
||||
export interface CallResult {
|
||||
behaviorId: string;
|
||||
inputs: Record<string, Value>;
|
||||
/** The flow input the call came in by, which is the output its start node leaves through (#294). */
|
||||
entry: string;
|
||||
}
|
||||
|
||||
export interface RunResult {
|
||||
|
||||
@@ -20,6 +20,7 @@ import { agreedType, type SharedPortGroup } from './portTypes';
|
||||
export const BEHAVIOR_START = 'BehaviorStart';
|
||||
export const BEHAVIOR_END = 'BehaviorEnd';
|
||||
export const RUN_BEHAVIOR = 'RunBehavior';
|
||||
export const ON_BEHAVIOR = 'OnBehavior';
|
||||
export const VARIABLES = 'Variables';
|
||||
export const PROPERTIES = 'Properties';
|
||||
const ON_START = 'OnStart';
|
||||
@@ -123,6 +124,16 @@ export function isTerminalNode(node: GraphNode): boolean {
|
||||
return isTerminalType(node.type);
|
||||
}
|
||||
|
||||
/** The two nodes that stand for another behavior: the one running it, the one listening to it (#294). */
|
||||
export function namesBehavior(type: string): boolean {
|
||||
return type === RUN_BEHAVIOR || type === ON_BEHAVIOR;
|
||||
}
|
||||
|
||||
/** A further flow port of a start or end node, next to its fixed `exec` (#294). */
|
||||
export function isFlowPort(port: DeclaredPort): boolean {
|
||||
return port.kind === 'flow';
|
||||
}
|
||||
|
||||
/**
|
||||
* A tagged kind is one the value cannot show, so its port carries the field that edits it – except
|
||||
* an object, which nothing can type in.
|
||||
@@ -324,6 +335,7 @@ export function ghostProblem(node: GraphNode, graph: Graph, def: NodeDef): strin
|
||||
* `Lerp` depends on another asset as well, the curve it eases along (#247), and says so here too.
|
||||
*/
|
||||
export function callProblem(node: GraphNode, lookup: GraphLookup, ownerId = ''): string | null {
|
||||
if (node.type === ON_BEHAVIOR) return listenProblem(node, lookup, ownerId);
|
||||
if (node.type !== RUN_BEHAVIOR) return lerpProblem(node, lookup);
|
||||
const id = textOf(node.params[BEHAVIOR_PARAM] ?? '');
|
||||
if (!id) return 'No behavior picked';
|
||||
@@ -334,6 +346,39 @@ export function callProblem(node: GraphNode, lookup: GraphLookup, ownerId = ''):
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Why an `On behavior` never fires: it hears nothing, itself, or a graph without an end to reach. */
|
||||
function listenProblem(node: GraphNode, lookup: GraphLookup, ownerId: string): string | null {
|
||||
const id = textOf(node.params[BEHAVIOR_PARAM] ?? '');
|
||||
if (!id) return 'No behavior picked';
|
||||
const program = lookup.behavior(id);
|
||||
if (!program) return 'That behavior is gone';
|
||||
if (ownerId && listensTo(lookup, id, ownerId)) return 'A behavior cannot listen to itself';
|
||||
if (!terminalNode(program.graph, BEHAVIOR_END)) return 'No End node – never fires';
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The behaviors the `On behavior` nodes of that graph name, picked or not found alike. */
|
||||
export function heardBehaviors(graph: Graph): string[] {
|
||||
return graph.nodes
|
||||
.filter((n) => n.type === ON_BEHAVIOR)
|
||||
.map((n) => textOf(n.params[BEHAVIOR_PARAM] ?? ''))
|
||||
.filter((id) => id !== '');
|
||||
}
|
||||
|
||||
/** Whether `from` is `target` or hears it, however many behaviors lie between. */
|
||||
export function listensTo(
|
||||
lookup: GraphLookup,
|
||||
from: string,
|
||||
target: string,
|
||||
seen: Set<string> = new Set(),
|
||||
): boolean {
|
||||
if (from === target) return true;
|
||||
if (seen.has(from)) return false;
|
||||
seen.add(from);
|
||||
const program = lookup.behavior(from);
|
||||
return program ? heardBehaviors(program.graph).some((id) => listensTo(lookup, id, target, seen)) : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { NodeDef } from '../../NodeRegistry';
|
||||
import { textOf } from '../../../model/Properties';
|
||||
import { BEHAVIOR_END, BEHAVIOR_PARAM, BEHAVIOR_START, declaredPorts, ON_BEHAVIOR } from '../../nested';
|
||||
import { exec } from '../shared';
|
||||
|
||||
/**
|
||||
* Another behavior used as an event (#294): it lives at this node for as long as the behavior around
|
||||
* it runs, its own events fire, and each of its pulses that reaches its end node goes on here. The
|
||||
* running game keeps that second behavior; the interpreter only ever sees the pulse arriving.
|
||||
*/
|
||||
export const OnBehavior: NodeDef = {
|
||||
type: ON_BEHAVIOR,
|
||||
label: 'On behavior',
|
||||
category: 'event',
|
||||
description:
|
||||
'Listens to another behavior. That behavior runs here with its own events and variables, and ' +
|
||||
'whenever one of its flows reaches its End, this node fires: through the output named like ' +
|
||||
'the flow port the End was reached by last, with the values the End was handed. The inputs ' +
|
||||
'are what its Start hands out.',
|
||||
inputs: [],
|
||||
outputs: [exec()],
|
||||
params: [{ key: BEHAVIOR_PARAM, label: 'Behavior', kind: 'asset', default: '', assetTypes: ['behavior'] }],
|
||||
derivePorts: ({ node, lookup }) => {
|
||||
const program = lookup.behavior(textOf(node.params[BEHAVIOR_PARAM] ?? ''));
|
||||
return {
|
||||
label: program ? `On ${program.name}` : undefined,
|
||||
// No flow in: the behavior starts its own pulses, so the ways into its Start have no use here.
|
||||
inputs: declaredPorts(program?.graph, BEHAVIOR_START).filter((port) => port.type !== 'exec'),
|
||||
outputs: declaredPorts(program?.graph, BEHAVIOR_END),
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -13,7 +13,8 @@ export const BehaviorEnd: NodeDef = {
|
||||
category: 'flow',
|
||||
description:
|
||||
'Ends this behavior and hands its results back to the graph that ran it. Every output declared ' +
|
||||
'here becomes an output port on that node.',
|
||||
'here becomes an output port on that node. An output of the kind Flow is a further way out: ' +
|
||||
'the node that ran or hears this behavior goes on through the one reached last.',
|
||||
inputs: [exec()],
|
||||
outputs: [],
|
||||
params: [],
|
||||
|
||||
@@ -12,7 +12,8 @@ export const BehaviorStart: NodeDef = {
|
||||
category: 'event',
|
||||
description:
|
||||
'Where this behavior begins when another graph runs it as a node. Every input declared here ' +
|
||||
'becomes an input port on that node.',
|
||||
'becomes an input port on that node. An input of the kind Flow is a further way in: a call ' +
|
||||
'arriving through it leaves here through the output of that name and not through the plain one.',
|
||||
inputs: [],
|
||||
outputs: [exec()],
|
||||
params: [],
|
||||
|
||||
@@ -16,7 +16,9 @@ export const RunBehavior: NodeDef = {
|
||||
'Runs another behavior as a step of this one, passing values in and taking results out. It ' +
|
||||
'begins at the Behavior start node, or at On start if that behavior has none. A ' +
|
||||
'variable marked Keep in that behavior carries on from the last call of this node on this ' +
|
||||
'object; the others start at their defaults every time.',
|
||||
'object; the others start at their defaults every time. A flow port declared at that ' +
|
||||
"behavior's Start is a further way in, one declared at its End a further way out: the " +
|
||||
'call leaves through the one its End was reached by last, and then through the plain one.',
|
||||
inputs: [exec()],
|
||||
outputs: [exec()],
|
||||
params: [{ key: BEHAVIOR_PARAM, label: 'Behavior', kind: 'asset', default: '', assetTypes: ['behavior'] }],
|
||||
@@ -29,8 +31,8 @@ export const RunBehavior: NodeDef = {
|
||||
outputs: declaredPorts(program?.graph, BEHAVIOR_END),
|
||||
};
|
||||
},
|
||||
run: (_ctx, inputs, params) => ({
|
||||
call: { behaviorId: textOf(params[BEHAVIOR_PARAM] ?? ''), inputs },
|
||||
run: (_ctx, inputs, params, _def, entry) => ({
|
||||
call: { behaviorId: textOf(params[BEHAVIOR_PARAM] ?? ''), inputs, entry },
|
||||
next: 'exec',
|
||||
}),
|
||||
};
|
||||
@@ -106,6 +106,7 @@ import { SetItem } from './data/SetItem';
|
||||
import { SubList } from './data/SubList';
|
||||
import { TextureSize } from './data/TextureSize';
|
||||
import { OnAnimationFinished } from './events/OnAnimationFinished';
|
||||
import { OnBehavior } from './events/OnBehavior';
|
||||
import { OnClick } from './events/OnClick';
|
||||
import { OnMouseWheel } from './events/OnMouseWheel';
|
||||
import { OnCollisionEnter } from './events/OnCollisionEnter';
|
||||
@@ -160,6 +161,7 @@ export const BUILT_IN_NODES: readonly NodeDef[] = [
|
||||
OnClick,
|
||||
OnMouseWheel,
|
||||
OnAnimationFinished,
|
||||
OnBehavior,
|
||||
OnStateEntered,
|
||||
OnStateExited,
|
||||
BehaviorStart,
|
||||
|
||||
@@ -176,6 +176,8 @@ export const KINDS = [
|
||||
},
|
||||
{ kind: 'list', label: 'List', travels: 'list', variable: true, port: true },
|
||||
{ kind: 'struct', label: 'Struct', travels: 'struct', variable: true, port: true },
|
||||
/** No value at all: a start or end node declares a further flow port with it (#294). */
|
||||
{ kind: 'flow', label: 'Flow', travels: 'exec', port: true },
|
||||
// Schema-only kinds: a setting has them, nothing a user declares does.
|
||||
{ kind: 'enum', label: 'Choice', travels: 'string', empty: '', coerce: text },
|
||||
/** A keyboard key name (`KeyboardEvent.key`), captured by pressing it. */
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
findNode,
|
||||
type GraphNode,
|
||||
nodeDef,
|
||||
RUN_BEHAVIOR,
|
||||
namesBehavior,
|
||||
} from '../core/graph';
|
||||
import type { GraphAsset } from '../core/model/Asset';
|
||||
import { type Clip, copyGraph, copyObjects, type GraphClip, type ObjectClip } from '../core/model/clipboard';
|
||||
@@ -160,7 +160,7 @@ function fitsGraph(project: Project, asset: GraphAsset, node: GraphNode): boolea
|
||||
return paletteEntries(project, asset).some(
|
||||
(entry) =>
|
||||
entry.def.type === node.type &&
|
||||
(node.type !== RUN_BEHAVIOR || entry.params[BEHAVIOR_PARAM] === node.params[BEHAVIOR_PARAM]),
|
||||
(!namesBehavior(node.type) || entry.params[BEHAVIOR_PARAM] === node.params[BEHAVIOR_PARAM]),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
type PortDef,
|
||||
type PortSide,
|
||||
resolveDef,
|
||||
namesBehavior,
|
||||
RUN_BEHAVIOR,
|
||||
startStateOf,
|
||||
} from '../../core/graph';
|
||||
@@ -627,7 +628,7 @@ export class GraphCanvas extends Widget {
|
||||
}
|
||||
|
||||
private openCalledBehavior(node: GraphNode): boolean {
|
||||
if (node.type !== RUN_BEHAVIOR) return false;
|
||||
if (!namesBehavior(node.type)) return false;
|
||||
const id = textOf(node.params[BEHAVIOR_PARAM] ?? '');
|
||||
const asset = id ? findAsset(this.state.project, id) : undefined;
|
||||
if (asset?.type !== 'behavior') return false;
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
import { searchRank } from '../../ui/search';
|
||||
import {
|
||||
allNodeDefs,
|
||||
BEHAVIOR_END,
|
||||
BEHAVIOR_PARAM,
|
||||
createEmptyGraph,
|
||||
isTerminalType,
|
||||
namesBehavior,
|
||||
nextStateName,
|
||||
type NodeCategory,
|
||||
type NodeDef,
|
||||
ON_BEHAVIOR,
|
||||
resolveDef,
|
||||
RUN_BEHAVIOR,
|
||||
State,
|
||||
@@ -83,7 +86,8 @@ function filterEntry(find: NodeDef): PaletteEntry {
|
||||
* The node types offerable in `asset`'s graph. A state machine holds states and nothing else, each
|
||||
* new one named by its number; a shader holds shader nodes, its one Output dropping out once
|
||||
* placed. In a behavior, every other behavior appears under its own name instead of behind a
|
||||
* generic "Run behavior", and the two terminals drop out once the graph has them.
|
||||
* generic "Run behavior" – and once more as the event "On <name>" if it has an End to be heard
|
||||
* through (#294) –, and the two terminals drop out once the graph has them.
|
||||
*/
|
||||
export function paletteEntries(project: Project, asset: GraphAsset): PaletteEntry[] {
|
||||
if (asset.type === 'statemachine') {
|
||||
@@ -109,7 +113,7 @@ export function paletteEntries(project: Project, asset: GraphAsset): PaletteEntr
|
||||
}
|
||||
const entries: PaletteEntry[] = [];
|
||||
for (const def of allNodeDefs()) {
|
||||
if (def.type === RUN_BEHAVIOR || def.category === 'state') continue;
|
||||
if (namesBehavior(def.type) || def.category === 'state') continue;
|
||||
if (def.category === 'shader' || def.category === 'particles') continue;
|
||||
if (isTerminalType(def.type) && terminalNode(asset.graph, def.type)) continue;
|
||||
entries.push({ id: def.type, hint: def.category, def, params: {} });
|
||||
@@ -121,8 +125,12 @@ export function paletteEntries(project: Project, asset: GraphAsset): PaletteEntr
|
||||
if (other.type !== 'behavior' || other.id === asset.id) continue;
|
||||
const params = { [BEHAVIOR_PARAM]: other.id };
|
||||
// The entry is a preview of a node that sits in no graph yet, hence the empty one.
|
||||
const def = resolveDef({ id: '', type: RUN_BEHAVIOR, x: 0, y: 0, params }, createEmptyGraph(), lookup);
|
||||
const preview = (type: string) =>
|
||||
resolveDef({ id: '', type, x: 0, y: 0, params }, createEmptyGraph(), lookup);
|
||||
const def = preview(RUN_BEHAVIOR);
|
||||
if (def) entries.push({ id: `${RUN_BEHAVIOR}:${other.id}`, hint: 'behavior', def, params });
|
||||
const heard = terminalNode(other.graph, BEHAVIOR_END) ? preview(ON_BEHAVIOR) : undefined;
|
||||
if (heard) entries.push({ id: `${ON_BEHAVIOR}:${other.id}`, hint: 'event', def: heard, params });
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
@@ -231,7 +231,9 @@ export function buildPortSection(
|
||||
if (noun === 'Field') addShapePicker(host, assetId, node, variables, header);
|
||||
const add = new Dropdown(`+ ${noun}`, { variant: 'ghost' });
|
||||
add.onClick = () => {
|
||||
const items = kindMenu(DECLARED_PORT_KINDS, (kind) =>
|
||||
// A further way in or out is a start or end node's to declare; a struct has fields only.
|
||||
const kinds = DECLARED_PORT_KINDS.filter((kind) => kind !== 'flow' || noun !== 'Field');
|
||||
const items = kindMenu(kinds, (kind) =>
|
||||
host.state.execute(new AddPortCommand(assetId, node.id, { key: nextPortName(node, base), kind })),
|
||||
);
|
||||
new Menu(items).openBelow(add);
|
||||
@@ -246,8 +248,8 @@ export function buildPortSection(
|
||||
noun === 'Field'
|
||||
? 'No fields yet. Every field added here becomes a port of the struct.'
|
||||
: onStart
|
||||
? 'No inputs yet. Every input added here becomes a port on the node that runs this behavior.'
|
||||
: 'No outputs yet. Every output added here becomes a result of running this behavior.',
|
||||
? 'No inputs yet. Every input added here becomes a port on the node that runs this behavior; one of the kind Flow is a further way in.'
|
||||
: 'No outputs yet. Every output added here becomes a result of running this behavior; one of the kind Flow is a further way out.',
|
||||
);
|
||||
|
||||
for (const port of ports) portRow(host, assetId, node, port, portNameField(host, assetId, node, port));
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" id="kind-flow" viewBox="-8 -8 16 16" width="16" height="16">
|
||||
<path d="M-3 -4.5 L4 0 L-3 4.5 Z" fill="currentColor" stroke="none" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 181 B |
@@ -13,6 +13,7 @@ import animation from './icons/kind-animation.svg?raw';
|
||||
import asset from './icons/kind-asset.svg?raw';
|
||||
import boolean from './icons/kind-boolean.svg?raw';
|
||||
import color from './icons/kind-color.svg?raw';
|
||||
import flow from './icons/kind-flow.svg?raw';
|
||||
import list from './icons/kind-list.svg?raw';
|
||||
import object from './icons/kind-object.svg?raw';
|
||||
import scene from './icons/kind-scene.svg?raw';
|
||||
@@ -30,6 +31,7 @@ export const KIND_ICON_SVG: Partial<Record<Kind, string>> = {
|
||||
asset,
|
||||
boolean,
|
||||
color,
|
||||
flow,
|
||||
list,
|
||||
object,
|
||||
scene,
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
import {
|
||||
adoptDeclarations,
|
||||
asBoolean,
|
||||
BEHAVIOR_PARAM,
|
||||
buildSharedState,
|
||||
carriedForward,
|
||||
declaredVariables,
|
||||
emptySharedState,
|
||||
type Graph,
|
||||
GraphInterpreter,
|
||||
type GraphNode,
|
||||
hierarchyRanks,
|
||||
inEventOrder,
|
||||
isHandleEnabled,
|
||||
type NodeContext,
|
||||
ON_BEHAVIOR,
|
||||
restartedAssets,
|
||||
restoreSaved,
|
||||
type SaveArea,
|
||||
@@ -356,6 +359,7 @@ export class BehaviorSystem implements System {
|
||||
this.instances.push(instance);
|
||||
born.add(instance);
|
||||
}
|
||||
if (born.size > 0 || this.unranked) this.syncHeard(world, born);
|
||||
if (born.size > 0 || this.unranked) this.rank(world);
|
||||
const fresh = this.instances.filter((i) => born.has(i));
|
||||
for (const instance of fresh) this.enterStartStates(instance, (starts ??= startStates(this.project)));
|
||||
@@ -365,6 +369,66 @@ export class BehaviorSystem implements System {
|
||||
this.flushStateChanges();
|
||||
}
|
||||
|
||||
/**
|
||||
* One further instance per `On behavior` node (#294), on the entity of the behavior holding it and
|
||||
* for as long as that one runs – and so on down, since the behavior heard may listen in turn. An
|
||||
* edit to a graph while it runs adds and drops them like objects coming and going.
|
||||
*/
|
||||
private syncHeard(world: World, born: Set<Instance>): void {
|
||||
const held = new Map<Instance, Instance[]>();
|
||||
for (const instance of this.instances) {
|
||||
const host = instance.host?.instance;
|
||||
if (host) held.set(host, [...(held.get(host) ?? []), instance]);
|
||||
}
|
||||
const dropped: Instance[] = [];
|
||||
const drop = (instance: Instance) => {
|
||||
dropped.push(instance);
|
||||
for (const below of held.get(instance) ?? []) drop(below);
|
||||
};
|
||||
const visit = (host: Instance, chain: readonly string[]) => {
|
||||
const below = held.get(host) ?? [];
|
||||
const kept = new Set<Instance>();
|
||||
for (const node of host.interpreter.eventNodes(ON_BEHAVIOR)) {
|
||||
const behaviorId = textOf(node.params[BEHAVIOR_PARAM] ?? '');
|
||||
// A behavior hearing itself, however far round, would be built without end.
|
||||
if (chain.includes(behaviorId) || !findAssetOf(this.project, behaviorId, 'behavior')) continue;
|
||||
const heard =
|
||||
below.find((i) => i.host?.nodeId === node.id && i.host.behaviorId === behaviorId) ??
|
||||
this.hear(host, node.id, behaviorId, world);
|
||||
if (!heard) continue;
|
||||
if (!below.includes(heard)) born.add(heard);
|
||||
kept.add(heard);
|
||||
visit(heard, [...chain, behaviorId]);
|
||||
}
|
||||
for (const instance of below) if (!kept.has(instance)) drop(instance);
|
||||
};
|
||||
for (const instance of [...this.instances])
|
||||
if (!instance.host) visit(instance, [instance.entity.assetId]);
|
||||
if (dropped.length === 0) return;
|
||||
this.instances = this.instances.filter((i) => !dropped.includes(i));
|
||||
this.finish(dropped);
|
||||
}
|
||||
|
||||
/** A running copy of that behavior for one `On behavior` node, with variables of its own. */
|
||||
private hear(host: Instance, nodeId: string, behaviorId: string, world: World): Instance | null {
|
||||
const lookup = graphLookup(this.project);
|
||||
const program = lookup.behavior(behaviorId);
|
||||
if (!program) return null;
|
||||
const heard: Instance = {
|
||||
entity: host.entity,
|
||||
interpreter: new GraphInterpreter(program.graph, lookup, this.graphs),
|
||||
trace: { edges: new Map(), nodes: new Map() },
|
||||
values: new Map(),
|
||||
states: {},
|
||||
active: true,
|
||||
host: { instance: host, nodeId, behaviorId },
|
||||
variables: structuredClone(program.defaults),
|
||||
};
|
||||
this.listen(heard, world);
|
||||
this.instances.push(heard);
|
||||
return heard;
|
||||
}
|
||||
|
||||
/** Has the instance note what it runs, timed by the world it runs in. */
|
||||
private listen({ interpreter, trace, values }: Instance, world: World): void {
|
||||
interpreter.trace = {
|
||||
@@ -488,7 +552,8 @@ export class BehaviorSystem implements System {
|
||||
this.runPulses(pulsesOf(instances, 'OnDestroy'), contextOf);
|
||||
// After `On destroy`, not before: that graph may still say something, and a sound it wants to
|
||||
// outlive the object says so itself by being detached.
|
||||
for (const instance of instances) this.audio.stopOwner(instance.entity.id);
|
||||
// Its sounds are the entity's, so they end with the behavior placed there and not with one it hears.
|
||||
for (const instance of instances) if (!instance.host) this.audio.stopOwner(instance.entity.id);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -579,7 +644,7 @@ export class BehaviorSystem implements System {
|
||||
}
|
||||
|
||||
runningIds(): string[] {
|
||||
return this.instances.map((i) => i.entity.objectId);
|
||||
return this.instances.filter((i) => !i.host).map((i) => i.entity.objectId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -594,7 +659,8 @@ export class BehaviorSystem implements System {
|
||||
const graph = findAssetOf(this.project, assetId, 'behavior')?.graph;
|
||||
const newest = new Map<string, Produced>();
|
||||
for (const instance of this.instances) {
|
||||
if (instance.entity.assetId !== assetId && !instance.interpreter.calledBehaviors.has(assetId)) continue;
|
||||
const own = instance.host?.behaviorId ?? instance.entity.assetId;
|
||||
if (own !== assetId && !instance.interpreter.calledBehaviors.has(assetId)) continue;
|
||||
latest(merged.edges, instance.trace.edges);
|
||||
latest(merged.nodes, instance.trace.nodes);
|
||||
for (const [id, produced] of (graph && instance.values.get(graph)) ?? []) {
|
||||
@@ -617,7 +683,9 @@ export class BehaviorSystem implements System {
|
||||
for (const { instance, node, outputs, port } of inEventOrder(pulses)) {
|
||||
if (living && !world.entities.includes(instance.entity)) continue;
|
||||
try {
|
||||
this.give(instance, contextOf);
|
||||
instance.interpreter.pulse(node, contextOf(instance), outputs, port);
|
||||
this.surface(instance, contextOf);
|
||||
} catch (error) {
|
||||
world.log.push(
|
||||
`${ERROR_PREFIX} "${instance.entity.name}": ${error instanceof Error ? error.message : String(error)}`,
|
||||
@@ -627,6 +695,33 @@ export class BehaviorSystem implements System {
|
||||
}
|
||||
}
|
||||
|
||||
/** The `On behavior` node an instance is heard by, as the graph holds it now. */
|
||||
private hearing(instance: Instance): { host: Instance; node: GraphNode } | null {
|
||||
const host = instance.host;
|
||||
const node = host?.instance.interpreter.eventNodes(ON_BEHAVIOR).find((n) => n.id === host.nodeId);
|
||||
return host && node ? { host: host.instance, node } : null;
|
||||
}
|
||||
|
||||
/** A heard behavior's start node hands out the inputs of the node hearing it, read anew for each pulse. */
|
||||
private give(instance: Instance, contextOf: (instance: Instance) => NodeContext): void {
|
||||
const heard = this.hearing(instance);
|
||||
if (heard)
|
||||
instance.interpreter.given = heard.host.interpreter.eventInputs(heard.node, contextOf(heard.host));
|
||||
}
|
||||
|
||||
/**
|
||||
* A pulse of a heard behavior that reached its end node goes on at the node hearing it, through
|
||||
* the output named like the way it took – and from there further up, if that graph ends in turn.
|
||||
*/
|
||||
private surface(instance: Instance, contextOf: (instance: Instance) => NodeContext): void {
|
||||
for (let inner = instance; inner.host; inner = inner.host.instance) {
|
||||
const ending = inner.interpreter.ending;
|
||||
const heard = this.hearing(inner);
|
||||
if (!ending || !heard) return;
|
||||
heard.host.interpreter.pulse(heard.node, contextOf(heard.host), ending.values, ending.port);
|
||||
}
|
||||
}
|
||||
|
||||
/** One context per instance for as long as the answer is used – a frame, or one round of events. */
|
||||
private contexts(world: World, dt: number): (instance: Instance) => NodeContext {
|
||||
const made = new Map<Instance, NodeContext>();
|
||||
|
||||
@@ -52,7 +52,7 @@ export function behaviorContext(
|
||||
return {
|
||||
self: entity,
|
||||
owner: entity.parent,
|
||||
variables: entity.props,
|
||||
variables: instance.variables ?? entity.props,
|
||||
states,
|
||||
shared: run.shared,
|
||||
stateChanged: (machineId, from, to) => run.stateChanged(machineId, from, to),
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
import { asNumber, type Graph, type GraphInterpreter, type GraphNode, type Value } from '../../core/graph';
|
||||
import { stepKeyRepeat } from '../../core/graph/keyRepeat';
|
||||
import { keyName } from '../../core/keys';
|
||||
import { textOf } from '../../core/model/Properties';
|
||||
import { type PropertyBag, textOf } from '../../core/model/Properties';
|
||||
import { parentChain } from '../../core/model/walk';
|
||||
import type { Entity } from '../Entity';
|
||||
import type { AnimationSystem } from './AnimationSystem';
|
||||
@@ -29,6 +29,13 @@ export interface Instance {
|
||||
states: Record<string, string>;
|
||||
/** Whether the behavior was effectively on when last looked at; a change fires On enable/On disable. */
|
||||
active: boolean;
|
||||
/**
|
||||
* Set on a behavior an `On behavior` node listens to (#294): it runs on the same entity as the
|
||||
* one holding that node, which hears every pulse of it that reaches the end node.
|
||||
*/
|
||||
host?: { instance: Instance; nodeId: string; behaviorId: string };
|
||||
/** Its own variables, where it has a host; the entity's belong to the behavior placed on it. */
|
||||
variables?: PropertyBag;
|
||||
}
|
||||
|
||||
/** One event node about to run for one instance: what the event hands it, and the output it leaves by. */
|
||||
|
||||
Reference in new issue
Block a user