threedog 0.7.0 → 0.8.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/CHANGELOG.md +196 -1
- package/README.md +6 -9
- package/core/{Animator.js → assets/Animator.js} +28 -18
- package/core/{Assets.js → assets/Assets.js} +98 -54
- package/core/{Baked.js → assets/Baked.js} +4 -4
- package/core/assets/assetEntry.js +237 -0
- package/core/{assetHot.js → assets/assetHot.js} +7 -6
- package/core/{assetLoad.js → assets/assetLoad.js} +55 -16
- package/core/assets/assetLod.js +113 -0
- package/core/{assetManifest.js → assets/assetManifest.js} +19 -11
- package/core/{assetReport.js → assets/assetReport.js} +6 -12
- package/core/{namedModel.js → assets/namedModel.js} +17 -13
- package/core/{Audio.js → audio/Audio.js} +26 -23
- package/core/{audioRules.js → audio/audioRules.js} +8 -5
- package/core/{audioVoice.js → audio/audioVoice.js} +17 -30
- package/core/{Events.js → base/Events.js} +3 -3
- package/core/{I18n.js → base/I18n.js} +10 -10
- package/core/{Random.js → base/Random.js} +5 -4
- package/core/{easing.js → base/easing.js} +1 -1
- package/core/{errorCodes.js → base/errorCodes.js} +98 -110
- package/core/{errorHints.js → base/errorHints.js} +5 -9
- package/core/{errors.js → base/errors.js} +6 -6
- package/core/{events.generated.js → base/events.generated.js} +1 -0
- package/core/{math.js → base/math.js} +15 -4
- package/core/{params.js → base/params.js} +3 -4
- package/core/base/util.js +32 -0
- package/core/{validate.js → base/validate.js} +28 -7
- package/core/{Engine.js → engine/Engine.js} +80 -77
- package/core/{Loading.js → engine/Loading.js} +4 -2
- package/core/{copies.js → engine/copies.js} +4 -4
- package/core/{headlessLoad.js → engine/headlessLoad.js} +4 -4
- package/core/{lifecycle.js → engine/lifecycle.js} +14 -12
- package/core/{loop.js → engine/loop.js} +68 -47
- package/core/{moduleSlots.js → engine/moduleSlots.js} +6 -6
- package/core/{moduleTypes.js → engine/moduleTypes.js} +13 -14
- package/core/{modules.js → engine/modules.js} +14 -11
- package/core/{page.js → engine/page.js} +36 -23
- package/core/{plugins.js → engine/plugins.js} +6 -9
- package/core/{services.js → engine/services.js} +47 -40
- package/core/{startup.js → engine/startup.js} +26 -24
- package/core/{Input.js → input/Input.js} +30 -22
- package/core/{inputContext.js → input/inputContext.js} +14 -5
- package/core/{inputPad.js → input/inputPad.js} +1 -1
- package/core/{inputPointer.js → input/inputPointer.js} +8 -2
- package/core/{inputTouch.js → input/inputTouch.js} +1 -1
- package/core/{Budget.js → inspect/Budget.js} +21 -20
- package/core/{DebugOverrides.js → inspect/DebugOverrides.js} +30 -16
- package/core/{Describe.js → inspect/Describe.js} +26 -22
- package/core/{Inspect.js → inspect/Inspect.js} +9 -7
- package/core/{InspectMaterials.js → inspect/InspectMaterials.js} +7 -8
- package/core/{InspectPerf.js → inspect/InspectPerf.js} +19 -13
- package/core/{InspectScene.js → inspect/InspectScene.js} +8 -5
- package/core/{MaterialInfo.js → inspect/MaterialInfo.js} +3 -2
- package/core/{UrlState.js → inspect/UrlState.js} +52 -20
- package/core/{catalog.js → inspect/catalog.js} +3 -3
- package/core/{checks.js → inspect/checks.js} +7 -5
- package/core/{debugView.js → inspect/debugView.js} +4 -4
- package/core/{describeRender.js → inspect/describeRender.js} +21 -20
- package/core/{describeText.js → inspect/describeText.js} +11 -6
- package/core/inspect/geometryWatch.js +38 -0
- package/core/{lightWatch.js → inspect/lightWatch.js} +8 -8
- package/core/{pictureWriters.js → inspect/pictureWriters.js} +15 -16
- package/core/{shaderCost.js → inspect/shaderCost.js} +1 -1
- package/core/{Ops.js → ops/Ops.js} +16 -11
- package/core/{control.js → ops/control.js} +13 -12
- package/core/ops/holds.js +139 -0
- package/core/{opsAtomic.js → ops/opsAtomic.js} +2 -1
- package/core/{opsCheck.js → ops/opsCheck.js} +4 -5
- package/core/{opsGuard.js → ops/opsGuard.js} +3 -3
- package/core/{opsRun.js → ops/opsRun.js} +7 -4
- package/core/{owned.js → ops/owned.js} +14 -17
- package/core/{sharedPoint.js → ops/sharedPoint.js} +8 -8
- package/core/{stackFrames.js → ops/stackFrames.js} +2 -2
- package/core/{stacks.js → ops/stacks.js} +12 -14
- package/core/{wrap.js → ops/wrap.js} +8 -6
- package/core/{SaveStore.js → saves/SaveStore.js} +1 -1
- package/core/{Saves.js → saves/Saves.js} +58 -36
- package/core/{saveApply.js → saves/saveApply.js} +13 -9
- package/core/{saveFiles.js → saves/saveFiles.js} +17 -15
- package/core/{saveValues.js → saves/saveValues.js} +20 -3
- package/core/{saveVersions.js → saves/saveVersions.js} +4 -17
- package/core/{session.js → saves/session.js} +31 -17
- package/core/{Rays.js → scene/Rays.js} +23 -25
- package/core/{Views.js → scene/Views.js} +14 -6
- package/core/{adaptive.js → scene/adaptive.js} +15 -8
- package/core/{canvasBox.js → scene/canvasBox.js} +2 -3
- package/core/{engineCamera.js → scene/engineCamera.js} +1 -1
- package/core/{gameLights.js → scene/gameLights.js} +17 -7
- package/core/{grayMap.js → scene/grayMap.js} +8 -2
- package/core/{grid.js → scene/grid.js} +4 -4
- package/core/{gridLoad.js → scene/gridLoad.js} +1 -1
- package/core/{ground.js → scene/ground.js} +9 -9
- package/core/{movement.js → scene/movement.js} +3 -3
- package/core/{pictureSlots.js → scene/pictureSlots.js} +2 -2
- package/core/{sceneDelta.js → scene/sceneDelta.js} +2 -2
- package/core/{sceneMethods.js → scene/sceneMethods.js} +36 -13
- package/core/scene/stepPoses.js +55 -0
- package/core/{targeting.js → scene/targeting.js} +4 -5
- package/core/{thingExplain.js → scene/thingExplain.js} +6 -5
- package/core/{thingOps.js → scene/thingOps.js} +4 -3
- package/core/{things.js → scene/things.js} +18 -5
- package/core/{threePatches.js → scene/threePatches.js} +1 -1
- package/core/{view.js → scene/view.js} +17 -16
- package/core/{Batching.js → stream/Batching.js} +85 -27
- package/core/{Stream.js → stream/Stream.js} +60 -30
- package/core/{batchGroups.js → stream/batchGroups.js} +10 -9
- package/core/{chunkStream.js → stream/chunkStream.js} +40 -0
- package/core/{scatter.js → stream/scatter.js} +2 -2
- package/core/{streamSources.js → stream/streamSources.js} +12 -7
- package/core/{Commits.js → threads/Commits.js} +6 -5
- package/core/{Jobs.js → threads/Jobs.js} +12 -10
- package/core/{Threads.js → threads/Threads.js} +16 -16
- package/core/{threadPure.js → threads/threadPure.js} +7 -5
- package/core/{threadServe.js → threads/threadServe.js} +3 -3
- package/core/{Clock.js → time/Clock.js} +17 -10
- package/core/{dayTime.js → time/dayTime.js} +5 -1
- package/core/{skip.js → time/skip.js} +18 -17
- package/core/{time.js → time/time.js} +18 -12
- package/core/{uiClock.js → time/uiClock.js} +4 -4
- package/docs/AI.md +22 -19
- package/docs/API.md +24 -23
- package/docs/CODEMAP.md +76 -183
- package/docs/COMMANDS.md +66 -58
- package/docs/CONVENTIONS.md +54 -14
- package/docs/MIGRATING-0.8.md +169 -0
- package/docs/THREE.md +78 -29
- package/docs/api/assets.md +12 -13
- package/docs/api/audio.md +6 -5
- package/docs/api/budget.md +4 -4
- package/docs/api/calendar.md +10 -11
- package/docs/api/cameraRig.md +29 -29
- package/docs/api/characters.md +23 -18
- package/docs/api/clock.md +1 -1
- package/docs/api/collision.md +12 -9
- package/docs/api/content.md +6 -6
- package/docs/api/dialogue.md +3 -3
- package/docs/api/engine.md +45 -43
- package/docs/api/events.md +3 -2
- package/docs/api/flow.md +1 -1
- package/docs/api/grids.md +1 -1
- package/docs/api/ground.md +4 -5
- package/docs/api/hud.md +2 -2
- package/docs/api/i18n.md +6 -6
- package/docs/api/input.md +7 -7
- package/docs/api/interactions.md +4 -4
- package/docs/api/inventory.md +9 -9
- package/docs/api/jobs.md +5 -5
- package/docs/api/level.md +7 -7
- package/docs/api/lightPool.md +1 -6
- package/docs/api/music.md +3 -3
- package/docs/api/nav.md +10 -10
- package/docs/api/openWorld.md +1 -1
- package/docs/api/particles.md +2 -2
- package/docs/api/photo.md +4 -2
- package/docs/api/pickups.md +2 -2
- package/docs/api/post.md +20 -3
- package/docs/api/quests.md +3 -3
- package/docs/api/rays.md +5 -7
- package/docs/api/rigid.md +27 -18
- package/docs/api/saves.md +8 -7
- package/docs/api/settings.md +9 -8
- package/docs/api/sky.md +8 -7
- package/docs/api/stream.md +7 -7
- package/docs/api/swarm.md +34 -0
- package/docs/api/terrain.md +7 -8
- package/docs/api/terrainDraw.md +1 -1
- package/docs/api/timeline.md +2 -2
- package/docs/api/tools.md +25 -22
- package/docs/api/vars.md +1 -1
- package/docs/api/vegetation.md +4 -3
- package/docs/api/vegetationDraw.md +1 -1
- package/docs/api/water.md +1 -1
- package/docs/api/weather.md +9 -9
- package/docs/api/weatherDraw.md +3 -3
- package/docs/api/world.md +5 -5
- package/docs/recipes/01-new-game.md +25 -40
- package/docs/recipes/02-npc.md +19 -20
- package/docs/recipes/03-items-pickups.md +27 -43
- package/docs/recipes/04-quests.md +3 -4
- package/docs/recipes/05-props-bake.md +29 -39
- package/docs/recipes/06-clock-events.md +27 -18
- package/docs/recipes/07-flow-scenes-pause.md +12 -17
- package/docs/recipes/08-weather-sky.md +88 -34
- package/docs/recipes/09-materials-lights-models.md +22 -36
- package/docs/recipes/10-blender-level.md +6 -7
- package/docs/recipes/11-vehicles.md +30 -22
- package/docs/recipes/12-navmesh.md +9 -8
- package/docs/recipes/13-animation.md +39 -17
- package/docs/recipes/14-custom-module.md +14 -13
- package/docs/recipes/15-perf.md +49 -26
- package/docs/recipes/16-dev-bridge.md +32 -52
- package/docs/recipes/18-world.md +36 -23
- package/docs/recipes/19-shooting-picking.md +4 -2
- package/docs/recipes/20-content-actions-save.md +30 -35
- package/docs/recipes/21-camera.md +33 -5
- package/docs/recipes/22-shop-gold.md +0 -4
- package/docs/recipes/23-ops.md +10 -10
- package/docs/recipes/26-ui-parts.md +22 -12
- package/docs/recipes/27-net.md +0 -2
- package/docs/recipes/28-terrain.md +117 -21
- package/docs/recipes/29-grid.md +2 -2
- package/docs/recipes/30-templates.md +55 -19
- package/docs/recipes/31-audio.md +5 -5
- package/docs/recipes/32-action-game.md +15 -6
- package/docs/recipes/33-stream-sources.md +2 -2
- package/docs/recipes/34-environment-lighting.md +67 -19
- package/docs/recipes/35-picture-from-reference.md +10 -17
- package/docs/recipes/36-ground-plants.md +105 -0
- package/docs/recipes/40-scene.md +7 -11
- package/docs/recipes/43-shader-patches-surfaces.md +20 -41
- package/docs/recipes/44-water-weather-hooks.md +48 -43
- package/docs/recipes/45-cascaded-shadows.md +39 -17
- package/docs/recipes/46-blender-art-route.md +7 -8
- package/docs/recipes/49-game-module-contract.md +5 -5
- package/docs/recipes/50-own-renderer.md +2 -2
- package/docs/recipes/52-around-the-picture.md +54 -98
- package/docs/recipes/53-ground-up-close.md +61 -24
- package/docs/recipes/55-mods-time-wrap.md +12 -16
- package/docs/recipes/56-webgpu-tsl.md +16 -14
- package/docs/recipes/57-control.md +9 -2
- package/docs/recipes/58-input.md +2 -2
- package/docs/recipes/59-depth-post-effects.md +1 -1
- package/docs/recipes/60-judge-the-picture.md +29 -24
- package/docs/recipes/62-picture-code.md +49 -17
- package/docs/recipes/63-third-person-start.md +17 -4
- package/docs/recipes/64-particles.md +1 -1
- package/docs/recipes/65-swarm.md +140 -0
- package/examples/action/.threedog/content-index.json +1 -1
- package/examples/action/GAMEMAP.md +2 -2
- package/examples/{sheepisland → perf-island}/.threedog/content-index.json +1 -1
- package/examples/{sheepisland → perf-island}/GAMEMAP.md +12 -11
- package/examples/{sheepisland → perf-island}/assets.js +1 -1
- package/examples/{sheepisland → perf-island}/main.js +8 -8
- package/examples/{sheepisland → perf-island}/models.js +1 -1
- package/examples/{sheepisland → perf-island}/params.js +1 -1
- package/examples/{sheepisland → perf-island}/picture/index.js +1 -1
- package/examples/{sheepisland → perf-island}/picture/palette.js +2 -2
- package/examples/{sheepisland → perf-island}/views.js +1 -1
- package/examples/plain-picture/GAMEMAP.md +1 -0
- package/examples/rc2d/GAMEMAP.md +3 -2
- package/examples/rc2d/main.js +1 -3
- package/examples/styletest/.threedog/content-index.json +1 -1
- package/examples/styletest/GAMEMAP.md +3 -2
- package/examples/techniques/contact-shadows/contactShadows.js +1 -1
- package/examples/techniques/contact-shadows/main.js +1 -1
- package/examples/techniques/interior-light/main.js +1 -1
- package/examples/techniques/modular-building/README.md +7 -6
- package/examples/techniques/outlines-and-rim/picture/post.js +1 -1
- package/examples/techniques/procedural-animation/README.md +1 -1
- package/examples/webgpu-tsl/GAMEMAP.md +1 -0
- package/examples/world/.threedog/content-index.json +1 -1
- package/examples/world/GAMEMAP.md +4 -3
- package/examples/world/picture/sky.js +1 -1
- package/index.d.ts +8 -7
- package/index.js +31 -31
- package/llms.txt +9 -13
- package/modules/ambience/Ambience.js +11 -8
- package/modules/calendar/Calendar.js +19 -19
- package/modules/calendar/index.js +13 -13
- package/modules/calendar/schedule.js +11 -6
- package/modules/calendar/seasons.js +7 -7
- package/modules/camera/FirstPersonCamera.js +2 -2
- package/modules/camera/FixedCamera.js +14 -15
- package/modules/camera/FollowCamera.js +4 -4
- package/modules/camera/RtsCamera.js +11 -11
- package/modules/camera/common.js +48 -24
- package/modules/camera/contract.js +1 -0
- package/modules/camera/projection.js +2 -2
- package/modules/characters/Character.js +33 -30
- package/modules/characters/NPC.js +27 -19
- package/modules/characters/assetModel.js +14 -10
- package/modules/characters/astar.js +7 -5
- package/modules/characters/behaviors.js +4 -5
- package/modules/characters/contract.js +2 -2
- package/modules/characters/index.js +168 -214
- package/modules/characters/moveHelpers.js +14 -3
- package/modules/characters/movers/common.js +16 -14
- package/modules/characters/movers/manual.js +1 -1
- package/modules/characters/movers/rapier.js +7 -6
- package/modules/characters/movers/simple.js +3 -3
- package/modules/characters/movers/support.js +8 -8
- package/modules/characters/npcAvoid.js +4 -4
- package/modules/characters/npcSim.js +23 -17
- package/modules/characters/npcView.js +6 -5
- package/modules/characters/pathAsync.js +12 -10
- package/modules/characters/pathWorker.js +1 -1
- package/modules/characters/player.js +108 -0
- package/modules/characters/playerStrings.js +2 -2
- package/modules/characters/proceduralRig.js +2 -2
- package/modules/characters/useModel.js +3 -3
- package/modules/characters/walkTo.js +11 -17
- package/modules/collision/Collision.js +26 -20
- package/modules/collision/contract.js +15 -0
- package/modules/content/explain.js +1 -2
- package/modules/content/fields.js +24 -3
- package/modules/content/ids.js +2 -2
- package/modules/content/index.js +61 -99
- package/modules/content/loader.js +14 -17
- package/modules/content/markers.js +25 -0
- package/modules/content/models.js +10 -7
- package/modules/content/packs.js +3 -3
- package/modules/content/parts.js +2 -2
- package/modules/content/places.js +35 -0
- package/modules/content/props.js +17 -14
- package/modules/content/rules.js +25 -21
- package/modules/content/stages.js +7 -7
- package/modules/content/templates.js +20 -20
- package/modules/content/words.js +34 -0
- package/modules/debug/DebugPanel.js +10 -43
- package/modules/flow/contract.js +1 -1
- package/modules/flow/index.js +11 -7
- package/modules/gameplay/Container.js +12 -11
- package/modules/gameplay/Containers.js +14 -5
- package/modules/gameplay/Dialogue.js +13 -11
- package/modules/gameplay/Interactions.js +37 -24
- package/modules/gameplay/Inventory.js +8 -9
- package/modules/gameplay/Quests.js +16 -9
- package/modules/gameplay/boxOps.js +1 -1
- package/modules/gameplay/dialogueBubbles.js +3 -4
- package/modules/gameplay/inventoryOps.js +0 -1
- package/modules/gameplay/pickups.js +22 -23
- package/modules/gameplay/questSave.js +3 -3
- package/modules/grid/Grid.js +1 -1
- package/modules/grid/Layer.js +4 -4
- package/modules/grid/index.js +7 -8
- package/modules/grid/preview.js +7 -7
- package/modules/grid/tiles.js +6 -6
- package/modules/hlod/index.js +37 -55
- package/modules/hud/index.js +17 -11
- package/modules/hud/parts.js +4 -4
- package/modules/level/contract.js +16 -0
- package/modules/level/heightfield.js +12 -10
- package/modules/level/index.js +47 -152
- package/modules/level/load.js +79 -0
- package/modules/level/meshes.js +65 -0
- package/modules/level/nodes.js +6 -7
- package/modules/lights/index.js +28 -181
- package/modules/lights/slots.js +93 -0
- package/modules/lights/sources.js +88 -0
- package/modules/music/Music.js +30 -26
- package/modules/music/rules.js +1 -1
- package/modules/nav/contract.js +14 -0
- package/modules/nav/index.js +11 -10
- package/modules/net/Client.js +7 -7
- package/modules/net/Host.js +7 -7
- package/modules/net/Net.js +1 -1
- package/modules/net/index.js +5 -4
- package/modules/net/sync.js +2 -2
- package/modules/net/transports.js +2 -2
- package/modules/particles/Particles.js +11 -8
- package/modules/particles/effect.js +7 -5
- package/modules/particles/shaders.js +2 -1
- package/modules/photo/Photo.js +15 -17
- package/modules/rigid/RigidBodies.js +66 -43
- package/modules/rigid/Vehicles.js +2 -3
- package/modules/rigid/ragdoll.js +287 -0
- package/modules/rigid/ragdollBones.js +159 -0
- package/modules/rigid/sync.js +6 -6
- package/modules/settings/Settings.js +108 -39
- package/modules/settings/apply.js +6 -6
- package/modules/settings/sections.js +16 -14
- package/modules/settings/view.js +3 -3
- package/modules/sky/Sky.js +29 -22
- package/modules/sky/clouds.js +7 -7
- package/modules/sky/dome.js +33 -20
- package/modules/sky/domeLayers.js +9 -9
- package/modules/sky/environment.js +6 -6
- package/modules/sky/frame.js +19 -10
- package/modules/sky/season.js +7 -1
- package/modules/sky/shader.js +24 -25
- package/modules/sky/skyModule.js +14 -27
- package/modules/sky/tint.js +1 -1
- package/modules/swarm/Swarm.js +346 -0
- package/modules/swarm/draw.js +68 -0
- package/modules/swarm/grid.js +63 -0
- package/modules/terrain/ChunkManager.js +70 -52
- package/modules/terrain/chunkQueries.js +7 -24
- package/modules/terrain/chunkWorker.js +1 -1
- package/modules/terrain/draw.js +14 -11
- package/modules/terrain/index.js +28 -34
- package/modules/terrain/terrainColorMap.js +6 -3
- package/modules/terrain/terrainDefaults.js +2 -1
- package/modules/terrain/terrainEdit.js +32 -27
- package/modules/terrain/terrainGen.js +17 -12
- package/modules/terrain/terrainIsland.js +2 -2
- package/modules/terrain/terrainMesh.js +7 -6
- package/modules/terrain/terrainShape.js +8 -10
- package/modules/terrain/terrainShapeMain.js +3 -3
- package/modules/timeline/Timeline.js +27 -19
- package/modules/timeline/Tween.js +6 -6
- package/modules/timeline/shots.js +5 -7
- package/modules/triggers/index.js +9 -9
- package/modules/vegetation/Vegetation.js +30 -23
- package/modules/vegetation/densityMap.js +4 -7
- package/modules/vegetation/draw.js +23 -18
- package/modules/vegetation/groundChunks.js +11 -31
- package/modules/vegetation/index.js +8 -6
- package/modules/vegetation/modelGeometry.js +3 -6
- package/modules/vegetation/nearFade.js +1 -1
- package/modules/water/Water.js +16 -16
- package/modules/water/surface.js +3 -3
- package/modules/weather/Weather.js +41 -30
- package/modules/weather/particles.js +8 -8
- package/modules/weather/weatherDraw.js +22 -18
- package/modules/world/World.js +8 -8
- package/modules/world/explain.js +1 -1
- package/modules/world/index.js +18 -12
- package/modules/world/persist.js +73 -25
- package/modules/world/pos.js +4 -4
- package/modules/world/records.js +28 -8
- package/modules/world/sim.js +4 -4
- package/modules/world/state.js +12 -5
- package/modules/world/thingSource.js +4 -2
- package/modules/world/views.js +11 -9
- package/package.json +42 -7
- package/presets.js +1 -3
- package/render/PostFX.js +39 -27
- package/render/backend.js +26 -32
- package/render/cascades.js +17 -12
- package/render/cascades.tsl.js +5 -8
- package/render/daylight.js +20 -3
- package/render/detail.js +8 -7
- package/render/effects.js +28 -25
- package/render/fuse.js +3 -3
- package/render/fx/cloudShadow.tsl.js +3 -3
- package/render/fx/detail.tsl.js +1 -1
- package/render/fx/index.js +5 -10
- package/render/fx/library.tsl.js +11 -0
- package/render/fx/lighting.tsl.js +2 -1
- package/render/fx/nodeErrors.tsl.js +2 -2
- package/render/fx/objectOrigin.tsl.js +1 -2
- package/render/fx/patchNodes.tsl.js +5 -15
- package/render/fx/postWebGPU.tsl.js +27 -23
- package/render/fx/sky.tsl.js +15 -17
- package/render/fx/uniforms.tsl.js +4 -4
- package/render/fx/wind.tsl.js +1 -1
- package/render/fxNumbers.js +3 -0
- package/render/layers.js +1 -1
- package/render/lighting.js +5 -3
- package/render/lightmap.js +20 -20
- package/render/lights.js +6 -6
- package/render/lit.js +24 -0
- package/render/materials.js +8 -7
- package/render/mergeCommon.js +22 -0
- package/render/modeling.js +2 -2
- package/render/occlusion.js +20 -4
- package/render/ownFrame.js +4 -4
- package/render/patches.js +13 -13
- package/render/postWebGL.js +12 -10
- package/render/probes.js +16 -19
- package/render/recordSweep.js +117 -0
- package/render/shaderErrors.js +10 -9
- package/render/shadowCache.tsl.js +107 -0
- package/render/shadowTypes.js +9 -0
- package/{core → render}/shadows.js +57 -11
- package/render/slots.js +7 -7
- package/render/terms.js +22 -24
- package/render/uniformDecl.js +1 -1
- package/types/core.d.ts +200 -153
- package/types/gameplay.d.ts +163 -91
- package/types/generated/core/{Audio.d.ts → audio/Audio.d.ts} +22 -7
- package/types/generated/core/{audioVoice.d.ts → audio/audioVoice.d.ts} +2 -2
- package/types/generated/core/{Events.d.ts → base/Events.d.ts} +4 -4
- package/types/generated/core/{I18n.d.ts → base/I18n.d.ts} +7 -15
- package/types/generated/core/{Random.d.ts → base/Random.d.ts} +4 -3
- package/types/generated/core/{page.d.ts → engine/page.d.ts} +8 -9
- package/types/generated/core/{Input.d.ts → input/Input.d.ts} +12 -8
- package/types/generated/core/{Budget.d.ts → inspect/Budget.d.ts} +36 -26
- package/types/generated/core/{DebugOverrides.d.ts → inspect/DebugOverrides.d.ts} +2 -2
- package/types/generated/core/{Ops.d.ts → ops/Ops.d.ts} +4 -3
- package/types/generated/core/{control.d.ts → ops/control.d.ts} +4 -10
- package/types/generated/core/{Saves.d.ts → saves/Saves.d.ts} +37 -13
- package/types/generated/core/{session.d.ts → saves/session.d.ts} +2 -1
- package/types/generated/core/{Rays.d.ts → scene/Rays.d.ts} +8 -27
- package/types/generated/core/{Views.d.ts → scene/Views.d.ts} +1 -1
- package/types/generated/core/{Batching.d.ts → stream/Batching.d.ts} +7 -7
- package/types/generated/core/{Stream.d.ts → stream/Stream.d.ts} +18 -16
- package/types/generated/core/{Commits.d.ts → threads/Commits.d.ts} +1 -1
- package/types/generated/core/{Jobs.d.ts → threads/Jobs.d.ts} +6 -6
- package/types/generated/core/{Threads.d.ts → threads/Threads.d.ts} +4 -4
- package/types/generated/modules/calendar/Calendar.d.ts +10 -11
- package/types/generated/modules/debug/DebugPanel.d.ts +1 -9
- package/types/generated/modules/grid/Layer.d.ts +1 -1
- package/types/generated/modules/grid/index.d.ts +3 -3
- package/types/generated/modules/music/Music.d.ts +7 -5
- package/types/generated/modules/particles/Particles.d.ts +1 -1
- package/types/generated/modules/sky/Sky.d.ts +21 -10
- package/types/generated/modules/swarm/Swarm.d.ts +80 -0
- package/types/generated/modules/timeline/Timeline.d.ts +2 -1
- package/types/generated/modules/water/Water.d.ts +1 -0
- package/types/generated/modules/weather/Weather.d.ts +16 -12
- package/types/generated/modules/weather/weatherDraw.d.ts +3 -3
- package/types/generated/modules/world/World.d.ts +5 -3
- package/types/generated/render/PostFX.d.ts +17 -11
- package/types/generated/render/materials.d.ts +1 -0
- package/types/generated/render/occlusion.d.ts +9 -0
- package/types/generated/render/patches.d.ts +1 -0
- package/types/generated/ui/Focus.d.ts +1 -0
- package/types/generated/ui/UI.d.ts +1 -0
- package/types/nav.d.ts +11 -11
- package/types/physics.d.ts +99 -70
- package/types/tsl.d.ts +37 -4
- package/types/world.d.ts +38 -71
- package/ui/Focus.js +10 -9
- package/ui/Parts.js +4 -3
- package/ui/UI.js +7 -7
- package/ui/defaults.js +3 -2
- package/ui/theme.js +5 -3
- package/core/assetEntry.js +0 -109
- package/core/holds.js +0 -134
- package/core/shadowTypes.js +0 -16
- package/core/util.js +0 -17
- package/docs/MIGRATING-0.3.md +0 -248
- package/docs/MIGRATING-0.4.md +0 -320
- package/docs/MIGRATING-0.5.md +0 -68
- package/docs/MIGRATING-0.6.md +0 -126
- package/docs/PERF.md +0 -245
- package/docs/recipes/36-sky-ground-plants.md +0 -158
- package/docs/recipes/37-terrain-hooks.md +0 -115
- package/docs/recipes/38-environment-hooks.md +0 -67
- package/docs/recipes/42-terrain-shape.md +0 -64
- package/docs/recipes/47-island-snow-backdrop.md +0 -43
- package/docs/recipes/54-three-idioms.md +0 -88
- package/examples/plain-picture/FINDINGS.md +0 -53
- /package/core/{Vars.js → base/Vars.js} +0 -0
- /package/core/{mulberry32.js → base/mulberry32.js} +0 -0
- /package/core/{inputDefaults.js → input/inputDefaults.js} +0 -0
- /package/core/{textureBytes.js → inspect/textureBytes.js} +0 -0
- /package/core/{actor.js → ops/actor.js} +0 -0
- /package/core/{opsFail.js → ops/opsFail.js} +0 -0
- /package/core/{opsHistory.js → ops/opsHistory.js} +0 -0
- /package/core/{saveIds.js → saves/saveIds.js} +0 -0
- /package/core/{screenToGround.js → scene/screenToGround.js} +0 -0
- /package/core/{tier.js → scene/tier.js} +0 -0
- /package/core/{cells.js → stream/cells.js} +0 -0
- /package/core/{streamCells.js → stream/streamCells.js} +0 -0
- /package/core/{pureWorker.js → threads/pureWorker.js} +0 -0
- /package/examples/{sheepisland → perf-island}/content/index.js +0 -0
- /package/examples/{sheepisland → perf-island}/content/props.js +0 -0
- /package/examples/{sheepisland → perf-island}/content/templates.js +0 -0
- /package/examples/{sheepisland → perf-island}/content/vegetation.js +0 -0
- /package/examples/{sheepisland → perf-island}/picture/lights.js +0 -0
- /package/examples/{sheepisland → perf-island}/picture/materials.js +0 -0
- /package/examples/{sheepisland → perf-island}/picture/sky.js +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// One ownership model for every property the engine writes on its own (a sky's background, the shadow box's center, camera, pixel ratio ...).
|
|
2
2
|
//
|
|
3
3
|
// const o = defineOwned(engine, { id: 'view.far', part: 'view', key: 'far', read: () => camera.far, write: v => { camera.far = v; },
|
|
4
|
-
// levels: { manual: "engine.
|
|
4
|
+
// levels: { manual: "engine.autoView.manual('far')" } });
|
|
5
5
|
// per frame: o.check(); if (o.on) target.position.copy(focus); o.mark(); (or o.drive(v) when the write is one value: needs write)
|
|
6
6
|
//
|
|
7
7
|
// Why "the engine yields" (user decision 1, 2026-11-02): a game that writes sun.target.position directly means it. Silently writing the old value
|
|
@@ -9,10 +9,10 @@
|
|
|
9
9
|
// to the game (mode 'yielded'), the value stays, and one warning names the explicit takeover and the hand-back. Detection runs in release builds too
|
|
10
10
|
// (a few number compares per frame), so the game behaves the same with and without dev checks; only the warning text is dev-only.
|
|
11
11
|
//
|
|
12
|
-
// Modes per property: 'engine' (the engine writes it) | 'manual' (engine.
|
|
13
|
-
// (the game wrote it directly). engine.
|
|
14
|
-
import { warnOnce, DEV } from '
|
|
15
|
-
import { codedError, coded } from '
|
|
12
|
+
// Modes per property: 'engine' (the engine writes it) | 'manual' (engine.autoView.manual(key), or the entry that hands the value to the game) | 'yielded'
|
|
13
|
+
// (the game wrote it directly). engine.autoView.manual(key, false) hands any of them back. describe().owned lists them all.
|
|
14
|
+
import { warnOnce, DEV, fmt } from '../base/validate.js';
|
|
15
|
+
import { codedError, coded } from '../base/errorHints.js';
|
|
16
16
|
|
|
17
17
|
const STRINGS = { // yielded: the prefix up to "stopped writing it" is matched by tests (the owned-prop tag carries the fix); the rest leads with the next calls
|
|
18
18
|
yielded: '{id} was changed outside the engine, so the engine stopped writing it (your value stays). Next: {manual} to own it on purpose (no warning);{set} ' +
|
|
@@ -26,7 +26,7 @@ const exempt = new Map(); // owner -> Set of ids (strings) and objects
|
|
|
26
26
|
const live = new Set(); // every registered property on the page: ending an exemption re-reads the ones it covered
|
|
27
27
|
/**
|
|
28
28
|
* Exempt properties from outside-write detection while owner animates them (a timeline tweening a light): neither a warning nor a yield.
|
|
29
|
-
* @param {
|
|
29
|
+
* @param {any} owner a name or any unique key @param {Iterable<any> | false} [what] owned ids ('sun.intensity') or the three.js objects being animated; false ends it
|
|
30
30
|
*/
|
|
31
31
|
export function allowOwned(owner, what) {
|
|
32
32
|
if (what === false || what == null) {
|
|
@@ -58,8 +58,8 @@ class Owned {
|
|
|
58
58
|
/** who took it: 'game' (manual()), or 'three' for a direct write */ this.by = 'engine';
|
|
59
59
|
this._snap = null;
|
|
60
60
|
this._onChange = spec.onChange;
|
|
61
|
-
// once: the engine writes it
|
|
62
|
-
// nothing), and handing it back writes
|
|
61
|
+
// once: the engine never writes it, it only keeps the value read here (renderer.toneMapping). So a direct write is the documented way to change it (yielding warns
|
|
62
|
+
// nothing), and handing it back writes that value again (spec.write)
|
|
63
63
|
this._once = spec.once ? { value: this._read() } : null;
|
|
64
64
|
}
|
|
65
65
|
/** Does the engine write this property now */
|
|
@@ -72,8 +72,7 @@ class Owned {
|
|
|
72
72
|
this._set('yielded', 'three');
|
|
73
73
|
if (DEV && this._e.validate && !this._once) {
|
|
74
74
|
const L = this.levels, back = L.back ?? L.manual.replace(/\(([^()]*)\)\s*$/, (_, a) => `(${a ? a + ', ' : ''}false)`);
|
|
75
|
-
warnOnce(coded('owned-prop', STRINGS.yielded
|
|
76
|
-
.replace('{set}', L.set ? STRINGS.set.replace('{set}', L.set) : '').replace('{back}', back)));
|
|
75
|
+
warnOnce(coded('owned-prop', fmt(STRINGS.yielded, { id: this.id, manual: L.manual, set: L.set ? fmt(STRINGS.set, { set: L.set }) : '', back })));
|
|
77
76
|
}
|
|
78
77
|
}
|
|
79
78
|
/**
|
|
@@ -95,14 +94,14 @@ class Owned {
|
|
|
95
94
|
this.mode = mode; this.by = by; this.at = this._e.time?.frame ?? null;
|
|
96
95
|
if (was !== mode) this._onChange?.(this);
|
|
97
96
|
}
|
|
98
|
-
/** describe().owned row: writer = who writes it now ('engine' | 'manual:<who>' | 'three (engine yielded)')
|
|
97
|
+
/** describe().owned row: writer = who writes it now ('engine' | 'manual:<who>' | 'three (engine yielded)') */
|
|
99
98
|
info() {
|
|
100
99
|
return ({ part: this.part, key: this.key, writer: this.mode === 'engine' ? 'engine' : this.mode === 'yielded' ? 'three (engine yielded)' : `manual:${this.by}`, ...(this.levels.manual ? { manual: this.levels.manual } : {}) });
|
|
101
100
|
}
|
|
102
101
|
}
|
|
103
102
|
|
|
104
103
|
/**
|
|
105
|
-
*
|
|
104
|
+
* Values the engine only keeps and never writes (toneMapping) meet no engine write that would notice a takeover, so describe() looks before any section reads
|
|
106
105
|
* them. Why one place: the render section checked on its own, after the picture section had read the stale writer, and describe('owned') alone
|
|
107
106
|
* said 'engine' for a curve the game had set
|
|
108
107
|
* @param {any} engine @internal
|
|
@@ -114,7 +113,7 @@ export function checkWrittenOnce(engine) { for (const o of engine._owned?.values
|
|
|
114
113
|
* @param {any} engine
|
|
115
114
|
* @param {{ id: string, part: string, key?: string, read: () => any, write?: (v: any) => void, objects?: any[],
|
|
116
115
|
* levels: { manual: string, set?: string, back?: string }, onChange?: (o: Owned) => void, once?: boolean }} spec
|
|
117
|
-
* part: the group whose manual() takes it (engine.
|
|
116
|
+
* part: the group whose manual() takes it (engine.autoView.manual(key)); key: the name manual() matches (prefix match on dots: 'sun' takes
|
|
118
117
|
* 'sun.intensity' and 'sun.color'); once: written only at creation (read now is the creation value; needs write for the hand-back); levels: the copyable calls the warning quotes (manual is required); onChange: mode changed (the sky hides its dome when the game
|
|
119
118
|
* takes scene.background)
|
|
120
119
|
* @returns {Owned}
|
|
@@ -122,7 +121,7 @@ export function checkWrittenOnce(engine) { for (const o of engine._owned?.values
|
|
|
122
121
|
export function defineOwned(engine, spec) {
|
|
123
122
|
if (!spec?.id || !spec.part || typeof spec.read !== 'function') throw codedError('owned-misuse', 'defineOwned(engine, { id, part, read, write?, levels }): id, part and read are required');
|
|
124
123
|
// the yield warning leads with this call, so a property nobody can take on purpose cannot be registered
|
|
125
|
-
if (typeof spec.levels?.manual !== 'string' || !spec.levels.manual) throw codedError('owned-misuse', `defineOwned(engine, { id: '${spec.id}', levels: { manual } }): levels.manual is required, the copyable takeover call the warning quotes, e.g. levels: { manual: "engine.
|
|
124
|
+
if (typeof spec.levels?.manual !== 'string' || !spec.levels.manual) throw codedError('owned-misuse', `defineOwned(engine, { id: '${spec.id}', levels: { manual } }): levels.manual is required, the copyable takeover call the warning quotes, e.g. levels: { manual: "engine.autoView.manual('far')" }`);
|
|
126
125
|
const reg = engine._owned ??= new Map();
|
|
127
126
|
const o = new Owned(engine, spec);
|
|
128
127
|
const old = reg.get(spec.id); if (old) live.delete(old);
|
|
@@ -140,7 +139,7 @@ function ownedOf(engine, part, keys) {
|
|
|
140
139
|
}
|
|
141
140
|
|
|
142
141
|
/**
|
|
143
|
-
* manual(keys?, on?) of a group (engine.
|
|
142
|
+
* manual(keys?, on?) of a group (engine.autoView.manual): the game takes these properties (the engine stops writing them) or hands them back (on false).
|
|
144
143
|
* Throws with the part's takeable keys when nothing matches, so a typo does not silently do nothing.
|
|
145
144
|
* @returns {{ remove(): void }} remove() hands them back
|
|
146
145
|
*/
|
|
@@ -167,5 +166,3 @@ export function describeOwned(engine) {
|
|
|
167
166
|
* @param {any} engine @param {string} id @param {() => (object | undefined)} row
|
|
168
167
|
*/
|
|
169
168
|
export function ownedRow(engine, id, row) { (engine._ownedRows ??= {})[id] = row; }
|
|
170
|
-
/** Remove an ownedRow (its module disposed) @param {any} engine @param {string} id */
|
|
171
|
-
export function dropOwnedRow(engine, id) { if (engine._ownedRows) delete engine._ownedRows[id]; }
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Shared points: the ONE way several owners change a shared thing (time channels, the calendar rate,
|
|
1
|
+
// Shared points: the ONE way several owners change a shared thing (time channels, the calendar rate, halt / freeze / camera holders, move speed,
|
|
2
2
|
// input gates, shadows.enabled, sky.tint, post values, a game's own). One entry, one line:
|
|
3
3
|
// const h = engine.mod('time.enemies', { owner: 'bullet-time', mul: 0.35, for: 2 }); // bullet time; h.remove() ends it early
|
|
4
4
|
// ctx.mod('time.world', { mul: 0.8, layer: 'effect' }); // inside a module: owned by it, removed with it
|
|
@@ -17,12 +17,12 @@
|
|
|
17
17
|
// - the settings layer only restricts: clamp { max } or mul 0..1 on a number, set false on a value point; it can never raise a number or
|
|
18
18
|
// switch something on (one exception a point opts into with settingsSet: key bindings, where the player's rebinding is a replacement).
|
|
19
19
|
// It sits above system: a cutscene or menu cannot turn back on what the player turned off; only debug overrides the player
|
|
20
|
-
// - kinds: 'number' (default) | 'value' (any data: a color, a string, a boolean; set only) | 'any' (true while anyone holds it:
|
|
20
|
+
// - kinds: 'number' (default) | 'value' (any data: a color, a string, a boolean; set only) | 'any' (true while anyone holds it: freeze, gates)
|
|
21
21
|
// | 'top' (the latest holder is in charge: the camera) | 'one' (an exclusive slot: a second holder is shared-taken; module `provides`)
|
|
22
22
|
// Plain JS stays first-class: a game's own fields and onFixed logic never need this; it is for things several owners write.
|
|
23
|
-
// The registry (engine.stacks: define / get / mod, save, timers, describe().shared) is core/stacks.js.
|
|
24
|
-
import { codedError, coded } from '
|
|
25
|
-
import { DEV, warnOnce, note } from '
|
|
23
|
+
// The registry (engine.stacks: define / get / mod, save, timers, describe().shared) is core/ops/stacks.js.
|
|
24
|
+
import { codedError, coded } from '../base/errorHints.js';
|
|
25
|
+
import { DEV, warnOnce, note } from '../base/validate.js';
|
|
26
26
|
import { callerAt } from './stackFrames.js';
|
|
27
27
|
|
|
28
28
|
/** The one layer table, lowest first. Who uses which: engine = the engine's own defaults and drivers, game = game code and
|
|
@@ -53,7 +53,7 @@ function numCheck(op, v, call) {
|
|
|
53
53
|
}
|
|
54
54
|
|
|
55
55
|
/**
|
|
56
|
-
*
|
|
56
|
+
* freeze('x') and freeze({ owner: 'x' }) both work everywhere an owner is named
|
|
57
57
|
* @param {string | { owner?: string } | undefined} a @param {any} [b] @returns {{ owner: string, opts: any }}
|
|
58
58
|
*/
|
|
59
59
|
export function ownerArgs(a, b, fallback = 'game') {
|
|
@@ -184,7 +184,7 @@ export class Stack {
|
|
|
184
184
|
}
|
|
185
185
|
/** @internal */
|
|
186
186
|
_changed(id) { this._ver++; this.all._version++; this.onChange?.(id ?? null); }
|
|
187
|
-
/** @internal End owner's entry by name (engine holds: the
|
|
187
|
+
/** @internal End owner's entry by name (engine holds: the halt handle); games end theirs with the handle's remove(). false when it held none @param {string} owner @param {{ id?: string }} [o] */
|
|
188
188
|
release(owner, { id } = {}) { return this._drop(owner, id); }
|
|
189
189
|
/** Drop every entry for record id (world.remove does it, so no orphan entries) @param {string} id */
|
|
190
190
|
dropId(id) { this._memo.delete(id); const m = this._by.get(id); if (!m) return; this._by.delete(id); this._changed(id); }
|
|
@@ -242,7 +242,7 @@ export class Stack {
|
|
|
242
242
|
}
|
|
243
243
|
return v;
|
|
244
244
|
}
|
|
245
|
-
/** Each holder's value in take order: [{ owner, value }] (the data an 'any' holder gave, e.g. a
|
|
245
|
+
/** Each holder's value in take order: [{ owner, value }] (the data an 'any' holder gave, e.g. a freeze's kind) @param {string} [id] */
|
|
246
246
|
entries(id) { return [...(this._map(id)?.values() ?? [])].map(e => ({ owner: e.owner, value: e.value })); }
|
|
247
247
|
/** The latest holder's entry ({ owner, value }) or null: the camera in charge, the slot's holder @param {string} [id] */
|
|
248
248
|
top(id) { let t = null; const m = this._map(id); if (m) for (const e of m.values()) t = e; return t; }
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// a shared point (sharedPoint.js: the conflict error names both sides' lines).
|
|
3
3
|
// Why one file: the two copies of the frame regex drifted apart once already (a query string after the file name, a Windows path), and a fix made in
|
|
4
4
|
// one never reached the other. Both read V8 and Firefox / Safari frame lines ("at f (http://host/src/main.js?v=1:50:7)" and "f@http://host/src/main.js:50:7").
|
|
5
|
-
import { DEV } from '
|
|
5
|
+
import { DEV } from '../base/validate.js';
|
|
6
6
|
const FRAME = /\(?((?:[a-z]+:\/\/[^/\s]+)?[^\s()]+?\.[cm]?[jt]sx?)(?:\?[^:\s)]*)?:(\d+):\d+\)?\s*$/i;
|
|
7
7
|
const FUNC = /^[^@\s/]*@(?=[a-z]+:\/\/)/i;
|
|
8
8
|
const NAME = /^\s*(?:at\s+(?:async\s+)?([^\s(]+(?: \[as [^\]]+\])?)\s+\(|([^@\s/]+)@)/; // V8 "at name (file" / Firefox "name@file"; none for an anonymous function
|
|
@@ -26,7 +26,7 @@ const ENGINE_FRAME = /(?:engine|threedog)\/(?:core|modules|render|ui)\//; // e
|
|
|
26
26
|
const ENGINE_PARTS = /^(?:core|modules|render|ui)\//;
|
|
27
27
|
// the engine's own folder as this page's server names it. Why not only the path pattern above: a page served from the engine's folder (its tests) has
|
|
28
28
|
// /core/x.js with no 'engine' in it, and a game's own core/ folder must not pass for the engine's. String work, not new URL('..', import.meta.url): a bundler reads that form as an asset
|
|
29
|
-
const engineDir = () => import.meta.url.replace(/\?.*$/, '').replace(/[^/]*\/[^/]*$/, '');
|
|
29
|
+
const engineDir = () => import.meta.url.replace(/\?.*$/, '').replace(/(?:[^/]*\/){2}[^/]*$/, '');
|
|
30
30
|
|
|
31
31
|
/** Is this frame file the engine's own code? @param {string} file a frame's file */
|
|
32
32
|
export function engineFile(file) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
// engine.stacks: the registry of every shared point (the point itself and its rules are core/sharedPoint.js). Here: define / get / mod, the timers
|
|
1
|
+
// engine.stacks: the registry of every shared point (the point itself and its rules are core/ops/sharedPoint.js). Here: define / get / mod, the timers
|
|
2
2
|
// behind `for`, saving entries, and describe().shared. Kept apart from sharedPoint.js only for size: the rules read without the bookkeeping between.
|
|
3
|
-
import { codedError } from '
|
|
4
|
-
import { DEV, warnOnce } from '
|
|
3
|
+
import { codedError } from '../base/errorHints.js';
|
|
4
|
+
import { DEV, warnOnce } from '../base/validate.js';
|
|
5
5
|
import { Stack } from './sharedPoint.js';
|
|
6
6
|
|
|
7
7
|
const KEYS = ['owner', 'set', 'add', 'mul', 'clamp', 'value', 'for', 'clock', 'id', 'layer'];
|
|
@@ -17,20 +17,18 @@ export class Stacks {
|
|
|
17
17
|
/** @type {Map<string, Stack>} */ this._all = new Map();
|
|
18
18
|
/** @internal saved entries of a point the game has not defined yet: applied when it does */ this._pending = {};
|
|
19
19
|
this._version = 0; this._timedDirty = false;
|
|
20
|
-
/** @internal now on a clock ('real' or a channel); core/time.js replaces it */ this._nowOf = () => 0;
|
|
21
|
-
// since = game clock time of the take (
|
|
20
|
+
/** @internal now on a clock ('real' or a channel); core/time/time.js replaces it */ this._nowOf = () => 0;
|
|
21
|
+
// since = game clock time of the take (calendar seconds), not engine.time.now('real'): session.newGame resets the clock, so an entry a fresh
|
|
22
22
|
// playthrough makes reads the same in every new game
|
|
23
|
-
this._at = () =>
|
|
24
|
-
this._hooked = false; this._hook();
|
|
23
|
+
this._at = () => this._nowOf('calendar');
|
|
25
24
|
}
|
|
26
25
|
/** @internal saves and world:remove. The registry is made before them (Engine.js: the drawing parts' points exist from the first drawing part on);
|
|
27
|
-
* createServices calls this
|
|
26
|
+
* createServices calls this once saves and events exist */
|
|
28
27
|
_hook() {
|
|
29
28
|
const e = this.engine;
|
|
30
|
-
if (this._hooked || !e.saves || !e.events) return;
|
|
31
|
-
this._hooked = true;
|
|
32
29
|
e.saves.register('stacks', { save: () => this._save(), load: d => this._load(d) });
|
|
33
|
-
|
|
30
|
+
// input.keys and input.gate key their entries by action name, not record id: a removed record 'fire' must not unbind the action 'fire'
|
|
31
|
+
e.events.on('world:remove', ({ id }) => { for (const s of this._all.values()) if (s.per && !s.name.startsWith('input.')) s.dropId(id); });
|
|
34
32
|
}
|
|
35
33
|
/**
|
|
36
34
|
* Define a shared point (engine modules and games use the same call). kind: 'number' (default; base 1), 'value' (any data, set only), 'any'
|
|
@@ -43,7 +41,7 @@ export class Stacks {
|
|
|
43
41
|
* @example engine.stacks.define('damageTaken', { per: true, min: 0 }); engine.mod('damageTaken', { owner: 'shield', id: 'player', mul: 0.5, for: 3 });
|
|
44
42
|
*/
|
|
45
43
|
define(name, o = {}) {
|
|
46
|
-
if (this._all.has(name)) throw codedError('
|
|
44
|
+
if (this._all.has(name)) throw codedError('engine-misuse', `engine.stacks.define('${name}'): already defined; read it with engine.stacks.get('${name}')`);
|
|
47
45
|
const s = new Stack(this, name, o);
|
|
48
46
|
this._all.set(name, s);
|
|
49
47
|
if (this._pending[name]) { this._loadOne(s, this._pending[name]); delete this._pending[name]; }
|
|
@@ -104,7 +102,7 @@ export class Stacks {
|
|
|
104
102
|
return out;
|
|
105
103
|
}
|
|
106
104
|
/**
|
|
107
|
-
* @internal End every entry whose time is up (core/time.js calls it after advancing the clocks), earliest first; emits mod:end for each.
|
|
105
|
+
* @internal End every entry whose time is up (core/time/time.js calls it after advancing the clocks), earliest first; emits mod:end for each.
|
|
108
106
|
* @returns {number} how many ended
|
|
109
107
|
*/
|
|
110
108
|
_expire() {
|
|
@@ -119,7 +117,7 @@ export class Stacks {
|
|
|
119
117
|
}
|
|
120
118
|
return due.length;
|
|
121
119
|
}
|
|
122
|
-
/** @internal smallest time left on any timed entry, converted to
|
|
120
|
+
/** @internal smallest time left on any timed entry, converted to calendar seconds by toGame(clock, left) (engine.skip ends a segment there) */
|
|
123
121
|
_untilNext(toGame) {
|
|
124
122
|
let best = Infinity;
|
|
125
123
|
for (const [, e] of this._timed()) best = Math.min(best, toGame(e.clock, Math.max(0, e.until - this._nowOf(e.clock))));
|
|
@@ -10,14 +10,15 @@
|
|
|
10
10
|
// The wrapper is installed on the object itself, so every caller of that method goes through it: the game, the module's ops (the op
|
|
11
11
|
// inventory.transfer calls engine.inventory.transfer) and other modules alike. It wraps one method, not a behaviour: a rule that must hold for
|
|
12
12
|
// every way items enter the bag wraps each api method that can do it (add and transfer), or uses the module's own option (maxWeight).
|
|
13
|
-
//
|
|
14
|
-
import { fmt } from '
|
|
15
|
-
import { codedError } from '
|
|
13
|
+
// Wrap what the contract lists (modules/<m>/contract.js). A name starting with '_' is the module's inside: it works, and dev warns once that it may change.
|
|
14
|
+
import { DEV, fmt, warnOnce } from '../base/validate.js';
|
|
15
|
+
import { coded, codedError } from '../base/errorHints.js';
|
|
16
16
|
|
|
17
17
|
const STRINGS = {
|
|
18
|
-
target:
|
|
18
|
+
target: 'engine.wrap(target, method, fn): target is an object with the method, such as engine.inventory or engine.flow; got {got}',
|
|
19
19
|
fn: "engine.wrap(target, '{method}', fn): fn must be a function (next, ...args) => ..., e.g. (next, ...a) => next(...a)",
|
|
20
|
-
|
|
20
|
+
name: "engine.wrap(target, method, fn): method is a method name, got {method}; public methods: {list}",
|
|
21
|
+
priv: "engine.wrap({name}, '{method}'): '{method}' is the object's inside (leading _), so an engine update may change it without notice. Public methods: {list}",
|
|
21
22
|
missing: "engine.wrap({name}, '{method}'): {name} has no method '{method}'; public methods: {list}",
|
|
22
23
|
};
|
|
23
24
|
|
|
@@ -55,7 +56,8 @@ export class Wraps {
|
|
|
55
56
|
if (!target || (typeof target !== 'object' && typeof target !== 'function')) throw codedError('wrap-misuse', fmt(STRINGS.target, { got: target === null ? 'null' : typeof target }), TypeError);
|
|
56
57
|
if (typeof fn !== 'function') throw codedError('wrap-misuse', fmt(STRINGS.fn, { method }), TypeError);
|
|
57
58
|
const name = this._name(target);
|
|
58
|
-
if (typeof method !== 'string'
|
|
59
|
+
if (typeof method !== 'string') throw codedError('wrap-misuse', fmt(STRINGS.name, { method: String(method), list: methodsOf(target).join(', ') }));
|
|
60
|
+
if (DEV && method.startsWith('_')) warnOnce(coded('wrap-misuse', fmt(STRINGS.priv, { name, method, list: methodsOf(target).join(', ') })));
|
|
59
61
|
let slots = this._map.get(target);
|
|
60
62
|
if (!slots) this._map.set(target, slots = new Map());
|
|
61
63
|
let slot = slots.get(method);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { codedError } from '
|
|
1
|
+
import { codedError } from '../base/errorHints.js';
|
|
2
2
|
// Save storage layer: uses the browser's native IndexedDB (no third-party library) and falls back to localStorage when it is unavailable. Saves uses it; modules never touch it directly.
|
|
3
3
|
//
|
|
4
4
|
// Two stores in the database:
|
|
@@ -10,14 +10,14 @@
|
|
|
10
10
|
// Several tabs of one game share the storage. Each write carries a rev; a tab overwrites a slot only while the stored rev is the one it last read,
|
|
11
11
|
// wrote or loaded (compare-and-write in one IndexedDB transaction), so a forgotten tab's autosave can never replace newer progress made in another
|
|
12
12
|
// tab: that save is refused (false, toast, save-stale). A BroadcastChannel tells the other tabs a slot changed, so their list / load see it at once.
|
|
13
|
-
/** @import { SaveProvider } from '
|
|
13
|
+
/** @import { SaveProvider } from '../../types/core' */
|
|
14
14
|
import { SaveStore } from './SaveStore.js';
|
|
15
|
-
import { checkTypeRule } from '
|
|
16
|
-
import { toast } from '
|
|
17
|
-
import { warnOnce, fmt } from '
|
|
18
|
-
import { readParams, keysSchema } from '
|
|
19
|
-
import { reportError } from '
|
|
20
|
-
import { codedError, coded } from '
|
|
15
|
+
import { checkTypeRule } from '../engine/moduleTypes.js';
|
|
16
|
+
import { toast } from '../../ui/UI.js';
|
|
17
|
+
import { warnOnce, fmt } from '../base/validate.js';
|
|
18
|
+
import { readParams, keysSchema } from '../base/params.js';
|
|
19
|
+
import { reportError } from '../base/errors.js';
|
|
20
|
+
import { codedError, coded } from '../base/errorHints.js';
|
|
21
21
|
import { checkPartVersion, readSave } from './saveVersions.js';
|
|
22
22
|
import { exportSaveFile, importSaveFile, importText, SAVE_STRINGS } from './saveFiles.js';
|
|
23
23
|
import { applySave, loadSlot, adoptPart, collectParts } from './saveApply.js';
|
|
@@ -37,8 +37,8 @@ export class Saves {
|
|
|
37
37
|
/** @internal */
|
|
38
38
|
constructor(engine, { prefix = 'game-' } = {}) {
|
|
39
39
|
/** @internal */ this.engine = engine;
|
|
40
|
-
/**
|
|
41
|
-
this.
|
|
40
|
+
/** @internal Start of the key names in the localStorage fallback and of the IndexedDB database name; a module asks storageKey(name) instead */
|
|
41
|
+
this._prefix = prefix + 'save-';
|
|
42
42
|
/** @internal */ this.providers = new Map();
|
|
43
43
|
/** @internal */ this._auto = null;
|
|
44
44
|
/** @internal Slot -> JSON text (all saves stay in memory: list / check / export are synchronous) */ this._json = new Map();
|
|
@@ -50,7 +50,7 @@ export class Saves {
|
|
|
50
50
|
this._tab = globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${performance.now()}`; // wall-clock: only a fallback id, unique per tab
|
|
51
51
|
/** @internal */ this._n = 0;
|
|
52
52
|
/** @internal other tabs of this game: 'slot changed' notes */
|
|
53
|
-
this._bc = typeof BroadcastChannel === 'function' ? new BroadcastChannel(this.
|
|
53
|
+
this._bc = typeof BroadcastChannel === 'function' ? new BroadcastChannel(this._prefix + 'db') : null;
|
|
54
54
|
if (this._bc) this._bc.onmessage = ev => this._remote(ev.data?.slot);
|
|
55
55
|
/** @internal Parts of the last loaded save that no registered module owns (a module not installed in this build): written back unchanged on every save */
|
|
56
56
|
this._foreign = { parts: {}, versions: {} };
|
|
@@ -59,8 +59,9 @@ export class Saves {
|
|
|
59
59
|
* Storage layer: saves in the IndexedDB slots store, attachments (by group, e.g. 'photo') in the blobs store; mode 'localStorage' without IndexedDB.
|
|
60
60
|
* @type {{ mode: 'idb' | 'localStorage', blobs(group?: string): Promise<{ group: string, id: string, at: number, blob: Blob, meta: any }[]>,
|
|
61
61
|
* putBlob(group: string, id: string, blob: Blob, meta?: any, at?: number): Promise<void>, deleteBlob(group: string, id: string): Promise<void> }}
|
|
62
|
+
* @experimental
|
|
62
63
|
*/
|
|
63
|
-
this.store = /** @type {any} */ (new SaveStore(this.
|
|
64
|
+
this.store = /** @type {any} */ (new SaveStore(this._prefix + 'db', this._prefix));
|
|
64
65
|
/** Has the save index been read into memory? (start() waits for it; game code rarely needs to care) */
|
|
65
66
|
this.ready = false;
|
|
66
67
|
/** Resolves once the save index is in memory; await it only to list / load before start() @type {Promise<void>} */
|
|
@@ -73,9 +74,6 @@ export class Saves {
|
|
|
73
74
|
* shape.
|
|
74
75
|
* A save whose part is newer than this build's version is refused as a whole (load returns false, the save is kept).
|
|
75
76
|
* A part registered after a save was loaded (a module installed later) is handed its data from that save at once.
|
|
76
|
-
* movedFrom: { oldPart: data => newData } when this part's data used to be saved under another part's name (a module split in two: the calendar's
|
|
77
|
-
* time and day were part 'sky'); an old save without this part but with oldPart hands that data, converted, to this part, and oldPart is dropped
|
|
78
|
-
* (unless a registered part still owns that name).
|
|
79
77
|
* atomic: true joins this part to atomic ops: it is copied before an atomic op runs and put back if the op fails (plain data only; afterLoad does not run on rollback).
|
|
80
78
|
* checkNewGame(data): dev only, called once start() finished with this part's data in the new-game state, to warn about what should not be there yet
|
|
81
79
|
* (world: records placed by code instead of content). The part knows its own format; core only hands the data over.
|
|
@@ -88,14 +86,11 @@ export class Saves {
|
|
|
88
86
|
*/
|
|
89
87
|
register(key, provider) {
|
|
90
88
|
checkTypeRule(this.engine, 'saves.register', `registered save part '${key}'`);
|
|
91
|
-
readParams(`saves.register('${key}')`, keysSchema(['save', 'load', 'first', 'version', 'migrate', 'atomic', '
|
|
92
|
-
const { save, load, first = false, version = 1, migrate = {}, atomic = false,
|
|
93
|
-
checkPartVersion(key, version, migrate
|
|
94
|
-
this.providers.set(key, { save, load, first, version, migrate, atomic: atomic === true,
|
|
89
|
+
readParams(`saves.register('${key}')`, keysSchema(['save', 'load', 'first', 'version', 'migrate', 'atomic', 'checkNewGame']), provider);
|
|
90
|
+
const { save, load, first = false, version = 1, migrate = {}, atomic = false, checkNewGame = null } = provider;
|
|
91
|
+
checkPartVersion(key, version, migrate);
|
|
92
|
+
this.providers.set(key, { save, load, first, version, migrate, atomic: atomic === true, checkNewGame });
|
|
95
93
|
this.engine.session._late(key); // a part registered after start() (a module installed later) joins the new-game state as it is now
|
|
96
|
-
// registered after a save was loaded: the old part's data is still kept as foreign, move it over now (the same step readSave does on load)
|
|
97
|
-
const F = this._foreign, old = movedFrom && !(key in F.parts) && Object.keys(movedFrom).find(o => o in F.parts && !this.providers.has(o));
|
|
98
|
-
if (old) { F.parts[key] = movedFrom[old](structuredClone(F.parts[old])); F.versions[key] = version; delete F.parts[old]; delete F.versions[old]; }
|
|
99
94
|
if (key in this._foreign.parts) adoptPart(this, key);
|
|
100
95
|
}
|
|
101
96
|
/**
|
|
@@ -110,18 +105,14 @@ export class Saves {
|
|
|
110
105
|
const idb = await this.store.open();
|
|
111
106
|
if (!idb) warnOnce(coded('indexeddb', DEV_STRINGS.noIdb));
|
|
112
107
|
try {
|
|
113
|
-
for (const r of await this.store.slots())
|
|
114
|
-
this.
|
|
108
|
+
for (const r of await this.store.slots()) {
|
|
109
|
+
this._rev.set(r.slot, r.rev ?? ''); this._mine.set(r.slot, r.rev ?? ''); // also for a save made before this ran: its write comes after and expects this record
|
|
110
|
+
if (!this._json.has(r.slot)) { this._json.set(r.slot, r.json); this._meta.set(r.slot, r.savedAt); }
|
|
115
111
|
}
|
|
116
112
|
} catch (e) { this._fail(e); }
|
|
117
113
|
}
|
|
118
|
-
/**
|
|
119
|
-
|
|
120
|
-
* @template T
|
|
121
|
-
* @param {() => Promise<T>} fn
|
|
122
|
-
* @returns {Promise<T>}
|
|
123
|
-
*/
|
|
124
|
-
queue(fn) {
|
|
114
|
+
/** @internal Disk writes run in call order once storage is ready, and flush waits for them: the one place that order is kept */
|
|
115
|
+
_enqueue(fn) {
|
|
125
116
|
const p = this._queue.then(() => this.whenReady).then(fn);
|
|
126
117
|
this._queue = p.catch(() => {});
|
|
127
118
|
return p;
|
|
@@ -133,6 +124,36 @@ export class Saves {
|
|
|
133
124
|
else warnOnce(coded('save-write', `[saves] failed to write ${slot ? `slot "${slot}"` : 'save'}: ${err?.message ?? err}`));
|
|
134
125
|
toast(this.engine, why, { kind: 'error', ms: 5000 });
|
|
135
126
|
}
|
|
127
|
+
/**
|
|
128
|
+
* Store a binary attachment outside the world save (a photo, a replay). It rides in the queue of save writes, so flush() waits for it, and exportFile() carries it.
|
|
129
|
+
* Pass a function to make the bytes when the write runs: flush() then waits for that too. Without IndexedDB it is not kept.
|
|
130
|
+
* @example await engine.saves.putAttachment('replay', 'run-1', blob, { score: 12 });
|
|
131
|
+
* @param {string} group what the attachment is for
|
|
132
|
+
* @param {string} id unique inside the group; the same id replaces
|
|
133
|
+
* @param {Blob | (() => Promise<Blob>)} blob
|
|
134
|
+
* @param {any} [meta] plain data kept with it
|
|
135
|
+
* @returns {Promise<void>}
|
|
136
|
+
* @experimental
|
|
137
|
+
*/
|
|
138
|
+
putAttachment(group, id, blob, meta) {
|
|
139
|
+
return this._enqueue(async () => this.store.putBlob(group, id, typeof blob === 'function' ? await blob() : blob, meta));
|
|
140
|
+
}
|
|
141
|
+
/** Delete an attachment; no such id is fine @param {string} group @param {string} id @returns {Promise<void>} @experimental */
|
|
142
|
+
removeAttachment(group, id) { return this._enqueue(() => this.store.deleteBlob(group, id)); }
|
|
143
|
+
/**
|
|
144
|
+
* The attachments of a group, once storage is ready. Empty without IndexedDB.
|
|
145
|
+
* @param {string} group
|
|
146
|
+
* @returns {Promise<{ group: string, id: string, at: number, blob: Blob, meta: any }[]>}
|
|
147
|
+
* @experimental
|
|
148
|
+
*/
|
|
149
|
+
async attachments(group) { await this.whenReady; return this.store.blobs(group); }
|
|
150
|
+
/**
|
|
151
|
+
* A localStorage key for what belongs to this game but is not a save (settings, a last-used tab): it shares the game's name, so two games on one site stay apart, and stays out of list().
|
|
152
|
+
* @example localStorage.setItem(engine.saves.storageKey('lastTab'), 'map');
|
|
153
|
+
* @param {string} name
|
|
154
|
+
* @returns {string}
|
|
155
|
+
*/
|
|
156
|
+
storageKey(name) { return this._prefix.replace(/save-$/, '') + name; }
|
|
136
157
|
/** Wait for all queued disk writes to finish (for tests and before the page closes) @returns {Promise<void>} */
|
|
137
158
|
flush() { return this._queue; }
|
|
138
159
|
|
|
@@ -177,7 +198,7 @@ export class Saves {
|
|
|
177
198
|
const prev = this._json.get(slot), prevAt = this._meta.get(slot), rev = `${this._tab}:${++this._n}`;
|
|
178
199
|
this._json.set(slot, json); this._meta.set(slot, savedAt);
|
|
179
200
|
// expect is read when the write runs, not now: an earlier queued save of this tab moves _mine first
|
|
180
|
-
return this.
|
|
201
|
+
return this._enqueue(() => this.store.putSlot(slot, savedAt, json, rev, this._mine.get(slot) ?? null)).then(() => {
|
|
181
202
|
this._rev.set(slot, rev); this._mine.set(slot, rev);
|
|
182
203
|
this._tell(slot);
|
|
183
204
|
return true;
|
|
@@ -196,15 +217,15 @@ export class Saves {
|
|
|
196
217
|
this._fail(e, slot); return false;
|
|
197
218
|
});
|
|
198
219
|
}
|
|
199
|
-
/** @internal Memory shows a stored record (null = none); the rev this tab may overwrite
|
|
220
|
+
/** @internal Memory shows a stored record (null = none); a stored record leaves the rev this tab may overwrite as it was */
|
|
200
221
|
_show(slot, r) {
|
|
201
|
-
if (!r) { this._json.delete(slot); this._meta.delete(slot); this._rev.delete(slot); return; }
|
|
222
|
+
if (!r) { this._json.delete(slot); this._meta.delete(slot); this._rev.delete(slot); this._mine.delete(slot); return; } // deleted: no newer progress to protect, so the next save may write
|
|
202
223
|
this._json.set(slot, r.json); this._meta.set(slot, r.savedAt); this._rev.set(slot, r.rev ?? '');
|
|
203
224
|
}
|
|
204
225
|
/** @internal Another tab changed a slot: read it again (after this tab's queued writes, so a late note cannot undo a newer own write) */
|
|
205
226
|
_remote(slot) {
|
|
206
227
|
if (typeof slot !== 'string' || !this._bc) return;
|
|
207
|
-
this.
|
|
228
|
+
this._enqueue(() => this.store.getSlot(slot)).then(r => this._show(slot, r), () => {});
|
|
208
229
|
}
|
|
209
230
|
/** @internal Tell the other tabs a slot changed (they read it again from storage: the note carries no save text, which can be MBs) */
|
|
210
231
|
_tell(slot) { this._bc?.postMessage({ slot }); } // BroadcastChannel, not a worker
|
|
@@ -255,10 +276,10 @@ export class Saves {
|
|
|
255
276
|
this._json.delete(slot); this._meta.delete(slot);
|
|
256
277
|
// the revs are cleared when the delete runs, not now: a save queued before this remove sets _mine when its write lands,
|
|
257
278
|
// and a _mine left over for a deleted record would refuse every later save of this slot as "another tab saved"
|
|
258
|
-
return this.
|
|
279
|
+
return this._enqueue(async () => { await this.store.deleteSlot(slot); this._rev.delete(slot); this._mine.delete(slot); })
|
|
259
280
|
.then(() => this._tell(slot), e => this._fail(e, slot));
|
|
260
281
|
}
|
|
261
|
-
/** Export as a piece of text (can be copied as a backup; synchronous, without binary attachments) @param {string} [slot] @returns {string} */
|
|
282
|
+
/** Export as a piece of text (can be copied as a backup; synchronous, without binary attachments) @param {string} [slot] @returns {string} @experimental */
|
|
262
283
|
export(slot = 'auto') { try { return btoa(unescape(encodeURIComponent(this._json.get(slot) || ''))); } catch { return ''; } }
|
|
263
284
|
/**
|
|
264
285
|
* Import text from export() into a slot (default 'imported'); checked like importFile and written before it resolves.
|
|
@@ -277,6 +298,7 @@ export class Saves {
|
|
|
277
298
|
* @param {{ files?: boolean }} [opts]
|
|
278
299
|
* @returns {Promise<boolean>}
|
|
279
300
|
* @example engine.saves.exportFile('slot1');
|
|
301
|
+
* @experimental
|
|
280
302
|
*/
|
|
281
303
|
exportFile(slot = 'auto', opts = {}) { return exportSaveFile(this, slot, opts); }
|
|
282
304
|
/**
|
|
@@ -10,12 +10,13 @@
|
|
|
10
10
|
// overlapping loads were never sound anyway (the second one's rollback point is the first one's half-applied state). An unrelated listener that
|
|
11
11
|
// throws while a load is still settling 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
|
-
import { toast } from '
|
|
14
|
-
import { fmt, warnOnce } from '
|
|
15
|
-
import { reportError } from '
|
|
16
|
-
import { codedError, coded } from '
|
|
13
|
+
import { toast } from '../../ui/UI.js';
|
|
14
|
+
import { fmt, warnOnce } from '../base/validate.js';
|
|
15
|
+
import { reportError } from '../base/errors.js';
|
|
16
|
+
import { codedError, coded } from '../base/errorHints.js';
|
|
17
17
|
import { FORMAT, readSave, parseSave, upgradePart } from './saveVersions.js';
|
|
18
|
-
import { PARTS_LOADING } from '
|
|
18
|
+
import { PARTS_LOADING } from '../ops/opsFail.js';
|
|
19
|
+
import { isObject } from '../base/util.js';
|
|
19
20
|
|
|
20
21
|
const DEV_STRINGS = {
|
|
21
22
|
loadThrew: "load() of save part '{k}' threw ({msg}); the game was rolled back to how it was before loading '{slot}'",
|
|
@@ -59,7 +60,7 @@ function applyParts(s, e, r, slot, before, foreign0, scope) {
|
|
|
59
60
|
e.commits.invalidate(); e.ops._mark('(load)'); // old background results die with the old world; the op log shows where the load cut in
|
|
60
61
|
s._foreign = r.foreign;
|
|
61
62
|
const fail = err => {
|
|
62
|
-
// a malformed save (
|
|
63
|
+
// 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
|
|
63
64
|
// does not freeze gameplay as a code error would; a load() / listener / afterLoad that throws is a bug and goes through the error tiers
|
|
64
65
|
if (err?.cause?.code === 'save-bad-record') { warnOnce(err.message); toast(e, e.t('saves.corrupt'), { kind: 'error', ms: 5000 }); }
|
|
65
66
|
else reportError(e, err, err?.part ? fmt(DEV_STRINGS.partAt, { k: err.part }) : `saves.apply('${slot}')`);
|
|
@@ -67,12 +68,15 @@ function applyParts(s, e, r, slot, before, foreign0, scope) {
|
|
|
67
68
|
const back = readSave(before, s.providers, '(rollback)');
|
|
68
69
|
// every part reloads its pre-load state; a part that throws again is reported (once) and the rest still roll back
|
|
69
70
|
const onPart = er => reportError(e, er, fmt(DEV_STRINGS.rollback, { k: er.part }), { soft: true });
|
|
70
|
-
|
|
71
|
+
const undone = 'list' in back ? e.ops.allow(() => runParts(e, back.list, '(rollback)', scope, onPart)) : true;
|
|
72
|
+
// a rollback that waits on an async part holds gameplay too, whichever way the load failed (the load's own hold may be gone or never taken)
|
|
73
|
+
const fz = undone !== true ? e.freeze(PARTS_LOADING) : null;
|
|
74
|
+
return Promise.resolve(undone).then(() => false).finally(() => fz?.remove());
|
|
71
75
|
};
|
|
72
76
|
let out;
|
|
73
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)
|
|
74
78
|
// a part still loading (its load() returned a Promise): gameplay waits until every part is applied -- no fixed step, no op (opsFail.js
|
|
75
|
-
// PARTS_LOADING).
|
|
79
|
+
// PARTS_LOADING). A fully sync load never takes it.
|
|
76
80
|
const fz = out !== true ? e.freeze(PARTS_LOADING) : null;
|
|
77
81
|
const partsDone = () => { fz?.remove(); };
|
|
78
82
|
// 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()
|
|
@@ -160,7 +164,7 @@ export function loadSlot(s, slot, base) {
|
|
|
160
164
|
if (base && data != null) {
|
|
161
165
|
try {
|
|
162
166
|
const sv = parseSave(data);
|
|
163
|
-
if (sv?.parts
|
|
167
|
+
if (isObject(sv?.parts)) {
|
|
164
168
|
const own = Object.fromEntries(Object.keys(sv.parts).map(k => [k, sv.versions?.[k] ?? 1])); // a part without a version is version 1, not base's
|
|
165
169
|
data = { ...sv, parts: { ...base.parts, ...sv.parts }, versions: { ...base.versions, ...own } };
|
|
166
170
|
}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// Save files (.json download / restore), split out of Saves.js: the world save plus every binary attachment, for backups that survive wiped browser data.
|
|
2
2
|
// File shape: { threedog: 'save', format: FILE_FORMAT, game, slot, savedAt, data: <the save envelope>, files: [{ group, id, at, meta, type, url: 'data:...' }] }.
|
|
3
3
|
// Import is offline: attachments must be data: URLs and are decoded in place, never fetched.
|
|
4
|
-
import { toast } from '
|
|
5
|
-
import { coded } from '
|
|
6
|
-
import { fmt, warnOnce } from '
|
|
4
|
+
import { toast } from '../../ui/UI.js';
|
|
5
|
+
import { coded } from '../base/errorHints.js';
|
|
6
|
+
import { fmt, warnOnce } from '../base/validate.js';
|
|
7
7
|
import { readSave, parseSave } from './saveVersions.js';
|
|
8
8
|
|
|
9
9
|
/** Version of the export file wrapper (the save inside carries its own format) */
|
|
@@ -31,12 +31,14 @@ const STRINGS = {
|
|
|
31
31
|
/** Blob -> data: URL (attachments are stored as text in the export file) */
|
|
32
32
|
const toDataURL = blob => new Promise((res, rej) => { const r = new FileReader(); r.onload = () => res(r.result); r.onerror = () => rej(r.error); r.readAsDataURL(blob); });
|
|
33
33
|
|
|
34
|
-
/** data: URL -> Blob without the network; null when it is not a data: URL */
|
|
34
|
+
/** data: URL -> Blob without the network; null when it is not a readable data: URL */
|
|
35
35
|
function dataUrlBlob(url, type) {
|
|
36
36
|
const m = typeof url === 'string' && /^data:([^,]*?)(;base64)?,(.*)$/s.exec(url);
|
|
37
37
|
if (!m) return null;
|
|
38
|
-
|
|
39
|
-
|
|
38
|
+
try {
|
|
39
|
+
const bytes = m[2] ? Uint8Array.from(atob(m[3]), c => c.charCodeAt(0)) : new TextEncoder().encode(decodeURIComponent(m[3]));
|
|
40
|
+
return new Blob([bytes], { type: typeof type === 'string' ? type : m[1].split(';')[0] });
|
|
41
|
+
} catch { return null; } // a hand-edited file: bad base64 or a bad % escape
|
|
40
42
|
}
|
|
41
43
|
|
|
42
44
|
/**
|
|
@@ -54,10 +56,10 @@ export async function exportSaveFile(s, slot, { files = true } = {}) {
|
|
|
54
56
|
const list = [];
|
|
55
57
|
if (files) for (const b of await s.store.blobs()) list.push({ group: b.group, id: b.id, at: b.at, meta: b.meta, type: b.blob.type, url: await toDataURL(b.blob) });
|
|
56
58
|
// splice the world save's JSON text in directly instead of parsing it again (halves memory at tens of MB)
|
|
57
|
-
const head = `{"threedog":"save","format":${FILE_FORMAT},"game":${JSON.stringify(s.
|
|
59
|
+
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":`;
|
|
58
60
|
const blob = new Blob([head, json, ',"files":', JSON.stringify(list), '}'], { type: 'application/json' });
|
|
59
61
|
const a = document.createElement('a'), url = URL.createObjectURL(blob);
|
|
60
|
-
a.href = url; a.download = `${s.
|
|
62
|
+
a.href = url; a.download = `${s._prefix.replace(/-save-$/, '')}-${slot}-${new Date().toISOString().slice(0, 10)}.json`;
|
|
61
63
|
document.body.appendChild(a); a.click(); a.remove();
|
|
62
64
|
setTimeout(() => URL.revokeObjectURL(url), 10000); // presentation: release only after the browser has started the download
|
|
63
65
|
return true;
|
|
@@ -75,22 +77,22 @@ export async function importSaveFile(s, file, slot = 'imported') {
|
|
|
75
77
|
file ??= await pick();
|
|
76
78
|
if (!file) return null;
|
|
77
79
|
const refuse = why => { warnOnce(coded('save-import', why)); toast(s.engine, s.engine.t('saves.badFile'), { kind: 'save' }); return null; }; // handled: the player is told, nothing changed
|
|
78
|
-
if (file.size > MAX_BYTES) return refuse(STRINGS.bad
|
|
80
|
+
if (file.size > MAX_BYTES) return refuse(fmt(STRINGS.bad, { why: `${Math.round(file.size / 1e6)} MB` }));
|
|
79
81
|
let obj;
|
|
80
|
-
try { obj = JSON.parse(await file.text()); } catch (e) { return refuse(STRINGS.bad
|
|
81
|
-
if (obj?.threedog !== 'save') return refuse(STRINGS.bad
|
|
82
|
-
if ((obj.format ?? 1) > FILE_FORMAT) return refuse(STRINGS.bad
|
|
82
|
+
try { obj = JSON.parse(await file.text()); } catch (e) { return refuse(fmt(STRINGS.bad, { why: e.message })); }
|
|
83
|
+
if (obj?.threedog !== 'save') return refuse(fmt(STRINGS.bad, { why: 'no "threedog": "save" marker' }));
|
|
84
|
+
if ((obj.format ?? 1) > FILE_FORMAT) return refuse(fmt(STRINGS.bad, { why: `file format ${obj.format}, this build reads up to ${FILE_FORMAT}` }));
|
|
83
85
|
const blobs = [];
|
|
84
86
|
for (const [i, p] of (Array.isArray(obj.files) ? obj.files : []).entries()) {
|
|
85
87
|
const blob = typeof p?.group === 'string' && typeof p.id === 'string' ? dataUrlBlob(p.url, p.type) : null;
|
|
86
|
-
if (!blob) return refuse(STRINGS.attachment
|
|
88
|
+
if (!blob) return refuse(fmt(STRINGS.attachment, { i: String(i) }));
|
|
87
89
|
blobs.push([p, blob]);
|
|
88
90
|
}
|
|
89
91
|
const r = await importData(s, obj.data, slot);
|
|
90
|
-
if (r !== true) return r === 'write' ? null : refuse(STRINGS.bad
|
|
92
|
+
if (r !== true) return r === 'write' ? null : refuse(fmt(STRINGS.bad, { why: r })); // a failed write already showed its toast
|
|
91
93
|
let ok = true;
|
|
92
94
|
for (const [p, blob] of blobs) {
|
|
93
|
-
try { await s.
|
|
95
|
+
try { await s._enqueue(() => s.store.putBlob(p.group, p.id, blob, p.meta, p.at)); } catch (e) { ok = false; s._fail(e); }
|
|
94
96
|
}
|
|
95
97
|
if (!ok) return null;
|
|
96
98
|
s.engine.events.emit('save:imported', slot);
|