Skip to content
Open
132 changes: 132 additions & 0 deletions scripts/selector-cost-bench.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
#!/usr/bin/env node
// @ts-nocheck — a Playwright driver; the page-side code runs in the app, not under checkJs
// 102b-flows — THE MANY-TARGET SELECTOR'S COST GATE: "a 200-object set adds at most 1 ms per tick".
//
// 200 boxes, three scenarios over the SAME scene, the flow tick pumped synchronously
// (flowRuntime.pumpFlowTick, the XR pump) on a monotonic synthetic clock:
// none — no flow at all (the floor)
// single — 200 Spin -> Object Selector (one object each) chains: how a scene does it today
// tag — ONE Spin -> ONE Object Selector picking "every object tagged bench" (all 200)
// A click is applied every 15 ticks on a 4th scenario's trigger so the sensor path is measured too
// (tag+click: an On Click wired to the set, a Fired Object reading it).
//
// LANE_DEV_CMD='node scripts/serve-build.cjs --port $PORT' APP_URL=https://theprototype.app:7092/ \
// e2e-slot --exclusive --dev <dir> 7092 -- node scripts/selector-cost-bench.cjs [--out file.json]
//
// Gate: median(tag) - median(none) <= 1 ms/tick (and tag+click likewise). Rounds alternate scenarios;
// medians are reported. Measure a PROD build (dev-mode module wrappers inflate a tick several fold).
const { chromium } = require('playwright');
const fs = require('fs');

const URL = process.env.APP_URL || 'https://localhost:5491/';
const arg = (name, fallback) => {
const i = process.argv.indexOf(name);
return i !== -1 ? process.argv[i + 1] : fallback;
};
const OUT = arg('--out', null);
const COUNT = Number(arg('--objects', '200'));
const TICKS = Number(arg('--ticks', '600'));
const ROUNDS = Number(arg('--rounds', '7'));
const GATE_MS = 1;

