--- url: /pawn/docs/guide/getting-started.md description: What Pawn is, its packages, and a first scene with a spinning cube. --- # Getting started Pawn is a 3D engine for the browser written in TypeScript. It renders with [three.js](https://threejs.org) and keeps game state in a [koota](https://github.com/pmndrs/koota) ECS world: * an **entity** is an id, * a **trait** is data attached to an entity (`Position`, `Visual`, your own), * a **system** is a function the engine runs every frame over the world. ## Packages | Package | What it adds | |---|---| | `@pawnjs/core` | `Engine`, frame phases and systems, transform traits, hierarchy, instancing, views, picking, input and actions, camera rig, labels, glTF models, sound, behaviors, presets, prefabs and `Spawner`, snapshots, `Grid` and `SpatialIndex`, seeded random, `Debug`, test helpers, plugin API | | `@pawnjs/react` | ``, ``, ``, `useEngine`, `useSystem`, `useSpawn`, `useEntityEvent`, `useAssetProgress` | | `@pawnjs/tween` | Tweens of `Position`, `Rotation` and `Scale`, the `TweenOn` behavior | | `@pawnjs/data` | Feeds that keep one entity per item of an API or WebSocket stream, smooth movement | | `@pawnjs/physics` | Rapier rigid bodies and colliders as traits | | `@pawnjs/maps` | The engine drawn into a Google Maps vector map | | `@pawnjs/json-render` | Scenes from a JSON spec of registered prefabs, streamed by an AI model | | `@pawnjs/create` | `bun create @pawnjs`: a new project from a template; `add`: a prefab from the item registry | `koota` is a peer dependency of every package, and `three` of every package except `@pawnjs/data`. ## Create a project `bun create @pawnjs` makes a new project from a template: Vite and TypeScript, a small solar system (planets on orbits to hover, click and follow) with a test of it, and the koota patch described under [Install](#install). ```bash bun create @pawnjs my-scene # TypeScript and Vite bun create @pawnjs my-scene --template react # with @pawnjs/react cd my-scene bun install bun run dev ``` Without a directory or template it asks for them. The project depends on exactly the `@pawnjs` versions released with the command, and `bun run test` runs its scene [headless](./headless). `bun create pawn` does the same. From code, `createProject({ directory, template, name })` from `@pawnjs/create` does the same without asking and resolves to the project's `directory`, `name`, `template` and `@pawnjs` `version`. The directory must be missing or empty. `TEMPLATES` lists the template names (`DEFAULT_TEMPLATE` is `"vanilla"`), `parseTemplate(text)` checks one, and `packageName(text)` turns a directory name into a valid package name (`DEFAULT_NAME` when nothing is left). ### Add a prefab from the registry Pawn.'s item registries hold prefabs to copy into a project, with the modules they import, one beside each example that has one. The [racer's](https://jakubprill.github.io/pawn/racer/) holds `ship`, `sky`, `tower` and `stadium`. Add one in the project's directory, named `/`: ```bash bunx @pawnjs/create add racer/ship ``` Its files go under `src/pawn/` (`src/pawn/racer/ship.ts` and what it imports), as your own code to change. Import `Ship` from `./pawn/racer/ship` and spawn it with `engine.spawn(Ship)`. Everything is checked before a file is written. A file already there with other content stops the add unless you pass `--overwrite`; one with the same content, such as a module two items share, stays as it is. When the item imports a package the project lacks, the command prints the `bun add` to run. shadcn's CLI adds the same items, also to a project without a `components.json`: `npx shadcn@latest add https://jakubprill.github.io/pawn/racer/r/ship.json`. An item can also be a URL or a path to its JSON, or a name alone with `--registry` naming the registry (a URL or a directory) to look it up in. `PAWN_REGISTRIES` lists Pawn.'s registries by name. Items are JSON in [shadcn's registry item format](https://ui.shadcn.com/docs/registry/registry-item-json) (`name`, `dependencies`, and `files` with each one's `path`, `target` and `content`). From code, `addItem({ item, directory, registry, overwrite })` from `@pawnjs/create` does the same and `parseRegistryItem(json)` checks an item's JSON. To serve your own prefabs, `buildRegistry(entries, out, { src, folder })` builds items from their entry modules (`{ name, title, description, roots }`), following their local imports, and writes them with `registry.json`. Their files go in `src/pawn/`, or in `folder` inside it (the racer's use `racer`). ## Install Until 0.1.0 every version is a prerelease (`0.1.0-alpha.N`). Add the package with its peers: ```bash bun add @pawnjs/core koota@0.6.6 three bun add -d @types/three ``` `@types/three` is for TypeScript; [Versions and stability](./stability.md) says why, and what each version promises. `@pawnjs/react`, `@pawnjs/tween` and the starter (`@pawnjs/create`, `create-pawn`) are on npm too. Data, physics, maps and json-render are not published yet. ::: warning Patch koota for big scenes koota 0.6.6 takes time quadratic in the entities destroyed between two queries (20k destroys make a 1.4 s frame). The repository fixes it with [`patches/koota@0.6.6.patch`](https://github.com/jakubprill/pawn/blob/main/patches/koota@0.6.6.patch), which only applies inside the monorepo. In your app, copy the file to `patches/` and list it in `package.json`: ```json { "patchedDependencies": { "koota@0.6.6": "patches/koota@0.6.6.patch" } } ``` That is Bun's format; other package managers need the change in their own. Small scenes run fine without it. ::: To work on the engine itself, clone the repository: ```bash bun install bun run build # builds every package bun run test bunx turbo run dev --filter=pawn-showcase ``` ## Your first scene A canvas, a camera, lights, and a cube that spins: ```ts import { Engine, Shape, Spin } from "@pawnjs/core"; export default function firstScene(canvas: HTMLCanvasElement): Engine { canvas.style.cssText = "display:block;width:100%;height:100%"; const engine = new Engine({ canvas, camera: { position: { y: 2, z: 5 } }, background: "#09090b", lights: "studio", }); engine.spawn(Shape({ kind: "box", color: "#6366f1" }), Spin({ speed: 1.5 })); engine.start(); return engine; } ``` Call it with a canvas that has a CSS size, for example `firstScene(document.querySelector("canvas")!)`. The scene above runs this very file. What happens here: * `new Engine({ canvas })` creates a `WebGLRenderer` for the canvas and a new koota world (`engine.world`). Without a canvas the engine runs headless. * `camera` adds a view that draws a perspective camera into the whole canvas, looking at the origin. Without it nothing is drawn until you add a view yourself (see [Views](./views)). * `background` is the color the canvas is cleared to, and `lights: "studio"` spawns a soft hemisphere light and a sun as `Light` entities. * The drawing buffer follows the canvas's CSS size, also when the canvas resizes. The canvas needs a CSS size, as above, or it would grow with its own drawing buffer. * `engine.spawn(...)` spawns an entity into the world. `Shape` gives it a mesh described by data, and `Spin` is a behavior that turns it. * `engine.start()` ticks the engine on every `requestAnimationFrame`. Your own traits and systems take over where the built-in ones end: see [Entities and systems](./entities). When you are done, `engine.dispose()` stops the loop and releases what the engine created. Geometries and materials of your own `Visual`s stay yours; `disposeObject3D(root)` frees them. ## Next * [Engine and frame](./engine): phases, the clock and loop drivers. * [Entities and systems](./entities): traits, queries and the transform traits. * [Headless](./headless): the same scene in tests and scripts, without a page. * [@pawnjs/react](../packages/react): the same scene as React components. ## Docs for AI agents These docs are also published as plain Markdown for coding agents and LLM tools: [`llms.txt`](../llms.txt){target="\_self"} lists every page with a one-line summary, and [`llms-full.txt`](../llms-full.txt){target="\_self"} holds all pages in one file. Every page has a Markdown copy at the same path with `.md` in place of `.html`, and the **Copy page** button under each page title copies it or opens it in ChatGPT or Claude. Every `@pawnjs` library package also ships [For coding agents](./agents.md) as `AGENTS.md`, and a project made with `bun create @pawnjs` has an `AGENTS.md` and a `CLAUDE.md` that point agents to it. --- --- url: /pawn/docs/guide/engine.md description: Creating an Engine, frame phases, systems, the clock and loop drivers. --- # Engine and frame `Engine` runs one koota world: it ticks systems phase by phase and draws the scene into every view. ## Creating an engine ```ts import { Engine } from "@pawnjs/core"; const engine = new Engine({ canvas, // creates a WebGLRenderer for this canvas // renderer, // or pass your own WebGLRenderer // enableTransparency: true // page shows through where no view draws // pixelRatio: 1 // defaults to devicePixelRatio // driver, // when to tick; defaults to RafDriver // enablePauseWhenHidden: false, // keep ticking while the page is hidden // onContextLost, onContextRestored, // the GPU dropped the WebGL context // world, // an existing koota world; defaults to a new one // seed: 42, // seed for engine.random, so runs repeat // camera: { position: { y: 2, z: 5 } }, // a full-canvas view // background: "#09090b", // clear color of the canvas // lights: "studio", // hemisphere light and a sun // toneMapping: "aces", exposure: 1, // how bright colors fit the screen // enableShadows: true, // lights with enableShadow cast them // environment: "room", // reflections and light all around // fit: false, // the drawing buffer follows the canvas; false for none // fixedTimeStep, maxDelta, maxFixedSteps, timeScale (clock options) }); ``` | Option | Default | Meaning | |---|---|---| | `canvas` | | Canvas to create a renderer for. Ignored when `renderer` is given. | | `renderer` | | Renderer to draw with. Without `canvas` and `renderer` the engine runs headless. | | `enableTransparency` | `false` | Whether a renderer the engine creates has a transparent canvas. | | `pixelRatio` | `devicePixelRatio` | Pixel ratio for a renderer the engine creates. | | `driver` | `new RafDriver()` | Decides when the engine ticks. | | `enablePauseWhenHidden` | `true` | Whether a started engine stops its driver while the page is hidden, and starts it again when the page shows; see [Lifecycle](#lifecycle). | | `onContextLost` | | Called when the renderer's WebGL context is lost; see [Without WebGL](#without-webgl). | | `onContextRestored` | | Called when a lost WebGL context is restored. | | `world` | new world | World to run on. A world the engine creates is destroyed on `dispose()`. A world belongs to one engine: pass a world made earlier, not one another engine runs. | | `seed` | new each time | Seed for `engine.random`; see [Testing and debugging](./testing#random-numbers-from-a-seed). | | `camera` | | A three.js camera, or `{ position, target, fov, near, far }` for a perspective one. Adds a full-canvas view named `"main"`. | | `background` | | Color the canvas is cleared to, for a renderer the engine creates. | | `lights` | `false` | `"studio"` spawns a hemisphere light and a sun from above, front right, as [`Light`](./entities#light) entities. | | `toneMapping` | `"none"` | How a renderer the engine creates brings bright colors into the screen's range: `"neutral"` keeps colors as given (dashboards), `"aces"` is filmic with strong contrast (games), `"agx"` rolls highlights off softly, `"none"` clips them. | | `exposure` | `1` | Brightness before tone mapping, for a renderer the engine creates. | | `enableShadows` | `false` | Whether a renderer the engine creates draws shadows. | | `environment` | | What the scene reflects and is lit by all around, for any renderer: `"room"` for a neutral studio, or a panorama texture of your own (e.g. a loaded HDR). | | `fit` | `true` | Element whose size the drawing buffer follows (see `fitToElement` below): `true` for the canvas, `false` for none. Only for a renderer the engine creates. | ### How the scene looks Three options make a scene look finished: tone mapping, shadows and an environment for metal and glossy surfaces to reflect. ```ts import { Engine, Light, Position, Shape } from "@pawnjs/core"; const engine = new Engine({ canvas, camera: { position: { y: 3, z: 8 } }, toneMapping: "aces", enableShadows: true, environment: "room", lights: "studio", // its sun casts shadows }); engine.spawn(Shape({ kind: "torus", metalness: 1, roughness: 0.2 }), Position({ y: 1 })); ``` Shapes and models cast and receive shadows; a light casts them with `enableShadow` (see [`Light`](./entities#light)). Settings of the renderer apply to one the engine creates; a renderer of your own keeps its own. To change them later, set them on `engine.renderer` (`toneMapping`, `toneMappingExposure`; materials drawn before shadows were turned on need `needsUpdate` to show them), and on `engine.scene` for the environment (`environment`, `environmentIntensity`). A panorama may still be loading: it shows once it has. A material with its own `envMap` reflects that at its own `envMapIntensity` instead. Camera options default to `{ x: 0, y: 2, z: 6 }` for `position`, the origin for `target`, a `fov` of 50 degrees, `near` 0.1 and `far` 1000. The view's camera is `engine.views.first.camera`; [`CameraRig`](./camera) moves it. The engine exposes `engine.world` (koota `World`), `engine.scene` (three.js `Scene`), `engine.clock`, `engine.random` (seeded random numbers), `engine.renderer` (or `null` when headless) and `engine.views` (the [views](./views#the-views-of-an-engine) and where they are). `engine.spawn` spawns an entity: from traits, the same as `engine.world.spawn(...traits)`, or from a [prefab](./prefabs.md) or the name it is registered under, with overrides (`engine.spawn(Tower, { position: { x: 2 } })`). ## Lifecycle ```ts engine.start(); // starts ticking through the driver engine.stop(); // stops; the pause is not counted as time engine.dispose(); // stops, runs plugin cleanups, destroys what the engine created ``` While the page is hidden (another tab, a minimized window), a started engine stops its driver and starts it again when the page shows; the pause is not counted as time, and `engine.running` stays `true`. Set `enablePauseWhenHidden: false` for a scene that must keep ticking hidden, such as one that records or streams. `dispose()` destroys the world and renderer only if the engine created them. A disposed engine throws on `use`, since a plugin's cleanup would never run. Geometries and materials of your entities belong to you; release them with `disposeObject3D(root)`. `engine.setSize(width, height, updateStyle = true)` resizes the drawing buffer in CSS pixels. Pass `false` as the third argument when CSS already sizes the canvas. `engine.fitToElement(element, onResize?)` keeps the drawing buffer the size of an element (`clientWidth` by `clientHeight`, so padding counts), usually the canvas's container, now and whenever it resizes. It leaves the canvas's CSS size alone, so give the canvas `width: 100%; height: 100%`; a canvas without a CSS size would grow with its own drawing buffer. `onResize(width, height)` runs after each resize, for example to reframe a camera for a new aspect. It returns a function that stops following; `dispose()` stops it too. Elements with no size (hidden) are skipped. The first call takes over from the `fit` option, so the engine no longer follows the canvas then. ```ts engine.fitToElement(container, (width, height) => { camera.position.z = width < height ? 8 : 5; }); ``` ### Without WebGL `new Engine({ canvas })` throws `WebGLUnavailableError` when the browser gives the canvas no WebGL context: the GPU is turned off or blocked, as in a virtual machine, over remote desktop or in a WebView without hardware acceleration. Catch it to show a page without 3D (in React, an error boundary around `` catches it); the browser's error is its `cause`. ```ts try { const engine = new Engine({ canvas, onContextLost: showFallback, // the GPU reset or the browser took it back onContextRestored: hideFallback, }); engine.start(); } catch (error) { if (error instanceof WebGLUnavailableError) showFallback(); else throw error; } ``` A context can also be lost later. Until it is restored the engine draws nothing, but systems keep running, so the scene is current when it comes back; `engine.contextLost` tells the state. After a restore three.js uploads geometries and textures again, and the engine remakes the `"room"` environment; a render target of your own must be drawn again. A renderer of your own is followed the same way, and a host that swaps in a new renderer with `setRenderer` (as `@pawnjs/maps` does after a loss) restores the engine with it. ## The frame Every tick runs these phases in order, then draws the views: 1. `input`: queued input events are applied first (see [Input](./input)). 2. `fixedUpdate`: zero or more times, each with the constant `fixedTimeStep`. Physics steps here. 3. `update`: game logic. The default phase for systems. 4. `lateUpdate`: logic that must see the results of `update`, such as following one entity with another. 5. `render`: the engine's scene sync runs first here (order `Engine.SCENE_SYNC_ORDER`), copying transforms into three.js objects and instance matrices; the camera rig and labels run after it. After the phases, the engine draws every enabled view. `PHASES` lists the phase names in this order, and `Phase` is their type. ## Systems A system is a function that receives a `FrameContext`: ```ts import type { System } from "@pawnjs/core"; const gravity: System = ({ world, delta, elapsed, frame, engine }) => { // ... }; const remove = engine.addSystem(gravity, { phase: "fixedUpdate", order: 10 }); remove(); // unregisters it ``` | Field | Meaning | |---|---| | `engine` | The engine. | | `world` | The koota world. | | `delta` | Seconds since the previous call of this phase; constant in `fixedUpdate`. | | `unscaledDelta` | Real seconds since the previous frame, before `clock.timeScale`; the same in every phase and above 0 while time is paused, for what keeps moving then (camera controls, a debug overlay). | | `elapsed` | Scaled seconds since the engine started. | | `frame` | Frame counter. | Within a phase, a lower `order` runs first (default `0`); ties keep the order of registration. Systems may add or remove systems while a phase runs. The context object is reused between calls, so do not keep a reference to it. ### Easing toward a moving goal To follow something that keeps moving (a target, a value from a feed), cover a share of the remaining way each frame. `easeByHalfLife(delta, halfLife)` gives that share for a half-life, the seconds to cover half the way, so the motion looks the same at any frame rate; a half-life of 0 jumps straight there. The camera rig, the chase camera and smoothing use it too. ```ts const follow: System = ({ delta }) => { marker.position.lerp(goal, easeByHalfLife(delta, 0.2)); }; ``` ## Timers `engine.after(seconds, callback)` runs a callback once after a delay and `engine.every(seconds, callback)` on an interval. Both return a function that cancels the timer: ```ts engine.after(0.6, () => engine.spawn(Fruit)); const stop = engine.every(1, () => engine.spawn(Balloon)); stop(); ``` Timers count scaled engine time, so a paused clock (`timeScale` 0) holds them and `engine.step()` drives them in tests. They run at the start of the `update` phase (order `Engine.TIMERS_ORDER`), earliest first; a frame longer than an interval runs it once per interval passed. `every` needs an interval above 0, and `dispose()` cancels every timer. ## Scopes `engine.scope()` creates a `Scope`: a group of entities and timers that end together, such as one level of a game or one screen of a dashboard. `dispose()` destroys its entities with their children and cancels its timers; the rest of the world (camera, lights, UI entities) stays. A restart is disposing the scope and building a new one: ```ts let level = engine.scope(); build(level); function build(level: Scope) { level.spawn(Tower, { position: { x: 2 } }); level.spawn(Position, Shape({ kind: "box" })); level.after(3, startWave); } function restart() { level.dispose(); level = engine.scope(); build(level); } ``` * `spawn` takes what `engine.spawn` takes (traits, or a prefab or its name with overrides and `{ parent, id }`) and spawns into the scope; `add(entity)` moves an existing entity in from another scope or none. * `after` and `every` work like the engine's and end with the scope. * `has(entity)`, `entities()` and `Scope.of(entity)` tell what belongs where; a [`Spawner`](./prefabs.md#spawner) puts what it spawns in its own scope. * A disposed scope throws when asked to spawn or start a timer. * `engine.dispose()` disposes the scopes still live, in a world of your own too. ## Clock `engine.clock` turns host timestamps into frame deltas: | Property | Default | Meaning | |---|---|---| | `fixedTimeStep` | `1 / 60` | Step of the `fixedUpdate` phase, in seconds. | | `maxDelta` | `0.1` | Upper bound for one driver frame's delta (for example after a long stall). | | `maxFixedSteps` | `5` | Upper bound for fixed steps in one frame; excess time is dropped. | | `timeScale` | `1` | Multiplier for every delta; `0` pauses simulation time. | These are writable at runtime (`engine.clock.timeScale = 0.5`). `clock.alpha` is the progress between the last and the next fixed step (0 to 1), for interpolating visuals of a fixed-step simulation. `Clock` is also exported, for timing a loop of your own outside an engine (an engine's own clock is advanced by the engine; don't advance it yourself): `advance(timeMs)` turns a host timestamp into a delta bounded by `maxDelta`, `advanceBy(seconds)` takes an explicit one, `consumeFixedSteps()` returns the fixed steps now due, and `clearTimestamp()` keeps a pause out of the next delta. ## Loop drivers A `LoopDriver` decides when the engine ticks: * `RafDriver` (default) ticks on every `requestAnimationFrame`. * `ManualDriver` ticks only when you call `driver.advance(ms)`. Use it in tests or when another loop owns the timing. * `DemandDriver` draws only when something changed; see [Render on demand](#render-on-demand). * `MapOverlay` from [@pawnjs/maps](../packages/maps) ticks on the map's draws. Without any driver, `engine.step(seconds)` runs one frame with an explicit delta. The delta is taken as given: `maxDelta` and `maxFixedSteps` bound only driver frames, so `engine.step(0.5)` advances half a second and runs every fixed step in it: ```ts const engine = new Engine(); // headless: no canvas, no renderer engine.world.spawn(Position); engine.step(1 / 60); ``` A custom driver implements two methods: ```ts import type { LoopDriver, TickCallback } from "@pawnjs/core"; class MyDriver implements LoopDriver { start(tick: TickCallback) { /* call tick(timeMs) whenever a frame is due */ } stop() { /* stop calling tick */ } } ``` A driver with an `invalidate()` method ticks on demand: the engine calls it when it needs a tick, and draws only the frames where something drawn changed. ### Render on demand A scene that stays open all day (a dashboard, a digital twin) does not need to draw 60 times a second while nothing moves. `DemandDriver` draws a frame only when something drawn changed, then keeps drawing on `requestAnimationFrame` while it goes on changing. In between it ticks every `idleInterval` seconds (0.08 by default) without drawing, so timers, feeds and gamepads keep going while the GPU rests. ```ts const engine = new Engine({ canvas, driver: new DemandDriver() }); engine.start(); // A change the engine cannot see: a three.js object changed by hand. material.color.set("#f59e0b"); engine.invalidate(); ``` The engine asks for a frame by itself when: * an entity's `Position`, `Rotation` or `Scale` changes, so motion behaviors, tweens, physics and feeds draw as they move; * a `Visual`, `Instance`, `Shape`, `Light` or `Tint` is added, changed or removed, or an entity is spawned under or taken from a parent; * a view's camera moves, turns or changes its projection (`CameraRig`, `ChaseCamera`), or a view moves or resizes (a view following an element, as the page scrolls); * the canvas resizes, the renderer changes or a lost WebGL context comes back. Input (pointer, keys, wheel, on-screen buttons, device tilt) and page scrolls tick at once, and draw only when what they do changes something above: moving the mouse over a still scene draws nothing. Gamepads are read on the ticks there are. A timer runs on any tick; what it changes in traits is drawn like any other change. A change smaller than a millionth (of a unit, or of a quaternion part) asks for no frame, so motion slower than that per tick waits for the next drawn frame. Call `engine.invalidate()` after anything else you change yourself: a material, a geometry, a texture that finished loading, a `Visual` moved through three.js instead of its traits. With other drivers it does nothing. A change found by a slow tick shows within `idleInterval`; keep that below `clock.maxDelta`, or engine time falls behind. --- --- url: /pawn/docs/guide/entities.md description: >- Spawning entities with traits, the transform traits, Visual, Shape, Light, Tint and Link, writing systems. --- # Entities and systems Pawn keeps all game state in a [koota](https://github.com/pmndrs/koota) world, `engine.world`. This page covers what pawn adds on top; see koota's documentation for its full API (queries, relations, `koota/react`). ## Spawning and changing entities ```ts import { Position, Rotation, Scale, Visual } from "@pawnjs/core"; const entity = engine.spawn( Position({ x: 1 }), // missing fields keep their defaults Rotation, // default value: identity Visual(mesh), ); entity.set(Position, { x: 2, y: 0, z: 0 }); entity.add(Scale({ x: 2, y: 2, z: 2 })); entity.remove(Scale); entity.destroy(); ``` `set` needs the entity to have the trait already. When it may not, `put(entity, trait, value)` sets the trait, adding it first if missing: ```ts import { put, Tint } from "@pawnjs/core"; put(entity, Tint, { color: "#ef4444", amount: 0.5 }); ``` ## Transform traits | Trait | Fields | Meaning | |---|---|---| | `Position` | `x, y, z` | Position relative to the parent, or to the world for roots. | | `Rotation` | `x, y, z, w` | Rotation as a unit quaternion, relative to the parent. Default `w: 1`. | | `Scale` | `x, y, z` | Scale per axis, relative to the parent. Default `1`. | Two helpers make values for them: `euler({ x, y, z })` turns angles in radians (around x, then y, then z) into a quaternion, and `uniform(n)` is the same scale on all three axes. ```ts import { euler, Rotation, Scale, Shape, uniform } from "@pawnjs/core"; engine.spawn(Shape, Rotation(euler({ y: Math.PI / 4 })), Scale(uniform(0.5))); ``` They are stored as structure of arrays, so systems over many entities stay fast. Write them from your systems; the engine copies them into three.js objects at the start of the `render` phase. Each trait is copied only when the entity has it: an entity without `Position` keeps whatever position its `Visual` object has. ## Visual `Visual(object)` is the three.js object drawn for the entity, any `Object3D`: a mesh, a light, a group. The engine: * adds it to `engine.scene` when the trait is added (or under the parent's visual, see [Hierarchy](./hierarchy)) and removes it when the trait is removed or the entity is destroyed, * swaps the object when you `entity.set(Visual, other)`, * tags it with `userData.entity`, so [picking](./views#picking) finds the entity. For thousands of similar objects use [`Instance`](./instancing) instead. ## Shape `Shape` draws a plain shape as the entity's `Visual`, described by data alone, so it can be saved where an `Object3D` cannot: ```ts import { Position, Scale, Shape } from "@pawnjs/core"; world.spawn(Shape({ kind: "sphere", color: "#f59e0b" }), Position, Scale); entity.set(Shape, { color: "#22c55e" }); ``` `kind` is `"box"`, `"sphere"`, `"cylinder"`, `"cone"`, `"capsule"`, `"torus"` or `"plane"`. Every kind fits a 1 × 1 × 1 box around the origin (the plane lies flat, facing up; the torus stands upright, facing +z); size it with `Scale`. The mesh comes with `Shape` and goes with it. An entity that already has a `Visual` keeps it. | Param | Default | Meaning | |---|---|---| | `kind` | `"box"` | Shape drawn. | | `color` | `"#ffffff"` | CSS color. | | `roughness` | `1` | From 0 (mirror) to 1 (matte). | | `metalness` | `0` | From 0 to 1. | | `emissive` | `"#000000"` | Color the shape glows with, unlit. | | `opacity` | `1` | From 0 (invisible) to 1 (opaque). | | `enableInstancing` | `false` | Draw as an instance of a shared batch. | With `enableInstancing: true`, shapes of a kind are drawn as instances of one shared batch instead of a mesh each, so thousands of them cost one draw call; see [Instancing](./instancing.md#instanced-shapes). Instances of a kind share one material: each keeps its own `color`, but `roughness`, `metalness`, `emissive` and `opacity` are not applied to them. A shape with measures of its own (a flat ring with an inner radius, an arc of a gauge) is a [prefab with a visual](./prefabs.md#rebuilding-the-look): a trait holds the measures, so snapshots save them, and `rebuildOn` draws it again when they change. ```ts import { definePrefab, defineTrait, disposeObject3D, Position } from "@pawnjs/core"; import { Mesh, MeshStandardMaterial, RingGeometry } from "three"; const Arc = defineTrait({ name: "arc", params: { innerRadius: { default: 0.35, min: 0 }, thetaStart: { default: 0 }, thetaLength: { default: Math.PI, min: 0 }, color: { default: "#3fd2e8" }, }, }); const Gauge = definePrefab({ name: "gauge", traits: [Position, Arc], visual: (entity) => { const arc = entity.get(Arc); const geometry = new RingGeometry( arc?.innerRadius, 0.5, 48, 1, arc?.thetaStart, arc?.thetaLength, ).rotateX(-Math.PI / 2); // flat, like the plane return new Mesh(geometry, new MeshStandardMaterial({ color: arc?.color })); }, rebuildOn: [Arc], disposeVisual: disposeObject3D, }); engine.prefabs.register(Gauge); // so snapshots save and restore it const gauge = engine.spawn(Gauge); gauge.set(Arc, { thetaLength: Math.PI / 3 }); ``` ## Light `Light` is a light described by data, like `Shape`: the engine makes the three.js light as the entity's `Visual`, keeps it in step with the params and takes it away with the trait. ```ts import { Light, Position } from "@pawnjs/core"; engine.spawn(Light({ kind: "hemisphere", intensity: 1, groundColor: "#334155" })); engine.spawn(Light({ kind: "directional", intensity: 2 }), Position({ x: 5, y: 10, z: 7 })); ``` | Param | Default | Meaning | |---|---|---| | `kind` | `"directional"` | `"ambient"`, `"hemisphere"`, `"directional"`, `"point"` or `"spot"`. | | `color` | `"#ffffff"` | CSS color. | | `intensity` | `1` | Brightness. | | `groundColor` | `"#444444"` | Hemisphere: color of the light from below. | | `distance` | `0` | Point and spot: range in units; 0 for no limit. | | `angle` | `π / 6` | Spot: half-angle of the cone, in radians. | | `enableShadow` | `false` | Directional, point and spot: casts shadows when the engine draws them (`enableShadows`). | | `shadowSize` | `10` | Directional: half the side of the square around the origin it shadows, in units. | `ambient` and `hemisphere` light everything evenly. `directional` and `spot` shine from the entity's `Position` toward the origin, and `point` all around its `Position`. `new Engine({ lights: "studio" })` spawns two of them for you; its sun casts shadows when the engine draws them. ## Tint `Tint` gives one entity its own color, blended toward `color` by `amount` (0 to 1): ```ts import { Tint } from "@pawnjs/core"; entity.add(Tint({ color: "#6366f1", amount: 0.4 })); entity.set(Tint, { color: "#6366f1", amount: 0.8 }); entity.remove(Tint); // back to the original look ``` An instance gets an instance color. A `Visual` gets copies of its materials while tinted, so other entities that share them, such as clones of the same glTF model, keep their look. Visuals of `ChildOf` children are not tinted with their parent. ## Link `Link` draws a tube between two entities, named by their [`EntityId`](/guide/snapshots), such as pipes between machines or edges of a network. The tube follows its ends as they move and hides while either end is missing, so the ends can be spawned before or after the link, and again later. ```ts import { EntityId, Link, Position, Shape } from "@pawnjs/core"; engine.spawn(EntityId({ id: "pump" }), Shape, Position({ x: -2 })); engine.spawn(EntityId({ id: "tank" }), Shape, Position({ x: 2, y: 1 })); const pipe = engine.spawn(Link({ from: "pump", to: "tank", color: "#38bdf8" })); pipe.set(Link, { width: 0.1, opacity: 0.6 }); ``` | Param | Default | Meaning | |---|---|---| | `from`, `to` | `""` | `EntityId` of each end. | | `color` | `"#ffffff"` | CSS color. | | `width` | `0.05` | Thickness of the tube, in units. | | `opacity` | `1` | From 0 (invisible) to 1 (opaque). | The link is an entity of its own with the tube as its `Visual`, so `Hoverable`, `Clickable` and `Tint` work on it as on any look. The `Links` plugin, installed with the first `Link`, places its `Position`, `Rotation` and `Scale` in world space: spawn links without a parent. A link is not picked while it is hidden, and a `Visual` you set on the entity wins over the tube. Snapshots save links by their ends' ids. ## Your own traits and systems Define data with koota's `trait()` and logic as a `System`: ```ts import { Position, type System } from "@pawnjs/core"; import { trait } from "koota"; const Velocity = trait({ x: 0, y: 0, z: 0 }); const move: System = ({ world, delta }) => { world.query(Velocity, Position).updateEach(([v, p]) => { p.x += v.x * delta; p.y += v.y * delta; p.z += v.z * delta; }); }; engine.addSystem(move); engine.world.spawn(Position, Velocity({ x: 1, y: 0, z: 0 }), Visual(mesh)); ``` See [Engine and frame](./engine#systems) for phases and ordering. --- --- url: /pawn/docs/guide/hierarchy.md description: Parenting entities with ChildOf and reading world positions. --- # Hierarchy `ChildOf(parent)` makes an entity the child of another: ```ts import { ChildOf, Position, Rotation, Visual } from "@pawnjs/core"; const ship = engine.world.spawn(Position, Rotation, Visual(hull)); const turret = engine.world.spawn( Position({ x: 0, y: 1, z: 0 }), Rotation, Visual(gun), ChildOf(ship), ); ``` * The child's `Position`, `Rotation` and `Scale` become relative to the parent. * The child's `Visual` is nested under the parent's `Visual`, so three.js composes world transforms. * An entity has at most one parent. Adding another `ChildOf` reparents it, keeping its local transform (so its world pose changes). * Removing `ChildOf` moves the child's visual back to the scene root. * Destroying a parent destroys its children. * A relation that would create a cycle is removed with a warning. A parent without a `Visual` gets an empty `Group` as its visual, so its children have something to hang from. Give it a mesh later with `parent.set(Visual, mesh)` (`add` keeps the existing value). A pivot without a visual is a handy way to orbit things. The [Solar example](https://jakubprill.github.io/pawn/solar.html) spins a pivot and puts a planet at a distance on it: ```ts const pivot = engine.world.spawn(Rotation, Spin({ speed }), ChildOf(center)); const anchor = engine.world.spawn(Position({ x: distance }), ChildOf(pivot)); engine.world.spawn(Visual(planet), ChildOf(anchor)); ``` Here a pivot carries a planet around the sun, and the planet's own spin carries its moon: ```ts import { ChildOf, Engine, Position, Scale, Shape, Spin, View, } from "@pawnjs/core"; import { AmbientLight, DirectionalLight, PerspectiveCamera } from "three"; export default function hierarchy(canvas: HTMLCanvasElement): Engine { canvas.style.cssText = "display:block;width:100%;height:100%"; const engine = new Engine({ canvas }); const { world } = engine; engine.scene.add(new AmbientLight(0xffffff, 0.8)); const light = new DirectionalLight(0xffffff, 2); light.position.set(3, 6, 5); engine.scene.add(light); const sun = world.spawn( Shape({ kind: "sphere", color: "#fbbf24" }), Position, Scale({ x: 1.2, y: 1.2, z: 1.2 }), ); // A spinning pivot carries the planet around the sun... const orbit = world.spawn(Spin({ speed: 0.6 }), ChildOf(sun)); const planet = world.spawn( Shape({ kind: "sphere", color: "#6366f1" }), Position({ x: 2.2 }), Scale({ x: 0.5, y: 0.5, z: 0.5 }), Spin({ speed: 1 }), ChildOf(orbit), ); // ...and the planet's own spin carries its moon. Transforms are relative // to the parent, so the moon follows both turns and the planet's scale. world.spawn( Shape({ kind: "sphere", color: "#e2e8f0" }), Position({ x: 1.6 }), Scale({ x: 0.6, y: 0.6, z: 0.6 }), ChildOf(planet), ); const camera = new PerspectiveCamera(45, 1, 0.1, 100); camera.position.set(0, 3, 4.5); camera.lookAt(0, 0, 0); engine.views.add(new View({ camera, background: 0x09090b })); engine.fitToElement(canvas); engine.start(); return engine; } ``` ## World position `worldPositionOf(entity, target)` writes an entity's world position into a `Vector3` and returns whether it has one. It reads the `Visual` once that is in the scene, so `ChildOf` parents are composed. An entity without one (a data-only entity, in a headless test or a feed) has its `Position`, `Rotation` and `Scale` composed with its parents' up `ChildOf` instead, so it lands where a drawn one would. Visuals are synced at the start of the `render` phase, so call it in `render` (after `Engine.SCENE_SYNC_ORDER`) for this frame's position; `Labels` and `CameraRig` do. ```ts import { worldPositionOf } from "@pawnjs/core"; import { Vector3 } from "three"; const point = new Vector3(); if (worldPositionOf(turret, point)) aimAt(point); ``` ## Limits * Instances (`Instance`) are drawn in world space and ignore `ChildOf`. * Physics bodies work in world space and belong on root entities. * Entities without a `Visual` have no stored world transform: `worldPositionOf` composes it on each call, walking up the parents. --- --- url: /pawn/docs/guide/space.md description: >- Finding entities near a point (SpatialIndex) and mapping board cells to world points with Grid. --- # Grids and spatial queries Two helpers for where things are on the ground: finding the entities within reach of a point, and turning the cells of a board into world points and back. Distances are measured between [world positions](./hierarchy.md#world-position), so `ChildOf` children count where they are drawn. ## Entities near a point `SpatialIndex` finds the entities with a trait whose world position is within `radius` of a world-space point, nearest first, e.g. the enemies a tower reaches or the vehicles near a stop. It keeps a hash grid, so it stays fast for thousands of entities and many queries a frame: ```ts import { SpatialIndex } from "@pawnjs/core"; engine.use(new SpatialIndex({ cellSize: 2 })); // optional; plugin() installs one const [target] = engine.plugin(SpatialIndex).near(tower, 2.5, Enemy); ``` * The grid of a trait is built on its first query in a frame and reused by the frame's later queries, so positions are as of that first query. Entities that get or lose the trait count at once. * `cellSize` (2 by default) works best close to the usual query radius. A radius much wider than a cell checks every entity. * With 100,000 entities and 100 queries a frame, `near` takes about 33 ms where checking every entity takes about 1.2 s (`bun run bench` in `packages/core`, headless). ## Grids `Grid` maps the cells of a board on the ground (the xz plane) to world points and back, such as the tiles of a game or the slots of a warehouse. Columns run along x, rows along z, and the grid is centered on `center`: ```ts import { Grid } from "@pawnjs/core"; const grid = new Grid({ columns: 12, rows: 8, size: 1 }); tower.set(Position, grid.toWorld(3, 2, 0.5)); // middle of the cell, y 0.5 grid.fromWorld(hit.point); // { column, row }, or undefined off the grid grid.contains(12, 0); // false grid.line([{ column: 0, row: 1 }, { column: 3, row: 1 }]); // 4 cells for (const { column, row } of grid.cells()) spawnTile(column, row); ``` `line(corners)` lists the cells along straight lines (across, down or diagonal) through corner cells, such as a road; `key(column, row)` gives `"column,row"` for maps and sets. A `Grid` is plain math and spawns nothing. --- --- url: /pawn/docs/guide/instancing.md description: >- Drawing thousands of entities as one InstancedMesh with Instance and InstanceBatch. --- # Instancing A `Visual` per entity means one `Object3D` and usually one draw call each. For thousands of similar entities, draw them as instances of one `InstancedMesh` instead: ```ts import { Instance, InstanceBatch, Position } from "@pawnjs/core"; import { Color, IcosahedronGeometry, MeshStandardMaterial } from "three"; // One batch, one draw call, however many entities point at it. const batch = new InstanceBatch({ geometry: new IcosahedronGeometry(0.1), material: new MeshStandardMaterial(), capacity: 10_000, // optional; grows by doubling when full (default 1024) }); const color = new Color(); for (let i = 0; i < 10_000; i++) { const entity = engine.world.spawn( Position({ x: engine.random.range(0, 10), y: 0, z: engine.random.range(0, 10) }), Instance(batch), ); batch.setColor(entity, color.setHSL(i / 10_000, 0.8, 0.6)); } ``` Here 4,900 boxes of one batch ride a wave, in one draw call: ```ts import { Engine, Instance, InstanceBatch, Position, type System, View, } from "@pawnjs/core"; import { trait } from "koota"; import { AmbientLight, BoxGeometry, Color, DirectionalLight, MeshStandardMaterial, PerspectiveCamera, } from "three"; const SIDE = 70; // 4,900 boxes, one draw call /** Where an entity sits on the floor, for the wave. */ const Cell = trait({ x: 0, z: 0 }); const wave: System = ({ world, elapsed }) => { world.query(Cell, Position).updateEach(([cell, position]) => { const d = Math.hypot(cell.x, cell.z); position.y = Math.sin(d * 0.35 - elapsed * 2.5) * 0.6; }); }; export default function instancing(canvas: HTMLCanvasElement): Engine { canvas.style.cssText = "display:block;width:100%;height:100%"; const engine = new Engine({ canvas }); engine.addSystem(wave); engine.scene.add(new AmbientLight(0xffffff, 0.6)); const sun = new DirectionalLight(0xffffff, 2); sun.position.set(5, 10, 3); engine.scene.add(sun); const batch = new InstanceBatch({ geometry: new BoxGeometry(0.8, 0.8, 0.8), material: new MeshStandardMaterial(), capacity: SIDE * SIDE, }); const color = new Color(); for (let i = 0; i < SIDE; i++) { for (let j = 0; j < SIDE; j++) { const x = i - SIDE / 2; const z = j - SIDE / 2; const box = engine.world.spawn( Position({ x, z }), Cell({ x, z }), Instance(batch), ); batch.setColor(box, color.setHSL(0.6 + (i + j) / (SIDE * 8), 0.7, 0.6)); } } const camera = new PerspectiveCamera(45, 1, 0.1, 200); camera.position.set(0, 30, 45); camera.lookAt(0, -4, 0); engine.views.add(new View({ camera, background: 0x09090b })); engine.fitToElement(canvas); engine.start(); return engine; } ``` * Adding `Instance` also adds `Position`, `Rotation` and `Scale` when missing. Keep them while the entity is instanced. * The engine writes instance matrices from the transform traits in the `render` phase; no `Object3D` exists per entity. * `batch.setColor(entity, color)` sets a per-instance color, multiplied with the material color. New instances start white; `batch.getColor(entity, target)` reads it back. * `batch.setMatrix(entity, matrix)` writes an instance's matrix at once (for picking before the next render); the next render writes it again from the transform traits. `batch.indexOf(entity)` and `batch.entityAt(index)` map between entities and instance indices, e.g. for a raycast hit's `instanceId`. * The batch's mesh joins the scene with its first entity and leaves it when the batch empties. Settings on `batch.mesh` (shadows, for example) survive growth. * Picking maps the hit instance back to its entity, like a `Visual`. * Use either `Instance` or `Visual` on an entity, not both. * Instances are drawn in world space and ignore `ChildOf`. Geometry and material belong to you. `batch.dispose()` releases only the batch's own instance buffers. ## Instanced shapes A [`Shape`](./entities.md#shape) with `enableInstancing` is drawn as an instance without a batch of your own: the engine keeps one batch per kind of shape and colors each instance with the shape's `color`. ```ts import { Position, Scale, Shape } from "@pawnjs/core"; for (let i = 0; i < 1000; i++) { engine.world.spawn( Shape({ kind: "sphere", color: "#38bdf8", enableInstancing: true }), Position({ x: engine.random.range(-10, 10), z: engine.random.range(-10, 10) }), Scale({ x: 0.2, y: 0.2, z: 0.2 }), ); } ``` * `Tint`, hover and clicks work on instanced shapes as on meshes. * Changing `kind` moves the entity to that kind's batch; turning `enableInstancing` off gives it a mesh of its own again. * Instances are drawn in world space, so a shape under a `ChildOf` parent stays a mesh. * `burst()` throws instanced spheres. ## Measured Measured headless with 100,000 moving entities (`bun run bench` in `packages/core`), a frame takes about 12 ms with `Instance` or instanced `Shape`, about 46 ms with a `Shape` mesh each and about 100 ms with a `Visual` each; drawing, which instancing cuts to one call per batch, comes on top. The [Swarm example](https://jakubprill.github.io/pawn/swarm.html) shows it live. --- --- url: /pawn/docs/guide/views.md description: >- Views as camera rectangles of the canvas, views that follow DOM elements, picking. --- # Views and picking A `View` is a camera drawn into a rectangle of the engine's canvas. All views share one scene and are drawn in the order they were added, so later views draw on top. ```ts import { View } from "@pawnjs/core"; import { OrthographicCamera } from "three"; // Full canvas. engine.views.add(new View({ camera: main, background: 0x09090b })); // A minimap in the top-right corner, drawn on top. const top = new OrthographicCamera(-6, 6, 6, -6, 0.1, 100); top.position.set(0, 20, 0); top.lookAt(0, 0, 0); engine.views.add( new View({ camera: top, x: 0.72, y: 0.04, width: 0.24, height: 0.24, background: 0x27272a }), ); ``` | Option | Default | Meaning | |---|---|---| | `camera` | (required) | Any three.js camera. | | `x`, `y` | `0` | Top-left corner as fractions of the canvas (origin top-left). | | `width`, `height` | `1` | Size as fractions of the canvas. | | `background` | `null` | Clear color of the view's area; `null` keeps what is underneath. | | `fit` | `"height"` | How an orthographic camera fits the view's aspect ratio (below). | | `element` | `null` | A DOM element whose on-screen box the view follows. | | `name` | `""` | A label. | The engine keeps each camera's aspect ratio in sync with its view: a `PerspectiveCamera` gets a new `aspect`, and an `OrthographicCamera` follows the view's `fit`: | `fit` | What stays | |---|---| | `"height"` | The vertical extent; the camera widens or narrows horizontally. | | `"width"` | The horizontal extent; the camera grows or shrinks vertically. | | `"contain"` | Both extents in sight: taller on a narrow view, wider on a wide one. | Each fit starts from the camera's own extents: the ones it was made with, or the ones you last set on it. `"contain"` keeps a scene in frame from a wide desktop window to a phone. The vertical extent scales about the camera's axis (or its nearest edge, when the axis lies outside it), so a camera whose `bottom` is `0` keeps the bottom edge of the view on the same line: ```ts // 12 wide and 4 tall from the camera's height up, wherever the view is. const camera = new OrthographicCamera(-6, 6, 4, 0, 0.1, 100); camera.position.set(0, 0, 20); engine.views.add(new View({ camera, fit: "contain" })); ``` `engine.views.add(view)` returns a function that removes the view; so does `engine.views.remove(view)`. Set `view.enabled = false` to skip a view in both drawing and picking. ## The views of an engine `engine.views` holds the views in draw order and answers where they are. Drawing, picking, labels and the camera rig all ask it, so they agree on which views are drawn: enabled ones, and views following an element whose element is on screen. | Member | Meaning | |---|---| | `all`, `length`, iteration | Every view, in draw order: `for (const view of engine.views)`. | | `first` | The first view drawn now, or `null`. `CameraRig` and `Labels` use it by default. | | `drawn()`, `isDrawn(view)` | Views drawn now, and whether one is. | | `sizeOf(view)` | Size of a drawn view in CSS pixels, or `null`. | | `rayAt(u, v, raycaster)`, `ray(view, u, v, raycaster)` | Point a raycaster through a canvas position, in the topmost drawn view there or in a given view. | | `project(point, view?)` | Client coordinates of a world point and whether it is visible. | | `canvasRect()` | The canvas box in client pixels, or `null` without a canvas in a page. | During a frame each element's box is read once and kept until the frame ends, so asking often costs no extra layout. ## Views in page layout A view with an `element` follows that element's box every frame, as the page lays out and scrolls; hidden or scrolled-out elements are skipped. With a transparent canvas fixed over the whole page, one canvas can draw 3D into any number of elements: ```ts const engine = new Engine({ canvas, enableTransparency: true }); // canvas CSS: position: fixed; inset: 0; pointer-events: none; for (const card of document.querySelectorAll(".card")) { engine.views.add(new View({ camera: makeCamera(), element: card })); } ``` `` in [@pawnjs/react](../packages/react#views-in-page-layout) does this for React. The [Views example](https://jakubprill.github.io/pawn/views.html) shows it live. ## Picking `engine.pick(clientX, clientY)` raycasts in the topmost enabled view under a point given in client (viewport) coordinates, for example from a pointer event. It returns hits sorted by distance: ```ts canvas.addEventListener("click", (event) => { const [hit] = engine.pick(event.clientX, event.clientY); if (!hit?.entity) return; hit.entity.set(Position, { x: 0, y: 1, z: 0 }); }); ``` Each hit is `{ view, entity, intersection }`: the view it happened in, the entity that owns the hit object (or `undefined` for objects you added to the scene yourself), and the raw three.js `Intersection`. Hits on a child mesh of a `Visual` resolve to the entity, and hits on an instance resolve to the instance's entity. `engine.pickAt(u, v)` does the same for a canvas position given as fractions (0 to 1, origin top-left). [`Pointer`](./input#pointer) picks under the pointer for you: every frame for `target` and `hits`, and once for each press and click. A view points a picking ray with `view.updateRay(raycaster, ndc)`; a view with its own projection overrides it, as `MapView` from [@pawnjs/maps](../packages/maps) does. ## Post-processing A view's `render` function draws it in place of a plain `renderer.render(scene, camera)`, so one view can go through three's `EffectComposer` (bloom, outlines, color grading) while the others stay plain. It gets the renderer with its viewport and scissor already set to the view's area (and its clear color to the view's `background`, which the composer's first pass clears to), the scene, the view, its `rect` in canvas CSS pixels, and the engine's `elapsed` and `delta` seconds for effects that move. Size the composer to the rect; a composer that renders to the screen draws into the view's area. ```ts const camera = new PerspectiveCamera(60, 1, 0.1, 500); let composer: EffectComposer | null = null; let width = 0; let height = 0; engine.views.add( new View({ camera, render({ renderer, scene, view, rect }) { if (!composer) { composer = new EffectComposer(renderer); composer.addPass(new RenderPass(scene, view.camera)); // Strength, radius, and the brightness that starts to glow. composer.addPass(new UnrealBloomPass(new Vector2(), 0.8, 0.4, 0.9)); composer.addPass(new OutputPass()); } if (rect.width !== width || rect.height !== height) { ({ width, height } = rect); composer.setSize(width, height); } composer.render(); }, }), ); ``` `OutputPass` applies the engine's tone mapping and color space to the whole image, so keep it last; through a composer, a material's `toneMapped: false` no longer opts out of tone mapping. Bloom picks what is brighter than its threshold before tone mapping, so brightly lit surfaces glow along with emissive ones. The composer's render targets are yours to free with `composer.dispose()` when the view goes. ### Drawing the scene into a texture `drawToTarget(data, target, camera?)` draws the scene into a render target the size of the view's area in device pixels, then points the renderer back at the view's area on screen. A view can then show the scene through a shader of its own, such as a reflection in water: the view below draws the scene upside down and rippling. ```ts const camera = new PerspectiveCamera(50, 1, 0.1, 100); const target = new WebGLRenderTarget(1, 1); const ripple = new ShaderMaterial({ uniforms: { image: { value: target.texture }, time: { value: 0 } }, vertexShader: `varying vec2 vUv; void main() { vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }`, fragmentShader: `uniform sampler2D image; uniform float time; varying vec2 vUv; void main() { vec2 uv = vec2(vUv.x + 0.005 * sin(vUv.y * 80.0 - time), 1.0 - vUv.y); gl_FragColor = texture2D(image, uv); #include #include }`, }); const quad = new Scene().add(new Mesh(new PlaneGeometry(2, 2), ripple)); const screen = new OrthographicCamera(-1, 1, 1, -1, 0, 1); engine.views.add( new View({ camera, element: water, render(data) { drawToTarget(data, target); ripple.uniforms.time.value = data.elapsed; data.renderer.render(quad, screen); }, }), ); ``` The target is yours: free it with `target.dispose()` when the view goes. ## Headless and external renderers Without `canvas` and `renderer` the engine runs headless: systems tick, nothing is drawn. `engine.setRenderer(renderer)` sets or swaps the renderer later, for hosts that hand over a WebGL context after the engine exists (as [@pawnjs/maps](../packages/maps) does). The engine clears the canvas each frame only when `renderer.autoClear` is on; turn it off to draw over a host's content. --- --- url: /pawn/docs/guide/input.md description: >- The Input plugin: keyboard, pointer and wheel state per frame, and the Pointer module. --- # Input `Input` is a plugin that reads keyboard, pointer and wheel input per frame. ```ts import { Input } from "@pawnjs/core"; const input = new Input(); engine.use(input); ``` DOM events are queued and applied at the start of the `input` phase, so every system in a frame sees the same state, and listeners run in frame order rather than DOM order. ## Polling ```ts const drive: System = ({ delta }) => { if (input.isDown("KeyW")) speed += delta; if (input.wasPressed("Space")) jump(); if (input.isButtonDown(0)) aim(input.pointer.dx, input.pointer.dy); zoom(input.wheel.y); }; ``` | Member | Meaning | |---|---| | `isDown(code)` | Whether a key is held. | | `wasPressed(code)` | Whether a key went down this frame. | | `wasReleased(code)` | Whether a key went up this frame. | | `isButtonDown(button = 0)` | Whether a pointer button is held: 0 primary, 1 middle, 2 secondary. | | `pointer` | Last state of the primary pointer: `clientX`, `clientY`, per-frame `dx`/`dy`, `buttons`, `inside`, `pointerType`. | | `lockPointer()`, `unlockPointer()`, `pointerLocked` | Pointer lock, below. | | `wheel` | Wheel movement summed over this frame, `{ x, y }` in pixels. | Keys use `KeyboardEvent.code` (`"KeyW"`, `"Space"`, `"ArrowLeft"`), which does not depend on the keyboard layout. Typing into form fields is ignored, and losing window focus releases held keys. ## Listeners ```ts const off = input.on("keydown", (event) => { if (event.code === "Escape") closeMenu(); }); off(); // removes the listener ``` Listeners run in the `input` phase. Event types: `pointerdown`, `pointermove`, `pointerup`, `click`, `wheel`, `keydown`, `keyup`. Pointer and wheel events carry `clientX` and `clientY`, pointer events also `pointerId`, `pointerType`, `button`, `buttons` and `isPrimary`, wheel events `deltaX` and `deltaY`; key events carry `code`, `key` and `repeat`. Every event has the original DOM event as `native`. `input.pointer` and these events are the raw pointer, in CSS pixels and before any entity is involved. For the entity under the pointer, and for clicks and double clicks that skip drags, use [`Pointer`](#pointer); for a `click` on an entity itself, use the `Clickable` behavior. Keys are polled in a system, and a `Pointer` click on the floor sets where the box walks to: ```ts import { Engine, Input, Pointer, Position, Scale, Shape, View, } from "@pawnjs/core"; import { AmbientLight, DirectionalLight, PerspectiveCamera } from "three"; const SPEED = 3; // units a second export default function input(canvas: HTMLCanvasElement): Engine { canvas.style.cssText = "display:block;width:100%;height:100%"; const engine = new Engine({ canvas }); const { world } = engine; const keys = engine.plugin(Input); const pointer = engine.plugin(Pointer); engine.scene.add(new AmbientLight(0xffffff, 0.7)); const sun = new DirectionalLight(0xffffff, 2); sun.position.set(3, 8, 5); engine.scene.add(sun); world.spawn( Shape({ kind: "plane", color: "#27272a" }), Position({ y: -0.5 }), Scale({ x: 8, y: 1, z: 6 }), ); const box = world.spawn(Shape({ kind: "box", color: "#6366f1" }), Position); let goal: { x: number; z: number } | null = null; // A click on the floor sets where the box walks to. pointer.on("click", ({ hit }) => { if (hit) goal = { x: hit.intersection.point.x, z: hit.intersection.point.z }; }); // Keys are polled every frame: WASD or the arrow keys steer the box. engine.addSystem(({ delta }) => { const p = box.get(Position); if (!p) return; const dx = +keys.isDown("KeyD") - +keys.isDown("KeyA"); const dz = +keys.isDown("KeyS") - +keys.isDown("KeyW"); if (dx || dz) goal = null; let x = dx; let z = dz; if (goal) { x = goal.x - p.x; z = goal.z - p.z; if (Math.hypot(x, z) < 0.05) goal = null; } const length = Math.hypot(x, z); if (length === 0) return; const step = Math.min(SPEED * delta, goal ? length : Infinity) / length; box.set(Position, { x: Math.max(-3.5, Math.min(3.5, p.x + x * step)), y: p.y, z: Math.max(-2.5, Math.min(2.5, p.z + z * step)), }); }); const camera = new PerspectiveCamera(45, 1, 0.1, 100); camera.position.set(0, 6, 6); camera.lookAt(0, -0.5, 0); engine.views.add(new View({ camera, background: 0x09090b })); engine.fitToElement(canvas); engine.start(); return engine; } ``` ## Options ```ts new Input({ element: document.body, // pointer events; defaults to the engine's canvas keyboardTarget: window, // keyboard events; defaults to window orientationTarget: window, // device orientation for tilt; defaults to window // Decide while the DOM event is dispatched whether to cancel its default // action. Listeners run a frame later, too late for preventDefault(). preventDefault: (event) => event.type === "keydown" && (event as KeyboardEvent).code === "Space", }); ``` ## Pointer lock `input.lockPointer()` locks the pointer to the element and hides it, for looking around with the mouse in a first-person view. While locked, `input.pointer.dx` and `dy` carry the mouse's own movement, as the position stays put: ```ts const input = engine.plugin(Input); engine.plugin(Pointer).on("click", () => input.lockPointer()); engine.addSystem(() => { if (input.pointerLocked) look(input.pointer.dx, input.pointer.dy); }); ``` Browsers lock only soon after a click or key press, so call it from one. `pointerLocked` turns true the frame after the browser grants it; Escape or `input.unlockPointer()` gives the pointer back. ## Page layout When the canvas covers the page with `pointer-events: none` (views in page layout), listen on the page: `element: document.body`. An `Input` can be installed on one engine. `engine.plugin(Input)` returns the engine's `Input`, installing a default one when there is none; plugins that read input (such as `CameraRig`) use it. ## Pointer `Pointer` turns the pointers into what most scenes ask about: the entity under the pointer and the entity clicked (not dragged across). It owns the gesture: a press, any drag, the release, and the click or double click that follows. It works in canvas fractions, follows `Input` in a page and can be driven from code, so pointer logic runs and is tested without a browser. ```ts import { Pointer } from "@pawnjs/core"; const pointer = engine.plugin(Pointer); pointer.on("click", ({ entity }) => entity && select(entity)); pointer.on("doubleclick", ({ entity }) => entity && rig.focus(entity)); pointer.on("hover", ({ entity, previous }) => highlight(entity, previous)); // in a system: const overLamp = pointer.target === lamp; ``` | Member | Meaning | |---|---| | `u`, `v`, `inside` | Position of the primary pointer over the canvas, 0 to 1 from the top left, and whether it is over it. | | `target`, `hit`, `hits` | Entity, nearest hit and every hit directly under the primary pointer (`Hovered` may sit on an ancestor), picked each frame in the `input` phase. | | `all` | The primary pointer, then every other pointer holding a button: `pointerId`, `primary`, `u`, `v`, `inside`, `buttons`, `dragged`. | | `isDown(button = 0, pointerId?)` | Whether a button is held. | | `dragged` | Whether the current gesture moved past the drag threshold. | | `captured` | Whether a `press` listener took the current gesture over with `event.capture()`. | | `on(type, listener)` | `press`, `click` and `doubleclick` carry `pointerId`, `primary`, `button`, `u`, `v`, `hits`, `hit` and `entity`; `hover` carries `entity` and `previous`; `release` carries `pointerId`, `primary`, `button`, `dragged` and `cancelled`, for every press, wherever it ends. | | `moveTo(u, v, pointerId?)`, `leave(pointerId?)` | Move a pointer from code. | | `press(button, pointerId?)`, `release(button, pointerId?)`, `cancel(pointerId?)` | Press and release from code. | Every pointer presses and clicks, so two fingers tap two things at once; events tell them apart by `pointerId`, and `primary` is true for the mouse or the first finger down. Only the primary pointer hovers and moves `u`, `v` and `target`. From code, a `pointerId` other than the primary one's is another finger: `pointer.moveTo(0.2, 0.5, 7)` then `pointer.press(0, 7)`. A gesture runs from the first button pressed until the last is released, with every pointer down meanwhile, so both fingers of a pinch count. It is a drag once any of them moves further than `dragThreshold` (4 CSS pixels by default) from where it was pressed, and the release of a drag is no click, so a click never also ends a camera drag. A click soon after another (`doubleClickInterval`, 0.3 s of unscaled engine time by default), near it and with the same button, is followed by `doubleclick`. A `press` listener may call `event.capture()` to take the gesture over until its last button is released (`pointer.captured`): `CameraRig` then leaves it alone, which is how `Draggable` drags an entity without turning the camera. Clicks still happen. Events carry every hit, nearest first, for code that picks its own: the nearest body that is still falling, or a node past a pulse in front of it. ```ts pointer.on("click", ({ hits }) => { const body = hits.find((h) => h.entity?.has(Falling))?.entity; if (body) pop(body); }); ``` A lifted finger and a cancelled touch hover nothing. The pointer follows `engine.plugin(Input)` when the engine has a canvas, so install a configured `Input` before it, or pass one as `input`. With `input: null`, or on a headless engine, it is driven only from code, e.g. by another source of pointer positions. `enableHover: false` skips the per-frame pick when only clicks matter. ```ts new Pointer({ enableHover: true, // pick under the pointer every frame dragThreshold: 4, // CSS pixels a tap may travel doubleClickInterval: 0.3, // seconds between the clicks of a double click }); ``` ```ts // A test, headless: const pointer = engine.plugin(Pointer); pointer.moveTo(0.5, 0.5); engine.step(1 / 60); expect(pointer.target).toBe(box); pointer.press(); pointer.release(); // emits click with the box pointer.press(); pointer.moveTo(0.6, 0.5); pointer.release(); // a drag: no click ``` Headless there are no CSS pixels, so distances are measured on a canvas of `Pointer.HEADLESS_SIZE` (1000) pixels a side: `moveTo(0.5, 0.5)` then `moveTo(0.51, 0.5)` moves 10 pixels. Several fingers act at once: in Balloons every finger pops what it presses, with one `press` listener. ## Actions `Actions` names what the player does (`"jump"`, `"build"`, `"pause"`) and binds each action to keys, pointer buttons and gamepads, so a game asks for the action instead of a key, and a settings screen can rebind it: ```ts import { Actions } from "@pawnjs/core"; const actions = new Actions({ bindings: { left: ["KeyA", "ArrowLeft", "PadLeft", "LeftStickLeft"], right: ["KeyD", "ArrowRight", "PadRight", "LeftStickRight"], jump: ["Space", "PadA"], fire: ["Mouse0", "PadRT"], pause: ["Escape", "KeyP", "PadStart"], }, }); engine.use(actions); engine.addSystem(({ delta }) => { player.x += actions.axis("left", "right") * speed * delta; if (actions.wasPressed("jump")) jump(); if (actions.wasPressed("pause")) togglePause(); }); actions.bind("jump", ["KeyW", "PadA"]); // rebind actions.bindingsOf("jump"); // ["KeyW", "PadA"], for a settings screen ``` | Binding | Means | | --- | --- | | `"KeyW"`, `"Space"`, `"ArrowLeft"` | A key, as `KeyboardEvent.code` | | `"Mouse0"`, `"Mouse1"`, `"Mouse2"` | Primary, middle and secondary pointer button; a finger on the screen is `"Mouse0"` | | `"SwipeUp"`, `"SwipeDown"`, `"SwipeLeft"`, `"SwipeRight"` | A held pointer moving `swipeDistance` one way, pressed for one frame | | `"WheelUp"`, `"WheelDown"`, `"WheelLeft"`, `"WheelRight"` | The wheel turning, pressed for the frame it turns | | `"PadA"`, `"PadB"`, `"PadX"`, `"PadY"`, `"PadLB"`, `"PadRB"`, `"PadLT"`, `"PadRT"`, `"PadSelect"`, `"PadStart"`, `"PadL3"`, `"PadR3"`, `"PadUp"`, `"PadDown"`, `"PadLeft"`, `"PadRight"` | A button of a standard gamepad, any one connected | | `"LeftStickLeft"`, `"LeftStickUp"`, `"RightStickRight"`... | A stick pushed one way | | `"TiltLeft"`, `"TiltRight"`, `"TiltForward"`, `"TiltBack"` | The phone or tablet tilted one way, once `Input.requestTilt()` turned tilt on | * `isDown`, `wasPressed` and `wasReleased` work like `Input`'s, per frame; a key or a pointer button tapped between two frames still counts as one press. * `value(action)` is how far an action is pressed, 0..1: 1 for a key, how far for a stick or trigger. `axis(negative, positive)` gives -1..1. * A stick or trigger counts once past `deadZone` (default 0.5); its value is rescaled from there. * `Actions` reads after `Input` in the `input` phase (order `Actions.ORDER`) and installs a default `Input` when there is none. `engine.plugin(Actions)` returns the installed one, or one without bindings. * Gamepads come from `navigator.getGamepads()`. Pass `readGamepads` to feed them in tests, or `enableGamepad: false` to ignore them. * A bound key does not also do what it does in the page: Space does not scroll or press a focused button, arrows do not scroll. This holds on the whole page while `Actions` is installed, as keys are read on `window`; give `Input` a `keyboardTarget` to keep a small embedded scene from taking them. Keys held with Ctrl, Alt or Cmd, Tab and Escape keep their action in the page as well. Keys pressed in a form field (an input, a slider, a text area) go to the field and do not press actions. Pass `enablePreventDefault: false` to leave every key to the page. ### Touch screens On a phone, buttons on the page and tilting the device drive the same actions. `addButton(element, action)` holds an action while a finger presses the element; each finger counts on its own, and a quick tap still presses once, as does pressing the element from the keyboard: ```ts actions.bind("left", ["KeyA", "TiltLeft"]); actions.bind("right", ["KeyD", "TiltRight"]); actions.addButton(boostButton, "boost"); // returns a function to remove it // Tilt needs a tap first: iOS asks the player for permission. const input = engine.plugin(Input); tiltButton.addEventListener("click", async () => { if (input.tilt.available) input.calibrateTilt(); // level is how it is held now else await input.requestTilt(); }); ``` A finger anywhere on the engine's canvas (the `Input` element) presses `"Mouse0"`, so one binding serves the mouse and a one-thumb game. One finger counts at a time: a second one is ignored while the first is down, and the next to land after the first lifts takes over, so thumbs can take turns. Moving that finger `swipeDistance` CSS pixels (default `Actions.DEFAULT_SWIPE_DISTANCE`, 30) from where it went down presses the `Swipe*` binding of the way it moved, for one frame and once a press. Swipes work with the mouse too, while its primary button is held, which helps when trying a touch game on a desktop: ```ts const actions = new Actions({ bindings: { ollie: ["Space", "Mouse0"], // held while the finger is down flip: ["ArrowUp", "SwipeUp"], shuvit: ["ArrowRight", "SwipeRight"], }, swipeDistance: 26, }); engine.use(actions); ``` `input.tilt` is the tilt in degrees, measured on the screen as it is turned, portrait or landscape: `x` is the right side down, `y` the top edge down, both from where the device was held when tilt started or was last calibrated. A `Tilt*` binding reads 0 within `tiltDeadZone` degrees (default 2) and 1 at `tiltRange` degrees (default 20), counted as at least a degree past the dead zone; both are properties of `Actions` too, so a settings screen can change them live. ### Input buffer `Actions` keeps the last presses of every action with their times (`bufferSize`, default `Actions.DEFAULT_BUFFER_SIZE`, 16), for presses a moment early and presses in order. Times are game time (`FrameContext.elapsed`), so `timeScale` applies. * `pressedWithin(action, seconds)` is true when the action went down at most that long ago, this frame included: a jump pressed just before landing still jumps. It stays true for those seconds, so forget a press once it is used with `clearBuffer(action)`. * `sequence(actions, { within, among })` is true when the last presses are those actions in order, nothing between, the first at most `within` seconds ago (default `Actions.DEFAULT_SEQUENCE_WINDOW`, 0.5). With `among`, only presses of those actions count, so steering between the two presses of a skater's manual does not break it. A match is taken out of the buffer, so it counts once. The order of actions pressed in the same frame is not defined. * `clearBuffer()` forgets every press, as when a run restarts or a menu opens. ```ts if (grounded && actions.pressedWithin("jump", 0.15)) { jump(); actions.clearBuffer("jump"); } if (actions.sequence(["down", "right", "punch"], { within: 0.4 })) dashAttack(); ``` `press(action, device)` presses an action once, in the next frame, as a tap of an on-screen button does: for controls of your own, such as a virtual stick that presses directions (`actions.press("up", "touch")`). The device becomes `lastDevice`. ### Hints and rumble `actions.lastDevice` is the device that last pressed an action: `"keyboard"`, `"mouse"`, `"touch"` (a finger or a pen, on the screen or on an on-screen button), `"gamepad"` or `"tilt"`, and `null` until one is pressed. A HUD reads it to show the hints for what the player holds; `actions.playedByTouch` is true for touch and tilt, when the player plays with what is on the screen. `actions.rumble({ strength, duration })` gives the player a jolt they feel, as on a crash: it rumbles every gamepad that can, and vibrates a phone played by touch or tilt. `strength` is 0..1 (default 1) and only gamepads feel it; `duration` is in seconds (default `Actions.DEFAULT_RUMBLE_DURATION`, 0.15). Phones vibrate only once the page has been tapped, and Safari and iOS do not vibrate at all. Pass `vibrate` to `Actions` to feed it in tests. ```ts hint.textContent = actions.playedByTouch ? "Tap Start" : "W to start"; if (crashed) actions.rumble({ strength: 0.8, duration: 0.2 }); ``` --- --- url: /pawn/docs/guide/sound.md description: >- Sound: Web Audio playback of files and synthesized tones, master volume and mute. --- # Sound `Sound` plays sounds with the Web Audio API: audio files by URL, loaded once and cached, and short synthesized tones for feedback without any files. Everything goes through one master volume. ```ts import { Sound } from "@pawnjs/core"; const sound = engine.plugin(Sound); await sound.load("/sounds/coin.mp3"); // optional: avoids a late first play sound.play("/sounds/coin.mp3", { volume: 0.6, rate: 1.2 }); sound.tone({ frequency: 880, to: 1320, duration: 0.1, wave: "square" }); sound.volume = 0.5; sound.muted = true; ``` * `play(url, { volume, rate })` loads the file when needed; `rate` 2 is an octave up. A file that fails to load logs a warning and is tried again on the next call. * `tone({ frequency, to, duration, wave, volume })` plays a tone that fades out over `duration` seconds, sliding from `frequency` to `to` Hz. `wave` is `"sine"`, `"square"`, `"triangle"` or `"sawtooth"`. * Browsers start audio suspended until the page gets a press. `Sound` resumes it on the first pointer or key press (`enableUnlock`, on by default); sounds played before that are dropped rather than all played at once later. * Without Web Audio (a test, a server) `Sound` stays silent, so the same code runs headless. Pass `context` to play into an `AudioContext` of your own. ## Your own sounds For a sound that runs and changes with the game, like an engine whose pitch follows its speed, build a Web Audio graph on `sound.context` and connect it to `sound.destination`, so it follows `volume` and `muted`: ```ts const sound = engine.plugin(Sound); const { context, destination } = sound; if (context && destination) { const hum = context.createOscillator(); hum.type = "sawtooth"; const gain = context.createGain(); gain.gain.value = 0.1; hum.connect(gain).connect(destination); hum.start(); engine.addSystem(() => { // Until a press, time stands still and changes would only pile up. if (context.state !== "running") return; // Glide toward the new pitch rather than jump each frame. hum.frequency.setTargetAtTime(60 + car.speed * 4, context.currentTime, 0.05); }); } ``` Both are `null` without Web Audio. A source started before the page is pressed waits, and is heard once audio is unlocked. Audio also keeps playing in a hidden tab, where systems stop running: turn a running sound down on `visibilitychange`. `SoundOn` plays a sound on an entity event; see [Behaviors](./behaviors.md#feedback-sound-flash-burst). --- --- url: /pawn/docs/guide/camera.md description: >- CameraRig: orbit, pan and zoom by pointer, plus focus, follow, fit and reset. ChaseCamera: a camera behind a moving entity. --- # Camera rig `CameraRig` is a plugin that lets people move the camera: drag to rotate around a target, right-drag or Shift-drag to pan, wheel or pinch to zoom. It reads pointers through [`Input`](./input.md) and works with perspective and orthographic cameras. ```ts import { CameraRig } from "@pawnjs/core"; const rig = new CameraRig({ target: { y: 1 }, maxPolarAngle: 1.4, // stay above the ground }); engine.use(rig); ``` The rig takes the camera's position at the first frame and orbits the target from there. It moves the camera of the engine's first view, or of `view` when given. | Gesture | Mouse | Touch | |---|---|---| | Rotate | drag | one finger | | Pan | right-drag, middle-drag, Shift/Ctrl/Cmd-drag | two fingers | | Zoom | wheel | pinch | A perspective camera zooms by moving closer to the target; an orthographic camera by changing `camera.zoom`. Moves are damped (`halfLife` is the half-life in seconds, 0 turns it off) and keep going while the engine's `timeScale` is 0. On touch screens the canvas needs a `touch-action` that leaves the gestures to the page: `none` gives the rig every gesture, `pan-y` keeps vertical scrolling of the page and gives the rig horizontal drags and pinching. Drag to orbit, wheel or pinch to zoom, and click a tower to focus it: ```ts import { CameraRig, Clickable, Engine, Hoverable, Position, Scale, Shape, View, } from "@pawnjs/core"; import { AmbientLight, DirectionalLight, PerspectiveCamera } from "three"; export default function camera(canvas: HTMLCanvasElement): Engine { // `pan-y` keeps the page scrolling on touch and gives the rig the rest. canvas.style.cssText = "display:block;width:100%;height:100%;touch-action:pan-y"; const engine = new Engine({ canvas, seed: 3 }); const { world, random } = engine; engine.scene.add(new AmbientLight(0xffffff, 0.6)); const sun = new DirectionalLight(0xffffff, 2); sun.position.set(6, 10, 4); engine.scene.add(sun); const view = new PerspectiveCamera(45, 1, 0.1, 200); view.position.set(8, 8, 10); engine.views.add(new View({ camera: view, background: 0x09090b })); const rig = new CameraRig({ maxPolarAngle: 1.35, maxDistance: 30 }); engine.use(rig); world.spawn( Shape({ kind: "plane", color: "#27272a" }), Scale({ x: 12, y: 1, z: 12 }), ); // A small town of towers; click one to fly to it. for (let i = 0; i < 25; i++) { const height = random.range(0.5, 3); const tower = world.spawn( Shape({ kind: "box", color: "#e2e8f0" }), Position({ x: (i % 5) * 2 - 4, y: height / 2, z: Math.floor(i / 5) * 2 - 4, }), Scale({ x: 1, y: height, z: 1 }), Hoverable({ tint: "#6366f1", amount: 0.7 }), Clickable, ); engine.events.on(tower, "click", () => rig.focus(tower, { distance: 6 })); } engine.fitToElement(canvas); engine.start(); return engine; } ``` ## Moving the camera from code ```ts rig.focus(entity); // target the entity's position rig.focus({ x: 0, y: 0, z: 0 }, { zoom: 2, immediate: true }); rig.follow(player, { y: 1 }); // keep the target on a moving entity rig.fit(new Box3(min, max), { margin: 16 }); // frame the bounds rig.reset(); // back to where the rig started ``` `focus()` and `fit()` ease in with the rig's `halfLife` unless `immediate: true`. `fit()` keeps the current direction and changes the target and the zoom (orthographic) or distance (perspective). Panning stops `follow()`; rotating and zooming keep it. ## Panels over the scene When UI covers part of the canvas, tell the rig how much, in CSS pixels: ```ts rig.padding = { right: 320, top: 80 }; rig.fit(bounds); ``` The target is then centered in the uncovered area (the projection is shifted with `setViewOffset`), and `fit()` fits the bounds into that area. ## Clicks after a drag The browser sends `click` when a drag ends, including one that rotates the camera. [`Pointer`](./input#pointer) clicks only when the gesture was no drag, so selecting on its clicks never fights the rig: ```ts engine.plugin(Pointer).on("click", ({ entity }) => select(entity)); ``` A gesture that a `Pointer` press listener captured, such as dragging an entity with the [`Draggable`](./behaviors#ready-made-behaviors) behavior, does not move the camera. ## Options | Option | Default | Meaning | |---|---|---| | `view` | first view | View whose camera the rig moves. | | `input` | `engine.plugin(Input)` | Input to read pointers from. | | `target` | origin | Point to orbit. | | `padding` | none | Area covered by UI, in CSS pixels per side. | | `enableRotate`, `enablePan`, `enableZoom` | `true` | Which gestures move the camera. | | `minDistance`, `maxDistance` | `0`, `Infinity` | Distance limits (perspective). | | `minZoom`, `maxZoom` | `0`, `Infinity` | `camera.zoom` limits (orthographic). | | `minPolarAngle`, `maxPolarAngle` | `0`, `π` | Angle from straight above, in radians. | | `halfLife` | `0.06` | Half-life of moves, in seconds. | | `rotateSpeed`, `panSpeed`, `zoomSpeed` | `1` | Gesture multipliers. | All options except `view`, `input` and `target` are also properties that can be changed later; `rig.enabled = false` ignores input but keeps `focus()`, `follow()` and `fit()` working. The [Energy flow](https://jakubprill.github.io/pawn/energy.html) and CMS Health examples use the rig with an orthographic camera and panels over the scene. ## Chase camera `ChaseCamera` is a plugin for games: it sits behind an entity, in the entity's own space, so it swings round with it in turns, and looks at a point ahead of it. It trails the entity by a half-life, rolls part of the way with it, eases its field of view and shakes on demand. ```ts const chase = new ChaseCamera({ target: ship, offset: { y: 3, z: 10 }, // behind and above a model whose nose is -z lookAt: { z: -9 }, // ahead of it lean: 0.5, // roll half as far as the ship }); engine.use(chase); chase.fov = boosting ? 76 : 64; // eases there chase.shake({ strength: 0.4 }); // on a hit chase.follow(null); // hand the camera to another one chase.follow(ship); // and take it back: cuts to the spot ``` It moves the camera of the engine's first view, or of `view`, after the game's systems have moved the target each frame. It runs on game time, so a paused engine holds the camera and its shake still. `shake()` takes a `strength` in meters (default `0.3`) and a `duration` in seconds (default `0.4`); a weaker shake during a stronger one changes nothing. `cut()` jumps to the spot on the next frame instead of easing there, as after a teleport. When the target is destroyed, the camera stays where it was. Tap to shake the camera: ```ts import { ChaseCamera, Engine, Position, Rotation, Scale, Shape, View, } from "@pawnjs/core"; import { AmbientLight, DirectionalLight, Matrix4, PerspectiveCamera, Quaternion, Vector3, } from "three"; export default function chase(canvas: HTMLCanvasElement): Engine { canvas.style.cssText = "display:block;width:100%;height:100%"; const engine = new Engine({ canvas, seed: 5 }); const { world, random } = engine; engine.scene.add(new AmbientLight(0xffffff, 0.6)); const sun = new DirectionalLight(0xffffff, 2); sun.position.set(6, 10, 4); engine.scene.add(sun); const camera = new PerspectiveCamera(60, 1, 0.1, 300); engine.views.add(new View({ camera, background: 0x09090b })); world.spawn( Shape({ kind: "plane", color: "#27272a" }), Scale({ x: 80, y: 1, z: 80 }), ); // Towers inside and outside the ring the dart flies. for (let i = 0; i < 60; i++) { const angle = random.range(0, Math.PI * 2); const radius = i % 2 ? random.range(4, 10) : random.range(18, 30); const height = random.range(1, 6); world.spawn( Shape({ kind: "box", color: "#e2e8f0" }), Position({ x: Math.cos(angle) * radius, y: height / 2, z: Math.sin(angle) * radius, }), Scale({ x: 1.5, y: height, z: 1.5 }), ); } const dart = world.spawn( Shape({ kind: "box", color: "#6366f1" }), Position, Rotation, Scale({ x: 0.8, y: 0.3, z: 2 }), ); // Behind and above the dart, looking ahead of it, rolling with it. const chase = new ChaseCamera({ target: dart, offset: { y: 1.5, z: 5 }, lookAt: { y: 0.5, z: -4 }, lean: 0.6, }); engine.use(chase); canvas.addEventListener("pointerdown", () => chase.shake({ strength: 0.5 })); // A wavy right-hand circle, nose first and banked into the turn. const at = new Vector3(); const ahead = new Vector3(); const up = new Vector3(0, 1, 0); const back = new Vector3(0, 0, 1); const basis = new Matrix4(); const turn = new Quaternion(); const bank = new Quaternion().setFromAxisAngle(back, -0.5); const place = (t: number, out: Vector3) => out.set(Math.cos(t) * 14, 2 + Math.sin(t * 3), Math.sin(t) * 14); engine.addSystem(({ elapsed }) => { place(elapsed * 0.5, at); place(elapsed * 0.5 + 0.01, ahead); turn.setFromRotationMatrix(basis.lookAt(at, ahead, up)).multiply(bank); dart.set(Position, { x: at.x, y: at.y, z: at.z }); dart.set(Rotation, { x: turn.x, y: turn.y, z: turn.z, w: turn.w }); }); engine.fitToElement(canvas); engine.start(); return engine; } ``` | Option | Default | Meaning | |---|---|---| | `view` | first view | View whose camera it moves. | | `target` | none | Entity to chase; or `follow(entity)` later. | | `offset` | `{ x: 0, y: 3, z: 8 }` | Where the camera sits, in the target's own space. | | `lookAt` | `{ x: 0, y: 1, z: -8 }` | Point it looks at, in the target's own space. | | `halfLife` | `0.06` | Seconds to cover half the way to its spot; 0 keeps it there. | | `lean` | `0.5` | How far it rolls with the target, 0 (level) to 1. Where a level horizon points nowhere it rolls further: from nothing extra with the target on its side to all of it a third of the way on to upside down, as through a loop, and all the way while it looks almost straight up or down at a target whose up still reaches across the view. | | `fov` | camera's | Field of view in degrees to ease toward. | | `fovHalfLife` | `0.25` | Seconds for `fov` to cover half the way. | All options except `view` and `target` are also properties; `offset` and `lookAt` are `Vector3`s to change in place. --- --- url: /pawn/docs/guide/labels.md description: 'The Labels plugin: HTML elements pinned to entities on screen.' --- # Labels `Labels` is a plugin that pins HTML elements to entities on screen: names, values, buttons, tooltips. The elements are ordinary DOM, so they take CSS, text selection and clicks; the plugin only moves them. An engine installs it when an entity first gets a `Label`. ```ts import { Label, Position, Visual } from "@pawnjs/core"; const tag = document.createElement("div"); tag.textContent = "Wind park · 19 MW"; engine.world.spawn( Position({ x: -7, z: 5 }), Visual(turbines), Label({ element: tag, offset: { y: 3 } }), ); ``` Late in the `render` phase, after transforms reach the scene, each label is placed over its entity's world position plus `offset`. A label is hidden (`visibility: hidden`) while its entity is off screen, behind the camera, outside its view or has no position. ## `Label` options | Option | Meaning | |---|---| | `element` | Element to move. | | `offset` | World-space offset from the entity, e.g. `{ y: 2 }` above it. | | `align` | Point of the element placed on the entity, as fractions of its size. Defaults to `{ x: 0.5, y: 1 }`: centered, above the point. | | `view` | View to project through. Defaults to the first enabled view. | The plugin sets `position: absolute`, `left`, `top`, `transform` and `visibility` on the element; style everything else yourself. ## Many labels For scenes with hundreds of labelled entities, `Labels` can show only the ones that matter, configured by installing it yourself before the first label: ```ts import { Labels } from "@pawnjs/core"; engine.use(new Labels({ maxDistance: 40, maxVisible: 50 })); ``` * `maxDistance` hides labels farther than this from their view's camera, in world units. * `maxVisible` shows at most this many labels, the nearest to the camera. * Both default to `Infinity`. A label only rewrites its element's `transform` when its place on screen changes. ## Container Labels are positioned in a container, by default the canvas's parent element (give it `position: relative`). Pass another one with `new Labels({ container })`. An element without a parent is appended to the container and removed again with its label; an element already in the page stays where it is and is only moved. `engine.plugin(Labels)` returns the installed plugin, or installs a default one. ## World position An entity is labelled at its [world position](./hierarchy.md#world-position), so labels on `ChildOf` children follow their parents, with a `Visual` or without one. An `Instance` is drawn in world space, so its `Position` is its world position. ## Projecting points yourself `engine.views.project(point, view?)` returns the client coordinates of a world point and whether it is visible, or `null` without a canvas. Without a view it projects through `engine.views.first`, the first view drawn: ```ts const at = engine.views.project(new Vector3(0, 2, 0)); if (at?.visible) showTooltip(at.x, at.y); ``` In React, use [``](/packages/react#entitylabel). --- --- url: /pawn/docs/guide/assets.md description: Loading glTF models with Assets and the Model trait. --- # Models (glTF) The `Assets` plugin loads glTF files (`.gltf` and `.glb`) and draws them for entities with a `Model` trait. Each URL is fetched once. Every entity gets its own copy of the scene, and the copies share the file's geometries, materials and textures. An engine installs `Assets` when an entity first gets a `Model`; install it yourself for decoders or to preload. ```ts import { Model, Position } from "@pawnjs/core"; engine.world.spawn(Position({ x: 2 }), Model({ url: "/models/lantern.glb" })); ``` Until the file is loaded, the entity has the `Loading` tag. Once loaded, it gets a `Visual` with its copy of the model, and the tag goes away. Finished loads are applied early in the `input` phase, so a frame never shows half of a change. A model already loaded is shown on the next frame, without `Loading`. A `Visual` set by hand wins: the model does not replace it. A `Shape` or `Light` look is replaced, so a `Shape` can stand in until the model arrives. ```ts import { Loading, Model } from "@pawnjs/core"; entity.set(Model, { url: "/models/lamp-on.glb" }); // swap; the old model stays until the new one is ready entity.remove(Model); // removes the Visual the model added for (const entity of world.query(Model, Loading)) { // still loading } ``` Skinned models are copied with their skeletons, so each copy can play its own animation. ## Animations `Animation` plays one of the model's clips, by its name in the file. It needs a `Model`; the `Animations` plugin, installed with the first `Animation`, gives each entity its own three.js `AnimationMixer` and steps it on the engine clock, so a paused or slowed clock (`clock.timeScale`) pauses or slows the clips, on a headless engine too. ```ts import { Animation, Model } from "@pawnjs/core"; const skater = engine.spawn( Model({ url: "/models/skater.glb" }), Animation({ clip: "Idle" }), ); skater.set(Animation, { clip: "Jump", enableLoop: false, speed: 1.5 }); engine.events.on(skater, "animationend", ({ clip }) => { if (clip === "Jump") skater.set(Animation, { clip: "Idle" }); }); ``` Setting another `clip` cross-fades to it: the old clip fades out as the new one fades in, halfway after `halfLife` seconds (`0` cuts at once). A clip with `enableLoop: false` plays once, holds its last pose and the entity gets an `animationend` entity event. `engine.plugin(Animations).restart(entity)` plays the current clip again from its start, such as the same trick twice, and `time(entity)` tells how far into it the clip is. A clip the file does not have is reported once through `onMissingClip` (by default `console.warn`). The loaded file lists its clips: ```ts const names = engine.plugin(Assets).get("/models/skater.glb")?.animations.map((clip) => clip.name); ``` ## Loading ahead and progress ```ts const assets = new Assets(); engine.use(assets); await assets.preload(["/models/pawn.glb", "/models/board.glb"], (loaded, total) => { bar.style.width = `${(loaded / total) * 100}%`; }); const gltf = await assets.load("/models/pawn.glb"); // the same load, from the cache assets.get("/models/pawn.glb"); // the loaded file, or undefined while loading ``` `assets.progress` counts the files that are loading now, as `{ loaded, total }`. A count starts again when a file starts loading while nothing else is. While the plugin is installed, the engine's world holds the same count as the `AssetProgress` trait, so systems read it with `world.get(AssetProgress)` and React with `useAssetProgress()` (or koota's `useTrait(world, AssetProgress)`): ```tsx import { useAssetProgress } from "@pawnjs/react"; function LoadingBar() { const { loaded, total } = useAssetProgress(); if (loaded === total) return null; return ; } ``` ## Compressed files Files compressed with Draco or meshopt need their decoder: ```ts engine.use( new Assets({ draco: "https://www.gstatic.com/draco/versioned/decoders/1.5.7/", enableMeshopt: true, }), ); ``` `draco` is the folder with the Draco decoder files (from three's `examples/jsm/libs/draco/`, or a CDN). With `enableMeshopt: true`, three's meshopt decoder is fetched when the first file starts loading. [`gltf-transform optimize`](https://gltf-transform.dev/cli) makes files much smaller. The lanterns in the showcase's Energy demo went from 9.6 MB to 70 KB with `--compress meshopt --texture-compress webp --texture-size 256`. ## Errors and cleanup A file that fails to load is reported once through `onError` (by default `console.warn`). Its entities lose `Loading` and keep what they showed before, if anything. A failed URL is not cached: the next `load()`, or setting the same `Model` URL again, tries again. Loaded files stay in memory until `assets.unload(url)`, which frees their geometries, materials and textures, or until the engine is disposed. Call `unload()` only when no entity draws the model anymore. --- --- url: /pawn/docs/guide/behaviors.md description: >- Behaviors (Hoverable, Clickable, Draggable, Lifetime, Health, motion, SoundOn, FlashOn, Burst, your own), presets and entity events. --- # Behaviors and events A **behavior** packages one feature (spinning, reacting to the pointer, playing a sound) as a koota trait with JSON params plus the plugin that makes it work. It is added to entities like any other trait, and because its params are plain data, a scene built from behaviors can be saved, generated or tested headless. Core has `defineBehavior`, entity events, `closest()` and the `Hoverable`, `Clickable`, `Draggable`, `Lifetime`, `Health` and motion (`Velocity`, `Spin`, `Bob`, `FollowPath`) behaviors; `@pawnjs/tween` has [`TweenOn`](/packages/tween#tweenon). [Presets](#presets) bundle behaviors, [prefabs](./prefabs.md) describe whole entities (and [`Spawner`](./prefabs.md#spawner) spawns waves of them), and [snapshots](/guide/snapshots) save scenes built from them. ## Ready-made behaviors Hover a shape to tint it, click it to make it jump and spin faster: ```ts import { Clickable, Engine, Hoverable, Position, Shape, Spin, } from "@pawnjs/core"; import { TweenOn } from "@pawnjs/tween"; export default function behaviors(canvas: HTMLCanvasElement): Engine { canvas.style.cssText = "display:block;width:100%;height:100%"; const engine = new Engine({ canvas, camera: { position: { y: 1.2, z: 4.5 } }, background: "#09090b", lights: "studio", }); // Hover tints a shape, a click makes it jump and spin faster. const kinds = ["box", "sphere", "cylinder"] as const; kinds.forEach((kind, i) => { const shape = engine.spawn( Shape({ kind, color: "#e2e8f0" }), Position({ x: (i - 1) * 1.8, y: 0, z: 0 }), Spin({ speed: 0.6 }), Hoverable({ tint: "#6366f1", amount: 0.7 }), Clickable, TweenOn({ on: "click", lift: 0.6, duration: 0.25, easing: "quadOut" }), ); let speed = 0.6; engine.events.on(shape, "click", () => { speed += 2; shape.set(Spin, { speed }); }); }); engine.start(); return engine; } ``` In short: ```ts import { Clickable, Hoverable, Hovered, Position, Shape } from "@pawnjs/core"; import { TweenOn } from "@pawnjs/tween"; const button = world.spawn( Shape({ kind: "box", color: "#e2e8f0" }), Position, Hoverable({ tint: "#6366f1" }), Clickable, TweenOn({ on: "click", scale: 1.1, duration: 0.15 }), ); engine.events.on(button, "click", () => console.log("clicked")); world.query(Hovered); // what is hovered now ``` | Behavior | Params | What it does | |---|---|---| | `Hoverable` | `tint` (`""`), `amount` (`0.3`), `cursor` (`"pointer"`) | Keeps the `Hovered` tag on the entity while the pointer is over it and emits `pointerenter` and `pointerleave` on it; with a `tint`, adds a `Tint` meanwhile (a `Tint` already there is left alone); sets the canvas cursor. | | `Clickable` | none | Emits `pointerdown`, `pointerup`, `click`, `doubleclick` and `contextmenu` entity events and keeps the `Pressed` tag while a button pressed on the entity is held. | | `Draggable` | `plane` (`"view"`, or `"xy"`, `"xz"`, `"yz"`), `enableMove` (`true`) | Drags the entity across a plane through the grabbed point; keeps the `Dragged` tag and emits `dragstart`, `drag` and `dragend` entity events. | | `Lifetime` | `seconds` (`1`), `shrink` (`0`) | Counts `seconds` down in scaled time; over the last `shrink` seconds scales the entity down to nothing; then emits `expire` and destroys the entity with its children. | | `Health` | `hp` (`10`), `max` (`10`), `enableDestroy` (`true`) | Hit points, changed with [`damage()`](#health). | | `Velocity` | `x`, `y`, `z` (`0`) | Moves `Position` by that many units per second, along the parent's axes. | | `Spin` | `axis` (`"y"`, or `"x"`, `"z"`), `speed` (`1`) | Turns `Rotation` around the entity's own axis, in radians per second. | | `Bob` | `axis` (`"y"`), `amplitude` (`0.25`), `period` (`2`), `phase` (`0`) | Swings `Position` back and forth along an axis; adds the change each frame, so it combines with other motion. | | `FollowPath` | `points` (`[]`), `speed` (`1`), `distance` (`0`), `enableLoop` (`false`), `enableFacing` (`true`) | Moves `Position` along the points at `speed`; `distance` is how far it got. At the end it stops and emits `pathend`, or loops. With `enableFacing` it turns around y to face its way (front +z). | | [`TweenOn`](/packages/tween#tweenon) | `on`, `off`, `scale`, `lift`, `turn`, `duration`, `easing` | Plays a tween when an entity event reaches the entity. | The pointer behaviors read the engine's [`Pointer`](/guide/input#pointer), installing it if needed, and count the pointer over a `ChildOf` descendant's `Visual` as over the entity, so a model built of child entities reacts as one. `Clickable` emits on the entity that was hit, and the event bubbles through the clickable entity. `pointerup` goes to the entity the press was on, wherever the button is released or the press cancelled; `click` comes only from a press and release on the same clickable entity, without a drag, and `doubleclick` after the second of two quick clicks on the same clickable entity. A click with the secondary button is followed by `contextmenu`, and the browser's own menu does not open over clickable entities. Every finger presses and clicks, so two clickable entities tapped together both get their events; hover follows the primary pointer. `Hoverable` needs the `Pointer`'s hover picking, which is on unless the pointer was made with `enableHover: false`. `Draggable` takes a primary press on the entity (or a child) for itself, so a [`CameraRig`](/guide/camera) holds still. Once the pointer moves past the drag threshold the entity gets `Dragged` and `dragstart`, then `drag` on every move and `dragend` on release; each event carries the `point` under the pointer on the plane. With `enableMove` the entity's `Position` follows the pointer (relative to its parent, so children drag too); `enableMove: false` only emits the events, for code that moves the entity itself. A press released without a drag is still a click. ```ts fruit.add(Position, Draggable({ plane: "xy" })); engine.events.on(fruit, "dragend", () => { if (nearMouth(fruit)) eat(fruit); }); ``` Entering and leaving are koota's query modifiers, and React reads the tags with `useHas`: ```ts const Entered = createAdded(); for (const entity of world.query(Entered(Hovered))) playSound(); const hovered = useHas(entity, Hovered); ``` ### Reduced motion Only your app knows which motion is decoration (a spinning logo) and which carries meaning (`FollowPath` showing a flow), so the motion behaviors have no global switch for `prefers-reduced-motion`. Leave the decorative ones out while the user asks for less motion, and follow the setting when it changes: ```ts import { Spin } from "@pawnjs/core"; const reduce = matchMedia("(prefers-reduced-motion: reduce)"); const follow = () => { if (reduce.matches) logo.remove(Spin); else logo.add(Spin({ speed: 0.5 })); }; follow(); reduce.addEventListener("change", follow); ``` `Bob` and a decorative `FollowPath` go the same way; a `FollowPath` that shows a flow can stay, slower (`speed`). `engine.clock.timeScale` slows everything at once, the motion that matters too (see [Clock](./engine.md#clock)). ## Defining a behavior ```ts import { defineBehavior, Rotation } from "@pawnjs/core"; export const Wobble = defineBehavior({ name: "wobble", params: { speed: { default: 1, min: 0, description: "Wobbles per second" }, axis: { default: "y", enum: ["x", "y", "z"] }, }, install(engine, { trait }) { return engine.addSystem(({ world, delta }) => { world .query(trait, Rotation) .select(Rotation) .updateEach(([rotation], entity) => { const { speed } = entity.get(trait)!; // ... tilt `rotation` back and forth, speed times a second }); }); }, }); entity.add(Wobble({ speed: 0.5 })); // a normal koota trait entity.set(Wobble, { speed: 2 }); // change params with set ``` `defineBehavior` returns a koota trait, used like any other: its fields are the params, with their defaults. The engine installs what makes it work the first time an entity gets it. The trait also carries: | Member | Meaning | |---|---| | `name` | Stable kebab-case id, used by presets and saved scenes. | | `plugin` | Runs `install` once per engine; its name is `"@pawnjs/behavior/"`. `engine.use(Wobble.plugin)` installs it before any entity has the behavior. | | `params` | The param specs as defined: `default`, `min`, `max`, `enum`, `description`, `schema`. | Params are numbers, strings and booleans. A list or object param takes a factory default (`points: { default: () => [] }`), so each entity gets its own; change it with `entity.set`, since changes inside it are not seen. `defineBehavior` throws on a name that is not kebab-case and on a default that is not one of these, or not in its `enum`. A behavior without params is a tag. The name is the behavior's id on an engine, so two behaviors may not share one: the second is not added to entities, and the engine warns once, while `applyPreset` and `engine.use(behavior.plugin)` throw for it. A hot reload that defines a behavior again does this too, so reload the page. Core's behaviors take theirs (`spin`, `bob`, `velocity`, `follow-path`, `hoverable`, `clickable`, `draggable`, `health`, `lifetime`, `spawner`, `sound-on`, `flash-on`, `burst`) and `@pawnjs/tween` takes `tween-on`; name your own otherwise. Give a list or object param a `schema`, in a subset of JSON Schema, and its values are checked too, by presets, prefabs, saved scenes and `@pawnjs/json-render`; `toJSONSchema` passes it on: ```ts export const Patrol = defineBehavior({ name: "patrol", install: () => undefined, // its system, as above params: { points: { default: (): Vec3Like[] => [], schema: { type: "array", items: { type: "object", properties: { x: { type: "number" }, z: { type: "number" } }, required: ["x", "z"], }, }, }, }, }); ``` It takes `type`, `properties`, `required`, `additionalProperties`, `items`, `minItems`, `maxItems`, `minimum`, `maximum`, `enum`, `const`, `anyOf` and `description`; the type is `ValueSchema`. `validateValue(schema, value)` checks one value against it, and `valueSchemaOf(spec)` gives any param's spec as one (a plain param's type, `enum`, `min` and `max`), so every check reads params the same way. A behavior that reacts to an entity event chosen as data, like `SoundOn` or `TweenOn`, installs with `listenOn`: it calls the handler of each param whenever the event that param names reaches an entity with the behavior, follows `entity.set` changes and stops on removal. An empty param listens to nothing. ```ts export const Toggle = defineBehavior({ name: "toggle", params: { on: { default: "click", description: "Event that switches it on." }, off: { default: "", description: "Event that switches it off." }, }, install: (engine, { trait }) => listenOn(engine, trait, { on: (entity) => console.log("on", entity), off: (entity, event) => console.log("off by", event.type), }), }); ``` For typed code around params, core exports `ParamSpec` (one param's spec), `ValueSchema` (the values a param takes), `ParamSpecs` (a record of them), `ParamDefault` and `ParamValue` (the value a spec describes), and `BehaviorData

