# Passes

> `@typegpu/kit` 0.1.0. If it is installed, read `node_modules/@typegpu/kit/docs/` instead.

Describe a frame's render targets once, so every renderer writes colour, depth and whatever else a later pass reads.

> `import { passes } from '@typegpu/kit'`: `passes.create(root, screen, { shared?, … }?) → Description`, `passes.create(root, screen, writes, { shared?, … }?) → Description`, `passes.output(schema, spec) → Output`, `passes.drawing(spec) → Drawing`. Describes the targets and outputs for passes that draw a scene. **records** `pipe().record` encoder, `pipe().composite` encoder, `beneath().record` encoder, `beneath().composite` encoder, `record` encoder, `composite` encoder, `add().draw` render, `draw` render: `begin` from the frame, with the `shared` group set, then each drawing's `draw` from `add` into the pass; into targets with layers, `record` does so once per layer. `composite` records a pass of its own. **owns** the pipelines `add` builds, until the drawing or description is destroyed, a pipeline per description that composites, bind groups, a buffer per layer, a buffer per viewport its pipelines read, bindings when given parts as `shared`: WebGPU pipelines and bind groups need no destruction. Compound drawings free the resources they built for the description. `composite` lays translucent drawings over the colour with that pipeline and a bind group per pair of textures. A description drawn into layers holds each layer's index in a uniform with a bind group. **lifecycle** `initAsync()`, `destroy()`, `[Symbol.dispose]`. **injects** member: what was piped into it, such as the camera, for a drawing's kernels per description. **needs** `bindings`: as `options.shared`; fills accessors in its pipelines. **accessors** `layer`, `viewport`, `sampleCount`, `depthOnly`. **outputs** `shaded`, `accumulation`, `revealage`. **schemas** `ScreenVertex`, `Region`. **constants** `color`, `depth`. **helpers** `fullScreen`. **types** `Output`, `Write`, `Writes`, `Fits`, `Shaders`, `Compound`, `Drawable`, `AnyDrawing`, `Drawn`, `Built`, `Into`, `Screen`. `src/passes.ts`; afterimage, benthos, blockfall, censer, classroom, cloister, dominoes, ember-mirror, falling-sand, fireworks, fishtank, forest, hex-isle, jellies, jelly-world, kinetic, lattice, night-market, platformer, quiver-trees, robot-arm, skeletons, solar-system, spider, stampede, star-map, survey-model.
>
> `Options`, taken by `create`:
> - `jitter?: Position` A `'use gpu'` function. Moves clip positions for rasterisation. Default none.
> - `clear?: readonly number[] | GPUColorDict` Sets the `color` target value where nothing drew. Default transparent black.
> - `bias?: { readonly constant?: number; readonly slope?: number }` Adds a depth bias to every pipeline, in depth-format steps and per unit of slope, as `depthBias` and `depthBiasSlopeScale`. Default none.
> - `depthClear?: number` Sets the depth clear value. Default 1.
> - `depthCompare?: GPUCompareFunction` Sets the depth comparison. Default `'less'`.
> - `stencilClear?: number` Sets the stencil clear value for formats with stencil. Default 0.
> - `enabled?: () => boolean` Reports whether the description should draw in the current frame, exposed as `enabled`. Default always.
> - `active?: (layer: number) => boolean` Reports whether a layer draws in the current frame, exposed as `active`. Default every layer.
> - `label?: string` Labels passes in the GPU debug panel and captures. Default none.
> - `shared?: Shared | Readonly<Record<string, AnyPart>>` Shares these parts, by key, in one layout the description owns: every pass `begin` and `record` start sets its group, and every pipeline the description builds reads the parts through it. Default none.
>
> `TargetOptions`, taken by `create`:
> - `resolve?: { readonly [K in keyof T]?: Exclude<keyof T, K> | Surface }` Maps multisampled targets to their resolve destinations at the end of a pass. Default none.
> - `jitter?: Position` A `'use gpu'` function. Moves clip positions for rasterisation. Default none.
> - `clear?: readonly number[] | GPUColorDict` Sets the `color` target value where nothing drew. Default transparent black.
> - `bias?: { readonly constant?: number; readonly slope?: number }` Adds a depth bias to every pipeline, in depth-format steps and per unit of slope, as `depthBias` and `depthBiasSlopeScale`. Default none.
> - `depthClear?: number` Sets the depth clear value. Default 1.
> - `depthCompare?: GPUCompareFunction` Sets the depth comparison. Default `'less'`.
> - `stencilClear?: number` Sets the stencil clear value for formats with stencil. Default 0.
> - `enabled?: () => boolean` Reports whether the description should draw in the current frame, exposed as `enabled`. Default always.
> - `active?: (layer: number) => boolean` Reports whether a layer draws in the current frame, exposed as `active`. Default every layer.
> - `label?: string` Labels passes in the GPU debug panel and captures. Default none.
> - `shared?: Shared | Readonly<Record<string, AnyPart>>` Shares these parts, by key, in one layout the description owns: every pass `begin` and `record` start sets its group, and every pipeline the description builds reads the parts through it. Default none.
>
> `BeginOptions`, taken by `Description.begin`, `Description.record`:
> - `clear?: boolean | readonly (keyof W & string)[]` Selects targets to clear. Default `true`.
> - `layer?: number` Draws into this layer of a description drawn into layers. Default none.
> - `timestampWrites?: TimestampWrites | undefined` Supplies a timer's writes for the passes. Default none.
>
> `ScreenVertex`, a schema:
> - `position: d.vec4f`
> - `uv: d.vec2f`
>
> `Region`, a schema:
> - `size: d.vec2f` Holds the width and height of the drawn region in pixels.
> - `pixelRatio: d.f32` Holds pixels per point: the surface's `pixelRatio`, scaled with a target's resolution, so a one-point line keeps its size in a low-resolution target.
>
> `Description`, from `create`:
> - `pipe(fill)` Adds `fill` after existing fills and returns a description of the same passes.
> - `beneath(fill)` Adds `fill` after the fills given to earlier `beneath` calls and returns a description of the same passes.
> - `initAsync()` Compiles every pipeline built for this description and the resources required by each added drawing, including drawings added while it compiles.
> - `destroy()` Destroys drawings added to this description or descriptions derived with `pipe`, `without` and `instead`.
> - `begin(frame, options?)` Begins a render pass on the targets using the frame encoder.
> - `record(frame, drawn, options?)` Begins a pass, draws `drawn` or each drawing in a list in order, then ends the pass.
> - `composite(frame, options?)` Lays what translucent drawings added to the targets marked `passes.accumulation` and `passes.revealage` over the colour target, or over its resolve destination, in a pass of its own.
> - `writes: W` Describes what renderers write into each target.
> - `depthFormat: GPUTextureFormat | undefined` Reports the depth target format, or undefined without a depth target.
> - `depthOnly: boolean` Reports whether the description writes only depth, as a shadow map does.
> - `depthCompare: GPUCompareFunction` Reports the depth comparison drawings use unless their `depthStencil` overrides it.
> - `samples: number` Reports the number of samples per pixel for every target.
> - `enabled: boolean` Reports whether this description draws in the current frame, from `enabled`.
> - `active(layer)` Reports whether layer `layer` draws in the current frame, from `active`.
> - `layers: number` Reports how many layers `record` draws, one pass each: the `layers` of the targets it draws into, or 1.
> - `inject()` Fills shader accessors for kernels built by a drawing for this description: the fills given to `beneath`, then the piped fills such as the camera.
> - `add(drawing)` Builds a pipeline for `drawing` that writes every described output and returns its draw methods.
> - `pipeline(drawing, from?)` Builds a pipeline from `drawing` using `from` and the description's piped fills.
> - `without(...keys)` Returns a description with `keys` left out for a renderer that cannot write them.
> - `instead(outputs)` Returns a description with the given outputs replaced by target key.
>
> `Drawing`, from `drawing`:
> - `inject()` Fills shader accessors over the fills given to the description's `beneath` and under those piped into it, which take precedence.
> - `indices?: TgpuBuffer<d.BaseData> & IndexFlag` Supplies an index buffer bound to each pipeline built for this drawing.
> - `draw(pass)` Records a draw into the pass, on which the description has set the pipeline it built.
> - `initAsync()` Compiles resources besides the render pipeline, such as kernels.
> - `label?: string` Labels the pipelines in GPU captures.
> - `Vertex(props?)` Defines a vertex with its `position` in clip space and data carried to pixels.
> - `at(vertexIndex, instanceIndex)` Computes the vertex for a vertex and instance index, as a `'use gpu'` function.
> - `pixelOf(vertex)` Computes data at a pixel from the interpolated vertex.
> - `color?: Output<P, d.Infer<V>>` Supplies the output for the target marked `passes.color`.
> - `blend?: GPUBlendState` Sets blending for the `color` target.
> - `translucent?: boolean` Draws the `color` output, premultiplied by its alpha, as a translucent layer.
> - `writeMask?: GPUColorWriteFlags` Selects the channels written to the `color` target.
> - `depthStencil?: Omit<GPUDepthStencilState, 'format'>` Controls depth testing and writing when the description has a depth target.
> - `depthOf(pixel)` Computes pixel depth from the pixel's data instead of using rasterised depth, such as the depth of a point shown by an impostor.
> - `cutout(vertex)` Returns true where the pixel is cut out of the shape, such as where a sprite's texture is clear.
> - `invariant?: boolean` Computes the same vertex `position` in every pipeline built from this vertex.
> - `flat?: readonly (Exclude<keyof d.Infer<V>, 'position'> & string)[]` Carries these vertex fields to pixels without interpolation.
> - `linear?: readonly (Exclude<keyof d.Infer<V>, 'position'> & string)[]` Interpolates these vertex fields linearly in screen space, without perspective correction, such as a distance measured across a shape extruded on screen.
> - `primitive?: GPUPrimitiveState` Sets the primitive state, such as the topology and culling.
> - `alphaToCoverage?: boolean` Uses the alpha of the `color` output to select the covered samples in a multisampled target.
> - `sampleMask(vertex, pixel)` Returns the samples a pixel writes in a multisampled target, bit `i` for sample `i`, such as the share of a pixel one drawing hands to another.

