---
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<string>(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)).