`, the trait value of a behavior with params `P`. ## Presets A **preset** is a named list of behaviors with their params, so a whole feature is applied to an entity in one call: ```ts import { applyPreset, Clickable, definePreset, Hoverable, removePreset, } from "@pawnjs/core"; import { TweenOn } from "@pawnjs/tween"; export const Button3D = definePreset({ name: "button3d", behaviors: [ [Hoverable, { tint: "#6366f1" }], Clickable, [TweenOn, { on: "click", scale: 1.1, duration: 0.15 }], ], }); applyPreset(engine, entity, Button3D); applyPreset(engine, other, Button3D, { hoverable: { tint: "#f59e0b" } }); removePreset(other, Button3D); ``` `applyPreset` installs each behavior's plugin the engine lacks, then adds each behavior's trait with the preset's params and the overrides, keyed by behavior name. An entity that already has a trait gets those params set, and its other params keep their values; lists and objects in params are copied per entity. `removePreset` removes every behavior the preset lists, also one the entity had before or got from another preset. Presets do not nest; list the behaviors instead. Params are checked against each behavior's specs: `definePreset` and `applyPreset` throw on an unknown behavior or param, a value of the wrong type, or one outside its `min`, `max` or `enum`, and nothing is applied. TypeScript catches the first two already: `applyPreset`'s overrides are typed by the preset's behaviors. `validateParams(behavior, values)` runs the same check and returns the problems as messages: ```ts validateParams(Hoverable, { amount: 2 }); // ["hoverable.amount: 2 is above the maximum 1."] ``` ## Feedback: sound, flash, burst Three behaviors answer an entity event with feedback, so a hit or a pickup feels like one without code. Each has an `on` param naming the event, and follows changes to it. ```ts import { Burst, FlashOn, SoundOn } from "@pawnjs/core"; enemy.add( FlashOn({ on: "damage", color: "#ffffff", amount: 0.85, seconds: 0.12 }), Burst({ on: "died", count: 16, speed: 2.5, color: "#f43f5e" }), SoundOn({ on: "died", frequency: 660, to: 990, wave: "triangle", variation: 0.1 }), ); ``` * `SoundOn` plays an audio file (`url`) or, without one, a synthesized tone (`frequency`, `to` for a slide, `duration`, `wave`), at `volume`, with a random pitch change of up to `variation` (from `engine.random`). It plays through [`Sound`](./sound.md). * `FlashOn` tints the entity with `color` by `amount` for `seconds` of scaled time. A flash during a flash starts the time again, and a `Tint` the entity had before comes back after. * `Burst` throws `count` small spheres from the entity's world position at `speed`, each `size` wide in `color`, living `seconds` and shrinking at the end; `flatten` goes from a sphere (0) to a flat ring (1). The particles are plain entities (`Velocity`, `Lifetime`, `Shape`) in the entity's scope. `burst(engine, point, options)` throws one from code. An entity has each behavior once, so one `SoundOn` per entity; play other sounds from listeners with `engine.plugin(Sound)`. ## Health `Health` holds hit points; `damage(engine, entity, amount)` takes them (a negative amount heals, up to `max`) and returns what is left: ```ts import { damage, Health } from "@pawnjs/core"; enemy.add(Health({ hp: 8, max: 8 })); engine.events.on(enemy, "damage", ({ amount }) => flash(enemy)); engine.events.on(enemy, "died", () => addGold(1)); damage(engine, enemy, 3); // 5 ``` It emits a `damage` entity event with the hit points taken, and when they reach 0 a `died` event, then destroys the entity with its children unless `enableDestroy` is off or a listener healed it. Damage to an entity without `Health`, or already at 0, does nothing. ## Entity events `engine.events` carries instant events on entities, such as `click`. An event goes to the entity's listeners, then bubbles up `ChildOf`, so a click on a wheel reaches the car: ```ts const off = engine.events.on(car, "click", (event) => { event.target; // the wheel event.currentTarget; // the car event.stopPropagation(); }); engine.events.emit(wheel, "click", { button: 0, point: undefined }); off(); ``` Emitting runs the listeners at once. Emit after iterating a query rather than inside it, since listeners may add or remove traits. Core defines `click`, `doubleclick`, `contextmenu`, `pointerdown`, `pointerup`, `pointerenter`, `pointerleave`, `dragstart`, `drag`, `dragend`, `damage` and `died` (from `damage()`), `expire` (from `Lifetime`), `pathend` (from `FollowPath`) and `wavestart`, `waveend`, `spawn` and `spawnerend` (from [`Spawner`](./prefabs.md#spawner)); add your own with declaration merging: ```ts declare module "@pawnjs/core" { interface EntityEventMap { alarm: { level: number }; } } ``` Lasting state, such as being hovered, is a trait that systems and UI query, not an event. `engine.events` is an `EntityEvents`. A plain `new EntityEvents()` works without an engine, for tests of code that only emits and listens. Listeners are typed as `EntityEvent`: the payload plus `type`, `target`, `currentTarget` and `stopPropagation()`. ## Finding the entity that carries a behavior Picking returns the entity whose `Visual` was hit, often a child of the entity that has the behavior. `closest(entity, trait)` returns the entity itself or its nearest ancestor up `ChildOf` with the trait: ```ts import { closest, Pointer, Spin } from "@pawnjs/core"; engine.plugin(Pointer).on("click", ({ entity }) => { const spinning = closest(entity, Spin); if (spinning) spinning.set(Spin, { speed: 0 }); }); ``` `Hoverable` and `Clickable` find their entity this way. --- --- url: /pawn/docs/guide/prefabs.md description: >- Prefabs (definePrefab, engine.spawn, variants, params, named children, engine.prefabs, prefabs as JSON) and the Spawner behavior that spawns waves of them as data. --- # Prefabs and spawning A **prefab** is one kind of entity (a balloon, a tower, a pump): its traits with their params, its [presets](./behaviors.md#presets), its look and its children. A preset says how an entity behaves; a prefab says what it is, and may use presets. `engine.spawn(prefab, overrides)` makes a whole entity from one in a single call: ```ts import { definePrefab, defineTrait, Position, Shape } from "@pawnjs/core"; const Health = defineTrait({ name: "health", params: { hp: { default: 100, min: 0 } }, }); const Barrel = definePrefab({ name: "barrel", traits: [Position, [Shape, { kind: "cylinder" }]], }); export const Tower = definePrefab({ name: "tower", traits: [Position, [Shape, { kind: "box" }], [Health, { hp: 50 }]], presets: [Button3D], children: [[Barrel, { position: { y: 1 } }]], }); const tower = engine.spawn(Tower, { position: { x: 2, z: -1 }, health: { hp: 80 }, hoverable: { tint: "#f59e0b" }, }); ``` `engine.spawn` also takes a prefab's registered name, and a third argument (below). `spawnPrefab(engine, prefab, overrides, options)` is the same as a function, for code that holds an engine but is not a method. * `description` says what the prefab is in a sentence (`"Storage rack, 2.4 m tall."`), for people and agents reading a catalog. It is on `prefab.description` (`""` for none), and a variant without one (or with `""`) keeps its base's. * `traits` lists traits and behaviors made by `defineTrait` or `defineBehavior`, alone or with params, each at most once (also across the presets' behaviors). Behavior plugins install as usual. * `visual(entity)` builds the entity's `Visual` once its traits are on, so it can read them (a mesh in the color a trait holds). It is code, not data; for a look that snapshots save, list `Shape` or `Model` instead. Share its geometries and materials between entities, or free those one entity makes for itself with `disposeVisual` (see [Rebuilding the look](#rebuilding-the-look)). * `children` are prefabs, alone or with overrides, spawned under the entity with `ChildOf`. * Overrides are keyed by trait or behavior name and merged over the prefab's params; lists and objects are copied per entity. An override may also name a trait the prefab lacks but `engine.traits` has (`position`, `tint`, `rigid-body`), which is then added. * Overrides are type-checked: a name the prefab does not have (`helth`), or a param of the wrong type, is a TypeScript error. Core traits (`position`, `rotation`, `scale`, `tint`, `shape`, `light`, `model`) may always be named; other registered traits go through a spawn by registered name, which is not checked. * The third argument places the entity: `{ parent, id, scope }` puts it under a parent, gives it an `EntityId` and adds it to a [scope](./engine.md#scopes). * A behavior in the prefab that adds a default trait (`FollowPath` adds `Position`) gets the one the prefab or an override gives. Params are checked like a preset's: `definePrefab` throws on bad params of its traits and children, and a spawn on an override naming an unknown trait or not fitting its trait, before anything is spawned. ## Rebuilding the look A `visual` reads its traits once, when the entity spawns. When a trait describes the whole look (a sign's size, a track's course), list it in `rebuildOn`: setting or adding it, by hand or by a snapshot restore, builds the `Visual` again. The new one takes the old one's place in the scene, under the same parent and over the same children. `disposeVisual` frees a `Visual` the prefab built once it is gone: replaced by a rebuild or by hand, removed with its entity, or when the engine is disposed. ```ts import { definePrefab, defineTrait, disposeObject3D, Position } from "@pawnjs/core"; import { BoxGeometry, Mesh, MeshStandardMaterial } from "three"; const Board = defineTrait({ name: "board", params: { width: { default: 4, min: 1 }, color: { default: "#38bdf8" } }, }); const Billboard = definePrefab({ name: "billboard", traits: [Position, Board], visual: (entity) => { const { width, color } = entity.get(Board) ?? { width: 4, color: "#fff" }; return new Mesh( new BoxGeometry(width, 2, 0.2), new MeshStandardMaterial({ color }), ); }, rebuildOn: [Board], disposeVisual: disposeObject3D, }); const board = engine.spawn(Billboard); board.set(Board, { width: 8 }); // a new, wider mesh; the old one is freed ``` * Only traits the prefab lists may be in `rebuildOn`. Each one makes every `updateEach` that writes it compare values, so keep traits written every frame out. * A `Visual` set by hand wins, as for `Shape`: the prefab's is freed and no longer rebuilt. * A variant without a `visual` of its own keeps its base's `rebuildOn` and `disposeVisual`; one with its own visual starts without them. ## Variants `extends` makes a prefab a variant of another: it starts from the base's traits, presets, look, children and params. Its own traits replace the params of the same trait in the base, merged over them, or add new ones. ```ts const Enemy = definePrefab({ name: "enemy", traits: [Health, FollowPath, Shape, [Burst, { on: "died" }]], }); export const Tank = definePrefab({ name: "enemy-tank", extends: Enemy, traits: [ [Health, { hp: 16, max: 16 }], [FollowPath, { speed: 0.9 }], [Shape, { kind: "box", color: "#7c3aed" }], [Burst, { count: 18 }], // still on "died" ], }); ``` A variant cannot take a trait away; put what not every variant has in the variants instead. ## Prefab params `params` gives names to params of the prefab's traits, so a spawn sets one value in several places without knowing which traits hold it. Each name lists `"trait.param"` paths, checked by TypeScript and by `definePrefab`: ```ts const Balloon = definePrefab({ name: "balloon", traits: [Shape, [Burst, { on: "click" }]], params: { color: ["shape.color", "burst.color"] }, }); engine.spawn(Balloon, { color: "#f43f5e" }); ``` A param's value has the type of its first path. A trait named in the same overrides wins over a param (`{ color: "red", shape: { color: "blue" } }` gives a blue shape and a red burst). A param may not be named like a trait or a child of the prefab. ## Named children `children` is a list, or an object that names each child. Spawn overrides then reach a named child by its name, and `childNamed` finds it under a spawned entity: ```ts const Turret = definePrefab({ name: "turret", traits: [Position, [Shape, { kind: "cylinder" }], Spin], }); const Tower = definePrefab({ name: "tower", traits: [Position, [Shape, { kind: "box" }]], children: { turret: [Turret, { position: { y: 1 } }] }, }); const tower = engine.spawn(Tower, { turret: { spin: { speed: 3 } } }); const turret = childNamed(tower, "turret"); ``` A child's own prefab params work under its name too (`{ turret: { color: "#f00" } }` for a turret with a `color` param), and win over the parent prefab's override of the same trait. A variant's named child replaces the base's child of the same name. ## Which prefab an entity is Every entity spawned from a prefab gets `PrefabOf`, which holds the prefab's name and its name among its parent's children (`slot`), and snapshots save. It also gets the prefab's `tag`, and the tags of the prefabs it is a variant of, for queries: ```ts for (const enemy of engine.world.query(Enemy.tag, Position)) { // every enemy, variants included } Enemy.is(entity); // whether it was spawned from Enemy or a variant ``` `isPrefab(value)` tells a prefab from anything else. ## Prefabs by name `engine.prefabs` is a `PrefabRegistry`. Register prefabs there and data can name them: `engine.spawn` takes a name, and a [`Spawner`](#spawner)'s waves list names. ```ts engine.prefabs.register(Runner, Tank); engine.spawn("tank", { position: { x: 2 } }); engine.prefabs.get("tank"); // Tank ``` Registering a prefab also registers its traits and behaviors (its base's and children's too) in `engine.traits`, so [snapshots](/guide/snapshots) save and restore them. Registering the same prefab again does nothing; another prefab under a taken name throws, as does a trait of it whose name another trait has, and so does spawning a name nothing is registered as. For hot module replacement, which runs `definePrefab` again, `engine.prefabs.replace(prefab)` puts the new prefab and its traits in place of the old ones; entities spawned before keep what they have. ## Prefabs as data `prefabToJSON(prefab)` writes a prefab as plain data, for a file, an editor or an agent, and `prefabFromJSON(engine, json)` reads it back. Traits are named as `engine.traits` knows them, and the base and children as `engine.prefabs` does, so register them first: ```ts import { prefabFromJSON, prefabToJSON } from "@pawnjs/core"; const json = prefabToJSON(Tank); // { name: "enemy-tank", extends: "enemy", traits: { health: { hp: 16, max: 16 } } } const Boss = prefabFromJSON(engine, { name: "enemy-boss", extends: "enemy", traits: { health: { hp: 80, max: 80 }, shape: { kind: "torus" } }, }); engine.prefabs.register(Boss); ``` * A variant is written as its base's name and what it adds or changes; its `description` only when it has its own. * Presets are written as their behaviors, so the prefab read back lists them as traits. * A prefab with its own `visual` cannot be written: that is code. Use `Shape` or `Model` for a look that is data. * `prefabFromJSON` checks the data like `definePrefab` and throws with every problem found. Its overrides are checked when spawned, not by TypeScript. `toJSONSchema(prefab)` describes the overrides a prefab's spawns take, as JSON Schema: its traits and behaviors, the core traits (`CORE_TRAITS`, which any prefab's overrides may name), its params and its named children, with the prefab's `description`. To read a prefab in code, `prefabTraits(prefab)` lists its traits and behaviors (its presets' ones too) by name, `prefabParamSpec(prefab, "color")` gives a prefab param's spec, and `prefabValue(prefab, "trait.param")` gives the value a spawn without overrides gets: ```ts import { prefabTraits, prefabValue } from "@pawnjs/core"; [...prefabTraits(Tank).keys()]; // ["health", "follow-path", "shape", "burst"] prefabValue(Tank, "health.hp"); // 16 ``` `resolvePrefab(prefab, overrides, engine)` applies overrides without spawning: each entity's traits with their params, its children, and what is wrong with the overrides. `resolvedValue` reads a param from it: ```ts import { resolvedValue, resolvePrefab } from "@pawnjs/core"; const tank = resolvePrefab(Tank, { health: { hp: 30 } }, engine); tank.problems; // [] resolvedValue(tank, "health.hp"); // 30 tank.traits.map(({ trait }) => trait.name); // ["health", "follow-path", "shape", "burst"] ``` [Snapshots](/guide/snapshots#entities-from-prefabs) save an entity from a registered prefab as the prefab's name and what differs from it. ## Spawner `Spawner` spawns waves of registered prefabs at its entity's world position, such as enemies in a game or vehicles in a simulation. The waves are data: ```ts import { Position, Spawner } from "@pawnjs/core"; engine.prefabs.register(Runner, Tank); const gate = engine.world.spawn( Position({ x: -6 }), Spawner({ waves: [ { spawns: [{ prefab: "runner", count: 6 }], every: 1 }, { spawns: [ { prefab: "runner", count: 8 }, { prefab: "tank", count: 2, overrides: { health: { hp: 30 } } }, ], every: 0.8, }, ], pause: 3, overrides: { "follow-path": { points } }, }), ); engine.events.on(gate, "spawn", ({ entity }) => track(entity)); engine.events.on(gate, "spawnerend", () => win()); ``` * Each wave starts `pause` seconds after the previous one ended (the first `pause` seconds after the spawner is added). It spawns its groups in order, one entity every `every` seconds, the first at once. * A wave ends once all its entities are destroyed. With `enableWaitForClear: false` it ends as soon as the last one is spawned. * Spawned entities get `overrides`, then their group's `overrides`, over the prefab's params, and `position` at the spawner unless an override sets it. Overrides name traits, children or prefab params (`{ color: "#f00" }`), as in `engine.spawn`; the type is `SpawnOverrides`. They get `SpawnedBy(spawner)` and join the spawner's [scope](./engine.md#scopes). * The spawner gets entity events: `wavestart` and `waveend` with the 1-based `wave`, `spawn` with the `entity` and `wave`, and `spawnerend` after the last wave. * `wave`, `stage` (`"waiting"`, `"spawning"`, `"clearing"`, `"done"`), `time` and `spawned` hold the progress, so snapshots keep it. Remove `Spawner` to stop it. * Time is scaled engine time. A prefab that is not registered stops the spawner with an error. --- --- url: /pawn/docs/guide/snapshots.md description: >- Saving and restoring worlds as JSON snapshots, the trait registry and EntityId. --- # Saving scenes A **snapshot** is the serializable part of a world as plain JSON: which entities exist, how they nest, and the data of their traits. Save it to a file or a database, send it over the network, have an agent write one, and restore it into any engine. ```ts const saved = engine.snapshot(); localStorage.setItem("scene", JSON.stringify(saved)); const errors = engine.restore(JSON.parse(localStorage.getItem("scene")!)); if (errors.length > 0) console.warn(errors); ``` ```json { "version": 1, "entities": [ { "id": "pump-1", "parent": "site", "traits": { "position": { "x": 0, "y": 1, "z": 0 }, "shape": { "kind": "cylinder", "color": "#38bdf8" }, "hoverable": { "tint": "#6366f1", "amount": 0.3, "cursor": "pointer" } } } ] } ``` ## Entity ids Only entities with an `EntityId` are saved. The id is a stable string you choose; koota's entity numbers change between runs. `engine.findEntity(id)` returns the entity with an id: ```ts import { EntityId, Position } from "@pawnjs/core"; world.spawn(EntityId({ id: "pump-1" }), Position); engine.findEntity("pump-1"); ``` An id belongs to one entity. When a second entity takes an id already in use, a warning is logged and the first one keeps it. Feeds of [`@pawnjs/data`](/packages/data#feed-options) give their entities ids from their keys. ### One entity per key `KeyedEntities` keeps one entity per key of your own data, the way feeds, the [json-render renderer](/packages/json-render) and `restore` do. An entity that already has a key's id, such as one restored from a snapshot, is taken over instead of spawning another, and one destroyed elsewhere is spawned again: ```ts const pumps = new KeyedEntities(engine, { id: (key) => `pump-${key}`, }); for (const pump of data) { const entity = pumps.ensure(pump.id, () => engine.spawn("pump")); entity?.set(Position, { x: pump.x }); } pumps.retain(new Set(data.map((pump) => pump.id))); // destroys the rest ``` * `ensure(key, spawn)` returns the key's entity, takes one over by id, or calls `spawn`; `claim(key, accept?)` does the first two only, and `set(key, entity)` records one you spawned. * `get`, `has`, `keys()` and `size` read it; `delete(key)`, `retain(keys)` and `clear()` let entities go, through `release` when you pass one (default: destroy). ## Which traits are saved A snapshot saves the traits in `engine.traits`, a `TraitRegistry` of names (`register(trait)`, `replace(trait)`, `get(name)`, `values()`): | Name | Trait | |---|---| | `position`, `rotation`, `scale` | transforms | | `model` | [`Model`](/guide/assets) (a glTF url) | | `tint`, `shape` | [`Tint` and `Shape`](/guide/entities#shape) | | `link` | [`Link`](/guide/entities#link) | | a behavior's name | every [behavior](/guide/behaviors) whose plugin is installed | | a trait's name | every trait and behavior of a prefab registered in [`engine.prefabs`](/guide/prefabs#prefabs-by-name) | | `rigid-body`, `collider`, `character-controller` | [`RigidBody`, `Collider` and `CharacterController`](/packages/physics#snapshots), once `Physics` is installed | `ChildOf` is saved as `parent`, the parent's id. `Visual` and `Label` hold a three.js object or an HTML element and are not saved; for a scene that round-trips, draw with `Shape` or `Model`. Tweens and other state that lives only while something runs are not saved either. Define your own traits with `defineTrait`: its params describe each field once, with a default and, optionally, `min`, `max`, `enum` and a `description`, like a [behavior's params](/guide/behaviors). The result is an ordinary koota trait that knows its name, so it can be registered as is: ```ts import { defineTrait } from "@pawnjs/core"; const Health = defineTrait({ name: "health", params: { hp: { default: 100, min: 0 }, tags: { default: (): string[] => [] }, // lists and objects: a factory }, }); world.spawn(Health({ hp: 50 })); engine.traits.register(Health); ``` `paramDefaults(Health.params)` returns a full value of defaults, factories called. ## Entities from prefabs An entity [spawned from a prefab](/guide/prefabs) registered in `engine.prefabs` is saved as the prefab's name and only what differs from it: the changed fields of its traits, and in `removed` the prefab's traits it no longer has. Restoring spawns a missing one from the prefab, children and look included, then applies the differences, so register the prefabs before restoring. A change to the prefab reaches saved entities that did not change that field. A named child saved with its own id, under a parent that also has one, takes over the copy of it the prefab spawns. ```json { "id": "tank-1", "parent": null, "prefab": "enemy-tank", "traits": { "position": { "x": 4 }, "health": { "hp": 9 } }, "removed": ["bob"] } ``` ## Restoring `engine.restore(snapshot)` makes the world's entities with an id match the snapshot: * entities it lists are created, or updated when they exist; * their registered traits are set to the saved values, filled in with defaults, and registered traits they do not list are removed. A trait that already has those values is not set again, so restoring the state the world is in changes nothing; * parents are set once every entity exists. A parent must be in the snapshot; a parent without an id, which is saved as `null`, is kept; * entities with an id it does not list are destroyed. Entities without an id are left alone. A behavior's plugin is installed when a snapshot uses it, so register the behaviors a snapshot may contain before restoring into a fresh engine: ```ts engine.traits.register(Hoverable); engine.traits.register(TweenOn); engine.restore(saved); ``` Restoring does not stop at the first problem. Each trait is checked like [preset params](/guide/behaviors#presets): types, `min`, `max`, `enum` and `schema`. An invalid trait or parent is skipped, the rest is applied, and `restore` returns one message per problem. A field the trait no longer has, say a param renamed since the save, is skipped on its own, so older saves still load: ```ts [ 'pump-1: unknown trait "sparkle".', 'pump-1: health: skipped unknown param "hitPoints".', "pump-1: tint.amount: 2 is above the maximum 1.", 'pump-2: parent "site" is not in the snapshot or the world.', ] ``` ## JSON Schema `toJSONSchema(behavior)` describes a behavior's params as JSON Schema, for validating snapshots elsewhere, building an editor, or telling an agent what it may write. A registered trait works too: ```ts import { Shape, toJSONSchema } from "@pawnjs/core"; toJSONSchema(Hoverable); toJSONSchema(Shape); // a trait from defineTrait ``` Given a prefab, `toJSONSchema` describes the overrides its spawns take (see [Prefabs as data](/guide/prefabs#prefabs-as-data)). --- --- 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({ 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). --- --- url: /pawn/docs/guide/testing.md description: >- Testing and debugging: seeded random numbers (engine.random), headless test helpers from @pawnjs/core/testing, and the Debug overlay with an entity inspector. --- # Testing and debugging An engine runs headless: without a canvas it skips drawing, and with a `ManualDriver` time moves only when the code says so. That makes game and dashboard logic testable with any test runner; [Headless](./headless.md) shows what runs without a page and how to write a scene for both. Three things help. ## Random numbers from a seed `engine.random` gives random numbers from a seed. The same seed gives the same numbers, so a run with a seed plays out the same way every time: in a test, a replay or a bug report. Use it instead of `Math.random()` in systems and behaviors. ```ts import { Engine } from "@pawnjs/core"; const engine = new Engine({ canvas, seed: 42 }); const { random } = engine; random.next(); // 0..1, like Math.random() random.range(-1, 1); // -1 up to (not including) 1 random.int(1, 6); // a die: 1, 2, 3, 4, 5 or 6 random.chance(0.1); // true one time in ten random.pick(["runner", "tank"]); random.shuffle([1, 2, 3]); ``` * Without `seed` the engine picks a new one each time; read it back from `engine.random.seed`, say to log it with an error and replay the run. * `random.state` is where the sequence is: save it and set it back to repeat the numbers from that point. `random.reseed(seed)` starts over. * Core behaviors that need chance (`burst`, `SoundOn`'s pitch `variation`) use `engine.random`. * `Random` is also exported on its own: `new Random(seed)`, or `new Random()` for a seed from `Random.newSeed()` (`Math.random()`). ## Test helpers `@pawnjs/core/testing` creates engines for tests and moves them through time. ```ts import { Position, Velocity } from "@pawnjs/core"; import { createTestEngine, runFor, runUntil } from "@pawnjs/core/testing"; const engine = createTestEngine(); const ball = engine.world.spawn(Position, Velocity({ y: 1 })); runFor(engine, 2); // two seconds in frames of 1/60 s ball.get(Position)?.y; // 2 const seconds = runUntil(engine, () => (ball.get(Position)?.y ?? 0) > 5); engine.dispose(); ``` * `createTestEngine(config?)` is a headless engine driven only by `engine.step()`, with `engine.random` seeded by `TEST_SEED` (1). Any `EngineConfig` goes over these defaults. * `runFor(engine, seconds, { step })` steps the engine through `seconds` in equal frames (`TEST_STEP`, 1/60 s, unless `step` says otherwise) and returns how many ran. * `runUntil(engine, done, { step, timeout })` steps until `done()` is true and returns the seconds it took; after `timeout` seconds (60 by default) it throws. * Drive the pointer from code with `Pointer`'s `moveTo`, `press` and `release`; see [Input](./input.md). ## Debug overlay and inspector `Debug` shows what the engine is doing while an app is built: frames a second, milliseconds spent in each phase's systems, entities in the world and how many have each trait. Click an entity to inspect it: the panel lists its traits with their values, and numbers, switches, text and choices can be changed live. ```ts import { Debug } from "@pawnjs/core"; engine.use(new Debug({ visible: false })); // e.g. in development builds only const debug = engine.plugin(Debug); debug.visible = true; // or press ` (backquote, left of 1) debug.select(entity); const { fps, entities, phaseMs } = debug.stats; ``` * `debug.selected` is the entity the inspector shows (`select(undefined)` clears it). * The backquote key shows and hides the overlay; `toggleKey` changes it (`""` for none). `visible` sets whether it starts shown. * Clicking an entity while the overlay is shown selects it, once the engine has a `Pointer`; `enablePick: false` turns that off. * `stats` holds `fps`, `phaseMs` (milliseconds in systems per phase), `systemsMs` (all phases), `entities` and `traits` (entities per registered trait, most first, without zeros). * `stats` is averaged over `interval` seconds (0.5 by default) and `subscribe(listener)` hears each update and each new selection. Without a page (a test, a server), or with `enableOverlay: false`, `Debug` only gathers the data. * `inspect(entity)` returns the entity's traits, their params and values as data, for a panel of your own. * The inspector lists the traits in `engine.traits`: core transforms, `Tint`, `Shape`, behaviors, and your own traits from `defineTrait` once registered with `engine.traits.register(Trait)`; see [Saving scenes](./snapshots.md). --- --- url: /pawn/docs/guide/plugins.md description: Writing and installing plugins that add systems, traits and observers. --- # Plugins A plugin extends an engine with systems, traits and world observers. Every add-on package ships as one, and so does [`Input`](./input). ```ts engine.use(new Input()).use(new Tween()); engine.hasPlugin(Tween.NAME); // true engine.getPlugin(Tween.NAME); // the installed plugin engine.plugin(Input); // the installed Input, or a new default one engine.plugin(Input); // the same, as a shortcut ``` `engine.use(plugin)` calls `plugin.install(engine)` once. Using the same plugin object again does nothing; installing a different plugin with the same name throws, and so does installing on a disposed engine. `install` may return a cleanup function, which `engine.dispose()` runs in reverse install order. Plugins are classes that take one config object, keep their name in `static NAME` (`"@pawnjs//"`) and, when they add a system, its default order in `static ORDER`. `engine.plugin(Class)` returns the installed plugin of a class or installs one with the default config: ```ts const pointer = engine.plugin(Pointer); engine.plugin(Sound).tone({ frequency: 660 }); ``` To configure one, `engine.use(new Pointer({ dragThreshold: 12 }))` before anything asks for it. `engine.getPlugin(name)` only looks, by `NAME`. For a plugin an engine may run several of, such as `CameraRig` and `ChaseCamera`, `engine.plugin(Class)` returns the first one installed. ## Traits that bring their plugin A trait that only works with a plugin says which one with `usesPlugin`. An engine then installs that plugin, with its default config, when an entity of its world first gets the trait, so nobody has to remember it. `Label` brings `Labels`, `Model` brings `Assets`, the tween traits bring `Tween` and `Smooth` brings `Smoothing`; behaviors bring theirs the same way. A plugin installed before that, with a config of your own, is the one used. ## Writing a plugin ```ts import { type Engine, type PawnPlugin, Position } from "@pawnjs/core"; import { trait } from "koota"; export const Float = trait({ height: 0.5, speed: 2 }); export class Floating implements PawnPlugin { static readonly NAME = "my-game/floating"; static readonly ORDER = 0; readonly name = Floating.NAME; install(engine: Engine) { return engine.addSystem( ({ world, elapsed }) => { world.query(Float, Position).updateEach(([float, p]) => { p.y = Math.sin(elapsed * float.speed) * float.height; }); }, { order: Floating.ORDER }, ); } } ``` `engine.addSystem()` returns a function that removes the system, which makes a fine cleanup. A plugin an engine may run several of sets `static readonly MULTIPLE = true` and gives each instance its own `name` (`CameraRig` uses `` `${CameraRig.NAME}#${n}` ``). `usesPlugin(Float, Floating)` after the class makes `entity.add(Float)` install `Floating`. To react to entities gaining or losing a trait, subscribe with koota's `engine.world.onAdd(trait, callback)` and `engine.world.onRemove(trait, callback)`, and unsubscribe in the cleanup. Add-on packages peer-depend on `@pawnjs/core` and `koota`, and on `three` when they import it; the core never imports an add-on. --- --- url: /pawn/docs/guide/stability.md description: >- What a Pawn. version promises: semver 0.x, one version for all packages, ESM only, supported environments, pinned peers and experimental packages. --- # Versions and stability Pawn. follows [semver](https://semver.org) for 0.x versions: * **A patch fixes.** `0.1.0` to `0.1.1` changes no public API. * **A minor may break.** `0.1.x` to `0.2.0` may change or remove public API. Every break is listed in the package's `CHANGELOG.md`, with what to change. * **Prereleases break between themselves.** Until `0.1.0` every version is `0.1.0-alpha.N`, and any of them may break. All `@pawnjs/*` packages share one version. Install the same version of each, as `bun create pawn` does. Public API is what a package exports and these docs describe. Direct access to a library underneath, such as `physics.rapierWorld`, follows that library's versions instead. ## Modules and environments * **ESM only.** The packages have `import` exports and no `require`. * **Browsers** with WebGL 2, which three.js needs. * **Bun and Node.** The packages load in Node's ESM loader; tests and headless engines are tested with Bun, as these docs show. The starter runs with Bun or Node 20.12 or later, and its templates build with Vite 8. * **React** 19 or later, for `@pawnjs/react`. * **TypeScript** needs `@types/three` next to `three`: without it, the three.js types in the Pawn. API are `any`, silently when `skipLibCheck` is on (as in the starter). Its versions follow `three`'s. ## Peer dependencies * **koota** is pinned to one minor, `^0.6.6` today; install `0.6.6` exactly for the [koota patch](./getting-started.md#install). Its types (`Entity`, `World`, `Trait`) are part of the Pawn. API, so a new koota minor comes with a new minor of Pawn. * **three** is supported from `0.186.0`, below `0.200.0`; the repository tests with `0.186.1`. A version of Pawn. that tests an older or newer one widens the range. ## Packages not on npm yet A package whose page says "Not on npm yet" is experimental. Until it is published, its API may break in any version. --- --- url: /pawn/docs/guide/agents.md description: >- Rules for coding agents that build apps with Pawn: where the docs and types are, how a scene is made, and how to test it. Every @pawnjs library package ships this page as AGENTS.md. --- # For coding agents This page is for coding agents (Claude Code, Codex, Cursor...) that write apps with Pawn. Every `@pawnjs` library package ships it as `AGENTS.md`, so an agent finds it in `node_modules/@pawnjs/core/AGENTS.md` without searching; a project made with `bun create @pawnjs` points its own `AGENTS.md` and `CLAUDE.md` there. ## Where to look * The types: `node_modules/@pawnjs//dist/*.d.ts`. Every public name has JSDoc. They match the installed version, so when they and the docs differ, the types win. Do not guess an API: look it up. * The docs: [jakubprill.github.io/pawn/docs](https://jakubprill.github.io/pawn/docs/), which follow the latest version. [`llms.txt`](https://jakubprill.github.io/pawn/docs/llms.txt) lists every page with a summary, [`llms-full.txt`](https://jakubprill.github.io/pawn/docs/llms-full.txt) holds them all in one file, and each page has a Markdown copy (`.md` in place of `.html`). * Each package's `README.md` says what it is for. | Package | What it adds | |---|---| | `@pawnjs/core` | The engine, entities and traits, shapes, lights, cameras, input, sound, models, behaviors, prefabs, snapshots, test helpers (`@pawnjs/core/testing`). | | `@pawnjs/react` | ``, `` and hooks; read world state with `koota/react`. | | `@pawnjs/tween` | Tweens of position, rotation and scale. | | `@pawnjs/physics` | Rapier rigid bodies, colliders (meshes and heightfields too), a character controller, collision events. Not on npm yet. | | `@pawnjs/data` | One entity per item of a live feed. Not on npm yet. | | `@pawnjs/maps` | A scene on a Google map. Not on npm yet. | | `@pawnjs/json-render` | Scenes generated as JSON from a catalog of prefabs. Not on npm yet. | ## How a Pawn app is built Pawn is an ECS on [koota](https://github.com/pmndrs/koota) and three.js. An entity is an id, a trait is data on it, a system is a function the engine runs each frame. Write the scene in those terms, not as three.js objects. ```ts import { Engine, Shape, Spin } from "@pawnjs/core"; const canvas = document.querySelector("#scene"); if (!canvas) throw new Error("no canvas"); // The quick start options set up a camera, a background and lights. const engine = new Engine({ canvas, camera: { position: { y: 1.5, z: 4 } }, lights: "studio", }); engine.spawn(Shape({ kind: "box", color: "#6366f1" }), Spin({ speed: 1 })); engine.start(); ``` * **Spawn entities with traits** (`engine.spawn(...)`). `Shape` draws a primitive, `Model` a glTF file, and `Visual(object)` any three.js object you made. Do not add meshes to `engine.scene` yourself: the engine adds, moves and removes the visuals of entities. * **Move things by their traits**: `Position`, `Rotation` (a quaternion; `euler()` makes one from angles) and `Scale`. The engine copies them into three.js before drawing. `entity.set(Trait, value)` needs the trait on the entity; `put(entity, Trait, value)` adds it when missing. * **A kind of entity is a prefab** (`definePrefab`): its traits with defaults, spawned by `engine.spawn(Prefab)`, with overrides checked against its params. **What one entity does is a behavior** (`defineBehavior`), and a bundle of behaviors is a preset. Look for a built-in first: `Hoverable`, `Clickable`, `Spin`, `SoundOn`, `FlashOn`, `Spawner` and more. * **Logic across many entities goes in systems** (`engine.addSystem(fn, { phase })`; the default phase is `update`, physics steps in `fixedUpdate`). Take time from the system's `delta`, never from `Date.now()`, and random numbers from `engine.random`, never `Math.random()`, so a run can be replayed. * **Plugins are classes**: `engine.plugin(Class)` returns the installed one and installs a default one when missing. * **Input goes through `Input` or `Actions`** (named actions over keys, mouse, touch and swipes, gamepad, tilt and on-screen buttons, with `pressedWithin()` / `sequence()` for buffered presses), and clicks on entities through `Clickable` and entity events (`engine.events`), not DOM listeners on the canvas. * **With React**, `` creates the engine and hooks such as `useSystem` and `useSpawn` replace `engine.addSystem` and `engine.spawn`. * **Dispose what you create**: `engine.dispose()` when the scene goes away, and on a hot reload. ```ts import { Engine, Position, type System } from "@pawnjs/core"; import { trait } from "koota"; const engine = new Engine(); const Drift = trait({ x: 0, y: 0, z: 0 }); const move: System = ({ world, delta }) => { world.query(Drift, Position).updateEach(([d, p]) => { p.x += d.x * delta; p.y += d.y * delta; p.z += d.z * delta; }); }; engine.addSystem(move); engine.spawn(Position, Drift({ x: 1 })); ``` One koota trap: a query with `Changed(Trait)` does not see values another system wrote with `updateEach`, unless something subscribes to `onChange(Trait)`. Write with `entity.set()` when another system must notice the change. ## Test it headless An engine without a canvas runs without a page, so scene logic is tested like any other code. `@pawnjs/core/testing` makes an engine whose time moves only when the test says so. ```ts import { Position, Velocity } from "@pawnjs/core"; import { createTestEngine, runFor } from "@pawnjs/core/testing"; import { expect, test } from "bun:test"; test("the ball rises", () => { const engine = createTestEngine(); const ball = engine.spawn(Position, Velocity({ y: 1 })); runFor(engine, 2); // two seconds of frames expect(ball.get(Position)?.y).toBeCloseTo(2); engine.dispose(); }); ``` A test sends clicks and other entity events itself: `engine.events.emit(entity, "click", { button: 0, point: undefined })`. --- --- url: /pawn/docs/packages/react.md description: , , and hooks. --- # @pawnjs/react React bindings: a component that owns an engine, a component that draws a view into page layout, and hooks for systems and entities. Read world state in UI with koota's own `koota/react` hooks (`useQuery`, `useTrait`, ...). The core does not need React; this package is optional. It needs React 19. ## `` Creates an engine on its own canvas, keeps it sized to the container, starts it, and provides it (and its koota world) to children. The engine is disposed on unmount. ```tsx import { Position, Rotation, Visual } from "@pawnjs/core"; import { Pawn, useSpawn, useSystem } from "@pawnjs/react"; import { useQuery } from "koota/react"; function App() { return ( ); } ``` | Prop | Meaning | |---|---| | `config` | Engine options such as `lights` and `background` (all but `canvas`, `renderer`, `camera` and `fit`); read once, on mount. | | `camera` | Camera of the default full-canvas view, or [camera options](../guide/engine#creating-an-engine) for one; read once. Defaults to a perspective camera at `(0, 2, 6)` looking at the origin. Pass `null` to start without views. | | `onCreated` | Called for each engine `` creates, once it is running. Install plugins here. React's `StrictMode` mounts twice in development, so it gets two engines, and the first one is disposed right after. | | `className`, `style` | For the container `