(async () => {
const browser = await chromium.launch({ args: ['--ignore-gpu-blocklist', '--enable-gpu', '--use-angle=default'] });
const ctx = await browser.newContext({ ignoreHTTPSErrors: true });
await ctx.addInitScript(() => {
localStorage.setItem('debugStores', 'true');
localStorage.setItem('hasSeenDisclaimer', 'true');
localStorage.setItem('hasSeenWelcome', 'true');
});
const page = await ctx.newPage();
await page.goto(URL, { waitUntil: 'domcontentloaded', timeout: 120000 });
await page.waitForFunction(() => window.__stores && !!window.__stores.flowRuntime && !!window.__stores.moduleSDK, null, { timeout: 120000 });
await page.waitForTimeout(3000);
const boxes = await page.evaluate(async (count) => {
const s = window.__stores;
for (let i = 0; i < count; i++) s.commandsHandler.sceneCommand('/create box');
await new Promise((r) => setTimeout(r, 3000));
let group;
s.objectsGroup.subscribe((v) => (group = v))();
const out = [];
for (const c of group.children) if (c.isMesh) (c.userData.tags = ['bench']), out.push(c.uuid);
return out;
}, COUNT);
console.log(`scene: ${boxes.length} boxes tagged "bench"`);

const scenarios = ['none', 'single', 'tag', 'tag+click'];
/** @type {Record<string, number[]>} */
const samples = Object.fromEntries(scenarios.map((s) => [s, []]));
for (let round = 0; round < ROUNDS; round++) {
for (const scenario of scenarios) {
const ms = await page.evaluate(
async ({ scenario, ticks, boxes }) => {
const s = window.__stores;
const fr = s.flowRuntime;
const nodes = [];
const edges = [];
const N = (id, type, data = {}) => nodes.push({ id, type, position: { x: 0, y: 0 }, data: { type, ...data } });
const E = (source, target, targetHandle) =>
edges.push({ id: 'e-' + source + '-' + target + (targetHandle ? '.' + targetHandle : ''), source, target, ...(targetHandle ? { targetHandle } : {}) });
if (scenario === 'single')
boxes.forEach((u, i) => {
N('s' + i, 'spin', { axis: 'y', speed: 1 });
N('o' + i, 'objectselector', { selected: u });
E('s' + i, 'o' + i);
});
if (scenario === 'tag' || scenario === 'tag+click') {
N('s', 'spin', { axis: 'y', speed: 1 });
N('o', 'objectselector', { pick: 'tag', match: 'bench' });
E('s', 'o');
}
if (scenario === 'tag+click') {
N('c', 'onclick');
N('f', 'firedobject');
E('c', 'o');
E('c', 'f', 'trigger');
}
s.flowGraphs.update((g) => ({ ...g, scene: { nodes, edges } }));
s.flowNodes.set(nodes);
s.flowEdges.set(edges);
// the resolver chunk loads on the first set selector (async); let it land before timing
await new Promise((r) => setTimeout(r, 400));
let now = Math.max(performance.now(), window.__benchNow ?? 0);
for (let i = 0; i < 60; i++) fr.pumpFlowTick((now += 16.7));
const t0 = performance.now();
for (let i = 0; i < ticks; i++) {
now += 16.7;
if (scenario === 'tag+click' && i % 15 === 0) fr.fireObjectClick(boxes[i % boxes.length]);
fr.pumpFlowTick(now);
}
const per = (performance.now() - t0) / ticks;
window.__benchNow = now;
return per;
},
{ scenario, ticks: TICKS, boxes }
);
samples[scenario].push(ms);
await page.waitForTimeout(300);
}
}
const median = (xs) => [...xs].sort((a, b) => a - b)[Math.floor(xs.length / 2)];
const result = { url: URL, objects: boxes.length, ticks: TICKS, rounds: ROUNDS, gateMs: GATE_MS };
for (const scenario of scenarios) {
result[scenario] = { medianMs: Number(median(samples[scenario]).toFixed(4)), samples: samples[scenario].map((x) => Number(x.toFixed(4))) };
console.log(`${scenario.padEnd(10)} median ${result[scenario].medianMs} ms/tick (${result[scenario].samples.join(', ')})`);
}
const spun = await page.evaluate((u) => {
let g;
window.__stores.objectsGroup.subscribe((v) => (g = v))();
return u.filter((x) => Math.abs(g.getObjectByProperty('uuid', x)?.rotation?.y ?? 0) > 1e-6).length;
}, boxes);
result.spunByLastScenario = spun;
result.tagOverNone = Number((result.tag.medianMs - result.none.medianMs).toFixed(4));
result.tagClickOverNone = Number((result['tag+click'].medianMs - result.none.medianMs).toFixed(4));
result.pass = result.tagOverNone <= GATE_MS && result.tagClickOverNone <= GATE_MS;
console.log(`tag - none = ${result.tagOverNone} ms, tag+click - none = ${result.tagClickOverNone} ms (gate ${GATE_MS} ms): ${result.pass ? 'PASS' : 'FAIL'}; ${spun}/${boxes.length} boxes turned`);
if (OUT) fs.writeFileSync(OUT, JSON.stringify(result, null, 2));
await browser.close();
process.exit(result.pass ? 0 : 1);
})().catch((error) => {
console.error(error);
process.exit(2);
});
4 changes: 4 additions & 0 deletions src/components/editors/FlowDebugger.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,10 @@
{#if focus.why.standing}<span class="debug-why-block text-warn-text">{focus.why.standing}</span>{/if}
</div>
{/if}
{#if focus.set}
<!-- 102b-flows: a many-target Object Selector's resolved set (or the set this node acts on) -->
<p class="tbx-row text-[11px] text-text-muted" id="debug-set" title={focus.set}>{focus.set}</p>
{/if}
{#if focus.eventless}
<p class="tbx-row text-[11px] text-text-muted">No event reaches this node, so a breakpoint here never pauses — watch it instead.</p>
{/if}
Expand Down
24 changes: 22 additions & 2 deletions src/components/editors/Nodes.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,8 @@
import { flowMouseBindings } from '$lib/flowPrefs';
import Breadcrumbs from '../ui/Breadcrumbs.svelte'; // 41 G15
import { readPanelOpen, writePanelOpen, handheld } from '$lib/ui/handheldPanels.js'; // 41 G18 (+ 2.0-n3c: the read-only code sheet)
import { objectsGroup, selectedObject, selectedObjects, isVRMode } from '../../stores/sceneStore';
import { objectsGroup, selectedObject, selectedObjects, isVRMode, sceneRevision } from '../../stores/sceneStore';
import { resolveTargets, selectorCoreVersion } from '$lib/selectorPick.js'; // 102b-flows
import { serializeNode, serializeEdge, deleteFlowNodes, deleteFlowEdges, setNodeData } from '$lib/nodesHandler';
import ThemedSelect from '../ui/ThemedSelect.svelte';
import { defDefaults } from '$lib/customNodes';
Expand Down Expand Up @@ -1792,7 +1793,13 @@
const lintFindings: FlowLintFinding[] = $derived.by(() => {
const drawn = (nodes as any[]).filter((n) => !n.hidden);
const ids = new Set(drawn.map((n) => n.id));
return lintFlowGraph(drawn, (edges as any[]).filter((e) => !e.hidden && ids.has(e.source) && ids.has(e.target)));
void $sceneRevision; // 102b-flows: a tag / group / name set follows the scene
void $selectorCoreVersion; // …and is only known once the resolver chunk is in
const root = $objectsGroup;
return lintFlowGraph(drawn, (edges as any[]).filter((e) => !e.hidden && ids.has(e.source) && ids.has(e.target)), {
// null = still loading: not flagged yet
resolve: (data) => resolveTargets(data, root) ?? ['?']
});
});
/** where a flagged wire's chip sits: halfway between the source's right edge and the target's left */
const lintChips = $derived.by(() => {
Expand All @@ -1815,6 +1822,7 @@
});
/** Apply a finding's fix: the flagged wire goes, the reversed one comes — ONE undo step. */
function reverseWire(f: FlowLintFinding) {
if (!f.fix) return;
const fresh = makeEdge(f.fix);
const exists = storeEdgesNow().some((e) => e.id === fresh.id);
inBatch('Reverse wire', () => {
Expand All @@ -1824,6 +1832,18 @@
showToast(exists ? 'Removed the backwards wire (the right one was already there)' : 'Wire reversed');
}
function lintMenu(f: FlowLintFinding, x: number, y: number) {
if (f.code === 'selector-matches-nothing') {
menu = {
x,
y,
items: [
{ header: { title: 'Matches no objects', badge: 'acts on nothing' } },
{ label: 'Disconnect', icon: 'x', tooltip: f.message, action: () => commitDelete([], [f.edgeId]) }
]
};
return;
}
if (!f.fix) return;
menu = {
x,
y,
Expand Down
54 changes: 47 additions & 7 deletions src/components/editors/nodes/ObjectSelectorNode.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import NodeWrapper from './NodeWrapper.svelte';
import { objectsGroup } from '../../../stores/sceneStore';
import { setNodeData } from '$lib/nodesHandler';
import { pickOf, matchOf } from '$lib/selectorPick.js';

type $$Props = NodeProps;
export let id: string;
Expand All @@ -17,24 +18,63 @@
? sceneObjects.children.map((child: any) => ({ id: child.uuid, name: child.name || child.type }))
: [];
// One-way flow: render from data, write through setNodeData (replicates to peers)

// 102b-flows: pick ONE object (the default, what every saved selector is) or a SET — every object
// with a tag, every object in a group, or every object whose name matches. Effects wired in act
// on all of them; triggers wired in fire for any of them (Fired Object says which).
const PICKS = [
{ value: 'object', label: 'One object' },
{ value: 'tag', label: 'By tag' },
{ value: 'group', label: 'By group' },
{ value: 'name', label: 'By name' }
];
let pick: string;
$: pick = pickOf(data);
let match: string;
$: match = matchOf(data);
function setPick(next: string) {
// back to one object: the fields go, so the node is exactly a plain selector again
if (next === 'object') setNodeData(id, { pick: undefined, match: undefined });
else setNodeData(id, { pick: next, match: next === pick ? match : '' });
}
</script>

<NodeWrapper type={data.type} label={data.label}>
<div class="flex w-full items-center space-x-2">
<div class="flex w-full flex-col gap-1">
<select
class="nodrag nopan"
value={data.selected ?? '-None-'}
on:change={(e) => setNodeData(id, { selected: e.currentTarget.value })}
aria-label="What this selector picks"
data-selector-pick
value={pick}
on:change={(e) => setPick(e.currentTarget.value)}
>
<option>-None-</option>
{#each items as option}
<option value={option.id}>{option.name}</option>
{#each PICKS as p (p.value)}
<option value={p.value}>{p.label}</option>
{/each}
</select>
{#if pick === 'object'}
<select
class="nodrag nopan"
aria-label="Object"
value={data.selected ?? '-None-'}
on:change={(e) => setNodeData(id, { selected: e.currentTarget.value })}
>
<option>-None-</option>
{#each items as option}
<option value={option.id}>{option.name}</option>
{/each}
</select>
{:else}
<!-- 102b-flows: the set fields + live count are a lazy chunk (a One object card never loads it) -->
{#await import('./SelectorSetFields.svelte') then m}
<m.default {id} {data} {pick} {match} />
{/await}
{/if}
</div>
<Socket kind="target" nodeType={data.type} position={Position.Left} />
<!-- the chosen object, as a value: this is what every `object` input in the
catalog wires from. Declared in flowSockets since 165; the card simply
never offered the handle, so those inputs were unreachable. -->
never offered the handle, so those inputs were unreachable.
102b-flows: for a set, the member a trigger fired for last (else the first). -->
<Socket kind="source" nodeType={data.type} position={Position.Right} />
</NodeWrapper>
71 changes: 71 additions & 0 deletions src/components/editors/nodes/SelectorSetFields.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<script>
// 102b-flows — the Object Selector card's "By tag / By group / By name" fields and the live count of
// what the set resolves to. A lazy chunk: a card set to One object (every saved selector) never
// loads it. Writes go through setNodeData, as the card's own select does.
import { objectsGroup, sceneRevision } from '../../../stores/sceneStore';
import { setNodeData } from '$lib/nodesHandler';
import { resolveSelector, sceneTags, describeSet } from '$lib/selectorCore.js';

/** @type {{ id: string, data: any, pick: string, match: string }} */
let { id, data, pick, match } = $props();
/** @type {Record<string, string>} */
const TITLES = { tag: 'Every object with a tag (Inspector > Tags)', group: 'Every object in a group', name: 'Every object whose name matches: Star*, coin (contains)' };
const title = $derived(TITLES[pick] ?? '');

const root = $derived($objectsGroup);
/** the groups a "By group" selector can name: any object with children (nested ones too) */
const groups = $derived.by(() => {
void $sceneRevision;
/** @type {{id: string, name: string}[]} */
const out = [];
if (pick !== 'group') return out;
/** @type {any} */ (root)?.traverse?.((/** @type {any} */ o) => {
if (o === root || !o.children?.length || o.isMesh || o.userData?.helper) return;
if (o.type === 'Group' || o.type === 'Object3D') out.push({ id: o.uuid, name: o.name || 'Group' });
});
return out;
});
const tags = $derived.by(() => {
void $sceneRevision;
return pick === 'tag' ? sceneTags(root) : [];
});
const set = $derived.by(() => {
void $sceneRevision;
return resolveSelector(data, root);
});
const nameOf = (/** @type {string} */ uuid) => /** @type {any} */ (root)?.getObjectByProperty?.('uuid', uuid)?.name || null;
/** @type {Record<string, string>} */
const placeholder = { tag: 'tag', name: 'Star* or coin' };
</script>

{#if pick === 'group'}
<select class="nodrag nopan" aria-label="Group" {title} data-selector-match value={match} onchange={(e) => setNodeData(id, { match: e.currentTarget.value })}>
<option value="">-None-</option>
{#each groups as g (g.id)}
<option value={g.id}>{g.name}</option>
{/each}
</select>
{:else}
<input
class="nodrag nopan ui-input px-1 py-0.5 text-xs"
aria-label={pick === 'tag' ? 'Tag' : 'Name pattern'}
{title}
data-selector-match
list={pick === 'tag' ? 'selector-tags-' + id : undefined}
placeholder={placeholder[pick]}
maxlength="120"
value={match}
onchange={(e) => setNodeData(id, { match: e.currentTarget.value.trim() })}
onkeydown={(e) => {
if (e.key === 'Enter') e.currentTarget.blur();
}}
/>
{#if pick === 'tag'}
<datalist id={'selector-tags-' + id}>
{#each tags as t (t.tag)}<option value={t.tag}>{t.count} object{t.count === 1 ? '' : 's'}</option>{/each}
</datalist>
{/if}
{/if}
<span class="selector-count text-[length:var(--fs-badge)] text-text-muted" data-selector-count={set.length} title={describeSet(set, nameOf, 8)}>
{set.length === 0 ? 'matches no objects' : `${set.length} object${set.length === 1 ? '' : 's'}`}
</span>
5 changes: 5 additions & 0 deletions src/components/menu/Inspector.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -3997,6 +3997,11 @@
<MeasureSection object={$selectedObject} />
{/if}

{#if insTargets.length}
<!-- 102b-flows: the tags an Object Selector set to By tag finds (union over a multi-select) -->
{#await import('./inspector/TagsSection.svelte') then m}<m.default objects={insTargets} />{/await}
{/if}

{#if isGroup}
<Section variant="panel" label="Group">
<p class="px-1 text-xs text-text-muted">
Expand Down
Loading
Loading