# tilt-shift.js (J-04 module, v1.0.0)

One plain script with no dependencies and no `import`/`export`. It defines one global, `GameDNA_TiltShift`. Load it after `webgl-post.js` (I-08, global `GameDNA_Post`), with `<script src>` or pasted into a `<script>` tag, without changing it.

It turns the finished frame into a **tabletop miniature**: a horizontal band stays exactly as the game drew it, and above and below it the picture blurs more and more (a smooth ease from 0 to the full blur over `falloff`), with a small saturation and contrast lift. The band can **pull focus** to a point (a timed pull on the game clock) or **follow** a moving target. **Depth mode** focuses one layer of a parallax game instead of screen rows. HUD rects are never blurred, and HUD pixels are never smeared into the scene around them.

It adds four passes to the I-08 chain (order 400-403): a masked downsample, a horizontal and a vertical Gaussian whose radius grows with the distance from the band, and a composite. The game keeps drawing exactly as before; the module draws nothing on the game canvas. **Without WebGL** (or `?webgl=0`, or no `GameDNA_Post`) `create()` returns an instance whose methods are safe no-ops and the 2D canvas shows unchanged. **No method ever throws.**

## API

`GameDNA_TiltShift.create(options) → tilt`

| option | meaning |
|---|---|
| `canvas` | The game's canvas (or a selector, or its 2D context). The module reuses the `GameDNA_Post` instance already made for it, or makes one with `passes: 'none'`. |
| `post` | Optional: the game's existing `GameDNA_Post` instance. |
| `clock` | `() => gameMs`, the game's own step-counted time (e.g. `() => frame * 1000 / 60`). Focus pulls run on it, so `?t=&freeze=1` stills match play. Never `Date.now()`. |
| `uiRects` | Optional `[{x, y, w, h, r?}]` in canvas px (or `view` units), or a function returning them (read every frame). Those pixels stay as drawn and never bleed into the blur. The shared I-08 `uiMask` is read too. |
| `view` | Optional `{w, h}` when the game works in other units than the canvas backing store (a devicePixelRatio-sized canvas): `uiRects`, `focus` and `blurAt` then use those units. |
| `depth` | Optional canvas for depth mode: red = layer depth 0..1, same orientation and aspect as the game canvas (any size). |
| `params` | See below. |

| param | default | meaning |
|---|---|---|
| `center` | 0.55 | Band centre, fraction of the view height from the top (depth mode: the depth in focus). |
| `band` | 0.2 | Height of the sharp band, fraction of the view height (depth mode: depth units). |
| `falloff` | 0.3 | Distance over which the blur grows from 0 to `blur`, fraction of the view height. |
| `blur` | 6 | Largest blur radius in px at a 360 px tall view (scales with the view height; 0..16). |
| `angle` | 0 | Band tilt in degrees (−60..60). |
| `saturation` / `contrast` | 0.18 / 0.08 | Colour lift outside the HUD (0 = none). |
| `pullMs` | 600 | Default focus-pull time (game ms). |
| `lag` | 220 | `track()` spring time scale (ms) when `update()` is called each step: a critically damped glide that starts from rest and settles in about 2.4 × `lag`, no overshoot. |
| `res` | 'auto' | Blur buffer scale: 'auto' (0.5, or 0.25 when the overlay is taller than 800 px), 1, 0.5, 0.25. |
| `mode` | 'band' | 'band' (screen rows) or 'depth' (the `depth` canvas). |
| `showBand` | false | Thin guide lines at the band edges and at full blur (tuning aid). |
| `split` | 0 | Left fraction of the view shown untouched (comparison aid). |

| method | |
|---|---|
| `focus(target, {ms, band, instant})` | Pull the band centre to `target`: a y in view px, `{y}`, or `{x, y}` (with `angle`, the tilted line passes through the point). Depth mode: a depth 0..1. `ms` (default `pullMs`) on the game clock, eased in-out; `band` = new band height in view px. The same target again does not restart the pull, so calling it every step is safe. NaN or nothing is ignored (the band never jumps). Call it **in the game step**, where the point of interest changes. |
| `track(fn, {lag})` / `track(null)` | Follow `fn() → y` (or `{x, y}`) every frame. Starts from where the band is (no jump). With `update()` called per step it glides after it on a critically damped spring (`lag`); without it, the band sits on the target. `track(null)` stops and keeps the band where it is. |
| `update(dtMs)` | Once per fixed step (also in the `?t=` fast-forward) when you use `track` with a lag. |
| `render()` | Same as `post.render()`; once per drawn frame on every draw path. |
| `band()` | `{center, top, bottom, falloff, angle, mode, pulling, tracking}` in view px. |
| `blurAt(x, y)` | Blur radius (view px) the shader uses at that point now. |
| `setParams(o)`, `params()`, `setEnabled(on)`, `setUiRects(fn)`, `setDepth(canvas)` | Live changes. `setParams({center})` jumps the band (use `focus` for a pull). |
| `stats()` | `{active, mode, shared, frames, drawn, focusCalls, focusIgnored, focusBad, center, band, maxR, scale, uiRects, depth, errors, broken, passes, avgMs, w, h}`. |
| `destroy()` | Removes the passes (and the post instance if the module made it). |

