threedog 0.8.0 โ 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +223 -4
- package/README.md +6 -6
- package/core/assets/Animator.js +2 -0
- package/core/assets/Assets.js +44 -13
- package/core/assets/assetEntry.js +87 -22
- package/core/assets/assetHot.js +2 -1
- package/core/assets/assetReport.js +1 -2
- package/core/audio/Audio.js +24 -5
- package/core/base/I18n.js +6 -3
- package/core/base/Random.js +3 -1
- package/core/base/Vars.js +14 -4
- package/core/base/errorCodes.js +54 -16
- package/core/base/errorHints.js +12 -1
- package/core/base/errors.js +6 -4
- package/core/base/events.generated.js +10 -0
- package/core/base/follows.js +26 -0
- package/core/base/math.js +15 -8
- package/core/base/params.js +2 -2
- package/core/{saves โ base}/saveValues.js +24 -6
- package/core/base/sections.js +97 -0
- package/core/base/spelling.js +32 -0
- package/core/base/validate.js +8 -29
- package/core/engine/Engine.js +61 -18
- package/core/engine/Loading.js +30 -3
- package/core/engine/copies.js +1 -1
- package/core/engine/headlessLoad.js +30 -13
- package/core/engine/lifecycle.js +30 -25
- package/core/engine/loop.js +22 -4
- package/core/engine/moduleSlots.js +91 -15
- package/core/engine/moduleTypes.js +13 -0
- package/core/engine/modules.js +248 -62
- package/core/engine/page.js +25 -8
- package/core/engine/plugins.js +15 -3
- package/core/engine/services.js +3 -0
- package/core/engine/startup.js +46 -36
- package/core/input/Input.js +39 -19
- package/core/input/inputKeyboard.js +39 -0
- package/core/input/inputPad.js +23 -2
- package/core/input/inputPointer.js +3 -1
- package/core/input/inputSeat.js +66 -0
- package/core/input/inputTouch.js +23 -6
- package/core/inspect/DebugOverrides.js +13 -2
- package/core/inspect/Describe.js +10 -6
- package/core/inspect/Inspect.js +31 -4
- package/core/inspect/UrlState.js +14 -10
- package/core/inspect/catalog.js +12 -5
- package/core/inspect/describeRender.js +3 -2
- package/core/inspect/describeText.js +6 -2
- package/core/inspect/metadata.generated.js +4140 -0
- package/core/inspect/pictureWriters.js +117 -33
- package/core/inspect/toolDoor.js +21 -0
- package/core/inspect/valueHistory.js +35 -0
- package/core/ops/Ops.js +32 -7
- package/core/ops/control.js +48 -23
- package/core/ops/holds.js +4 -3
- package/core/ops/opsAtomic.js +18 -6
- package/core/ops/opsCheck.js +7 -5
- package/core/ops/opsFail.js +5 -7
- package/core/ops/opsRun.js +2 -2
- package/core/ops/owned.js +20 -3
- package/core/ops/sharedPoint.js +7 -10
- package/core/ops/stacks.js +22 -1
- package/core/saves/SaveStore.js +52 -26
- package/core/saves/Saves.js +122 -27
- package/core/saves/saveApply.js +159 -61
- package/core/saves/saveFiles.js +30 -25
- package/core/saves/saveVersions.js +20 -6
- package/core/saves/session.js +76 -33
- package/core/saves/stateReplace.js +184 -0
- package/core/scene/Rays.js +21 -5
- package/core/scene/Views.js +6 -6
- package/core/scene/adaptive.js +13 -10
- package/core/scene/canvasBox.js +2 -0
- package/core/scene/compositeGround.js +72 -0
- package/core/scene/floor.js +17 -0
- package/core/scene/grid.js +2 -0
- package/core/scene/ground.contract.js +14 -0
- package/core/scene/ground.js +52 -17
- package/core/scene/pixel.js +154 -0
- package/core/scene/pixelRatio.js +167 -0
- package/core/scene/sceneDelta.js +3 -3
- package/core/scene/sceneMethods.js +11 -6
- package/core/scene/stepPoses.js +6 -1
- package/core/scene/thingExplain.js +1 -1
- package/core/scene/thingOps.js +22 -14
- package/core/scene/things.js +1 -1
- package/core/scene/tier.js +10 -0
- package/core/scene/view.js +126 -9
- package/core/stream/Batching.js +0 -1
- package/core/stream/Stream.js +24 -12
- package/core/stream/batchGroups.js +1 -0
- package/core/stream/scatter.js +5 -2
- package/core/stream/streamSources.js +2 -1
- package/core/threads/Commits.js +12 -7
- package/core/threads/Jobs.js +15 -5
- package/core/threads/Threads.js +5 -2
- package/core/time/Clock.js +3 -1
- package/core/time/skip.js +10 -4
- package/core/time/time.js +16 -10
- package/docs/AI.md +89 -72
- package/docs/API.md +18 -14
- package/docs/CODEMAP.md +68 -40
- package/docs/COMMANDS.md +22 -23
- package/docs/CONVENTIONS.md +120 -17
- package/docs/MIGRATING-0.8.md +2 -0
- package/docs/MIGRATING-1.0.md +101 -0
- package/docs/THREE.md +65 -12
- package/docs/api/cameraRig.md +3 -0
- package/docs/api/characters.md +13 -7
- package/docs/api/collider3d.md +9 -0
- package/docs/api/content.md +16 -15
- package/docs/api/dialogue.md +2 -1
- package/docs/api/engine.md +18 -16
- package/docs/api/events.md +14 -4
- package/docs/api/ground.md +2 -2
- package/docs/api/i18n.md +1 -1
- package/docs/api/input.md +2 -1
- package/docs/api/interactions.md +1 -1
- package/docs/api/inventory.md +1 -1
- package/docs/api/level.md +3 -2
- package/docs/api/nav.md +4 -2
- package/docs/api/particles.md +8 -5
- package/docs/api/pickups.md +1 -1
- package/docs/api/post.md +3 -4
- package/docs/api/quests.md +4 -2
- package/docs/api/rays.md +2 -0
- package/docs/api/rigid.md +3 -2
- package/docs/api/saves.md +8 -7
- package/docs/api/stream.md +4 -5
- package/docs/api/terrain.md +3 -4
- package/docs/api/terrainDraw.md +1 -1
- package/docs/api/timeline.md +2 -2
- package/docs/api/tools.md +3 -1
- package/docs/api/triggers.md +2 -0
- package/docs/api/vegetationDraw.md +1 -1
- package/docs/api/water.md +6 -2
- package/docs/api/weather.md +19 -4
- package/docs/api/weatherDraw.md +1 -1
- package/docs/api/world.md +1 -1
- package/docs/recipes/01-new-game.md +3 -3
- package/docs/recipes/02-npc.md +3 -4
- package/docs/recipes/03-items-pickups.md +11 -11
- package/docs/recipes/04-quests.md +2 -0
- package/docs/recipes/05-props-bake.md +9 -9
- package/docs/recipes/06-clock-events.md +6 -6
- package/docs/recipes/07-flow-scenes-pause.md +18 -15
- package/docs/recipes/08-weather-sky.md +5 -5
- package/docs/recipes/09-materials-lights-models.md +3 -3
- package/docs/recipes/10-blender-level.md +16 -4
- package/docs/recipes/11-vehicles.md +18 -6
- package/docs/recipes/12-navmesh.md +52 -8
- package/docs/recipes/13-animation.md +34 -8
- package/docs/recipes/14-custom-module.md +20 -8
- package/docs/recipes/15-perf.md +4 -4
- package/docs/recipes/16-dev-bridge.md +9 -8
- package/docs/recipes/18-world.md +13 -5
- package/docs/recipes/19-shooting-picking.md +3 -2
- package/docs/recipes/20-content-actions-save.md +26 -6
- package/docs/recipes/21-camera.md +17 -23
- package/docs/recipes/22-shop-gold.md +21 -12
- package/docs/recipes/23-ops.md +19 -15
- package/docs/recipes/26-ui-parts.md +3 -2
- package/docs/recipes/27-net.md +3 -3
- package/docs/recipes/28-terrain.md +3 -3
- package/docs/recipes/29-grid.md +1 -1
- package/docs/recipes/30-templates.md +10 -13
- package/docs/recipes/31-audio.md +2 -2
- package/docs/recipes/32-action-game.md +6 -5
- package/docs/recipes/33-stream-sources.md +4 -1
- package/docs/recipes/34-environment-lighting.md +7 -8
- package/docs/recipes/35-picture-from-reference.md +13 -9
- package/docs/recipes/36-ground-plants.md +3 -2
- package/docs/recipes/40-scene.md +11 -10
- package/docs/recipes/43-shader-patches-surfaces.md +7 -7
- package/docs/recipes/44-water-weather-hooks.md +9 -8
- package/docs/recipes/45-cascaded-shadows.md +3 -4
- package/docs/recipes/46-blender-art-route.md +3 -3
- package/docs/recipes/49-game-module-contract.md +2 -1
- package/docs/recipes/50-own-renderer.md +1 -0
- package/docs/recipes/51-capability-catalog.md +14 -8
- package/docs/recipes/52-around-the-picture.md +4 -4
- package/docs/recipes/55-mods-time-wrap.md +5 -4
- package/docs/recipes/56-webgpu-tsl.md +12 -1
- package/docs/recipes/57-control.md +30 -10
- package/docs/recipes/58-input.md +13 -0
- package/docs/recipes/60-judge-the-picture.md +1 -1
- package/docs/recipes/62-picture-code.md +106 -48
- package/docs/recipes/63-third-person-start.md +2 -1
- package/docs/recipes/64-particles.md +53 -4
- package/docs/recipes/65-swarm.md +2 -2
- package/docs/recipes/66-common-tasks.md +313 -0
- package/examples/action/.threedog/content-index.json +1 -1
- package/examples/action/GAMEMAP.md +3 -3
- package/examples/perf-island/.threedog/content-index.json +1 -1
- package/examples/perf-island/GAMEMAP.md +3 -3
- package/examples/perf-island/main.js +2 -2
- package/examples/plain-picture/GAMEMAP.md +3 -1
- package/examples/rc2d/GAMEMAP.md +1 -1
- package/examples/rc2d/rc2d.js +1 -1
- package/examples/styletest/.threedog/content-index.json +1 -1
- package/examples/styletest/GAMEMAP.md +3 -3
- package/examples/webgpu-tsl/GAMEMAP.md +1 -1
- package/examples/world/.threedog/content-index.json +1 -1
- package/examples/world/GAMEMAP.md +5 -4
- package/examples/world/main.js +3 -3
- package/index.d.ts +8 -5
- package/index.js +22 -1
- package/llms.txt +2 -1
- package/modules/ambience/Ambience.js +5 -3
- package/modules/calendar/index.js +7 -5
- package/modules/camera/FirstPersonCamera.js +3 -3
- package/modules/camera/FixedCamera.js +34 -20
- package/modules/camera/FollowCamera.js +20 -11
- package/modules/camera/RtsCamera.js +1 -0
- package/modules/camera/common.js +33 -22
- package/modules/camera/pixelSnap.js +62 -0
- package/modules/characters/Character.js +136 -43
- package/modules/characters/NPC.js +60 -28
- package/modules/characters/assetModel.js +2 -2
- package/modules/characters/astar.js +47 -28
- package/modules/characters/character.contract.js +21 -0
- package/modules/characters/contract.js +17 -3
- package/modules/characters/index.js +94 -34
- package/modules/characters/moveHelpers.js +80 -15
- package/modules/characters/mover.contract.js +14 -0
- package/modules/characters/movers/common.js +6 -4
- package/modules/characters/movers/rapier.js +12 -5
- package/modules/characters/movers/simple.js +25 -12
- package/modules/characters/movers/support.js +18 -7
- package/modules/characters/npcAvoid.js +15 -12
- package/modules/characters/npcSim.js +75 -25
- package/modules/characters/npcView.js +13 -6
- package/modules/characters/pathAsync.js +74 -24
- package/modules/characters/pathJob.js +38 -21
- package/modules/characters/player.js +59 -47
- package/modules/characters/seat.js +56 -0
- package/modules/characters/vehicle.contract.js +8 -5
- package/modules/characters/walkTo.js +31 -18
- package/modules/collision/Collision.js +44 -26
- package/modules/collision/contract.js +2 -2
- package/modules/collision/grid.js +6 -1
- package/modules/content/explain.js +1 -1
- package/modules/content/fields.js +3 -3
- package/modules/content/ids.js +3 -1
- package/modules/content/index.js +83 -27
- package/modules/content/loader.js +110 -130
- package/modules/content/markers.js +1 -1
- package/modules/content/models.js +48 -14
- package/modules/content/packs.js +2 -1
- package/modules/content/places.js +5 -4
- package/modules/content/props.js +8 -6
- package/modules/content/rules.js +29 -47
- package/modules/content/templates.js +66 -35
- package/modules/content/words.js +19 -6
- package/modules/debug/DebugPanel.js +4 -2
- package/modules/flow/contract.js +1 -0
- package/modules/flow/index.js +24 -14
- package/modules/gameplay/Container.js +5 -2
- package/modules/gameplay/Containers.js +9 -1
- package/modules/gameplay/Dialogue.js +82 -25
- package/modules/gameplay/Interactions.js +61 -32
- package/modules/gameplay/Inventory.js +56 -13
- package/modules/gameplay/Quests.js +133 -24
- package/modules/gameplay/boxOps.js +7 -0
- package/modules/gameplay/dialogueBubbles.js +14 -9
- package/modules/gameplay/inventoryOps.js +11 -7
- package/modules/gameplay/pickups.js +43 -16
- package/modules/gameplay/questLog.js +4 -2
- package/modules/gameplay/questSave.js +6 -1
- package/modules/gameplay/quests.contract.js +1 -1
- package/modules/grid/Grid.js +1 -1
- package/modules/grid/Layer.js +8 -4
- package/modules/grid/index.js +21 -15
- package/modules/grid/ops.js +43 -46
- package/modules/grid/tiles.js +1 -1
- package/modules/hlod/index.js +6 -3
- package/modules/hud/index.js +6 -4
- package/modules/hud/parts.js +4 -4
- package/modules/level/contract.js +2 -2
- package/modules/level/heightfield.js +17 -21
- package/modules/level/index.js +83 -26
- package/modules/level/load.js +165 -48
- package/modules/level/nodes.js +34 -16
- package/modules/lights/index.js +6 -3
- package/modules/lights/sources.js +3 -1
- package/modules/music/Music.js +4 -2
- package/modules/nav/contract.js +7 -5
- package/modules/nav/index.js +174 -44
- package/modules/nav/navPath.js +45 -10
- package/modules/net/index.js +1 -1
- package/modules/particles/Particles.js +85 -22
- package/modules/particles/effect.js +80 -28
- package/modules/particles/shaders.js +17 -0
- package/modules/photo/Photo.js +12 -10
- package/modules/rigid/RigidBodies.js +200 -57
- package/modules/rigid/Vehicles.js +15 -5
- package/modules/rigid/collider3d.contract.js +26 -0
- package/modules/rigid/ragdoll.js +55 -44
- package/modules/rigid/ragdollBones.js +83 -33
- package/modules/rigid/refresh.js +10 -0
- package/modules/rigid/sync.js +46 -15
- package/modules/settings/Settings.js +84 -37
- package/modules/settings/apply.js +15 -8
- package/modules/settings/sections.js +7 -4
- package/modules/settings/strings.js +2 -2
- package/modules/sky/skyModule.js +3 -1
- package/modules/swarm/Swarm.js +16 -6
- package/modules/terrain/ChunkManager.js +10 -16
- package/modules/terrain/index.js +17 -11
- package/modules/terrain/terrainEdit.js +13 -2
- package/modules/terrain/terrainGen.js +5 -3
- package/modules/terrain/terrainShape.js +1 -1
- package/modules/timeline/Timeline.js +58 -26
- package/modules/timeline/Tween.js +19 -13
- package/modules/timeline/shots.js +19 -10
- package/modules/triggers/index.js +87 -20
- package/modules/vegetation/Vegetation.js +4 -3
- package/modules/vegetation/draw.js +16 -0
- package/modules/vegetation/groundChunks.js +10 -7
- package/modules/vegetation/index.js +30 -7
- package/modules/water/Water.js +6 -2
- package/modules/weather/Weather.js +16 -15
- package/modules/weather/weatherDraw.js +7 -6
- package/modules/world/World.js +20 -7
- package/modules/world/explain.js +1 -1
- package/modules/world/index.js +13 -6
- package/modules/world/persist.js +23 -8
- package/modules/world/pos.js +4 -4
- package/modules/world/records.js +13 -7
- package/modules/world/sim.js +74 -23
- package/modules/world/simFar.js +2 -2
- package/modules/world/state.js +31 -6
- package/modules/world/thingSource.js +16 -3
- package/modules/world/views.js +19 -8
- package/package.json +7 -1
- package/render/PostFX.js +47 -29
- package/render/backend.js +5 -1
- package/render/fx/particles.tsl.js +8 -6
- package/render/fx/postWebGPU.tsl.js +3 -3
- package/render/layers.js +1 -1
- package/render/lightmap.js +23 -3
- package/render/occlusion.js +43 -12
- package/render/patches.js +2 -2
- package/render/postWebGL.js +4 -3
- package/render/probes.js +25 -0
- package/render/shadows.js +2 -2
- package/types/core.d.ts +142 -55
- package/types/gameplay.d.ts +92 -40
- package/types/generated/core/base/I18n.d.ts +2 -2
- package/types/generated/core/input/Input.d.ts +16 -2
- package/types/generated/core/input/inputSeat.d.ts +26 -0
- package/types/generated/core/inspect/DebugOverrides.d.ts +15 -1
- package/types/generated/core/ops/Ops.d.ts +2 -1
- package/types/generated/core/ops/control.d.ts +12 -2
- package/types/generated/core/saves/Saves.d.ts +26 -6
- package/types/generated/core/saves/session.d.ts +1 -1
- package/types/generated/core/scene/Views.d.ts +1 -1
- package/types/generated/core/stream/Stream.d.ts +6 -4
- package/types/generated/modules/grid/Grid.d.ts +1 -0
- package/types/generated/modules/particles/Particles.d.ts +4 -3
- package/types/generated/modules/timeline/Timeline.d.ts +5 -4
- package/types/generated/modules/weather/Weather.d.ts +1 -7
- package/types/generated/modules/world/World.d.ts +6 -4
- package/types/generated/render/PostFX.d.ts +6 -14
- package/types/nav.d.ts +36 -4
- package/types/physics.d.ts +55 -7
- package/types/pixel.d.ts +75 -0
- package/types/world.d.ts +14 -8
- package/ui/Parts.js +9 -2
- package/ui/theme.js +2 -2
- package/core/scene/engineCamera.js +0 -32
- package/modules/camera/projection.js +0 -21
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
// Using one is the op interaction.use { id?, action? } (recipes/23-ops.md): the interact key (in fixed), a click on the prompt, the dev bridge and tests all
|
|
5
5
|
// run it,
|
|
6
6
|
// so every use is logged and checked by the same can (exists, enabled, in range, input not locked). Without id it uses the one the actor would pick now.
|
|
7
|
-
// Who interacts is engine.actor (core/ops/actor.js), measured with engine.actorPosition(): the player by default, a vehicle or squad member when the game says so
|
|
7
|
+
// Who interacts is engine.actor (core/ops/actor.js), measured with engine.actorPosition(): the player by default, a vehicle or squad member when the game says so.
|
|
8
|
+
// A seat (engine.input.seat) presses for its own seat.actor; the prompt and the options stay engine.actor's, since one screen shows one prompt;
|
|
8
9
|
// the op's ctx.actor (a net peer, an NPC) is handed to label / enabled / onUse as (object, { actor }).
|
|
9
10
|
// How the one in front of you is chosen is the pick option: 'nearest' | 'facing' | 'aim' | a function (see interactions()). Each action is picked on its own,
|
|
10
11
|
// so one object can carry "Open" and "Lock" as two interactions with different action names (each bound to the game's own key).
|
|
@@ -28,7 +29,9 @@ import { promptPart } from './interactionPrompt.js';
|
|
|
28
29
|
|
|
29
30
|
import { readParams, keysSchema } from '../../core/base/params.js';
|
|
30
31
|
import { codedError, coded } from '../../core/base/errorHints.js';
|
|
31
|
-
import {
|
|
32
|
+
import { reportError } from '../../core/base/errors.js';
|
|
33
|
+
import { failure } from '../../core/ops/opsFail.js';
|
|
34
|
+
import { refuseSave } from '../../core/base/saveValues.js';
|
|
32
35
|
import { isPlainObject } from '../../core/base/util.js';
|
|
33
36
|
import { DEV, warnOnce } from '../../core/base/validate.js';
|
|
34
37
|
import { vec3 } from '../../core/base/math.js';
|
|
@@ -51,12 +54,12 @@ const bindLine = action => action === 'interact' ? 'createEngine({ bindings: { .
|
|
|
51
54
|
const SETUP_FIX = "e.g. engine.use(interactions({ ...presets.interactions.nearest })) (import { presets } from 'threedog'), or interactions({ pick: 'nearest' | 'facing' | 'aim' | fn })";
|
|
52
55
|
|
|
53
56
|
export class Interactions {
|
|
54
|
-
constructor(engine, { action, promptHeight, radius, pick } = {},
|
|
57
|
+
constructor(engine, { action, promptHeight, radius, pick } = {}, ctx) {
|
|
55
58
|
// No default pick and no default key: which object counts as "in front of you" and which key uses it are the game's choices (genericity rule:
|
|
56
59
|
// core carries no preset). presets.interactions.* are the picks, presets.bindings.interact the keys (declared here, bound by the game).
|
|
57
60
|
if (pick === undefined) throw codedError('interaction-setup', `interactions(): no pick given; ${SETUP_FIX}`);
|
|
58
61
|
if (typeof pick !== 'function' && !PICKS.includes(pick)) throw codedError('interaction-setup', `interactions({ pick }): '${pick}' is not a pick mode. Use ${PICKS.map(p => `'${p}'`).join(' | ')} or a function (candidates, ctx) => candidate`);
|
|
59
|
-
track(engine.input.action(action, { label: 'input.interact', owner: 'interactions' }));
|
|
62
|
+
ctx.track(engine.input.action(action, { label: 'input.interact', owner: 'interactions' }));
|
|
60
63
|
this.engine = engine;
|
|
61
64
|
this.action = action;
|
|
62
65
|
this.radius = radius;
|
|
@@ -84,8 +87,8 @@ export class Interactions {
|
|
|
84
87
|
this._seq = 0; this._order = 0;
|
|
85
88
|
/** @internal non-zero during one fixed() / update() pass: each item's world position is computed once per pass, not once per action */ this._pass = 0;
|
|
86
89
|
this._passes = 0;
|
|
87
|
-
engine.input.touchButton(action, 'input.interact');
|
|
88
|
-
|
|
90
|
+
ctx.track(engine.input.touchButton(action, 'input.interact'));
|
|
91
|
+
ctx.ui.define('prompt', promptPart);
|
|
89
92
|
/** @internal clicking the prompt: the same op as the interact key */
|
|
90
93
|
this._use = () => { if (this.current) engine.ops.run('interaction.use', { id: this.current.id }, { source: 'player' }); };
|
|
91
94
|
this._shown = false;
|
|
@@ -94,7 +97,8 @@ export class Interactions {
|
|
|
94
97
|
/** @internal dev: an add since the last key check */ this._keysDue = false;
|
|
95
98
|
/** @internal ids of the once items already used; _counted: counter name -> what uses added. The saved state, so both follow a load and a new game */
|
|
96
99
|
this._spent = new Set(); this._counted = new Map();
|
|
97
|
-
|
|
100
|
+
/** @internal ids of the once items whose async onUse has not settled: not spent yet, but not usable twice either */ this._waiting = new Set();
|
|
101
|
+
ctx.saves.register('interactions', { atomic: true, version: 1, save: () => ({ spent: [...this._spent], counted: Object.fromEntries(this._counted) }), load: d => this._load(d) });
|
|
98
102
|
}
|
|
99
103
|
|
|
100
104
|
/**
|
|
@@ -104,7 +108,8 @@ export class Interactions {
|
|
|
104
108
|
* radius defaults to interactions({ radius }) (2.5 m; Infinity = from anywhere, usually with approach). Add two with different actions to give one object
|
|
105
109
|
* two verbs. hold: seconds the key must stay down (progress goes to the prompt; release, leaving reach or disabled interrupts it: interaction:interrupt).
|
|
106
110
|
* approach: true walks the player there first (walkTo, stops 1.2 m away), then uses it. Returns a handle { remove() }.
|
|
107
|
-
* once: true hides the object after a use and it cannot be used again (onUse returning { ok: false } leaves it
|
|
111
|
+
* once: true hides the object after a use and it cannot be used again (onUse returning { ok: false } leaves it, also when an async onUse resolves to it or rejects: the use is judged
|
|
112
|
+
* when it settles, and the item cannot be used again meanwhile); saved, and back on a new game. The save
|
|
108
113
|
* knows it by id, else the object's name; development throws when it has neither. counter: name of a HUD counter that each use
|
|
109
114
|
* adds 1 to (hud.bump; nothing without hud()); declare it once at setup with hud.counter(name, { label, value: 0, max }), not on session:start.
|
|
110
115
|
* label, enabled and onUse are called with (object, { actor }): actor is the world record id of who asks / uses it (engine.actor for the local user,
|
|
@@ -118,6 +123,8 @@ export class Interactions {
|
|
|
118
123
|
* engine.interactions.add(clerk, { label: 'Talk', radius: Infinity, approach: true, onUse: talk }); // from anywhere: walk over, then talk
|
|
119
124
|
* @example // onUse may return a result; interaction.use hands it back as value. Returning { ok: false, code } (failure(code)) fails the op with that code:
|
|
120
125
|
* const r = engine.ops.run('interaction.use'); if (!r.ok) say(r.code) // 'full' for a pickup in a full bag
|
|
126
|
+
* @example // an async onUse: the op is ok once it started, and its value is a Promise of the answer (never a rejection: a throw answers { ok: false, code: 'error' })
|
|
127
|
+
* const r = engine.ops.run('interaction.use', { id: 'shrine' }); const a = await r.value; if (a?.ok === false) say(a.code);
|
|
121
128
|
*/
|
|
122
129
|
add(target, opts = {}) {
|
|
123
130
|
readParams('interactions.add()', keysSchema(['id', 'label', 'radius', 'action', 'onUse', 'enabled', 'height', 'hold', 'approach', 'once', 'counter']), opts);
|
|
@@ -127,16 +134,16 @@ export class Interactions {
|
|
|
127
134
|
if (counter !== undefined && !(typeof counter === 'string' && counter)) throw codedError('interaction-option', `interactions.add(): counter is the name of a HUD counter (counter: 'shells'), got ${JSON.stringify(counter)}`, TypeError);
|
|
128
135
|
// stable id for the interaction.use op: given, else the world record being built (pickup, NPC, entity), else (once: the save knows it by id) the mesh's
|
|
129
136
|
// name, else a running number. The number counts adds over the page's life, so it means another thing after a rebuild: a once item kept under one
|
|
130
|
-
// comes back after a load while its count stays, or hides the wrong thing. So once refuses it
|
|
137
|
+
// comes back after a load while its count stays, or hides the wrong thing. So once refuses it, and the fix is one word
|
|
131
138
|
let id = opts.id ?? this.engine.world?.buildingId ?? (once && target?.name || null);
|
|
132
|
-
if (once &&
|
|
139
|
+
if (once && (id == null || this.get(id))) throw codedError('interaction-option', `interactions.add(): a once item is saved by its id, and this one has ${id == null ? 'none' : `the same id as another ('${id}')`}. Give each a stable one: { id: 'shell-3', once: true }, or set mesh.name`, TypeError);
|
|
133
140
|
id ??= 'interaction' + (++this._seq);
|
|
134
141
|
if (this.get(id)) id += '#' + (++this._seq);
|
|
135
142
|
let object = target;
|
|
136
143
|
if (!target?.isObject3D) { object = new THREE.Object3D(); vec3(target, object.position); }
|
|
137
144
|
// a fixed position never moves: its world position is known now; an object is measured once per pass (_at)
|
|
138
145
|
// a used once item is simply not enabled: pick, the hold, describe and the op's can all ask enabled, so none of them needs a rule of its own
|
|
139
|
-
const enabled = once ? (o, c) => !this._spent.has(id) && allowed(o, c) : allowed;
|
|
146
|
+
const enabled = once ? (o, c) => !this._spent.has(id) && !this._waiting.has(id) && allowed(o, c) : allowed;
|
|
140
147
|
const it = { id, object, label, radius, action, onUse, enabled, height, hold, approach: !!approach, once: !!once, counter, _p: new THREE.Vector3(), _at: target?.isObject3D ? -1 : Infinity,
|
|
141
148
|
_n: this._order++, _en: null, _ix: null, _lx: NaN, _lz: NaN, _par: undefined };
|
|
142
149
|
if (!target?.isObject3D) it._p.copy(object.position);
|
|
@@ -145,9 +152,20 @@ export class Interactions {
|
|
|
145
152
|
this._index(it);
|
|
146
153
|
return { remove: () => { if (it._gone) return; it._gone = true; this._byId.delete(it.id); this._unindex(it); if (this.current === it) this.current = null; } };
|
|
147
154
|
}
|
|
148
|
-
/**
|
|
155
|
+
/**
|
|
156
|
+
* @internal Every use ends here (key, click, hold, approach, op), and is judged when onUse has settled, sync or async. An async one hands back a Promise of the same answer,
|
|
157
|
+
* which never rejects: the key press that started it has nobody listening. A state replaced while it waited is not the state it was used in, so it spends nothing there
|
|
158
|
+
*/
|
|
149
159
|
_run(it, actor) {
|
|
150
|
-
const r = it.onUse?.(it.object, { actor });
|
|
160
|
+
const e = this.engine, r = it.onUse?.(it.object, { actor });
|
|
161
|
+
if (typeof r?.then !== 'function') return this._judge(it, r);
|
|
162
|
+
const state = e.saves.generation;
|
|
163
|
+
this._waiting.add(it.id);
|
|
164
|
+
return r.then(v => e.saves.generation === state ? e.ops.allow(() => this._judge(it, v)) : v, err => { reportError(e, err, `interaction '${it.id}' onUse`, { soft: true }); return failure('error'); })
|
|
165
|
+
.finally(() => { if (e.saves.generation === state) this._waiting.delete(it.id); });
|
|
166
|
+
}
|
|
167
|
+
/** @internal once and counter count only a use that went through */
|
|
168
|
+
_judge(it, r) {
|
|
151
169
|
if (r?.ok === false) return r;
|
|
152
170
|
if (it.counter && this.engine.hud) { this.engine.hud.bump(it.counter); this._counted.set(it.counter, (this._counted.get(it.counter) ?? 0) + 1); }
|
|
153
171
|
// shortcut: once lives on the local peer (interaction.use is net: 'local'); a thing all peers share in a net game is a pickup (the host decides)
|
|
@@ -163,6 +181,7 @@ export class Interactions {
|
|
|
163
181
|
if (!Array.isArray(spent) || !spent.every(id => typeof id === 'string') || !isPlainObject(counted) || !Object.values(counted).every(Number.isFinite))
|
|
164
182
|
refuseSave('interactions', 'the part', 'must be { spent: [id], counted: { id: number } }', d);
|
|
165
183
|
const was = this._spent; this._spent = new Set(spent);
|
|
184
|
+
if (this.engine.saves.replacing) this._waiting.clear(); // a load, not an atomic rollback: what was waiting belongs to the state just left
|
|
166
185
|
for (const it of this._byId.values()) if (it.once && was.has(it.id) !== this._spent.has(it.id)) it.object.visible = !this._spent.has(it.id);
|
|
167
186
|
for (const name of new Set([...this._counted.keys(), ...Object.keys(counted)])) {
|
|
168
187
|
const d = (counted[name] ?? 0) - (this._counted.get(name) ?? 0);
|
|
@@ -240,7 +259,7 @@ export class Interactions {
|
|
|
240
259
|
// 'aim' follows the camera, which only the local user looks through; anyone else aims where they face
|
|
241
260
|
const aim = mode === 'aim' && actor === e.actor;
|
|
242
261
|
// the actor's body, for its facing
|
|
243
|
-
const obj = mode === 'nearest' || aim ? null : actor === 'player' && e.player ? e.player.root : e.world?.view(actor) ?? null;
|
|
262
|
+
const obj = mode === 'nearest' || aim ? null : actor === 'player' && e.player ? e.player.root : e.control.characterOf(actor)?.root ?? e.world?.view(actor) ?? null;
|
|
244
263
|
if (obj) { obj.getWorldDirection(D); D.y = 0; D.normalize(); }
|
|
245
264
|
if (aim) { e.camera.getWorldPosition(O); e.camera.getWorldDirection(D); }
|
|
246
265
|
let best = null, bestS = Infinity;
|
|
@@ -288,7 +307,7 @@ export class Interactions {
|
|
|
288
307
|
return c ? this.get(c.id) : null;
|
|
289
308
|
}
|
|
290
309
|
/** @internal The key went down and nothing was used: logged like a refused interaction.use, with the same codes. A record, not a warning: tapping E in a menu is normal play */
|
|
291
|
-
_pressRefused(action, reason) { const e = this.engine; e.ops.refused('interaction.use', { action, ...(reason === 'inputLocked' && { by: lockFacts(e).by }) }, { reason, actor
|
|
310
|
+
_pressRefused(action, reason, actor = this.engine.actor) { const e = this.engine; e.ops.refused('interaction.use', { action, ...(reason === 'inputLocked' && { by: lockFacts(e).by }) }, { reason, actor, source: 'player' }); }
|
|
292
311
|
/** Fixed step: each action's key fires that action's pick (input snapshot, frame-rate independent; picked on the spot, not from last frame). @internal */
|
|
293
312
|
fixed(dt) {
|
|
294
313
|
const inp = this.engine.input;
|
|
@@ -300,25 +319,30 @@ export class Interactions {
|
|
|
300
319
|
}
|
|
301
320
|
this._pass = ++this._passes;
|
|
302
321
|
if (this._hold) this._tickHold(dt);
|
|
322
|
+
this._presses(inp, this.engine.actor);
|
|
323
|
+
for (const s of inp.seats) if (s.actor) this._presses(s, s.actor);
|
|
324
|
+
this._pass = 0;
|
|
325
|
+
}
|
|
326
|
+
/** @internal The presses of one input, engine.input or a seat, for the actor it acts for. One hold at a time: a press during someone's hold waits for it to end */
|
|
327
|
+
_presses(input, actor) {
|
|
303
328
|
for (const a of this._actions.keys()) {
|
|
304
|
-
if (!
|
|
305
|
-
const b = this.pick(
|
|
306
|
-
if (!b) { this._pressRefused(a, 'nothingNear'); continue; }
|
|
307
|
-
if (b.hold > 0) { this._hold = { it: b, action: a, t: 0 }; this._holdView(); this.engine.events.emit('interaction:hold', { id: b.id, action: a, seconds: b.hold }); }
|
|
308
|
-
else this.engine.ops.run('interaction.use', { id: b.id }, { source: 'player' });
|
|
329
|
+
if (!input.pressed(a) || this._hold) continue;
|
|
330
|
+
const b = this.pick(actor, a);
|
|
331
|
+
if (!b) { this._pressRefused(a, 'nothingNear', actor); continue; }
|
|
332
|
+
if (b.hold > 0) { this._hold = { it: b, action: a, t: 0, input, actor }; this._holdView(); this.engine.events.emit('interaction:hold', { id: b.id, action: a, seconds: b.hold }); }
|
|
333
|
+
else this.engine.ops.run('interaction.use', { id: b.id }, { source: 'player', actor });
|
|
309
334
|
}
|
|
310
|
-
this._pass = 0;
|
|
311
335
|
}
|
|
312
336
|
/** @internal One fixed step of the hold: released / removed / disabled / out of reach interrupts it, else it counts; complete = the op interaction.use */
|
|
313
337
|
_tickHold(dt) {
|
|
314
|
-
const h = this._hold, it = h.it, e = this.engine, p = e.actorPosition();
|
|
315
|
-
const why = !
|
|
338
|
+
const h = this._hold, it = h.it, e = this.engine, p = e.actorPosition(h.actor);
|
|
339
|
+
const why = !h.input.down(h.action) ? 'released' : it._gone ? 'removed' : !it.enabled(it.object, { actor: h.actor }) ? 'disabled'
|
|
316
340
|
: !p || this._where(it).distanceTo(W.set(p.x, p.y ?? 0, p.z)) >= it.radius ? 'tooFar' : null;
|
|
317
341
|
if (why) return this._interrupt(why);
|
|
318
342
|
h.t += dt; this._holdView();
|
|
319
343
|
if (h.t < it.hold) return;
|
|
320
344
|
this._hold = this.holding = null;
|
|
321
|
-
e.ops.run('interaction.use', { id: it.id }, { source: 'player' });
|
|
345
|
+
e.ops.run('interaction.use', { id: it.id }, { source: 'player', actor: h.actor });
|
|
322
346
|
}
|
|
323
347
|
/** @internal */
|
|
324
348
|
_holdView() { const h = this._hold; this.holding = { id: h.it.id, action: h.action, seconds: h.it.hold, progress: Math.min(1, h.t / h.it.hold) }; }
|
|
@@ -379,8 +403,8 @@ export class Interactions {
|
|
|
379
403
|
// label / enabled / onUse all get (object, { actor }): who is asking is part of the question (a door that only its owner may open, a shop that greets each
|
|
380
404
|
// net peer by name), so a game never has to read engine.actor or engine.player inside them and they stay right for NPCs and peers
|
|
381
405
|
const labelOf = (it, actor) => typeof it.label === 'function' ? it.label(it.object, { actor }) : it.label;
|
|
382
|
-
// shortcut: approach walks only
|
|
383
|
-
const walkerOf = (e, actor) => actor === 'player'
|
|
406
|
+
// shortcut: approach walks only players (actor 'player' or a seat's); a squad / RTS game whose actor is an NPC gets 'cannotWalk' until NPC actors map to a Character
|
|
407
|
+
const walkerOf = (e, actor) => { const c = actor === 'player' ? e.player : e.input.seats.some(s => s.actor === actor) ? e.control.characterOf(actor) : null; return c?.walkTo ? c : null; };
|
|
384
408
|
|
|
385
409
|
const INTERACTION_PARAMS = {
|
|
386
410
|
action: { type: 'string', default: 'interact', desc: 'input action that uses the interaction' },
|
|
@@ -404,9 +428,9 @@ const INTERACTION_PARAMS = {
|
|
|
404
428
|
export function interactions(opts) {
|
|
405
429
|
const o = readParams('interactions', INTERACTION_PARAMS, opts ?? {});
|
|
406
430
|
let i = null;
|
|
407
|
-
return { name: 'interactions', type: 'rules', provides: ['interactions'], optional: ['hud'], label: 'Interactions', params: INTERACTION_PARAMS, options: o, noSkip: 'input and prompt state only', stage: 'gameplay',
|
|
431
|
+
return { name: 'interactions', skipKind: 'none', type: 'rules', provides: ['interactions'], optional: ['hud'], label: 'Interactions', params: INTERACTION_PARAMS, options: o, noSkip: 'input and prompt state only', stage: 'gameplay',
|
|
408
432
|
// o: the schema defaults are filled in, the class repeats none
|
|
409
|
-
install(e, ctx) { e.i18n.add({ 'zh-CN': { 'module.interactions': 'ไบคไบ' }, en: { 'module.interactions': 'interactions' } }); i = new Interactions(e, o, ctx
|
|
433
|
+
install(e, ctx) { e.i18n.add({ 'zh-CN': { 'module.interactions': 'ไบคไบ' }, en: { 'module.interactions': 'interactions' } }); i = new Interactions(e, o, ctx); defineUse(e, ctx, i); return i; },
|
|
410
434
|
fixed(dt) { i.fixed(dt); }, frame() { i.update(); },
|
|
411
435
|
// interactions are "weak" info: when an NPC, pickup or entity already reported the same object, only add "interactable: xxx"
|
|
412
436
|
describe(e, ctx) {
|
|
@@ -429,9 +453,9 @@ function lockFacts(e) {
|
|
|
429
453
|
}
|
|
430
454
|
|
|
431
455
|
/** The engine op interaction.use { id?, action? }: what the interact key, the prompt click, the dev bridge and tests all run */
|
|
432
|
-
function defineUse(e, i) {
|
|
456
|
+
function defineUse(e, ctx, i) {
|
|
433
457
|
const find = (id, action, ctx) => id !== undefined ? i.get(id) : i.pick(ctx.actor, action);
|
|
434
|
-
|
|
458
|
+
ctx.ops.define('interaction.use', {
|
|
435
459
|
desc: 'Use an interaction (talk, pick up, open...); without id, the one the actor would pick now (optionally for one action)',
|
|
436
460
|
args: { id: 'string?', action: 'string?' },
|
|
437
461
|
net: 'local', // the prompt and reach are this player's; game ops inside onUse are routed to the host (net: 'peer' ones) or refused
|
|
@@ -448,7 +472,7 @@ function defineUse(e, i) {
|
|
|
448
472
|
const d = it.object.getWorldPosition(V).distanceTo(W.set(p.x, p.y ?? 0, p.z)), r1 = v => Math.round(v * 10) / 10;
|
|
449
473
|
return d >= it.radius ? { code: 'tooFar', facts: { distance: r1(d), radius: it.radius, at: { x: r1(V.x), z: r1(V.z) } } } : true;
|
|
450
474
|
},
|
|
451
|
-
// onUse's return value is the op's value; { ok: false, code } fails the op (pickups: code 'full' when the bag is full).
|
|
475
|
+
// onUse's return value is the op's value; { ok: false, code } fails the op (pickups: code 'full' when the bag is full). An async onUse: the value is a Promise of that answer.
|
|
452
476
|
// approach from afar: the value is { approaching } (a Promise of onUse's result after arrival, or the walk's { status } when it did not arrive)
|
|
453
477
|
run(e, { id, action }, ctx) {
|
|
454
478
|
const it = find(id, action, ctx);
|
|
@@ -458,10 +482,15 @@ function defineUse(e, i) {
|
|
|
458
482
|
// the game holds this character on the walk's layer: 'cannot walk now' is an answer, and from the key press in a fixed step a throw would freeze play
|
|
459
483
|
let walk; try { walk = ch.walkTo(q, { arrive: APPROACH_ARRIVE }); } catch (err) { if (err?.code === 'control-conflict') return { ok: false, code: 'cannotWalk' }; throw err; }
|
|
460
484
|
// used after arrival, so checked again then: removed or disabled while walking = not used
|
|
461
|
-
|
|
485
|
+
// the op ended steps ago: the use is the same op again, now in reach, so it has its actor, source, checks and a line in the history
|
|
486
|
+
const use = () => { const u = e.ops.run('interaction.use', { id: it.id }, { actor: ctx.actor, source: ctx.source }); return u.ok ? u.value : u; };
|
|
487
|
+
// the handle of the task it started: remove() calls the walk off, and the walk's cancelled answer is what approaching settles with
|
|
488
|
+
return { approaching: Object.assign(walk.then(r => r.status === 'arrived' && !it._gone && it.enabled(it.object, { actor: ctx.actor }) ? use() : r), { remove: () => walk.remove() }) };
|
|
462
489
|
},
|
|
463
490
|
// no key: the op still runs when code asks (a click-only game), but it is not offered, so `ops` shows no โ for what no key reaches; describe() says why
|
|
464
491
|
offers(e, ctx) { const it = find(undefined, undefined, ctx); return it && !(ctx.actor === e.actor && e.input.isUnbound(it.action)) ? [{ id: it.id }] : []; },
|
|
465
492
|
reasons: { unknown: 'No interaction with this id', nothingNear: 'No interaction in range', disabled: 'Its enabled() is false', tooFar: 'Actor is outside its radius', cannotWalk: 'approach walks the player; this actor has no character to walk', inputLocked: 'A title, window, dialogue or cutscene locks input; facts.by names it' },
|
|
466
493
|
});
|
|
467
494
|
}
|
|
495
|
+
|
|
496
|
+
export const handRolled = [{ kind: 'reach', seen: 'a hand-made reach check for interacting', use: 'engine.interactions.add(target, { ... }): prompt, range and the interact action are handled (recipe 20)', quiet: /\b(engine|e|eng|ctx)\.interactions\b/, code: /(?:\bdistanceTo(?:Squared)?\(|\bMath\.hypot\(|\bdist(?:ance)?\w*)[^;]*<=?\s*\d/, near: [{ re: /KeyE|['"]e['"]|interact|press e\b|talk/i, lines: 3, on: 'raw' }] }];
|
|
@@ -13,17 +13,21 @@
|
|
|
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 { keepTable } from '../../core/base/sections.js';
|
|
16
17
|
import { checkOptions, warnMissing, freezeDef } from '../../core/base/validate.js';
|
|
17
18
|
import { readParams } from '../../core/base/params.js';
|
|
18
19
|
import { codedError } from '../../core/base/errorHints.js';
|
|
19
20
|
import { Container } from './Container.js';
|
|
20
21
|
import { Containers } from './Containers.js';
|
|
21
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
|
|
@@ -185,6 +207,24 @@ const INVENTORY_PARAMS = {
|
|
|
185
207
|
pauseGame: { type: 'bool', optional: true, desc: 'true: gameplay freezes while the window is open (default false)' },
|
|
186
208
|
};
|
|
187
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
|
+
|
|
188
228
|
/**
|
|
189
229
|
* Inventory module. Installs engine.inventory, the 'inventory' UI part and the ops inventory.transfer / use / drop / trade (drop needs pickups()); items
|
|
190
230
|
* on the ground are the pickups() module.
|
|
@@ -197,13 +237,14 @@ export function inventory(opts = {}) {
|
|
|
197
237
|
const o = readParams('inventory', INVENTORY_PARAMS, opts);
|
|
198
238
|
let inv = null;
|
|
199
239
|
return {
|
|
200
|
-
|
|
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',
|
|
201
242
|
install(e, ctx) {
|
|
202
|
-
inv = new Inventory(e, o, ctx
|
|
243
|
+
inv = new Inventory(e, o, ctx); // o: the schema defaults are filled in, the class repeats none
|
|
203
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.
|
|
204
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).
|
|
205
246
|
inv.pauseGame = !!opts.pauseGame; // also settable at runtime: engine.inventory.pauseGame = true
|
|
206
|
-
defineInventoryOps(e, inv);
|
|
247
|
+
defineInventoryOps(e, ctx, inv);
|
|
207
248
|
return inv;
|
|
208
249
|
},
|
|
209
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
|
|
@@ -217,3 +258,5 @@ export function inventory(opts = {}) {
|
|
|
217
258
|
},
|
|
218
259
|
};
|
|
219
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 }];
|