`. | | `canvasStyle` | Extra style for the canvas; when given, the canvas's own box decides its size. | | `children` | Rendered once the engine exists. | To draw only when something changes, pass a [`DemandDriver`](../guide/engine#render-on-demand) in `config` (`driver: new DemandDriver()`). Traits your UI sets (through koota's hooks or `entity.set`) are seen as long as they move or restyle what is drawn. Without WebGL (a GPU turned off, a remote desktop) `` throws [`WebGLUnavailableError`](../guide/engine#without-webgl) when it mounts; an error boundary around it shows a page without 3D instead. Pass `onContextLost` and `onContextRestored` in `config` for a context lost later. Plugins that load asynchronously (physics) can be installed from `onCreated`. The engine may be disposed by the time they load (an unmount, or `StrictMode`'s first mount), and `engine.use` throws on a disposed engine, so check first: ```tsx { const physics = await createPhysics(); if (!engine.disposed) engine.use(physics); }} /> ``` ## `` Renders its children in an element pinned to an entity on screen, through the core [`Labels`](/guide/labels) plugin (installed on first use). Use it inside ``; the element sits over the canvas in ``'s container. ```tsx function NodeTag({ entity, name }: { entity: Entity; name: string }) { return ( ); } ``` | Prop | Meaning | |---|---| | `entity` | Entity to follow; nothing is shown while it is `undefined`. | | `offset`, `align`, `view` | As for the `Label` trait. | | `className`, `style` | For the label element; the plugin owns its position, transform and visibility. | ## Hooks ### `useEngine()` Returns the engine of the closest ``. Throws outside of one. ### `useSystem(system, options?)` Runs a system while the component is mounted. The latest `system` is always called, so it may close over props and state. `options` takes `phase` and `order`, as in `engine.addSystem()`. ```tsx function Spinner() { useSystem(({ world, elapsed }) => { world.query(Orbit, Position).updateEach(([orbit, p]) => { p.x = Math.cos(elapsed * orbit.speed) * orbit.radius; p.z = Math.sin(elapsed * orbit.speed) * orbit.radius; }); }); return null; } ``` ### `useSpawn(factory, deps)` Spawns an entity while the component is mounted and destroys it on unmount or when `deps` change. `factory` returns what `engine.spawn` takes: traits, or a prefab (or its registered name) with overrides, such as `() => [Tower, { position: { x: 2 } }]`. Returns the entity, or `undefined` before the first effect. ```tsx function Orbiter({ radius }: { radius: number }) { useSpawn( () => [Position, Rotation, Orbit({ radius, speed: 1 }), Visual(new Mesh(geometry, material))], [radius], ); return null; } ``` ### `useEntityEvent(entity, type, listener)` Listens to an [entity event](/guide/behaviors#entity-events) while the component is mounted, also for events bubbling up from the entity's children. The latest `listener` is called, so it may use props and state. `entity` may be `undefined`, such as the result of `useSpawn` before its first effect; nothing is listened to then. ```tsx function Crate() { const [clicks, setClicks] = useState(0); const crate = useSpawn(() => [Shape({ kind: "box" }), Clickable], []); useEntityEvent(crate, "click", () => setClicks((n) => n + 1)); return

Clicked {clicks} times

; } ``` ### `useAssetProgress()` Returns `{ loaded, total }` for the glTF files loading now, from the `AssetProgress` world trait that the engine's [`Assets`](../guide/assets.md) plugin keeps; without the plugin it returns `{ loaded: 0, total: 0 }`. Re-renders as files finish. ```tsx function LoadingBar() { const { loaded, total } = useAssetProgress(); return loaded < total ? : null; } ``` ### Reading the world in UI `` wraps children in koota's `WorldProvider`, so `koota/react` hooks work directly: ```tsx function Count() { const orbiters = useQuery(Orbit); return {orbiters.length} entities; } ``` ## Views in page layout `` is a `
` the engine draws a view into. The view follows the element's box as the page lays out and scrolls. Put the `` canvas over the whole page and start it without a default view: ```tsx import { Pawn, PawnView } from "@pawnjs/react";
{cards.map((card) => (

{card.title}

))}
``` | Prop | Meaning | |---|---| | `camera` | Camera drawn into this element's box. A new camera creates a new view. | | `background` | Clear color of the view; `null` (default) keeps what is underneath. | | `name`, `className`, `style` | Passed to the view and the `
`. | | `children` | Page content laid over the view. | Because the canvas lets pointer events through, install [`Input`](../guide/input) with `element: document.body` to pick through the views. The [Views example](https://jakubprill.github.io/pawn/views.html) puts it all together. --- --- url: /pawn/docs/packages/tween.md description: Tweens of Position, Rotation and Scale, easings and tweenend. --- # @pawnjs/tween Tweens of `Position`, `Rotation` and `Scale`, driven by engine time. ```bash bun add @pawnjs/core @pawnjs/tween koota@0.6.6 three bun add -d @types/three ``` ```ts import { TweenPosition, TweenScale, tween } from "@pawnjs/tween"; entity.add( TweenPosition(tween({ x: 0, y: 2, z: 0 }, { duration: 0.5, easing: "cubicOut" })), ); ``` Three spheres slide with three easings, `linear`, `cubicInOut` and `backOut`; each `tweenend` starts the next slide: ```ts import { Engine, Position, Shape, View } from "@pawnjs/core"; import { type EasingName, TweenPosition, tween } from "@pawnjs/tween"; import { AmbientLight, DirectionalLight, PerspectiveCamera } from "three"; export default function tweenDemo(canvas: HTMLCanvasElement): Engine { canvas.style.cssText = "display:block;width:100%;height:100%"; const engine = new Engine({ canvas }); engine.scene.add(new AmbientLight(0xffffff, 0.7)); const sun = new DirectionalLight(0xffffff, 2); sun.position.set(3, 6, 5); engine.scene.add(sun); // One sphere per easing, sliding from side to side. const easings: EasingName[] = ["linear", "cubicInOut", "backOut"]; easings.forEach((easing, i) => { const y = 0.9 - i * 0.9; const ball = engine.world.spawn( Shape({ kind: "sphere", color: ["#94a3b8", "#6366f1", "#f59e0b"][i] }), Position({ x: -2, y }), ); let x = 2; const slide = () => { ball.add(TweenPosition(tween({ x, y, z: 0 }, { duration: 1.2, easing }))); x = -x; }; // Each tween that plays to its end starts the next one. engine.events.on(ball, "tweenend", slide); slide(); }); const camera = new PerspectiveCamera(45, 1, 0.1, 100); camera.position.set(0, 0, 6); engine.views.add(new View({ camera, background: 0x09090b })); engine.fitToElement(canvas); engine.start(); return engine; } ``` The `Tween` plugin runs one system in the `update` phase. An engine installs it when an entity first gets a tween trait; to move the system within the phase, `engine.use(new Tween({ order }))` before that. Each tween trait changes one transform trait: | Trait | Changes | Interpolation | |---|---|---| | `TweenPosition` | `Position` | linear per axis | | `TweenScale` | `Scale` | linear per axis | | `TweenRotation` | `Rotation` | spherical (quaternion slerp) | A tween trait is removed when its tween ends, so `entity.has(TweenScale)` tells you whether one is still running. A tween that plays to its end also emits a `tweenend` [entity event](/guide/behaviors#entity-events) with the `property` it changed (`"position"`, `"rotation"` or `"scale"`): ```ts engine.events.on(entity, "tweenend", ({ property }) => { if (property === "scale") entity.add(TweenPosition(tween(next))); }); ``` An entity missing the tweened trait gets it with its default value (scale 1, for example). ## `tween(to, options)` | Option | Default | Meaning | |---|---|---| | `from` | current value | Start value; taken from the entity when the tween starts. | | `duration` | `1` | Seconds per play. | | `delay` | `0` | Seconds before the first play. | | `easing` | `"linear"` | Name of a curve in `Easing`, or a function from linear progress (0 to 1) to eased progress. | | `repeat` | `0` | Extra plays after the first; `Infinity` loops forever. | | `enableYoyo` | `false` | Play every other repeat backwards. | A pulse that grows and returns: ```ts entity.add( TweenScale( tween({ x: 1.5, y: 1.5, z: 1.5 }, { duration: 0.2, enableYoyo: true, repeat: 1, easing: "backOut" }), ), ); ``` ## Easing `Easing` has `linear`, `quadIn`, `quadOut`, `quadInOut`, `cubicIn`, `cubicOut`, `cubicInOut`, `sineInOut` and `backOut`; `EASING_NAMES` lists them. Pass a curve by name (`easing: "quadOut"`) so tween state stays plain data that can be saved. Any `(t: number) => number` works too, as an `EasingFunction`, but does not serialize. ## `TweenOn` A [behavior](/guide/behaviors) that plays a tween when an entity event reaches the entity: it scales, lifts or turns the entity from where it rests, taken when a run starts while no tween moves it. ```ts import { Clickable } from "@pawnjs/core"; import { TweenOn } from "@pawnjs/tween"; button.add( Clickable, TweenOn({ on: "click", scale: 1.1, duration: 0.15 }), ); // Down while pressed, back up on release: key.add(TweenOn({ on: "pointerdown", off: "pointerup", lift: -0.1 })); ``` | Param | Default | Meaning | |---|---|---| | `on` | `"click"` | Entity event that plays the tween. | | `off` | `""` | Entity event that plays it back; empty to go there and back on `on`. | | `scale` | `1` | Scale to reach, as a multiple of the resting scale. | | `lift` | `0` | How far to rise along Y. | | `turn` | `0` | How far to turn around Y, in radians. | | `duration` | `0.2` | Seconds to get there (and as many to get back). | | `easing` | `"quadOut"` | Curve, by name in `Easing`. | Events bubble, so a click on a child entity plays the parent's `TweenOn`. The plugin installs `Tween` if the engine has none. --- --- url: /pawn/docs/packages/data.md description: Feeds that keep one entity per item of an API or WebSocket stream. --- # @pawnjs/data ::: info Not on npm yet This package comes with a later release of Pawn. ::: Data streams as entities: one entity per item of an API response, a WebSocket or anything you push. `@pawnjs/data` imports no three.js and no DOM; it needs `@pawnjs/core` and `koota`. ```ts import { Feed, poll, smoothTo } from "@pawnjs/data"; interface Vehicle { id: string; x: number; z: number; } const vehicles = new Feed({ key: (v) => v.id, spawn: (v, engine) => engine.spawn(Visual(truck())), update: (entity, v) => smoothTo(entity, { x: v.x, z: v.z }), source: poll(() => fetch("/api/vehicles").then((r) => r.json()), { every: 2 }), }); engine.use(vehicles); ``` Deliveries are queued and applied first in the `input` phase (right after `Input`), so every system in a frame sees the same data, whenever the response arrived. `spawn` runs for a key seen for the first time and `update` for every item, new ones included. ## Feed options | Option | Default | Meaning | |---|---|---| | `key` | (required) | Identity of an item; one entity per key. | | `spawn` | (required) | `(item, engine)`: creates the entity of a new key, e.g. `engine.spawn("truck")` for a prefab, or returns an existing one (an entity the scene built). Returning `undefined` skips the item. | | `update` | none | Writes an item into its entity. | | `remove` | destroy | Lets go of the entity of a key that is gone. | | `source` | none | Delivers items while the feed is installed. | | `mode` | `"replace"` | `"replace"`: each delivery is the whole set and missing keys are removed. `"patch"`: deliveries add and change only. | | `onError` | `console.warn` | Called with errors a source reports, and with an error `spawn` or `update` throws for one item, which is skipped. | | `name` | none | Shown in the plugin name, for debugging, and the start of entity ids. | | `id` | `"/"` | [`EntityId`](/guide/snapshots#entity-ids) of a key's entity; without `id` or `name`, entities get none. | With an id, a feed's entities are saved by [snapshots](/guide/snapshots). An entity that already has the key's id, such as one restored from a snapshot, is taken over instead of spawning another. `spawn` is not called for it, so add what a snapshot does not save (a `Visual`) in `update`, or draw with `Shape` or `Model`. Ids must differ between keys and between feeds. In replace mode only the latest undelivered delivery is applied; in patch mode every delivery is applied in order. ## Reading and writing a feed * `feed.push(items)` delivers by hand, like a source does. * `feed.remove(keys)` removes keys at the next frame. * `feed.entity(key)` returns the entity of a key; `feed.keys()` and `feed.size` list them. * `feed.version` grows with every applied delivery, for cheap change checks. * `feed.dispose()` stops the source and lets go of the entities before the engine is disposed, e.g. when a React effect cleans up. ## Sources A source is a function that gets a sink (`push(items)`, `error(e)`) and returns a function that stops it. Two come with the package: ```ts // Calls the fetcher, then again `every` seconds after it settles. poll((signal) => fetch(url, { signal }).then((r) => r.json()), { every: 5 }); // Delivers each message; reconnects `retry` seconds after a close. websocket("wss://example.com/live", (data) => JSON.parse(String(data)).items, { retry: 2, }); ``` A failed fetch or a message that does not parse is reported to `onError` and the source keeps going. One response can feed several feeds: call a source with your own sink and `push` into each. ## Smooth movement Data that arrives every few seconds would make entities jump. `smoothTo` sets a `Smooth` target instead of `Position`; the first call places the entity at once, later ones let it ease there with `halfLife` (seconds to cover half of the way, default 0.3). The first `Smooth` installs the `Smoothing` plugin, with or without a feed. It runs on unscaled time. The [Energy flow](https://jakubprill.github.io/pawn/energy.html) example polls two endpoints of a simulated backend into its scene's nodes and links. --- --- url: /pawn/docs/packages/physics.md description: >- Rapier rigid bodies and colliders as traits, mesh and terrain colliders, a character controller, collision events, raycasts. --- # @pawnjs/physics ::: info Not on npm yet This package comes with a later release of Pawn. ::: [Rapier](https://rapier.rs) rigid bodies and colliders as traits, stepped in the `fixedUpdate` phase with the engine's fixed time step: primitive, mesh and terrain colliders, a character controller, collision events, raycasts and shape casts. ::: tip TypeScript Rapier's types use `Symbol.dispose`. Unless `skipLibCheck` is on (the starter turns it on), add `"ESNext"` (or `"ESNext.Disposable"`) to `lib` in `tsconfig.json`. ::: ```ts import { Position, Rotation, Visual } from "@pawnjs/core"; import { Collider, createPhysics, RigidBody } from "@pawnjs/physics"; // Rapier loads its WASM module asynchronously (once per page). const physics = await createPhysics({ gravity: { x: 0, y: -9.81, z: 0 } }); engine.use(physics); // A fixed floor. engine.world.spawn( Position, RigidBody({ type: "fixed" }), Collider({ shape: { type: "cuboid", halfExtents: { x: 5, y: 0.2, z: 5 } } }), Visual(floorMesh), ); // A bouncing ball. const ball = engine.world.spawn( Position({ x: 0, y: 5, z: 0 }), Rotation, RigidBody, Collider({ shape: { type: "ball", radius: 0.5 }, restitution: 0.6 }), Visual(ballMesh), ); ``` ## `RigidBody` Fields left out keep their defaults (`RigidBody({ type: "fixed" })`): | Field | Default | Meaning | |---|---|---| | `type` | `"dynamic"` | `"dynamic"`, `"fixed"`, `"kinematicPosition"` or `"kinematicVelocity"`. | | `linearDamping` | `0` | | | `angularDamping` | `0` | | | `gravityScale` | `1` | | | `ccd` | `false` | Continuous collision detection, for fast and small bodies. | | `linearVelocity` | `{ x: 0, y: 0, z: 0 }` | Initial linear velocity. | * The body starts at the entity's `Position` and `Rotation`. * Dynamic and kinematic velocity bodies write their pose back to `Position` and `Rotation` every fixed step. * Kinematic position bodies follow `Position` and `Rotation`; move them by writing those traits. * Setting `Position` or `Rotation` of any other body, by hand, with a tween, another system or `engine.restore()`, moves the body there at the start of the next fixed step, or sooner when you call `getBody()` or `raycast()`. * Setting `RigidBody` (e.g. `entity.set(RigidBody, { type: "fixed" })`) applies it to the existing body; `linearVelocity` then sets the body's velocity. * Bodies work in world space: put them on root entities, not on `ChildOf` children. ## `Collider` A collider has a `shape` (default: a ball of radius 0.5) and material fields, e.g. `Collider({ shape: { type: "ball", radius: 1 }, restitution: 0.6 })`: | Shape | Fields | |---|---| | `ball` | `radius` | | `cuboid` | `halfExtents: { x, y, z }` | | `capsule` | `halfHeight`, `radius` | | `cylinder` | `halfHeight`, `radius` | | `trimesh` | `vertices`, `indices`: a triangle mesh (see [Level geometry](#level-geometry)) | | `heightfield` | `rows`, `columns`, `heights`, `size: { x, z }`: a grid of heights (see [Level geometry](#level-geometry)) | | Material field | Default | Meaning | |---|---|---| | `density` | `1` | | | `friction` | `0.5` | | | `restitution` | `0` | Bounciness. | | `sensor` | `false` | Sensors detect overlaps without producing contact forces. | A `Collider` attaches to the entity's `RigidBody`. On an entity without one, it is a fixed collider at the entity's `Position` and `Rotation`, and moves when they change, the same way as a body. Setting `Collider` rebuilds the collider with the new shape and material. ## Level geometry A level modelled in three.js or a 3D tool (a skatepark, a building) collides as a `trimesh`, and terrain as a `heightfield`. Both are meant for fixed colliders (an entity without a `RigidBody`, or a `fixed` one) and kinematic bodies: they are hollow surfaces, so dynamic bodies collide with them but not with each other's meshes. `trimeshFromObject(object)` makes a `trimesh` shape from the meshes of a three.js object, such as a `Visual` or a loaded glTF scene. It keeps the transforms between each mesh and `object`, in `object`'s own space, so give the collider entity the pose the object has (here both sit on the same entity): ```ts import { Position, Visual } from "@pawnjs/core"; import { Collider, trimeshFromObject } from "@pawnjs/physics"; engine.world.spawn( Position, Collider({ shape: trimeshFromObject(park) }), Visual(park), ); ``` Hidden objects, instanced and batched meshes, points and lines are left out; a geometry's `drawRange` is kept. A trimesh can also be written by hand, three numbers per vertex and three indices per triangle: `{ type: "trimesh", vertices: [x0, y0, z0, x1, ...], indices: [0, 1, 2, ...] }`. A `heightfield` is a grid of `rows` by `columns` heights (at least 2 each), centered on the entity and spanning `size.x` by `size.z` meters. Rows run from -z to +z and columns from -x to +x: the height at `row`, `column` is `heights[row * columns + column]`, in meters. It matches the vertices of a three.js `PlaneGeometry(size.x, size.z, columns - 1, rows - 1)` rotated flat with `rotateX(-Math.PI / 2)`: ```ts import { Position, Visual } from "@pawnjs/core"; import { Collider } from "@pawnjs/physics"; import { Mesh, MeshStandardMaterial, PlaneGeometry } from "three"; const rows = 33; const columns = 33; const heights: number[] = []; for (let row = 0; row < rows; row++) { for (let column = 0; column < columns; column++) { heights.push(Math.sin(column * 0.4) * Math.cos(row * 0.3)); } } const plane = new PlaneGeometry(40, 40, columns - 1, rows - 1); plane.rotateX(-Math.PI / 2); heights.forEach((h, i) => { plane.attributes.position?.setY(i, h); }); plane.computeVertexNormals(); engine.world.spawn( Position, Collider({ shape: { type: "heightfield", rows, columns, heights, size: { x: 40, z: 40 } }, }), Visual(new Mesh(plane, new MeshStandardMaterial())), ); ``` Both shapes smooth contacts across the edges between their triangles, so balls roll and characters walk over them without catching. Their numbers are trait data, so [snapshots](#snapshots) save every vertex and height. A trimesh without triangles or with an index that is not one of its vertices, or a heightfield whose `heights` is not `rows * columns` long, makes no collider: the entity keeps its `Collider` and a warning names the problem. ## Character controller A character walked by a player (or by a game's AI) is moved by code, not by forces, but still has to stop at walls and stand on the ground. `CharacterController` makes an entity's collider one that `physics.moveCharacter(entity, translation)` moves by a wanted translation: it slides along walls, climbs steps, follows the ground down steps and slopes, and reports whether the character stands on the ground. Give the character a `kinematicPosition` `RigidBody` (or no body) and a collider, usually a capsule, and move it from a `fixedUpdate` system that runs before the physics step: ```ts const hero = engine.world.spawn( Position({ y: 1 }), RigidBody({ type: "kinematicPosition" }), Collider({ shape: { type: "capsule", halfHeight: 0.5, radius: 0.4 } }), CharacterController({ maxStepHeight: 0.3 }), ); let fall = 0; // vertical speed, m/s let grounded = false; engine.addSystem( ({ delta }) => { const x = +keys.isDown("KeyD") - +keys.isDown("KeyA"); const z = +keys.isDown("KeyS") - +keys.isDown("KeyW"); fall -= 9.81 * delta; if (keys.isDown("Space") && grounded) fall = 5; const move = physics.moveCharacter(hero, { x: x * 4 * delta, y: fall * delta, z: z * 4 * delta, }); grounded = move.grounded; // Standing: stop falling, or gravity keeps pressing into the ground. if (move.grounded && fall < 0) fall = 0; }, { phase: "fixedUpdate", order: Physics.ORDER - 1 }, ); ``` `moveCharacter()` adds what the character could move to its `Position`; its kinematic body glides there in the physics step. Other bodies, dynamic ones too, block it like walls. It returns `{ translation, grounded, groundNormal }`: | Field | Meaning | |---|---| | `translation` | What it moved, a three.js `Vector3`: the wanted translation after walls and steps. | | `grounded` | Whether it stands on ground no steeper than `maxSlopeClimbAngle`. | | `groundNormal` | Up normal of that ground, e.g. to tilt a board along a ramp; zero when not grounded. A character that touched no ground while moving (standing still) probes below itself for it. | `CharacterController` fields (set them like any trait; the controller follows): | Field | Default | Meaning | |---|---|---| | `offset` | `0.02` | Gap in meters kept between the character and what it touches. | | `maxStepHeight` | `0.3` | Highest step in meters it climbs (`0` climbs none). | | `minStepWidth` | `0.2` | Narrowest step top it climbs onto, so it does not climb thin edges. | | `snapToGround` | `0.3` | Drop in meters it follows down to the ground instead of leaving it, down steps and slopes (`0` for none). | | `maxSlopeClimbAngle` | `Math.PI / 4` | Steepest slope it walks up, in radians. | | `minSlopeSlideAngle` | `Math.PI / 4` | Slopes at least this steep slide it down. | * The world's up is +y. Sensors do not block the character. * While it rises (`y` above 0) it does not snap to the ground, so a jump keeps its height. * The horizontal part of the translation moves first, climbing steps, then the vertical part (a fall or a jump) from where that ended. * Like `raycast()`, it sees colliders as of the last physics step. * It throws for an entity without a `CharacterController`, a `Collider` or a `Position`, for a body that is not `kinematicPosition`, and for a translation that is not finite. ## Snapshots `Physics` registers `RigidBody`, `Collider` and `CharacterController` in `engine.traits` when it is installed, as `rigid-body`, `collider` and `character-controller`, so [snapshots](../guide/snapshots) save them. Restore into an engine with a `Physics` installed: the bodies and colliders are made as the traits are added. Restoring into the same engine puts existing bodies back at their saved pose, with the saved `RigidBody` and `Collider`. Fields are checked like other traits (`type` must be one of the four body types, damping and material at least 0); `linearVelocity` and the collider `shape` are only checked for being set. ## Collision events After each physics step, `collisionstart` and `collisionend` are emitted on both entities of a pair through `engine.events`, and bubble up `ChildOf` like other [entity events](../guide/behaviors): ```ts engine.events.on(ball, "collisionstart", (e) => { if (e.other === goal) score += 1; }); ``` | Field | Meaning | |---|---| | `other` | The other entity. On `collisionend` it may already be destroyed. | | `sensor` | Whether either collider is a sensor: an overlap, not a contact. | * Listeners run in `fixedUpdate`, after the bodies' poses are written back, so `Position` and `Rotation` are current. * Destroying an entity or removing its `Collider` ends its collisions; the other entity gets `collisionend` on the next step. * A sensor is a `Collider` with `sensor: true`: a trigger zone that reports what enters and leaves it without pushing back. * Solid colliders report pairs where at least one body is dynamic; two fixed or kinematic colliders never collide. Sensors also report kinematic and fixed bodies, so a kinematic character can walk into a trigger zone. * A collider that is re-created in place (a `RigidBody` added to an entity that already has a `Collider`) keeps its contacts without an end and a new start. ## Raycast `physics.raycast(origin, direction, options?)` returns the first collider a ray hits, or `null`: ```ts const hit = physics.raycast(player.get(Position)!, { x: 0, y: -1, z: 0 }, { maxDistance: 1.2, exclude: player, }); const grounded = hit !== null; ``` | Option | Default | Meaning | |---|---|---| | `maxDistance` | `Physics.DEFAULT_MAX_DISTANCE` (1000) | Longest distance in meters. | | `includeSensors` | `false` | Whether sensors can be hit. | | `exclude` | | An entity whose body and collider the ray ignores. | | `solid` | `true` | Whether a ray starting inside a collider hits it at distance 0 (with a zero normal). | A hit is `{ entity, point, normal, distance }`, with `point` and `normal` as three.js `Vector3` in world space. `direction` need not be normalized. Raycasts see colliders as of the last physics step: a collider added since is hit after the next step. For picking under the pointer, use the engine's picking ([Views and picking](../guide/views#picking)); it works on what is drawn, not on colliders. ## Shape cast `physics.castShape(shape, origin, direction, options?)` moves a shape, as a `Collider` takes it, along a direction and returns the first collider it touches, or `null`. It is a raycast with thickness: a probe as wide as a character's feet finds a ledge a ray down its middle misses. ```ts const below = physics.castShape( { type: "ball", radius: 0.3 }, feet, { x: 0, y: -1, z: 0 }, { maxDistance: 1, exclude: player }, ); ``` The options are `rotation` (a quaternion, of the shape), `maxDistance`, `includeSensors` and `exclude`, as for `raycast()`. The hit has the same fields, with `point` and `normal` on the collider hit, and `distance` how far the shape moved before touching it. ## Rapier access For queries, joints, forces and anything else Rapier offers, use the underlying objects: ```ts physics.rapierWorld; // RAPIER.World physics.getBody(ball); // RAPIER.RigidBody | undefined physics.getCollider(ball); // RAPIER.Collider | undefined physics.getBody(ball)?.applyImpulse({ x: 0, y: 5, z: 0 }, true); ``` A physics plugin can be installed on one engine; `engine.dispose()` frees its Rapier world. Create a new one with `createPhysics()` for another engine. --- --- url: /pawn/docs/packages/maps.md description: The engine drawn into a Google Maps vector map. --- # @pawnjs/maps ::: info Not on npm yet This package comes with a later release of Pawn. ::: Draws a pawn engine into a [Google Maps](https://developers.google.com/maps/documentation/javascript) vector map through `WebGLOverlayView`. The engine shares the map's WebGL context and ticks on the map's draws. ```ts import { Engine, Position, Visual } from "@pawnjs/core"; import { latLngToPosition, MapOverlay } from "@pawnjs/maps"; const anchor = { lat: 52.2318, lng: 21.006 }; const map = new google.maps.Map(element, { center: anchor, zoom: 17, tilt: 60, mapId }); const overlay = new MapOverlay({ map, anchor }); const engine = new Engine({ driver: overlay }).use(overlay); engine.world.spawn( Position(latLngToPosition(anchor, { lat: 52.232, lng: 21.007 })), Visual(mesh), ); engine.start(); ``` `MapOverlay` is both the engine's [loop driver](../guide/engine#loop-drivers) and a [plugin](../guide/plugins): installing it adds its view (`overlay.view`, a `MapView` drawn with the map's camera) and hands the map's renderer to the engine. ## Requirements * The map needs a `mapId` of a **vector** map; raster maps cannot host WebGL overlays. * Load the Maps JavaScript API before creating a `MapOverlay`. Importing this package does not need it. * Use the overlay as the engine's driver. With another driver the engine would draw into the map's context outside the map's draw callback. ## `MapOverlay` options | Option | Meaning | |---|---| | `map` | A vector map (created with a `mapId`). | | `anchor` | `{ lat, lng, altitude? }`, the geographic point of the engine's origin. `overlay.anchor` can be changed later; it takes effect on the next draw. | | `createRenderer` | `(gl) => WebGLRenderer`, to customize the renderer (for example to enable shadows). It must keep `autoClear` off so the map stays visible. | | `enablePointer` | Whether the map's events drive the engine's `Pointer` (see [Picking](#picking)). Defaults to `true`. | ## Coordinates Positions are meters from the anchor: `x` east, `y` up, `-z` north. * `latLngToPosition(anchor, point, target?)` converts a geographic point (`{ lat, lng, altitude? }`) into a position. * `positionToLatLng(anchor, position)` converts back. Both use a flat approximation on a sphere of `EARTH_RADIUS` (6378137 m, as in Web Mercator) around the anchor, off by about a meter at 3 km from it and a few meters at 5 km. ## Picking The map takes the page's pointer events, so the overlay drives the engine's [`Pointer`](../guide/input#pointer) from the map's `mousemove`, `mouseout` and `click` events, installing one (without `Input`) if the engine has none. Pointer clicks, `Hoverable` and `Clickable` then work over the map as anywhere else: ```ts engine.plugin(Pointer).on("click", ({ entity }) => { if (entity) select(entity); }); ``` The map clicks only when it was not dragged, and a drag pans the map, so `Draggable` does not work on a map. Pass `enablePointer: false` to drive the pointer yourself. `engine.pick(clientX, clientY)` still picks through `overlay.view` from any map listener. ## Notes * With the engine stopped, map draws still render the scene. Call `overlay.requestRedraw()` after changes. * `engine.dispose()` disposes the overlay's renderer, but the map's context lives on: dispose your geometries and materials first to free their GPU memory. * Lighting treats the eye as sitting at the anchor (the map's camera pose is baked into one matrix), so specular highlights and reflections are approximate. The [Maps example](https://jakubprill.github.io/pawn/maps.html) shows a pawn and boxes over Warsaw. --- --- url: /pawn/docs/packages/json-render.md description: Scenes a model writes as json-render specs, from your registered prefabs. --- # @pawnjs/json-render ::: info Not on npm yet This package comes with a later release of Pawn. ::: Lets a language model build scenes from your prefabs with [json-render](https://github.com/vercel-labs/json-render): the model answers with a **spec**, one element per entity, streamed as JSON Patch lines. The package needs `@pawnjs/core`, `koota`, `three` and `zod` 4.3.6 or later; it does not need React and does not call any model API itself, so the API key stays in your app or on your server. ## Scene catalog `createCatalog(engine, options)` offers the engine's registered prefabs to a model: what each element takes as props, and the system prompt that teaches the spec. ```ts import { createCatalog } from "@pawnjs/json-render"; const Tank = definePrefab({ name: "tank", description: "Liquid tank, 3.2 m tall.", traits: [Position, [Shape, { kind: "cylinder" }]], params: { color: ["shape.color"] }, }); engine.prefabs.register(Tank); const catalog = createCatalog(engine, { grid: new Grid({ columns: 24, rows: 16 }), footprints: { tank: [2, 2] }, scene: "an industrial hall", }); const system = catalog.prompt({ rules: ["Tanks go along the west wall."] }); ``` The model then answers with lines such as: ```json {"op":"add","path":"/elements/tank-1","value":{"type":"tank","props":{"at":[2,3],"color":"#ef4444"}}} ``` | Option | Default | Meaning | |---|---|---| | `prefabs` | every registered prefab | Names of the prefabs to offer. | | `grid` | none | Floor grid: elements place with `at: [column, row]` and `turn` of 0, 90, 180 or 270 degrees. Without it they place with `position` in meters and any `turn` in degrees. | | `footprints` | `[1, 1]` | Cells each prefab covers on the grid, columns × rows. | | `scene` | `"a 3D scene"` | What the scene is, for the prompt's first line. | * An element's props are its placement, the prefab's [params](/guide/prefabs#prefab-params) and its own traits and behaviors, every one optional. Core traits such as `shape` are set only through params, so give the prefab a `color` param to let a model color it. * The prompt lists each prefab with its [`description`](/guide/prefabs), footprint and props. Keep descriptions to a sentence; ten prefabs make a prompt of under 6 KB. * A `group` element (type `GROUP`, `"group"`) lists other elements in `children`, to edit or remove them together. * `catalog.validate(spec)` returns `{ ok, problems }` with every problem it finds: unknown types, props that do not fit, children on anything but a group, missing children and groups that contain themselves. It does not check placement on the grid (a footprint past the edge, overlaps); the [renderer](#rendering-a-spec) does. * A prefab param or behavior named like a placement prop (`at`, `turn`, `position`) is rejected by `createCatalog`. * `catalog.catalog` is the json-render catalog itself, for json-render's own tools. ## Rendering a spec `createRenderer(catalog)` spawns a spec's elements from the catalog's prefabs and keeps them in step as the spec changes. Feed it the model's answer as it streams: ```ts import { createRenderer } from "@pawnjs/json-render"; const catalog = createCatalog(engine); const scene = createRenderer(catalog); for await (const chunk of answer) scene.push(chunk); scene.flush(); scene.entity("tank-1"); // also engine.findEntity("tank-1") for (const { key, text } of scene.problems) console.warn(key, text); ``` * `push(chunk)` takes text split anywhere and renders every whole line; `flush()` renders a last line without a newline. A line that is not JSON Patch is listed in `problems` and skipped. * Each call returns what it did, for a log of the stream: the keys it `spawned`, `updated` and `destroyed`, and its own `problems`: its lines that did not apply, problems it brought (a group that lost a child), and the problems of the elements its lines touched. ```ts const { spawned, problems } = scene.push(`${line}\n`); if (problems.length === 0) console.log("spawned", spawned); ``` * `render(spec)` renders a whole spec, from a file or an editor; a later `push` patches it. Either way only what differs is changed: a new element is spawned, a changed prop is set on the same entity (a removed one goes back to the prefab's value), a removed element is destroyed, and an element whose type changes is spawned again. * Each element's key is its [`EntityId`](/guide/snapshots#entity-ids), so snapshots and `engine.findEntity` know it. After `engine.restore()`, rendering the spec again takes over the restored entities of each element's prefab instead of spawning them twice, sets them as the spec says and lists them in `updated`; an entity from another prefab, or one another renderer or scope holds, with a key's id is listed in `problems`. An element whose entity was destroyed elsewhere frees its cells and is spawned again by a later call. * An element that does not fit (wrong props, off the floor, overlapping another footprint) is left as it was last rendered, or not spawned, and listed in `problems` until the spec fixes it. * A `group` element becomes an entity with its children under it (`ChildOf`). Without a grid, children's positions are relative to the group. Removing a group keeps the children the spec still has. * `scene.spec` is the spec as compiled so far, `scene.keys` the rendered elements, and `scene.clear()` destroys every entity the renderer spawned or took over (it spawns into its own [scope](/guide/engine#scopes)). ## A recorded answer The scene below plays back a model's answer line by line: elements are added on a 10 × 6 grid, then one tank turns red with `replace` and a rack goes away with `remove`. The [AI scene](https://jakubprill.github.io/pawn/ai-scene.html) showcase streams the same kind of answer live from Claude, on your own API key. ```ts import { definePrefab, Engine, Grid, Position, Rotation, Scale, Shape, } from "@pawnjs/core"; import { createCatalog, createRenderer } from "@pawnjs/json-render"; /** A model's answer, recorded: one JSON Patch line per element or edit. */ const ANSWER = [ '{"op":"add","path":"/elements/tank-1","value":{"type":"tank","props":{"at":[1,1]}}}', '{"op":"add","path":"/elements/tank-2","value":{"type":"tank","props":{"at":[4,1]}}}', '{"op":"add","path":"/elements/pump-1","value":{"type":"pump","props":{"at":[3,2]}}}', '{"op":"add","path":"/elements/pump-2","value":{"type":"pump","props":{"at":[6,2]}}}', '{"op":"add","path":"/elements/rack-1","value":{"type":"rack","props":{"at":[8,0]}}}', '{"op":"add","path":"/elements/rack-2","value":{"type":"rack","props":{"at":[9,0]}}}', '{"op":"add","path":"/elements/rack-3","value":{"type":"rack","props":{"at":[1,4],"turn":90}}}', '{"op":"replace","path":"/elements/tank-2/props/color","value":"#ef4444"}', '{"op":"remove","path":"/elements/rack-3"}', ]; export default function aiScene(canvas: HTMLCanvasElement): Engine { canvas.style.cssText = "display:block;width:100%;height:100%"; const engine = new Engine({ canvas, camera: { position: { x: 0, y: 9, z: 9 } }, background: "#09090b", lights: "studio", }); const standing = (name: string, kind: "box" | "cylinder", size: number[]) => definePrefab({ name, traits: [ [Position, { y: size[1] / 2 }], Rotation, [Scale, { x: size[0], y: size[1], z: size[2] }], [Shape, { kind, color: "#cbd5e1" }], ], params: { color: ["shape.color"] }, }); engine.prefabs.register( standing("tank", "cylinder", [1.8, 2.4, 1.8]), standing("pump", "cylinder", [0.6, 0.8, 0.6]), standing("rack", "box", [0.9, 1.8, 2.9]), ); const grid = new Grid({ columns: 10, rows: 6 }); engine.spawn( Shape({ kind: "plane", color: "#27272a" }), Scale({ x: grid.columns, y: 1, z: grid.rows }), ); const catalog = createCatalog(engine, { grid, footprints: { tank: [2, 2], rack: [1, 3] }, }); // A model reads catalog.prompt(); here its answer plays back line by line. const scene = createRenderer(catalog); // One line every half second, then the finished scene for 2 s. const PAUSE = 4; let line = 0; engine.every(0.5, () => { if (line === ANSWER.length + PAUSE) { scene.clear(); line = 0; } if (line < ANSWER.length) scene.push(`${ANSWER[line]}\n`); line++; }); engine.start(); return engine; } ``` --- --- url: /pawn/docs/examples.md description: The live showcase examples and where their sources are. --- # Showcase Every example below runs live in the [showcase](https://jakubprill.github.io/pawn/). Their sources live in `apps/showcase/src` of the repository, one folder per example, with the entry each card names; helpers used by several examples sit in `shared/`. The racer is an app of its own, in `apps/racer`. * [Cube](https://jakubprill.github.io/pawn/cube.html): Shapes, two views, clicks bubbling to one listener, `TweenOn` (vanilla TypeScript). Source: `apps/showcase/src/cube/`. * [React](https://jakubprill.github.io/pawn/react.html): ``, `useSpawn`, `useSystem`, instanced `Shape`s and koota queries driving UI. Source: `apps/showcase/src/react/`. * [Physics](https://jakubprill.github.io/pawn/physics.html): Rapier bodies in prefab variants, stepped in `fixedUpdate`; a sensor pad's `collisionstart`. Source: `apps/showcase/src/physics/`. * [Solar](https://jakubprill.github.io/pawn/solar.html): Prefabs with named children: orbits inside orbits, `Spin`, `Clickable` and `TweenOn`. Source: `apps/showcase/src/solar/`. * [Swarm](https://jakubprill.github.io/pawn/swarm.html): Thousands of entities with `Instance` and `InstanceBatch`. Source: `apps/showcase/src/swarm/`. * [Maps](https://jakubprill.github.io/pawn/maps.html): The engine drawn into a Google vector map. Source: `apps/showcase/src/maps/`. * [Views](https://jakubprill.github.io/pawn/views.html): One canvas drawing a view into every card of a page: `Hoverable`, `Clickable`, `Input`. Source: `apps/showcase/src/views/`. * [Balloons](https://jakubprill.github.io/pawn/balloons.html): A tap-only game for little kids with a score and storm clouds to avoid: picking, tweens, physics confetti. Source: `apps/showcase/src/balloons/`. * [Munch](https://jakubprill.github.io/pawn/munch.html): A drag-or-tap feeding game for little kids: `Draggable` on a plane, tweens, physics crumbs. Source: `apps/showcase/src/munch/`. * [Energy](https://jakubprill.github.io/pawn/energy.html): A microgrid dashboard in React: node picking, `ChildOf` rotors, instanced power pulses, live charts. Source: `apps/showcase/src/energy/`. * [CMS Health](https://jakubprill.github.io/pawn/cms.html): A Payload CMS site in 3D, fed by `@pawnjs/data`: instanced blocks, `EntityLabel`, `CameraRig`. Source: `apps/showcase/src/cms/`. * [CMS Flow](https://jakubprill.github.io/pawn/cms-flow.html): The same CMS as a full-screen pipeline of tiles and pipes: feeds, tweens, `CameraRig`. Source: `apps/showcase/src/cms-flow/`. * [Defense](https://jakubprill.github.io/pawn/defense.html): A tower defense built from prefabs, presets and behaviors: `Spawner` waves, `Grid`, `Actions`, `Sound`, `Debug`, tested headless. Source: `apps/showcase/src/defense/`. * [Pawn. Racer](https://jakubprill.github.io/pawn/racer/): The racer's hub, linking the race and each micro demo below. Each racer scene (the race and every micro demo) opened with `?debug` shows the `Debug` overlay. * [Racer hangar](https://jakubprill.github.io/pawn/racer/hangar.html): The ship prefab of an anti-gravity racer in five team liveries, on a turntable: `CameraRig`, shadows and tone mapping. Source: `apps/racer/src/hangar.ts`. * [Racer track](https://jakubprill.github.io/pawn/racer/track.html): A three-lap race against four rivals who pass and bump, on the banked Vanta Loop, the climbing, diving Altair Drop, Zenith Wall straight up a wall, Vega Coil round a spring of road or Rigel Orbit upside down through a loop: `ChaseCamera`, `Actions` with tilt and on-screen buttons, synthesized engine `Sound`, a radar `View`, team names over the rivals with `Labels`. Source: `apps/racer/src/circuit.ts`. * [Racer trackside](https://jakubprill.github.io/pawn/racer/trackside.html): The track's barriers and gates close up: holo grid fields and neon rings glowing through a bloom pass, or solid walls and beams, in any accent. Source: `apps/racer/src/trackside.ts`. * [Racer stadium](https://jakubprill.github.io/pawn/racer/stadium.html): Stands by the track with LED ribbons that scroll a message; a plugin, installed through `usesPlugin`, moves their textures each frame. Type a message, set its speed and accent. Source: `apps/racer/src/stands.ts`. * [Racer towers](https://jakubprill.github.io/pawn/racer/towers.html): Art deco towers along a climbing street, each a `definePrefab` whose look rebuilds when its layout trait is set (`rebuildOn`): height, setbacks, signs and accent. Source: `apps/racer/src/towers.ts`. * [Racer sky](https://jakubprill.github.io/pawn/racer/sky.html): Night, dusk and day over a straight of triangle boost pads: a sky prefab with stars and a glowing sun, rebuilt when its layout trait is set; raise the sun, thin the stars, color the pads. Source: `apps/racer/src/skies.ts`. * [Seabirds](https://jakubprill.github.io/pawn/birds.html): Low-poly birds soaring over a sea and a hill drawn in colored pencil: a `definePrefab` bird with two behaviors, flapping in bursts and flying a figure eight as a loose flock; tap to rouse it. Source: `apps/showcase/src/birds/`. * [AI scene](https://jakubprill.github.io/pawn/ai-scene.html): A hall described in words and streamed in by Claude as `@pawnjs/json-render` lines of registered prefabs (prototype). Source: `apps/showcase/src/ai-scene/`. To run them locally: ```bash bun install bunx turbo run dev --filter=pawn-showcase ``` The Maps example needs a Google Maps API key in `apps/showcase/.env.local` (`VITE_GOOGLE_MAPS_API_KEY`, optionally `VITE_GOOGLE_MAPS_MAP_ID`).