---
url: /pawn/docs/guide/headless.md
description: >-
  Running Pawn without a canvas: one scene for the browser and for tests, clicks
  and data from code, physics, and scripts in Node or Bun.
---

# Headless

An engine without a canvas runs everything but the drawing. Systems tick,
behaviors react, feeds apply data, physics steps and picking finds
entities. Only `render` has nothing to draw. So the logic of a scene can
run in `bun test`, in CI or in a Node script, with no browser and no GPU,
and the same code draws in the page.

```ts
const engine = new Engine(); // no canvas, no renderer: headless
```

## What runs without a canvas

| Runs as in the browser | Without a page |
|---|---|
| Systems in every phase, the clock, `engine.after` and `engine.every` | Nothing is drawn; `engine.renderer` is `null`. |
| Behaviors, presets, prefabs, `Spawner`, `Lifetime`, motion, `Health` | `Sound` stays silent, so code that plays sounds runs unchanged. |
| Entity events (`click`, `died`, `wavestart`...) | `Labels` creates no elements; `engine.views.project()` returns `null`. |
| Picking and `Pointer`, driven from code | `Pointer` has no DOM events to follow; move it with `moveTo`, `press` and `release`. |
| Feeds from `@pawnjs/data`, tweens, physics | `Debug` gathers its stats, without an overlay. |
| Snapshots, `engine.random` with a seed | |

## One scene for the page and for tests

Write the scene as a function of the engine: it spawns entities and adds
systems, but leaves the canvas, the views and the loop to whoever calls it.

```ts
// scene.ts
import { Clickable, type Engine, Position, Shape, Spin } from "@pawnjs/core";

export function createScene(engine: Engine) {
  const button = engine.world.spawn(
    Shape({ kind: "box", color: "#6366f1" }),
    Position,
    Spin({ speed: 1 }),
    Clickable,
  );
  let clicks = 0;
  engine.events.on(button, "click", () => {
    clicks++;
  });
  return { button, clicks: () => clicks };
}
```

The page adds a canvas, a view and the loop:

```ts
// main.ts, in the page
import { Engine, View } from "@pawnjs/core";
import { PerspectiveCamera } from "three";
import { createScene } from "./scene";

const engine = new Engine({ canvas });
const camera = new PerspectiveCamera(50, 1, 0.1, 100);
camera.position.set(0, 0, 5);
engine.views.add(new View({ camera }));
engine.fitToElement(canvas);
createScene(engine);
engine.start();
```

A test calls the same function on a headless engine and moves time by
hand. `createTestEngine()` from `@pawnjs/core/testing` is an engine without
a canvas, ticked only by your code, with `engine.random` on a fixed seed;
see [Testing and debugging](./testing.md#test-helpers).

```ts
// scene.test.ts, run with `bun test`
import { Rotation } from "@pawnjs/core";
import { createTestEngine, runFor } from "@pawnjs/core/testing";
import { createScene } from "./scene";

test("the button spins", () => {
  const engine = createTestEngine();
  const { button } = createScene(engine);
  runFor(engine, 1); // one second in frames of 1/60 s
  expect(button.get(Rotation)?.y).toBeCloseTo(Math.sin(0.5));
  engine.dispose();
});
```

The [Defense](https://jakubprill.github.io/pawn/defense.html) example is
built this way: `createGame(engine)` in
`apps/showcase/src/defense/game.ts` holds the whole game, `main.ts` adds
the view, sounds and keys, and `game.test.ts` plays waves to the end
without a browser.

## Clicks from code

Picking works headless too: it needs a view with a camera, not a canvas.
`Pointer` then takes positions as fractions of the canvas (0 to 1, origin
top-left), and presses on an entity become the same `click` events and
`Pressed` tag as in the page:

```ts
import { Pointer, Pressed, View } from "@pawnjs/core";
import { createTestEngine, runFor } from "@pawnjs/core/testing";
import { PerspectiveCamera } from "three";
import { createScene } from "./scene";

const engine = createTestEngine();
const scene = createScene(engine);
const camera = new PerspectiveCamera(50, 1, 0.1, 100);
camera.position.set(0, 0, 5);
engine.views.add(new View({ camera }));

const pointer = engine.plugin(Pointer);
pointer.moveTo(0.5, 0.5); // the middle of the canvas, where the box is
pointer.press();
runFor(engine, 1 / 60);
expect(scene.button.has(Pressed)).toBe(true);
pointer.release();
expect(scene.clicks()).toBe(1);
```

Headless distances, such as how far a press may travel and still click,
are measured on a canvas of `Pointer.HEADLESS_SIZE` (1000) pixels a side;
see [Input](./input.md#pointer).

## Data without a network

A [feed](../packages/data.md) takes deliveries from `push()` as well as
from a source, so a test hands it the data an API would send and steps
until the scene has caught up:

```ts
import { Position } from "@pawnjs/core";
import { createTestEngine, runFor, runUntil } from "@pawnjs/core/testing";
import { Feed, smoothTo } from "@pawnjs/data";

interface Pump {
  id: string;
  x: number;
}

const engine = createTestEngine();
const pumps = new Feed<Pump>({
  key: (pump) => pump.id,
  spawn: (_pump, engine) => engine.spawn(Position),
  update: (entity, pump) => smoothTo(entity, { x: pump.x }),
});
engine.use(pumps);

pumps.push([{ id: "a", x: 0 }, { id: "b", x: 4 }]);
runFor(engine, 1 / 60); // deliveries apply in the next frame
expect(pumps.size).toBe(2);

pumps.push([{ id: "a", x: 10 }]); // "b" is gone from the API
runUntil(engine, () => (pumps.entity("a")?.get(Position)?.x ?? 0) > 9.9);
expect(pumps.entity("b")).toBe(undefined);
```

`runUntil` throws after `timeout` seconds (60 by default), so a scene that
never catches up fails the test instead of hanging it.

In the page the same feed gets a `source`, such as `poll()` or
`websocket()`, and the scene code does not change.

## Physics

`@pawnjs/physics` runs Rapier's WASM build, which loads in Bun and Node as
well. Create it once per test (it is asynchronous) and step as usual:

```ts
import { Position } from "@pawnjs/core";
import { createTestEngine, runFor } from "@pawnjs/core/testing";
import { Collider, createPhysics, RigidBody } from "@pawnjs/physics";

const engine = createTestEngine();
engine.use(await createPhysics());
const ball = engine.world.spawn(
  Position({ y: 5 }),
  RigidBody,
  Collider({ shape: { type: "ball", radius: 0.5 } }),
);
runFor(engine, 1);
expect((ball.get(Position)?.y ?? 5) < 5).toBe(true); // it fell
```

## Outside tests

The packages load in Node's ESM loader as well as in Bun, so a script or
a server can run a scene: simulate ahead, check data before it reaches
users, or prepare a [snapshot](./snapshots.md) that the page restores.

```ts
import { Engine, ManualDriver } from "@pawnjs/core";

const engine = new Engine({ driver: new ManualDriver(), seed: 7 });
// ...build the scene, then simulate ten minutes
// (the snapshot saves the entities that have an EntityId)
for (let i = 0; i < 600 * 30; i++) engine.step(1 / 30);
await writeFile("scene.json", JSON.stringify(engine.snapshot()));
engine.dispose();
```

`engine.step(seconds)` takes the delta as given, so a script can step in
any size of frame; see [Engine and frame](./engine.md#loop-drivers).
