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
package/core/scene/Rays.js
CHANGED
|
@@ -17,9 +17,40 @@ import { acceleratedRaycast, computeBoundsTree } from 'three-mesh-bvh';
|
|
|
17
17
|
import { thingOf } from '../inspect/Inspect.js';
|
|
18
18
|
import { RESERVED_LAYERS } from '../../render/layers.js';
|
|
19
19
|
import { DEV, warnOnce } from '../base/validate.js';
|
|
20
|
+
import { notePatch, patchOn } from './threePatches.js';
|
|
20
21
|
|
|
21
22
|
// No three.js prototype is changed: a registered static mesh gets its own BVH and its own raycast (an own property on that mesh), so the engine's
|
|
22
23
|
// rays are fast and the game's own Raycaster stays plain three.js. A game that wants BVH page-wide writes three-mesh-bvh's three documented lines.
|
|
24
|
+
// Those two writes on the game's objects are a change to three like any other, so they are listed (threePatches 'ray-bvh') and undone:
|
|
25
|
+
// the last registration of a mesh going (remove, forget, geometry dispose, engine.dispose) gives it back the raycast it had, and a
|
|
26
|
+
// boundsTree Rays built is dropped once no registered mesh uses that geometry. A boundsTree the game (or another library) built stays theirs.
|
|
27
|
+
// Module-level, not per engine: two engines may register one mesh, and only the last one leaving may put it back.
|
|
28
|
+
const PATCH = 'ray-bvh';
|
|
29
|
+
/** mesh -> { users, own, prev }: own / prev is the raycast as it was (an own property or the class's) @type {Map<THREE.Object3D, any>} */
|
|
30
|
+
const fast = new Map();
|
|
31
|
+
/** geometry -> { users, tree }: only the trees Rays built @type {Map<THREE.BufferGeometry, any>} */
|
|
32
|
+
const built = new Map();
|
|
33
|
+
function accelerate(m) {
|
|
34
|
+
const f = fast.get(m); if (f) { f.users++; return; }
|
|
35
|
+
if (!patchOn(PATCH)) return;
|
|
36
|
+
const g = m.geometry;
|
|
37
|
+
if (!g.boundsTree && triangles(g) >= BVH_MIN) { computeBoundsTree.call(g); built.set(g, { users: 0, tree: g.boundsTree }); }
|
|
38
|
+
const b = built.get(g); if (b) b.users++;
|
|
39
|
+
// a game's own raycast override wins: only the class's own method is replaced
|
|
40
|
+
if (g.boundsTree && m.raycast === THREE.Mesh.prototype.raycast) { fast.set(m, { users: 1, own: Object.hasOwn(m, 'raycast'), prev: m.raycast, geometry: g }); m.raycast = acceleratedRaycast; }
|
|
41
|
+
else if (b) fast.set(m, { users: 1, own: null, prev: null, geometry: g }); // holds the tree it uses, no raycast to give back
|
|
42
|
+
}
|
|
43
|
+
function decelerate(m, g, all = false) {
|
|
44
|
+
const f = fast.get(m); if (!f || (--f.users > 0 && !all)) return;
|
|
45
|
+
fast.delete(m);
|
|
46
|
+
// a raycast the game wrote since is the game's: left alone
|
|
47
|
+
if (f.prev && m.raycast === acceleratedRaycast) { if (f.own) m.raycast = f.prev; else delete m.raycast; }
|
|
48
|
+
const b = built.get(g);
|
|
49
|
+
if (b && --b.users <= 0) { built.delete(g); if (g.boundsTree === b.tree) g.boundsTree = null; }
|
|
50
|
+
}
|
|
51
|
+
notePatch(PATCH, 'geometry.boundsTree (three-mesh-bvh) and an own mesh.raycast = acceleratedRaycast on each mesh of 256+ triangles registered with engine.rays.addStatic; its last registration going gives the raycast back and drops a boundsTree Rays built (core/scene/Rays.js)',
|
|
52
|
+
() => { for (const [m, f] of [...fast]) decelerate(m, f.geometry, true); },
|
|
53
|
+
{ scope: 'objects in the scene', lost: 'engine.raycast tests every triangle of a large static mesh: the same hits, slower' });
|
|
23
54
|
|
|
24
55
|
// Meshes under this many triangles get no BVH (blocky buildings etc.: the per-triangle check is faster)
|
|
25
56
|
const BVH_MIN = 256;
|
|
@@ -43,7 +74,7 @@ export class Rays {
|
|
|
43
74
|
constructor(engine) {
|
|
44
75
|
/** @internal */ this.engine = engine;
|
|
45
76
|
/** @internal */ this.providers = [];
|
|
46
|
-
/** @internal the tick the statics' world matrices were last brought up to date */ this.fresh = -1;
|
|
77
|
+
/** @internal the tick the statics' world matrices were last brought up to date; -1 = refresh at the next ray (a registration, a new frame) */ this.fresh = -1;
|
|
47
78
|
/** Registered mesh -> { refs: registration count, occ: camera-blocker registration count } @type {Map<THREE.Object3D, { refs: number, occ: number }>} @experimental */
|
|
48
79
|
this.statics = new Map();
|
|
49
80
|
/** The three.js Raycaster (firstHitOnly is on) @type {any} @experimental */
|
|
@@ -52,7 +83,7 @@ export class Rays {
|
|
|
52
83
|
this.ray.layers.enable(RESERVED_LAYERS.batched); // originals drawn through engine.batching sit here and must still be hit
|
|
53
84
|
}
|
|
54
85
|
/**
|
|
55
|
-
* Register a static object and every mesh under it (an array also works; meshes over 256 triangles get a BVH); occluder: true also blocks the camera. Returns a handle { remove() }.
|
|
86
|
+
* Register a static object and every mesh under it (an array also works; meshes over 256 triangles get a BVH); occluder: true also blocks the camera. Returns a handle { remove() }. Matrices are read once per tick and frame: a registered mesh moved between two rays of one step needs updateMatrixWorld() first.
|
|
56
87
|
* Only visible objects are hit. Something that is merely not drawn is still hit: batched originals, far hlod originals and the full model of a far assets.lod sit on a reserved layer, with their visible true.
|
|
57
88
|
* Unregisters automatically on geometry dispose or engine.remove.
|
|
58
89
|
* @param {THREE.Object3D | THREE.Object3D[]} obj
|
|
@@ -67,31 +98,40 @@ export class Rays {
|
|
|
67
98
|
for (const o of [].concat(obj)) o.traverse(m => {
|
|
68
99
|
if (DEV && (m.isInstancedMesh || m.isSkinnedMesh)) warnOnce(`engine.rays.addStatic: skipped ${m.isInstancedMesh ? 'an InstancedMesh' : 'a SkinnedMesh'} ("${m.name}"): rays do not hit these and they do not block the camera. Use a collider, or register a plain stand-in mesh.`, 'rays-skip-' + m.type);
|
|
69
100
|
if (!m.isMesh || m.isInstancedMesh || m.isSkinnedMesh || m.userData.lodLevel || !m.geometry?.attributes.position) return; // a low level stands in on screen only: rays use the full model
|
|
70
|
-
if (!m.geometry.boundsTree && triangles(m.geometry) >= BVH_MIN) computeBoundsTree.call(m.geometry);
|
|
71
|
-
if (m.geometry.boundsTree && m.raycast === THREE.Mesh.prototype.raycast) m.raycast = acceleratedRaycast; // a game's own raycast override wins
|
|
72
101
|
let s = this.statics.get(m);
|
|
73
102
|
if (!s) {
|
|
74
|
-
s = { refs: 0, occ: 0, geometry: m.geometry, onDispose: () => this._drop(m) };
|
|
103
|
+
s = { refs: 0, occ: 0, geometry: m.geometry, onDispose: () => m.geometry === s.geometry ? this._drop(m) : this._rebind(m, s) };
|
|
75
104
|
m.geometry.addEventListener('dispose', s.onDispose);
|
|
105
|
+
accelerate(m);
|
|
76
106
|
}
|
|
77
107
|
s.refs++; if (occluder) s.occ++;
|
|
78
|
-
this.statics.set(m, s); added.push(m);
|
|
108
|
+
this.statics.set(m, s); added.push([m, s]);
|
|
79
109
|
});
|
|
80
110
|
return { remove: () => {
|
|
81
|
-
for (const m of added.splice(0)) {
|
|
82
|
-
const s = this.statics.get(m); if (
|
|
111
|
+
for (const [m, mine] of added.splice(0)) {
|
|
112
|
+
const s = this.statics.get(m); if (s !== mine) continue; // forgotten, or registered again since: that count is not this handle's
|
|
83
113
|
s.refs--; if (occluder) s.occ--;
|
|
84
114
|
if (s.refs <= 0) this._drop(m);
|
|
85
115
|
}
|
|
86
116
|
} };
|
|
87
117
|
}
|
|
88
|
-
/** Unregister every mesh under the object (engine.remove calls this
|
|
118
|
+
/** Unregister every mesh under the object (engine.remove calls this) @param {THREE.Object3D} obj @internal */
|
|
89
119
|
forget(obj) { obj.traverse(m => this._drop(m)); }
|
|
120
|
+
/** @internal The mesh got another geometry (mesh.geometry = ...) and the old one was disposed: the mesh stays registered, and now follows the new one (listener and BVH) */
|
|
121
|
+
_rebind(m, s) {
|
|
122
|
+
s.geometry.removeEventListener('dispose', s.onDispose);
|
|
123
|
+
decelerate(m, s.geometry);
|
|
124
|
+
s.geometry = m.geometry;
|
|
125
|
+
if (!s.geometry?.attributes.position) return this._drop(m); // nothing to hit any more
|
|
126
|
+
s.geometry.addEventListener('dispose', s.onDispose);
|
|
127
|
+
accelerate(m);
|
|
128
|
+
}
|
|
90
129
|
/** @internal */
|
|
91
130
|
_drop(m) {
|
|
92
131
|
const s = this.statics.get(m); if (!s) return;
|
|
93
132
|
s.geometry.removeEventListener('dispose', s.onDispose);
|
|
94
133
|
this.statics.delete(m);
|
|
134
|
+
decelerate(m, s.geometry);
|
|
95
135
|
}
|
|
96
136
|
/** @internal Clear all registrations (called by engine.dispose) */
|
|
97
137
|
dispose() { for (const m of [...this.statics.keys()]) this._drop(m); this.providers = []; }
|
|
@@ -141,8 +181,9 @@ export class Rays {
|
|
|
141
181
|
} else {
|
|
142
182
|
const ray = this.ray.ray, tick = this.engine.time.tick;
|
|
143
183
|
// matrices are refreshed by the render, and a fixed step runs before it: what moved or was added since would answer from where it was.
|
|
144
|
-
//
|
|
184
|
+
// Once per tick and per frame, not per ray (5000 statics x 4 rays a frame measured 12 ms against 3-5 ms): a static moved between two rays of one step needs updateMatrixWorld() on it first (docs/api/rays.md)
|
|
145
185
|
if (this.fresh !== tick) { this.fresh = tick; for (const m of this.statics.keys()) m.updateWorldMatrix(true, false); }
|
|
186
|
+
this.ray.firstHitOnly = !filter; // BVH keeps one hit per mesh: a filter running after that would lose the hit it accepts behind the one it refuses
|
|
146
187
|
for (const [m, s] of this.statics) {
|
|
147
188
|
if (occluders && !s.occ) continue; // first: a camera ray then pays one flag check for every mesh that is no blocker
|
|
148
189
|
if (!mayHit(ray, m, far)) continue; // most statics are nowhere near the ray: skip them before walking parents
|
|
@@ -150,6 +191,7 @@ export class Rays {
|
|
|
150
191
|
hits.length = 0; m.raycast(this.ray, hits);
|
|
151
192
|
for (const h of hits) take(toHit(h));
|
|
152
193
|
}
|
|
194
|
+
this.ray.firstHitOnly = true;
|
|
153
195
|
if (targets === 'all') for (const p of this.providers) take(p(o.clone(), d.clone(), far));
|
|
154
196
|
}
|
|
155
197
|
if (best) { const e = this.engine, h = best; Object.defineProperty(h, 'thing', { get: () => thingOf(e, h.object, h), configurable: true }); } // computed only when read
|
package/core/scene/Views.js
CHANGED
|
@@ -1,15 +1,24 @@
|
|
|
1
1
|
// Named fixed camera views declared by the game, so a screenshot of "the same place" can be taken again after any change:
|
|
2
2
|
// engine.views.define('gate', { position: [10, 4, 12], target: [0, 1, 0], fov: 50 });
|
|
3
3
|
// engine.views.show('gate'); // or the URL ?view=gate, or `npm run shot -- -w my-game --view gate`
|
|
4
|
+
// engine.views.show({ position: [0, 20, -300], target: [0, 15, -500] }); // a pose with no name: a look from outside nobody declared (?view=0,20,-300,0,15,-500, `threedog state view=...`, `shot --cam`)
|
|
4
5
|
// A view takes over the camera with engine.takeCamera('views') (the same claim cutscenes use) until release() or the handle's remove(): a cutscene that
|
|
5
6
|
// held the camera before gets it back, instead of the camera going to nobody. It is a diagnostic aid, not a camera mode.
|
|
6
7
|
import { warnMissing } from '../base/validate.js';
|
|
7
8
|
import { readParams, keysSchema } from '../base/params.js';
|
|
8
9
|
import { codedError } from '../base/errorHints.js';
|
|
9
|
-
import { holdFov } from './view.js';
|
|
10
|
+
import { holdFov, baseFov } from './view.js';
|
|
10
11
|
|
|
11
12
|
const vec3 = a => Array.isArray(a) && a.length === 3 && a.every(Number.isFinite);
|
|
12
13
|
|
|
14
|
+
/** A view as given, checked: { position, target, fov } @param {string} where @param {any} v */
|
|
15
|
+
function checked(where, v) {
|
|
16
|
+
readParams(where, keysSchema(['position', 'target', 'fov']), v);
|
|
17
|
+
if (!vec3(v.position)) throw codedError('views-define', `${where}: position must be [x, y, z], got ${JSON.stringify(v.position)}`);
|
|
18
|
+
if (v.target !== undefined && !vec3(v.target)) throw codedError('views-define', `${where}: target must be [x, y, z], got ${JSON.stringify(v.target)}`);
|
|
19
|
+
return { position: v.position, target: v.target ?? [0, 0, 0], fov: v.fov };
|
|
20
|
+
}
|
|
21
|
+
|
|
13
22
|
export class Views {
|
|
14
23
|
/** @param {any} engine */
|
|
15
24
|
constructor(engine) {
|
|
@@ -23,10 +32,7 @@ export class Views {
|
|
|
23
32
|
* @returns {{ remove(): void }}
|
|
24
33
|
*/
|
|
25
34
|
define(name, v) {
|
|
26
|
-
|
|
27
|
-
if (!vec3(v.position)) throw codedError('views-define', `views.define('${name}'): position must be [x, y, z], got ${JSON.stringify(v.position)}`);
|
|
28
|
-
if (v.target !== undefined && !vec3(v.target)) throw codedError('views-define', `views.define('${name}'): target must be [x, y, z], got ${JSON.stringify(v.target)}`);
|
|
29
|
-
const rec = { position: v.position, target: v.target ?? [0, 0, 0], fov: v.fov };
|
|
35
|
+
const rec = checked(`views.define('${name}')`, v);
|
|
30
36
|
this.map.set(name, rec);
|
|
31
37
|
return { remove: () => { if (this.map.get(name) === rec) { if (this.current === name) this.release(); this.map.delete(name); } } };
|
|
32
38
|
}
|
|
@@ -35,24 +41,39 @@ export class Views {
|
|
|
35
41
|
/** @returns {string[]} the declared view names */
|
|
36
42
|
list() { return [...this.map.keys()]; }
|
|
37
43
|
/**
|
|
38
|
-
*
|
|
39
|
-
* @param {string}
|
|
44
|
+
* A pose written as text, 'x,y,z,targetX,targetY,targetZ[,fov]' (meters, fov in degrees): the form a URL's ?view= and `threedog state view=` carry. null when the text is not one
|
|
45
|
+
* @param {string} text @returns {{ position: number[], target: number[], fov?: number } | null}
|
|
46
|
+
*/
|
|
47
|
+
static pose(text) {
|
|
48
|
+
const n = String(text).split(',').map(s => (s.trim() === '' ? NaN : Number(s)));
|
|
49
|
+
return [6, 7].includes(n.length) && n.every(Number.isFinite) ? { position: n.slice(0, 3), target: n.slice(3, 6), ...(n.length === 7 && { fov: n[6] }) } : null;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Put the camera on a view and keep it there (the camera rigs leave it alone) until release() or the returned handle's remove(); null for an unknown name.
|
|
53
|
+
* A pose { position, target?, fov? } in place of a name shows that pose without declaring it (current reads '(pose)')
|
|
54
|
+
* @param {string | { position: number[], target?: number[], fov?: number }} view @returns {{ remove(): void } | null}
|
|
40
55
|
*/
|
|
41
|
-
show(
|
|
42
|
-
const v = this.map.get(
|
|
56
|
+
show(view) {
|
|
57
|
+
const name = typeof view === 'string' ? view : '(pose)', v = typeof view === 'string' ? this.map.get(view) : checked('views.show()', view);
|
|
43
58
|
if (!v) { warnMissing('view', name, this.list()); return null; }
|
|
44
|
-
const e = this.engine
|
|
59
|
+
const e = this.engine;
|
|
45
60
|
// focus: the world loads around what the view looks at, not around a player far away (the view was an empty sheet of ground without it)
|
|
46
|
-
const focus =
|
|
47
|
-
|
|
61
|
+
const focus = e.camera.position.clone().fromArray(v.target);
|
|
62
|
+
// onTop: a newer claim (a timeline shot) that moved the camera has released, and this one is in charge again: the view is put back, not just the claim (stack hook in core/ops/holds.js)
|
|
63
|
+
this._cam = e.takeCamera('views', { focus, onTop: () => this._put(name, v, focus) });
|
|
64
|
+
this._put(name, v, focus);
|
|
65
|
+
const cam = this._cam; // this showing, not the name: a handle kept from an earlier one must not end a later one
|
|
66
|
+
return { remove: () => { if (this._cam === cam) this.release(); } };
|
|
67
|
+
}
|
|
68
|
+
/** The view's pose and lens, on show and again each time the claim comes back on top */
|
|
69
|
+
_put(name, v, focus) {
|
|
70
|
+
const e = this.engine, c = e.camera;
|
|
48
71
|
e.focus.copy(focus);
|
|
49
72
|
c.position.fromArray(v.position); c.lookAt(...v.target);
|
|
50
|
-
|
|
73
|
+
holdFov(e, v.fov ?? baseFov(e)); // a view without a fov shows the base lens: a shot that stood in front of it may have left its own
|
|
51
74
|
c.updateMatrixWorld(true);
|
|
52
75
|
this.current = name;
|
|
53
76
|
e.events.emit('camera:shot', { name }); // a cut: what follows the camera (the light pool) settles at once instead of easing over
|
|
54
|
-
const cam = this._cam; // this showing, not the name: a handle kept from an earlier one must not end a later one
|
|
55
|
-
return { remove: () => { if (this._cam === cam) this.release(); } };
|
|
56
77
|
}
|
|
57
78
|
/** Give the camera back (to the previous holder, e.g. a running cutscene, or to the rig) */
|
|
58
79
|
release() {
|
package/core/scene/adaptive.js
CHANGED
|
@@ -1,16 +1,19 @@
|
|
|
1
|
-
// Adaptive
|
|
2
|
-
//
|
|
1
|
+
// Adaptive quality by frame cost: one controller, one ladder of steps.
|
|
2
|
+
// When frames cost more than the target allows it lowers one step, when they are cheap it raises the last lowered step back, slowly.
|
|
3
3
|
// It judges frame COST (main-thread cpuMs, plus GPU time from EXT_disjoint_timer_query_webgl2 when the browser has it), not fps, because a low fps
|
|
4
4
|
// alone is ambiguous: a display or power mode that refreshes at 30 Hz (laptop battery saver, phone low-power mode) gives 33.3 ms frames with
|
|
5
|
-
// almost no work, and lowering the
|
|
5
|
+
// almost no work, and lowering the picture there only blurs it for nothing. The fps path stays only as the fallback without GPU time
|
|
6
6
|
// (a GPU-bound game shows a low cpuMs), and even then a frame interval locked to the display's own refresh does not count as overload.
|
|
7
7
|
// Frames that compiled shaders (ApplyCost.rendered reports them) and the first GRACE seconds after ready are not judged: startup hitches are
|
|
8
|
-
// one-off costs that
|
|
8
|
+
// one-off costs that lowering cannot fix, and a step that rebuilds the post chain must not judge its own compile.
|
|
9
9
|
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
10
|
+
// The ladder (engine.adaptive.steps; docs/plans/2026-11-09-quality-ladder.md): the game says what may be lowered and in which order. Default, cheapest
|
|
11
|
+
// to see first (Unity's Adaptive Performance lowers low-visual-impact scalers first): each post effect's own `cheaper` params (live uniforms: no
|
|
12
|
+
// recompile), then the resolution, then the effects that declare skipOnLowTier held off (a chain rebuild and a compile: last, and never back and forth,
|
|
13
|
+
// see FLAP). No list of expensive effects lives here: an effect declares cheaper / skipOnLowTier itself, the engine follows. Only downward: nothing is
|
|
14
|
+
// set above what the game wrote, an effect the player or game has off is not a step, and a hold sits on the 'effect' layer: above the game's own writes, under a cutscene or menu (system) and the player's settings, so their later sets never clash with it.
|
|
12
15
|
import { DEV, warnOnce } from '../base/validate.js';
|
|
13
|
-
import { coded } from '../base/errorHints.js';
|
|
16
|
+
import { coded, codedError } from '../base/errorHints.js';
|
|
14
17
|
import { writeRatio } from './pixelRatio.js';
|
|
15
18
|
|
|
16
19
|
const GRACE = 3; // s after ready that are not judged (warm-up compiles, first uploads, stream fill)
|
|
@@ -19,36 +22,149 @@ const HEAVY = 0.85; // cost above this share of the frame budget = overloa
|
|
|
19
22
|
const LIGHT = 0.6; // cost under this share = headroom (raise after RAISE_AFTER windows in a row)
|
|
20
23
|
const RAISE_AFTER = 4;
|
|
21
24
|
const LOCK_TOL = 0.08; // intervals within 8 % of the window median count as "clustered"
|
|
25
|
+
// a step other than the resolution that comes down again within FLAP s of going up was not affordable: its next raise waits WAIT s, doubled each time.
|
|
26
|
+
// Why: the cost with an effect off says nothing about its cost on, so "cheap now" can raise it into the same overload; without this it toggles, and each toggle compiles
|
|
27
|
+
const FLAP = 20, WAIT = 15;
|
|
28
|
+
const OWNER = 'adaptive';
|
|
22
29
|
const HELD = coded('pixel-conflict', 'engine.adaptive.on = true does nothing while pixelSize is on; it comes back with engine.setPixelSize(null)');
|
|
30
|
+
const STEP_FORMS = "'resolution', 'post.<name>' (the effect's cheaper params), 'post.<name>.off' (the effect held off) or { name, down(), up() } (down returns false when it cannot go lower)";
|
|
31
|
+
|
|
32
|
+
/** Adaptive resolution lowered the render scale and it has not climbed back to its top: describe().render.scale's answer
|
|
33
|
+
* @param {any} e @returns {boolean} */
|
|
34
|
+
export function autoLowered(e) {
|
|
35
|
+
const a = e.adaptive, cur = e.renderer.getPixelRatio();
|
|
36
|
+
return !!a?.lowered && cur < (a.max ?? cur) - 0.01;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** What the ladder holds lowered now, in one clause, or null: the one report, read by engine.budget.notice() (shot, verify, describe text print it)
|
|
40
|
+
* @param {any} e @returns {string | null} */
|
|
41
|
+
export function loweredText(e) {
|
|
42
|
+
const a = e.adaptive;
|
|
43
|
+
if (!a) return null;
|
|
44
|
+
const parts = [...(autoLowered(e) ? [`resolution ${a.max} -> ${Math.round(e.renderer.getPixelRatio() * 100) / 100}`] : []), ...[...a.held.values()].map(s => s.text())];
|
|
45
|
+
return parts.length ? `lowered automatically: ${parts.join(', ')} (${a.reason})` : null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** @param {any} v */
|
|
49
|
+
function checkSteps(v) {
|
|
50
|
+
if (v === null) return v;
|
|
51
|
+
const bad = !Array.isArray(v) ? [v] : v.filter(s => !(s === 'resolution' || (typeof s === 'string' && /^post\.[^.]+(\.off)?$/.test(s))
|
|
52
|
+
|| (s && typeof s === 'object' && typeof s.name === 'string' && typeof s.down === 'function' && typeof s.up === 'function')));
|
|
53
|
+
if (bad.length) throw codedError('engine-misuse', `engine.adaptive.steps: a list (first lowered first) of ${STEP_FORMS}; null = the default ladder; got ${JSON.stringify(bad[0]) ?? String(bad[0])}`);
|
|
54
|
+
const keys = v.map(keyOf), twice = keys.find((k, i) => keys.indexOf(k) !== i);
|
|
55
|
+
if (twice) throw codedError('engine-misuse', `engine.adaptive.steps: '${twice}' is listed twice; each step once, in the order it is lowered`);
|
|
56
|
+
return v.slice();
|
|
57
|
+
}
|
|
58
|
+
const keyOf = s => (typeof s === 'string' ? s : `game.${s.name}`);
|
|
23
59
|
|
|
24
60
|
/**
|
|
25
|
-
* The engine.adaptive state object: the public fields (on, target, min, max, base, lowered, from; base is what this device or game starts at, the settings presets' base) plus the
|
|
61
|
+
* The engine.adaptive state object: the public fields (on, target, min, max, base, lowered, from, steps; base is what this device or game starts at, the settings presets' base) plus the
|
|
26
62
|
* controller's own counters. on is an accessor because every reader (the loop's GPU timer, describe, settings) must see false under pixelSize; what was asked for stays and returns with setPixelSize(null).
|
|
63
|
+
* held: what the ladder lowers now besides the resolution, key -> { text, undo }; the resolution needs no entry (renderer ratio against max says it).
|
|
27
64
|
* @param {{ on: boolean, target: number, max: number, held: () => boolean }} o held: pixelSize decides the ratio now
|
|
28
65
|
*/
|
|
29
66
|
export function createAdaptive({ on, target, max, held }) {
|
|
30
|
-
let wanted = on;
|
|
67
|
+
let wanted = on, steps = null;
|
|
31
68
|
return { get on() { return wanted && !held(); },
|
|
32
69
|
set on(v) { wanted = v; if (DEV && v && held()) warnOnce(HELD); },
|
|
70
|
+
get steps() { return steps; }, set steps(v) { steps = checkSteps(v); },
|
|
33
71
|
target, min: 0.6, max, base: max, t: 0, good: 0, cooldown: 0, lowered: false, from: null,
|
|
34
|
-
age: 0, costs: [], gaps: [], refresh: Infinity, reason: null };
|
|
72
|
+
age: 0, costs: [], gaps: [], refresh: Infinity, reason: null, held: new Map(), raisedAt: {}, wait: {}, notBefore: {}, warned: false };
|
|
35
73
|
}
|
|
36
74
|
|
|
37
75
|
const median = a => { const s = a.slice().sort((x, y) => x - y); return s.length ? s[s.length >> 1] : 0; };
|
|
38
76
|
|
|
77
|
+
/** The default ladder: from the effects added now, in chain order @param {any} e */
|
|
78
|
+
function defaultSteps(e) {
|
|
79
|
+
const fx = e.post?._sorted?.() ?? [];
|
|
80
|
+
return [...fx.filter(h => h._def.cheaper).map(h => `post.${h.name}`), 'resolution', ...fx.filter(h => h._def.skipOnLowTier).map(h => `post.${h.name}.off`)];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* One step as { key, down(), lowered(), up() }. down() lowers one notch and says whether it did; up() raises one notch. Every lowered step but the
|
|
85
|
+
* resolution keeps an entry in a.held with its undo, so turning the controller off, a step leaving the list or its effect going away puts it back.
|
|
86
|
+
* @param {any} e @param {any} s
|
|
87
|
+
*/
|
|
88
|
+
function stepOf(e, s) {
|
|
89
|
+
const a = e.adaptive, held = a.held, key = keyOf(s), pr = () => e.renderer.getPixelRatio();
|
|
90
|
+
if (s === 'resolution') return { key,
|
|
91
|
+
// a ratio the game wrote with renderer.setPixelRatio is the game's (core/ops/owned.js): this step stands aside, the others still run
|
|
92
|
+
down() {
|
|
93
|
+
const p = pr();
|
|
94
|
+
if (!e._oPixelRatio.on || p <= a.min + 0.01) return false;
|
|
95
|
+
if (!a.lowered) { a.lowered = true; a.from = p; }
|
|
96
|
+
writeRatio(e, Math.max(a.min, +(p - 0.1).toFixed(2)));
|
|
97
|
+
return true;
|
|
98
|
+
},
|
|
99
|
+
lowered: () => e._oPixelRatio.on && pr() < a.max - 0.01,
|
|
100
|
+
up() { writeRatio(e, Math.min(a.max, +(pr() + 0.05).toFixed(2))); } };
|
|
101
|
+
const up = () => held.get(key)?.undo();
|
|
102
|
+
if (typeof s === 'object') return { key, lowered: () => held.has(key), up,
|
|
103
|
+
// the game's own knob (view distance, density): it says when it is at its floor; each notch down is undone by one up()
|
|
104
|
+
down() {
|
|
105
|
+
if (s.down() === false) return false;
|
|
106
|
+
// step: which object holds these notches, so a new step of the same name never raises with this one's up() (ladder)
|
|
107
|
+
const st = held.get(key) ?? { n: 0, step: s, text: () => (st.n > 1 ? `${s.name} x${st.n}` : s.name), undo: () => { s.up(); if (--st.n <= 0) held.delete(key); } };
|
|
108
|
+
st.n++; held.set(key, st);
|
|
109
|
+
return true;
|
|
110
|
+
} };
|
|
111
|
+
const [, name, off] = /^post\.([^.]+)(\.off)?$/.exec(s) ?? [];
|
|
112
|
+
return { key, lowered: () => held.has(key), up,
|
|
113
|
+
down() {
|
|
114
|
+
const h = e.post.get(name);
|
|
115
|
+
if (!h || !h.enabled || held.has(key)) return false; // not added, off by the game or player, held by the tier: nothing to lower
|
|
116
|
+
if (off) {
|
|
117
|
+
const point = e.post.switchPoint(`post.${name}.enabled`);
|
|
118
|
+
// an effect-layer set by another owner throws shared-conflict: then this step is not ours to take
|
|
119
|
+
try { point.take({ owner: OWNER, layer: 'effect', set: false }); } catch { return false; }
|
|
120
|
+
held.set(key, { h, text: () => `${name} off`, undo: () => { held.delete(key); point.release(OWNER); } });
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
// only downward: a number param goes lower, never higher; any other kind is taken as the effect wrote it
|
|
124
|
+
const to = Object.fromEntries(Object.entries(h._def.cheaper ?? {}).filter(([k, v]) => k in h.params && (typeof v === 'number' ? v < h.params[k] : v !== h.params[k])));
|
|
125
|
+
if (!Object.keys(to).length) return false;
|
|
126
|
+
const was = Object.fromEntries(Object.keys(to).map(k => [k, h.params[k]]));
|
|
127
|
+
h.set(to);
|
|
128
|
+
// back only what still holds the lowered value: a param the game set meanwhile is the game's newer word
|
|
129
|
+
held.set(key, { h, text: () => `${name} cheaper`, undo: () => {
|
|
130
|
+
held.delete(key);
|
|
131
|
+
const back = Object.fromEntries(Object.entries(was).filter(([k]) => h.params[k] === to[k]));
|
|
132
|
+
if (!h._removed && Object.keys(back).length) h.set(back);
|
|
133
|
+
} });
|
|
134
|
+
return true;
|
|
135
|
+
} };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* The steps now, and anything held by a step that left the list, whose effect was removed, or that was replaced by another of that name (an effect or a
|
|
140
|
+
* game step: same key, other object) put back, with the old one's own undo, before the new one lowers anything @param {any} e
|
|
141
|
+
*/
|
|
142
|
+
function ladder(e) {
|
|
143
|
+
const a = e.adaptive, given = a.steps ?? defaultSteps(e), list = given.map(s => stepOf(e, s)), now = new Map(given.map(s => [keyOf(s), s]));
|
|
144
|
+
for (const [k, st] of [...a.held]) if (!now.has(k) || (st.h && e.post.get(st.h.name) !== st.h) || (st.step && now.get(k) !== st.step)) drop(a.held, k);
|
|
145
|
+
return list;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Every notch of one held step undone (a game step lowered three times is raised three times) @param {Map<string, any>} held @param {string} k */
|
|
149
|
+
function drop(held, k) { while (held.has(k)) held.get(k).undo(); }
|
|
150
|
+
|
|
151
|
+
/** Put back everything the ladder holds (the controller turned off, pixelSize on). The resolution stays where it is: settings' 'adaptive' row and setPixelRatio own that write @param {any} e */
|
|
152
|
+
function releaseAll(e) { for (const k of [...e.adaptive.held.keys()]) drop(e.adaptive.held, k); }
|
|
153
|
+
|
|
39
154
|
/**
|
|
40
155
|
* One frame's sample. dt in s (the requestAnimationFrame interval), cost in ms (max of cpu and gpu), compiled: this frame compiled shaders.
|
|
41
156
|
* gpuKnown: cost includes measured GPU time, so a slow interval with a cheap cost is never our overload.
|
|
42
157
|
*/
|
|
43
158
|
export function adapt(e, dt, cost, compiled, gpuKnown) {
|
|
44
159
|
const a = e.adaptive;
|
|
45
|
-
if (!a.on
|
|
160
|
+
if (!a.on) { if (a.held.size) releaseAll(e); return; }
|
|
161
|
+
if (!e.ready) return;
|
|
46
162
|
a.age += dt; a.t += dt; a.cooldown -= dt;
|
|
47
163
|
if (!compiled) { a.costs.push(cost); a.gaps.push(dt * 1000); }
|
|
48
164
|
if (a.t < WINDOW) return;
|
|
49
165
|
const costs = a.costs, gaps = a.gaps; a.t = 0; a.costs = []; a.gaps = [];
|
|
50
|
-
// the game set renderer.setPixelRatio itself:
|
|
51
|
-
e._oPixelRatio.check();
|
|
166
|
+
// the game set renderer.setPixelRatio itself: the resolution step stands aside (core/ops/owned.js); engine.autoView.manual('pixelRatio', false) resumes it
|
|
167
|
+
e._oPixelRatio.check();
|
|
52
168
|
if (!gaps.length) return;
|
|
53
169
|
const gap = median(gaps), clustered = gaps.filter(g => Math.abs(g - gap) <= gap * LOCK_TOL).length >= gaps.length * 0.7;
|
|
54
170
|
// the fastest steady interval ever seen is the display's refresh (learned during grace too: loading frames are slower, never faster)
|
|
@@ -60,15 +176,22 @@ export function adapt(e, dt, cost, compiled, gpuKnown) {
|
|
|
60
176
|
// locked: the frames wait on the display (steady at its refresh, work clearly shorter than the interval), not on us
|
|
61
177
|
const locked = clustered && Math.abs(gap - a.refresh) <= a.refresh * LOCK_TOL && c < gap * 0.8;
|
|
62
178
|
const overload = heavy || (!gpuKnown && slow && !locked);
|
|
63
|
-
const
|
|
64
|
-
if (overload
|
|
65
|
-
|
|
179
|
+
const steps = ladder(e);
|
|
180
|
+
if (overload) {
|
|
181
|
+
a.good = 0;
|
|
182
|
+
const s = steps.find(x => x.down());
|
|
183
|
+
if (!s) return;
|
|
66
184
|
a.reason = heavy ? `frames cost ${c.toFixed(1)} ms of a ${budget.toFixed(1)} ms budget (target ${a.target} fps)` : `fps ${(1000 / gap).toFixed(0)} is under ${a.target}`;
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
if (
|
|
185
|
+
a.cooldown = 5;
|
|
186
|
+
// a step that stayed up for 4 x FLAP was affordable after all: its wait starts over
|
|
187
|
+
if (s.key !== 'resolution') { const up = a.age - (a.raisedAt[s.key] ?? -Infinity); if (up < FLAP) { a.wait[s.key] = (a.wait[s.key] ?? WAIT / 2) * 2; a.notBefore[s.key] = a.age + a.wait[s.key]; } else if (up > FLAP * 4) delete a.wait[s.key]; }
|
|
188
|
+
// never silent: the picture changes, and the game or an AI should know why (dev warning once; engine.budget.notice() keeps what is lowered now)
|
|
189
|
+
if (DEV && !a.warned) { a.warned = true; warnOnce(`${loweredText(e)}; adaptive quality lowers engine.adaptive.steps in order (resolution down to ${a.min}). Turn off with createEngine({ adaptiveResolution: false }) or engine.adaptive.on = false; engine.budget.notice() says what is lowered`); }
|
|
190
|
+
} else if (c < budget * LIGHT && a.cooldown <= 0) {
|
|
191
|
+
// last lowered goes up first; a step that flapped waits its turn, and the ones before it with it
|
|
192
|
+
const s = steps.findLast(x => x.lowered());
|
|
193
|
+
if (!s || a.age < (a.notBefore[s.key] ?? 0)) { a.good = 0; return; }
|
|
194
|
+
if (++a.good >= RAISE_AFTER) { s.up(); a.good = 0; if (s.key !== 'resolution') a.raisedAt[s.key] = a.age; }
|
|
72
195
|
} else a.good = 0;
|
|
73
196
|
}
|
|
74
197
|
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// Parts the engine draws for something else, not things of their own: a cascade's extra copies of the sun (the material patch adds them up to
|
|
2
|
+
// one sun), far impostor cards placed only in the vertex shader, the sky dome. Whatever copies the scene (the photo path trace, the gallery's
|
|
3
|
+
// 'game' light) leaves every marked object out: one rule here, so no copier keeps its own list and a new such part is covered by marking it.
|
|
4
|
+
// A WeakMap, not userData: three's clone() copies userData, so a game's own clone of a marked object (a cascade light reused as a fill light,
|
|
5
|
+
// a cloned sky mesh) would be hidden too. The tools package reads it through the 'threedog/draw-only' export (the same module instance).
|
|
6
|
+
|
|
7
|
+
/** object -> what a copy lacks without it, in plain words ('' when nothing is: the real sun stays) */
|
|
8
|
+
const MARKED = new WeakMap();
|
|
9
|
+
/**
|
|
10
|
+
* Mark objects as drawn for something else (returns the first, so it fits in the call). For engine module code.
|
|
11
|
+
* @template {import('three').Object3D} T @param {string} what @param {[T, ...import('three').Object3D[]]} objs @returns {T}
|
|
12
|
+
*/
|
|
13
|
+
export function drawOnly(what, ...objs) { for (const o of objs) MARKED.set(o, what); return objs[0]; }
|
|
14
|
+
/** True for an object drawOnly marked (never for a clone of one) @param {any} o @returns {boolean} */
|
|
15
|
+
export const isDrawOnly = o => MARKED.has(o);
|
|
16
|
+
/** What a copy lacks without o ('' when nothing), undefined when o is not marked @param {any} o @returns {string | undefined} */
|
|
17
|
+
export const drawOnlyWhat = o => MARKED.get(o);
|
package/core/scene/gameLights.js
CHANGED
|
@@ -12,10 +12,15 @@
|
|
|
12
12
|
// What stays the game's: color, intensity, distance, castShadow (turning shadows off is the renderer's switch, render/shadows.js), the shadow map size and bias. The engine never writes them (P1).
|
|
13
13
|
// lightPool stays the optional helper for "many lamps, few real lights": that trade-off is a game decision the engine cannot guess.
|
|
14
14
|
// Cost: a scene visitor (no walk per frame); per frame one loop over the shadow-casting game lights, usually zero to three.
|
|
15
|
+
// RectAreaLight: three leaves its LTC tables (314 KB of numbers) to the game, and a game that forgets gets a failed shader build on WebGPU and a black
|
|
16
|
+
// light on WebGL. The first one to enter the scene loads them, once per page (three keeps them in statics too). The import is async and a frame may draw
|
|
17
|
+
// first, so WebGPU gets same-shaped stand-ins at once (an identity matrix: the diffuse part is exact, the shine is missing for that frame) that the real
|
|
18
|
+
// numbers are then copied into. Area lights have no shadows in three, and light only MeshStandard / MeshPhysical materials.
|
|
19
|
+
import { DataTexture, FloatType, HalfFloatType, RGBAFormat, UVMapping, ClampToEdgeWrapping, LinearFilter, NearestFilter } from 'three';
|
|
15
20
|
import { sceneVisitor } from './sceneDelta.js';
|
|
16
21
|
import { moduleOwnerOf } from './things.js';
|
|
17
22
|
import { notePatch, patchOn } from './threePatches.js';
|
|
18
|
-
import { shadowMaps } from '../../render/backend.js';
|
|
23
|
+
import { shadowMaps, webgpuPartOrNull } from '../../render/backend.js';
|
|
19
24
|
import { warnOnce, fmt } from '../base/validate.js';
|
|
20
25
|
import { MANY } from '../inspect/lightWatch.js';
|
|
21
26
|
import { isShown } from '../base/util.js';
|
|
@@ -31,33 +36,65 @@ const placeholderOn = e => ['sun', 'hemi'].some(k => { const l = e.lights?.[k];
|
|
|
31
36
|
/** The engine module that owns o (it or an ancestor carries engineOwned), else null */
|
|
32
37
|
function engineOwner(o) { for (let p = o; p; p = p.parent) { const m = moduleOwnerOf(p); if (m) return m; } return null; }
|
|
33
38
|
|
|
39
|
+
let areaTables = false; // page-wide, as three's own tables are (R29 ALLOW)
|
|
40
|
+
function loadAreaTables() {
|
|
41
|
+
if (areaTables) return;
|
|
42
|
+
areaTables = true;
|
|
43
|
+
const node = webgpuPartOrNull('classes')?.RectAreaLightNode, size = 64 * 64 * 4;
|
|
44
|
+
const standIn = (half, matrix) => {
|
|
45
|
+
const data = half ? new Uint16Array(size) : new Float32Array(size);
|
|
46
|
+
if (matrix) for (let i = 0; i < size; i += 4) data[i] = data[i + 3] = half ? 0x3c00 : 1; // 0x3c00 is 1 as a half float
|
|
47
|
+
const t = new DataTexture(data, 64, 64, RGBAFormat, half ? HalfFloatType : FloatType, UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, NearestFilter, 1);
|
|
48
|
+
t.needsUpdate = true;
|
|
49
|
+
return t;
|
|
50
|
+
};
|
|
51
|
+
/** @type {Record<string, any> | null} */
|
|
52
|
+
const stand = node ? { LTC_FLOAT_1: standIn(false, true), LTC_FLOAT_2: standIn(false, false), LTC_HALF_1: standIn(true, true), LTC_HALF_2: standIn(true, false) } : null;
|
|
53
|
+
if (stand) node.setLTC(stand);
|
|
54
|
+
Promise.all([import('three/addons/lights/RectAreaLightUniformsLib.js'), import('three/addons/lights/RectAreaLightTexturesLib.js')]).then(([{ RectAreaLightUniformsLib }, { RectAreaLightTexturesLib: lib }]) => {
|
|
55
|
+
RectAreaLightUniformsLib.init(); // WebGLRenderer reads them from UniformsLib, the WebGPU node from the stand-ins
|
|
56
|
+
for (const k in stand) { stand[k].image.data.set(lib[k].image.data); stand[k].needsUpdate = true; }
|
|
57
|
+
}, err => {
|
|
58
|
+
areaTables = false;
|
|
59
|
+
for (const k in stand) stand[k].dispose();
|
|
60
|
+
warnOnce(`RectAreaLight: three's LTC tables did not load (${err?.message ?? err}): on WebGPU the light gives diffuse light only, no shine; on WebGL none. Loading is tried again when a RectAreaLight next enters the scene`);
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
34
64
|
/** @param {any} e */
|
|
35
65
|
export function watchGameLights(e) {
|
|
36
66
|
const all = new Set(), game = new Set(), idled = new WeakSet(), handed = new WeakSet();
|
|
67
|
+
// The one place autoUpdate goes back to the game: only a light the engine idled, and only if the game has not written the value since (then it is the game's)
|
|
68
|
+
const giveBack = l => { if (!idled.delete(l)) return; if (!l.shadow.autoUpdate) { l.shadow.autoUpdate = true; l.shadow.needsUpdate = true; } };
|
|
37
69
|
const view = sceneVisitor(e.scene, {
|
|
38
70
|
enter(o) {
|
|
39
71
|
if (o.isLight && !o.isLightProbe && !o.isLightProbeGrid && o !== e.lights?.sun && o !== e.lights?.hemi && !o.userData.fixedCount && !engineOwner(o) && placeholderOn(e))
|
|
40
72
|
warnOnce(fmt(ADDED_UP, { what: o.name || o.type }), 'game-light-adds-up');
|
|
73
|
+
if (o.isRectAreaLight) loadAreaTables();
|
|
41
74
|
if (!o.isPointLight && !o.isSpotLight) return;
|
|
42
75
|
all.add(o);
|
|
43
76
|
if (!o.userData.fixedCount && !engineOwner(o)) game.add(o);
|
|
44
77
|
},
|
|
45
78
|
leave(o) {
|
|
46
79
|
all.delete(o); game.delete(o);
|
|
47
|
-
|
|
80
|
+
giveBack(o); // leaves as the game left it
|
|
48
81
|
},
|
|
49
82
|
});
|
|
50
83
|
const count = (fn) => { view.sync(); let n = 0; for (const l of all) if (fn(l)) n++; return n; };
|
|
51
84
|
e.budget.metric('lights', () => count(l => isShown(l) && l.intensity > 0), { limit: MANY });
|
|
52
85
|
e.budget.metric('shadowLights', () => e.renderer.shadowMap.enabled ? count(l => isShown(l) && l.castShadow && l.intensity > 0) : 0);
|
|
53
86
|
const maps = () => shadowMaps(e.renderer, e.scene);
|
|
54
|
-
|
|
87
|
+
// a guide like the one for lights (nothing is cut at it): the sun and one point light (six maps) fit; a second shadowed point light, or one beside cascades,
|
|
88
|
+
// is where the frame's triangles multiply (two of them took a 12 M triangle scene to 42 M) and nothing said so
|
|
89
|
+
e.budget.metric('shadowMaps', () => maps().reduce((n, m) => n + m.faces, 0), { limit: 7 });
|
|
55
90
|
e.budget.metric('shadowMapSize', () => maps().reduce((n, m) => Math.max(n, m.shadow.mapSize.x, m.shadow.mapSize.y), 0));
|
|
56
91
|
e._gameLights = {
|
|
57
92
|
/** The game's own point / spot lights (not a module's, not a pool's) */
|
|
58
93
|
list() { view.sync(); return [...game]; },
|
|
59
94
|
/** Every point / spot light in the scene, modules' and pools' too; a live set, for reading */
|
|
60
95
|
all() { view.sync(); return all; },
|
|
96
|
+
/** Catch up with what entered the scene: before a compile or a draw outside the loop, so a RectAreaLight has its tables first */
|
|
97
|
+
sync() { view.sync(); },
|
|
61
98
|
/** Before each render (loop.js): the idle-shadow rule */
|
|
62
99
|
frame() {
|
|
63
100
|
view.sync();
|
|
@@ -67,13 +104,19 @@ export function watchGameLights(e) {
|
|
|
67
104
|
const opted = !patchOn('light-idle-shadow') || l.userData.idleShadow === false;
|
|
68
105
|
if (idled.has(l)) {
|
|
69
106
|
if (s.autoUpdate) { idled.delete(l); handed.add(l); } // the game turned redraws on itself while idled: its light from now on
|
|
70
|
-
else if (l.intensity > 0 || !l.castShadow || opted)
|
|
107
|
+
else if (l.intensity > 0 || !l.castShadow || opted) giveBack(l); // put back what was taken
|
|
71
108
|
} else if (l.castShadow && l.intensity <= 0 && s.autoUpdate && !opted && !handed.has(l)) { s.autoUpdate = false; idled.add(l); }
|
|
72
109
|
}
|
|
73
110
|
},
|
|
111
|
+
/** Engine dispose: stop watching the scene and hand every idled light back (a light may outlive the engine in another scene) */
|
|
112
|
+
dispose() { view.remove(); for (const l of game) giveBack(l); },
|
|
74
113
|
/** Whether the engine holds this light's shadow redraw now (describe) */
|
|
75
114
|
idled: l => idled.has(l),
|
|
76
115
|
};
|
|
77
116
|
}
|
|
117
|
+
/** @internal Every point / spot light in the scene (a live set, for reading; empty before the watch starts): for modules, which do not reach into e._gameLights */
|
|
118
|
+
export function pointSpotLights(e) { return e._gameLights?.all() ?? EMPTY; }
|
|
119
|
+
const EMPTY = new Set();
|
|
120
|
+
|
|
78
121
|
notePatch('light-idle-shadow', "shadow.autoUpdate of the game's own shadow-casting point / spot lights: off while intensity is 0, back on when lit (core/scene/gameLights.js)",
|
|
79
122
|
() => {}, { scope: 'objects in the scene', lost: 'a casting light at intensity 0 redraws its shadow map every frame, as in plain three.js' });
|