# Player

The browser API in @motion-sdk/core. Load a scene into a canvas, stream patches, and drive it from code.

`@motion-sdk/core` runs a scene in a `<canvas>`. The renderer is Rust compiled to WebAssembly. Each animation frame makes one call into wasm. Input goes through shared memory and patches are batched.

```bash title="Terminal"
npm run build:wasm
```

```ts title="main.ts"
import { createPlayer } from "@motion-sdk/core"

const player = await createPlayer(canvas, scene)
player.patch({ op: "replace", path: "/nodes/orb/transform/position", value: [0, 1, 0] })
```

## `createPlayer`

```ts
createPlayer(canvas: HTMLCanvasElement, scene: Scene | string, options?: PlayerOptions): Promise<Player>
```

Creates a player for a typed `Scene` object (see [TypeScript SDK](/docs/concepts/typescript)) or JSON text. WebGPU is used when the browser gives an adapter. Otherwise the WebGL2 build loads instead. If WebGPU fails to start, the player swaps in a fresh canvas and falls back to WebGL2, unless you forced `backend: "webgpu"`.

### `PlayerOptions`

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `backend` | `"auto" \| "webgpu" \| "webgl2"` | `"auto"` | Force a backend. `auto` picks WebGPU when an adapter is available. |
| `authoring` | `boolean \| "auto"` | `"auto"` | Load the authoring bundle, which adds prefabs, repeats, glTF models, rigid bodies and full validation with JSON Pointer paths. `auto` picks it when the first scene uses them. Pass `true` if an agent or editor will stream them in later. WebGL2 always includes authoring. |
| `textureBase` | `string` | the page | Base URL for relative texture and model `src` paths. |
| `fontBase` | `string` | `"/fonts/"` | Base URL for font files. Fonts load on demand. |
| `autoplay` | `boolean` | `true` | Start playing at once. |
| `maxPixelRatio` | `number` | `2` | Cap for `devicePixelRatio`. |
| `trackScroll` | `boolean` | `true` | Map page scroll to the scene's scroll input. |
| `onFrame` | `(dt, player) => void` | — | Runs every frame before rendering, with the elapsed seconds. Update overrides here. |
| `onError` | `(message) => void` | — | Runs for rejected patches and load failures, with the engine's explanation. |

## `Player`

### Properties

| Property | Type | Description |
| --- | --- | --- |
| `time` | `number` | Playback time in seconds. |
| `playing` | `boolean` | Whether time advances. |
| `canvas` | `HTMLCanvasElement` | The canvas in use. It changes after a WebGL2 fallback. |
| `backend` | `"webgpu" \| "webgl2"` | The backend in use. |
| `stats` | `FrameStats` | Live counters, updated every frame. |
| `texturesLoaded` | `number` | Textures decoded and handed to the engine so far. |
| `modelsLoaded` | `number` | glTF models loaded so far. |

### Methods

| Method | Description |
| --- | --- |
| `patch(patch)` | Queue a JSON Patch: one `PatchOp`, an array of ops, or JSON text. `patch.*` in `@motion-sdk/scene` builds ops with checked paths. It applies atomically on the next frame. A rejected patch changes nothing and calls `onError`. See [Patches](/docs/reference/patch). |
| `load(scene)` | Replace the scene and keep the GPU device. Resets time to 0. |
| `play()`, `pause()` | Start or stop time. |
| `seek(t)` | Jump to `t` seconds. |
| `key(key)` | Send a key press, such as `"Escape"`, to the [state machines](/docs/features/state-machines). |
| `event(name)` | Send a custom event to the state machines. |
| `machineStates()` | The current state of each machine, such as `{ cta: "hover" }`. |
| `nodeIndex(id)` | The index of a node for `setTransforms`, or `-1`. Ids are expanded ids, such as `"car.3"`. Look them up again after a structural patch. |
| `setTransforms(records, count?)` | Set node transforms directly. See [Runtime Overrides](#runtime-overrides). |
| `setCamera(position, target?, fov?)` | Place the camera directly, replacing the scene camera, moves and shots. `null` restores the scene camera. |
| `adapter()` | The adapter and backend, such as `"NVIDIA ... (BrowserWebGpu)"`. |
| `lastError()` | The last rejected patch or message. |
| `gpuError()` | The first uncaught GPU error or device loss. |
| `destroy()` | Stop the loop, remove listeners and free the engine. |

If the WebGPU device is lost, the player moves the current document to a WebGL2 engine on a fresh canvas and keeps playing. It reports the move through `onError`.

## Runtime Overrides

Games and simulations move many nodes every frame. Patching each one costs a JSON parse. Overrides skip that. Write transform records straight into wasm memory.

```ts title="game.ts"
import { createPlayer, OVERRIDE_LEN } from "@motion-sdk/core"

const player = await createPlayer(canvas, scene, {
  onFrame(dt, p) {
    const car = p.nodeIndex("car")
    x += dt * 4
    p.setTransforms(new Float32Array([car, x, 0, 0, 0, x * 20, 0, 1, 1, 1]))
  },
})
```

Each record is `OVERRIDE_LEN` (10) floats.

| Index | Value |
| --- | --- |
| 0 | Node index from `nodeIndex` |
| 1-3 | Position x, y, z |
| 4-6 | Rotation x, y, z in degrees |
| 7-9 | Scale x, y, z |

Overrides win over the timeline and state machines, and they last until cleared. A `NaN` position x clears that node's override. They never change the scene document, so `validate` and exports don't see them.

## `FrameStats`

| Field | Description |
| --- | --- |
| `drawCalls` | Draw calls last frame. |
| `instances` | Instances drawn. |
| `culled` | Instances skipped by frustum culling. |
| `particles` | Live particles. |
| `textNodes` | Text nodes drawn. |
| `revision` | Patches committed since the scene loaded. |
| `rejected` | Patches rejected. |
| `hovering` | Whether the pointer is over a hit target. |
| `frameMs` | Smoothed time between frames, in ms. |
| `cpuMs` | Smoothed time inside the wasm frame call, in ms. |
| `fps` | Frames per second. |

## Helpers

| Export | Description |
| --- | --- |
| `detectBackend()` | Resolves to `"webgpu"` if the browser gives an adapter, otherwise `"webgl2"`. |
| `needsAuthoring(json)` | Whether scene text uses prefabs, repeats, models, bodies, shatter, 2D shapes, SVG drawings, stylise or pixel art. It's a cheap check that may over-report. |
| `OVERRIDE_LEN` | Floats per override record, `10`. |

## Bundles

Only one bundle is fetched. CI fails if a bundle grows past its cap in `size-limit.json` (set just above today's sizes). `size-budget.json` holds the smaller targets, and a bundle over its target gets a warning.

| Bundle | When | Budget (brotli) |
| --- | --- | --- |
| WebGPU player | Plain scenes | 300 kB |
| WebGPU authoring | Prefabs, repeats, models, bodies, 2D shapes or SVG drawings, or `authoring: true` | 420 kB |
| WebGL2 | No WebGPU adapter | 450 kB |
| JS wrapper | Always | 12 kB gzip |

A scene with templates also plays on the lean player if you expand it first with [`motion-sdk expand`](/docs/reference/cli#expand). See [Runtimes](/docs/concepts/runtimes) and [Performance](/docs/guides/performance).