TAA needs motion vectors and a pick of your own needs ids at each pixel. Every renderer must write these alongside colour. Implementing each output separately in every renderer duplicates shader code. Renderers that lack an output's data, such as particles without ids, also need a rule for what that target gets.

`passes.create` defines what each target holds. A renderer supplies a **drawing**, which holds a vertex function, a draw call and a `pixelOf` function. `pixelOf` gives the renderer's data at each pixel, such as colour or id. `scene.add(drawing)` builds a pipeline that computes every output from that data. `scene.record(frame, drawn)` draws it into the targets.

```ts
import { d } from 'typegpu';
import { passes } from '@typegpu/kit';

const screen = targets.create(root, surface, {
  hdr: { format: 'rgba16float', sampled: true },
  motion: { format: 'rg16float', sampled: true },
  depth: { format: 'depth24plus', sampled: true },
});
const scene = passes
  .create(root, screen, { hdr: passes.color, motion, depth: passes.depth })
  .pipe(view.inject());

// What each vertex carries to its pixels, and what the renderer knows at a pixel
const Corner = d.struct({ position: d.vec4f, world: d.vec3f });
const Seen = d.struct({ color: d.vec4f });

const at = (vertexIndex: number, instanceIndex: number) => {
  'use gpu';
  const corners = [d.vec3f(-1, 0, 0), d.vec3f(1, 0, 0), d.vec3f(0, 2, 0)];
  const world = corners[vertexIndex] + d.vec3f(d.f32(instanceIndex) * 3, 0, 0);
  return Corner({ position: cameras.toClip(world), world });
};
const pixelOf = (corner: d.Infer<typeof Corner>) => {
  'use gpu';
  return Seen({ color: d.vec4f(corner.world * 0.25 + 0.5, 1) });
};

// Four triangles, drawn into every target the scene describes
const triangles = scene.add({
  Vertex: Corner,
  at,
  pixelOf,
  color: passes.shaded,
  draw: (pass) => pass.draw(3, 4),
});
await scene.initAsync();

frames.animate(frames.create(root, (frame) => scene.record(frame, triangles)));
```

