@threedog/post-effects 0.7.0 → 1.0.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
@@ -3,10 +3,10 @@
3
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.7
6
+ npm install @threedog/post-effects@0.9
7
7
  ```
8
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).
9
+ This describes 0.9.0: `npm install @threedog/post-effects@0.9` (games made in the [repository](https://github.com/penstic123-code/Threedog.js-Game-Engine) already have it).
10
10
 
11
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
 
package/depth.js ADDED
@@ -0,0 +1,26 @@
1
+ // What the depth-reading effects (dof, outline) share: the fullscreen vertex shader and scene depth as distance from the camera, in GLSL and as nodes.
2
+ import { CopyShader } from 'three/addons/shaders/CopyShader.js';
3
+
4
+ export const FULLSCREEN_VERT = CopyShader.vertexShader;
5
+
6
+ /** GLSL lin(depth texture, uv): distance from the camera. Goes with depthUniforms() */
7
+ export const DEPTH_GLSL = `uniform float uNear; uniform float uFar; uniform float uOrtho;
8
+ float lin(sampler2D t, vec2 uv){ float z = texture2D(t, uv).x * 2.0 - 1.0; if (uOrtho > 0.5) return uNear + (z * 0.5 + 0.5) * (uFar - uNear); return 2.0 * uNear * uFar / (uFar + uNear - z * (uFar - uNear)); }`;
9
+
10
+ export const depthUniforms = () => ({ uNear: { value: 0.3 }, uFar: { value: 1000 }, uOrtho: { value: 0 } });
11
+
12
+ /** The camera into depthUniforms() before a draw; ortho depth is linear already @param {any} u @param {any} camera */
13
+ export function writeDepthUniforms(u, camera) {
14
+ u.uNear.value = camera.near; u.uFar.value = camera.far; u.uOrtho.value = camera.isOrthographicCamera ? 1 : 0;
15
+ }
16
+
17
+ /**
18
+ * The same on WebGPU. far: the camera's far as a uniform node; lin(texture node, uv): distance from the camera (the depth -> view z helpers follow the backend's depth range).
19
+ * @param {any} T three/tsl @param {any} camera
20
+ */
21
+ export function depthNodes(T, camera) {
22
+ const near = T.uniform(camera.near).onRenderUpdate(() => camera.near), far = T.uniform(camera.far).onRenderUpdate(() => camera.far);
23
+ const ortho = T.uniform(0).onRenderUpdate(() => (camera.isOrthographicCamera ? 1 : 0));
24
+ 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(); };
25
+ return { far, lin };
26
+ }
package/dof.js CHANGED
@@ -3,6 +3,7 @@
3
3
  // so a later depth reader such as outline still finds the scene's depth in the buffer it reads; keepsDepth tells the chain check so.
4
4
  import * as THREE from 'three';
5
5
  import { Pass, FullScreenQuad } from 'three/addons/postprocessing/Pass.js';
6
+ import { FULLSCREEN_VERT, DEPTH_GLSL, depthUniforms, writeDepthUniforms, depthNodes } from './depth.js';
6
7
  /** @import { PostEffect } from 'threedog' */
7
8
 
8
9
  class DofPass extends Pass {
@@ -11,24 +12,24 @@ class DofPass extends Pass {
11
12
  this.camera = camera;
12
13
  this.keepsDepth = true;
13
14
  this.material = new THREE.ShaderMaterial({
14
- uniforms: { tDiffuse: { value: null }, tDepth: { value: null }, uTexel: { value: new THREE.Vector2() }, uNear: { value: 0.3 }, uFar: { value: 1000 }, uOrtho: { value: 0 },
15
+ uniforms: { tDiffuse: { value: null }, tDepth: { value: null }, uTexel: { value: new THREE.Vector2() }, ...depthUniforms(),
15
16
  uFocus: { value: 10 }, uRange: { value: 2 }, uFalloff: { value: 20 }, uMaxBlur: { value: 6 } },
16
- vertexShader: 'varying vec2 vUv; void main(){ vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }',
17
- fragmentShader: `uniform sampler2D tDiffuse; uniform sampler2D tDepth; uniform vec2 uTexel; uniform float uNear; uniform float uFar; uniform float uOrtho;
17
+ vertexShader: FULLSCREEN_VERT,
18
+ fragmentShader: `uniform sampler2D tDiffuse; uniform sampler2D tDepth; uniform vec2 uTexel;
18
19
  uniform float uFocus; uniform float uRange; uniform float uFalloff; uniform float uMaxBlur;
19
20
  varying vec2 vUv;
20
- float lin(vec2 uv){ float z = texture2D(tDepth, uv).x * 2.0 - 1.0; if (uOrtho > 0.5) return uNear + (z * 0.5 + 0.5) * (uFar - uNear); return 2.0 * uNear * uFar / (uFar + uNear - z * (uFar - uNear)); }
21
+ ${DEPTH_GLSL}
21
22
  float coc(float d){ return clamp((abs(d - uFocus) - uRange) / uFalloff, 0.0, 1.0) * uMaxBlur; }
22
23
  void main(){
23
24
  gl_FragDepth = texture2D(tDepth, vUv).x;
24
- float r = coc(lin(vUv));
25
+ float r = coc(lin(tDepth, vUv));
25
26
  if (r < 0.5) { gl_FragColor = texture2D(tDiffuse, vUv); return; }
26
27
  vec3 sum = texture2D(tDiffuse, vUv).rgb; float w = 1.0;
27
28
  // golden-angle disk; a neighbor in sharp focus (smaller blur than its distance) is left out so a crisp object does not bleed into the haze
28
29
  for (int i = 1; i < 16; i++) {
29
30
  float t = float(i) / 16.0, a = float(i) * 2.39996;
30
31
  vec2 o = vec2(cos(a), sin(a)) * sqrt(t) * r;
31
- float s = step(length(o) * 0.5, coc(lin(vUv + o * uTexel)) + 0.5);
32
+ float s = step(length(o) * 0.5, coc(lin(tDepth, vUv + o * uTexel)) + 0.5);
32
33
  sum += texture2D(tDiffuse, vUv + o * uTexel).rgb * s; w += s;
33
34
  }
34
35
  gl_FragColor = vec4(sum / w, 1.0);
@@ -42,7 +43,7 @@ class DofPass extends Pass {
42
43
  const u = this.material.uniforms;
43
44
  u.tDiffuse.value = readBuffer.texture; u.tDepth.value = readBuffer.depthTexture;
44
45
  u.uTexel.value.set(1 / readBuffer.width, 1 / readBuffer.height);
45
- u.uNear.value = this.camera.near; u.uFar.value = this.camera.far; u.uOrtho.value = this.camera.isOrthographicCamera ? 1 : 0; // ortho depth is linear already
46
+ writeDepthUniforms(u, this.camera);
46
47
  renderer.setRenderTarget(this.renderToScreen ? null : writeBuffer);
47
48
  this.quad.render(renderer);
48
49
  }
@@ -54,7 +55,7 @@ class DofPass extends Pass {
54
55
  * 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
56
  * 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
57
  * engine.post.get('dof').set({ focus: distanceToTarget }).
57
- * @example engine.post.add(dof({ enabled: true, focus: 8, range: 3, maxBlur: 5 }))
58
+ * @example engine.post.add(dof({ focus: 8, range: 3, maxBlur: 5 }))
58
59
  * @param {{ focus?: number, range?: number, falloff?: number, maxBlur?: number, enabled?: boolean, order?: number }} [o]
59
60
  * focus, range, falloff in meters; maxBlur in device pixels
60
61
  * @returns {PostEffect}
@@ -73,10 +74,8 @@ export function dof({ focus = 10, range = 2, falloff = 20, maxBlur = 6, enabled,
73
74
  * @param {any} input @param {any} ctx
74
75
  */
75
76
  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
77
  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(); };
78
+ const { lin: linOf } = depthNodes(T, camera), lin = q => linOf(depth, q);
80
79
  const coc = d => T.clamp(d.sub(p.focus).abs().sub(p.range).div(p.falloff), 0, 1).mul(p.maxBlur);
81
80
  const r = coc(lin(uv)).toVar();
82
81
  let sum = color.sample(uv).rgb, w = T.float(1);
package/hdr.js CHANGED
@@ -12,7 +12,7 @@ import { GTAOPass } from 'three/addons/postprocessing/GTAOPass.js';
12
12
  const BLOOM_NODE_STRENGTH = 3;
13
13
 
14
14
  /**
15
- * Bloom (glow around bright pixels), hdr slot. Off by default on low-tier devices.
15
+ * Bloom (glow around bright pixels), hdr slot.
16
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}
@@ -28,10 +28,10 @@ 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; heavy on weak devices), 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. 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
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 }))
34
+ * @example engine.post.add(ao({ radius: 0.5 }))
35
35
  * @param {{ radius?: number, intensity?: number, enabled?: boolean, order?: number }} [o]
36
36
  * @returns {PostEffect}
37
37
  */
package/index.d.ts CHANGED
@@ -3,15 +3,15 @@
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). On when listed (enabled: false lists it off) */
6
+ /** Color grading (ldr, fused): contrast / saturation 1 = unchanged, temperature -1 cool .. 1 warm, optional 3D LUT (e.g. LUTCubeLoader's texture3D). On when added (enabled: false adds 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
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
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) */
10
+ /** Film grain (ldr, fused); size in device pixels, animated = new noise 24 times a second. On when added (enabled: false adds it off) */
11
11
  export function grain(o?: { amount?: number; size?: number; animated?: boolean; enabled?: boolean; order?: number }): PostEffect;
12
- /** Darker corners (ldr, fused); start: 0 center .. 1 corner. On when listed (enabled: false lists it off) */
12
+ /** Darker corners (ldr, fused); start: 0 center .. 1 corner. On when added (enabled: false adds it off) */
13
13
  export function vignette(o?: { strength?: number; start?: number; enabled?: boolean; order?: number }): PostEffect;
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) */
14
+ /** Red / blue shift apart toward the screen edge (ldr, fused; starts a fused group because it samples the input). On when added (enabled: false adds it off) */
15
15
  export function chromatic(o?: { amount?: number; enabled?: boolean; order?: number }): PostEffect;
16
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) */
17
17
  export function dof(o?: { focus?: number; range?: number; falloff?: number; maxBlur?: number; enabled?: boolean; order?: number }): PostEffect;
@@ -20,7 +20,7 @@ export function dof(o?: { focus?: number; range?: number; falloff?: number; maxB
20
20
  export function bloom(o?: { strength?: number; radius?: number; threshold?: number; enabled?: boolean; order?: number }): PostEffect;
21
21
  /** Ambient occlusion (soft contact shadows in corners; hdr, heavy on weak devices). On when added (enabled: false adds it off) */
22
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) */
23
+ /** Outline (hdr, reads scene depth). On when added (enabled: false adds 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) */
24
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;
25
25
  /** Layer number (29) for outline({ offLayer }): mesh.layers.enable(OUTLINE_OFF_LAYER) exempts that object from the lines */
26
26
  export const OUTLINE_OFF_LAYER: number;
package/index.js CHANGED
@@ -12,10 +12,13 @@
12
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
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
+ import { codedError } from 'threedog/error-hints';
15
16
  export { dof } from './dof.js';
16
17
  export { bloom, ao } from './hdr.js';
17
18
  export { outline, OUTLINE_OFF_LAYER } from './outline.js';
18
19
  /** @import { PostEffect } from 'threedog' */
20
+ // luminance weights: Rec. 709 for lut's saturation, Rec. 601 for grain's fade on bright pixels (the engine's own are in render/fxNumbers.js, which is not public)
21
+ const LUMA = [0.2126, 0.7152, 0.0722], LUMA_601 = [0.299, 0.587, 0.114];
19
22
 
20
23
  // A 2x2x2 identity LUT stands in until the game gives a real one (a sampler uniform must always hold a texture)
21
24
  const identity = new THREE.Data3DTexture(new Uint8Array([0, 0, 0, 255, 255, 0, 0, 255, 0, 255, 0, 255, 255, 255, 0, 255,
@@ -29,7 +32,7 @@ identity.format = THREE.RGBAFormat; identity.minFilter = identity.magFilter = TH
29
32
  * @example
30
33
  * import { LUTCubeLoader } from 'three/addons/loaders/LUTCubeLoader.js';
31
34
  * const { texture3D } = await new LUTCubeLoader().loadAsync('/luts/warm.cube');
32
- * engine.post.add(lut({ enabled: true, lut: texture3D, amount: 0.8, saturation: 1.1, temperature: 0.2 }))
35
+ * engine.post.add(lut({ lut: texture3D, amount: 0.8, saturation: 1.1, temperature: 0.2 }))
33
36
  * @param {{ lut?: import('three').Data3DTexture | null, amount?: number, contrast?: number, saturation?: number, temperature?: number, enabled?: boolean, order?: number }} [o]
34
37
  * 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;
35
38
  * temperature: -1 cool .. 1 warm
@@ -43,13 +46,13 @@ export function lut({ lut = null, amount = 1, contrast = 1, saturation = 1, temp
43
46
  uLutContrast: p.contrast, uLutSaturation: p.saturation, uLutTemp: p.temperature }),
44
47
  glsl: `color.rgb += vec3(uLutTemp * 0.06, 0.0, -uLutTemp * 0.06);
