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
package/render/effects.js
CHANGED
|
@@ -61,16 +61,38 @@ export function createUniforms() {
|
|
|
61
61
|
for (const [k, v] of Object.entries(UNIFORM_DEFAULTS)) u[k] = engineUniform(k, typeof v === 'function' ? v() : v);
|
|
62
62
|
return u;
|
|
63
63
|
}
|
|
64
|
+
/**
|
|
65
|
+
* Give signals back to their neutral defaults: a module that wrote shared signals every frame calls this when it is removed, or the last value
|
|
66
|
+
* (a blizzard's uSnow, a winter ground tint) would stay for every reader. The one way to take a written signal back; the defaults are the table above
|
|
67
|
+
* @internal @param {any} e @param {string[]} names uniform names
|
|
68
|
+
*/
|
|
69
|
+
export function resetSignals(e, names) {
|
|
70
|
+
for (const n of names) { const d = UNIFORM_DEFAULTS[n], v = typeof d === 'function' ? d() : d, u = e.uniforms[n]; if (v?.isColor || v?.isVector2 || v?.isVector3) u.value.copy(v); else u.value = v; }
|
|
71
|
+
}
|
|
64
72
|
const TEMPLATE = createUniforms(); // what built-in patches name; resolved to the compiling engine's uniforms
|
|
65
73
|
|
|
66
74
|
// ---------- GLSL ----------
|
|
67
75
|
/**
|
|
68
|
-
* Shared GLSL value noise: threedogHash(vec2), threedogNoise(vec2) (used by sky clouds and cloud shadows)
|
|
76
|
+
* Shared GLSL value noise: threedogHash(vec2), threedogNoise(vec2) (used by sky clouds and cloud shadows).
|
|
77
|
+
* One pcg2d core (threedogHashStep, fxNumbers.js HASH), two ways in. Public threedogHash(p): any vec2, hashed by its float bits (exact on
|
|
78
|
+
* both backends for the same floats; a fractional p such as vUv gives a value per pixel, as the 1.0 contract says). Internal threedogHashCell:
|
|
79
|
+
* the lattice cell floor(p), for the engine's noise and dabs, because pcg2d's first step is linear: cell (x + 1) starts at
|
|
80
|
+
* threedogHashCell(x) + mul, so neighbor cells cost an add instead of a conversion and two multiplies (slow on some GPUs).
|
|
81
|
+
* highp on the uints: a fragment shader's default int precision is mediump in GLSL ES 3.0, and the hash needs all 32 bits.
|
|
69
82
|
* @internal
|
|
70
83
|
*/
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
84
|
+
const M = `${HASH.mul}u`;
|
|
85
|
+
// Guarded inside: the dome and the post pass paste it, and a game snippet there may still #include <threedog_noise>
|
|
86
|
+
export const NOISE_GLSL = `#ifndef THREEDOG_NOISE
|
|
87
|
+
#define THREEDOG_NOISE
|
|
88
|
+
highp uvec2 threedogHashCell(vec2 p){ return uvec2(ivec2(floor(p))) * ${M} + ${HASH.add}u; }
|
|
89
|
+
float threedogHashStep(highp uvec2 v){ v.x += v.y * ${M}; v.y += v.x * ${M}; v ^= v >> 16u; v.x += v.y * ${M};
|
|
90
|
+
highp uint x = v.x ^ (v.x >> 16u); return float(x >> 8u) * ${f(1 / 2 ** 24)}; }
|
|
91
|
+
// b ^= b >> 16: a whole-number float has zero low mantissa bits, and without this fold the x output draws diagonal stripes
|
|
92
|
+
float threedogHash(vec2 p){ highp uvec2 b = floatBitsToUint(p); b ^= b >> 16u; return threedogHashStep(b * ${M} + ${HASH.add}u); }
|
|
93
|
+
float threedogNoise(vec2 p){ highp uvec2 v = threedogHashCell(p); vec2 f = fract(p); f = f*f*(3.0-2.0*f);
|
|
94
|
+
return mix(mix(threedogHashStep(v), threedogHashStep(v + uvec2(${M}, 0u)), f.x), mix(threedogHashStep(v + uvec2(0u, ${M})), threedogHashStep(v + uvec2(${M})), f.x), f.y); }
|
|
95
|
+
#endif`;
|
|
74
96
|
|
|
75
97
|
// GLSL pieces, also registered as THREE.ShaderChunk.threedog_* so a hand-written ShaderMaterial can #include them.
|
|
76
98
|
// The callable ones (fixed signatures, for your own ShaderMaterial; the automatic patches call the same functions, so the math lives once):
|
|
@@ -93,10 +115,7 @@ const CALLABLE = {
|
|
|
93
115
|
float k = max(position.y, 0.0) * amplitude * uWind;
|
|
94
116
|
return vec3(sw * k + k * ${f(WIND.lean)} * (uWind - 1.0), 0.0, sw * k * ${f(WIND.side)});
|
|
95
117
|
}`,
|
|
96
|
-
threedog_noise:
|
|
97
|
-
#define THREEDOG_NOISE
|
|
98
|
-
${NOISE_GLSL}
|
|
99
|
-
#endif`,
|
|
118
|
+
threedog_noise: NOISE_GLSL,
|
|
100
119
|
threedog_cloudShadow: `
|
|
101
120
|
#include <threedog_noise>
|
|
102
121
|
float threedogCloudShadow(vec3 worldPos){
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// What fog a scene is drawn with, for the parts that match something to it (the sky dome's fog band, the water's grazing colour, the horizon check).
|
|
2
|
+
// WebGL fog is scene.fog (a three Fog / FogExp2) and WebGLRenderer never draws a fogNode. WebGPU fog as the engine documents it (recipes 56) is
|
|
3
|
+
// scene.fogNode = fog(color, factor), a TSL node, and WebGPURenderer draws it in place of scene.fog when both are set (three NodeManager.getFogNode).
|
|
4
|
+
// One reading that follows the renderer, so a part never answers "no fog" for a scene that has one, nor "fog" for a fogNode WebGL ignores.
|
|
5
|
+
import { warnOnce } from '../core/base/validate.js';
|
|
6
|
+
import { coded } from '../core/base/errorHints.js';
|
|
7
|
+
import { isWebGPU } from './backend.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The fog the renderer draws: on WebGPURenderer scene.fogNode when set, else scene.fog; on WebGLRenderer scene.fog only. A fogNode comes back as
|
|
11
|
+
* { color, isNode: true } read from fog(color, factor) when color is a THREE.Color or a color() / uniform(Color) node (the first argument of the
|
|
12
|
+
* call, kept in rawInputs). A computed color cannot be read before the shader runs: the parts then get color null and the game is told once, instead of
|
|
13
|
+
* the dome / water silently ignoring its fog. A node's range is not read (fog() takes any factor node), so it has no near / far / density.
|
|
14
|
+
* @param {any} scene @param {any} renderer
|
|
15
|
+
* @returns {{ color: any, near?: number, far?: number, density?: number, isFog?: boolean, isFogExp2?: boolean, isNode?: boolean } | null}
|
|
16
|
+
*/
|
|
17
|
+
export function fogLook(scene, renderer) {
|
|
18
|
+
const n = isWebGPU(renderer) && scene.fogNode;
|
|
19
|
+
if (!n) return scene.fog || null;
|
|
20
|
+
const c = n.rawInputs?.[0], v = c?.isColor ? c : c?.value;
|
|
21
|
+
if (v?.isColor) return { color: v, isNode: true };
|
|
22
|
+
warnOnce(coded('fog-fallback', 'scene.fogNode: its color is not a THREE.Color, color(..) or uniform(Color) (as in fog(color(0xaabbcc), factor)), so the sky dome\'s fog band, the water\'s grazing colour and the horizon check cannot match your fog and leave it out'), 'fog-node-unread');
|
|
23
|
+
return { color: null, isNode: true };
|
|
24
|
+
}
|
package/render/fuse.js
CHANGED
|
@@ -5,10 +5,13 @@ import * as THREE from 'three';
|
|
|
5
5
|
import { Pass, FullScreenQuad } from 'three/addons/postprocessing/Pass.js';
|
|
6
6
|
import { CopyShader } from 'three/addons/shaders/CopyShader.js';
|
|
7
7
|
import { codedError } from '../core/base/errorHints.js';
|
|
8
|
+
import { NOISE_GLSL } from './effects.js';
|
|
8
9
|
/** @import { PostFuse } from './PostFX' */
|
|
9
10
|
|
|
10
|
-
// Helpers every snippet may call
|
|
11
|
-
|
|
11
|
+
// Helpers every snippet may call: the engine's one hash / value noise (threedogHash, threedogNoise), so a post effect's random pattern is the
|
|
12
|
+
// same as its TSL side's (fx.hash / fx.noise) and as every other effect's
|
|
13
|
+
const HELPERS = `${NOISE_GLSL}
|
|
14
|
+
#define fxHash threedogHash // the frozen 1.0 name for post snippets (recipe 52), the same function`;
|
|
12
15
|
const EMPTY = { float: () => 0, int: () => 0, vec2: () => new THREE.Vector2(), vec3: () => new THREE.Vector3(), vec4: () => new THREE.Vector4() };
|
|
13
16
|
|
|
14
17
|
export class FusedPass extends Pass {
|
package/render/fx/detail.tsl.js
CHANGED
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
// Why not import detail.js: it registers a ShaderChunk and pulls in the WebGL patch machinery, which threedog/tsl must not.
|
|
4
4
|
// The projections (world / triplanar / screen) and the fade are part of the `detail` patch (its uniforms), not callable functions, so they
|
|
5
5
|
// belong to the patch's tsl field; a NodeMaterial gets the same pattern by feeding detailNoise any 2D position it likes.
|
|
6
|
-
import { Fn, vec2, vec3, vec4, float, int, sin, cos, floor, mix, smoothstep, length, cross, dot, normalize, abs, sign, dFdx, dFdy, Loop, Break, If } from 'three/tsl';
|
|
7
|
-
import {
|
|
8
|
-
import { DETAIL as D } from '../fxNumbers.js';
|
|
6
|
+
import { Fn, vec2, vec3, vec4, float, int, uint, sin, cos, floor, mix, smoothstep, length, cross, dot, normalize, abs, sign, dFdx, dFdy, Loop, Break, If } from 'three/tsl';
|
|
7
|
+
import { hashCell, hashStep, noise } from './noise.tsl.js'; // the GLSL side calls the same threedogHash / threedogNoise (#include <threedog_noise>)
|
|
8
|
+
import { DETAIL as D, hashOffset } from '../fxNumbers.js';
|
|
9
9
|
|
|
10
10
|
/** @template {string} T @typedef {import('three/webgpu').Node<T>} N */
|
|
11
11
|
// three's Loop reads `name` (the loop variable's name), but @types/three does not list it yet (a TODO there): the same Loop, typed with names
|
|
@@ -31,10 +31,12 @@ const dabs = Fn(/** @param {[N<'vec2'>, N<'float'>]} a */ ([p0, octaves]) => {
|
|
|
31
31
|
const ip = floor(p).toVar();
|
|
32
32
|
// Why named loop variables: nested Loop() calls default to `i` each, and the inner one would shadow the outer one
|
|
33
33
|
namedLoop({ start: -1, end: 1, condition: '<=', name: 'tdDj' }, { start: -1, end: 1, condition: '<=', name: 'tdDi' }, ({ tdDj, tdDi }) => {
|
|
34
|
-
|
|
35
|
-
const
|
|
36
|
-
const
|
|
37
|
-
const
|
|
34
|
+
// five hashes of whole cells k + salt, the salt added to k's first step (GLSL detail.js says why)
|
|
35
|
+
const c = ip.add(vec2(float(tdDi), float(tdDj))), [kx, ky] = hashCell(c.add(fo.mul(131))).map(n => n.toVar());
|
|
36
|
+
const salted = (/** @type {number} */ sx, /** @type {number} */ sy) => hashStep(kx.add(uint(hashOffset(sx))), ky.add(uint(hashOffset(sy))));
|
|
37
|
+
const h = vec2(hashStep(kx, ky), salted(57, 113));
|
|
38
|
+
const ang = salted(211, 37).mul(6.2832), r = salted(89, 271).mul(0.3).add(0.35);
|
|
39
|
+
const tone = salted(163, 199);
|
|
38
40
|
const d0 = p.sub(c.add(0.15).add(h.mul(0.7))), ca = cos(ang), sa = sin(ang);
|
|
39
41
|
const d = vec2(ca.mul(d0.x).add(sa.mul(d0.y)), sa.negate().mul(d0.x).add(ca.mul(d0.y))).div(vec2(r.mul(1.3), r.mul(0.75)));
|
|
40
42
|
s.assign(mix(s, tone, float(1).sub(smoothstep(0.3, 1, length(d))).mul(w)));
|
package/render/fx/index.js
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
// Import only three/tsl, three/webgpu and engine files that pull in nothing WebGL-only (effects.js registers ShaderChunks, so it stays out).
|
|
5
5
|
export * from './library.tsl.js';
|
|
6
6
|
export { uniforms } from './uniforms.tsl.js';
|
|
7
|
+
// A mesh maker, not an Fn: lists here and not in library.tsl.js, so patch code's `fx` (Fn only) does not offer it
|
|
8
|
+
export { lightShaft } from './lightShaft.tsl.js';
|
|
7
9
|
// Registers what a patch's `tsl` field does on a NodeMaterial (render/patches.js looks it up; nothing to call)
|
|
8
10
|
import './patchNodes.tsl.js';
|
|
9
11
|
// Registers the node versions of the particle / weather shaders (modules/particles and modules/weather drawing them up on WebGPURenderer)
|
|
@@ -16,8 +18,11 @@ import './sky.tsl.js';
|
|
|
16
18
|
import '../cascades.tsl.js';
|
|
17
19
|
// Registers kept shadows (engine.shadows.cache) the same way
|
|
18
20
|
import '../shadowCache.tsl.js';
|
|
19
|
-
|
|
21
|
+
// Registers impostor baking and cards for far plants (vegetation.define({ impostor }), modules/vegetation/draw.js looks it up)
|
|
22
|
+
import '../impostor.tsl.js';
|
|
23
|
+
import { WebGPURenderer, PMREMGenerator, MeshBasicNodeMaterial, RectAreaLightNode } from 'three/webgpu';
|
|
20
24
|
import { LightProbeGrid } from 'three/addons/lighting/LightProbeGrid.js';
|
|
21
25
|
import { registerWebGPUPart } from '../backend.js';
|
|
22
26
|
// createEngine({ renderer: 'webgpu' }) builds from these, so the engine core never imports three/webgpu itself (WebGL bundles stay as they are)
|
|
23
|
-
|
|
27
|
+
// RectAreaLightNode: core/scene/gameLights.js hands it three's area-light tables when the first RectAreaLight enters a scene
|
|
28
|
+
registerWebGPUPart('classes', Object.freeze({ WebGPURenderer, PMREMGenerator, MeshBasicNodeMaterial, LightProbeGrid, RectAreaLightNode }));
|
package/render/fx/library.tsl.js
CHANGED
|
@@ -8,4 +8,5 @@ export { hash, noise } from './noise.tsl.js';
|
|
|
8
8
|
export { detailNoise, detailBump } from './detail.tsl.js';
|
|
9
9
|
export { wrapDiffuse, shadowTint, rim } from './lighting.tsl.js';
|
|
10
10
|
export { celLighting } from './cel.tsl.js';
|
|
11
|
+
export { pcss } from './pcss.tsl.js';
|
|
11
12
|
export { waterWave, waterSurface, waterFresnel } from './water.tsl.js';
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// TSL lightShaft(engine, opts): a cheap beam of light you can see in the air (daylight through a ceiling hole, a window, a stage or a lighthouse beam).
|
|
2
|
+
// Research and the five questions: docs/plans/research/2026-11-10-light-shafts.md. Why a mesh and not a post effect: the shadowed ways already exist
|
|
3
|
+
// (sunShafts, lightVolumes in @threedog/post-effects/tsl, cost high); what every game rebuilt by hand was one additive cone, and its hard parts are the
|
|
4
|
+
// same in every game: sides that fade by view angle, a fade where it meets geometry (scene depth, the soft-particle trick), a fade near the camera so
|
|
5
|
+
// standing inside it does not blow the screen, scene fog that dims it instead of adding fog colour, and the tier.
|
|
6
|
+
// What it does not do: occluders do not cut it (a pillar in the beam leaves it whole); that is sunShafts / lightVolumes.
|
|
7
|
+
// It returns a plain THREE.Mesh: the game adds, moves and removes it (engine.remove frees its geometry and material; no textures are made).
|
|
8
|
+
import * as THREE from 'three/webgpu'; // three/webgpu, not three: threedog/tsl stays WebGL-free (both share three.core.js)
|
|
9
|
+
import { MeshBasicNodeMaterial } from 'three/webgpu';
|
|
10
|
+
import { Fn, If, float, vec2, vec3, vec4, abs, dot, normalize, normalView, positionView, positionWorld, positionGeometry, cameraNear, cameraFar,
|
|
11
|
+
viewportLinearDepth, output } from 'three/tsl';
|
|
12
|
+
import { codedError } from '../../core/base/errorHints.js';
|
|
13
|
+
import { readParams } from '../../core/base/params.js';
|
|
14
|
+
import { isWebGPU } from '../backend.js';
|
|
15
|
+
import { valueNode, uniforms } from './uniforms.tsl.js';
|
|
16
|
+
import { noise } from './noise.tsl.js';
|
|
17
|
+
|
|
18
|
+
const PARAMS = {
|
|
19
|
+
light: { type: 'object', optional: true, desc: 'a SpotLight (position, aim, cone width, colour) or DirectionalLight (aim, colour) to follow every frame' },
|
|
20
|
+
length: { type: 'number', optional: true, min: 0, desc: 'metres from the top (the opening) to the far end; default the spot light\'s distance, else 4' },
|
|
21
|
+
radiusTop: { type: 'number', default: 0.3, min: 0, desc: 'radius at the opening in m' },
|
|
22
|
+
radiusBottom: { type: 'number', optional: true, min: 0, desc: 'radius at the far end in m; default from the spot light\'s angle, else radiusTop' },
|
|
23
|
+
color: { type: 'any', optional: true, desc: 'beam colour; default the light\'s colour (followed live), else white' },
|
|
24
|
+
intensity: { type: 'number', default: 1, min: 0, desc: 'brightness added at the beam\'s core' },
|
|
25
|
+
softness: { type: 'number', default: 0.6, min: 0, max: 1, desc: 'how far in from the sides the fade reaches: 0 hard edge, 1 fades all the way to the centre' },
|
|
26
|
+
fallOff: { type: 'number', default: 0.5, min: 0, max: 1, desc: 'how much dimmer the far end is than the opening' },
|
|
27
|
+
fadeAtGeometry: { type: 'number', default: 0.5, min: 0, desc: 'metres over which it fades where it meets walls and floor (0 = off, and no depth read)' },
|
|
28
|
+
fadeNear: { type: 'number', default: 1, min: 0, desc: 'metres in front of the camera over which it fades out' },
|
|
29
|
+
dust: { type: 'number', default: 0, min: 0, max: 1, desc: 'how much drifting dust patterns the beam (0 = even beam)' },
|
|
30
|
+
dustScale: { type: 'number', default: 2, min: 0, desc: 'dust pattern size: higher = finer' },
|
|
31
|
+
dustSpeed: { type: 'number', default: 0.3, desc: 'how fast the dust drifts down the beam, m/s' },
|
|
32
|
+
segments: { type: 'int', default: 24, min: 3, desc: 'sides of the cone' },
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const _p = new THREE.Vector3(), _t = new THREE.Vector3(), _q = new THREE.Quaternion(), _pq = new THREE.Quaternion(), DOWN = new THREE.Vector3(0, -1, 0);
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* A light shaft: an open cone, top (the opening) at the mesh origin, pointing down its -Y axis. WebGPURenderer only (its WebGPU and WebGL2 backends).
|
|
39
|
+
* @param {any} engine
|
|
40
|
+
* @param {Record<string, any>} [opts] see PARAMS above (types/tsl.d.ts LightShaftOptions)
|
|
41
|
+
* @returns {THREE.Mesh & { shaft: Record<string, { value: any }> }}
|
|
42
|
+
*/
|
|
43
|
+
export function lightShaft(engine, opts = {}) {
|
|
44
|
+
// refused, not silently blank: WebGLRenderer cannot draw a node material at all
|
|
45
|
+
if (!isWebGPU(engine?.renderer)) throw codedError('tsl-misuse', 'threedog/tsl lightShaft(engine, ...): needs the engine on WebGPURenderer (its node material does not draw on WebGLRenderer). A WebGL game: the depth haze of recipe 59, or its own additive cone');
|
|
46
|
+
const o = /** @type {any} */ (readParams('lightShaft', PARAMS, opts)); // values checked against PARAMS, defaults filled
|
|
47
|
+
const light = o.light ?? null;
|
|
48
|
+
if (light && !light.isSpotLight && !light.isDirectionalLight) throw codedError('tsl-misuse', `threedog/tsl lightShaft({ light }): a SpotLight or DirectionalLight (got ${light.type ?? typeof light})`);
|
|
49
|
+
const length = o.length ?? (light?.isSpotLight && light.distance > 0 ? light.distance : 4);
|
|
50
|
+
const radiusBottom = o.radiusBottom ?? (light?.isSpotLight ? Math.tan(light.angle) * length : o.radiusTop);
|
|
51
|
+
|
|
52
|
+
// the game's numbers, as { value } objects it writes later (beam.shaft.intensity.value = 2); valueNode reads them every render (uniforms.tsl.js says why not uniform())
|
|
53
|
+
const color = o.color != null ? new THREE.Color(o.color) : light ? light.color : new THREE.Color(1, 1, 1);
|
|
54
|
+
const S = { color: { value: color }, intensity: { value: o.intensity }, softness: { value: o.softness }, fallOff: { value: o.fallOff },
|
|
55
|
+
fadeAtGeometry: { value: o.fadeAtGeometry }, fadeNear: { value: o.fadeNear }, dust: { value: o.dust }, dustScale: { value: o.dustScale }, dustSpeed: { value: o.dustSpeed } };
|
|
56
|
+
// dust on: the game's dust and not low tier, so the noise branch is skipped on the GPU (a uniform branch, not a multiply by 0). Worked out where the
|
|
57
|
+
// uniform is read (every render): no per-frame writer to keep in step, and a tier change is followed on the next frame without a rebuild
|
|
58
|
+
const dustOn = { get value() { return S.dust.value > 0 && engine.tier !== 'low' ? 1 : 0; } };
|
|
59
|
+
const U = Object.fromEntries(Object.entries(S).map(([k, v]) => [k, valueNode(v)]));
|
|
60
|
+
const uDustOn = valueNode(dustOn), uTime = uniforms(engine).uTime; // engine time: pause and slow motion hold the dust too
|
|
61
|
+
|
|
62
|
+
const geometry = new THREE.CylinderGeometry(o.radiusTop, radiusBottom, length, o.segments, 1, true).translate(0, -length / 2, 0);
|
|
63
|
+
// additive, unlit, no depth write: it adds light to what is behind and never hides it. Both sides: from inside the cone the far wall still shows.
|
|
64
|
+
const material = new MeshBasicNodeMaterial({ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, side: THREE.DoubleSide });
|
|
65
|
+
const depthFade = o.fadeAtGeometry > 0; // 0 at creation: no depth read, so a scene with no other depth reader skips three's depth copy
|
|
66
|
+
material.colorNode = Fn(() => {
|
|
67
|
+
// sides: |n . v| is 1 face-on and 0 at the silhouette; curved (smoothstep shape) because the straight value looks solid face-on (research note)
|
|
68
|
+
const facing = abs(dot(normalize(normalView), normalize(positionView.negate())));
|
|
69
|
+
const e = facing.div(U.softness.max(0.001)).clamp(), edge = e.mul(e).mul(e.mul(-2).add(3));
|
|
70
|
+
const along = positionGeometry.y.negate().div(length).clamp(); // 0 at the opening, 1 at the far end
|
|
71
|
+
// the first 5% of the length fades in: a beam hanging free (a stage light) shows no hard ring at its opening (seen in the first shot); at a ceiling hole the ceiling's depth fade does the same
|
|
72
|
+
const a = edge.mul(float(1).sub(U.fallOff.mul(along))).mul(along.div(0.05).clamp()).mul(U.intensity).toVar();
|
|
73
|
+
const dist = positionView.z.negate();
|
|
74
|
+
a.mulAssign(dist.sub(cameraNear).div(U.fadeNear.max(0.001)).clamp());
|
|
75
|
+
if (depthFade) {
|
|
76
|
+
// metres between the beam and what is drawn behind it: the same read as soft particles (render/fx/particles.tsl.js), one depth copy per render shared by both
|
|
77
|
+
const gap = viewportLinearDepth.mul(cameraFar.sub(cameraNear)).add(cameraNear).sub(dist);
|
|
78
|
+
a.mulAssign(gap.div(U.fadeAtGeometry.max(0.001)).clamp());
|
|
79
|
+
}
|
|
80
|
+
If(uDustOn.greaterThan(0.5), () => {
|
|
81
|
+
// streaks along the beam that drift down it: noise stretched 4x along the axis, scrolled by engine time
|
|
82
|
+
const p = positionWorld.mul(U.dustScale), n = noise(vec2(p.x.add(p.z.mul(0.7)), p.y.mul(0.25).add(uTime.mul(U.dustSpeed).mul(U.dustScale).mul(0.25))));
|
|
83
|
+
a.mulAssign(float(1).sub(U.dust).add(U.dust.mul(n).mul(2)).max(0));
|
|
84
|
+
});
|
|
85
|
+
return vec4(vec3(U.color).mul(a), 1);
|
|
86
|
+
})();
|
|
87
|
+
// Fog dims the beam: three's fog mixes the output toward the fog colour, which under additive blending ADDS fog colour (a glowing haze where the beam
|
|
88
|
+
// should fade). The fog node is fog(color, factor) for scene.fog and for the engine's documented scene.fogNode (render/fogLook.js reads it the same way),
|
|
89
|
+
// so its factor is rawInputs[1]: the beam is scaled by 1 - factor. A fog node built otherwise has no factor to read: the beam then draws unfogged.
|
|
90
|
+
/** @type {any} */ (material).setupFog = (/** @type {any} */ builder, /** @type {any} */ outputNode) => {
|
|
91
|
+
const factor = builder.fogNode?.rawInputs?.[1];
|
|
92
|
+
if (!factor) return outputNode;
|
|
93
|
+
output.assign(outputNode);
|
|
94
|
+
return vec4(output.rgb.mul(float(1).sub(factor.toFloat())), output.a);
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
const mesh = /** @type {THREE.Mesh & { shaft: typeof S }} */ (/** @type {unknown} */ (new THREE.Mesh(geometry, material)));
|
|
98
|
+
mesh.name = 'lightShaft';
|
|
99
|
+
mesh.shaft = S;
|
|
100
|
+
mesh.castShadow = mesh.receiveShadow = false;
|
|
101
|
+
if (!light) return mesh;
|
|
102
|
+
mesh.frustumCulled = false; // it moves in onBeforeRender, after culling: a stale box must not cull it for good
|
|
103
|
+
mesh.onBeforeRender = () => {
|
|
104
|
+
// follow the light: a spot light gives position and aim, a directional light only the aim (the game places the opening, e.g. at the hole)
|
|
105
|
+
light.updateMatrixWorld(); light.target.updateMatrixWorld();
|
|
106
|
+
light.getWorldPosition(_p); light.target.getWorldPosition(_t);
|
|
107
|
+
_q.setFromUnitVectors(DOWN, _t.sub(_p).normalize());
|
|
108
|
+
if (light.isSpotLight) { mesh.position.copy(_p); mesh.parent?.worldToLocal(mesh.position); }
|
|
109
|
+
if (mesh.parent) _q.premultiply(mesh.parent.getWorldQuaternion(_pq).invert());
|
|
110
|
+
mesh.quaternion.copy(_q);
|
|
111
|
+
mesh.updateMatrixWorld();
|
|
112
|
+
};
|
|
113
|
+
return mesh;
|
|
114
|
+
}
|
package/render/fx/noise.tsl.js
CHANGED
|
@@ -1,12 +1,29 @@
|
|
|
1
1
|
// TSL hash() / noise() (GLSL NOISE_GLSL).
|
|
2
|
-
// TSL value noise: hash(vec2) / noise(vec2), line for line NOISE_GLSL (render/effects.js
|
|
3
|
-
import { Fn, vec2,
|
|
2
|
+
// TSL value noise: hash(vec2) / noise(vec2), line for line NOISE_GLSL (render/effects.js threedogHashCell / Step / Hash / Noise).
|
|
3
|
+
import { Fn, vec2, uint, fract, floor, mix, floatBitsToUint } from 'three/tsl';
|
|
4
4
|
import { HASH } from '../fxNumbers.js';
|
|
5
5
|
|
|
6
|
-
/**
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
6
|
+
/** @template {string} T @typedef {import('three/webgpu').Node<T>} N */
|
|
7
|
+
const M = uint(HASH.mul);
|
|
8
|
+
/** threedogHashCell: the cell floor(p)'s first pcg2d step, as two uints [x, y]. float -> int -> uint: a negative float cast straight to
|
|
9
|
+
* uint clamps to 0 in WGSL, int -> uint keeps the bits on both backends @param {N<'vec2'>} p @returns {[N<'uint'>, N<'uint'>]} */
|
|
10
|
+
export const hashCell = p => { const c = floor(p); return [c.x.toInt().toUint().mul(M).add(uint(HASH.add)), c.y.toInt().toUint().mul(M).add(uint(HASH.add))]; };
|
|
11
|
+
/** threedogHashStep: the rest of pcg2d's x from a first step, 0 <= value < 1 */
|
|
12
|
+
export const hashStep = Fn(/** @param {[N<'uint'>, N<'uint'>]} a */ ([x0, y0]) => {
|
|
13
|
+
const x = uint(x0).toVar(), y = uint(y0).toVar();
|
|
14
|
+
x.addAssign(y.mul(M)); y.addAssign(x.mul(M));
|
|
15
|
+
x.assign(x.bitXor(x.shiftRight(16))); y.assign(y.bitXor(y.shiftRight(16)));
|
|
16
|
+
x.addAssign(y.mul(M));
|
|
17
|
+
return x.bitXor(x.shiftRight(16)).shiftRight(8).toFloat().mul(1 / 2 ** 24);
|
|
18
|
+
});
|
|
19
|
+
/** threedogHash: pcg2d of p's float bits, any vec2, 0 <= value < 1 (fxNumbers.js HASH says why integers, effects.js why two ways in) */
|
|
20
|
+
export const hash = Fn(/** @param {[N<'vec2'>]} a */ ([p]) => {
|
|
21
|
+
const b = /** @type {N<'uvec2'>} */ (/** @type {unknown} */ (floatBitsToUint(vec2(p)))); // @types/three types bitcast as its node class
|
|
22
|
+
const fold = (/** @type {N<'uint'>} */ v) => v.bitXor(v.shiftRight(16)).mul(M).add(uint(HASH.add)); // GLSL b ^= b >> 16 says why
|
|
23
|
+
return hashStep(fold(b.x), fold(b.y));
|
|
24
|
+
});
|
|
25
|
+
/** threedogNoise: smooth value noise, 0-1; the neighbor cells' first steps are the cell's plus mul (no second conversion) */
|
|
26
|
+
export const noise = Fn(/** @param {[N<'vec2'>]} a */ ([p]) => {
|
|
27
|
+
const [x, y] = hashCell(p).map(n => n.toVar()), x1 = x.add(M), y1 = y.add(M), f0 = fract(p), f = f0.mul(f0).mul(f0.mul(-2).add(3));
|
|
28
|
+
return mix(mix(hashStep(x, y), hashStep(x1, y), f.x), mix(hashStep(x, y1), hashStep(x1, y1), f.x), f.y);
|
|
12
29
|
});
|
|
@@ -1,18 +1,43 @@
|
|
|
1
|
-
// TSL objectOrigin(): object / instance world origin.
|
|
2
1
|
// TSL objectOrigin(): world origin of the drawn object / instance (the `ip` of GLSL threedog_wind_vertex).
|
|
3
2
|
// GLSL version: modelMatrix * instanceMatrix * vec4(0,0,0,1). three has no public instance-matrix node; the first experiment wrapped mesh.instanceMatrix
|
|
4
|
-
// in a second instanced attribute, which tied the material to one mesh.
|
|
5
|
-
//
|
|
3
|
+
// in a second instanced attribute, which tied the material to one mesh. Like three's own instancing (referenceAttribute('instanceMatrix')), the columns here
|
|
4
|
+
// are read from the object being drawn at build time, each object binding its own, so several InstancedMeshes can share one material.
|
|
5
|
+
// Why columns, and one node per column for the whole page: every vertex input counts against the device's 16 (WebGPU maxVertexAttributes, WebGL2
|
|
6
|
+
// MAX_VERTEX_ATTRIBS), and three's instancing already spends 4 on the matrix, temporalAA's velocity 4 more on last frame's. A fresh mat4 attribute per call
|
|
7
|
+
// cost 4 inputs each time, so wind and the near fade on grass with temporalAA needed 21. Now the origin is column 3 alone (instanceMatrix * (0,0,0,1) is
|
|
8
|
+
// exactly that column), and every call in a program shares it: one input for the origin, 4 at most with instanceOffset(). The column views the same GPU
|
|
9
|
+
// buffer as three's matrix, so no vertex buffer is added.
|
|
6
10
|
// three takes this path only while vertex buffers suffice (Instance.js canReferenceInstanceData, 8-buffer limit); otherwise it compiles per mesh,
|
|
7
11
|
// which would mean copying three's private logic, so that case throws by name. BatchedMesh's batch matrices are also private to three: same error.
|
|
8
12
|
import { Fn, vec4, mat3, modelWorldMatrix, referenceAttribute } from 'three/tsl';
|
|
13
|
+
import { ReferenceAttributeNode, InterleavedBufferAttribute } from 'three/webgpu'; // three/webgpu, not three: threedog/tsl stays WebGL-free (both share three.core.js)
|
|
9
14
|
import { codedError } from '../../core/base/errorHints.js';
|
|
10
15
|
|
|
11
16
|
const MAX_VERTEX_BUFFERS = 8; // three/src/nodes/accessors/Instance.js (same constant, same test)
|
|
17
|
+
/** what render/vertexInputs.js names these inputs in a vertex-input error */
|
|
18
|
+
const LABEL = 'the instance origin of threedog/tsl objectOrigin() / instanceOffset() (engine wind, near fade)';
|
|
19
|
+
|
|
20
|
+
const VIEWS = new WeakMap(); // instanceMatrix -> its column views, made as three makes its own (ReferenceAttributeNode.js getAttributeColumn)
|
|
21
|
+
/** One column (vec4) of the drawn InstancedMesh's instanceMatrix, bound per object like three's referenceAttribute */
|
|
22
|
+
class InstanceColumn extends ReferenceAttributeNode {
|
|
23
|
+
/** @param {number} column 0..3 */
|
|
24
|
+
constructor(column) { super('instanceMatrix', 'vec4'); this.column = column; this.threedogLabel = LABEL; }
|
|
25
|
+
/** @param {any} object */
|
|
26
|
+
getValueFromReference(object) {
|
|
27
|
+
const m = object?.instanceMatrix;
|
|
28
|
+
if (!m) return m;
|
|
29
|
+
let v = VIEWS.get(m);
|
|
30
|
+
if (!v) VIEWS.set(m, v = []);
|
|
31
|
+
return v[this.column] ??= new InterleavedBufferAttribute(m, 4, this.column * 4);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
// one node per column for every program: three keeps a node's build data per builder, so all calls in one program read one input each
|
|
35
|
+
const COLUMNS = [0, 1, 2, 3].map(i => /** @type {any} */ (new InstanceColumn(i)));
|
|
12
36
|
|
|
13
37
|
/**
|
|
14
|
-
* The
|
|
15
|
-
*
|
|
38
|
+
* The columns of the object being built's instance matrix, null when it is not instanced (throws for what three binds privately).
|
|
39
|
+
* A storage matrix is read whole: storage reads cost no vertex input.
|
|
40
|
+
* @param {any} builder @returns {{ column: (i: number) => import('three/webgpu').Node<'vec4'> } | null}
|
|
16
41
|
*/
|
|
17
42
|
function instanceMatrixOf(builder) {
|
|
18
43
|
const o = builder.object;
|
|
@@ -21,14 +46,18 @@ function instanceMatrixOf(builder) {
|
|
|
21
46
|
const buffers = 1 + (o.instanceColor !== null ? 1 : 0) + (builder.needsPreviousData() ? 1 : 0);
|
|
22
47
|
if (builder.renderer?.isRenderer !== true || Object.keys(o.geometry.attributes).length + buffers > MAX_VERTEX_BUFFERS)
|
|
23
48
|
throw codedError('tsl-misuse', `threedog/tsl objectOrigin(): InstancedMesh '${o.name || o.uuid}' has too many vertex attributes for a shared instance matrix`);
|
|
24
|
-
|
|
25
|
-
|
|
49
|
+
if (o.instanceMatrix.isStorageInstancedBufferAttribute) {
|
|
50
|
+
// @types/three types referenceAttribute() as a bare ReferenceAttributeNode (no node type, no operators); with 'mat4' it is a mat4 node
|
|
51
|
+
const m = /** @type {any} */ (referenceAttribute('instanceMatrix', 'mat4'));
|
|
52
|
+
return { column: i => m.element(i) };
|
|
53
|
+
}
|
|
54
|
+
return { column: i => COLUMNS[i] };
|
|
26
55
|
}
|
|
27
56
|
|
|
28
57
|
/** World position of the object's (or instance's) origin, vec3 */
|
|
29
58
|
export const objectOrigin = Fn((_, builder) => {
|
|
30
|
-
const m = instanceMatrixOf(builder)
|
|
31
|
-
return modelWorldMatrix.mul(m ? m.
|
|
59
|
+
const m = instanceMatrixOf(builder);
|
|
60
|
+
return modelWorldMatrix.mul(m ? m.column(3) : vec4(0, 0, 0, 1)).xyz;
|
|
32
61
|
});
|
|
33
62
|
|
|
34
63
|
/**
|
|
@@ -37,5 +66,5 @@ export const objectOrigin = Fn((_, builder) => {
|
|
|
37
66
|
*/
|
|
38
67
|
export const instanceOffset = Fn(/** @param {[import('three/webgpu').Node<'vec3'>]} a @param {any} builder */ ([v], builder) => {
|
|
39
68
|
const m = instanceMatrixOf(builder);
|
|
40
|
-
return m ? mat3(m).mul(v) : v;
|
|
69
|
+
return m ? mat3(m.column(0).xyz, m.column(1).xyz, m.column(2).xyz).mul(v) : v;
|
|
41
70
|
});
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
// Same numbers as GLSL: the modules keep their { value } uniform objects (game and engine code writes .value on either renderer) and the nodes read them
|
|
8
8
|
// back each render; sizes are device pixels like gl_PointSize (sizeNode is in CSS pixels, so it is divided by the pixel ratio), sprite uv is
|
|
9
9
|
// flipped to gl_PointCoord's y-down so textures and rotation land the same way.
|
|
10
|
-
// Fog: the node material's own fog (mixed before the output transform
|
|
10
|
+
// Fog: particles and weather use the node material's own fog (the weather GLSL has the same fog chunks: rain and snow fade into fog on both backends). It is mixed before the output transform. The GLSL mixes fog after its tone-mapping / color-space chunks, which
|
|
11
11
|
// only matters straight on the canvas: in a linear target (every frame with post on) those chunks do nothing and both match (fog parity in
|
|
12
12
|
// tests/specs/fx-particles.mjs, mean within 0.01%). On the canvas WebGPU differs anyway for every material: it blends and fogs in its linear
|
|
13
13
|
// frame buffer, WebGL on the encoded canvas (9-15% on the test puff, as much without fog), and three's own WebGL materials fog in that same
|
|
@@ -18,7 +18,7 @@ import { Sprite, PointsNodeMaterial, LineBasicNodeMaterial, InstancedBufferAttri
|
|
|
18
18
|
import { valueNode } from './uniforms.tsl.js';
|
|
19
19
|
import { registerWebGPUPart } from '../backend.js';
|
|
20
20
|
|
|
21
|
-
const { Fn, texture, instancedDynamicBufferAttribute, attribute, varying, positionGeometry, modelViewMatrix, screenDPR, uv, viewportLinearDepth, cameraNear, cameraFar,
|
|
21
|
+
const { Fn, texture, cameraProjectionMatrix, instancedDynamicBufferAttribute, attribute, varying, positionGeometry, modelViewMatrix, screenDPR, uv, viewportLinearDepth, cameraNear, cameraFar,
|
|
22
22
|
float, vec2, vec3, vec4, select, min, max, cos, sin, mod, smoothstep, step, dot, length, If, Discard } = TSL;
|
|
23
23
|
|
|
24
24
|
/** @template {string} T @typedef {import('three/webgpu').Node<T>} N */
|
|
@@ -49,10 +49,25 @@ function nodesOf(u) {
|
|
|
49
49
|
// sRGB like the textures games load, so swapping in a real one does not change the colour conversion the node was built with
|
|
50
50
|
const white = () => { const t = new DataTexture(new Uint8Array([255, 255, 255, 255]), 1, 1); t.colorSpace = SRGBColorSpace; t.needsUpdate = true; return t; };
|
|
51
51
|
|
|
52
|
-
/**
|
|
52
|
+
/**
|
|
53
|
+
* uniforms.uMap as a texture node: writing .value swaps the texture and rebuilds the material (the GLSL side just swaps the sampler).
|
|
54
|
+
* The white stand-in for "no texture" is the slot's own (made here, so freed here): disposed when a real texture replaces it and with the material.
|
|
55
|
+
* A texture the game passes in stays the game's. `.own` is true while the stand-in is drawn: a copy of these values (weather's rebuild) skips it,
|
|
56
|
+
* since the stand-in is freed with this material and a new slot would take it for the game's
|
|
57
|
+
*/
|
|
53
58
|
function mapSlot(u, mat) {
|
|
54
|
-
|
|
55
|
-
|
|
59
|
+
let own = null;
|
|
60
|
+
const blank = () => (own ??= white());
|
|
61
|
+
const node = texture(u.uMap?.value || blank());
|
|
62
|
+
u.uMap = { get own() { return !!own && node.value === own; }, get value() { return node.value; }, set value(t) {
|
|
63
|
+
const old = own;
|
|
64
|
+
if (t) own = null;
|
|
65
|
+
node.value = t || blank();
|
|
66
|
+
if (old && old !== node.value) old.dispose();
|
|
67
|
+
mat.needsUpdate = true;
|
|
68
|
+
} };
|
|
69
|
+
// own stays named after the dispose: a copy made after the old system is dropped (weather's rebuild) still sees it is not the game's
|
|
70
|
+
mat.addEventListener('dispose', () => own?.dispose());
|
|
56
71
|
return node;
|
|
57
72
|
}
|
|
58
73
|
|
|
@@ -77,8 +92,10 @@ function particles({ attrs, count, fog, additive, maxPixels, soft }) {
|
|
|
77
92
|
const pos = at(attrs.aPos, 'vec3'), size = at(attrs.aSize, 'float'), alpha = at(attrs.aAlpha, 'float');
|
|
78
93
|
m.positionNode = pos;
|
|
79
94
|
const z = modelViewMatrix.mul(vec4(pos, 1)).z;
|
|
95
|
+
// an orthographic camera (projection [2][3] is 0, -1 for perspective; the test the GLSL isOrthographic makes) has no shrink with distance: uScale is pixels per meter
|
|
96
|
+
const dist = select(/** @type {any} */ (cameraProjectionMatrix).element(2).element(3).lessThan(-0.5), max(0.1, z.negate()), float(1));
|
|
80
97
|
m.sizeNode = Fn(() => {
|
|
81
|
-
return select(alpha.lessThanEqual(0), float(0), min(size.mul(U.uScale).div(
|
|
98
|
+
return select(alpha.lessThanEqual(0), float(0), min(size.mul(U.uScale).div(dist), U.uMaxPx)).div(screenDPR);
|
|
82
99
|
})();
|
|
83
100
|
// meters between the particle and what is drawn behind it; viewportLinearDepth is three's one copy of the depth buffer per render, shared by every effect that reads it
|
|
84
101
|
const gap = soft ? viewportLinearDepth.mul(cameraFar.sub(cameraNear)).add(cameraNear).add(varying(z)) : null;
|
|
@@ -29,6 +29,7 @@ import { registerWebGPUPart } from '../backend.js';
|
|
|
29
29
|
import { engineUniformName } from '../engineUniforms.js';
|
|
30
30
|
import { SLOTS, LIGHT_HOOKS as HOOKS } from '../slots.js';
|
|
31
31
|
import { notePatch } from '../../core/scene/threePatches.js';
|
|
32
|
+
const WRAPPED = Symbol.for('threedog.patchWrapper'); // the same key as render/patches.js WRAPPED (a registry symbol, so this WebGL-free file need not import it)
|
|
32
33
|
import { nameNodeBuild, lostStatements } from './nodeErrors.tsl.js';
|
|
33
34
|
|
|
34
35
|
const { Fn, positionLocal, modelViewProjection, materialColor, materialRoughness, materialEmissive, materialNormal, diffuseColor, vec3 } = TSL;
|
|
@@ -69,7 +70,10 @@ const PROPS = Object.fromEntries(Object.entries(SLOTS).filter(([, s]) => s.node?
|
|
|
69
70
|
return [n, [s.node.prop, DEFAULTS[s.node.prop]]];
|
|
70
71
|
}));
|
|
71
72
|
// position chains, by their stand-in node: what setupPosition runs before three's morph / skinning / instancing steps
|
|
72
|
-
|
|
73
|
+
// The registry lives on the shared wrapper below (a second copy of this module, hot reload or another URL, finds the first copy's wrapper and must fill the same map)
|
|
74
|
+
const setupPosition = NodeMaterial.prototype.setupPosition;
|
|
75
|
+
/** @type {WeakMap<object, any>} */
|
|
76
|
+
const PRE = /** @type {any} */ (setupPosition)._threedogPre ?? new WeakMap();
|
|
73
77
|
/**
|
|
74
78
|
* The stand-in for a position chain: evaluates to the game's own value (or positionLocal, i.e. leaves three's result as it is) where three
|
|
75
79
|
* applies positionNode, while the chain itself runs at the start of setupPosition. Its cache key is the chain's, so a different chain is a
|
|
@@ -83,13 +87,12 @@ function preMarker(chain, base) {
|
|
|
83
87
|
}
|
|
84
88
|
// Why the prototype and not each material: three's shadow pass draws with its own NodeMaterial, handed our positionNode / castShadowPositionNode
|
|
85
89
|
// (Renderer._getShadowNodes), and the shadow must sway exactly like the surface. Only materials carrying one of our stand-ins are affected.
|
|
86
|
-
|
|
87
|
-
if (!(/** @type {{ _threedogPre?: boolean }} */ (/** @type {unknown} */ (setupPosition)))._threedogPre) { // already wrapped (module loaded twice)
|
|
90
|
+
if (!(/** @type {any} */ (setupPosition))._threedogPre) { // already wrapped (module loaded twice)
|
|
88
91
|
NodeMaterial.prototype.setupPosition = Object.assign(function (builder) {
|
|
89
92
|
const chain = PRE.get(this.positionNode);
|
|
90
93
|
if (chain) positionLocal.assign(TSL.subBuild(chain, 'POSITION', 'vec3'));
|
|
91
94
|
return setupPosition.call(this, builder);
|
|
92
|
-
}, { _threedogPre:
|
|
95
|
+
}, { _threedogPre: PRE });
|
|
93
96
|
notePatch('node-setup-position', 'NodeMaterial.prototype.setupPosition: runs the vertex-moving patch chain before three builds the position (WebGPU wind and its shadow)',
|
|
94
97
|
() => { NodeMaterial.prototype.setupPosition = setupPosition; }, { lost: 'on WebGPURenderer, wind and other vertex-moving patches no longer move vertices or their shadow' });
|
|
95
98
|
}
|
|
@@ -181,14 +184,16 @@ function accessors(target, st, enumerable) {
|
|
|
181
184
|
}
|
|
182
185
|
}
|
|
183
186
|
|
|
187
|
+
/** fn, marked as the engine's wrapper of inner (the game's own method or three's): cloneMaterial carries inner, never fn, which runs this material's st */
|
|
188
|
+
const wrapper = (fn, inner) => Object.assign(fn, { [WRAPPED]: () => inner });
|
|
184
189
|
/** Wrap three's setup methods of the NodeMaterial m (a patched one, or a classic material's node twin) to run st's color / normal / output / lighting code */
|
|
185
190
|
function wrapSetup(m, st, src) {
|
|
186
191
|
const ctx = extra => ({ fx: FX, tsl: TSL, material: src, ...extra });
|
|
187
192
|
const diffuse = m.setupDiffuseColor, normal = m.setupNormal, output = m.setupOutput, model = m.setupLightingModel;
|
|
188
|
-
m.setupDiffuseColor = function (builder) { const r = diffuse.call(this, builder); if (st.color) diffuseColor.assign(st.color); return r; };
|
|
189
|
-
m.setupNormal = function (builder) { return chain(st.list, 'normal', normal.call(this, builder), ctx({ builder })); };
|
|
190
|
-
m.setupOutput = function (builder, node) { return output.call(this, builder, chain(st.list, 'output', node, ctx({ builder }))); };
|
|
191
|
-
m.setupLightingModel = function (builder) {
|
|
193
|
+
m.setupDiffuseColor = wrapper(function (builder) { const r = diffuse.call(this, builder); if (st.color) diffuseColor.assign(st.color); return r; }, diffuse);
|
|
194
|
+
m.setupNormal = wrapper(function (builder) { return chain(st.list, 'normal', normal.call(this, builder), ctx({ builder })); }, normal);
|
|
195
|
+
m.setupOutput = wrapper(function (builder, node) { return output.call(this, builder, chain(st.list, 'output', node, ctx({ builder }))); }, output);
|
|
196
|
+
m.setupLightingModel = wrapper(function (builder) {
|
|
192
197
|
const lm = model.call(this, builder);
|
|
193
198
|
const hooks = st.list.filter(p => codeOf(p, 'lighting')).map(p => [p, hooksOf(codeOf(p, 'lighting'))]);
|
|
194
199
|
if (!lm || !hooks.length) return lm;
|
|
@@ -232,7 +237,7 @@ function wrapSetup(m, st, src) {
|
|
|
232
237
|
return r;
|
|
233
238
|
};
|
|
234
239
|
return lm;
|
|
235
|
-
};
|
|
240
|
+
}, model);
|
|
236
241
|
}
|
|
237
242
|
|
|
238
243
|
/** Install the accessors and method wrappers once on a NodeMaterial patched directly */
|
|
@@ -244,14 +249,14 @@ function install(m) {
|
|
|
244
249
|
// clone() carries no patches (as on the GLSL side, where Material.copy skips onBeforeCompile): the copy gets the game's own values, not the
|
|
245
250
|
// chains, so a clone without copyPatches is the plain material and one with copyPatches has each effect once
|
|
246
251
|
const clone = m.clone, key = m.customProgramCacheKey;
|
|
247
|
-
m.clone = function () {
|
|
252
|
+
m.clone = wrapper(function () {
|
|
248
253
|
const c = clone.call(this);
|
|
249
254
|
for (const [prop] of Object.values(PROPS)) if (c[prop] === st.out[prop]) c[prop] = st.own[prop];
|
|
250
255
|
return c;
|
|
251
|
-
};
|
|
256
|
+
}, clone);
|
|
252
257
|
// three keys NodeMaterial programs by their node properties only; code added inside the setup methods is not one, so two materials
|
|
253
258
|
// differing only in a color / normal / output / lighting patch would share a program. st.key is built from those patches' node graphs
|
|
254
|
-
m.customProgramCacheKey = function () { return key.call(this) + (st.key ? '|threedog:' + st.key : ''); };
|
|
259
|
+
m.customProgramCacheKey = wrapper(function () { return key.call(this) + (st.key ? '|threedog:' + st.key : ''); }, key);
|
|
255
260
|
return st;
|
|
256
261
|
}
|
|
257
262
|
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// TSL pcss(): a shadow filter whose edge softens with the distance from caster to receiver (percentage-closer soft shadows), for light.shadow.filterNode.
|
|
2
|
+
// The game assigns it; the engine never does: light.shadow.filterNode = pcss({ lightSize: 0.04 }).
|
|
3
|
+
// Why comparisons only, with no raw depth read: the shadow map keeps three's compare sampler, which WebGL2 refuses to read as plain depth
|
|
4
|
+
// (a sampler type that disagrees with the texture's compare mode fails the draw) and which sunShafts reads too. So the blocker search asks
|
|
5
|
+
// "is a caster at least t nearer the light here?" at four depths t and adds the answers up: the area under that curve is the average distance.
|
|
6
|
+
// Each t is jittered inside its band (per tap and pixel), so on average the estimate is continuous: a sloped caster's edge widens smoothly, not in four steps.
|
|
7
|
+
// Directional lights only (orthographic shadow cameras, the engine's cascades included): depth there is linear, so a depth step is a world distance.
|
|
8
|
+
import { Fn, Loop, float, texture, reference, screenCoordinate, interleavedGradientNoise, vogelDiskSample, max, min } from 'three/tsl';
|
|
9
|
+
import { codedError } from '../../core/base/errorHints.js';
|
|
10
|
+
|
|
11
|
+
/** @typedef {import('three/webgpu').Node} N */
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @param {{ lightSize?: number, samples?: number, maxDistance?: number }} [o]
|
|
15
|
+
* lightSize: how wide the edge grows per world unit between caster and receiver (the sun is about 0.01, a hazy sky 0.05);
|
|
16
|
+
* samples: taps of the final filter (the search takes half, at least 4); maxDistance: world units from caster to receiver beyond which the edge stops growing.
|
|
17
|
+
* @returns {any} a filter for light.shadow.filterNode
|
|
18
|
+
*/
|
|
19
|
+
export function pcss({ lightSize = 0.04, samples = 16, maxDistance = 4 } = {}) {
|
|
20
|
+
if (!(lightSize >= 0 && samples >= 1 && maxDistance > 0)) throw codedError('tsl-misuse', `threedog/tsl pcss(): lightSize >= 0, samples >= 1 and maxDistance > 0 (got ${lightSize}, ${samples}, ${maxDistance})`);
|
|
21
|
+
const taps = Math.round(samples), search = Math.max(4, taps >> 1);
|
|
22
|
+
// depths asked in the search, squared steps so a caster close to its receiver (the hard part) is told apart finely
|
|
23
|
+
const steps = [1, 2, 3, 4].map(k => maxDistance * (k / 4) ** 2);
|
|
24
|
+
return Fn(/** @param {any} a @param {any} builder */ ({ depthTexture, shadowCoord, shadow, depthLayer }, builder) => {
|
|
25
|
+
const cam = shadow.camera;
|
|
26
|
+
if (!cam.isOrthographicCamera) throw codedError('tsl-misuse', 'threedog/tsl pcss(): only for a DirectionalLight (an orthographic shadow camera); a spot or point light keeps three\'s filter');
|
|
27
|
+
const lit = (/** @type {N} */ uv, /** @type {any} */ z) => { let d = /** @type {any} */ (texture(depthTexture, uv)); if (depthTexture.isArrayTexture) d = d.depth(depthLayer); return d.compare(z); };
|
|
28
|
+
// per world unit, in shadow-map depth (0 at near, 1 at far, flipped with a reversed depth buffer) and in shadow-map uv (the camera's width)
|
|
29
|
+
const perUnit = float(builder.renderer.reversedDepthBuffer ? -1 : 1).div(reference('far', 'float', cam).sub(reference('near', 'float', cam)));
|
|
30
|
+
const width = reference('right', 'float', cam).sub(reference('left', 'float', cam)).div(reference('zoom', 'float', cam));
|
|
31
|
+
const texel = float(1).div(reference('mapSize', 'vec2', shadow).x);
|
|
32
|
+
const ign = interleavedGradientNoise(screenCoordinate.xy), phi = ign.mul(6.283185307);
|
|
33
|
+
// blocker search over the widest edge that can occur here
|
|
34
|
+
const blocked = float(0).toVar(), gap = float(0).toVar();
|
|
35
|
+
const reach = float(lightSize * maxDistance).div(width).max(texel);
|
|
36
|
+
Loop(search, ({ i }) => {
|
|
37
|
+
const uv = shadowCoord.xy.add(vogelDiskSample(i, search, phi).mul(reach));
|
|
38
|
+
blocked.addAssign(lit(uv, shadowCoord.z).oneMinus());
|
|
39
|
+
for (let k = 0; k < 4; k++) {
|
|
40
|
+
const from = steps[k - 1] ?? 0, band = steps[k] - from, u = ign.add(float(i).mul(4).add(k).mul(0.618034)).fract();
|
|
41
|
+
gap.addAssign(lit(uv, shadowCoord.z.sub(perUnit.mul(u.mul(band).add(from)))).oneMinus().mul(band));
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
const distance = gap.div(max(blocked, 1e-4));
|
|
45
|
+
// edge width in shadow-map uv, never under one texel; then plain percentage-closer filtering at that width
|
|
46
|
+
const radius = min(distance.mul(lightSize).div(width), reach).max(texel);
|
|
47
|
+
const sum = float(0).toVar();
|
|
48
|
+
Loop(taps, ({ i }) => { sum.addAssign(lit(shadowCoord.xy.add(vogelDiskSample(i, taps, phi).mul(radius)), shadowCoord.z)); });
|
|
49
|
+
return sum.div(taps);
|
|
50
|
+
});
|
|
51
|
+
}
|