`passes.create(root, surface)` draws each renderer's colour into the canvas without extra targets or outputs.

## Drawing into your own texture

`passes.create` takes a target set or a surface. A surface is `{ format, view(frame), width, height }`, with an optional `pixelRatio`. The surface form is for textures created outside the kit, such as a canvas. A texture you create to draw into and sample elsewhere, such as a label, a decal or a mirror, is a target set. `targets.create` takes any `{ width, height }` and sizes a fixed set once, when it is created:

```ts
import { passes, targets } from '@typegpu/kit';

const size = { width: 512, height: 256, pixelRatio: 1 };
const page = targets.create(root, size, { ink: { format: 'rgba8unorm', sampled: true } });
const tags = text.create(root, font, { capacity: 1, length: 3, place: text.screen });
const paint = passes.create(root, page, { ink: passes.color });
const drawn = paint.add(tags.drawing);
tags.labels.patch({ 0: { position: [330, 128, 0.5], color: [1, 1, 1, 1] } });

// When the value changes, draw it into the page before the passes that sample it
tags.write(0, '42', { em: 180, align: 'right' });
paint.record(frame, drawn);

// Sample it from another shader, such as a floor's
const ink = page.textures.ink.createView();
```

The [jelly slider](../examples/jelly-world.md) draws its value this way and samples it from the floor under the jelly.

## Drawings

A drawing of one pipeline is a plain object, a `passes.Drawing<Vertex, Pixel>`. It needs a `Vertex`, an `at` that makes one and a `draw`. A drawing that writes colour or outputs also needs `pixelOf`, and `color` when the description has a `passes.color` target. The other fields are optional. The kit's drawings have a `label`, and `scene.add({ ...sparks.drawing, label: 'sparks' })` renames one. A blended drawing that tests the depth without writing it sets `depthWriteEnabled: false` in its `depthStencil`.

`passes.fullScreen` is the `Vertex` and `at` of one triangle that covers the screen at depth 0, drawn with `draw(3)`. `passes.drawing({ … })` returns the drawing you pass unchanged and infers its vertex and pixel types. `at`, `pixelOf` and `draw` then need no annotations. A function that takes any drawing types it as `passes.AnyDrawing`.

