@threedog/post-effects 0.1.0 → 0.5.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,26 @@
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), `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.5
7
+ ```
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).
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`:
12
+
13
+ ```js
14
+ import { bloom, vignette } from '@threedog/post-effects';
15
+
16
+ engine.look.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 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 })`.
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`.
25
+
26
+ Peer dependencies: `threedog` and `three` (the same copy the game uses). MIT license.
package/dof.js CHANGED
@@ -11,13 +11,13 @@ class DofPass extends Pass {
11
11
  this.camera = camera;
12
12
  this.keepsDepth = true;
13
13
  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 },
14
+ uniforms: { tDiffuse: { value: null }, tDepth: { value: null }, uTexel: { value: new THREE.Vector2() }, uNear: { value: 0.3 }, uFar: { value: 1000 }, uOrtho: { value: 0 },
15
15
  uFocus: { value: 10 }, uRange: { value: 2 }, uFalloff: { value: 20 }, uMaxBlur: { value: 6 } },
16
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;
17
+ fragmentShader: `uniform sampler2D tDiffuse; uniform sampler2D tDepth; uniform vec2 uTexel; uniform float uNear; uniform float uFar; uniform float uOrtho;
18
18
  uniform float uFocus; uniform float uRange; uniform float uFalloff; uniform float uMaxBlur;
19
19
  varying vec2 vUv;
20
- float lin(vec2 uv){ float z = texture2D(tDepth, uv).x * 2.0 - 1.0; return 2.0 * uNear * uFar / (uFar + uNear - z * (uFar - uNear)); }
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
21
  float coc(float d){ return clamp((abs(d - uFocus) - uRange) / uFalloff, 0.0, 1.0) * uMaxBlur; }
22
22
  void main(){
23
23
  gl_FragDepth = texture2D(tDepth, vUv).x;
@@ -42,7 +42,7 @@ class DofPass extends Pass {
42
42
  const u = this.material.uniforms;
43
43
  u.tDiffuse.value = readBuffer.texture; u.tDepth.value = readBuffer.depthTexture;
44
44
  u.uTexel.value.set(1 / readBuffer.width, 1 / readBuffer.height);
45
- u.uNear.value = this.camera.near; u.uFar.value = this.camera.far;
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
46
  renderer.setRenderTarget(this.renderToScreen ? null : writeBuffer);
47
47
  this.quad.render(renderer);
48
48
  }
@@ -53,14 +53,38 @@ class DofPass extends Pass {
53
53
  * Depth of field (hdr slot, costly): 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.post.get('dof').set({ focus: distanceToTarget }).
57
- * @example post: [dof({ enabled: true, focus: 8, range: 3, maxBlur: 5 })]
56
+ * engine.look.post.set({ 'dof.focus': distanceToTarget }).
57
+ * @example engine.look.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
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 };
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
@@ -4,25 +4,46 @@ 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.look.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
21
  return { name: 'bloom', slot: 'hdr', order, enabled, costly: true, 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; costly), 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) 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 }))
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, costly: true, 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,22 @@
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
+ /** Film grain (ldr, fused); size in device pixels, animated = new noise 24 times a second. On when listed (enabled: false lists it off) */
9
9
  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 */
10
+ /** Darker corners (ldr, fused); start: 0 center .. 1 corner. On when listed (enabled: false lists it off) */
11
11
  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) */
12
+ /** 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
13
  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 */
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 */
15
15
  export function dof(o?: { focus?: number; range?: number; falloff?: number; maxBlur?: number; enabled?: boolean; order?: number }): PostEffect;
16
16
 
17
- /** Bloom (glow around bright pixels; hdr, costly: off by default on low-tier devices) */
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) */
18
18
  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) */
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) */
20
+ 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) */
22
22
  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
23
  /** Layer number (29) for outline({ offLayer }): mesh.layers.enable(OUTLINE_OFF_LAYER) exempts that object from the lines */
24
24
  export const OUTLINE_OFF_LAYER: number;
package/index.js CHANGED
@@ -1,10 +1,14 @@
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.
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:
3
+ // import { vignette, grain } from '@threedog/post-effects';
4
+ // engine.look.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.
5
7
  // hdr slot (linear, before tone mapping): bloom, ao, outline, dof. ldr slot (sRGB, after it): lut, grain, vignette, chromatic.
6
8
  // 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.
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.
8
12
  import * as THREE from 'three';
9
13
  export { dof } from './dof.js';
10
14
  export { bloom, ao } from './hdr.js';
@@ -21,13 +25,13 @@ identity.format = THREE.RGBAFormat; identity.minFilter = identity.magFilter = TH
21
25
  * @example
22
26
  * import { LUTCubeLoader } from 'three/addons/loaders/LUTCubeLoader.js';
23
27
  * 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 })]
28
+ * engine.look.post.add(lut({ enabled: true, lut: texture3D, amount: 0.8, saturation: 1.1, temperature: 0.2 }))
25
29
  * @param {{ lut?: import('three').Data3DTexture | null, amount?: number, contrast?: number, saturation?: number, temperature?: number, enabled?: boolean, order?: number }} [o]
26
30
  * 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
31
  * temperature: -1 cool .. 1 warm
28
32
  * @returns {PostEffect}
29
33
  */
30
- export function lut({ lut = null, amount = 1, contrast = 1, saturation = 1, temperature = 0, enabled = false, order = 10 } = {}) {
34
+ export function lut({ lut = null, amount = 1, contrast = 1, saturation = 1, temperature = 0, enabled, order = 10 } = {}) {
31
35
  return { name: 'lut', slot: 'ldr', order, enabled, params: { lut, amount, contrast, saturation, temperature },
32
36
  fuse: {
33
37
  uniforms: { uLutTex: 'sampler3D', uLutSize: 'float', uLutAmount: 'float', uLutContrast: 'float', uLutSaturation: 'float', uLutTemp: 'float' },
@@ -36,53 +40,73 @@ export function lut({ lut = null, amount = 1, contrast = 1, saturation = 1, temp
36
40
  glsl: `color.rgb += vec3(uLutTemp * 0.06, 0.0, -uLutTemp * 0.06);
