# Physically-informed parametric sound: objects, contact, motion in space

## Contents
1. The model: exciter → resonator → space
2. Objects: modes from shape, material, size
3. Forces: strike, bounce, roll, scrape, stick–slip, break
4. Driving sound from a physics engine (`PhysicsSonifier`)
5. Space: distance, Doppler, binaural cues, occlusion, rooms
6. Hacks that work better than physics
7. Verifying

## 1. The model

Every contact sound is **a force signal driving a set of resonances, heard through a space**.
Keep the three separate and each becomes a parameter set you can map to a game/physics variable:

```
force (what touched it, how hard, how fast)  →  modes (what it is)  →  spatialize / reverb (where it is)
strikeForce / rollForce / scrapeForce / stickSlipForce      objectModes      spatialize, synthIR, SpatialSource
```
`resonate(force, modes, n)` runs any force through any object. `strike(modes, opts)` is the one-impact shortcut
(adds the contact click and an optional low thud). `strikes(modes, events)` renders a list of impacts.

## 2. Objects

`objectModes({ shape, material, f0 | size, count, hit, damping, split, spread, aspect, seed })` → `[{ f, t60, amp }]`

- **shape** sets the partial ratios: `bar` (chime, rod, wrench), `tine` (clamped: kalimba, ruler), `string`,
  `tube` (odd harmonics: hollow, bottle), `membrane` (drum skin), `disc` (lid, coin, plate), `shell` (cup, bowl,
  glass rim), `bell`, `plate` (dense inharmonic: sheet, pane, table top; `aspect` = side ratio), `block`
  (compact solid: stone, brick — a cluster with no clear pitch).
- **material** sets how fast each mode dies: decay rate = π·f·tanPhi + loss. Internal friction `tanPhi` is the
  perceptual signature of material (Klatzky, Pai & Krotkov 2000): tiny for steel/bronze/crystal, ~0.02 for wood
  and stone, 0.06+ plastic, 0.3 rubber. Because it multiplies frequency, highs always die first.
  `MATERIALS` are ball-park values — interpolate and invent (rusty = steel × 4 tanPhi; wet wood = wood × 2).
- **size / f0**: pitch scales with 1/size for the same shape and material. Give `f0` when you know the pitch you
  want, `size` (metres) when you know the object.
- **hit** (0–1) = where it is struck: centre hits (0.5) suppress every second mode (hollow, "boing"); near the
  edge everything speaks (bright, clangy). Randomize per hit for natural variation.
- **damping** multiplies all losses: free-hanging 1, hand-held 3–6, on cloth 10. The cheapest realism control.
- **split** detunes mode pairs by a fraction (0.002–0.01): slow beating, the shimmer of real bells and glasses.
- **spread** randomly mistunes ratios: 0 = textbook, 0.03–0.08 = handmade, cracked, irregular.

`morphModes(modes, { pitch, damping, tiltDbOct, jitter, seed })` transforms a set (size change, material
change, per-hit variation). Mode amplitudes are energy-normalized, so objects with 4 or 40 modes are comparably loud.

## 3. Forces

**Strike** — `strikeForce(sr, { hardness, velocity, mass })`. Contact time shrinks with hardness and (weakly)
velocity; a shorter pulse contains higher frequencies. Consequence: *the same object is brighter when hit harder
or with something harder* — the main cue of impact strength, obtained for free. If a soft hit does not ring,
the contact is longer than the mode's period: raise `hardness` or lower `f0` (soft mallets only excite low modes).
Velocity guide (m/s): 0.2 tap, 1.5 knock, 5 drop, 15 smash.

**Bounce** — `bounceEvents({ height, restitution, irregular })` → `[{ t, velocity }]`. Intervals and velocities
shrink by the restitution each time (0.3 clay, 0.6 wood, 0.85 steel on stone). The accelerating rhythm is the
signature; `irregular` scatters it for non-spherical things (coin, bolt, bottle). Feed to `strikes()`.

**Roll** — `rollForce(n, sr, { speed, radius, roughness, wobble })`. A surface profile read at the rolling
speed (louder *and* brighter when faster) plus one bump per revolution (rate = speed / 2πr): that slow throb
is what makes it read as rolling rather than as noise. Drive the *surface's* modes with it; the ball itself
is nearly inaudible while rolling.

**Scrape / slide** — `scrapeForce(n, sr, { speed, pressure, grain, roughness })`. `grain` (metres between
surface features) turns noise into a pitched rasp at speed/grain Hz: zipper, comb, file, tyre tread, guiro.

**Stick–slip** — `stickSlipForce(n, sr, { rate, jitter, sharpness })`. Pulses at `rate`: 3–40 Hz a creak you
can count, 40–300 a groan, above that a squeak whose pitch is the rate. Slow rate with large pulses then a
rush upward = a door; steady high rate = a brake squeal. Drive a damped plate (door panel) or a ringing one
(metal gate, wine glass).

**Break** — `shatter({ material, shape, f0, pieces, scatter, restitution, energy })`. One hard strike of the
whole object, then fragments with power-law sizes (few low, many high) that each fall and bounce.

Continuous forces are level-calibrated far below impacts (as in reality): a rolling ball sits ~20 dB under its
own drop. Scale deliberately if the scene needs otherwise.

## 4. Driving sound from a physics engine

`PhysicsSonifier` is a kernel (realtime in a worklet, or offline) holding named bodies as modal banks:

