# Clock

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

Simulation steps of a set length, work that is due every few frames, and easing and springs that keep their pace at any display rate.

> `import { clock } from '@typegpu/kit'`: `clock.fixedStep({ step, … }) → FixedStep`, `clock.cadence(options) → Cadence`, `clock.ease(dt, rate)`, `clock.spring({ stiffness, damping, … }) → Spring`, `clock.spring({ value, damping, stiffness, … }) → VectorSpring`. Counts fixed steps and cadences, and eases and springs values at the same pace at any frame rate. **kind** cpu. **records** `update(dt)` once a frame and run that many steps; a cadence's `due(dt)` says whether its work runs in the frame. **types** `Vector`. `src/clock.ts`; benthos, blockfall, censer, classroom, dominoes, ember-mirror, falling-sand, fireworks, fishtank, flow-field, jellies, jelly-world, kinetic, lattice, night-market, ocean, platformer, robot-arm, skeletons, slime-mould, solar-system, sph-sculpt, stampede.
>
> `FixedStepOptions`, taken by `fixedStep`:
> - `step: number` Sets the step duration in seconds, such as 1 / 120.
> - `maxSteps?: number` Limits the steps run per frame. Default 4.
> - `steady?: boolean` Counts a frame longer than both frames before it as the longer of the two. Default false.
>
> `CadenceOptions`, taken by `cadence`:
> - `every?: number` Runs work every `every` frames. Default none: set this or `hz`.
> - `hz?: number` Runs work `hz` times per second on average. Default none: set this or `every`.
>
> `SpringOptions`, taken by `spring`:
> - `stiffness: number` Sets how hard the spring pulls toward its target, per second squared for each unit away.
> - `damping: number` Sets how much speed the spring loses, per second.
> - `value?: number` Sets the starting position. Default 0.
> - `velocity?: number` Sets the starting speed in units per second. Default 0.
>
> `VectorSpringOptions`, taken by `spring`:
> - `value: V` Sets the vector the spring moves in place, and its starting position.
> - `velocity?: ArrayLike<number>` Sets the starting speed of each component in units per second. Default zeros.
> - `damping: number` Sets how much speed the spring loses, per second.
> - `stiffness: number` Sets how hard the spring pulls toward its target, per second squared for each unit away.
>
> `FixedStep`, from `fixedStep`:
> - `step: number` Sets the step duration in seconds.
> - `time: number` Reports the simulated seconds: the sum of every step `update` has returned.
> - `debt: number` Reports the unstepped time in seconds, capped at `maxSteps * step`.
> - `alpha: number` Reports the unstepped fraction of a step, capped at 1, for interpolation between two states.
> - `ahead: number` Reports the unstepped time in seconds, capped at one step.
> - `paused: boolean` Pauses the clock while true: `update` returns 0 and keeps the unstepped time.
> - `update(dt)` Adds `dt` seconds and returns the number of steps to run.
> - `reset()` Discards unstepped time after a reload or a long pause.
>
> `Cadence`, from `cadence`:
> - `dt: number` Reports the seconds since the last run.
> - `due(dt)` Adds `dt` seconds and returns whether work is due this frame, always on the first call.
> - `reset()` Restarts the schedule so the next `due` returns true.
>
> `Spring`, from `spring`:
> - `value: number` Holds the spring's position.
> - `velocity: number` Holds its speed in units per second.
> - `step(target, dt)` Moves the spring `dt` seconds toward `target` and returns the new `value`.
>
> `VectorSpring`, from `spring`:
> - `value: V` Holds the spring's position, the vector given as `value`, which `step` writes in place.
> - `velocity: number[]` Holds its speed per component, in units per second.
> - `step(target, dt)` Moves each component `dt` seconds toward `target`'s and returns `value`.

Display rates vary, and a resumed tab can have a long first frame. A simulation that uses frame time can behave differently at each rate. With a **fixed step**, the simulation advances in steps of one set length, and `clock.fixedStep` tells you how many to run this frame. A **cadence** tells you when work that runs less often is due. Easing and springs move values at the same pace at any rate.

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

const sim = clock.fixedStep({ step: 1 / 120, maxSteps: 4 });
const giCadence = clock.cadence({ every: 4 });

