@clarity-js/fx 0.0.0-stage → 0.1.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 +72 -2
- package/index.d.ts +80 -0
- package/package.json +23 -4
- package/src/index.js +251 -0
package/README.md
CHANGED
|
@@ -1,3 +1,73 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @clarity-js/fx
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The pieces a lens is made of, for scenes built with [`@clarity-js/three`](../clarity-three):
|
|
4
|
+
full-screen passes, HDR render targets, bloom, feedback buffers, 3D noise and a frame-rate
|
|
5
|
+
guard. Plain three.js (WebGL2) underneath; no build step, no image files.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @clarity-js/fx three
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
`<Scene effects={…}>` hands you the renderer, the scene and the camera and asks for
|
|
12
|
+
`{ render(dt), setSize(w, h), setPixelRatio?(r), dispose() }`. A lens with bloom:
|
|
13
|
+
|
|
14
|
+
```js
|
|
15
|
+
import { createPass, createTarget, createBloom, GLSL } from '@clarity-js/fx';
|
|
16
|
+
|
|
17
|
+
export function makeLens({ renderer, scene, camera }) {
|
|
18
|
+
const bloom = createBloom({ levels: 5, threshold: 1.0 });
|
|
19
|
+
const final = createPass(`
|
|
20
|
+
in vec2 vUv; out vec4 o;
|
|
21
|
+
uniform sampler2D tColor, tBloom;
|
|
22
|
+
${GLSL.aces} ${GLSL.srgb}
|
|
23
|
+
void main() {
|
|
24
|
+
vec3 c = texture(tColor, vUv).rgb + texture(tBloom, vUv).rgb * 0.6;
|
|
25
|
+
o = vec4(toSRGB(aces(c)), 1.0);
|
|
26
|
+
}`, { tColor: { value: null }, tBloom: { value: null } });
|
|
27
|
+
let rt, w = 1, h = 1, dpr = 1;
|
|
28
|
+
return {
|
|
29
|
+
setPixelRatio(r) { dpr = r; },
|
|
30
|
+
setSize(nw, nh) {
|
|
31
|
+
w = nw; h = nh; rt?.dispose();
|
|
32
|
+
rt = createTarget(Math.round(w * dpr), Math.round(h * dpr), { depth: true, samples: 4 });
|
|
33
|
+
bloom.setSize(rt.width, rt.height);
|
|
34
|
+
final.uniforms.tColor.value = rt.texture;
|
|
35
|
+
},
|
|
36
|
+
render() {
|
|
37
|
+
renderer.setRenderTarget(rt); renderer.clear(); renderer.render(scene, camera);
|
|
38
|
+
final.uniforms.tBloom.value = bloom.render(renderer, rt.texture);
|
|
39
|
+
final.render(renderer, null);
|
|
40
|
+
},
|
|
41
|
+
dispose() { rt?.dispose(); bloom.dispose(); final.dispose(); },
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
```clarity
|
|
47
|
+
<Scene toneMapping="none" effects={ makeLens }> … </Scene>
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Render with `toneMapping="none"`: the scene goes into the HDR target in linear light, and
|
|
51
|
+
your last pass does the tone mapping and the sRGB conversion (`GLSL.aces`, `GLSL.srgb`).
|
|
52
|
+
|
|
53
|
+
## What is in the box
|
|
54
|
+
|
|
55
|
+
| | |
|
|
56
|
+
|---|---|
|
|
57
|
+
| `createPass(fragment, uniforms, { defines, blending })` | A full-screen shader pass (GLSL ES 3). The fragment gets `in vec2 vUv` and declares its own `out vec4`. `render(renderer, target)`; `null` is the screen. |
|
|
58
|
+
| `createTarget(w, h, { depth, samples, type, filter, wrap })` | A half-float render target. `depth: true` adds a depth texture you can sample; `samples: 4` turns on MSAA. |
|
|
59
|
+
| `createBloom({ levels, threshold, knee, spread })` | Mip-chain bloom: 13-tap downsample with a Karis average on the first step (thin, very bright lights do not flicker), tent upsample. `render(renderer, texture)` returns a half-resolution texture to add to the image. |
|
|
60
|
+
| `createFeedback(w, h, fragment, uniforms)` | A texture that feeds back into itself. Each `step(renderer)` runs your fragment with the previous state in `tPrev`. Hand `feedback.uniform` to any material: it always points at the latest state. Wakes, trails, ink, heat. |
|
|
61
|
+
| `noiseTexture3D(size, seed)` | Tileable 3D value noise (R8, trilinear). Sample it at two scales for drifting fog. |
|
|
62
|
+
| `createAutoScale({ fps, min })` | Watches the frame time; when the device cannot hold `fps`, `tick(dt)` returns true and `scale` has dropped. Re-allocate your targets at `size × scale`. It only steps down. |
|
|
63
|
+
| `GLSL` | Chunks to paste into a shader: `aces`, `srgb`, `ign` (dither noise for ray-march offsets), `hash`. |
|
|
64
|
+
|
|
65
|
+
## In use
|
|
66
|
+
|
|
67
|
+
The [Lightkeeper demo](https://clarity-js.com/demos/Lightkeeper.html) is built from these: the wakes
|
|
68
|
+
and the glowing plankton are one `createFeedback` texture; the light in the air is one
|
|
69
|
+
`createPass` that ray-marches the beam's cone through `noiseTexture3D` mist; `createBloom`
|
|
70
|
+
and a final `createPass` finish the picture; `createAutoScale` keeps it smooth on phones.
|
|
71
|
+
Source: `website/demos-src/src/lightkeeper/lens.js`.
|
|
72
|
+
|
|
73
|
+
MIT
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// @clarity-js/fx — type definitions
|
|
2
|
+
import type * as THREE from 'three';
|
|
3
|
+
|
|
4
|
+
export declare const GLSL: {
|
|
5
|
+
/** ACES filmic tone mapping: `vec3 aces(vec3)`. */
|
|
6
|
+
aces: string;
|
|
7
|
+
/** Linear → sRGB: `vec3 toSRGB(vec3)`. The last pass of a pipeline must do this. */
|
|
8
|
+
srgb: string;
|
|
9
|
+
/** Interleaved gradient noise: `float ign(vec2)`. */
|
|
10
|
+
ign: string;
|
|
11
|
+
/** `float hash12(vec2)`. */
|
|
12
|
+
hash: string;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export interface Pass<U extends Record<string, THREE.IUniform> = Record<string, THREE.IUniform>> {
|
|
16
|
+
material: THREE.RawShaderMaterial;
|
|
17
|
+
uniforms: U;
|
|
18
|
+
/** Draw the pass into `target` (null = the screen). */
|
|
19
|
+
render(renderer: THREE.WebGLRenderer, target?: THREE.WebGLRenderTarget | null): void;
|
|
20
|
+
dispose(): void;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** A full-screen shader pass (GLSL ES 3). The fragment shader gets `in vec2 vUv` and declares its own `out vec4`. */
|
|
24
|
+
export declare function createPass<U extends Record<string, THREE.IUniform>>(
|
|
25
|
+
fragment: string,
|
|
26
|
+
uniforms?: U,
|
|
27
|
+
options?: { defines?: Record<string, string | number>; blending?: THREE.Blending },
|
|
28
|
+
): Pass<U>;
|
|
29
|
+
|
|
30
|
+
/** An HDR (half-float) render target. `depth: true` adds a depth texture you can sample; `samples` enables MSAA. */
|
|
31
|
+
export declare function createTarget(
|
|
32
|
+
width: number,
|
|
33
|
+
height: number,
|
|
34
|
+
options?: { depth?: boolean; samples?: number; type?: THREE.TextureDataType; filter?: THREE.MagnificationTextureFilter; wrap?: THREE.Wrapping; format?: THREE.PixelFormat },
|
|
35
|
+
): THREE.WebGLRenderTarget;
|
|
36
|
+
|
|
37
|
+
export interface Bloom {
|
|
38
|
+
uniforms: { threshold: THREE.IUniform<number>; knee: THREE.IUniform<number>; spread: THREE.IUniform<number> };
|
|
39
|
+
/** Size of the texture you will pass to render(). */
|
|
40
|
+
setSize(width: number, height: number): void;
|
|
41
|
+
/** Returns a half-resolution texture to add to the image. */
|
|
42
|
+
render(renderer: THREE.WebGLRenderer, texture: THREE.Texture): THREE.Texture;
|
|
43
|
+
dispose(): void;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** A wide, stable bloom: 13-tap downsample chain with a Karis average, tent upsample. */
|
|
47
|
+
export declare function createBloom(options?: { levels?: number; threshold?: number; knee?: number; spread?: number }): Bloom;
|
|
48
|
+
|
|
49
|
+
export interface Feedback<U extends Record<string, THREE.IUniform> = Record<string, THREE.IUniform>> {
|
|
50
|
+
/** The pass's uniforms: `tPrev` (the previous state), `uTexel`, and yours. */
|
|
51
|
+
uniforms: U & { tPrev: THREE.IUniform<THREE.Texture | null>; uTexel: THREE.IUniform<THREE.Vector2> };
|
|
52
|
+
/** A uniform object that always holds the latest state: share it with your materials. */
|
|
53
|
+
uniform: THREE.IUniform<THREE.Texture>;
|
|
54
|
+
readonly texture: THREE.Texture;
|
|
55
|
+
step(renderer: THREE.WebGLRenderer): void;
|
|
56
|
+
clear(renderer: THREE.WebGLRenderer): void;
|
|
57
|
+
dispose(): void;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A texture that feeds back into itself: trails, wakes, ink, heat. */
|
|
61
|
+
export declare function createFeedback<U extends Record<string, THREE.IUniform>>(
|
|
62
|
+
width: number,
|
|
63
|
+
height: number,
|
|
64
|
+
fragment: string,
|
|
65
|
+
uniforms?: U,
|
|
66
|
+
options?: { type?: THREE.TextureDataType; filter?: THREE.MagnificationTextureFilter; wrap?: THREE.Wrapping },
|
|
67
|
+
): Feedback<U>;
|
|
68
|
+
|
|
69
|
+
/** Tileable 3D value noise (R8, trilinear, repeating). */
|
|
70
|
+
export declare function noiseTexture3D(size?: number, seed?: number): THREE.Data3DTexture;
|
|
71
|
+
|
|
72
|
+
export interface AutoScale {
|
|
73
|
+
/** Current render scale, 1 … min. */
|
|
74
|
+
scale: number;
|
|
75
|
+
/** Call once a frame. Returns true when `scale` dropped: re-allocate your targets. */
|
|
76
|
+
tick(dt: number): boolean;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Lowers the render scale when the frame rate stays under `fps`. It only steps down. */
|
|
80
|
+
export declare function createAutoScale(options?: { fps?: number; min?: number; step?: number; settle?: number }): AutoScale;
|
package/package.json
CHANGED
|
@@ -1,6 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@clarity-js/fx",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "The pieces a lens is made of: full-screen passes, HDR targets, bloom, feedback buffers and 3D noise for Clarity.js scenes (@clarity-js/three) — plain three.js underneath.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.js",
|
|
7
|
+
"module": "./src/index.js",
|
|
8
|
+
"types": "./index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": { "types": "./index.d.ts", "import": "./src/index.js", "default": "./src/index.js" }
|
|
11
|
+
},
|
|
12
|
+
"files": ["src/", "index.d.ts", "README.md"],
|
|
13
|
+
"sideEffects": false,
|
|
14
|
+
"keywords": ["clarity", "@clarity-js/three", "three", "threejs", "postprocessing", "bloom", "volumetric", "webgl", "effects", "game"],
|
|
15
|
+
"license": "MIT",
|
|
16
|
+
"peerDependencies": {
|
|
17
|
+
"three": ">=0.170.0"
|
|
18
|
+
},
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "git+https://gitlab.com/ozsarman/clarity.js.git",
|
|
22
|
+
"directory": "packages/clarity-fx"
|
|
23
|
+
},
|
|
24
|
+
"homepage": "https://clarity-js.com/docs/three"
|
|
25
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
// @clarity-js/fx — the pieces a lens is made of.
|
|
2
|
+
//
|
|
3
|
+
// <Scene effects={…}> hands you the renderer, the scene and the camera and asks for
|
|
4
|
+
// { render(dt), setSize(w, h), dispose() }. These are the building blocks for that:
|
|
5
|
+
//
|
|
6
|
+
// createPass(fragment, uniforms) a full-screen shader pass
|
|
7
|
+
// createTarget(w, h, options) an HDR render target, optionally with a depth texture / MSAA
|
|
8
|
+
// createBloom(options) a wide, stable bloom (mip chain, 13-tap down, tent up)
|
|
9
|
+
// createFeedback(w, h, fragment) a texture that remembers: trails, wakes, ink, heat
|
|
10
|
+
// noiseTexture3D(size) tileable 3D noise for fog and smoke
|
|
11
|
+
// createAutoScale(options) watches the frame time and lowers the render scale on slow devices
|
|
12
|
+
// GLSL small shader chunks: tone mapping, sRGB, dither noise
|
|
13
|
+
//
|
|
14
|
+
// Everything is plain three.js (WebGL2); nothing here knows about Clarity components.
|
|
15
|
+
|
|
16
|
+
import * as THREE from 'three';
|
|
17
|
+
|
|
18
|
+
const FS_VERT = /* glsl */`
|
|
19
|
+
in vec3 position;
|
|
20
|
+
out vec2 vUv;
|
|
21
|
+
void main() { vUv = position.xy * 0.5 + 0.5; gl_Position = vec4(position.xy, 0.0, 1.0); }
|
|
22
|
+
`;
|
|
23
|
+
|
|
24
|
+
let triGeo = null, triCam = null;
|
|
25
|
+
function triangle() {
|
|
26
|
+
if (!triGeo) {
|
|
27
|
+
triGeo = new THREE.BufferGeometry();
|
|
28
|
+
triGeo.setAttribute('position', new THREE.BufferAttribute(new Float32Array([-1, -1, 0, 3, -1, 0, -1, 3, 0]), 3));
|
|
29
|
+
triCam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
|
|
30
|
+
}
|
|
31
|
+
return triGeo;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Shader chunks. Paste into a fragment shader: `${GLSL.aces}`. */
|
|
35
|
+
export const GLSL = {
|
|
36
|
+
/** ACES filmic tone mapping (Narkowicz fit). */
|
|
37
|
+
aces: /* glsl */`
|
|
38
|
+
vec3 aces(vec3 x) { return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), 0.0, 1.0); }
|
|
39
|
+
`,
|
|
40
|
+
/** Linear → sRGB. A raw pass writes to the screen as-is, so the last pass must do this. */
|
|
41
|
+
srgb: /* glsl */`
|
|
42
|
+
vec3 toSRGB(vec3 c) { return mix(c * 12.92, 1.055 * pow(max(c, 0.0), vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c)); }
|
|
43
|
+
`,
|
|
44
|
+
/** Interleaved gradient noise: a cheap, even dither for ray-march offsets and banding. */
|
|
45
|
+
ign: /* glsl */`
|
|
46
|
+
float ign(vec2 p) { return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); }
|
|
47
|
+
`,
|
|
48
|
+
hash: /* glsl */`
|
|
49
|
+
float hash12(vec2 p) { vec3 q = fract(vec3(p.xyx) * 0.1031); q += dot(q, q.yzx + 33.33); return fract((q.x + q.y) * q.z); }
|
|
50
|
+
`,
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* A full-screen pass. `fragment` gets `in vec2 vUv` and must declare its own `out vec4`.
|
|
55
|
+
* render(renderer, target) draws it into a render target (null = the screen).
|
|
56
|
+
*/
|
|
57
|
+
export function createPass(fragment, uniforms = {}, { defines = {}, blending = THREE.NoBlending } = {}) {
|
|
58
|
+
const material = new THREE.RawShaderMaterial({
|
|
59
|
+
glslVersion: THREE.GLSL3,
|
|
60
|
+
vertexShader: FS_VERT,
|
|
61
|
+
fragmentShader: 'precision highp float;\nprecision highp sampler3D;\n' + fragment,
|
|
62
|
+
uniforms, defines, blending,
|
|
63
|
+
depthTest: false, depthWrite: false, transparent: blending !== THREE.NoBlending,
|
|
64
|
+
});
|
|
65
|
+
const mesh = new THREE.Mesh(triangle(), material);
|
|
66
|
+
mesh.frustumCulled = false;
|
|
67
|
+
return {
|
|
68
|
+
material, uniforms: material.uniforms,
|
|
69
|
+
render(renderer, target = null) {
|
|
70
|
+
renderer.setRenderTarget(target);
|
|
71
|
+
renderer.render(mesh, triCam);
|
|
72
|
+
},
|
|
73
|
+
dispose() { material.dispose(); },
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** An HDR (half-float) render target. `depth: true` adds a depth texture you can sample. */
|
|
78
|
+
export function createTarget(w, h, { depth = false, samples = 0, type = THREE.HalfFloatType, filter = THREE.LinearFilter, wrap = THREE.ClampToEdgeWrapping, format = THREE.RGBAFormat } = {}) {
|
|
79
|
+
const options = { type, format, samples, minFilter: filter, magFilter: filter, wrapS: wrap, wrapT: wrap, depthBuffer: !!depth };
|
|
80
|
+
if (depth) {
|
|
81
|
+
options.depthTexture = new THREE.DepthTexture(w, h);
|
|
82
|
+
options.depthTexture.type = THREE.UnsignedIntType;
|
|
83
|
+
}
|
|
84
|
+
return new THREE.WebGLRenderTarget(Math.max(1, w), Math.max(1, h), options);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const BLOOM_DOWN = /* glsl */`
|
|
88
|
+
in vec2 vUv; out vec4 o;
|
|
89
|
+
uniform sampler2D tSrc; uniform vec2 uTexel; uniform float uThreshold; uniform float uKnee; uniform float uFirst;
|
|
90
|
+
float luma(vec3 c) { return dot(c, vec3(0.2126, 0.7152, 0.0722)); }
|
|
91
|
+
vec3 pre(vec3 c) { // soft threshold, on the first step only
|
|
92
|
+
float b = max(c.r, max(c.g, c.b));
|
|
93
|
+
float s = clamp(b - uThreshold + uKnee, 0.0, 2.0 * uKnee);
|
|
94
|
+
s = s * s / (4.0 * uKnee + 1e-4);
|
|
95
|
+
return c * max(s, b - uThreshold) / max(b, 1e-4);
|
|
96
|
+
}
|
|
97
|
+
void main() {
|
|
98
|
+
// 13 taps (Jimenez 2014): wide and free of the pulsing a 4-tap box gives on thin lights
|
|
99
|
+
vec2 t = uTexel;
|
|
100
|
+
vec3 a = texture(tSrc, vUv + t * vec2(-2.0, 2.0)).rgb, b = texture(tSrc, vUv + t * vec2(0.0, 2.0)).rgb, c = texture(tSrc, vUv + t * vec2(2.0, 2.0)).rgb;
|
|
101
|
+
vec3 d = texture(tSrc, vUv + t * vec2(-2.0, 0.0)).rgb, e = texture(tSrc, vUv).rgb, f = texture(tSrc, vUv + t * vec2(2.0, 0.0)).rgb;
|
|
102
|
+
vec3 g = texture(tSrc, vUv + t * vec2(-2.0, -2.0)).rgb, h = texture(tSrc, vUv + t * vec2(0.0, -2.0)).rgb, i = texture(tSrc, vUv + t * vec2(2.0, -2.0)).rgb;
|
|
103
|
+
vec3 j = texture(tSrc, vUv + t * vec2(-1.0, 1.0)).rgb, k = texture(tSrc, vUv + t * vec2(1.0, 1.0)).rgb;
|
|
104
|
+
vec3 l = texture(tSrc, vUv + t * vec2(-1.0, -1.0)).rgb, m = texture(tSrc, vUv + t * vec2(1.0, -1.0)).rgb;
|
|
105
|
+
vec3 col;
|
|
106
|
+
if (uFirst > 0.5) {
|
|
107
|
+
// Karis average: weigh each group by 1/(1+luma) so one very bright pixel cannot flicker
|
|
108
|
+
vec3 g0 = (a + b + d + e) * 0.25, g1 = (b + c + e + f) * 0.25, g2 = (d + e + g + h) * 0.25, g3 = (e + f + h + i) * 0.25, g4 = (j + k + l + m) * 0.25;
|
|
109
|
+
float w0 = 1.0 / (1.0 + luma(g0)), w1 = 1.0 / (1.0 + luma(g1)), w2 = 1.0 / (1.0 + luma(g2)), w3 = 1.0 / (1.0 + luma(g3)), w4 = 4.0 / (1.0 + luma(g4));
|
|
110
|
+
col = pre((g0 * w0 + g1 * w1 + g2 * w2 + g3 * w3 + g4 * w4) / (w0 + w1 + w2 + w3 + w4));
|
|
111
|
+
} else {
|
|
112
|
+
col = e * 0.125 + (a + c + g + i) * 0.03125 + (b + d + f + h) * 0.0625 + (j + k + l + m) * 0.125;
|
|
113
|
+
}
|
|
114
|
+
o = vec4(max(col, 0.0), 1.0);
|
|
115
|
+
}
|
|
116
|
+
`;
|
|
117
|
+
|
|
118
|
+
const BLOOM_UP = /* glsl */`
|
|
119
|
+
in vec2 vUv; out vec4 o;
|
|
120
|
+
uniform sampler2D tLow; uniform sampler2D tHigh; uniform vec2 uTexel; uniform float uSpread;
|
|
121
|
+
void main() {
|
|
122
|
+
vec2 t = uTexel;
|
|
123
|
+
vec3 s = texture(tLow, vUv).rgb * 4.0;
|
|
124
|
+
s += (texture(tLow, vUv + vec2(t.x, 0.0)).rgb + texture(tLow, vUv - vec2(t.x, 0.0)).rgb + texture(tLow, vUv + vec2(0.0, t.y)).rgb + texture(tLow, vUv - vec2(0.0, t.y)).rgb) * 2.0;
|
|
125
|
+
s += texture(tLow, vUv + t).rgb + texture(tLow, vUv - t).rgb + texture(tLow, vUv + vec2(t.x, -t.y)).rgb + texture(tLow, vUv + vec2(-t.x, t.y)).rgb;
|
|
126
|
+
o = vec4(s / 16.0 * uSpread + texture(tHigh, vUv).rgb, 1.0);
|
|
127
|
+
}
|
|
128
|
+
`;
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Bloom. render(renderer, hdrTexture) returns a half-resolution texture to add to the image.
|
|
132
|
+
* levels: how wide the glow reaches (each level doubles it). threshold/knee are in scene
|
|
133
|
+
* (linear, HDR) units: 1 = paper white.
|
|
134
|
+
*/
|
|
135
|
+
export function createBloom({ levels = 5, threshold = 1.0, knee = 0.5, spread = 1.0 } = {}) {
|
|
136
|
+
const down = createPass(BLOOM_DOWN, { tSrc: { value: null }, uTexel: { value: new THREE.Vector2() }, uThreshold: { value: threshold }, uKnee: { value: knee }, uFirst: { value: 0 } });
|
|
137
|
+
const up = createPass(BLOOM_UP, { tLow: { value: null }, tHigh: { value: null }, uTexel: { value: new THREE.Vector2() }, uSpread: { value: spread } });
|
|
138
|
+
let downs = [], ups = [], srcW = 1, srcH = 1;
|
|
139
|
+
const free = () => { for (const t of [...downs, ...ups]) t.dispose(); downs = []; ups = []; };
|
|
140
|
+
return {
|
|
141
|
+
uniforms: { threshold: down.uniforms.uThreshold, knee: down.uniforms.uKnee, spread: up.uniforms.uSpread },
|
|
142
|
+
setSize(w, h) {
|
|
143
|
+
free(); srcW = w; srcH = h;
|
|
144
|
+
for (let i = 0; i < levels; i++) {
|
|
145
|
+
const W = Math.max(2, w >> (i + 1)), H = Math.max(2, h >> (i + 1));
|
|
146
|
+
downs.push(createTarget(W, H));
|
|
147
|
+
if (i < levels - 1) ups.push(createTarget(W, H));
|
|
148
|
+
}
|
|
149
|
+
},
|
|
150
|
+
render(renderer, texture) {
|
|
151
|
+
if (!downs.length) return texture;
|
|
152
|
+
for (let i = 0; i < downs.length; i++) {
|
|
153
|
+
const src = i === 0 ? texture : downs[i - 1].texture;
|
|
154
|
+
const sw = i === 0 ? srcW : downs[i - 1].width, sh = i === 0 ? srcH : downs[i - 1].height;
|
|
155
|
+
down.uniforms.tSrc.value = src; down.uniforms.uTexel.value.set(1 / sw, 1 / sh); down.uniforms.uFirst.value = i === 0 ? 1 : 0;
|
|
156
|
+
down.render(renderer, downs[i]);
|
|
157
|
+
}
|
|
158
|
+
let low = downs[downs.length - 1];
|
|
159
|
+
for (let i = downs.length - 2; i >= 0; i--) {
|
|
160
|
+
up.uniforms.tLow.value = low.texture; up.uniforms.tHigh.value = downs[i].texture; up.uniforms.uTexel.value.set(1 / low.width, 1 / low.height);
|
|
161
|
+
up.render(renderer, ups[i]);
|
|
162
|
+
low = ups[i];
|
|
163
|
+
}
|
|
164
|
+
return low.texture;
|
|
165
|
+
},
|
|
166
|
+
dispose() { free(); down.dispose(); up.dispose(); },
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* A texture that feeds back into itself: each step() runs `fragment` with the previous
|
|
172
|
+
* state in `tPrev` and keeps the result. Use it for anything that leaves a trace.
|
|
173
|
+
*/
|
|
174
|
+
export function createFeedback(w, h, fragment, uniforms = {}, { type = THREE.HalfFloatType, filter = THREE.LinearFilter, wrap = THREE.ClampToEdgeWrapping } = {}) {
|
|
175
|
+
let a = createTarget(w, h, { type, filter, wrap }), b = createTarget(w, h, { type, filter, wrap });
|
|
176
|
+
const pass = createPass(fragment, { tPrev: { value: null }, uTexel: { value: new THREE.Vector2(1 / w, 1 / h) }, ...uniforms });
|
|
177
|
+
const out = { value: a.texture };
|
|
178
|
+
return {
|
|
179
|
+
uniforms: pass.uniforms,
|
|
180
|
+
/** A uniform object ({ value }) that always holds the latest state: share it with materials. */
|
|
181
|
+
uniform: out,
|
|
182
|
+
get texture() { return a.texture; },
|
|
183
|
+
step(renderer) {
|
|
184
|
+
pass.uniforms.tPrev.value = a.texture;
|
|
185
|
+
pass.render(renderer, b);
|
|
186
|
+
const t = a; a = b; b = t;
|
|
187
|
+
out.value = a.texture;
|
|
188
|
+
},
|
|
189
|
+
clear(renderer) {
|
|
190
|
+
const prev = renderer.getClearColor(new THREE.Color()), alpha = renderer.getClearAlpha();
|
|
191
|
+
renderer.setClearColor(0x000000, 0);
|
|
192
|
+
for (const t of [a, b]) { renderer.setRenderTarget(t); renderer.clear(); }
|
|
193
|
+
renderer.setClearColor(prev, alpha);
|
|
194
|
+
},
|
|
195
|
+
dispose() { a.dispose(); b.dispose(); pass.dispose(); },
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Tileable 3D value noise (R8, trilinear, repeating): sample it twice at different scales for fog. */
|
|
200
|
+
export function noiseTexture3D(size = 32, seed = 1) {
|
|
201
|
+
let s = seed >>> 0;
|
|
202
|
+
const rnd = () => { s = (s + 0x6d2b79f5) | 0; let t = Math.imul(s ^ (s >>> 15), 1 | s); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
|
|
203
|
+
const G = 8, lattice = new Float32Array(G * G * G);
|
|
204
|
+
for (let i = 0; i < lattice.length; i++) lattice[i] = rnd();
|
|
205
|
+
const at = (x, y, z) => lattice[((z % G) * G + (y % G)) * G + (x % G)];
|
|
206
|
+
const fade = (t) => t * t * (3 - 2 * t);
|
|
207
|
+
const data = new Uint8Array(size * size * size);
|
|
208
|
+
for (let z = 0; z < size; z++) for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) {
|
|
209
|
+
let v = 0, amp = 0.6, f = 1;
|
|
210
|
+
for (let o = 0; o < 2; o++) { // two octaves, both tile
|
|
211
|
+
const px = (x / size) * G * f, py = (y / size) * G * f, pz = (z / size) * G * f;
|
|
212
|
+
const x0 = Math.floor(px), y0 = Math.floor(py), z0 = Math.floor(pz);
|
|
213
|
+
const tx = fade(px - x0), ty = fade(py - y0), tz = fade(pz - z0);
|
|
214
|
+
const l = (a, b2, t) => a + (b2 - a) * t;
|
|
215
|
+
v += amp * l(
|
|
216
|
+
l(l(at(x0, y0, z0), at(x0 + 1, y0, z0), tx), l(at(x0, y0 + 1, z0), at(x0 + 1, y0 + 1, z0), tx), ty),
|
|
217
|
+
l(l(at(x0, y0, z0 + 1), at(x0 + 1, y0, z0 + 1), tx), l(at(x0, y0 + 1, z0 + 1), at(x0 + 1, y0 + 1, z0 + 1), tx), ty), tz);
|
|
218
|
+
amp *= 0.66; f *= 2;
|
|
219
|
+
}
|
|
220
|
+
data[(z * size + y) * size + x] = Math.max(0, Math.min(255, Math.round(v * 255)));
|
|
221
|
+
}
|
|
222
|
+
const tex = new THREE.Data3DTexture(data, size, size, size);
|
|
223
|
+
tex.format = THREE.RedFormat; tex.type = THREE.UnsignedByteType;
|
|
224
|
+
tex.minFilter = tex.magFilter = THREE.LinearFilter;
|
|
225
|
+
tex.wrapS = tex.wrapT = tex.wrapR = THREE.RepeatWrapping;
|
|
226
|
+
tex.unpackAlignment = 1; tex.needsUpdate = true;
|
|
227
|
+
return tex;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Keeps a scene smooth on devices that cannot afford it at full resolution. Call tick(dt)
|
|
232
|
+
* once a frame; when it returns true, `scale` has dropped and your render targets should be
|
|
233
|
+
* re-allocated at (size × scale). It only ever steps down: a display that is in sync with
|
|
234
|
+
* the screen cannot tell you how much headroom is left, so going back up would be a guess.
|
|
235
|
+
*/
|
|
236
|
+
export function createAutoScale({ fps = 45, min = 0.6, step = 0.86, settle = 1.5 } = {}) {
|
|
237
|
+
let ema = 1 / 60, wait = settle * 1.5, slow = 0;
|
|
238
|
+
const api = {
|
|
239
|
+
scale: 1,
|
|
240
|
+
tick(dt) {
|
|
241
|
+
if (!(dt > 0) || dt > 0.25) return false; // a paused tab is not a slow device
|
|
242
|
+
ema += (dt - ema) * 0.06;
|
|
243
|
+
if (wait > 0) { wait -= dt; return false; }
|
|
244
|
+
slow = ema > 1 / fps ? slow + dt : 0;
|
|
245
|
+
if (slow < 0.6 || api.scale <= min) return false;
|
|
246
|
+
api.scale = Math.max(min, api.scale * step); slow = 0; wait = settle; ema = 1 / 60;
|
|
247
|
+
return true;
|
|
248
|
+
},
|
|
249
|
+
};
|
|
250
|
+
return api;
|
|
251
|
+
}
|