threedog 0.8.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +219 -4
- package/README.md +6 -6
- package/core/assets/Animator.js +2 -0
- package/core/assets/Assets.js +44 -13
- package/core/assets/assetEntry.js +87 -22
- package/core/assets/assetHot.js +2 -1
- package/core/assets/assetReport.js +1 -2
- package/core/audio/Audio.js +24 -5
- package/core/base/I18n.js +6 -3
- package/core/base/Random.js +3 -1
- package/core/base/Vars.js +14 -4
- package/core/base/errorCodes.js +54 -16
- package/core/base/errorHints.js +12 -1
- package/core/base/errors.js +6 -4
- package/core/base/events.generated.js +10 -0
- package/core/base/follows.js +26 -0
- package/core/base/math.js +15 -8
- package/core/base/params.js +2 -2
- package/core/{saves → base}/saveValues.js +24 -6
- package/core/base/sections.js +97 -0
- package/core/base/spelling.js +32 -0
- package/core/base/validate.js +8 -29
- package/core/engine/Engine.js +61 -18
- package/core/engine/Loading.js +30 -3
- package/core/engine/copies.js +1 -1
- package/core/engine/headlessLoad.js +30 -13
- package/core/engine/lifecycle.js +30 -25
- package/core/engine/loop.js +22 -4
- package/core/engine/moduleSlots.js +91 -15
- package/core/engine/moduleTypes.js +13 -0
- package/core/engine/modules.js +248 -62
- package/core/engine/page.js +25 -8
- package/core/engine/plugins.js +15 -3
- package/core/engine/services.js +3 -0
- package/core/engine/startup.js +46 -36
- package/core/input/Input.js +39 -19
- package/core/input/inputKeyboard.js +39 -0
- package/core/input/inputPad.js +23 -2
- package/core/input/inputPointer.js +3 -1
- package/core/input/inputSeat.js +66 -0
- package/core/input/inputTouch.js +23 -6
- package/core/inspect/DebugOverrides.js +13 -2
- package/core/inspect/Describe.js +10 -6
- package/core/inspect/Inspect.js +31 -4
- package/core/inspect/UrlState.js +14 -10
- package/core/inspect/catalog.js +12 -5
- package/core/inspect/describeRender.js +3 -2
- package/core/inspect/describeText.js +6 -2
- package/core/inspect/metadata.generated.js +4140 -0
- package/core/inspect/pictureWriters.js +117 -33
- package/core/inspect/toolDoor.js +21 -0
- package/core/inspect/valueHistory.js +35 -0
- package/core/ops/Ops.js +32 -7
- package/core/ops/control.js +48 -23
- package/core/ops/holds.js +4 -3
- package/core/ops/opsAtomic.js +18 -6
- package/core/ops/opsCheck.js +7 -5
- package/core/ops/opsFail.js +5 -7
- package/core/ops/opsRun.js +2 -2
- package/core/ops/owned.js +20 -3
- package/core/ops/sharedPoint.js +7 -10
- package/core/ops/stacks.js +22 -1
- package/core/saves/SaveStore.js +52 -26
- package/core/saves/Saves.js +122 -27
- package/core/saves/saveApply.js +159 -61
- package/core/saves/saveFiles.js +30 -25
- package/core/saves/saveVersions.js +20 -6
- package/core/saves/session.js +76 -33
- package/core/saves/stateReplace.js +184 -0
- package/core/scene/Rays.js +21 -5
- package/core/scene/Views.js +6 -6
- package/core/scene/adaptive.js +13 -10
- package/core/scene/canvasBox.js +2 -0
- package/core/scene/compositeGround.js +72 -0
- package/core/scene/floor.js +17 -0
- package/core/scene/grid.js +2 -0
- package/core/scene/ground.contract.js +14 -0
- package/core/scene/ground.js +52 -17
- package/core/scene/pixel.js +154 -0
- package/core/scene/pixelRatio.js +167 -0
- package/core/scene/sceneDelta.js +3 -3
- package/core/scene/sceneMethods.js +11 -6
- package/core/scene/stepPoses.js +6 -1
- package/core/scene/thingExplain.js +1 -1
- package/core/scene/thingOps.js +22 -14
- package/core/scene/things.js +1 -1
- package/core/scene/tier.js +10 -0
- package/core/scene/view.js +126 -9
- package/core/stream/Batching.js +0 -1
- package/core/stream/Stream.js +24 -12
- package/core/stream/batchGroups.js +1 -0
- package/core/stream/scatter.js +5 -2
- package/core/stream/streamSources.js +2 -1
- package/core/threads/Commits.js +12 -7
- package/core/threads/Jobs.js +15 -5
- package/core/threads/Threads.js +5 -2
- package/core/time/Clock.js +3 -1
- package/core/time/skip.js +10 -4
- package/core/time/time.js +16 -10
- package/docs/AI.md +89 -72
- package/docs/API.md +18 -14
- package/docs/CODEMAP.md +68 -40
- package/docs/COMMANDS.md +22 -23
- package/docs/CONVENTIONS.md +120 -17
- package/docs/MIGRATING-0.8.md +2 -0
- package/docs/MIGRATING-1.0.md +101 -0
- package/docs/THREE.md +65 -12
- package/docs/api/cameraRig.md +3 -0
- package/docs/api/characters.md +13 -7
- package/docs/api/collider3d.md +9 -0
- package/docs/api/content.md +16 -15
- package/docs/api/dialogue.md +2 -1
- package/docs/api/engine.md +18 -16
- package/docs/api/events.md +14 -4
- package/docs/api/ground.md +2 -2
- package/docs/api/i18n.md +1 -1
- package/docs/api/input.md +2 -1
- package/docs/api/interactions.md +1 -1
- package/docs/api/inventory.md +1 -1
- package/docs/api/level.md +3 -2
- package/docs/api/nav.md +4 -2
- package/docs/api/particles.md +8 -5
- package/docs/api/pickups.md +1 -1
- package/docs/api/post.md +3 -4
- package/docs/api/quests.md +4 -2
- package/docs/api/rays.md +2 -0
- package/docs/api/rigid.md +3 -2
- package/docs/api/saves.md +8 -7
- package/docs/api/stream.md +4 -5
- package/docs/api/terrain.md +3 -4
- package/docs/api/terrainDraw.md +1 -1
- package/docs/api/timeline.md +2 -2
- package/docs/api/tools.md +3 -1
- package/docs/api/triggers.md +2 -0
- package/docs/api/vegetationDraw.md +1 -1
- package/docs/api/water.md +6 -2
- package/docs/api/weather.md +19 -4
- package/docs/api/weatherDraw.md +1 -1
- package/docs/api/world.md +1 -1
- package/docs/recipes/01-new-game.md +3 -3
- package/docs/recipes/02-npc.md +3 -4
- package/docs/recipes/03-items-pickups.md +11 -11
- package/docs/recipes/04-quests.md +2 -0
- package/docs/recipes/05-props-bake.md +9 -9
- package/docs/recipes/06-clock-events.md +6 -6
- package/docs/recipes/07-flow-scenes-pause.md +18 -15
- package/docs/recipes/08-weather-sky.md +5 -5
- package/docs/recipes/09-materials-lights-models.md +3 -3
- package/docs/recipes/10-blender-level.md +16 -4
- package/docs/recipes/11-vehicles.md +18 -6
- package/docs/recipes/12-navmesh.md +52 -8
- package/docs/recipes/13-animation.md +34 -8
- package/docs/recipes/14-custom-module.md +20 -8
- package/docs/recipes/15-perf.md +4 -4
- package/docs/recipes/16-dev-bridge.md +9 -8
- package/docs/recipes/18-world.md +13 -5
- package/docs/recipes/19-shooting-picking.md +3 -2
- package/docs/recipes/20-content-actions-save.md +26 -6
- package/docs/recipes/21-camera.md +17 -23
- package/docs/recipes/22-shop-gold.md +21 -12
- package/docs/recipes/23-ops.md +19 -15
- package/docs/recipes/26-ui-parts.md +3 -2
- package/docs/recipes/27-net.md +3 -3
- package/docs/recipes/28-terrain.md +3 -3
- package/docs/recipes/29-grid.md +1 -1
- package/docs/recipes/30-templates.md +10 -13
- package/docs/recipes/31-audio.md +2 -2
- package/docs/recipes/32-action-game.md +6 -5
- package/docs/recipes/33-stream-sources.md +4 -1
- package/docs/recipes/34-environment-lighting.md +7 -8
- package/docs/recipes/35-picture-from-reference.md +13 -9
- package/docs/recipes/36-ground-plants.md +3 -2
- package/docs/recipes/40-scene.md +11 -10
- package/docs/recipes/43-shader-patches-surfaces.md +7 -7
- package/docs/recipes/44-water-weather-hooks.md +9 -8
- package/docs/recipes/45-cascaded-shadows.md +3 -4
- package/docs/recipes/46-blender-art-route.md +3 -3
- package/docs/recipes/49-game-module-contract.md +2 -1
- package/docs/recipes/50-own-renderer.md +1 -0
- package/docs/recipes/51-capability-catalog.md +14 -8
- package/docs/recipes/52-around-the-picture.md +4 -4
- package/docs/recipes/55-mods-time-wrap.md +5 -4
- package/docs/recipes/56-webgpu-tsl.md +12 -1
- package/docs/recipes/57-control.md +30 -10
- package/docs/recipes/58-input.md +13 -0
- package/docs/recipes/60-judge-the-picture.md +1 -1
- package/docs/recipes/62-picture-code.md +106 -48
- package/docs/recipes/63-third-person-start.md +2 -1
- package/docs/recipes/64-particles.md +53 -4
- package/docs/recipes/65-swarm.md +2 -2
- package/docs/recipes/66-common-tasks.md +313 -0
- package/examples/action/.threedog/content-index.json +1 -1
- package/examples/action/GAMEMAP.md +3 -3
- package/examples/perf-island/.threedog/content-index.json +1 -1
- package/examples/perf-island/GAMEMAP.md +3 -3
- package/examples/perf-island/main.js +2 -2
- package/examples/plain-picture/GAMEMAP.md +3 -1
- package/examples/rc2d/GAMEMAP.md +1 -1
- package/examples/rc2d/rc2d.js +1 -1
- package/examples/styletest/.threedog/content-index.json +1 -1
- package/examples/styletest/GAMEMAP.md +3 -3
- package/examples/webgpu-tsl/GAMEMAP.md +1 -1
- package/examples/world/.threedog/content-index.json +1 -1
- package/examples/world/GAMEMAP.md +5 -4
- package/examples/world/main.js +3 -3
- package/index.d.ts +8 -5
- package/index.js +22 -1
- package/llms.txt +2 -1
- package/modules/ambience/Ambience.js +5 -3
- package/modules/calendar/index.js +7 -5
- package/modules/camera/FirstPersonCamera.js +3 -3
- package/modules/camera/FixedCamera.js +34 -20
- package/modules/camera/FollowCamera.js +20 -11
- package/modules/camera/RtsCamera.js +1 -0
- package/modules/camera/common.js +33 -22
- package/modules/camera/pixelSnap.js +62 -0
- package/modules/characters/Character.js +136 -43
- package/modules/characters/NPC.js +60 -28
- package/modules/characters/assetModel.js +2 -2
- package/modules/characters/astar.js +47 -28
- package/modules/characters/character.contract.js +21 -0
- package/modules/characters/contract.js +17 -3
- package/modules/characters/index.js +94 -34
- package/modules/characters/moveHelpers.js +80 -15
- package/modules/characters/mover.contract.js +14 -0
- package/modules/characters/movers/common.js +6 -4
- package/modules/characters/movers/rapier.js +12 -5
- package/modules/characters/movers/simple.js +25 -12
- package/modules/characters/movers/support.js +18 -7
- package/modules/characters/npcAvoid.js +15 -12
- package/modules/characters/npcSim.js +75 -25
- package/modules/characters/npcView.js +13 -6
- package/modules/characters/pathAsync.js +74 -24
- package/modules/characters/pathJob.js +38 -21
- package/modules/characters/player.js +59 -47
- package/modules/characters/seat.js +56 -0
- package/modules/characters/vehicle.contract.js +8 -5
- package/modules/characters/walkTo.js +31 -18
- package/modules/collision/Collision.js +44 -26
- package/modules/collision/contract.js +2 -2
- package/modules/collision/grid.js +6 -1
- package/modules/content/explain.js +1 -1
- package/modules/content/fields.js +3 -3
- package/modules/content/ids.js +3 -1
- package/modules/content/index.js +83 -27
- package/modules/content/loader.js +110 -130
- package/modules/content/markers.js +1 -1
- package/modules/content/models.js +48 -14
- package/modules/content/packs.js +2 -1
- package/modules/content/places.js +5 -4
- package/modules/content/props.js +8 -6
- package/modules/content/rules.js +29 -47
- package/modules/content/templates.js +66 -35
- package/modules/content/words.js +19 -6
- package/modules/debug/DebugPanel.js +4 -2
- package/modules/flow/contract.js +1 -0
- package/modules/flow/index.js +24 -14
- package/modules/gameplay/Container.js +5 -2
- package/modules/gameplay/Containers.js +9 -1
- package/modules/gameplay/Dialogue.js +82 -25
- package/modules/gameplay/Interactions.js +61 -32
- package/modules/gameplay/Inventory.js +56 -13
- package/modules/gameplay/Quests.js +133 -24
- package/modules/gameplay/boxOps.js +7 -0
- package/modules/gameplay/dialogueBubbles.js +14 -9
- package/modules/gameplay/inventoryOps.js +11 -7
- package/modules/gameplay/pickups.js +43 -16
- package/modules/gameplay/questLog.js +4 -2
- package/modules/gameplay/questSave.js +6 -1
- package/modules/gameplay/quests.contract.js +1 -1
- package/modules/grid/Grid.js +1 -1
- package/modules/grid/Layer.js +8 -4
- package/modules/grid/index.js +21 -15
- package/modules/grid/ops.js +43 -46
- package/modules/grid/tiles.js +1 -1
- package/modules/hlod/index.js +6 -3
- package/modules/hud/index.js +6 -4
- package/modules/hud/parts.js +4 -4
- package/modules/level/contract.js +2 -2
- package/modules/level/heightfield.js +17 -21
- package/modules/level/index.js +83 -26
- package/modules/level/load.js +165 -48
- package/modules/level/nodes.js +34 -16
- package/modules/lights/index.js +6 -3
- package/modules/lights/sources.js +3 -1
- package/modules/music/Music.js +4 -2
- package/modules/nav/contract.js +7 -5
- package/modules/nav/index.js +174 -44
- package/modules/nav/navPath.js +45 -10
- package/modules/net/index.js +1 -1
- package/modules/particles/Particles.js +85 -22
- package/modules/particles/effect.js +80 -28
- package/modules/particles/shaders.js +17 -0
- package/modules/photo/Photo.js +12 -10
- package/modules/rigid/RigidBodies.js +200 -57
- package/modules/rigid/Vehicles.js +15 -5
- package/modules/rigid/collider3d.contract.js +26 -0
- package/modules/rigid/ragdoll.js +55 -44
- package/modules/rigid/ragdollBones.js +83 -33
- package/modules/rigid/refresh.js +10 -0
- package/modules/rigid/sync.js +46 -15
- package/modules/settings/Settings.js +84 -37
- package/modules/settings/apply.js +15 -8
- package/modules/settings/sections.js +7 -4
- package/modules/settings/strings.js +2 -2
- package/modules/sky/skyModule.js +3 -1
- package/modules/swarm/Swarm.js +16 -6
- package/modules/terrain/ChunkManager.js +10 -16
- package/modules/terrain/index.js +17 -11
- package/modules/terrain/terrainEdit.js +13 -2
- package/modules/terrain/terrainGen.js +5 -3
- package/modules/terrain/terrainShape.js +1 -1
- package/modules/timeline/Timeline.js +58 -26
- package/modules/timeline/Tween.js +19 -13
- package/modules/timeline/shots.js +19 -10
- package/modules/triggers/index.js +87 -20
- package/modules/vegetation/Vegetation.js +4 -3
- package/modules/vegetation/draw.js +16 -0
- package/modules/vegetation/groundChunks.js +10 -7
- package/modules/vegetation/index.js +30 -7
- package/modules/water/Water.js +6 -2
- package/modules/weather/Weather.js +16 -15
- package/modules/weather/weatherDraw.js +7 -6
- package/modules/world/World.js +20 -7
- package/modules/world/explain.js +1 -1
- package/modules/world/index.js +13 -6
- package/modules/world/persist.js +23 -8
- package/modules/world/pos.js +4 -4
- package/modules/world/records.js +13 -7
- package/modules/world/sim.js +74 -23
- package/modules/world/simFar.js +2 -2
- package/modules/world/state.js +31 -6
- package/modules/world/thingSource.js +16 -3
- package/modules/world/views.js +19 -8
- package/package.json +7 -1
- package/render/PostFX.js +47 -29
- package/render/backend.js +5 -1
- package/render/fx/particles.tsl.js +8 -6
- package/render/fx/postWebGPU.tsl.js +3 -3
- package/render/layers.js +1 -1
- package/render/lightmap.js +23 -3
- package/render/occlusion.js +43 -12
- package/render/patches.js +2 -2
- package/render/postWebGL.js +4 -3
- package/render/probes.js +25 -0
- package/render/shadows.js +2 -2
- package/types/core.d.ts +142 -55
- package/types/gameplay.d.ts +92 -40
- package/types/generated/core/base/I18n.d.ts +2 -2
- package/types/generated/core/input/Input.d.ts +16 -2
- package/types/generated/core/input/inputSeat.d.ts +26 -0
- package/types/generated/core/inspect/DebugOverrides.d.ts +15 -1
- package/types/generated/core/ops/Ops.d.ts +2 -1
- package/types/generated/core/ops/control.d.ts +12 -2
- package/types/generated/core/saves/Saves.d.ts +26 -6
- package/types/generated/core/saves/session.d.ts +1 -1
- package/types/generated/core/scene/Views.d.ts +1 -1
- package/types/generated/core/stream/Stream.d.ts +6 -4
- package/types/generated/modules/grid/Grid.d.ts +1 -0
- package/types/generated/modules/particles/Particles.d.ts +4 -3
- package/types/generated/modules/timeline/Timeline.d.ts +5 -4
- package/types/generated/modules/weather/Weather.d.ts +1 -7
- package/types/generated/modules/world/World.d.ts +6 -4
- package/types/generated/render/PostFX.d.ts +6 -14
- package/types/nav.d.ts +36 -4
- package/types/physics.d.ts +55 -7
- package/types/pixel.d.ts +75 -0
- package/types/world.d.ts +14 -8
- package/ui/Parts.js +9 -2
- package/ui/theme.js +2 -2
- package/core/scene/engineCamera.js +0 -32
- package/modules/camera/projection.js +0 -21
package/core/engine/modules.js
CHANGED
|
@@ -6,27 +6,39 @@
|
|
|
6
6
|
// Stages (first to last): control timeline, camera -> ground terrain, level -> environment weather, sky, water
|
|
7
7
|
// -> gameplay interactions, dialogue, trigger zones -> effects particles, settings, objective markers
|
|
8
8
|
// -> late (the default) characters, physics, navigation... -> audio music
|
|
9
|
-
// before / after: lists of module names (not-installed names are ignored
|
|
10
|
-
// One that contradicts the stage order (a 'control' module with after: ['sky']) makes use() throw naming both modules and stages;
|
|
11
|
-
// a cycle makes use() throw on the spot, naming the modules on it.
|
|
12
|
-
//
|
|
13
|
-
// before anything
|
|
14
|
-
// (engine.name, module table, hooks; their dispose() runs) and the error is rethrown.
|
|
15
|
-
// Module state (engine.
|
|
9
|
+
// before / after: lists of module or capability names (not-installed names are ignored; a capability means whichever module provides it now, so the order follows a replaces);
|
|
10
|
+
// they order modules only inside one stage. One that contradicts the stage order (a 'control' module with after: ['sky']) makes use() throw naming both modules and stages;
|
|
11
|
+
// a cycle makes use() throw on the spot, naming the modules on it. A contradiction reached through provides throws the same way: an order must not turn into a hint after a replaces.
|
|
12
|
+
// One change plan: use, unuse, replaces and plugin on / off all go through _planChange (moduleSlots.js), which works out the module graph after the change and checks every
|
|
13
|
+
// consumer, new or kept, before anything is touched. Then install is all-or-nothing per engine.use(...) call: if a module's install() throws, the modules this call already
|
|
14
|
+
// installed are removed again (engine.name, module table, hooks; their dispose() runs) and the error is rethrown.
|
|
15
|
+
// Module state (engine.explain({ module })): registered -> initializing -> running | failed; disposed after engine.dispose(). Modules without init() are
|
|
16
16
|
// running at once. fixed / frame / afterRender / skip hooks run only for running modules, so no module gets a hook before its init() finished
|
|
17
17
|
// (during start() or when installed later).
|
|
18
|
-
//
|
|
18
|
+
// requires is a promise that the provider works, not only that it is installed: a module whose required provider is not running (still initializing, failed, or blocked itself)
|
|
19
|
+
// is 'blocked': its init waits, its hooks do not run, and engine.catalog(name).blockedBy says on what. It starts by itself when a provider comes up (a replaces of a failed one).
|
|
20
|
+
// A critical module blocked by a failure stops start(), or is reported when it happens later. Modules that do not depend on the failed one go on.
|
|
21
|
+
// Installed is not usable: engine.has(name) says a module of that name or a provider of that capability is in the module table; engine.usable(name), internal, says it can be called now
|
|
22
|
+
// (running, not blocked, not disabled). A game waits with loading.settled and asks engine.explain({ module }).
|
|
23
|
+
// A capability binds where provides meets requires: dev checks the provider's API against the capability's contract then, on a module change and never per frame (moduleSlots.js).
|
|
24
|
+
// Ownership: install(e, ctx) and init(e, ctx) get ctx = { name, track(handle), mod(point, o), borrow(obj, values), control.take(character, o) }. A handle passed to ctx.track (events.on, onFixed, onFrame,
|
|
19
25
|
// clock timers, audio.measure... anything with remove()) belongs to the module and is removed with it: when the use() batch rolls back,
|
|
20
26
|
// when its init fails, and on engine.dispose() (before the module's own dispose). Listeners a module adds go through it, so an install
|
|
21
27
|
// that fails halfway leaves no ghost listener behind (review 0.4 A; the rollback spec checks every built-in module).
|
|
22
28
|
// ctx.mod(point, o) = ctx.track(engine.mod(point, { ...o, owner: ctx.name })): a module's changes to shared values go with it too.
|
|
29
|
+
// ctx.rule(name, default, names?) = a replaceable rule on a plain shared point: .decide(id, facts) gives a built-in name, false for manual, or what the game's function answered.
|
|
23
30
|
// ctx.input.action(name, { context }) / ctx.input.bind(name, keys): the module's input declarations and bindings, gone with it too.
|
|
31
|
+
// ctx.ops.define, ctx.saves.register, ctx.ui.define, ctx.stream.addReadyCheck, ctx.budget.metric, ctx.things.addSource / explainWith, ctx.ground.provide / addColliders:
|
|
32
|
+
// the same registrars, recorded in the one scope with kind, id, owner and instance (engine.catalog(name).resources reads it). Built-in modules register only through
|
|
33
|
+
// these (tools/tests/module-boundaries). A save part leaving keeps its data as unattached data of the save (Saves.register), so a module unloaded for a while loses nothing.
|
|
24
34
|
// Every install is its own instance (engine._modInst: name -> token): a ctx belongs to one install, not to a name. An async init that resumes after
|
|
25
|
-
// its module was unloaded (replaces, a plugin removed) and a same-named one installed must not act on the newcomer:
|
|
26
|
-
//
|
|
35
|
+
// its module was unloaded (replaces, a plugin removed) and a same-named one installed must not act on the newcomer: a stale ctx verb does nothing and gives a spent handle, because
|
|
36
|
+
// the owner name is shared and doing it first would replace the newcomer's entry (dev warning naming the module); what it tracks is removed at once; its completion or failure
|
|
37
|
+
// changes no state and drops no handle of the newcomer.
|
|
27
38
|
// Exclusive slots: provides: ['inventory'] takes each named slot (a kind 'one' shared point, core/ops/sharedPoint.js) for the module before its install;
|
|
28
39
|
// a second provider is shared-taken. requires may name a slot instead of a module. engine.use(mine(), { replaces: 'inventory' }) unloads the
|
|
29
|
-
// holder first (its handles, slot, drawing parts, dispose), and puts it back if the new install fails.
|
|
40
|
+
// holder first (its handles, slot, drawing parts, dispose), and puts it back if the new install fails, with its save data and content sections (_putBack). Either way the holder now is a fresh install that has none of what
|
|
41
|
+
// others put into the old one, so 'module:restored' tells whoever fed it, once its init is done: they feed it again. The word means "this module is back and holds nothing yet", not that its old state came back; its save data did, its definitions did not.
|
|
30
42
|
// critical: true on a module makes a failed init() stop engine.start() with the reason; without it a failed init is reported (picture / ui: disabled;
|
|
31
43
|
// other types: error tiers in errors.js) and start() goes on.
|
|
32
44
|
// Dependencies: requires must be installed first (throws if missing). optional is a soft dependency: an array is only recorded (for GAMEMAP and rule R16);
|
|
@@ -37,7 +49,7 @@ import { codedError, coded } from '../base/errorHints.js';
|
|
|
37
49
|
import { reportError } from '../base/errors.js';
|
|
38
50
|
import { catalog, catalogSnap, catalogClaim } from '../inspect/catalog.js';
|
|
39
51
|
import { readParams } from '../base/params.js';
|
|
40
|
-
import { slotMethods, isUseOpts, checkProvides } from './moduleSlots.js';
|
|
52
|
+
import { slotMethods, isUseOpts, checkProvides, slotTaken, giversOf, CORE_SLOTS } from './moduleSlots.js';
|
|
41
53
|
import { checkType, asModule } from './moduleTypes.js';
|
|
42
54
|
|
|
43
55
|
/** Stage -> sort position */
|
|
@@ -58,25 +70,40 @@ const STRINGS = {
|
|
|
58
70
|
clash: 'module name {name} clashes with an existing engine property; pick another name',
|
|
59
71
|
slotClash: "module {name} provides '{slot}', but engine.{slot} is already an engine property, so dependents could not reach it there. Fix: pick another slot name",
|
|
60
72
|
lateInit: 'init of module {name} (installed after start)',
|
|
61
|
-
|
|
62
|
-
|
|
73
|
+
groundClaim: "module {name} called ctx.ground.provide, but ground is an exclusive capability it did not claim. Fix: add 'ground' to its provides",
|
|
74
|
+
critical: "critical module {name} cannot run: it requires '{dep}', and {by} is {state}. Fix what stopped {by}, or drop critical from {name}",
|
|
75
|
+
conflict: 'module {a} (stage "{sa}") sets {kind}: ["{said}"], but module {b} is in stage "{sb}", which always runs {kind} stage "{sa}" (stage order: {list}); '
|
|
76
|
+
+ 'before / after only order modules inside one stage. Fix: give both modules the same stage, or remove {kind}: ["{said}"] from {a}',
|
|
77
|
+
capStage: 'module {a} (stage "{sa}") sets {kind}: ["{said}"], but the provider of \'{said}\' is module {b} in stage "{sb}", so this order cannot hold. Fix: give {b} stage: \'{sa}\', or drop the order from {a}',
|
|
63
78
|
};
|
|
79
|
+
const LOST = "engine.use(..., { replaces }): this unloads {gone}, and module {name} requires '{dep}', which nothing would provide afterwards. Fix: add provides: ['{dep}'] to the module that takes over, or unload {name} first";
|
|
64
80
|
const CTX_OWNER = "ctx.mod('{point}', { owner }) in module {name}: ctx.mod names the module as the owner itself; drop owner (use engine.mod for another owner name)";
|
|
81
|
+
const BORROW_HELD = "ctx.borrow in module {name}: '{key}' is already borrowed by module {holder}. A borrow is one holder's temporary use: end that one first, or, when several parties want this value, put it on a shared point (engine.mod)";
|
|
82
|
+
const BAD_BORROW = 'ctx.borrow(obj, values) in module {name}: obj is the object to write on and values the properties to write, like ctx.borrow(e.renderer, { toneMapping: THREE.AgXToneMapping }); got {got}';
|
|
65
83
|
const BAD_HANDLE = 'ctx.track(handle) in module {name}: handle must have remove(), like the result of engine.events.on / onFixed / clock.after; got {got}';
|
|
66
|
-
const STALE = 'module {name} registered something after it was unloaded (its async init or a callback resumed after replaces / unload);
|
|
84
|
+
const STALE = 'module {name} registered something after it was unloaded (its async init or a callback resumed after replaces / unload); nothing of it stays. '
|
|
67
85
|
+ 'The module installed under that name now is not affected';
|
|
68
86
|
const STALE_INIT = 'init of module {name}, which was unloaded before it finished';
|
|
69
87
|
const hookCache = new WeakMap(); // module definition -> { fixed, frame, afterRender, skip } hook entries (reused when re-sorting)
|
|
70
88
|
|
|
89
|
+
/** Every before / after declaration as an ordered pair: first runs before then. said is the name as written, by the module that wrote it. Its own capability orders nothing */
|
|
90
|
+
function orderPairs(list) {
|
|
91
|
+
const out = [];
|
|
92
|
+
for (const m of list) for (const kind of ['before', 'after']) for (const said of m[kind] ?? []) for (const o of giversOf(list, said)) {
|
|
93
|
+
if (o !== m || said === m.name) out.push({ m, o, kind, said, first: kind === 'before' ? m : o, then: kind === 'before' ? o : m });
|
|
94
|
+
}
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
97
|
+
const rankOf = m => STAGES[m.stage] ?? STAGES.late;
|
|
98
|
+
|
|
71
99
|
/** Sort modules by stage, before / after and install order (Kahn topological sort; among the ready ones take the earliest stage,
|
|
72
100
|
* then earliest installed); throws on a cycle. */
|
|
73
101
|
function sortModules(list) {
|
|
74
102
|
const idx = new Map(list.map((m, i) => [m.name, i])), byName = new Map(list.map(m => [m.name, m]));
|
|
75
|
-
const rank = m => STAGES[m.stage] ?? STAGES.late;
|
|
76
103
|
const succ = new Map(list.map(m => [m.name, new Set()])), indeg = new Map(list.map(m => [m.name, 0]));
|
|
77
104
|
const edge = (a, b) => { if (!idx.has(a) || !idx.has(b) || succ.get(a).has(b)) return; succ.get(a).add(b); indeg.set(b, indeg.get(b) + 1); };
|
|
78
|
-
for (const
|
|
79
|
-
const cmp = (a, b) =>
|
|
105
|
+
for (const { first, then } of orderPairs(list)) edge(first.name, then.name);
|
|
106
|
+
const cmp = (a, b) => rankOf(a) - rankOf(b) || idx.get(a.name) - idx.get(b.name);
|
|
80
107
|
const ready = list.filter(m => !indeg.get(m.name)), out = [];
|
|
81
108
|
while (ready.length) {
|
|
82
109
|
ready.sort(cmp);
|
|
@@ -94,17 +121,13 @@ function sortModules(list) {
|
|
|
94
121
|
throw codedError('module-cycle', fmt(STRINGS.cycle, { path: [...cyc, cyc[0]].join(' -> ') }));
|
|
95
122
|
}
|
|
96
123
|
|
|
97
|
-
/** before / after across stages must agree with the stage order (the stage always wins), else the declaration would be silently ignored:
|
|
98
|
-
* throw naming both modules */
|
|
124
|
+
/** before / after across stages must agree with the stage order (the stage always wins), else the declaration would be silently ignored: throw naming both modules */
|
|
99
125
|
function checkStages(list) {
|
|
100
|
-
const
|
|
101
|
-
const
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
for (const m of list) {
|
|
106
|
-
for (const n of m.before || []) { const o = byName.get(n); if (o && rank(m) > rank(o)) fail(m, 'before', o); }
|
|
107
|
-
for (const n of m.after || []) { const o = byName.get(n); if (o && rank(o) > rank(m)) fail(m, 'after', o); }
|
|
126
|
+
const stage = m => m.stage ?? 'late', order = Object.keys(STAGES).join(' -> ');
|
|
127
|
+
for (const { m, o, kind, said, first, then } of orderPairs(list)) {
|
|
128
|
+
if (rankOf(first) <= rankOf(then)) continue;
|
|
129
|
+
const v = { a: m.name, sa: stage(m), kind, said, b: o.name, sb: stage(o), list: order };
|
|
130
|
+
throw codedError('module-order', fmt(o.name === said ? STRINGS.conflict : STRINGS.capStage, v));
|
|
108
131
|
}
|
|
109
132
|
}
|
|
110
133
|
|
|
@@ -115,19 +138,31 @@ export const moduleMethods = {
|
|
|
115
138
|
* All-or-nothing: the batch is validated first, and if an install() throws, the modules this call installed are removed again.
|
|
116
139
|
* A module installed after start() has its init(e) run at once (a task in engine.loading; an error goes through the error tiers) and gets no hooks
|
|
117
140
|
* until it succeeded:
|
|
118
|
-
* `await engine.loading.settled()` waits for it; engine.
|
|
141
|
+
* `await engine.loading.settled()` waits for it; engine.explain({ module }) shows where each module is.
|
|
119
142
|
*/
|
|
120
143
|
use(...mods) {
|
|
121
144
|
const opts = isUseOpts(mods.at(-1)) ? mods.pop() : null;
|
|
122
145
|
const list = mods.flat(Infinity), gone = this._replaced(list, opts?.replaces);
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
146
|
+
this._applyChange(this._planChange(list, gone, { code: 'module-replaces', text: LOST }), gone);
|
|
147
|
+
return this;
|
|
148
|
+
},
|
|
149
|
+
/** @internal A change is finished when queries can trust it: everyone feeding a name these modules answer to (ctx.feeds) has fed the newcomer, so the line after use() reads it whole */
|
|
150
|
+
_feed(plan) {
|
|
151
|
+
const names = new Set(plan.flatMap(m => [m.name, ...(m.provides ?? [])]));
|
|
152
|
+
for (const f of [...(this._feeders ?? [])]) if (names.has(f.name)) f.fn();
|
|
153
|
+
},
|
|
154
|
+
/** @internal carry out a change _planChange accepted: the modules in gone leave, then the plan installs (all or nothing) */
|
|
155
|
+
_applyChange(plan, gone, swapping = plan.length > 0) {
|
|
156
|
+
const done = [], order = [...this.modules.keys()], base = this.session._base;
|
|
157
|
+
// replaces: the holder goes first (its tracked handles, its slot, its drawing parts, its dispose), so the newcomer's install sees a free slot. It cannot wait for the
|
|
158
|
+
// newcomer to prove itself: both would claim the slot, the save key, the ops and engine.<name>, so a failure is undone instead (_putBack).
|
|
159
|
+
// Newest first like dispose; removed ends in install order, so each module comes back after what it requires
|
|
160
|
+
const removed = order.filter(n => gone.has(n)).reverse().map(n => this._unuse(n, swapping)).reverse();
|
|
126
161
|
try {
|
|
127
162
|
for (const m of plan) {
|
|
128
163
|
const had = Object.hasOwn(this, m.name), prev = this[m.name], snap = catalogSnap(this);
|
|
129
164
|
done.push({ m, had, prev }); // before install(): what it tracked before throwing is removed too
|
|
130
|
-
this._modInst.set(m.name, {}); // this install's identity: install and init ctx check it, so a stale async init cannot act on a later install
|
|
165
|
+
this._modInst.set(m.name, { ac: new AbortController() }); // this install's identity: install and init ctx check it, so a stale async init cannot act on a later install
|
|
131
166
|
const ctx = this._modCtx(m);
|
|
132
167
|
this._picture?.installing(m);
|
|
133
168
|
for (const slot of m.provides ?? []) ctx.track(this._slot(slot, m.name).take({ owner: m.name })); // shared-taken when another module holds it
|
|
@@ -137,30 +172,57 @@ export const moduleMethods = {
|
|
|
137
172
|
if (m.name) this[m.name] = api;
|
|
138
173
|
// engine.<slot> is the provider's API too, so a module that requires 'inventory' reaches the game's own bag at engine.inventory after
|
|
139
174
|
// a replaces: dependents name the capability, never the module that gives it
|
|
140
|
-
for (const slot of m.provides ?? []) if (slot !== m.name) { this[slot] = api; ctx.track(this._aliasSlot(slot, api)); }
|
|
141
|
-
this._modState.set(m.name, m.init ?
|
|
175
|
+
for (const slot of m.provides ?? []) if (slot !== m.name && !CORE_SLOTS.has(slot)) { this[slot] = api; ctx.track(this._aliasSlot(slot, api)); }
|
|
176
|
+
this._modState.set(m.name, m.init ? 'registered' : 'running');
|
|
142
177
|
}
|
|
178
|
+
this._feed(plan); // inside the try: a provider that cannot take what feeds it fails its install
|
|
143
179
|
} catch (err) {
|
|
144
180
|
for (const { m, had, prev } of done.reverse()) { // undo in reverse install order, like dispose
|
|
145
181
|
const installed = this.modules.get(m.name) === m;
|
|
182
|
+
this._modInst.get(m.name)?.ac.abort(); // before the token goes: ctx.signal of a rolled-back install
|
|
146
183
|
this.modules.delete(m.name); this._modState.delete(m.name); this._modInst.delete(m.name);
|
|
147
184
|
if (had) this[m.name] = prev; else delete this[m.name]; // put back what was there (an undefined slot stays undefined), never blank it
|
|
148
185
|
this._dropTracked(m.name);
|
|
149
186
|
if (installed) try { m.dispose?.(this); } catch { /* the install error below is the one to report */ }
|
|
150
187
|
}
|
|
151
188
|
this._sortHooks();
|
|
152
|
-
|
|
153
|
-
if (removed.length) try { this.use(...removed); } catch (e2) { reportError(this, e2, 'putting back the module a failed replaces removed', { soft: true }); }
|
|
189
|
+
if (removed.length) this._putBack(removed, order, base);
|
|
154
190
|
throw err;
|
|
155
191
|
}
|
|
156
192
|
this._sortHooks();
|
|
157
|
-
if (
|
|
158
|
-
|
|
193
|
+
if (removed.length && plan.length) this._tellRestored(plan);
|
|
194
|
+
},
|
|
195
|
+
/**
|
|
196
|
+
* @internal 'module:restored' for these fresh modules, after their init: what is fed then lands as it does on a running game, where content.load comes after init
|
|
197
|
+
* (a level's own url would otherwise overtake the pack's level). Nothing in flight tells at once. One replaced again meanwhile is not told about
|
|
198
|
+
*/
|
|
199
|
+
_tellRestored(modules) {
|
|
200
|
+
const tell = () => {
|
|
201
|
+
const live = modules.filter(m => this.modules.get(m.name) === m);
|
|
202
|
+
if (live.length && !this.disposed) this.events.emit('module:restored', { modules: live });
|
|
203
|
+
};
|
|
204
|
+
if (this.loading._inits.size) this.loading.settled().then(tell); else tell();
|
|
205
|
+
},
|
|
206
|
+
/**
|
|
207
|
+
* @internal a failed swap leaves the game as it was: the replaced modules install fresh (their old handles already went), their save parts take back their data as a part registered
|
|
208
|
+
* late does (Saves.register), and 'module:restored' tells whoever fed them, because a fresh install has no definitions, as after a swap that worked: content sections load again (modules/content).
|
|
209
|
+
* What game code defined by hand it defines again on that event. Colliders of the level and of props need no event: they check the holder themselves.
|
|
210
|
+
* @param {any[]} removed in install order @param {string[]} order the module names to go back to @param {string | null} base the new-game state to go back to
|
|
211
|
+
*/
|
|
212
|
+
_putBack(removed, order, base) {
|
|
213
|
+
this.session._base = base; // a newcomer's save part may have written over a part of the same key (session._late)
|
|
214
|
+
try { this.use(...removed); } catch (e2) { return reportError(this, e2, 'putting back the module a failed replaces removed', { soft: true }); }
|
|
215
|
+
for (const n of order) { const m = this.modules.get(n); this.modules.delete(n); this.modules.set(n, m); } // hooks of one stage run in install order: same places
|
|
216
|
+
this._sortHooks();
|
|
217
|
+
this._tellRestored(removed);
|
|
159
218
|
},
|
|
160
219
|
/** @internal validate a batch without touching the engine (so a failure leaves nothing half-installed);
|
|
161
220
|
* returns the modules to install */
|
|
162
221
|
_planUse(list, gone = new Set()) {
|
|
163
222
|
const names = new Set([...this.modules.keys()].filter(n => !gone.has(n))), plan = [];
|
|
223
|
+
// who holds each exclusive slot after this change: read from the graph, so a clash is refused here, before a replaced module is disposed
|
|
224
|
+
const holders = new Map();
|
|
225
|
+
for (const n of names) for (const s of this.modules.get(n).provides ?? []) holders.set(s, n);
|
|
164
226
|
// requires names a module or a capability: another module's provides (depend on 'inventory', not on whichever module gives it)
|
|
165
227
|
const caps = new Set(names);
|
|
166
228
|
for (const n of names) for (const s of this.modules.get(n).provides ?? []) caps.add(s);
|
|
@@ -178,8 +240,12 @@ export const moduleMethods = {
|
|
|
178
240
|
throw codedError('module-requires', fmt(STRINGS.needs, { name: m.name, dep, typo: hint ? fmt(STRINGS.typo, { hint, list: [...caps].join(', ') }) : '' }));
|
|
179
241
|
}
|
|
180
242
|
checkProvides(m);
|
|
181
|
-
for (const slot of m.provides ?? [])
|
|
182
|
-
throw
|
|
243
|
+
for (const slot of m.provides ?? []) {
|
|
244
|
+
if (holders.has(slot)) throw slotTaken(slot, holders.get(slot), m.name);
|
|
245
|
+
holders.set(slot, m.name);
|
|
246
|
+
if (slot !== m.name && !gone.has(slot) && !names.has(slot) && !CORE_SLOTS.has(slot) && slot in this && this[slot] !== undefined && !this._slotAlias?.has(slot))
|
|
247
|
+
throw codedError('module-provides', fmt(STRINGS.slotClash, { name: m.name, slot }));
|
|
248
|
+
}
|
|
183
249
|
if (DEV && m.params && m.options) readParams(m.name, m.params, m.options); // a definition built by hand still gets its options checked
|
|
184
250
|
if (!gone.has(m.name) && m.name in this && this[m.name] !== undefined) throw codedError('module-name', fmt(STRINGS.clash, { name: m.name }));
|
|
185
251
|
names.add(m.name); caps.add(m.name); for (const s of m.provides ?? []) caps.add(s);
|
|
@@ -188,16 +254,24 @@ export const moduleMethods = {
|
|
|
188
254
|
if (plan.length) { const all = [...[...this.modules.values()].filter(m => !gone.has(m.name)), ...plan]; checkStages(all); sortModules(all); }
|
|
189
255
|
return plan;
|
|
190
256
|
},
|
|
257
|
+
/** @internal after start(): every module whose init has not run and whose providers are up gets it now, in install order */
|
|
258
|
+
_initWaiting() {
|
|
259
|
+
if (!this._initsDone) return;
|
|
260
|
+
const start = [...this.modules.values()].filter(m => m.init && this._modState.get(m.name) === 'registered' && !this._modBlocked.has(m.name));
|
|
261
|
+
for (const m of start) this._lateInit(m);
|
|
262
|
+
if (start.length) this._refreshBlocks(); // what waits on them now reads 'initializing', not 'registered'
|
|
263
|
+
},
|
|
191
264
|
/** @internal init of a module installed after start(): run now, tracked in engine.loading, errors through the error tiers;
|
|
192
265
|
* its hooks join only after it succeeded */
|
|
193
266
|
_lateInit(m) {
|
|
267
|
+
this._modState.set(m.name, 'initializing');
|
|
194
268
|
const L = this.loading, task = L._begin(m.name, 'module');
|
|
195
269
|
task.phase('build');
|
|
196
270
|
const snap = catalogSnap(this);
|
|
197
271
|
// the instance and its ctx are taken now, not when the microtask runs: by then a same-named module may be installed in its place
|
|
198
272
|
const inst = this._modInst.get(m.name), ctx = this._modCtx(m, inst), live = () => this._isLive(m.name, inst);
|
|
199
273
|
L._track(Promise.resolve().then(() => asModule(this, m, () => m.init(this, ctx))).then(
|
|
200
|
-
() => { L._done(task); if (live()) { catalogClaim(this, m.name, snap); this._setModState(m, 'running'); } },
|
|
274
|
+
() => { L._done(task); if (live()) { catalogClaim(this, m.name, snap); this._setModState(m, 'running'); this.session._lateInit([...(this._modTracked.get(m.name) ?? [])].filter(h => h.kind === 'save').map(h => h.id)); } },
|
|
201
275
|
e => {
|
|
202
276
|
L._fail(task, e);
|
|
203
277
|
// unloaded meanwhile: its handles already went with it, and the state / handles under this name belong to the newcomer now
|
|
@@ -210,28 +284,54 @@ export const moduleMethods = {
|
|
|
210
284
|
/** @internal the ctx install / init receive: track(handle) ties a handle to the module's life (see the top of this file) */
|
|
211
285
|
_modCtx(m, inst = this._modInst.get(m.name)) {
|
|
212
286
|
const name = m.name;
|
|
287
|
+
const stale = () => { if (this._isLive(name, inst)) return false; if (DEV && !this.disposed) warnOnce(coded('module-handle', fmt(STALE, { name }))); return true; };
|
|
288
|
+
const spent = { owner: name, active: false, remove() {}, change: () => false, move: () => false }; // what a verb of a gone install answers: every handle shape, doing nothing
|
|
289
|
+
const ifLive = fn => (...a) => (stale() ? spent : fn(...a));
|
|
213
290
|
const track = h => {
|
|
214
291
|
if (typeof h?.remove !== 'function') throw codedError('module-handle', fmt(BAD_HANDLE, { name, got: String(h) }));
|
|
215
|
-
|
|
216
|
-
// a registration from an install that is gone (replaced / unloaded while its async init awaited): filing it under the name would hand it
|
|
292
|
+
// a registration from an install that is gone (replaced / unloaded while its async init awaited, or a dispose): filing it under the name would hand it
|
|
217
293
|
// to the newcomer, which would then own a listener it never made; remove it now instead
|
|
218
|
-
if (
|
|
294
|
+
if (stale()) { h.remove(); return h; }
|
|
219
295
|
let set = this._modTracked.get(name);
|
|
220
296
|
if (!set) this._modTracked.set(name, set = new Set());
|
|
221
297
|
set.add(h);
|
|
298
|
+
if (h._timer && this._modState.get(name) !== 'running') this.session._keepTimer(h._timer);
|
|
222
299
|
if (this._curModule === m) this._picture?.learn(m); // the module's own code called this: its file is the part's (core/inspect/pictureWriters.js)
|
|
223
300
|
return h;
|
|
224
301
|
};
|
|
225
302
|
// mod: engine.mod with the module as owner, tracked. Why a ctx verb and not "guess the running module": in an async callback the guess is wrong;
|
|
226
303
|
// and a handle that is not tracked is a weather multiplier still on after the module went
|
|
227
|
-
const mod = (point, o) => {
|
|
304
|
+
const mod = ifLive((point, o) => {
|
|
228
305
|
if (o?.owner !== undefined) throw codedError('mod-owner', fmt(CTX_OWNER, { point, name }));
|
|
229
306
|
return track(this.mod(point, { ...o, owner: name }));
|
|
230
|
-
};
|
|
307
|
+
});
|
|
308
|
+
// borrow: write values on an object the module does not own (a renderer setting, scene.fog, the engine dome's visible) and give them back when it goes.
|
|
309
|
+
// Why compare on the way back: a later legal takeover (the game set its own fog meanwhile) must win, so a value goes back only if it is still what this borrow left there.
|
|
310
|
+
// Why read back after writing: a setter may keep something else than it was handed, and that is what "still mine" has to compare with.
|
|
311
|
+
// Why one holder: a borrow is one party's temporary use. Two overlapping ones ended oldest first brought an ended value back, and a value with two parties is what
|
|
312
|
+
// shared points own (engine.mod). A holder whose value the game replaced has lost it, so that property is free again.
|
|
313
|
+
const borrow = ifLive((obj, values) => {
|
|
314
|
+
if (!obj || typeof obj !== 'object' || !values || typeof values !== 'object') throw codedError('module-handle', fmt(BAD_BORROW, { name, got: `${String(obj)}, ${String(values)}` }));
|
|
315
|
+
let lent = this._borrowed.get(obj);
|
|
316
|
+
if (!lent) this._borrowed.set(obj, lent = new Map());
|
|
317
|
+
for (const key of Object.keys(values)) {
|
|
318
|
+
const t = lent.get(key);
|
|
319
|
+
if (t && Object.is(obj[key], t.wrote)) throw codedError('module-handle', fmt(BORROW_HELD, { name, key, holder: t.name }));
|
|
320
|
+
}
|
|
321
|
+
const taken = Object.keys(values).map(key => { const was = obj[key]; obj[key] = values[key]; const t = { key, was, wrote: obj[key], name }; lent.set(key, t); return t; });
|
|
322
|
+
const h = { borrow: true, remove: () => {
|
|
323
|
+
for (const t of taken.splice(0)) {
|
|
324
|
+
if (Object.is(obj[t.key], t.wrote)) obj[t.key] = t.was;
|
|
325
|
+
if (lent.get(t.key) === t) lent.delete(t.key);
|
|
326
|
+
}
|
|
327
|
+
this._modTracked.get(name)?.delete(h); // a module that borrows often (a cutscene a minute) does not pile up dead handles, as with control below
|
|
328
|
+
} };
|
|
329
|
+
return track(h);
|
|
330
|
+
});
|
|
231
331
|
// input: declare actions / bind the keys the game handed the module, owned by the module (removed with it); never a key of its own
|
|
232
332
|
const input = {
|
|
233
|
-
action: (n, o) => track(this.input.action(n, { ...o, owner: name })),
|
|
234
|
-
bind: (n, keys) => track(this.input.bind(n, keys, { owner: name })),
|
|
333
|
+
action: ifLive((n, o) => track(this.input.action(n, { ...o, owner: name }))),
|
|
334
|
+
bind: ifLive((n, keys) => track(this.input.bind(n, keys, { owner: name }))),
|
|
235
335
|
};
|
|
236
336
|
// control: engine.control.take with the module as default owner, tracked, so a module that goes (unload, rollback, replaces) hands back every
|
|
237
337
|
// character it was steering. Unlike mod an owner may be given: one module can hold several characters on its own names (one per cutscene run).
|
|
@@ -239,14 +339,14 @@ export const moduleMethods = {
|
|
|
239
339
|
// Taking the same character again under the same owner replaces the hold, so the stale handle leaves the tracked set as well.
|
|
240
340
|
const held = new Map(); // `${id} ${owner}` -> the live handle
|
|
241
341
|
const control = {
|
|
242
|
-
take: (who, o = {}) => {
|
|
243
|
-
const h = this.control.take(who, { ...o, owner: o.owner ?? name }), end = h.remove, key = `${h.id} ${h.owner}`;
|
|
342
|
+
take: ifLive((who, o = {}) => {
|
|
343
|
+
const h = this.session._untrack(this.control.take(who, { ...o, owner: o.owner ?? name })), end = h.remove, key = `${h.id} ${h.owner}`;
|
|
244
344
|
const old = held.get(key);
|
|
245
345
|
if (old) this._modTracked.get(name)?.delete(old);
|
|
246
346
|
held.set(key, h);
|
|
247
347
|
h.remove = () => { end(); if (held.get(key) === h) held.delete(key); this._modTracked.get(name)?.delete(h); };
|
|
248
348
|
return track(h);
|
|
249
|
-
},
|
|
349
|
+
}),
|
|
250
350
|
has: (who, owner = name) => this.control.has(who, owner),
|
|
251
351
|
};
|
|
252
352
|
// whileCompiling: a one-time warm-up (a WASM library's first call) run while start() waits for the GPU to compile shaders, when the page's
|
|
@@ -258,14 +358,55 @@ export const moduleMethods = {
|
|
|
258
358
|
const run = () => { if (this._isLive(name, inst)) fn(); };
|
|
259
359
|
if (this.ready) run(); else this._whileCompiling.push(run);
|
|
260
360
|
};
|
|
261
|
-
|
|
361
|
+
// one scope for everything a module registers, so unload, rollback and a failed init all clean up through _dropTracked and none of them needs its own list.
|
|
362
|
+
// Why ctx verbs and not "the module installing now": the callback that registers may run long after install; inst says which install it belongs to
|
|
363
|
+
const own = (kind, id, h) => track(Object.assign(h, { kind, id, owner: name, inst }));
|
|
364
|
+
const owned = (kind, add) => ifLive((id, ...rest) => own(kind, id, add(id, ...rest)));
|
|
365
|
+
// a part keeps its data only when the module ran: a rolled-back or failed install has only half-built state to offer (Saves.register)
|
|
366
|
+
const register = ifLive((key, part) => {
|
|
367
|
+
const h = this.saves.register(key, part);
|
|
368
|
+
return own('save', key, { remove: () => h.remove({ keep: this._isLive(name, inst) && this._modState.get(name) === 'running' }) });
|
|
369
|
+
});
|
|
370
|
+
// declared, not just called: _planUse finds a ground conflict from provides before anything installs, which a call inside install() could not give
|
|
371
|
+
const provideGround = ifLive(g => {
|
|
372
|
+
if (!m.provides?.includes('ground')) throw codedError('module-provides', fmt(STRINGS.groundClaim, { name }));
|
|
373
|
+
return own('ground', 'ground', this._provideGround(g));
|
|
374
|
+
});
|
|
375
|
+
// feeds: this module puts data into whoever holds that capability. fn runs when a new holder arrives, before its use() returns, and leaves with this module
|
|
376
|
+
const feeds = (capability, fn) => {
|
|
377
|
+
const f = { name: capability, fn };
|
|
378
|
+
(this._feeders ??= []).push(f);
|
|
379
|
+
return track({ remove: () => this._feeders.splice(this._feeders.indexOf(f), 1) });
|
|
380
|
+
};
|
|
381
|
+
// signal: aborts when this install ends (_dropTracked), the one lifecycle; an async init checks it after each await instead of keeping its own flag
|
|
382
|
+
return { name, signal: inst?.ac.signal, track, mod, borrow, feeds, input, control, whileCompiling,
|
|
383
|
+
// rule: a replaceable rule of this module, set by anyone with engine.mod(name, { owner, id?, set }). Not tracked: the point outlives a module that shares it, its entries go with their owners
|
|
384
|
+
rule: (n, def, names) => this.stacks.rule(n, def, names),
|
|
385
|
+
ops: { define: owned('op', (n, def) => this.ops.define(n, def)) },
|
|
386
|
+
saves: { register },
|
|
387
|
+
ui: { define: owned('ui', (n, factory, def) => this.ui.define(n, factory, def)) },
|
|
388
|
+
stream: { addReadyCheck: owned('ready', (n, fn) => this.stream.addReadyCheck(n, fn)) },
|
|
389
|
+
budget: { metric: owned('metric', (n, read, o) => this.budget.metric(n, read, o)) },
|
|
390
|
+
things: { addSource: ifLive(src => own('source', name, this._things.addSource(src))), explainWith: ifLive(fn => own('explainer', name, this.explainWith(fn))) },
|
|
391
|
+
ground: { provide: provideGround, addColliders: ifLive(fn => own('colliders', name, this.addGroundColliders(fn))) },
|
|
392
|
+
};
|
|
262
393
|
},
|
|
263
|
-
/** @internal remove every handle a module tracked; one that throws is reported and the rest still go */
|
|
394
|
+
/** @internal remove every handle a module tracked, newest first like dispose; one that throws is reported and the rest still go */
|
|
264
395
|
_dropTracked(name) {
|
|
396
|
+
this._modInst.get(name)?.ac.abort(); // ctx.signal: the install is over (unload, rollback, failed init), async work it started stops
|
|
265
397
|
const set = this._modTracked.get(name);
|
|
266
398
|
if (!set) return;
|
|
267
399
|
this._modTracked.delete(name);
|
|
268
|
-
for (const h of set) { try { h.remove(); } catch (err) { reportError(this, err, `remove() of a handle module ${name} tracked`, { soft: true }); } }
|
|
400
|
+
for (const h of [...set].reverse()) { if (h._timer) this.session._dropTimer(h._timer); try { h.remove(); } catch (err) { reportError(this, err, `remove() of a handle module ${name} tracked`, { soft: true }); } }
|
|
401
|
+
},
|
|
402
|
+
/**
|
|
403
|
+
* @internal a module disabled after an error stays installed, so its other handles wait for unload, but what it borrowed goes back now: nothing keeps that value up any more.
|
|
404
|
+
* Newest first, like unload: oldest first would leave a first borrow's value in place of the original.
|
|
405
|
+
*/
|
|
406
|
+
_returnBorrowed(name) {
|
|
407
|
+
for (const h of [...this._modTracked.get(name) ?? []].reverse()) if (h.borrow) {
|
|
408
|
+
try { h.remove(); } catch (err) { reportError(this, err, `remove() of a borrow module ${name} made`, { soft: true }); }
|
|
409
|
+
}
|
|
269
410
|
},
|
|
270
411
|
/** @internal move a module to a new state and refresh the hooks (initializing / failed modules run none) */
|
|
271
412
|
_setModState(m, state) {
|
|
@@ -274,11 +415,15 @@ export const moduleMethods = {
|
|
|
274
415
|
this._sortHooks();
|
|
275
416
|
},
|
|
276
417
|
/**
|
|
277
|
-
* Where each module is: 'registered' (init not started yet), 'initializing', 'running', 'failed' (init threw: no hooks) or
|
|
418
|
+
* Where each module is: 'registered' (init not started yet), 'initializing', 'running', 'failed' (init threw: no hooks), 'disabled' (a picture or ui module that threw while
|
|
419
|
+
* running: switched off, the game goes on), 'blocked' (a provider it requires is not running: no init, no hooks; engine.catalog(name).blockedBy says which) or 'disposed'.
|
|
278
420
|
* @returns {Record<string, string>}
|
|
279
|
-
* @example engine.use(shop()); await engine.loading.settled(); engine.
|
|
421
|
+
* @example engine.use(shop()); await engine.loading.settled(); engine.explain({ module: 'shop' }).ok // true
|
|
280
422
|
*/
|
|
281
|
-
|
|
423
|
+
/** @internal */
|
|
424
|
+
get moduleStates() {
|
|
425
|
+
return Object.fromEntries([...this._modState].map(([n, s]) => [n, s !== 'failed' && s !== 'disposed' && this._modBlocked.has(n) ? 'blocked' : s]));
|
|
426
|
+
},
|
|
282
427
|
/**
|
|
283
428
|
* What this game can do, read from the registrations (see core/inspect/catalog.js): no argument = short list, a module id or op name = that entry expanded.
|
|
284
429
|
* @param {string | { find?: string }} [id]
|
|
@@ -286,8 +431,16 @@ export const moduleMethods = {
|
|
|
286
431
|
* @example engine.catalog(); engine.catalog('sky'); engine.catalog('shop.buy'); engine.catalog({ find: 'buy' })
|
|
287
432
|
*/
|
|
288
433
|
catalog(id) { return catalog(this, id); },
|
|
289
|
-
/**
|
|
290
|
-
|
|
434
|
+
/**
|
|
435
|
+
* Is a module of this name, or a provider of this capability, installed? Installed only: engine.explain({ module: name }) says whether it is running.
|
|
436
|
+
* @param {string} name
|
|
437
|
+
* @example if (!engine.has('inventory')) engine.use(inventory());
|
|
438
|
+
*/
|
|
439
|
+
has(name) { return this.modules.has(name) || this._provided(name); },
|
|
440
|
+
/** @internal Can this module or capability be called now? True once it is running: init finished, nothing it requires is down, not disabled after an error. Game code asks engine.explain({ module }) */
|
|
441
|
+
usable(name) {
|
|
442
|
+
return giversOf([...this.modules.values()], name).some(m => this._modState.get(m.name) === 'running' && !this._modBlocked.has(m.name));
|
|
443
|
+
},
|
|
291
444
|
/** Run order of module hooks (module names, first to last), for debugging "who runs first". */
|
|
292
445
|
get moduleOrder() { return this._moduleOrder ?? []; },
|
|
293
446
|
|
|
@@ -295,14 +448,47 @@ export const moduleMethods = {
|
|
|
295
448
|
_sortHooks() {
|
|
296
449
|
const order = sortModules([...this.modules.values()]);
|
|
297
450
|
this._moduleOrder = order.map(m => m.name);
|
|
451
|
+
this._refreshBlocks();
|
|
298
452
|
for (const k of HOOKS) this._hooks[k] = [];
|
|
299
453
|
for (const m of order) {
|
|
300
454
|
const st = this._modState.get(m.name);
|
|
301
|
-
if (this.
|
|
455
|
+
if (st !== 'running' || this._modBlocked.has(m.name)) continue; // registered (init not run yet), initializing, failed, disabled, blocked: no hooks
|
|
302
456
|
let c = hookCache.get(m);
|
|
303
457
|
if (!c) hookCache.set(m, c = {});
|
|
304
458
|
for (const k of HOOKS) if (m[k]) this._hooks[k].push(c[k] ??= { fn: m[k].bind(m), name: m.name, mod: m });
|
|
305
459
|
}
|
|
460
|
+
this._initWaiting();
|
|
461
|
+
this._warnContractGaps();
|
|
462
|
+
},
|
|
463
|
+
/** @internal who is blocked now: derived from the states on every change, so install, unload, replace and a failed init need no rule of their own */
|
|
464
|
+
_refreshBlocks() {
|
|
465
|
+
const mods = [...this.modules.values()], seen = new Map(), blocks = new Map(), dead = new Set();
|
|
466
|
+
const up = m => {
|
|
467
|
+
if (seen.has(m)) return seen.get(m);
|
|
468
|
+
seen.set(m, true); // a requires cycle does not block itself
|
|
469
|
+
const by = [];
|
|
470
|
+
for (const dep of m.requires ?? []) {
|
|
471
|
+
const givers = giversOf(mods, dep);
|
|
472
|
+
if (givers.some(up)) continue;
|
|
473
|
+
const p = givers[0], state = !p ? 'missing' : blocks.has(p.name) ? 'blocked' : this._modState.get(p.name);
|
|
474
|
+
by.push({ requires: dep, module: p?.name ?? null, state });
|
|
475
|
+
if (state === 'failed' || dead.has(p?.name)) dead.add(m.name); // waiting ends by itself; a failure does not
|
|
476
|
+
}
|
|
477
|
+
if (by.length) blocks.set(m.name, by);
|
|
478
|
+
const ok = !by.length && this._modState.get(m.name) === 'running';
|
|
479
|
+
seen.set(m, ok);
|
|
480
|
+
return ok;
|
|
481
|
+
};
|
|
482
|
+
mods.forEach(up);
|
|
483
|
+
this._modBlocked = blocks;
|
|
484
|
+
for (const name of dead) {
|
|
485
|
+
const m = this.modules.get(name), inst = this._modInst.get(name);
|
|
486
|
+
if (!m.critical || this._modFatal.has(inst)) continue;
|
|
487
|
+
this._modFatal.add(inst);
|
|
488
|
+
const b = blocks.get(name)[0], err = codedError('module-critical', fmt(STRINGS.critical, { name, dep: b.requires, by: b.module, state: b.state }));
|
|
489
|
+
if (this._initsDone) reportError(this, err, fmt(STRINGS.lateInit, { name }), { module: m });
|
|
490
|
+
else this.loading._fail(this.loading._begin(name, 'module', { critical: true }), err); // start() stops on it, like a critical init that threw
|
|
491
|
+
}
|
|
306
492
|
},
|
|
307
493
|
/** Called by start(): warn once in dev when an optional dependency written as { module: 'what is lost' } is not installed. */
|
|
308
494
|
_checkOptional() {
|
|
@@ -310,7 +496,7 @@ export const moduleMethods = {
|
|
|
310
496
|
for (const m of this.modules.values()) {
|
|
311
497
|
const opt = m.optional;
|
|
312
498
|
if (!opt || Array.isArray(opt)) continue;
|
|
313
|
-
for (const [dep, what] of Object.entries(opt)) if (!this.
|
|
499
|
+
for (const [dep, what] of Object.entries(opt)) if (!this.has(dep))
|
|
314
500
|
warnOnce(coded('module-requires', fmt(STRINGS.optional, { name: m.name, dep, what })));
|
|
315
501
|
}
|
|
316
502
|
},
|
package/core/engine/page.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// engine.page.pauseOnBlur = false; // same, at runtime (e.g. a settings toggle)
|
|
5
5
|
// engine.events.on('page:blur', () => engine.flow?.go('paused')); // show the pause menu as well, if the game wants one
|
|
6
6
|
// While the page is away (window lost focus or tab hidden) with pauseOnBlur, gameplay is frozen by owner 'page': an ordinary freeze, so everything that obeys a freeze
|
|
7
|
-
// (fixed steps, timers, cutscenes, engine.frozen, runState, describe) agrees with no code of its own here. It is a full still ({ ambient: true }): limbs walking on
|
|
7
|
+
// (fixed steps, timers, cutscenes, engine.frozen, runState, describe) agrees with no code of its own here, and the sound waits too (Audio._hold). It is a full still ({ ambient: true }): limbs walking on
|
|
8
8
|
// the spot over a stopped world look broken. Rendering and UI go on. Coming back resumes from where it stopped, with no catch-up burst (the loop drops the time spent
|
|
9
9
|
// away). A halted engine (tests, the dev bridge) has no real-time loop to hold, so there is no page freeze, and step() drives a page in a background window.
|
|
10
10
|
// Held keys are released by Input when it hears page:blur.
|
|
@@ -14,7 +14,7 @@ import { coded } from '../base/errorHints.js';
|
|
|
14
14
|
import { toast } from '../../ui/UI.js';
|
|
15
15
|
import { warnOnce } from '../base/validate.js';
|
|
16
16
|
import { notePatch, patchOn } from '../scene/threePatches.js';
|
|
17
|
-
import { isWebGPU } from '../../render/backend.js';
|
|
17
|
+
import { isWebGPU, setShadowUpdate } from '../../render/backend.js';
|
|
18
18
|
|
|
19
19
|
const STRINGS = {
|
|
20
20
|
'zh-CN': { 'page.gpuLost': '图形设备暂时不可用,正在恢复……如果画面一直不恢复,请刷新页面', 'page.gpuBack': '画面已恢复', 'page.gpuGone': '图形设备已丢失,请刷新页面' },
|
|
@@ -26,6 +26,22 @@ const DEV = { lost: '[page] WebGL context lost: gameplay waits until the browser
|
|
|
26
26
|
notePatch('device-lost-hook', "renderer.onDeviceLost of a WebGPURenderer (three's own hook, kept and called first): reports the loss through engine.page (core/engine/page.js)", () => {},
|
|
27
27
|
{ scope: 'engine renderer', lost: 'engines made from now on: after a device loss the picture freezes while the game keeps running, with no message' });
|
|
28
28
|
|
|
29
|
+
// document.exitPointerLock is one property for the page: one wrapper for every live engine, gone with the last. A wrapper per engine could only be taken off all at once
|
|
30
|
+
const lockers = new Set();
|
|
31
|
+
/** @param {Page} page @param {AbortSignal} signal */
|
|
32
|
+
function watchExitLock(page, signal) {
|
|
33
|
+
const exitLock = document.exitPointerLock;
|
|
34
|
+
if (!exitLock) return;
|
|
35
|
+
if (!lockers.size) {
|
|
36
|
+
const own = Object.hasOwn(document, 'exitPointerLock');
|
|
37
|
+
const wrapper = () => { for (const p of lockers) p._releasing = document.pointerLockElement === p.engine.renderer.domElement; return exitLock.call(document); };
|
|
38
|
+
document.exitPointerLock = wrapper;
|
|
39
|
+
lockers.unwrap = () => { if (document.exitPointerLock !== wrapper) return; if (own) document.exitPointerLock = exitLock; else delete document.exitPointerLock; };
|
|
40
|
+
}
|
|
41
|
+
lockers.add(page);
|
|
42
|
+
signal.addEventListener('abort', () => { lockers.delete(page); if (!lockers.size) lockers.unwrap(); });
|
|
43
|
+
}
|
|
44
|
+
|
|
29
45
|
/** engine.page: window focus, tab visibility, mouse lock and WebGL context, all handled here. */
|
|
30
46
|
export class Page {
|
|
31
47
|
/** @internal */
|
|
@@ -50,13 +66,11 @@ export class Page {
|
|
|
50
66
|
addEventListener('focus', () => this._set('focused', true), { signal });
|
|
51
67
|
document.addEventListener('visibilitychange', () => this._set('visible', document.visibilityState !== 'hidden'), { signal });
|
|
52
68
|
// Esc and a script's exitPointerLock() end in the same pointerlockchange, so the call is the one place to tell them apart: a game that calls it is not the player pausing
|
|
53
|
-
|
|
54
|
-
if (exitLock) {
|
|
55
|
-
document.exitPointerLock = () => { this._releasing = !!document.pointerLockElement; return exitLock.call(document); };
|
|
56
|
-
signal.addEventListener('abort', () => { delete document.exitPointerLock; });
|
|
57
|
-
}
|
|
69
|
+
watchExitLock(this, signal);
|
|
58
70
|
document.addEventListener('pointerlockchange', () => {
|
|
59
|
-
|
|
71
|
+
const locked = document.pointerLockElement === canvas;
|
|
72
|
+
if (locked === this.pointerLocked) return; // another engine's canvas on this page: not locking is not "the player pressed Esc"
|
|
73
|
+
this.pointerLocked = locked;
|
|
60
74
|
// the camera locks again on the next click (camera/common.js). byEngine: the engine let go itself; otherwise it was the player's Esc (ui/Focus.js)
|
|
61
75
|
engine.events.emit('page:pointerlock', { locked: this.pointerLocked, byEngine: !this.pointerLocked && this._releasing });
|
|
62
76
|
this._releasing = false;
|
|
@@ -68,6 +82,8 @@ export class Page {
|
|
|
68
82
|
canvas.addEventListener('webglcontextrestored', () => {
|
|
69
83
|
this.contextLost = false; this._resync = true; this._sync();
|
|
70
84
|
toast(engine, engine.t('page.gpuBack'));
|
|
85
|
+
// a restored context has empty shadow maps, and a map kept on purpose (autoUpdate off, a budget) would stay blank until the game next asked for it
|
|
86
|
+
setShadowUpdate(engine.renderer, engine.scene, { now: true });
|
|
71
87
|
engine.events.emit('page:contextrestored');
|
|
72
88
|
}, { signal });
|
|
73
89
|
// WebGPU fires no canvas event, three calls this hook. Its WebGL2 backend calls it too, but there the listeners above report the loss and its return
|
|
@@ -85,6 +101,7 @@ export class Page {
|
|
|
85
101
|
if (want === !!this._hold) return;
|
|
86
102
|
if (want) this._hold = this.engine.freeze('page', { ambient: true });
|
|
87
103
|
else { this._hold.remove(); this._hold = null; }
|
|
104
|
+
this.engine.audio?._hold(want); // a frozen game keeps no loop sounding on its own in a background tab
|
|
88
105
|
}
|
|
89
106
|
|
|
90
107
|
/** @internal the graphics went away: gameplay freezes, the developer and the player are told, page:contextlost goes out. Once per loss */
|