45
48
  color.rgb = clamp((color.rgb - 0.5) * uLutContrast + 0.5, 0.0, 1.0);
46
- color.rgb = mix(vec3(dot(color.rgb, vec3(0.2126, 0.7152, 0.0722))), color.rgb, uLutSaturation);
49
+ color.rgb = mix(vec3(dot(color.rgb, vec3(${LUMA.join(', ')}))), color.rgb, uLutSaturation);
47
50
  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
51
  // 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
52
  tsl: (color, uv, { tsl: T, p, params }) => {
50
53
  let c = color.rgb.add(T.vec3(p.temperature.mul(0.06), 0, p.temperature.mul(-0.06)));
51
54
  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);
55
+ c = T.mix(T.vec3(T.dot(c, T.vec3(...LUMA))), c, p.saturation);
53
56
  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
57
  return T.vec4(c, color.a);
55
58
  } } };
@@ -64,7 +67,7 @@ export function lut({ lut = null, amount = 1, contrast = 1, saturation = 1, temp
64
67
  * @returns {import('three').Data3DTexture}
65
68
  */
66
69
  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]');
70
+ if (!Array.isArray(colors) || colors.length < 2) throw codedError('post-effect', 'paletteLut(colors): colors must be an array of at least 2 colors, e.g. [0x101014, 0xf4f1e8]');
68
71
  const pal = colors.map(c => new THREE.Color(c).getRGB({ r: 0, g: 0, b: 0 }, THREE.SRGBColorSpace));
69
72
  const data = new Uint8Array(size ** 3 * 4);
70
73
  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) {
@@ -80,7 +83,7 @@ export function paletteLut(colors, size = 32) {
80
83
 
81
84
  /**
82
85
  * Film grain (ldr slot): per-pixel noise, a little weaker in highlights.
83
- * @example engine.post.add(grain({ enabled: true, amount: 0.06 }))
86
+ * @example engine.post.add(grain({ amount: 0.06 }))
84
87
  * @param {{ amount?: number, size?: number, animated?: boolean, enabled?: boolean, order?: number }} [o]
85
88
  * amount: noise strength; size: grain size in device pixels; animated: new noise every frame (24 per second)
86
89
  * @returns {PostEffect}
@@ -91,18 +94,18 @@ export function grain({ amount = 0.06, size = 1, animated = true, enabled, order
91
94
  uniforms: { uGrainAmount: 'float', uGrainSize: 'float', uGrainAnimated: 'float' },
92
95
  values: p => ({ uGrainAmount: p.amount, uGrainSize: Math.max(1, p.size), uGrainAnimated: p.animated ? 1 : 0 }),
93
96
  glsl: `float n = fxHash(floor(vUv * uResolution / uGrainSize) + (uGrainAnimated > 0.5 ? floor(uTime * 24.0) * 17.0 : 0.0)) - 0.5;
94
- color.rgb += n * uGrainAmount * (1.0 - 0.5 * dot(color.rgb, vec3(0.299, 0.587, 0.114)));`,
97
+ color.rgb += n * uGrainAmount * (1.0 - 0.5 * dot(color.rgb, vec3(${LUMA_601.join(', ')})));`,
95
98
  // same shape; three's hash() stands in for fxHash, so the noise pattern differs from WebGL's (its strength does not)
96
99
  tsl: (color, uv, { tsl: T, p, time, resolution }) => {
97
100
  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
101
  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);
102
+ 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);
100
103
  } } };
101
104
  }
102
105
 
103
106
  /**
104
107
  * Vignette (ldr slot): darker screen corners.
105
- * @example engine.post.add(vignette({ enabled: true, strength: 0.4 }))
108
+ * @example engine.post.add(vignette({ strength: 0.4 }))
106
109
  * @param {{ strength?: number, start?: number, enabled?: boolean, order?: number }} [o]
107
110
  * strength: darkness at the corners (0..1); start: distance from the center where darkening begins (0 center .. 1 corner)
108
111
  * @returns {PostEffect}
@@ -119,7 +122,7 @@ export function vignette({ strength = 0.35, start = 0.45, enabled, order = 20 }
119
122
  /**
120
123
  * Chromatic aberration (ldr slot): red and blue shift apart toward the screen edge. Samples the pass input, so it starts a fused group
121
124
  * (default order puts it first, so it still joins the others).
122
- * @example engine.post.add(chromatic({ enabled: true, amount: 0.004 }))
125
+ * @example engine.post.add(chromatic({ amount: 0.004 }))
123
126
  * @param {{ amount?: number, enabled?: boolean, order?: number }} [o] amount: edge shift in screen fractions
124
127
  * @returns {PostEffect}
125
128
  */
package/outline.js CHANGED
@@ -3,11 +3,16 @@
3
3
  import * as THREE from 'three';
4
4
  import { Pass, FullScreenQuad } from 'three/addons/postprocessing/Pass.js';
5
5
  import { RESERVED_LAYERS } from 'threedog/layers';
6
+ import { codedError } from 'threedog/error-hints';
7
+ import { FULLSCREEN_VERT, DEPTH_GLSL, depthUniforms, writeDepthUniforms, depthNodes } from './depth.js';
6
8
  /** @import { PostEffect } from 'threedog' */
7
9
 
8
10
  /** Layer number to put on objects that should get no outline: mesh.layers.enable(OUTLINE_OFF_LAYER), with outline({ offLayer: OUTLINE_OFF_LAYER }) */
9
11
  export const OUTLINE_OFF_LAYER = RESERVED_LAYERS.outlineOff;
10
12
  const MODES = { depth: 0, normal: 1, both: 2 };
13
+ // 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 badMode = mode => codedError('post-effect', `outline: unknown mode '${mode}', use 'depth' | 'normal' | 'both'`);
11
16
 
12
17
  class OutlinePass extends Pass {
13
18
  /** @param {any} scene @param {any} camera @param {Record<string, any>} p */
@@ -19,24 +24,22 @@ class OutlinePass extends Pass {
19
24
  this.normalRT = null; this.maskRT = null;
20
25
  this.material = new THREE.ShaderMaterial({
21
26
  uniforms: { tDiffuse: { value: null }, tDepth: { value: null }, tNormal: { value: null }, tMask: { value: null }, tMaskDepth: { value: null },
22
- uTexel: { value: new THREE.Vector2() }, uNear: { value: 0.3 }, uFar: { value: 1000 }, uOrtho: { value: 0 }, uColor: { value: new THREE.Color(p.color) },
27
+ uTexel: { value: new THREE.Vector2() }, ...depthUniforms(), uColor: { value: new THREE.Color(p.color) },
23
28
  uThick: { value: 1 }, uStrength: { value: 1 }, uMode: { value: 0 }, uFade: { value: 1 }, uWobble: { value: 0 }, uTime: { value: 0 }, uUseMask: { value: 0 } },
24
- vertexShader: 'varying vec2 vUv; void main(){ vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }',
29
+ vertexShader: FULLSCREEN_VERT,
25
30
  fragmentShader: `uniform sampler2D tDiffuse; uniform sampler2D tDepth; uniform sampler2D tNormal; uniform sampler2D tMask; uniform sampler2D tMaskDepth;
26
- uniform vec2 uTexel; uniform float uNear; uniform float uFar; uniform float uOrtho; uniform vec3 uColor; uniform float uThick; uniform float uStrength;
31
+ uniform vec2 uTexel; uniform vec3 uColor; uniform float uThick; uniform float uStrength;
27
32
  uniform float uMode; uniform float uFade; uniform float uWobble; uniform float uTime; uniform float uUseMask;
28
33
  varying vec2 vUv;
29
- float lin(sampler2D t, vec2 uv){ float z = texture2D(t, uv).x * 2.0 - 1.0; if (uOrtho > 0.5) return uNear + (z * 0.5 + 0.5) * (uFar - uNear); return 2.0 * uNear * uFar / (uFar + uNear - z * (uFar - uNear)); }
30
- float h2(vec2 p){ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
31
- float vn(vec2 p){ vec2 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);
32
- return mix(mix(h2(i), h2(i + vec2(1, 0)), f.x), mix(h2(i + vec2(0, 1)), h2(i + vec2(1, 1)), f.x), f.y); }
34
+ ${DEPTH_GLSL}
35
+ #include <threedog_noise>
33
36
  // object in the exempt layer at this pixel: its own render is not behind what the scene depth saw
34
37
  float masked(vec2 uv){ return texture2D(tMask, uv).r > 0.5 && lin(tMaskDepth, uv) <= lin(tDepth, uv) + 0.05 ? 1.0 : 0.0; }
35
38
  void main(){
36
39
  vec4 c = texture2D(tDiffuse, vUv);
37
40
  vec2 o = uTexel * uThick;
38
41
  vec2 uv = vUv;
39
- if (uWobble > 0.0) uv += (vec2(vn(vUv / uTexel * 0.04 + uTime), vn(vUv / uTexel * 0.04 + 17.3 + uTime)) - 0.5) * 2.0 * uWobble * uTexel;
42
+ if (uWobble > 0.0) uv += (vec2(threedogNoise(vUv / uTexel * 0.04 + uTime), threedogNoise(vUv / uTexel * 0.04 + 17.3 + uTime)) - 0.5) * 2.0 * uWobble * uTexel;
40
43
  vec2 nb[4] = vec2[4](vec2(o.x, 0.0), vec2(-o.x, 0.0), vec2(0.0, o.y), vec2(0.0, -o.y)); // the four neighbors, thickness apart
41
44
  float d = lin(tDepth, uv), edge = 0.0;
42
45
  if (uMode != 1.0) {
@@ -59,16 +62,14 @@ class OutlinePass extends Pass {
59
62
  }
60
63
  // Render the scene once with an override material into a target the size of the input
61
64
  _pass(renderer, rt, mat, layer) {
62
- const { scene, camera } = this, bg = scene.background, fog = scene.fog, mask = camera.layers.mask, color = renderer.getClearColor(new THREE.Color()), alpha = renderer.getClearAlpha();
63
- const shadows = renderer.shadowMap.autoUpdate;
64
- renderer.shadowMap.autoUpdate = false; // an override material is unlit: redrawing the shadow maps for it would be pure waste
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);
65
67
  scene.overrideMaterial = mat; scene.background = null; scene.fog = null;
66
68
  if (layer != null) camera.layers.set(layer);
67
- // 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
68
- renderer.setClearColor(new THREE.Color().setRGB(0.5, 0.5, 1, THREE.LinearSRGBColorSpace), 1);
69
- renderer.setRenderTarget(rt); renderer.clear(); renderer.render(scene, camera);
70
- scene.overrideMaterial = null; scene.background = bg; scene.fog = fog; camera.layers.mask = mask; renderer.setClearColor(color, alpha);
71
- renderer.shadowMap.autoUpdate = shadows;
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); }
72
73
  }
73
74
  _target(rt, w, h, depth) {
74
75
  if (rt && (rt.width !== w || rt.height !== h)) { rt.setSize(w, h); return rt; }
@@ -86,7 +87,7 @@ class OutlinePass extends Pass {
86
87
  if (useMask) { this.maskRT = this._target(this.maskRT, w, h, true); this._pass(renderer, this.maskRT, this.maskMat, p.offLayer); u.tMask.value = this.maskRT.texture; u.tMaskDepth.value = this.maskRT.depthTexture; }
87
88
  u.tDiffuse.value = readBuffer.texture; u.tDepth.value = readBuffer.depthTexture;
88
89
  u.uTexel.value.set(1 / w, 1 / h);
89
- u.uNear.value = this.camera.near; u.uFar.value = this.camera.far; u.uOrtho.value = this.camera.isOrthographicCamera ? 1 : 0; // ortho depth is linear already
90
+ writeDepthUniforms(u, this.camera);
90
91
  u.uMode.value = mode; u.uUseMask.value = useMask ? 1 : 0; u.uTime.value = Math.floor(this.time * 8);
91
92
  renderer.setRenderTarget(this.renderToScreen ? null : writeBuffer);
92
93
  this.quad.render(renderer);
@@ -95,7 +96,7 @@ class OutlinePass extends Pass {
95
96
  }
96
97
 
97
98
  function apply(pass, p) {
98
- if (!(p.mode in MODES)) throw new Error(`outline: unknown mode '${p.mode}', use 'depth' | 'normal' | 'both'`);
99
+ if (!(p.mode in MODES)) throw badMode(p.mode);
99
100
  pass.p = p;
100
101
  const u = pass.material.uniforms;
101
102
  u.uColor.value.set(p.color); u.uThick.value = p.thickness; u.uStrength.value = p.strength; u.uFade.value = p.fadeWithDistance ? 1 : 0; u.uWobble.value = p.wobble;
@@ -106,8 +107,8 @@ function apply(pass, p) {
106
107
  * mode 'depth' (default): silhouettes where depth jumps; 'normal': creases where surface normals turn (the scene is drawn once more with
107
108
  * normals; heavy on weak devices); 'both': either. Objects can opt out of the lines with offLayer.
108
109
  * @example
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
+ * engine.post.add(outline({ color: 0x222222, thickness: 1.5 }))
111
+ * engine.post.add(outline({ mode: 'both', wobble: 1.5, offLayer: OUTLINE_OFF_LAYER })) // hand-drawn; then: sky.layers.enable(OUTLINE_OFF_LAYER)
111
112
  * @param {{ color?: any, thickness?: number, strength?: number, mode?: 'depth' | 'normal' | 'both', fadeWithDistance?: boolean, wobble?: number,
112
113
  * offLayer?: number | null, enabled?: boolean, order?: number }} [o]
113
114
  * fadeWithDistance: lines fade out in the far 40..90% of the camera range (default true); wobble: line jitter in pixels (0 = straight);
@@ -126,24 +127,18 @@ export function outline({ color = 0x222222, thickness = 1, strength = 0.8, mode
126
127
  * 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
128
  * @param {any} input @param {any} ctx
128
129
  */
129
- function outlineNode(input, { tsl: T, display, scenePass, scene, camera, params, p }) {
130
+ function outlineNode(input, { tsl: T, fx, display, scenePass, scene, camera, params, p }) {
130
131
  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));
132
+ if (mode === undefined) throw badMode(params.mode);
133
+ const { far, lin } = depthNodes(T, camera);
134
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
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
136
  const depthTex = scenePass.getTextureNode('depth');
139
137
  const texel = T.vec2(1).div(T.screenSize), o = texel.mul(p.thickness), base = T.screenUV;
140
138
  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
139
  // 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
140
  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);
141
+ const jitter = T.vec2(fx.noise(px.add(tick)), fx.noise(px.add(17.3).add(tick))).sub(0.5).mul(2).mul(p.wobble).mul(texel);
147
142
  const uv = T.select(p.wobble.greaterThan(0), base.add(jitter), base);
148
143
  const d = lin(depthTex, uv);
149
144
  let edge = T.float(0);
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "@threedog/post-effects",
3
- "version": "0.7.0",
3
+ "version": "1.0.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": {
7
7
  "type": "git",
8
- "url": "git+https://github.com/penstic123-code/ThreeDog.js-Game-Engine.git",
8
+ "url": "git+https://github.com/penstic123-code/Threedog.js-Game-Engine.git",
9
9
  "directory": "packages/post-effects"
10
10
  },
11
- "homepage": "https://github.com/penstic123-code/ThreeDog.js-Game-Engine#readme",
11
+ "homepage": "https://github.com/penstic123-code/Threedog.js-Game-Engine#readme",
12
12
  "type": "module",
13
13
  "engines": {
14
14
  "node": "^20.19.0 || >=22.12.0"
@@ -31,7 +31,7 @@
31
31
  "*.d.ts"
32
32
  ],
33
33
  "peerDependencies": {
34
- "threedog": "^0.7.0",
34
+ "threedog": "^1.0.0",
35
35
  "three": "^0.187.0"
36
36
  }
37
37
  }
package/tsl.d.ts CHANGED
@@ -2,11 +2,11 @@
2
2
  import type { PostEffect } from 'threedog';
3
3
  import type { Box3, Light } from 'three';
4
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 */
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
- /** Temporal antialiasing (three's TRAANode; last in hdr): clears the dots of stochastic effects before it and replaces MSAA while on. WebGPURenderer only */
7
+ /** 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
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 */
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 @experimental */
10
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 */
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 @experimental */
12
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 CHANGED
@@ -15,6 +15,7 @@ import { gaussianBlur } from 'three/addons/tsl/display/GaussianBlurNode.js';
15
15
  import { bayer16 } from 'three/addons/tsl/math/Bayer.js';
16
16
  import { Box3, BoxGeometry, Color, Layers, Mesh, Vector3, VolumeNodeMaterial } from 'three/webgpu';
17
17
  import { RESERVED_LAYERS } from 'threedog/layers';
18
+ import { codedError } from 'threedog/error-hints';
18
19
  /** @import { PostEffect } from 'threedog' */
19
20
 
20
21
  const { lightVolumes: VOLUME_LAYER } = RESERVED_LAYERS;
@@ -37,7 +38,6 @@ export function voxelGI({ resolution = 128, bounds, intensity = 1, occlusion = 0
37
38
  const { tsl, p, scenePass, scene, camera, display } = ctx;
38
39
  gi = display.own(vxgi(scenePass.getTextureNode('depth'), scenePass.getTextureNode('normal'), scene, camera, resolution));
39
40
  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
41
  if (bounds) gi.volume.bounds.copy(bounds);
42
42
  setup?.(gi);
43
43
  const light = gi.getGINode().rgb.mul(scenePass.getTextureNode('diffuse').rgb).mul(p.intensity);
@@ -67,11 +67,11 @@ export function temporalAA({ order = 900, enabled, name = 'temporalAA' } = {}) {
67
67
  * @returns {PostEffect}
68
68
  */
69
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 },
70
+ return { name, slot: 'hdr', order, enabled, params: { density, maxDensity, falloff, color: new Color(color) },
71
71
  node(input, { engine, tsl, p, scenePass, camera, display }) {
72
72
  const depth = scenePass.getTextureNode('depth'), sun = light ?? engine.lights?.sun;
73
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)');
74
+ if (!sun?.parent || !sun.castShadow) throw codedError('post-effect', 'sunShafts: no light to follow; give sunShafts({ light }) a light that is in the scene and casts shadows (default: engine.lights.sun)');
75
75
  const rays = display.own(godrays(depth, camera, sun));
76
76
  Object.assign(rays, { density: p.density, maxDensity: p.maxDensity, distanceAttenuation: p.falloff });
77
77
  rays.raymarchSteps.value = steps;
@@ -90,9 +90,9 @@ export function sunShafts({ light, density = 2, maxDensity = 0.6, falloff = 2, c
90
90
  * @returns {PostEffect}
91
91
  */
92
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) })');
93
+ 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
94
  return { name, slot: 'hdr', order, enabled, params: { density },
95
- node(input, { engine, tsl, p, scene, camera, scenePass, display }) {
95
+ node(input, { tsl, p, scene, camera, scenePass, display }) {
96
96
  const size = bounds.getSize(new Vector3()), mat = new VolumeNodeMaterial();
97
97
  mat.steps = steps;
98
98
  mat.offsetNode = bayer16(tsl.screenCoordinate);
@@ -112,7 +112,7 @@ export function lightVolumes({ bounds, density = 0.3, steps = 16, scale = 0.25,
112
112
  let look = 0;
113
113
  air.updateBefore = frame => {
114
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); } }
115
+ 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
116
  const r = frame.renderer, { background, backgroundNode } = scene, clear = r.getClearColor(new Color()), alpha = r.getClearAlpha();
117
117
  // three prefers backgroundNode over background, so both go
118
118
  scene.background = scene.backgroundNode = null; r.setClearColor(0x000000, 0);