## Integration (15 lines)

```js
// <script src="webgl-post.js"></script><script src="tilt-shift.js"></script> before the game script
const tilt = GameDNA_TiltShift.create({
  canvas: gameCanvas,                                   // the canvas the game draws on, unchanged
  clock: () => frameCount * 1000 / 60,                  // the game's fixed-step counter
  uiRects: () => hudRects,                              // every HUD panel / window drawn now, canvas px
  params: { band: 0.2, falloff: 0.3, blur: 6, saturation: 0.18, contrast: 0.08 }
});
tilt.track(() => player.y - camera.y);                  // follow the point of interest (on-screen px)
function step() {                                       // the game's fixed update
  /* ...existing step... */
  tilt.update(1000 / 60);
}
function onSelect(unit) { tilt.focus(unit.y + 8 - camera.y, { ms: 500 }); }   // a pull when the focus moves
function draw() { /* ...existing drawing, unchanged... */ tilt.render(); }    // last line of every draw path
```

## Choosing the focus

- **Follow the player** (camera follows the hero): `track(() => heroScreenY)`. The band stays on the hero and the edges of the screen blur.
- **Tactics or board games** (fixed map): `focus(cursorOrSelectedUnitScreenY)` whenever the cursor or the selected unit changes row; during the enemy phase focus the acting unit.
- **Title / attract screens**: a fixed `center` and a slow series of `focus` calls.
- Use on-screen coordinates: subtract the camera, add any HUD offset the draw uses (e.g. a map drawn 16 px below a top HUD bar).
- Battle screens, menus and dialogue that need the whole screen readable: `setEnabled(false)` there, or a wide `band`.

## Keep the rest of the game working

- Change nothing in how the game draws: canvas size, CSS, transform, smoothing. Never read the overlay or `tilt.active` for game logic: `?auto=1` must end the same with WebGL on and off.
- Find every draw path (title, play, pause, battle, result, and the single draw after the `?t=` fast-forward) and end each with `tilt.render()` (or `post.render()`).
- `focus` / `update` go in the step, not in draw, so the fast-forward replays them.
- One `GameDNA_Post` per canvas: pass the game's instance as `post` if it has one.

## Self-check without a browser

- Both modules byte-identical, `webgl-post.js` first; `create` once, after the canvas exists.
- `clock` is step-counted; `update(1000/60)` sits in the fixed step (if `track` is used).
- Every draw path ends with `render()`; `uiRects` lists every HUD panel in canvas px, plate-less text included.
- Focus targets are on-screen y (camera subtracted, HUD offset added) of something the player looks at.
- Walk the defaults on a 224 px tall game: band 45 px tall around the target, blur growing over 67 px to 3.7 px radius (6 × 224 / 360); a target at y = 100 gives sharp rows 78–122 and full blur above y = 11 and below y = 189.
- `?webgl=0`: the module is a no-op; the game looks and plays as before.

## What it guarantees

- Inside the band the output equals the input exactly (with `saturation` and `contrast` at 0; otherwise it equals the lifted input). Checked to ±1/255 (`checks/core-check.py`).
- The blur radius never shrinks as you move away from the band; the full-resolution blur near the band crossfades into the low-resolution blur where the two agree, so there is no seam row.
- HUD pixels are copied unchanged and carry zero weight in every blur tap.
- Everything depends only on the game clock, the canvas pixels and the parameters.

## Cost

Measured 2026-11-28 in `checks/cost.json` (headless Chromium, SwiftShader CPU renderer, `renderNow` + a 1 px `readPixels`, 60 frames, median of 3). The machine load was 15-20 throughout (other builds running), so these are **upper bounds**; a real GPU is many times faster.

| view | overlay px | post, tilt off | tilt, res auto | res 1 | res 0.5 | res 0.25 |
|---|---|---|---|---|---|---|
| demo 1280 px, dpr 2 | 1784x1004 | 3.7 ms | 32.2 ms (x0.25) | 66.7 ms | 36.8 ms | 32.2 ms |
| demo 390 px, dpr 3 (I-08 caps dpr at 2) | 780x439 | 0.9 ms | 9.9 ms (x0.5) | 15.6 ms | 9.5 ms | 9.3 ms |

Most of the cost is the full-resolution composite (one pass over the overlay, plus a 25-tap disc in the rows next to the band); the blur passes run at half or quarter resolution. On a weak device lower the post `dpr` to 1 (a quarter of the pixels) before lowering `res`.