37
41
  color.rgb = clamp((color.rgb - 0.5) * uLutContrast + 0.5, 0.0, 1.0);
38
42
  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);` } };
43
+ 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);`,
44
+ // 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
45
+ tsl: (color, uv, { tsl: T, p, params }) => {
46
+ let c = color.rgb.add(T.vec3(p.temperature.mul(0.06), 0, p.temperature.mul(-0.06)));
47
+ c = T.clamp(c.sub(0.5).mul(p.contrast).add(0.5), 0, 1);
48
+ c = T.mix(T.vec3(T.dot(c, T.vec3(0.2126, 0.7152, 0.0722))), c, p.saturation);
49
+ 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); }
50
+ return T.vec4(c, color.a);
51
+ } } };
40
52
  }
41
53
 
42
54
  /**
43
55
  * Film grain (ldr slot): per-pixel noise, a little weaker in highlights.
44
- * @example post: [grain({ enabled: true, amount: 0.06 })]
56
+ * @example engine.look.post.add(grain({ enabled: true, amount: 0.06 }))
45
57
  * @param {{ amount?: number, size?: number, animated?: boolean, enabled?: boolean, order?: number }} [o]
46
58
  * amount: noise strength; size: grain size in device pixels; animated: new noise every frame (24 per second)
47
59
  * @returns {PostEffect}
48
60
  */
49
- export function grain({ amount = 0.06, size = 1, animated = true, enabled = false, order = 30 } = {}) {
61
+ export function grain({ amount = 0.06, size = 1, animated = true, enabled, order = 30 } = {}) {
50
62
  return { name: 'grain', slot: 'ldr', order, enabled, params: { amount, size, animated },
51
63
  fuse: {
52
64
  uniforms: { uGrainAmount: 'float', uGrainSize: 'float', uGrainAnimated: 'float' },
53
65
  values: p => ({ uGrainAmount: p.amount, uGrainSize: Math.max(1, p.size), uGrainAnimated: p.animated ? 1 : 0 }),
54
66
  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)));` } };
67
+ color.rgb += n * uGrainAmount * (1.0 - 0.5 * dot(color.rgb, vec3(0.299, 0.587, 0.114)));`,
68
+ // same shape; three's hash() stands in for fxHash, so the noise pattern differs from WebGL's (its strength does not)
69
+ tsl: (color, uv, { tsl: T, p, time, resolution }) => {
70
+ const q = T.floor(uv.mul(resolution).div(T.max(p.size, 1))), frame = T.floor(time.mul(24)).mul(17).mul(p.animated);
71
+ const n = T.hash(q.x.add(q.y.mul(1103)).add(frame)).sub(0.5);
72
+ 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);
73
+ } } };
56
74
  }
