Files
feuerwerk/src/editor/graph/paletteEntries.ts
T
adminandClaude Opus 5.5 25084f8576
game-maker / gate (push) Successful in 4m3s
game-maker / suite (push) Successful in 14m52s
Refactoring round 10: split SoundLibrary, fold sound duplicates (#85)
Refactoring round 10 covers everything since round 9 (808e1ee): 110
commits with about 47 000 new lines, nearly all of them sound, sound
FX, instruments, patterns and songs. Behaviour is unchanged.

Duplicate code (jscpd over src, 50 tokens, TypeScript only, measured
on 808e1ee and here alike: 47 clones / 426 lines before, 33 / 245
after; round 9 itself ended at 22 / 160 by this count):

- PreviewParams (new, editor/soundfx) is the header's parameter bar
  of the Sound FX and the Instrument tab: values, defaults, fields
  and the voices a moved field reaches. Both tabs had it line for
  line.
- fxWorklet: an Effect base runs the bit crusher, phaser, flanger,
  limiter, LFO and bus shifter, a Source base the pitch player and
  the Chip. Start is the one wait for a voice's first sample, which
  four processors wrote out each.
- nodes/shared has checkPort, detachedPort, fxParamsPort and
  letRingPort. The Play and Stop nodes of sounds, notes, patterns and
  songs spelled each port out, up to five times.
- parameterValues builds both Sound FX parameters and Instrument
  parameters, which differed in name and text only.
- SetLoopCommand sets the ruler loop of a pattern or a song. It
  replaces SetPatternLoopCommand and SetSongLoopCommand.
- addLink in music/routing is the one rule for a link that both the
  song routing and the Master routing keep.
- eqCurves works out each band and their sum for the EQ tab, which
  did that in its drawing code. It replaces eqCurveDb, which only a
  test called.
- Smaller ones: the eight neighbour directions of a tile cell, and
  drawFloatingBox for the shadowed box of Popup and FloatWindow.
- Left on purpose: Play pattern and Play song stay two parallel node
  definitions, and the smaller clones under ten lines stay.

Architecture:

- SoundLibrary.ts goes from 2897 to 2188 lines. What a stage of a
  sound FX becomes as Web Audio nodes, and how the knobs of a playing
  voice move, is now viewport/fxNodes.ts. None of it keeps state of
  the library.

Dead code (TS language service, references per export and member):

- soundRefIds, LFO_SHAPE_INDEX, TREMOLO_ROWS, VIBRATO_ROWS and
  REVERB_ROWS had no reader. The four routing node defs are
  registered without an unused exported name.
- soundFileOf and portTypeOf were called by tests only. The tests
  now ask findSound and portOf, which the editor uses. DRY moves
  from src into the one test that uses it.
- 51 values used only in their own file lose their `export`. Types
  and the node catalogues stay exported.
- Kept on purpose: neighboursOf is the cell by cell reading the
  indexed neighboursIn is checked against, and PitchShifter.latency
  is the test's one view of how late the shifter is.

Comments and docs:

- Seven comments told history ("no longer", "any more", "as
  before", "of before #354"). Nine comment blocks ran far past the
  line width. Proof that this changed no code: the bundle was md5
  identical, and the touched tests and e2e modules were identical
  after esbuild.
- README: sound FX, instrument, pattern, song and bus in the asset
  list, the pages Instruments, Patterns and Songs, 1919 checks.
- Wiki: see its own commit.

Tests:

  Gate (melektaus-atx)    274 files, 4236 tests, CHECK EXIT 0
  e2e 34, 64, 65          ALL PASSED, 180 checks
  Unit, touched areas     16 files, 804 tests

No check was added, the e2e sum stays at 1919. Counter-checks, each
put back by copy and compared with cmp:

- addLink without the loop rule: 2 tests fail, one per routing.
- eqCurves with the sum of the last band only: 1 test fails.
- Start in the worklet never waiting: e2e 34 fails in exactly the
  four checks that hang on a voice's first sample (Flanger, Tremolo,
  Chip, a pitched note planned ahead).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 15:31:33 +02:00

191 lines
8.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { searchRank } from '../../ui/search';
import {
allNodeDefs,
BEHAVIOR_END,
BEHAVIOR_PARAM,
callsFunction,
createEmptyGraph,
FUNCTION_PARAM,
isTerminalType,
namesBehavior,
nextStateName,
type NodeCategory,
type NodeDef,
ON_BEHAVIOR,
resolveDef,
RUN_BEHAVIOR,
SHADER_CALL,
SHADER_FUNCTION_INPUT,
SHADER_FUNCTION_OUTPUT,
State,
STATE_NAME_PARAM,
terminalNode,
} from '../../core/graph';
import type { ShaderAsset, ShaderFunctionAsset } 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 { GraphHolder, Project } from '../../core/model/Project';
import {
isParticlePropertyNode,
PARTICLE_PROPERTY,
PROPERTY_NAME_PARAM as PARTICLE_NAME_PARAM,
propertyNameOf,
} from '../../core/properties/particles';
import {
nextPropertyName,
PROPERTY_NAME_PARAM,
SHADER_COLOR_PROPERTY,
SHADER_PROPERTY,
} from '../../core/properties/shaders';
import { nextParticlePropertyName, PARTICLE_NODES, PARTICLE_OUTPUT } from '../../core/particles/nodes';
import { offeredIn, ShaderFunctionInput, ShaderFunctionOutput } from '../../core/shader/functions';
import { SHADER_NODES, SHADER_OUTPUT, SHADER_VERTEX_OUTPUT } from '../../core/shader/nodes';
import { SOUND_FX_INPUT, SOUND_FX_NODES, SOUND_FX_OUTPUT } from '../../core/soundfx/nodes';
import { INSTRUMENT_NODES } from '../../core/instrument/nodes';
/**
* One row of the palette. `def` is the definition the node would actually have once placed, so the
* drop filter and the port it lands on are right for a behavior entry too.
*/
export interface PaletteEntry {
id: string;
hint: string;
def: NodeDef;
params: PropertyBag;
}
const CATEGORY_ORDER: NodeCategory[] = ['event', 'flow', 'variable', 'data', 'action', 'state'];
/**
* The entries a query answers, best first. How well the entry matches decides before anything else;
* category and alphabet only order what is equally good. A node named after the query therefore
* beats one that merely mentions it in its description – without that, "variable" + Enter adds
* `Run behavior`, whose description happens to contain the word.
*
* An empty query ranks everything alike, which leaves the plain category order of the palette.
*/
export function rankedEntries(entries: PaletteEntry[], query: string): PaletteEntry[] {
const needle = query.trim().toLowerCase();
return entries
.map((entry) => ({
entry,
rank: searchRank(needle, [entry.def.label, entry.id, entry.def.description]),
}))
.filter(({ rank }) => rank >= 0)
.sort(
(a, b) =>
a.rank - b.rank ||
CATEGORY_ORDER.indexOf(a.entry.def.category) - CATEGORY_ORDER.indexOf(b.entry.def.category) ||
a.entry.def.label.localeCompare(b.entry.def.label),
)
.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' } };
}
/**
* A shader's nodes, its one Output dropping out once placed, and every shader function under its own
* name (#303). A function holds the same nodes but those that end a shader or give the wearer a row,
* and its own two ends instead; it calls every function but those that would come back to it.
*/
function shaderEntries(project: Project, asset: ShaderAsset | ShaderFunctionAsset): PaletteEntry[] {
const inFunction = asset.type === 'shaderfunction';
const placed = new Set(asset.graph.nodes.map((n) => n.type));
const once = [SHADER_OUTPUT, SHADER_VERTEX_OUTPUT, SHADER_FUNCTION_INPUT, SHADER_FUNCTION_OUTPUT];
const entries: PaletteEntry[] = [...SHADER_NODES, ShaderFunctionInput, ShaderFunctionOutput]
.filter((def) => offeredIn(def.type, inFunction) && (!once.includes(def.type) || !placed.has(def.type)))
.map((def) => {
const params: PropertyBag =
def.type === SHADER_PROPERTY
? { [PROPERTY_NAME_PARAM]: nextPropertyName(asset.graph) }
: def.type === SHADER_COLOR_PROPERTY
? { [PROPERTY_NAME_PARAM]: nextPropertyName(asset.graph, 'tint') }
: {};
return { id: def.type, hint: def.category, def, params };
});
const lookup = graphLookup(project);
for (const other of project.assets) {
if (other.type !== 'shaderfunction' || callsFunction(lookup, other.id, asset.id)) continue;
const params = { [FUNCTION_PARAM]: other.id };
const def = resolveDef({ id: '', type: SHADER_CALL, x: 0, y: 0, params }, createEmptyGraph(), lookup);
if (def) entries.push({ id: `${SHADER_CALL}:${other.id}`, hint: 'function', def, params });
}
return entries;
}
/**
* 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 (`shaderEntries`), a sound FX its effects
* with one Input and one Output, an instrument its own nodes and the same effects. In a behavior,
* every other behavior appears under its own name instead of behind a 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: GraphHolder): PaletteEntry[] {
if (asset.type === 'statemachine') {
const params = { [STATE_NAME_PARAM]: nextStateName(asset.graph) };
return [{ id: State.type, hint: State.category, def: State, params }];
}
if (asset.type === 'shader' || asset.type === 'shaderfunction') return shaderEntries(project, asset);
// A routing holds nodes that come and go on their own: a song's tracks (#350), the assets (#351).
if (asset.type === 'song' || asset.type === 'routing') return [];
if (asset.type === 'soundfx') {
const placed = new Set(asset.graph.nodes.map((n) => n.type));
return SOUND_FX_NODES.filter(
(def) => !(def.type === SOUND_FX_INPUT || def.type === SOUND_FX_OUTPUT) || !placed.has(def.type),
).map((def) => ({ id: def.type, hint: def.category, def, params: {} }));
}
if (asset.type === 'instrument') {
const placed = new Set(asset.graph.nodes.map((n) => n.type));
const effects = SOUND_FX_NODES.filter(
(def) => def.type !== SOUND_FX_INPUT && def.type !== SOUND_FX_OUTPUT,
);
return [...INSTRUMENT_NODES, ...effects]
.filter((def) => !isTerminalType(def.type) || !placed.has(def.type))
.map((def) => ({ id: def.type, hint: def.category, def, params: {} }));
}
if (asset.type === 'particles') {
const hasOutput = asset.graph.nodes.some((n) => n.type === PARTICLE_OUTPUT);
const taken = new Set(asset.graph.nodes.filter(isParticlePropertyNode).map(propertyNameOf));
return PARTICLE_NODES.filter((def) => def.type !== PARTICLE_OUTPUT || !hasOutput).map((def) => {
const params: PropertyBag =
def.type === PARTICLE_PROPERTY ? { [PARTICLE_NAME_PARAM]: nextParticlePropertyName(taken) } : {};
return { id: def.type, hint: def.category, def, params };
});
}
const entries: PaletteEntry[] = [];
for (const def of allNodeDefs()) {
if (namesBehavior(def.type) || def.category === 'state') continue;
if (def.category === 'shader' || def.category === 'particles' || def.category === 'sound') 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) {
// A behavior running itself is an endless loop, so it is not on offer.
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 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;
}