threedog 1.0.1 → 1.2.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 +90 -0
- 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 +178 -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 +16 -6
- 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 +5 -5
- 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 +46 -27
- 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 +13 -7
- package/core/scene/adaptive.js +144 -21
- package/core/scene/drawOnly.js +17 -0
- package/core/scene/gameLights.js +44 -3
- 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 +16 -11
- package/docs/COMMANDS.md +31 -33
- 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 +28 -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/cameraRig.md +2 -2
- 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 +23 -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 +6 -1
- 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 +74 -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 +9 -8
- package/docs/recipes/61-deploy.md +5 -0
- package/docs/recipes/62-picture-code.md +70 -79
- package/docs/recipes/63-third-person-start.md +47 -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/GAMEMAP.md +2 -3
- package/examples/action/main.js +3 -3
- package/examples/action/picture/lights.js +3 -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/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/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 +4 -1
- package/presets.js +5 -5
- package/render/PostFX.js +84 -41
- package/render/backend.js +137 -16
- 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/detail.tsl.js +9 -7
- package/render/fx/index.js +7 -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 +89 -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 +2 -1
- 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 +114 -46
- 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/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 +43 -11
- 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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// The life of one engine.assets entry, split from Assets.js (which keeps the public API and the manifest):
|
|
2
2
|
// load: fetchEntry runs the load as a task in engine.loading and, for a registered non-critical file that fails, falls back (gray placeholder / silence / the entry's fallback)
|
|
3
|
-
// free: freeEntry gives the GPU memory back, deferred while model copies are still in the scene;
|
|
3
|
+
// free: freeEntry gives the GPU memory back, deferred while model copies are still in the scene; share marks what a load owns so engine.remove and engine.dispose never dispose it
|
|
4
4
|
// sounds: freeing one needs no count. A playing voice holds its own buffer, so it plays on and the memory goes when it ends; the next play loads the file again
|
|
5
5
|
// Plain functions that take the Assets instance, so they stay out of the class's public surface.
|
|
6
6
|
//
|
|
@@ -32,6 +32,9 @@ import { codedError, coded } from '../base/errorHints.js';
|
|
|
32
32
|
import { loadGltf, loadTexture, loadFont, loadAudio, generated, placeholder } from './assetLoad.js';
|
|
33
33
|
import { failureText } from '../engine/Loading.js';
|
|
34
34
|
import { paramValues } from './assetManifest.js';
|
|
35
|
+
import { loadPart } from './assetPart.js';
|
|
36
|
+
import { needsProblems, needsText } from './modelNeeds.js';
|
|
37
|
+
import { freeParts } from '../base/freeParts.js';
|
|
35
38
|
|
|
36
39
|
const STRINGS = {
|
|
37
40
|
failed: 'Asset failed to load: {what}',
|
|
@@ -51,10 +54,17 @@ export const longSound = e => e.type === 'sound' && e.value?.duration >= LONG_SO
|
|
|
51
54
|
/** What a caller holds once the engine is gone: never settles, so nothing runs against a disposed engine (the rule is at the top of this file) */
|
|
52
55
|
const NEVER = new Promise(() => {});
|
|
53
56
|
|
|
54
|
-
/**
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
57
|
+
/**
|
|
58
|
+
* Mark what a load owns as shared: a model template's geometry, materials and their textures (copies share them), or a loaded texture. engine.remove and
|
|
59
|
+
* engine.dispose never dispose a shared part; freeValue frees it, once (design.md 6.2: an asset load owns what it loaded)
|
|
60
|
+
*/
|
|
61
|
+
function share(a, v) {
|
|
62
|
+
if (v?.isTexture) a.shared.add(v);
|
|
63
|
+
else v?.scene?.traverse(o => {
|
|
64
|
+
if (o.geometry) a.shared.add(o.geometry);
|
|
65
|
+
for (const m of [].concat(o.material || [])) { a.shared.add(m); for (const k in m) if (m[k]?.isTexture) a.shared.add(m[k]); }
|
|
66
|
+
});
|
|
67
|
+
return v;
|
|
58
68
|
}
|
|
59
69
|
|
|
60
70
|
/**
|
|
@@ -72,6 +82,14 @@ export function shadowDefaults(root, { castShadow, receiveShadow } = {}) {
|
|
|
72
82
|
return root;
|
|
73
83
|
}
|
|
74
84
|
|
|
85
|
+
/** A model entry's declared nodes and clips (manifest `needs`) against what loaded: one warning naming each missing one. A warning, not a throw, like a missing reference: the model still shows; `threedog assets check` is the gate that fails a build */
|
|
86
|
+
function checkNeeds(name, e, g) {
|
|
87
|
+
const nodes = [];
|
|
88
|
+
g.scene.traverse(o => { if (o !== g.scene && o.name) nodes.push(o.name); });
|
|
89
|
+
const miss = needsProblems(e.opts.needs, { nodes, clips: (g.animations ?? []).map(c => c.name) });
|
|
90
|
+
if (miss.length) warnOnce(coded('asset-needs', needsText(name, e.url, miss)));
|
|
91
|
+
}
|
|
92
|
+
|
|
75
93
|
/** Load an entry as a task in engine.loading; a registered, non-critical file that fails resolves to its fallback */
|
|
76
94
|
export function fetchEntry(a, e) {
|
|
77
95
|
if (a._disposed) return NEVER;
|
|
@@ -80,13 +98,13 @@ export function fetchEntry(a, e) {
|
|
|
80
98
|
e.palette = a._paletteKey;
|
|
81
99
|
const L = a.engine.loading, name = e.variantOf ?? e.name ?? e.url;
|
|
82
100
|
const t = L._begin(name, e.type, { critical: e.opts.critical === true, url: e.opts.build || e.opts.texture ? null : e.url, manifest: e.manifest ?? null });
|
|
83
|
-
const load = e.load = { owner: e, type: e.type, gameOwned: !!e.opts.texture, task: t, stop: new AbortController(), value: null, users: 0, settled: false, pinned: false, waits: 1, left: false, stuck: false, whole: false };
|
|
101
|
+
const load = e.load = { owner: e, of: assetOf(e.name ?? e.url), type: e.type, gameOwned: !!e.opts.texture, task: t, stop: new AbortController(), value: null, users: 0, settled: false, pinned: false, waits: 1, left: false, stuck: false, whole: false };
|
|
84
102
|
t.signal = load.stop.signal; // the loaders read it between phases, and a download passes it to fetch
|
|
85
103
|
let work;
|
|
86
104
|
if (e.type === 'model') {
|
|
87
|
-
const got = e.opts.build ? (t.phase('build'), new Promise(res => res(generated(a, e.url, e.opts.build, e.schema ? paramValues(e) : e.opts.params, t)))) /* a sync throw takes the failure path below */ : loadGltf(a, e.url, t);
|
|
88
|
-
work = got.then(g =>
|
|
89
|
-
} else if (e.type === 'texture') work = loadTexture(a, e, t);
|
|
105
|
+
const got = e.opts.build ? (t.phase('build'), new Promise(res => res(generated(a, e.url, e.opts.build, e.schema ? paramValues(e) : e.opts.params, t)))) /* a sync throw takes the failure path below */ : e.opts.node ? loadPart(a, e, t) : loadGltf(a, e.url, t);
|
|
106
|
+
work = got.then(g => share(a, g));
|
|
107
|
+
} else if (e.type === 'texture') work = loadTexture(a, e, t).then(v => share(a, v));
|
|
90
108
|
else if (e.type === 'font') work = loadFont(a, e, t);
|
|
91
109
|
else if (e.type === 'sound' && e.opts.build) work = Promise.resolve(e.opts.build); // a synth function: nothing to download
|
|
92
110
|
else if (e.type === 'sound') work = loadAudio(a, e, t);
|
|
@@ -97,6 +115,7 @@ export function fetchEntry(a, e) {
|
|
|
97
115
|
L._done(t);
|
|
98
116
|
const what = `${e.type} "${name}" <- ${e.url}`;
|
|
99
117
|
if (t.missing.length) warnOnce(coded('asset-missing-ref', fmt(STRINGS.missingRefs, { what, list: t.missing.join(', ') })));
|
|
118
|
+
if (e.type === 'model' && e.opts.needs) checkNeeds(name, e, v);
|
|
100
119
|
load.settled = true;
|
|
101
120
|
load.value = e.value = v;
|
|
102
121
|
if (e.type === 'sound') capSounds(a, e);
|
|
@@ -175,7 +194,7 @@ function failedEntry(a, e, load, err) {
|
|
|
175
194
|
if (!load.whole) warnOnce(coded('asset-load', msg + fmt(STRINGS.fellBack, { fallback: e.opts.fallback ? `"${fb}"` : fb })));
|
|
176
195
|
if (e.opts.fallback) return (e.promise = borrow(a, e, load, a._resolve(e.opts.fallback, e.type)));
|
|
177
196
|
load.settled = true;
|
|
178
|
-
load.value = e.value =
|
|
197
|
+
load.value = e.value = share(a, placeholder(e.type));
|
|
179
198
|
return (e.promise = Promise.resolve(e.value));
|
|
180
199
|
}
|
|
181
200
|
|
|
@@ -210,13 +229,9 @@ function freeValue(load, v) {
|
|
|
210
229
|
if (!v) return;
|
|
211
230
|
if (load.type === 'texture' && !load.gameOwned) v.dispose(); // a Texture the game registered is the game's: never disposed here
|
|
212
231
|
if (load.type === 'font') document.fonts.delete(v); // a released font stops matching its family
|
|
213
|
-
if (
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
o.geometry.dispose();
|
|
217
|
-
[].concat(o.material).forEach(m => { for (const k in m) if (m[k]?.isTexture) m[k].dispose(); m.dispose(); });
|
|
218
|
-
});
|
|
219
|
-
}
|
|
232
|
+
if (v.fileLease) { v.fileLease.remove(); return; } // one node of a file (assetPart.js): its data is the file's, which goes when nothing holds it
|
|
233
|
+
// always { scene, ... }: generated() wraps a bare geometry too. Everything in it is this load's, each part freed once (two meshes of a file often share a material)
|
|
234
|
+
if (load.type === 'model') freeParts(v.scene, () => true, { textures: true });
|
|
220
235
|
}
|
|
221
236
|
|
|
222
237
|
/** Free an entry's GPU memory; while model copies are still in use it waits (releasePending) and the last engine.remove frees it. A load in flight ends here */
|
|
@@ -246,21 +261,27 @@ export function retireEntry(a, e) {
|
|
|
246
261
|
else if (load.type === 'model') freeValue(load, load.value);
|
|
247
262
|
}
|
|
248
263
|
|
|
264
|
+
/** A retired load that the caller has seen nothing draws any more is freed now instead of waiting for engine.dispose (a hot swap's old generated builds, which stay pinned) */
|
|
265
|
+
export function freeRetired(a, load) { if (a._retired.delete(load)) freeValue(load, load.value); }
|
|
266
|
+
|
|
249
267
|
/**
|
|
250
268
|
* The one count of who holds an entry's data: a model copy holds a lease (Assets._copy, ended by engine.remove), and assets.lease hands one to a module (content models). Why one count and not
|
|
251
269
|
* a lease table beside the copies: release, trim and a retired build would then have two answers to "is anybody using this". The handle is idempotent, so a module may
|
|
252
270
|
* end it itself and still have it tracked.
|
|
271
|
+
* load: the load the holder's data came from (a copy cloned from a prototype holds the prototype's load, not whatever the name reads by the time it asks)
|
|
253
272
|
* @returns {{ name: string, remove(): void }}
|
|
254
273
|
*/
|
|
255
|
-
export function takeLease(a, e, name = e.name) {
|
|
256
|
-
const
|
|
274
|
+
export function takeLease(a, e, name = e.name, load = e.load, by = 'unnamed') {
|
|
275
|
+
const owner = load.owner, who = load.holders ||= new Map();
|
|
276
|
+
who.set(by, (who.get(by) ?? 0) + 1); // by: a label set once here (a module, 'content:<id>', 'model copy'); explain({ asset }) reads it, so "why is this still in memory" needs no stack
|
|
257
277
|
load.users++; e.users = (e.users || 0) + 1;
|
|
258
278
|
if (owner !== e) owner.users = (owner.users || 0) + 1;
|
|
259
279
|
e.releasePending = owner.releasePending = false;
|
|
260
280
|
let held = true;
|
|
261
|
-
return { name, remove() {
|
|
281
|
+
return { name, by, remove() {
|
|
262
282
|
if (!held) return;
|
|
263
283
|
held = false;
|
|
284
|
+
if (who.get(by) > 1) who.set(by, who.get(by) - 1); else who.delete(by);
|
|
264
285
|
load.users--; e.users--;
|
|
265
286
|
if (owner !== e) owner.users--;
|
|
266
287
|
if (load.users <= 0 && !load.pinned && a._retired.delete(load)) freeValue(load, load.value);
|
|
@@ -268,6 +289,38 @@ export function takeLease(a, e, name = e.name) {
|
|
|
268
289
|
} };
|
|
269
290
|
}
|
|
270
291
|
|
|
292
|
+
const HOLDERS_SHOWN = 10;
|
|
293
|
+
/** The asset name behind a table key: a generated build is keyed 'cached:<name>:<params>:...' and its entry goes when the name is rebuilt, but its retired load still belongs to <name> */
|
|
294
|
+
const assetOf = k => typeof k === 'string' && k.startsWith('cached:') ? k.slice(7, k.indexOf(':', 7)) : k;
|
|
295
|
+
const holderText = who => {
|
|
296
|
+
const all = [...(who ?? [])].map(([k, n]) => n > 1 ? `${k} x${n}` : k);
|
|
297
|
+
return all.slice(0, HOLDERS_SHOWN).concat(all.length > HOLDERS_SHOWN ? [`+${all.length - HOLDERS_SHOWN} more (detail.holders)`] : []);
|
|
298
|
+
};
|
|
299
|
+
/**
|
|
300
|
+
* engine.explain({ asset: name }): who holds an entry's data and why it is still in memory. Reads the lease labels (takeLease) of the current build and of
|
|
301
|
+
* retired builds, and says in one line why a pinned or retired build stays. text is short; detail has every label.
|
|
302
|
+
*/
|
|
303
|
+
export function explainAsset(a, name) {
|
|
304
|
+
const e = a.entries.get(name), of = assetOf(name);
|
|
305
|
+
const retired = [...a._retired].filter(l => l.of === of); // by the name it was made for: its entry may be gone (rebuilt generated model)
|
|
306
|
+
if (!e && !retired.length) return { ok: false, text: `asset '${name}': nothing is registered under that name. Names: ${[...a.entries.keys()].slice(0, 8).join(', ') || '(none)'}`, detail: null };
|
|
307
|
+
const cur = e?.load;
|
|
308
|
+
const lines = [];
|
|
309
|
+
const build = (l, head) => {
|
|
310
|
+
lines.push(`${head}: ${l.users} holder${l.users === 1 ? '' : 's'}${l.users ? '' : ', nothing holds it'}`);
|
|
311
|
+
for (const t of holderText(l.holders)) lines.push(` ${t}`);
|
|
312
|
+
if (l.pinned) lines.push(' pinned: generated model prototypes and handed-out geometry stay until engine.dispose (nobody counts who draws them)');
|
|
313
|
+
};
|
|
314
|
+
if (!e) lines.push(`${name}: no entry under this key any more`);
|
|
315
|
+
else if (!cur) lines.push(`${name}: not loaded`);
|
|
316
|
+
else build(cur, `${name} (${cur.settled ? 'loaded' : 'loading'}${cur.owner !== e ? `, data owned by '${cur.owner.name}'` : ''})`);
|
|
317
|
+
for (const l of retired) { build(l, 'retired build'); lines.push(l.pinned ? ' retired: replaced (hot swap, palette write) but pinned: stays until engine.dispose' : ' retired: replaced (hot swap, palette write, release); freed when its last holder lets go'); }
|
|
318
|
+
if (e?.releasePending) lines.push('release() was asked: the data is freed when the last holder lets go');
|
|
319
|
+
else if (cur?.value && !cur.users && !cur.pinned) lines.push('nothing holds it: assets.release(name) or trim() frees it');
|
|
320
|
+
const tell = l => ({ users: l.users, holders: Object.fromEntries(l.holders ?? []), pinned: !!l.pinned });
|
|
321
|
+
return { ok: true, text: lines.join('\n'), detail: { name, current: cur ? tell(cur) : null, retired: retired.map(tell), releasePending: !!e?.releasePending } };
|
|
322
|
+
}
|
|
323
|
+
|
|
271
324
|
/** e just loaded: while long sounds are over the budget, the one asked for longest ago goes (never e itself) */
|
|
272
325
|
function capSounds(a, e) {
|
|
273
326
|
const long = [...a.entries.values()].filter(longSound).sort((x, y) => (x.usedAt ?? 0) - (y.usedAt ?? 0));
|
package/core/assets/assetHot.js
CHANGED
|
@@ -10,12 +10,13 @@
|
|
|
10
10
|
// Limits (said in the report): a copy's collision box keeps the size it was placed with until the next load; an InstancedMesh or a merged batch
|
|
11
11
|
// the game built itself from a geometry is not found (only engine paths are).
|
|
12
12
|
import { registerManifest, paramValues } from './assetManifest.js';
|
|
13
|
-
import {
|
|
14
|
-
import { clone as skeletonClone } from 'three/addons/utils/SkeletonUtils.js';
|
|
13
|
+
import { protoSlots, protoOf, dropProto, cachedModel } from './namedModel.js';
|
|
15
14
|
import { list } from '../base/util.js';
|
|
16
15
|
import { reportError } from '../base/errors.js';
|
|
17
16
|
import { codedError } from '../base/errorHints.js';
|
|
18
|
-
import { note } from '../base/validate.js';
|
|
17
|
+
import { note, warnOnce } from '../base/validate.js';
|
|
18
|
+
import { freeRetired } from './assetEntry.js';
|
|
19
|
+
import { partsOf, cloneModel } from '../base/freeParts.js';
|
|
19
20
|
|
|
20
21
|
// a failed rebuild is reported (soft: the old copies stay on screen) and the swap goes on with the other names
|
|
21
22
|
const failWith = e => (err, what) => reportError(e, err, `asset hot swap: ${what}`, { soft: true });
|
|
@@ -60,11 +61,13 @@ async function swapModels(e, changed, why = 'edit') {
|
|
|
60
61
|
if (type === 'model' && neu) pair(old.value.scene, neu.scene, name);
|
|
61
62
|
}
|
|
62
63
|
// 2. cached builds (what content, pickups and vegetation got): drop them, build every name + params asked for so far again
|
|
63
|
-
const oldCached = new Map();
|
|
64
|
+
const oldCached = new Map(), builds = [];
|
|
64
65
|
for (const [k, ent] of [...a.entries]) {
|
|
65
66
|
const n = k.startsWith('cached:') ? k.slice(7, k.indexOf(':', 7)) : null;
|
|
66
67
|
if (n == null || !names.has(n)) continue;
|
|
67
68
|
if (ent.value) oldCached.set(unhashed(k), ent.value);
|
|
69
|
+
// retired, not just dropped: the load is pinned (Assets.cached), so it waits in a._retired where dispose reaches it, and is freed below once nothing draws it
|
|
70
|
+
const load = ent.load; a._retire(ent); if (load?.settled) builds.push(load);
|
|
68
71
|
a.entries.delete(k);
|
|
69
72
|
}
|
|
70
73
|
for (const n of names) a._cachedSrc?.delete(n); // a new source under the same name is not a name clash
|
|
@@ -75,13 +78,15 @@ async function swapModels(e, changed, why = 'edit') {
|
|
|
75
78
|
const o = oldCached.get(unhashed(k)), name = k.slice(7, k.indexOf(':', 7));
|
|
76
79
|
pair(o.geometry ?? o.scene, ent.value.geometry ?? ent.value.scene, name);
|
|
77
80
|
}
|
|
78
|
-
// 3. prototypes (content props / templates, pickups): a new prototype per old one; copies point at it from now on
|
|
79
|
-
|
|
81
|
+
// 3. prototypes (content props / templates, pickups): a new prototype per old one, held by the same consumers; copies point at it from now on.
|
|
82
|
+
// The old one's lease goes back once the scene below no longer draws its parts (swapped), so trim and release can free the old file then
|
|
83
|
+
let swapped; const offScene = new Promise(r => { swapped = r; });
|
|
84
|
+
for (const [key, slot] of protoSlots(e)) {
|
|
80
85
|
const model = JSON.parse(key), name = list(model)[0];
|
|
81
86
|
if (!names.has(name)) continue;
|
|
82
|
-
const old = await
|
|
83
|
-
|
|
84
|
-
const neu = await
|
|
87
|
+
const old = await slot.promise.catch(() => null);
|
|
88
|
+
let next = null; for (const h of dropProto(e, key, offScene)) next = protoOf(e, h, model);
|
|
89
|
+
const neu = await next?.catch(err => { fail(err, `model "${name}"`); return null; });
|
|
85
90
|
if (!old || !neu) continue;
|
|
86
91
|
protoNew.set(old, neu);
|
|
87
92
|
pair(old.obj, neu.obj, name);
|
|
@@ -91,17 +96,26 @@ async function swapModels(e, changed, why = 'edit') {
|
|
|
91
96
|
const b = e.batching, batched = !!b?.enabled;
|
|
92
97
|
if (batched) b.enabled = false;
|
|
93
98
|
const count = n => { copies[n] = (copies[n] || 0) + 1; };
|
|
94
|
-
const oldGeo = new Set(geo.keys());
|
|
99
|
+
const oldGeo = new Set(geo.keys()), moved = [];
|
|
95
100
|
e.scene.traverse(o => {
|
|
96
101
|
const ud = o.userData;
|
|
97
|
-
|
|
102
|
+
// a model() copy whose parts do not pair 1:1 (2 parts became 1) is rebuilt whole from the new load, like the prototype copies below: never a mix of old and new parts
|
|
103
|
+
const rec = a._instances.get(o), whole = rec && structure.has(rec.e.name) ? a.entries.get(rec.e.name) : null;
|
|
104
|
+
if (whole?.load?.value) {
|
|
105
|
+
const was = new Set(); rec.load.value?.scene?.traverse(x => { for (const p of partsOf(x)) was.add(p); });
|
|
106
|
+
const known = new Set(); rec.load.value?.scene?.traverse(x => { if (x.name) known.add(x.name); });
|
|
107
|
+
rebuildCopy(a, o, rec.e.name, whole.load.value.scene, whole.load.value.animations, c => {
|
|
108
|
+
let old = false; c.traverse(x => { if (partsOf(x).some(p => was.has(p))) old = true; });
|
|
109
|
+
if (old) c.traverse(x => { if (x.name && !known.has(x.name)) warnOnce(`asset hot swap: the parts of "${rec.e.name}" changed, so its copies were rebuilt; objects you attached inside them ("${x.name}") were dropped. Attach them again in onModel`); });
|
|
110
|
+
return old;
|
|
111
|
+
}, count, fail);
|
|
112
|
+
}
|
|
113
|
+
// content copies: later aligns read the new size, measured once their parts are swapped below
|
|
114
|
+
if (ud?.proto && protoNew.has(ud.proto)) { ud.proto = protoNew.get(ud.proto); moved.push(ud); }
|
|
98
115
|
// a model whose part count changed: the copy root stays (code holds it), its parts from the old prototype are replaced by the new ones
|
|
99
|
-
if (ud?.modelKey && structure.has(list(JSON.parse(ud.modelKey))[0]) && !o.isMesh) {
|
|
116
|
+
if (ud?.modelKey && !whole?.load?.value && structure.has(list(JSON.parse(ud.modelKey))[0]) && !o.isMesh) { // not twice: a model() copy was rebuilt above
|
|
100
117
|
const neu = [...protoNew.values()].find(p => p.obj.userData.modelKey === ud.modelKey);
|
|
101
|
-
if (neu)
|
|
102
|
-
for (const c of [...o.children]) if (meshesOf(c).some(m => oldGeo.has(m.geometry))) o.remove(c);
|
|
103
|
-
for (const c of [...skeletonClone(neu.obj).children]) { o.add(c); count(list(JSON.parse(ud.modelKey))[0]); } // a copy: add() takes c out of the live list
|
|
104
|
-
}
|
|
118
|
+
if (neu) rebuildCopy(a, o, list(JSON.parse(ud.modelKey))[0], neu.obj, neu.obj.animations, c => meshesOf(c).some(m => oldGeo.has(m.geometry)), count, fail);
|
|
105
119
|
}
|
|
106
120
|
});
|
|
107
121
|
const seenMat = new Set();
|
|
@@ -117,12 +131,33 @@ async function swapModels(e, changed, why = 'edit') {
|
|
|
117
131
|
for (const k of Object.keys(m)) { const t = tex.get(m[k]); if (t) { m[k] = t.to; m.needsUpdate = true; count(t.name); } }
|
|
118
132
|
}
|
|
119
133
|
});
|
|
134
|
+
// Leases follow the data: every copy now draws only the new load (a copy whose parts do not pair 1:1 was rebuilt whole above), so its lease moves with it, at this moment
|
|
135
|
+
const stale = [];
|
|
136
|
+
e.scene.traverse(o => {
|
|
137
|
+
const rec = a._instances.get(o), lease = o.userData.lease;
|
|
138
|
+
const next = rec && names.has(rec.e.name) ? a.entries.get(rec.e.name) : null;
|
|
139
|
+
if (next?.load?.value && next.load !== rec.load) { a._instances.set(o, { ...rec, e: next, load: next.load, lease: a._lease(next, undefined, undefined, rec.lease.by) }); stale.push(rec.lease); }
|
|
140
|
+
const own = lease && names.has(lease.name) ? a.entries.get(lease.name) : null; // content props and pickups lease by name
|
|
141
|
+
if (own?.load?.value) { stale.push(lease); o.userData.lease = a._lease(own, lease.name, undefined, lease.by); }
|
|
142
|
+
});
|
|
143
|
+
// the copy as it stands now (what its setup added stays on it), by the rule content measures every build with: never the bare prototype
|
|
144
|
+
for (const ud of moved) ud.remeasure?.();
|
|
145
|
+
swapped();
|
|
146
|
+
for (const l of stale) l.remove();
|
|
120
147
|
// 5. module hooks: vegetation rebuilds its species from the new models (its materials are patched copies, not found above)
|
|
121
148
|
for (const fn of a._swapHooks ?? []) {
|
|
122
149
|
try { const r = await fn({ names, geometry: geo, material: mat }); for (const [n, k] of Object.entries(r ?? {})) copies[n] = (copies[n] || 0) + k; }
|
|
123
150
|
catch (err) { fail(err, "a module's own copies"); }
|
|
124
151
|
}
|
|
125
152
|
if (batched) b.enabled = true;
|
|
153
|
+
// the old generated builds: what no scene mesh draws any more goes now (a part something still draws, one the swap could not find, waits for dispose)
|
|
154
|
+
if (builds.length) {
|
|
155
|
+
const drawn = new Set(); e.scene.traverse(o => { for (const x of partsOf(o)) drawn.add(x); });
|
|
156
|
+
for (const load of builds) {
|
|
157
|
+
let used = false; load.value?.scene?.traverse(o => { if (partsOf(o).some(x => drawn.has(x))) used = true; });
|
|
158
|
+
if (!used) freeRetired(a, load);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
126
161
|
|
|
127
162
|
const report = {
|
|
128
163
|
why, names: [...new Set(changed.map(c => c.name))], copies, ms: Math.round(performance.now() - t0), // measure
|
|
@@ -133,6 +168,23 @@ async function swapModels(e, changed, why = 'edit') {
|
|
|
133
168
|
return report;
|
|
134
169
|
}
|
|
135
170
|
|
|
171
|
+
/**
|
|
172
|
+
* The one rebuild of a copy whose parts changed (model() copies, content props, pickups): the old parts go through dropCopy (leases, cloned bones, instance buffers),
|
|
173
|
+
* the new ones are cloned (cloneModel), and the same steps a first build runs follow: the game's onModel setup (the copy root is the same object) and the static rays.
|
|
174
|
+
* An Animator drives the old skeleton: it is stopped, and unless the setup made a new one the game animates again (one dev warning). Why not rebind: a Character
|
|
175
|
+
* holds that Animator object and its hooks, and hot reload is a dev aid, so the simplest rule that is never wrong wins.
|
|
176
|
+
*/
|
|
177
|
+
function rebuildCopy(a, o, name, fresh, clips, isOld, count, fail) {
|
|
178
|
+
const was = a.animatorOf(o);
|
|
179
|
+
if (was) { was.dispose(); a._animators.delete(o); }
|
|
180
|
+
for (const c of [...o.children]) if (isOld(c)) { o.remove(c); a.dropCopy(c); }
|
|
181
|
+
for (const c of [...cloneModel(fresh).children]) { o.add(c); count(name); } // a copy: add() takes c out of the live list
|
|
182
|
+
o.animations = clips;
|
|
183
|
+
try { a._setup?.(o, name); } catch (err) { fail(err, `onModel for "${name}"`); }
|
|
184
|
+
a.restatic(o);
|
|
185
|
+
if (was && !a.animatorOf(o)) warnOnce(`asset hot swap: "${name}" has new parts, so its animation was stopped (it drove the old skeleton). Call assets.animate() on the copy again, or reload the page`);
|
|
186
|
+
}
|
|
187
|
+
|
|
136
188
|
/** Keep the last swaps for describe().assetSwaps, say it in the console and as a toast (dev aid: the AI and the person both see it) */
|
|
137
189
|
function remember(e, r) {
|
|
138
190
|
const a = e.assets;
|
package/core/assets/assetLoad.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// (a texture / .bin that 404s), so "the model looks gray" is traceable to one path instead of a bare "failed".
|
|
4
4
|
import { coded } from '../base/errorHints.js';
|
|
5
5
|
import * as THREE from 'three';
|
|
6
|
+
import { texturesOf } from '../stream/prepare.js';
|
|
6
7
|
import { restoreBaked, toGLB, fromGLTF } from './Baked.js';
|
|
7
8
|
import { warnOnce, DEV_SERVER, BASE_URL, fmt } from '../base/validate.js';
|
|
8
9
|
import { neutralMaterial } from '../../render/neutral.js';
|
|
@@ -88,9 +89,7 @@ export async function loadGltf(assets, url, task) {
|
|
|
88
89
|
if (task.signal.aborted) return gltf;
|
|
89
90
|
await noteFailedTextures(gltf, missing);
|
|
90
91
|
task.source.animations = gltf.animations.map(a => a.name);
|
|
91
|
-
|
|
92
|
-
gltf.scene.traverse(o => { for (const m of [].concat(o.material || [])) for (const k in m) if (m[k]?.isTexture) tex.add(m[k]); });
|
|
93
|
-
upload(assets, tex, task);
|
|
92
|
+
upload(assets, texturesOf(gltf.scene), task);
|
|
94
93
|
return gltf;
|
|
95
94
|
}
|
|
96
95
|
|
|
@@ -248,7 +247,8 @@ export async function generated(assets, name, build, params, task) {
|
|
|
248
247
|
toGLB(v, name).then(buf => fetch(CACHE + info.key + '.glb', { method: 'PUT', body: buf })).catch(err => warnOnce(coded('asset-cache', '[cache] could not store a built model in .threedog/cache (' + err.message + '); it is built again next time')));
|
|
249
248
|
return wrap(v);
|
|
250
249
|
}
|
|
251
|
-
/** Bake manifest public/models/baked/index.json (empty if missing) */
|
|
252
|
-
function bakedIndex(assets) {
|
|
253
|
-
|
|
250
|
+
/** Bake manifest public/models/baked/index.json (empty if missing: a 404 means nothing was baked; any other failure or a malformed file is said once) */
|
|
251
|
+
export function bakedIndex(assets) {
|
|
252
|
+
const bad = why => { warnOnce(coded('asset-cache', `[assets] the bake manifest models/baked/index.json could not be used (${why}); baked models are ignored and built again`)); return {}; };
|
|
253
|
+
return assets._baked ||= fetch(BASE + 'models/baked/index.json').then(r => (r.ok ? r.text() : r.status === 404 ? '{}' : bad('HTTP ' + r.status))).then(t => { try { const m = typeof t === 'string' ? JSON.parse(t) : t; return m && typeof m === 'object' && !Array.isArray(m) ? m : bad('the top level is not an object: ' + String(t).slice(0, 20)); } catch (e) { return bad(e.message); } }, e => bad(e.message));
|
|
254
254
|
}
|
package/core/assets/assetLod.js
CHANGED
|
@@ -78,7 +78,11 @@ function readDistances(d) {
|
|
|
78
78
|
* Wrap one copy of a model. scale: what the copy will be scaled by, so default distances follow its size on screen.
|
|
79
79
|
* @param {any} a the Assets instance @param {string} name @param {THREE.Object3D} full @returns {Promise<THREE.LOD>}
|
|
80
80
|
*/
|
|
81
|
-
export async function wrapLod(a, name, full,
|
|
81
|
+
export async function wrapLod(a, name, full, opts = {}) {
|
|
82
|
+
// `full` is the caller's already (a lease, a clone's bones): a LOD that cannot be made gives it back, so a rejected call leaves nothing counted
|
|
83
|
+
try { return await assemble(a, name, full, opts); } catch (err) { a.dropCopy(full); throw err; }
|
|
84
|
+
}
|
|
85
|
+
async function assemble(a, name, full, { distances, hysteresis = HYSTERESIS, scale = 1 } = {}) {
|
|
82
86
|
const asked = readDistances(distances), e = a.entries.get(name), lod = new THREE.LOD();
|
|
83
87
|
lod.name = full.name;
|
|
84
88
|
Object.assign(lod.userData, { batch: false, ...(full.userData.modelName && { modelName: full.userData.modelName }) });
|
|
@@ -92,7 +96,10 @@ export async function wrapLod(a, name, full, { distances, hysteresis = HYSTERESI
|
|
|
92
96
|
if (DEV && e?.lodCopies === MANY_COPIES) warnOnce(coded('asset-lod', `assets.lod('${name}'): ${MANY_COPIES} copies, and a LOD object is never batched, so each one is its own draw calls. Check engine.batching is not the better fit: drop lod for this model and compare describe().perf`));
|
|
93
97
|
const fullMeshes = meshesOf(full);
|
|
94
98
|
const size = new THREE.Box3().setFromObject(full).getSize(new THREE.Vector3()).length() * scale;
|
|
95
|
-
|
|
99
|
+
// allSettled: one level failing to load must not strand the others that did (each holds a lease)
|
|
100
|
+
const got = await Promise.allSettled(urls.map(u => a._bare(u, {}, 'lod'))), failed = got.find(r => r.status === 'rejected');
|
|
101
|
+
if (failed) { for (const r of got) if (r.status === 'fulfilled') a.dropCopy(r.value); throw failed.reason; }
|
|
102
|
+
const copies = got.map(r => r.value); // bare: a level is part of the LOD, which is what gets the onModel setup
|
|
96
103
|
copies.forEach((copy, i) => {
|
|
97
104
|
const low = meshesOf(copy), at = asked ? asked[i] : size * FIRST_LENGTHS * STEP ** i;
|
|
98
105
|
// a level built from another version of the model, or more levels than the game gave distances: leave it out rather than draw the wrong material on it
|
|
@@ -2,10 +2,12 @@
|
|
|
2
2
|
import { fmt, warnOnce, BASE_URL } from '../base/validate.js';
|
|
3
3
|
import { codedError } from '../base/errorHints.js';
|
|
4
4
|
import { parseSchema, readParams, keysSchema } from '../base/params.js';
|
|
5
|
+
import { readNeeds } from './modelNeeds.js';
|
|
5
6
|
|
|
6
7
|
const STRINGS = {
|
|
7
8
|
clash: 'assets.manifest(): "{name}" is already registered as a {was} (manifest "{list}"), and now as a {type}; one name is one asset, ' +
|
|
8
9
|
'so the second would replace the first. Rename one, e.g. {name}_{type}',
|
|
10
|
+
node: 'assets.manifest() models.{name}: node names one node of a file, so it needs the file as a url and a node name as a string, e.g. { url: \'/models/kit.glb\', node: \'Wall.001\' } (no build)',
|
|
9
11
|
replaced: 'assets.manifest(): {type} "{name}" from manifest "{was}" is replaced by manifest "{list}" (the later one wins). If both packs mean their own asset, rename one; '
|
|
10
12
|
+ 'if the override is intended (a mod replacing a model), ignore this',
|
|
11
13
|
};
|
|
@@ -13,6 +15,9 @@ const STRINGS = {
|
|
|
13
15
|
const MANIFEST_KEYS = ['name', 'base', 'models', 'textures', 'sounds', 'fonts'];
|
|
14
16
|
/** Keys of one fonts entry: the file, the CSS family it registers (default: the asset name), FontFace descriptors, and the usual asset flags */
|
|
15
17
|
const FONT_KEYS = ['url', 'family', 'weight', 'style', 'stretch', 'unicodeRange', 'display', 'featureSettings', 'variationSettings', 'critical', 'preload'];
|
|
18
|
+
/** What the 'optimized' pack replaces in an entry: the file (so a generator or Texture it replaces goes too: build is checked before url). Everything else stays the game's */
|
|
19
|
+
const FILE_KEYS = new Set(['url', 'lods', 'node', 'build', 'texture']);
|
|
20
|
+
const without = (o, keys) => Object.fromEntries(Object.entries(o).filter(([k]) => !keys.has(k)));
|
|
16
21
|
|
|
17
22
|
/**
|
|
18
23
|
* hot: { changed: [] } = a dev hot swap (core/assets/assetHot.js) registering the edited packs again: an entry whose build function (or Texture) and url are unchanged
|
|
@@ -33,12 +38,17 @@ export function registerManifest(a, pack, hot = null) {
|
|
|
33
38
|
for (const [name, v] of Object.entries(map)) {
|
|
34
39
|
const o0 = typeof v === 'string' ? { url: v } : typeof v === 'function' ? { build: v } : v?.isTexture && type === 'texture' ? { texture: v } : v;
|
|
35
40
|
if (type === 'font') readParams(`assets.manifest() fonts.${name}`, keysSchema(FONT_KEYS), o0);
|
|
36
|
-
|
|
41
|
+
if (type === 'model' && o0.node != null && (typeof o0.url !== 'string' || typeof o0.node !== 'string' || o0.build)) throw codedError('asset-misuse', fmt(STRINGS.node, { name }));
|
|
42
|
+
if (type === 'model' && o0.needs != null) readNeeds(`models.${name}`, o0.needs); // a typo'd key or a non-list fails here, naming the entry
|
|
37
43
|
const old = a.entries.get(name);
|
|
44
|
+
// the 'optimized' pack (`threedog assets optimize`) swaps the file only: url, lods and a part's node. The game's other options (needs,
|
|
45
|
+
// prepare, params, ...) stay, since that pack is written as JSON and cannot carry them
|
|
46
|
+
const o1 = list === 'optimized' && old?.named && old.type === type ? { ...without(old.opts, FILE_KEYS), ...o0 } : o0;
|
|
47
|
+
const o = o1.url ? { ...o1, url: resolve(o1.url), ...(o1.lods && { lods: o1.lods.map(resolve) }) } : o1;
|
|
38
48
|
// a model's params is a schema (core/base/params.js format, parsed here so a bad spec fails at registration, naming the field)
|
|
39
49
|
const schema = type === 'model' && o.params ? parseSchema(`assets.manifest() models.${name}.params`, o.params) : null;
|
|
40
50
|
if (hot && old?.named && old.type === type) {
|
|
41
|
-
if (old.opts.build === o.build && old.opts.texture === o.texture && old.url === (o.url ?? name) && JSON.stringify(old.opts.params ?? null) === JSON.stringify(o.params ?? null)) continue;
|
|
51
|
+
if (old.opts.build === o.build && old.opts.texture === o.texture && old.opts.node === o.node && old.url === (o.url ?? name) && JSON.stringify(old.opts.params ?? null) === JSON.stringify(o.params ?? null)) continue;
|
|
42
52
|
const was = { ...old }; // the swap pairs the old data with the new
|
|
43
53
|
a._retire(old);
|
|
44
54
|
Object.assign(old, { url: o.url ?? name, opts: o, schema });
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// One node of a multi-part file as its own model (manifest models: { wall: { url: '/models/kit.glb', node: 'Wall.001' } }), helper of assetEntry.js.
|
|
2
|
+
// The file is loaded once, as the entry of its path (what assets.model('/models/kit.glb') reads too), and each part holds a lease on it: the part's
|
|
3
|
+
// geometry and materials are the file's, so freeing a part only gives that lease back, and the file goes when nothing holds it.
|
|
4
|
+
import * as THREE from 'three';
|
|
5
|
+
import { clone as skeletonClone } from 'three/addons/utils/SkeletonUtils.js';
|
|
6
|
+
import { sanitize, closest } from '../base/spelling.js';
|
|
7
|
+
import { fmt } from '../base/validate.js';
|
|
8
|
+
import { LoadError } from './assetLoad.js';
|
|
9
|
+
|
|
10
|
+
const MISSING = 'no node "{node}" in {url}{near}. three renames nodes on load: a dot, colon, slash or bracket is dropped ("Wall.001" is Wall001), a space becomes _, '
|
|
11
|
+
+ 'and a second node of the same name gets _1, _2 ("Fence", "Fence_1"); either spelling works here. Nodes in the file: {list}';
|
|
12
|
+
const BONES = 'node "{node}" in {url} holds a skinned mesh whose bones are outside it, so a copy would have no skeleton. Name the node that holds both the mesh and its armature';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The part of a loaded gltf: the named node in a group of its own, at the origin. Why the world turn and size are kept and only the place is dropped:
|
|
16
|
+
* a kit lays its parts out side by side (the place), while the turn and size are how the part should look, often set on a parent (a Z-up root turned
|
|
17
|
+
* -90 degrees about x, a scaled root). A wrapper group, so content's rot / scale on the copy root add to that turn instead of replacing it.
|
|
18
|
+
* Geometry and materials are shared with the file (SkeletonUtils clone: a skinned part gets its own bones); the file's scene is not changed.
|
|
19
|
+
* @returns {{ scene: THREE.Group, animations: THREE.AnimationClip[] }}
|
|
20
|
+
*/
|
|
21
|
+
export function partOf(gltf, node, url) {
|
|
22
|
+
const all = [];
|
|
23
|
+
gltf.scene.traverse(o => { if (o !== gltf.scene && o.name) all.push(o.name); });
|
|
24
|
+
const name = all.includes(node) ? node : sanitize(node);
|
|
25
|
+
const src = all.includes(name) ? gltf.scene.getObjectByName(name) : null;
|
|
26
|
+
if (!src) {
|
|
27
|
+
const near = closest(sanitize(node), all);
|
|
28
|
+
const list = all.slice(0, 20).join(', ') + (all.length > 20 ? `, ... (${all.length})` : '');
|
|
29
|
+
throw new LoadError(fmt(MISSING, { node, url, near: near ? ` (did you mean "${near}"?)` : '', list }), { url });
|
|
30
|
+
}
|
|
31
|
+
const inside = new Set();
|
|
32
|
+
src.traverse(o => inside.add(o));
|
|
33
|
+
src.traverse(o => { if (o.isSkinnedMesh && o.skeleton.bones.some(b => !inside.has(b))) throw new LoadError(fmt(BONES, { node, url }), { url }); });
|
|
34
|
+
src.updateWorldMatrix(true, false);
|
|
35
|
+
const part = skeletonClone(src), p = new THREE.Vector3();
|
|
36
|
+
src.matrixWorld.decompose(p, part.quaternion, part.scale);
|
|
37
|
+
part.position.set(0, 0, 0);
|
|
38
|
+
// a node hidden in the file (KHR_node_visibility, nodeVisibility.js) is still shown when a manifest names it: a kit keeps its spare parts hidden. Hidden nodes inside it stay hidden
|
|
39
|
+
part.visible = true;
|
|
40
|
+
const scene = new THREE.Group();
|
|
41
|
+
scene.name = name;
|
|
42
|
+
scene.add(part);
|
|
43
|
+
// clips that move something inside the part; the rest name nodes this model does not have
|
|
44
|
+
const names = new Set([...inside].map(o => o.name));
|
|
45
|
+
const animations = gltf.animations.filter(c => c.tracks.some(t => names.has(THREE.PropertyBinding.parseTrackName(t.name).nodeName)));
|
|
46
|
+
return { scene, animations };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The load of a part entry: wait for the file's own entry, take the part and a lease on the file (released by freeValue, assetEntry.js) */
|
|
50
|
+
export function loadPart(a, e, task) {
|
|
51
|
+
task.phase('download');
|
|
52
|
+
const file = a._resolve(e.url, 'model');
|
|
53
|
+
return a._with(file, g => ({ ...partOf(g, e.opts.node, e.url), fileLease: a._lease(file, undefined, undefined, `file part ${e.name}`) }));
|
|
54
|
+
}
|