# Per-frame code and simulations

Most motion is a [tween](/docs/framework/animation/values.md): a value, a duration, an easing. Two steps cover what a tween cannot express:

- [`custom`](/docs/framework/reference/framescript.md#custom) runs a function of time for every frame: a formula, a path, a shader uniform.
- [`simulate`](/docs/framework/reference/framescript.md#simulate) runs a rule that moves a state on step by step: bouncing, chasing, particles.

Both keep the promise every scene makes: a frame depends only on its time, so any frame can be drawn by itself and comes out the same on every run.

## `custom`

`custom(duration, fn, options?)` lasts `duration` seconds. For every frame its span covers, `fn(progress, time)` is called with the progress from 0 to 1 and the seconds since the step started. The function must depend only on those two arguments.

```ts
import { add, camera, custom, timeline, tween, video, wait } from "framescript"
import { panel } from "framescript/shapes"
import { PerspectiveCamera } from "three"

// The radius of the circle, and how many turns the dot makes.
const RADIUS = 2
const TURNS = 2

export default video(
  { width: 1920, height: 1080, fps: 60 },
  timeline(function* () {
    const lens = yield* add(new PerspectiveCamera(32, 16 / 9, 0.1, 100), {
      position: [0, 0, 14],
    })
    yield* camera(lens)
    const dot = yield* add(
      panel({ width: 0.6, height: 0.6, radius: 0.3, color: "#ff6467" }),
      { position: [RADIUS, 0, 0] }
    )

    yield* custom(
      3,
      (progress) => {
        const angle = progress * TURNS * Math.PI * 2
        dot.position.x = Math.cos(angle) * RADIUS
        dot.position.y = Math.sin(angle) * RADIUS
      },
      {
        writes: [{ target: dot.position, keys: ["x", "y"] }],
        label: "orbit",
      }
    )
    // An ordinary tween takes over from where the function left the dot.
    yield* tween(dot.position, { x: 0 }, 0.6)
    yield* wait(0.4)
  })
)
```

### Say what the function writes

`writes` names the properties the function writes, as a tween would be given them: a target and the keys on it.

When the step starts, the function is called along its span, sixty times a second, and the named properties are read after each call. The values become an ordinary record on the timeline, like the one a tween leaves. That gives you:

- The studio's inspector shows the values at the playhead.
- A later `tween` or `set` on the same property starts from where the function left it.
- Frames before and after the span are right whichever frame was drawn before them.

Two rules follow from how the values are recorded:

- Name everything the function writes. After the span, the record holds the values and the function is not called again.
- The function is recorded from its arguments alone. A function that reads other moving things, such as the position of an object a tween is moving, cannot be recorded this way. Write it with [`simulate`](#simulate), or name nothing.

A property that cannot be animated, see [what can be animated](/docs/framework/animation/values.md#what-can-be-animated), cannot be named either.

### The other options

| Option  | Means                                                                                                                           |
| ------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `label` | A name for the step's bar on the studio's timeline.                                                                             |
| `curve` | An [easing](/docs/framework/animation/easings.md) to draw on the bar, to show how the step moves. It does not change what the function does. |
| `rest`  | A function that puts back what `fn` changed. It is called for every frame outside the span.                                     |

In an entry of `writes`, `of` and `name` are for a target that is no part of an added object by itself, such as a clipping plane of a material. `of` is the added object it belongs to, and `name` is what it is called under that object:

```ts
import { add, custom, easeInOut } from "framescript"
import { panel } from "framescript/shapes"
import { MeshBasicMaterial, Plane, Vector3 } from "three"

// Everything to the right of the plane is cut away.
const edge = new Plane(new Vector3(-1, 0, 0), -3)
const card = yield* add(
  panel({
    width: 6,
    height: 3.4,
    material: new MeshBasicMaterial({
      color: "#ff6467",
      clippingPlanes: [edge],
    }),
  })
)

yield* custom(
  1.8,
  (progress) => {
    edge.constant = -3 + 6 * easeInOut(progress)
  },
  {
    writes: [{ target: edge, keys: ["constant"], of: card, name: "wipe" }],
    label: "wipe",
    curve: easeInOut,
  }
)
```

### A custom step that names nothing

Without `writes`, the step leaves no record. Its function is called for every frame from the start of its span on; after the span it is called with progress 1, so its last state stays.

Two things to know:

- It must only write what no tween or `set` writes while it runs or after. The function is applied after the recorded values, so it would win over a later tween on the same property. A tween that ended before the step began is taken over, as a later tween takes over from it.
- Nothing puts back what it changed for frames before its span. If the function changes something that should be as it was outside the span, give it a `rest`. With `rest`, the function holds only while its span runs.

A function as the third argument is taken as `rest`:

```ts
import { add, custom } from "framescript"
import { panel } from "framescript/shapes"

const card = yield* add(panel({ width: 3, height: 2, color: "#ff6467" }))

// Shakes for a second, and stands straight before and after.
yield* custom(
  1,
  (_progress, time) => {
    card.rotation.z = Math.sin(time * 40) * 0.05
  },
  () => {
    card.rotation.z = 0
  }
)
```

## `simulate`

Where a bouncing ball is depends on where it was and how fast it was going. A frame cannot ask what the frame before looked like, so a rule like that is not run when a frame is drawn. `simulate(duration, options)` runs it once, when the scene is run: in even steps, with random numbers from a seed, and the state after every step is kept. Drawing a frame looks its state up.

The state is plain numbers in a `Float32Array`. You say how many, and give three functions:

| Option                          | Means                                                                                                                  |
| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `size`                          | How many numbers the state holds.                                                                                      |
| `start(state, random)`          | Fills in the state before the first step. Without it, the state starts as zeros.                                       |
| `rule(state, dt, time, random)` | Moves the state one step on, in place. `dt` is the length of a step in seconds.                                        |
| `draw(state, since)`            | Writes a state to the objects it stands for. It is called for every frame drawn and must depend only on its arguments. |

```ts
import { add, camera, simulate, timeline, video, wait } from "framescript"
import { panel } from "framescript/shapes"
import { PerspectiveCamera } from "three"

// Where the floor is, how hard the ball is pulled down, and how much of
// its speed it keeps when it lands.
const FLOOR = -2
const GRAVITY = 18
const KEPT = 0.78

export default video(
  { width: 1920, height: 1080, fps: 60 },
  timeline(function* () {
    const lens = yield* add(new PerspectiveCamera(32, 16 / 9, 0.1, 100), {
      position: [0, 0, 14],
    })
    yield* camera(lens)
    const ball = yield* add(
      panel({ width: 0.6, height: 0.6, radius: 0.3, color: "#ff6467" }),
      { position: [0, FLOOR, 0] }
    )

    yield* simulate(4, {
      // A height above the floor, and a speed.
      size: 2,
      seed: 4,
      start: (state, random) => {
        state[0] = random.range(3, 5)
      },
      rule: (state, dt) => {
        const speed = (state[1] ?? 0) - GRAVITY * dt
        const height = (state[0] ?? 0) + speed * dt
        // Below the floor: back up, with a part of the speed.
        state[0] = height < 0 ? -height : height
        state[1] = height < 0 ? -speed * KEPT : speed
      },
      draw: (state) => {
        ball.position.y = FLOOR + (state[0] ?? 0)
      },
      writes: [{ target: ball.position, keys: ["y"] }],
      label: "bounce",
    })
    yield* wait(0.3)
  })
)
```

The remaining options:

| Option   | Means                                                                                                                                                                                                                                                   |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `step`   | The longest time between two steps, in seconds. The default is a sixtieth of a second. The steps are spread evenly, so the last one lands on the end.                                                                                                   |
| `seed`   | The seed of the random numbers `start` and `rule` are given. The default is 1.                                                                                                                                                                          |
| `blend`  | Whether a frame between two steps gets the two states blended. The default is `true`. With `false`, `draw` gets the earlier state and, as `since`, the seconds that have passed after it. Use `false` for a state in which things appear and disappear. |
| `writes` | What `draw` writes, as with `custom`. Those properties are recorded, one piece for each step.                                                                                                                                                           |
| `label`  | A name for the step's bar.                                                                                                                                                                                                                              |
| `rest`   | Puts back what `draw` changed, for every frame outside the span. Without it, frames after the span get the last state.                                                                                                                                  |

What to know:

- The rule may read the scene. At each step, the objects are where the timeline has them at that moment, so a rule can chase an object that a tween is moving.
- A simulation keeps every state: (steps + 1) × `size` numbers of four bytes each. A minute at the default step with a state of 1000 numbers is about 14 MB.
- For an object that follows another with a lag, [`follow`](/docs/framework/reference/motion.md#follow) in `framescript/motion` is a ready-made simulation.

## The same frames on every run

A scene is run again whenever its source changes, and a frame may be drawn alone, out of order, or on another machine during an export. So the code of a timeline has to give the same result on every run:

- No `Math.random()`. Use [`random(seed)`](/docs/framework/reference/values.md#random), which gives the same numbers for the same seed, with `range(min, max)`, `pick(items)` and `shuffle(items)`. [`noise(seed)`](/docs/framework/reference/values.md#noise) gives smooth random motion the same way. Inside `simulate`, use the `random` that `start` and `rule` are handed.
- No `Date.now()` and no `performance.now()`. Time is what `custom` and `simulate` hand to your functions.
- A function given to `custom`, and the `draw` of a simulation, depend only on their arguments. Do not count calls or keep a running sum in a variable outside: frames are not drawn in order.

[Check](/docs/framework/agents/checking.md) holds a video to this: the lint of its source names each such call where it stands, and check runs the timeline twice and plays frames in both orders, so a video that differs anyway fails with `nondeterminism`.

```ts
import { add, custom, noise } from "framescript"
import { panel } from "framescript/shapes"

const card = yield* add(panel({ width: 3, height: 2, color: "#ff6467" }))

// A slow wander, the same on every run.
const wander = noise(5)
yield* custom(
  4,
  (_progress, time) => {
    card.position.y = wander(time * 0.8) * 0.5
  },
  { writes: [{ target: card.position, keys: ["y"] }], label: "wander" }
)
```

## Raw engine code

[`effect(value)`](/docs/framework/reference/framescript.md#effect) runs a value of the `effect` library, which Framescript's engine is built on, as a step. It is an escape hatch you will rarely need: the studio shows it as one opaque step, and work inside it takes no scene time. A scene imports only `framescript` and `three`, so it takes the library's `Effect` module from `framescript` as well.

```ts
import { Effect, effect } from "framescript"

const share = yield* effect(Effect.succeed(Math.round(0.724 * 100) / 100))
```

## See also

- [Values](/docs/framework/animation/values.md): tweens, for everything they can express
- [Easings and springs](/docs/framework/animation/easings.md): easings as functions, and the functions for numbers
- [Instances, trails and particles](/docs/framework/objects/instances.md)
- [Motion presets](/docs/framework/animation/motion.md): `follow` and other ready-made moves
- [Reference: the main entry](/docs/framework/reference/framescript.md)
- Examples: steps/custom-writes, time/simulate, values/utilities
