Refactoring round 10: split SoundLibrary, fold sound duplicates (#85)
game-maker / gate (push) Successful in 4m3s
game-maker / suite (push) Successful in 14m52s

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>
This commit is contained in:
adminandClaude Opus 5.5 committed 2026-10-09 15:31:33 +02:00
1 parent 76f5097a38
commit 25084f8576
72 files changed
+1369 -1458

No files matched your search

+1 -1
View File
@@ -48,7 +48,7 @@ export function withAssetNames<S extends StoredFile>(
}
/** Whose a file is (#344), as the line under the list says it. */
export function ownerText(owner: string | null): string {
function ownerText(owner: string | null): string {
return owner === null ? 'no owner' : owner === '' ? 'owner deleted' : `owner ${owner}`;
}
+2 -4
View File
@@ -1,5 +1,5 @@
import { type Container, type FederatedPointerEvent, Graphics, Rectangle } from 'pixi.js';
import { Button, crisp, drawControlBox, Icon, Label, Spacer, Theme, ui, Widget } from '../ui';
import { Button, crisp, drawFloatingBox, Icon, Label, Spacer, Theme, ui, Widget } from '../ui';
import { onScreen, sized, type WindowBox } from './floating';
import { TabHeader } from './TabHeader';
@@ -170,9 +170,7 @@ export class FloatWindow extends Widget {
override redraw(): void {
const c = Theme.colors;
this.bg.clear();
this.bg.roundRect(2, 3, this.w, this.h, Theme.radius).fill({ color: 0x000000, alpha: 0.35 }); // drop shadow
drawControlBox(this.bg, this.w, this.h, { fill: c.panel, border: c.border });
drawFloatingBox(this.bg, this.w, this.h, c.panel);
// Three short diagonals in the corner, the usual sign of a handle that sizes a window.
this.grip.clear();
for (const at of [4, 8, 12]) this.grip.moveTo(GRIP - at, GRIP).lineTo(GRIP, GRIP - at);
+2 -8
View File
@@ -4,14 +4,8 @@ import type { SchedulerOptions } from '../core/music/Scheduler';
import type { Sequence } from '../core/music/sequence';
import type { FxEnvelope, FxStage } from '../core/soundfx/nodes';
import { Music } from '../viewport/music';
import {
bothAtCenter,
envelopeDriver,
followCurve,
releaseEnvelope,
soundLibrary,
stageNodes,
} from '../viewport/SoundLibrary';
import { bothAtCenter, envelopeDriver, followCurve, releaseEnvelope, stageNodes } from '../viewport/fxNodes';
import { soundLibrary } from '../viewport/SoundLibrary';
import { saturationAutoGain } from '../core/soundfx/saturation';
import { curveHooks } from './debug/curveHooks';
import { soundHooks } from './debug/soundHooks';
+1 -1
View File
@@ -13,7 +13,7 @@ export interface WindowBox {
export const MIN_WINDOW_WIDTH = 320;
export const MIN_WINDOW_HEIGHT = 200;
/** How far each further window opens down and to the right, so it does not hide the one before. */
export const WINDOW_STEP = 24;
const WINDOW_STEP = 24;
/** Half the screen's width and 60 % of its height, in the middle; the `count`-th one a step further. */
export function openingBox(screenW: number, screenH: number, count: number): WindowBox {
+4 -3
View File
@@ -128,9 +128,10 @@ function shaderEntries(project: Project, asset: ShaderAsset | ShaderFunctionAsse
/**
* 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.
* 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') {
+12 -74
View File
@@ -24,29 +24,18 @@ import { fxVoiceOf } from '../../core/music/needs';
import { MASTER_MIX } from '../../core/music/mixer';
import { DEFAULT_TEMPO } from '../../core/music/time';
import { instrumentFx, playNote } from '../../runtime/systems/behaviorContext';
import {
Button,
Dropdown,
HStack,
Label,
Menu,
NumberField,
Stack,
Theme,
VStack,
type Widget,
} from '../../ui';
import { Button, Dropdown, Label, Menu, VStack, type Widget } from '../../ui';
import { soundLibrary } from '../../viewport/SoundLibrary';
import { AssetTabEditor } from '../AssetTabEditor';
import { GraphCanvas } from '../graph/GraphCanvas';
import { SnapToggle } from '../graph/SnapToggle';
import { TOOLBAR_ICON_SVG } from '../panels/toolbarIcons';
import { PreviewParams } from '../soundfx/PreviewParams';
import type { EditorState } from '../state';
import { PianoKeyboard } from './PianoKeyboard';
/** Room kept for "N notes", or for the reason the graph does not compile: "No sound picked" fits, a longer one is cut. */
const INFO_WIDTH = 140;
const PARAM_WIDTH = 48;
/** Whose voices the tab's Stop silences: its own, never a running game's. */
const PREVIEW_OWNER = 'instrument-preview';
/** How long a note is heard after Randomize, Mutate or a change with Audition on: a held one is let go then. */
@@ -74,14 +63,8 @@ export class InstrumentEditor extends AssetTabEditor<InstrumentAsset, GraphCanva
/** The note Randomize, Mutate or Audition plays: the one last played. */
lastNote = MIDDLE_C;
private readonly octaveLabel = new Label('', { style: 'small' });
private readonly paramBar = new HStack({ gap: Theme.gap, align: 'center' });
private readonly paramFields = new Map<string, NumberField>();
private values: Record<string, number> = {};
private defaults: Record<string, number> = {};
private paramsKey = '';
private valuesFor = '';
/** The voices the tab started that may still be playing – what a moved field reaches – and whose. */
private voices: number[] = [];
private readonly params = new PreviewParams();
/** The asset whose voices the tab may still be playing. */
private playedFor = '';
/** The graph as last heard or shown, by `soundPrint`, and whose it was. */
private heard = '';
@@ -122,11 +105,11 @@ export class InstrumentEditor extends AssetTabEditor<InstrumentAsset, GraphCanva
this.mutateButton,
this.auditionButton,
this.octaveLabel,
this.paramBar,
this.params.bar,
]);
this.syncOctave();
state.on('load', () => {
this.valuesFor = '';
this.params.forget();
this.heardFor = '';
});
}
@@ -148,13 +131,11 @@ export class InstrumentEditor extends AssetTabEditor<InstrumentAsset, GraphCanva
/** What the header's parameter fields are set to – the check scripts read this. */
get previewValues(): Record<string, number> {
return { ...this.values };
return this.params.current;
}
setPreviewValue(key: string, value: number): void {
if (!(key in this.values)) return;
this.paramFields.get(key)?.setNumber(value);
this.setValue(key, value);
this.params.set(key, value);
}
/** Starts one note as the keys do, held until it is released or for `duration` seconds; gives back its voice. */
@@ -168,12 +149,12 @@ export class InstrumentEditor extends AssetTabEditor<InstrumentAsset, GraphCanva
asset.id,
struck,
PREVIEW_OWNER,
{ ...this.values },
this.params.current,
// Straight into the master: a preview leaves the routing of the instrument out (#368).
{ bus: MASTER_MIX },
fxVoiceOf(this.state.project, instrumentFx(this.state.project, asset.id, ''), DEFAULT_TEMPO),
);
if (voice) this.voices.push(voice);
this.params.heard(voice);
this.playedFor = asset.id;
return voice;
}
@@ -224,7 +205,7 @@ export class InstrumentEditor extends AssetTabEditor<InstrumentAsset, GraphCanva
stop(): void {
this.keyboard.releaseAll();
soundLibrary.stopOwner(PREVIEW_OWNER);
this.voices = [];
this.params.silenced();
this.keyboard.syncRinging();
}
@@ -242,11 +223,6 @@ export class InstrumentEditor extends AssetTabEditor<InstrumentAsset, GraphCanva
.sort((a, b) => a - b);
}
private setValue(key: string, value: number): void {
this.values[key] = value;
this.voices = this.voices.filter((voice) => soundLibrary.tune(voice, { [key]: value }));
}
protected override infoText(asset: InstrumentAsset): string {
const build = instrumentCheck(asset, instrumentSourcesOf(this.state.project));
if (build.reason) return build.reason;
@@ -264,7 +240,7 @@ export class InstrumentEditor extends AssetTabEditor<InstrumentAsset, GraphCanva
this.keyboard.setEnabled(Boolean(asset));
if (!asset) this.keyboard.releaseAll();
this.keyboard.setSounding(new Set(this.soundingNotes()));
this.syncParams(asset);
this.params.sync(asset?.id ?? '', asset ? instrumentParams(asset.graph) : []);
this.followEdits(asset);
}
@@ -283,44 +259,6 @@ export class InstrumentEditor extends AssetTabEditor<InstrumentAsset, GraphCanva
const octave = this.keyboard.bottomOctave;
this.octaveLabel.setText(`Keys ${noteName((octave + 1) * 12)} to ${noteName((octave + 3) * 12 + 4)}`);
}
/** As in the Sound FX tab: another asset starts from its defaults, an edit keeps a moved value. */
private syncParams(asset: InstrumentAsset | null): void {
const params = asset ? instrumentParams(asset.graph) : [];
const same = (asset?.id ?? '') === this.valuesFor;
this.valuesFor = asset?.id ?? '';
const values: Record<string, number> = {};
const defaults: Record<string, number> = {};
for (const port of params) {
const fallback = port.default ?? 0;
const kept = same && this.defaults[port.key] === fallback ? this.values[port.key] : undefined;
values[port.key] = kept ?? fallback;
defaults[port.key] = fallback;
}
this.values = values;
this.defaults = defaults;
const key = params.map((p) => p.key).join('\u0000');
if (key !== this.paramsKey) {
this.paramsKey = key;
for (const child of this.paramBar.removeChildren()) child.destroy({ children: true });
this.paramFields.clear();
for (const port of params) {
this.paramBar.add(new Label(port.key, { style: 'small' }));
const field = new NumberField(values[port.key], {
width: PARAM_WIDTH,
step: 0.1,
onInput: (value) => this.setValue(port.key, value),
onChange: (value) => this.setValue(port.key, value),
});
this.paramFields.set(port.key, field);
this.paramBar.add(field);
}
if (this.paramBar.parent instanceof Stack) this.paramBar.parent.relayout();
this.paramBar.relayout();
}
for (const [name, field] of this.paramFields) field.setNumber(this.values[name] ?? 0);
}
}
/** How a note of the instrument sounds hangs on its nodes' settings and edges, not on where they lie. */
+2 -2
View File
@@ -38,7 +38,7 @@ export function zoomTime(view: TimeView, factor: number, x: number, most = MAX_P
}
/** How far right of the area's left edge tick 0 can be panned, as a share of the area's width. */
export const TIME_LEAD = 0.5;
const TIME_LEAD = 0.5;
/**
* Time starts at 0, but it need not stand at the left edge: a pan can take it up to half the area in,
@@ -51,7 +51,7 @@ export function clampTimePan<V extends TimeView>(view: V, width: number, earlies
}
/** How far past the first or the last row (a note, a track) a pan can go, as a share of the area's height. */
export const ROW_LEAD = 0.5;
const ROW_LEAD = 0.5;
/**
* Down the area as across it: the first row can be panned up to half the height down from the top
+9 -8
View File
@@ -5,7 +5,7 @@ import {
Graphics,
type Text,
} from 'pixi.js';
import { SetPatternLoopCommand, SetPatternNotesCommand } from '../../core/commands/patternCommands';
import { SetLoopCommand, SetPatternNotesCommand } from '../../core/commands/patternCommands';
import type { GhostNote, Ghosts } from '../../core/music/ghosts';
import { HIGHEST_NOTE, isSharp, LOWEST_NOTE, MIDDLE_C, noteName } from '../../core/instrument/notes';
import {
@@ -81,8 +81,8 @@ import {
zoomRows,
} from './rollView';
export const KEYS_WIDTH = 84;
export const VELOCITY_HEIGHT = 64;
const KEYS_WIDTH = 84;
const VELOCITY_HEIGHT = 64;
const DRAG_THRESHOLD = 3;
/** How close to an end of the loop a press on the ruler takes that end. */
const LOOP_EDGE_REACH = 4;
@@ -151,8 +151,9 @@ function mix(a: number, b: number, t: number): number {
* The Pattern tab's canvas (#333): the keys down the left, a ruler along the top, the notes in a grid
* between them and their velocities in a lane below. A click into the grid draws a note, a drag spans
* a band that picks notes; a note is dragged by its body, sized by either end, which lights up under
* the pointer, and goes with a right-click or Delete. A press or a drag on the ruler moves where playing starts, one on the strip
* along its top sets the loop. The wheel zooms: the time over the grid, the rows over the keys.
* the pointer, and goes with a right-click or Delete. A press or a drag on the ruler moves where
* playing starts, one on the strip along its top sets the loop. The wheel zooms: the time over the
* grid, the rows over the keys.
*/
export class PianoRoll extends Widget {
private readonly bg = new Graphics();
@@ -718,7 +719,7 @@ export class PianoRoll extends Widget {
case 'loop': {
const same = JSON.stringify(gesture.loop) === JSON.stringify(patternLoop(asset));
if (gesture.active && gesture.loop && !same)
this.state.execute(new SetPatternLoopCommand(asset.id, gesture.loop));
this.state.execute(new SetLoopCommand('pattern', asset.id, gesture.loop));
break;
}
case 'cursor':
@@ -884,12 +885,12 @@ export class PianoRoll extends Widget {
{
label: `Loop bar ${first / bar + 1}`,
onSelect: () =>
this.state.execute(new SetPatternLoopCommand(asset.id, { start: first, end: first + bar })),
this.state.execute(new SetLoopCommand('pattern', asset.id, { start: first, end: first + bar })),
},
{
label: 'Loop the whole pattern',
disabled: !asset.loop,
onSelect: () => this.state.execute(new SetPatternLoopCommand(asset.id, null)),
onSelect: () => this.state.execute(new SetLoopCommand('pattern', asset.id, null)),
},
]).open(global.x, global.y);
}
+2 -2
View File
@@ -16,8 +16,8 @@ export interface RollView extends TimeView {
}
export const ROWS = HIGHEST_NOTE - LOWEST_NOTE + 1;
export const MIN_ROW_HEIGHT = 6;
export const MAX_ROW_HEIGHT = 64;
const MIN_ROW_HEIGHT = 6;
const MAX_ROW_HEIGHT = 64;
export const DEFAULT_ROW_HEIGHT = 14;
/** How far in from an end of a note a press takes that end rather than the note. */
export const END_GRIP = 6;
+9 -7
View File
@@ -7,7 +7,8 @@ import {
} from 'pixi.js';
import { CreateAssetCommand, MakeProjectAssetCommand } from '../../core/commands/assetCommands';
import { CompoundCommand } from '../../core/commands/CompoundCommand';
import { SetSongCommand, SetSongLoopCommand, type SongParts } from '../../core/commands/songCommands';
import { SetLoopCommand } from '../../core/commands/patternCommands';
import { SetSongCommand, type SongParts } from '../../core/commands/songCommands';
import {
embeddedCopy,
embeddedName,
@@ -218,9 +219,10 @@ interface Drop {
* The Song tab's canvas (#334): the heads of the tracks down the left, a ruler along the top and the
* items on the lanes between. An asset dragged in from the panel lands as an item; an item is moved
* by its body and sized by either end – pulled out past what it plays, it repeats that, and an end
* snaps to where a round starts as well as to the grid –, and goes with Delete or its menu. A head sets its track's mute, solo, volume and pan. What is picked lives in the editor's
* selection, so the inspector shows it; a click on nothing picks the song. The wheel zooms: the time
* over the lanes, the tracks over their heads.
* snaps to where a round starts as well as to the grid –, and goes with Delete or its menu. A head
* sets its track's mute, solo, volume and pan. What is picked lives in the editor's selection, so
* the inspector shows it; a click on nothing picks the song. The wheel zooms: the time over the
* lanes, the tracks over their heads.
*/
export class SongTimeline extends Widget {
private readonly bg = new Graphics();
@@ -975,7 +977,7 @@ export class SongTimeline extends Widget {
case 'loop': {
const same = JSON.stringify(gesture.loop) === JSON.stringify(songLoop(asset));
if (gesture.active && gesture.loop && !same)
this.state.execute(new SetSongLoopCommand(asset.id, gesture.loop));
this.state.execute(new SetLoopCommand('song', asset.id, gesture.loop));
break;
}
case 'cursor':
@@ -1118,12 +1120,12 @@ export class SongTimeline extends Widget {
{
label: `Loop bar ${first / bar + 1}`,
onSelect: () =>
this.state.execute(new SetSongLoopCommand(asset.id, { start: first, end: first + bar })),
this.state.execute(new SetLoopCommand('song', asset.id, { start: first, end: first + bar })),
},
{
label: 'Loop the whole song',
disabled: !asset.loop,
onSelect: () => this.state.execute(new SetSongLoopCommand(asset.id, null)),
onSelect: () => this.state.execute(new SetLoopCommand('song', asset.id, null)),
},
]).open(global.x, global.y);
}
+2 -2
View File
@@ -1,8 +1,8 @@
import { clamp } from '../../ui';
/** The scale of a level meter (#359) in dBFS: what is quieter shows nothing, past 0 it clips. */
export const METER_MIN_DB = -48;
export const METER_MAX_DB = 6;
const METER_MIN_DB = -48;
const METER_MAX_DB = 6;
/** From here on a meter is yellow; past 0 dBFS it is red. */
export const METER_WARM_DB = -6;
/** Seconds the loudest peak stays put before it falls. */
+4 -4
View File
@@ -11,12 +11,12 @@ export interface WaveView {
}
/** From a few minutes across a screen to a sample every few pixels at 48 kHz. */
export const MIN_PX_PER_SECOND = 0.5;
export const MAX_PX_PER_SECOND = 200_000;
const MIN_PX_PER_SECOND = 0.5;
const MAX_PX_PER_SECOND = 200_000;
/** How far either end of the file can be panned in from its edge of the area, as a share of its width. */
const LEAD = 0.5;
/** Pixels either side of a handle that grab it. */
export const EDGE_REACH = 6;
const EDGE_REACH = 6;
export function secondsToX(view: WaveView, seconds: number): number {
return view.panX + seconds * view.pxPerSecond;
@@ -210,7 +210,7 @@ function roundTo(seconds: number, rate: number): number {
}
/** Samples each block of `WavePeaks` covers. */
export const PEAK_BLOCK = 256;
const PEAK_BLOCK = 256;
/** The lowest and highest sample of each block of a sound, over all its channels. */
export interface WavePeaks {
+7 -10
View File
@@ -17,13 +17,12 @@ import {
EQ_GAIN,
EQ_Q,
EQ_SLOPES,
eqBandResponse,
eqBandsOf,
eqBandsValue,
eqCurves,
hasGain,
hasQ,
hasSlope,
isEqBandHeard,
MAX_EQ_BANDS,
newEqBand,
withBandSet,
@@ -230,21 +229,19 @@ class EqCurve extends Widget {
const zero = Math.round(dbToY(0, area)) + 0.5;
this.grid.moveTo(0, zero).lineTo(this.w, zero).stroke({ color: c.textMuted, width: 1, alpha: 0.5 });
// Each band once at every step; the sum is added up from them rather than worked out again.
const bands = this.host.bands();
this.lines.clear();
const xs = Array.from({ length: CURVE_STEPS + 1 }, (_, i) => (i / CURVE_STEPS) * this.w);
const frequencies = xs.map((x) => xToFrequency(x, area));
const yOf = (db: number) => Math.max(-2, Math.min(this.h + 2, dbToY(db, area)));
const sum = new Array<number>(xs.length).fill(0);
bands.forEach((band, i) => {
const response = eqBandResponse(band);
const dbs = frequencies.map(response);
if (isEqBandHeard(band)) dbs.forEach((db, j) => (sum[j]! += db));
const curves = eqCurves(
bands,
xs.map((x) => xToFrequency(x, area)),
);
curves.bands.forEach((dbs, i) => {
this.trace(xs, dbs.map(yOf));
this.lines.stroke({ color: BAND_COLORS[i]!, width: 1, alpha: i === this.host.picked ? 0.9 : 0.4 });
});
const ys = sum.map(yOf);
const ys = curves.sum.map(yOf);
for (const shape of fillShapes(xs, ys, zero))
this.lines.poly(shape).fill({ color: c.accent, alpha: 0.12 });
this.trace(xs, ys);
+89
View File
@@ -0,0 +1,89 @@
import type { DeclaredPort } from '../../core/graph/Graph';
import { HStack, Label, NumberField, Stack, Theme } from '../../ui';
import { soundLibrary } from '../../viewport/SoundLibrary';
const FIELD_WIDTH = 48;
/**
* The header's fields for the parameters of the graph a tab plays (#311, #331): a name and a number
* each, the tab's own values, never written into the asset. A moved field is heard at once on the
* voices the tab started that still play (#315). Another asset starts from its defaults; an edit of
* the graph keeps what a field was moved to, unless that parameter's default changed with it.
*/
export class PreviewParams {
readonly bar = new HStack({ gap: Theme.gap, align: 'center' });
private readonly fields = new Map<string, NumberField>();
private values: Record<string, number> = {};
private defaults: Record<string, number> = {};
private keys = '';
private valuesFor = '';
private voices: number[] = [];
/** What the fields are set to. */
get current(): Record<string, number> {
return { ...this.values };
}
/** Sets one parameter, as typing into its field does. */
set(key: string, value: number): void {
if (!(key in this.values)) return;
this.fields.get(key)?.setNumber(value);
this.setValue(key, value);
}
/** A voice the tab started, for a moved field to reach while it plays. */
heard(voice: number): void {
if (voice) this.voices.push(voice);
}
/** The tab stopped everything it played. */
silenced(): void {
this.voices = [];
}
/** Another project: the next asset starts from its defaults. */
forget(): void {
this.valuesFor = '';
}
sync(assetId: string, params: readonly DeclaredPort[]): void {
const same = assetId === this.valuesFor;
this.valuesFor = assetId;
const values: Record<string, number> = {};
const defaults: Record<string, number> = {};
for (const port of params) {
const fallback = port.default ?? 0;
const kept = same && this.defaults[port.key] === fallback ? this.values[port.key] : undefined;
values[port.key] = kept ?? fallback;
defaults[port.key] = fallback;
}
this.values = values;
this.defaults = defaults;
const keys = params.map((p) => p.key).join('\u0000');
if (keys !== this.keys) {
this.keys = keys;
for (const child of this.bar.removeChildren()) child.destroy({ children: true });
this.fields.clear();
for (const port of params) {
this.bar.add(new Label(port.key, { style: 'small' }));
const field = new NumberField(values[port.key], {
width: FIELD_WIDTH,
step: 0.1,
onInput: (value) => this.setValue(port.key, value),
onChange: (value) => this.setValue(port.key, value),
});
this.fields.set(port.key, field);
this.bar.add(field);
}
if (this.bar.parent instanceof Stack) this.bar.parent.relayout();
this.bar.relayout();
}
for (const [name, field] of this.fields) field.setNumber(this.values[name] ?? 0);
}
private setValue(key: string, value: number): void {
this.values[key] = value;
this.voices = this.voices.filter((voice) => soundLibrary.tune(voice, { [key]: value }));
}
}
+12 -69
View File
@@ -5,7 +5,7 @@ import { playedSoundOf } from '../../core/properties/playedSound';
import { resolveAssetProps } from '../../core/properties/resolve';
import { volumeOf } from '../../core/properties/sounds';
import { soundFxBuildFor, soundFxParams } from '../../core/soundfx/compile';
import { Button, Dropdown, HStack, Label, Menu, NumberField, Stack, Theme } from '../../ui';
import { Button, Dropdown, Menu } from '../../ui';
import { soundLibrary } from '../../viewport/SoundLibrary';
import { MASTER_MIX } from '../../core/music/mixer';
import { AssetTabEditor } from '../AssetTabEditor';
@@ -13,11 +13,11 @@ import { GraphCanvas } from '../graph/GraphCanvas';
import { SnapToggle } from '../graph/SnapToggle';
import { TOOLBAR_ICON_SVG } from '../panels/toolbarIcons';
import type { EditorState } from '../state';
import { PreviewParams } from './PreviewParams';
/** Room kept for "N effects", or for the reason the graph does not compile. */
const INFO_WIDTH = 220;
const SOUND_WIDTH = 140;
const PARAM_WIDTH = 48;
/** Whose voices the tab's Stop silences: its own, never a running game's. */
const PREVIEW_OWNER = 'soundfx-preview';
@@ -34,16 +34,8 @@ export class SoundFxEditor extends AssetTabEditor<SoundFxAsset, GraphCanvas> {
readonly stopButton: Button;
private soundId = '';
/** One name and number per parameter of the Input: what the header's Play hands in. */
private readonly paramBar = new HStack({ gap: Theme.gap, align: 'center' });
private readonly paramFields = new Map<string, NumberField>();
/** The values the tab plays with – its own, never written into the asset. */
private values: Record<string, number> = {};
/** The defaults the values were taken from, so an edited default comes through and a moved value stays. */
private defaults: Record<string, number> = {};
private paramsKey = '';
private valuesFor = '';
/** The voices the tab started that may still be playing – what a moved field reaches – and whose. */
private voices: number[] = [];
private readonly params = new PreviewParams();
/** The asset whose voices the tab may still be playing. */
private playedFor = '';
constructor(state: EditorState) {
@@ -59,11 +51,11 @@ export class SoundFxEditor extends AssetTabEditor<SoundFxAsset, GraphCanvas> {
this.soundPicker,
this.playButton,
this.stopButton,
this.paramBar,
this.params.bar,
]);
state.on('load', () => {
this.soundId = '';
this.valuesFor = '';
this.params.forget();
});
}
@@ -88,14 +80,12 @@ export class SoundFxEditor extends AssetTabEditor<SoundFxAsset, GraphCanvas> {
/** What the header's parameter fields are set to – the check scripts read this. */
get previewValues(): Record<string, number> {
return { ...this.values };
return this.params.current;
}
/** Sets one parameter the header plays with, as typing into its field does. */
setPreviewValue(key: string, value: number): void {
if (!(key in this.values)) return;
this.paramFields.get(key)?.setNumber(value);
this.setValue(key, value);
this.params.set(key, value);
}
/** Plays the picked sound through the graph; a graph that does not compile is not played at all. */
@@ -105,23 +95,17 @@ export class SoundFxEditor extends AssetTabEditor<SoundFxAsset, GraphCanvas> {
const plan = asset && soundFxBuildFor(asset, this.state.project).compiled;
if (!sound?.asset.file || !plan) return;
const props = resolveAssetProps(this.state.project, sound.asset);
const fx = { plan, params: { ...this.values } };
const fx = { plan, params: this.params.current };
// Straight into the master: a preview leaves the routing of the sound out (#368).
const file = playedSoundOf(sound);
const voice = soundLibrary.play(file, volumeOf(props), false, PREVIEW_OWNER, fx, MASTER_MIX);
if (voice) this.voices.push(voice);
this.params.heard(voice);
this.playedFor = asset.id;
}
/** A moved field is heard at once on what the tab is playing (#315); an ended voice is let go. */
private setValue(key: string, value: number): void {
this.values[key] = value;
this.voices = this.voices.filter((voice) => soundLibrary.tune(voice, { [key]: value }));
}
stop(): void {
soundLibrary.stopOwner(PREVIEW_OWNER);
this.voices = [];
this.params.silenced();
}
protected override closed(assetId: string): void {
@@ -144,48 +128,7 @@ export class SoundFxEditor extends AssetTabEditor<SoundFxAsset, GraphCanvas> {
Boolean(asset && sound?.asset.file && soundFxBuildFor(asset, this.state.project).compiled),
);
this.stopButton.setEnabled(Boolean(asset));
this.syncParams(asset);
}
/**
* Another asset starts from its defaults; an edit of the graph keeps what a field was moved to,
* unless that parameter's default changed with it.
*/
private syncParams(asset: SoundFxAsset | null): void {
const params = asset ? soundFxParams(asset.graph) : [];
const same = (asset?.id ?? '') === this.valuesFor;
this.valuesFor = asset?.id ?? '';
const values: Record<string, number> = {};
const defaults: Record<string, number> = {};
for (const port of params) {
const fallback = port.default ?? 0;
const kept = same && this.defaults[port.key] === fallback ? this.values[port.key] : undefined;
values[port.key] = kept ?? fallback;
defaults[port.key] = fallback;
}
this.values = values;
this.defaults = defaults;
const key = params.map((p) => p.key).join('\u0000');
if (key !== this.paramsKey) {
this.paramsKey = key;
for (const child of this.paramBar.removeChildren()) child.destroy({ children: true });
this.paramFields.clear();
for (const port of params) {
this.paramBar.add(new Label(port.key, { style: 'small' }));
const field = new NumberField(values[port.key], {
width: PARAM_WIDTH,
step: 0.1,
onInput: (value) => this.setValue(port.key, value),
onChange: (value) => this.setValue(port.key, value),
});
this.paramFields.set(port.key, field);
this.paramBar.add(field);
}
if (this.paramBar.parent instanceof Stack) this.paramBar.parent.relayout();
this.paramBar.relayout();
}
for (const [name, field] of this.paramFields) field.setNumber(this.values[name] ?? 0);
this.params.sync(asset?.id ?? '', asset ? soundFxParams(asset.graph) : []);
}
private openSoundPicker(): void {
+1 -1
View File
@@ -10,7 +10,7 @@ export interface EqArea {
}
/** The dB the picture shows above and below 0. */
export const EQ_VIEW_DB = EQ_GAIN.max;
const EQ_VIEW_DB = EQ_GAIN.max;
const SPAN = Math.log(EQ_FREQUENCY.max / EQ_FREQUENCY.min);