threedog 0.0.0-stage → 0.1.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 +5 -0
- package/LICENSE +21 -0
- package/README.md +39 -2
- package/core/Animator.js +267 -0
- package/core/Assets.js +240 -0
- package/core/Audio.js +267 -0
- package/core/Baked.js +72 -0
- package/core/Batching.js +247 -0
- package/core/Budget.js +221 -0
- package/core/Clock.js +94 -0
- package/core/Commits.js +77 -0
- package/core/Describe.js +134 -0
- package/core/Engine.js +221 -0
- package/core/Events.js +95 -0
- package/core/I18n.js +94 -0
- package/core/Input.js +245 -0
- package/core/Inspect.js +97 -0
- package/core/InspectScene.js +187 -0
- package/core/Jobs.js +146 -0
- package/core/Loading.js +149 -0
- package/core/Ops.js +272 -0
- package/core/Random.js +52 -0
- package/core/Rays.js +160 -0
- package/core/SaveStore.js +85 -0
- package/core/Saves.js +253 -0
- package/core/Stream.js +279 -0
- package/core/Threads.js +158 -0
- package/core/UrlState.js +93 -0
- package/core/Vars.js +34 -0
- package/core/actor.js +23 -0
- package/core/assetEntry.js +89 -0
- package/core/assetLoad.js +190 -0
- package/core/assetManifest.js +35 -0
- package/core/audioRules.js +121 -0
- package/core/audioVoice.js +225 -0
- package/core/batchGroups.js +116 -0
- package/core/canvasBox.js +63 -0
- package/core/dayTime.js +15 -0
- package/core/describeText.js +136 -0
- package/core/easing.js +34 -0
- package/core/errorCodes.js +172 -0
- package/core/errorHints.js +203 -0
- package/core/errors.js +40 -0
- package/core/events.generated.js +84 -0
- package/core/ground.js +102 -0
- package/core/inputContext.js +69 -0
- package/core/inputDefaults.js +22 -0
- package/core/inputPad.js +35 -0
- package/core/inputPointer.js +48 -0
- package/core/inputTouch.js +48 -0
- package/core/lifecycle.js +68 -0
- package/core/lightWatch.js +36 -0
- package/core/loop.js +199 -0
- package/core/math.js +33 -0
- package/core/modules.js +182 -0
- package/core/movement.js +19 -0
- package/core/mulberry32.js +14 -0
- package/core/opsCheck.js +86 -0
- package/core/opsGuard.js +26 -0
- package/core/opsHistory.js +27 -0
- package/core/page.js +78 -0
- package/core/pureWorker.js +5 -0
- package/core/saveApply.js +128 -0
- package/core/saveFiles.js +139 -0
- package/core/saveIds.js +53 -0
- package/core/saveVersions.js +97 -0
- package/core/scatter.js +92 -0
- package/core/sceneMethods.js +125 -0
- package/core/screenToGround.js +39 -0
- package/core/session.js +171 -0
- package/core/shadowTypes.js +15 -0
- package/core/skip.js +104 -0
- package/core/startup.js +133 -0
- package/core/streamCells.js +24 -0
- package/core/streamSources.js +73 -0
- package/core/styleParts.js +96 -0
- package/core/targeting.js +64 -0
- package/core/thingOps.js +157 -0
- package/core/things.js +198 -0
- package/core/threadPure.js +120 -0
- package/core/threadServe.js +25 -0
- package/core/tier.js +11 -0
- package/core/validate.js +188 -0
- package/docs/AI.md +149 -0
- package/docs/API.md +84 -0
- package/docs/CODEMAP.md +335 -0
- package/docs/COMMANDS.md +96 -0
- package/docs/CONVENTIONS.md +134 -0
- package/docs/PERF.md +217 -0
- package/docs/THREE.md +86 -0
- package/docs/api/ambience.md +15 -0
- package/docs/api/assets.md +60 -0
- package/docs/api/audio.md +53 -0
- package/docs/api/budget.md +40 -0
- package/docs/api/cameraRig.md +120 -0
- package/docs/api/characters.md +142 -0
- package/docs/api/clock.md +7 -0
- package/docs/api/collision.md +35 -0
- package/docs/api/content.md +63 -0
- package/docs/api/debug.md +10 -0
- package/docs/api/dialogue.md +39 -0
- package/docs/api/engine.md +190 -0
- package/docs/api/entities.md +61 -0
- package/docs/api/events.md +91 -0
- package/docs/api/flow.md +27 -0
- package/docs/api/grids.md +11 -0
- package/docs/api/ground.md +16 -0
- package/docs/api/hlod.md +34 -0
- package/docs/api/hud.md +31 -0
- package/docs/api/i18n.md +10 -0
- package/docs/api/input.md +24 -0
- package/docs/api/interactions.md +31 -0
- package/docs/api/inventory.md +66 -0
- package/docs/api/jobs.md +10 -0
- package/docs/api/level.md +41 -0
- package/docs/api/lightPool.md +56 -0
- package/docs/api/music.md +34 -0
- package/docs/api/nav.md +26 -0
- package/docs/api/net.md +14 -0
- package/docs/api/openWorld.md +24 -0
- package/docs/api/particles.md +41 -0
- package/docs/api/photo.md +15 -0
- package/docs/api/post.md +9 -0
- package/docs/api/quests.md +36 -0
- package/docs/api/rays.md +26 -0
- package/docs/api/rigid.md +84 -0
- package/docs/api/saves.md +31 -0
- package/docs/api/settings.md +36 -0
- package/docs/api/sky.md +58 -0
- package/docs/api/stream.md +31 -0
- package/docs/api/style.md +134 -0
- package/docs/api/terrain.md +34 -0
- package/docs/api/timeline.md +39 -0
- package/docs/api/tools.md +55 -0
- package/docs/api/triggers.md +56 -0
- package/docs/api/vars.md +9 -0
- package/docs/api/vegetation.md +52 -0
- package/docs/api/water.md +48 -0
- package/docs/api/weather.md +29 -0
- package/docs/api/world.md +30 -0
- package/docs/recipes/01-new-game.md +148 -0
- package/docs/recipes/02-npc.md +151 -0
- package/docs/recipes/03-items-pickups.md +158 -0
- package/docs/recipes/04-quests.md +83 -0
- package/docs/recipes/05-props-bake.md +159 -0
- package/docs/recipes/06-clock-events.md +104 -0
- package/docs/recipes/07-flow-scenes-pause.md +128 -0
- package/docs/recipes/08-weather-sky.md +74 -0
- package/docs/recipes/09-style-pack.md +234 -0
- package/docs/recipes/10-blender-level.md +67 -0
- package/docs/recipes/11-vehicles.md +55 -0
- package/docs/recipes/12-navmesh.md +57 -0
- package/docs/recipes/13-animation.md +146 -0
- package/docs/recipes/14-custom-module.md +91 -0
- package/docs/recipes/15-perf.md +78 -0
- package/docs/recipes/16-dev-bridge.md +146 -0
- package/docs/recipes/18-world.md +185 -0
- package/docs/recipes/19-shooting-picking.md +76 -0
- package/docs/recipes/20-content-actions-save.md +176 -0
- package/docs/recipes/21-camera.md +104 -0
- package/docs/recipes/22-shop-gold.md +107 -0
- package/docs/recipes/23-ops.md +139 -0
- package/docs/recipes/26-ui-parts.md +138 -0
- package/docs/recipes/27-net.md +96 -0
- package/docs/recipes/28-terrain.md +80 -0
- package/docs/recipes/29-grid.md +87 -0
- package/docs/recipes/30-templates.md +131 -0
- package/docs/recipes/31-audio.md +126 -0
- package/docs/recipes/32-action-game.md +33 -0
- package/docs/recipes/33-stream-sources.md +37 -0
- package/docs/recipes/34-environment-lighting.md +35 -0
- package/docs/recipes/35-style-from-reference.md +89 -0
- package/docs/recipes/36-sky-ground-plant-looks.md +116 -0
- package/docs/recipes/37-terrain-look-hooks.md +97 -0
- package/docs/recipes/38-environment-look-hooks.md +81 -0
- package/docs/recipes/40-scene.md +79 -0
- package/docs/recipes/41-thing-registry.md +64 -0
- package/docs/recipes/42-terrain-shape.md +64 -0
- package/docs/recipes/43-shader-patches-surface-looks.md +118 -0
- package/docs/recipes/44-water-weather-look-hooks.md +133 -0
- package/docs/recipes/45-cascaded-shadows.md +51 -0
- package/docs/recipes/46-blender-art-route.md +92 -0
- package/docs/recipes/47-island-snow-backdrop.md +44 -0
- package/examples/action/DESIGN.md +3 -0
- package/examples/action/GAMEMAP.md +127 -0
- package/examples/action/content/actions.js +8 -0
- package/examples/action/content/audio.js +9 -0
- package/examples/action/content/index.js +9 -0
- package/examples/action/content/items.js +4 -0
- package/examples/action/content/places.js +4 -0
- package/examples/action/content/props.js +11 -0
- package/examples/action/content/templates.js +10 -0
- package/examples/action/look.js +5 -0
- package/examples/action/main.js +137 -0
- package/examples/action/models.js +25 -0
- package/examples/sheepisland/GAMEMAP.md +108 -0
- package/examples/sheepisland/content/index.js +6 -0
- package/examples/sheepisland/content/props.js +19 -0
- package/examples/sheepisland/content/templates.js +5 -0
- package/examples/sheepisland/content/vegetation.js +8 -0
- package/examples/sheepisland/main.js +71 -0
- package/examples/sheepisland/params.js +25 -0
- package/examples/sheepisland/style/index.js +79 -0
- package/examples/sheepisland/style/models.js +59 -0
- package/examples/sheepisland/views.js +9 -0
- package/examples/styletest/GAMEMAP.md +135 -0
- package/examples/styletest/content/index.js +9 -0
- package/examples/styletest/content/items.js +8 -0
- package/examples/styletest/content/npcs.js +8 -0
- package/examples/styletest/content/places.js +5 -0
- package/examples/styletest/content/props.js +16 -0
- package/examples/styletest/content/templates.js +9 -0
- package/examples/styletest/content/vegetation.js +31 -0
- package/examples/styletest/look.js +11 -0
- package/examples/styletest/main.js +95 -0
- package/examples/styletest/models.js +87 -0
- package/examples/styletest/overrides.js +33 -0
- package/examples/styletest/panel.js +135 -0
- package/examples/styletest/params.js +32 -0
- package/examples/styletest/views.js +31 -0
- package/examples/world/DESIGN.md +5 -0
- package/examples/world/GAMEMAP.md +171 -0
- package/examples/world/content/actions.js +8 -0
- package/examples/world/content/audio.js +25 -0
- package/examples/world/content/bodies.js +12 -0
- package/examples/world/content/containers.js +4 -0
- package/examples/world/content/dialogues.js +33 -0
- package/examples/world/content/index.js +17 -0
- package/examples/world/content/items.js +10 -0
- package/examples/world/content/npcs.js +14 -0
- package/examples/world/content/pickups.js +11 -0
- package/examples/world/content/places.js +6 -0
- package/examples/world/content/props.js +12 -0
- package/examples/world/content/quests.js +15 -0
- package/examples/world/content/rules.js +23 -0
- package/examples/world/content/templates.js +5 -0
- package/examples/world/content/vegetation.js +32 -0
- package/examples/world/main.js +168 -0
- package/examples/world/models.js +28 -0
- package/index.d.ts +279 -0
- package/index.js +120 -0
- package/llms.txt +56 -0
- package/modules/ambience/Ambience.js +183 -0
- package/modules/camera/FirstPersonCamera.js +133 -0
- package/modules/camera/FixedCamera.js +155 -0
- package/modules/camera/FollowCamera.js +85 -0
- package/modules/camera/RtsCamera.js +134 -0
- package/modules/camera/common.js +152 -0
- package/modules/camera/index.js +11 -0
- package/modules/characters/Character.js +223 -0
- package/modules/characters/NPC.js +242 -0
- package/modules/characters/assetModel.js +42 -0
- package/modules/characters/astar.js +59 -0
- package/modules/characters/behaviors.js +72 -0
- package/modules/characters/footsteps.js +13 -0
- package/modules/characters/index.js +212 -0
- package/modules/characters/moveHelpers.js +29 -0
- package/modules/characters/movers/common.js +62 -0
- package/modules/characters/movers/rapier.js +74 -0
- package/modules/characters/movers/simple.js +38 -0
- package/modules/characters/npcAvoid.js +129 -0
- package/modules/characters/npcSim.js +144 -0
- package/modules/characters/npcView.js +42 -0
- package/modules/characters/pathAsync.js +107 -0
- package/modules/characters/pathJob.js +61 -0
- package/modules/characters/pathWorker.js +7 -0
- package/modules/characters/playerStrings.js +12 -0
- package/modules/characters/proceduralRig.js +54 -0
- package/modules/collision/Collision.js +176 -0
- package/modules/collision/grid.js +63 -0
- package/modules/content/ids.js +95 -0
- package/modules/content/index.js +152 -0
- package/modules/content/loader.js +187 -0
- package/modules/content/models.js +69 -0
- package/modules/content/packs.js +69 -0
- package/modules/content/props.js +89 -0
- package/modules/content/rules.js +133 -0
- package/modules/content/templates.js +189 -0
- package/modules/debug/DebugPanel.js +168 -0
- package/modules/entities/Entities.js +239 -0
- package/modules/entities/build.js +25 -0
- package/modules/entities/index.js +4 -0
- package/modules/flow/index.js +98 -0
- package/modules/gameplay/Container.js +227 -0
- package/modules/gameplay/Containers.js +89 -0
- package/modules/gameplay/Dialogue.js +216 -0
- package/modules/gameplay/Interactions.js +243 -0
- package/modules/gameplay/Inventory.js +214 -0
- package/modules/gameplay/Quests.js +195 -0
- package/modules/gameplay/boxOps.js +60 -0
- package/modules/gameplay/dialogueBox.js +48 -0
- package/modules/gameplay/interactionPrompt.js +28 -0
- package/modules/gameplay/inventoryOps.js +137 -0
- package/modules/gameplay/pickups.js +113 -0
- package/modules/gameplay/questLog.js +54 -0
- package/modules/gameplay/questSave.js +71 -0
- package/modules/grid/Grid.js +184 -0
- package/modules/grid/Layer.js +142 -0
- package/modules/grid/index.js +236 -0
- package/modules/grid/ops.js +73 -0
- package/modules/grid/preview.js +85 -0
- package/modules/grid/tiles.js +75 -0
- package/modules/hlod/index.js +164 -0
- package/modules/hud/index.js +164 -0
- package/modules/hud/parts.js +80 -0
- package/modules/level/geometry.js +46 -0
- package/modules/level/heightfield.js +160 -0
- package/modules/level/index.js +231 -0
- package/modules/level/nodes.js +84 -0
- package/modules/lights/index.js +224 -0
- package/modules/music/Music.js +290 -0
- package/modules/music/index.js +2 -0
- package/modules/music/rules.js +28 -0
- package/modules/nav/index.js +154 -0
- package/modules/nav/navPath.js +17 -0
- package/modules/net/Client.js +136 -0
- package/modules/net/Host.js +117 -0
- package/modules/net/Net.js +49 -0
- package/modules/net/index.js +75 -0
- package/modules/net/sync.js +114 -0
- package/modules/net/transports.js +118 -0
- package/modules/particles/Particles.js +179 -0
- package/modules/particles/effect.js +112 -0
- package/modules/particles/shaders.js +28 -0
- package/modules/photo/Photo.js +143 -0
- package/modules/rigid/RigidBodies.js +262 -0
- package/modules/rigid/Vehicles.js +97 -0
- package/modules/rigid/sync.js +158 -0
- package/modules/settings/Settings.js +294 -0
- package/modules/settings/apply.js +20 -0
- package/modules/settings/index.js +3 -0
- package/modules/settings/sections.js +156 -0
- package/modules/settings/strings.js +53 -0
- package/modules/settings/view.js +65 -0
- package/modules/sky/Sky.js +257 -0
- package/modules/sky/calendar.js +80 -0
- package/modules/sky/cascades.js +125 -0
- package/modules/sky/clouds.js +79 -0
- package/modules/sky/domeLayers.js +33 -0
- package/modules/sky/environment.js +115 -0
- package/modules/sky/fog.js +136 -0
- package/modules/sky/frame.js +76 -0
- package/modules/sky/layers.js +69 -0
- package/modules/sky/look.js +50 -0
- package/modules/sky/schedule.js +80 -0
- package/modules/sky/shader.js +96 -0
- package/modules/sky/shadow.js +80 -0
- package/modules/sky/skyModule.js +59 -0
- package/modules/terrain/ChunkManager.js +291 -0
- package/modules/terrain/chunkJob.js +19 -0
- package/modules/terrain/chunkQueries.js +42 -0
- package/modules/terrain/chunkWorker.js +5 -0
- package/modules/terrain/index.js +110 -0
- package/modules/terrain/mountTerrain.js +32 -0
- package/modules/terrain/terrainColorMap.js +41 -0
- package/modules/terrain/terrainDefaults.js +39 -0
- package/modules/terrain/terrainEdit.js +139 -0
- package/modules/terrain/terrainGen.js +155 -0
- package/modules/terrain/terrainIsland.js +131 -0
- package/modules/terrain/terrainMesh.js +92 -0
- package/modules/terrain/terrainShape.js +108 -0
- package/modules/terrain/terrainShapeMain.js +41 -0
- package/modules/terrain/terrainTexture.js +44 -0
- package/modules/timeline/Timeline.js +249 -0
- package/modules/timeline/Tween.js +118 -0
- package/modules/timeline/letterbox.js +24 -0
- package/modules/timeline/shots.js +88 -0
- package/modules/triggers/index.js +261 -0
- package/modules/vegetation/Vegetation.js +255 -0
- package/modules/vegetation/groundChunks.js +177 -0
- package/modules/vegetation/index.js +40 -0
- package/modules/vegetation/modelGeometry.js +21 -0
- package/modules/water/Water.js +144 -0
- package/modules/water/surface.js +88 -0
- package/modules/weather/Weather.js +251 -0
- package/modules/weather/particles.js +92 -0
- package/modules/weather/shaders.js +49 -0
- package/modules/world/World.js +231 -0
- package/modules/world/cells.js +42 -0
- package/modules/world/index.js +64 -0
- package/modules/world/persist.js +107 -0
- package/modules/world/pos.js +20 -0
- package/modules/world/records.js +89 -0
- package/modules/world/sim.js +175 -0
- package/modules/world/simFar.js +82 -0
- package/modules/world/state.js +115 -0
- package/modules/world/views.js +182 -0
- package/package.json +66 -4
- package/presets.js +96 -0
- package/render/PostFX.js +243 -0
- package/render/detail.js +105 -0
- package/render/effects.js +142 -0
- package/render/engineUniforms.js +23 -0
- package/render/fuse.js +72 -0
- package/render/lighting.js +100 -0
- package/render/lights.js +16 -0
- package/render/materials.js +203 -0
- package/render/patches.js +252 -0
- package/render/surface.js +67 -0
- package/render/uniformDecl.js +29 -0
- package/types/common.d.ts +34 -0
- package/types/core.d.ts +1773 -0
- package/types/gameplay.d.ts +1812 -0
- package/types/generated/core/Audio.d.ts +200 -0
- package/types/generated/core/Batching.d.ts +47 -0
- package/types/generated/core/Budget.d.ts +90 -0
- package/types/generated/core/Commits.d.ts +31 -0
- package/types/generated/core/Events.d.ts +46 -0
- package/types/generated/core/I18n.d.ts +30 -0
- package/types/generated/core/Input.d.ts +118 -0
- package/types/generated/core/Jobs.d.ts +41 -0
- package/types/generated/core/Ops.d.ts +162 -0
- package/types/generated/core/Random.d.ts +49 -0
- package/types/generated/core/Rays.d.ts +49 -0
- package/types/generated/core/Saves.d.ts +161 -0
- package/types/generated/core/Stream.d.ts +93 -0
- package/types/generated/core/Threads.d.ts +82 -0
- package/types/generated/core/audioVoice.d.ts +47 -0
- package/types/generated/core/page.d.ts +18 -0
- package/types/generated/core/session.d.ts +48 -0
- package/types/generated/modules/ambience/Ambience.d.ts +48 -0
- package/types/generated/modules/debug/DebugPanel.d.ts +24 -0
- package/types/generated/modules/flow/index.d.ts +10 -0
- package/types/generated/modules/grid/Grid.d.ts +151 -0
- package/types/generated/modules/grid/Layer.d.ts +64 -0
- package/types/generated/modules/grid/index.d.ts +86 -0
- package/types/generated/modules/hlod/index.d.ts +11 -0
- package/types/generated/modules/hud/index.d.ts +10 -0
- package/types/generated/modules/lights/index.d.ts +13 -0
- package/types/generated/modules/music/Music.d.ts +111 -0
- package/types/generated/modules/net/Net.d.ts +34 -0
- package/types/generated/modules/net/index.d.ts +53 -0
- package/types/generated/modules/net/transports.d.ts +58 -0
- package/types/generated/modules/particles/Particles.d.ts +69 -0
- package/types/generated/modules/sky/Sky.d.ts +152 -0
- package/types/generated/modules/sky/skyModule.d.ts +10 -0
- package/types/generated/modules/timeline/Timeline.d.ts +51 -0
- package/types/generated/modules/water/Water.d.ts +29 -0
- package/types/generated/modules/weather/Weather.d.ts +72 -0
- package/types/generated/modules/world/World.d.ts +242 -0
- package/types/generated/modules/world/index.d.ts +15 -0
- package/types/generated/render/PostFX.d.ts +128 -0
- package/types/generated/render/materials.d.ts +90 -0
- package/types/generated/render/patches.d.ts +41 -0
- package/types/generated/ui/Focus.d.ts +11 -0
- package/types/generated/ui/LoadingScreen.d.ts +2 -0
- package/types/generated/ui/UI.d.ts +57 -0
- package/types/nav.d.ts +52 -0
- package/types/physics.d.ts +584 -0
- package/types/style.d.ts +628 -0
- package/types/worker.d.ts +11 -0
- package/types/world.d.ts +772 -0
- package/ui/Focus.js +51 -0
- package/ui/LoadingScreen.js +42 -0
- package/ui/Parts.js +195 -0
- package/ui/UI.js +167 -0
- package/ui/defaults.js +85 -0
- package/ui/theme.js +124 -0
- package/ui/touchPart.js +49 -0
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
// Inventory module: define items first, then add/remove. Press I by default to open the inventory window (the 'inventory' UI part). Pickups on the ground use
|
|
2
|
+
// spawnPickup() (data lives in engine.world, so install world() first; openWorld() includes it).
|
|
3
|
+
//
|
|
4
|
+
// inventory.define('fish', { name: '鲫鱼', icon: '🐟', iconUrl: '/textures/fish.png', desc: '河里钓的', stack: 20, weight: 0.5 });
|
|
5
|
+
// inventory.add('fish', 2); inventory.has('fish', 1); inventory.remove('fish'); // all operate on the player inventory
|
|
6
|
+
// One piece with its own data: const key = inventory.add('sword', 1, { data: { durability: 80 } }); // 'sword#1'; count('sword') counts every sword
|
|
7
|
+
// Chest / corpse / shelf: inventory.container('chest-1', { capacity: 8 }).add('fish'); inventory.transfer('chest-1', 'player', 'fish', 2);
|
|
8
|
+
// Player actions with items are ops: inventory.transfer / inventory.use / inventory.drop (inventoryOps.js).
|
|
9
|
+
//
|
|
10
|
+
// Look:
|
|
11
|
+
// window UI part 'inventory' (engine.ui.set('inventory', false | { drop: true } | yourPart)); body via style.ui.templates.inventory(data, { esc, t, icon })
|
|
12
|
+
// list styling CSS classes .threedog-win-inventory .threedog-row ... (override in style.ui.css)
|
|
13
|
+
// pickups style pack style.pickup = { color, size, lift, model: (item, { color, size }) => Object3D | BufferGeometry }, or pass a mesh each time
|
|
14
|
+
import { checkOptions, warnMissing, freezeDef, moduleKeys } from '../../core/validate.js';
|
|
15
|
+
import { Container } from './Container.js';
|
|
16
|
+
import { Containers } from './Containers.js';
|
|
17
|
+
import { followRuntimeIds } from '../../core/saveIds.js';
|
|
18
|
+
import { spawnPickup, nearestPickup, presentPickups, takeAuto } from './pickups.js';
|
|
19
|
+
import { inventoryWindow, windowData, defineInventoryOps, INVENTORY_STRINGS } from './inventoryOps.js';
|
|
20
|
+
|
|
21
|
+
export class Inventory {
|
|
22
|
+
constructor(engine, { action = 'inventory', keys, pad, capacity = Infinity, maxWeight = Infinity, defaultStack = 99, pickupRadius = 2, bobDistance = 60 } = {}) {
|
|
23
|
+
this.engine = engine;
|
|
24
|
+
this.defs = new Map();
|
|
25
|
+
this.defaultStack = defaultStack;
|
|
26
|
+
/** Interact radius of pickups that don't set their own (meters); auto pickups are taken within it */ this.pickupRadius = pickupRadius;
|
|
27
|
+
this.bag = new Container(this, 'player', { capacity, maxWeight, player: true }); // player inventory = the container with id 'player'
|
|
28
|
+
this._containers = new Containers(this, this.bag);
|
|
29
|
+
this.action = action;
|
|
30
|
+
this._meshes = new Map(); // world id -> custom mesh the game passed to spawnPickup (three.js objects can't go in world data)
|
|
31
|
+
// a pickup record gone (taken without respawn, removed, not in a loaded save): its custom mesh is no longer needed for a rebuild
|
|
32
|
+
engine.events.on('world:remove', ({ id }) => this._meshes.delete(id));
|
|
33
|
+
engine.events.on('world:load', () => { for (const id of this._meshes.keys()) if (!engine.world.get(id)) this._meshes.delete(id); });
|
|
34
|
+
this._presented = false;
|
|
35
|
+
this._autoQueue = []; // auto pickups in reach this step (pickups.js)
|
|
36
|
+
this._seq = 0; // entry key counter ('sword#7'), saved so keys never repeat
|
|
37
|
+
this.bobDistance = bobDistance;
|
|
38
|
+
engine.i18n.add(INVENTORY_STRINGS);
|
|
39
|
+
keys = moduleKeys('inventory()', action, keys, 'inventory', engine.input); // the game's key or a presets.keys bundle, never a built-in one
|
|
40
|
+
if (keys.length || pad) { engine.input.define(action, keys, 'inventory.action', { pad }); engine.input.touchButton(action, 'inventory.action'); }
|
|
41
|
+
engine.ui.define('inventory', inventoryWindow, { modal: { cancel: e => e.ui.close('inventory'), data: () => windowData(this) } });
|
|
42
|
+
for (const ev of ['i18n:change', 'input:rebind']) engine.events.on(ev, () => this._refresh());
|
|
43
|
+
// pickup state lives in world and is saved with it
|
|
44
|
+
// 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
|
|
45
|
+
// after the highest key it holds
|
|
46
|
+
engine.saves.register('inventory', { version: 1, save: () => ({ seq: this._seq, items: this.bag._save() }), load: d => {
|
|
47
|
+
this.bag._load(d?.items);
|
|
48
|
+
const top = Math.max(0, ...this.bag._entries.map(x => Number(x.key.split('#')[1]) || 0));
|
|
49
|
+
this._seq = Number.isInteger(d?.seq) && d.seq >= top ? d.seq : top;
|
|
50
|
+
this._refresh();
|
|
51
|
+
} });
|
|
52
|
+
// 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)
|
|
53
|
+
engine.saves.register('containers', { version: 2, migrate: { 1: followRuntimeIds }, save: () => this._containers.save(), load: d => this._containers.load(d) });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Max slots of the player inventory (Infinity = no limit). */
|
|
57
|
+
get capacity() { return this.bag.capacity; }
|
|
58
|
+
set capacity(n) { this.bag.capacity = n; }
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Get or create a container (chest, corpse, shelf...). The player inventory is the one with id 'player'; all have add / remove / count / has / get / list /
|
|
62
|
+
* room / setData / on with the same rules.
|
|
63
|
+
* id is any string (a world record id, 'shop-bakery'...); contents are saved. Far chests have no model but keep contents; a container created first by a load
|
|
64
|
+
* gets its limits by calling this again.
|
|
65
|
+
* Containers are not removed when their world record is (the game decides whether to keep a searched corpse): `engine.events.on('world:remove', ({ id }) =>
|
|
66
|
+
* engine.inventory.removeContainer(id))`.
|
|
67
|
+
* Limits are optional and off by default: capacity (slots, an entry uses ceil(count / stack)) and maxWeight (item weight × count). Locks and prices are game
|
|
68
|
+
* rules checked in its ops.
|
|
69
|
+
* @example
|
|
70
|
+
* const chest = engine.inventory.container('chest-1', { capacity: 8 }); // a second call returns the same one
|
|
71
|
+
* chest.add('bandage', 2);
|
|
72
|
+
* // with starting contents: placed only when this container is first created (if the save already has it, the save wins; not refilled after being emptied
|
|
73
|
+
* and loaded)
|
|
74
|
+
* engine.inventory.container('pack', { maxWeight: 30, items: { bandage: 2 } });
|
|
75
|
+
* engine.inventory.transfer(chest, 'player', 'bandage', 1); // returns how many were actually moved
|
|
76
|
+
* @param {string} id
|
|
77
|
+
* @param {{ capacity?: number, maxWeight?: number, items?: Record<string, number> }} [opts] capacity = slots, maxWeight = weight limit, both default
|
|
78
|
+
* Infinity; items = starting contents { itemId: count } (placed only the first time)
|
|
79
|
+
* @returns {Container}
|
|
80
|
+
*/
|
|
81
|
+
container(id, opts) { return this._containers.get(id, opts); }
|
|
82
|
+
/**
|
|
83
|
+
* @internal content/renames.js: containers saved under an old authored id move to the new one (content.load calls it before adding containers)
|
|
84
|
+
* @param {Record<string, string | null>} map
|
|
85
|
+
* @returns {void}
|
|
86
|
+
*/
|
|
87
|
+
renameIds(map) { this._containers.rename(map); }
|
|
88
|
+
/**
|
|
89
|
+
* Move n (default 1) of an item, or of one entry by key, between containers (container or id; player inventory is 'player'). Pieces keep their data and key.
|
|
90
|
+
* 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,
|
|
91
|
+
* to, item, n }).
|
|
92
|
+
* @example engine.inventory.transfer('player', 'chest-1', 'sword#3') // exactly that sword
|
|
93
|
+
* @param {Container | string} from
|
|
94
|
+
* @param {Container | string} to
|
|
95
|
+
* @param {string} item item id or entry key
|
|
96
|
+
* @param {number} [n]
|
|
97
|
+
* @returns {number}
|
|
98
|
+
*/
|
|
99
|
+
transfer(from, to, item, n = 1) { return this._containers.transfer(from, to, item, n); }
|
|
100
|
+
/** Delete a container with its contents ('player' cannot be deleted); returns whether one was deleted. */
|
|
101
|
+
removeContainer(id) { return this._containers.remove(id); }
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Define an item. stack = pieces per slot (default 99); weight counts against maxWeight; use(e, { actor, item, key, data }) makes it usable with the
|
|
105
|
+
* inventory.use op (canUse returns true or a reason, consume: true removes one first). Games may add their own fields (price...).
|
|
106
|
+
* The definition is shared by every piece and frozen; per-piece state (durability, ammo) goes in entry data: add('sword', 1, { data: { durability: 40 } }).
|
|
107
|
+
* @example engine.inventory.define('potion', { name: 'Potion', icon: '🧪', weight: 0.2, consume: true, use: (e, { actor }) => heal(actor, 30) })
|
|
108
|
+
* @param {string} id
|
|
109
|
+
* @param {Record<string, any>} def
|
|
110
|
+
* @returns {this}
|
|
111
|
+
*/
|
|
112
|
+
define(id, def) {
|
|
113
|
+
if (id.includes('#')) throw new Error(`inventory.define('${id}'): '#' is reserved for entry keys (sword#3); pick an id without it`);
|
|
114
|
+
checkOptions(`inventory.define('${id}')`, def, ['name', 'icon', 'iconUrl', 'desc', 'stack', 'color', 'weight', 'use', 'canUse', 'consume'], { loose: true }); // only near-miss spellings warn
|
|
115
|
+
this.defs.set(id, freezeDef({ stack: this.defaultStack, name: id, ...def })); return this; // shared by every entry of this item: read-only
|
|
116
|
+
}
|
|
117
|
+
// using an undefined item: warn when other items are defined (none defined means the game doesn't use define)
|
|
118
|
+
_known(id) { if (this.defs.size && !this.defs.has(id)) warnMissing('item', id, [...this.defs.keys()]); }
|
|
119
|
+
/** An item definition by id (a bare { name, stack } for an unknown id) */
|
|
120
|
+
item(id) { return this.defs.get(id) || { name: id, stack: this.defaultStack }; }
|
|
121
|
+
/** How many of an item (or of one entry key) the player has. */
|
|
122
|
+
count(id) { return this.bag.count(id); }
|
|
123
|
+
has(id, n = 1) { return this.bag.has(id, n); }
|
|
124
|
+
/**
|
|
125
|
+
* Atomic trade in the player inventory: take A and give B in one step, or change nothing (see Container.trade). Players run the op:
|
|
126
|
+
* engine.ops.run('inventory.trade', { take, give }).
|
|
127
|
+
* @example engine.inventory.trade('rusty_key', 'gold_key') // { ok: true, ... } or { ok: false, reason: 'full' | 'notEnough' }
|
|
128
|
+
* @param {string} take
|
|
129
|
+
* @param {string} give
|
|
130
|
+
* @param {{ takeN?: number, giveN?: number, data?: Record<string, any>, silent?: boolean }} [opts]
|
|
131
|
+
*/
|
|
132
|
+
trade(take, give, opts) { return this.bag.trade(take, give, opts); }
|
|
133
|
+
get slotsUsed() { return this.bag.slotsUsed; }
|
|
134
|
+
/** Player inventory entries: [{ key, id, count, data, def }] (for custom UI). */
|
|
135
|
+
list() { return this.bag.list(); }
|
|
136
|
+
/** One player inventory entry by key: { key, id, count, data, def } or null. */
|
|
137
|
+
get(key) { return this.bag.get(key); }
|
|
138
|
+
/** Add n (default 1) to the player inventory, opts { data, silent }; returns the entry key, false if it doesn't fit. */
|
|
139
|
+
add(id, n = 1, opts) { return this.bag.add(id, n, opts); }
|
|
140
|
+
/** Remove n (default 1) of an item or entry key from the player inventory; returns false if not enough. */
|
|
141
|
+
remove(id, n = 1) { return this.bag.remove(id, n); }
|
|
142
|
+
/** Replace the data of a player inventory entry (see Container.setData); returns the key holding the changed pieces. */
|
|
143
|
+
setData(key, data, n) { return this.bag.setData(key, data, n); }
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Place a pickup on the ground at position: walk up and press the interact key to take it (needs world() and interactions()); auto: true takes it by walking
|
|
147
|
+
* into it.
|
|
148
|
+
* The data is a plain record of kind 'pickup' in engine.world ({ id, item, count, data?, radius?, auto?, bob, respawn?, until?, zone?, position }, saved with
|
|
149
|
+
* it),
|
|
150
|
+
* the model is built only within bobDistance meters of the player; taking it deletes the record (with respawnSeconds it stays with until = clock.now of the
|
|
151
|
+
* respawn and comes back then).
|
|
152
|
+
* id: without it, auto-numbered (pickup-1...); give a stable id to recognize one in saves (content pickups use `pickup:<item>:<index>`). Existing data with
|
|
153
|
+
* the same id is reused.
|
|
154
|
+
* initial: true = written in content (needs an id; the save records only taken / waiting to respawn); zone = which level it belongs to.
|
|
155
|
+
* data = the piece's own data (a dropped sword keeps its durability); radius = reach in meters (default inventory pickupRadius).
|
|
156
|
+
* Returns a handle { id: item, worldId: id in world, object: current model (null when far), remove() }.
|
|
157
|
+
* @example engine.inventory.spawnPickup('berry', [3, 0, 5], { count: 2, respawnSeconds: 120 })
|
|
158
|
+
* @example engine.inventory.spawnPickup('ammo', [8, 0, 2], { count: 30, auto: true, radius: 1.2 }) // taken on touch
|
|
159
|
+
* @param {string} item
|
|
160
|
+
* @param {any} position
|
|
161
|
+
* @param {Record<string, any>} [opts]
|
|
162
|
+
*/
|
|
163
|
+
spawnPickup(item, position, opts = {}) { return spawnPickup(this, item, position, opts); }
|
|
164
|
+
|
|
165
|
+
/** Pickup data of an item that is still on the ground, nearest to from (default player) (used by hud's { nearest }); null if none. */
|
|
166
|
+
nearestPickup(item, from) { return nearestPickup(this, item, from); }
|
|
167
|
+
|
|
168
|
+
/** Register how pickups look and respawn (done once on first use; needs world installed first). @internal */
|
|
169
|
+
_world() { return presentPickups(this); }
|
|
170
|
+
/** Next entry key for an item with data @internal */
|
|
171
|
+
_newKey(id) { return `${id}#${++this._seq}`; }
|
|
172
|
+
/** Redraw the inventory part if it is open @internal */
|
|
173
|
+
_refresh() { const ui = this.engine.ui; if (ui.isOpen('inventory')) ui.get('inventory')?.update(windowData(this)); }
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Inventory module. Installs engine.inventory, the 'inventory' UI part and the ops inventory.transfer / use / drop / trade; ground pickups need world() and
|
|
178
|
+
* interactions().
|
|
179
|
+
* Options: action / keys / pad (the open key: required, keys: [] for none; presets.keys.inventory has I / gamepad Y), capacity / maxWeight / defaultStack (bag
|
|
180
|
+
* limits), pickupRadius / bobDistance (ground pickups),
|
|
181
|
+
* pauseGame (default false): true freezes gameplay while the window is open (monsters, timers and the game clock stop; the picture and UI stay alive).
|
|
182
|
+
* @example engine.use(inventory({ ...presets.keys.inventory, pauseGame: true })) // opening the bag with I stops the world until it closes
|
|
183
|
+
*/
|
|
184
|
+
export function inventory(opts = {}) {
|
|
185
|
+
let inv = null;
|
|
186
|
+
return {
|
|
187
|
+
name: 'inventory', label: 'Inventory', optional: ['world'],
|
|
188
|
+
install(e) {
|
|
189
|
+
checkOptions('inventory()', opts, ['action', 'keys', 'pad', 'capacity', 'maxWeight', 'defaultStack', 'pickupRadius', 'bobDistance', 'pauseGame']);
|
|
190
|
+
inv = new Inventory(e, opts);
|
|
191
|
+
// pauseGame: true freezes gameplay (engine.freeze, the same mechanism flow's 'paused' and settings({ freezeWorld }) use) while the window is open.
|
|
192
|
+
// 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).
|
|
193
|
+
if (opts.pauseGame != null && typeof opts.pauseGame !== 'boolean') throw new Error(`inventory({ pauseGame: ${JSON.stringify(opts.pauseGame)} }): pauseGame must be true or false. Example: engine.use(inventory({ pauseGame: true }))`);
|
|
194
|
+
inv.pauseGame = !!opts.pauseGame; // also settable at runtime: engine.inventory.pauseGame = true
|
|
195
|
+
e.events.on('ui:open', id => { if (id === 'inventory' && inv.pauseGame) e.freeze('inventory'); });
|
|
196
|
+
// always: switching pauseGame off while open must not leave the world frozen
|
|
197
|
+
e.events.on('ui:close', id => { if (id === 'inventory') e.unfreeze('inventory'); });
|
|
198
|
+
defineInventoryOps(e, inv);
|
|
199
|
+
return inv;
|
|
200
|
+
},
|
|
201
|
+
fixed() { takeAuto(inv); },
|
|
202
|
+
frame(dt, e) { // the inventory key toggles the part; while open the part holds the input lock, so the close press is read raw
|
|
203
|
+
const open = e.ui.isOpen('inventory');
|
|
204
|
+
if (open ? e.input.pressedRaw(inv.action) : e.input.pressed(inv.action)) { if (open) e.ui.close('inventory'); else e.ui.open('inventory'); }
|
|
205
|
+
},
|
|
206
|
+
describe(e, ctx) {
|
|
207
|
+
const w = e.world; // use the model if present (same object the interactions module reports, merged into one entry); far away only data
|
|
208
|
+
if (w) for (const r of w.query({ kind: 'pickup', near: ctx.center, radius: ctx.radius, where: r => r.until == null })) ctx.near(w.view(r.id) ?? r.position, { name: inv.item(r.item).name, kind: 'pickup', id: r.item });
|
|
209
|
+
const show = c => Object.fromEntries(c._entries.map(x => [x.key, x.data === undefined ? x.count : { count: x.count, data: x.data }]));
|
|
210
|
+
const boxes = Object.fromEntries([...inv._containers.map].filter(([, c]) => c !== inv.bag && c._entries.length).map(([id, c]) => [id, show(c)]));
|
|
211
|
+
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 }) };
|
|
212
|
+
},
|
|
213
|
+
};
|
|
214
|
+
}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
// Quests module: made of steps, each with a completion condition (function), checked every half second (game time, in the fixed step; not checked while
|
|
2
|
+
// frozen/paused). Press J by default to open the quest log.
|
|
3
|
+
//
|
|
4
|
+
// quests.define('first-photo', {
|
|
5
|
+
// title: '第一张照片', desc: '…',
|
|
6
|
+
// steps: [
|
|
7
|
+
// { text: '和老渔夫聊聊', done: e => e.vars.flag('metFisher'), target: npc.root }, // target: auto-marked when the hud module is present
|
|
8
|
+
// { id: 'sunset', text: '在傍晚拍一张照片', done: e => e.vars.counter('sunsetPhotos') >= 1 }, // id: the save's name for this step
|
|
9
|
+
// ],
|
|
10
|
+
// reward: e => e.inventory.add('film', 3),
|
|
11
|
+
// });
|
|
12
|
+
// quests.start('first-photo');
|
|
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
|
+
// 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
|
+
// 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 2): { state: { questId: { step?: stepId, done?, failed?, parts?: [partId met], got?: { stepId:
|
|
17
|
+
// [partId] } } } }.
|
|
18
|
+
// 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).
|
|
19
|
+
import { toast, toggleOnKey } from '../../ui/UI.js';
|
|
20
|
+
import { questLogWindow } from './questLog.js';
|
|
21
|
+
import { checkOptions, warnMissing, DEV, moduleKeys } from '../../core/validate.js';
|
|
22
|
+
import { codedError } from '../../core/errorHints.js';
|
|
23
|
+
import { toSaved, fromSaved, migrateV1, stepId } from './questSave.js';
|
|
24
|
+
|
|
25
|
+
const STRINGS = {
|
|
26
|
+
'zh-CN': { 'quests.title': '任务日志', 'quests.action': '任务', 'quests.empty': '还没有任务。', 'quests.new': '新任务:{title}', 'quests.done': '任务完成:{title}', 'quests.doneTag': '(已完成)', 'quests.failed': '任务失败:{title}' },
|
|
27
|
+
en: { '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}' },
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/** A step's text; a parallel step without its own text lists its required parts */
|
|
31
|
+
const stepText = st => st.text ?? st.all.filter(p => !p.optional).map(p => p.text).join(' / ');
|
|
32
|
+
export class Quests {
|
|
33
|
+
constructor(engine, { action = 'quests', keys, pad, checkInterval = 0.5, notify = true } = {}) {
|
|
34
|
+
this.engine = engine;
|
|
35
|
+
this.defs = new Map();
|
|
36
|
+
this.state = {}; // id -> { step, done, failed?, parts? (parts done in the current parallel step), got? (parts met in finished parallel steps) }
|
|
37
|
+
/** @internal saved progress of quests not defined yet (content loaded after the save): applied by define(), written back unchanged meanwhile */ this._saved = {};
|
|
38
|
+
this._t = 0;
|
|
39
|
+
this.action = action; this.checkInterval = checkInterval;
|
|
40
|
+
this.notify = notify; // true toast (kind 'quest') · false silent · function ({ type, id, text }) => void
|
|
41
|
+
engine.i18n.add(STRINGS);
|
|
42
|
+
keys = moduleKeys('quests()', action, keys, 'quests', engine.input); // the game's key or a presets.keys bundle, never a built-in one
|
|
43
|
+
if (keys.length || pad) engine.input.define(action, keys, 'quests.action', { pad });
|
|
44
|
+
this.win = questLogWindow(engine, this); // { open, toggle, refresh } over engine.ui
|
|
45
|
+
// counters live in engine.vars
|
|
46
|
+
// saved by stable step ids (questSave.js); version 1 saved positions
|
|
47
|
+
engine.saves.register('quests', { version: 2, migrate: { 1: d => migrateV1(this.defs, d) }, save: () => this._save(), load: d => this._load(d) });
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Define a quest. A step is { id?, text, done, target } or parallel goals { id?, text?, all: [{ id?, text, done, target, optional }] }.
|
|
52
|
+
* id: a stable name for the step (saves store progress by it, so steps can be inserted or reordered later); default its position.
|
|
53
|
+
* fail: checked while active; true fails the quest (onFail runs, quest:fail fires; start(id) can begin it again).
|
|
54
|
+
* @example quests.define('defend', { title: '守住营地', steps: [
|
|
55
|
+
* { text: '到营地', done: e => e.vars.flag('atCamp') },
|
|
56
|
+
* { all: [{ text: '守住 A 点', done: e => e.vars.flag('heldA') }, { text: '守住 B 点', done: e => e.vars.flag('heldB') },
|
|
57
|
+
* { text: '没人受伤', done: e => e.vars.flag('noHurt'), optional: true }] },
|
|
58
|
+
* ], fail: e => e.vars.flag('campLost'), onFail: e => e.vars.setFlag('mayRetry') });
|
|
59
|
+
* @param {string} id
|
|
60
|
+
* @param {any} def
|
|
61
|
+
*/
|
|
62
|
+
define(id, def) {
|
|
63
|
+
const at = `quests.define('${id}')`;
|
|
64
|
+
checkOptions(at, def, ['title', 'desc', 'steps', 'reward', 'fail', 'onFail']);
|
|
65
|
+
for (const s of def.steps || []) {
|
|
66
|
+
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`);
|
|
67
|
+
checkOptions(`${at} steps`, s, s.all ? ['id', 'text', 'all'] : ['id', 'text', 'done', 'target']);
|
|
68
|
+
for (const p of s.all || []) checkOptions(`${at} parallel part`, p, ['id', 'text', 'done', 'target', 'optional']);
|
|
69
|
+
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`);
|
|
70
|
+
}
|
|
71
|
+
const ids = (def.steps || []).map((_, i) => stepId(def, i)), dup = ids.find((x, i) => ids.indexOf(x) !== i);
|
|
72
|
+
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)`);
|
|
73
|
+
this.defs.set(id, def);
|
|
74
|
+
if (id in this._saved) { this.state[id] = fromSaved(id, def, this._saved[id]); delete this._saved[id]; this.win.refresh(); }
|
|
75
|
+
return this;
|
|
76
|
+
}
|
|
77
|
+
/** @internal save part data: progress by step ids, plus saved quests not defined yet */
|
|
78
|
+
_save() {
|
|
79
|
+
const state = { ...this._saved };
|
|
80
|
+
for (const [id, s] of Object.entries(this.state)) { const d = this.defs.get(id); if (d) state[id] = toSaved(d, s); }
|
|
81
|
+
return { state };
|
|
82
|
+
}
|
|
83
|
+
/** @internal */
|
|
84
|
+
_load(d) {
|
|
85
|
+
this.state = {}; this._saved = {};
|
|
86
|
+
for (const [id, q] of Object.entries(d?.state || {})) { const def = this.defs.get(id); if (def) this.state[id] = fromSaved(id, def, q); else this._saved[id] = q; }
|
|
87
|
+
this.win.refresh();
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Quest list (for custom UI): unfinished first. A parallel step has parts [{ text, target, done, optional }]; its text defaults to the required parts joined.
|
|
91
|
+
*/
|
|
92
|
+
list() {
|
|
93
|
+
return Object.entries(this.state).filter(([id]) => this.defs.has(id)).sort((a, b) => a[1].done - b[1].done).map(([id, s]) => {
|
|
94
|
+
const d = this.defs.get(id), live = !s.done && !s.failed;
|
|
95
|
+
return { id, title: d.title, desc: d.desc, done: s.done, failed: !!s.failed, steps: d.steps.map((st, i) => {
|
|
96
|
+
const now = live && i === s.step, row = { text: st.text, target: st.target, done: s.done || i < s.step, current: now };
|
|
97
|
+
if (st.all) {
|
|
98
|
+
const met = now ? s.parts : s.got?.[i];
|
|
99
|
+
row.parts = st.all.map((p, k) => ({ text: p.text, target: p.target, optional: !!p.optional, done: !!met?.[k] || (row.done && !p.optional) }));
|
|
100
|
+
row.text = stepText(st);
|
|
101
|
+
}
|
|
102
|
+
return row;
|
|
103
|
+
}) };
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
start(id) {
|
|
107
|
+
if (!this.defs.has(id)) { warnMissing('quest', id, [...this.defs.keys()]); return; }
|
|
108
|
+
if (this.state[id] && !this.state[id].failed) return; // a failed quest may be taken again (a daily order, a retry)
|
|
109
|
+
DEV && this.engine.ops.guard('quests.start');
|
|
110
|
+
this.state[id] = { step: 0, done: false };
|
|
111
|
+
this._say('start', id, this.engine.t('quests.new', { title: this.defs.get(id).title }));
|
|
112
|
+
this.engine.events.emit('quest:start', { id });
|
|
113
|
+
this.win.refresh();
|
|
114
|
+
}
|
|
115
|
+
/** @internal A quest message: a toast, nothing, or the game's own function (souls-likes keep quests silent) */
|
|
116
|
+
_say(type, id, text) {
|
|
117
|
+
if (this.notify === true) toast(this.engine, text, { kind: 'quest' });
|
|
118
|
+
else if (typeof this.notify === 'function') this.notify({ type, id, text });
|
|
119
|
+
}
|
|
120
|
+
isDone(id) { return !!this.state[id]?.done; }
|
|
121
|
+
isActive(id) { const s = this.state[id]; return !!s && !s.done && !s.failed; }
|
|
122
|
+
isFailed(id) { return !!this.state[id]?.failed; }
|
|
123
|
+
|
|
124
|
+
check() {
|
|
125
|
+
const e = this.engine;
|
|
126
|
+
for (const [id, s] of Object.entries(this.state)) {
|
|
127
|
+
if (s.done || s.failed) continue;
|
|
128
|
+
const d = this.defs.get(id); if (!d) continue;
|
|
129
|
+
if (d.fail?.(e)) { this._fail(id, s, d); continue; }
|
|
130
|
+
let advanced = false;
|
|
131
|
+
while (s.step < d.steps.length && this._stepDone(id, s, d.steps[s.step])) { DEV && e.ops.guard('quests.advance'); s.step++; delete s.parts; advanced = true; e.events.emit('quest:step', { id, step: s.step }); }
|
|
132
|
+
if (s.step >= d.steps.length) {
|
|
133
|
+
s.done = true; d.reward?.(this.engine);
|
|
134
|
+
this._say('done', id, this.engine.t('quests.done', { title: d.title })); this.engine.events.emit('quest:done', { id });
|
|
135
|
+
} else if (advanced) this._say('step', id, stepText(d.steps[s.step]));
|
|
136
|
+
if (advanced) this.win.refresh();
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/** @internal Plain step: its condition. Parallel step: tick off parts as they are met (each stays done); done when no required part is left */
|
|
140
|
+
_stepDone(id, s, st) {
|
|
141
|
+
if (!st.all) return st.done(this.engine);
|
|
142
|
+
s.parts ??= st.all.map(() => false);
|
|
143
|
+
let left = false;
|
|
144
|
+
st.all.forEach((p, k) => {
|
|
145
|
+
if (!s.parts[k] && p.done(this.engine)) {
|
|
146
|
+
DEV && this.engine.ops.guard('quests.advance');
|
|
147
|
+
s.parts[k] = true; this.engine.events.emit('quest:part', { id, step: s.step, part: k }); this.win.refresh();
|
|
148
|
+
}
|
|
149
|
+
if (!s.parts[k] && !p.optional) left = true;
|
|
150
|
+
});
|
|
151
|
+
if (!left && s.parts.some((x, k) => x && st.all[k].optional)) (s.got ??= {})[s.step] = s.parts; // optional goals met stay visible in list()
|
|
152
|
+
return !left;
|
|
153
|
+
}
|
|
154
|
+
/** @internal */
|
|
155
|
+
_fail(id, s, d) {
|
|
156
|
+
DEV && this.engine.ops.guard('quests.fail');
|
|
157
|
+
s.failed = true;
|
|
158
|
+
d.onFail?.(this.engine);
|
|
159
|
+
this._say('fail', id, this.engine.t('quests.failed', { title: d.title }));
|
|
160
|
+
this.engine.events.emit('quest:fail', { id });
|
|
161
|
+
this.win.refresh();
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Quests module. Installs engine.quests. keys / pad open the quest log: required (keys: [] for none; presets.keys.quests has J / gamepad Select) @example
|
|
167
|
+
* engine.use(quests({ ...presets.keys.quests }))
|
|
168
|
+
*/
|
|
169
|
+
export function quests(opts = {}) {
|
|
170
|
+
let q = null;
|
|
171
|
+
return {
|
|
172
|
+
name: 'quests', label: 'Quests',
|
|
173
|
+
install(e) { checkOptions('quests()', opts, ['action', 'keys', 'pad', 'checkInterval', 'notify']); q = new Quests(e, opts); return q; },
|
|
174
|
+
// Check quests in the fixed step (game time; not while frozen or flow is paused, so no rewards are granted while paused)
|
|
175
|
+
fixed(dt) { q._t -= dt; if (q._t <= 0) { q._t = q.checkInterval; q.check(); } },
|
|
176
|
+
frame(dt, e) { toggleOnKey(e, q.win, q.action); },
|
|
177
|
+
// engine.explain({ quest: id }): where a quest is stuck, so the AI need not read every done() function
|
|
178
|
+
explain: { quest(e, id) {
|
|
179
|
+
const d = q.defs.get(id), s = q.state[id];
|
|
180
|
+
if (!d) return { ok: false, text: `quest '${id}' is not defined (defined: ${[...q.defs.keys()].join(', ') || 'none'})` };
|
|
181
|
+
if (!s) return { ok: false, text: `quest '${id}' has not started (quests.start('${id}') or a content start effect)` };
|
|
182
|
+
if (s.done) return { ok: true, text: `quest '${id}' is done` };
|
|
183
|
+
if (s.failed) return { ok: false, text: `quest '${id}' failed (its fail() returned true; start('${id}') begins it again)` };
|
|
184
|
+
const st = d.steps[s.step], at = `quest '${id}' waits on step ${s.step + 1}/${d.steps.length} "${stepText(st)}"`, every = `(checked every ${q.checkInterval} s in fixed steps)`;
|
|
185
|
+
if (!st.all) return { ok: false, step: s.step, text: `${at}: its done() returns ${!!st.done(e)} ${every}` };
|
|
186
|
+
const left = st.all.filter((p, k) => !p.optional && !s.parts?.[k]).map(p => `"${p.text}"`);
|
|
187
|
+
return { ok: false, step: s.step, text: `${at}: required parts not done yet: ${left.join(', ')} ${every}` };
|
|
188
|
+
} },
|
|
189
|
+
describe() {
|
|
190
|
+
const list = q.list();
|
|
191
|
+
return { active: list.filter(x => !x.done && !x.failed).map(x => ({ id: x.id, title: x.title, step: x.steps.find(s => s.current)?.text ?? null })),
|
|
192
|
+
done: list.filter(x => x.done).length, failed: list.filter(x => x.failed).length };
|
|
193
|
+
},
|
|
194
|
+
};
|
|
195
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
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
|
+
// the room check and its dev messages, and reading a saved list.
|
|
3
|
+
import { toast } from '../../ui/UI.js';
|
|
4
|
+
import { warnOnce, fmt } from '../../core/validate.js';
|
|
5
|
+
|
|
6
|
+
const STRINGS = {
|
|
7
|
+
full: 'Container {box} has no room for {id} (capacity {cap} slots, maxWeight {mw}): add returns false. Raise capacity / maxWeight, or remove something first',
|
|
8
|
+
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
|
+
badRow: "container '{box}': dropped a saved entry that is not { id: string, count: whole number > 0, data?: plain object } ({got}); the save was edited by hand or is damaged",
|
|
10
|
+
};
|
|
11
|
+
// order-independent signature: entries with equal data stack together whatever the key order
|
|
12
|
+
export const sig = v => v === undefined ? '' : v && typeof v === 'object'
|
|
13
|
+
? (Array.isArray(v) ? `[${v.map(sig)}]` : `{${Object.keys(v).sort().map(k => JSON.stringify(k) + ':' + sig(v[k]))}}`) : JSON.stringify(v);
|
|
14
|
+
// data is frozen: a piece's data only changes through setData (guarded like every other saved write), never by editing the object in place
|
|
15
|
+
export const freeze = o => { if (o && typeof o === 'object') { Object.freeze(o); for (const v of Object.values(o)) freeze(v); } return o; };
|
|
16
|
+
|
|
17
|
+
export function canTrade(b, take, give, takeN, giveN, data) {
|
|
18
|
+
if (!b.has(take, takeN)) return 'notEnough';
|
|
19
|
+
const sim = Object.create(b); sim._entries = b._entries.map(x => ({ ...x }));
|
|
20
|
+
let rest = takeN;
|
|
21
|
+
for (const en of sim._of(take)) { const k = Math.min(rest, en.count); en.count -= k; if (!(rest -= k)) break; }
|
|
22
|
+
sim._entries = sim._entries.filter(x => x.count > 0);
|
|
23
|
+
return sim._room(give, data) < giveN ? 'full' : true;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function acceptsFrom(b, src, item, n) {
|
|
27
|
+
const sim = Object.create(b), inv = b.inv;
|
|
28
|
+
sim._entries = b._entries.map(x => ({ ...x }));
|
|
29
|
+
sim.inv = Object.create(inv, { _newKey: { value: id => id + '#?' } }); // a dry run hands out no real keys
|
|
30
|
+
let moved = 0;
|
|
31
|
+
for (const en of src._of(item)) {
|
|
32
|
+
if (moved >= n) break;
|
|
33
|
+
const k = Math.min(n - moved, en.count, sim._room(en.id, en.data));
|
|
34
|
+
if (k > 0) sim._place(en.id, k, en.data, en.key, sim._entries.length);
|
|
35
|
+
moved += k;
|
|
36
|
+
}
|
|
37
|
+
return moved;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function putIn(b, id, n, data, key, silent) {
|
|
41
|
+
const def = b.inv.item(id), say = !silent && b._player, t = (k, p) => b.inv.engine.t(k, p);
|
|
42
|
+
const fit = Math.min(n, b._room(id, data)), info = { box: b.id, id, n, fit, stack: def.stack, cap: b.capacity, mw: b.maxWeight };
|
|
43
|
+
if (fit <= 0) { if (say) toast(b.inv.engine, t('inventory.full'), { kind: 'item' }); warnOnce(fmt(STRINGS.full, info)); return false; }
|
|
44
|
+
if (fit < n) warnOnce(fmt(STRINGS.partial, info));
|
|
45
|
+
const out = b._place(id, fit, data, key, b._entries.length);
|
|
46
|
+
if (say) toast(b.inv.engine, t('inventory.got', { icon: def.iconUrl ? '' : (def.icon || ''), name: def.name, n: fit }), { kind: 'item' });
|
|
47
|
+
b._emit('add', id, fit, out);
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function loadEntries(b, list) {
|
|
52
|
+
const plain = d => d === undefined || (d !== null && typeof d === 'object' && Object.getPrototypeOf(d) === Object.prototype);
|
|
53
|
+
b._entries = [];
|
|
54
|
+
for (const r of Array.isArray(list) ? list : []) {
|
|
55
|
+
const key = r?.key ?? r?.id;
|
|
56
|
+
if (typeof r?.id !== 'string' || !Number.isInteger(r.count) || r.count <= 0 || typeof key !== 'string' || !plain(r.data)) { warnOnce(fmt(STRINGS.badRow, { box: b.id, got: JSON.stringify(r) })); continue; }
|
|
57
|
+
b.inv._known(r.id); // an id the game no longer defines warns like add() does
|
|
58
|
+
b._entries.push({ key, id: r.id, count: r.count, data: freeze(r.data), sig: sig(r.data) });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Default 'dialogue' UI part: a box at the bottom with the speaker, the typed text, numbered choice buttons and a "continue" hint.
|
|
2
|
+
// It only draws what Dialogue hands it; a click calls d.advance() / d.choose(i), which run the ops dialogue.advance / dialogue.choose.
|
|
3
|
+
// Look: CSS classes .threedog-dlg* (style pack style.ui.css). A whole different box: engine.ui.set('dialogue', yourPart) (recipes/26-ui-parts.md).
|
|
4
|
+
import { injectUICSS } from '../../ui/UI.js';
|
|
5
|
+
/** @import { Engine, UIPart } from '../../types/core' */
|
|
6
|
+
/** @import { DialogueView } from '../../types/gameplay' */
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @param {Engine} engine
|
|
10
|
+
* @returns {UIPart}
|
|
11
|
+
* @internal
|
|
12
|
+
*/
|
|
13
|
+
export function dialogueBox(engine) {
|
|
14
|
+
injectUICSS();
|
|
15
|
+
let box = null, name, text, opts, hint, choices = null;
|
|
16
|
+
/** @type {DialogueView | null} */ let cur = null;
|
|
17
|
+
const build = () => {
|
|
18
|
+
box = document.createElement('div'); box.className = 'threedog-ui threedog-dlg';
|
|
19
|
+
name = document.createElement('b'); name.className = 'threedog-dlg-name';
|
|
20
|
+
text = document.createElement('div'); text.className = 'threedog-dlg-text';
|
|
21
|
+
opts = document.createElement('div'); opts.className = 'threedog-dlg-opts';
|
|
22
|
+
hint = document.createElement('span'); hint.className = 'threedog-dlg-hint';
|
|
23
|
+
box.append(name, text, opts, hint);
|
|
24
|
+
box.addEventListener('click', () => cur?.advance());
|
|
25
|
+
engine.uiRoot.appendChild(box);
|
|
26
|
+
};
|
|
27
|
+
return {
|
|
28
|
+
show() { if (!box) build(); box.hidden = false; },
|
|
29
|
+
/** @param {DialogueView} d */
|
|
30
|
+
update(d) {
|
|
31
|
+
cur = d;
|
|
32
|
+
name.textContent = d.speaker;
|
|
33
|
+
text.textContent = d.text;
|
|
34
|
+
if (d.choices !== choices) { // the choice list is the same array for the whole line: rebuild the buttons only when it changes
|
|
35
|
+
choices = d.choices; opts.innerHTML = '';
|
|
36
|
+
d.choices.forEach((c, i) => {
|
|
37
|
+
const b = document.createElement('button');
|
|
38
|
+
b.type = 'button'; b.className = 'threedog-btn'; b.textContent = c.key ? `${c.key}. ${c.text}` : c.text;
|
|
39
|
+
b.onclick = ev => { ev.stopPropagation(); cur?.choose(i); };
|
|
40
|
+
opts.appendChild(b);
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
hint.textContent = d.hint; hint.hidden = !d.hint;
|
|
44
|
+
},
|
|
45
|
+
hide() { if (box) box.hidden = true; cur = null; choices = null; },
|
|
46
|
+
dispose() { box?.remove(); box = null; },
|
|
47
|
+
};
|
|
48
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// Default 'prompt' UI part: the "E · Talk" label that follows the nearest interaction. Interactions picks the target and projects it to the screen;
|
|
2
|
+
// this only draws { x, y, text } and turns a click into view.use() (the op interaction.use). Look: CSS class .threedog-prompt (style pack style.ui.css).
|
|
3
|
+
import { injectUICSS, placeAt } from '../../ui/UI.js';
|
|
4
|
+
/** @import { Engine, UIPart } from '../../types/core' */
|
|
5
|
+
/** @import { PromptView } from '../../types/gameplay' */
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* @param {Engine} engine
|
|
9
|
+
* @returns {UIPart}
|
|
10
|
+
* @internal
|
|
11
|
+
*/
|
|
12
|
+
export function promptPart(engine) {
|
|
13
|
+
injectUICSS();
|
|
14
|
+
let el = null;
|
|
15
|
+
/** @type {PromptView | null} */ let cur = null;
|
|
16
|
+
return {
|
|
17
|
+
/** @param {PromptView} d */
|
|
18
|
+
update(d) {
|
|
19
|
+
if (!el) { el = document.createElement('div'); el.className = 'threedog-prompt'; el.addEventListener('click', () => cur?.use()); engine.uiRoot.appendChild(el); }
|
|
20
|
+
cur = d;
|
|
21
|
+
el.hidden = false;
|
|
22
|
+
if (el.textContent !== d.text) el.textContent = d.text;
|
|
23
|
+
placeAt(el, d.x, d.y);
|
|
24
|
+
},
|
|
25
|
+
hide() { if (el) el.hidden = true; cur = null; },
|
|
26
|
+
dispose() { el?.remove(); el = null; },
|
|
27
|
+
};
|
|
28
|
+
}
|