Skip to content

Save

@shell/save keeps what a game wants between visits, in the player’s browser. Every Project has it as the save resource: defineProject() installs SavePlugin. The engines export its names.

A script or resource that keeps something registers a slice, and says when it changed:

const save = resources.get('save');
save.register({
key: 'park',
version: 2,
save: () => ({ bricks: park.bricks }),
load: (data) => {
/* check data, put it in place; throw where it is not what was kept */
},
upgrade: { 1: (data) => ({ bricks: data }) },
});
save.changed(); // written 300 ms after the last change, when the page is hidden, and as it goes
MemberWhat it does
register(slice)Adds a slice; its kept data is put in place now, upgraded step by step to its version. Answers a function that removes it
changed()Something kept changed: the save is written delayMs (300) after, once for many changes
saveNow()Writes every slice now; false where it could not be written
clear()Forgets the save: the next game is a new one
resumed, awayWhether the game goes on from a save, and the seconds since it was written
kept, savedAtEach slice the save keeps (key, version, bytes, data), and when it was written
subscribe(listen)Calls listen now and after each read, write and clear; answers a function that stops it

A slice’s data is JSON. Data of an older version goes through upgrade one step at a time; data that load throws on, or of a newer version, starts that slice new; a save that is no save at all starts a new game. A slice not registered now keeps its data in the save.

IndexedDbSaveStore keeps each save in the page’s IndexedDB (database shell-save) and asks the browser once to keep it for good (navigator.storage.persist()). Where IndexedDB will not open, it keeps the save in memory for as long as the page is open. pageSaveStore() is the page’s one.

A tab closed, or another page opened, ends a write to IndexedDB that has begun. So as the page goes (pagehide) what changed is written at once to the page’s localStorage (shell-save:<name>), and the next visit’s read takes it in where it is newer than what IndexedDB kept. Two tabs of one game keep one save: the one that writes last wins.

A host sets the save’s name, store, backup and time away with SavePlugin.config({ name, awaySeconds, store, backup }). The editor’s play keeps a save of its own under another name, so it never reads or writes the published game’s. SavePlugin binds save only where nothing has bound it before, and an edit world keeps its save in memory and reads none.