
# Sound design

You cannot hear. This skill replaces ears with a loop: **state the intent → synthesize → measure → look → revise**.
It ships a zero-dependency JavaScript DSP library (`lib/`), analyzers (`tools/`), and references that explain
what matters for each kind of sound. Everything runs with `bun` or `node ≥ 18`; nothing to install for the core.

```bash
SKILL=<this folder>
bun $SKILL/tools/analyze.mjs out/hit.wav --lens impact --png      # report + picture
bun $SKILL/tools/compare.mjs ref.wav out/hit.wav                    # how it differs from a reference / last version
bun $SKILL/tools/compare.mjs --variety out/var_*.wav                # are variations too similar / too different
bun $SKILL/tools/loopcheck.mjs out/bed.wav --png                    # does it loop
```
In scripts: `import * as sd from '<skill>/lib/node.js'` (everything + file IO) — in pages: `lib/index.js` and
`lib/webaudio/index.js`. Start from `templates/generate.mjs` (offline) or `templates/browser/index.html` (realtime).
`references/api.md` is the one-page map of every function.

## The loop

1. **Intent first.** Before any code write two or three sentences: what is the source, what happens to it, where,
   and what should the listener feel. Then translate *only this brief's* consequences into measurable
   expectations (`--expect` / `sd.save(..., { expect })`). "Hit lands on 2.00 s", "feels heavy → sub present for
   ≥ 0.8 s", "tiny object → modes above 1.5 kHz, decay < 0.4 s". Three to six lines. Leave everything the brief
   does not constrain unconstrained.
2. **Choose a route, preferably two.** Most sounds can be reached by different mechanisms (modal strike vs.
   layered noise; kernel vs. granulated recording). For any asset that matters, sketch two routes with different
   mechanisms and let the measurements and pictures choose; this is the main protection against every asset
   sounding like the library's defaults.
3. **Render and read the report.** `sd.save()` writes the WAV and prints the analysis. Read the `TIME` heat map
   (band × time) and the `ENV` line first — they show the gesture. Add the lens for the sound's family. Open the
   PNG when timing, layering or a suspected artifact needs eyes (`--zoom t0,t1` for attacks and seams).
4. **Revise from evidence.** Change the mechanism when the *shape* is wrong; change parameters when the shape is
   right but the amounts are off. If an expectation fails, also ask whether the expectation was right.
5. **Finish like a deliverable.** Fix every item under `DEFECTS` (they are wrong for any brief), set loudness with
   `sd.master()` or `sd.normalizeLoudness()`, keep the seed and parameters next to the file (`meta`), and say
   plainly to the user that the result was verified by measurement, not by ear — offer the preview page or files
   so a human can listen.

Read `references/workflow.md` once per session: it explains how to turn adjectives into expectations and how
to keep taste from collapsing into the analyzer's numbers.

## Where to look

| The task is… | Read | Main entry points |
|---|---|---|
| Objects hitting, rolling, scraping, breaking; sound driven by a physics engine; Doppler, pass-bys, 3D placement | `references/physics.md` | `objectModes strike strikes bounceEvents rollForce scrapeForce stickSlipForce shatter PhysicsSonifier spatialize` |
| Sand, gravel, grain, rain-on-things, debris, crunchy footsteps | `references/sand.md` | `GrainFlow pour crunch SURFACES` |
| Trailer / advert / cutscene SFX, anything "cinematic", urgency, sync to picture | `references/cinematic.md` | `impact boom subDrop riser whoosh braam downer shimmer drone glitch cue master` |
| Game asset sets, variations, using or extending recorded samples, free libraries | `references/game-assets.md` | `sampleModel resynth variations enhance granulate` |
| Voices without TTS: babble, creature/robot talk, Animalese, walla | `references/speech.md` | `speak voiceFx crowd VOICES` |
| Ambience beds, loops, weather/city/nature/machines, moving through spaces | `references/ambience.md` | `Wind Rain Fire Stream Sea Birds Insects Traffic Engine Machine Hum Air Clock RoomTone loopKernel makeLoop tailWrap renderScene AmbienceMixer` |
| Which runtime: WAV file, AudioWorklet, native Web Audio graph, server render | `references/deployment.md` | `renderKernel kernelNode tract SpatialSource renderOffline` |
| What a metric means, which lens, how to read the spectrogram | `references/analysis.md` | `tools/*.mjs analyze checkExpectations` |
| Sources, books, other skills, papers behind the models | `references/prior-art.md` | — |