57
75
 
58
76
  /**
59
77
  * Vignette (ldr slot): darker screen corners.
60
- * @example post: [vignette({ enabled: true, strength: 0.4 })]
78
+ * @example engine.look.post.add(vignette({ enabled: true, strength: 0.4 }))
61
79
  * @param {{ strength?: number, start?: number, enabled?: boolean, order?: number }} [o]
62
80
  * strength: darkness at the corners (0..1); start: distance from the center where darkening begins (0 center .. 1 corner)
63
81
  * @returns {PostEffect}
64
82
  */
65
- export function vignette({ strength = 0.35, start = 0.45, enabled = false, order = 20 } = {}) {
83
+ export function vignette({ strength = 0.35, start = 0.45, enabled, order = 20 } = {}) {
66
84
  return { name: 'vignette', slot: 'ldr', order, enabled, params: { strength, start },
67
85
  fuse: {
68
86
  uniforms: { uVigStrength: 'float', uVigStart: 'float' },
69
87
  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);' } };
88
+ glsl: 'color.rgb *= 1.0 - uVigStrength * smoothstep(uVigStart, 1.0, length(vUv - 0.5) * 1.4142);',
89
+ 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
90
  }
72
91
 
73
92
  /**
74
93
  * Chromatic aberration (ldr slot): red and blue shift apart toward the screen edge. Samples the pass input, so it starts a fused group
75
94
  * (default order puts it first, so it still joins the others).
76
- * @example post: [chromatic({ enabled: true, amount: 0.004 })]
95
+ * @example engine.look.post.add(chromatic({ enabled: true, amount: 0.004 }))
77
96
  * @param {{ amount?: number, enabled?: boolean, order?: number }} [o] amount: edge shift in screen fractions
78
97
  * @returns {PostEffect}
79
98
  */
80
- export function chromatic({ amount = 0.004, enabled = false, order = 5 } = {}) {
99
+ export function chromatic({ amount = 0.004, enabled, order = 5 } = {}) {
81
100
  return { name: 'chromatic', slot: 'ldr', order, enabled, params: { amount },
82
101
  fuse: {
83
102
  reads: true,
84
103
  uniforms: { uChromaAmount: 'float' },
85
104
  values: p => ({ uChromaAmount: p.amount }),
86
105
  glsl: `vec2 off = (vUv - 0.5) * uChromaAmount;
87
- color.r = texture2D(tDiffuse, vUv + off).r; color.b = texture2D(tDiffuse, vUv - off).b;` } };
106
+ color.r = texture2D(tDiffuse, vUv + off).r; color.b = texture2D(tDiffuse, vUv - off).b;`,
107
+ // input: the image before this effect as a texture (reads: true), sampled at the shifted uvs
108
+ tsl: (color, uv, { tsl: T, p, input }) => {
109
+ const off = uv.sub(0.5).mul(p.amount);
110
+ return T.vec4(input.sample(uv.add(off)).r, color.g, input.sample(uv.sub(off)).b, color.a);
111
+ } } };
88
112
  }
package/outline.js CHANGED
@@ -18,14 +18,14 @@ class OutlinePass extends Pass {
18
18
  this.normalRT = null; this.maskRT = null;
19
19
  this.material = new THREE.ShaderMaterial({
20
20
  uniforms: { tDiffuse: { value: null }, tDepth: { value: null }, tNormal: { value: null }, tMask: { value: null }, tMaskDepth: { value: null },
21
- uTexel: { value: new THREE.Vector2() }, uNear: { value: 0.3 }, uFar: { value: 1000 }, uColor: { value: new THREE.Color(p.color) },
21
+ uTexel: { value: new THREE.Vector2() }, uNear: { value: 0.3 }, uFar: { value: 1000 }, uOrtho: { value: 0 }, uColor: { value: new THREE.Color(p.color) },
22
22
  uThick: { value: 1 }, uStrength: { value: 1 }, uMode: { value: 0 }, uFade: { value: 1 }, uWobble: { value: 0 }, uTime: { value: 0 }, uUseMask: { value: 0 } },
23
23
  vertexShader: 'varying vec2 vUv; void main(){ vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }',
24
24
  fragmentShader: `uniform sampler2D tDiffuse; uniform sampler2D tDepth; uniform sampler2D tNormal; uniform sampler2D tMask; uniform sampler2D tMaskDepth;
25
- uniform vec2 uTexel; uniform float uNear; uniform float uFar; uniform vec3 uColor; uniform float uThick; uniform float uStrength;
25
+ uniform vec2 uTexel; uniform float uNear; uniform float uFar; uniform float uOrtho; uniform vec3 uColor; uniform float uThick; uniform float uStrength;
26
26
  uniform float uMode; uniform float uFade; uniform float uWobble; uniform float uTime; uniform float uUseMask;
27
27
  varying vec2 vUv;
28
- float lin(sampler2D t, vec2 uv){ float z = texture2D(t, uv).x * 2.0 - 1.0; return 2.0 * uNear * uFar / (uFar + uNear - z * (uFar - uNear)); }
28
+ 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)); }
29
29
  float h2(vec2 p){ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
30
30
  float vn(vec2 p){ vec2 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);
31
31
  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); }
