---
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.
