Query objects in bulk and filter, count or test a list (#259)
game-maker / gate (push) Successful in 3m36s
game-maker / suite (push) Failing after 10m6s

The object queries only ever returned one object: Object by name,
Child by name and Find all stop at the first hit. Getting every coin,
every child or every item that passes a test needed a For each with
its own bookkeeping. These nodes return the whole set as a list of
Object, so For each and Find can use item straight away.

- Objects by name returns every scene object with that name in scene
  order.
- Children by name returns every match below object, nearer levels
  first, the same order as the singular node.
- Children returns the direct children, with recursive all of them
  level by level.
- Objects of asset returns every instance of an object asset or
  container by the same rule as Is asset, spawned ones included.
- All four take a snapshot. Destroyed objects are never in it,
  disabled ones are, as with the singular nodes.
- Find has a Mode setting: First, All, Any and Count. First is the
  default and hides the row, so existing graphs look the same.
- Match follows the mode of its paired Find: done with items and
  indices, done with any, or done with count. An unpaired Match shows
  First, since the pairing only comes from the wiring.
- First and Any stop at the first hit, All and Count walk the list.
- Changing the mode drops edges at outputs the Match no longer has,
  in one undo step. SetNodeParamCommand now cleans the whole graph,
  but only edges that were valid before the change.
- The palette entry "filter" adds a Find set to All with its Match.

Found on the way:

- After adding the filter entry, "find" + Enter picked Filter. The
  entry has node type Find, counted as an exact hit, and the tie went
  to the alphabet. The search now ranks by the entry id. e2e 6z-v
  caught it.

Tests:

- ./check.sh: 188 files, 2746 tests, CHECK EXIT 0.
- find-modes.test.ts with 11 tests, 11 catalog cases for the four
  nodes, the asset input guard now expects 3.
- e2e 6z-vii with 3 checks: filter from the palette, Count picked in
  the inspector drops the items edge, a run logs 2, 2, 2, 3, 4, "0, 2".
- GM_STEPS=1-6: all passed, 278 checks.
- Counter-checks fail as expected: every mode stopping early (2),
  Match ignoring the mode (6), cleanup on the own node only (1), no
  recursion (2), no inOrder (2), old ranking (1). In the browser a
  Match ignoring the mode fails both editor checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
adminandClaude Opus 5.5 committed 2026-09-28 15:43:03 +02:00
1 parent f84defb9b6
commit 4e6aeb5f72
22 files changed
+671 -35

No files matched your search

+18 -8
View File
@@ -2,10 +2,12 @@ import {
edgesInto,
edgesOfNode,
findNode,
type Graph,
type GraphEdge,
type GraphNode,
portsCompatible,
} from '../graph/Graph';
import type { GraphLookup } from '../graph/lookup';
import { isTerminalType, resolveDef, terminalNode } from '../graph/nested';
import { nextTransitionName, parallelTransitions } from '../graph/stateMachine';
import { nodeDef } from '../graph/NodeRegistry';
@@ -148,18 +150,16 @@ export class SetNodeParamCommand extends SetBagValueCommand<GraphNode> {
}
override execute(project: Project): void {
super.execute(project);
const graph = requireGraph(project, this.assetId);
const node = requireNode(project, this.assetId, this.nodeId);
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));
const lookup = graphLookup(project);
// A param can reshape another node too – a Find's mode decides its Match's outputs (#259).
const held = new Set(graph.edges.filter((e) => edgeHolds(graph, e, lookup)));
super.execute(project);
this.orphans = removeWhere(
graph.edges,
(e) =>
(e.from.node === this.nodeId && !outputs.has(e.from.port)) ||
(e.to.node === this.nodeId && !inputs.has(e.to.port)),
(held.has(e) || e.from.node === this.nodeId || e.to.node === this.nodeId) &&
!edgeHolds(graph, e, lookup),
);
}
@@ -183,6 +183,16 @@ export class SetNodeParamCommand extends SetBagValueCommand<GraphNode> {
}
}
/** Whether both ends of an edge name a port their node has; a node of unknown type is not judged. */
function edgeHolds(graph: Graph, edge: GraphEdge, lookup: GraphLookup): boolean {
const has = (end: GraphEdge['from'], side: 'inputs' | 'outputs') => {
const node = findNode(graph, end.node);
const def = node && resolveDef(node, graph, lookup);
return !def || def[side].some((p) => p.key === end.port);
};
return has(edge.from, 'outputs') && has(edge.to, 'inputs');
}
/** A data input holds at most one edge, so an existing one is replaced (and restored on undo). */
export class ConnectCommand implements Command {
readonly label = 'Connect';
+13 -12
View File
@@ -1,4 +1,4 @@
import { blockProblem, MATCH_INPUT, matchOf } from './findBlock';
import { blockProblem, findMode, MATCH_INPUT, matchOf, searchOutcome, stopsAtHit } from './findBlock';
import { edgesInto, edgesOutOf, type Graph, type GraphNode } from './Graph';
import { type GraphLookup, NO_LOOKUP } from './lookup';
import { BEHAVIOR_END, callEntries, runDef, terminalNode } from './nested';
@@ -252,8 +252,9 @@ export class GraphInterpreter {
/**
* A Find's rounds: its `item` and `index` are set to one element after the other, and the Match
* closing the block reads its test anew each time, the way a loop's stop input is read. The first
* true one ends the search. Both nodes then hold the hit, and the flow goes on from the Match.
* closing the block reads its test anew each time, the way a loop's stop input is read. Its mode
* says whether the first true one ends the search; the Match then holds the outcome, and the flow
* goes on from there.
*/
private search(find: GraphNode, values: readonly Value[], ctx: NodeContext, depth: number): void {
const match = matchOf(this.frame.graph, find.id);
@@ -262,7 +263,8 @@ export class GraphInterpreter {
ctx.log(`Find: ${blockProblem(this.frame.graph, find) ?? 'no Match closes it'}`);
return;
}
let hit = -1;
const mode = findMode(find);
const hits: number[] = [];
for (let round = 0; round < values.length; round++) {
if (++this.steps > MAX_STEPS_PER_FIRE)
throw new Error('Behavior graph exceeded the step limit (endless loop?)');
@@ -271,18 +273,17 @@ export class GraphInterpreter {
this.frame.outputCache.set(find.id, roundOutputs);
this.record(find.id, roundOutputs);
if (asBoolean(this.inputValue(match, test, ctx))) {
hit = round;
break;
hits.push(round);
if (stopsAtHit(mode)) break;
}
}
this.frame.dataCache.clear();
const found = hit >= 0;
const outputs = found ? { item: values[hit] ?? null, index: hit } : { item: null, index: -1 };
this.frame.outputCache.set(find.id, outputs);
this.frame.outputCache.set(match.id, outputs);
const outcome = searchOutcome(mode, values, hits);
this.frame.outputCache.set(find.id, outcome.find);
this.frame.outputCache.set(match.id, outcome.match);
this.trace?.onNode(match.id);
this.record(match.id, outputs);
this.follow(match, found ? 'found' : 'notFound', ctx, depth);
this.record(match.id, outcome.match);
this.follow(match, outcome.next, ctx, depth);
}
/** Resolves every data input: connected → pulled from the source, else the inline param. */
+2
View File
@@ -148,6 +148,8 @@ export interface NodeContext {
findReferenced(from: EntityHandle, ref: string): EntityHandle | null;
/** The nearest object called `name` below `parent` – a child before a grandchild; null for none. */
childByName(parent: EntityHandle, name: string): EntityHandle | null;
/** Every object in the game right now, in scene order – what the plural lookups filter (#259). */
objects(): readonly EntityHandle[];
isKeyDown(key: string): boolean;
pointer: PointerState;
/**
+2
View File
@@ -89,6 +89,8 @@ export interface DerivedShape {
label?: string;
inputs?: PortDef[];
outputs?: PortDef[];
/** The ports stand in the order given instead of exec pins first – a node laying out a whole side. */
inOrder?: true;
}
/** Palette, port rendering, connection validation and inspector fields are all derived from this. */
+49
View File
@@ -1,5 +1,6 @@
import { findNode, type Graph, type GraphEdge, type GraphNode } from './Graph';
import { nodeDef } from './NodeRegistry';
import { asValueItem, type Value } from './values';
/*
* A `Find` … `Match` block is not stored anywhere: it is the wiring. A Match closes the one Find its
@@ -12,6 +13,54 @@ export const MATCH = 'Match';
/** The boolean input a `Match` reads its test from. */
export const MATCH_INPUT = 'match';
/** The Find's setting saying what its block answers (#259); a Find saved without one is `first`. */
export const FIND_MODE = 'mode';
export type FindMode = 'first' | 'all' | 'any' | 'count';
const MODES: readonly FindMode[] = ['first', 'all', 'any', 'count'];
export function findMode(node: GraphNode): FindMode {
const mode = node.params[FIND_MODE];
return MODES.find((m) => m === mode) ?? 'first';
}
/** The mode of the Find a Match's test is built from; `first` while it is built from none or several. */
export function matchMode(graph: Graph, match: GraphNode): FindMode {
const finds = findsOf(graph, match);
return finds.length === 1 ? findMode(finds[0]!) : 'first';
}
/**
* Whether the search goes on after a hit. `first` and `any` have their answer with the first one;
* `all` and `count` look at every element.
*/
export function stopsAtHit(mode: FindMode): boolean {
return mode === 'first' || mode === 'any';
}
/**
* What a finished search hands on: the exec output of the Match to continue along, what the Match
* holds, and what the Find is left holding. `hits` are the indices the test was true for.
*/
export function searchOutcome(
mode: FindMode,
values: readonly Value[],
hits: readonly number[],
): { next: string; match: Record<string, Value>; find: Record<string, Value> } {
const first = hits[0];
const none = { item: null, index: -1 };
if (mode === 'first') {
const held = first === undefined ? none : { item: values[first] ?? null, index: first };
return { next: first === undefined ? 'notFound' : 'found', match: held, find: held };
}
const match: Record<string, Value> =
mode === 'all'
? { items: hits.map((i) => asValueItem(values[i] ?? null)), indices: [...hits] }
: mode === 'any'
? { any: first !== undefined }
: { count: hits.length };
return { next: 'done', match, find: none };
}
function isExecPort(type: string | undefined, key: string, side: 'inputs' | 'outputs'): boolean {
return (type && nodeDef(type)?.[side].find((p) => p.key === key)?.type) === 'exec';
}
+4 -1
View File
@@ -181,7 +181,10 @@ function shapedDef(
def.declaredPort ? def.declaredPort(p, node) : portDefOf(p),
);
const grown = def.derivePorts?.({ node, graph, lookup }) ?? {};
const side = (key: 'inputs' | 'outputs') => execFirst([...def[key], ...(grown[key] ?? []), ...own(key)]);
const side = (key: 'inputs' | 'outputs') => {
const ports = [...def[key], ...(grown[key] ?? []), ...own(key)];
return grown.inOrder ? ports : execFirst(ports);
};
const resolved = {
...def,
label: grown.label ?? def.label,
+21
View File
@@ -0,0 +1,21 @@
import type { NodeDef } from '../../NodeRegistry';
import { childrenOf } from '../../objectQueries';
import { asBoolean, asEntity } from '../../values';
import { bool, list, obj } from '../shared';
export const Children: NodeDef = {
type: 'Children',
label: 'Children',
category: 'data',
description:
'The children of an object as a list, in scene order. With recursive, every object below it: ' +
'the children first, then their children and so on.',
inputs: [obj('object'), bool('recursive')],
outputs: [list('children')],
params: [],
run: (ctx, inputs) => {
const parent = asEntity(inputs.object);
const children = parent ? childrenOf(ctx.objects(), parent, asBoolean(inputs.recursive)) : [];
return { outputs: { children } };
},
};
@@ -0,0 +1,21 @@
import type { NodeDef } from '../../NodeRegistry';
import { childrenOf, objectsNamed } from '../../objectQueries';
import { asEntity, asString } from '../../values';
import { list, obj, str } from '../shared';
export const ChildrenByName: NodeDef = {
type: 'ChildrenByName',
label: 'Children by name',
category: 'data',
description:
'Every object with that name below the given one – its children, their children and so on. ' +
'Nearer levels come first, within a level scene order, as Child by name searches.',
inputs: [obj('object'), str('name')],
outputs: [list('children')],
params: [],
run: (ctx, inputs) => {
const parent = asEntity(inputs.object);
const below = parent ? childrenOf(ctx.objects(), parent, true) : [];
return { outputs: { children: objectsNamed(below, asString(inputs.name)) } };
},
};
@@ -0,0 +1,17 @@
import type { NodeDef } from '../../NodeRegistry';
import { objectsNamed } from '../../objectQueries';
import { asString } from '../../values';
import { list, str } from '../shared';
export const ObjectsByName: NodeDef = {
type: 'ObjectsByName',
label: 'Objects by name',
category: 'data',
description:
'Every scene object with that name, as a list in scene order – empty when none is called so. ' +
'The list is taken when it is read and does not follow later changes.',
inputs: [str('name')],
outputs: [list('objects')],
params: [],
run: (ctx, inputs) => ({ outputs: { objects: objectsNamed(ctx.objects(), asString(inputs.name)) } }),
};
@@ -0,0 +1,17 @@
import type { NodeDef } from '../../NodeRegistry';
import { objectsOfAsset } from '../../objectQueries';
import { asString } from '../../values';
import { assetPort, list } from '../shared';
export const ObjectsOfAsset: NodeDef = {
type: 'ObjectsOfAsset',
label: 'Objects of asset',
category: 'data',
description:
'Every object in the game that is an instance of the chosen asset – the ones Is asset says ' +
'yes to –, as a list in scene order. Spawned ones count, destroyed ones do not.',
inputs: [assetPort()],
outputs: [list('objects')],
params: [],
run: (ctx, inputs) => ({ outputs: { objects: objectsOfAsset(ctx.objects(), asString(inputs.asset)) } }),
};
+19 -4
View File
@@ -1,4 +1,4 @@
import { FIND, MATCH } from '../../findBlock';
import { FIND, FIND_MODE, MATCH } from '../../findBlock';
import type { NodeDef } from '../../NodeRegistry';
import { asList } from '../../values';
import { any, exec, list, num } from '../shared';
@@ -9,11 +9,26 @@ export const Find: NodeDef = {
category: 'flow',
description:
'Opens a search block, closed by a Match. "item" and "index" go through one element after the ' +
'other; whatever is built from them into the Match\'s "match" is the test. The first element it ' +
'is true for continues at "found" of the Match, none at "not found".',
'other; whatever is built from them into the Match\'s "match" is the test. Mode says what the ' +
'Match answers: the first element the test is true for, all of them, whether there is any, or ' +
'how many.',
inputs: [exec(), list('list')],
outputs: [any('item'), num('index')],
params: [],
params: [
{
key: FIND_MODE,
label: 'Mode',
kind: 'enum',
default: 'first',
options: [
{ value: 'first', label: 'First' },
{ value: 'all', label: 'All' },
{ value: 'any', label: 'Any' },
{ value: 'count', label: 'Count' },
],
},
],
hiddenParams: (params) => ((params[FIND_MODE] ?? 'first') === 'first' ? [FIND_MODE] : []),
opens: { type: MATCH, dx: 480 },
run: (_ctx, inputs) => ({ outputs: { item: null, index: -1 }, find: asList(inputs.list) }),
};
+17 -7
View File
@@ -1,16 +1,26 @@
import { MATCH, MATCH_INPUT } from '../../findBlock';
import type { NodeDef } from '../../NodeRegistry';
import { any, bool, exec, num } from '../shared';
import { type FindMode, MATCH, MATCH_INPUT, matchMode } from '../../findBlock';
import type { NodeDef, PortDef } from '../../NodeRegistry';
import { any, bool, exec, list, num } from '../shared';
/** Never runs itself: the Find its test is built from hands it the hit and continues from here. */
/** The Match's outputs per mode of its Find; each mode but `first` goes on along one `done`. */
const OUTPUTS: Record<FindMode, PortDef[]> = {
first: [exec('found', 'found'), any('item'), num('index'), exec('notFound', 'not found')],
all: [exec('done', 'done'), list('items'), list('indices')],
any: [exec('done', 'done'), bool('any')],
count: [exec('done', 'done'), num('count')],
};
/** Never runs itself: the Find its test is built from hands it the outcome and continues from here. */
export const Match: NodeDef = {
type: MATCH,
label: 'Match',
category: 'flow',
description:
'Closes the search block of the Find its "match" is built from. Continues at "found" with the ' +
'first element "match" was true for, or at "not found" with no item and index -1.',
'Closes the search block of the Find its "match" is built from. What it answers follows the ' +
'Find\'s mode: First continues at "found" with the first element "match" was true for, or at ' +
'"not found"; All hands on every such item and index, Any whether there was one, Count how many.',
inputs: [{ ...bool(MATCH_INPUT), inline: false }],
outputs: [exec('found', 'found'), any('item'), num('index'), exec('notFound', 'not found')],
outputs: [],
params: [],
derivePorts: ({ node, graph }) => ({ outputs: OUTPUTS[matchMode(graph, node)], inOrder: true }),
};
+8
View File
@@ -39,6 +39,8 @@ import { FirstNotEmpty } from './data/FirstNotEmpty';
import { Floor } from './data/Floor';
import { GetPosition } from './data/GetPosition';
import { ChildByName } from './data/ChildByName';
import { Children } from './data/Children';
import { ChildrenByName } from './data/ChildrenByName';
import { IsAsset } from './data/IsAsset';
import { IsEnabled } from './data/IsEnabled';
import { IsHovered } from './data/IsHovered';
@@ -70,6 +72,8 @@ import { NameOf } from './data/NameOf';
import { Normalize } from './data/Normalize';
import { Not } from './data/Not';
import { ObjectByName } from './data/ObjectByName';
import { ObjectsByName } from './data/ObjectsByName';
import { ObjectsOfAsset } from './data/ObjectsOfAsset';
import { Or } from './data/Or';
import { Owner } from './data/Owner';
import { PackStruct } from './data/PackStruct';
@@ -170,9 +174,13 @@ export const BUILT_IN_NODES: readonly NodeDef[] = [
Owner,
Parent,
ObjectByName,
ObjectsByName,
ChildByName,
ChildrenByName,
Children,
NameOf,
IsAsset,
ObjectsOfAsset,
IsEnabled,
Properties,
GetPosition,
+39
View File
@@ -0,0 +1,39 @@
import type { EntityHandle } from './NodeContext';
/*
* The plural lookups (#259) all filter the one list `NodeContext.objects()` hands out: every living
* object of the scene, in scene order. A list is a snapshot of that moment and does not follow.
*/
function isBelow(child: EntityHandle, parent: EntityHandle): boolean {
return child.parent !== null && child.parent.id === parent.id;
}
/**
* The objects below `parent`, level by level: its children in scene order, then theirs – the order
* `Child by name` searches in. Without `recursive`, the children only.
*/
export function childrenOf(
objects: readonly EntityHandle[],
parent: EntityHandle,
recursive: boolean,
): EntityHandle[] {
const found: EntityHandle[] = [];
let level = objects.filter((e) => isBelow(e, parent));
while (level.length > 0) {
found.push(...level);
if (!recursive) break;
const above = level;
level = objects.filter((e) => above.some((p) => isBelow(e, p)));
}
return found;
}
export function objectsNamed(objects: readonly EntityHandle[], name: string): EntityHandle[] {
return objects.filter((e) => e.name === name);
}
/** The instances of an asset, by the rule `Is asset` answers with; no asset, no objects. */
export function objectsOfAsset(objects: readonly EntityHandle[], assetId: string): EntityHandle[] {
return assetId ? objects.filter((e) => e.assetId === assetId) : [];
}
+16 -1
View File
@@ -14,6 +14,7 @@ import {
terminalNode,
} from '../../core/graph';
import type { GraphAsset } from '../../core/model/Asset';
import { FIND, FIND_MODE } from '../../core/graph/findBlock';
import { graphLookup } from '../../core/model/graphLookup';
import type { PropertyBag } from '../../core/model/Properties';
import type { Project } from '../../core/model/Project';
@@ -53,7 +54,7 @@ export function rankedEntries(entries: PaletteEntry[], query: string): PaletteEn
return entries
.map((entry) => ({
entry,
rank: searchRank(needle, [entry.def.label, entry.def.type, entry.def.description]),
rank: searchRank(needle, [entry.def.label, entry.id, entry.def.description]),
}))
.filter(({ rank }) => rank >= 0)
.sort(
@@ -65,6 +66,19 @@ export function rankedEntries(entries: PaletteEntry[], query: string): PaletteEn
.map(({ entry }) => entry);
}
/**
* A Find set to All under a name of its own (#259). Its id is what the search reads besides the
* label, so "find" still lands on the plain Find rather than on this one.
*/
function filterEntry(find: NodeDef): PaletteEntry {
const def = {
...find,
label: 'Filter',
description: 'A Find set to All: its Match hands on every item the test is true for, and their indices.',
};
return { id: 'Filter', hint: find.category, def, params: { [FIND_MODE]: 'all' } };
}
/**
* 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
@@ -99,6 +113,7 @@ export function paletteEntries(project: Project, asset: GraphAsset): PaletteEntr
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: {} });
if (def.type === FIND) entries.push(filterEntry(def));
}
const lookup = graphLookup(project);
for (const other of project.assets) {
+1
View File
@@ -672,6 +672,7 @@ export class BehaviorSystem implements System {
const found = resolve(parent);
return (found && world.childByName(found, name)) ?? null;
},
objects: () => world.entities,
isKeyDown: (key) => this.input.isDown(key),
pointer: world.pointer,
hitTest: (target, x, y) => {