# light-shafts.js (J-05 module, v1.1.0)

One plain script with no dependencies and no `import`/`export`. It defines one global, `GameDNA_LightShafts`. Paste it into a `<script>` tag or load it with `<script src>`, without changing it. It needs **I-08 `webgl-post.js`** (global `GameDNA_Post`) loaded **before** it.

It adds **screen-space light shafts** ("god rays") to a game drawn on an ordinary 2D canvas. Each frame, the bright, unoccluded parts of the picture near a light position (a sun, a window, a lamp, a glowing creature) are blurred radially toward that light, so anything darker in front of them cuts a visible streak that points away from the light. Optional dust motes drift inside the beams. There is no depth buffer: **occlusion comes from brightness** (bright = light gets through, dark = solid) and from an optional **light layer** the game draws.

Four passes on the shared I-08 chain, order 500–503 (the volumetric band, before bloom and colour grading): source (1/2 or 1/4 resolution), a coarse radial gather, a fine radial gather, and a full-resolution composite. **Without WebGL, without `GameDNA_Post`, or with `?webgl=0` nothing changes** and every method is a safe no-op. **No method ever throws.**

## API

`GameDNA_LightShafts.create(options) → shafts`

| option | meaning |
|---|---|
| `canvas` | The game's canvas (element, selector or its 2D context). Used to find or create the `GameDNA_Post` instance. |
| `post` | An existing `GameDNA_Post` instance to add the passes to (preferred when the game already has one). Without it the module reuses the post made for `canvas`, or creates one with `passes: 'none'`. |
| `clock` | `() => gameMs`, the game's step-counted time. Dust motes move on it only, so `?t=&freeze=1` frames are identical every run. Never `Date.now()`. (With a shared `post`, the post's own clock is used.) |
| `light` | The light position, in canvas px or `view` units: `{x, y}` or a function returning `{x, y}` (read once per frame). **May be off-screen** (a sun above the top edge: nearly parallel shafts). Default: above the top-left corner. Also `setLight()`. |
| `view` | `{w, h}`: the units of `light`, `uiRects`, `disc()` and `layer()` when the canvas backing store is a multiple of the game's logical size (e.g. `{w: 640, h: 360}` for a 1280×720 backing store). Default: canvas px. |
| `uiRects` | `[{x, y, w, h, r?}]` or a function returning them (read every frame, re-uploaded only when they change): HUD panels. HUD pixels never emit light and are left unchanged. Without it, the shared `uiMask` slot (I-08 or another J element) is read. |
| `layer` | Optional: your own light-layer canvas (same aspect as the game canvas). Normally use `layer()` instead. |
| `params` | See the table below. |

| param | default | range | meaning |
|---|---|---|---|
| `intensity` | 0.9 | 0–3 | Strength of the shafts |
| `decay` | 0.965 | 0.8–1 | Weight kept per 1/64 of a ray (independent of the sample count): lower = shafts fade faster away from their source |
| `contrast` | 1.6 | 1–3 | Power on the gathered light: higher = crisper streaks and less overall haze |
| `haze` | 0.3 | 0–1 | Share of the light added as fog; the rest lights what is there (c + c(1 − c)·k), so dark sprites stay dark and highlights never clip |
| `veil` | 0.7 | 0–1 | How far the fog may go toward white at the brightest point; below 1 a sprite sitting on its own light (a glowing creature, a lamp) keeps its face instead of turning into a white blob |
| `wrap` | 0 | 0–1 | Light that wraps onto things standing right in front of the light, so a backlit post keeps its value next to the lit air instead of reading as a dark cut-out; 0 = streaks only (window beams with dark gaps); 0.6–0.8 for a light that hides behind posts or columns |
| `density` | 0.85 | 0.1–1 | Share of the way to the light each ray gathers: longer streaks toward 1 |
| `threshold` | 0.72 | 0–1 | Brightest-RGB-channel value above which a pixel lets light through (`source` luma / both) |
| `knee` | 0.35 | 0–1 | Soft knee, as a fraction of the threshold |
| `reach` | 0.6 | 0.05–3 | Radius of the emitting area around the light, in screen heights (an off-screen light: around the nearest screen edge point) |
| `tint` | `#ffe2b0` | colour | Shaft colour (also a skin token like `fx.hot` with `skin-api.js`) |
| `blend` | `add` | add, screen | `add` is a soft add (never a flat clip); `screen` for bright daylight scenes |
| `source` | `both` | both, luma, layer | Bright pixels, the light layer, or both (the layer counts only on frames where it was drawn) |
| `samples` | 32 | 8–64 | Ray samples per pixel in `high` quality (× 6 fine samples); `cheap` uses ≤ 16 (× 4) |
| `quality` | `auto` | auto, high, cheap | `high` = 1/2 resolution; `cheap` = 1/4 resolution for phones; `auto` = cheap on coarse-pointer devices and overlays over 3.2 MP |
| `dust` | 0.5 | 0–1 | Dust motes drifting inside lit beams (0 = none) |
| `dustSize` | 1 | 0.5–3 | Mote size multiplier |
| `dustStyle` | `auto` | auto, soft, pixel | `pixel` = square motes on the game's pixel grid; `auto` = pixel when the view is ≤ 480 px wide |
| `wind` | 0.3 | −1–1 | Horizontal drift of the motes |

