@threedog/post-effects 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/README.md CHANGED
@@ -21,16 +21,16 @@ export default vignette();
21
21
 
22
22
  An added effect is on unless it says `enabled: false`. The heavy ones (`bloom`, `ao`, `dof`, outline `normal` / `both`) are the game's call on weak devices: read `engine.tier` before adding them. `engine.post.add` returns a handle; on / off and tuning go through it: `glow.enabled = false`, `engine.post.get('ao').set({ radius: 0.6 })`.
23
23
 
24
- Four effects exist only as TSL nodes and live in a subpath, for games on WebGPURenderer: `voxelGI`, `temporalAA`, `sunShafts`, `lightVolumes`, from `@threedog/post-effects/tsl`. That file imports `three/webgpu`; the main entry does not, so a WebGL game's bundle does not grow.
24
+ Six effects exist only as TSL nodes and live in a subpath, for games on WebGPURenderer: `voxelGI`, `reflections`, `temporalAA`, `sunShafts`, `lightVolumes`, `autoExposure`, from `@threedog/post-effects/tsl`. That file imports `three/webgpu`; the main entry does not, so a WebGL game's bundle does not grow.
25
25
 
26
26
  What each does, by how the game runs (held: switched off, the game's `enabled` stays as written, and `describe().render.post` says why):
27
27
 
28
- | Case | voxelGI | temporalAA, sunShafts, lightVolumes |
29
- |---|---|---|
30
- | Real WebGPU | runs (held on `engine.tier` 'low') | run |
31
- | WebGL2 backend (no WebGPU in the browser, or `forceWebGL: true`) | held | run |
32
- | Fell back to `WebGLRenderer` | held | held |
33
- | Game chose WebGL (`--webgl`) | throws by name | throw by name |
28
+ | Case | voxelGI | reflections | temporalAA, sunShafts, lightVolumes, autoExposure |
29
+ |---|---|---|---|
30
+ | Real WebGPU | runs (held on `engine.tier` 'low') | runs (held on 'low') | run |
31
+ | WebGL2 backend (no WebGPU in the browser, or `forceWebGL: true`) | held | runs (held on 'low') | run |
32
+ | Fell back to `WebGLRenderer` | held | held | held |
33
+ | Game chose WebGL (`--webgl`) | throws by name | throws by name | throw by name |
34
34
 
35
35
  Docs ship with the engine: `node_modules/threedog/docs/recipes/52-around-the-picture.md` (post-effect chain, order, depth readers) and `docs/AI.md`.
36
36
 
package/about.js ADDED
@@ -0,0 +1,10 @@
1
+ // What an effect says about itself for the picture menu (engine.catalog('picture')), written once next to its factory as fn.about.
2
+ // Why on the factory and not only on the definition: the menu lists effects the game has not added yet, so it reads them without calling
3
+ // the factory (some need a light or a box). The definition the factory returns carries the same object and takes backend / skipOnLowTier
4
+ // from it, so "where it runs" is declared in one place. Fields: cost 'low' | 'medium' | 'high' (rough GPU class, not a measurement),
5
+ // on (one line that turns it on), recipe (where it is explained), limits (one line of what it cannot do), webgpuOnly (node only, no WebGL
6
+ // version), backend / skipOnLowTier as on PostEffect, acts (what it does to the light, for the engine's combination checks: 'glow' lifts what passes
7
+ // params.threshold, 'exposure' scales the light by a value it keeps on the GPU, 'ao' darkens the ambient light; the checks, the settings rows and photo read this, never the effect's name). tests/specs/picture-menu.mjs fails when an exported effect has none or contradicts it.
8
+
9
+ /** @param {Function & { about: any }} fn @returns {{ about: any, backend?: 'webgpu', skipOnLowTier?: true }} the fields its definition carries */
10
+ export const declared = fn => ({ about: fn.about, ...(fn.about.backend ? { backend: fn.about.backend } : {}), ...(fn.about.skipOnLowTier ? { skipOnLowTier: true } : {}) });
package/dof.js CHANGED
@@ -4,6 +4,7 @@
4
4
  import * as THREE from 'three';
5
5
  import { Pass, FullScreenQuad } from 'three/addons/postprocessing/Pass.js';
6
6
  import { FULLSCREEN_VERT, DEPTH_GLSL, depthUniforms, writeDepthUniforms, depthNodes } from './depth.js';
7
+ import { declared } from './about.js';
7
8
  /** @import { PostEffect } from 'threedog' */
8
9
 
9
10
  class DofPass extends Pass {
@@ -62,7 +63,7 @@ class DofPass extends Pass {
62
63
  */
63
64
  export function dof({ focus = 10, range = 2, falloff = 20, maxBlur = 6, enabled, order = 5 } = {}) {
64
65
  const update = (pass, p) => { const u = pass.material.uniforms; u.uFocus.value = p.focus; u.uRange.value = p.range; u.uFalloff.value = p.falloff; u.uMaxBlur.value = p.maxBlur; };
65
- return { name: 'dof', slot: 'hdr', order, enabled, needsDepth: true, params: { focus, range, falloff, maxBlur },
66
+ return { ...declared(dof), name: 'dof', slot: 'hdr', order, enabled, needsDepth: true, params: { focus, range, falloff, maxBlur },
66
67
  create: ({ camera, params }) => { const pass = new DofPass(camera); update(pass, params); return pass; }, update, node: dofNode };
67
68
  }
68
69
 
@@ -87,3 +88,6 @@ function dofNode(input, { tsl: T, display, scenePass, camera, p }) {
87
88
  }
88
89
  return T.select(r.lessThan(0.5), color.sample(uv), T.vec4(sum.div(w), 1));
89
90
  }
91
+
92
+ // the picture menu facts of each effect (about.js says why they sit on the factory)
93
+ dof.about = { cost: 'high', on: 'engine.post.add(dof({ focus }))', recipe: 'recipes/52-around-the-picture.md "dof: blur the background"', limits: 'one focus band for the whole screen; transparent things blur with what is behind them' };
package/hdr.js CHANGED
@@ -2,6 +2,7 @@
2
2
  import * as THREE from 'three';
3
3
  import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
4
4
  import { GTAOPass } from 'three/addons/postprocessing/GTAOPass.js';
5
+ import { declared } from './about.js';
5
6
  /** @import { PostEffect } from 'threedog' */
6
7
 
7
8
  /**
@@ -18,7 +19,7 @@ const BLOOM_NODE_STRENGTH = 3;
18
19
  * @returns {PostEffect}
19
20
  */
20
21
  export function bloom({ strength = 0.35, radius = 0.5, threshold = 0.85, enabled, order = 30 } = {}) {
21
- return { name: 'bloom', slot: 'hdr', order, enabled, params: { strength, radius, threshold },
22
+ return { ...declared(bloom), name: 'bloom', slot: 'hdr', order, enabled, params: { strength, radius, threshold },
22
23
  create: ({ width, height, params: p }) => new UnrealBloomPass(new THREE.Vector2(width, height), p.strength, p.radius, p.threshold),
23
24
  update: (pass, p) => { pass.strength = p.strength; pass.radius = p.radius; pass.threshold = p.threshold; },
24
25
  // WebGPU: three's BloomNode returns only the glow, so it is added to the input. Same params do not give the same picture: UnrealBloomPass
@@ -38,7 +39,7 @@ export function bloom({ strength = 0.35, radius = 0.5, threshold = 0.85, enabled
38
39
  export function ao({ radius = 0.25, intensity = 1, enabled, order = 20 } = {}) {
39
40
  // update in place: GTAOPass keeps its targets and noise, so changing radius never rebuilds it
40
41
  const update = (pass, p) => { pass.updateGtaoMaterial({ radius: p.radius }); pass.blendIntensity = p.intensity; };
41
- return { name: 'ao', slot: 'hdr', order, enabled, params: { radius, intensity }, update,
42
+ return { ...declared(ao), name: 'ao', slot: 'hdr', order, enabled, params: { radius, intensity }, update,
42
43
  create: ({ scene, camera, width, height, params }) => { const pass = new GTAOPass(scene, camera, width, height); update(pass, params); return pass; },
43
44
  // WebGPU: GTAONode on the scene pass's depth (normals reconstructed from depth), its .r darkens the color; intensity mixes toward no AO as blendIntensity does
44
45
  node: (input, { display, scenePass, camera, tsl, p }) => {
@@ -47,3 +48,7 @@ export function ao({ radius = 0.25, intensity = 1, enabled, order = 20 } = {}) {
47
48
  return tsl.vec4(input.rgb.mul(tsl.mix(tsl.float(1), n.getTextureNode().r, p.intensity)), input.a);
48
49
  } };
49
50
  }
51
+
52
+ // the picture menu facts of each effect (about.js says why they sit on the factory)
53
+ bloom.about = { cost: 'medium', on: 'engine.post.add(bloom())', recipe: 'recipes/52-around-the-picture.md "Post effect chain"', limits: 'glows by brightness alone (no per-object choice); reads the light before exposure', acts: 'glow' };
54
+ ao.about = { cost: 'high', on: 'engine.post.add(ao())', recipe: 'recipes/52-around-the-picture.md "Post effect chain"', limits: 'screen space: nothing off screen or hidden behind darkens, thin edges get a halo', acts: 'ao' };
package/index.js CHANGED
@@ -13,6 +13,7 @@
13
13
  // ones (bloom, ao, dof, outline mode normal/both) stay the game's call on weak devices: read engine.tier and leave them out.
14
14
  import * as THREE from 'three';
15
15
  import { codedError } from 'threedog/error-hints';
16
+ import { declared } from './about.js';
16
17
  export { dof } from './dof.js';
17
18
  export { bloom, ao } from './hdr.js';
18
19
  export { outline, OUTLINE_OFF_LAYER } from './outline.js';
@@ -38,8 +39,8 @@ identity.format = THREE.RGBAFormat; identity.minFilter = identity.magFilter = TH
38
39
  * temperature: -1 cool .. 1 warm
39
40
  * @returns {PostEffect}
40
41
  */
41
- export function lut({ lut = null, amount = 1, contrast = 1, saturation = 1, temperature = 0, enabled, order = 10 } = {}) {
42
- return { name: 'lut', slot: 'ldr', order, enabled, params: { lut, amount, contrast, saturation, temperature },
42
+ export function lut({ lut: table = null, amount = 1, contrast = 1, saturation = 1, temperature = 0, enabled, order = 10 } = {}) { // the texture is bound as table: named lut it would hide this function, which declared(lut) reads
43
+ return { ...declared(lut), name: 'lut', slot: 'ldr', order, enabled, params: { lut: table, amount, contrast, saturation, temperature },
43
44
  fuse: {
44
45
  uniforms: { uLutTex: 'sampler3D', uLutSize: 'float', uLutAmount: 'float', uLutContrast: 'float', uLutSaturation: 'float', uLutTemp: 'float' },
45
46
  values: p => ({ uLutTex: p.lut ?? identity, uLutSize: (p.lut ?? identity).image.width, uLutAmount: p.lut ? p.amount : 0,
@@ -89,16 +90,16 @@ export function paletteLut(colors, size = 32) {
89
90
  * @returns {PostEffect}
90
91
  */
91
92
  export function grain({ amount = 0.06, size = 1, animated = true, enabled, order = 30 } = {}) {
92
- return { name: 'grain', slot: 'ldr', order, enabled, params: { amount, size, animated },
93
+ return { ...declared(grain), name: 'grain', slot: 'ldr', order, enabled, params: { amount, size, animated },
93
94
  fuse: {
94
95
  uniforms: { uGrainAmount: 'float', uGrainSize: 'float', uGrainAnimated: 'float' },
95
96
  values: p => ({ uGrainAmount: p.amount, uGrainSize: Math.max(1, p.size), uGrainAnimated: p.animated ? 1 : 0 }),
96
- glsl: `float n = fxHash(floor(vUv * uResolution / uGrainSize) + (uGrainAnimated > 0.5 ? floor(uTime * 24.0) * 17.0 : 0.0)) - 0.5;
97
+ glsl: `float n = threedogHash(floor(vUv * uResolution / uGrainSize) + (uGrainAnimated > 0.5 ? floor(uTime * 24.0) * 17.0 : 0.0)) - 0.5;
97
98
  color.rgb += n * uGrainAmount * (1.0 - 0.5 * dot(color.rgb, vec3(${LUMA_601.join(', ')})));`,
98
- // same shape; three's hash() stands in for fxHash, so the noise pattern differs from WebGL's (its strength does not)
99
- tsl: (color, uv, { tsl: T, p, time, resolution }) => {
99
+ // the same cells through the same hash (fx.hash = threedogHash), so both renderers draw the same grain
100
+ tsl: (color, uv, { tsl: T, fx, p, time, resolution }) => {
100
101
  const q = T.floor(uv.mul(resolution).div(T.max(p.size, 1))), frame = T.floor(time.mul(24)).mul(17).mul(p.animated);
101
- const n = T.hash(q.x.add(q.y.mul(1103)).add(frame)).sub(0.5);
102
+ const n = fx.hash(q.add(frame)).sub(0.5);
102
103
  return T.vec4(color.rgb.add(n.mul(p.amount).mul(T.float(1).sub(T.dot(color.rgb, T.vec3(...LUMA_601)).mul(0.5)))), color.a);
103
104
  } } };
104
105
  }
@@ -111,7 +112,7 @@ export function grain({ amount = 0.06, size = 1, animated = true, enabled, order
111
112
  * @returns {PostEffect}
112
113
  */
113
114
  export function vignette({ strength = 0.35, start = 0.45, enabled, order = 20 } = {}) {
114
- return { name: 'vignette', slot: 'ldr', order, enabled, params: { strength, start },
115
+ return { ...declared(vignette), name: 'vignette', slot: 'ldr', order, enabled, params: { strength, start },
115
116
  fuse: {
116
117
  uniforms: { uVigStrength: 'float', uVigStart: 'float' },
117
118
  values: p => ({ uVigStrength: p.strength, uVigStart: p.start }),
@@ -127,7 +128,7 @@ export function vignette({ strength = 0.35, start = 0.45, enabled, order = 20 }
127
128
  * @returns {PostEffect}
128
129
  */
129
130
  export function chromatic({ amount = 0.004, enabled, order = 5 } = {}) {
130
- return { name: 'chromatic', slot: 'ldr', order, enabled, params: { amount },
131
+ return { ...declared(chromatic), name: 'chromatic', slot: 'ldr', order, enabled, params: { amount },
131
132
  fuse: {
132
133
  reads: true,
133
134
  uniforms: { uChromaAmount: 'float' },
@@ -140,3 +141,9 @@ export function chromatic({ amount = 0.004, enabled, order = 5 } = {}) {
140
141
  return T.vec4(input.sample(uv.add(off)).r, color.g, input.sample(uv.sub(off)).b, color.a);
141
142
  } } };
142
143
  }
144
+
145
+ // the picture menu facts of each effect (about.js says why they sit on the factory)
146
+ lut.about = { cost: 'low', on: 'engine.post.add(lut({ lut: texture3D }))', recipe: 'recipes/52-around-the-picture.md "Post effect chain"', limits: 'grades the finished display image (after tone mapping), not linear light' };
147
+ grain.about = { cost: 'low', on: 'engine.post.add(grain())', recipe: 'recipes/52-around-the-picture.md "Post effect chain"', limits: 'noise on the screen, not on surfaces: it does not move with the world' };
148
+ vignette.about = { cost: 'low', on: 'engine.post.add(vignette())', recipe: 'recipes/52-around-the-picture.md "Post effect chain"', limits: 'darkens toward the corners of the screen only, no lens shape' };
149
+ chromatic.about = { cost: 'low', on: 'engine.post.add(chromatic())', recipe: 'recipes/52-around-the-picture.md "Post effect chain"', limits: 'the color split grows from the screen center only' };
package/outline.js CHANGED
@@ -5,20 +5,21 @@ import { Pass, FullScreenQuad } from 'three/addons/postprocessing/Pass.js';
5
5
  import { RESERVED_LAYERS } from 'threedog/layers';
6
6
  import { codedError } from 'threedog/error-hints';
7
7
  import { FULLSCREEN_VERT, DEPTH_GLSL, depthUniforms, writeDepthUniforms, depthNodes } from './depth.js';
8
+ import { declared } from './about.js';
8
9
  /** @import { PostEffect } from 'threedog' */
9
10
 
10
11
  /** Layer number to put on objects that should get no outline: mesh.layers.enable(OUTLINE_OFF_LAYER), with outline({ offLayer: OUTLINE_OFF_LAYER }) */
11
12
  export const OUTLINE_OFF_LAYER = RESERVED_LAYERS.outlineOff;
12
13
  const MODES = { depth: 0, normal: 1, both: 2 };
13
14
  // linear (0.5, 0.5, 1): an empty pixel reads as a normal facing the camera, and for the mask its red 0.5 stays below the > 0.5 test
14
- const EMPTY = new THREE.Color().setRGB(0.5, 0.5, 1, THREE.LinearSRGBColorSpace), _clear = new THREE.Color();
15
+ const EMPTY = new THREE.Color().setRGB(0.5, 0.5, 1, THREE.LinearSRGBColorSpace);
15
16
  const badMode = mode => codedError('post-effect', `outline: unknown mode '${mode}', use 'depth' | 'normal' | 'both'`);
16
17
 
17
18
  class OutlinePass extends Pass {
18
- /** @param {any} scene @param {any} camera @param {Record<string, any>} p */
19
- constructor(scene, camera, p) {
19
+ /** @param {any} scene @param {any} camera @param {Record<string, any>} p @param {(renderer: any, draw: () => void, opts?: object) => void} borrow ctx.borrowRenderer, the engine's renderer borrow */
20
+ constructor(scene, camera, p, borrow) {
20
21
  super();
21
- this.scene = scene; this.camera = camera; this.p = p; this.time = 0;
22
+ this.scene = scene; this.camera = camera; this.p = p; this.time = 0; this.borrow = borrow;
22
23
  this.normalMat = new THREE.MeshNormalMaterial();
23
24
  this.maskMat = new THREE.MeshBasicMaterial({ color: 0xffffff });
24
25
  this.normalRT = null; this.maskRT = null;
@@ -62,14 +63,14 @@ class OutlinePass extends Pass {
62
63
  }
63
64
  // Render the scene once with an override material into a target the size of the input
64
65
  _pass(renderer, rt, mat, layer) {
65
- const { scene, camera } = this, bg = scene.background, fog = scene.fog, over = scene.overrideMaterial, mask = camera.layers.mask, alpha = renderer.getClearAlpha();
66
- renderer.getClearColor(_clear);
67
- scene.overrideMaterial = mat; scene.background = null; scene.fog = null;
68
- if (layer != null) camera.layers.set(layer);
69
- renderer.setClearColor(EMPTY, 1);
70
- // what was there goes back, even when the render throws: an override may be a debug view's, and it must outlive this pass
71
- try { renderer.setRenderTarget(rt); renderer.clear(); renderer.render(scene, camera); }
72
- finally { scene.overrideMaterial = over; scene.background = bg; scene.fog = fog; camera.layers.mask = mask; renderer.setClearColor(_clear, alpha); }
66
+ const { scene, camera } = this;
67
+ // what was there goes back, even when the render throws (the engine's one borrow): an override may be a debug view's, and it must outlive this pass
68
+ this.borrow(renderer, () => {
69
+ scene.overrideMaterial = mat; scene.background = null; scene.fog = null;
70
+ if (layer != null) camera.layers.set(layer);
71
+ renderer.setClearColor(EMPTY, 1);
72
+ renderer.setRenderTarget(rt); renderer.clear(); renderer.render(scene, camera);
73
+ }, { scene, camera });
73
74
  }
74
75
  _target(rt, w, h, depth) {
75
76
  if (rt && (rt.width !== w || rt.height !== h)) { rt.setSize(w, h); return rt; }
@@ -116,8 +117,8 @@ function apply(pass, p) {
116
117
  * @returns {PostEffect}
117
118
  */
118
119
  export function outline({ color = 0x222222, thickness = 1, strength = 0.8, mode = 'depth', fadeWithDistance = true, wobble = 0, offLayer = null, enabled, order = 10 } = {}) {
119
- return { name: 'outline', slot: 'hdr', order, enabled, needsDepth: true, params: { color, thickness, strength, mode, fadeWithDistance, wobble, offLayer },
120
- create: ({ scene, camera, params }) => { const pass = new OutlinePass(scene, camera, params); apply(pass, params); return pass; },
120
+ return { ...declared(outline), name: 'outline', slot: 'hdr', order, enabled, needsDepth: true, params: { color, thickness, strength, mode, fadeWithDistance, wobble, offLayer },
121
+ create: ({ scene, camera, params, borrowRenderer }) => { const pass = new OutlinePass(scene, camera, params, borrowRenderer); apply(pass, params); return pass; },
121
122
  update: apply, node: outlineNode };
122
123
  }
123
124
 
@@ -127,7 +128,7 @@ export function outline({ color = 0x222222, thickness = 1, strength = 0.8, mode
127
128
  * imports three/webgpu. Number / boolean params are live uniforms (ctx.p); mode and offLayer on / off rebuild the node, as any non-number param does.
128
129
  * @param {any} input @param {any} ctx
129
130
  */
130
- function outlineNode(input, { tsl: T, fx, display, scenePass, scene, camera, params, p }) {
131
+ function outlineNode(input, { tsl: T, fx, display, scenePass, scene, camera, params, p, borrowRenderer }) {
131
132
  const mode = MODES[params.mode];
132
133
  if (mode === undefined) throw badMode(params.mode);
133
134
  const { far, lin } = depthNodes(T, camera);
@@ -153,15 +154,16 @@ function outlineNode(input, { tsl: T, fx, display, scenePass, scene, camera, par
153
154
  const view = (mat, layer) => {
154
155
  const v = display.pass(scene, camera);
155
156
  v.overrideMaterial = mat;
156
- const L = layer && new THREE.Layers(), run = v.updateBefore.bind(v), free = v.dispose.bind(v), clear = new THREE.Color(), was = new THREE.Color();
157
+ const L = layer && new THREE.Layers(), run = v.updateBefore.bind(v), free = v.dispose.bind(v), clear = new THREE.Color();
157
158
  if (L) v.setLayers(L);
158
159
  v.updateBefore = frame => {
159
- const r = frame.renderer, bg = scene.background, bgNode = scene.backgroundNode, fog = scene.fog, a = r.getClearAlpha();
160
160
  if (L) L.set(params.offLayer);
161
- r.getClearColor(was);
162
- r.setClearColor(clear.setRGB(0.5, 0.5, 1, THREE.SRGBColorSpace), 1);
163
- scene.background = scene.backgroundNode = null; scene.fog = null; // three prefers backgroundNode over background, so both go
164
- try { run(frame); } finally { scene.background = bg; scene.backgroundNode = bgNode; scene.fog = fog; r.setClearColor(was, a); }
161
+ // the engine's one borrow gives the clear and the scene's background / fog back, also when the pass throws
162
+ borrowRenderer(frame.renderer, () => {
163
+ frame.renderer.setClearColor(clear.setRGB(0.5, 0.5, 1, THREE.SRGBColorSpace), 1);
164
+ scene.background = scene.backgroundNode = null; scene.fog = null; // three prefers backgroundNode over background, so both go
165
+ run(frame);
166
+ }, { scene });
165
167
  };
166
168
  v.dispose = () => { free(); mat.dispose(); };
167
169
  return v;
@@ -180,3 +182,6 @@ function outlineNode(input, { tsl: T, fx, display, scenePass, scene, camera, par
180
182
  }
181
183
  return T.vec4(T.mix(input.rgb, col, edge.mul(p.strength)), input.a);
182
184
  }
185
+
186
+ // the picture menu facts of each effect (about.js says why they sit on the factory)
187
+ outline.about = { cost: 'medium', on: 'engine.post.add(outline())', recipe: 'recipes/52-around-the-picture.md "Post effect chain"', limits: "one color for every edge; mode 'depth' misses edges between surfaces at one depth" };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threedog/post-effects",
3
- "version": "1.0.1",
3
+ "version": "1.2.0",
4
4
  "description": "Optional post effects for threedog: bloom, ambient occlusion, outline, LUT color grading, film grain, vignette, chromatic aberration and depth of field (light ldr effects are fused into one fullscreen pass)",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -31,7 +31,7 @@
31
31
  "*.d.ts"
32
32
  ],
33
33
  "peerDependencies": {
34
- "threedog": "^1.0.1",
34
+ "threedog": "^1.2.0",
35
35
  "three": "^0.187.0"
36
36
  }
37
37
  }
package/tsl.d.ts CHANGED
@@ -4,6 +4,10 @@ import type { Box3, Light } from 'three';
4
4
 
5
5
  /** Real-time bounced light (three's vxgi; hdr). Needs three's WebGPU backend; held off on low tier and on WebGPURenderer's WebGL2 backend, and describe().render.post says why. setup gets the VXGINode @experimental */
6
6
  export function voxelGI(o?: { resolution?: number; bounds?: Box3; intensity?: number; occlusion?: number; setup?: (gi: any) => void; enabled?: boolean; order?: number; name?: string }): PostEffect;
7
+ /** Screen-space reflections (three's SSRNode, mirror mode; hdr): in proportion to metalness, only what is on screen. Held off on low tier; blurQuality and binaryRefine rebuild the chain. setup gets the SSRNode @experimental */
8
+ export function reflections(o?: { intensity?: number; maxDistance?: number; thickness?: number; quality?: number; resolutionScale?: number; blurQuality?: number; binaryRefine?: boolean; setup?: (ssr: any) => void; enabled?: boolean; order?: number; name?: string }): PostEffect;
9
+ /** Exposure that adapts like an eye (hdr, order 800, before tone mapping): log-average brightness measured on the GPU, eased toward key inside min..max; params change in place. WebGPURenderer only @experimental */
10
+ export function autoExposure(o?: { key?: number; speedUp?: number; speedDown?: number; min?: number; max?: number; enabled?: boolean; order?: number; name?: string }): PostEffect;
7
11
  /** Temporal antialiasing (three's TRAANode; last in hdr): clears the dots of stochastic effects before it and replaces MSAA while on. WebGPURenderer only @experimental */
8
12
  export function temporalAA(o?: { enabled?: boolean; order?: number; name?: string }): PostEffect;
9
13
  /** Sun shafts through gaps, from the light's shadow map (three's GodraysNode; hdr). Best where most of the air is in shadow; open scenes turn to haze. WebGPURenderer only @experimental */
package/tsl.js CHANGED
@@ -3,19 +3,23 @@
3
3
  // engine.post.add(voxelGI({ bounds })); engine.post.add(temporalAA());
4
4
  // Why a subpath and not the main entry: these import three's vxgi and display nodes, which import three/webgpu; a WebGL game never loads this file, so its bundle stays as it is.
5
5
  // Everything here is plain three.js plugged into engine.post: voxelGI and sunShafts hand three's node back through setup(), so its settings stay the game's.
6
- // Default order in the hdr slot, low first, one scale with the main entry: voxelGI 2 (the bounce is scene light, so the rest works on it), dof 5, outline 10, ao 20, bloom 30,
7
- // sunShafts and lightVolumes 200, temporalAA 900 (last: it clears the dots of everything before it).
8
- // Tier rule as in index.js: of these only voxelGI declares skipOnLowTier. Each effect is held, and describe().render.post says why, on a device where start() fell back to WebGLRenderer;
6
+ // Default order in the hdr slot, low first, one scale with the main entry: voxelGI 2 (the bounce is scene light, so the rest works on it), reflections 3 (it reflects the bounce,
7
+ // and dof, ao and bloom then treat a reflection as part of the scene: a reflected lamp blooms), dof 5, outline 10, ao 20, bloom 30,
8
+ // sunShafts and lightVolumes 200, autoExposure 800 (after all that adds light: where toneMappingExposure acts), temporalAA 900 (last: it clears the dots of everything before it).
9
+ // Tier rule as in index.js: of these voxelGI and reflections declare skipOnLowTier; under load adaptive quality also holds them off as its last step,
10
+ // after reflections' declared cheaper params and the resolution (engine.adaptive.steps reorders or drops that). Each effect is held, and describe().render.post says why, on a device where start() fell back to WebGLRenderer;
9
11
  // voxelGI also on WebGPURenderer's WebGL2 backend. On a WebGLRenderer the game chose, adding any of them throws by name.
10
12
  import { vxgi } from 'three/addons/lighting/vxgi/VXGINode.js';
11
13
  import { traa } from 'three/addons/tsl/display/TRAANode.js';
14
+ import { ssr } from 'three/addons/tsl/display/SSRNode.js';
12
15
  import { godrays } from 'three/addons/tsl/display/GodraysNode.js';
13
16
  import { depthAwareBlend } from 'three/addons/tsl/display/depthAwareBlend.js';
14
17
  import { gaussianBlur } from 'three/addons/tsl/display/GaussianBlurNode.js';
15
18
  import { bayer16 } from 'three/addons/tsl/math/Bayer.js';
16
- import { Box3, BoxGeometry, Color, Layers, Mesh, Vector3, VolumeNodeMaterial } from 'three/webgpu';
19
+ import { Box3, BoxGeometry, Color, Layers, Mesh, Vector3, VolumeNodeMaterial, QuadMesh, NodeMaterial, RenderTarget, HalfFloatType, FloatType, LinearMipmapLinearFilter } from 'three/webgpu';
17
20
  import { RESERVED_LAYERS } from 'threedog/layers';
18
21
  import { codedError } from 'threedog/error-hints';
22
+ import { declared } from './about.js';
19
23
  /** @import { PostEffect } from 'threedog' */
20
24
 
21
25
  const { lightVolumes: VOLUME_LAYER } = RESERVED_LAYERS;
@@ -33,7 +37,7 @@ const { lightVolumes: VOLUME_LAYER } = RESERVED_LAYERS;
33
37
  */
34
38
  export function voxelGI({ resolution = 128, bounds, intensity = 1, occlusion = 0, setup, order = 2, enabled, name = 'voxelGI' } = {}) {
35
39
  /** @type {any} */ let gi = null;
36
- return { name, slot: 'hdr', order, enabled, backend: 'webgpu', skipOnLowTier: true, needsBuffers: ['normal', 'diffuse'], params: { intensity, occlusion },
40
+ return { ...declared(voxelGI), name, slot: 'hdr', order, enabled, needsBuffers: ['normal', 'diffuse'], params: { intensity, occlusion },
37
41
  node(input, ctx) {
38
42
  const { tsl, p, scenePass, scene, camera, display } = ctx;
39
43
  gi = display.own(vxgi(scenePass.getTextureNode('depth'), scenePass.getTextureNode('normal'), scene, camera, resolution));
@@ -47,6 +51,47 @@ export function voxelGI({ resolution = 128, bounds, intensity = 1, occlusion = 0
47
51
  facts: () => (gi ? { resolution, voxelSize: +gi.volume.voxelSizeNode.value.toFixed(3) } : null) };
48
52
  }
49
53
 
54
+ /**
55
+ * Screen-space reflections (three's SSRNode, mirror mode: one ray per pixel, blurred by roughness), added to the scene color in the hdr slot. Held off on low tier.
56
+ * A surface reflects in proportion to its metalness, and one at metalness 0 is skipped (three's early-out): a wet or polished stone floor wants a small metalness.
57
+ * Why reflectNonMetals is not offered: in this mode three weights the ray by metalness, so the flag only spends the rays on surfaces that then add black.
58
+ * It reflects only what is on screen: things behind the camera or off the edge fade out, and the environment map stays the reflection there.
59
+ * Known limit, double counting: where a ray hits, three's lighting has already added the environment's specular to that pixel, and the reflection comes on top of it.
60
+ * three keeps that term inside each material's lighting, never in a buffer, so a post effect cannot take it out; doing it in the lighting would recompile every lit material
61
+ * of the game when the effect is added. Tune by eye: in a closed place lower the reflective materials' envMapIntensity, under open sky lower intensity.
62
+ * @param {{ intensity?: number, maxDistance?: number, thickness?: number, quality?: number, resolutionScale?: number, blurQuality?: number, binaryRefine?: boolean,
63
+ * setup?: (ssr: any) => void, order?: number, enabled?: boolean, name?: string }} [o]
64
+ * intensity: how strong; maxDistance: world units, how far a reflected thing may stand from the surface (it fades toward there); thickness: how deep a thing on screen counts
65
+ * as solid behind its front; quality: 0 to 1, steps per ray (up to 64); resolutionScale: size of the reflection target against the screen. These change in place.
66
+ * resolutionScale defaults to 0.5: a screen-filling mirror cost +12.5 ms at 1080p at 1 and +2.9 ms at 0.5 on an integrated GPU (docs/testing/perf.md 6b), and the roughness blur hides
67
+ * the half size; a sharp mirror sets 1. Cost follows the pixel count (pixel ratio too) and grows with maxDistance.
68
+ * Built into the shader, so set() of them rebuilds the chain: blurQuality (kernel of the roughness blur), binaryRefine (sharper contact where a thing meets the mirror).
69
+ * setup(ssr): gets three's SSRNode each time the chain builds it.
70
+ * @returns {PostEffect}
71
+ */
72
+ export function reflections({ intensity = 1, maxDistance = 5, thickness = 0.1, quality = 0.5, resolutionScale = 0.5, blurQuality = 2, binaryRefine = false,
73
+ setup, order = 3, enabled, name = 'reflections' } = {}) {
74
+ /** @type {any} */ let node = null;
75
+ return { ...declared(reflections), name, slot: 'hdr', order, enabled, needsBuffers: ['normal', 'metalRough'],
76
+ params: { intensity, maxDistance, thickness, quality, resolutionScale, blurQuality, binaryRefine },
77
+ // adaptive quality's first step under load: both change in place (no recompile), and the roughness blur hides most of a quarter-size target
78
+ cheaper: { quality: 0.25, resolutionScale: 0.25 },
79
+ node(input, { tsl, p, params, scenePass, buffer, camera, display }) {
80
+ const mr = buffer('metalRough'); // not scenePass.getTextureNode: with temporalAA on it shares velocity's target
81
+ // the build-time two are read as plain values here, so set() of them rebuilds the chain; the rest are the engine's uniforms, written in place
82
+ node = display.own(ssr(display.texture(input), scenePass.getTextureNode('depth'), scenePass.getTextureNode('normal'),
83
+ { metalnessNode: mr.x, roughnessNode: mr.y, binaryRefine: params.binaryRefine, camera }));
84
+ display.own({ dispose() { node = null; } });
85
+ Object.assign(node, { intensity: p.intensity, maxDistance: p.maxDistance, thickness: p.thickness, quality: p.quality, blurQuality: params.blurQuality });
86
+ // three reads resolutionScale as a number at each frame's resize: it reads and writes the live uniform, so set() needs no rebuild and setup's s.resolutionScale = x holds
87
+ Object.defineProperty(node, 'resolutionScale', { get: () => p.resolutionScale.value, set(v) { p.resolutionScale.value = v; } });
88
+ setup?.(node);
89
+ // the result is premultiplied (already weighted by metalness, distance and angle): it adds
90
+ return tsl.vec4(input.rgb.add(node.getTextureNode().rgb), input.a);
91
+ },
92
+ facts: () => (node ? { surfaces: 'metalness above 0, in proportion', target: node._resolution.value.toArray() } : null) };
93
+ }
94
+
50
95
  /**
51
96
  * Temporal antialiasing (three's TRAANode): averages jittered frames, so it also clears the dots of every stochastic effect before it (voxelGI, lightVolumes).
52
97
  * Runs last in the hdr slot. It replaces MSAA while it is on. Moving things can trail; judge it in motion.
@@ -54,8 +99,65 @@ export function voxelGI({ resolution = 128, bounds, intensity = 1, occlusion = 0
54
99
  * @returns {PostEffect}
55
100
  */
56
101
  export function temporalAA({ order = 900, enabled, name = 'temporalAA' } = {}) {
57
- return { name, slot: 'hdr', order, enabled, needsBuffers: ['velocity'],
58
- node: (input, { scenePass, camera, display }) => display.own(traa(input, scenePass.getTextureNode('depth'), scenePass.getTextureNode('velocity'), camera)) };
102
+ return { ...declared(temporalAA), name, slot: 'hdr', order, enabled, needsBuffers: ['velocity'],
103
+ // display.texture: traa() would wrap a non-texture input (any effect before it) in a render target of its own that its dispose() leaves behind, two textures per chain rebuild
104
+ node: (input, { scenePass, camera, display }) => display.own(traa(display.texture(input), scenePass.getTextureNode('depth'), scenePass.getTextureNode('velocity'), camera)) };
105
+ }
106
+
107
+ /**
108
+ * Exposure that adapts like an eye: each frame the log-average brightness of the hdr picture is measured on the GPU (never read back to the CPU, which would stall),
109
+ * and the picture's exposure eases toward key / average, faster one way than the other, inside min..max. A multiply in the hdr slot at 800, after everything that adds light
110
+ * and before temporalAA and tone mapping: where renderer.toneMappingExposure acts, so bloom's threshold reads the scene's own light as before, and the game's
111
+ * toneMappingExposure stays on top as a fixed trim (the effect never writes it). It weighs the whole screen evenly, from a 64x64 sample.
112
+ * @param {{ key?: number, speedUp?: number, speedDown?: number, min?: number, max?: number, order?: number, enabled?: boolean, name?: string }} [o]
113
+ * key: the average brightness the picture is brought to (0.18 is middle gray); speedUp: how fast exposure rises when the picture gets darker (per second, larger is faster);
114
+ * speedDown: how fast it falls when it gets brighter (eyes adapt to light faster than to the dark); min, max: the range exposure stays in (narrow it to keep an authored look).
115
+ * All change in place. The first frame starts at its goal; a chain rebuild keeps the adapted value. Time is engine.time's ambient clock.
116
+ * Measured from a 64x64 point sample of the picture, so a small very bright thing moving across it can nudge the exposure.
117
+ * @returns {PostEffect}
118
+ */
119
+ export function autoExposure({ key = 0.18, speedUp = 1, speedDown = 3, min = 0.1, max = 10, order = 800, enabled, name = 'autoExposure' } = {}) {
120
+ if (!(min > 0 && max >= min)) throw codedError('post-effect', `autoExposure: min must be above 0 and max at least min (got min ${min}, max ${max})`);
121
+ // the adapted value outlives a chain rebuild (another effect added or toggled): its two 1x1 targets stay, so exposure does not snap back to the goal.
122
+ // Float, not half: half's steps near 1 are coarser than one frame's easing at a slow speed, and the value stalled short of the goal
123
+ /** @type {any} */ let S = null;
124
+ return { ...declared(autoExposure), name, slot: 'hdr', order, enabled, params: { key, speedUp, speedDown, min, max },
125
+ node(input, { engine, tsl, p, display, borrowRenderer }) {
126
+ const { vec2, vec4, float, uniform, texture, exp, log, clamp, select, mix } = tsl;
127
+ S ??= { ex: [0, 1].map(() => new RenderTarget(1, 1, { type: FloatType, depthBuffer: false })), i: 0, last: 0, started: false }; // last frame's value and this one's: a target cannot be read while drawn into
128
+ S.built = true;
129
+ // log brightness at 64x64; its mip chain ends in one texel holding the average log: the log-average with no reduction pass of our own
130
+ const lum = new RenderTarget(64, 64, { type: HalfFloatType, depthBuffer: false, generateMipmaps: true, minFilter: LinearMipmapLinearFilter });
131
+ const measure = new QuadMesh(new NodeMaterial()), adapt = new QuadMesh(new NodeMaterial());
132
+ measure.material.fragmentNode = vec4(log(clamp(tsl.luminance(input.rgb), 1e-4, 6e4)), 0, 0, 1);
133
+ const was = texture(S.ex[S.i].texture, vec2(0.5)), now = texture(S.ex[1 - S.i].texture, vec2(0.5)), dt = uniform(0), fresh = uniform(S.started ? 0 : 1);
134
+ const ok = (/** @type {any} */ x) => x.equal(x).and(x.lessThan(1e30)); // not NaN, not infinite: one bad pixel must not poison every later frame
135
+ const raw = p.key.div(exp(texture(lum.texture, vec2(0.5)).level(6).r)), goal = clamp(select(ok(raw), raw, float(1)), p.min, p.max);
136
+ const before = select(ok(was.r).and(was.r.greaterThan(1e-4)), was.r, goal);
137
+ const k = select(fresh.greaterThan(0), float(1), float(1).sub(exp(dt.mul(select(goal.greaterThan(before), p.speedUp, p.speedDown)).negate())));
138
+ const next = exp(mix(log(before), log(goal), k)); // eased in log steps: a stop up and a stop down take the same time
139
+ adapt.material.fragmentNode = vec4(select(ok(next), next, goal), 0, 0, 1);
140
+ // the output's read of the value draws the two small passes first, once per frame. Time is the engine's ambient clock (the presentation one, core/time/time.js):
141
+ // a stepped or slowed run adapts by the seconds it advanced
142
+ now.updateBeforeType = 'frame';
143
+ now.updateBefore = ({ renderer }) => {
144
+ const t = engine.time.now('ambient');
145
+ dt.value = Math.min(Math.max(t - S.last, 0), 0.25); S.last = t; // a jump of the clock (a skip, a new game) does not jump the exposure
146
+ // the engine's one borrow (clean: no scene-pass MRT on these quads); it puts the renderer back even when a pass throws
147
+ borrowRenderer(renderer, () => {
148
+ renderer.setRenderTarget(lum); measure.render(renderer);
149
+ was.value = S.ex[S.i].texture; renderer.setRenderTarget(S.ex[1 - S.i]); adapt.render(renderer);
150
+ }, { clean: true });
151
+ now.value = S.ex[1 - S.i].texture; S.i = 1 - S.i; fresh.value = 0; S.started = true;
152
+ };
153
+ display.own({ dispose() {
154
+ lum.dispose(); measure.material.dispose(); adapt.material.dispose();
155
+ // a rebuild calls node() again in the same task; when nothing did (removed, switched off), the kept value goes too
156
+ const mine = S; mine.built = false;
157
+ queueMicrotask(() => { if (S === mine && !mine.built) { for (const t of mine.ex) t.dispose(); S = null; } });
158
+ } });
159
+ return vec4(input.rgb.mul(now.r), input.a);
160
+ } };
59
161
  }
60
162
 
61
163
  /**
@@ -67,7 +169,7 @@ export function temporalAA({ order = 900, enabled, name = 'temporalAA' } = {}) {
67
169
  * @returns {PostEffect}
68
170
  */
69
171
  export function sunShafts({ light, density = 2, maxDensity = 0.6, falloff = 2, color = new Color(1, 1, 1), steps = 60, setup, order = 200, enabled, name = 'sunShafts' } = {}) {
70
- return { name, slot: 'hdr', order, enabled, params: { density, maxDensity, falloff, color: new Color(color) },
172
+ return { ...declared(sunShafts), name, slot: 'hdr', order, enabled, params: { density, maxDensity, falloff, color: new Color(color) },
71
173
  node(input, { engine, tsl, p, scenePass, camera, display }) {
72
174
  const depth = scenePass.getTextureNode('depth'), sun = light ?? engine.lights?.sun;
73
175
  // engine.lights.sun exists even under createEngine({ lights: false }), out of the scene; three's own error for a light with no shadow map names nothing
@@ -91,8 +193,8 @@ export function sunShafts({ light, density = 2, maxDensity = 0.6, falloff = 2, c
91
193
  */
92
194
  export function lightVolumes({ bounds, density = 0.3, steps = 16, scale = 0.25, blur = 4, scattering, order = 200, enabled, name = 'lightVolumes' } = /** @type {any} */ ({})) {
93
195
  if (!bounds?.isBox3) throw codedError('post-effect', 'lightVolumes: bounds is required, the box of air to light: lightVolumes({ bounds: new THREE.Box3(min, max) })');
94
- return { name, slot: 'hdr', order, enabled, params: { density },
95
- node(input, { tsl, p, scene, camera, scenePass, display }) {
196
+ return { ...declared(lightVolumes), name, slot: 'hdr', order, enabled, params: { density },
197
+ node(input, { tsl, p, scene, camera, scenePass, display, borrowRenderer }) {
96
198
  const size = bounds.getSize(new Vector3()), mat = new VolumeNodeMaterial();
97
199
  mat.steps = steps;
98
200
  mat.offsetNode = bayer16(tsl.screenCoordinate);
@@ -113,13 +215,19 @@ export function lightVolumes({ bounds, density = 0.3, steps = 16, scale = 0.25,
113
215
  air.updateBefore = frame => {
114
216
  // three lights a pass only with the lights on its layers; a new lamp is found within half a second
115
217
  if (look-- <= 0) { look = 30; scene.traverse(l => { if ((l.isPointLight || l.isSpotLight) && !l.layers.isEnabled(VOLUME_LAYER)) { l.layers.enable(VOLUME_LAYER); lamps.add(l); } }); }
116
- const r = frame.renderer, { background, backgroundNode } = scene, clear = r.getClearColor(new Color()), alpha = r.getClearAlpha();
117
- // three prefers backgroundNode over background, so both go
118
- scene.background = scene.backgroundNode = null; r.setClearColor(0x000000, 0);
119
- try { draw.call(air, frame); } finally { scene.background = background; scene.backgroundNode = backgroundNode; r.setClearColor(clear, alpha); }
218
+ // three prefers backgroundNode over background, so both go; the engine's one borrow gives them and the clear back
219
+ borrowRenderer(frame.renderer, () => { scene.background = scene.backgroundNode = null; frame.renderer.setClearColor(0x000000, 0); draw.call(air, frame); }, { scene });
120
220
  };
121
221
  display.own({ dispose() { for (const l of lamps) l.layers.disable(VOLUME_LAYER); box.removeFromParent(); box.geometry.dispose(); mat.dispose(); } });
122
222
  return tsl.vec4(input.rgb.add(display.own(gaussianBlur(air.getTextureNode(), blur)).rgb), input.a);
123
223
  },
124
224
  facts: () => ({ lights: 'point and spot only; the sun does nothing here (sunShafts)' }) };
125
225
  }
226
+
227
+ // the picture menu facts of each effect (about.js says why they sit on the factory)
228
+ voxelGI.about = { cost: 'high', on: "engine.post.add(voxelGI({ bounds })) from '@threedog/post-effects/tsl'", recipe: 'recipes/34-environment-lighting.md "Real-time bounced light (WebGPU games only)"', limits: 'bounce only inside its box; a chain change at or before it voxelizes again (a stall; on WebGPU a change after it keeps it); walls thinner than a voxel leak', webgpuOnly: true, backend: 'webgpu', skipOnLowTier: true };
229
+ reflections.about = { cost: 'high', on: "engine.post.add(reflections()) from '@threedog/post-effects/tsl'", recipe: 'recipes/34-environment-lighting.md "Reflections"', limits: 'screen space: what is off screen is not reflected; it adds on top of the environment map', webgpuOnly: true, skipOnLowTier: true };
230
+ temporalAA.about = { cost: 'medium', on: "engine.post.add(temporalAA()) from '@threedog/post-effects/tsl'", recipe: 'recipes/34-environment-lighting.md "Real-time bounced light (WebGPU games only)"', limits: 'smears fast motion a little; replaces MSAA while on', webgpuOnly: true };
231
+ autoExposure.about = { cost: 'low', on: "engine.post.add(autoExposure()) from '@threedog/post-effects/tsl'", recipe: 'recipes/34-environment-lighting.md "Exposure and the tone curve"', limits: 'weighs the whole screen evenly; bloom ordered before it sees the unexposed light', webgpuOnly: true, acts: 'exposure' };
232
+ sunShafts.about = { cost: 'high', on: "engine.post.add(sunShafts({ light: engine.lights.sun })) from '@threedog/post-effects/tsl'", recipe: 'recipes/34-environment-lighting.md "Light you can see in the air"', limits: 'one light, which must cast shadows; open daylight turns to haze', webgpuOnly: true };
233
+ lightVolumes.about = { cost: 'high', on: "engine.post.add(lightVolumes({ bounds })) from '@threedog/post-effects/tsl'", recipe: 'recipes/34-environment-lighting.md "Light you can see in the air"', limits: 'point and spot lights only (the sun does nothing); dithered, so temporalAA after it', webgpuOnly: true };