@threedog/post-effects 0.2.0 → 0.7.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 ADDED
@@ -0,0 +1,37 @@
1
+ # @threedog/post-effects
2
+
3
+ Optional post effects for [threedog](https://www.npmjs.com/package/threedog): `bloom`, `ao` (ambient occlusion), `outline`, `dof` (depth of field) on the HDR side, and `lut` (color grade; `paletteLut` makes its LUT from a fixed palette), `grain`, `vignette`, `chromatic` (chromatic aberration) fused into one fullscreen LDR pass. Import only what you use; the engine itself ships no effects.
4
+
5
+ ```sh
6
+ npm install @threedog/post-effects@0.7
7
+ ```
8
+
9
+ This describes 0.7.0: `npm install @threedog/post-effects@0.7` (games made in the [repository](https://github.com/penstic123-code/ThreeDog.js-Game-Engine) already have it).
10
+
11
+ Each effect is one value that runs on WebGL and on WebGPU. It goes in the way every post effect does, `engine.post.add`:
12
+
13
+ ```js
14
+ import { bloom, vignette } from '@threedog/post-effects';
15
+
16
+ engine.post.add(bloom({ strength: 0.6 })); // game code
17
+ // or a file in the game's plugins/ folder, or in a style's style/plugins/ folder:
18
+ // plugins/20-vignette.js
19
+ export default vignette();
20
+ ```
21
+
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
+
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.
25
+
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
+
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 |
34
+
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
+
37
+ Peer dependencies: `threedog` and `three` (the same copy the game uses). MIT license.
package/dof.js CHANGED
@@ -50,17 +50,41 @@ class DofPass extends Pass {
50
50
  }
51
51
 
52
52
  /**
53
- * Depth of field (hdr slot, costly): everything farther from `focus` than `range` blurs, up to `maxBlur` pixels over `falloff` meters.
53
+ * Depth of field (hdr slot, heavy on weak devices): everything farther from `focus` than `range` blurs, up to `maxBlur` pixels over `falloff` meters.
54
54
  * It reads scene depth, so it must run before any pass that swaps buffers; it passes the scene depth on in its output, so a depth reader
55
55
  * after it (outline, whose default order is later) works: both can be on, lines drawn over the blurred image. Move the focus per frame with
56
- * engine.look.post.set({ 'dof.focus': distanceToTarget }).
57
- * @example post: [dof({ enabled: true, focus: 8, range: 3, maxBlur: 5 })]
56
+ * engine.post.get('dof').set({ focus: distanceToTarget }).
57
+ * @example engine.post.add(dof({ enabled: true, focus: 8, range: 3, maxBlur: 5 }))
58
58
  * @param {{ focus?: number, range?: number, falloff?: number, maxBlur?: number, enabled?: boolean, order?: number }} [o]
59
59
  * focus, range, falloff in meters; maxBlur in device pixels
60
60
  * @returns {PostEffect}
61
61
  */
62
- export function dof({ focus = 10, range = 2, falloff = 20, maxBlur = 6, enabled = false, order = 5 } = {}) {
62
+ export function dof({ focus = 10, range = 2, falloff = 20, maxBlur = 6, enabled, order = 5 } = {}) {
63
63
  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; };
64
- return { name: 'dof', slot: 'hdr', order, enabled, costly: true, needsDepth: true, params: { focus, range, falloff, maxBlur },
65
- create: ({ camera, params }) => { const pass = new DofPass(camera); update(pass, params); return pass; }, update };
64
+ return { name: 'dof', slot: 'hdr', order, enabled, needsDepth: true, params: { focus, range, falloff, maxBlur },
65
+ create: ({ camera, params }) => { const pass = new DofPass(camera); update(pass, params); return pass; }, update, node: dofNode };
66
+ }
67
+
68
+ /**
69
+ * WebGPU: DofPass's fragment shader as a node (not three's DepthOfFieldNode, whose focus / blur parameters mean other things), same
70
+ * golden-angle disk and the same rule that keeps sharp neighbors out. The color so far becomes a texture (ctx.display.texture) because the disk
71
+ * samples it at other pixels; depth is always the scene pass's own, so no depth copy is needed here (that is the WebGL pass's keepsDepth).
72
+ * All four params are numbers, so set() of any of them writes a uniform and never rebuilds.
73
+ * @param {any} input @param {any} ctx
74
+ */
75
+ function dofNode(input, { tsl: T, display, scenePass, camera, p }) {
76
+ const near = T.uniform(camera.near).onRenderUpdate(() => camera.near), far = T.uniform(camera.far).onRenderUpdate(() => camera.far);
77
+ const ortho = T.uniform(0).onRenderUpdate(() => (camera.isOrthographicCamera ? 1 : 0));
78
+ const depth = scenePass.getTextureNode('depth'), color = display.texture(input), uv = T.screenUV, texel = T.vec2(1).div(T.screenSize);
79
+ const lin = q => { const d = depth.sample(q).x; return T.select(ortho.greaterThan(0.5), T.orthographicDepthToViewZ(d, near, far), T.perspectiveDepthToViewZ(d, near, far)).negate(); };
80
+ const coc = d => T.clamp(d.sub(p.focus).abs().sub(p.range).div(p.falloff), 0, 1).mul(p.maxBlur);
81
+ const r = coc(lin(uv)).toVar();
82
+ let sum = color.sample(uv).rgb, w = T.float(1);
83
+ for (let i = 1; i < 16; i++) {
84
+ const t = i / 16, a = i * 2.39996;
85
+ const o = T.vec2(Math.cos(a), Math.sin(a)).mul(Math.sqrt(t)).mul(r), q = uv.add(o.mul(texel));
86
+ const s = T.step(r.mul(Math.sqrt(t) * 0.5), coc(lin(q)).add(0.5)); // length(o) * 0.5, with |o| = sqrt(t) * r
87
+ sum = sum.add(color.sample(q).rgb.mul(s)); w = w.add(s);
88
+ }
89
+ return T.select(r.lessThan(0.5), color.sample(uv), T.vec4(sum.div(w), 1));
66
90
  }
package/hdr.js CHANGED
@@ -1,28 +1,49 @@
1
- // Bloom and ambient occlusion (GTAO) as engine.post effects (hdr slot). Both are costly, so they start off on low-tier devices.
1
+ // Bloom and ambient occlusion (GTAO) as engine.post effects (hdr slot). Both are heavy on weak devices: the game reads engine.tier to decide whether to add them.
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
5
  /** @import { PostEffect } from 'threedog' */
6
6
 
7
+ /**
8
+ * bloom()'s strength per unit of UnrealBloomPass strength, for the same picture. Measured 2026-11-03 (tests/post-webgpu, software WebGL2 backend):
9
+ * with strength 0.2 / 0.5 / 1 and radius 0 / 0.5 / 1, a factor of 3 put the screenshot mean within 0.2% of UnrealBloomPass's in all nine cases
10
+ * (1 left it 20-30% darker). Why one factor fits: both sum the same five mips with the same radius lerp; UnrealBloomPass weights them three times higher.
11
+ */
12
+ const BLOOM_NODE_STRENGTH = 3;
13
+
7
14
  /**
8
15
  * Bloom (glow around bright pixels), hdr slot. Off by default on low-tier devices.
9
- * @example post: [bloom({ strength: 0.35, radius: 0.5, threshold: 0.85 })]
16
+ * @example engine.post.add(bloom({ strength: 0.35, radius: 0.5, threshold: 0.85 }))
10
17
  * @param {{ strength?: number, radius?: number, threshold?: number, enabled?: boolean, order?: number }} [o]
11
18
  * @returns {PostEffect}
12
19
  */
13
20
  export function bloom({ strength = 0.35, radius = 0.5, threshold = 0.85, enabled, order = 30 } = {}) {
14
- return { name: 'bloom', slot: 'hdr', order, enabled, costly: true, params: { strength, radius, threshold },
21
+ return { name: 'bloom', slot: 'hdr', order, enabled, params: { strength, radius, threshold },
15
22
  create: ({ width, height, params: p }) => new UnrealBloomPass(new THREE.Vector2(width, height), p.strength, p.radius, p.threshold),
16
- update: (pass, p) => { pass.strength = p.strength; pass.radius = p.radius; pass.threshold = p.threshold; } };
23
+ update: (pass, p) => { pass.strength = p.strength; pass.radius = p.radius; pass.threshold = p.threshold; },
24
+ // WebGPU: three's BloomNode returns only the glow, so it is added to the input. Same params do not give the same picture: UnrealBloomPass
25
+ // and bloom() differ in brightness (docs/plans/2026-11-03-webgpu-phase2.md §3), so strength is scaled by BLOOM_NODE_STRENGTH (measured,
26
+ // see above; tests/specs/post-webgpu.mjs keeps the two means within 3%); radius and threshold pass through unchanged (same mip lerp and luminance cut).
27
+ node: (input, { display, p }) => input.add(display.bloom(input, p.strength.mul(BLOOM_NODE_STRENGTH), p.radius, p.threshold)) };
17
28
  }
18
29
 
19
30
  /**
20
- * Ambient occlusion (soft contact shadows in corners; costly), hdr slot, off unless enabled.
21
- * @example post: [ao({ enabled: true })]
22
- * @param {{ enabled?: boolean, order?: number }} [o]
31
+ * Ambient occlusion (soft contact shadows in corners; heavy on weak devices), hdr slot, on when listed (enabled: false lists it off). radius: how far a surface looks for
32
+ * occluders, in world units; intensity: 0 = none, 1 = full. Defaults are three's GTAOPass defaults (no look chosen here).
33
+ * Order 20 puts it before bloom (30), so bloom sees the darkened corners. Other GTAOPass settings: post.object().
34
+ * @example engine.post.add(ao({ enabled: true, radius: 0.5 }))
35
+ * @param {{ radius?: number, intensity?: number, enabled?: boolean, order?: number }} [o]
23
36
  * @returns {PostEffect}
24
37
  */
25
- export function ao({ enabled = false, order = 20 } = {}) {
26
- return { name: 'ao', slot: 'hdr', order, enabled, costly: true,
27
- create: ({ scene, camera, width, height }) => new GTAOPass(scene, camera, width, height) };
38
+ export function ao({ radius = 0.25, intensity = 1, enabled, order = 20 } = {}) {
39
+ // update in place: GTAOPass keeps its targets and noise, so changing radius never rebuilds it
40
+ 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
+ create: ({ scene, camera, width, height, params }) => { const pass = new GTAOPass(scene, camera, width, height); update(pass, params); return pass; },
43
+ // 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
+ node: (input, { display, scenePass, camera, tsl, p }) => {
45
+ const n = display.ao(scenePass.getTextureNode('depth'), null, camera);
46
+ n.radius = p.radius;
47
+ return tsl.vec4(input.rgb.mul(tsl.mix(tsl.float(1), n.getTextureNode().r, p.intensity)), input.a);
48
+ } };
28
49
  }
package/index.d.ts CHANGED
@@ -3,22 +3,24 @@
3
3
  import type { PostEffect, ColorLike } from 'threedog';
4
4
  import type { Data3DTexture } from 'three';
5
5
 
6
- /** Color grading (ldr, fused): contrast / saturation 1 = unchanged, temperature -1 cool .. 1 warm, optional 3D LUT (e.g. LUTCubeLoader's texture3D) */
6
+ /** Color grading (ldr, fused): contrast / saturation 1 = unchanged, temperature -1 cool .. 1 warm, optional 3D LUT (e.g. LUTCubeLoader's texture3D). On when listed (enabled: false lists it off) */
7
7
  export function lut(o?: { lut?: Data3DTexture | null; amount?: number; contrast?: number; saturation?: number; temperature?: number; enabled?: boolean; order?: number }): PostEffect;
8
- /** Film grain (ldr, fused); size in device pixels, animated = new noise 24 times a second */
8
+ /** A 3D LUT that snaps every color to the nearest of `colors` (display sRGB, nearest filter), for lut({ lut }). colors: at least 2; size: cells per side (default 32). */
9
+ export function paletteLut(colors: ColorLike[], size?: number): Data3DTexture;
10
+ /** Film grain (ldr, fused); size in device pixels, animated = new noise 24 times a second. On when listed (enabled: false lists it off) */
9
11
  export function grain(o?: { amount?: number; size?: number; animated?: boolean; enabled?: boolean; order?: number }): PostEffect;
10
- /** Darker corners (ldr, fused); start: 0 center .. 1 corner */
12
+ /** Darker corners (ldr, fused); start: 0 center .. 1 corner. On when listed (enabled: false lists it off) */
11
13
  export function vignette(o?: { strength?: number; start?: number; enabled?: boolean; order?: number }): PostEffect;
12
- /** Red / blue shift apart toward the screen edge (ldr, fused; starts a fused group because it samples the input) */
14
+ /** Red / blue shift apart toward the screen edge (ldr, fused; starts a fused group because it samples the input). On when listed (enabled: false lists it off) */
13
15
  export function chromatic(o?: { amount?: number; enabled?: boolean; order?: number }): PostEffect;
14
- /** Depth of field (hdr, costly, reads scene depth; passes it on, so it can be on with outline when its order is lower, lines then stay sharp); meters / device pixels */
16
+ /** Depth of field (hdr, heavy on weak devices, reads scene depth; passes it on, so it can be on with outline when its order is lower, lines then stay sharp); meters / device pixels. On when added (enabled: false adds it off) */
15
17
  export function dof(o?: { focus?: number; range?: number; falloff?: number; maxBlur?: number; enabled?: boolean; order?: number }): PostEffect;
16
18
 
17
- /** Bloom (glow around bright pixels; hdr, costly: off by default on low-tier devices) */
19
+ /** Bloom (glow around bright pixels; hdr, heavy on weak devices). On when added (enabled: false adds it off) */
18
20
  export function bloom(o?: { strength?: number; radius?: number; threshold?: number; enabled?: boolean; order?: number }): PostEffect;
19
- /** Ambient occlusion (soft contact shadows in corners; hdr, costly, off unless enabled) */
20
- export function ao(o?: { enabled?: boolean; order?: number }): PostEffect;
21
- /** Outline (hdr, reads scene depth, off unless enabled). mode 'depth' (default) = silhouettes, 'normal' = creases (extra scene render, costly), 'both'; wobble = line jitter in pixels; offLayer = objects with that three.js layer enabled get no lines (use OUTLINE_OFF_LAYER) */
21
+ /** Ambient occlusion (soft contact shadows in corners; hdr, heavy on weak devices). On when added (enabled: false adds it off) */
22
+ export function ao(o?: { radius?: number; intensity?: number; enabled?: boolean; order?: number }): PostEffect;
23
+ /** Outline (hdr, reads scene depth). On when listed (enabled: false lists it off). mode 'depth' (default) = silhouettes, 'normal' = creases (an extra scene render), 'both'; wobble = line jitter in pixels; offLayer = objects with that three.js layer enabled get no lines (use OUTLINE_OFF_LAYER) */
22
24
  export function outline(o?: { color?: ColorLike; thickness?: number; strength?: number; mode?: 'depth' | 'normal' | 'both'; fadeWithDistance?: boolean; wobble?: number; offLayer?: number | null; enabled?: boolean; order?: number }): PostEffect;
23
25
  /** Layer number (29) for outline({ offLayer }): mesh.layers.enable(OUTLINE_OFF_LAYER) exempts that object from the lines */
24
26
  export const OUTLINE_OFF_LAYER: number;
package/index.js CHANGED
@@ -1,10 +1,16 @@
1
- // @threedog/post-effects: optional post effects for engine.post. The engine ships none (it owns no look); a style pack or a game adds the ones it wants:
2
- // import { vignette, grain, lut } from '@threedog/post-effects';
3
- // createEngine({ canvas, style: [lowpoly, postAdd(vignette({ enabled: true }), grain({ enabled: true }))] });
4
- // Style packs list bloom / ao / outline in their own style.post; they all import from here, never from each other.
5
- // hdr slot (linear, before tone mapping): bloom, ao, outline, dof. ldr slot (sRGB, after it): lut, grain, vignette, chromatic.
1
+ // @threedog/post-effects: optional post effects. The engine ships none (it owns no look); a style or a game adds the ones it wants, the one
2
+ // way every post effect gets in (engine.post.add). Each effect gives create (WebGL) and node (WebGPU), so one value runs on both:
3
+ // import { vignette, grain } from '@threedog/post-effects';
4
+ // engine.post.add(vignette()); // game code
5
+ // plugins/20-grain.js: export default grain(); // the game's plugins folder, or a style's style/plugins/ folder
6
+ // Styles bring bloom / ao / outline as their own plugin files; they all import from here, never from each other.
7
+ // Effects that exist only as TSL nodes (voxelGI, temporalAA, sunShafts, lightVolumes) live in the subpath @threedog/post-effects/tsl: they import three/webgpu, this entry does not.
8
+ // hdr slot (linear, before tone mapping): bloom, ao, outline, dof. ldr slot (display sRGB, after it): lut, paletteLut through lut, grain, vignette, chromatic.
6
9
  // lut / grain / vignette / chromatic carry a `fuse` GLSL snippet, so when several are on they run as one fullscreen pass.
7
- // All are off unless you pass enabled: true.
10
+ // Added = on: an effect given to engine.post.add (or exported by a plugin file) is on unless it says enabled: false (added off for the game to switch on later with
11
+ // handle.enabled = true); the engine's rule for every effect, so adding one never silently does nothing. Tier rule, the same as at skipOnLowTier in the engine's render/PostFX.js:
12
+ // an effect declares skipOnLowTier itself, the engine only follows that declaration, and says so in describe() and with one console note when it holds one. None here declare it, so the heavy
13
+ // ones (bloom, ao, dof, outline mode normal/both) stay the game's call on weak devices: read engine.tier and leave them out.
8
14
  import * as THREE from 'three';
9
15
  export { dof } from './dof.js';
10
16
  export { bloom, ao } from './hdr.js';
@@ -17,17 +23,19 @@ const identity = new THREE.Data3DTexture(new Uint8Array([0, 0, 0, 255, 255, 0, 0
17
23
  identity.format = THREE.RGBAFormat; identity.minFilter = identity.magFilter = THREE.LinearFilter; identity.unpackAlignment = 1; identity.needsUpdate = true;
18
24
 
19
25
  /**
20
- * Color grading in sRGB space (ldr slot): contrast, saturation, warm/cool shift and an optional 3D LUT, in one fused snippet.
26
+ * Color grading (ldr slot): contrast, saturation, warm/cool shift and an optional 3D LUT, in one fused snippet.
27
+ * It reads the picture after tone mapping and the output encoding (display sRGB, 0..1), so a LUT is one made on a finished display image, and
28
+ * nothing here tone-maps again; for a grade on linear light before the tone curve, write an hdr effect of your own.
21
29
  * @example
22
30
  * import { LUTCubeLoader } from 'three/addons/loaders/LUTCubeLoader.js';
23
31
  * const { texture3D } = await new LUTCubeLoader().loadAsync('/luts/warm.cube');
24
- * post: [lut({ enabled: true, lut: texture3D, amount: 0.8, saturation: 1.1, temperature: 0.2 })]
32
+ * engine.post.add(lut({ enabled: true, lut: texture3D, amount: 0.8, saturation: 1.1, temperature: 0.2 }))
25
33
  * @param {{ lut?: import('three').Data3DTexture | null, amount?: number, contrast?: number, saturation?: number, temperature?: number, enabled?: boolean, order?: number }} [o]
26
34
  * lut: a 3D LUT texture (null = only the numbers below); amount: how much of the LUT result to use (0..1); contrast, saturation: 1 = unchanged;
27
35
  * temperature: -1 cool .. 1 warm
28
36
  * @returns {PostEffect}
29
37
  */
30
- export function lut({ lut = null, amount = 1, contrast = 1, saturation = 1, temperature = 0, enabled = false, order = 10 } = {}) {
38
+ export function lut({ lut = null, amount = 1, contrast = 1, saturation = 1, temperature = 0, enabled, order = 10 } = {}) {
31
39
  return { name: 'lut', slot: 'ldr', order, enabled, params: { lut, amount, contrast, saturation, temperature },
32
40
  fuse: {
33
41
  uniforms: { uLutTex: 'sampler3D', uLutSize: 'float', uLutAmount: 'float', uLutContrast: 'float', uLutSaturation: 'float', uLutTemp: 'float' },
@@ -36,53 +44,96 @@ export function lut({ lut = null, amount = 1, contrast = 1, saturation = 1, temp
36
44
  glsl: `color.rgb += vec3(uLutTemp * 0.06, 0.0, -uLutTemp * 0.06);
37
45
  color.rgb = clamp((color.rgb - 0.5) * uLutContrast + 0.5, 0.0, 1.0);
38
46
  color.rgb = mix(vec3(dot(color.rgb, vec3(0.2126, 0.7152, 0.0722))), color.rgb, uLutSaturation);
39
- if (uLutAmount > 0.0) color.rgb = mix(color.rgb, texture(uLutTex, clamp(color.rgb, 0.0, 1.0) * ((uLutSize - 1.0) / uLutSize) + 0.5 / uLutSize).rgb, uLutAmount);` } };
47
+ if (uLutAmount > 0.0) color.rgb = mix(color.rgb, texture(uLutTex, clamp(color.rgb, 0.0, 1.0) * ((uLutSize - 1.0) / uLutSize) + 0.5 / uLutSize).rgb, uLutAmount);`,
48
+ // the same steps as the GLSL above; the LUT texture is not a live param (changing it rebuilds the chain), so its branch is chosen here
49
+ tsl: (color, uv, { tsl: T, p, params }) => {
50
+ let c = color.rgb.add(T.vec3(p.temperature.mul(0.06), 0, p.temperature.mul(-0.06)));
51
+ c = T.clamp(c.sub(0.5).mul(p.contrast).add(0.5), 0, 1);
52
+ c = T.mix(T.vec3(T.dot(c, T.vec3(0.2126, 0.7152, 0.0722))), c, p.saturation);
53
+ if (params.lut) { const n = params.lut.image.width; c = T.mix(c, T.texture3D(params.lut, T.clamp(c, 0, 1).mul((n - 1) / n).add(0.5 / n)).rgb, p.amount); }
54
+ return T.vec4(c, color.a);
55
+ } } };
56
+ }
57
+
58
+ /**
59
+ * A 3D LUT that snaps every color to the nearest of `colors` (nearest in display sRGB), for lut({ lut }): the picture then holds only those colors.
60
+ * Nearest filtering on purpose: a linear lookup would blend neighbors into colors outside the palette. Whatever runs after lut (grain, vignette) moves off it again.
61
+ * @example engine.post.add(lut({ lut: paletteLut([0x101014, 0x8a8a90, 0xf4f1e8]), saturation: 0 }))
62
+ * @param {import('three').ColorRepresentation[]} colors at least 2
63
+ * @param {number} [size] cells per side; a higher size places the borders between colors more finely
64
+ * @returns {import('three').Data3DTexture}
65
+ */
66
+ export function paletteLut(colors, size = 32) {
67
+ if (!Array.isArray(colors) || colors.length < 2) throw new Error('paletteLut(colors): colors must be an array of at least 2 colors, e.g. [0x101014, 0xf4f1e8]');
68
+ const pal = colors.map(c => new THREE.Color(c).getRGB({ r: 0, g: 0, b: 0 }, THREE.SRGBColorSpace));
69
+ const data = new Uint8Array(size ** 3 * 4);
70
+ for (let i = 0, b = 0; b < size; b++) for (let g = 0; g < size; g++) for (let r = 0; r < size; r++, i += 4) {
71
+ const x = r / (size - 1), y = g / (size - 1), z = b / (size - 1);
72
+ let best = pal[0], bestD = Infinity;
73
+ for (const c of pal) { const d = (c.r - x) ** 2 + (c.g - y) ** 2 + (c.b - z) ** 2; if (d < bestD) { bestD = d; best = c; } }
74
+ data.set([best.r * 255 + 0.5, best.g * 255 + 0.5, best.b * 255 + 0.5, 255], i);
75
+ }
76
+ const t = new THREE.Data3DTexture(data, size, size, size);
77
+ t.format = THREE.RGBAFormat; t.minFilter = t.magFilter = THREE.NearestFilter; t.unpackAlignment = 1; t.needsUpdate = true;
78
+ return t;
40
79
  }
41
80
 
42
81
  /**
43
82
  * Film grain (ldr slot): per-pixel noise, a little weaker in highlights.
44
- * @example post: [grain({ enabled: true, amount: 0.06 })]
83
+ * @example engine.post.add(grain({ enabled: true, amount: 0.06 }))
45
84
  * @param {{ amount?: number, size?: number, animated?: boolean, enabled?: boolean, order?: number }} [o]
46
85
  * amount: noise strength; size: grain size in device pixels; animated: new noise every frame (24 per second)
47
86
  * @returns {PostEffect}
48
87
  */
49
- export function grain({ amount = 0.06, size = 1, animated = true, enabled = false, order = 30 } = {}) {
88
+ export function grain({ amount = 0.06, size = 1, animated = true, enabled, order = 30 } = {}) {
50
89
  return { name: 'grain', slot: 'ldr', order, enabled, params: { amount, size, animated },
51
90
  fuse: {
52
91
  uniforms: { uGrainAmount: 'float', uGrainSize: 'float', uGrainAnimated: 'float' },
53
92
  values: p => ({ uGrainAmount: p.amount, uGrainSize: Math.max(1, p.size), uGrainAnimated: p.animated ? 1 : 0 }),
54
93
  glsl: `float n = fxHash(floor(vUv * uResolution / uGrainSize) + (uGrainAnimated > 0.5 ? floor(uTime * 24.0) * 17.0 : 0.0)) - 0.5;
55
- color.rgb += n * uGrainAmount * (1.0 - 0.5 * dot(color.rgb, vec3(0.299, 0.587, 0.114)));` } };
94
+ color.rgb += n * uGrainAmount * (1.0 - 0.5 * dot(color.rgb, vec3(0.299, 0.587, 0.114)));`,
95
+ // same shape; three's hash() stands in for fxHash, so the noise pattern differs from WebGL's (its strength does not)
96
+ tsl: (color, uv, { tsl: T, p, time, resolution }) => {
97
+ const q = T.floor(uv.mul(resolution).div(T.max(p.size, 1))), frame = T.floor(time.mul(24)).mul(17).mul(p.animated);
98
+ const n = T.hash(q.x.add(q.y.mul(1103)).add(frame)).sub(0.5);
99
+ return T.vec4(color.rgb.add(n.mul(p.amount).mul(T.float(1).sub(T.dot(color.rgb, T.vec3(0.299, 0.587, 0.114)).mul(0.5)))), color.a);
100
+ } } };
56
101
  }
57
102
 
58
103
  /**
59
104
  * Vignette (ldr slot): darker screen corners.
60
- * @example post: [vignette({ enabled: true, strength: 0.4 })]
105
+ * @example engine.post.add(vignette({ enabled: true, strength: 0.4 }))
61
106
  * @param {{ strength?: number, start?: number, enabled?: boolean, order?: number }} [o]
62
107
  * strength: darkness at the corners (0..1); start: distance from the center where darkening begins (0 center .. 1 corner)
63
108
  * @returns {PostEffect}
64
109
  */
65
- export function vignette({ strength = 0.35, start = 0.45, enabled = false, order = 20 } = {}) {
110
+ export function vignette({ strength = 0.35, start = 0.45, enabled, order = 20 } = {}) {
66
111
  return { name: 'vignette', slot: 'ldr', order, enabled, params: { strength, start },
67
112
  fuse: {
68
113
  uniforms: { uVigStrength: 'float', uVigStart: 'float' },
69
114
  values: p => ({ uVigStrength: p.strength, uVigStart: p.start }),
70
- glsl: 'color.rgb *= 1.0 - uVigStrength * smoothstep(uVigStart, 1.0, length(vUv - 0.5) * 1.4142);' } };
115
+ glsl: 'color.rgb *= 1.0 - uVigStrength * smoothstep(uVigStart, 1.0, length(vUv - 0.5) * 1.4142);',
116
+ tsl: (color, uv, { tsl: T, p }) => T.vec4(color.rgb.mul(T.float(1).sub(p.strength.mul(T.smoothstep(p.start, 1, uv.sub(0.5).length().mul(1.4142))))), color.a) } };
71
117
  }
72
118
 
73
119
  /**
74
120
  * Chromatic aberration (ldr slot): red and blue shift apart toward the screen edge. Samples the pass input, so it starts a fused group
75
121
  * (default order puts it first, so it still joins the others).
76
- * @example post: [chromatic({ enabled: true, amount: 0.004 })]
122
+ * @example engine.post.add(chromatic({ enabled: true, amount: 0.004 }))
77
123
  * @param {{ amount?: number, enabled?: boolean, order?: number }} [o] amount: edge shift in screen fractions
78
124
  * @returns {PostEffect}
79
125
  */
80
- export function chromatic({ amount = 0.004, enabled = false, order = 5 } = {}) {
126
+ export function chromatic({ amount = 0.004, enabled, order = 5 } = {}) {
81
127
  return { name: 'chromatic', slot: 'ldr', order, enabled, params: { amount },
82
128
  fuse: {
83
129
  reads: true,
84
130
  uniforms: { uChromaAmount: 'float' },
85
131
  values: p => ({ uChromaAmount: p.amount }),
86
132
  glsl: `vec2 off = (vUv - 0.5) * uChromaAmount;
87
- color.r = texture2D(tDiffuse, vUv + off).r; color.b = texture2D(tDiffuse, vUv - off).b;` } };
133
+ color.r = texture2D(tDiffuse, vUv + off).r; color.b = texture2D(tDiffuse, vUv - off).b;`,
134
+ // input: the image before this effect as a texture (reads: true), sampled at the shifted uvs
135
+ tsl: (color, uv, { tsl: T, p, input }) => {
136
+ const off = uv.sub(0.5).mul(p.amount);
137
+ return T.vec4(input.sample(uv.add(off)).r, color.g, input.sample(uv.sub(off)).b, color.a);
138
+ } } };
88
139
  }
package/outline.js CHANGED
@@ -2,10 +2,11 @@
2
2
  // optional hand-drawn wobble and per-object exemption through a three.js layer.
3
3
  import * as THREE from 'three';
4
4
  import { Pass, FullScreenQuad } from 'three/addons/postprocessing/Pass.js';
5
+ import { RESERVED_LAYERS } from 'threedog/layers';
5
6
  /** @import { PostEffect } from 'threedog' */
6
7
 
7
8
  /** Layer number to put on objects that should get no outline: mesh.layers.enable(OUTLINE_OFF_LAYER), with outline({ offLayer: OUTLINE_OFF_LAYER }) */
8
- export const OUTLINE_OFF_LAYER = 29;
9
+ export const OUTLINE_OFF_LAYER = RESERVED_LAYERS.outlineOff;
9
10
  const MODES = { depth: 0, normal: 1, both: 2 };
10
11
 
11
12
  class OutlinePass extends Pass {
@@ -103,18 +104,84 @@ function apply(pass, p) {
103
104
  /**
104
105
  * Dark lines (cartoon look), hdr slot, before bloom so the glow does not blur the lines.
105
106
  * mode 'depth' (default): silhouettes where depth jumps; 'normal': creases where surface normals turn (the scene is drawn once more with
106
- * normals; costly, off by default on low-tier devices); 'both': either. Objects can opt out of the lines with offLayer.
107
+ * normals; heavy on weak devices); 'both': either. Objects can opt out of the lines with offLayer.
107
108
  * @example
108
- * post: [outline({ enabled: true, color: 0x222222, thickness: 1.5 })]
109
- * post: [outline({ enabled: true, mode: 'both', wobble: 1.5, offLayer: OUTLINE_OFF_LAYER })] // hand-drawn; then: sky.layers.enable(OUTLINE_OFF_LAYER)
109
+ * engine.post.add(outline({ enabled: true, color: 0x222222, thickness: 1.5 }))
110
+ * engine.post.add(outline({ enabled: true, mode: 'both', wobble: 1.5, offLayer: OUTLINE_OFF_LAYER })) // hand-drawn; then: sky.layers.enable(OUTLINE_OFF_LAYER)
110
111
  * @param {{ color?: any, thickness?: number, strength?: number, mode?: 'depth' | 'normal' | 'both', fadeWithDistance?: boolean, wobble?: number,
111
112
  * offLayer?: number | null, enabled?: boolean, order?: number }} [o]
112
113
  * fadeWithDistance: lines fade out in the far 40..90% of the camera range (default true); wobble: line jitter in pixels (0 = straight);
113
114
  * offLayer: objects with this three.js layer enabled get no outline (costs one extra render of just those objects; null = off)
114
115
  * @returns {PostEffect}
115
116
  */
116
- export function outline({ color = 0x222222, thickness = 1, strength = 0.8, mode = 'depth', fadeWithDistance = true, wobble = 0, offLayer = null, enabled = false, order = 10 } = {}) {
117
- return { name: 'outline', slot: 'hdr', order, enabled, needsDepth: true, costly: mode !== 'depth', params: { color, thickness, strength, mode, fadeWithDistance, wobble, offLayer },
117
+ export function outline({ color = 0x222222, thickness = 1, strength = 0.8, mode = 'depth', fadeWithDistance = true, wobble = 0, offLayer = null, enabled, order = 10 } = {}) {
118
+ return { name: 'outline', slot: 'hdr', order, enabled, needsDepth: true, params: { color, thickness, strength, mode, fadeWithDistance, wobble, offLayer },
118
119
  create: ({ scene, camera, params }) => { const pass = new OutlinePass(scene, camera, params); apply(pass, params); return pass; },
119
- update: apply };
120
+ update: apply, node: outlineNode };
121
+ }
122
+
123
+ /**
124
+ * WebGPU: the same steps as OutlinePass's fragment shader, as one node (not three's OutlineNode, which outlines selected objects, a different
125
+ * effect). Depth comes from the scene pass; the normal and mask views are extra scene renders made through ctx.display.pass, so this file never
126
+ * 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.
127
+ * @param {any} input @param {any} ctx
128
+ */
129
+ function outlineNode(input, { tsl: T, display, scenePass, scene, camera, params, p }) {
130
+ const mode = MODES[params.mode];
131
+ if (mode === undefined) throw new Error(`outline: unknown mode '${params.mode}', use 'depth' | 'normal' | 'both'`);
132
+ const near = T.uniform(camera.near).onRenderUpdate(() => camera.near), far = T.uniform(camera.far).onRenderUpdate(() => camera.far);
133
+ const ortho = T.uniform(0).onRenderUpdate(() => (camera.isOrthographicCamera ? 1 : 0));
134
+ // the color param may be a number (then ctx.p holds a float uniform, not a color) or a Color: read the param itself every render
135
+ const tint = new THREE.Color(), col = T.uniform(tint).onRenderUpdate(() => { tint.set(params.color); });
136
+ // distance from the camera, from a depth texture; the depth -> view z helpers follow the backend's depth range, the GLSL does it by hand
137
+ const lin = (tex, uv) => { const d = tex.sample(uv).x; return T.select(ortho.greaterThan(0.5), T.orthographicDepthToViewZ(d, near, far), T.perspectiveDepthToViewZ(d, near, far)).negate(); };
138
+ const depthTex = scenePass.getTextureNode('depth');
139
+ const texel = T.vec2(1).div(T.screenSize), o = texel.mul(p.thickness), base = T.screenUV;
140
+ const nb = [T.vec2(o.x, 0), T.vec2(o.x.negate(), 0), T.vec2(0, o.y), T.vec2(0, o.y.negate())]; // the four neighbors, thickness apart
141
+ // wobble: value noise on the pixel grid, redrawn 8 times a second (flip-book trembling); the GLSL counts its own clock modulo 64 s the same way
142
+ const h2 = q => T.fract(T.sin(T.dot(q, T.vec2(127.1, 311.7))).mul(43758.5453));
143
+ const vn = q => { const i = T.floor(q), f0 = T.fract(q), f = f0.mul(f0).mul(f0.mul(-2).add(3));
144
+ return T.mix(T.mix(h2(i), h2(i.add(T.vec2(1, 0))), f.x), T.mix(h2(i.add(T.vec2(0, 1))), h2(i.add(T.vec2(1, 1))), f.x), f.y); };
145
+ const tick = T.floor(T.mod(T.time, 64).mul(8)), px = base.div(texel).mul(0.04);
146
+ const jitter = T.vec2(vn(px.add(tick)), vn(px.add(17.3).add(tick))).sub(0.5).mul(2).mul(p.wobble).mul(texel);
147
+ const uv = T.select(p.wobble.greaterThan(0), base.add(jitter), base);
148
+ const d = lin(depthTex, uv);
149
+ let edge = T.float(0);
150
+ if (mode !== 1) {
151
+ const e = nb.reduce((s, n) => s.add(lin(depthTex, uv.add(n)).sub(d).abs()), T.float(0));
152
+ edge = T.smoothstep(0.08, 0.3, e.div(T.max(d, 0.5)).mul(4));
153
+ }
154
+ // An extra render of the scene with one material, no background or fog. three's MeshNormalNodeMaterial stores its packed normal as an sRGB
155
+ // color (decoded to linear, so the canvas looks like WebGL's), unlike WebGL's MeshNormalMaterial in a render target, so the sample is
156
+ // re-encoded with the sRGB curve before unpacking; the clear is the sRGB (0.5, 0.5, 1) for the same reason: an empty pixel then reads as a
157
+ // normal facing the camera (as OutlinePass._pass), and for the mask its red (0.21 linear) stays below the > 0.5 test
158
+ const view = (mat, layer) => {
159
+ const v = display.pass(scene, camera);
160
+ v.overrideMaterial = mat;
161
+ const L = layer && new THREE.Layers(), run = v.updateBefore.bind(v), free = v.dispose.bind(v), clear = new THREE.Color(), was = new THREE.Color();
162
+ if (L) v.setLayers(L);
163
+ v.updateBefore = frame => {
164
+ const r = frame.renderer, bg = scene.background, bgNode = scene.backgroundNode, fog = scene.fog, a = r.getClearAlpha();
165
+ if (L) L.set(params.offLayer);
166
+ r.getClearColor(was);
167
+ r.setClearColor(clear.setRGB(0.5, 0.5, 1, THREE.SRGBColorSpace), 1);
168
+ scene.background = scene.backgroundNode = null; scene.fog = null; // three prefers backgroundNode over background, so both go
169
+ try { run(frame); } finally { scene.background = bg; scene.backgroundNode = bgNode; scene.fog = fog; r.setClearColor(was, a); }
170
+ };
171
+ v.dispose = () => { free(); mat.dispose(); };
172
+ return v;
173
+ };
174
+ if (mode !== 0) {
175
+ const nTex = view(new THREE.MeshNormalMaterial()).getTextureNode(), unpack = q => T.sRGBTransferOETF(nTex.sample(q).xyz).mul(2).sub(1), n = unpack(uv);
176
+ const k = nb.reduce((s, q) => s.add(T.float(1).sub(T.dot(n, unpack(uv.add(q))))), T.float(0));
177
+ edge = T.max(edge, T.smoothstep(0.35, 0.8, k));
178
+ }
179
+ edge = edge.mul(T.select(p.fadeWithDistance.greaterThan(0.5), T.float(1).sub(T.smoothstep(far.mul(0.4), far.mul(0.9), d)), T.float(1)));
180
+ if (params.offLayer != null) {
181
+ const m = view(new THREE.MeshBasicMaterial({ color: 0xffffff }), true), mTex = m.getTextureNode(), mDepth = m.getTextureNode('depth');
182
+ // object in the exempt layer at this pixel: its own render is not behind what the scene depth saw (unwobbled uv, as the GLSL)
183
+ const masked = q => T.select(mTex.sample(q).r.greaterThan(0.5).and(lin(mDepth, q).lessThanEqual(lin(depthTex, q).add(0.05))), T.float(1), T.float(0));
184
+ edge = edge.mul(T.float(1).sub(nb.reduce((s, q) => T.max(s, masked(base.add(q))), masked(base))));
185
+ }
186
+ return T.vec4(T.mix(input.rgb, col, edge.mul(p.strength)), input.a);
120
187
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threedog/post-effects",
3
- "version": "0.2.0",
3
+ "version": "0.7.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": {
@@ -10,6 +10,9 @@
10
10
  },
11
11
  "homepage": "https://github.com/penstic123-code/ThreeDog.js-Game-Engine#readme",
12
12
  "type": "module",
13
+ "engines": {
14
+ "node": "^20.19.0 || >=22.12.0"
15
+ },
13
16
  "main": "./index.js",
14
17
  "types": "./index.d.ts",
15
18
  "exports": {
@@ -17,6 +20,10 @@
17
20
  "types": "./index.d.ts",
18
21
  "default": "./index.js"
19
22
  },
23
+ "./tsl": {
24
+ "types": "./tsl.d.ts",
25
+ "default": "./tsl.js"
26
+ },
20
27
  "./package.json": "./package.json"
21
28
  },
22
29
  "files": [
@@ -24,7 +31,7 @@
24
31
  "*.d.ts"
25
32
  ],
26
33
  "peerDependencies": {
27
- "threedog": "^0.2.0",
34
+ "threedog": "^0.7.0",
28
35
  "three": "^0.187.0"
29
36
  }
30
37
  }
package/tsl.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ // Types of @threedog/post-effects/tsl for code that imports it from the published package.
2
+ import type { PostEffect } from 'threedog';
3
+ import type { Box3, Light } from 'three';
4
+
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 */
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
+ /** Temporal antialiasing (three's TRAANode; last in hdr): clears the dots of stochastic effects before it and replaces MSAA while on. WebGPURenderer only */
8
+ export function temporalAA(o?: { enabled?: boolean; order?: number; name?: string }): PostEffect;
9
+ /** 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 */
10
+ export function sunShafts(o?: { light?: Light; density?: number; maxDensity?: number; falloff?: number; color?: any; steps?: number; setup?: (rays: any) => void; enabled?: boolean; order?: number; name?: string }): PostEffect;
11
+ /** Lit air in a box: spot cones and point glows with shadows (three's VolumeNodeMaterial; hdr). Point and spot lights only, the sun does nothing here. WebGPURenderer only */
12
+ export function lightVolumes(o: { bounds: Box3; density?: number; steps?: number; scale?: number; blur?: number; scattering?: (tsl: any, at: { positionRay: any; density: any }) => any; enabled?: boolean; order?: number; name?: string }): PostEffect;
package/tsl.js ADDED
@@ -0,0 +1,125 @@
1
+ // @threedog/post-effects/tsl: post effects that exist only as TSL nodes, for games that chose WebGPU when they started.
2
+ // import { voxelGI, temporalAA } from '@threedog/post-effects/tsl';
3
+ // engine.post.add(voxelGI({ bounds })); engine.post.add(temporalAA());
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
+ // 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;
9
+ // voxelGI also on WebGPURenderer's WebGL2 backend. On a WebGLRenderer the game chose, adding any of them throws by name.
10
+ import { vxgi } from 'three/addons/lighting/vxgi/VXGINode.js';
11
+ import { traa } from 'three/addons/tsl/display/TRAANode.js';
12
+ import { godrays } from 'three/addons/tsl/display/GodraysNode.js';
13
+ import { depthAwareBlend } from 'three/addons/tsl/display/depthAwareBlend.js';
14
+ import { gaussianBlur } from 'three/addons/tsl/display/GaussianBlurNode.js';
15
+ import { bayer16 } from 'three/addons/tsl/math/Bayer.js';
16
+ import { Box3, BoxGeometry, Color, Layers, Mesh, Vector3, VolumeNodeMaterial } from 'three/webgpu';
17
+ import { RESERVED_LAYERS } from 'threedog/layers';
18
+ /** @import { PostEffect } from 'threedog' */
19
+
20
+ const { lightVolumes: VOLUME_LAYER } = RESERVED_LAYERS;
21
+
22
+ /**
23
+ * Real-time bounced light from a voxel volume (three's vxgi), added to the scene color in the hdr slot. Only on three's WebGPU backend; held off on low tier.
24
+ * Light may move every frame (three notices); geometry that moves needs a new voxelization, too slow per frame, so keep moving things out of the volume
25
+ * (gi.volume.layers) and call gi.needsUpdate = true only for a rare change. It injects direct light only: sky light stays the game's. Metal counts as diffuse.
26
+ * What occlusion culling hides stays in the volume (its layer is on gi.volume.layers; setup can take it off). Changing any effect of the chain rebuilds the chain, which voxelizes the scene again: a stall.
27
+ * @param {{ resolution?: number, bounds?: import('three').Box3, intensity?: number, occlusion?: number, setup?: (gi: any) => void, order?: number, enabled?: boolean, name?: string }} [o]
28
+ * resolution: voxels along the longest side; bounds: the part of the world to voxelize (default: the whole scene, so a far sky mesh makes voxels huge);
29
+ * intensity: how strong the bounce is; occlusion: 0 to 1, how much the voxel occlusion darkens the picture (it darkens direct light too, so it starts at 0);
30
+ * setup(gi): gets three's VXGINode each time the chain builds it (coneCount, volume.bounces ...).
31
+ * @returns {PostEffect}
32
+ */
33
+ export function voxelGI({ resolution = 128, bounds, intensity = 1, occlusion = 0, setup, order = 2, enabled, name = 'voxelGI' } = {}) {
34
+ /** @type {any} */ let gi = null;
35
+ return { name, slot: 'hdr', order, enabled, backend: 'webgpu', skipOnLowTier: true, needsBuffers: ['normal', 'diffuse'], params: { intensity, occlusion },
36
+ node(input, ctx) {
37
+ const { tsl, p, scenePass, scene, camera, display } = ctx;
38
+ gi = display.own(vxgi(scenePass.getTextureNode('depth'), scenePass.getTextureNode('normal'), scene, camera, resolution));
39
+ display.own({ dispose() { gi = null; } });
40
+ gi.volume.layers.enable(RESERVED_LAYERS.occlusionHidden); // a wall out of the camera's sight still throws its color
41
+ if (bounds) gi.volume.bounds.copy(bounds);
42
+ setup?.(gi);
43
+ const light = gi.getGINode().rgb.mul(scenePass.getTextureNode('diffuse').rgb).mul(p.intensity);
44
+ return tsl.vec4(input.rgb.mul(tsl.mix(tsl.float(1), gi.getAONode().r, p.occlusion)).add(light), input.a);
45
+ },
46
+ // voxelSize is 0 until the first frame voxelized the scene
47
+ facts: () => (gi ? { resolution, voxelSize: +gi.volume.voxelSizeNode.value.toFixed(3) } : null) };
48
+ }
49
+
50
+ /**
51
+ * Temporal antialiasing (three's TRAANode): averages jittered frames, so it also clears the dots of every stochastic effect before it (voxelGI, lightVolumes).
52
+ * Runs last in the hdr slot. It replaces MSAA while it is on. Moving things can trail; judge it in motion.
53
+ * @param {{ order?: number, enabled?: boolean, name?: string }} [o]
54
+ * @returns {PostEffect}
55
+ */
56
+ 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)) };
59
+ }
60
+
61
+ /**
62
+ * Light shafts from the sun (or a point light) through gaps, from its shadow map (three's GodraysNode), blended over the picture in the hdr slot. The light and the things that make the
63
+ * gaps must cast shadows. It lights the air everywhere the shadow map says is lit, so a big open scene turns to haze: it reads best where most of the air is in shadow (a room with a window).
64
+ * @param {{ light?: any, density?: number, maxDensity?: number, falloff?: number, color?: any, steps?: number, setup?: (rays: any) => void, order?: number, enabled?: boolean, name?: string }} [o]
65
+ * light: default engine.lights.sun; one that is not in the scene or casts no shadow throws by name; density and maxDensity: how thick the air is, and the ceiling of what one pixel can gather; falloff: how fast the shafts fade away from the light;
66
+ * setup(rays): gets three's GodraysNode each time the chain builds it.
67
+ * @returns {PostEffect}
68
+ */
69
+ 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 },
71
+ node(input, { engine, tsl, p, scenePass, camera, display }) {
72
+ const depth = scenePass.getTextureNode('depth'), sun = light ?? engine.lights?.sun;
73
+ // 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
74
+ if (!sun?.parent || !sun.castShadow) throw new Error('sunShafts: no light to follow; give sunShafts({ light }) a light that is in the scene and casts shadows (default: engine.lights.sun)');
75
+ const rays = display.own(godrays(depth, camera, sun));
76
+ Object.assign(rays, { density: p.density, maxDensity: p.maxDensity, distanceAttenuation: p.falloff });
77
+ rays.raymarchSteps.value = steps;
78
+ setup?.(rays);
79
+ const blended = depthAwareBlend(display.texture(input), rays.getTextureNode(), depth, camera, { blendColor: p.color });
80
+ return tsl.vec4(blended.rgb, input.a);
81
+ } };
82
+ }
83
+
84
+ /**
85
+ * Lit air inside a box: spot light cones and point light glows with their shadows (three's VolumeNodeMaterial), drawn at a fraction of the screen size (scale), blurred and added in the hdr slot.
86
+ * Reads point and spot lights only: three skips lights at infinity, so the sun and directional lights do nothing here (use sunShafts). Dithered, so temporalAA after it clears the pattern.
87
+ * @param {{ bounds: Box3, density?: number, steps?: number, scale?: number, blur?: number, scattering?: (tsl: any, at: { positionRay: any, density: any }) => any, order?: number, enabled?: boolean, name?: string }} o
88
+ * bounds: the box of air, required (the march covers it, so keep it tight); density: how thick the air is; scale: fraction of the screen size the air is drawn at; scattering: density per point, for smoke or ground fog
89
+ * (it gets the world position of the sample and the density uniform).
90
+ * @returns {PostEffect}
91
+ */
92
+ export function lightVolumes({ bounds, density = 0.3, steps = 16, scale = 0.25, blur = 4, scattering, order = 200, enabled, name = 'lightVolumes' } = /** @type {any} */ ({})) {
93
+ if (!bounds?.isBox3) throw new Error('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, { engine, tsl, p, scene, camera, scenePass, display }) {
96
+ const size = bounds.getSize(new Vector3()), mat = new VolumeNodeMaterial();
97
+ mat.steps = steps;
98
+ mat.offsetNode = bayer16(tsl.screenCoordinate);
99
+ mat.scatteringNode = ({ positionRay }) => (scattering ? scattering(tsl, { positionRay, density: p.density }) : p.density);
100
+ mat.depthNode = scenePass.getTextureNode('depth').sample(tsl.screenUV);
101
+ const box = new Mesh(new BoxGeometry(size.x, size.y, size.z), mat);
102
+ bounds.getCenter(box.position);
103
+ box.receiveShadow = true;
104
+ box.layers.set(VOLUME_LAYER); // not on the view camera: only the small pass below draws it, and voxel GI or probes never take it for geometry
105
+ scene.add(box);
106
+ const layers = new Layers(); layers.set(VOLUME_LAYER);
107
+ const air = display.pass(scene, camera, { depthBuffer: false, samples: 0 });
108
+ air.setLayers(layers); air.setResolutionScale(scale);
109
+ // a pass clears to the scene's background and the renderer's clear color; this one is added over the picture, so it must start from nothing
110
+ const draw = air.updateBefore;
111
+ const lamps = new Set();
112
+ let look = 0;
113
+ air.updateBefore = frame => {
114
+ // three lights a pass only with the lights on its layers; a new lamp is found within half a second
115
+ if (look-- <= 0) { look = 30; for (const l of engine._gameLights.all()) if (!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); }
120
+ };
121
+ display.own({ dispose() { for (const l of lamps) l.layers.disable(VOLUME_LAYER); box.removeFromParent(); box.geometry.dispose(); mat.dispose(); } });
122
+ return tsl.vec4(input.rgb.add(display.own(gaussianBlur(air.getTextureNode(), blur)).rgb), input.a);
123
+ },
124
+ facts: () => ({ lights: 'point and spot only; the sun does nothing here (sunShafts)' }) };
125
+ }