| method | |
|---|---|
| `setLight({x, y})`, `setLight(x, y)`, `setLight(fn)` | Move the light (view units). A function is read once per frame. |
| `light()` | The light position used this frame `{x, y}`. |
| `layer()` | The light layer's 2D context in view units, **cleared on the first call of each frame**. Draw what IS a light (a window opening, a lamp flame, a glowing creature) in its light colour. Then cut out what stands **in front of** that light with `globalCompositeOperation = 'destination-out'`, so a hidden light makes no shafts. |
| `disc(x, y, r, color, alpha)` | A soft light disc on the layer (a lamp, a wisp, the sun). |
| `render(arg?)` | Once per drawn frame, last line of every draw path (the same as `post.render()`; either is enough). |
| `setParams(o)`, `params()` | Live parameters. |
| `setEnabled(on)` | Off = the frame without shafts (the passes are skipped). |
| `setUiRects(fn)` | Replace the HUD rects. |
| `clear()` | Clears the light layer now. |
| `stats()` | `{active, mode, reason, shared, quality, scale, samples, frames, layerFrames, layerOn, light: {x, y, onScreen}, lightOnFrames, lightOffFrames, uiRects, errors, broken, passes, w, h, avgMs}` |
| `destroy()` | Remove the passes and inputs (and the post, if the module made it). |
| `active`, `reason`, `post`, `shared` | `active` false = 2D only (`reason`: 'no-post', 'no-canvas', 'url', 'no-webgl', ...). |

## Integration (15 lines)

```js
// <script src="webgl-post.js"></script><script src="light-shafts.js"></script> before the game script
const post = GameDNA_Post.create({ canvas: gameCanvas, clock: () => frame * STEP_MS, params: { passes: 'none' } });
const shafts = GameDNA_LightShafts.create({ post, clock: () => frame * STEP_MS,
  light: () => ({ x: sun.x - camX, y: sun.y - camY }),        // same screen units as your draw; off-screen is fine
  uiRects: () => [hudPanelRect],                               // whole HUD plates drawn now
  params: { intensity: 0.9, threshold: 0.75, reach: 0.6, tint: '#ffe2b0', dust: 0.5 } });
function draw() {
  /* ...your existing drawing, unchanged... */
  const L = shafts.layer();                                    // optional: real light sources
  shafts.disc(lamp.x - camX, lamp.y - camY, 14, '#ffd890');    // a lamp or a glowing creature
  L.globalCompositeOperation = 'destination-out';              // things IN FRONT of that light hide it
  L.fillRect(pillar.x - camX, pillar.y - camY, pillar.w, pillar.h);
  L.globalCompositeOperation = 'source-over';
  shafts.render();                                             // last line of every draw path
}
```

## Choosing the source

- **Bright sky or windows in a darker scene** (dusk, forest, interiors seen against a bright outside): `source: 'luma'` (or `both`), `threshold` just above the brightest **solid** thing near the light (the brightest-channel value of a lit wall or path), `reach` 0.4–0.8.
- **Daylight with a bright ground** (grass, sand, snow, top-down maps): put the light off-screen in a top corner, `threshold` 0.8–0.9, `intensity` 0.5–0.8, `blend: 'screen'`; trees, roofs and walls cut the streaks. Or use `source: 'layer'` and draw only the sky openings.
- **A light that is a thing in the world** (a lamp, a torch, a wisp, a window, the sun disc you draw yourself): `source: 'layer'` (or `both`); draw it with `disc()` or fill its shape on `layer()`, then cut out the occluders drawn in front of it.
- **Night scene with no bright pixels**: luma finds nothing; draw the lights into the layer.

## Keep the rest of the game working

- Change nothing in how the game draws: canvas size, CSS, transform, smoothing stay as they are. Never read the overlay for game logic and never make game logic depend on `shafts.active`: `?auto=1` must end the same with WebGL on and off.
- One `GameDNA_Post` per canvas: reuse an existing one (pass it as `post`).
- Every path that draws a frame (title, play, pause, result, the single draw after the `?t=` fast-forward) ends with `shafts.render()` (or `post.render()`).
- Light layer drawing goes in the draw path, not in the update step; draw it in every draw path where the light should shine.
- `light`, `uiRects`, `disc()` and `layer()` use the same screen units as the game's draw: subtract the camera; pass `view` if the backing store is scaled.

## Self-check without a browser

- Both scripts byte-identical, `webgl-post.js` first; `create` runs once after the canvas exists; `clock` is step-counted.
- Walk one pixel: light at (100, 50), pixel at (300, 150), density 0.85, 32 samples: the ray gathers from the pixel toward the light over 85 % of the way, one sample every 5.9 px, weights 1, 0.965², 0.965⁴, … (decay per 1/64 of the ray); a dark sprite 40 px from the pixel along that line removes those samples, so the pixel is darker than its neighbours: a streak pointing away from the light.
- An occluded light: when the light sits inside a dark shape (or is cut out of the layer) wider than about 3 × `reach` × screen height, nothing within reach emits, so no shaft appears.
- `uiRects` covers the HUD plates only (never the whole screen); with `?webgl=0` the game looks and plays exactly as before.

## What it guarantees

- Shafts always point away from the light: each pixel gathers only along the line toward the light; samples off-screen add nothing.
- A light hidden behind something darker than `threshold` (or cut out of the layer) emits nothing, so it makes no streak.
- HUD pixels (uiRects / shared uiMask) neither emit nor change.
- Dust motes depend only on the game clock, the shafts and the parameters (never wall-clock time or `Math.random`), and appear only inside lit beams.
- Without WebGL: no overlay, the canvas untouched, every method callable.

## Cost

Measured numbers are in `../checks/cost.json` (headless Chromium, SwiftShader CPU renderer: a real GPU is many times faster). `cheap` quality runs every ray pass at 1/4 resolution with 16 × 4 samples.
