@margoengine/save 0.1.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -201
- package/NOTICE +4 -4
- package/README.md +656 -513
- package/dist/engine.js +3 -3
- package/dist/materials.d.ts +7 -3
- package/package.json +121 -121
package/README.md
CHANGED
|
@@ -1,513 +1,656 @@
|
|
|
1
|
-
# @margoengine/save
|
|
2
|
-
|
|
3
|
-
Import `margoengine/save` from the `margoengine` package, or `@margoengine/save` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
|
|
4
|
-
|
|
5
|
-
Save games, scene files and prefabs: a versioned JSON document of entities with stable ids, components and
|
|
6
|
-
references; prefab definitions with instances, overrides and nesting; a tested migration registry for schema
|
|
7
|
-
changes; validation that names every problem and its fix; loading into your world that is all or nothing; optional
|
|
8
|
-
gzip; and storage adapters for memory, localStorage, IndexedDB and files behind one promise-based interface with
|
|
9
|
-
AbortSignal.
|
|
10
|
-
|
|
11
|
-
```ts
|
|
12
|
-
import { Migrations, loadGame, memoryStorage, saveGame, type SaveDocument } from 'margoengine/save';
|
|
13
|
-
|
|
14
|
-
const level: SaveDocument = {
|
|
15
|
-
format: 'margo-save',
|
|
16
|
-
version: 2,
|
|
17
|
-
meta: { title: 'Chapter 1', playTime: 754 },
|
|
18
|
-
prefabs: {
|
|
19
|
-
door: {
|
|
20
|
-
entities: [
|
|
21
|
-
{ id: 'frame', components: { mesh: 'door.glb', locked: false } },
|
|
22
|
-
{ id: 'handle', parent: 'frame', components: { opens: { $ref: 'frame' } } },
|
|
23
|
-
],
|
|
24
|
-
},
|
|
25
|
-
},
|
|
26
|
-
entities: [
|
|
27
|
-
{ id: 'player', transform: { position: [0, 0, 0] }, components: { health: { hp: 80, max: 100 }, target: { $ref: 'gate' } } },
|
|
28
|
-
{ id: 'gate', prefab: 'door', transform: { position: [0, 0, -8] }, components: { locked: true } },
|
|
29
|
-
],
|
|
30
|
-
};
|
|
31
|
-
|
|
32
|
-
const storage = memoryStorage(); // or webStorage(), indexedDBStorage(), fileStorage('./saves') from margoengine/save/node
|
|
33
|
-
await saveGame(storage, 'slot-1', level); // validated, gzipped where CompressionStream exists, written in one step
|
|
34
|
-
|
|
35
|
-
const migrations = new Migrations(2).register(1, (old) => ({ ...old, version: 2 }));
|
|
36
|
-
const loaded = await loadGame(storage, 'slot-1', { migrations }); // decoded, migrated, validated; null when empty
|
|
37
|
-
```
|
|
38
|
-
|
|
39
|
-
`indexedDBStorage()` keeps one database connection open while the storage is in use. Call `await storage.close()` (or declare it with `using`) when you are done with saving; it is safe to call twice, and the next call opens the database again.
|
|
40
|
-
|
|
41
|
-
## The document
|
|
42
|
-
|
|
43
|
-
`{format: 'margo-save', version, entities, prefabs?, meta?}`. `version` is your schema version. Each entity has a
|
|
44
|
-
stable `id`, and optionally a `name`, a `parent` (an id), a local `transform` (`position`, unit-quaternion
|
|
45
|
-
`rotation`, `scale`) and `components`: any JSON by component name. A reference to another entity is
|
|
46
|
-
`{"$ref": "id"}` anywhere inside a component; references, parents and prefab overrides all use ids, so a save
|
|
47
|
-
survives reordering and stays diffable.
|
|
48
|
-
|
|
49
|
-
## Prefabs
|
|
50
|
-
|
|
51
|
-
A prefab is a list of entities with ids local to it; its `root` (default the first) becomes the instance. An entity
|
|
52
|
-
with `prefab: 'door'` expands to the prefab's entities: the root merged into the instance (the instance's own
|
|
53
|
-
components, name, transform and parent win), and the others as `gate/handle`, `gate/...`, with their parents and
|
|
54
|
-
local references re-pointed at the copies. `overrides` change the copies by prefab-local id as JSON Merge Patches
|
|
55
|
-
(RFC 7386: objects merge, other values replace, `null` removes a key), and a `parent` or `$ref` inside an override
|
|
56
|
-
names a prefab-local id, like the override's key; `null` for a whole entity removes it and its children. Prefabs may contain instances of other prefabs (ids like `cart/load/lid`), without cycles, up to 32
|
|
57
|
-
deep.
|
|
58
|
-
|
|
59
|
-
```ts
|
|
60
|
-
import { expandSave, parseSave } from 'margoengine/save';
|
|
61
|
-
|
|
62
|
-
const flat = expandSave(parseSave({
|
|
63
|
-
format: 'margo-save',
|
|
64
|
-
version: 1,
|
|
65
|
-
prefabs: { crate: { entities: [{ id: 'box', components: { mass: 2 } }, { id: 'lid', parent: 'box', components: {} }] } },
|
|
66
|
-
entities: [{ id: 'c1', prefab: 'crate', overrides: { lid: { components: { colour: 'red' } } } }],
|
|
67
|
-
}));
|
|
68
|
-
// [{ id: 'c1', components: { mass: 2 }, ... }, { id: 'c1/lid', parent: 'c1', components: { colour: 'red' }, ... }]
|
|
69
|
-
```
|
|
70
|
-
|
|
71
|
-
## Loading into a world, all or nothing
|
|
72
|
-
|
|
73
|
-
```ts
|
|
74
|
-
import { loadWorld, type WorldAdapter } from 'margoengine/save';
|
|
75
|
-
|
|
76
|
-
const scene = new Map<string, { id: string; components: Record<string, unknown> }>();
|
|
77
|
-
const adapter: WorldAdapter<{ id: string; components: Record<string, unknown> }> = {
|
|
78
|
-
create: (entity) => ({ id: entity.id, components: entity.components }), // build off-screen
|
|
79
|
-
commit: (handles) => {
|
|
80
|
-
scene.clear();
|
|
81
|
-
for (const [id, object] of handles) scene.set(id, object); // swap the new world in
|
|
82
|
-
},
|
|
83
|
-
destroy: () => {}, // undo one create
|
|
84
|
-
};
|
|
85
|
-
loadWorld({ format: 'margo-save', version: 1, entities: [{ id: 'a' }, { id: 'b', parent: 'a' }] }, adapter);
|
|
86
|
-
```
|
|
87
|
-
|
|
88
|
-
`loadWorld(document, adapter, {migrations, components, signal})` validates, migrates and expands everything before
|
|
89
|
-
building anything, then calls `create` for every entity (parents first), `link` for every entity once all exist
|
|
90
|
-
(with `resolve(id)` for references) and `commit` once. If any step throws or the signal aborts, it calls `destroy` for
|
|
91
|
-
everything built, latest first, and throws `MargoError` `'failed'` with the cause: a bad file never leaves a
|
|
92
|
-
half-loaded world.
|
|
93
|
-
|
|
94
|
-
For an `@margoengine/ecs` World, `saveEcs(world, components)` writes the entities that hold the named components and
|
|
95
|
-
`ecsAdapter(world, components)` loads them back; a value that does not fit a field (a fraction in an `Int32Array`
|
|
96
|
-
field) undoes the whole load.
|
|
97
|
-
|
|
98
|
-
```ts
|
|
99
|
-
import { World } from 'margoengine/ecs';
|
|
100
|
-
import { ecsAdapter, loadWorld, saveEcs } from 'margoengine/save';
|
|
101
|
-
|
|
102
|
-
const world = new World(1024);
|
|
103
|
-
const position = world.component({ x: Float32Array, y: Float32Array });
|
|
104
|
-
position.add(world.create(), { x: 3, y: 4 });
|
|
105
|
-
const snapshot = saveEcs(world, { position });
|
|
106
|
-
const copy = new World(1024);
|
|
107
|
-
const copyPosition = copy.component({ x: Float32Array, y: Float32Array });
|
|
108
|
-
loadWorld(snapshot, ecsAdapter(copy, { position: copyPosition }));
|
|
109
|
-
```
|
|
110
|
-
|
|
111
|
-
## Saving a running scene
|
|
112
|
-
|
|
113
|
-
`@margoengine/save/engine` needs no mapping. `captureScene(engine)` reads the scene as it stands and gives a save
|
|
114
|
-
document; `restoreScene(engine, document)` puts it back.
|
|
115
|
-
|
|
116
|
-
```ts
|
|
117
|
-
import { Engine, box } from 'margoengine/core';
|
|
118
|
-
import { loadGame, memoryStorage, saveGame } from 'margoengine/save';
|
|
119
|
-
import { captureScene, restoreScene } from 'margoengine/save/engine';
|
|
120
|
-
|
|
121
|
-
const engine = await Engine.create(document.createElement('canvas'));
|
|
122
|
-
const crate = engine.createMesh().setGeometry(box()).setPosition([0, 1, 0]);
|
|
123
|
-
crate.name = 'crate';
|
|
124
|
-
|
|
125
|
-
const storage = memoryStorage();
|
|
126
|
-
await saveGame(storage, 'slot-1', captureScene(engine, { meta: { title: 'Chapter 1' } }));
|
|
127
|
-
|
|
128
|
-
crate.setPosition([5, 0, 0]);
|
|
129
|
-
const { meshes, meta } = await restoreScene(engine, await loadGame(storage, 'slot-1'));
|
|
130
|
-
console.log(meshes.get('crate')?.position.y, meta.title); // 1 'Chapter 1'
|
|
131
|
-
```
|
|
132
|
-
|
|
133
|
-
What it saves:
|
|
134
|
-
|
|
135
|
-
| Part | Saved as |
|
|
136
|
-
| --- | --- |
|
|
137
|
-
| A mesh | Its name, parent, local transform, geometry, material, `visible` and `receiveShadow`. Meshes that share a geometry or a material share one again. |
|
|
138
|
-
| A glTF model | Its URL (`model.asset.baseURL`), the material variant, and only the nodes that differ from the file. A mesh hanging from a node stays on that node. A URL used twice loads once, and the rest are `cloneModel` copies. |
|
|
139
|
-
| The view | The camera, the scene's lighting and its background. `camera: false` leaves the camera alone. |
|
|
140
|
-
| A plugin | Its own `saveState()` and `loadState(state)` when it has them, else its JSON `options` and every property with both a getter and a setter. |
|
|
141
|
-
|
|
142
|
-
A mesh's id is its name, or its name with a number when two share one, and it stays the same across saves (`meshId`).
|
|
143
|
-
|
|
144
|
-
Plugins keep much of their state in public fields, which the default cannot tell from private ones, so name those,
|
|
145
|
-
or write the two functions:
|
|
146
|
-
|
|
147
|
-
```ts
|
|
148
|
-
import { Engine } from 'margoengine/core';
|
|
149
|
-
import { captureScene, restoreScene } from 'margoengine/save/engine';
|
|
150
|
-
|
|
151
|
-
const engine = await Engine.create(document.createElement('canvas'));
|
|
152
|
-
const weather = { name: 'weather', rain: 0.5, setup() {} };
|
|
153
|
-
const score = { name: 'score', points: 12, setup() {} };
|
|
154
|
-
engine.use(weather).use(score);
|
|
155
|
-
|
|
156
|
-
const plugins = {
|
|
157
|
-
weather: { properties: ['rain'] }, // these fields, in place of the default
|
|
158
|
-
score: { save: (p: typeof score) => p.points, load: (p: typeof score, state: unknown) => void (p.points = state as number) },
|
|
159
|
-
debugOverlay: null, // leave this one out
|
|
160
|
-
};
|
|
161
|
-
const saved = captureScene(engine, { plugins, onSkip: (plugin) => console.warn('nothing saved for', plugin.name) });
|
|
162
|
-
weather.rain = 0;
|
|
163
|
-
await restoreScene(engine, saved, { plugins });
|
|
164
|
-
console.log(weather.rain); // 0.5
|
|
165
|
-
```
|
|
166
|
-
|
|
167
|
-
A plugin in the save and not in the scene needs `type` in its binding (`{ type: Sky }`), which attaches it with the
|
|
168
|
-
saved options; without one the save is refused before anything changes. So is a damaged `meta.engine`: a camera the
|
|
169
|
-
engine would refuse each frame (fov outside 0 to 180, near at 0 or below, far not past near, position at the target,
|
|
170
|
-
up along the view), lighting arrays of another length than the scene's, or a background that is not a string or null.
|
|
171
|
-
|
|
172
|
-
With `scene`, factories receive the real engine inside that scene's setup scope, so `use`, `createMesh`, lighting
|
|
173
|
-
and passes belong to the target scene. State callbacks and rollback run in the same scope. A factory that throws
|
|
174
|
-
after attaching plugins has those registrations removed in reverse order. Rollback checks instance identity and
|
|
175
|
-
preserves a later replacement. Factories must dispose their own resources; binding callbacks must undo their own
|
|
176
|
-
effects beyond the saved plugin state.
|
|
177
|
-
|
|
178
|
-
```ts
|
|
179
|
-
import { Engine, type EngineKernel } from 'margoengine/core';
|
|
180
|
-
import { captureScene, restoreScene } from 'margoengine/save/engine';
|
|
181
|
-
|
|
182
|
-
const engine = await Engine.create(document.createElement('canvas'));
|
|
183
|
-
const scene = engine.createScene('restored');
|
|
184
|
-
const type = {
|
|
185
|
-
attach(host: EngineKernel) {
|
|
186
|
-
const plugin = { name: 'score', points: 0, setup() {} };
|
|
187
|
-
host.use(plugin);
|
|
188
|
-
return plugin;
|
|
189
|
-
},
|
|
190
|
-
};
|
|
191
|
-
type.attach(engine).points = 12;
|
|
192
|
-
const plugins = { score: { type, properties: ['points'] } };
|
|
193
|
-
const saved = captureScene(engine, { plugins });
|
|
194
|
-
await restoreScene(engine, saved, { scene, plugins });
|
|
195
|
-
console.log(engine.sceneOf(scene.plugins.get('score')!) === scene); // true
|
|
196
|
-
engine.dispose();
|
|
197
|
-
```
|
|
198
|
-
|
|
199
|
-
`restoreScene` is all or nothing. It checks the whole save, loads the models out of sight and builds every mesh, and
|
|
200
|
-
only then applies plugin state, camera and lighting and removes what the scene held. A model that fails to load, a
|
|
201
|
-
throw from `onEntity` or a plugin, or an abort leaves the running scene as it was, and `signal` stops it. `filter`
|
|
202
|
-
keeps a mesh and all under it out of a capture and out of what a restore removes, such as your UI; `clear: false` adds
|
|
203
|
-
to the scene. `components(mesh)` adds your own data, and `onEntity(mesh, entity, get)` reads it back. Other options:
|
|
204
|
-
`scene`, `version`, `meta`, `migrations`, `modelURL` for a model not loaded from a URL, `load` and `clone`.
|
|
205
|
-
|
|
206
|
-
Geometry is written into the save, so a large static mesh is better as a glTF model, which saves as a URL.
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
`
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
const
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
The
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
`
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
`
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
```ts
|
|
341
|
-
import {
|
|
342
|
-
import {
|
|
343
|
-
|
|
344
|
-
const
|
|
345
|
-
|
|
346
|
-
const
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
await
|
|
351
|
-
|
|
352
|
-
const
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
`
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
await
|
|
417
|
-
console.log(
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
|
425
|
-
|
|
|
426
|
-
|
|
427
|
-
|
|
|
428
|
-
|
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
import {
|
|
444
|
-
import {
|
|
445
|
-
|
|
446
|
-
const
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
```
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
1
|
+
# @margoengine/save
|
|
2
|
+
|
|
3
|
+
Import `margoengine/save` from the `margoengine` package, or `@margoengine/save` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
|
|
4
|
+
|
|
5
|
+
Save games, scene files and prefabs: a versioned JSON document of entities with stable ids, components and
|
|
6
|
+
references; prefab definitions with instances, overrides and nesting; a tested migration registry for schema
|
|
7
|
+
changes; validation that names every problem and its fix; loading into your world that is all or nothing; optional
|
|
8
|
+
gzip; and storage adapters for memory, localStorage, IndexedDB and files behind one promise-based interface with
|
|
9
|
+
AbortSignal.
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { Migrations, loadGame, memoryStorage, saveGame, type SaveDocument } from 'margoengine/save';
|
|
13
|
+
|
|
14
|
+
const level: SaveDocument = {
|
|
15
|
+
format: 'margo-save',
|
|
16
|
+
version: 2,
|
|
17
|
+
meta: { title: 'Chapter 1', playTime: 754 },
|
|
18
|
+
prefabs: {
|
|
19
|
+
door: {
|
|
20
|
+
entities: [
|
|
21
|
+
{ id: 'frame', components: { mesh: 'door.glb', locked: false } },
|
|
22
|
+
{ id: 'handle', parent: 'frame', components: { opens: { $ref: 'frame' } } },
|
|
23
|
+
],
|
|
24
|
+
},
|
|
25
|
+
},
|
|
26
|
+
entities: [
|
|
27
|
+
{ id: 'player', transform: { position: [0, 0, 0] }, components: { health: { hp: 80, max: 100 }, target: { $ref: 'gate' } } },
|
|
28
|
+
{ id: 'gate', prefab: 'door', transform: { position: [0, 0, -8] }, components: { locked: true } },
|
|
29
|
+
],
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const storage = memoryStorage(); // or webStorage(), indexedDBStorage(), fileStorage('./saves') from margoengine/save/node
|
|
33
|
+
await saveGame(storage, 'slot-1', level); // validated, gzipped where CompressionStream exists, written in one step
|
|
34
|
+
|
|
35
|
+
const migrations = new Migrations(2).register(1, (old) => ({ ...old, version: 2 }));
|
|
36
|
+
const loaded = await loadGame(storage, 'slot-1', { migrations }); // decoded, migrated, validated; null when empty
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
`indexedDBStorage()` keeps one database connection open while the storage is in use. Call `await storage.close()` (or declare it with `using`) when you are done with saving; it is safe to call twice, and the next call opens the database again.
|
|
40
|
+
|
|
41
|
+
## The document
|
|
42
|
+
|
|
43
|
+
`{format: 'margo-save', version, entities, prefabs?, meta?}`. `version` is your schema version. Each entity has a
|
|
44
|
+
stable `id`, and optionally a `name`, a `parent` (an id), a local `transform` (`position`, unit-quaternion
|
|
45
|
+
`rotation`, `scale`) and `components`: any JSON by component name. A reference to another entity is
|
|
46
|
+
`{"$ref": "id"}` anywhere inside a component; references, parents and prefab overrides all use ids, so a save
|
|
47
|
+
survives reordering and stays diffable.
|
|
48
|
+
|
|
49
|
+
## Prefabs
|
|
50
|
+
|
|
51
|
+
A prefab is a list of entities with ids local to it; its `root` (default the first) becomes the instance. An entity
|
|
52
|
+
with `prefab: 'door'` expands to the prefab's entities: the root merged into the instance (the instance's own
|
|
53
|
+
components, name, transform and parent win), and the others as `gate/handle`, `gate/...`, with their parents and
|
|
54
|
+
local references re-pointed at the copies. `overrides` change the copies by prefab-local id as JSON Merge Patches
|
|
55
|
+
(RFC 7386: objects merge, other values replace, `null` removes a key), and a `parent` or `$ref` inside an override
|
|
56
|
+
names a prefab-local id, like the override's key; `null` for a whole entity removes it and its children. Prefabs may contain instances of other prefabs (ids like `cart/load/lid`), without cycles, up to 32
|
|
57
|
+
deep.
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
import { expandSave, parseSave } from 'margoengine/save';
|
|
61
|
+
|
|
62
|
+
const flat = expandSave(parseSave({
|
|
63
|
+
format: 'margo-save',
|
|
64
|
+
version: 1,
|
|
65
|
+
prefabs: { crate: { entities: [{ id: 'box', components: { mass: 2 } }, { id: 'lid', parent: 'box', components: {} }] } },
|
|
66
|
+
entities: [{ id: 'c1', prefab: 'crate', overrides: { lid: { components: { colour: 'red' } } } }],
|
|
67
|
+
}));
|
|
68
|
+
// [{ id: 'c1', components: { mass: 2 }, ... }, { id: 'c1/lid', parent: 'c1', components: { colour: 'red' }, ... }]
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Loading into a world, all or nothing
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
import { loadWorld, type WorldAdapter } from 'margoengine/save';
|
|
75
|
+
|
|
76
|
+
const scene = new Map<string, { id: string; components: Record<string, unknown> }>();
|
|
77
|
+
const adapter: WorldAdapter<{ id: string; components: Record<string, unknown> }> = {
|
|
78
|
+
create: (entity) => ({ id: entity.id, components: entity.components }), // build off-screen
|
|
79
|
+
commit: (handles) => {
|
|
80
|
+
scene.clear();
|
|
81
|
+
for (const [id, object] of handles) scene.set(id, object); // swap the new world in
|
|
82
|
+
},
|
|
83
|
+
destroy: () => {}, // undo one create
|
|
84
|
+
};
|
|
85
|
+
loadWorld({ format: 'margo-save', version: 1, entities: [{ id: 'a' }, { id: 'b', parent: 'a' }] }, adapter);
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
`loadWorld(document, adapter, {migrations, components, signal})` validates, migrates and expands everything before
|
|
89
|
+
building anything, then calls `create` for every entity (parents first), `link` for every entity once all exist
|
|
90
|
+
(with `resolve(id)` for references) and `commit` once. If any step throws or the signal aborts, it calls `destroy` for
|
|
91
|
+
everything built, latest first, and throws `MargoError` `'failed'` with the cause: a bad file never leaves a
|
|
92
|
+
half-loaded world.
|
|
93
|
+
|
|
94
|
+
For an `@margoengine/ecs` World, `saveEcs(world, components)` writes the entities that hold the named components and
|
|
95
|
+
`ecsAdapter(world, components)` loads them back; a value that does not fit a field (a fraction in an `Int32Array`
|
|
96
|
+
field) undoes the whole load.
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
import { World } from 'margoengine/ecs';
|
|
100
|
+
import { ecsAdapter, loadWorld, saveEcs } from 'margoengine/save';
|
|
101
|
+
|
|
102
|
+
const world = new World(1024);
|
|
103
|
+
const position = world.component({ x: Float32Array, y: Float32Array });
|
|
104
|
+
position.add(world.create(), { x: 3, y: 4 });
|
|
105
|
+
const snapshot = saveEcs(world, { position });
|
|
106
|
+
const copy = new World(1024);
|
|
107
|
+
const copyPosition = copy.component({ x: Float32Array, y: Float32Array });
|
|
108
|
+
loadWorld(snapshot, ecsAdapter(copy, { position: copyPosition }));
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## Saving a running scene
|
|
112
|
+
|
|
113
|
+
`@margoengine/save/engine` needs no mapping. `captureScene(engine)` reads the scene as it stands and gives a save
|
|
114
|
+
document; `restoreScene(engine, document)` puts it back.
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
import { Engine, box } from 'margoengine/core';
|
|
118
|
+
import { loadGame, memoryStorage, saveGame } from 'margoengine/save';
|
|
119
|
+
import { captureScene, restoreScene } from 'margoengine/save/engine';
|
|
120
|
+
|
|
121
|
+
const engine = await Engine.create(document.createElement('canvas'));
|
|
122
|
+
const crate = engine.createMesh().setGeometry(box()).setPosition([0, 1, 0]);
|
|
123
|
+
crate.name = 'crate';
|
|
124
|
+
|
|
125
|
+
const storage = memoryStorage();
|
|
126
|
+
await saveGame(storage, 'slot-1', captureScene(engine, { meta: { title: 'Chapter 1' } }));
|
|
127
|
+
|
|
128
|
+
crate.setPosition([5, 0, 0]);
|
|
129
|
+
const { meshes, meta } = await restoreScene(engine, await loadGame(storage, 'slot-1'));
|
|
130
|
+
console.log(meshes.get('crate')?.position.y, meta.title); // 1 'Chapter 1'
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
What it saves:
|
|
134
|
+
|
|
135
|
+
| Part | Saved as |
|
|
136
|
+
| --- | --- |
|
|
137
|
+
| A mesh | Its name, parent, local transform, geometry, material, `visible` and `receiveShadow`. Meshes that share a geometry or a material share one again. |
|
|
138
|
+
| A glTF model | Its URL (`model.asset.baseURL`), the material variant, and only the nodes that differ from the file. A mesh hanging from a node stays on that node. A URL used twice loads once, and the rest are `cloneModel` copies. |
|
|
139
|
+
| The view | The camera, the scene's lighting and its background. `camera: false` leaves the camera alone. |
|
|
140
|
+
| A plugin | Its own `saveState()` and `loadState(state)` when it has them, else its JSON `options` and every property with both a getter and a setter. |
|
|
141
|
+
|
|
142
|
+
A mesh's id is its name, or its name with a number when two share one, and it stays the same across saves (`meshId`).
|
|
143
|
+
|
|
144
|
+
Plugins keep much of their state in public fields, which the default cannot tell from private ones, so name those,
|
|
145
|
+
or write the two functions:
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
import { Engine } from 'margoengine/core';
|
|
149
|
+
import { captureScene, restoreScene } from 'margoengine/save/engine';
|
|
150
|
+
|
|
151
|
+
const engine = await Engine.create(document.createElement('canvas'));
|
|
152
|
+
const weather = { name: 'weather', rain: 0.5, setup() {} };
|
|
153
|
+
const score = { name: 'score', points: 12, setup() {} };
|
|
154
|
+
engine.use(weather).use(score);
|
|
155
|
+
|
|
156
|
+
const plugins = {
|
|
157
|
+
weather: { properties: ['rain'] }, // these fields, in place of the default
|
|
158
|
+
score: { save: (p: typeof score) => p.points, load: (p: typeof score, state: unknown) => void (p.points = state as number) },
|
|
159
|
+
debugOverlay: null, // leave this one out
|
|
160
|
+
};
|
|
161
|
+
const saved = captureScene(engine, { plugins, onSkip: (plugin) => console.warn('nothing saved for', plugin.name) });
|
|
162
|
+
weather.rain = 0;
|
|
163
|
+
await restoreScene(engine, saved, { plugins });
|
|
164
|
+
console.log(weather.rain); // 0.5
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
A plugin in the save and not in the scene needs `type` in its binding (`{ type: Sky }`), which attaches it with the
|
|
168
|
+
saved options; without one the save is refused before anything changes. So is a damaged `meta.engine`: a camera the
|
|
169
|
+
engine would refuse each frame (fov outside 0 to 180, near at 0 or below, far not past near, position at the target,
|
|
170
|
+
up along the view), lighting arrays of another length than the scene's, or a background that is not a string or null.
|
|
171
|
+
|
|
172
|
+
With `scene`, factories receive the real engine inside that scene's setup scope, so `use`, `createMesh`, lighting
|
|
173
|
+
and passes belong to the target scene. State callbacks and rollback run in the same scope. A factory that throws
|
|
174
|
+
after attaching plugins has those registrations removed in reverse order. Rollback checks instance identity and
|
|
175
|
+
preserves a later replacement. Factories must dispose their own resources; binding callbacks must undo their own
|
|
176
|
+
effects beyond the saved plugin state.
|
|
177
|
+
|
|
178
|
+
```ts
|
|
179
|
+
import { Engine, type EngineKernel } from 'margoengine/core';
|
|
180
|
+
import { captureScene, restoreScene } from 'margoengine/save/engine';
|
|
181
|
+
|
|
182
|
+
const engine = await Engine.create(document.createElement('canvas'));
|
|
183
|
+
const scene = engine.createScene('restored');
|
|
184
|
+
const type = {
|
|
185
|
+
attach(host: EngineKernel) {
|
|
186
|
+
const plugin = { name: 'score', points: 0, setup() {} };
|
|
187
|
+
host.use(plugin);
|
|
188
|
+
return plugin;
|
|
189
|
+
},
|
|
190
|
+
};
|
|
191
|
+
type.attach(engine).points = 12;
|
|
192
|
+
const plugins = { score: { type, properties: ['points'] } };
|
|
193
|
+
const saved = captureScene(engine, { plugins });
|
|
194
|
+
await restoreScene(engine, saved, { scene, plugins });
|
|
195
|
+
console.log(engine.sceneOf(scene.plugins.get('score')!) === scene); // true
|
|
196
|
+
engine.dispose();
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
`restoreScene` is all or nothing. It checks the whole save, loads the models out of sight and builds every mesh, and
|
|
200
|
+
only then applies plugin state, camera and lighting and removes what the scene held. A model that fails to load, a
|
|
201
|
+
throw from `onEntity` or a plugin, or an abort leaves the running scene as it was, and `signal` stops it. `filter`
|
|
202
|
+
keeps a mesh and all under it out of a capture and out of what a restore removes, such as your UI; `clear: false` adds
|
|
203
|
+
to the scene. `components(mesh)` adds your own data, and `onEntity(mesh, entity, get)` reads it back. Other options:
|
|
204
|
+
`scene`, `version`, `meta`, `migrations`, `modelURL` for a model not loaded from a URL, `load` and `clone`.
|
|
205
|
+
|
|
206
|
+
Geometry is written into the save, so a large static mesh is better as a glTF model, which saves as a URL.
|
|
207
|
+
|
|
208
|
+
### Animation, lights and shadows (`@margoengine/save/scene-state`)
|
|
209
|
+
|
|
210
|
+
`captureScene` saves meshes, models, the view and plugins. `captureSceneState(bindings)` adds what plays on top of
|
|
211
|
+
them: animation players, light lists and shadow settings, each under a stable id you choose. It writes plain JSON and
|
|
212
|
+
no GPU objects; `restoreSceneState(state, bindings)` puts the values back onto objects you have already loaded and
|
|
213
|
+
bound under the same ids.
|
|
214
|
+
|
|
215
|
+
| Binding | What fits | Saved |
|
|
216
|
+
| --- | --- | --- |
|
|
217
|
+
| `animations` | anything with `captureState()` and `restoreState(state)`: `Animation`, `AnimationMixer` (`@margoengine/animation`), `AnimatorGraph` (`@margoengine/animator`) | the player's own state: clip times, blend parameters, weights, masks, fades and triggers |
|
|
218
|
+
| `lights` | anything with `list` and `setLights(list)`: `Clustered`, `DirectionalLights`, `AreaLights` and the other `@margoengine/clustered` light sets | every light in `list`, with its per-light shadow settings |
|
|
219
|
+
| `shadows` | a mutable settings object, such as `Shadows.options` (`@margoengine/shadows`) | its own properties |
|
|
220
|
+
|
|
221
|
+
```ts
|
|
222
|
+
import { captureSceneState, restoreSceneState } from 'margoengine/save/scene-state';
|
|
223
|
+
|
|
224
|
+
// Stand-ins with the same shape as an Animation, a Clustered light set and Shadows.options.
|
|
225
|
+
let walk = { clip: 'walk', time: 1.25, weight: 1 };
|
|
226
|
+
const hero = { captureState: () => ({ ...walk }), restoreState: (s: typeof walk) => void (walk = { ...s }) };
|
|
227
|
+
let list = [{ type: 'point', position: [0, 2, 0], intensity: 40, castShadow: true }];
|
|
228
|
+
const lamps = { get list() { return list; }, setLights: (l: typeof list) => void (list = l.map((x) => ({ ...x }))) };
|
|
229
|
+
const sun: Record<string, number> = { mapSize: 2048, cascades: 3, bias: 0.0005 };
|
|
230
|
+
const bindings = { animations: { hero }, lights: { lamps }, shadows: { sun } };
|
|
231
|
+
|
|
232
|
+
const state = captureSceneState(bindings);
|
|
233
|
+
const text = JSON.stringify(state); // { version: 1, animations: { hero: ... }, lights: { lamps: [...] }, shadows: { sun: ... } }
|
|
234
|
+
|
|
235
|
+
walk.time = 9;
|
|
236
|
+
list = [];
|
|
237
|
+
sun.mapSize = 512;
|
|
238
|
+
sun.extra = 1;
|
|
239
|
+
restoreSceneState(JSON.parse(text), bindings);
|
|
240
|
+
console.log(walk.time, list.length, sun.mapSize, 'extra' in sun); // 1.25 1 2048 false
|
|
241
|
+
|
|
242
|
+
// All or nothing: a binding that throws undoes the ones applied before it.
|
|
243
|
+
let failOnce = true;
|
|
244
|
+
const flaky = { list: [], setLights: () => { if (failOnce) { failOnce = false; throw new Error('lost'); } } };
|
|
245
|
+
walk.time = 3;
|
|
246
|
+
try {
|
|
247
|
+
restoreSceneState(state, { ...bindings, lights: { lamps: flaky } });
|
|
248
|
+
} catch (e) {
|
|
249
|
+
console.log((e as Error).message, walk.time); // 'lost' 3: the animation was put back
|
|
250
|
+
}
|
|
251
|
+
try {
|
|
252
|
+
restoreSceneState(state, { lights: { lamps }, shadows: { sun } });
|
|
253
|
+
} catch (e) {
|
|
254
|
+
console.log((e as Error).message); // "Missing animations binding 'hero'; load and bind that object before restoring"
|
|
255
|
+
}
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
- Every id in the state needs its binding (an own property of `bindings.animations`, `lights` or `shadows`), or the
|
|
259
|
+
restore throws a `MargoError` with code `'state'` before anything changes. Bindings the state does not name are left
|
|
260
|
+
alone, so a newer scene can bind more than an older save holds.
|
|
261
|
+
- Values must be JSON: finite numbers, strings, booleans, `null`, arrays, typed arrays (saved as arrays) and plain
|
|
262
|
+
objects. A function, `Map`, class instance, `NaN`, infinity or a cycle throws on capture, so a callback or GPU
|
|
263
|
+
resource never lands in a save; bind its portable settings instead. Keys such as `__proto__` and `constructor`
|
|
264
|
+
round-trip as ordinary keys and never change an object's prototype.
|
|
265
|
+
- A shadow restore replaces the settings object's own properties: keys the save does not hold are removed, and the
|
|
266
|
+
object keeps its identity and prototype. A light restore calls `setLights` with the saved list.
|
|
267
|
+
- Restore applies every animation, then every light set, then every shadow setting, each in the order of the state. If one throws, those
|
|
268
|
+
already applied are put back to what they held before the call, last first, and the error is rethrown; if putting
|
|
269
|
+
one back throws too, you get an `AggregateError` with every failure. A state whose `version` is not 1 throws.
|
|
270
|
+
|
|
271
|
+
### Materials (`@margoengine/save/materials`)
|
|
272
|
+
|
|
273
|
+
`captureMaterials(materials, options)` saves named materials as a `MaterialLibrary`: each material's kind, every factor,
|
|
274
|
+
its maps with their samplers and per-slot UV sets, render state and shader parameters. A texture or other object used
|
|
275
|
+
by several materials is saved once and shared again on restore. `restoreMaterials(library, options)` builds new
|
|
276
|
+
materials and textures; put them on the loaded scene's meshes.
|
|
277
|
+
|
|
278
|
+
```ts
|
|
279
|
+
import { PbrMaterial, Texture } from 'margoengine/materials';
|
|
280
|
+
import { captureMaterials, restoreMaterials } from 'margoengine/save/materials';
|
|
281
|
+
|
|
282
|
+
const pixels = new Texture({ width: 2, height: 2, data: new Uint8Array(16).fill(200) });
|
|
283
|
+
const red = new PbrMaterial({ color: [1, 0, 0, 1], roughness: 0.4, map: pixels });
|
|
284
|
+
const blue = new PbrMaterial({ color: [0, 0, 1, 1], map: pixels });
|
|
285
|
+
|
|
286
|
+
const library = await captureMaterials({ red, blue });
|
|
287
|
+
const text = JSON.stringify(library); // plain JSON: { version: 1, materials: { red, blue }, objects: [...] }
|
|
288
|
+
|
|
289
|
+
const restored = await restoreMaterials(JSON.parse(text), { expect: { red: PbrMaterial, blue: PbrMaterial } });
|
|
290
|
+
const { red: red2, blue: blue2 } = restored; // both typed PbrMaterial, no cast
|
|
291
|
+
console.log(red2 instanceof PbrMaterial, red2.roughness); // true 0.4
|
|
292
|
+
console.log(red2.map === blue2.map); // true: still one texture
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
- `expect` names the class each material must be. The result is typed by it, and the restore checks it: a name that is
|
|
296
|
+
missing or of another class throws a `MargoError` with code `'state'` and disposes everything the restore made.
|
|
297
|
+
Without `expect` the result is `Record<string, object>`, one entry per saved name.
|
|
298
|
+
|
|
299
|
+
- Texture pixels are embedded by default. `textureURL(texture)` returns a URL (or a list of six for a cube) to save
|
|
300
|
+
in their place; restore downloads it with `fetch` (default the global one) within `limits`, the download and decode
|
|
301
|
+
caps, which only the restore's caller sets, never the file.
|
|
302
|
+
- A value of a type no codec knows, such as a callback or your own resource, throws a `MargoError` with code `'state'`.
|
|
303
|
+
`externalKey(value)` names it instead, and on restore `resolveExternal(key, { signal })` hands back your object.
|
|
304
|
+
- `codecs` adds your own `MaterialValueCodec`s (`type`, `test`, `capture`, `restore`). Shader materials
|
|
305
|
+
(`@margoengine/shader`) load their codecs only when the library holds one, so a save without them never downloads
|
|
306
|
+
the shader package; `loadCodecs` replaces that loader.
|
|
307
|
+
- `signal` stops a capture or restore. A restore that fails or is aborted disposes every material and texture it had
|
|
308
|
+
made.
|
|
309
|
+
|
|
310
|
+
## Change recorder (`@margoengine/save/delta`)
|
|
311
|
+
|
|
312
|
+
`diffSave(base, edited)` is what a user changed in a loaded scene, as a small JSON delta; `applyDelta(base, delta)` puts it back on the base. Changed entities are JSON Merge Patches (RFC 7386, as prefab overrides already are), added entities are whole, removed ones are ids, and `meta` is patched too. Keep the delta instead of the whole document: it stays valid while the shipped base changes elsewhere, and it is a few lines of JSON.
|
|
313
|
+
|
|
314
|
+
```ts
|
|
315
|
+
import {diffSave, applyDelta, SaveRecorder} from 'margoengine/save/delta';
|
|
316
|
+
|
|
317
|
+
const door = {id: 'door', transform: {position: [1, 0, 0] as const}, components: {hinge: {angle: 0}}};
|
|
318
|
+
const base = {format: 'margo-save' as const, version: 1, entities: [door, {id: 'crate'}]};
|
|
319
|
+
// The player opened the door and smashed the crate.
|
|
320
|
+
const edited = {...base, entities: [{...door, components: {hinge: {angle: 90}}}]};
|
|
321
|
+
|
|
322
|
+
const delta = diffSave(base, edited);
|
|
323
|
+
console.log(JSON.stringify(delta.changed), delta.removed); // {"door":{"components":{"hinge":{"angle":90}}}} ["crate"]
|
|
324
|
+
console.log(applyDelta(base, JSON.parse(JSON.stringify(delta))).entities.length); // 1
|
|
325
|
+
|
|
326
|
+
const recorder = new SaveRecorder(base); // measures from its base; commit(current) moves the base forward
|
|
327
|
+
console.log(recorder.changes(edited).removed);
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
- `diffSave(base, edited)`: entities are matched by id; reordering the list is not recorded. A merge patch cannot store `null` (it means remove), so a changed value holding `null` throws a `TypeError` naming its path. Duplicate ids throw.
|
|
331
|
+
- `applyDelta(base, delta, {validate = true, components, strictComponents})`: pure; throws a `TypeError` when the delta removes or changes an id the base lacks, adds one it has, was made for another `version`, or (with `validate`) leaves an invalid document, which `parseSave` names.
|
|
332
|
+
- `SaveRecorder(base)`: `changes(current)`, `commit(current)`, `apply(delta)` and `base`. `isEmptyDelta(delta)` tells a no-op.
|
|
333
|
+
- A delta is made from the document shape (`captureScene(engine)` of `@margoengine/save/engine` makes it), not by watching the running scene: take the current document with the engine's save functions, then diff it.
|
|
334
|
+
|
|
335
|
+
## Save slots
|
|
336
|
+
|
|
337
|
+
`@margoengine/save/slots` puts a load screen over any storage. A slot holds a save, a small record of what it is and a
|
|
338
|
+
thumbnail, and `list()` reads the records alone, so a load screen opens without reading one save.
|
|
339
|
+
|
|
340
|
+
```ts
|
|
341
|
+
import { memoryStorage, type SaveDocument } from 'margoengine/save';
|
|
342
|
+
import { SaveSlots } from 'margoengine/save/slots';
|
|
343
|
+
|
|
344
|
+
const game = (title: string): SaveDocument => ({ format: 'margo-save', version: 1, meta: { title }, entities: [] });
|
|
345
|
+
|
|
346
|
+
const slots = new SaveSlots(memoryStorage()); // or indexedDBStorage(), fileStorage('./saves')
|
|
347
|
+
await slots.save('slot-1', game('Chapter 2'), { playTime: 754, meta: { level: 3 } });
|
|
348
|
+
for (let i = 0; i < 5; i++) await slots.autosave(game(`Autosave ${i}`)); // a ring of 3, oldest first
|
|
349
|
+
|
|
350
|
+
for (const slot of await slots.list()) console.log(slot.id, slot.title, new Date(slot.savedAt), slot.meta);
|
|
351
|
+
|
|
352
|
+
const newest = await slots.latest(); // what a Continue button loads, autosaves included
|
|
353
|
+
const loaded = newest && (await slots.load(newest.id)); // as loadGame: pass migrations here
|
|
354
|
+
console.log(loaded?.meta?.title); // Autosave 4
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
For a thumbnail, take the canvas right after a frame, in the same task: a WebGPU canvas keeps its picture only until the
|
|
358
|
+
frame is shown. `slots.thumbnail(id)` gives it back as a Blob.
|
|
359
|
+
|
|
360
|
+
```ts
|
|
361
|
+
import { Engine, box } from 'margoengine/core';
|
|
362
|
+
import { memoryStorage } from 'margoengine/save';
|
|
363
|
+
import { captureScene } from 'margoengine/save/engine';
|
|
364
|
+
import { SaveSlots, captureThumbnail } from 'margoengine/save/slots';
|
|
365
|
+
|
|
366
|
+
const engine = await Engine.create(document.createElement('canvas'));
|
|
367
|
+
engine.createMesh().setGeometry(box());
|
|
368
|
+
const slots = new SaveSlots(memoryStorage());
|
|
369
|
+
|
|
370
|
+
engine.render();
|
|
371
|
+
const thumbnail = await captureThumbnail(engine.canvas, { width: 320 }); // WebP where the browser has it, else PNG
|
|
372
|
+
await slots.save('slot-1', captureScene(engine, { meta: { title: 'Chapter 2' } }), { thumbnail });
|
|
373
|
+
|
|
374
|
+
const picture = await slots.thumbnail('slot-1');
|
|
375
|
+
if (picture) document.body.append(Object.assign(new Image(), { src: URL.createObjectURL(picture) }));
|
|
376
|
+
```
|
|
377
|
+
|
|
378
|
+
`autosaveEvery(milliseconds, capture, { onError })` runs the ring on a timer: `capture` returns the document, or null
|
|
379
|
+
to skip a turn in a menu or a cutscene, and the result has `stop()` and works with `using`. An autosave never touches a
|
|
380
|
+
player's slot, and `auto-` ids are refused in `save` and as the target of `copy`.
|
|
381
|
+
|
|
382
|
+
| Option | Default | What it does |
|
|
383
|
+
| --- | --- | --- |
|
|
384
|
+
| `namespace` | `'slot'` | Keeps profiles apart in one storage. |
|
|
385
|
+
| `autosaves` | `3` | How many autosaves take turns. |
|
|
386
|
+
| `now` | `Date.now` | The clock for `savedAt`. |
|
|
387
|
+
| `compress`, `validate` | as `saveGame` | Passed to each save. |
|
|
388
|
+
|
|
389
|
+
Also `info(id)`, `copy(from, to)` and `delete(id)`. Writes run one at a time, in call order, and every call takes
|
|
390
|
+
`signal`.
|
|
391
|
+
|
|
392
|
+
A slot's files carry a generation in their keys, and writing its record is the one step that switches to them. A failed
|
|
393
|
+
write or a crash before that leaves the old slot whole, with some unused files that the next save clears. A record that
|
|
394
|
+
cannot be read shows in `list()` with `damaged: true`, and `save` or `delete` replaces it.
|
|
395
|
+
|
|
396
|
+
## Safe writes
|
|
397
|
+
|
|
398
|
+
`safeStorage` from `@margoengine/save/safe` wraps any storage so a failed or torn write never loses the last good save,
|
|
399
|
+
and damage is found on read. Each key keeps two copies, `key~a` and `key~b`, each with a generation and a CRC-32. A write
|
|
400
|
+
only ever goes over the copy that is not the newest good one, and is read back to check it. A read gives the newest good
|
|
401
|
+
copy. Generations are 64-bit: a write at the last one, 2^64 - 1, rejects with MargoError `'failed'` before any copy
|
|
402
|
+
changes, and `check` rejects a generation above 2^53 - 1 that a number cannot hold exactly (`read` still loads it).
|
|
403
|
+
|
|
404
|
+
```ts
|
|
405
|
+
import { loadGame, memoryStorage, saveGame, type SaveDocument } from 'margoengine/save';
|
|
406
|
+
import { safeStorage } from 'margoengine/save/safe';
|
|
407
|
+
|
|
408
|
+
const disk = memoryStorage(); // or indexedDBStorage(), fileStorage('./saves')
|
|
409
|
+
const storage = safeStorage(disk, { onRecover: ({ key, reason }) => console.warn(key, 'fell back:', reason) });
|
|
410
|
+
const game = (title: string): SaveDocument => ({ format: 'margo-save', version: 1, meta: { title }, entities: [] });
|
|
411
|
+
|
|
412
|
+
await saveGame(storage, 'slot-1', game('older'));
|
|
413
|
+
await saveGame(storage, 'slot-1', game('newer'));
|
|
414
|
+
|
|
415
|
+
await disk.write('slot-1~b', new Uint8Array(10)); // what a torn write leaves
|
|
416
|
+
const save = await loadGame(storage, 'slot-1');
|
|
417
|
+
console.log(save?.meta?.title); // older
|
|
418
|
+
console.log(await storage.check('slot-1')); // { ok: true, good: 1, bad: 1, generation: 1 }
|
|
419
|
+
```
|
|
420
|
+
|
|
421
|
+
The result is a storage like any other, so `SaveSlots` runs over it. With both copies bad a read rejects with `MargoError`
|
|
422
|
+
`'failed'`; `check(key)` reports without changing anything, and the next write goes over the bad copy.
|
|
423
|
+
|
|
424
|
+
| Option | Default | What it does |
|
|
425
|
+
| --- | --- | --- |
|
|
426
|
+
| `verify` | `true` | Reads each write back and compares it; a mismatch rejects, and the last good save stands. |
|
|
427
|
+
| `legacy` | `false` | Reads a save from before this wrapper, stored plainly under `key`, unchecked. The next write moves it over. Off, such a save is refused. |
|
|
428
|
+
| `onRecover` | none | Called with `{key, copy, reason}` when a read passes over a bad copy. |
|
|
429
|
+
|
|
430
|
+
A write costs two reads, a write and a read back, and a key takes twice the room. The CRC finds accidents; it is no
|
|
431
|
+
signature, and someone editing a save can make a matching one.
|
|
432
|
+
|
|
433
|
+
## Signed saves
|
|
434
|
+
|
|
435
|
+
`signedStorage` from `@margoengine/save/signed` is `safeStorage` with an HMAC-SHA-256 tag on every copy, so an edited save
|
|
436
|
+
is refused instead of read. The tag covers the copy, its physical key and its generation. Pass a secret key of at least 32 random
|
|
437
|
+
bytes, or an HMAC-SHA-256 `CryptoKey` of 256 bits or more with `sign` and `verify` usages; the key is never saved. A forged or torn
|
|
438
|
+
newest copy goes to `onRecover` and the older signed copy is read. With no signed copy left a read rejects with `MargoError`
|
|
439
|
+
`'failed'`. WebCrypto is `crypto.subtle` unless you pass `options.subtle`; without it the call throws `'unsupported'`. Unsigned
|
|
440
|
+
legacy data is never accepted.
|
|
441
|
+
|
|
442
|
+
```ts
|
|
443
|
+
import { loadGame, memoryStorage, saveGame, type SaveDocument } from 'margoengine/save';
|
|
444
|
+
import { signedStorage } from 'margoengine/save/signed';
|
|
445
|
+
|
|
446
|
+
const disk = memoryStorage();
|
|
447
|
+
const key = crypto.getRandomValues(new Uint8Array(32)); // keep this secret outside the save, and the same between runs
|
|
448
|
+
const storage = signedStorage(disk, key, { onRecover: ({ key, reason }) => console.warn(key, 'fell back:', reason) });
|
|
449
|
+
const game = (title: string): SaveDocument => ({ format: 'margo-save', version: 1, meta: { title }, entities: [] });
|
|
450
|
+
|
|
451
|
+
await saveGame(storage, 'slot-1', game('older'));
|
|
452
|
+
await saveGame(storage, 'slot-1', game('newer'));
|
|
453
|
+
|
|
454
|
+
const copy = (await disk.read('slot-1~a')) ?? (await disk.read('slot-1~b'));
|
|
455
|
+
console.log(copy !== null); // true: the signed frame is on disk
|
|
456
|
+
await disk.write('slot-1~b', new Uint8Array(40)); // someone's edit, with no valid tag
|
|
457
|
+
const save = await loadGame(storage, 'slot-1');
|
|
458
|
+
console.log(save?.meta?.title); // older: the edited copy fails its tag
|
|
459
|
+
```
|
|
460
|
+
|
|
461
|
+
A non-extractable `CryptoKey` keeps the secret out of reach of page script, and `check` reports on both copies without
|
|
462
|
+
changing anything. A wrong key reads every copy as bad, the same as an edit; a key that is too short throws a `TypeError`
|
|
463
|
+
at once. A raw key is copied when the storage is made, so changing your array later does not change it.
|
|
464
|
+
|
|
465
|
+
```ts
|
|
466
|
+
import { loadGame, memoryStorage, saveGame } from 'margoengine/save';
|
|
467
|
+
import { signedStorage } from 'margoengine/save/signed';
|
|
468
|
+
|
|
469
|
+
const hmac = await crypto.subtle.generateKey({ name: 'HMAC', hash: 'SHA-256', length: 256 }, false, ['sign', 'verify']);
|
|
470
|
+
const disk = memoryStorage();
|
|
471
|
+
const keyed = signedStorage(disk, hmac);
|
|
472
|
+
await saveGame(keyed, 'slot-1', { format: 'margo-save', version: 1, entities: [] });
|
|
473
|
+
console.log(await keyed.check('slot-1')); // { ok: true, good: 1, bad: 0, generation: 1 }
|
|
474
|
+
|
|
475
|
+
const wrongKey = signedStorage(disk, crypto.getRandomValues(new Uint8Array(32)));
|
|
476
|
+
console.log(await wrongKey.check('slot-1')); // { ok: false, good: 0, bad: 2, generation: 0 }
|
|
477
|
+
await loadGame(wrongKey, 'slot-1').catch((error) => console.log(error.code)); // failed
|
|
478
|
+
```
|
|
479
|
+
|
|
480
|
+
Signing proves a save was written with your key; it does not encrypt it, and it cannot tell a copy from an older one
|
|
481
|
+
written under the same key and slot (a player can put back an old signed file). Anyone with the key in the page can sign.
|
|
482
|
+
|
|
483
|
+
## Browser file storage
|
|
484
|
+
|
|
485
|
+
`opfsStorage` from `@margoengine/save/opfs` keeps each save as one file in the origin private file system, with no size
|
|
486
|
+
limit of Web Storage and no database to open. A write goes to a temporary stream whose close swaps it into place, so a
|
|
487
|
+
failed or aborted write keeps the previous file. Operations on one key run in call order for one adapter; two tabs or
|
|
488
|
+
adapters on one key are last-close-wins. An abort is checked after each step and before the close, the point of no
|
|
489
|
+
return. Pass `namespace` to pick the directory (default `'margo-saves'`) or `directory` to give a handle you opened, as a
|
|
490
|
+
worker does. A browser without OPFS throws `MargoError` `'unsupported'`; a file with a damaged frame throws `'failed'`;
|
|
491
|
+
a key over 175 UTF-8 bytes is a `RangeError`.
|
|
492
|
+
|
|
493
|
+
```ts
|
|
494
|
+
import { loadGame, saveGame, type SaveDocument } from 'margoengine/save';
|
|
495
|
+
import { opfsStorage } from 'margoengine/save/opfs';
|
|
496
|
+
|
|
497
|
+
const storage = opfsStorage({ namespace: 'readme-saves' });
|
|
498
|
+
const game: SaveDocument = { format: 'margo-save', version: 1, meta: { title: 'OPFS' }, entities: [] };
|
|
499
|
+
await saveGame(storage, 'slot-1', game);
|
|
500
|
+
console.log((await loadGame(storage, 'slot-1'))?.meta?.title); // OPFS
|
|
501
|
+
console.log(await storage.keys()); // ['slot-1']
|
|
502
|
+
await storage.delete('slot-1');
|
|
503
|
+
```
|
|
504
|
+
|
|
505
|
+
Wrap it in `safeStorage` or `signedStorage` for two copies and tamper checks.
|
|
506
|
+
|
|
507
|
+
The adapter stores any bytes, not only save documents, and an empty save is a real save: each file is the bytes after a
|
|
508
|
+
5-byte header, so a committed empty write reads back as an empty `Uint8Array`, while a file left empty by a first write
|
|
509
|
+
that never closed (a tab closed mid-write) reads as `null` and is not in `keys()`. Keys may be any well-formed Unicode up
|
|
510
|
+
to 175 UTF-8 bytes; each is stored under a base64url file name, so `keys()` returns them as written, sorted.
|
|
511
|
+
|
|
512
|
+
```ts
|
|
513
|
+
import { opfsStorage } from 'margoengine/save/opfs';
|
|
514
|
+
|
|
515
|
+
const files = opfsStorage({ namespace: 'readme-binary' });
|
|
516
|
+
await files.write('thumbnail', new Uint8Array([137, 80, 78, 71]));
|
|
517
|
+
await files.write('empty', new Uint8Array(0));
|
|
518
|
+
console.log(await files.read('thumbnail'), (await files.read('empty'))?.length, await files.read('missing'));
|
|
519
|
+
// Uint8Array(4) [137, 80, 78, 71] 0 null
|
|
520
|
+
|
|
521
|
+
const late = new AbortController();
|
|
522
|
+
late.abort(new Error('player quit'));
|
|
523
|
+
await files.write('thumbnail', new Uint8Array([0]), { signal: late.signal }).catch((error) => console.log(error.message));
|
|
524
|
+
// player quit: aborted before the close, so the old file stays
|
|
525
|
+
console.log((await files.read('thumbnail'))?.length, await files.keys()); // 4 ['empty', 'thumbnail']
|
|
526
|
+
for (const key of await files.keys()) await files.delete(key);
|
|
527
|
+
```
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
## Cloud saves
|
|
531
|
+
|
|
532
|
+
`remoteStorage` from `@margoengine/save/remote` keeps saves on an HTTP server: GET, PUT and DELETE on
|
|
533
|
+
`${url}/${encodeURIComponent(key)}`, and GET on `url` for a JSON array of keys. A read remembers the key's ETag and a
|
|
534
|
+
write sends it as `If-Match`, so the server finds a save another device made in between, and `conflict` says what happens
|
|
535
|
+
then. `remoteHandler` is the other half: a server over any storage, as a function from a `Request` to a `Response`.
|
|
536
|
+
|
|
537
|
+
```ts
|
|
538
|
+
import { memoryStorage } from 'margoengine/save';
|
|
539
|
+
import { remoteHandler, remoteStorage } from 'margoengine/save/remote';
|
|
540
|
+
|
|
541
|
+
const server = remoteHandler(memoryStorage(), { base: '/saves' });
|
|
542
|
+
const fetch = async (input: RequestInfo | URL, init?: RequestInit) => server(new Request(input, init)); // or the network
|
|
543
|
+
const url = 'https://game.example/saves';
|
|
544
|
+
const bytes = (text: string) => new TextEncoder().encode(text);
|
|
545
|
+
|
|
546
|
+
const phone = remoteStorage({ url, fetch });
|
|
547
|
+
const laptop = remoteStorage({ url, fetch });
|
|
548
|
+
await phone.write('slot-1', bytes('level 1'));
|
|
549
|
+
await laptop.read('slot-1');
|
|
550
|
+
await phone.write('slot-1', bytes('level 2'));
|
|
551
|
+
|
|
552
|
+
await laptop.write('slot-1', bytes('level 1, with a side quest')).catch((error) => console.log(error.code)); // 'state'
|
|
553
|
+
|
|
554
|
+
const merging = remoteStorage({
|
|
555
|
+
url,
|
|
556
|
+
fetch,
|
|
557
|
+
conflict: ({ local, remote }) => (remote && remote.length > (local?.length ?? 0) ? remote : local), // keeps the longer
|
|
558
|
+
});
|
|
559
|
+
await merging.write('slot-1', bytes('level 2 and more'));
|
|
560
|
+
console.log(new TextDecoder().decode((await phone.read('slot-1'))!)); // level 2 and more
|
|
561
|
+
```
|
|
562
|
+
|
|
563
|
+
| `conflict` | When the server's save is not the one this client last saw |
|
|
564
|
+
| --- | --- |
|
|
565
|
+
| `'error'` (default) | The write rejects with `MargoError` `'state'` and nothing changes. Read the key, then save again. |
|
|
566
|
+
| `'local'` | This write goes over it. |
|
|
567
|
+
| `'remote'` | The server's stays, and this write is dropped. |
|
|
568
|
+
| a function | Gets `{key, local, remote}` and returns the bytes to keep, or null for none. `local` is null for a delete and `remote` for a save deleted elsewhere. |
|
|
569
|
+
|
|
570
|
+
| Option | Default | What it does |
|
|
571
|
+
| --- | --- | --- |
|
|
572
|
+
| `url` | none | The folder of saves. |
|
|
573
|
+
| `fetch` | `globalThis.fetch` | How requests go out. |
|
|
574
|
+
| `headers` | none | Sent with each request. A function runs for each attempt, for a token that expires. |
|
|
575
|
+
| `timeout` | `30000` | Milliseconds for one attempt. |
|
|
576
|
+
| `retries` | `3` | Further attempts after a network failure, a timeout, a 408, a 429 or a 5xx, waiting as `Retry-After` says, up to a minute; longer, the call fails. |
|
|
577
|
+
|
|
578
|
+
A write that lost its answer and tried again gets a 412 from its own earlier write; the bytes on the server are then the
|
|
579
|
+
same, and it counts as done. A device that has never read a key cannot write over it: read first on a new device.
|
|
580
|
+
|
|
581
|
+
On Node, the handler needs a few lines around it:
|
|
582
|
+
|
|
583
|
+
```ts
|
|
584
|
+
import { createServer } from 'node:http';
|
|
585
|
+
import { Readable } from 'node:stream';
|
|
586
|
+
import { fileStorage } from 'margoengine/save/node';
|
|
587
|
+
import { remoteHandler, remoteStorage } from 'margoengine/save/remote';
|
|
588
|
+
|
|
589
|
+
const handle = remoteHandler(fileStorage('./cloud-saves'), {
|
|
590
|
+
base: '/saves',
|
|
591
|
+
origin: 'https://game.example', // the page's origin, for CORS; leave it out for the same origin
|
|
592
|
+
authorize: (request) => request.headers.get('authorization') === 'Bearer secret', // yours to write
|
|
593
|
+
});
|
|
594
|
+
const server = createServer(async (request, response) => {
|
|
595
|
+
const body = request.method === 'PUT' ? { body: Readable.toWeb(request) as ReadableStream, duplex: 'half' } : {};
|
|
596
|
+
const answer = await handle(new Request(`http://${request.headers.host}${request.url}`, { method: request.method, headers: request.headers as HeadersInit, ...body } as RequestInit));
|
|
597
|
+
response.writeHead(answer.status, Object.fromEntries(answer.headers));
|
|
598
|
+
response.end(Buffer.from(await answer.arrayBuffer()));
|
|
599
|
+
});
|
|
600
|
+
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
|
601
|
+
|
|
602
|
+
const { port } = server.address() as { port: number };
|
|
603
|
+
const storage = remoteStorage({ url: `http://127.0.0.1:${port}/saves`, headers: { authorization: 'Bearer secret' } });
|
|
604
|
+
await storage.write('slot-1', new Uint8Array([1, 2, 3]));
|
|
605
|
+
console.log(await storage.keys()); // ['slot-1']
|
|
606
|
+
await storage.delete('slot-1');
|
|
607
|
+
server.close();
|
|
608
|
+
```
|
|
609
|
+
|
|
610
|
+
With no `authorize`, anyone who reaches the handler can read and write every save, so a public server needs it. Other
|
|
611
|
+
options: `allowHeaders` for CORS and `maxBytes`, default 64 MiB, which a body is read only up to, sent with a length or
|
|
612
|
+
without one. Any other server works when it sends strong ETags and
|
|
613
|
+
honours `If-Match` and `If-None-Match`, and `keys()` needs its JSON list. Apache with mod_dav was tested: it sends no ETag
|
|
614
|
+
with a PUT, so a GET follows, and for about a second after a change it gives a weak tag, so a second write inside that
|
|
615
|
+
second is refused.
|
|
616
|
+
|
|
617
|
+
`safeStorage(remoteStorage(...))` and `SaveSlots` run over it.
|
|
618
|
+
|
|
619
|
+
## Validation and migrations
|
|
620
|
+
|
|
621
|
+
`validateSave(document, {components, strictComponents})` never throws and lists every problem with its path and fix
|
|
622
|
+
(`entities[3].parent: 'door' is not an entity of this document`): shape, duplicate ids, parent cycles, references,
|
|
623
|
+
unknown or cyclic prefabs, overrides of entities a prefab does not have, non-JSON values, and your component checks
|
|
624
|
+
(`components: {health: (v) => typeof v === 'object' ? null : 'must be {hp, max}'}`). `parseSave` returns a fresh
|
|
625
|
+
copy or throws a `TypeError` naming the first problem.
|
|
626
|
+
|
|
627
|
+
`new Migrations(latest).register(from, step)` holds one step per version; `migrate(document)` runs them in order on
|
|
628
|
+
a deep copy and checks each step returns the next version. A missing step, a step that throws or returns the wrong
|
|
629
|
+
version is `MargoError` `'failed'` naming it; a save newer than the game is a `RangeError`.
|
|
630
|
+
|
|
631
|
+
## Bytes and storage
|
|
632
|
+
|
|
633
|
+
`encodeSave(document, {compress, signal})` gives UTF-8 JSON, gzipped with `compress: true` (CompressionStream, in
|
|
634
|
+
browsers and Node 18+); `decodeSave(bytes, {signal, maxBytes})` reads either, and stops gzip data that decompresses past
|
|
635
|
+
`maxBytes` (default 268435456, 256 MiB) with a RangeError, so a small hostile file cannot fill memory. Storage adapters
|
|
636
|
+
share one interface, `read`, `write`,
|
|
637
|
+
`delete` and `keys`, each async with `{signal}`:
|
|
638
|
+
|
|
639
|
+
| Adapter | Where | Atomic write |
|
|
640
|
+
| --- | --- | --- |
|
|
641
|
+
| `memoryStorage()` | a Map (tests, servers, undo snapshots) | yes |
|
|
642
|
+
| `webStorage(storage = localStorage, prefix = 'margo-save:')` | Web Storage, base64; about 5 MB per origin | one `setItem` |
|
|
643
|
+
| `indexedDBStorage({database, store, factory})` | IndexedDB, binary, large; several stores in one database each get theirs (the database is opened one version up to add a store, and a connection closes when another needs a newer version) | one transaction |
|
|
644
|
+
| `opfsStorage({namespace, directory})` from `margoengine/save/opfs` | the origin private file system, one file per key | temporary stream swapped in on close |
|
|
645
|
+
| `fileStorage(directory, {maxBytes})` from `margoengine/save/node` | one file per key | temporary file, made exclusively, renamed into place; a read refuses a file past `maxBytes` (default 256 MiB) from its size, before reading it; one writer per folder; `keys()` lists only file names it writes; on Windows a save another program has open cannot be replaced, so the write rejects and the old save stands |
|
|
646
|
+
|
|
647
|
+
A full Web Storage or a failed transaction throws `MargoError` `'failed'` and keeps the previous save; a missing
|
|
648
|
+
API throws `'unsupported'`. `saveGame` never writes an invalid document.
|
|
649
|
+
|
|
650
|
+
Apache-2.0. Optional, tree-shakable package. Only `/engine` uses core, as an optional peer (`/slots`, `/safe` and `/remote` need none of them), with `@margoengine/gltf/pbr` and `@margoengine/animation` loaded when a save holds a model.
|
|
651
|
+
|
|
652
|
+
Build and unit tests: npm test --workspace @margoengine/save. Real GPU, models, thumbnails, IndexedDB and cross-origin fetch: npm run test:gpu --workspace @margoengine/save
|
|
653
|
+
|
|
654
|
+
### Scene of the result
|
|
655
|
+
|
|
656
|
+
`restoreScene`'s default model loader loads each model into the `scene` being restored, not into whichever scene is active when the load finishes. An abort or a failure leaves nothing in either scene.
|