- **Pipelines** Each description a drawing is added to builds a pipeline of its own, for its targets, jitter, samples and fills. A renderer gives its drawing, `scene.add(particles.drawing)`, and holds no pipeline.
- **Sample count** Every target in a description has the same sample count. `passes.create` reads it once to build pipelines. To change MSAA, create another target set and description, then add each drawing again. Destroy the old description to free its compound drawings' per-view work.
- **Missing fields** A drawing whose pixel or vertex lacks a field an output reads fails to type-check at `add`. The error names the target and the fields its output reads. [`without`](#what-each-target-gets) leaves the output out.
- **What add returns** `add` returns a `passes.Drawn`. `drawn.draw(pass)` records into a pass from `begin`. `drawn.destroy()` removes it from the description's compilation list and frees its per-view resources.

### Indirect draws

`draw` receives TypeGPU's render commands, so it can issue an indirect draw. `pass.drawIndirect(buffer, offset)` reads its counts from a buffer with `indirect` usage, at `offset` bytes. With `storage` usage too, a kernel decides how much to draw and the CPU never reads the count:

```ts
const Draw = d.struct({
  vertexCount: d.atomic(d.u32),
  instanceCount: d.u32,
  firstVertex: d.u32,
  firstInstance: d.u32,
});
const args = root
  .createBuffer(Draw, { vertexCount: 0, instanceCount: 1, firstVertex: 0, firstInstance: 0 })
  .$usage('storage', 'indirect');
const counts = args.as('mutable');

// Called from a kernel: claims a quad's six vertices and returns the first
const claim = () => {
  'use gpu';
  return std.atomicAdd(counts.$.vertexCount, 6);
};

const drawn = scene.add({ ...quads, draw: (pass) => pass.drawIndirect(args) });
```

- Zero the count before the kernel runs each frame, such as with `args.patch({ vertexCount: 0 })`.
- Each record takes 16 bytes. To draw record `k` from a buffer of records, pass `16 * k` to `drawIndirect` as its byte offset. `at` receives vertex indices from `firstVertex` on, so records can split one list of vertices.
- `pass.drawIndexedIndirect(buffer, offset)` reads 20-byte records of `indexCount`, `instanceCount`, `firstIndex`, `baseVertex` and `firstInstance`, and needs the drawing's `indices`.
- A record whose `firstInstance` is not 0 requires the [`indirect-first-instance`](../platforms.md#device-features) feature.
- [Live lists](live-lists.md) write these records for the live rows of a table.

### Depth alone

A description whose only target is `passes.depth` draws depth alone, as a shadow map or a depth prepass does. Its drawings need no `pixelOf` or `color`, and one without `depthOf`, `cutout` or `sampleMask` builds a pipeline with no fragment stage. A description with any other target requires `pixelOf`, even from a drawing with `writeMask: 0`. A full-screen sea can sample the scene depth in its colour pass. That pass cannot also write to the depth it samples. To write the sea's depth to the same texture, add its shape to a separate description of depth alone:

```ts
const Corner = d.struct({ position: d.vec4f });
const level = passes.create(root, screen, { depth: passes.depth }).pipe(view.inject());

// The sea's plane at y = 0, with no pixel function
const plane = level.add({
  Vertex: Corner,
  at: (vertexIndex: number) => {
    'use gpu';
    const corners = [d.vec2f(-1, -1), d.vec2f(1, -1), d.vec2f(-1, 1), d.vec2f(1, 1)];
    const xz = corners[vertexIndex] * 500;
    return Corner({ position: cameras.toClip(d.vec3f(xz.x, 0, xz.y)) });
  },
  primitive: { topology: 'triangle-strip' },
  draw: (pass) => pass.draw(4),
});

frames.create(root, (frame) => {
  scene.record(frame, sea);
  level.record(frame, plane, { clear: false }); // keeps the depth the scene drew
});
```

- A translucent drawing throws there.
- A later pass that tests this depth with `depthCompare: 'equal'` needs `invariant: true` on both drawings.

### What `color` takes

`color` requires an output. Passing a function such as `color: (s) => s.color` fails to type-check at `add`. `passes.shaded` writes the pixel's `color` field as it is. Any other colour is an [output](#outputs) of your own whose `write` reads the pixel's data:

```ts
// The pixel's colour, premultiplied for `pipelines.blend.over`
const premultiplied = passes.output(d.vec4f, {
  write: (pixel: { readonly color: d.v4f }) => {
    'use gpu';
    return d.vec4f(pixel.color.xyz * pixel.color.w, pixel.color.w);
  },
});

const veil = scene.add({ ...drawing, color: premultiplied, blend: pipelines.blend.over });
```

### Compound drawings

A renderer with several pipelines or per-view resources supplies a `passes.Compound` object with `build(into)`. Per-view resources can include a list of objects visible to a camera. Each description calls `build` once, so the shadow and scene get separate pipelines. `build` receives a `passes.Into`: the description's targets and outputs, its fills, and `pipeline`, `add`, `without` and `instead`. It creates the pipelines with `into.pipeline(drawing)` and returns a `passes.Built` with `draw`, `initAsync` and an optional `destroy` for per-view cleanup. The description's `destroy` calls every drawing's `destroy`, even after one of them throws. [Instances](instances.md) renderers use this form.

These drawings share a vertex function. Their two pipelines draw a fill, then an outline:

```ts
const outlined: passes.Compound<Seen, d.Infer<typeof Corner>> = {
  build(into) {
    const filling = into.pipeline(fill);
    const rimming = into.pipeline(rim);
    return {
      draw(pass) {
        pass.setPipeline(filling);
        pass.draw(4, count);
        pass.setPipeline(rimming);
        pass.draw(4, count);
      },
      async initAsync() {
        await Promise.all([filling.initAsync(), rimming.initAsync()]);
      },
    };
  },
};

const drawn = scene.add(outlined);
```

`into.pipeline(drawing, from)` builds from a configuration of your own, such as `root.pipe(into.inject()).with(slot, value)`, to fill a slot differently in each pipeline.

In a description with [layers](#layers), `into.layers` is how many there are, for per-layer work such as a visible list for each. The built `draw(pass, layer)` receives the layer of the pass it draws into, to pick that layer's work.

## Outputs

`passes.output(schema, spec)` defines the value each renderer writes per pixel to one target:

- **Writing** `write(pixel, carried)` runs per pixel and returns a value of `schema`. Its first parameter types the data it reads. `(pixel: { id: number })` requires an `id`, so only drawings whose `pixelOf` returns that field can write it.
- **Varying** `vary(vertex, before)` runs per vertex and returns a `varyings` struct. The rasteriser interpolates it for `write`'s `carried` parameter. With `previous: true`, `before` holds last frame's vertex. The renderer's vertex code compiles again with [`history.previously`](history.md) to read last frame's camera and other `temporal` fills.
- **Clearing** `clear` is what the target holds where nothing drew, zero by default. The `color` target clears to the description's `clear` option instead.
- **Integers** Integers go between the stages flat.

```ts
// Where what each pixel shows was last frame, in UV
const Clips = d.struct({ now: d.vec4f, before: d.vec4f });
const motion = passes.output(d.vec2f, {
  varyings: Clips,
  previous: true,
  vary: (now: { position: d.v4f }, before: { position: d.v4f }) => {
    'use gpu';
    return Clips({ now: now.position, before: before.position });
  },
  write: (_pixel: unknown, clips) => {
    'use gpu';
    return uvOf(clips.before) - uvOf(clips.now);
  },
});

const id = passes.output(d.u32, {
  clear: 0xffffffff, // nothing here
  write: (pixel: { id: number }) => {
    'use gpu';
    return pixel.id;
  },
});
```

`passes.color` marks the target for each renderer's colour. `passes.depth` marks the depth target. A description allows at most one of each and leaves unlisted targets untouched. A key the set lacks fails to type-check at the key. An output comes only from `passes.output` and has no members to read.

## What each target gets

`scene.without('id')` omits the `id` output and its varyings for drawings that can't supply it. `scene.instead({ motion: skyMotion })` writes an output of the drawing's own into that target. Both draw into the pass `scene.begin` starts:

```ts
const embers = scene.without('id').add(sparks.drawing);
const sky = scene.without('id').instead({ motion: skyMotion }).add(skyDrawing);
```

| Target                                         | What the drawing writes there                                                                                                                                                                             |
| ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `passes.color`                                 | Its own `color`, through its `blend` and `writeMask`.                                                                                                                                                     |
| `passes.depth`                                 | Its depth, or `depthOf`'s, as its `depthStencil` state says: tested and written by default.                                                                                                               |
| An output                                      | The output's `write`, from its pixel data and the output's varyings. Outputs such as motion and ids don't blend. A blended drawing replaces the value wherever it draws, even at its transparent corners. |
| An output `instead` replaces                   | The replacement's `write`.                                                                                                                                                                                |
| An output `without` leaves out, opaque         | The output's `clear`, as if nothing drew there.                                                                                                                                                           |
| An output `without` leaves out, with a `blend` | Nothing, so what is under it stays.                                                                                                                                                                       |

The kit's drawings:

| Drawing                                  | Vertex             | Pixel            | Blend                        | Depth                                 |
| ---------------------------------------- | ------------------ | ---------------- | ---------------------------- | ------------------------------------- |
| An [instances](instances.md) renderer | `instances.Corner` | `instances.Lit`  | none, or as its `blend` says | written; tested only when translucent |
| [`particles.drawing`](particles.md)   | `particles.Corner` | `particles.Seen` | add, or as its `blend` says  | tested only                           |
| A [lines](lines.md) set's `drawing`   | `lines.Corner`     | `lines.Seen`     | over, or as its `blend` says | tested only; written with `opaque`    |
| [`trails.drawing`](trails.md)         | `lines.Corner`     | `lines.Seen`     | add, or as its `blend` says  | tested only                           |
| A [text](text.md) set's `drawing`     | `text.Corner`      | `text.Seen`      | over, or as its `blend` says | tested only                           |

Draw what tests the depth without writing it after the opaque drawings. [Impostors](impostors.md) draw through an instances renderer.

## Translucent drawings

Blending translucent drawings over each other looks right only when they draw from far to near. That needs sorting every frame, and still fails where two surfaces cross. A drawing with `translucent: true` needs no order. Give the description two more targets, one marked `passes.accumulation` and one marked `passes.revealage`. Each translucent pixel adds its colour into the first, weighted by its alpha and by distance so that nearer layers count most. It also multiplies the second by the share of what lies behind it that still shows. `scene.composite(frame)` then lays the average over the colour target in a pass of its own:

```ts
import { passes, targets } from '@typegpu/kit';

const screen = targets.create(root, surface, {
  hdr: { format: 'rgba16float', sampled: true },
  accum: { format: 'rgba16float', sampled: true },
  reveal: { format: 'r16float', sampled: true },
  depth: { format: 'depth24plus' },
});
const scene = passes
  .create(root, screen, {
    hdr: passes.color,
    accum: passes.accumulation,
    reveal: passes.revealage,
    depth: passes.depth,
  })
  .pipe(view.inject());

// The opaque ground first, then the translucent bells
const drawn = [scene.add(ground), scene.add({ ...bells, translucent: true })];

frames.create(root, (frame) => {
  scene.record(frame, drawn);
  scene.composite(frame);
});
```

- **Colour** A translucent drawing's `color` output is premultiplied, `d.vec4f(rgb * alpha, alpha)`. Colour with an alpha of 0 adds light, as a glow does.
- **Depth** It tests the depth that opaque drawings wrote before it and writes none. Draw it after them, in any order among the translucent ones.
- **Opaque drawings** Opaque drawings leave the two targets alone. Outputs such as motion take a translucent drawing's value as they take a [blended one's](#what-each-target-gets).
- **Without the targets** In a description without the two targets, the same drawing blends over the colour target in draw order. The jellies keep a second description to turn the targets off.
- **Compositing** `composite` reads both targets as textures, so each needs `sampled: true`.
- **Instances** An [instances](instances.md#transparency) renderer with `blend: 'translucent'` or `'clear'` draws translucent.

## Fills

`pipe(fill)` adds a fill to every pipeline built from the returned description. It applies after the drawing's fill and takes precedence. `passes.create(…).pipe(view.inject())` uses `view` as its camera. A [shadow map](lighting.md#shadows) uses a description of depth alone, viewed from the sun.

`beneath(fill)` adds a fill that applies before the drawing's fill, as a default the drawing can override. `scene.beneath(light.inject())` lights every drawing that doesn't fill the lighting's hooks itself. Fills given to `beneath` and to `pipe` each apply in call order.

A compound drawing that builds pipelines from its own configuration, such as an [instances renderer](instances.md#renderers), starts from `inject()` and applies its own fills over it. `beneath` then lights it too.

## Pixels and points

A line two points wide or a label pinned beside a star needs the size of what the pass draws into. That size differs between the canvas, a low-resolution target and a shadow map. Every description fills `passes.viewport` in each pipeline and kernel it builds. It holds the drawn region's `size` in pixels and its `pixelRatio`, the pixels a point takes:

```ts
import { cameras, passes } from '@typegpu/kit';

/** Where a world point lands on the target, moved `offset` points right and up. */
const besideInPoints = (world: d.v3f, offset: d.v2f) => {
  'use gpu';
  const view = passes.viewport.$;
  const clip = cameras.toClip(world);
  return d.vec4f(clip.xy + ((offset * 2 * view.pixelRatio) / view.size) * clip.w, clip.zw);
};
```

- **Size and ratio** Over a surface, `size` is the surface's and `pixelRatio` its `pixelRatio`. Over targets, `size` is the drawn region, and `pixelRatio` is the source's, scaled by the region. A point then keeps its size at a lower `resolution` or through `targets.scaled`. A source without a ratio, such as a shadow map's fixed size, has a `pixelRatio` of 1.
- **Updates** `begin` and `record` write it when the region has changed. A pipeline from `pipeline()` that draws into a pass you began yourself reads the region of the last `begin`. So does a kernel built from `inject()` in a frame where the description begins no pass.
- **Bindings** Each description holds its own uniform, even beside another over the same targets. A pipeline that reads it binds 1 uniform.
- **Slots** Descriptions also fill two slots: `passes.sampleCount` with the samples per pixel, and `passes.depthOnly` with whether they draw into depth alone. A drawing reads them to cut its own edges where there is one sample, or to leave out what only shows in colour, such as an antialiased edge in a shadow map.

## Buffers and textures of your own

A drawing's shaders read buffers, textures and samplers through accessors, which its `inject()` fills. The description builds each pipeline from that fill, so a draw binds no group of yours:

```ts
const tints = tgpu.accessor(d.arrayOf(d.vec4f, 4));
const picture = tgpu.accessor(d.texture2d(d.f32));
const smooth = tgpu.accessor(d.sampler());

const tintBuffer = root.createReadonly(d.arrayOf(d.vec4f, 4));
const image = root.createTexture({ size: [512, 512], format: 'rgba8unorm' }).$usage('sampled');
const view = image.createView(d.texture2d(d.f32));
const sampler = root.createSampler({ magFilter: 'linear', minFilter: 'linear' });

const backdrop = scene.add({
  ...passes.fullScreen,
  pixelOf: (corner: d.Infer<typeof passes.fullScreen.Vertex>) => {
    'use gpu';
    const band = std.min(d.u32(corner.uv.y * 4), 3);
    return Seen({ color: std.textureSample(picture.$, smooth.$, corner.uv) * tints.$[band] });
  },
  color: passes.shaded,
  inject: () => (cfg) =>
    cfg
      .with(tints, tintBuffer)
      .with(picture, () => view.$)
      .with(smooth, () => sampler.$),
  draw: (pass) => pass.draw(3),
});
```

- Shaders can read `tintBuffer.$` and `view.$` without accessors. The resources become fixed bindings in each pipeline's automatic group.
- A kernel of your own reads them the same way, created from `root.pipe(fill)`, with `scene.inject()` piped in too when it reads the camera.
- WebGPU forbids read-write storage in a vertex stage. Fill an accessor that a kernel writes and a vertex stage reads with `byStage(buffer)`, read-write in compute and read-only elsewhere.
- `cfg.with` takes a slot or accessor and its value. Passing a bind group as `cfg.with(group)` fails with TS2554.

A resource you swap without new pipelines, such as a texture that follows the canvas, goes in a [`bindings.layout`](bindings.md) part. Give the description its parts by key as `shared`. It shares them in one layout, and every pass it begins sets that layout's group:

```ts
import { bindings } from '@typegpu/kit';

const backdropBindings = bindings.layout({
  picture: { texture: d.texture2d(d.f32) },
  smooth: { sampler: 'filtering' },
});
const part = backdropBindings.bind({ picture: image, smooth: sampler });
const scene = passes.create(root, screen, { hdr: passes.color }, { shared: { backdrop: part } });

const backdrop = scene.add({
  ...passes.fullScreen,
  pixelOf: (corner: d.Infer<typeof passes.fullScreen.Vertex>) => {
    'use gpu';
    const color = std.textureSample(
      backdropBindings.$.picture,
      backdropBindings.$.smooth,
      corner.uv,
    );
    return Seen({ color });
  },
  color: passes.shaded,
  draw: (pass) => pass.draw(3),
});

frames.create(root, (frame) => scene.record(frame, backdrop));

part.replace({ picture: bigger }); // between frames, keeping the pipeline
```

- `shared` also fills every shared part in the pipelines the description builds, so a drawing or a callback needs no `inject` for them.
- Create the description before any other pipeline that reads its parts builds. A pipeline built before then holds the part as fixed bindings, and `passes.create` throws.
- A pipeline the description builds that reads a shared part it wasn't given throws as it builds, and names the `shared` to add.
- When two descriptions or a pass of your own read the same parts, call [`bindings.share`](bindings.md#sharing) once and give its result to each description as `shared`. A pass you open yourself sets the group with `pass.setBindGroup(shared.layout, shared.group())`.

## Every frame

`record(frame, drawn)` draws one handle or a list in order in a pass of its own. Create the list at setup. Use `begin(frame)` to choose drawings per frame or set a bind group of your own before drawing.

```ts
const timing = profiler.create(root);
const sceneTime = timing.timer('scene');
const opaque = [ground, herd];

frames.create(root, (frame) => {
  scene.record(frame, opaque, { timestampWrites: sceneTime.writes() });
  glows.record(frame, sparks, { clear: false }); // over what the scene drew
  timing.capture(frame);
});
```

- **Clearing** Output targets clear to their output's `clear`. The colour target uses the description's `clear`, which the pass reads at each begin. Depth uses `depthClear`, which defaults to 1. Stencil uses `stencilClear`.
- **Keeping contents** `clear: false` keeps what every target holds, so a later pass, such as the glows after the scene, draws over the colour and depth already there. `clear: ['hdr']` clears the targets it names and keeps the rest, such as the depth an earlier pass drew.
- **Transient targets** A [transient](targets.md#transient-targets) target can't retain its contents between passes. `begin` throws if asked to keep it. Set `transient: false` in its spec to retain contents. Multisampled targets are transient by default.
- **Storing** Each pass stores what it drew with `'store'`. A transient target uses `'discard'` instead, so only what it resolves to another target survives the pass.
- **Timing** `timestampWrites` times the pass with a [profiler](profiler.md).
- **Jitter** The `jitter` option moves each vertex where the rasteriser sees it and nowhere else. Outputs read where the vertex is, so motion holds no jitter. [Temporal antialiasing](taa.md) sets it.
- **Disabled descriptions** `record` and `composite` skip a disabled description; `begin` does not.

## Reversed depth

Standard depth puts the near plane at 0 and the far plane at 1. With perspective and a float depth target, that leaves less precision for distant surfaces, which can z-fight. Reversed depth puts the near plane at 1 and the far plane at 0. Set it up in two places: the description clears depth to 0 and keeps the greater depth, and the camera projects reversed depth.

```ts
import { cameras, passes, targets } from '@typegpu/kit';

const screen = targets.create(root, surface, {
  hdr: { format: 'rgba16float', sampled: true },
  depth: { format: 'depth32float', sampled: true },
});
const view = cameras.orbit(root, {
  size: surface,
  target: [0, 0, 0],
  distance: 6,
  reversed: true,
});
const scene = passes
  .create(
    root,
    screen,
    { hdr: passes.color, depth: passes.depth },
    { depthClear: 0, depthCompare: 'greater' },
  )
  .pipe(view.inject());
```

- **Depth test** The kit's drawings test depth with the description's `depthCompare`. [`environment.background`](environment.md) sits at depth 0 and draws where depth still holds it.
- **Depth readers** The camera's `inject()` fills `cameras.reversed`, so [TAA](taa.md), [depth of field](dof.md), [ambient occlusion](ao.md) and the [picker](picker.md) read the depth that camera drew the reversed way. Give TAA `reversed: true` when it has no `camera`.
- **Custom cameras** A [custom camera](cameras.md) takes `reversed: true` too. Write a reversed projection into it, such as `mat4.perspectiveReverseZ(fov, aspect, near, far)`.
- **Your own shaders** A shader of your own that reads the depth starts from `cameras.farDepth()` and keeps the nearer of two depths with `cameras.nearerDepth()(a, b)`, through the camera's fills.
- **Unchanged values** A drawing's own `depthStencil` compare, `passes.fullScreen`'s depth of 0 and the depth `text.screen` takes stay as you write them. Give them reversed values yourself.
- **Shadows** [Shadows](lighting.md#shadows) draw into maps of their own with standard depth, whatever the scene uses.

## Layers

A shadow map in cascades, one per distance, draws the same casters into several layers of one texture, each through its own view. Give `targets.create` a target with `layers`, and the description draws a pass into each. [`cameras.layered`](cameras.md#a-view-per-layer) holds a view per layer:

```ts
import { mat4 } from 'wgpu-matrix';
import { cameras, passes, targets } from '@typegpu/kit';

const size = { width: 1024, height: 1024, pixelRatio: 1 };
const maps = targets.create(root, size, {
  depth: { format: 'depth16unorm', layers: 3, sampled: true },
});
const views = cameras.layered(root, 3);
const casters = passes
  .create(root, maps, { depth: passes.depth }, { bias: { constant: 2, slope: 2 } })
  .pipe(views.inject());
const drawn = casters.add(herd);

frames.create(root, (frame) => {
  // A wider view for each layer
  for (let k = 0; k < 3; k++) {
    const reach = 8 * 4 ** k;
    const view = mat4.lookAt([20, 40, 20], [0, 0, 0], [0, 1, 0]);
    views.write(k, view, mat4.ortho(-reach, reach, -reach, reach, 0, 200));
  }
  casters.record(frame, drawn); // a pass into each layer
});
```

- **One pipeline** The description builds each pipeline once, for all layers. Each pass sets a uniform holding its layer, which shaders read as `passes.layer.$`. `cameras.layered` reads it to give `cameras.current.$` the layer's view. Data of your own per layer can be indexed by it too.
- **Recording** `record` draws a pass into each layer, in order, with the same options. `record(frame, drawn, { layer })` draws into one. `begin(frame, { layer })` begins one and throws without a layer when there are several.
- **Timing** With `timestampWrites`, the first layer's pass writes the start and the last layer's pass writes the end.
- **Layer counts** Every target a description draws into needs the same `layers`, or `passes.create` throws naming each target and its count. Translucency targets and resolves aren't drawn into layers.
- **Render bundles** A render bundle can't draw into a description of 2 or more layers, and `draw` throws for one. Record the drawing into the passes that `record` or `begin` opens.
- **Kit drawings** Drawings of one pipeline, [particles](particles.md), [trails](trails.md) and [text](text.md) draw the same way into each layer, through the layer's view. An [instances](instances.md#culling) renderer with `cull: true` keeps a visible list per layer and culls every layer in one pair of dispatches. [Impostors](impostors.md) and [poses](poses.md) draw through an instances renderer.
- **Kernels** A kernel built from a layered description's `inject()` runs outside its passes, so it fills `passes.layer` itself. The instances culling fills it from each invocation's y.
- **Bindings** The layer takes 1 uniform and one of WebGPU's 4 bind groups in each pipeline that reads `passes.layer`. With `cameras.layered`, a caster binds 2 uniforms: the views and the layer.

## Limits

- **Bind groups** A pipeline a description builds uses up to three of WebGPU's four bind groups: one for its fixed bindings, one for the [shared parts](#buffers-and-textures-of-your-own) and one for the [layer](#layers). One is left for a group of your own.
- **Fragment inputs** The fragment inputs to a drawing's `pixelOf` are its vertex's fields and the pixel's `position`. WebGPU's other fragment inputs, such as `frontFacing`, aren't available to it.
- **Derivatives** In `pixelOf`, take `std.fwidth`, `std.dpdx` and `std.dpdy` before any branch or `return` that depends on the pixel. WGSL rejects a derivative in control flow that varies between pixels.
- **Large coordinates** A few thousand units from the origin, a 32-bit float steps by about 0.0002, too coarse for derivatives of a world position or for noise coordinates across a pixel. Carry `world - cameras.current.$.position` in the vertex, and add the eye's position back in `pixelOf` where it needs the world position.
- **Varying names** Each output's varyings go between the stages as `<target>_<n>`, numbered from 0 in the order of its `varyings` struct. A name a vertex field already has gets a number added. They count towards WebGPU's 16 inter-stage variables, with the vertex's own fields.
- **Previous frame** An output with `previous: true` runs the renderer's `at` twice per vertex, and binds last frame's uniforms beside this frame's.
- **Overlapping layers** Translucent layers that overlap in depth average their colours by weight, so a layer close behind another shows through more than it would in order. The weight suits distances from the eye of about 0.1 to 500.
- **Translucent motion** A translucent drawing's motion is that of the layer drawn last where it shows, so TAA can smear what lies behind it. Leave it out of motion with `without('motion')` to keep the motion beneath it.
- **Blended drawings** [Particles](particles.md), [trails](trails.md) and [text](text.md) drawings set a `blend` and draw over in order. To draw one of these in any order, make a drawing of your own from it. Leave out its `blend`, set `translucent: true` and supply premultiplied colour. Use a description with accumulation and revealage targets.