```js
const son = new sd.PhysicsSonifier(sr, { bodies: {
  ball:  { shape: 'shell', material: 'steel', size: 0.05, damping: 3 },
  floor: { shape: 'plate', material: 'hardwood', f0: 80, count: 36, damping: 2, gain: 0.6 } } });
son.impact({ a: 'ball', b: 'floor', velocity: 3.1, pan: -0.2 });          // collision callback
son.contact('id7', { a: 'ball', b: 'floor', type: 'roll', speed: 1.4, radius: 0.025 });  // each frame while touching
son.contactEnd('id7');
```
Mapping from engine data (Rapier, cannon-es, Matter, Box2D, PhysX):

| Engine gives | Use as |
|---|---|
| relative normal velocity at contact (or impulse / mass) | `impact.velocity` — ignore contacts below ~0.05 m/s |
| tangential speed while in contact, rolling vs sliding (angular·radius ≈ linear → roll) | `contact.type`, `speed` |
| normal force / weight | `contact.force` (scrape pressure) |
| contact point relative to the listener/camera | `pan` here, or route to a `SpatialSource` |
| body material tags | body `material`, `shape`, `size`; pair hardness defaults to the softer of the two |

Both bodies of a pair receive the same force, so one mug sounds different on wood and on stone without
authoring pairs. In the browser: `kernelNode(ctx, 'physics', { bodies })` then `node.call('impact', {...})`.
Rate-limit: merge impacts closer than ~5 ms on the same pair; cap active contacts.
Beyond rigid bodies: `GrainFlow` (many small impacts, see `sand.md`), `Stream`/`Fire`/`Wind` kernels with a
simulation value mapped to `flow`/`size`/`speed`, `Engine` with `rpm`/`load`.

## 5. Space

Offline: `spatialize(buf, { path, listener, model, refDistance, rolloff, doppler, air, occlusion, room, roomDb })`.
Realtime/browser: `SpatialSource` (HRTF `PannerNode` + delay line + air filter) — same cues, native quality.

- **Propagation delay is the engine.** Reading the source through a delay equal to distance/c gives the arrival
  lag and, when the distance changes, the Doppler shift — no separate pitch-shifter needed. Approaching at v:
  f·c/(c−v); receding: f·c/(c+v). A 90 km/h pass shifts about −250 cents in total. `doppler: 0` disables,
  `> 1` exaggerates (film/game pass-bys often use 1.5–3).
- **Distance** = four cues together: level (inverse law; `rolloff < 1` for game-friendly falloff), high-frequency
  loss (`air`: ~3 dB at 4 kHz per 100 m, modelled as a low-pass that closes with distance), direct-to-reverb
  ratio (`room`: the reverberant level barely changes with distance, so far sources are mostly room), and
  loudness-independent spectral balance. Level alone reads as "quieter", not "farther".
- **Direction**: `model: 'binaural'` adds inter-aural time difference (≤ 0.66 ms) and head shadow on the far ear
  (headphones); `'pan'` is equal-power only (speakers, mono-safe). For true elevation and front/back, render
  through the Web Audio HRTF panner (`SpatialSource`, also offline via `renderOffline`).
- **Occlusion** (0–1): low-pass falling toward ~350 Hz plus up to −20 dB. Obstruction (direct path blocked, room
  open) = occlude the dry signal only and keep the reverb.
- **Paths**: `passBy({ speed, distance, at })`, `orbit({ radius, period })`, `flyThrough({ from, to, duration })`,
  or `pathFromKeys([[t, x, y, z], …])` (smooth: velocity stays continuous, so no pitch jumps). Coordinates:
  listener at origin facing −Z, +X right, +Y up, metres.
- **Rooms**: `synthIR({ rt60, size, damping, bassRatio, er, predelay, density })`; `SPACES` holds starting points.
  Derive from the scene: volume and wall hardness → rt60; nearest wall → predelay/early reflections;
  furnishings → damping; `density < 1` for flutter and sparse outdoor echoes (street canyon, forest).

## 6. Hacks that work better than physics

- **Layer what the model lacks.** Pure modal hits miss the broadband click and the supporting surface; `strike`
  adds both (`click`, `thud`). For big impacts add a sub layer (`boom`) and debris (`crunch`).
- **Exaggerate couplings**, don't remove them: more brightness-per-velocity, more Doppler, faster air roll-off
  read as *more real* on small speakers.
- **Per-event variation over model accuracy**: ±20 % mode gains and ±1 % tuning per hit (`variation` in
  `strikes`) matters more than exact ratios.
- **Size by time-scaling**: a bigger version of the same event is lower *and* slower (decays and gaps stretch
  with size). `varispeed` does both at once; `morphModes({ pitch })` + `damping` does it parametrically.
- **Hollow = one extra resonance**: add a broad band-pass "cavity" (150–600 Hz) to any shell for boxes, buckets, bodies.
- **Friction as source–filter**: a pulse train through resonances makes creaks, squeaks, brakes, chair legs,
  rope strain, bowed anything — and, with formant-like resonances, animal vocalisations.
- **Fake rolling under a moving object**: low-passed noise amplitude-modulated at the wheel rate is usually enough.

## 7. Verifying

- Material: `--lens impact` — the band T60s must order low > mid > high for real solids, and their absolute
  size places the material (steel bar seconds; glass ~1 s; wood ~0.1 s).
- Strength scaling: render velocity 0.5 / 2 / 8 and `--brief` them — both loudness and centroid must rise.
- Bounce: onset times must form a shrinking geometric series (ratio ≈ restitution).
- Rolling/scrape: centroid and level in the `TIME` map must follow the speed curve.
- Doppler: `--lens spatial` reports the shift in cents and the implied speed; it should equal the scene's speed
  (× the `doppler` factor). The fastest glide must coincide with closest approach and with the level peak.
- Pan: the stereo sparkline must trace the programmed path; `ITD` non-zero for static off-centre binaural sources.