Read only the reference for the family you are working in; they are independent.

## Three ways to ship a sound

| Mode | What it is | Choose when |
|---|---|---|
| **Baked** | Render to WAV (`renderKernel`, offline functions, `renderScene`), optionally with N variations | Linear media, engines with their own audio pipeline (Unity/Unreal/Godot/FMOD/Wwise), heavy one-shots |
| **Kernel** | A parametric generator class running in an `AudioWorklet` (and identically offline) | The sound must respond continuously: physics, weather intensity, engine RPM, sand flow, endless non-repeating beds |
| **Graph** | Native Web Audio nodes: baked or kernel sources into `tract()` effects, `SpatialSource` (HRTF + Doppler), `AmbienceMixer` zones | Placement, rooms, mixing and interaction in the browser; same graph renders on a server for tests |

They combine: bake the expensive layer, keep the responsive layer as a kernel, place both with the graph.
Details and trade-offs: `references/deployment.md`.

## Keeping sounds from converging

The library and the analyzers both pull toward an average. Push back deliberately:

- **Presets are starting data.** `MATERIALS`, `SURFACES`, `SPACES`, `VOICES` and every default are examples of
  the parameter space. Derive values from the brief (how big, how hard, how far, how wet) and invent entries.
- **Measure what the brief names, ignore the rest.** A metric you did not put in the expectations is
  information, not a target. Never "improve" a number nobody asked about.
- **One distinguishing idea per asset.** Decide what is particular about *this* sound — an odd resonance, a
  double hit, a breath before the impact, a rattle after it — and build it in; then check it is visible in the
  report or picture.
- **Vary structure, not only the seed.** Variations that differ just by random jitter read as repeats; change
  event count, order, balance of layers, the route itself.
- **Check a set as a set.** `compare.mjs --variety` on a batch: variations of one asset should sit roughly
  1.5–5 dB apart; assets for different briefs landing under ~4 dB apart means the generator is deciding, not you.
- **Write your own DSP when the brief needs it.** `lib/core` is small on purpose; a 20-line custom generator
  made for the brief beats the nearest ready function bent out of shape.

## Things that are always wrong

Clipping; inter-sample peaks above −1 dBTP on delivery; DC offset; a click at the first/last sample; a tail cut
while audible; NaNs (reported loudly by `writeWav`); a "loop" that fails `loopcheck`; stereo that vanishes in mono
(`mono-sum loss` below about −3 dB) when the target may play mono; sub-bass panned off-centre. The analyzer lists
these under `DEFECTS`; none of them is a matter of taste.

## Layout

```
lib/core      rng, buffers, noise, oscillators/envelopes, filters, FFT, effects, reverb, WAV, Kernel base
lib/synth     modal (objects & contact), particles (grain flows), nature, mech, voice
lib/gen       cinematic building blocks, cue(), master()
lib/scene     spatialize (Doppler/3D, offline), scenes with zones, loop tools
lib/sample    sample → model → resynthesis, enhance, granulate
lib/analysis  loudness, measurements, report + lenses, compare/variety, PNG spectrogram
lib/webaudio  worklet host, kernelNode, tract, SpatialSource, AmbienceMixer, renderOffline
tools/        analyze · compare · loopcheck · build-worklet        dist/sd-worklet.js  single-file worklet bundle
templates/    generate.mjs (offline loop) · browser/index.html (realtime)
```
