# Counters

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

Named counters that kernels increment and the CPU reads as changes since its last read.

> `import { counters } from '@typegpu/kit'`: `counters.create(root, names, options?) → Counters`. Keeps a counter for each named kind of event, and no details of one. **records** `capture` frame, `clear` encoder: `capture` after the passes that add; `clear` before them, whenever the counting starts again; in frame mode, `capture` clears after copying. **owns** a buffer, a readback: the counters; the readback copies them at `hz`. **lifecycle** `destroy()`, `[Symbol.dispose]`. **injects** member: `add`, which adds to its own counters in any pipeline. **types** `Counts`. `src/counters.ts`; dominoes, falling-sand, platformer, stampede.
>
> `Options`, taken by `create`:
> - `per?: 'total' | 'frame'` Selects accumulated counters or counters for individual frames. Default `'total'`.
> - `hz?: number` Reads counters for `take` and `latest` this many times per second on average. Default 30.
> - `staging?: number` Sets the number of readback staging buffers. Default 3.
>
> `Counters`, from `create`:
> - `names: readonly K[]` Lists the counter names in the order they were given.
> - `inject()` Fills `add` with these counters, as its default does.
> - `add: { readonly [name in K]: (amount: number) => void }` Adds `amount` to a counter atomically in any shader, such as `contacts.add.stomps(1)`.
> - `buffer: TgpuBuffer<d.WgslArray<d.Atomic<d.U32>>> & StorageFlag` Stores one `u32` per counter, in the order of `names`.
> - `latest: Counts<K> | undefined` Reports the latest counts read back.
> - `capture(frame)` Copies counters when a read is due, then clears them in frame mode.
> - `take()` Returns the increase in each counter since the last `take`, or the captured counts in frame mode.
> - `clear(target)` Resets all counters to 0, recorded into `target`, a frame or an encoder.
> - `destroy()` Destroys the counters and readback.

`counters` keeps a **counter** for each kind of event, such as a hit, a kill or a pickup. It carries counts and no details: kernels add to a counter, and the CPU reads how much it grew a frame or two later. That is enough to update a score, play a sound or restart a level, none of which a kernel can do. The details of each event take a queue of your own.

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

const contacts = counters.create(root, ['stomps', 'hurts'], { hz: 60 });

const touch = tgpu.computeFn({
  workgroupSize: [64],
  in: { gid: d.builtin.globalInvocationId },
})(({ gid }) => {
  'use gpu';
  if (gid.x >= 64) return;

  const offset = hero.$ - critters.$[gid.x];
  if (offset.y > 0.4 && offset.y < 0.8) contacts.add.stomps(1);
});
const touching = root.createComputePipeline({ compute: touch });

frames.create(root, (frame) => {
  const contact = contacts.take(); // what each gained since the last take, or undefined
  if (contact?.stomps) bounce(contact.stomps);
  if (contact?.hurts) restart();

  const compute = frame.encoder.beginComputePass();
  compute.setPipeline(touching);
  compute.dispatchWorkgroups(1);
  compute.end();
  contacts.capture(frame); // after the passes that add
});
```

- **Adding** `add.stomps(amount)` adds atomically, from any thread of any kernel. The amount can vary, such as a kill's reward of 1, 4 or 1000 gold.
- **Capturing** `capture` copies counters at `hz`, 30 times per second by default. It uses a [readback](readback.md) with `staging` buffers, 3 by default, and skips a capture while all are mapping. The platformer reads at 60 Hz, so the hero bounces a frame or two after a stomp.
- **Reading** `take()` returns each counter's increase since the last `take`, once per completed read, and `undefined` between reads. `latest` holds totals since the last `clear`. Each reuses an object and updates it in place. Copy a result to keep it.
- **Late reads** Counters only increase, so late or repeated reads lose no events. The next difference includes them. Differences use `u32` arithmetic and remain correct across a wrap at 2^32.

Use `{ per: 'frame' }` to count objects in a frame, such as the stampede's skinned horses and cards. `capture` copies when a read is due and clears counters every frame. `latest` and `take()` then return one frame's counts. Call `capture` every frame, after the passes that count.

## Starting again

`clear(frame)` sets every counter to 0 in the frame and drops the reads made before it, so the next gains count from the clear. Record it before the passes that add, as at a restart:

```ts
frames.create(root, (frame) => {
  if (restarting) tally.clear(frame);
  restarting = false;
  // ... the passes that add, then tally.capture(frame)
});
```

Read `latest` to display totals such as enemies spawned, slain or through the gate. The platformer keeps its counters across restarts and ignores damage for 1.5 s, longer than a read takes to complete.

## Limits

- Counters omit event details such as location. Handle immediate effects on the GPU, such as squashing a critter or emitting dust. Let the CPU react to the count.
- Per-item thresholds need separate counters. The fish tank uses its own counter array to count bites per pellet and decide on the GPU when each is eaten.
