threedog 1.1.0 → 1.3.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 +893 -798
- package/README.md +1 -1
- package/core/assets/Animator.js +41 -3
- package/core/assets/Assets.js +100 -24
- package/core/assets/assetEntry.js +73 -20
- package/core/assets/assetHot.js +68 -16
- package/core/assets/assetLoad.js +6 -6
- package/core/assets/assetLod.js +9 -2
- package/core/assets/assetManifest.js +12 -2
- package/core/assets/assetPart.js +54 -0
- package/core/assets/ik.js +271 -0
- package/core/assets/modelNeeds.js +37 -0
- package/core/assets/namedModel.js +102 -29
- package/core/assets/nodeVisibility.js +15 -0
- package/core/audio/Audio.js +36 -4
- package/core/audio/audioReverb.js +99 -0
- package/core/audio/audioRules.js +1 -1
- package/core/audio/audioVoice.js +1 -1
- package/core/base/Events.js +14 -4
- package/core/base/Random.js +1 -1
- package/core/base/Vars.js +1 -1
- package/core/base/docRef.js +51 -0
- package/core/base/errorCodes.js +187 -126
- package/core/base/errorHints.js +9 -7
- package/core/base/errors.js +25 -10
- package/core/base/events.generated.js +2 -0
- package/core/base/freeParts.js +76 -0
- package/core/base/math.js +28 -0
- package/core/base/sections.js +5 -5
- package/core/base/validate.js +31 -3
- package/core/engine/Engine.js +17 -7
- package/core/engine/Loading.js +5 -3
- package/core/engine/copies.js +1 -1
- package/core/engine/headlessLoad.js +4 -1
- package/core/engine/lifecycle.js +32 -16
- package/core/engine/loop.js +71 -27
- package/core/engine/moduleSlots.js +2 -2
- package/core/engine/moduleTypes.js +3 -3
- package/core/engine/modules.js +65 -39
- package/core/engine/page.js +6 -3
- package/core/engine/services.js +6 -5
- package/core/engine/startup.js +8 -7
- package/core/input/Input.js +28 -14
- package/core/input/inputContext.js +28 -16
- package/core/input/inputKeyboard.js +31 -3
- package/core/input/inputPad.js +4 -0
- package/core/input/inputPointer.js +2 -1
- package/core/input/inputSeat.js +1 -1
- package/core/inspect/Budget.js +109 -19
- package/core/inspect/DebugOverrides.js +28 -4
- package/core/inspect/Describe.js +17 -9
- package/core/inspect/Inspect.js +4 -2
- package/core/inspect/InspectMaterials.js +3 -1
- package/core/inspect/InspectPerf.js +19 -9
- package/core/inspect/InspectScene.js +32 -7
- package/core/inspect/MaterialInfo.js +19 -2
- package/core/inspect/UrlState.js +50 -28
- package/core/inspect/catalog.js +28 -9
- package/core/inspect/debugView.js +2 -1
- package/core/inspect/describeRender.js +25 -13
- package/core/inspect/describeText.js +14 -6
- package/core/inspect/lightWatch.js +1 -1
- package/core/inspect/metadata.generated.js +35 -17
- package/core/inspect/pictureChecks.js +148 -0
- package/core/inspect/pictureMenu.js +84 -0
- package/core/inspect/pictureWriters.js +26 -6
- package/core/inspect/textureBytes.js +12 -2
- package/core/inspect/toolDoor.js +2 -4
- package/core/ops/Ops.js +11 -4
- package/core/ops/holds.js +27 -10
- package/core/ops/opsAtomic.js +15 -7
- package/core/ops/opsGuard.js +2 -2
- package/core/ops/opsRun.js +8 -7
- package/core/ops/sharedPoint.js +72 -21
- package/core/ops/stacks.js +56 -16
- package/core/saves/SaveStore.js +9 -3
- package/core/saves/Saves.js +32 -23
- package/core/saves/saveApply.js +96 -44
- package/core/saves/saveIds.js +1 -1
- package/core/saves/saveVersions.js +7 -5
- package/core/saves/session.js +17 -8
- package/core/saves/stateReplace.js +34 -15
- package/core/scene/Rays.js +52 -10
- package/core/scene/Views.js +36 -15
- package/core/scene/adaptive.js +144 -21
- package/core/scene/drawOnly.js +17 -0
- package/core/scene/gameLights.js +47 -4
- package/core/scene/sceneMethods.js +13 -11
- package/core/scene/stepPoses.js +11 -3
- package/core/scene/targeting.js +5 -3
- package/core/scene/thingOps.js +1 -1
- package/core/scene/tier.js +15 -0
- package/core/stream/Batching.js +30 -7
- package/core/stream/Stream.js +26 -7
- package/core/stream/batchGroups.js +2 -2
- package/core/stream/chunkStream.js +7 -5
- package/core/stream/prepare.js +77 -0
- package/core/time/skip.js +3 -1
- package/core/time/time.js +4 -2
- package/docs/AI.md +82 -83
- package/docs/API.md +16 -16
- package/docs/CODEMAP.md +17 -11
- package/docs/COMMANDS.md +139 -142
- package/docs/CONVENTIONS.md +37 -49
- package/docs/MIGRATING-0.8.md +2 -2
- package/docs/MIGRATING-1.0.md +2 -2
- package/docs/THREE.md +30 -35
- package/docs/api/assets.md +3 -1
- package/docs/api/audio.md +4 -2
- package/docs/api/budget.md +5 -0
- package/docs/api/characters.md +10 -8
- package/docs/api/collision.md +6 -4
- package/docs/api/engine.md +16 -16
- package/docs/api/events.md +3 -2
- package/docs/api/ground.md +6 -5
- package/docs/api/hud.md +4 -2
- package/docs/api/input.md +5 -5
- package/docs/api/particles.md +2 -1
- package/docs/api/photo.md +3 -0
- package/docs/api/post.md +7 -4
- package/docs/api/quests.md +2 -2
- package/docs/api/rays.md +1 -2
- package/docs/api/saves.md +7 -7
- package/docs/api/settings.md +2 -2
- package/docs/api/tools.md +3 -1
- package/docs/api/vars.md +1 -1
- package/docs/api/vegetation.md +4 -2
- package/docs/api/world.md +1 -1
- package/docs/recipes/01-new-game.md +16 -17
- package/docs/recipes/02-npc.md +22 -18
- package/docs/recipes/03-items-pickups.md +37 -35
- package/docs/recipes/04-quests.md +15 -10
- package/docs/recipes/05-props-bake.md +101 -95
- package/docs/recipes/06-clock-events.md +28 -28
- package/docs/recipes/07-flow-scenes-pause.md +29 -26
- package/docs/recipes/08-weather-sky.md +52 -64
- package/docs/recipes/09-materials-lights-models.md +26 -17
- package/docs/recipes/10-blender-level.md +15 -10
- package/docs/recipes/11-vehicles.md +12 -7
- package/docs/recipes/12-navmesh.md +44 -26
- package/docs/recipes/13-animation.md +56 -45
- package/docs/recipes/14-custom-module.md +21 -18
- package/docs/recipes/15-perf.md +61 -55
- package/docs/recipes/16-dev-bridge.md +24 -33
- package/docs/recipes/18-world.md +36 -42
- package/docs/recipes/19-shooting-picking.md +20 -15
- package/docs/recipes/20-content-actions-save.md +48 -56
- package/docs/recipes/21-camera.md +45 -54
- package/docs/recipes/22-shop-gold.md +12 -7
- package/docs/recipes/23-ops.md +25 -23
- package/docs/recipes/26-ui-parts.md +67 -47
- package/docs/recipes/27-net.md +12 -7
- package/docs/recipes/28-terrain.md +24 -21
- package/docs/recipes/29-grid.md +32 -27
- package/docs/recipes/30-templates.md +21 -20
- package/docs/recipes/31-audio.md +39 -22
- package/docs/recipes/32-action-game.md +19 -14
- package/docs/recipes/33-stream-sources.md +15 -11
- package/docs/recipes/34-environment-lighting.md +126 -70
- package/docs/recipes/35-picture-from-reference.md +8 -8
- package/docs/recipes/36-ground-plants.md +27 -21
- package/docs/recipes/40-scene.md +19 -28
- package/docs/recipes/43-shader-patches-surfaces.md +15 -12
- package/docs/recipes/44-water-weather-hooks.md +34 -31
- package/docs/recipes/45-cascaded-shadows.md +35 -26
- package/docs/recipes/46-blender-art-route.md +7 -2
- package/docs/recipes/49-game-module-contract.md +13 -8
- package/docs/recipes/50-own-renderer.md +6 -2
- package/docs/recipes/51-capability-catalog.md +15 -8
- package/docs/recipes/52-around-the-picture.md +34 -32
- package/docs/recipes/53-ground-up-close.md +6 -1
- package/docs/recipes/55-mods-time-wrap.md +27 -19
- package/docs/recipes/56-webgpu-tsl.md +75 -43
- package/docs/recipes/57-control.md +18 -13
- package/docs/recipes/58-input.md +26 -16
- package/docs/recipes/59-depth-post-effects.md +8 -3
- package/docs/recipes/60-judge-the-picture.md +10 -9
- package/docs/recipes/61-deploy.md +5 -0
- package/docs/recipes/62-picture-code.md +72 -79
- package/docs/recipes/63-third-person-start.md +48 -45
- package/docs/recipes/64-particles.md +22 -10
- package/docs/recipes/65-swarm.md +18 -13
- package/docs/recipes/66-common-tasks.md +38 -35
- package/examples/action/.threedog/content-index.json +1 -1
- package/examples/action/GAMEMAP.md +2 -3
- package/examples/action/main.js +3 -3
- package/examples/action/picture/lights.js +3 -1
- package/examples/perf-island/.threedog/content-index.json +1 -1
- package/examples/perf-island/GAMEMAP.md +3 -3
- package/examples/perf-island/picture/lights.js +2 -1
- package/examples/plain-picture/GAMEMAP.md +1 -1
- package/examples/rc2d/GAMEMAP.md +1 -1
- package/examples/styletest/.threedog/content-index.json +1 -1
- package/examples/styletest/GAMEMAP.md +2 -2
- package/examples/styletest/main.js +1 -1
- package/examples/techniques/interior-light/README.md +3 -3
- package/examples/techniques/interior-light/interiorLight.js +2 -4
- package/examples/techniques/interior-light/picture/lights.js +2 -1
- package/examples/techniques/modular-building/picture/lights.js +3 -1
- package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
- package/examples/techniques/procedural-animation/README.md +1 -1
- package/examples/techniques/procedural-animation/main.js +1 -1
- package/examples/webgpu-tsl/GAMEMAP.md +1 -1
- package/examples/world/.threedog/content-index.json +1 -1
- package/examples/world/GAMEMAP.md +2 -3
- package/examples/world/art/humanoid.js +1 -1
- package/examples/world/main.js +6 -3
- package/index.d.ts +2 -2
- package/llms.txt +101 -0
- package/modules/ambience/Ambience.js +21 -5
- package/modules/calendar/index.js +9 -5
- package/modules/calendar/schedule.js +23 -8
- package/modules/camera/FirstPersonCamera.js +3 -1
- package/modules/camera/FollowCamera.js +10 -5
- package/modules/camera/RtsCamera.js +4 -3
- package/modules/camera/common.js +70 -8
- package/modules/camera/contract.js +1 -1
- package/modules/characters/Character.js +16 -10
- package/modules/characters/NPC.js +31 -19
- package/modules/characters/assetModel.js +14 -9
- package/modules/characters/astar.js +6 -1
- package/modules/characters/contract.js +2 -2
- package/modules/characters/index.js +34 -22
- package/modules/characters/movers/manual.js +1 -1
- package/modules/characters/movers/rapier.js +17 -2
- package/modules/characters/movers/simple.js +1 -1
- package/modules/characters/movers/support.js +16 -7
- package/modules/characters/npcAvoid.js +2 -2
- package/modules/characters/npcSim.js +3 -2
- package/modules/characters/pathAsync.js +24 -8
- package/modules/characters/pathJob.js +1 -1
- package/modules/characters/player.js +10 -9
- package/modules/characters/playerStrings.js +5 -5
- package/modules/characters/proceduralRig.js +5 -5
- package/modules/characters/useModel.js +6 -0
- package/modules/characters/walkTo.js +1 -1
- package/modules/collision/Collision.js +29 -18
- package/modules/collision/grid.js +22 -4
- package/modules/content/index.js +3 -1
- package/modules/content/loader.js +1 -1
- package/modules/content/models.js +82 -33
- package/modules/content/props.js +2 -1
- package/modules/content/rules.js +11 -5
- package/modules/content/templates.js +3 -3
- package/modules/content/words.js +2 -2
- package/modules/debug/DebugPanel.js +9 -9
- package/modules/flow/index.js +9 -6
- package/modules/gameplay/Dialogue.js +34 -20
- package/modules/gameplay/Interactions.js +19 -15
- package/modules/gameplay/Inventory.js +9 -4
- package/modules/gameplay/Quests.js +12 -10
- package/modules/gameplay/pickups.js +23 -11
- package/modules/grid/index.js +1 -1
- package/modules/grid/preview.js +2 -2
- package/modules/grid/tiles.js +1 -1
- package/modules/hlod/index.js +4 -1
- package/modules/hud/index.js +47 -10
- package/modules/hud/parts.js +28 -9
- package/modules/level/geometry.js +8 -3
- package/modules/level/index.js +10 -5
- package/modules/level/load.js +4 -2
- package/modules/lights/sources.js +1 -1
- package/modules/music/Music.js +22 -4
- package/modules/nav/index.js +20 -10
- package/modules/particles/Particles.js +31 -14
- package/modules/particles/effect.js +20 -5
- package/modules/particles/lit.js +72 -0
- package/modules/photo/Photo.js +72 -28
- package/modules/photo/pathTrace.js +106 -0
- package/modules/rigid/RigidBodies.js +23 -14
- package/modules/rigid/Vehicles.js +3 -13
- package/modules/rigid/sync.js +2 -1
- package/modules/settings/Settings.js +52 -20
- package/modules/settings/apply.js +23 -9
- package/modules/settings/sections.js +39 -6
- package/modules/settings/strings.js +2 -0
- package/modules/settings/view.js +19 -3
- package/modules/sky/dome.js +15 -3
- package/modules/sky/environment.js +28 -12
- package/modules/sky/fog.js +1 -1
- package/modules/sky/frame.js +6 -1
- package/modules/sky/shader.js +4 -3
- package/modules/sky/skyModule.js +8 -4
- package/modules/swarm/Swarm.js +1 -1
- package/modules/terrain/ChunkManager.js +61 -15
- package/modules/terrain/chunkJob.js +2 -2
- package/modules/terrain/index.js +20 -5
- package/modules/terrain/terrainEdit.js +8 -4
- package/modules/terrain/terrainTexture.js +4 -2
- package/modules/timeline/Timeline.js +4 -3
- package/modules/timeline/Tween.js +3 -0
- package/modules/timeline/letterbox.js +1 -0
- package/modules/triggers/index.js +36 -17
- package/modules/vegetation/Vegetation.js +81 -19
- package/modules/vegetation/densityMap.js +13 -8
- package/modules/vegetation/draw.js +147 -24
- package/modules/vegetation/groundChunks.js +20 -5
- package/modules/vegetation/index.js +3 -3
- package/modules/vegetation/modelGeometry.js +9 -4
- package/modules/water/Water.js +11 -8
- package/modules/weather/Weather.js +7 -2
- package/modules/weather/shaders.js +25 -5
- package/modules/weather/weatherDraw.js +20 -6
- package/modules/world/World.js +2 -1
- package/modules/world/index.js +2 -2
- package/modules/world/persist.js +6 -2
- package/modules/world/views.js +15 -2
- package/package.json +5 -1
- package/presets.js +5 -5
- package/render/PostFX.js +102 -42
- package/render/backend.js +142 -16
- package/render/bindingLimits.js +59 -0
- package/render/cascades.js +3 -1
- package/render/cascades.tsl.js +2 -0
- package/render/daylight.js +7 -1
- package/render/detail.js +7 -4
- package/render/effects.js +27 -8
- package/render/fogLook.js +24 -0
- package/render/fuse.js +5 -2
- package/render/fx/compareLevel.tsl.js +23 -0
- package/render/fx/detail.tsl.js +9 -7
- package/render/fx/index.js +9 -2
- package/render/fx/library.tsl.js +1 -0
- package/render/fx/lightShaft.tsl.js +114 -0
- package/render/fx/noise.tsl.js +25 -8
- package/render/fx/objectOrigin.tsl.js +39 -10
- package/render/fx/particles.tsl.js +23 -6
- package/render/fx/patchNodes.tsl.js +17 -12
- package/render/fx/pcss.tsl.js +51 -0
- package/render/fx/postWebGPU.tsl.js +104 -29
- package/render/fx/sky.tsl.js +3 -9
- package/render/fxNumbers.js +10 -4
- package/render/impostor.tsl.js +107 -0
- package/render/lighting.js +33 -1
- package/render/lightmap.js +42 -28
- package/render/lights.js +19 -3
- package/render/materials.js +6 -4
- package/render/mergeCommon.js +4 -1
- package/render/occlusion.js +14 -4
- package/render/patches.js +79 -41
- package/render/postRuns.js +32 -0
- package/render/postWebGL.js +97 -10
- package/render/probes.js +10 -14
- package/render/shaderErrors.js +44 -7
- package/render/shadowCache.tsl.js +33 -5
- package/render/shadows.js +42 -16
- package/render/slots.js +8 -5
- package/render/vertexInputs.js +52 -0
- package/types/core.d.ts +115 -47
- package/types/gameplay.d.ts +56 -23
- package/types/generated/core/audio/Audio.d.ts +27 -1
- package/types/generated/core/base/Random.d.ts +1 -1
- package/types/generated/core/input/Input.d.ts +6 -8
- package/types/generated/core/input/inputSeat.d.ts +1 -1
- package/types/generated/core/inspect/Budget.d.ts +26 -0
- package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
- package/types/generated/core/saves/Saves.d.ts +10 -7
- package/types/generated/core/saves/session.d.ts +8 -2
- package/types/generated/core/scene/Rays.d.ts +1 -3
- package/types/generated/core/scene/Views.d.ts +17 -3
- package/types/generated/modules/particles/Particles.d.ts +1 -1
- package/types/generated/modules/world/World.d.ts +2 -1
- package/types/generated/render/PostFX.d.ts +35 -9
- package/types/physics.d.ts +796 -764
- package/types/pixel.d.ts +1 -1
- package/types/tsl.d.ts +62 -1
- package/types/world.d.ts +12 -3
- package/ui/Focus.js +7 -5
- package/ui/Parts.js +1 -1
- package/ui/touchPart.js +6 -3
|
@@ -6,6 +6,7 @@ import { neutralMaterial } from '../../render/neutral.js';
|
|
|
6
6
|
import { shadowDefaults } from './assetEntry.js';
|
|
7
7
|
import { paramValues } from './assetManifest.js';
|
|
8
8
|
import { list } from '../base/util.js';
|
|
9
|
+
import { keepPart, partsOf } from '../base/freeParts.js';
|
|
9
10
|
|
|
10
11
|
/**
|
|
11
12
|
* A model name (name or [name, params...]) whose asset entry is a generator (an asset pack's procedural model) goes through assets.cached:
|
|
@@ -38,41 +39,113 @@ export function builderArgs(e, m) {
|
|
|
38
39
|
*/
|
|
39
40
|
export async function vegetationModel(e, m) {
|
|
40
41
|
const r = await (cachedModel(e, m) ?? e.assets.geometry(list(m)[0]));
|
|
41
|
-
|
|
42
|
+
// a fresh copy (assets.cached copies its prototype on every call) handed out like a content prop of the same name, so the game's onModel
|
|
43
|
+
// (its own materials, say) is on the meshes vegetation then copies; a bare geometry has no materials for it to change
|
|
44
|
+
return r?.isObject3D ? { model: e.assets.handOut(r, list(m)[0]) } : { geometry: r };
|
|
42
45
|
}
|
|
43
46
|
|
|
44
47
|
// One prototype per model name: a generator entry -> assets.cached (baked file / dev cache); a file entry -> assets.model. Content names models only (no paths).
|
|
45
48
|
// The only entry for "reuse a code-made model by name": content props / templates / vegetation and ground pickups all take it from here, so cache, bake and shadow rules exist once.
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
49
|
+
// Who owns a prototype (design.md 6.2): engine.assets, one per model key and palette, shared by every consumer. A consumer (content, pickups) is a holder:
|
|
50
|
+
// it asks through protoOf and lets go with holdProtos(e, holder), which it ctx.tracks, so unloading it gives back what it held. A file prototype is a bare
|
|
51
|
+
// copy holding a lease (Assets._copy); the last holder letting go, a palette write and a hot swap all drop it through dropProto, which returns that lease,
|
|
52
|
+
// so assets.release / trim can free the model afterwards. Why not one table per consumer: it would hold two copies of one model and keep an unloaded consumer's table.
|
|
53
|
+
/** engine.assets' prototype table: model key -> { promise, palette, holders } (holders: the consumers that asked for it, any object as the key) */
|
|
54
|
+
const table = e => (e.assets._protos ||= new Map());
|
|
55
|
+
/** Every prototype of this engine as [key, slot]. For core/assets/assetHot.js @internal */
|
|
56
|
+
export const protoSlots = e => [...table(e)];
|
|
57
|
+
/**
|
|
58
|
+
* The prototype leaves the table and gives back its lease once its build settles (a generator's prototype holds none: assets.cached pins it). Returns the
|
|
59
|
+
* slot's holders, so a rebuild (palette, hot swap) keeps them. after: hold the lease until that promise settles (a hot swap pairs old parts with new first) @internal
|
|
60
|
+
*/
|
|
61
|
+
export function dropProto(e, key, after = null) {
|
|
62
|
+
const slot = table(e).get(key);
|
|
63
|
+
if (!slot) return new Set();
|
|
64
|
+
table(e).delete(key);
|
|
65
|
+
slot.promise.then(p => Promise.resolve(after).then(() => retire(e, p)), () => {});
|
|
66
|
+
return slot.holders;
|
|
67
|
+
}
|
|
68
|
+
// What a prototype makes itself (the neutral material around a bare geometry) is the table's from build to free, held with keepPart so engine.remove and the
|
|
69
|
+
// engine.dispose walk leave it; no asset load owns it. A retired one that copies still draw (a palette write leaves placed props as they are) waits here
|
|
70
|
+
// until its last copy leaves: content and pickups report each copy that leaves (copyLeft), which frees the ones nothing draws any more.
|
|
71
|
+
/** Retired prototypes' parts that copies still draw: part -> its hold */
|
|
72
|
+
const deferredOf = e => (e.assets._deferredParts ||= new Map());
|
|
73
|
+
/** A retired prototype gives back its lease, and what it made waits for its last copy (sweep) */
|
|
74
|
+
function retire(e, p) {
|
|
75
|
+
e.assets._giveBack(p.obj);
|
|
76
|
+
for (const h of p.made) deferredOf(e).set(h.part, h);
|
|
77
|
+
sweep(e);
|
|
78
|
+
}
|
|
79
|
+
/** Free each waiting part no scene object draws any more */
|
|
80
|
+
function sweep(e) {
|
|
81
|
+
const d = deferredOf(e);
|
|
82
|
+
if (!d.size) return;
|
|
83
|
+
const drawn = new Set(); e.scene.traverse(o => { for (const x of partsOf(o)) drawn.add(x); });
|
|
84
|
+
for (const [x, h] of [...d]) if (!drawn.has(x)) { d.delete(x); h.remove(); x.dispose(); }
|
|
85
|
+
}
|
|
86
|
+
/** A prototype's copy left the scene (content, pickups call it): once per task, the waiting parts it may have been the last to draw are freed @internal */
|
|
87
|
+
export function copyLeft(e) {
|
|
88
|
+
const a = e.assets;
|
|
89
|
+
if (!deferredOf(e).size || a._sweepQueued) return;
|
|
90
|
+
a._sweepQueued = true;
|
|
91
|
+
queueMicrotask(() => { a._sweepQueued = false; if (!e.disposed) sweep(e); });
|
|
92
|
+
}
|
|
93
|
+
/** engine.dispose (Assets.dispose): what every prototype made goes, live or waiting, each once @internal */
|
|
94
|
+
export function disposeProtos(e) {
|
|
95
|
+
for (const [x, h] of deferredOf(e)) { h.remove(); x.dispose(); }
|
|
96
|
+
deferredOf(e).clear();
|
|
97
|
+
for (const slot of table(e).values()) slot.promise.then(p => { for (const h of p.made) { h.remove(); h.part.dispose(); } }, () => {});
|
|
98
|
+
table(e).clear();
|
|
99
|
+
}
|
|
100
|
+
/** Holders that let go, per engine: a later protoOf from one is refused (its module is gone, and nobody would give back what it took) */
|
|
101
|
+
const closedOf = e => (e.assets._closedHolders ||= new WeakSet());
|
|
102
|
+
/** Never settles: what a refused protoOf answers, as a wait in a disposed engine does (assetEntry.js), so the late caller's code after it never runs */
|
|
103
|
+
const NEVER = new Promise(() => {});
|
|
104
|
+
/**
|
|
105
|
+
* A consumer's hold on the prototypes it asks for, opened here (again, for a module installed anew): remove() closes it, lets go of each prototype, and one
|
|
106
|
+
* that no other consumer holds is dropped (dropProto). ctx.track it @internal
|
|
107
|
+
*/
|
|
108
|
+
export function holdProtos(e, holder) {
|
|
109
|
+
closedOf(e).delete(holder);
|
|
110
|
+
return { remove() {
|
|
111
|
+
closedOf(e).add(holder);
|
|
112
|
+
for (const [key, slot] of [...table(e)]) if (slot.holders.delete(holder) && !slot.holders.size) dropProto(e, key);
|
|
113
|
+
} };
|
|
114
|
+
}
|
|
51
115
|
/**
|
|
52
116
|
* The shared prototype of a model name (or [name, ...params]): { obj, size, center, fromGeometry }. fromGeometry: the generator returned a bare
|
|
53
|
-
* geometry, wrapped here in a mesh of neutral gray; a caller with a material of its own (pickups) swaps that one. @internal
|
|
117
|
+
* geometry, wrapped here in a mesh of neutral gray; a caller with a material of its own (pickups) swaps that one. holder: who asks; it lets go with holdProtos. @internal
|
|
54
118
|
*/
|
|
55
|
-
export function protoOf(e,
|
|
56
|
-
if (
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
// a palette written since this prototype was built: the next placement builds again, the same rule assets.cached has by its key
|
|
60
|
-
|
|
61
|
-
if (!
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
const p = r.isObject3D ? r : new THREE.Mesh(r, neutralMaterial('prop', { vertexColors: !!r.attributes.color }));
|
|
65
|
-
if (!r.isObject3D) p.userData.fromGeometry = true;
|
|
66
|
-
// the generator's own castShadow / receiveShadow are kept (a decal or flat rug that must not cast); the manifest entry can set them;
|
|
67
|
-
// a generator that set none gets cast + receive. Same rule as assets.model (core/assets/assetEntry.js shadowDefaults)
|
|
68
|
-
return shadowDefaults(p, e.assets.entries.get(list(model)[0])?.opts);
|
|
69
|
-
}) : e.assets.model(list(model)[0])).then(obj => {
|
|
70
|
-
const box = new THREE.Box3().setFromObject(obj); // collision and the "build within what distance" check both use the prototype's bounding box, computed once
|
|
71
|
-
obj.userData.modelKey = key; // copies carry it (clone copies userData): a hot swap whose new model has other parts finds them by it
|
|
72
|
-
return { obj, size: box.getSize(new THREE.Vector3()), center: box.getCenter(new THREE.Vector3()), fromGeometry: !!obj.userData.fromGeometry };
|
|
73
|
-
}));
|
|
74
|
-
protoPalette.set(cache.get(key), palette);
|
|
75
|
-
}
|
|
76
|
-
return cache.get(key);
|
|
119
|
+
export function protoOf(e, holder, model) {
|
|
120
|
+
if (closedOf(e).has(holder)) return NEVER; // a build that resumed after its module unloaded: it takes nothing, so nothing is left unreturned
|
|
121
|
+
const key = JSON.stringify(model), palette = e.assets.builder(list(model)[0]) ? e.assets._paletteKey : null;
|
|
122
|
+
let slot = table(e).get(key);
|
|
123
|
+
// a palette written since this prototype was built: the next placement builds again, the same rule assets.cached has by its key; the holders carry over
|
|
124
|
+
const holders = slot && slot.palette !== palette ? dropProto(e, key) : null;
|
|
125
|
+
if (!slot || holders) table(e).set(key, slot = { promise: buildProto(e, model, key), palette, holders: holders ?? new Set() });
|
|
126
|
+
slot.holders.add(holder);
|
|
127
|
+
return slot.promise;
|
|
77
128
|
}
|
|
78
129
|
|
|
130
|
+
/** One build of a prototype: the generator's result (a bare geometry wrapped in a neutral mesh) or a bare copy of the file, measured once */
|
|
131
|
+
function buildProto(e, model, key) {
|
|
132
|
+
const gen = cachedModel(e, model), made = []; // made: holds on what this prototype makes itself (see deferredOf)
|
|
133
|
+
return (gen ? gen.then(r => {
|
|
134
|
+
const p = r.isObject3D ? r : new THREE.Mesh(r, neutralMaterial('prop', { vertexColors: !!r.attributes.color }));
|
|
135
|
+
if (!r.isObject3D) made.push(keepPart(p.material));
|
|
136
|
+
if (!r.isObject3D) p.userData.fromGeometry = true;
|
|
137
|
+
// the generator's own castShadow / receiveShadow are kept (a decal or flat rug that must not cast); the manifest entry can set them;
|
|
138
|
+
// a generator that set none gets cast + receive. Same rule as assets.model (core/assets/assetEntry.js shadowDefaults)
|
|
139
|
+
return shadowDefaults(p, e.assets.entries.get(list(model)[0])?.opts);
|
|
140
|
+
}) : e.assets._bare(list(model)[0], {}, 'prototype')).then(obj => { // bare: the prototype is never shown, each clone of it gets the onModel setup
|
|
141
|
+
const box = new THREE.Box3().setFromObject(obj); // collision and the "build within what distance" check both use the prototype's bounding box, computed once
|
|
142
|
+
obj.userData.modelKey = key; // copies carry it (clone copies userData): a hot swap whose new model has other parts finds them by it
|
|
143
|
+
return { obj, size: box.getSize(new THREE.Vector3()), center: box.getCenter(new THREE.Vector3()), fromGeometry: !!obj.userData.fromGeometry, made, from: e.assets._instances.get(obj) ?? null };
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* A lease for a copy cloned from this prototype, on the load the prototype itself came from, taken in the same step as the clone. Why not assets.lease(name): the name may
|
|
149
|
+
* point at another load by then (a hot swap, a pack registered again), and the copy would hold data it does not draw. Null for a generator's prototype (pinned) @internal
|
|
150
|
+
*/
|
|
151
|
+
export const protoLease = (e, proto, by) => proto.from ? e.assets._lease(proto.from.e, proto.from.e.name, proto.from.load, by) : null;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// KHR_node_visibility: a glTF node authored hidden ({ "extensions": { "KHR_node_visibility": { "visible": false } } }). three's GLTFLoader (0.187)
|
|
2
|
+
// does not read it, so a part hidden in Blender showed in the game. The children of a hidden node are hidden with it, which Object3D.visible already does.
|
|
3
|
+
// Registered on the engine's GLTFLoader (Assets.js): `loader.register(nodeVisibility)`.
|
|
4
|
+
const NAME = 'KHR_node_visibility';
|
|
5
|
+
|
|
6
|
+
/** GLTFLoader plugin: after the file is built, set visible = false on every node that says so */
|
|
7
|
+
export function nodeVisibility(parser) {
|
|
8
|
+
return {
|
|
9
|
+
name: NAME,
|
|
10
|
+
async afterRoot() {
|
|
11
|
+
const nodes = parser.json.nodes ?? [];
|
|
12
|
+
for (let i = 0; i < nodes.length; i++) if (nodes[i].extensions?.[NAME]?.visible === false) (await parser.getDependency('node', i)).visible = false;
|
|
13
|
+
},
|
|
14
|
+
};
|
|
15
|
+
}
|
package/core/audio/Audio.js
CHANGED
|
@@ -11,6 +11,7 @@ import { codedError, coded } from '../base/errorHints.js';
|
|
|
11
11
|
import { missingText, warnOnce } from '../base/validate.js';
|
|
12
12
|
import { readParams } from '../base/params.js';
|
|
13
13
|
import { SoundHandle, playSound, placeListener, synthNoise, synthTone, loadSound, playFile, soundDef } from './audioVoice.js';
|
|
14
|
+
import { Reverb } from './audioReverb.js';
|
|
14
15
|
import { matchesWhen, volumeOf, checkRuleName, packAudio, applyDucks, audioInfo } from './audioRules.js';
|
|
15
16
|
// createEngine({ audio }) schema: unknown keys throw in dev with did-you-mean. Object / array defaults are not kept here: they would be shared by all engines as one object
|
|
16
17
|
const AUDIO_PARAMS = { levels: 'object?', sounds: 'object?', ambience: 'array?', music: 'object?', footsteps: 'object?' };
|
|
@@ -44,7 +45,7 @@ export class Audio {
|
|
|
44
45
|
/** The game's current mode for rule lists, e.g. 'combat' / 'explore' (condition `state` in music and ambience rules) @type {string | null} */
|
|
45
46
|
this.state = null;
|
|
46
47
|
// the mode belongs to the playthrough: a new game opens as the page did, a load in the mode it was saved in
|
|
47
|
-
engine.saves.
|
|
48
|
+
engine.saves.define('audio', { notAtomic: 'sound, which an atomic op leaves alone: side effects go in after', save: () => ({ state: this.state }), load: d => { this.state = d.state ?? null; } });
|
|
48
49
|
/** @internal */ this.conditions = new Map([['state', v => [].concat(v).includes(this.state)]]);
|
|
49
50
|
/** @internal name -> (engine) => number: values rule data compares ({ daylight: { gt: 0.15 } }) and data volumes add up */
|
|
50
51
|
this.measures = new Map();
|
|
@@ -58,6 +59,7 @@ export class Audio {
|
|
|
58
59
|
/** @internal */ this._voices = new Map(); // name -> live voices (voice limit, info)
|
|
59
60
|
/** @internal */ this._last = new Map(); // name -> { at, variant } (cooldown, no-repeat)
|
|
60
61
|
/** @internal */ this._spatial = new Set(); // positional voices: the listener and followed objects update only while any exist
|
|
62
|
+
/** @internal the one reverb send/return (audioReverb.js), made by the first reverb() call */ this._reverb = null;
|
|
61
63
|
/** @internal */ this._readySent = false;
|
|
62
64
|
/** @internal the game is held by the page (core/engine/page.js): the sound waits with it */ this._held = false;
|
|
63
65
|
// Create or resume audio on a click/keypress (a context created earlier is suspended and must be resumed inside a user gesture). Every press, not only the first:
|
|
@@ -80,6 +82,7 @@ export class Audio {
|
|
|
80
82
|
this.master = this.buses.master = ctx.createGain(); this.master.gain.value = this.levels.master; this.master.connect(ctx.destination);
|
|
81
83
|
for (const name of Object.keys(this.levels)) if (name !== 'master') this._makeBus(name);
|
|
82
84
|
this._applyDucks(0);
|
|
85
|
+
this._reverb?.build();
|
|
83
86
|
const len = ctx.sampleRate * 2, buf = ctx.createBuffer(1, len, ctx.sampleRate), d = buf.getChannelData(0);
|
|
84
87
|
for (let i = 0; i < len; i++) d[i] = Math.random() * 2 - 1; // presentation
|
|
85
88
|
/** 2 s of white noise, reused by synthesized sounds @type {any} */
|
|
@@ -92,6 +95,7 @@ export class Audio {
|
|
|
92
95
|
const ctx = this.ctx, g = ctx.createGain(), d = ctx.createGain();
|
|
93
96
|
g.gain.value = this.levels[name]; g.connect(d).connect(this.master);
|
|
94
97
|
this.buses[name] = g; this._duckNodes[name] = d;
|
|
98
|
+
this._reverb?.busMade(name);
|
|
95
99
|
}
|
|
96
100
|
/** Is audio usable (the player has clicked/pressed a key)? @returns {boolean} @experimental */
|
|
97
101
|
get running() { return this.ctx?.state === 'running'; }
|
|
@@ -117,12 +121,18 @@ export class Audio {
|
|
|
117
121
|
const { level, owner } = readParams('audio.addBus()', BUS_PARAMS, opts);
|
|
118
122
|
if (name === 'master' || name in this.levels) throw codedError('engine-misuse', `audio.addBus('${name}'): '${name}' is already a bus (${Object.keys(this.levels).join(', ')}); use it by name, or remove the handle that added it first`);
|
|
119
123
|
this.levels[name] = level; if (this.ctx) this._makeBus(name);
|
|
120
|
-
|
|
121
|
-
|
|
124
|
+
// identity, not name: a stale handle (already removed, the name taken again by a newer bus) must not delete the newer bus
|
|
125
|
+
const handles = this._busHandles ??= new Map();
|
|
126
|
+
const h = { owner, remove: () => {
|
|
127
|
+
if (handles.get(name) !== h) return;
|
|
128
|
+
handles.delete(name);
|
|
122
129
|
delete this.levels[name];
|
|
123
130
|
if (this.ctx) { this.buses[name].disconnect(); this._duckNodes[name].disconnect(); } // sounds still playing on this bus are cut with the node (bus gone, no sound should linger)
|
|
131
|
+
this._reverb?.busGone(name);
|
|
124
132
|
delete this.buses[name]; delete this._duckNodes[name];
|
|
125
133
|
} };
|
|
134
|
+
handles.set(name, h);
|
|
135
|
+
return h;
|
|
126
136
|
}
|
|
127
137
|
/**
|
|
128
138
|
* Set a bus volume 0-1 ('master' for the total)
|
|
@@ -137,6 +147,27 @@ export class Audio {
|
|
|
137
147
|
(bus === 'master' ? this.master : this.buses[bus]).gain.value = v;
|
|
138
148
|
}
|
|
139
149
|
|
|
150
|
+
/**
|
|
151
|
+
* The one reverb: a send/return any bus can feed (a cave, a hall, a bathroom). Off until called: nothing is built or heard before. Each call
|
|
152
|
+
* changes only the keys given (sends merge per bus; 0 stops one); null turns it off. The echo of a bus follows its slider and its ducks, and
|
|
153
|
+
* comes back through master. The impulse is generated (decaying noise, no file): changing size or decay rebuilds it, wet and sends only fade.
|
|
154
|
+
* Called before the first click it waits for audio to unlock. Places: an ambience rule { reverb: 0.6, when: { zone: 'cave' } } sets wet while it holds (recipes/31 §9)
|
|
155
|
+
* @param {{ wet?: number, decay?: number, size?: number, sends?: Record<string, number>, fade?: number } | null} opts wet 0-1 (0.3), decay seconds to -60 dB (2), size 0-1 (0.5), fade seconds
|
|
156
|
+
* @returns {void}
|
|
157
|
+
* @example engine.audio.reverb({ sends: { sfx: 0.5, ambience: 0.8 }, decay: 3, size: 0.8, wet: 0.4 });
|
|
158
|
+
* @experimental
|
|
159
|
+
*/
|
|
160
|
+
reverb(opts) {
|
|
161
|
+
if (opts === null) { this._reverb?.off(); this._reverb = null; return; }
|
|
162
|
+
const first = !this._reverb, r = this._reverb ??= new Reverb(this);
|
|
163
|
+
try { r.configure(opts ?? {}, 'audio.reverb()'); } catch (err) { if (first) this._reverb = null; throw err; }
|
|
164
|
+
if (this.ctx) r.build();
|
|
165
|
+
}
|
|
166
|
+
/** @internal ambience reverb rules: the wet a place asks for, null when none holds */
|
|
167
|
+
reverbPlace(v, fade) { this._reverb?.setPlace(v, fade); }
|
|
168
|
+
/** @internal has the game turned the reverb on (ambience warns when a reverb rule would echo nothing) */
|
|
169
|
+
get reverbOn() { return !!this._reverb; }
|
|
170
|
+
|
|
140
171
|
/**
|
|
141
172
|
* Lower buses until the handle is removed (dialogue, pause menu, a cutscene). Several ducks stack (their levels multiply).
|
|
142
173
|
* @param {Record<string, number>} levels bus -> multiplier 0-1
|
|
@@ -255,7 +286,8 @@ export class Audio {
|
|
|
255
286
|
/**
|
|
256
287
|
* What is playing (describe().audio shows it while something is ducked or playing): bus levels, the duck multiplier per bus, live voices per sound name.
|
|
257
288
|
* ducks is the level the active ducks ask for (1 = not lowered), read at once even while a fade is still ramping or the audio clock does not run (headless page).
|
|
258
|
-
*
|
|
289
|
+
* reverb (only once reverb() was called): its targets, `place` while an ambience rule sets wet, `built` once audio unlocked.
|
|
290
|
+
* @returns {{ running: boolean, state: string | null, levels: Record<string, number>, ducks: Record<string, number>, voices: Record<string, number>, reverb?: { wet: number, decay: number, size: number, sends: Record<string, number>, place?: number, built: boolean } }}
|
|
259
291
|
* @example engine.audio.duck({ music: 0.3 }); engine.audio.info.ducks.music // 0.3
|
|
260
292
|
*/
|
|
261
293
|
get info() { return audioInfo(this); }
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// The one reverb (helper of Audio.js, engine.audio.reverb): a send/return on the bus graph. Each bus that sends taps its own output (after its
|
|
2
|
+
// level and duck, so the settings slider and a duck lower the echo with the dry sound) into one ConvolverNode, whose return goes into master
|
|
3
|
+
// (the master slider covers it). Off until the game calls reverb(); nothing is built before that, and nothing plays through it the game did not send.
|
|
4
|
+
// Why one convolver with a generated impulse: decaying noise is the classic cheap room (Moorer; Tone.js Reverb does the same), the convolution
|
|
5
|
+
// runs on the audio thread at a fixed cost however many sounds send, and no impulse file has to ship. One reverb, not one per zone: a place
|
|
6
|
+
// changes how much comes back (wet), not the room's build, and rebuilding the impulse is the only expensive step (only size / decay do it).
|
|
7
|
+
// Details: docs/plans/research/2026-11-10-reverb-lit-particles.md.
|
|
8
|
+
import { codedError } from '../base/errorHints.js';
|
|
9
|
+
import { readParams } from '../base/params.js';
|
|
10
|
+
|
|
11
|
+
const REVERB_PARAMS = {
|
|
12
|
+
wet: { type: 'number', optional: true, min: 0, max: 1, desc: 'how much of the echo comes back, 0-1' },
|
|
13
|
+
decay: { type: 'number', optional: true, min: 0.1, max: 10, desc: 'seconds the echo takes to fall 60 dB' },
|
|
14
|
+
size: { type: 'number', optional: true, min: 0, max: 1, desc: 'room size 0-1: the gap before the echo (0-80 ms) and how slowly it builds' },
|
|
15
|
+
sends: { type: 'object', optional: true, desc: 'bus -> how much of it goes in, 0-1 (0 stops that send)' },
|
|
16
|
+
fade: { type: 'number', optional: true, min: 0, desc: 'seconds a wet or send change takes' },
|
|
17
|
+
};
|
|
18
|
+
const DEFAULTS = { wet: 0.3, decay: 2, size: 0.5 };
|
|
19
|
+
|
|
20
|
+
/** Stereo decaying noise: silent for the pre-delay, a short build, then exp fall to -60 dB at `decay`, darkening as it goes (a one-pole low-pass closing) */
|
|
21
|
+
function impulse(ctx, size, decay) {
|
|
22
|
+
const sr = ctx.sampleRate, pre = size * 0.08, build = 0.004 + size * 0.03, len = Math.ceil((pre + decay) * sr), buf = ctx.createBuffer(2, len, sr);
|
|
23
|
+
for (let ch = 0; ch < 2; ch++) {
|
|
24
|
+
const d = buf.getChannelData(ch); let y = 0;
|
|
25
|
+
for (let i = Math.floor(pre * sr); i < len; i++) {
|
|
26
|
+
const t = i / sr - pre, env = Math.exp(-6.9 * t / decay) * Math.min(1, t / build), a = 1 - 0.8 * Math.min(1, t / decay);
|
|
27
|
+
y += a * ((Math.random() * 2 - 1) - y); // presentation: the noise of the room
|
|
28
|
+
d[i] = y * env;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return buf;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export class Reverb {
|
|
35
|
+
/** @param {any} audio the engine's Audio */
|
|
36
|
+
constructor(audio) {
|
|
37
|
+
this.audio = audio;
|
|
38
|
+
/** what the game asked for */ this.set = { ...DEFAULTS, sends: {} };
|
|
39
|
+
/** wet a place asks for (ambience reverb rules), over the game's own while it holds; null = none */ this.place = null;
|
|
40
|
+
this.nodes = null;
|
|
41
|
+
}
|
|
42
|
+
get wet() { return this.place ?? this.set.wet; }
|
|
43
|
+
|
|
44
|
+
/** Merge new settings, check sends name buses, and apply them to the live graph (or keep them for when audio unlocks) */
|
|
45
|
+
configure(opts, where) {
|
|
46
|
+
const o = readParams(where, REVERB_PARAMS, opts), s = this.set, rebuild = (o.size != null && o.size !== s.size) || (o.decay != null && o.decay !== s.decay);
|
|
47
|
+
for (const [bus, v] of Object.entries(o.sends || {})) {
|
|
48
|
+
this.audio._bus(bus); // an unknown bus throws with the fix
|
|
49
|
+
if (!(v >= 0 && v <= 1)) throw codedError('engine-misuse', `${where}: sends.${bus} is how much of the bus goes into the reverb, 0-1; got ${JSON.stringify(v)}`);
|
|
50
|
+
}
|
|
51
|
+
for (const k of ['wet', 'decay', 'size']) if (o[k] != null) s[k] = o[k];
|
|
52
|
+
Object.assign(s.sends, o.sends);
|
|
53
|
+
// only what this call names moves: a wet change must not restart a send's fade, nor a send change the wet's
|
|
54
|
+
if (this.nodes) { if (rebuild) this._impulse(); if (o.wet != null) this._wet(o.fade ?? 0); for (const bus of Object.keys(o.sends || {})) this._send(bus, o.fade ?? 0); }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Build the graph on the unlocked context (Audio._init, or configure after unlock) */
|
|
58
|
+
build() {
|
|
59
|
+
const ctx = this.audio.ctx; if (!ctx || this.nodes) return;
|
|
60
|
+
const input = ctx.createGain(), out = ctx.createGain();
|
|
61
|
+
out.gain.value = this.wet; out.connect(this.audio.master);
|
|
62
|
+
this.nodes = { input, out, conv: null, sends: {} };
|
|
63
|
+
this._impulse(); this._wet(0);
|
|
64
|
+
for (const bus of Object.keys(this.set.sends)) this._send(bus, 0);
|
|
65
|
+
}
|
|
66
|
+
/** A new convolver with a new impulse (a ConvolverNode's buffer is set once per node in older browsers): swapped in, the old one let go */
|
|
67
|
+
_impulse() {
|
|
68
|
+
const ctx = this.audio.ctx, n = this.nodes, conv = ctx.createConvolver();
|
|
69
|
+
conv.buffer = impulse(ctx, this.set.size, this.set.decay);
|
|
70
|
+
n.input.disconnect(); n.conv?.disconnect();
|
|
71
|
+
n.input.connect(conv).connect(n.out); n.conv = conv;
|
|
72
|
+
}
|
|
73
|
+
/** @internal a gain toward v: at once, or over about fade seconds */
|
|
74
|
+
_to(p, v, fade) { const t = this.audio.ctx.currentTime; if (fade > 0) p.setTargetAtTime(v, t, fade / 3); else p.setValueAtTime(v, t); }
|
|
75
|
+
/** The return level toward the wet in force (the place's, else the game's) */
|
|
76
|
+
_wet(fade) { this._to(this.nodes.out.gain, this.wet, fade); }
|
|
77
|
+
/** One bus's send toward its amount. The node is made once per bus and kept (with its tap, so off() can cut both ends); a bus with no node
|
|
78
|
+
* yet (added later) is linked when it is made */
|
|
79
|
+
_send(bus, fade) {
|
|
80
|
+
const n = this.nodes, tap = this.audio._duckNodes[bus]; if (!tap) return;
|
|
81
|
+
let s = n.sends[bus];
|
|
82
|
+
if (!s) { const g = this.audio.ctx.createGain(); g.gain.value = 0; tap.connect(g).connect(n.input); s = n.sends[bus] = { g, tap }; }
|
|
83
|
+
this._to(s.g.gain, this.set.sends[bus], fade);
|
|
84
|
+
}
|
|
85
|
+
/** A bus was made (addBus after unlock): link its send if the game named it */
|
|
86
|
+
busMade(name) { if (this.nodes && name in this.set.sends) this._send(name, 0); }
|
|
87
|
+
/** A bus was removed: its send node goes with it (the bus's own disconnect already cut the tap) */
|
|
88
|
+
busGone(name) { const s = this.nodes?.sends[name]; if (!s) return; s.g.disconnect(); delete this.nodes.sends[name]; }
|
|
89
|
+
/** A place's wet (ambience reverb rules) or null to give the game's back: the wet only, sends keep their own fades */
|
|
90
|
+
setPlace(v, fade) { if (v === this.place) return; this.place = v; if (this.nodes) this._wet(fade); }
|
|
91
|
+
/** Off: every node is disconnected at both ends (the bus's tap -> send too, or each off / on would leave one more dead branch on the live bus) and dropped */
|
|
92
|
+
off() {
|
|
93
|
+
const n = this.nodes; if (!n) return;
|
|
94
|
+
for (const { g, tap } of Object.values(n.sends)) { try { tap.disconnect(g); } catch { /* the bus was removed meanwhile */ } g.disconnect(); }
|
|
95
|
+
n.input.disconnect(); n.conv?.disconnect(); n.out.disconnect(); this.nodes = null;
|
|
96
|
+
}
|
|
97
|
+
/** What info shows: the targets asked for (the audio clock may stand still on a headless page) and whether the graph is built */
|
|
98
|
+
get info() { return { wet: this.wet, decay: this.set.decay, size: this.set.size, sends: { ...this.set.sends }, ...(this.place != null ? { place: this.place } : {}), built: !!this.nodes }; }
|
|
99
|
+
}
|
package/core/audio/audioRules.js
CHANGED
|
@@ -122,5 +122,5 @@ export function audioInfo(a) {
|
|
|
122
122
|
// still on a headless page, so the node would read 1 for ever there. The target is what the game asked for, and what the ramp ends at
|
|
123
123
|
for (const b of Object.keys(a._duckNodes)) { let v = 1; for (const d of a._ducks) v *= d.levels[b] ?? 1; ducks[b] = +v.toFixed(3); }
|
|
124
124
|
for (const [name, list] of a._voices) { const n = list.filter(v => v.playing).length; if (n) voices[name] = n; }
|
|
125
|
-
return { running: a.running, state: a.state, levels: { ...a.levels }, ducks, voices };
|
|
125
|
+
return { running: a.running, state: a.state, levels: { ...a.levels }, ducks, voices, ...(a._reverb ? { reverb: a._reverb.info } : {}) };
|
|
126
126
|
}
|
package/core/audio/audioVoice.js
CHANGED
|
@@ -195,7 +195,7 @@ export function synthTone(audio, opts) {
|
|
|
195
195
|
/** audio.load body: a file sound is an engine.assets entry, by name or by path (a path gets an entry of its own, like a model path), so release, trim and dispose reach it */
|
|
196
196
|
export async function loadSound(audio, url) {
|
|
197
197
|
const { assets } = audio.engine, e = assets._resolve(url, 'sound');
|
|
198
|
-
if (e.type !== 'sound') throw codedError('asset-
|
|
198
|
+
if (e.type !== 'sound') throw codedError('asset-misuse', `audio.load('${url}'): ${url} is registered as a ${e.type}, not a sound. Use a sound entry from assets.manifest({ sounds })`);
|
|
199
199
|
if (e.opts.build) throw codedError('audio-synth-gone', `audio.load('${url}'): ${url} is a synth (a function in the asset pack), not a file: play it with audio.sfx('${url}')`);
|
|
200
200
|
audio._init();
|
|
201
201
|
if (!audio.ctx && !e.named) throw codedError('audio-unsupported', 'Audio is not supported by this browser; check typeof AudioContext before calling'); // a named sound falls back to silence
|
package/core/base/Events.js
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
// In dev (npm run dev) event names are checked: a name never seen before that is one or two letters off a known event warns "did you mean xxx".
|
|
11
11
|
/** @import { Handle } from '../../types/common' */
|
|
12
12
|
/** @import { EventName, EventArgs } from '../../types/core' */
|
|
13
|
-
import { checkEventName } from './validate.js';
|
|
13
|
+
import { checkEventName, syncOnly, warnOnce } from './validate.js';
|
|
14
14
|
|
|
15
15
|
// Event names the engine and modules emit (for spelling checks): generated from EventMap in packages/engine/types/core.d.ts, never a hand-written second copy
|
|
16
16
|
import { ENGINE_EVENTS } from './events.generated.js';
|
|
@@ -28,6 +28,7 @@ export class Events {
|
|
|
28
28
|
/** How many history entries to keep, default 200; 0 records nothing */
|
|
29
29
|
this.historySize = 200;
|
|
30
30
|
/** @internal >0 while an atomic rollback reloads state: emit does nothing */ this.muted = 0;
|
|
31
|
+
/** @internal name -> { tick, when, msg }: events their owner marked as already fired this step (_firedNow) */ this._fired = null;
|
|
31
32
|
/** @internal save loads in flight (saveApply.js), each an array of the listener errors it collected; the last one gets a listener error
|
|
32
33
|
* instead of the error report, so the load fails and rolls back (reported on its own, the load would carry on half-applied: a world:load
|
|
33
34
|
* listener that throws mid-load froze the game). A load stays here until it settled, async parts and afterLoad included */ this._scopes = [];
|
|
@@ -100,7 +101,7 @@ export class Events {
|
|
|
100
101
|
* @example const h = engine.events.on('item:add', ({ id, count }) => console.log(id, count));
|
|
101
102
|
* h.remove();
|
|
102
103
|
*/
|
|
103
|
-
on(name, fn) { this.seen && this._check(name); if (!this.map.has(name)) this.map.set(name, new Set()); this.map.get(name).add(fn); return { remove: () => this._off(name, fn) }; }
|
|
104
|
+
on(name, fn) { this.seen && this._check(name); this._fired && this._lateOn(name); if (!this.map.has(name)) this.map.set(name, new Set()); this.map.get(name).add(fn); return { remove: () => this._off(name, fn) }; }
|
|
104
105
|
/**
|
|
105
106
|
* Listen once; returns a handle { remove() } (can be removed before it fires)
|
|
106
107
|
* @template {EventName} K
|
|
@@ -108,7 +109,16 @@ export class Events {
|
|
|
108
109
|
* @param {(...args: EventArgs<K & string>) => void} fn
|
|
109
110
|
* @returns {Handle}
|
|
110
111
|
*/
|
|
111
|
-
once(name, fn) { const h = this.on(name, (...a) => { h.remove(); fn(...a); }); return h; }
|
|
112
|
+
once(name, fn) { const h = this.on(name, (...a) => { h.remove(); return fn(...a); }); return h; } // returns fn's result: a once-listener is guarded in a load scope like any other
|
|
113
|
+
/**
|
|
114
|
+
* @internal Owner marks "this already fired this tick": a listener attached later in the same tick (when() true) never hears it, so the owner calls warnOnce(msg).
|
|
115
|
+
* Why detection lives here and the message with the owner: only on() sees a late listener; only the owner (e.g. session) knows whether it will fire again and how to fix it.
|
|
116
|
+
* Event semantics unchanged: no replay, no queue, just a hint; once the tick moves on the mark is void and a later listener is simply waiting for the next one.
|
|
117
|
+
* @param {string} name @param {() => boolean} when @param {string} msg
|
|
118
|
+
*/
|
|
119
|
+
_firedNow(name, when, msg) { (this._fired ??= new Map()).set(name, { tick: this.now(), when, msg }); }
|
|
120
|
+
/** @internal @param {string} name */
|
|
121
|
+
_lateOn(name) { const m = this._fired.get(name); if (!m) return; if (m.tick !== this.now()) this._fired.delete(name); else if (m.when()) warnOnce(m.msg); }
|
|
112
122
|
/** @internal Total listeners (used by engine.counts()) */
|
|
113
123
|
get size() { let n = 0; for (const s of this.map.values()) n += s.size; return n; }
|
|
114
124
|
/** @internal Remove all listeners (engine.dispose calls it) */
|
|
@@ -129,7 +139,7 @@ export class Events {
|
|
|
129
139
|
const s = this.map.get(name); if (!s) { if (this.traceSize > 0) this._note(name); return; }
|
|
130
140
|
const prev = this._cur;
|
|
131
141
|
if (this.traceSize > 0) this._cur = `ev:${this._note(name)}`; // handlers run under this event: what they emit names it as parent
|
|
132
|
-
try { for (const fn of [...s]) { if (!s.has(fn)) continue; /* removed by an earlier listener of this emit */ try { fn(...args); } catch (err) { if (this._scopes.length) this._scopes.at(-1).push({ name, err }); else if (this.onError) this.onError(name, err); else console.error(`[event ${name}]`, err); } } }
|
|
142
|
+
try { for (const fn of [...s]) { if (!s.has(fn)) continue; /* removed by an earlier listener of this emit */ try { const r = fn(...args); if (this._scopes.length) syncOnly(r, `a listener of '${name}' inside a load`, true); } catch (err) { if (this._scopes.length) this._scopes.at(-1).push({ name, err }); else if (this.onError) this.onError(name, err); else console.error(`[event ${name}]`, err); } } }
|
|
133
143
|
finally { this._cur = prev; }
|
|
134
144
|
}
|
|
135
145
|
/** @internal trace entries old -> new */
|
package/core/base/Random.js
CHANGED
|
@@ -27,7 +27,7 @@ export class Random {
|
|
|
27
27
|
next() { const v = mulberry32(this); this.state >>>= 0; return v; } // state kept unsigned (as saved)
|
|
28
28
|
/** A decimal between a and b @param {number} a @param {number} b @returns {number} */
|
|
29
29
|
range(a, b) { return a + this.next() * (b - a); }
|
|
30
|
-
/** An integer between a and b (inclusive) @param {number} a @param {number} b @returns {number} @example const dice = engine.random.int(1, 6);
|
|
30
|
+
/** An integer between a and b (inclusive) @param {number} a @param {number} b @returns {number} @example const dice = engine.random.int(1, 6); */
|
|
31
31
|
int(a, b) { return a + Math.floor(this.next() * (b - a + 1)); }
|
|
32
32
|
/**
|
|
33
33
|
* Pick one element of the array at random (undefined for an empty array).
|
package/core/base/Vars.js
CHANGED
|
@@ -12,7 +12,7 @@ export class Vars {
|
|
|
12
12
|
this.engine = engine;
|
|
13
13
|
this.flags = Object.create(null); // no prototype: a flag or counter named 'constructor' is unset like any other name
|
|
14
14
|
this.counters = Object.create(null);
|
|
15
|
-
engine.saves.
|
|
15
|
+
engine.saves.define('vars', {
|
|
16
16
|
atomic: true,
|
|
17
17
|
save: () => ({ flags: { ...this.flags }, counters: { ...this.counters } }), // copy: save data must not share objects with the live state
|
|
18
18
|
load: d => {
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// A pointer to one section of the docs: one spelling, one formatter, one parser. Why one: error codes, check hints, describe() pointers and threedog how
|
|
2
|
+
// each built their own ("#anchor", "§1b", "\"Post effect chain\""), so an AI saw three shapes and the tools could not read them all back; now all go through
|
|
3
|
+
// here, and `threedog how --read <pointer>` prints the section for any of them.
|
|
4
|
+
// Spelling: `recipes/34-environment-lighting.md §"Light you can see in the air"` (the heading as written, so a text search finds it; a " or \ in it is
|
|
5
|
+
// written \" or \\ and read back as itself), or only the number when the heading starts with one, `recipes/62-picture-code.md §3b` (shorter, and it
|
|
6
|
+
// survives a reworded heading). The file alone means its card (the top of the page).
|
|
7
|
+
// The command that prints a section uses the #anchor form (docReadCommand): an anchor holds only letters, digits, - and _, so it needs no quotes in bash
|
|
8
|
+
// or PowerShell, where a heading with an apostrophe (`NPCs don't clump`) or a quote would break any quoting.
|
|
9
|
+
// Plain data, no imports: the browser (warnings) and the node tools (how, check) both load it.
|
|
10
|
+
|
|
11
|
+
/** GitHub-style heading anchor: "4b. Third-person action" -> "4b-third-person-action" (letters of any script kept) @param {string} h */
|
|
12
|
+
export const docSlug = h => h.trim().toLowerCase().replace(/[`*]/g, '').replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-');
|
|
13
|
+
|
|
14
|
+
/** The pointer to a section; no heading = the whole page (its card). @param {string} file path under docs/, e.g. recipes/34-x.md @param {string} [heading] the heading as written */
|
|
15
|
+
export function docRef(file, heading) {
|
|
16
|
+
if (!heading) return file;
|
|
17
|
+
const num = /^(\d+[a-z]?)\.\s/.exec(heading);
|
|
18
|
+
return `${file} §${num ? num[1] : `"${heading.replace(/[\\"]/g, c => '\\' + c)}"`}`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// the whole input or nothing: a path, then at most one selector that parses completely (§number, §"heading" with \" \\ escapes, #anchor, or the
|
|
22
|
+
// older bare "heading"); `§1.2`, `§不存在` or a stray tail is no pointer, so a typo is reported instead of reading as the whole page
|
|
23
|
+
const REF = /^\s*([^\s#§"]+\.md)\s*(?:§(\d+[a-z]?)|§"((?:\\.|[^"\\])+)"|#([\p{L}\p{N}_-]+)|"((?:\\.|[^"\\])+)")?\s*$/u;
|
|
24
|
+
const unescape = s => s.replace(/\\(.)/g, '$1');
|
|
25
|
+
|
|
26
|
+
/** One pointer read back: { file, sec?: number, title?: start of the heading, anchor?: #anchor }, or null when any part of it does not parse. @param {string} ref */
|
|
27
|
+
export function parseDocRef(ref) {
|
|
28
|
+
const m = REF.exec(String(ref));
|
|
29
|
+
if (!m) return null;
|
|
30
|
+
const title = m[3] ?? m[5];
|
|
31
|
+
return { file: m[1], ...(m[2] ? { sec: m[2] } : {}), ...(title ? { title: unescape(title) } : {}), ...(m[4] ? { anchor: m[4] } : {}) };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The shell command that prints a section in full, safe to paste in bash and PowerShell: the #anchor form, no quotes. A section number becomes `#3b`
|
|
36
|
+
* and a heading its anchor (`#light-you-can-see-in-the-air`); --read takes an anchor that starts the heading's anchor, so a heading start is enough.
|
|
37
|
+
* @param {string} ref any pointer parseDocRef reads; '' when it does not parse
|
|
38
|
+
*/
|
|
39
|
+
export function docReadCommand(ref) {
|
|
40
|
+
const r = parseDocRef(ref);
|
|
41
|
+
if (!r) return '';
|
|
42
|
+
const a = r.sec ?? (r.title ? docSlug(r.title) : r.anchor);
|
|
43
|
+
return `threedog how --read ${r.file}${a ? '#' + a : ''} --full`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Pointers printed as one line, with the command that prints the first one: the AI need not open a whole page to find the section. @param {string[]} refs */
|
|
47
|
+
export function docRefsLine(refs) {
|
|
48
|
+
if (!refs?.length) return '';
|
|
49
|
+
const cmd = docReadCommand(refs[0]);
|
|
50
|
+
return `${refs.join(', ')}${cmd ? ` (${cmd})` : ''}`;
|
|
51
|
+
}
|