@@ -85,7 +85,7 @@ class OutlinePass extends Pass {
85
85
  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; }
86
86
  u.tDiffuse.value = readBuffer.texture; u.tDepth.value = readBuffer.depthTexture;
87
87
  u.uTexel.value.set(1 / w, 1 / h);
88
- u.uNear.value = this.camera.near; u.uFar.value = this.camera.far;
88
+ 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
89
89
  u.uMode.value = mode; u.uUseMask.value = useMask ? 1 : 0; u.uTime.value = Math.floor(this.time * 8);
90
90
  renderer.setRenderTarget(this.renderToScreen ? null : writeBuffer);
91
91
  this.quad.render(renderer);
@@ -105,16 +105,82 @@ function apply(pass, p) {
105
105
  * mode 'depth' (default): silhouettes where depth jumps; 'normal': creases where surface normals turn (the scene is drawn once more with
106
106
  * normals; costly, off by default on low-tier devices); 'both': either. Objects can opt out of the lines with offLayer.
107
107
  * @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)
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)
110
110
  * @param {{ color?: any, thickness?: number, strength?: number, mode?: 'depth' | 'normal' | 'both', fadeWithDistance?: boolean, wobble?: number,
111
111
  * offLayer?: number | null, enabled?: boolean, order?: number }} [o]
112
112
  * fadeWithDistance: lines fade out in the far 40..90% of the camera range (default true); wobble: line jitter in pixels (0 = straight);
113
113
  * offLayer: objects with this three.js layer enabled get no outline (costs one extra render of just those objects; null = off)
114
114
  * @returns {PostEffect}
115
115
  */
