threedog 0.7.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +411 -1
- package/README.md +8 -11
- package/core/{Animator.js → assets/Animator.js} +30 -18
- package/core/{Assets.js → assets/Assets.js} +131 -56
- package/core/{Baked.js → assets/Baked.js} +4 -4
- package/core/assets/assetEntry.js +302 -0
- package/core/{assetHot.js → assets/assetHot.js} +9 -7
- 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} +7 -14
- package/core/{namedModel.js → assets/namedModel.js} +17 -13
- package/core/{Audio.js → audio/Audio.js} +47 -25
- 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} +15 -12
- package/core/{Random.js → base/Random.js} +7 -4
- package/core/{Vars.js → base/Vars.js} +14 -4
- package/core/{easing.js → base/easing.js} +1 -1
- package/core/{errorCodes.js → base/errorCodes.js} +151 -125
- package/core/{errorHints.js → base/errorHints.js} +17 -10
- package/core/{errors.js → base/errors.js} +12 -10
- package/core/{events.generated.js → base/events.generated.js} +11 -0
- package/core/base/follows.js +26 -0
- package/core/base/math.js +66 -0
- package/core/{params.js → base/params.js} +5 -6
- package/core/base/saveValues.js +81 -0
- package/core/base/sections.js +97 -0
- package/core/base/spelling.js +32 -0
- package/core/base/util.js +32 -0
- package/core/{validate.js → base/validate.js} +34 -34
- package/core/{Engine.js → engine/Engine.js} +137 -91
- package/core/{Loading.js → engine/Loading.js} +34 -5
- package/core/{copies.js → engine/copies.js} +4 -4
- package/core/{headlessLoad.js → engine/headlessLoad.js} +32 -15
- package/core/{lifecycle.js → engine/lifecycle.js} +41 -34
- package/core/{loop.js → engine/loop.js} +88 -49
- package/core/engine/moduleSlots.js +176 -0
- package/core/{moduleTypes.js → engine/moduleTypes.js} +26 -14
- package/core/engine/modules.js +503 -0
- package/core/{page.js → engine/page.js} +59 -29
- package/core/{plugins.js → engine/plugins.js} +21 -12
- package/core/{services.js → engine/services.js} +50 -40
- package/core/{startup.js → engine/startup.js} +66 -54
- package/core/{Input.js → input/Input.js} +67 -39
- package/core/{inputContext.js → input/inputContext.js} +14 -5
- package/core/input/inputKeyboard.js +39 -0
- package/core/{inputPad.js → input/inputPad.js} +24 -3
- package/core/{inputPointer.js → input/inputPointer.js} +11 -3
- package/core/input/inputSeat.js +66 -0
- package/core/{inputTouch.js → input/inputTouch.js} +24 -7
- package/core/{Budget.js → inspect/Budget.js} +21 -20
- package/core/{DebugOverrides.js → inspect/DebugOverrides.js} +43 -18
- package/core/{Describe.js → inspect/Describe.js} +34 -26
- package/core/{Inspect.js → inspect/Inspect.js} +39 -10
- 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} +60 -24
- package/core/{catalog.js → inspect/catalog.js} +15 -8
- 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} +24 -22
- package/core/{describeText.js → inspect/describeText.js} +17 -8
- package/core/inspect/geometryWatch.js +38 -0
- package/core/{lightWatch.js → inspect/lightWatch.js} +8 -8
- package/core/inspect/metadata.generated.js +4140 -0
- package/core/{pictureWriters.js → inspect/pictureWriters.js} +130 -47
- package/core/{shaderCost.js → inspect/shaderCost.js} +1 -1
- package/core/inspect/toolDoor.js +21 -0
- package/core/inspect/valueHistory.js +35 -0
- package/core/{Ops.js → ops/Ops.js} +44 -14
- package/core/{control.js → ops/control.js} +57 -31
- package/core/ops/holds.js +140 -0
- package/core/{opsAtomic.js → ops/opsAtomic.js} +18 -5
- package/core/{opsCheck.js → ops/opsCheck.js} +11 -10
- package/core/{opsFail.js → ops/opsFail.js} +5 -7
- package/core/{opsGuard.js → ops/opsGuard.js} +3 -3
- package/core/{opsRun.js → ops/opsRun.js} +9 -6
- package/core/{owned.js → ops/owned.js} +33 -19
- package/core/{sharedPoint.js → ops/sharedPoint.js} +13 -16
- package/core/{stackFrames.js → ops/stackFrames.js} +2 -2
- package/core/{stacks.js → ops/stacks.js} +34 -15
- package/core/{wrap.js → ops/wrap.js} +8 -6
- package/core/{SaveStore.js → saves/SaveStore.js} +53 -27
- package/core/{Saves.js → saves/Saves.js} +171 -54
- package/core/saves/saveApply.js +312 -0
- package/core/{saveFiles.js → saves/saveFiles.js} +45 -38
- package/core/{saveVersions.js → saves/saveVersions.js} +24 -23
- package/core/saves/session.js +231 -0
- package/core/saves/stateReplace.js +184 -0
- package/core/{Rays.js → scene/Rays.js} +44 -30
- package/core/{Views.js → scene/Views.js} +16 -8
- package/core/{adaptive.js → scene/adaptive.js} +19 -9
- package/core/{canvasBox.js → scene/canvasBox.js} +4 -3
- package/core/scene/compositeGround.js +72 -0
- package/core/scene/floor.js +17 -0
- 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} +6 -4
- package/core/{gridLoad.js → scene/gridLoad.js} +1 -1
- package/core/scene/ground.contract.js +14 -0
- package/core/scene/ground.js +139 -0
- package/core/{movement.js → scene/movement.js} +3 -3
- package/core/{pictureSlots.js → scene/pictureSlots.js} +2 -2
- package/core/scene/pixel.js +154 -0
- package/core/scene/pixelRatio.js +167 -0
- package/core/{sceneDelta.js → scene/sceneDelta.js} +5 -5
- package/core/{sceneMethods.js → scene/sceneMethods.js} +43 -15
- package/core/scene/stepPoses.js +60 -0
- package/core/{targeting.js → scene/targeting.js} +4 -5
- package/core/{thingExplain.js → scene/thingExplain.js} +7 -6
- package/core/{thingOps.js → scene/thingOps.js} +25 -16
- package/core/{things.js → scene/things.js} +18 -5
- package/core/{threePatches.js → scene/threePatches.js} +1 -1
- package/core/{tier.js → scene/tier.js} +10 -0
- package/core/scene/view.js +161 -0
- package/core/{Batching.js → stream/Batching.js} +85 -28
- package/core/{Stream.js → stream/Stream.js} +80 -38
- package/core/{batchGroups.js → stream/batchGroups.js} +11 -9
- package/core/{chunkStream.js → stream/chunkStream.js} +40 -0
- package/core/{scatter.js → stream/scatter.js} +7 -4
- package/core/{streamSources.js → stream/streamSources.js} +14 -8
- package/core/{Commits.js → threads/Commits.js} +17 -11
- package/core/{Jobs.js → threads/Jobs.js} +25 -13
- package/core/{Threads.js → threads/Threads.js} +21 -18
- 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} +20 -11
- package/core/{dayTime.js → time/dayTime.js} +5 -1
- package/core/{skip.js → time/skip.js} +28 -21
- package/core/{time.js → time/time.js} +32 -20
- package/core/{uiClock.js → time/uiClock.js} +4 -4
- package/docs/AI.md +92 -72
- package/docs/API.md +33 -28
- package/docs/CODEMAP.md +121 -200
- package/docs/COMMANDS.md +77 -70
- package/docs/CONVENTIONS.md +167 -24
- package/docs/MIGRATING-0.8.md +171 -0
- package/docs/MIGRATING-1.0.md +101 -0
- package/docs/THREE.md +140 -38
- 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 +32 -29
- package/docs/api/characters.md +35 -24
- package/docs/api/clock.md +1 -1
- package/docs/api/collider3d.md +9 -0
- package/docs/api/collision.md +12 -9
- package/docs/api/content.md +18 -17
- package/docs/api/dialogue.md +5 -4
- package/docs/api/engine.md +58 -54
- package/docs/api/events.md +17 -6
- package/docs/api/flow.md +1 -1
- package/docs/api/grids.md +1 -1
- package/docs/api/ground.md +6 -7
- package/docs/api/hud.md +2 -2
- package/docs/api/i18n.md +6 -6
- package/docs/api/input.md +9 -8
- package/docs/api/interactions.md +5 -5
- package/docs/api/inventory.md +10 -10
- package/docs/api/jobs.md +5 -5
- package/docs/api/level.md +10 -9
- package/docs/api/lightPool.md +1 -6
- package/docs/api/music.md +3 -3
- package/docs/api/nav.md +14 -12
- package/docs/api/openWorld.md +1 -1
- package/docs/api/particles.md +10 -7
- package/docs/api/photo.md +4 -2
- package/docs/api/pickups.md +3 -3
- package/docs/api/post.md +21 -5
- package/docs/api/quests.md +7 -5
- package/docs/api/rays.md +7 -7
- package/docs/api/rigid.md +29 -19
- package/docs/api/saves.md +13 -11
- package/docs/api/settings.md +9 -8
- package/docs/api/sky.md +8 -7
- package/docs/api/stream.md +8 -9
- package/docs/api/swarm.md +34 -0
- package/docs/api/terrain.md +6 -8
- package/docs/api/terrainDraw.md +2 -2
- package/docs/api/timeline.md +4 -4
- package/docs/api/tools.md +27 -22
- package/docs/api/triggers.md +2 -0
- package/docs/api/vars.md +1 -1
- package/docs/api/vegetation.md +4 -3
- package/docs/api/vegetationDraw.md +2 -2
- package/docs/api/water.md +7 -3
- package/docs/api/weather.md +27 -12
- package/docs/api/weatherDraw.md +4 -4
- package/docs/api/world.md +6 -6
- package/docs/recipes/01-new-game.md +28 -43
- package/docs/recipes/02-npc.md +21 -23
- package/docs/recipes/03-items-pickups.md +37 -53
- package/docs/recipes/04-quests.md +5 -4
- package/docs/recipes/05-props-bake.md +34 -44
- package/docs/recipes/06-clock-events.md +31 -22
- package/docs/recipes/07-flow-scenes-pause.md +30 -32
- package/docs/recipes/08-weather-sky.md +91 -37
- package/docs/recipes/09-materials-lights-models.md +25 -39
- package/docs/recipes/10-blender-level.md +22 -11
- package/docs/recipes/11-vehicles.md +44 -24
- package/docs/recipes/12-navmesh.md +60 -15
- package/docs/recipes/13-animation.md +70 -22
- package/docs/recipes/14-custom-module.md +33 -20
- package/docs/recipes/15-perf.md +51 -28
- package/docs/recipes/16-dev-bridge.md +39 -58
- package/docs/recipes/18-world.md +49 -28
- package/docs/recipes/19-shooting-picking.md +7 -4
- package/docs/recipes/20-content-actions-save.md +55 -40
- package/docs/recipes/21-camera.md +47 -25
- package/docs/recipes/22-shop-gold.md +21 -16
- package/docs/recipes/23-ops.md +28 -24
- package/docs/recipes/26-ui-parts.md +25 -14
- package/docs/recipes/27-net.md +3 -5
- package/docs/recipes/28-terrain.md +119 -23
- package/docs/recipes/29-grid.md +3 -3
- package/docs/recipes/30-templates.md +63 -30
- package/docs/recipes/31-audio.md +7 -7
- package/docs/recipes/32-action-game.md +21 -11
- package/docs/recipes/33-stream-sources.md +6 -3
- package/docs/recipes/34-environment-lighting.md +72 -25
- package/docs/recipes/35-picture-from-reference.md +20 -23
- package/docs/recipes/36-ground-plants.md +106 -0
- package/docs/recipes/40-scene.md +18 -21
- package/docs/recipes/43-shader-patches-surfaces.md +27 -48
- package/docs/recipes/44-water-weather-hooks.md +56 -50
- package/docs/recipes/45-cascaded-shadows.md +41 -20
- package/docs/recipes/46-blender-art-route.md +9 -10
- package/docs/recipes/49-game-module-contract.md +7 -6
- package/docs/recipes/50-own-renderer.md +3 -2
- package/docs/recipes/51-capability-catalog.md +14 -8
- package/docs/recipes/52-around-the-picture.md +56 -100
- package/docs/recipes/53-ground-up-close.md +61 -24
- package/docs/recipes/55-mods-time-wrap.md +17 -20
- package/docs/recipes/56-webgpu-tsl.md +28 -15
- package/docs/recipes/57-control.md +39 -12
- package/docs/recipes/58-input.md +15 -2
- package/docs/recipes/59-depth-post-effects.md +1 -1
- package/docs/recipes/60-judge-the-picture.md +30 -25
- package/docs/recipes/62-picture-code.md +129 -39
- package/docs/recipes/63-third-person-start.md +19 -5
- package/docs/recipes/64-particles.md +54 -5
- package/docs/recipes/65-swarm.md +140 -0
- package/docs/recipes/66-common-tasks.md +313 -0
- package/examples/action/.threedog/content-index.json +1 -1
- package/examples/action/GAMEMAP.md +5 -5
- package/examples/perf-island/.threedog/content-index.json +1 -0
- package/examples/{sheepisland → perf-island}/GAMEMAP.md +15 -14
- 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 +4 -1
- package/examples/rc2d/GAMEMAP.md +4 -3
- package/examples/rc2d/main.js +1 -3
- package/examples/rc2d/rc2d.js +1 -1
- package/examples/styletest/.threedog/content-index.json +1 -1
- package/examples/styletest/GAMEMAP.md +6 -5
- 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 +2 -1
- package/examples/world/.threedog/content-index.json +1 -1
- package/examples/world/GAMEMAP.md +9 -7
- package/examples/world/main.js +3 -3
- package/examples/world/picture/sky.js +1 -1
- package/index.d.ts +16 -12
- package/index.js +53 -32
- package/llms.txt +11 -14
- package/modules/ambience/Ambience.js +16 -11
- package/modules/calendar/Calendar.js +19 -19
- package/modules/calendar/index.js +18 -16
- package/modules/calendar/schedule.js +11 -6
- package/modules/calendar/seasons.js +7 -7
- package/modules/camera/FirstPersonCamera.js +5 -5
- package/modules/camera/FixedCamera.js +43 -30
- package/modules/camera/FollowCamera.js +24 -15
- package/modules/camera/RtsCamera.js +12 -11
- package/modules/camera/common.js +72 -37
- package/modules/camera/contract.js +1 -0
- package/modules/camera/pixelSnap.js +62 -0
- package/modules/characters/Character.js +166 -70
- package/modules/characters/NPC.js +84 -44
- package/modules/characters/assetModel.js +16 -12
- package/modules/characters/astar.js +48 -27
- package/modules/characters/behaviors.js +4 -5
- package/modules/characters/character.contract.js +21 -0
- package/modules/characters/contract.js +17 -3
- package/modules/characters/index.js +240 -226
- package/modules/characters/moveHelpers.js +88 -12
- package/modules/characters/mover.contract.js +14 -0
- package/modules/characters/movers/common.js +22 -18
- package/modules/characters/movers/manual.js +1 -1
- package/modules/characters/movers/rapier.js +18 -10
- package/modules/characters/movers/simple.js +26 -13
- package/modules/characters/movers/support.js +24 -13
- package/modules/characters/npcAvoid.js +19 -16
- package/modules/characters/npcSim.js +88 -32
- package/modules/characters/npcView.js +19 -11
- package/modules/characters/pathAsync.js +81 -29
- package/modules/characters/pathJob.js +38 -21
- package/modules/characters/pathWorker.js +1 -1
- package/modules/characters/player.js +120 -0
- package/modules/characters/playerStrings.js +2 -2
- package/modules/characters/proceduralRig.js +2 -2
- package/modules/characters/seat.js +56 -0
- package/modules/characters/useModel.js +3 -3
- package/modules/characters/vehicle.contract.js +8 -5
- package/modules/characters/walkTo.js +40 -33
- package/modules/collision/Collision.js +69 -45
- package/modules/collision/contract.js +15 -0
- package/modules/collision/grid.js +6 -1
- package/modules/content/explain.js +2 -3
- package/modules/content/fields.js +24 -3
- package/modules/content/ids.js +5 -3
- package/modules/content/index.js +132 -114
- package/modules/content/loader.js +117 -140
- package/modules/content/markers.js +25 -0
- package/modules/content/models.js +54 -17
- package/modules/content/packs.js +5 -4
- package/modules/content/parts.js +2 -2
- package/modules/content/places.js +36 -0
- package/modules/content/props.js +22 -17
- package/modules/content/rules.js +47 -61
- package/modules/content/stages.js +7 -7
- package/modules/content/templates.js +80 -49
- package/modules/content/words.js +47 -0
- package/modules/debug/DebugPanel.js +14 -45
- package/modules/flow/contract.js +2 -1
- package/modules/flow/index.js +30 -16
- package/modules/gameplay/Container.js +17 -13
- package/modules/gameplay/Containers.js +23 -6
- package/modules/gameplay/Dialogue.js +93 -34
- package/modules/gameplay/Interactions.js +93 -51
- package/modules/gameplay/Inventory.js +64 -22
- package/modules/gameplay/Quests.js +146 -30
- package/modules/gameplay/boxOps.js +8 -1
- package/modules/gameplay/dialogueBubbles.js +16 -12
- package/modules/gameplay/inventoryOps.js +11 -8
- package/modules/gameplay/pickups.js +63 -37
- package/modules/gameplay/questLog.js +4 -2
- package/modules/gameplay/questSave.js +9 -4
- package/modules/gameplay/quests.contract.js +1 -1
- package/modules/grid/Grid.js +2 -2
- package/modules/grid/Layer.js +12 -8
- package/modules/grid/index.js +28 -23
- package/modules/grid/ops.js +43 -46
- package/modules/grid/preview.js +7 -7
- package/modules/grid/tiles.js +6 -6
- package/modules/hlod/index.js +42 -57
- package/modules/hud/index.js +22 -14
- package/modules/hud/parts.js +8 -8
- package/modules/level/contract.js +16 -0
- package/modules/level/heightfield.js +29 -31
- package/modules/level/index.js +113 -161
- package/modules/level/load.js +196 -0
- package/modules/level/meshes.js +65 -0
- package/modules/level/nodes.js +40 -23
- package/modules/lights/index.js +33 -183
- package/modules/lights/slots.js +93 -0
- package/modules/lights/sources.js +90 -0
- package/modules/music/Music.js +34 -28
- package/modules/music/rules.js +1 -1
- package/modules/nav/contract.js +16 -0
- package/modules/nav/index.js +180 -49
- package/modules/nav/navPath.js +45 -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 +6 -5
- package/modules/net/sync.js +2 -2
- package/modules/net/transports.js +2 -2
- package/modules/particles/Particles.js +95 -29
- package/modules/particles/effect.js +86 -32
- package/modules/particles/shaders.js +19 -1
- package/modules/photo/Photo.js +23 -23
- package/modules/rigid/RigidBodies.js +255 -89
- package/modules/rigid/Vehicles.js +17 -8
- package/modules/rigid/collider3d.contract.js +26 -0
- package/modules/rigid/ragdoll.js +298 -0
- package/modules/rigid/ragdollBones.js +209 -0
- package/modules/rigid/refresh.js +10 -0
- package/modules/rigid/sync.js +51 -20
- package/modules/settings/Settings.js +177 -61
- package/modules/settings/apply.js +20 -13
- package/modules/settings/sections.js +19 -14
- package/modules/settings/strings.js +2 -2
- 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 +17 -28
- package/modules/sky/tint.js +1 -1
- package/modules/swarm/Swarm.js +356 -0
- package/modules/swarm/draw.js +68 -0
- package/modules/swarm/grid.js +63 -0
- package/modules/terrain/ChunkManager.js +71 -59
- 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 +42 -42
- package/modules/terrain/terrainColorMap.js +6 -3
- package/modules/terrain/terrainDefaults.js +2 -1
- package/modules/terrain/terrainEdit.js +45 -29
- package/modules/terrain/terrainGen.js +19 -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 +83 -43
- package/modules/timeline/Tween.js +25 -19
- package/modules/timeline/shots.js +24 -17
- package/modules/triggers/index.js +95 -28
- package/modules/vegetation/Vegetation.js +34 -26
- package/modules/vegetation/densityMap.js +4 -7
- package/modules/vegetation/draw.js +39 -18
- package/modules/vegetation/groundChunks.js +21 -38
- package/modules/vegetation/index.js +37 -12
- package/modules/vegetation/modelGeometry.js +3 -6
- package/modules/vegetation/nearFade.js +1 -1
- package/modules/water/Water.js +20 -16
- package/modules/water/surface.js +3 -3
- package/modules/weather/Weather.js +52 -40
- package/modules/weather/particles.js +8 -8
- package/modules/weather/weatherDraw.js +28 -23
- package/modules/world/World.js +28 -15
- package/modules/world/explain.js +1 -1
- package/modules/world/index.js +30 -17
- package/modules/world/persist.js +90 -27
- package/modules/world/pos.js +5 -5
- package/modules/world/records.js +37 -11
- package/modules/world/sim.js +78 -27
- package/modules/world/simFar.js +2 -2
- package/modules/world/state.js +43 -11
- package/modules/world/thingSource.js +20 -5
- package/modules/world/views.js +27 -14
- package/package.json +48 -7
- package/presets.js +1 -3
- package/render/PostFX.js +83 -53
- package/render/backend.js +31 -33
- 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/particles.tsl.js +8 -6
- package/render/fx/patchNodes.tsl.js +5 -15
- package/render/fx/postWebGPU.tsl.js +30 -26
- 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 +2 -2
- package/render/lighting.js +5 -3
- package/render/lightmap.js +41 -21
- 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 +62 -15
- package/render/ownFrame.js +4 -4
- package/render/patches.js +15 -15
- package/render/postWebGL.js +15 -12
- package/render/probes.js +41 -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 +59 -13
- package/render/slots.js +7 -7
- package/render/terms.js +22 -24
- package/render/uniformDecl.js +1 -1
- package/types/core.d.ts +336 -202
- package/types/gameplay.d.ts +254 -130
- 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} +8 -16
- 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} +28 -10
- package/types/generated/core/input/inputSeat.d.ts +26 -0
- package/types/generated/core/{Budget.d.ts → inspect/Budget.d.ts} +36 -26
- package/types/generated/core/{DebugOverrides.d.ts → inspect/DebugOverrides.d.ts} +17 -3
- package/types/generated/core/{Ops.d.ts → ops/Ops.d.ts} +6 -4
- package/types/generated/core/{control.d.ts → ops/control.d.ts} +14 -10
- package/types/generated/core/{Saves.d.ts → saves/Saves.d.ts} +62 -18
- package/types/generated/core/{session.d.ts → saves/session.d.ts} +3 -2
- package/types/generated/core/{Rays.d.ts → scene/Rays.d.ts} +8 -27
- package/types/generated/core/{Views.d.ts → scene/Views.d.ts} +2 -2
- package/types/generated/core/{Batching.d.ts → stream/Batching.d.ts} +7 -7
- package/types/generated/core/{Stream.d.ts → stream/Stream.d.ts} +22 -18
- 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/Grid.d.ts +1 -0
- 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 +5 -4
- 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 +7 -5
- package/types/generated/modules/water/Water.d.ts +1 -0
- package/types/generated/modules/weather/Weather.d.ts +14 -16
- package/types/generated/modules/weather/weatherDraw.d.ts +3 -3
- package/types/generated/modules/world/World.d.ts +11 -7
- package/types/generated/render/PostFX.d.ts +21 -23
- 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 +47 -15
- package/types/physics.d.ts +150 -73
- package/types/pixel.d.ts +75 -0
- package/types/tsl.d.ts +37 -4
- package/types/world.d.ts +48 -75
- package/ui/Focus.js +10 -9
- package/ui/Parts.js +13 -5
- package/ui/UI.js +7 -7
- package/ui/defaults.js +3 -2
- package/ui/theme.js +7 -5
- package/core/assetEntry.js +0 -109
- package/core/engineCamera.js +0 -32
- package/core/ground.js +0 -104
- package/core/holds.js +0 -134
- package/core/math.js +0 -48
- package/core/moduleSlots.js +0 -100
- package/core/modules.js +0 -314
- package/core/saveApply.js +0 -210
- package/core/saveValues.js +0 -46
- package/core/session.js +0 -174
- package/core/shadowTypes.js +0 -16
- package/core/util.js +0 -17
- package/core/view.js +0 -43
- 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/examples/sheepisland/.threedog/content-index.json +0 -1
- package/modules/camera/projection.js +0 -21
- /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/{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/{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
|
@@ -6,24 +6,28 @@
|
|
|
6
6
|
// inventory.define('fish', { name: '鲫鱼', icon: '🐟', iconUrl: '/textures/fish.png', desc: '河里钓的', stack: 20, weight: 0.5 });
|
|
7
7
|
// inventory.add('fish', 2); inventory.has('fish', 1); inventory.remove('fish'); // the local user's bag (engine.actor)
|
|
8
8
|
// inventory.of(ctx.actor).add('fish'); // inside an op: the bag of whoever runs it (a net peer, an NPC)
|
|
9
|
-
// One piece with its own data: const key = inventory.add('sword', 1, { data: { durability: 80 } }); // 'sword#1'; count('sword') counts every sword
|
|
9
|
+
// One piece with its own data: const { key } = inventory.add('sword', 1, { data: { durability: 80 } }); // 'sword#1'; count('sword') counts every sword
|
|
10
10
|
// Chest / corpse / shelf: inventory.container('chest-1', { capacity: 8 }).add('fish'); inventory.transfer('chest-1', 'player', 'fish', 2);
|
|
11
11
|
// Player actions with items are ops: inventory.transfer / inventory.use / inventory.drop (inventoryOps.js).
|
|
12
12
|
//
|
|
13
13
|
// Picture:
|
|
14
14
|
// window UI part 'inventory' (engine.ui.set('inventory', false | { drop: true } | yourPart)); body via ui.templates.inventory(data, { esc, t, icon })
|
|
15
15
|
// list styling CSS classes .threedog-win-inventory .threedog-row ... (override in ui.css)
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
16
|
+
import { keepTable } from '../../core/base/sections.js';
|
|
17
|
+
import { checkOptions, warnMissing, freezeDef } from '../../core/base/validate.js';
|
|
18
|
+
import { readParams } from '../../core/base/params.js';
|
|
19
|
+
import { codedError } from '../../core/base/errorHints.js';
|
|
19
20
|
import { Container } from './Container.js';
|
|
20
21
|
import { Containers } from './Containers.js';
|
|
21
|
-
import { followRuntimeIds } from '../../core/saveIds.js';
|
|
22
|
+
import { followRuntimeIds } from '../../core/saves/saveIds.js';
|
|
23
|
+
import { refuseSave } from '../../core/base/saveValues.js';
|
|
24
|
+
import { isPlainObject } from '../../core/base/util.js';
|
|
22
25
|
import { inventoryWindow, windowData, defineInventoryOps, INVENTORY_STRINGS } from './inventoryOps.js';
|
|
23
26
|
|
|
24
27
|
export class Inventory {
|
|
25
28
|
/** @internal track: the module's ctx.track */
|
|
26
|
-
constructor(engine, { action, capacity = Infinity, maxWeight = Infinity, defaultStack } = {},
|
|
29
|
+
constructor(engine, { action, capacity = Infinity, maxWeight = Infinity, defaultStack } = {}, ctx) {
|
|
30
|
+
const { track } = ctx;
|
|
27
31
|
this.engine = engine;
|
|
28
32
|
this.defs = new Map();
|
|
29
33
|
this.defaultStack = defaultStack;
|
|
@@ -31,24 +35,29 @@ export class Inventory {
|
|
|
31
35
|
// 'inventory' part. Other actors' bags are plain containers (net creates one per peer).
|
|
32
36
|
/** @internal */ this.home = new Container(this, 'player', { capacity, maxWeight });
|
|
33
37
|
this._containers = new Containers(this, this.home);
|
|
38
|
+
/** @internal start items of packs loaded after start(), given again at each new game */ this._lateStart = new Set();
|
|
34
39
|
this.action = action;
|
|
35
40
|
this._seq = 0; // entry key counter ('sword#7'), saved so keys never repeat
|
|
36
41
|
engine.i18n.add(INVENTORY_STRINGS);
|
|
37
42
|
// declared only: the game binds the key (presets.bindings.inventory or its own; [] = no key), so every key in a game comes from one bindings table
|
|
38
43
|
track(engine.input.action(action, { label: 'inventory.action', owner: 'inventory' }));
|
|
39
|
-
if (engine.input.keysOf(action).length) engine.input.touchButton(action, 'inventory.action');
|
|
40
|
-
|
|
44
|
+
if (engine.input.keysOf(action).length) track(engine.input.touchButton(action, 'inventory.action'));
|
|
45
|
+
ctx.ui.define('inventory', inventoryWindow, { modal: { cancel: e => e.ui.close('inventory'), freeze: () => this.pauseGame, data: () => windowData(this) } });
|
|
41
46
|
for (const ev of ['i18n:change', 'input:rebind']) track(engine.events.on(ev, () => this._refresh()));
|
|
47
|
+
// a pack loaded after start() stays for the next playthrough with its props and definitions, and its start items with them
|
|
48
|
+
track(engine.events.on('session:start', ({ kind }) => { if (kind === 'new') for (const d of this._lateStart) this.giveStart(d); }));
|
|
49
|
+
track(engine.events.on('session:end', () => engine.ui.close('inventory'))); // it shows the playthrough that ended, and its freeze must not reach the next one
|
|
42
50
|
// version 1 is the current shape; raise it with a migrate step when it changes. seq: the numbering of entry keys (sword#3); a save without it continues
|
|
43
51
|
// after the highest key it holds
|
|
44
|
-
|
|
52
|
+
ctx.saves.register('inventory', { atomic: true, version: 1, save: () => ({ seq: this._seq, items: this.home._save() }), load: d => {
|
|
53
|
+
if (d != null && !(isPlainObject(d) && (d.items == null || Array.isArray(d.items)))) refuseSave('inventory', 'the part', 'must be { seq, items: [{ id, count }] }', d);
|
|
45
54
|
this.home._load(d?.items);
|
|
46
55
|
const top = Math.max(0, ...this.home._entries.map(x => Number(x.key.split('#')[1]) || 0));
|
|
47
|
-
this._seq = Number.
|
|
56
|
+
this._seq = Number.isSafeInteger(d?.seq) && d.seq >= top ? d.seq : top; // past safe whole numbers ++ stops counting and keys repeat
|
|
48
57
|
this._refresh();
|
|
49
58
|
} });
|
|
50
59
|
// version 2: container ids that are runtime record ids (a spawned chest) follow the world part's `kind-n` -> `kind#n` rename (world/persist.js)
|
|
51
|
-
|
|
60
|
+
ctx.saves.register('containers', { atomic: true, version: 2, migrate: { 1: followRuntimeIds }, save: () => this._containers.save(), load: d => this._containers.load(d) });
|
|
52
61
|
}
|
|
53
62
|
|
|
54
63
|
/**
|
|
@@ -58,6 +67,10 @@ export class Inventory {
|
|
|
58
67
|
* @param {string} [actor]
|
|
59
68
|
* @returns {Container}
|
|
60
69
|
*/
|
|
70
|
+
/** @internal start items into the bag, written outside ops like the load they stand for; late: every new game gives them again */
|
|
71
|
+
giveStart(d, late = false) { this.engine.ops.allow(() => { for (const [id, n] of Object.entries(d)) this.add(id, n, { silent: true }); }); if (late) this._lateStart.add(d); }
|
|
72
|
+
/** @internal the pack that gave them left */
|
|
73
|
+
forgetStart(d) { this._lateStart.delete(d); }
|
|
61
74
|
of(actor = this.engine.actor) { return this._containers.map.get(actor) ?? this._containers.get(actor); }
|
|
62
75
|
/** The player inventory: the container of engine.actor (read live, so it follows a hand-over of control). */
|
|
63
76
|
get bag() { return this.of(); }
|
|
@@ -88,11 +101,20 @@ export class Inventory {
|
|
|
88
101
|
*/
|
|
89
102
|
container(id, opts) { return this._containers.get(id, opts); }
|
|
90
103
|
/**
|
|
91
|
-
* Content renames (content/renames.js): containers saved under an old authored id move to the new one (content.load calls it before adding containers)
|
|
104
|
+
* @internal Content renames (content/renames.js): containers saved under an old authored id move to the new one (content.load calls it before adding containers)
|
|
92
105
|
* @param {Record<string, string | null>} map
|
|
93
|
-
* @returns {void}
|
|
106
|
+
* @returns {() => void} what puts the containers back, for a failed load
|
|
107
|
+
*/
|
|
108
|
+
renameIds(map) { return this._containers.rename(map); }
|
|
109
|
+
/**
|
|
110
|
+
* @internal A failed content load puts defs, containers and goods back (core/base/sections.js undo): the function that does it
|
|
111
|
+
* @returns {() => void}
|
|
94
112
|
*/
|
|
95
|
-
|
|
113
|
+
undoPoint() {
|
|
114
|
+
const boxes = this._containers, seq = this._seq, tables = [this.defs, boxes.map, boxes.renames].map(keepTable);
|
|
115
|
+
const was = [...boxes.map.values()].map(c => [c, { id: c.id, capacity: c.capacity, maxWeight: c.maxWeight, seeded: c.seeded, _start: c._start, _entries: c._entries.map(x => ({ ...x })) }]);
|
|
116
|
+
return () => { for (const fn of tables) fn(); for (const [c, v] of was) Object.assign(c, v); this._seq = seq; };
|
|
117
|
+
}
|
|
96
118
|
/**
|
|
97
119
|
* Move n (default 1) of an item, or of one entry by key, between containers (container or id; an actor's bag has the actor's id). Pieces keep their data and key.
|
|
98
120
|
* Moves fewer if the target is full, returns how many moved (0 = none). Players moving items run the op instead: engine.ops.run('inventory.transfer', { from,
|
|
@@ -132,7 +154,7 @@ export class Inventory {
|
|
|
132
154
|
|
|
133
155
|
/**
|
|
134
156
|
* Define an item. stack = pieces per slot (default 99); weight counts against maxWeight; use(e, { actor, item, key, data }) makes it usable with the
|
|
135
|
-
* inventory.use op (canUse returns true or a reason, consume: true removes one first). Games may add their own fields (price...).
|
|
157
|
+
* inventory.use op (canUse returns true or a reason, consume: true removes one first; use answers { ok: false, code } or throws: the item stays and no item:use). Games may add their own fields (price...).
|
|
136
158
|
* The definition is shared by every piece and frozen; per-piece state (durability, ammo) goes in entry data: add('sword', 1, { data: { durability: 40 } }).
|
|
137
159
|
* @example engine.inventory.define('potion', { name: 'Potion', icon: '🧪', weight: 0.2, consume: true, use: (e, { actor }) => heal(actor, 30) })
|
|
138
160
|
* @param {string} id
|
|
@@ -160,12 +182,11 @@ export class Inventory {
|
|
|
160
182
|
* @param {{ takeN?: number, giveN?: number, data?: Record<string, any>, silent?: boolean }} [opts]
|
|
161
183
|
*/
|
|
162
184
|
trade(take, give, opts) { return this.bag.trade(take, give, opts); }
|
|
163
|
-
get slotsUsed() { return this.bag.slotsUsed; }
|
|
164
185
|
/** Player inventory entries: [{ key, id, count, data, def }] (for custom UI). */
|
|
165
186
|
list() { return this.bag.list(); }
|
|
166
|
-
/** One player inventory entry by key: { key, id, count, data, def } or
|
|
187
|
+
/** One player inventory entry by key: { key, id, count, data, def } or undefined. */
|
|
167
188
|
get(key) { return this.bag.get(key); }
|
|
168
|
-
/** Add n (default 1) to the player inventory, opts { data, silent }; returns
|
|
189
|
+
/** Add n (default 1) to the player inventory, opts { data, silent }; returns { ok: true, key, added }, or { ok: false, code: 'full' } when none fit. */
|
|
169
190
|
add(id, n = 1, opts) { return this.bag.add(id, n, opts); }
|
|
170
191
|
/** Remove n (default 1) of an item or entry key from the player inventory; returns false if not enough. */
|
|
171
192
|
remove(id, n = 1) { return this.bag.remove(id, n); }
|
|
@@ -186,6 +207,24 @@ const INVENTORY_PARAMS = {
|
|
|
186
207
|
pauseGame: { type: 'bool', optional: true, desc: 'true: gameplay freezes while the window is open (default false)' },
|
|
187
208
|
};
|
|
188
209
|
|
|
210
|
+
/** The item sections of content data. Containers hold their goods only the first time: the save wins, an emptied chest does not refill on reload */
|
|
211
|
+
const keepBag = (d, { engine: e }) => e.inventory.undoPoint();
|
|
212
|
+
const INVENTORY_CONTENT = {
|
|
213
|
+
items: { desc: 'items (id -> name, icon, description); also export startItems for starting items', undo: keepBag, commit(d, { engine: e }) { for (const [id, def] of Object.entries(d)) e.inventory.define(id, def); } },
|
|
214
|
+
startItems: {
|
|
215
|
+
desc: 'starting items (exported from items.js)', once: true,
|
|
216
|
+
undo(d, c) { const back = keepBag(d, c); return () => { back(); c.engine.inventory.forgetStart(d); }; },
|
|
217
|
+
references: d => Object.keys(d).map(id => ({ section: 'items', id, at: 'startItems' })),
|
|
218
|
+
commit(d, { engine: e }) { e.inventory.giveStart(d, e.session.captured); }, // after start() the new-game state has no such items
|
|
219
|
+
},
|
|
220
|
+
containers: {
|
|
221
|
+
desc: 'chests / shelves (container id -> { capacity, items: starting goods }; starting goods are placed only the first time, then saved)', undo: keepBag,
|
|
222
|
+
references: d => Object.entries(d).flatMap(([box, c]) => Object.keys(c.items ?? {}).map(id => ({ section: 'items', id, at: `containers.${box}` }))),
|
|
223
|
+
validate(d, { ids }) { for (const id of Object.keys(d)) ids.claim(id, `containers.${id}`); },
|
|
224
|
+
commit(d, { engine: e }) { for (const [id, c] of Object.entries(d)) e.inventory.container(id, { capacity: c.capacity, items: c.items }); },
|
|
225
|
+
},
|
|
226
|
+
};
|
|
227
|
+
|
|
189
228
|
/**
|
|
190
229
|
* Inventory module. Installs engine.inventory, the 'inventory' UI part and the ops inventory.transfer / use / drop / trade (drop needs pickups()); items
|
|
191
230
|
* on the ground are the pickups() module.
|
|
@@ -198,13 +237,14 @@ export function inventory(opts = {}) {
|
|
|
198
237
|
const o = readParams('inventory', INVENTORY_PARAMS, opts);
|
|
199
238
|
let inv = null;
|
|
200
239
|
return {
|
|
201
|
-
|
|
240
|
+
content: INVENTORY_CONTENT,
|
|
241
|
+
name: 'inventory', skipKind: 'none', type: 'rules', provides: ['inventory'], label: 'Inventory', params: INVENTORY_PARAMS, options: o, noSkip: 'no timers or spatial state',
|
|
202
242
|
install(e, ctx) {
|
|
203
|
-
inv = new Inventory(e, o, ctx
|
|
243
|
+
inv = new Inventory(e, o, ctx); // o: the schema defaults are filled in, the class repeats none
|
|
204
244
|
// pauseGame: true freezes gameplay (engine.freeze('ui-inventory'), the part's own owner; the same mechanism flow's 'paused' and settings({ freezeWorld }) use) while the window is open.
|
|
205
245
|
// Rendering and UI go on; the freeze is released when the window closes or the inventory is turned off with engine.ui.set('inventory', false).
|
|
206
246
|
inv.pauseGame = !!opts.pauseGame; // also settable at runtime: engine.inventory.pauseGame = true
|
|
207
|
-
defineInventoryOps(e, inv);
|
|
247
|
+
defineInventoryOps(e, ctx, inv);
|
|
208
248
|
return inv;
|
|
209
249
|
},
|
|
210
250
|
frame(dt, e) { // the inventory key toggles the part; while open the part holds the input lock, so the close press is read raw
|
|
@@ -214,7 +254,9 @@ export function inventory(opts = {}) {
|
|
|
214
254
|
describe(e) {
|
|
215
255
|
const show = c => Object.fromEntries(c._entries.map(x => [x.key, x.data === undefined ? x.count : { count: x.count, data: x.data }]));
|
|
216
256
|
const boxes = Object.fromEntries([...inv._containers.map].filter(([, c]) => c !== inv.bag && c._entries.length).map(([id, c]) => [id, show(c)]));
|
|
217
|
-
return { items: show(inv.bag), slots: inv.capacity === Infinity ? `${inv.slotsUsed}` : `${inv.slotsUsed}/${inv.capacity}`, ...(inv.bag.weight && { weight: `${inv.bag.weight}/${inv.bag.maxWeight}` }), ...(Object.keys(boxes).length && { containers: boxes }) };
|
|
257
|
+
return { items: show(inv.bag), slots: inv.capacity === Infinity ? `${inv.bag.slotsUsed}` : `${inv.bag.slotsUsed}/${inv.capacity}`, ...(inv.bag.weight && { weight: `${inv.bag.weight}/${inv.bag.maxWeight}` }), ...(Object.keys(boxes).length && { containers: boxes }) };
|
|
218
258
|
},
|
|
219
259
|
};
|
|
220
260
|
}
|
|
261
|
+
|
|
262
|
+
export const handRolled = [{ kind: 'inventory', seen: 'a hand-made inventory (items kept in your own array / object)', use: 'the inventory module: engine.use(inventory()), engine.inventory.add / remove / has (counts, containers, events, saved with the game)', quiet: /\b(engine|e|eng)\.inventory\b|\binventory\(\s*[{)]/, code: /(?:\b(?:const|let|var)\s+|\bthis\.)(inventory|backpack|bag|pockets|inv)(?:Items|Slots|List|Contents|Data|Map|Counts?|s)?\s*=\s*(\[\s*\]|\{\s*\}|new Map\b|new Set\b)/i, tags: false }];
|
|
@@ -12,26 +12,35 @@
|
|
|
12
12
|
// quests.start('first-photo');
|
|
13
13
|
// A step can be parallel goals { text?, all: [{ text, done, target, optional }] } (done when every non-optional part is done, in any order);
|
|
14
14
|
// a quest can fail: fail: e => bool is checked while it is active, then onFail runs, quest:fail fires, and start(id) may begin it again.
|
|
15
|
+
// Reward: the quest finishes either way. A reward that answers with a failure (content.run's answer, or { ok: false, code } from a function) is decided in _pay, the one place
|
|
16
|
+
// for it: the game's onUnpaid if it has one; else the items that did not fit are owed (saved, in list()) and go into the bag when there is room. Either way quest:unpaid fires.
|
|
15
17
|
// Saves name steps and parts by id (step / part id: 'mayor'), else by position; give them ids once the game ships, so inserting a step later
|
|
16
|
-
// does not move players to another step. Save shape (version
|
|
17
|
-
// [partId] } } } }.
|
|
18
|
+
// does not move players to another step. Save shape (version 3): { state: { questId: { step?: stepId, done?, failed?, owed?: { itemId: n }, parts?: [partId met], got?: { stepId:
|
|
19
|
+
// [partId] }, visited?: [stepId left] } } }.
|
|
20
|
+
// A step goes to the next in the list unless it has `next`: a step id, or e => id chosen when the step is done (branches; visited says which ran); false finishes the quest there.
|
|
18
21
|
// The log window is the UI part 'questLog' (questLog.js): replace it or turn it off with engine.ui.set('questLog', ...) (recipes/26-ui-parts.md).
|
|
22
|
+
import { keepTable } from '../../core/base/sections.js';
|
|
19
23
|
import { toast, toggleOnKey } from '../../ui/UI.js';
|
|
20
24
|
import { questLogWindow } from './questLog.js';
|
|
21
|
-
import { warnMissing, DEV } from '../../core/validate.js';
|
|
22
|
-
import { readParams, keysSchema } from '../../core/params.js';
|
|
23
|
-
import { codedError } from '../../core/errorHints.js';
|
|
25
|
+
import { warnMissing, warnOnce, DEV } from '../../core/base/validate.js';
|
|
26
|
+
import { readParams, keysSchema } from '../../core/base/params.js';
|
|
27
|
+
import { codedError } from '../../core/base/errorHints.js';
|
|
28
|
+
import { reportError } from '../../core/base/errors.js';
|
|
29
|
+
import { isPlainObject } from '../../core/base/util.js';
|
|
30
|
+
import { failure, isRunFailure } from '../../core/ops/opsFail.js';
|
|
31
|
+
import { refuseSave } from '../../core/base/saveValues.js';
|
|
24
32
|
import { toSaved, fromSaved, migrateV1, stepId } from './questSave.js';
|
|
25
33
|
|
|
26
34
|
const STRINGS = {
|
|
27
|
-
'zh-CN': { 'module.quests': '任务', 'quests.title': '任务日志', 'quests.action': '任务', 'quests.empty': '还没有任务。', 'quests.new': '新任务:{title}', 'quests.done': '任务完成:{title}', 'quests.doneTag': '(已完成)', 'quests.failed': '任务失败:{title}' },
|
|
28
|
-
en: { 'module.quests': 'quests', 'quests.title': 'Journal', 'quests.action': 'Journal', 'quests.empty': 'No quests yet.', 'quests.new': 'New quest: {title}', 'quests.done': 'Quest complete: {title}', 'quests.doneTag': ' (done)', 'quests.failed': 'Quest failed: {title}' },
|
|
35
|
+
'zh-CN': { 'module.quests': '任务', 'quests.title': '任务日志', 'quests.action': '任务', 'quests.empty': '还没有任务。', 'quests.new': '新任务:{title}', 'quests.done': '任务完成:{title}', 'quests.unpaid': '奖励未能发放:{title}', 'quests.doneTag': '(已完成)', 'quests.failed': '任务失败:{title}' },
|
|
36
|
+
en: { 'module.quests': 'quests', 'quests.title': 'Journal', 'quests.action': 'Journal', 'quests.empty': 'No quests yet.', 'quests.new': 'New quest: {title}', 'quests.done': 'Quest complete: {title}', 'quests.unpaid': 'Reward not given: {title}', 'quests.doneTag': ' (done)', 'quests.failed': 'Quest failed: {title}' },
|
|
29
37
|
};
|
|
30
38
|
|
|
31
39
|
/** A step's text; a parallel step without its own text lists its required parts */
|
|
32
40
|
const stepText = st => st.text ?? st.all.filter(p => !p.optional).map(p => p.text).join(' / ');
|
|
33
41
|
export class Quests {
|
|
34
|
-
constructor(engine, { action, checkInterval, notify } = {},
|
|
42
|
+
constructor(engine, { action, checkInterval, notify } = {}, ctx) {
|
|
43
|
+
const { track } = ctx;
|
|
35
44
|
this.engine = engine;
|
|
36
45
|
this.defs = new Map();
|
|
37
46
|
/** @internal id -> { step, done, failed?, parts? (parts done in the current parallel step), got? (parts met in finished parallel steps) }; read it with state(id) */
|
|
@@ -44,10 +53,9 @@ export class Quests {
|
|
|
44
53
|
engine.i18n.add(STRINGS);
|
|
45
54
|
// declared only: the game binds the key (presets.bindings.quests or its own; [] = no key), so every key in a game comes from one bindings table
|
|
46
55
|
track(engine.input.action(action, { label: 'quests.action', owner: 'quests' }));
|
|
47
|
-
this.win = questLogWindow(engine, this,
|
|
48
|
-
// counters live in engine.vars
|
|
56
|
+
this.win = questLogWindow(engine, this, ctx); // { open, toggle, refresh } over engine.ui
|
|
49
57
|
// saved by stable step ids (questSave.js); version 1 saved positions
|
|
50
|
-
|
|
58
|
+
ctx.saves.register('quests', { atomic: true, version: 3, migrate: { 1: d => migrateV1(this.defs, d), 2: d => d }, save: () => this._save(), load: d => this._load(d) });
|
|
51
59
|
}
|
|
52
60
|
|
|
53
61
|
/**
|
|
@@ -62,17 +70,24 @@ export class Quests {
|
|
|
62
70
|
* @param {string} id
|
|
63
71
|
* @param {any} def
|
|
64
72
|
*/
|
|
73
|
+
/** @internal A failed content load puts the definitions back, and the progress define took from the save (core/base/sections.js undo): the function that does it @returns {() => void} */
|
|
74
|
+
undoPoint() {
|
|
75
|
+
const defs = keepTable(this.defs), saved = { ...this._saved }, progress = { ...this._progress };
|
|
76
|
+
return () => { defs(); this._saved = saved; this._progress = progress; };
|
|
77
|
+
}
|
|
65
78
|
define(id, def) {
|
|
66
79
|
const at = `quests.define('${id}')`;
|
|
67
|
-
readParams(at, keysSchema(['title', 'desc', 'steps', 'reward', 'fail', 'onFail']), def);
|
|
68
|
-
|
|
80
|
+
readParams(at, keysSchema(['title', 'desc', 'steps', 'reward', 'onUnpaid', 'fail', 'onFail']), def);
|
|
81
|
+
if (!Array.isArray(def?.steps)) throw codedError('quest-step', `${at}: steps is a list of steps, e.g. steps: [{ text: 'Find the key', done: e => e.vars.flag('key') }]; got ${JSON.stringify(def?.steps)}`); // every later read needs it, and this one names the quest
|
|
82
|
+
for (const s of def.steps) {
|
|
69
83
|
if (!s.all && (typeof s.done !== 'function' || s.optional !== undefined)) throw codedError('quest-step', `${at}: a step needs done (a function), or all: [parts] for parallel goals; optional goes on a part inside all`);
|
|
70
|
-
readParams(`${at} steps`, keysSchema(s.all ? ['id', 'text', 'all'] : ['id', 'text', 'done', 'target']), s);
|
|
84
|
+
readParams(`${at} steps`, keysSchema(s.all ? ['id', 'text', 'all', 'next'] : ['id', 'text', 'done', 'target', 'next']), s);
|
|
71
85
|
for (const p of s.all || []) readParams(`${at} parallel part`, keysSchema(['id', 'text', 'done', 'target', 'optional']), p);
|
|
72
86
|
if (s.all && !s.all.some(p => !p.optional)) throw codedError('quest-step', `${at}: a parallel step needs at least one part without optional: true, or it would finish at once`);
|
|
73
87
|
}
|
|
74
|
-
const ids =
|
|
88
|
+
const ids = def.steps.map((_, i) => stepId(def, i)), dup = ids.find((x, i) => ids.indexOf(x) !== i);
|
|
75
89
|
if (dup != null) throw codedError('quest-step', `${at}: two steps have the id '${dup}'; step ids must be unique (saves find a step by it)`);
|
|
90
|
+
for (const s of def.steps) if (s.next != null && s.next !== false && typeof s.next !== 'function' && !ids.includes(s.next)) throw codedError('quest-step', `${at}: next is a step id or e => id; '${s.next}' is not a step of this quest (${ids.join(', ')})`);
|
|
76
91
|
this.defs.set(id, def);
|
|
77
92
|
if (id in this._saved) { this._progress[id] = fromSaved(id, def, this._saved[id]); delete this._saved[id]; this.win.refresh(); }
|
|
78
93
|
return this;
|
|
@@ -87,18 +102,20 @@ export class Quests {
|
|
|
87
102
|
get _period() { return Math.max(1, Math.round(this.checkInterval * 60)); } // 60 = the engine's fixed steps per second
|
|
88
103
|
/** @internal */
|
|
89
104
|
_load(d) {
|
|
105
|
+
const quest = q => isPlainObject(q) && (q.visited == null || Array.isArray(q.visited)) && (q.parts == null || Array.isArray(q.parts)) && (q.got == null || (isPlainObject(q.got) && Object.values(q.got).every(Array.isArray)));
|
|
106
|
+
if (d != null && !(isPlainObject(d) && (d.state == null || (isPlainObject(d.state) && Object.values(d.state).every(quest))))) refuseSave('quests', 'the part', 'must be { state: { quest id: { step, done, parts, got } } }', d);
|
|
90
107
|
this._progress = {}; this._saved = {}; this._t = Number.isInteger(d?.checkIn) ? d.checkIn : 0;
|
|
91
108
|
for (const [id, q] of Object.entries(d?.state || {})) { const def = this.defs.get(id); if (def) this._progress[id] = fromSaved(id, def, q); else this._saved[id] = q; }
|
|
92
109
|
this.win.refresh();
|
|
93
110
|
}
|
|
94
111
|
/**
|
|
95
|
-
* Quest list (for custom UI): unfinished first. A parallel step has parts [{ text, target, done, optional }]; its text defaults to the required parts joined.
|
|
112
|
+
* Quest list (for custom UI): unfinished first. A step is done once the quest has left it, so a step `next` jumped over stays not done, and the step a loop came back to is current. A parallel step has parts [{ text, target, done, optional }]; its text defaults to the required parts joined.
|
|
96
113
|
*/
|
|
97
114
|
list() {
|
|
98
115
|
return Object.entries(this._progress).filter(([id]) => this.defs.has(id)).sort((a, b) => a[1].done - b[1].done).map(([id, s]) => {
|
|
99
|
-
const d = this.defs.get(id), live = !s.done && !s.failed;
|
|
100
|
-
return { id, title: d.title, desc: d.desc, done: s.done, failed: !!s.failed, steps: d.steps.map((st, i) => {
|
|
101
|
-
const now = live && i === s.step, row = { text: st.text, target: st.target, done:
|
|
116
|
+
const d = this.defs.get(id), live = !s.done && !s.failed, ran = new Set(s.visited);
|
|
117
|
+
return { id, title: d.title, desc: d.desc, done: s.done, failed: !!s.failed, ...(s.owed && { owed: { ...s.owed } }), steps: d.steps.map((st, i) => {
|
|
118
|
+
const now = live && i === s.step, row = { text: st.text, target: st.target, done: !now && ran.has(stepId(d, i)), current: now };
|
|
102
119
|
if (st.all) {
|
|
103
120
|
const met = now ? s.parts : s.got?.[i];
|
|
104
121
|
row.parts = st.all.map((p, k) => ({ text: p.text, target: p.target, optional: !!p.optional, done: !!met?.[k] || (row.done && !p.optional) }));
|
|
@@ -110,7 +127,10 @@ export class Quests {
|
|
|
110
127
|
}
|
|
111
128
|
start(id) {
|
|
112
129
|
if (!this.defs.has(id)) { warnMissing('quest', id, [...this.defs.keys()]); return; }
|
|
113
|
-
if (this._progress[id] && !this._progress[id].failed)
|
|
130
|
+
if (this._progress[id] && !this._progress[id].failed) { // a failed quest may be taken again (a daily order, a retry); an active one is a harmless repeat
|
|
131
|
+
if (this._progress[id].done) warnOnce(`quests.start('${id}'): the quest is already done, so nothing happens (a done quest does not restart). Use a new quest id for a repeatable order, or let it fail first`);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
114
134
|
DEV && this.engine.ops.guard('quests.start');
|
|
115
135
|
this._progress[id] = { step: 0, done: false };
|
|
116
136
|
this._say('start', id, this.engine.t('quests.new', { title: this.defs.get(id).title }));
|
|
@@ -123,13 +143,13 @@ export class Quests {
|
|
|
123
143
|
else if (typeof this.notify === 'function') this.notify({ type, id, text });
|
|
124
144
|
}
|
|
125
145
|
/**
|
|
126
|
-
* One quest's progress as plain values: { step (index of the current step), steps (how many), done, failed, active } or null when it has not started.
|
|
146
|
+
* One quest's progress as plain values: { step (index of the current step), steps (how many), done, failed, active, visited (ids of the steps left) } or null when it has not started.
|
|
127
147
|
* A copy: change progress with start / advance, never by writing it.
|
|
128
148
|
* @param {string} id
|
|
129
149
|
*/
|
|
130
150
|
state(id) {
|
|
131
151
|
const s = this._progress[id], d = this.defs.get(id);
|
|
132
|
-
return s && d ? { step: s.step, steps: d.steps.length, done: !!s.done, failed: !!s.failed, active: !s.done && !s.failed } : null;
|
|
152
|
+
return s && d ? { step: s.step, steps: d.steps.length, done: !!s.done, failed: !!s.failed, active: !s.done && !s.failed, visited: [...s.visited ?? []] } : null;
|
|
133
153
|
}
|
|
134
154
|
/**
|
|
135
155
|
* Finish the current step by hand (a step the game completes from its own code: a cutscene ended, a boss fell) and go on; the last step completes the
|
|
@@ -138,20 +158,69 @@ export class Quests {
|
|
|
138
158
|
*/
|
|
139
159
|
advance(id) {
|
|
140
160
|
const s = this._progress[id], d = this.defs.get(id), e = this.engine;
|
|
141
|
-
if (!s || !d || s.done || s.failed) return false;
|
|
161
|
+
if (!s || !d || s.done || s.failed || s.step >= d.steps.length) return false; // past the last step: a quest:step listener, the quest is finishing
|
|
142
162
|
DEV && e.ops.guard('quests.advance');
|
|
143
|
-
|
|
163
|
+
this._leave(id, s, d); e.events.emit('quest:step', { id, step: s.step });
|
|
144
164
|
this._finishOrSay(id, s, d, true);
|
|
145
165
|
return true;
|
|
146
166
|
}
|
|
167
|
+
/** @internal go from the finished step to the next: its `next` (an id, or e => id asked now) else the following one; the step left goes into visited */
|
|
168
|
+
_leave(id, s, d) {
|
|
169
|
+
const here = stepId(d, s.step), st = d.steps[s.step];
|
|
170
|
+
let want = st.next;
|
|
171
|
+
if (typeof want === 'function') { try { want = want(this.engine); } catch (err) { reportError(this.engine, err, `quest '${id}' next`, { soft: true }); want = undefined; } }
|
|
172
|
+
(s.visited ??= []).includes(here) || s.visited.push(here);
|
|
173
|
+
delete s.parts;
|
|
174
|
+
const to = want == null ? s.step + 1 : want === false ? d.steps.length : d.steps.findIndex((_, i) => stepId(d, i) === want);
|
|
175
|
+
if (to < 0) { reportError(this.engine, codedError('quest-step', `quest '${id}': step '${here}' chose next '${want}', which is not a step; going to the following step`), 'quest next', { soft: true }); s.step++; } else s.step = to;
|
|
176
|
+
}
|
|
147
177
|
/** @internal after steps moved: complete the quest at the end, else announce the new step */
|
|
148
178
|
_finishOrSay(id, s, d, advanced) {
|
|
179
|
+
if (s.done || s.failed) return; // a quest:step listener already took it to its end: the reward is paid once
|
|
149
180
|
if (s.step >= d.steps.length) {
|
|
150
|
-
s.done = true;
|
|
181
|
+
s.done = true;
|
|
182
|
+
const paid = this._ask(id, 'reward', d.reward);
|
|
151
183
|
this._say('done', id, this.engine.t('quests.done', { title: d.title })); this.engine.events.emit('quest:done', { id });
|
|
184
|
+
this._pay(id, s, d, paid);
|
|
152
185
|
} else if (advanced) this._say('step', id, stepText(d.steps[s.step]));
|
|
153
186
|
if (advanced) this.win.refresh();
|
|
154
187
|
}
|
|
188
|
+
/**
|
|
189
|
+
* @internal Run a reward or onFail and read its answer. The quest has already moved on, so one that throws must not stop here: quest:done and the toast would be lost and the
|
|
190
|
+
* reward half given. It is reported (soft, no freeze) and answers as a failure, with what the words beside it said (words.js)
|
|
191
|
+
*/
|
|
192
|
+
_ask(id, what, fn, ...args) {
|
|
193
|
+
try { return fn?.(this.engine, ...args); } catch (err) {
|
|
194
|
+
reportError(this.engine, err, `quest '${id}' ${what}`, { soft: true });
|
|
195
|
+
return err.answer?.ok === false ? err.answer : failure('error');
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* @internal The one place that says what a reward not given means. What happens to it is the game's: onUnpaid decides, and then nothing is kept. Without one the safe default
|
|
200
|
+
* keeps what can be given later as a debt and tells the player. Function rewards and other words cannot be asked twice (they may have half run), so they are only reported
|
|
201
|
+
*/
|
|
202
|
+
_pay(id, s, d, answer) {
|
|
203
|
+
if (!isRunFailure(answer)) return;
|
|
204
|
+
const failed = answer.facts.failed ?? [{ word: 'reward', code: answer.code, facts: answer.facts }];
|
|
205
|
+
if (d.onUnpaid) this._ask(id, 'onUnpaid', d.onUnpaid, answer);
|
|
206
|
+
else {
|
|
207
|
+
for (const f of failed) for (const [item, n] of Object.entries(f.word === 'give' ? f.facts.left : {})) (s.owed ??= {})[item] = (s.owed?.[item] ?? 0) + n;
|
|
208
|
+
this._say('unpaid', id, this.engine.t('quests.unpaid', { title: d.title }));
|
|
209
|
+
}
|
|
210
|
+
this.engine.events.emit('quest:unpaid', { id, code: answer.code, failed, owed: s.owed ? { ...s.owed } : null });
|
|
211
|
+
}
|
|
212
|
+
/** @internal Pay a debt as far as it fits. Only when something does: add in a full bag tells the player so, and this asks twice a second. A debt that throws (the item is gone from the game) cannot be paid, ever */
|
|
213
|
+
_collect(id, s) {
|
|
214
|
+
const e = this.engine, bag = e.inventory?.of(e.ops.actor);
|
|
215
|
+
const answer = bag && this._ask(id, 'owed reward', () => {
|
|
216
|
+
for (const [item, n] of Object.entries(s.owed)) {
|
|
217
|
+
if ((bag.room?.(item) ?? 1) < 1) continue; // room is the engine bag's; a replacement without it is just asked
|
|
218
|
+
const r = bag.add(item, n), got = r.ok ? r.added : 0;
|
|
219
|
+
if (got < n) s.owed[item] = n - got; else delete s.owed[item];
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
if (isRunFailure(answer) || !Object.keys(s.owed).length) delete s.owed;
|
|
223
|
+
}
|
|
155
224
|
isDone(id) { return !!this._progress[id]?.done; }
|
|
156
225
|
isActive(id) { const s = this._progress[id]; return !!s && !s.done && !s.failed; }
|
|
157
226
|
isFailed(id) { return !!this._progress[id]?.failed; }
|
|
@@ -159,11 +228,13 @@ export class Quests {
|
|
|
159
228
|
check() {
|
|
160
229
|
const e = this.engine;
|
|
161
230
|
for (const [id, s] of Object.entries(this._progress)) {
|
|
231
|
+
if (s.owed) this._collect(id, s);
|
|
162
232
|
if (s.done || s.failed) continue;
|
|
163
233
|
const d = this.defs.get(id); if (!d) continue;
|
|
164
234
|
if (d.fail?.(e)) { this._fail(id, s, d); continue; }
|
|
165
235
|
let advanced = false;
|
|
166
|
-
|
|
236
|
+
// at most one pass over the steps per check: a `next` that loops back to a step already done must wait for the next check, not hang
|
|
237
|
+
for (let n = 0; n < d.steps.length && s.step < d.steps.length && this._stepDone(id, s, d.steps[s.step]); n++) { DEV && e.ops.guard('quests.advance'); this._leave(id, s, d); advanced = true; e.events.emit('quest:step', { id, step: s.step }); }
|
|
167
238
|
this._finishOrSay(id, s, d, advanced);
|
|
168
239
|
}
|
|
169
240
|
}
|
|
@@ -186,7 +257,7 @@ export class Quests {
|
|
|
186
257
|
_fail(id, s, d) {
|
|
187
258
|
DEV && this.engine.ops.guard('quests.fail');
|
|
188
259
|
s.failed = true;
|
|
189
|
-
d.onFail
|
|
260
|
+
this._ask(id, 'onFail', d.onFail);
|
|
190
261
|
this._say('fail', id, this.engine.t('quests.failed', { title: d.title }));
|
|
191
262
|
this.engine.events.emit('quest:fail', { id });
|
|
192
263
|
this.win.refresh();
|
|
@@ -195,10 +266,52 @@ export class Quests {
|
|
|
195
266
|
|
|
196
267
|
const QUEST_PARAMS = {
|
|
197
268
|
action: { type: 'string', default: 'quests', desc: 'input action that opens the quest log' },
|
|
198
|
-
checkInterval: { type: 'number', default: 0.5, min: 0, desc: 'seconds
|
|
269
|
+
checkInterval: { type: 'number', default: 0.5, min: 0, desc: 'real seconds between quest condition checks' },
|
|
199
270
|
notify: { type: 'any', default: true, desc: 'true = toast, false = silent, or a function ({ type, id, text }) => void' },
|
|
200
271
|
};
|
|
201
272
|
|
|
273
|
+
/**
|
|
274
|
+
* The quests section of content data, and its startQuest effect word. A step target can be a place, { place, x, z }, { x, z }, { npc: 'id' } (follows the NPC: the
|
|
275
|
+
* position is read each frame) or { nearest: itemId } (the nearest pickup). A step may be parallel goals { text?, all: [{ text, done, target, optional }] };
|
|
276
|
+
* fail / onFail are a condition and an effect like done / reward
|
|
277
|
+
*/
|
|
278
|
+
function questContent() {
|
|
279
|
+
const startOn = new Map();
|
|
280
|
+
const targets = q => q.steps.flatMap(s => s.all ?? [s]).map(s => s.target).filter(Boolean);
|
|
281
|
+
const listen = (e, track, id, event) => startOn.set(id, { event, on: track(e.events.on(event, () => e.quests?.start(id))) });
|
|
282
|
+
return {
|
|
283
|
+
desc: 'quests (id -> title, steps, reward; a step can have a target position)',
|
|
284
|
+
references: d => Object.entries(d).flatMap(([id, q]) => targets(q).flatMap(t => [
|
|
285
|
+
...(t.npc ? [{ section: 'npcs', id: t.npc, at: `quests.${id}` }] : []), ...(t.nearest ? [{ section: 'items', id: t.nearest, at: `quests.${id}` }] : [])])),
|
|
286
|
+
effects: { startQuest: { ref: 'quest', desc: 'start a quest', describe: v => `start quest ${v}`, run: (e, v) => e.quests.start(v) } },
|
|
287
|
+
undo(d, { engine: e, track }) {
|
|
288
|
+
const back = e.quests.undoPoint(), was = new Map(startOn);
|
|
289
|
+
return () => {
|
|
290
|
+
back();
|
|
291
|
+
for (const id of Object.keys(d)) {
|
|
292
|
+
startOn.get(id)?.on.remove(); startOn.delete(id);
|
|
293
|
+
if (was.has(id)) listen(e, track, id, was.get(id).event);
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
},
|
|
297
|
+
commit(d, { engine: e, content, where, track }) {
|
|
298
|
+
const target = t => t == null ? undefined : t.npc ? () => e.npcs?.get(t.npc)?.position : t.nearest ? t : where(typeof t === 'string' ? { place: t } : t);
|
|
299
|
+
const goal = s => ({ ...(s.id != null && { id: s.id }), text: s.text, done: () => content.test(s.done), target: target(s.target), ...(s.optional && { optional: true }), ...(s.next != null && { next: s.next }) }); // id: stable for saves
|
|
300
|
+
for (const [id, q] of Object.entries(d)) {
|
|
301
|
+
e.quests.define(id, {
|
|
302
|
+
title: q.title, desc: q.desc,
|
|
303
|
+
steps: q.steps.map(s => s.all ? { ...(s.id != null && { id: s.id }), text: s.text, all: s.all.map(goal), ...(s.next != null && { next: s.next }) } : goal(s)),
|
|
304
|
+
reward: q.reward && (() => content.run(q.reward)),
|
|
305
|
+
...(q.onUnpaid && { onUnpaid: () => content.run(q.onUnpaid) }),
|
|
306
|
+
...(q.fail && { fail: () => content.test(q.fail) }), ...(q.onFail && { onFail: () => content.run(q.onFail) }),
|
|
307
|
+
});
|
|
308
|
+
startOn.get(id)?.on.remove(); // loading the same quest again: replace the old listener instead of attaching twice
|
|
309
|
+
if (q.startOn) listen(e, track, id, q.startOn);
|
|
310
|
+
}
|
|
311
|
+
},
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
|
|
202
315
|
/**
|
|
203
316
|
* Quests module. Installs engine.quests. The 'quests' action opens the quest log; the game binds it (presets.bindings.quests has J / gamepad Select) @example
|
|
204
317
|
* engine.use(quests()); engine.input.bind(presets.bindings.quests)
|
|
@@ -207,9 +320,10 @@ export function quests(opts = {}) {
|
|
|
207
320
|
const o = readParams('quests', QUEST_PARAMS, opts);
|
|
208
321
|
let q = null;
|
|
209
322
|
return {
|
|
210
|
-
|
|
323
|
+
content: { quests: questContent() },
|
|
324
|
+
name: 'quests', skipKind: 'approx', type: 'rules', provides: ['quests'], label: 'Quests', params: QUEST_PARAMS, options: o,
|
|
211
325
|
// o: the schema defaults are filled in, the class repeats none
|
|
212
|
-
install(e, ctx) { q = new Quests(e, o, ctx
|
|
326
|
+
install(e, ctx) { q = new Quests(e, o, ctx); return q; },
|
|
213
327
|
// Check quests in the fixed step (game time; not while frozen or flow is paused, so no rewards are granted while paused)
|
|
214
328
|
fixed() { if (--q._t <= 0) { q._t = q._period; q.check(); } },
|
|
215
329
|
// engine.skip: the countdown lands where stepping would have left it; conditions are checked once, on the last segment, if a check fell inside
|
|
@@ -239,3 +353,5 @@ export function quests(opts = {}) {
|
|
|
239
353
|
},
|
|
240
354
|
};
|
|
241
355
|
}
|
|
356
|
+
|
|
357
|
+
export const handRolled = [{ kind: 'quests', seen: 'a quest list of its own', use: 'the quests module: steps, rewards, markers and the log, saved with the game (recipe 04)', quiet: /\b(engine|e|eng|ctx)\.quests\b|\bquests\(\s*[{)]/, code: /(?:\b(?:const|let|var)\s+|\bthis\.)(?:quests?|questLog|missions?|objectives?)(?:List|Log|Data|s)?\s*=\s*(?:\[\s*\]|\{\s*\}|new Map\b)/i }];
|
|
@@ -1,13 +1,20 @@
|
|
|
1
1
|
// Container internals that need no class state beyond the box they get as `b` (helper of Container.js): the dry runs behind trade / transfer, adding with
|
|
2
2
|
// the room check and its dev messages, and reading a saved list.
|
|
3
3
|
import { toast } from '../../ui/UI.js';
|
|
4
|
-
import { warnOnce, fmt } from '../../core/validate.js';
|
|
4
|
+
import { warnOnce, fmt } from '../../core/base/validate.js';
|
|
5
|
+
import { codedError } from '../../core/base/errorHints.js';
|
|
5
6
|
|
|
6
7
|
const STRINGS = {
|
|
7
8
|
full: 'Container {box} has no room for {id} (capacity {cap} slots, maxWeight {mw}): add returns false. Raise capacity / maxWeight, or remove something first',
|
|
8
9
|
partial: 'Only {fit} of {n} {id} fit in container {box} (stack {stack} per slot, capacity {cap} slots, maxWeight {mw}); add still returns the entry key. Raise capacity / maxWeight or the item\'s stack',
|
|
9
10
|
badRow: "container '{box}': dropped a saved entry that is not { id: string, count: whole number 1..2^53-1, data?: plain object } ({got}); the save was edited by hand or is damaged",
|
|
10
11
|
};
|
|
12
|
+
/** The one quantity rule of add / remove / setData / transfer / trade (saves already demand it): a whole number >= 1. Pieces are discrete, so 0, -2, 1.5, NaN
|
|
13
|
+
* and values past 2^53 are a bug in the caller; checked in every build and before anything is written, since a negative remove would otherwise ADD stock @internal */
|
|
14
|
+
export function checkCount(where, name, n) {
|
|
15
|
+
if (!Number.isSafeInteger(n) || n < 1) throw codedError('container', `${where}: ${name} must be a whole number >= 1, got ${n}. Example: bag.remove('arrow', 3)`);
|
|
16
|
+
return n;
|
|
17
|
+
}
|
|
11
18
|
// order-independent signature: entries with equal data stack together whatever the key order
|
|
12
19
|
export const sig = v => v === undefined ? '' : v && typeof v === 'object'
|
|
13
20
|
? (Array.isArray(v) ? `[${v.map(sig)}]` : `{${Object.keys(v).sort().map(k => JSON.stringify(k) + ':' + sig(v[k]))}}`) : JSON.stringify(v);
|
|
@@ -8,10 +8,12 @@
|
|
|
8
8
|
// default below; replace it with engine.ui.set('dialogue.bubble', ...)). Events: dialogue:bubble { speaker, text, at } when a line shows.
|
|
9
9
|
import * as THREE from 'three';
|
|
10
10
|
import { injectUICSS, worldToScreen, placeAt, esc } from '../../ui/UI.js';
|
|
11
|
+
import { vec3 } from '../../core/base/math.js';
|
|
11
12
|
/** @import { Engine, UIPart } from '../../types/core' */
|
|
12
13
|
|
|
13
14
|
const CSS = `
|
|
14
15
|
.threedog-bubble{position:absolute;left:0;top:0;transform:translate(-50%,-100%);max-width:240px;padding:6px 10px;border-radius:var(--threedog-radius-small);background:var(--threedog-bg);color:var(--threedog-fg);font:14px/1.35 var(--threedog-font);pointer-events:none;box-shadow:var(--threedog-shadow-small)}
|
|
16
|
+
.threedog-bubble button{display:block;pointer-events:auto;margin-top:4px;font:inherit;cursor:pointer}
|
|
15
17
|
.threedog-bubble b{display:block;font-size:12px;opacity:.75}
|
|
16
18
|
.threedog-bubbles-screen{position:absolute;left:50%;bottom:22%;transform:translateX(-50%);display:flex;flex-direction:column;align-items:center;gap:6px;pointer-events:none}
|
|
17
19
|
.threedog-bubbles-screen .threedog-bubble{position:static;transform:none}
|
|
@@ -27,7 +29,8 @@ const _v = new THREE.Vector3();
|
|
|
27
29
|
export function bubblePart(e) {
|
|
28
30
|
injectUICSS(CSS);
|
|
29
31
|
const el = document.createElement('div'); el.className = 'threedog-ui threedog-bubble'; el.hidden = true;
|
|
30
|
-
let html = null, parent = null;
|
|
32
|
+
let html = null, parent = null, pick = null;
|
|
33
|
+
el.addEventListener('click', ev => { const i = ev.target.closest?.('button')?.dataset.i; if (i != null) pick?.(+i); }); // a choice asked by a bubble line
|
|
31
34
|
return {
|
|
32
35
|
el,
|
|
33
36
|
update(d) {
|
|
@@ -35,7 +38,8 @@ export function bubblePart(e) {
|
|
|
35
38
|
if (parent !== want) { parent = want; want.appendChild(el); }
|
|
36
39
|
el.hidden = !d.onScreen;
|
|
37
40
|
if (!d.screen) placeAt(el, d.x, d.y);
|
|
38
|
-
|
|
41
|
+
pick = d.choose ?? null;
|
|
42
|
+
const h = `${d.speaker ? `<b>${esc(d.speaker)}</b>` : ''}${esc(d.text)}${(d.choices ?? []).map((c, i) => `<button data-i="${i}">${esc(c)}</button>`).join('')}`;
|
|
39
43
|
if (h !== html) { html = h; el.innerHTML = h; } // called every frame: rebuild only when the line changed
|
|
40
44
|
},
|
|
41
45
|
hide() { el.hidden = true; },
|
|
@@ -60,26 +64,25 @@ export class Bubbles {
|
|
|
60
64
|
_place(at, height) {
|
|
61
65
|
const e = this.engine;
|
|
62
66
|
if (at == null) return { x: 0, y: 0, onScreen: true, screen: true };
|
|
63
|
-
|
|
64
|
-
if (at
|
|
65
|
-
else
|
|
66
|
-
else p = _v.set(at.x, at.y ?? 0, at.z);
|
|
67
|
+
if (at.isObject3D) at.getWorldPosition(_v);
|
|
68
|
+
else if (typeof at === 'string') { const q = e.actorPosition?.(at); if (!q) return { x: 0, y: 0, onScreen: false, screen: false }; _v.set(q.x, q.y ?? 0, q.z); }
|
|
69
|
+
else vec3(at, _v); // every position form the engine takes: [x, y, z] here read as no position at all
|
|
67
70
|
_v.y += height;
|
|
68
71
|
const s = worldToScreen(e, _v);
|
|
69
72
|
return { x: s.x, y: s.y, onScreen: s.onScreen, screen: false };
|
|
70
73
|
}
|
|
71
74
|
/**
|
|
72
75
|
* Queue one line on a speaker. Returns a Promise (resolves when the line has been shown for its seconds) with remove() (drop it now; resolves too).
|
|
73
|
-
* @param {any} at @param {string} text @param {{ speaker?: string, seconds?: number, queue?: boolean, height?: number }} o
|
|
76
|
+
* @param {any} at @param {string} text @param {{ speaker?: string, seconds?: number, queue?: boolean, height?: number, run?: number | null, choices?: string[] | null }} o
|
|
74
77
|
*/
|
|
75
|
-
say(at, text, { speaker = '', seconds, queue = true, height = 2.2 } = {}) {
|
|
78
|
+
say(at, text, { speaker = '', seconds, queue = true, height = 2.2, run = null, choices = null } = {}) {
|
|
76
79
|
const key = at ?? 'screen:' + speaker;
|
|
77
80
|
let s = this.lines.get(key);
|
|
78
81
|
if (!s) { s = { at, part: this.engine.ui.create('dialogue.bubble'), cur: null, queue: [] }; this.lines.set(key, s); }
|
|
79
82
|
let line;
|
|
80
83
|
const p = new Promise(res => {
|
|
81
84
|
// reading time: holdSeconds plus about 15 characters a second, so a long line stays longer than a shout
|
|
82
|
-
line = { speaker, text: String(text ?? ''), left: seconds ?? this.d.holdSeconds + String(text ?? '').length / 15, height, done: res };
|
|
85
|
+
line = { speaker, text: String(text ?? ''), left: seconds ?? this.d.holdSeconds + String(text ?? '').length / 15, height, run, choices, done: res };
|
|
83
86
|
});
|
|
84
87
|
p.remove = () => this._drop(key, line);
|
|
85
88
|
if (!queue && s.cur) { s.cur.done(); s.cur = null; s.queue.forEach(l => l.done()); s.queue = []; }
|
|
@@ -106,11 +109,12 @@ export class Bubbles {
|
|
|
106
109
|
for (const [key, s] of this.lines) {
|
|
107
110
|
if (!s.cur) continue;
|
|
108
111
|
if ((s.cur.left -= dt) <= 0) { this._next(key, s); if (!this.lines.has(key)) continue; }
|
|
109
|
-
|
|
112
|
+
const c = s.cur, ops = this.engine.ops;
|
|
113
|
+
s.part?.update?.({ speaker: c.speaker, text: c.text, ...(c.choices && { choices: c.choices, run: c.run, choose: index => ops.run('dialogue.choose', { index, run: c.run }, { source: 'player', actor: this.d._asks.get(c.run)?.actor }) }), ...this._place(s.at, c.height) });
|
|
110
114
|
}
|
|
111
115
|
}
|
|
112
|
-
/** Lines showing now: [{ speaker, text, queued }] */
|
|
113
|
-
list() { return [...this.lines.values()].filter(s => s.cur).map(s => ({ speaker: s.cur.speaker, text: s.cur.text, queued: s.queue.length })); }
|
|
116
|
+
/** Lines showing now: [{ speaker, text, queued }], plus run and choices on a line waiting for a choice (dialogue({ bubbleChoice: 'ask' })) */
|
|
117
|
+
list() { return [...this.lines.values()].filter(s => s.cur).map(s => ({ speaker: s.cur.speaker, text: s.cur.text, queued: s.queue.length, ...(s.cur.choices && { run: s.cur.run, choices: s.cur.choices }) })); }
|
|
114
118
|
/** session:end: drop every line without resolving (awaiting code belonged to the old playthrough) @internal */
|
|
115
119
|
clear() { for (const s of this.lines.values()) s.part?.dispose?.(); this.lines.clear(); }
|
|
116
120
|
}
|