# Expressions

> Values computed per frame from time, layer index, size and audio. Every variable, operator and function, plus colors, strings and `${...}` live text.

An expression is a string that starts with `=`. vidmake evaluates it for every frame (and every
motion-blur sub-frame) and uses the result as the field's value:

```json
"rotation": "=t * 90"
"y": "=360 + sin(t * 2 * pi) * 50"
"opacity": "=map(f, 0, 20, 0, 1)"
"fill": "=hsl(i * 30, 60, 70)"
```

Expressions are the fifth [animation form](https://vidmake.app/docs/animation.md), next to constants, keyframes, tweens and
springs. Reach for them when a value depends on something keyframes can't express: a copy's index, a
continuous oscillation, randomness, the music, or a formula. They are pure functions of their inputs,
so a frame always renders the same way, whether in `render`, `still` or `storyboard`.

**Demo: One repeated dot; position, size and color are expressions of time t and copy index i** (rendered video: https://vidmake.app/media/expr-wave.mp4)

```json
{
  "compositions": [{
    "id": "wave", "description": "One repeated dot; position, size and color are expressions of time t and copy index i",
    "width": 1280, "height": 720, "fps": 30, "duration": "4s", "background": "#f4f1ea",
    "layers": [
      { "id": "dot", "type": "ellipse", "width": 26, "x": 640, "repeat": { "count": 25, "layout": "row", "spacing": 44 },
        "y": "=360 + sin(t * pi + i * 0.45) * 120",
        "scale": "=0.5 + 0.5 * (0.5 + 0.5 * cos(t * pi + i * 0.45))",
        "fill": "=lerp('#161412', '#c92a26', 0.5 + 0.5 * sin(t * pi + i * 0.45))" }
    ]
  }]
}
```

That whole wave is one layer, [repeated](https://vidmake.app/docs/repeat.md) 25 times. Each copy reads its index `i`, so
the same three expressions put every dot at a different phase of the same sine wave.

## Where expressions work

- Any [animatable numeric field](https://vidmake.app/docs/animation.md#which-fields-animate): `"x": "=..."`.
- Color fields (`fill`, `stroke`, `shadow.color`, `glow.color`, text `background`): the expression
  should return a color, see [strings and colors](#strings-and-colors).
- Inside text, as `${...}` templates: see [live text](#live-text).
- Inside keyframes and tweens? No: a keyframe value or a tween's `from`/`to` must be a plain value.
  Use an expression for the whole field instead, often with an [easing function](https://vidmake.app/docs/easing.md#easing-functions-in-expressions).

## Variables

| variable | alias | value |
|---|---|---|
| `t` | `time` | layer-local time in seconds (0 at the layer's `start`) |
| `f` | `frame` | layer-local frame (fractional during motion-blur sub-frames) |
| `gt` | | global time in seconds, from the start of the composition being rendered |
| `gf` | | global frame |
| `fps` | | composition frame rate |
| `dur` | | the layer's duration in seconds |
| `durf` | | the layer's duration in frames |
| `p` | `progress` | progress through the layer, `f / durf`, clamped to 0..1 |
| `w`, `h` | `width`, `height` | size of the composition being rendered |
| `pw`, `ph` | | size of the parent: the composition for top-level layers, the group box inside a group |
| `i` | `index` | copy index for [repeated](https://vidmake.app/docs/repeat.md) layers (0-based); otherwise the layer's index among its siblings |
| `n` | `count` | number of copies for repeated layers; otherwise `1` |
| `since('m')` | | seconds since the composition [marker](https://vidmake.app/docs/time.md#markers) `m` (negative before it). Written like a function |
| `marker('m')` | | the marker's time in this layer's local seconds |
| `amp`, `bass`, `beat`, `beats` | | [audio-reactive](https://vidmake.app/docs/audio-reactive.md) values from the soundtrack. `amp` and `bass` are 0..1, scaled so the loudest 2% of the soundtrack reads 1; `vidmake analyze` shows their curves and the beat times |
| `pi` | `PI` | 3.14159... |
| `tau` | | 2π |
| `e` | | 2.71828... |

Some details that matter in practice:

- **Local time.** `t` and `f` restart at 0 for every layer, at its own `start`. Inside a [group](https://vidmake.app/docs/groups.md), a
  child's `start` is relative to the group, and so is its `t`. Use `gt` when several layers must share one clock.
- **Children of a repeated group** see the group copy's `i` and `n`, so one card definition can vary per
  copy. A repeated layer inside a repeated group uses its own `i`.
- **`w`/`h` inside a [component](https://vidmake.app/docs/components.md)** are still the size of the composition you render,
  not the referenced one. Use `pw`/`ph` there: they are the `use` layer's box.
- **`p` and `dur`** depend on the layer's duration: a layer without `duration`/`end` lasts until its parent ends.

## Operators

From lowest to highest precedence:

| operators | notes |
|---|---|
| `c ? a : b` | ternary; `c` is true when it isn't 0 |
| `\|\|` | logical or, returns 1 or 0 |
| `&&` | logical and, returns 1 or 0 |
| `==` `!=` | numbers compare within 1e-9; two strings compare exactly |
| `<` `<=` `>` `>=` | return 1 or 0 |
| `+` `-` | `+` concatenates when either side is a string |
| `*` `/` `%` | division by 0 gives 0; `%` is a Euclidean modulo that is never negative (`-1 % 3` = `2`), handy for cycling |
| unary `-` `!` `+` | `!x` is 1 when `x` is 0 |
| `^` (also `**`) | power, right-associative; binds tighter than unary minus, so `-2^2` = `-4` |

Parentheses group as usual. Booleans are numbers, so `"opacity": "=t > 1"` is 0 before one second
and 1 after, and `"=(t > 1) * 200"` is a jump from 0 to 200.

## Functions

### Math

| function | result |
|---|---|
| `sin(x)` `cos(x)` `tan(x)` | trigonometry in **radians** (`sin(t * tau)` completes one cycle per second) |
| `asin(x)` `acos(x)` `atan(x)` | inverse trigonometry, in radians |
| `atan2(y, x)` | angle of the point (x, y), in radians |
| `deg(x)`, `rad(x)` | radians → degrees, degrees → radians |
| `abs(x)` `sign(x)` | absolute value; −1, 0 or 1 (`sign(0)` is 1) |
| `floor(x)` `ceil(x)` | round down, round up |
| `round(x)`, `round(x, d)` | nearest integer, or `d` decimals: `round(3.14159, 2)` = 3.14 |
| `fract(x)` | fractional part, `x - trunc(x)` (`fract(2.75)` = 0.75) |
| `sqrt(x)` | square root (negative input gives 0) |
| `pow(x, y)` `exp(x)` | power, e^x |
| `ln(x)` (alias `log`) `log10(x)` | natural and base-10 logarithm |
| `min(a, b, ...)` `max(a, b, ...)` | 2 to 16 arguments |
| `mod(a, b)` | same as `a % b` |

### Mapping and shaping

| function | result |
|---|---|
| `clamp(x, a, b)` | `x` limited to the range between `a` and `b` (in either order) |
| `lerp(a, b, t)` (alias `mix`) | `a + (b - a) * t`, with `t` not clamped. With two colors it blends them, see [below](#strings-and-colors) |
| `map(x, inA, inB, outA, outB)` (alias `interpolate`) | maps `x` from `inA..inB` to `outA..outB`, **clamped** to the output range. Like Remotion's `interpolate()` with clamping |
| `mapu(x, inA, inB, outA, outB)` | the same, unclamped: keeps extrapolating outside `inA..inB` |
| `step(edge, x)` | 1 when `x >= edge`, else 0 |
| `smoothstep(a, b, x)` | 0 below `a`, 1 above `b`, a smooth S-curve between |
| `pingpong(x, len)` | `x` bounced between 0 and `len`: 0 → len → 0 → ... |
| `easeOutCubic(x)`, ... | any [easing name](https://vidmake.app/docs/easing.md#easing-functions-in-expressions) as a function of 0..1, including the built-in and theme [motions](https://vidmake.app/docs/easing.md#your-own-motions) (`smooth(x)`, `house(x)`) |
| `spring(frame[, damping, stiffness, mass])` | the [spring](https://vidmake.app/docs/animation.md#springs) curve from 0 to 1 at a frame count (defaults 10, 100, 1). `spring(f - 15)` starts half a second in at 30 fps |

```json
"opacity": "=map(t, 0, 0.5, 0, 1) * map(t, dur - 0.5, dur, 1, 0)"
"x": "=mapu(t, 0, 1, 100, 300)"
"scale": "=0.5 + 0.5 * spring(f, 12, 180)"
"y": "=500 - 200 * pingpong(t, 1)"
```

### Randomness and noise

There is no `Math.random()` in vidmake. Every "random" function is a hash of its arguments, so it
returns the same value for the same input on every frame, every machine and every render. Pass a
different seed (often `i`) to get a different value.

| function | result |
|---|---|
| `rand(seed)` (alias `random`) | a value in 0..1 that is fixed for a given seed. `rand(i)` gives each copy its own constant. Seeds closer than 0.001 give the same value |
| `noise(x[, seed])` | smooth 1D noise in 0..1 (most values fall between about 0.25 and 0.75). Feed it time for slow drift: `noise(t * 2, i)` |
| `noise2(x, y[, seed])` | smooth 2D value noise in 0..1, for fields like `noise2(i % 10, t)` |
| `wiggle(freq, amp[, seed])` | an offset that wanders between `-amp` and `amp` (usually within half of that), `freq` times per second. Uses `t` by itself: `"x": "=640 + wiggle(2, 30)"` |

**Demo: Deterministic randomness: rand(i) places each copy, wiggle and noise make it drift and flicker** (rendered video: https://vidmake.app/media/expr-noise.mp4)

```json
{
  "compositions": [{
    "id": "fireflies", "description": "Deterministic randomness: rand(i) places each copy, wiggle and noise make it drift and flicker",
    "width": 1280, "height": 720, "fps": 30, "duration": "5s", "background": { "type": "radial", "center": [0.5, 0.6], "radius": 0.9, "stops": ["#1d1b18", "#131210"] },
    "layers": [
      { "id": "fly", "type": "ellipse", "repeat": 50,
        "x": "=w * rand(i) + wiggle(0.4, 70, i)", "y": "=h * rand(i + 0.5) + wiggle(0.4, 50, i + 100)",
        "width": 12, "scale": "=0.6 + 1.2 * rand(i + 0.25)", "fill": "=pick(i, ['#efebe2', '#f05a4e', '#6aa6e8'])",
        "opacity": "=smoothstep(0.35, 0.75, noise(t * 1.2, i))", "glow": { "radius": 16, "strength": 2 },
        "lint": { "ignore": ["invisible", "offCanvas"] } }
    ]
  }]
}
```

Each firefly places itself with `rand(i)` and `rand(i + 0.5)`, drifts with two `wiggle` calls with
different seeds, and fades in and out with `noise(t * 1.2, i)` passed through `smoothstep`.

> [!NOTE]
> Because their opacity is 0 at some frames, a few copies trigger `validate`'s `invisible` lint at their
> midpoint. The demo silences that with `"lint": { "ignore": ["invisible", "offCanvas"] }`; see [Lint](https://vidmake.app/docs/lint.md).

## Strings and colors

Values in expressions are numbers, strings or colors. Strings use single or double quotes:
`'#c92a26'`. (Inside a JSON string, single quotes are easier.)

| function or form | result |
|---|---|
| `pick(i, a, b, c)` or `pick(i, [a, b, c])` | the item at index `i`, cycling: `pick(5, ['x', 'y'])` = `'y'`. Items may be numbers, strings or colors. Only the chosen item is evaluated |
| `hsl(h, s, l[, a])` (alias `hsla`) | a color: `h` in degrees (wraps), `s` and `l` in 0..100, `a` in 0..1 |
| `rgb(r, g, b[, a])` (alias `rgba`) | a color: `r`, `g`, `b` in 0..255, `a` in 0..1 |
| `lerp(c1, c2, t)` | when both are colors (or color strings like `'#f00'`), the blended color; `t` is clamped to 0..1 |
| `pad(x, width[, char])` | `x` as text, left-padded to `width` characters with `'0'` or `char`: `pad(7, 3)` = `"007"` |
| `fmt(x[, sep[, decimals]])` (alias `format`) | thousands separators: `fmt(1234567)` = `"1,234,567"`. With `'.'` as `sep` the decimal mark becomes a comma: `fmt(1234.5, '.', 2)` = `"1.234,50"` |
| `'a' + x` | string concatenation whenever either side is a string |
| `[a, b, c]` | a list; only useful as an argument to `pick` (elsewhere it means its first item) |

What happens to the result depends on the field:

- **Numeric fields** use numbers as they are. A string is parsed as a number (`'42'` → 42) and anything
  unparsable becomes 0; a color becomes 0.
- **Color fields** use colors as they are and parse strings as colors (`'#1f5fb0'`, `'rgb(...)'`, CSS names).
  A number, or a string that isn't a color, gives transparent.
- **Text `${...}`** prints the value: numbers with up to two decimals and no trailing zeros (`0.5`, `3`,
  `1.33`), strings as they are, colors as `#rrggbbaa`.

**Demo: Expressions that return colors: hsl() by index and time, pick() from a palette, lerp() between two colors** (rendered video: https://vidmake.app/media/expr-colors.mp4)

```json
{
  "fonts": [{ "family": "JetBrains Mono", "path": "fonts/JetBrainsMono.ttf" }],
  "compositions": [{
    "id": "colors", "description": "Expressions that return colors: hsl() by index and time, pick() from a palette, lerp() between two colors",
    "width": 1280, "height": 720, "fps": 30, "duration": "4s", "background": "#f4f1ea",
    "layers": [
      { "id": "label", "type": "text", "text": "${pick(i, ['hsl()', 'pick()', 'lerp()'])}", "font": "JetBrains Mono", "fontSize": 24,
        "fill": "#4a4640", "anchor": "right", "x": 250, "y": 360, "repeat": { "count": 3, "layout": "column", "spacing": 170 } },
      { "id": "hsl", "type": "rect", "width": 72, "height": 120, "cornerRadius": 4, "x": 750, "y": 190,
        "repeat": { "count": 10, "layout": "row", "spacing": 90 }, "fill": "=hsl(i * 36 + t * 90, 50, 70)" },
      { "id": "pick", "type": "rect", "width": 72, "height": 120, "cornerRadius": 4, "x": 750, "y": 360,
        "repeat": { "count": 10, "layout": "row", "spacing": 90 },
        "fill": "=pick(i + floor(t * 4), ['#c92a26', '#161412', '#1f5fb0', '#d8d1c1'])" },
      { "id": "lerp", "type": "rect", "width": 72, "height": 120, "cornerRadius": 4, "x": 750, "y": 530,
        "repeat": { "count": 10, "layout": "row", "spacing": 90 },
        "fill": "=lerp('#d8d1c1', '#161412', 0.5 + 0.5 * sin(t * pi - i * 0.5))" }
    ]
  }]
}
```

```json
"fill": "=hsl(i * 36 + t * 90, 50, 70)"
"fill": "=pick(i + floor(t * 4), ['#c92a26', '#161412', '#1f5fb0', '#d8d1c1'])"
"fill": "=lerp('#d8d1c1', '#161412', 0.5 + 0.5 * sin(t * pi - i * 0.5))"
```

## Live text

In a text layer's `text` (and in each [rich-text span](https://vidmake.app/docs/text.md#rich-text)), `${expr}` is replaced
by the expression's value every frame. This is how counters, clocks, timecodes and page numbers work:

```json
"text": "${fmt(round(map(t, 0, 2, 0, 1500000)))} users"
"text": "Slide ${pad(i + 1, 2)} / ${pad(n, 2)}"
"text": "${t:2}s"
```

`${expr:N}` formats a number with exactly `N` decimals (`${t:2}` → `1.50`). The suffix is ignored
when the expression contains a ternary `?`; use `round(x, N)` there instead. A template can't contain
a `}` inside the braces.

**Demo: Live text: ${...} templates re-evaluated every frame, with fmt, pad and fixed decimals** (rendered video: https://vidmake.app/media/expr-counter.mp4)

```json
{
  "fonts": [
    { "family": "Schibsted Grotesk", "path": "fonts/SchibstedGrotesk.ttf" },
    { "family": "JetBrains Mono", "path": "fonts/JetBrainsMono.ttf" }
  ],
  "compositions": [{
    "id": "counter", "description": "Live text: ${...} templates re-evaluated every frame, with fmt, pad and fixed decimals",
    "width": 1280, "height": 720, "fps": 30, "duration": "4s", "background": "#f4f1ea",
    "layers": [
      { "id": "count", "type": "text", "font": "Schibsted Grotesk", "fontWeight": 860, "fontSize": 190, "letterSpacing": -9, "fill": "#161412", "y": 300,
        "text": "${fmt(round(1284500 * easeOutCubic(clamp((t - 0.2) / 2.5, 0, 1))))}" },
      { "id": "unit", "type": "text", "text": "frames rendered", "font": "JetBrains Mono", "fontSize": 20, "letterSpacing": 2.4, "uppercase": true,
        "fill": "#8a857a", "y": 444 },
      { "id": "stats", "type": "text", "font": "JetBrains Mono", "fontSize": 26, "fill": "#4a4640", "y": 560, "whiteSpace": "pre",
        "text": "t ${t:2}s    f ${pad(f, 3)}    ${round(p * 100)}%    00:${pad(floor(t), 2)}" }
    ]
  }]
}
```

`trace` prints the evaluated text in its notes column, so you can check a counter without rendering:

```console
$ vidmake trace expr-counter.json -l count --every 15
 FRAME    TIME        X        Y       W       H    ROT  SCALE  OPAC  NOTES
     0   0.00s    640.0    300.0   122.6   228.0    0.0   1.00  1.00   "0"
    15   0.50s    640.0    300.0   700.2   228.0    0.0   1.00  1.00   "409,149"
    30   1.00s    640.0    300.0   688.0   228.0    0.0   1.00  1.00   "880,612"
    45   1.50s    640.0    300.0   824.8   228.0    0.0   1.00  1.00   "1,142,445"
    60   2.00s    640.0    300.0   845.1   228.0    0.0   1.00  1.00   "1,256,303"
    75   2.50s    640.0    300.0   845.3   228.0    0.0   1.00  1.00   "1,283,842"
    90   3.00s    640.0    300.0   857.4   228.0    0.0   1.00  1.00   "1,284,500"
   105   3.50s    640.0    300.0   857.4   228.0    0.0   1.00  1.00   "1,284,500"
```

> [!TIP]
> Text templates are evaluated at the whole frame even when the composition has
> [motion blur](https://vidmake.app/docs/effects.md#motion-blur), so numbers stay sharp instead of smearing between two values.

Text expressions see the same variables as any other field, including `i` and `n` in
[repeated](https://vidmake.app/docs/repeat.md) text and `beats` for [audio](https://vidmake.app/docs/audio-reactive.md). `{{prop}}`
[props](https://vidmake.app/docs/props.md) are substituted before any of this happens, so a numeric prop can be used inside a
template: `"${ {{count}} * 2 }"` (spaces keep the braces apart).

## Errors

Expressions are parsed when the project is compiled, so `vidmake validate` catches mistakes before
anything renders. An unknown variable or function lists every valid name, and a wrong argument count
says how many the function takes:

```output
✗ main: layer `dot` (main > layers[0]): `y`: unknown variable `tt` in expression `360 + sin(tt)`. Available: t f gt gf fps dur durf p w h pw ph i n amp bass beat beats pi e tau
```

> [!AGENT]
> Prefer one readable expression over a clever one. When a value looks wrong, `vidmake inspect project.json -t 2s -l <id>`
> shows the resolved numbers at one frame, and `vidmake trace` shows them over time. For text, both print
> the evaluated string.

## Recipes

| goal | expression |
|---|---|
| spin forever, 90° per second | `"rotation": "=t * 90"` |
| float up and down | `"y": "=ph * 0.45 + sin(t * 2) * 8"` |
| fade in and out over the layer's life | `"opacity": "=map(t, 0, 0.4, 0, 1) * map(t, dur - 0.4, dur, 1, 0)"` |
| blink twice a second | `"opacity": "=floor(t * 4) % 2"` |
| stagger copies | `"scale": "=easeOutBack(clamp((t - i * 0.05) / 0.5, 0, 1))"` |
| alternate colors | `"fill": "=pick(i, ['#161412', '#c92a26'])"` |
| shake | `"x": "=640 + wiggle(12, 6)", "y": "=360 + wiggle(12, 6, 1)"` |
| progress bar | `"width": "=pw * 0.8 * p"` |
| percentage label | `"text": "${round(p * 100)}%"` |
