Stores and saves
useWallet, useScenes, useInput, useTime and useLoading read stores the engine owns. usePlayer queries the world for the player’s character instead, and useMatch queries it for the match. usePlayer also says who plays: the name the player shows in the player app and an id that is theirs in this game alone. The app hands both to the page when the game runs in its frame, as the trust boundary says. In a game with rooms the app hands them with the seat, once the room opens, so both read undefined while the page loads during a room’s start. Both are undefined outside the app, as on the game’s dev server, so a game falls back to its own, such as a name the player types.
A game’s own state comes from the engine’s createStore, and a game reads it the same way; wrapped in the engine’s persist, it is kept in the player’s save, as Save a game’s own store says.
The stores’ shapes are WalletState, InputState, TimeState and LoadingState. useMatch returns a MatchStatus.
Game builds the quality store, and keeps it in the browser’s storage under its name: sled-quality for Game’s sample, so two games on one origin keep separate settings. Anything under Game reads it with useQualityStore(), which returns the store for useStore from zustand. A camera that remembers its framing keeps it beside it, as the camera page says. The player’s progress is the save, which Saving progress describes. The quality store holds what the player set in the Graphics rows and the level Automatic picked for the device. useQualitySettings() reads the values the engine draws with.
Game’s quality prop changes what each level means and the level each kind of device starts at, as Graphics quality describes. A scene mounted headless reads stores of its own that start empty and write to no storage. A game that renames itself loses its players’ settings on each device, so a game keeps its name.
An address with ?quality=<level>, one of auto, minimum, low, medium or high, opens the game at that level for the visit. The quality store keeps the saved level in storage, and saves a level the player picks after the game opens. The boot checks open every game at ?quality=minimum, so the GPU they run on never decides a level’s values. A page opened with ?profile also takes ?qualityLevels=, level values over the game’s own for the visit, as Frame shows.
A save is plain data, as it is stored. The character’s position reads back as three numbers, { x, y, z }, the StoredVector type from @spawnite/schema, not a three.js Vector3, so code that reads a save and draws nothing loads no three.js. A game that needs a vector builds one where it reads the save, new Vector3(x, y, z); the engine’s spawnCharacter does so itself. Unity, Unreal and Godot store a vector as three numbers the same way.
Where each save goes
Section titled “Where each save goes”A game keeps each piece of state in one record, and the engine’s defaults put each where most games want it. A game with worlds keeps three records for each player, as Worlds says, and the following table says which state goes where:
| State | Record | Such as |
|---|---|---|
| The world’s things, whoever plays in it | The world’s record | The loot taken, the levels finished, what was built, the weather |
| The player’s character in a world | The player’s record in that world | The character’s position, facing and health |
| What the player claims or builds there for themselves | The player’s record in that world | The player’s plot, own shed and standing in that town |
| What the player owns and the player’s progress | The player’s game-wide record | The character’s bag and stats, the player’s coins and purchases |
The player’s record in a world is one for each world and player: the player’s place on a friend’s island and on the player’s own island are two records.
The engine’s saves follow the table with no line of the game’s:
core.saves.positionandcore.saves.healthgo in the player’s record in each world.core.saves.stats,core.saves.wallet,inventory.saves.bagandcharacters.saves.respawnPointgo in the player’s game-wide record.core.saves.levelsandinventory.saves.lootgo in the world’s record.
A game moves one with one line, { perWorld: true } or { perWorld: false }. A visitor who finishes a level on a friend’s island finishes it for the island, and a flower the visitor picks there is gone from the island and in the visitor’s bag.
A pickup the scene lays that stays gone in one world, such as a flower on an island, is loot with an id, <Entity position={[2, 0, 2]}><Loot id="flower-1" item="flower" /></Entity>. inventory.saves.loot keeps it taken in the world’s record, and the game writes no save of its own for it. A loot with no id is kept nowhere, so it lies again, whole, at every load.
Carried gear: the defaults
Section titled “Carried gear: the defaults”Islands whose players carry their gear between them, as Valheim’s characters do, write no save line:
import { addTrait, defineGame, definePlugin, defineRoom, defineSave, defineTrait, setTrait,} from "@spawnite/engine/core";import { behaviours } from "@spawnite/engine/behaviours";import { characters } from "@spawnite/engine/characters";import { inventory } from "@spawnite/engine/inventory";import { stats } from "@spawnite/engine/stats";import { z } from "@spawnite/schema";import { cooldowns } from "@spawnite/engine/cooldowns";
// Islands whose players carry their gear between them, as Valheim's// characters do: the engine's defaults, with no save line at all. The// character's bag and stats and the player's coins are the same on every// island; the character's place and health are each island's; the loot// taken, the levels finished and the weather are the island's own.
const weathers = ["sun", "rain", "fog"] as const;
/** On the world: the island's weather. */export const WeatherTrait = defineTrait("islandWeather", { // eslint-disable-next-line typescript/no-unnecessary-type-assertion -- the cast widens what the trait infers kind: "sun" as (typeof weathers)[number],});
/** Adds the weather as the world is made, before its record restores. */const weather = definePlugin(() => ({ name: "island-weather", setup(world, writer) { addTrait(writer, world, WeatherTrait); },}));
/** The island's own state: its weather, in the world's record. */const islandWeather = defineSave({ scopes: ["world"], version: 1, schema: z.object({ kind: z.enum(weathers) }), read: ({ world }) => ({ kind: world.get(WeatherTrait)?.kind ?? "sun" }), restore: ({ world, writer }, saved) => setTrait(writer, world, WeatherTrait, saved),});
export const game = defineGame({ name: "carried-gear", start: "island", room: defineRoom({ maxPlayers: 8 }), // Each room holds an island; players make their own and invite friends. worlds: { play: "own", playerWorlds: "private" }, plugins: [ characters(), stats(), cooldowns(), behaviours(), inventory(), weather(), ], worldState: islandWeather,});The weather is the island’s own state, so it is the game’s worldState, which receives the world alone. The plugin’s setup adds the trait as the world is made, and the world’s record restores over it through writer before anyone is seated, as Worlds orders it. A world trait no save reads lives as long as its room.
Gear per world: two lines
Section titled “Gear per world: two lines”Worlds that each start the player afresh, as a Rust server does, move the character’s bag and stats into the player’s record in each world, one line each:
import { defineGame, defineRoom } from "@spawnite/engine/core";import { behaviours } from "@spawnite/engine/behaviours";import { characters } from "@spawnite/engine/characters";import { inventory } from "@spawnite/engine/inventory";import { stats } from "@spawnite/engine/stats";import { cooldowns } from "@spawnite/engine/cooldowns";
// Worlds that each start the player afresh, as a Rust server does: the// character's bag and stats belong to the world the player plays in,// one line each, and the player's coins stay the same everywhere.
export const game = defineGame({ name: "world-gear", start: "island", room: defineRoom({ maxPlayers: 50 }), // Play fills the worlds the creator lists. worlds: true, plugins: [ characters(), stats(), cooldowns(), behaviours(), // What the player gathers stays in the world the player // gathered it in. inventory({ saves: { bag: { perWorld: true } } }), ], // So does what the player trained there. saves: { stats: { perWorld: true } },});Declare what the save keeps
Section titled “Declare what the save keeps”A save is declared once, at module scope, with defineSave. A plugin declares its saves by name under saves, and a game declares its own state on defineGame as playerState, playerWorldState and worldState. Every save is on once its plugin is listed, in the first of its scopes and the record it declares, and the game changes that on the plugin’s call: inventory({ saves: { bag: { scope: "player" }, loot: false } }). The core’s saves are on too, each under engine.<name>, and defineGame’s saves turns one off or moves it: saves: { stats: false }, or saves: false to keep nothing at all. Saving progress says why saves: false is refused beside the game’s own state.
import { addOrSetTrait, defineGame, defineSave, defineTrait,} from "@spawnite/engine/core";import { stats } from "@spawnite/engine/stats";import { inventory } from "@spawnite/engine/inventory";import { behaviours } from "@spawnite/engine/behaviours";import { z } from "@spawnite/schema";import { cooldowns } from "@spawnite/engine/cooldowns";
// A game with a save of its own, kept on the player: the gold the player// holds and the quests the player finished, at version 2, whose step// gives a version 1 record its quests.
/** The gold a player holds. */export const GoldTrait = defineTrait("gold", { amount: 0 });
export const game = defineGame({ name: "quest", start: "meadow", plugins: [ stats(), cooldowns(), behaviours(), inventory({ saves: { loot: false } }), ], saves: { stats: false }, playerState: defineSave({ scopes: ["player"], version: 2, schema: z.object({ gold: z.int(), quests: z.array(z.string()) }), read: ({ player }) => ({ gold: player.get(GoldTrait)?.amount ?? 0, quests: [], }), restore: ({ player, writer }, saved) => { const gold = { amount: saved.gold }; addOrSetTrait(writer, player, GoldTrait, gold); }, migrations: { 2: (v1) => ({ ...v1, quests: [] }) }, }),});defineSave takes the following fields. scopes, schema, read, restore and version are required:
-
version: a whole number from 1 that counts the shape of the state. Any change to the shape raises it, an added optional field included, and adds a step. -
schema: types whatrestorereceives, and checks every state that loads. -
read: returns the state to keep, as plain JSON. It is synchronous and changes nothing. At every read, in development and when published, the engine checks that what it returns passes the schema and survives JSON. A read that throws, returnsundefined, or holds aSet, a symbol, anundefinedfield, a number that is not finite or a value inside itself is refused, and so is the whole record that read: the last save stays, and play goes on. -
restore: puts a loaded state back. A player-scope state goes onto the player entity after everyonPlayerJoinand before anyonPlayerReady, and an entity-scope state onto a saved entity assetSavedEntityregisters it, after its spawn set it up and after the engine saves are restored. A saved entity anonPlayerJoinregisters restores as the player’s save attaches, after the player entity’s restore and before anyonPlayerReady. A restore that throws refuses the load, as a record that fails to load does, so nothing is written over the save, and refuses a join it runs in. -
migrations: one step per version. Step 2 turns a version 1 state into version 2, so a version 1 state that a version 4 game loads runs steps 2, 3 and 4. A step is a pure function from old JSON to new JSON. A step that throws or returnsundefinedrefuses the load. -
scopes: where the state is kept, the first its own, required so the record a save lands in is on its face.["player"]is the player entity, wherereadandrestorereceive{ world, player, target, account, entities }.["entity"]is each saved entity underentities.<name>, where they receive{ world, player, target, account, entities, entity, savedAs }.["world"]is the world alone, kept in the world’s record, where they receive{ world }and noaccount, since a world’s state never depends on who loaded it. A save a game may move lists both,["entity", "player"], and the game’s override picks the other with{ scope: "player" }; a world’s save never moves. -
perWorld: for a save of the player entity’s or the player’s saved entities’, whether it is kept in the player’s record in each world rather than the player’s game-wide one, as the core’spositionis.falsewhen left out. The game’s override says otherwise with{ perWorld }. -
requires: the saves this one reads restored, by handle, such ascore.saves.stats, or by the name of another save of the same plugin. Each must be on, on the same target, and it restores before this one. A save it requires that listswithneeds those traits in this one’swithtoo, so this one never reads it where it was skipped. -
with: for a save of the player’s saved entities, the traits a saved entity holds for the save to keep its state on it, aswith: [HealthTrait]. A saved entity that lacks one is skipped, its read and its restore alike, and its record keeps the save’s stored state, so a chest with no health keeps no health. The save keeps none of these traits’ fields by listing them. A save kept on the player entity runs whatever the player entity holds. Left out, the save runs on every saved entity, but for the core’s stats save, which reads only a saved entity with stats.A trait added after
setSavedEntityregistered the entity comes too late for that registration: the record’s stored state was not restored, so a capture keeps it as stored. In development the capture throws instead and names the fix, which is to add the trait before registering the entity, or to register it withrestore: false. A trait removed from a live saved entity also leaves the stored state as it was.worldis the read-onlyWorld,playerthe player entity,entitythe saved entity andsavedAsthe name it is saved as.targetis the entity the save is kept on, the player entity or the saved entity, whichrestorereceives as aPredictedEntity, so it may write its predicted traits.accountis{ id }, the platform’s id for the player in this game.entitieslists what the player’s record keeps beside the player entity and the player’s saved entities, as What a player’s save reaches says.restorereceives one field more,writer, which every write takes first, as Writing a trait says:restoreStats(writer, entity, saved.stats). During the player’s join it is the join’s step, which writes the player entity and what the join made. A saved entity a system registers restores with the writersetSavedEntitywas handed, and a world’s save restores with the world’s authority as it loads. A writer kept past its restore keeps the rules of what was handed in, so a join’s step kept past the player’s join writes nothing.
A game sets no interval: the platform writes the save on its own schedule, as When the save is written and Saves in a room say. A game that keeps no state of its own leaves playerState out, and its record has no game key.
defineSave throws for no scopes, a version that is no whole number from 1, a step missing between 2 and the version, no schema, scopes that are not "player" and "entity" each once or "world" alone, and a perWorld on a world’s save. It also throws for a with on a save of the world or of the player entity alone, and for a with that lists anything but traits.
The engine owns the saved form of its own traits, so a game never stores the engine’s shapes itself, and an engine release that changes one converts the saves already stored. Each is on by default, in the record the table names; the game turns the core’s off on defineGame and a plugin’s on its call:
| Save | What it keeps, and where | Off with |
|---|---|---|
core.saves.position |
Each saved entity’s scene, position and facing, in the player’s record in each world, for a saved entity with a transform. A position saved in another scene is dropped | saves: { position: false } on the game |
core.saves.stats |
Each saved entity’s stat bases, the maximum health’s among them, and lasting modifiers, game-wide, read from a saved entity with stats and restored onto any. Timed modifiers are left out | saves: { stats: false } on the game |
core.saves.health |
Each saved entity’s current health, in the player’s record in each world, for a saved entity with health. It restores after the stats that cap it | saves: { health: false } on the game |
inventory.saves.bag |
Each saved entity’s bag and what it wears, game-wide | inventory({ saves: { bag: false } }) |
resources.saves.amounts |
What each saved entity has of each resource, such as mana, game-wide. Requires core.saves.stats, which sets each maximum |
resources({ saves: { amounts: false } }) |
core.saves.wallet |
The coins in the player’s wallet, game-wide. A restored wallet adds nothing to a match’s score | saves: { wallet: false } on the game |
characters.saves.respawnPoint |
Each player’s respawn point, game-wide, holding only in the world it was set in, as The player’s respawn point says | characters({ saves: { respawnPoint: false } }) |
core.saves.levels |
The levels finished, in the world’s record | saves: { levels: false } on the game |
inventory.saves.loot |
The loot already taken, in the world’s record | inventory({ saves: { loot: false } }) |
core.saves.random |
The world’s random stream, so a continued game draws what it would have drawn. On a page alone: a room seeds its own and keeps none | saves: { random: false } on the game |
A bag restored from a save that holds an item the game no longer registers throws in development, naming the item and the fix: register it again with defineItem. A published game keeps each such stack in the player’s record, out of the character’s bag, until a version registers the item again, so nothing the player held is lost. Nothing is invented.
A plugin’s saves
Section titled “A plugin’s saves”A plugin declares its saves under saves, each made with defineSave, and keeps each under kits.<plugin>.<name>. The plugin’s handle for a save is shop.saves.stock, which another save’s requires names. A save gives the following fields:
scopes, the first where it is kept, or["entity", "player"]where a game may keep it on the player entity instead.perWorldwhere it belongs to the player’s record in each world.requiresfor the saves it reads restored, which must be on in the same scope.
The game’s say is the saves option on the plugin’s call, typed from the plugin’s own declaration: false keeps nothing of the plugin, and { stock: false } or { stock: { scope: "player" } } turns one save off or moves it. { stock: { perWorld: true } } keeps it in the player’s record in each world, and { stock: { perWorld: false } } game-wide, as Worlds says. A name the plugin does not declare, and a scope outside the save’s scopes, fail to typecheck and throw at the call. A save turned off keeps its stored entry, so a game that turns it on again restores it. A save of the world’s scope takes no perWorld, since the world’s record is already the world’s.
The world reads a save against the plugin listed under its name, so a kit copied from an engine plugin, under the plugin’s name and with the same saves, keeps reading every player’s record. The plugin’s name and the save’s name are the record’s key for good: renaming either starts a new record. A factory’s options may not change its saves, their scopes, their records or what they require.
A record written before these three were plugins’ saves kept them under engine.inventory, engine.resources and engine.loot. The engine reads such a record under the new keys, and leaves under each old key a mark that an older engine release refuses. A game put back on an older release stops at its load-failure screen rather than starting the character with an empty bag.
The camera is not saved: its framing is a view setting, not progress. A world has its own record, and a plugin’s world save joins it, as Worlds says. A game with rooms exports its game from the room’s scene file, export { game } from "../game", which carries the saves with it.
Worlds
Section titled “Worlds”A world is a place that remembers: an island, a town, a base. A game declares its worlds once, on defineGame, whether it plays in rooms or alone, and keeps each world in records of its own beside each player’s. Each piece of state has one home, and the following table says which:
| Home | Declared with | Holds | Such as |
|---|---|---|---|
| The player’s game-wide record | playerState, and every save not kept per world |
What belongs to the player in every world | The character’s bag, the player’s coins and purchases |
| The player’s record in a world | playerWorldState, and each save kept per world |
What belongs to the player in one world, and gone in another | The character’s place and health, the player’s plot there |
| The world’s record | worldState, and each save of the world’s scope |
What belongs to the world, whoever plays in it | The farm’s fields, a base’s blocks |
| A keyed record | defineKeyedSave |
A named thing one room holds at a time | A plot, a guild’s bank, a village’s market |
The game’s own state in each record is a defineSave on defineGame: playerState in the player’s game-wide record, playerWorldState in the player’s record in each world, and worldState in the world’s. playerWorldState and worldState are a few letters apart, and the types tell them apart: worldState takes scopes: ["world"], and playerState and playerWorldState take the player entity’s or each saved entity’s. The two player fields take the same save, so the field names the record: playerState for what the player keeps everywhere, playerWorldState for what the player keeps in one world.
A save of a plugin or the core moves to the player’s record in each world with { perWorld: true }, on its plugin’s call or in the game’s saves, and back with { perWorld: false }. A save kept per world makes the player’s record in a world even where the game declares no playerWorldState. A save kept per world may require one kept game-wide, which restores first, and never the other way round; the mount, the build and the room refuse the reverse, naming both records.
defineGame({ worlds }) declares the worlds: true for the defaults, or their settings, each field optional:
play: in a game with rooms,"fill", the default, fills a listed world the creator owns, as Roblox’s Play fills a server."own"opens the player’s own world, made the first time, such as a private island, and needsplayerWorldsto let players make one.playerWorlds: in a game with rooms,"none", the default, lets only the creator make worlds;"private"lets players make worlds their friends join by code or link;"listed"lets them list theirs in Browse too.automaticWorlds: in a game with rooms, whether Play makes a new listed world the creator owns when every one a player may join is full; true when left out. Withfalseandplay: "fill", a publish needs a listed world the creator made.automaticWorldName: the name each world Play makes takes, followed by its number among Play’s worlds, such as"Public Island"for “Public Island 3”;"World"when left out. At most 43 characters. A version that changes it renames each world Play made that still carries the old name.updateNoticeSeconds: in a game with rooms, the seconds a room has, from an update’s notice, before its players move to a room on the new version; 60 when left out, at most 600.settings: the settings a world is made with, az.objectwhose fields each have a default, such as a seed or a mode.browseSettings: in a game with rooms, the fields ofsettingsBrowse shows beside a listed world, each an enum, a number or a boolean.
A game with rooms holds its worlds in its one kind of room, or in each kind its room marks, defineRoom({ kinds: { island: { world: true }, plaza: {} } }). A room moves its players to another kind’s room with teleportPlayers, as Teleports between rooms says. In a game with rooms that declares no worlds, worldState, playerWorldState and a core save’s { perWorld: true } fail to typecheck, and defineGame throws for a plugin’s { perWorld: true }, since no room would load them. A room that holds no world, such as a hub or a match, keeps the player’s game-wide record alone: each save of the world’s record or of the player’s record in a world is left out there, and a development room prints one line for each as it starts.
A game played alone holds one world, the player’s, and keeps all three records in the player’s one record, each part under its own key: the game-wide part at the top, the player’s part in the world under player-world, and the world’s under world. One that declares worlds keeps them as the player’s save slots, up to ten, which the player makes, renames and deletes on the same screens a room game’s worlds use, as Minecraft lists its worlds; it gives settings alone. The core’s random keeps the world’s random stream on a page, and a room seeds its own and keeps none, so turning it on in a game with rooms fails the build.
A world’s state never depends on who loaded it, so a world-scope save’s read and restore receive no account, and its read sees the world without the entities a player’s record or a key keeps.
As a room that holds a world opens, and as the player joins it, the room restores in this order:
- Each plugin’s
setupruns, as the world is made. - The scene mounts: its entities spawn and its loot is laid.
- The world’s record loads over what the scene laid, before anyone is seated: a loot taken is gone again.
WorldOpenedEventis emitted then, withisNewfor a world with no record, and a system reads it on the next step. - Each
onPlayerJoin. - The player’s game-wide player saves, then the player’s player saves in the world.
- Each saved entity a join hook registered, from both records, the game-wide one first.
- Each
onPlayerReady.
The room reads a world’s settings with readHeldWorld(world)?.settings once WorldOpenedEvent says the world opened, and its isNew says whether to build it from them. readHeldWorld(world) also names the world’s id, which a world’s keys and boards take as their parent, and its resetGeneration, which each wipe raises. A room under spawnite dev holds one stand-in world, dev, made with the settings’ defaults. useHeldWorld() reads the same on a page, as The world a page is in says.
A room mounts a scene and not <Game>, so a game with rooms exports its game from the room’s scene file, export { game } from "../game", which carries every record with it, as What the room’s scene exports lists.
Worlds on a page
Section titled “Worlds on a page”A game played alone that declares worlds keeps page worlds, the player’s save slots: each player makes their own, up to 10 in a game, and comes back to the one the player picks. A page world belongs to the player alone:
- It has no codes and no members, Browse never lists it, and no room ever opens it.
- The player’s page holds it, and the platform trusts it as it trusts the player’s own save, which a player can edit on their page.
- The player makes, plays, renames, deletes and brings back their page worlds from the same Worlds sheet a room game shows, and a game’s own menu reads them with the same
useWorldDirectory().
The player’s page holds one page world at a time, and the player’s one record keeps its three parts as Worlds lays out. The platform keeps each part on its own record: the player’s game-wide part on the player’s record, and the world’s part and the player’s part in it on the world the player plays.
On the page, readHeldWorld(world) and useHeldWorld() read the page world the player plays, its id, name and settings, and WorldOpenedEvent says whether its record was new, as a room’s world does. A game played alone that declares no worlds holds no page world, and they read null.
Under spawnite dev, and anywhere else outside the app, the page holds the stand-in page world dev, made with the settings’ defaults, as a room under spawnite dev holds one. Its record stays in the browser, so a reload opens it as it was, and spawnite save clear makes it new again.
Play opens the page world the player last played, and makes one named “My world” the first time. To play another, the player picks it from their worlds, or the game’s menu calls join({ worldId }), and the page loads the game again on it. A guest is asked to sign in first, since the guest’s worlds are kept on the guest’s account; a game played alone that declares no worlds keeps guest play as it is.
A saved state that is empty is saved as empty: an emptied bag writes an empty bag, never the bag the save held before.
What a player’s save reaches
Section titled “What a player’s save reaches”A player’s save keeps what belongs to the player alone. Its read reaches the player entity, the player’s saved entities and the entities the player’s record keeps. In development, a read of any other entity throws and names the world’s record, so an island’s flowers never copy into each visitor’s save. A world trait it reads, such as a rate the world sets, stays readable.
What the player builds for themselves in a world, such as their own shed on a friend’s island, belongs to the player. Register it with addRecordEntity(step, player, entity), to the player’s record in the world by default or the player’s game-wide one with { perWorld: false }. The player’s save’s read and restore receive what the player’s record keeps as entities. Each entity the player’s restore spawns is registered to the player’s record on its own, as a key’s restore registers its own. The world’s record reads the world without them, and the player’s leave takes them with the player. releaseRecordEntity(step, entity) lets one go, and listRecordEntities(world, player) lists them.
In development, a trait of one of the player’s entities that saves in both the player’s records read, and a restore writes, is one value kept twice: the player’s read throws, naming both saves. Keep the value in one record, with { perWorld } or a trait of its own.
Keep each entity of the world
Section titled “Keep each entity of the world”A world is entities: a block, a chest and a building each keep a record of their own, and a world save holds one value for the whole world. A world that grows, such as a base players build block by block, keeps one record for each entity rather than one list of everything. Declare a save with each, the trait its entities hold, and list it on defineGame({ worldSaves }). The save keeps every entity of the world holding that trait. A checkpoint reads again only the records whose entity changed since the last one, so the room’s pause follows what players changed, not the size of the world.
The base below is built from the engine’s public entry alone. It declares a block and a sign, the saves that keep each one, how a player builds and breaks a block, and how a sign names the block it hangs on:
import { definePrefab, defineSave, defineTrait, destroy, setTrait, spawn, type Authority, type Entity,} from "@spawnite/engine/core";
// A base players build block by block, from the engine's public entry// alone: one record for each block, so a checkpoint reads again only the// blocks that changed since the last one, however large the base grows.
/** A block's kind, and how many hits it has left. */export const BlockTrait = defineTrait( "outsideBlock", { kind: "stone", health: 3, }, { types: { health: "uint8" } },);
/** A sign's text, and the block it hangs on: a field that holds an * entity, which its record keeps as that block's record. */export const SignTrait = defineTrait( "outsideSign", { text: "", block: null as Entity | null }, { entities: ["block"] },);
/** A block, as a player's build spawns one. */export const block = definePrefab("outsideBlock", { traits: [BlockTrait()],});
/** One record for each block of the world: its kind and its health. The * engine keeps its prefab and its place beside them. */export const blocks = defineSave({ scopes: ["world"], each: BlockTrait, version: 1,});
/** One record for each sign. Its block comes back as that block's entity * in the next room, though the handle differs from room to room. */export const signs = defineSave({ scopes: ["world"], each: SignTrait, version: 1,});
/** Places a block of `kind` at `position`. */export function placeBlock( step: Authority, position: readonly [number, number, number], kind: string,) { return spawn(step, block, { position, traits: [BlockTrait({ kind, health: 3 })], });}
/** Strikes `struck`: one hit less, and gone at the last. */export function strikeBlock(step: Authority, struck: Entity) { const { kind, health } = struck.get(BlockTrait)!; if (health > 1) setTrait(step, struck, BlockTrait, { kind, health: health - 1 }); else destroy(step, struck);}
/** Hangs a sign reading `text` on `on`, a block. */export function hangSign(step: Authority, on: Entity, text: string) { return spawn(step, { traits: [SignTrait({ text, block: on })] });}
/** The block `sign` hangs on, or null once it is gone. */export function findSignBlock(sign: Entity): Entity | null { return sign.get(SignTrait)!.block;}List the saves on the game, defineGame({ worlds: true, worldSaves: { blocks, signs } }), beside any worldState. A game with rooms declares worlds for worldSaves to typecheck, as Worlds says. A plugin exports its saves with each for the game to list, as the building kit does: only the game’s worldSaves lists them.
Each key under worldSaves is camelCase and is where its records are stored, so renaming one leaves its records behind: they stay in the world’s record, and the engine makes no entity from them. A save you drop from the list leaves its parts the same way. Two saves never keep the same trait.
Your save keeps the following:
- The trait’s own fields. The record keeps every field of the trait, and the engine reads and writes them: a save with
eachtakes no schema,readorrestore. Name a field the record leaves out inexclude, and it comes back as the entity’s spawn gave it. - Every number says its width. The trait’s
typesnames the width each number field the record keeps takes, as the sample’s{ types: { health: "uint8" } }does. TypeScript refuses a save whose trait leaves one out, before anything runs: the width is what the record costs, and you choose it.NumberTypeholdsint8,uint8,int16,uint16,int32,uint32,float32andfloat64, which keeps any number exactly, NaN and -0 among them. In development, a write outside a width throws and names the field. A deployed room keeps that value in full and logs it. - A string as it is. A string field keeps any string. A narrower TypeScript type, such as a union of kinds, is not checked as a record loads: rename a stored value with a step.
- Links. A field that holds an entity, listed in the trait’s
entities, keeps the record of the entity it names. In the next room it holds that record’s new entity, though handles differ from room to room. A field that holds a list of entities, with an empty list as its default, keeps each link the same way. A link to an entity no record keeps reads null, and a list drops it. A link to a record of a level not mounted, loaded so or unloaded by a level change, reads null, or is left out of its list. Its record keeps the link until the level mounts or the game changes that field. onEntityRestore({ entity, world, writer }), a field of the save’sdefineSave, runs once every record’s fields and links are back, for what fields alone cannot make, such as the collider a stored building piece leaves out.
Spawn a kept entity from a prefab when it has a look, a collider or traits no save keeps: one spawned without a prefab comes back with its saved traits and its place alone, as the sample’s sign does.
Writes go through setTrait, editTrait, addTrait, addOrSetTrait, removeTrait, updateEach, spawn and destroy, which mark the entity they write. A value changed any other way, such as through a record editTrait handed out and kept past its system, is refused, since its record would not be marked. A pass that only reads takes readEach: updateEach marks each record of a factory trait it hands, changed or not.
A field added to the trait needs no new version: a record stored before it brings the field back as the spawn gives it. A field removed, renamed or retyped raises version and adds a step, migrations: { 2: (old) => next }. The step receives the record’s fields by name, a link as the id of the record it names, and a value JSON cannot hold in the checkpoint codec’s tagged form, such as { "$": "Vector3", "value": [1, 2, 3] }. A field a later build stored that this one does not declare is kept, and written back untouched.
The engine does the following:
- One record for each entity. An entity two saves keep, such as a chest that is also a block, has one record with a part for each. An entity a player’s record or a key keeps belongs to neither the world’s records nor its
worldState. - The entity made again. As the world loads, the engine spawns each record’s entity from the prefab it came from, at its position, rotation and scale. It then writes each save’s fields and links, and runs each
onEntityRestore. What no save keeps comes back as the prefab declares it. An entity spawned with no prefab comes back with its saved traits and its place alone. So does one whose prefab the game no longer defines: the engine warns, and its record keeps the prefab’s name for when you define it again. - The scene’s own entities. A scene’s entity that holds a kept trait is kept under its place in the scene, whether it holds the trait from its spawn or gains it later, as a
<CargoStation>‘s store does. Give its element akey. One with no key that spawns holding the trait throws in development. In a game played alone, one that gains it later is kept as an entity the game spawned, so the next load makes it again beside the scene’s own. Key each element you wrap it in too, such as a<group>: an unkeyed one moves the place when you add an element before it. Its record names its level, so two levels’ entities at one place keep two records. A record whose element the scene no longer places stays as it was, and the engine warns. One destroyed in play stays destroyed after the next load. One that comes back stands at its record’s pose, unless its save keeps the scene’s. A level change keeps the records of the level it leaves, and brings them back when that level mounts again. - One checkpoint for everyone. A checkpoint stores the world’s records and every player’s record together, or none of them. A trade that takes coins from a player and puts an item in a world’s chest is never kept half done.
- Checks. In development, each checkpoint reads kept entities again and throws where one changed with no mark.
spawnite save show <file> prints a save file with the world’s records by id, each save’s fields by name, as an agent reads a world.
A station the scene places
Section titled “A station the scene places”A load puts each scene entity back at the pose its record kept, so a piece a player moved stays where the player left it. A fixed station, such as a shop’s counter, belongs where the scene places it, and a version that moves it moves it in every saved world. Give its save restorePose: "scene": the record keeps the station’s fields, and the scene keeps its place.
import { defineSave, defineTrait } from "@spawnite/engine/core";
// A market stall the scene places, whose takings each world keeps. The// creator may move the stall in a later version, so the record keeps the// takings and the scene keeps the place.
/** A stall's takings, in coins. */export const StallTrait = defineTrait( "marketStall", { coins: 0 }, { types: { coins: "uint32" } },);
/** One record for each stall: its coins, at the place the scene gives it * now rather than the pose its record kept. */export const stalls = defineSave({ scopes: ["world"], each: StallTrait, version: 1, restorePose: "scene",});The option works as follows:
- The whole entity. One save of an entity that says
"scene"holds for the entity, whatever its other saves say. - Scene entities alone. An entity no scene places, made again from its prefab, takes its record’s pose.
- The pose still kept. The record keeps writing the pose, and the first checkpoint after a load writes the scene’s place. A save that goes back to
"record", the default, puts the station where it last stood. - No step for older worlds. A world saved before the option loads as it is, and the option needs no new
version. - A load alone. A system that moves the station in play moves it until the next load, and an
onEntityRestorethat moves it wins over the scene.
A world save holds one value
Section titled “A world save holds one value”A world save, worldState or a plugin’s save with scopes: ["world"] and no each, holds one value for the whole world, such as the day count or a bank’s coins. A trait it restores onto the world is added first, in a plugin’s setup, as the weather sample shows. It is read whole at every checkpoint and parsed whole at every open, so a list of things in it costs the whole world each time. Each world save holds at most 1 MiB of JSON, maxWorldSaveBytes from @spawnite/schema, and a save with each counts nothing toward it:
- In development, the console warns once a world save passes half the limit, and a world save past it throws within a second of game time, naming the save and the move below.
- In a room and on a page, a checkpoint still stores a world save past the limit with the rest, so a payment between a player and the world is never half saved.
WorldSaveLimitPassedEventfires on the step after it, once until the save falls back under.readSaveBudget(world).worldSaveBytesgives each world save’s size, and the room’s log and heartbeat name it.
To move a list out of a world save into a record for each thing, take the following steps:
- Declare a save with
eachfor the trait the list’s things hold, and list it inworldSaves. - Raise the world save’s
version, and keep the list optional in its schema, with a step that passes it on. - In its
restore, spawn one entity for each item of a stored list. - Return the list empty from its
read.
The next checkpoint writes a record for each entity and a small world save in place of the list.
A large shared world
Section titled “A large shared world”Saving a world that many players change, once a minute, without a pause and without losing a change, takes work most engines leave to the game. Rust and Minecraft build it into their own servers, and Roblox, Unity, Unreal, Godot and PlayCanvas leave it to each game’s code. The engine does it for every world that keeps its entities with each, and a game writes nothing for it:
- A checkpoint reads what changed. It reads again only the records whose entity changed since the last one.
- The reading is spread out. Before a checkpoint, the room reads the changed records a little at a time between steps, so a burst of changes does not hold a frame. The checkpoint is still one moment for the whole room.
- A save uploads what changed. The world is stored as pages of records, and a checkpoint uploads only the pages that changed.
- History is kept. The platform keeps earlier saves of the world for a restore: one for each hour of the last day, each 6 hours of the last week and each day of the last 30. Each holds every player’s record in the world at the same moment.
A game helps by keeping its state in the shape that suits it:
- Keep dense state in grids. Terrain, voxel blocks, tile maps, heightfields, fog and soil are cells with no identity of their own. Keep them in a
gridfield on a chunk entity, one record a chunk, never one entity a cell, as An entity or a cell says. - Write only what changed. A system that writes every kept trait each step, even with the same value, has the room read every record again before each checkpoint.
- Leave unsaved what changes all the time. A value that changes every few steps and that the game can work out again, such as a cart’s place on its track, needs no save. Thousands of such entities lengthen every checkpoint’s step, since their records never stop changing.
A world’s size
Section titled “A world’s size”A world’s limit is set by the room’s memory, its room class. Every room runs on the 1 GB class at launch. At each checkpoint the room estimates the memory the world takes: each saved entity by what it is, its record’s bytes, and three times the text of its world saves. readSaveBudget(world) answers that estimate as usedBytes, beside the room’s limit as maxBytes, so a building game refuses a placement before the room does.
The room holds a world to two lines, drawn from its memory and its seats:
- The limit. Past it, the room refuses each spawn or added trait that would add a world record or a grid, with
CommandRefusal.WorldFull,"world-full", which a HUD maps to a line. What the world holds still changes: a write, a move, a destroy and a player’s inventory. The development console warns from three quarters of the limit. - The reopen line. It is the most a fresh room of the class opens again: a room opens its world a page at a time, and a world opens in a heap of the empty room plus 1.6 times what the open world then holds, measured for each shape a world takes. A checkpoint that finds the world past it stores nothing, and the room ends with every player back at the last checkpoint. A room does not open a world past it.
The platform stores at most 12 MiB of a world gzipped, and a checkpoint past it stores nothing in the same way.
The 1 GB class’s limit is about 200 MiB of the estimate beside a room of 12 seats, under a reopen line of about 238 MiB. The following counts are estimates, from the memory each kind of entity took in a room, measured on 2026-10-11:
| An entity whose record holds a few small values | Count on the 1 GB class |
|---|---|
| That only the room sees | About 250,000 |
| That players see | About 86,000 |
| Props: a prefab at a pose with three saved traits | About 31,000 |
The room guards the memory no estimate sees too. When a full collection leaves its heap past 85 percent of its old space, or a heartbeat finds its container past 85 percent of its cap, the room refuses a new world record or grid the same way. A grid’s cells, its colliders and the compressed pages live outside the heap, so the container’s read guards them. The development console warns at 75 percent of the heap, naming the save that keeps the most records. Spawn inside transact so a refusal takes back what the command spent, as When a system throws says.
The saved record
Section titled “The saved record”The save is one JSON record. The game, each kit and each engine save keep their own key, each with its own version, so one owner’s change never touches another’s:
{ "game": { "version": 2, "state": { "gold": 140, "quests": ["intro"] } }, "stores": { "career": { "version": 1, "state": { "kills": 9, "runs": 2 } } }, "kits": { "shop": { "version": 3, "state": { "stock": [] } } }, "engine": { "inventory": { "version": 1, "state": { "slots": [], "equipment": {} } }, "random": { "version": 1, "state": [1, 2, 3, 4] } }}Every owner’s key loads the same way, the engine’s, a kit’s and the game’s own alike, in three steps:
- The version is compared. A stored version above the owner’s refuses the load.
- The steps run. A stored version below the owner’s goes through each numbered step in order, up to the current one.
- The schema reads the result, and it is the only judge. A field the schema does not name is dropped. A missing field that has a default gets it. A missing required field or a value of the wrong type fails the schema. A strict schema, such as
z.strictObject, refuses a field it does not name.
A key that fails any step, or a step that throws or is missing, refuses the whole record: the engine restores nothing and writes nothing over it, and the result names the owner, the key and the reason. A key no owner in this version claims, such as one a removed kit wrote, is kept as it is and written back.
A plugin’s key is its name and its save’s, kits.<plugin>.<save>. Two plugins of one name share a key, so a kit that takes the name of one the game removed reads that plugin’s saved data, and refuses the load where the data does not fit its schema or is at a higher version. A plugin’s call takes saves: false: the plugin then saves nothing, and its stored keys are kept untouched.
Every change to a saved shape raises its owner’s version and adds a step, an added optional field included. The engine holds its own saves to that in its tests, which also allow only added fields inside one compatibility line of engine releases: the major from 1.0.0 on, and the major and minor below it. spawnite build writes, for each owner, its version and a fingerprint of its schema into the bundle’s manifest, under save:
{ "game": { "version": 2, "fingerprint": { "format": 1, "hash": "9f3a0c2be1d47f60" } }, "kits.inventory.bag": { "version": 1, "fingerprint": null }}The fingerprint hashes the schema as JSON Schema, so the order of its fields, its descriptions, its titles and its examples do not change it. A codec’s tagged value counts by the codec’s name. A schema JSON Schema cannot say whole has a fingerprint of null: one with a refinement, a transform, a pipe, a check that rewrites the value, or a default or fallback that a function computes. compareSaveManifestEntries(published, next) from @spawnite/schema takes the save entry of every version the game published. It says how each owner changed since the highest version any of them gave it, since a player may hold a save from any of them. The answers are same, changed-without-version, version-lowered, version-raised, added, or unchecked where a fingerprint is missing or in another format, or a published entry cannot be read.
An override moves a save to the other side. inventory({ saves: { bag: { scope: "player" } } }) keeps one bag on the player entity across every saved entity, and saves: { wallet: { scope: "entity" } } on defineGame gives each saved entity its own coins, which a pickup and an item then pay into. A scope the save may not be kept in fails to typecheck.
The owners restore in a fixed order: the core’s saves, then each plugin’s saves in the order its plugin is listed, a save after each it requires, then the game’s own. The world’s saves restore as the record loads, the player’s onto the player entity as the player joins, and each saved entity’s as setSavedEntity registers it. A saved entity a join hook registers waits for the player’s save to attach, so it restores after the player entity’s state, over every join hook’s default. A saved entity is captured into the record as it goes, by releaseSavedEntity, a destroy or the player’s leave, and the player entity as the player leaves. So a character spawned at the next scene, or after a respawn by destroy and spawn, restores what the last one had saved as that name. The player page says how a game registers its own.
A saved entity a system registers after the player’s join restores in that system’s step, where no join can take the restore back. A restore that throws there makes setSavedEntity throw a SavedEntityRestoreError, which a deployed room logs as the system’s fault. A system may catch it, imported from @spawnite/engine/core or @spawnite/engine, to log it or tidy up, but catching it takes nothing back. What the restore wrote, spawned or emitted before it threw stays in the world. In a page, the restore refuses the load: the session hands out nothing more to write, so the player’s stored save stays as it was, and the game stops with the load-failure screen. In a room, that saved entity’s record keeps what was stored, and the player leaves, as The room’s promise says.
Game loads the record before anything inside it mounts, and writes it while the game plays, as Where the save goes says. createSaveSession(world, { game, account, onRefuse }) holds a player’s records while a game plays, resolving the saves of game, the world’s by default, where the game runs. Where no record is named, it holds a page’s one record of all three parts; record: SaveRecordPart.World holds one record of a room’s:
load(record)loads one, ornullfor a new game, and returns what it found. A record that fails, a saved entity’s record among them, or a restore that throws, refuses the load, andonRefusereceives the refusal, at the load or at a later restore.attachPlayer(player, writer)restores the player-scope saves onto the player entity, with the player’s join’s step as the restores’ writer, then each saved entity a join hook registered, except one registered withrestore: false. It makes the session the one the player’s saved entities restore from; the core’s join calls it.read()returns{ ok: true, record }with the record as it stands, or{ ok: false, problem }where one owner’s read failed, with the owner, its key, the reason and a message. Nothing is written for that read, the status readsunsavedwith the problem, and the next read tries again. The record holds what eachreadreturned, not a copy, so turn it into JSON before the game changes again. It returnsnullbefore a load and after a refused one, since nothing may be written then.versionsOf(record)names each owner’s version in a record by its key, such askits.inventory.bag, and an owner of a page’s world parts with the part’s prefix, such asworld:engine.levels.isOlderReadersays whether a reader is older than a record for any owner.
A kit or a game that keeps an engine value inside its own key keeps it through the engine’s codec, which tags it with its form and converts an older form wherever it sits: a shop keeps itemStack.toSave(stack) and reads itemStack.fromSave(saved). defineSaveCodec makes the same for a value of a kit’s own.
Save a game’s own store
Section titled “Save a game’s own store”To keep a store’s state in the player’s save, wrap its creator in the engine’s persist. It takes zustand’s persist options, so only the import differs from the zustand middleware you know:
import { createStore, persist } from "@spawnite/engine";
interface Progress { kills: number; addKill: () => void;}
export const useProgress = createStore<Progress>()( persist( (set) => ({ kills: 0, addKill: () => set((state) => ({ kills: state.kills + 1 })), }), { name: "progress", version: 1, partialize: ({ kills }) => ({ kills }), }, ),);The store keeps its entry under stores in the record, by its name, with its version. It differs from zustand’s own in three ways:
- It loads when the Game’s save has loaded, never when it is created. Game mounts nothing inside it until the record and every persisted store have loaded, so no component reads a default in place of a saved value.
- A change writes nothing by itself. Each record the engine writes reads the store as
partializekeeps it, as When the save is written says. - An entry the store cannot read refuses the whole save, as a game’s own key does: one a newer version wrote, an older one with no
migrate, and one whosemigrateormergethrows. Every store is checked before anything restores, so the game stops on the load-failure screen with no store loaded, and nothing is written over the save. zustand’s own throws that state away and plays on. A store with no entry in the save starts on its defaults, and itsmergeis not called.
A store that a lazily loaded module makes after the save has loaded reads its entry as it is made. An entry it cannot read refuses the save as a load does: the game stops on the load-failure screen, the app is told, the entry stays as it is, and the page writes nothing more that session.
useProgress.persist keeps zustand’s API: getOptions, rehydrate and hasHydrated read as they do there. Two persisted stores with one name throw, except under hot reload, where the store the edited module makes replaces the old one and keeps its live state. Stores live once per page, so the first Game on the page loads and saves them; a second Game, as on a Storybook page, saves nothing. A test that renders its Game calls resetPersistedStores() and awaits resetPageSave() from @spawnite/engine/testing after each case. The first puts every store back to its defaults, unloaded. The second waits for the write the last Game’s unmount sent to reach the host, then ends the page’s save, so the next Game loads its host’s record. A test that unmounts its Game and then reads what was saved awaits resetPageSave() first.
A persisted store is for a game with no rooms. In a game whose package.json gives it a room, a spawnite.room, the room writes every player’s save, so a persisted store is an error. The game says so when it mounts in development and in spawnite simulate, each naming the store, and spawnite build says so, naming each module that takes persist from @spawnite/engine.
The build reads the modules the bundler parses in both halves, so a re-export through a file of the game’s own, a file outside src and a lazily imported module all count. A module that takes @spawnite/engine or @spawnite/engine/core whole, as a namespace, an export * or a dynamic import, fails the build too, because the build cannot tell whether it uses persist or defineSave: import each name by name. spawnite build --server checks the server half the same way. Save that value from the server half with the game’s playerState or a plugin’s saves instead. The game lint refuses persist from zustand/middleware, which writes to one browser and bypasses the save. A setting that belongs to the device, as the engine’s quality and volume do, keeps the browser’s storage.
When the save is written
Section titled “When the save is written”A game never writes its save. It changes its state, and the platform writes the newest state on its own schedule, the same for every game. The engine reads the record every 5 seconds, or every 30 seconds while its JSON is over 256 KiB, and each time it changed, it numbers it, gzips it and hands it to the page’s host. The host keeps it in the journal on the device, which a reload on the same device picks up. It sends the record to the cloud at the following moments, each only when the record changed since the last one sent:
- Every 2 minutes.
- When the tab is hidden, but no sooner than 30 seconds after the last write.
- When the Game unmounts, and when another tab or device asks for the save.
save() saves now, at a moment that matters, such as a level’s end. The platform writes the record at once, where it changed, and the device keeps it at once, a second after its last read at the closest. The status reads unsaved from the call, and saving while the write is on its way. A call that finds the record unchanged writes nothing.
A call within 15 seconds of the last write to the platform waits until those seconds are over, which keeps a game within the backend’s 4 commits a minute. The 2 minutes count again from every write, whether a call or the timer made it. So a game can call save() as often as it likes: a call every frame writes every 15 seconds at most, and a game that never calls writes every 2 minutes. The engine reads a record over 256 KiB as JSON for such calls 30 seconds apart at the closest, since the read costs a frame.
A system passes its step: save(step) saves the page’s record in a game played alone, and asks the room for a checkpoint in a room, as Saves in a room says.
A new game reads unsaved until its first record is stored. Nothing is written until the save has loaded. A read of the record that throws, as a game’s read can, writes nothing: the status reads unsaved, the development console names the error, and the next read tries again.
A record must fit two limits: 16 MiB as JSON and 4 MiB gzipped. One that passes either while the player plays goes to the cloud at once, and nothing newer is read after it. The status reads refused, the development console names the limit and the measured size, and once the host stores it the game stops with the load-failure screen. A write of it that fails is sent again at the next window, a hidden page’s flush, or a hand-over’s ask. As it opens, the page reads the record once as a trial, after the migration steps and the restore of a world-scope save, measures that record as JSON and gzipped, and refuses a record past either limit the same way. The body it loaded is not measured, so a version whose migration step trims the record opens it.
A record past twice either limit, the platform’s ceiling, is never stored: the status reads refused, the last save that fit stays, and play goes on. Where the cloud lacks the last record that fit, as after its write failed, the engine sends that record again. A body that unpacks past 32 MiB, the platform’s ceiling, is not read. The console warns once a record passes three quarters of either limit, with both sizes.
useSaveStatus() answers the state of the save and where it goes, so a game can draw its own indicator; the engine draws none. It returns the following fields:
status:saved,unsaved,savingorrefused, as the table below says.destination:platform,browserornowhere, as Where the save goes says.size: the newest record’sunpackedBytesas JSON andcompressedBytesgzipped;nullbefore the first.problem: a size limit the newest record is past, with thelimit, thebytes, themaxBytesandceiling, true where it is past the platform’s ceiling and so never stored, whilestatusreadsrefused. Or an owner’s read that failed, with itskey,ownerandreason, whilestatusreadsunsaved.nullwhile neither holds.
| Status | Means |
|---|---|
saved |
The platform, or the browser on the dev server, holds the newest state |
unsaved |
A change waits for its write, the last write or read failed, or nothing was ever stored |
saving |
A write is on its way |
refused |
The newest record is past a size limit: stored once and the game stops, or past the ceiling and never stored |
Time while the game is closed
Section titled “Time while the game is closed”readUnixSeconds reads the room’s clock at the tick, in a system, a hook, a save’s read and restore, and a view alike. Keep a stamp, the moment something started or ends, never an amount of time grown. A system compares the stamp with the clock each tick, and the restore compares the stamp the save kept with the clock at the restore, so time the game was closed counts with no sum of its own. Time a hidden tab or a suspended machine skipped counts too, as The time of day says.
This farm keeps when the player’s crop was planted. Its system ripens the crop six real hours later, and its restore ripens it at once where the game stayed closed that long:
import { addTrait, createQuery, defineGame, definePlugin, defineSave, defineSystem, defineTrait, Phase, readUnixSeconds, setTrait, updateEach,} from "@spawnite/engine/core";import { z } from "@spawnite/schema";
// A crop that ripens six real hours after it is planted, whether the// player plays, closes the game or leaves the tab: it keeps when it was// planted, never how long it has grown.
/** Seconds of real time a crop takes to ripen. */export const growSeconds = 6 * 3_600;
export const CropTrait = defineTrait("crop", { plantedAtSeconds: 0, isRipe: false,});const crops = createQuery(CropTrait);
/** Whether a crop planted at `plantedAtSeconds` is ripe at `nowSeconds`. A stamp later * than the clock, from another machine or a clock set forward, reads as * not ripe yet. */function isRipeAt(plantedAtSeconds: number, nowSeconds: number) { return nowSeconds - plantedAtSeconds >= growSeconds;}
const farm = definePlugin(() => ({ name: "farm", onPlayerJoin({ step, player }) { addTrait(step, player, CropTrait, { plantedAtSeconds: readUnixSeconds(step), isRipe: false, }); }, systems: [ defineSystem({ name: "ripen", phase: Phase.Rules, run(step) { const nowSeconds = readUnixSeconds(step); updateEach(step, crops, ([crop]) => { if ( !crop.isRipe && isRipeAt(crop.plantedAtSeconds, nowSeconds) ) crop.isRipe = true; }); }, }), ],}));
export const game = defineGame({ name: "farm", start: "field", plugins: [farm()], playerState: defineSave({ version: 1, scopes: ["player"], schema: z.object({ plantedAtSeconds: z.number() }), read: ({ player }) => ({ plantedAtSeconds: player.get(CropTrait)?.plantedAtSeconds ?? 0, }), // The stamp kept at the last save against the clock now: ripe at // once where the game stayed closed long enough. restore: ({ world, player, writer }, saved) => { setTrait(writer, player, CropTrait, { plantedAtSeconds: saved.plantedAtSeconds, isRipe: isRipeAt( saved.plantedAtSeconds, readUnixSeconds(world), ), }); }, }),});A saved stamp from another machine, or from a clock the player set forward, can be later than the clock where the player returns. The farm’s crop then stays unripe until the clock passes its time; a sum of closed time would clamp at 0 for the same reason.
A UTC day is Math.floor(readUnixSeconds(step) / 86_400), and a day that turns at a given hour shifts the stamp back by that hour first. This market restocks once a day at 06:00 UTC, and keeps the last day it restocked in a world trait:
import { addTrait, definePlugin, defineSystem, defineTrait, Phase, readUnixSeconds, setTrait,} from "@spawnite/engine/core";
// A market that restocks once a day at 06:00 UTC: its day is the UTC day// shifted back by the restock hour, so it turns at 06:00, not midnight.
/** The UTC hour the market's day turns at. */export const restockHourUtc = 6;
/** The market's day at `unixSeconds`: it turns at `restockHourUtc`. */export function readMarketDay(unixSeconds: number) { return Math.floor((unixSeconds - restockHourUtc * 3_600) / 86_400);}
export const MarketTrait = defineTrait("market", { lastRestockedDay: -1, stock: 0, restocks: 0,});
export const market = definePlugin(() => ({ name: "market", setup(world, writer) { addTrait(writer, world, MarketTrait); }, systems: [ defineSystem({ name: "restock", phase: Phase.Rules, run(step) { const day = readMarketDay(readUnixSeconds(step)); const market = step.world.get(MarketTrait); if (market?.lastRestockedDay === day) return; setTrait(step, step.world, MarketTrait, { lastRestockedDay: day, stock: 10, restocks: (market?.restocks ?? 0) + 1, }); }, }), ],}));A world trait no save reads lives as long as its room, so a new room restocks on its first tick; the carried-gear recipe keeps its weather in the world’s record instead. A reward each player claims once a day goes in the player’s save, with the day the player claimed it.
The UTC hour is new Date(seconds * 1000).getUTCHours(). The local-time getters read the machine’s zone, which differs between the room and the player’s page, so the game lint refuses them in gameplay. A view formats the player’s local time.
The Unix clock reads real time. DayClockTrait is the in-game hour that moves the sun, which a creator sets; it is not the Unix clock.
Where the save goes
Section titled “Where the save goes”The page’s save goes to one of three places, which destination names:
platform: in the player app’s frame, for a game with no rooms. The app hands the page the newest body in itsinit, and the page hands each record back over the same channel, as the trust boundary lists. The page holds no credential and reaches no network for its save. Once the app has answered the page’s hello, the page waits for itsinit, however long it takes.browser: on the dev server, and on any page with no app around it, a frame that leaves the page’s hello unanswered for 2 seconds included. Every record is kept in the browser’s storage under<name>-record, so a reload restores the newest, and a record sent to the cloud readssavedonce written.nowhere: in a game with rooms, where the room writes each player’s save. Also on aspawnite play profilerun, which starts clean and seeds the world’s random stream with a fixed seed so runs compare, and in a second Game on one page, as on a Storybook page.
The page’s host is read once a page. A Game that mounts again, or another Game of the same name, loads the record the last one left, and the page’s records keep one rising number. Game opens its save once for its world.
A record that will not load stops the game: a key that fails, a restore that throws, or a body that cannot be read. Game restores nothing and mounts nothing, writes nothing over the save, tells the app, and shows “We couldn’t load your progress” with the reason, in development as a player sees it.
Saves in a room
Section titled “Saves in a room”A room mounts a scene and not <Game>, so a game with rooms exports its game from each scene’s file, export { game } from "../game";, which carries the saves. The room is the only writer of its players’ saves, and the page holds none.
The room saves everyone in it together, by a checkpoint: it reads every player’s record at one tick, uploads each record that changed, and commits them all at once. Either every player’s save moves to that tick, or none does. So whatever the game moved between two players, such as an item one hands the other, is in both saves or in neither, whatever fails. The room takes a checkpoint at the following moments:
- Every 60 seconds while any record changed, and every 2 minutes while the room holds one player.
- At
save(step), which a game’s server half calls at a moment that matters, such as a run’s end: the room takes a checkpoint now, where any record changed. A call within 5 seconds of the last checkpoint’s read waits until those seconds are over, so a call every tick takes 12 checkpoints a minute at most. The timed checkpoint counts again from every checkpoint, whether a call or the timer made it. The call names no player, since the checkpoint saves everyone. - When a player leaves the room, as the player’s page closes or another tab or room asks for the player’s seat, or as the last player leaves. The player’s leave is read in the tick the player leaves, after each plugin’s
onPlayerLeave, so what a hook hands on as the player goes is in the other player’s save and not the departing player’s. The checkpoint that holds it frees the player’s seat. - As the room stops, for every player still in it.
// Excerpt of src/systems/checkpoint.tssave(step);A player’s join enters whole or not at all. The room loads the player’s save before the player entity is made. It restores it onto the player entity after each plugin’s onPlayerJoin, so each onPlayerReady reads what the player saved. It restores each saved entity a join hook registered right after the player entity, and each one a ready hook registers as it registers, the character among them as the characters plugin spawns it. Once every onPlayerReady has run, it reads the player’s record once more as a trial and measures it as JSON and gzipped. It measures the record as this version reads it after its migration steps, so a version whose step trims it lets the player in.
A save the room cannot load, a restore that throws, onto the player entity or onto a saved entity, a trial read that fails, or a record past the size limit refuses the player’s join. The refusal takes out what the player’s join and ready hooks spawned, takes back their events, and writes nothing over the player’s save. The room closes the player’s socket with saveNotLoadedCloseCode, or with saveNewerCloseCode where a newer version of the game wrote the save. Each reason reads with readSaveRefusalReason, and the loading screen says the player’s progress did not load. The room’s other players are not touched.
Where a seated player’s save stands is on the player entity, as readTrait(player, PlayerSaveTrait)?.status. Between two checkpoints, the room reads the player’s record every 5 seconds, or every 30 seconds while its JSON is over 256 KiB, so a change shows by the next read. It reads one player a step, so a room with more players than steps in 5 seconds reads each less often. The status reads as follows:
saved: the player’s record is as the last checkpoint stored it, or, for a new player, as the player joined, since nothing is written for the player until it changes.unsaved: the player’s record changed since the last checkpoint stored it, as while a checkpoint that stopped without its commit waits for the next, or the player’s last read failed.saving: a checkpoint that holds the player’s record is on its way, its retries included.refused: a saved entity’s restore threw after the player’s join, and the player leaves once the checkpoint that holds the player lands.
A development room keeps each save as a JSON file in .spawnite/saves in the game’s folder, by the name the page sends, and commits it through the same checkpoints, so a restart or a rejoin restores progress. A room the cli starts for spawnite play, a playtest or a profile keeps its saves for its session instead, so it starts every player afresh while keys, world records and deliveries work as in a hosted room. A playtest’s rooms share theirs in the session’s folder, so a save goes with a player a teleport moves. --room-env ROOM_SAVES=1 keeps them in files, as a check of a save across a restart does. spawnite simulate runs no room.
What a checkpoint costs the tick
Section titled “What a checkpoint costs the tick”A checkpoint reads every record the room holds in one tick: each player’s records, the world’s and each key’s. Each read is checked, as What stops a save says, and turned into JSON, on the room’s thread, so every player waits for that tick. A large save makes the room lag for a moment at each checkpoint, about once a minute. The cost grows with the number of values in a record more than with its bytes, so a record of many small objects, such as a building’s blocks, costs the most for its size.
The table gives how long a checkpoint held the tick in a room of 50 players, each with a 300-item inventory in two records, beside a world’s record of small block objects. A frame is 16.7 ms.
| The world’s record | The tick, median |
|---|---|
| None | 6.5 ms |
| 1 MB, 27,000 blocks | 11 ms |
| 4 MB, 108,000 blocks | 25 ms |
| 16 MB, 430,000 blocks | 83 ms |
These were measured on 2026-10-10 on a desktop that other work kept 7 to 99 percent busy, not on a hosted room. That is about 5 ms for each MB of such a record.
The same blocks kept by a save with each, as Keep each entity of the world shows, cost what changed since the last checkpoint rather than what the world holds. The next table gives the tick in the same room, a block’s record holding its place and kind:
| Blocks | Kept as | None changed | 1% changed | 50% changed |
|---|---|---|---|---|
| 27,000 | One worldState list |
14 ms | 14 ms | 15 ms |
| 27,000 | A record for each block | 4.3 ms | 5.0 ms | 26 ms |
| 108,000 | One worldState list |
36 ms | 35 ms | 31 ms |
| 108,000 | A record for each block | 4.4 ms | 7.6 ms | 111 ms |
Each changed record costs about 2 µs, against 0.3 to 0.5 µs for a block in one list, so each costs less until about a fifth of the blocks change between two checkpoints. A building game changes a few blocks a minute. A world where most of what it keeps moves all the time, such as a herd of animals, keeps that in a worldState instead. A record for each entity takes about twice the bytes of one list, so 108,000 blocks take 7.7 MB. These were measured on 2026-10-10 on a desktop 6 to 91 percent busy, the bench’s own room included.
Before a checkpoint, the room reads the changed records ahead, a little each tick within what is left of the frame, so the checkpoint’s own tick reads only what changed in its last few ticks. The save is still one snapshot of the whole room at one tick: a record read ahead and changed again is read again. A game does nothing for it, as A large shared world says.
The next table gives the checkpoint’s tick in the same room at the real 60-second interval, 108,000 blocks each kept by a record, the players’ 4.4 ms included:
| Blocks changed before the checkpoint | Read on its tick | Read ahead first |
|---|---|---|
| 54,000 at once, about 40 s before it | 132 to 161 ms | 7.0 to 7.2 ms |
| 1% a second, a new 1% each second | 100 to 107 ms | 7.4 to 14 ms |
These were measured on 2026-10-10, two rounds each, alternating, on a desktop 15 to 32 percent busy, in a bench room that stepped about 13 times a second rather than 60.
An entity written every few ticks, such as a cart that moves all the time, never settles, so the checkpoint reads it on its tick: a few thousand of them cost a pause at every checkpoint. Keep such state in one worldState list, or keep no save for a value the game can work out again. In development, the room’s console warns at most once a minute when the checkpoint’s own reads lengthen its step, naming the save it read most of.
A checkpoint asked for at once, as when a player moves to another room, waits up to a second while the room reads the changed records ahead, then reads what is left.
A room whose world keeps records with each adds saveEach to its heartbeat, for the last checkpoint since the one before:
marked,readandchanged: the entities a write marked, the records read again, and the records whose text changed.removed: the records dropped.dependencies: the traits the saves’ reads reach, by name. A write to any of them marks its entity.readAheadRecords: the records read ahead of the checkpoints since the last heartbeat. A heartbeat with records read ahead and no checkpoint carries 0 for the others.
Each checkpoint also reads a few unmarked records again, to check that every write marked its entity:
- A development room throws where a record changed with no mark.
- A hosted room keeps the new text in that checkpoint, and logs a
save-audit-mismatchline with the count and the first record’s id.
Either is an engine bug to report, since every engine write marks what it writes. The room’s heartbeat log reports the longest read of each heartbeat as saveReadMilliseconds. In development, the room’s console warns, at most once a minute, when a checkpoint’s read holds the tick past one frame, naming its slowest record and that record’s size.
Two more heartbeat fields time the checkpoints: saveCommitSeconds, the longest from a checkpoint’s read to its commit, and saveLateSeconds, the longest a checkpoint read after it was due. A checkpoint reads late while the one before it is still on its way. It then carries everything changed since, and nothing is lost. A room logs a save-late line, at most once a minute, when a checkpoint reads more than a second late.
Keep a record the game names
Section titled “Keep a record the game names”A keyed record is a save the game names rather than a player: a plot in a world, a guild’s bank, a village’s market. Any room of the game may open one, one room at a time, and the room that holds it commits it with its players at every checkpoint, so an item a player takes from a bank lands in the player’s save and leaves the bank’s in one commit. Roblox keeps such a record in a data store any server writes, with a lock the game writes itself. Here the platform holds the lock.
Declare one with defineKeyedSave at module scope, and name one record with its for. Its parent says what it belongs to and goes with: "world" takes the world’s id and a key, "account" a player’s id alone, and "game" a key alone. The same parts give the same handle, so two handles of one record are ===. Every key event’s record carries the handle it names: isKeyedSaveEventFor(record, guildBanks.for("ravens")) tells whether the event is about the Ravens’ bank. A handle reads back its name, parent, parentId and key, so an event about any guild’s bank is record.handle.name === guildBanks.name, and its guild is record.handle.key.
A key’s read receives the entities registered to it alone: its own entity, which the engine makes as the key opens, each entity its restore spawns, and each a system registers with addKeyEntity(step, handle, entity). Another record never keeps one of them: addKeyEntity refuses a player and an entity a player’s save or another key keeps, setSavedEntity refuses a key’s entity, and the world’s read sees none. In development, a key’s read that reads an entity not registered to it throws.
listKeyEntities(world, handle) lists a key’s registered entities as its read receives them, such as a bank’s chests a deposit fills. releaseKeyEntity(step, entity) lets the key go of one, which then stays in the world: to hand a sword from a bank’s chest to a player, release it from the key and register it to the player with setSavedEntity in one tick. The next checkpoint commits both records. Destroying a registered entity drops it from the key, and destroying the key’s own entity closes the key, as closeKey does.
The garden below is a creator’s plugin built from the engine’s public entry alone. A new garden starts with a seedling, and another room’s ask is refused while anyone plays in the room that holds it:
import { defineSystem, Phase } from "@spawnite/engine/core";import { addKeyEntity, closeKey, defineKeyedSave, definePlugin, defineTrait, isKeyedSaveEventFor, KeyAskedEvent, KeyOpenedEvent, openKey, readEvents, readPlayers, refuseKeyAsk, requireWorldId, spawn, type Authority, type AuthoritativeStep,} from "@spawnite/engine/core";import { z } from "@spawnite/schema";
// A garden in a world that any room of the game may hold, one at a time,// built as a creator's plugin is, from the engine's public entry alone:// its crops are its entities, its record restores them in the room that// opens it, and an ask from another room is refused while anyone plays// here.
/** A crop, and how far it has grown. */export const CropTrait = defineTrait("outsideCrop", { grown: 0 });
/** Each garden's record: how far each of its crops has grown. */export const gardens = defineKeyedSave({ name: "garden", parent: "world", version: 1, schema: z.object({ crops: z.array(z.int()) }), // The garden's entities alone: its own and each crop registered to it. read: ({ entities }) => ({ crops: entities .filter((entity) => entity.has(CropTrait)) .map((entity) => entity.get(CropTrait)!.grown), }), // Each crop the restore spawns is registered to the garden. restore: ({ writer }, saved) => { for (const grown of saved.crops) spawn(writer, { traits: [CropTrait({ grown })] }); },});
/** The north garden of the world `main`. */export const northGarden = gardens.for(requireWorldId("main"), "north");
/** Asks for the north garden: opened at once where no room holds it, * passed by the room that does where its game lets it go. */export function openGarden(step: Authority) { openKey(step, northGarden, { ask: true });}
export const gardening = definePlugin(() => ({ name: "gardening", systems: [ defineSystem({ name: "tend", phase: Phase.Rules, run: tendGarden }), ],}));
function tendGarden(step: AuthoritativeStep) { const world = step.world; for (const { record } of readEvents(step, KeyOpenedEvent)) { if (!isKeyedSaveEventFor(record, northGarden) || !record.isNew) continue; // A new garden starts with one seedling. const seedling = spawn(step, { traits: [CropTrait()] }); addKeyEntity(step, northGarden, seedling); } for (const { record } of readEvents(step, KeyAskedEvent)) { if (!isKeyedSaveEventFor(record, northGarden)) continue; // Kept while anyone plays here; passed to the room that asked // once nobody does. if (readPlayers(world).length > 0) refuseKeyAsk(step, northGarden); else closeKey(step, northGarden); }}Crops that grow while nobody plays, or a reward once a UTC day, read the time with readUnixSeconds, as Time while the game is closed shows.
Open, close and ask for a key
Section titled “Open, close and ask for a key”Each call takes the room’s step and the handle, and the room answers on a later tick with an event:
openKey(step, handle)answersKeyOpenedEvent, with the key’s entity andisNewfor a key with no record yet, whoserestoredid not run. The record’sentityisnullwhere the entity is gone by the time a system reads the event, as when the key closed again, so a system checks it before it writes. A room that holds the key refuses it, andKeyRefusedEventnames that room asroomId.openKey(step, handle, { ask: true })opens the key at once where no room holds it, and otherwise asks the room that holds it to pass it. That room’s game hearsKeyAskedEvent, and answers withcloseKey, which passes the key, orrefuseKeyAsk, which this room hears as the refusalkept. A game that always opens withaskhandles both cases with one call.closeKey(step, handle)reads the key a last time and removes every entity registered to it in that call, so nothing after it can write the key, and raisesKeyClosedEvent. The room’s next checkpoint, due at once, commits that read and lets the key go. On a key still opening, it cancels the open.deleteKey(step, handle)closes the key where a room holds it, then empties its record;KeyDeletedEventanswers once the platform takes it.fetchKey(step, handle)reads the key’s last committed record without holding it, asKeyFetchedEvent, in the shapeSaveFetchedEventhas.
readKeyedSaveState(world, handle) answers a KeyedSaveState, Closed, Opening, Open or Closing, and a second openKey of a key opening or open throws. findKeyEntity, findEntityKey, listKeyEntities and listOpenKeys read the keys a room holds. KeyRefusedEvent’s reason is a KeyRefusal: Held, Kept, Limited past the room’s 256 records, RateLimited past its asks, PastLimit, Unreadable, Newer, Unavailable or Cancelled. KeyClosedEvent’s is a KeyCloseReason: Closed, Asked, PastLimit, Deleted, or WorldClosed where its world closes every key under it, as for the world’s restore. Each call throws on a world no room holds keys for, such as a game played alone, since a page could edit a key it held.
Two numbers keep a key from bouncing between rooms. For 30 seconds after a key opens, no room may ask for it: an ask is refused as held, with retryAfterSeconds saying when to ask again. Once asked, its holder’s game has 45 seconds to answer. Silence then does what the declaration’s whenUnanswered says: "close", the default, closes the key with the reason asked, and "refuse" refuses the ask, as a plot a player stands on wants. A room may ask for 20 keys a minute.
Each key’s record meets the size limit every record has alone, 16 MiB as JSON and 4 MiB gzipped, and the world meets its own. readSaveBudget(world) reads each held key’s record against the record limit, as text, at the last checkpoint, and the development console warns at 75 percent. A key whose record passes the limit is committed, then closes with the reason past-limit. An open of a key whose record, as this version reads it, is past the limit is refused as past-limit, so a version whose step trims the record opens it again. A world past its room’s reopen line is not committed, and its room ends. deleteAfterIdleSeconds on the declaration deletes a record no room opens for that long after its last close. It is off by default, so no record is deleted unasked.
A development room keeps each key in .spawnite/saves beside the players’ saves, and every room on the folder shares its keys with the same rules, a stopped room’s keys free at once. spawnite play keyed-save hold and spawnite play keyed-save ask, and the MCP’s hold_keyed_save and ask_keyed_save, act as a second room there, so you can check how your game’s room answers one.
Send a deposit to another record
Section titled “Send a deposit to another record”A deposit moves something from one record to another that this room may not hold: coins a player pays into the player’s guild’s bank, a gift to a friend in another room, a prize to a board’s winner. Declare its kind once with defineDeposit(name, { schema }). In the room’s step, deliver(step, from, to, { deposit, id, payload }) sends it from a record this room holds, from, to any record, to: a player’s, a player’s record in a world, a world’s or a key’s. Roblox leaves the same move to a game’s own two writes and its own retries; here the send leaves the sender’s record in the same commit as what the sender gave up, so the two never disagree.
- Send it inside
transact, beside what the sender gives up, such as the coinsspendCoinstakes.deliveranswers{ isQueued: true }, or a refusal such asnot-heldfor afromthis room does not hold; throw on a refusal so the spend goes back too. - The receiver takes it in its record’s
onDepositReceive, a hook for each kind, in the room that holds the receiving record, on the tick it is handed over. A player’s records’ hooks and the world’s are the game’s,defineGame({ deposits: { player, playerWorld, world } }), and a keyed record’s are on itsdefineKeyedSave. A player’s records’ hooks receive the player entity asplayer, the world’s none, and a keyed record’s itsentityandkey. The hook writes the record, or answers"decline", which sends the deposit back.deliverrefuses a deposit to a record with no hook for its kind, asno-receive-hook. - A deposit that comes back, declined, or handed to a room that did not commit it within 10 minutes, runs its record’s
onDepositReturnfor its kind, so the coins return to the wallet they left. - A hook writes its own record alone, in a deployed room as in development. Its
writerreaches its record’s entities and what the hook spawns, which its record keeps from then on. A write to another record’s entity, or to the world’s own traits from a player’s or a key’s hook, throws, so the deposit comes backthrew, naming both records, and the room runs on. A player’s hook that changes what the player’s other record keeps is refused the same way. A purchase’sgrantwrites any record, so a grant may write the island the player bought for, which the world’s restore marks througheffectAt. - Its
id, 1 to 128 characters, is the game’s: the same id sent twice delivers once, so a retry or two rooms awarding one prize send one deposit. - The limits: 20 sends a minute from one record, 5 a minute from one record to another, and 16 KiB a payload.
A record is named by records: records.player.for(playerId) is the player’s game-wide record, records.playerWorld.for(worldId, playerId) the player’s record in a world, and records.world.for(worldId) the world’s. A handle is an address: it opens nothing, and does not say the record exists. A player’s id is readPlayerId(player), and a world’s is readHeldWorld(world)?.id. Text from elsewhere, such as a friend’s id a command carries, becomes one through requirePlayerId or requireWorldId. The two ids are typed apart, so records.playerWorld.for(playerId, worldId) fails to typecheck. To type each hook’s payload by its kind, a game registers its kinds once, in its own source: declare module "@spawnite/engine" { interface Register { deposits: typeof tribute } }. The sample below leaves it out: its tests register it beside the other kinds they send.
The guild’s bank below takes tributes from any room of the game. A player pays from their wallet, and the room that shows the bank opens it with { ask: true }: it is handed every tribute that waits, applies each through the bank’s hook, and its next checkpoint commits them:
import { addCoins, addTrait, closeKey, defineDeposit, defineKeyedSave, defineGame, defineRoom, records, defineTrait, deliver, findKeyEntity, findWalletHolder, isKeyedSaveEventFor, KeyAskedEvent, openKey, readPlayerId, readEvents, readTrait, setTrait, spendCoins, transact, type Authority, type AuthoritativeStep, type Entity, type PlayerEntity, type JoinStep, type World,} from "@spawnite/engine/core";import { z } from "@spawnite/schema";
// A guild's bank that any room of the game pays into, built as a creator's// game is, from the engine's public entry alone. A player pays from their// wallet with a deposit, so the coins leave the player's record and reach// the bank in one commit, whichever room holds the bank; the room that// shows the bank opens it and is handed what waits.
/** Coins a player pays into * their guild's bank. */export const tribute = defineDeposit("tribute", { schema: z.object({ coins: z.int().check(z.positive()) }),});
/** The coins a bank holds, on the bank's own entity. */export const VaultTrait = defineTrait("outsideVault", { coins: 0 });
/** Writes the coins a bank holds, on its entity. */function writeVault(writer: Authority | JoinStep, bank: Entity, coins: number) { if (bank.has(VaultTrait)) setTrait(writer, bank, VaultTrait, { coins }); else addTrait(writer, bank, VaultTrait, { coins });}
/** A guild's bank, one record across the game: `banks.for(guild)`. */export const banks = defineKeyedSave({ name: "guild-bank", parent: "game", version: 1, schema: z.object({ coins: z.int().check(z.nonnegative()) }), read: ({ entity }) => ({ coins: readTrait(entity, VaultTrait)?.coins ?? 0, }), restore: ({ writer, entity }, saved) => writeVault(writer, entity, saved.coins), // The bank takes a tribute in the room that holds it, in the tick it // is handed over, and the next checkpoint commits it. onDepositReceive: { tribute: ({ writer, entity, delivery }) => { const held = readTrait(entity, VaultTrait)?.coins ?? 0; writeVault(writer, entity, held + delivery.payload.coins); return undefined; }, },});
/** Each player's record: the player's wallet, which takes back a tribute * the bank declined or never took. */export const game = defineGame({ name: "guild-bank", start: "test", room: defineRoom(), plugins: [], saves: { position: false, health: false, stats: false, levels: false, }, deposits: { player: { onDepositReturn: { tribute: ({ writer, player, delivery }) => { addCoins(writer, player, delivery.payload.coins); }, }, }, },});
/** Pays `coins` from the player's wallet into `guild`'s bank, and * answers whether it went: the spend and the send happen together or * not at all. */export function payTribute( step: Authority, world: World, player: PlayerEntity, guild: string, { coins, id }: { coins: number; id: string },): boolean { // The player's id in the game, which the player's // record is named by. const playerId = readPlayerId(player); const paid = transact(step, () => { if (!spendCoins(step, findWalletHolder(world, player), coins)) throw new Error("The player's wallet holds too few coins."); const sent = deliver( step, records.player.for(playerId), banks.for(guild), { deposit: tribute, id, payload: { coins }, }, ); if (!sent.isQueued) throw new Error(sent.refusal); }); return paid.isApplied;}
/** Opens `guild`'s bank in this room, asking the room that holds it to * pass it, so its tributes are handed here. */export function openBank(step: Authority, guild: string) { openKey(step, banks.for(guild), { ask: true });}
/** The coins `guild`'s bank holds, where this room holds it. */export function readVault(world: World, guild: string): number | null { const bank = findKeyEntity(world, banks.for(guild)); return bank ? (readTrait(bank, VaultTrait)?.coins ?? 0) : null;}
/** Passes the bank to another room that asks for it. */export function passBank(step: AuthoritativeStep, guild: string) { for (const { record } of readEvents(step, KeyAskedEvent)) if (isKeyedSaveEventFor(record, banks.for(guild))) closeKey(step, banks.for(guild));}The same shape serves any record every room writes, such as a village’s market. Each room reads it with fetchKey, which answers its last committed record, and sells into it with a deposit. The room that shows the market opens the key, with { ask: true } where another room holds it, and is handed what waits. No room needs a loop that holds the key for the others. A deposit to a key no room opens waits until one does: at launch the platform applies no deposit to a key nobody holds, so a game opens the keys it sells into.
The room’s promise
Section titled “The room’s promise”At every checkpoint, every player’s save in the room moves to the same tick, or none does: the room never commits one player’s save without the others’. The promise has no exception. A change to the room that departs from it needs a maintainer’s explicit approval, recorded in the pull request that makes it.
Each failure keeps the promise as follows:
-
A load refused at the player’s join: the player’s join is refused before the player enters, so no checkpoint holds the player.
-
A restore that throws after the player’s join, as a saved entity a system registers: that saved entity’s name keeps the record stored for it, and nothing is written over it that session, as a key no owner claims is kept. Every other saved entity of the player’s reads on. The player’s status reads
refusedin that step. Before the next, the player leaves, and the player’s record, read as the player leaves, commits with everyone else’s. The player’s socket closes withsaveNotLoadedCloseCodeonce that commit lands.As the room closes, its last checkpoint holds the player the same way. A restore can change more than its own entity before it throws, by a write, a spawn, an event, a pass over a query or a listener it set off. That would leave twice what it moved out of that entity’s record, so the room ends with nothing committed instead. A call the engine refused or skipped counts as none, such as a refused writer, a throw before the first write, a removal of a trait the entity lacks, a pass that matched nothing, or
checkEntityAuthorityalone. -
A read that fails at a checkpoint: the room reads again on the next tick, and a second failure ends the room with nothing committed, as What stops a save says.
What stops a save
Section titled “What stops a save”Three things stop a save, in a page and in a room alike. Each is the game’s to avoid:
- A record past the size limit. A record must fit 16 MiB as JSON and 4 MiB gzipped. In a page, a record over either is stored once, then the game stops with the load-failure screen, and each later open measures the save again and refuses it while it is still past the limit. A record past twice the limit is never stored, and the last save that fit stays. In a room, the checkpoint still saves it with everyone’s, up to twice the limit, and then removes the player from the room. The player takes no seat in that game for 10 minutes, and after that the player’s join is measured again and refused while the player’s save is still past the limit. Keep the record small: save what outlives a session, such as a level or a count, never a log that grows each time the player plays. The development console warns once a record passes three quarters of either limit.
- Save code that throws. A
read, arestoreor a migration step that throws. In a page, a read that throws writes nothing and the next read tries again. In a room, a read that throws at a checkpoint is tried once more on the next tick, and a second failure ends the room: every player in it goes back to the last checkpoint, and the player whose record failed takes no seat in that game for 10 minutes. A restore that throws after the player’s join keeps that name’s record as stored, and the player leaves. At a join, a restore or a trial read that throws refuses the player’s join. Keepreada plain copy of state into JSON, and test a restore withspawnite save check. - A value that is not JSON. A
readthat returnsundefined, or holds aSet, a symbol, anundefinedfield, a number that is not finite such asNaN, or a value inside itself, is refused as a read that throws is. So is a value the schema refuses. A schema’s own check, such as az.refine, can run twice on a value it refuses, so keep it pure: the same value always gets the same answer. Copy aSetinto an array, and keep numbers finite before they reach the trait the save reads.
spawnite save check plays a scene, reads its save, restores it into a fresh world and compares the two, so it catches a read or a restore that fails before a player does.