frames.create(root, (frame) => {
  const pass = frame.encoder.beginComputePass();
  for (let steps = sim.update(frame.dt); steps > 0; steps--) physics.step(pass);
  if (giCadence.due(frame.dt)) gi.step(pass, giCadence.dt);
  pass.end();
});
```

## Fixed step

- **Steps a frame** `update(dt)` returns the number of steps to run, capped at `maxSteps`, which defaults to 4. Time left over carries to the next frame, up to another `maxSteps` steps' worth. The rest is dropped, so catch-up work stays bounded. You need no extra clamp on `dt`, since this cap and [`frames.animate`](frames.md#running-the-loop)'s `maxDt` already bound a long frame.
- **Fixed length** Every step lasts `step`. A GPU simulation can bake that length into its kernel and dispatch the kernel once per step, all in one pass. A value that changes per step comes from [a count of the steps](#a-value-per-step).
- **Time** Write `time` to a uniform for animation that follows the simulation.
- **Changing the step** Set `step` to change the length, for example to fit a fixed number of steps into a beat of adjustable length. The next `update` that advances the clock counts steps of the new length from the time it carries and the time it adds. It returns at most `maxSteps`. [Particles](particles.md) and [machines](machines.md) read the step once, when created.
- **Steady frames** With `steady: true`, a frame that takes longer than both frames before it counts only as long as the longer of those two. A single slow frame then adds no time for the simulation to catch up on.
- **Between steps** Write `ahead` to a uniform once per frame to extrapolate along an object's velocity. [Particles](particles.md) take the fixed step and write their own value.

## A value per step

A queue write such as `buffer.write` enters the queue when you call it. Encoded commands enter the queue at submit. All writes made before that submit run before its first command, including writes made after recording a pass that reads them.

> **Caution: A uniform written per step**
>
> All the steps of a frame read the last value written:
>
> ```diff
>  for (let steps = sim.update(dt); steps > 0; steps--) {
> -  params.write({ phase: steps }); // every step reads the last write
>    field.step(compute);
>  }
> ```

Count steps on the GPU. A dispatch that increments a counter after each step gives every step its own number. Use it to derive time, seed randomness or select a buffer from a pair.

```ts
const STEP = 1 / 120;
const sim = clock.fixedStep({ step: STEP });

const count = root.createMutable(d.u32);
const counting = root.createComputePipeline({
  compute: tgpu.computeFn({ workgroupSize: [1] })(() => {
    'use gpu';
    count.$ += 1;
  }),
});

/** When the step that calls it starts, in seconds. */
const stepTime = () => {
  'use gpu';
  return d.f32(count.$) * STEP;
};

frames.create(root, (frame) => {
  const pass = frame.encoder.beginComputePass();
  for (let steps = sim.update(frame.dt); steps > 0; steps--) {
    field.step(pass);
    pass.setPipeline(counting);
    pass.dispatchWorkgroups(1);
  }
  pass.end();
});
```

- A kernel calls `stepTime` directly. A module that reads its time through an accessor gets the step's own time when you fill the accessor with it, as in `root.with(time, stepTime)`.
- Seed with the count, `randf.seed2(d.vec2f(i, count.$))`, and take the current half of a pair from `count.$ & 1`.
- A kernel can't read the count in the same dispatch that advances it, because its threads run in no set order. If the step's last kernel doesn't read the count, its thread 0 can advance it, saving a dispatch.
- Upload CPU-computed per-step values, such as body positions, in one array per frame. Include `first`, the step count at the frame's start, tracked on the CPU. Each step reads its value at `count.$ - first`.

Values that change between the passes of one algorithm belong inside its module. The [jump flood](../examples/jump-flood.md) uses a different step size in each of ten passes. It uses an immediate when `root.enabledWgslLanguageFeatures` includes `immediate_address_space`, or a bind group per pass otherwise. If neither approach works, [submit per step](frames.md#submitting-early).

## Cadences

- **By frames** `{ every: n }` runs on every `n`th frame, so its rate follows the display. `every: 4` runs 15 times per second at 60 Hz and 36 times at 144 Hz.
- **By rate** `{ hz: rate }` schedules a tick every `1 / rate` seconds. It uses the current frame's duration to choose the frame closest to the tick. At 60 fps, `hz: 25` gives gaps of two or three frames. After a stall it runs once and starts the schedule again.
- **Resetting** Call `reset()` when resuming work after a condition changes, such as global illumination after scene geometry settles.
- **Invalid values** Values that would run once or never, such as `hz: 0` or `maxSteps: 0`, throw a `RangeError`.

Use an `if` in the recorder for work controlled by a flag or trigger.

## Easing towards a goal

A value that moves a fixed fraction of the way to its goal each frame moves faster at 144 Hz than at 60 Hz. `clock.ease(dt, rate)` returns the fraction for a frame `dt` seconds long, `1 - Math.exp(-dt * rate)`, so the gap closes at the same pace at any frame rate:

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

// Half the gap closes every 87 ms, ln 2 / 8 seconds
follow += (goal - follow) * clock.ease(frame.dt, 8);
```

[Cameras](cameras.md#goal-and-update) ease towards their goal the same way.

## Springs

A spring follows its target with speed of its own, so it overshoots and settles where easing only slows down. Knock it by adding to its `velocity`. `clock.spring` solves the motion exactly for each step, so it settles the same at any frame rate and stays stable through a long frame:

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

const squash = clock.spring({ stiffness: 160, damping: 10 });
const tilt = clock.spring({ stiffness: 55, damping: 4.5, value: [0, 0, 0] });

if (landed) squash.velocity -= 2; // a knock
squash.step(0, frame.dt);
tilt.step(lean, frame.dt); // moves tilt.value in place
```

- `damping` of `2 * Math.sqrt(stiffness)` settles fastest without overshooting. Lower values bounce.
- A vector spring moves the array or vector you pass as `value` in place and allocates nothing per step.
- Set `value` to jump. The spring keeps its `velocity`.

## Limits

- A `hz` run can come up to half a frame early, so `hz` sets an average rate. Work that needs a minimum gap checks `dt`.
- Cadences don't stagger their phases. Work at the same rate or at rates that divide each other runs in the same frames. For example, 10, 20 and 30 Hz work all runs every 100 ms.
