threedog 0.8.0 → 1.0.1
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/CHANGELOG.md +223 -4
- package/README.md +6 -6
- package/core/assets/Animator.js +2 -0
- package/core/assets/Assets.js +44 -13
- package/core/assets/assetEntry.js +87 -22
- package/core/assets/assetHot.js +2 -1
- package/core/assets/assetReport.js +1 -2
- package/core/audio/Audio.js +24 -5
- package/core/base/I18n.js +6 -3
- package/core/base/Random.js +3 -1
- package/core/base/Vars.js +14 -4
- package/core/base/errorCodes.js +54 -16
- package/core/base/errorHints.js +12 -1
- package/core/base/errors.js +6 -4
- package/core/base/events.generated.js +10 -0
- package/core/base/follows.js +26 -0
- package/core/base/math.js +15 -8
- package/core/base/params.js +2 -2
- package/core/{saves → base}/saveValues.js +24 -6
- package/core/base/sections.js +97 -0
- package/core/base/spelling.js +32 -0
- package/core/base/validate.js +8 -29
- package/core/engine/Engine.js +61 -18
- package/core/engine/Loading.js +30 -3
- package/core/engine/copies.js +1 -1
- package/core/engine/headlessLoad.js +30 -13
- package/core/engine/lifecycle.js +30 -25
- package/core/engine/loop.js +22 -4
- package/core/engine/moduleSlots.js +91 -15
- package/core/engine/moduleTypes.js +13 -0
- package/core/engine/modules.js +248 -62
- package/core/engine/page.js +25 -8
- package/core/engine/plugins.js +15 -3
- package/core/engine/services.js +3 -0
- package/core/engine/startup.js +46 -36
- package/core/input/Input.js +39 -19
- package/core/input/inputKeyboard.js +39 -0
- package/core/input/inputPad.js +23 -2
- package/core/input/inputPointer.js +3 -1
- package/core/input/inputSeat.js +66 -0
- package/core/input/inputTouch.js +23 -6
- package/core/inspect/DebugOverrides.js +13 -2
- package/core/inspect/Describe.js +10 -6
- package/core/inspect/Inspect.js +31 -4
- package/core/inspect/UrlState.js +14 -10
- package/core/inspect/catalog.js +12 -5
- package/core/inspect/describeRender.js +3 -2
- package/core/inspect/describeText.js +6 -2
- package/core/inspect/metadata.generated.js +4140 -0
- package/core/inspect/pictureWriters.js +117 -33
- package/core/inspect/toolDoor.js +21 -0
- package/core/inspect/valueHistory.js +35 -0
- package/core/ops/Ops.js +32 -7
- package/core/ops/control.js +48 -23
- package/core/ops/holds.js +4 -3
- package/core/ops/opsAtomic.js +18 -6
- package/core/ops/opsCheck.js +7 -5
- package/core/ops/opsFail.js +5 -7
- package/core/ops/opsRun.js +2 -2
- package/core/ops/owned.js +20 -3
- package/core/ops/sharedPoint.js +7 -10
- package/core/ops/stacks.js +22 -1
- package/core/saves/SaveStore.js +52 -26
- package/core/saves/Saves.js +122 -27
- package/core/saves/saveApply.js +159 -61
- package/core/saves/saveFiles.js +30 -25
- package/core/saves/saveVersions.js +20 -6
- package/core/saves/session.js +76 -33
- package/core/saves/stateReplace.js +184 -0
- package/core/scene/Rays.js +21 -5
- package/core/scene/Views.js +6 -6
- package/core/scene/adaptive.js +13 -10
- package/core/scene/canvasBox.js +2 -0
- package/core/scene/compositeGround.js +72 -0
- package/core/scene/floor.js +17 -0
- package/core/scene/grid.js +2 -0
- package/core/scene/ground.contract.js +14 -0
- package/core/scene/ground.js +52 -17
- package/core/scene/pixel.js +154 -0
- package/core/scene/pixelRatio.js +167 -0
- package/core/scene/sceneDelta.js +3 -3
- package/core/scene/sceneMethods.js +11 -6
- package/core/scene/stepPoses.js +6 -1
- package/core/scene/thingExplain.js +1 -1
- package/core/scene/thingOps.js +22 -14
- package/core/scene/things.js +1 -1
- package/core/scene/tier.js +10 -0
- package/core/scene/view.js +126 -9
- package/core/stream/Batching.js +0 -1
- package/core/stream/Stream.js +24 -12
- package/core/stream/batchGroups.js +1 -0
- package/core/stream/scatter.js +5 -2
- package/core/stream/streamSources.js +2 -1
- package/core/threads/Commits.js +12 -7
- package/core/threads/Jobs.js +15 -5
- package/core/threads/Threads.js +5 -2
- package/core/time/Clock.js +3 -1
- package/core/time/skip.js +10 -4
- package/core/time/time.js +16 -10
- package/docs/AI.md +89 -72
- package/docs/API.md +18 -14
- package/docs/CODEMAP.md +68 -40
- package/docs/COMMANDS.md +22 -23
- package/docs/CONVENTIONS.md +120 -17
- package/docs/MIGRATING-0.8.md +2 -0
- package/docs/MIGRATING-1.0.md +101 -0
- package/docs/THREE.md +65 -12
- package/docs/api/cameraRig.md +3 -0
- package/docs/api/characters.md +13 -7
- package/docs/api/collider3d.md +9 -0
- package/docs/api/content.md +16 -15
- package/docs/api/dialogue.md +2 -1
- package/docs/api/engine.md +18 -16
- package/docs/api/events.md +14 -4
- package/docs/api/ground.md +2 -2
- package/docs/api/i18n.md +1 -1
- package/docs/api/input.md +2 -1
- package/docs/api/interactions.md +1 -1
- package/docs/api/inventory.md +1 -1
- package/docs/api/level.md +3 -2
- package/docs/api/nav.md +4 -2
- package/docs/api/particles.md +8 -5
- package/docs/api/pickups.md +1 -1
- package/docs/api/post.md +3 -4
- package/docs/api/quests.md +4 -2
- package/docs/api/rays.md +2 -0
- package/docs/api/rigid.md +3 -2
- package/docs/api/saves.md +8 -7
- package/docs/api/stream.md +4 -5
- package/docs/api/terrain.md +3 -4
- package/docs/api/terrainDraw.md +1 -1
- package/docs/api/timeline.md +2 -2
- package/docs/api/tools.md +3 -1
- package/docs/api/triggers.md +2 -0
- package/docs/api/vegetationDraw.md +1 -1
- package/docs/api/water.md +6 -2
- package/docs/api/weather.md +19 -4
- package/docs/api/weatherDraw.md +1 -1
- package/docs/api/world.md +1 -1
- package/docs/recipes/01-new-game.md +3 -3
- package/docs/recipes/02-npc.md +3 -4
- package/docs/recipes/03-items-pickups.md +11 -11
- package/docs/recipes/04-quests.md +2 -0
- package/docs/recipes/05-props-bake.md +9 -9
- package/docs/recipes/06-clock-events.md +6 -6
- package/docs/recipes/07-flow-scenes-pause.md +18 -15
- package/docs/recipes/08-weather-sky.md +5 -5
- package/docs/recipes/09-materials-lights-models.md +3 -3
- package/docs/recipes/10-blender-level.md +16 -4
- package/docs/recipes/11-vehicles.md +18 -6
- package/docs/recipes/12-navmesh.md +52 -8
- package/docs/recipes/13-animation.md +34 -8
- package/docs/recipes/14-custom-module.md +20 -8
- package/docs/recipes/15-perf.md +4 -4
- package/docs/recipes/16-dev-bridge.md +9 -8
- package/docs/recipes/18-world.md +13 -5
- package/docs/recipes/19-shooting-picking.md +3 -2
- package/docs/recipes/20-content-actions-save.md +26 -6
- package/docs/recipes/21-camera.md +17 -23
- package/docs/recipes/22-shop-gold.md +21 -12
- package/docs/recipes/23-ops.md +19 -15
- package/docs/recipes/26-ui-parts.md +3 -2
- package/docs/recipes/27-net.md +3 -3
- package/docs/recipes/28-terrain.md +3 -3
- package/docs/recipes/29-grid.md +1 -1
- package/docs/recipes/30-templates.md +10 -13
- package/docs/recipes/31-audio.md +2 -2
- package/docs/recipes/32-action-game.md +6 -5
- package/docs/recipes/33-stream-sources.md +4 -1
- package/docs/recipes/34-environment-lighting.md +7 -8
- package/docs/recipes/35-picture-from-reference.md +13 -9
- package/docs/recipes/36-ground-plants.md +3 -2
- package/docs/recipes/40-scene.md +11 -10
- package/docs/recipes/43-shader-patches-surfaces.md +7 -7
- package/docs/recipes/44-water-weather-hooks.md +9 -8
- package/docs/recipes/45-cascaded-shadows.md +3 -4
- package/docs/recipes/46-blender-art-route.md +3 -3
- package/docs/recipes/49-game-module-contract.md +2 -1
- package/docs/recipes/50-own-renderer.md +1 -0
- package/docs/recipes/51-capability-catalog.md +14 -8
- package/docs/recipes/52-around-the-picture.md +4 -4
- package/docs/recipes/55-mods-time-wrap.md +5 -4
- package/docs/recipes/56-webgpu-tsl.md +12 -1
- package/docs/recipes/57-control.md +30 -10
- package/docs/recipes/58-input.md +13 -0
- package/docs/recipes/60-judge-the-picture.md +1 -1
- package/docs/recipes/62-picture-code.md +106 -48
- package/docs/recipes/63-third-person-start.md +2 -1
- package/docs/recipes/64-particles.md +53 -4
- package/docs/recipes/65-swarm.md +2 -2
- package/docs/recipes/66-common-tasks.md +313 -0
- package/examples/action/.threedog/content-index.json +1 -1
- package/examples/action/GAMEMAP.md +3 -3
- package/examples/perf-island/.threedog/content-index.json +1 -1
- package/examples/perf-island/GAMEMAP.md +3 -3
- package/examples/perf-island/main.js +2 -2
- package/examples/plain-picture/GAMEMAP.md +3 -1
- package/examples/rc2d/GAMEMAP.md +1 -1
- package/examples/rc2d/rc2d.js +1 -1
- package/examples/styletest/.threedog/content-index.json +1 -1
- package/examples/styletest/GAMEMAP.md +3 -3
- package/examples/webgpu-tsl/GAMEMAP.md +1 -1
- package/examples/world/.threedog/content-index.json +1 -1
- package/examples/world/GAMEMAP.md +5 -4
- package/examples/world/main.js +3 -3
- package/index.d.ts +8 -5
- package/index.js +22 -1
- package/llms.txt +2 -1
- package/modules/ambience/Ambience.js +5 -3
- package/modules/calendar/index.js +7 -5
- package/modules/camera/FirstPersonCamera.js +3 -3
- package/modules/camera/FixedCamera.js +34 -20
- package/modules/camera/FollowCamera.js +20 -11
- package/modules/camera/RtsCamera.js +1 -0
- package/modules/camera/common.js +33 -22
- package/modules/camera/pixelSnap.js +62 -0
- package/modules/characters/Character.js +136 -43
- package/modules/characters/NPC.js +60 -28
- package/modules/characters/assetModel.js +2 -2
- package/modules/characters/astar.js +47 -28
- package/modules/characters/character.contract.js +21 -0
- package/modules/characters/contract.js +17 -3
- package/modules/characters/index.js +94 -34
- package/modules/characters/moveHelpers.js +80 -15
- package/modules/characters/mover.contract.js +14 -0
- package/modules/characters/movers/common.js +6 -4
- package/modules/characters/movers/rapier.js +12 -5
- package/modules/characters/movers/simple.js +25 -12
- package/modules/characters/movers/support.js +18 -7
- package/modules/characters/npcAvoid.js +15 -12
- package/modules/characters/npcSim.js +75 -25
- package/modules/characters/npcView.js +13 -6
- package/modules/characters/pathAsync.js +74 -24
- package/modules/characters/pathJob.js +38 -21
- package/modules/characters/player.js +59 -47
- package/modules/characters/seat.js +56 -0
- package/modules/characters/vehicle.contract.js +8 -5
- package/modules/characters/walkTo.js +31 -18
- package/modules/collision/Collision.js +44 -26
- package/modules/collision/contract.js +2 -2
- package/modules/collision/grid.js +6 -1
- package/modules/content/explain.js +1 -1
- package/modules/content/fields.js +3 -3
- package/modules/content/ids.js +3 -1
- package/modules/content/index.js +83 -27
- package/modules/content/loader.js +110 -130
- package/modules/content/markers.js +1 -1
- package/modules/content/models.js +48 -14
- package/modules/content/packs.js +2 -1
- package/modules/content/places.js +5 -4
- package/modules/content/props.js +8 -6
- package/modules/content/rules.js +29 -47
- package/modules/content/templates.js +66 -35
- package/modules/content/words.js +19 -6
- package/modules/debug/DebugPanel.js +4 -2
- package/modules/flow/contract.js +1 -0
- package/modules/flow/index.js +24 -14
- package/modules/gameplay/Container.js +5 -2
- package/modules/gameplay/Containers.js +9 -1
- package/modules/gameplay/Dialogue.js +82 -25
- package/modules/gameplay/Interactions.js +61 -32
- package/modules/gameplay/Inventory.js +56 -13
- package/modules/gameplay/Quests.js +133 -24
- package/modules/gameplay/boxOps.js +7 -0
- package/modules/gameplay/dialogueBubbles.js +14 -9
- package/modules/gameplay/inventoryOps.js +11 -7
- package/modules/gameplay/pickups.js +43 -16
- package/modules/gameplay/questLog.js +4 -2
- package/modules/gameplay/questSave.js +6 -1
- package/modules/gameplay/quests.contract.js +1 -1
- package/modules/grid/Grid.js +1 -1
- package/modules/grid/Layer.js +8 -4
- package/modules/grid/index.js +21 -15
- package/modules/grid/ops.js +43 -46
- package/modules/grid/tiles.js +1 -1
- package/modules/hlod/index.js +6 -3
- package/modules/hud/index.js +6 -4
- package/modules/hud/parts.js +4 -4
- package/modules/level/contract.js +2 -2
- package/modules/level/heightfield.js +17 -21
- package/modules/level/index.js +83 -26
- package/modules/level/load.js +165 -48
- package/modules/level/nodes.js +34 -16
- package/modules/lights/index.js +6 -3
- package/modules/lights/sources.js +3 -1
- package/modules/music/Music.js +4 -2
- package/modules/nav/contract.js +7 -5
- package/modules/nav/index.js +174 -44
- package/modules/nav/navPath.js +45 -10
- package/modules/net/index.js +1 -1
- package/modules/particles/Particles.js +85 -22
- package/modules/particles/effect.js +80 -28
- package/modules/particles/shaders.js +17 -0
- package/modules/photo/Photo.js +12 -10
- package/modules/rigid/RigidBodies.js +200 -57
- package/modules/rigid/Vehicles.js +15 -5
- package/modules/rigid/collider3d.contract.js +26 -0
- package/modules/rigid/ragdoll.js +55 -44
- package/modules/rigid/ragdollBones.js +83 -33
- package/modules/rigid/refresh.js +10 -0
- package/modules/rigid/sync.js +46 -15
- package/modules/settings/Settings.js +84 -37
- package/modules/settings/apply.js +15 -8
- package/modules/settings/sections.js +7 -4
- package/modules/settings/strings.js +2 -2
- package/modules/sky/skyModule.js +3 -1
- package/modules/swarm/Swarm.js +16 -6
- package/modules/terrain/ChunkManager.js +10 -16
- package/modules/terrain/index.js +17 -11
- package/modules/terrain/terrainEdit.js +13 -2
- package/modules/terrain/terrainGen.js +5 -3
- package/modules/terrain/terrainShape.js +1 -1
- package/modules/timeline/Timeline.js +58 -26
- package/modules/timeline/Tween.js +19 -13
- package/modules/timeline/shots.js +19 -10
- package/modules/triggers/index.js +87 -20
- package/modules/vegetation/Vegetation.js +4 -3
- package/modules/vegetation/draw.js +16 -0
- package/modules/vegetation/groundChunks.js +10 -7
- package/modules/vegetation/index.js +30 -7
- package/modules/water/Water.js +6 -2
- package/modules/weather/Weather.js +16 -15
- package/modules/weather/weatherDraw.js +7 -6
- package/modules/world/World.js +20 -7
- package/modules/world/explain.js +1 -1
- package/modules/world/index.js +13 -6
- package/modules/world/persist.js +23 -8
- package/modules/world/pos.js +4 -4
- package/modules/world/records.js +13 -7
- package/modules/world/sim.js +74 -23
- package/modules/world/simFar.js +2 -2
- package/modules/world/state.js +31 -6
- package/modules/world/thingSource.js +16 -3
- package/modules/world/views.js +19 -8
- package/package.json +7 -1
- package/render/PostFX.js +47 -29
- package/render/backend.js +5 -1
- package/render/fx/particles.tsl.js +8 -6
- package/render/fx/postWebGPU.tsl.js +3 -3
- package/render/layers.js +1 -1
- package/render/lightmap.js +23 -3
- package/render/occlusion.js +43 -12
- package/render/patches.js +2 -2
- package/render/postWebGL.js +4 -3
- package/render/probes.js +25 -0
- package/render/shadows.js +2 -2
- package/types/core.d.ts +142 -55
- package/types/gameplay.d.ts +92 -40
- package/types/generated/core/base/I18n.d.ts +2 -2
- package/types/generated/core/input/Input.d.ts +16 -2
- package/types/generated/core/input/inputSeat.d.ts +26 -0
- package/types/generated/core/inspect/DebugOverrides.d.ts +15 -1
- package/types/generated/core/ops/Ops.d.ts +2 -1
- package/types/generated/core/ops/control.d.ts +12 -2
- package/types/generated/core/saves/Saves.d.ts +26 -6
- package/types/generated/core/saves/session.d.ts +1 -1
- package/types/generated/core/scene/Views.d.ts +1 -1
- package/types/generated/core/stream/Stream.d.ts +6 -4
- package/types/generated/modules/grid/Grid.d.ts +1 -0
- package/types/generated/modules/particles/Particles.d.ts +4 -3
- package/types/generated/modules/timeline/Timeline.d.ts +5 -4
- package/types/generated/modules/weather/Weather.d.ts +1 -7
- package/types/generated/modules/world/World.d.ts +6 -4
- package/types/generated/render/PostFX.d.ts +6 -14
- package/types/nav.d.ts +36 -4
- package/types/physics.d.ts +55 -7
- package/types/pixel.d.ts +75 -0
- package/types/world.d.ts +14 -8
- package/ui/Parts.js +9 -2
- package/ui/theme.js +2 -2
- package/core/scene/engineCamera.js +0 -32
- package/modules/camera/projection.js +0 -21
package/core/saves/saveApply.js
CHANGED
|
@@ -6,22 +6,25 @@
|
|
|
6
6
|
// The capture lasts the whole load, past every await: an async part that emits after `await` (async load(d) { apply(d); await res(); emit(...) })
|
|
7
7
|
// is part of the load as much as its first line. The browser has no async context to tell whose code emitted after an await, so each load
|
|
8
8
|
// carries its own capture scope (Events._scopes): a part's synchronous run puts its load's scope on top; between awaits the load started last
|
|
9
|
-
// gets the errors.
|
|
10
|
-
//
|
|
11
|
-
//
|
|
9
|
+
// gets the errors. Only one load runs at a time, inside its turn (stateReplace.js), so that load is this one. Everything here returns a plain value
|
|
10
|
+
// while it stays synchronous: a fully synchronous save ends before apply returns. An unrelated listener that throws while a load is still settling
|
|
11
|
+
// fails that load too; gameplay is frozen while parts load, so that is rare, and the error is reported.
|
|
12
12
|
// The rollback point is a copy (structuredClone of every part's save()): save() may return the live object, which load() then writes into.
|
|
13
|
+
// A part about to load whose save() gives nothing to copy (null, or it threw) goes back to its new-game state; with none of that either it cannot go back, and a failed load says so.
|
|
13
14
|
import { toast } from '../../ui/UI.js';
|
|
14
15
|
import { fmt, warnOnce } from '../base/validate.js';
|
|
15
16
|
import { reportError } from '../base/errors.js';
|
|
16
17
|
import { codedError, coded } from '../base/errorHints.js';
|
|
17
|
-
import { FORMAT, readSave, parseSave, upgradePart } from './saveVersions.js';
|
|
18
|
-
import { PARTS_LOADING } from '../ops/opsFail.js';
|
|
18
|
+
import { FORMAT, readSave, parseSave, upgradePart, partVersion } from './saveVersions.js';
|
|
19
19
|
import { isObject } from '../base/util.js';
|
|
20
20
|
|
|
21
21
|
const DEV_STRINGS = {
|
|
22
22
|
loadThrew: "load() of save part '{k}' threw ({msg}); the game was rolled back to how it was before loading '{slot}'",
|
|
23
23
|
partAt: "load() of save part '{k}'", adoptAt: "load() of save part '{k}' (registered after the save was loaded)",
|
|
24
24
|
rollback: "rollback of save part '{k}' after a failed load (that part may be half-loaded; the other parts rolled back)",
|
|
25
|
+
noRollback: "save part '{k}' keeps what the failed load gave it: its save() gave nothing before the load and it has no new-game state to go back to (the other parts rolled back)",
|
|
26
|
+
notData: "save() of save part '{k}' returned {got}, which a save cannot hold; return plain data, or null when there is nothing to save",
|
|
27
|
+
notNumber: "save() of save part '{k}' holds {got} at {path}, which a save cannot hold (it would come back as null); save a finite number, or leave the field out",
|
|
25
28
|
listener: 'a listener of event {name} threw while the part loaded: {msg}',
|
|
26
29
|
hook: "afterLoad of module '{k}' threw ({msg}); the game was rolled back to how it was before loading '{slot}'",
|
|
27
30
|
notPlain: "save() of save part '{k}' returned data that cannot be copied ({msg}), so loading '{slot}' could not keep a rollback point and was refused "
|
|
@@ -33,61 +36,91 @@ const loadError = (k, err, slot) => Object.assign(codedError('save-load-threw',
|
|
|
33
36
|
|
|
34
37
|
/**
|
|
35
38
|
* Implementation of saves.apply (see its JSDoc): checked first, applied part by part, rolled back to the pre-load state if any part throws.
|
|
39
|
+
* Runs inside a turn of s._replace; the marker is on from the first read to the last rollback step.
|
|
36
40
|
* @param {any} s the Saves instance
|
|
37
41
|
* @param {any} data
|
|
38
42
|
* @param {string} slot
|
|
39
|
-
* @returns {Promise<boolean>}
|
|
43
|
+
* @returns {boolean | Promise<boolean>} a plain value when nothing waited
|
|
40
44
|
* @internal
|
|
41
45
|
*/
|
|
42
46
|
export function applySave(s, data, slot) {
|
|
47
|
+
const q = s._replace, job = q.job;
|
|
48
|
+
q.begin();
|
|
49
|
+
let out;
|
|
50
|
+
try { out = checkAndApply(s, data, slot); } catch (err) { q.end(); throw err; }
|
|
51
|
+
if (typeof out !== 'boolean') return out.finally(() => q.endOf(job));
|
|
52
|
+
q.end();
|
|
53
|
+
return out;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The body of applySave, under the marker */
|
|
57
|
+
function checkAndApply(s, data, slot) {
|
|
43
58
|
const r = readSave(data, s.providers, slot);
|
|
44
59
|
if ('reason' in r) {
|
|
45
60
|
if (r.reason !== 'missing') { warnOnce(coded('save-refused', r.dev)); // handled: the player is told, nothing changed
|
|
46
61
|
toast(s.engine, s.engine.t('saves.' + r.reason), { kind: 'error', ms: 5000 }); }
|
|
47
|
-
return
|
|
62
|
+
return false;
|
|
48
63
|
}
|
|
49
64
|
const e = s.engine, foreign0 = s._foreign;
|
|
50
65
|
let before; // the rollback point, a copy (rollbackPoint)
|
|
51
|
-
try { before = rollbackPoint(s, slot); } catch (err) { reportError(e, err, `saves.apply('${slot}')`); return
|
|
66
|
+
try { before = rollbackPoint(s, slot, r.list); } catch (err) { reportError(e, err, `saves.apply('${slot}')`); return false; }
|
|
52
67
|
const ev = e.events, scope = []; // this load's capture scope: listener errors from now until the load settled (top of the file)
|
|
53
68
|
ev._scopes.push(scope);
|
|
54
69
|
const settled = () => { const i = ev._scopes.lastIndexOf(scope); if (i >= 0) ev._scopes.splice(i, 1); };
|
|
55
|
-
|
|
70
|
+
let out;
|
|
71
|
+
try { out = applyParts(s, e, r, slot, before, foreign0, scope); } catch (err) { settled(); throw err; }
|
|
72
|
+
if (typeof out !== 'boolean') return out.finally(settled);
|
|
73
|
+
settled();
|
|
74
|
+
return out;
|
|
56
75
|
}
|
|
57
76
|
|
|
58
77
|
/** The rest of applySave, under the load's capture scope */
|
|
59
78
|
function applyParts(s, e, r, slot, before, foreign0, scope) {
|
|
60
|
-
|
|
79
|
+
const q = s._replace;
|
|
80
|
+
const keepResults = e.commits.invalidate(); e.ops._mark('(load)'); // old background results die with the old world; the op log shows where the load cut in
|
|
81
|
+
const generation = q.generation++;
|
|
82
|
+
q.changed();
|
|
61
83
|
s._foreign = r.foreign;
|
|
62
84
|
const fail = err => {
|
|
85
|
+
keepResults(); q.generation = generation; q.changed(true); // the old world stays, and what it was waiting for with it
|
|
63
86
|
// a malformed save (refuseSave, save-bad-record) is the save's fault, not the game's: refused like a corrupt save (warning + toast), so it
|
|
64
87
|
// does not freeze gameplay as a code error would; a load() / listener / afterLoad that throws is a bug and goes through the error tiers
|
|
65
|
-
|
|
88
|
+
const refused = err?.cause?.code === 'save-bad-record';
|
|
89
|
+
if (refused) { warnOnce(err.message); toast(e, e.t('saves.corrupt'), { kind: 'error', ms: 5000 }); }
|
|
66
90
|
else reportError(e, err, err?.part ? fmt(DEV_STRINGS.partAt, { k: err.part }) : `saves.apply('${slot}')`);
|
|
67
91
|
s._foreign = foreign0;
|
|
68
92
|
const back = readSave(before, s.providers, '(rollback)');
|
|
69
93
|
// every part reloads its pre-load state; a part that throws again is reported (once) and the rest still roll back
|
|
70
94
|
const onPart = er => reportError(e, er, fmt(DEV_STRINGS.rollback, { k: er.part }), { soft: true });
|
|
71
|
-
const undone = 'list' in back ? e.ops.allow(() => runParts(
|
|
72
|
-
// a
|
|
73
|
-
const
|
|
74
|
-
|
|
95
|
+
const undone = 'list' in back ? e.ops.allow(() => runParts(s, back.list, '(rollback)', scope, onPart)) : true;
|
|
96
|
+
// a part that refused its data took none of it: it has nothing to go back from
|
|
97
|
+
for (const [k] of r.list) if (!Object.hasOwn(before.parts, k) && !(refused && k === err.part)) reportError(e, codedError('save-load-threw', fmt(DEV_STRINGS.noRollback, { k })), `saves.apply('${slot}')`, { soft: true });
|
|
98
|
+
// a session door announces its own failure, after its clocks came back
|
|
99
|
+
const failed = () => { if (!e.session._busy) e.events.emit('session:failed', { kind: 'quick', slot }); return false; };
|
|
100
|
+
if (undone === true) return failed();
|
|
101
|
+
q.hold(); // a rollback that waits on an async part holds gameplay too, whichever way the load failed
|
|
102
|
+
return undone.then(failed);
|
|
75
103
|
};
|
|
76
|
-
let out;
|
|
77
|
-
try { out = e.ops.allow(() => runParts(e, r.list, slot, scope)); } catch (err) { return fail(err); } // loading writes state outside ops on purpose (guard allows it)
|
|
78
|
-
// a part still loading (its load() returned a Promise): gameplay waits until every part is applied -- no fixed step, no op (opsFail.js
|
|
79
|
-
// PARTS_LOADING). A fully sync load never takes it.
|
|
80
|
-
const fz = out !== true ? e.freeze(PARTS_LOADING) : null;
|
|
81
|
-
const partsDone = () => { fz?.remove(); };
|
|
82
104
|
// a load is a state change: ops.revision moves. afterLoad belongs to the load (Saves.apply doc): a hook that throws fails it like a part's load()
|
|
83
|
-
|
|
84
|
-
|
|
105
|
+
const partsDone = () => {
|
|
106
|
+
e.ops.revision++;
|
|
107
|
+
let hooks;
|
|
108
|
+
try { hooks = afterLoad(s, e, slot, scope); } catch (err) { return fail(err); }
|
|
109
|
+
return hooks === true ? true : hooks.then(() => true, fail);
|
|
110
|
+
};
|
|
111
|
+
let out;
|
|
112
|
+
try { out = e.ops.allow(() => runParts(s, r.list, slot, scope)); } catch (err) { return fail(err); } // loading writes state outside ops on purpose (guard allows it)
|
|
113
|
+
if (out === true) return partsDone();
|
|
114
|
+
q.hold(); // a part still loading (its load() returned a Promise): gameplay waits until every part is applied. A fully sync load never takes it
|
|
115
|
+
return out.then(partsDone, fail);
|
|
85
116
|
}
|
|
86
117
|
|
|
87
118
|
/** The rollback point: every part's save(), copied so a load() writing into the object its save() returned cannot change it.
|
|
88
|
-
* A part whose data cannot be copied throws (save-part-threw): without a true copy a failed load could not be undone
|
|
89
|
-
|
|
90
|
-
|
|
119
|
+
* A part whose data cannot be copied throws (save-part-threw): without a true copy a failed load could not be undone.
|
|
120
|
+
* list: the parts about to load; those with nothing to copy take their new-game data (top of the file) */
|
|
121
|
+
function rollbackPoint(s, slot, list) {
|
|
122
|
+
const data = s._collect().data, S = s.engine.session, base = S._base ? S._baseData() : { parts: {}, versions: {} };
|
|
123
|
+
for (const [k] of list) if (!Object.hasOwn(data.parts, k) && Object.hasOwn(base.parts, k)) { data.parts[k] = base.parts[k]; data.versions[k] = base.versions[k]; }
|
|
91
124
|
for (const k of Object.keys(data.parts)) {
|
|
92
125
|
try { data.parts[k] = structuredClone(data.parts[k]); }
|
|
93
126
|
catch (err) { throw Object.assign(codedError('save-part-threw', fmt(DEV_STRINGS.notPlain, { k, slot, msg: err?.message ?? String(err) })), { cause: err }); }
|
|
@@ -105,8 +138,8 @@ function takeListenerError(scope, from) {
|
|
|
105
138
|
|
|
106
139
|
/** Run one part's load with event-listener errors collected in the load's scope (on top while it runs synchronously, see the top of the file);
|
|
107
140
|
* an async load is checked once it settled, so a listener that throws after its await fails the part too */
|
|
108
|
-
function callLoad(
|
|
109
|
-
const ev =
|
|
141
|
+
function callLoad(s, fn, scope) {
|
|
142
|
+
const ev = s.engine.events, from = scope.length;
|
|
110
143
|
ev._scopes.push(scope);
|
|
111
144
|
let r;
|
|
112
145
|
try { r = fn(); } catch (err) { scope.length = from; throw err; } finally { ev._scopes.splice(ev._scopes.lastIndexOf(scope), 1); }
|
|
@@ -119,13 +152,13 @@ function callLoad(e, fn, scope) {
|
|
|
119
152
|
* Load parts in order; a part returning a Promise makes the rest wait for it. A failing part throws (or rejects) with the part named,
|
|
120
153
|
* unless onFail is given (rollback): then onFail(err) is called and the next part loads anyway.
|
|
121
154
|
*/
|
|
122
|
-
function runParts(
|
|
123
|
-
const failed = (k, err) => { const er = loadError(k, err, slot); if (!onFail) throw er; onFail(er); };
|
|
155
|
+
function runParts(s, list, slot, scope, onFail = null) {
|
|
156
|
+
const failed = (k, err) => { const er = loadError(k, err, slot); if (!onFail) throw er; onFail(er); }, { turn } = s._replace.job;
|
|
124
157
|
const step = i => {
|
|
125
158
|
for (; i < list.length; i++) {
|
|
126
159
|
const [k, p, d] = list[i];
|
|
127
160
|
let r;
|
|
128
|
-
try { r = callLoad(
|
|
161
|
+
try { r = callLoad(s, () => p.load(d, turn), scope); } catch (err) { failed(k, err); continue; }
|
|
129
162
|
if (r && typeof r.then === 'function') return r.then(() => step(i + 1), err => { failed(k, err); return step(i + 1); });
|
|
130
163
|
}
|
|
131
164
|
return true;
|
|
@@ -134,20 +167,28 @@ function runParts(e, list, slot, scope, onFail = null) {
|
|
|
134
167
|
}
|
|
135
168
|
|
|
136
169
|
/**
|
|
137
|
-
* A part registered after a save was loaded (a module installed later): hand it its data from that save now.
|
|
170
|
+
* A part registered after a save was loaded (a module installed later): hand it its data from that save in a turn of its own. Idle that is now. During a
|
|
171
|
+
* replacement it is after it, whole: its first line would write into a half-loaded state, and a newer load waits for it instead of having this older data
|
|
172
|
+
* land on top. A load that replaced the state while it waited took this data with it. The data stays unattached until then, so a save still carries it.
|
|
138
173
|
* @param {any} s the Saves instance
|
|
139
174
|
* @param {string} key
|
|
140
175
|
* @internal
|
|
141
176
|
*/
|
|
142
177
|
export function adoptPart(s, key) {
|
|
143
|
-
const
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
178
|
+
const f = s._foreign, q = s._replace, where = fmt(DEV_STRINGS.adoptAt, { k: key });
|
|
179
|
+
q.run(null, () => {
|
|
180
|
+
const p = s.providers.get(key);
|
|
181
|
+
if (s._foreign !== f || !p || !Object.hasOwn(f.parts, key)) return;
|
|
182
|
+
const d = f.parts[key], v = f.versions[key] ?? 1;
|
|
183
|
+
delete f.parts[key]; delete f.versions[key];
|
|
184
|
+
// data the part could not take stays unattached, and collectParts writes it instead of the part's empty state: the next save must not lose it
|
|
185
|
+
const refused = err => { if (s._foreign === f) { f.parts[key] = d; f.versions[key] = v; } reportError(s.engine, err, where); };
|
|
186
|
+
try {
|
|
187
|
+
if (v > p.version) throw codedError('save-refused', `save part '${key}' is version ${v}, this build reads up to ${p.version}`);
|
|
188
|
+
const r = s.engine.ops.allow(() => p.load(upgradePart(key, p, d, v, f.whole), q.job.turn));
|
|
189
|
+
if (r && typeof r.then === 'function') return r.catch(refused);
|
|
190
|
+
} catch (err) { refused(err); }
|
|
191
|
+
}, true);
|
|
151
192
|
}
|
|
152
193
|
|
|
153
194
|
|
|
@@ -157,21 +198,37 @@ export function adoptPart(s, key) {
|
|
|
157
198
|
* @param {string} slot
|
|
158
199
|
* @param {any} [base]
|
|
159
200
|
* @returns {Promise<boolean>}
|
|
160
|
-
* @internal
|
|
201
|
+
* @internal Runs inside a turn of s._replace
|
|
161
202
|
*/
|
|
162
203
|
export function loadSlot(s, slot, base) {
|
|
163
204
|
let data = s._json.get(slot);
|
|
164
205
|
if (base && data != null) {
|
|
165
206
|
try {
|
|
166
207
|
const sv = parseSave(data);
|
|
167
|
-
if (isObject(sv?.parts)) {
|
|
168
|
-
const own = Object.fromEntries(Object.keys(sv.parts).map(k => [k, sv.versions
|
|
208
|
+
if (isObject(sv?.parts) && (sv.versions === undefined || isObject(sv.versions))) { // other shapes go on as they are: apply refuses them with the reason
|
|
209
|
+
const own = Object.fromEntries(Object.keys(sv.parts).map(k => [k, partVersion(sv.versions, k)])); // a part without a version is version 1, not base's
|
|
169
210
|
data = { ...sv, parts: { ...base.parts, ...sv.parts }, versions: { ...base.versions, ...own } };
|
|
170
211
|
}
|
|
171
212
|
} catch { /* unreadable: apply refuses the text itself with the reason */ }
|
|
172
213
|
}
|
|
173
|
-
return s
|
|
174
|
-
|
|
214
|
+
return applyAnnounced(s, data, slot, () => s._adopt(slot)); // continuing from it: this tab may overwrite it now (Saves._put)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Apply a save onto the running playthrough and say so: what is not saved ends on save:loaded, derived state rebuilds on it, and the playthrough runs from here, whichever door the save came through (session.js lists them).
|
|
219
|
+
* @param {any} s the Saves instance
|
|
220
|
+
* @param {any} data
|
|
221
|
+
* @param {string} slot
|
|
222
|
+
* @param {() => void} [done] on success, before the event
|
|
223
|
+
* @returns {Promise<boolean>}
|
|
224
|
+
* @internal Runs inside a turn of s._replace
|
|
225
|
+
*/
|
|
226
|
+
export function applyAnnounced(s, data, slot, done) {
|
|
227
|
+
const q = s._replace, job = q.job, applied = applySave(s, data, slot);
|
|
228
|
+
if (typeof applied === 'boolean') q.pause(); // only the save:loaded below is left, a microtask on
|
|
229
|
+
return Promise.resolve(applied).then(ok => { // apply already ran the modules' afterLoad hooks
|
|
230
|
+
// not when a newer load took over: the game holds that one's state, and it announces itself
|
|
231
|
+
if (ok && q.job === job) { done?.(); s.engine.session._started(); s.engine.events.emit('save:loaded', slot); }
|
|
175
232
|
return ok;
|
|
176
233
|
});
|
|
177
234
|
}
|
|
@@ -183,21 +240,59 @@ export function loadSlot(s, slot, base) {
|
|
|
183
240
|
* The first failure rejects, named after its module (save-load-threw), and applySave rolls back. Rollback itself does not rerun afterLoad
|
|
184
241
|
* (the world rebuilds nearby models over the next frames).
|
|
185
242
|
* The hooks run side by side, so a listener error in this phase is not pinned on one hook: once all settled, any error the load's scope
|
|
186
|
-
* collected since its parts finished fails the load (the last check before apply resolves true).
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
243
|
+
* collected since its parts finished fails the load (the last check before apply resolves true).
|
|
244
|
+
* Returns true when no module has a hook (nothing waited), else a Promise. The hooks start a microtask after the parts, and the marker and the
|
|
245
|
+
* freeze with them: the lines right after an unawaited apply can still step, run ops and apply again (stateReplace.js, pause). */
|
|
246
|
+
function afterLoad(s, e, slot, scope) {
|
|
247
|
+
const hooks = [...e.modules.values()].filter(m => m.afterLoad), q = s._replace;
|
|
248
|
+
if (!hooks.length) { takeListenerError(scope, 0); return true; }
|
|
249
|
+
const job = q.pause();
|
|
250
|
+
const run = () => {
|
|
251
|
+
if (!q.resume(job)) return null;
|
|
252
|
+
q.hold();
|
|
253
|
+
return Promise.allSettled(hooks.map(m => Promise.resolve().then(() => m.afterLoad(e, job.turn))));
|
|
254
|
+
};
|
|
255
|
+
return Promise.resolve().then(run).then(res => {
|
|
256
|
+
// taken over: the state is the newer load's, so nothing here may fail or roll back; what the scope caught is a listener error like any other
|
|
257
|
+
if (!res) { for (const { name, err } of scope.splice(0)) e.events.onError(name, err); return; }
|
|
258
|
+
const i = res.findIndex(r => r.status === 'rejected');
|
|
259
|
+
if (i >= 0) {
|
|
260
|
+
scope.length = 0;
|
|
261
|
+
const err = /** @type {PromiseRejectedResult} */ (res[i]).reason, k = hooks[i].name;
|
|
262
|
+
throw Object.assign(codedError('save-load-threw', fmt(DEV_STRINGS.hook, { k, slot, msg: err?.message ?? String(err) })), { cause: err });
|
|
263
|
+
}
|
|
264
|
+
takeListenerError(scope, 0);
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Where inside a part's data JSON would turn a number into null, as 'pos[0]', else null. seen: a cycle is JSON.stringify's to refuse, not this walk's to chase */
|
|
269
|
+
function badNumberAt(v, path = '', seen = new Set()) {
|
|
270
|
+
if (typeof v === 'number') return Number.isFinite(v) ? null : { path, got: String(v) };
|
|
271
|
+
if (v === null || typeof v !== 'object' || seen.has(v)) return null;
|
|
272
|
+
seen.add(v);
|
|
273
|
+
const list = Array.isArray(v);
|
|
274
|
+
for (const k of Object.keys(v)) {
|
|
275
|
+
const bad = badNumberAt(v[k], list ? `${path}[${k}]` : path ? `${path}.${k}` : k, seen);
|
|
276
|
+
if (bad) return bad;
|
|
199
277
|
}
|
|
200
|
-
|
|
278
|
+
return null;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* What a part's save() gave, once it passed what a save can hold; throws save-part-threw otherwise. Everything that keeps a part's data goes through here, so no path turns a number into null.
|
|
283
|
+
* @param {string} k
|
|
284
|
+
* @param {{ save(): any }} p
|
|
285
|
+
* @returns {any}
|
|
286
|
+
* @internal
|
|
287
|
+
*/
|
|
288
|
+
export function partData(k, p) {
|
|
289
|
+
const d = p.save();
|
|
290
|
+
// what JSON turns into null (read back as damage, so the whole save would never load again) or drops is not save data
|
|
291
|
+
if (typeof d === 'function' || typeof d === 'symbol' || (typeof d === 'number' && !Number.isFinite(d))) throw codedError('save-part-threw', fmt(DEV_STRINGS.notData, { k, got: String(d) }));
|
|
292
|
+
// a whole save is not given up for a field: the slot keeps its last good save, by name, the way a part whose save() threw does. A silent null reads back as hp null, position null
|
|
293
|
+
const bad = badNumberAt(d);
|
|
294
|
+
if (bad) throw codedError('save-part-threw', fmt(DEV_STRINGS.notNumber, { k, ...bad }));
|
|
295
|
+
return d;
|
|
201
296
|
}
|
|
202
297
|
|
|
203
298
|
/** Collect every part: { data, failed: [[key, error]] }. Parts of the loaded save that no module owns are carried along. */
|
|
@@ -207,8 +302,11 @@ export function collectParts(s) {
|
|
|
207
302
|
for (const [k, p] of s.providers) {
|
|
208
303
|
// a part with nothing to save (save() returns null / undefined) is left out, so a null part in a save always means damage (readSave refuses it);
|
|
209
304
|
// loading a save without it keeps that part as it is (saves.load) or gives it its new-game state (session.load)
|
|
210
|
-
|
|
211
|
-
|
|
305
|
+
if (Object.hasOwn(f.parts, k)) continue; // data this part could not take when it joined (adoptPart): it rides along until a load replaces it
|
|
306
|
+
try {
|
|
307
|
+
const d = partData(k, p);
|
|
308
|
+
if (d == null) { delete data.parts[k]; delete data.versions[k]; } else { data.parts[k] = d; data.versions[k] = p.version; }
|
|
309
|
+
} catch (e) { failed.push([k, e]); delete data.parts[k]; delete data.versions[k]; }
|
|
212
310
|
}
|
|
213
311
|
return { data, failed };
|
|
214
312
|
}
|
package/core/saves/saveFiles.js
CHANGED
|
@@ -13,18 +13,21 @@ export const SAVE_STRINGS = {
|
|
|
13
13
|
'zh-CN': { 'saves.failed': '存档失败:{why}(之前的存档还在)', 'saves.badFile': '这不是有效的存档文件', 'saves.imported': '存档已导入到「{slot}」', 'saves.noSlot': '没有可导出的存档',
|
|
14
14
|
'saves.tooNew': '这个存档来自更新版本的游戏,无法读取(存档没有改动)', 'saves.corrupt': '这个存档已损坏,无法读取(存档没有改动)',
|
|
15
15
|
'saves.migrate': '这个存档的版本无法升级,无法读取(存档没有改动)',
|
|
16
|
-
'saves.otherTab': '没有存档:另一个标签页刚存过「{slot}」,为了不覆盖那边更新的进度,这里没有写入。读取它继续,或存到别的位置'
|
|
16
|
+
'saves.otherTab': '没有存档:另一个标签页刚存过「{slot}」,为了不覆盖那边更新的进度,这里没有写入。读取它继续,或存到别的位置',
|
|
17
|
+
'saves.otherTabKept': '没有删除:另一个标签页刚存过「{slot}」,那边更新的进度保留了' },
|
|
17
18
|
en: { 'saves.failed': 'Save failed: {why} (the previous save is kept)', 'saves.badFile': 'This is not a valid save file',
|
|
18
19
|
'saves.imported': 'Save imported into "{slot}"', 'saves.noSlot': 'Nothing to export',
|
|
19
20
|
'saves.tooNew': 'This save is from a newer version of the game and cannot be loaded (the save is unchanged)',
|
|
20
21
|
'saves.corrupt': 'This save is damaged and cannot be loaded (the save is unchanged)',
|
|
21
22
|
'saves.migrate': 'This save\'s version cannot be upgraded, so it cannot be loaded (the save is unchanged)',
|
|
22
|
-
'saves.otherTab': 'Not saved: another tab just saved "{slot}", so this one did not overwrite that newer progress. Load it to continue, or save to another slot'
|
|
23
|
+
'saves.otherTab': 'Not saved: another tab just saved "{slot}", so this one did not overwrite that newer progress. Load it to continue, or save to another slot',
|
|
24
|
+
'saves.otherTabKept': 'Not deleted: another tab just saved "{slot}", so that newer progress was kept' },
|
|
23
25
|
};
|
|
24
26
|
const MAX_BYTES = 512 * 1024 * 1024; // a bigger "save" is not one of ours; reading it would stall the tab
|
|
25
27
|
const STRINGS = {
|
|
26
28
|
badText: '[saves] import(text): not a save ({why}); nothing was imported',
|
|
27
29
|
bad: '[saves] importFile: not a save file ({why}); nothing was imported',
|
|
30
|
+
damaged: "[saves] exportFile: attachment '{g}/{id}' holds no data and was left out of the file",
|
|
28
31
|
attachment: '[saves] importFile: attachment {i} is not a data: URL with a string group and id; nothing was imported',
|
|
29
32
|
};
|
|
30
33
|
|
|
@@ -54,7 +57,13 @@ export async function exportSaveFile(s, slot, { files = true } = {}) {
|
|
|
54
57
|
if (!json) { toast(s.engine, s.engine.t('saves.noSlot'), { kind: 'save' }); return false; }
|
|
55
58
|
await s.flush(); // wait for freshly saved attachments to finish writing
|
|
56
59
|
const list = [];
|
|
57
|
-
|
|
60
|
+
try {
|
|
61
|
+
if (files) for (const b of await s.store.blobs()) {
|
|
62
|
+
// a row damaged outside the engine must not cost the player the whole backup
|
|
63
|
+
if (b.blob instanceof Blob) list.push({ group: b.group, id: b.id, at: b.at, meta: b.meta, type: b.blob.type, url: await toDataURL(b.blob) });
|
|
64
|
+
else warnOnce(coded('save-write', fmt(STRINGS.damaged, { g: b.group, id: b.id })));
|
|
65
|
+
}
|
|
66
|
+
} catch (e) { s._fail(e ?? new Error('attachment unreadable'), slot); return false; }
|
|
58
67
|
// splice the world save's JSON text in directly instead of parsing it again (halves memory at tens of MB)
|
|
59
68
|
const head = `{"threedog":"save","format":${FILE_FORMAT},"game":${JSON.stringify(s._prefix)},"slot":${JSON.stringify(slot)},"savedAt":${JSON.stringify(s._meta.get(slot) ?? 0)},"data":`;
|
|
60
69
|
const blob = new Blob([head, json, ',"files":', JSON.stringify(list), '}'], { type: 'application/json' });
|
|
@@ -88,13 +97,12 @@ export async function importSaveFile(s, file, slot = 'imported') {
|
|
|
88
97
|
if (!blob) return refuse(fmt(STRINGS.attachment, { i: String(i) }));
|
|
89
98
|
blobs.push([p, blob]);
|
|
90
99
|
}
|
|
91
|
-
const
|
|
92
|
-
if (
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
if (!ok) return null;
|
|
100
|
+
const bad = saveProblem(s, obj.data, slot);
|
|
101
|
+
if (bad) return refuse(fmt(STRINGS.bad, { why: bad }));
|
|
102
|
+
// attachments first and all at once: a failed write then leaves nothing, and only a stored file reaches the list
|
|
103
|
+
const rows = blobs.map(([p, blob]) => ({ group: p.group, id: p.id, blob, meta: p.meta ?? null, at: Number.isFinite(p.at) ? p.at : Date.now() })); // wall-clock: ordering, as putBlob
|
|
104
|
+
try { await s._enqueue(() => s.store.putBlobs(rows)); } catch (e) { s._fail(e); return null; }
|
|
105
|
+
if (!(await putImported(s, obj.data, slot))) return null; // a failed write already showed its toast
|
|
98
106
|
s.engine.events.emit('save:imported', slot);
|
|
99
107
|
toast(s.engine, s.engine.t('saves.imported', { slot }), { kind: 'save' });
|
|
100
108
|
return slot;
|
|
@@ -111,24 +119,21 @@ export async function importSaveFile(s, file, slot = 'imported') {
|
|
|
111
119
|
export async function importText(s, text, slot) {
|
|
112
120
|
let obj;
|
|
113
121
|
try { obj = JSON.parse(decodeURIComponent(escape(atob(String(text).trim())))); } catch (e) { warnOnce(coded('save-import', fmt(STRINGS.badText, { why: e.message }))); return false; }
|
|
114
|
-
const
|
|
115
|
-
if (
|
|
116
|
-
if (
|
|
117
|
-
|
|
122
|
+
const bad = saveProblem(s, obj, slot);
|
|
123
|
+
if (bad) { warnOnce(coded('save-import', fmt(STRINGS.badText, { why: bad }))); return false; }
|
|
124
|
+
if (!(await putImported(s, obj, slot))) return false; // a failed write already showed its toast
|
|
125
|
+
s.engine.events.emit('save:imported', slot);
|
|
126
|
+
return true;
|
|
118
127
|
}
|
|
119
|
-
/**
|
|
120
|
-
|
|
121
|
-
* @param {any} s the Saves instance
|
|
122
|
-
* @param {any} obj
|
|
123
|
-
* @param {string} slot
|
|
124
|
-
* @returns {Promise<true | string>}
|
|
125
|
-
* @internal
|
|
126
|
-
*/
|
|
127
|
-
async function importData(s, obj, slot) {
|
|
128
|
+
/** Why an imported save object is not one (checked like a load), or null. Too new / unmigratable saves are kept: a newer build can load them @internal */
|
|
129
|
+
function saveProblem(s, obj, slot) {
|
|
128
130
|
const r = readSave(obj, s.providers, slot);
|
|
129
|
-
|
|
131
|
+
return r.reason === 'corrupt' || r.reason === 'missing' ? r.dev : null;
|
|
132
|
+
}
|
|
133
|
+
/** Store a checked save object; false when the write failed. savedAt comes from outside: list() sorts by it @internal */
|
|
134
|
+
function putImported(s, obj, slot) {
|
|
130
135
|
const data = parseSave(obj);
|
|
131
|
-
return
|
|
136
|
+
return s._put(slot, JSON.stringify(data), Number.isFinite(data.savedAt) ? data.savedAt : 0);
|
|
132
137
|
}
|
|
133
138
|
|
|
134
139
|
/** Open a file picker; null when cancelled */
|
|
@@ -29,7 +29,7 @@ const DEV = {
|
|
|
29
29
|
export function checkPartVersion(key, version, migrate) {
|
|
30
30
|
if (!Number.isInteger(version) || version < 1) throw codedError('save-version', fmt(DEV.badVersion, { k: key, v: version }));
|
|
31
31
|
for (const [m, fn] of Object.entries(migrate)) {
|
|
32
|
-
if (
|
|
32
|
+
if (!/^[1-9]\d*$/.test(m) || Number(m) >= version || typeof fn !== 'function') throw codedError('save-version', fmt(DEV.badMigrate, { k: key, m, v: version }));
|
|
33
33
|
}
|
|
34
34
|
}
|
|
35
35
|
|
|
@@ -44,6 +44,15 @@ const clean = (k, v) => (k === '__proto__' ? undefined : v);
|
|
|
44
44
|
*/
|
|
45
45
|
export function parseSave(json) { return JSON.parse(typeof json === 'string' ? json : JSON.stringify(json), clean); }
|
|
46
46
|
|
|
47
|
+
/**
|
|
48
|
+
* A part's saved version; one the table does not have is version 1. Part names are the game's: 'constructor' finds Object's own in a plain lookup, as `in` does on parts.
|
|
49
|
+
* @param {Record<string, number> | undefined} versions
|
|
50
|
+
* @param {string} k
|
|
51
|
+
* @returns {number}
|
|
52
|
+
* @internal
|
|
53
|
+
*/
|
|
54
|
+
export function partVersion(versions, k) { return versions && Object.hasOwn(versions, k) ? versions[k] : 1; }
|
|
55
|
+
|
|
47
56
|
/**
|
|
48
57
|
* Upgrade one part's data from its saved version to the current one, step by step (on a copy: the caller's save stays as it was).
|
|
49
58
|
* @param {string} key
|
|
@@ -90,12 +99,17 @@ export function readSave(json, providers, slot) {
|
|
|
90
99
|
// (collectParts leaves out a part whose save() returns null / undefined), so only a hand edit or a broken file has it
|
|
91
100
|
const nul = Object.keys(data.parts).filter(k => data.parts[k] === null);
|
|
92
101
|
if (nul.length) return { reason: 'corrupt', dev: fmt(DEV.corrupt, { slot, why: `part${nul.length > 1 ? 's' : ''} ${nul.map(k => `'${k}'`).join(', ')} is null` }) };
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
const
|
|
102
|
+
// versions decide which migrate steps run: a value that is no whole number passes every comparison, so no step ran and load() got the old shape. Parts nobody owns here
|
|
103
|
+
// count too: a part registered later reads its version from this table. Only a missing table means version 1
|
|
104
|
+
const versions = data.versions === undefined ? (data.versions = {}) : data.versions;
|
|
105
|
+
if (!versions || typeof versions !== 'object' || Array.isArray(versions)) return { reason: 'corrupt', dev: fmt(DEV.corrupt, { slot, why: `versions ${JSON.stringify(versions)}` }) };
|
|
106
|
+
const odd = Object.keys(versions).filter(k => !Number.isInteger(versions[k]) || versions[k] < 1);
|
|
107
|
+
if (odd.length) return { reason: 'corrupt', dev: fmt(DEV.corrupt, { slot, why: `version of ${odd.map(k => `'${k}'`).join(', ')}` }) };
|
|
108
|
+
const list = [...providers].filter(([k]) => Object.hasOwn(data.parts, k)).sort((a, b) => (b[1].first ? 1 : 0) - (a[1].first ? 1 : 0));
|
|
109
|
+
const newer = list.filter(([k, p]) => partVersion(versions, k) > p.version).map(([k, p]) => `part '${k}' is version ${versions[k]}, this build reads up to ${p.version}`);
|
|
96
110
|
if (newer.length) return { reason: 'tooNew', dev: fmt(DEV.tooNew, { list: newer.join('; ') }) };
|
|
97
111
|
// whole: the save as read, for migrate steps that need another part (upgradePart); kept on foreign so a part registered later (adoptPart) sees it too
|
|
98
112
|
const whole = { parts: data.parts, versions }, foreign = { parts: {}, versions: {}, whole };
|
|
99
|
-
for (const k of Object.keys(data.parts)) if (!providers.has(k)) { foreign.parts[k] = data.parts[k]; foreign.versions[k] = versions
|
|
100
|
-
try { return { data, foreign, list: list.map(([k, p]) => [k, p, upgradePart(k, p, data.parts[k], versions
|
|
113
|
+
for (const k of Object.keys(data.parts)) if (!providers.has(k)) { foreign.parts[k] = data.parts[k]; foreign.versions[k] = partVersion(versions, k); }
|
|
114
|
+
try { return { data, foreign, list: list.map(([k, p]) => [k, p, upgradePart(k, p, data.parts[k], partVersion(versions, k), whole)]) }; } catch (e) { return { reason: 'migrate', dev: e.message }; }
|
|
101
115
|
}
|