116
- export function outline({ color = 0x222222, thickness = 1, strength = 0.8, mode = 'depth', fadeWithDistance = true, wobble = 0, offLayer = null, enabled = false, order = 10 } = {}) {
116
+ export function outline({ color = 0x222222, thickness = 1, strength = 0.8, mode = 'depth', fadeWithDistance = true, wobble = 0, offLayer = null, enabled, order = 10 } = {}) {
117
117
  return { name: 'outline', slot: 'hdr', order, enabled, needsDepth: true, costly: mode !== 'depth', params: { color, thickness, strength, mode, fadeWithDistance, wobble, offLayer },
118
118
  create: ({ scene, camera, params }) => { const pass = new OutlinePass(scene, camera, params); apply(pass, params); return pass; },
119
- update: apply };
119
+ update: apply, node: outlineNode };
120
+ }
121
+
122
+ /**
123
+ * WebGPU: the same steps as OutlinePass's fragment shader, as one node (not three's OutlineNode, which outlines selected objects, a different
124
+ * 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
125
+ * 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.
126
+ * @param {any} input @param {any} ctx
127
+ */
128
+ function outlineNode(input, { tsl: T, display, scenePass, scene, camera, params, p }) {
129
+ const mode = MODES[params.mode];
130
+ if (mode === undefined) throw new Error(`outline: unknown mode '${params.mode}', use 'depth' | 'normal' | 'both'`);
131
+ const near = T.uniform(camera.near).onRenderUpdate(() => camera.near), far = T.uniform(camera.far).onRenderUpdate(() => camera.far);
132
+ const ortho = T.uniform(0).onRenderUpdate(() => (camera.isOrthographicCamera ? 1 : 0));
133
+ // 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
134
+ const tint = new THREE.Color(), col = T.uniform(tint).onRenderUpdate(() => { tint.set(params.color); });
135
+ // 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
136
+ 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(); };
137
+ const depthTex = scenePass.getTextureNode('depth');
138
+ const texel = T.vec2(1).div(T.screenSize), o = texel.mul(p.thickness), base = T.screenUV;
139
+ 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
140
+ // 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
141
+ const h2 = q => T.fract(T.sin(T.dot(q, T.vec2(127.1, 311.7))).mul(43758.5453));
142
+ const vn = q => { const i = T.floor(q), f0 = T.fract(q), f = f0.mul(f0).mul(f0.mul(-2).add(3));
143
+ 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); };
144
+ const tick = T.floor(T.mod(T.time, 64).mul(8)), px = base.div(texel).mul(0.04);
145
+ 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);
146
+ const uv = T.select(p.wobble.greaterThan(0), base.add(jitter), base);
147
+ const d = lin(depthTex, uv);
148
+ let edge = T.float(0);
149
+ if (mode !== 1) {
150
+ const e = nb.reduce((s, n) => s.add(lin(depthTex, uv.add(n)).sub(d).abs()), T.float(0));
151
+ edge = T.smoothstep(0.08, 0.3, e.div(T.max(d, 0.5)).mul(4));
152
+ }
153
+ // An extra render of the scene with one material, no background or fog. three's MeshNormalNodeMaterial stores its packed normal as an sRGB
154
+ // color (decoded to linear, so the canvas looks like WebGL's), unlike WebGL's MeshNormalMaterial in a render target, so the sample is
155
+ // 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
156
+ // normal facing the camera (as OutlinePass._pass), and for the mask its red (0.21 linear) stays below the > 0.5 test
157
+ const view = (mat, layer) => {
158
+ const v = display.pass(scene, camera);
159
+ v.overrideMaterial = mat;
160
+ 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
+ if (L) v.setLayers(L);
162
+ v.updateBefore = frame => {
163
+ const r = frame.renderer, bg = scene.background, fog = scene.fog, a = r.getClearAlpha();
164
+ if (L) L.set(params.offLayer);
165
+ r.getClearColor(was);
166
+ 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); }
169
+ };
170
+ v.dispose = () => { free(); mat.dispose(); };
171
+ return v;
172
+ };
173
+ if (mode !== 0) {
174
+ const nTex = view(new THREE.MeshNormalMaterial()).getTextureNode(), unpack = q => T.sRGBTransferOETF(nTex.sample(q).xyz).mul(2).sub(1), n = unpack(uv);
175
+ const k = nb.reduce((s, q) => s.add(T.float(1).sub(T.dot(n, unpack(uv.add(q))))), T.float(0));
176
+ edge = T.max(edge, T.smoothstep(0.35, 0.8, k));
177
+ }
178
+ 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)));
179
+ if (params.offLayer != null) {
180
+ const m = view(new THREE.MeshBasicMaterial({ color: 0xffffff }), true), mTex = m.getTextureNode(), mDepth = m.getTextureNode('depth');
181
+ // object in the exempt layer at this pixel: its own render is not behind what the scene depth saw (unwobbled uv, as the GLSL)
182
+ 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));
183
+ edge = edge.mul(T.float(1).sub(nb.reduce((s, q) => T.max(s, masked(base.add(q))), masked(base))));
184
+ }
185
+ return T.vec4(T.mix(input.rgb, col, edge.mul(p.strength)), input.a);
120
186
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threedog/post-effects",
3
- "version": "0.1.0",
3
+ "version": "0.5.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": {
@@ -24,7 +27,7 @@
24
27
  "*.d.ts"
25
28
  ],
26
29
  "peerDependencies": {
27
- "threedog": "^0.1.0",
30
+ "threedog": "^0.5.0",
28
31
  "three": "^0.187.0"
29
32
  }
30
33
  }