@threedog/post-effects 0.5.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 CHANGED
@@ -1,26 +1,37 @@
1
1
  # @threedog/post-effects
2
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), `grain`, `vignette`, `chromatic` (chromatic aberration) fused into one fullscreen LDR pass. Import only what you use; the engine itself ships no effects.
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
4
 
5
5
  ```sh
6
- npm install @threedog/post-effects@0.5
6
+ npm install @threedog/post-effects@0.7
7
7
  ```
8
8
 
9
- This describes 0.5.0: `npm install @threedog/post-effects@0.5` (games made in the [repository](https://github.com/penstic123-code/ThreeDog.js-Game-Engine) already have it).
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
10
 
11
- Each effect is one value that runs on WebGL and on WebGPU. It goes in the way every post effect does, `engine.look.post.add`:
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
12
 
13
13
  ```js
14
14
  import { bloom, vignette } from '@threedog/post-effects';
15
15
 
16
- engine.look.post.add(bloom({ strength: 0.6 })); // game code
16
+ engine.post.add(bloom({ strength: 0.6 })); // game code
17
17
  // or a file in the game's plugins/ folder, or in a style's style/plugins/ folder:
18
18
  // plugins/20-vignette.js
19
19
  export default vignette();
20
20
  ```
21
21
 
22
- An added effect is on unless it says `enabled: false`; the costly ones (`bloom`, `ao`, `dof`, outline `normal` / `both`) that a style's plugins bring start off on low-tier devices. On / off and tuning: `engine.look.post.set({ bloom: false, 'ao.radius': 0.6 })`.
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
- Docs ship with the engine: `node_modules/threedog/docs/recipes/52-look.md` (post-effect chain, order, depth readers) and `docs/AI.md`.
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`.
25
36
 
26
37
  Peer dependencies: `threedog` and `three` (the same copy the game uses). MIT license.
package/dof.js CHANGED
@@ -50,18 +50,18 @@ 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 engine.look.post.add(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
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 },
64
+ return { name: 'dof', slot: 'hdr', order, enabled, needsDepth: true, params: { focus, range, falloff, maxBlur },
65
65
  create: ({ camera, params }) => { const pass = new DofPass(camera); update(pass, params); return pass; }, update, node: dofNode };
66
66
  }
67
67
 
package/hdr.js CHANGED
@@ -1,4 +1,4 @@
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';
@@ -13,12 +13,12 @@ const BLOOM_NODE_STRENGTH = 3;
13
13
 
14
14
  /**
15
15
  * Bloom (glow around bright pixels), hdr slot. Off by default on low-tier devices.
16
- * @example engine.look.post.add(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 }))
17
17
  * @param {{ strength?: number, radius?: number, threshold?: number, enabled?: boolean, order?: number }} [o]
18
18
  * @returns {PostEffect}
19
19
  */
20
20
  export function bloom({ strength = 0.35, radius = 0.5, threshold = 0.85, enabled, order = 30 } = {}) {
21
- 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 },
22
22
  create: ({ width, height, params: p }) => new UnrealBloomPass(new THREE.Vector2(width, height), p.strength, p.radius, p.threshold),
23
23
  update: (pass, p) => { pass.strength = p.strength; pass.radius = p.radius; pass.threshold = p.threshold; },
24
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
@@ -28,17 +28,17 @@ export function bloom({ strength = 0.35, radius = 0.5, threshold = 0.85, enabled
28
28
  }
29
29
 
30
30
  /**
31
- * Ambient occlusion (soft contact shadows in corners; costly), hdr slot, on when listed (enabled: false lists it off). radius: how far a surface looks for
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
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) and outline, so they see the darkened corners. Other GTAOPass settings: post.object().
34
- * @example engine.look.post.add(ao({ enabled: true, radius: 0.5 }))
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
35
  * @param {{ radius?: number, intensity?: number, enabled?: boolean, order?: number }} [o]
36
36
  * @returns {PostEffect}
37
37
  */
38
38
  export function ao({ radius = 0.25, intensity = 1, enabled, order = 20 } = {}) {
39
39
  // update in place: GTAOPass keeps its targets and noise, so changing radius never rebuilds it
40
40
  const update = (pass, p) => { pass.updateGtaoMaterial({ radius: p.radius }); pass.blendIntensity = p.intensity; };
41
- return { name: 'ao', slot: 'hdr', order, enabled, costly: true, params: { radius, intensity }, update,
41
+ return { name: 'ao', slot: 'hdr', order, enabled, params: { radius, intensity }, update,
42
42
  create: ({ scene, camera, width, height, params }) => { const pass = new GTAOPass(scene, camera, width, height); update(pass, params); return pass; },
43
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
44
  node: (input, { display, scenePass, camera, tsl, p }) => {
package/index.d.ts CHANGED
@@ -5,20 +5,22 @@ import type { Data3DTexture } from 'three';
5
5
 
6
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
+ /** 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;
8
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
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
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. On when listed (enabled: false lists it off); costly, so it still starts off on low-tier devices */
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). Default enabled: on; costly, so it starts off on low-tier devices when a style plugin brings it (look.post.set({ bloom: true }) turns it on; threedog shot renders the high tier unless --tier low) */
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). On when added (enabled: false adds it off); costly, so from a style plugin it starts off on low-tier devices (look.post.set({ ao: true }) turns it on) */
21
+ /** Ambient occlusion (soft contact shadows in corners; hdr, heavy on weak devices). On when added (enabled: false adds it off) */
20
22
  export function ao(o?: { radius?: number; intensity?: number; enabled?: boolean; order?: number }): PostEffect;
21
- /** Outline (hdr, reads scene depth). On when listed (enabled: false lists it off). 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) */
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,14 +1,16 @@
1
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.look.post.add). Each effect gives create (WebGL) and node (WebGPU), so one value runs on both:
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
3
  // import { vignette, grain } from '@threedog/post-effects';
4
- // engine.look.post.add(vignette()); // game code
4
+ // engine.post.add(vignette()); // game code
5
5
  // plugins/20-grain.js: export default grain(); // the game's plugins folder, or a style's style/plugins/ folder
6
6
  // Styles bring bloom / ao / outline as their own plugin files; they all import from here, never from each other.
7
- // hdr slot (linear, before tone mapping): bloom, ao, outline, dof. ldr slot (sRGB, after it): lut, grain, vignette, chromatic.
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.
8
9
  // lut / grain / vignette / chromatic carry a `fuse` GLSL snippet, so when several are on they run as one fullscreen pass.
9
- // Added = on: an effect given to look.post.add (or exported by a plugin file) is on unless it says enabled: false (list it off for the game to switch on later with
10
- // look.post.set({ '<name>.enabled': true })); the engine's rule for every effect, so listing one never silently does nothing. The costly ones
11
- // (bloom, ao, dof, outline mode normal/both) start off on low-tier devices when a style's plugins bring them; engine.look.post.set({ name: true }) turns them on.
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.
12
14
  import * as THREE from 'three';
13
15
  export { dof } from './dof.js';
14
16
  export { bloom, ao } from './hdr.js';
@@ -21,11 +23,13 @@ const identity = new THREE.Data3DTexture(new Uint8Array([0, 0, 0, 255, 255, 0, 0
21
23
  identity.format = THREE.RGBAFormat; identity.minFilter = identity.magFilter = THREE.LinearFilter; identity.unpackAlignment = 1; identity.needsUpdate = true;
22
24
 
23
25
  /**
24
- * 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.
25
29
  * @example
26
30
  * import { LUTCubeLoader } from 'three/addons/loaders/LUTCubeLoader.js';
27
31
  * const { texture3D } = await new LUTCubeLoader().loadAsync('/luts/warm.cube');
28
- * engine.look.post.add(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 }))
29
33
  * @param {{ lut?: import('three').Data3DTexture | null, amount?: number, contrast?: number, saturation?: number, temperature?: number, enabled?: boolean, order?: number }} [o]
30
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;
31
35
  * temperature: -1 cool .. 1 warm
@@ -51,9 +55,32 @@ export function lut({ lut = null, amount = 1, contrast = 1, saturation = 1, temp
51
55
  } } };
52
56
  }
53
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;
79
+ }
80
+
54
81
  /**
55
82
  * Film grain (ldr slot): per-pixel noise, a little weaker in highlights.
56
- * @example engine.look.post.add(grain({ enabled: true, amount: 0.06 }))
83
+ * @example engine.post.add(grain({ enabled: true, amount: 0.06 }))
57
84
  * @param {{ amount?: number, size?: number, animated?: boolean, enabled?: boolean, order?: number }} [o]
58
85
  * amount: noise strength; size: grain size in device pixels; animated: new noise every frame (24 per second)
59
86
  * @returns {PostEffect}
@@ -75,7 +102,7 @@ export function grain({ amount = 0.06, size = 1, animated = true, enabled, order
75
102
 
76
103
  /**
77
104
  * Vignette (ldr slot): darker screen corners.
78
- * @example engine.look.post.add(vignette({ enabled: true, strength: 0.4 }))
105
+ * @example engine.post.add(vignette({ enabled: true, strength: 0.4 }))
79
106
  * @param {{ strength?: number, start?: number, enabled?: boolean, order?: number }} [o]
80
107
  * strength: darkness at the corners (0..1); start: distance from the center where darkening begins (0 center .. 1 corner)
81
108
  * @returns {PostEffect}
@@ -92,7 +119,7 @@ export function vignette({ strength = 0.35, start = 0.45, enabled, order = 20 }
92
119
  /**
93
120
  * Chromatic aberration (ldr slot): red and blue shift apart toward the screen edge. Samples the pass input, so it starts a fused group
94
121
  * (default order puts it first, so it still joins the others).
95
- * @example engine.look.post.add(chromatic({ enabled: true, amount: 0.004 }))
122
+ * @example engine.post.add(chromatic({ enabled: true, amount: 0.004 }))
96
123
  * @param {{ amount?: number, enabled?: boolean, order?: number }} [o] amount: edge shift in screen fractions
97
124
  * @returns {PostEffect}
98
125
  */
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,10 +104,10 @@ 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
- * engine.look.post.add(outline({ enabled: true, color: 0x222222, thickness: 1.5 }))
109
- * engine.look.post.add(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);
@@ -114,7 +115,7 @@ function apply(pass, p) {
114
115
  * @returns {PostEffect}
115
116
  */
116
117
  export function outline({ color = 0x222222, thickness = 1, strength = 0.8, mode = 'depth', fadeWithDistance = true, wobble = 0, offLayer = null, enabled, order = 10 } = {}) {
117
- return { name: 'outline', slot: 'hdr', order, enabled, needsDepth: true, costly: mode !== 'depth', params: { color, thickness, strength, mode, fadeWithDistance, wobble, offLayer },
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
120
  update: apply, node: outlineNode };
120
121
  }
@@ -160,12 +161,12 @@ function outlineNode(input, { tsl: T, display, scenePass, scene, camera, params,
160
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();
161
162
  if (L) v.setLayers(L);
162
163
  v.updateBefore = frame => {
163
- const r = frame.renderer, bg = scene.background, fog = scene.fog, a = r.getClearAlpha();
164
+ const r = frame.renderer, bg = scene.background, bgNode = scene.backgroundNode, fog = scene.fog, a = r.getClearAlpha();
164
165
  if (L) L.set(params.offLayer);
165
166
  r.getClearColor(was);
166
167
  r.setClearColor(clear.setRGB(0.5, 0.5, 1, THREE.SRGBColorSpace), 1);
167
- scene.background = null; scene.fog = null;
168
- try { run(frame); } finally { scene.background = bg; scene.fog = fog; r.setClearColor(was, a); }
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); }
169
170
  };
170
171
  v.dispose = () => { free(); mat.dispose(); };
171
172
  return v;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threedog/post-effects",
3
- "version": "0.5.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": {
@@ -20,6 +20,10 @@
20
20
  "types": "./index.d.ts",
21
21
  "default": "./index.js"
22
22
  },
23
+ "./tsl": {
24
+ "types": "./tsl.d.ts",
25
+ "default": "./tsl.js"
26
+ },
23
27
  "./package.json": "./package.json"
24
28
  },
25
29
  "files": [
@@ -27,7 +31,7 @@
27
31
  "*.d.ts"
28
32
  ],
29
33
  "peerDependencies": {
30
- "threedog": "^0.5.0",
34
+ "threedog": "^0.7.0",
31
35
  "three": "^0.187.0"
32
36
  }
33
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
+ }