@arraypress/effects-astro 0.14.0 → 0.15.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.
@@ -0,0 +1,283 @@
1
+ /**
2
+ * @module @arraypress/effects-astro/lens-flare
3
+ *
4
+ * An anamorphic lens flare, built the way the lens makes one rather than as a
5
+ * sticker: a small hot source with its glow, the long thin horizontal streak a
6
+ * cylindrical (anamorphic) element smears it into (blue from the coatings,
7
+ * white at its core, falling off along its length), a fainter second streak,
8
+ * a veil of scattered light round the source, and the ghosts: soft internal
9
+ * reflections lying on the line from the source through the frame's centre
10
+ * (on the far side too), each a tinted oval squeezed upright as anamorphic
11
+ * ghosts are, brighter at the rim than the middle. The source drifts slowly as
12
+ * if the light or the camera moved, and the ghosts travel the other way
13
+ * through the centre, as real ones do. A faint flicker and grain.
14
+ *
15
+ * Every clock is in seconds and nothing is kept between frames; where the
16
+ * source and the ghosts are, and how bright the streak is, are here in plain
17
+ * JavaScript too (`flareSource`, `flareGhosts`, `streakAt`).
18
+ *
19
+ * Opaque: it paints its `background` (default near-black) everywhere.
20
+ * Without WebGL nothing is drawn; with prefers-reduced-motion it is one
21
+ * still frame.
22
+ */
23
+
24
+ import { createStage } from './stage.js';
25
+ import { GLSL_HASH33 } from './hash-noise.js';
26
+ import { parseColor, toHex, mixOklab } from './color.js';
27
+ import { GLSL_QUIET, quietUniform } from './glsl.js';
28
+
29
+ /**
30
+ * @typedef {object} LensFlareConfig
31
+ * @property {string} [background='#030406'] The ground, painted everywhere.
32
+ * @property {string} [streak='#4f8dff'] The streak's colour (the coating's): blue for the classic, amber or teal for others.
33
+ * @property {string} [ghost='#ffb36b'] The ghosts' main tint; they also take the streak's and a green one.
34
+ * @property {string} [haze] The ground's glow round the source; default the streak's, deep.
35
+ * @property {[number, number]} [source=[0.24, 0.32]] Where the light is, 0–1 from the top left.
36
+ * @property {number} [length=1.6] How long the streak reaches each way, in widths.
37
+ * @property {number} [width=0.006] The streak's half-height, a share of the height.
38
+ * @property {number} [power=1] How bright it all is.
39
+ * @property {number} [ghosts=5] How many ghosts (0–6).
40
+ * @property {number} [drift=0.06] How far the source wanders, a share of the height.
41
+ * @property {number} [rate=0.05] How fast it wanders, cycles a second.
42
+ * @property {number} [flicker=0.04] How much the source's brightness flickers.
43
+ * @property {number} [grain=0.035] Fine grain; 0 for none.
44
+ * @property {number} [seed=0] Where its wandering starts.
45
+ * @property {number} [speed=1] Plays every clock faster or slower; 0 for one still frame.
46
+ * @property {{ x?: number, y?: number, radius?: number, depth?: number } | null} [quiet=null] An area dimmed (see `quietUniform`).
47
+ */
48
+
49
+ /** The settings' defaults, shared by the shader and the JS twin. */
50
+ export const FLARE_DEFAULTS = {
51
+ background: '#030406',
52
+ streak: '#4f8dff',
53
+ ghost: '#ffb36b',
54
+ source: /** @type {[number, number]} */ ([0.24, 0.32]),
55
+ length: 1.6,
56
+ width: 0.006,
57
+ power: 1,
58
+ ghosts: 5,
59
+ drift: 0.06,
60
+ rate: 0.05,
61
+ flicker: 0.04,
62
+ grain: 0.035,
63
+ seed: 0,
64
+ };
65
+
66
+ /** The most ghosts the shader draws. */
67
+ export const MAX_GHOSTS = 6;
68
+
69
+ /** Each ghost: where it lies on the line from the source through the centre (0 the source, 1 the centre, 2 the mirror),
70
+ * its radius (a share of the height), how bright, and which tint (0 the main, 1 the streak's, 2 green). */
71
+ const GHOSTS = [
72
+ [1.35, 0.05, 0.22, 0],
73
+ [1.75, 0.11, 0.1, 1],
74
+ [0.55, 0.022, 0.3, 2],
75
+ [2.15, 0.17, 0.06, 0],
76
+ [1.12, 0.012, 0.5, 1],
77
+ [0.8, 0.07, 0.08, 0],
78
+ ];
79
+
80
+ const FRAG = `
81
+ precision highp float;
82
+ uniform vec2 uRes;
83
+ uniform float uTime;
84
+ uniform vec3 uBg;
85
+ uniform vec3 uStreakC;
86
+ uniform vec3 uHazeC;
87
+ uniform vec3 uTint[3];
88
+ uniform vec2 uSrc;
89
+ uniform float uLen;
90
+ uniform float uWidth;
91
+ uniform float uPower;
92
+ uniform float uGhosts;
93
+ uniform float uDrift;
94
+ uniform float uRate;
95
+ uniform float uFlicker;
96
+ uniform float uGrain;
97
+ uniform float uSeed;
98
+ uniform vec4 uGhost[${MAX_GHOSTS}];
99
+ ${GLSL_QUIET}
100
+ ${GLSL_HASH33}
101
+
102
+ void main() {
103
+ vec2 px = vec2(gl_FragCoord.x, uRes.y - gl_FragCoord.y);
104
+ float aspect = uRes.x / uRes.y;
105
+ vec2 p = px / uRes.y; // heights from the top left
106
+ vec2 mid = vec2(0.5 * aspect, 0.5);
107
+ float ph = 6.2831853 * uTime * uRate;
108
+ vec2 s = uSrc + uDrift * vec2(sin(ph + uSeed), 0.55 * sin(ph * 0.71 + uSeed * 1.7));
109
+ float flick = 1.0 + uFlicker * (sin(uTime * 7.3 + uSeed) * 0.6 + sin(uTime * 12.9) * 0.4);
110
+ float pw = uPower * flick;
111
+ vec2 d = p - s;
112
+
113
+ vec3 col = uBg;
114
+ // the veil: light scattered in the glass, wide and dim round the source
115
+ float veil = exp(-dot(d, d) * 6.0) * 0.22 + exp(-length(d) * 3.2) * 0.12;
116
+ col += uHazeC * veil * pw;
117
+
118
+ // the streak: thin and long; its core whiter, its body the coating's colour, falling off along its length
119
+ float along = abs(d.x) / (uLen * aspect);
120
+ float fall = 1.0 / (1.0 + along * along * 7.0) * smoothstep(1.0, 0.15, along);
121
+ float thin = exp(-abs(d.y) / uWidth);
122
+ float body = exp(-abs(d.y) / (uWidth * 3.5));
123
+ col += uStreakC * (body * 0.55 + thin * 0.8) * fall * pw;
124
+ col += vec3(1.0) * thin * fall * fall * 0.9 * pw;
125
+ // a second, fainter streak just off the first (the lens's other elements)
126
+ float th2 = exp(-abs(d.y - uWidth * 9.0) / (uWidth * 1.2));
127
+ col += uStreakC * th2 * fall * 0.18 * pw;
128
+
129
+ // the source: a small hot core and its glow
130
+ float r = length(d);
131
+ col += vec3(1.0, 0.97, 0.92) * (exp(-r * r / 0.00012) * 1.6 + exp(-r * r / 0.0018) * 0.55) * pw;
132
+ col += uStreakC * exp(-r * r / 0.012) * 0.35 * pw;
133
+
134
+ // the ghosts: on the line through the centre, squeezed upright, brighter at the rim, a little chromatic
135
+ vec2 axis = mid - s;
136
+ for (int i = 0; i < ${MAX_GHOSTS}; i++) {
137
+ if (float(i) >= uGhosts) break;
138
+ vec4 g = uGhost[i];
139
+ vec2 c = s + axis * g.x;
140
+ vec2 q = (p - c) / vec2(0.78, 1.0);
141
+ float rr = length(q) / g.y;
142
+ vec3 tint = g.w < 0.5 ? uTint[0] : (g.w < 1.5 ? uTint[1] : uTint[2]);
143
+ float disc = smoothstep(1.0, 0.82, rr);
144
+ float rim = smoothstep(0.7, 0.97, rr) * smoothstep(1.06, 0.97, rr);
145
+ // red reaches a hair further than blue, as in a real ghost's edge
146
+ float fringe = smoothstep(1.06, 0.99, rr) - smoothstep(1.0, 0.93, rr);
147
+ col += tint * (disc * 0.5 + rim * 0.45) * g.z * pw;
148
+ col += vec3(0.45, 0.08, -0.15) * fringe * g.z * 0.3 * pw;
149
+ }
150
+
151
+ vec2 qc = vec2(p.x - 0.5 * aspect, 0.5 - p.y);
152
+ col = mix(uBg, col, mix(1.0 - uQuiet.w, 1.0, quietOpen(qc)));
153
+ // a soft filmic shoulder, so the hot parts burn to white rather than clip
154
+ col = 1.0 - exp(-col * 1.25);
155
+ col += (hash33(vec3(px, floor(uTime * 24.0))).x - 0.5) * uGrain;
156
+ gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);
157
+ }
158
+ `;
159
+
160
+ /**
161
+ * The settings, filled with the defaults.
162
+ *
163
+ * @param {LensFlareConfig} config The settings.
164
+ * @returns {typeof FLARE_DEFAULTS & { haze: string, speed: number }} The settings.
165
+ */
166
+ function settings(config) {
167
+ const o = { ...FLARE_DEFAULTS, speed: 1, ...config };
168
+ const haze = o.haze ?? toHex(mixOklab(parseColor(o.background), parseColor(o.streak), 0.55));
169
+ return { ...o, haze };
170
+ }
171
+
172
+ /**
173
+ * Where the source is at a time (the shader's), in heights from the top left.
174
+ *
175
+ * @param {LensFlareConfig} config The settings.
176
+ * @param {number} aspect Width over height.
177
+ * @param {number} [time=0] Seconds (already at its speed).
178
+ * @returns {[number, number]} The source.
179
+ */
180
+ export function flareSource(config, aspect, time = 0) {
181
+ const o = settings(config);
182
+ const ph = 2 * Math.PI * time * o.rate;
183
+ return [o.source[0] * aspect + o.drift * Math.sin(ph + o.seed), o.source[1] + o.drift * 0.55 * Math.sin(ph * 0.71 + o.seed * 1.7)];
184
+ }
185
+
186
+ /**
187
+ * Where the ghosts are at a time: on the line from the source through the centre.
188
+ *
189
+ * @param {LensFlareConfig} config The settings.
190
+ * @param {number} aspect Width over height.
191
+ * @param {number} [time=0] Seconds.
192
+ * @returns {{ x: number, y: number, radius: number }[]} Each ghost's centre (heights) and radius.
193
+ */
194
+ export function flareGhosts(config, aspect, time = 0) {
195
+ const o = settings(config);
196
+ const [sx, sy] = flareSource(config, aspect, time);
197
+ const ax = 0.5 * aspect - sx,
198
+ ay = 0.5 - sy;
199
+ return GHOSTS.slice(0, Math.max(0, Math.min(MAX_GHOSTS, o.ghosts))).map(([t, radius]) => ({ x: sx + ax * t, y: sy + ay * t, radius }));
200
+ }
201
+
202
+ /**
203
+ * How bright the streak is at a point, before the colours (the shader's `fall × thin`).
204
+ *
205
+ * @param {LensFlareConfig} config The settings.
206
+ * @param {number} x Heights from the left.
207
+ * @param {number} y Heights from the top.
208
+ * @param {number} aspect Width over height.
209
+ * @param {number} [time=0] Seconds.
210
+ * @returns {number} 0–1.
211
+ */
212
+ export function streakAt(config, x, y, aspect, time = 0) {
213
+ const o = settings(config);
214
+ const [sx, sy] = flareSource(config, aspect, time);
215
+ const along = Math.abs(x - sx) / (o.length * aspect);
216
+ const t = Math.min(1, Math.max(0, (1 - along) / 0.85));
217
+ const fall = (1 / (1 + along * along * 7)) * t * t * (3 - 2 * t);
218
+ return fall * Math.exp(-Math.abs(y - sy) / o.width);
219
+ }
220
+
221
+ /**
222
+ * A CSS `background` that stands in for the flare before the shader starts
223
+ * and without WebGL: the source's glow, the streak as a thin horizontal band,
224
+ * the ground.
225
+ *
226
+ * @param {LensFlareConfig} config The settings.
227
+ * @returns {string} The CSS background.
228
+ */
229
+ export function flareStill(config) {
230
+ const o = settings(config);
231
+ const [x, y] = o.source.map((v) => Math.round(v * 100));
232
+ const streak = toHex(parseColor(o.streak));
233
+ const band = `linear-gradient(180deg, transparent ${y - 1.2}%, ${streak}66 ${y - 0.4}%, #ffffffcc ${y}%, ${streak}66 ${y + 0.4}%, transparent ${y + 1.2}%)`;
234
+ const glow = `radial-gradient(circle at ${x}% ${y}%, #ffffff 0, ${streak}aa 1.5%, ${o.haze} 12%, transparent 45%)`;
235
+ return [glow, band, o.background].join(', ');
236
+ }
237
+
238
+ /**
239
+ * Starts the flare on an element: a canvas inside it (its first).
240
+ *
241
+ * @param {HTMLElement} el The element.
242
+ * @param {LensFlareConfig} config The settings.
243
+ * @returns {() => void} Stops it.
244
+ */
245
+ export function lensFlare(el, config) {
246
+ const o = settings(config);
247
+ const rgb = (/** @type {string} */ c) => parseColor(c);
248
+ const start = performance.now();
249
+ const ghostTints = [rgb(o.ghost), rgb(o.streak), [0.35, 0.95, 0.6]];
250
+ const ghosts = new Float32Array(GHOSTS.flat());
251
+
252
+ const { stage, stop } = createStage(el, {
253
+ fragment: FRAG,
254
+ alpha: false,
255
+ still: o.speed <= 0,
256
+ setup({ gl, uniform }) {
257
+ gl.uniform3fv(uniform('uBg'), rgb(o.background));
258
+ gl.uniform3fv(uniform('uStreakC'), rgb(o.streak));
259
+ gl.uniform3fv(uniform('uHazeC'), rgb(o.haze));
260
+ gl.uniform3fv(uniform('uTint[0]'), new Float32Array(ghostTints.flat()));
261
+ gl.uniform1f(uniform('uLen'), o.length);
262
+ gl.uniform1f(uniform('uWidth'), o.width);
263
+ gl.uniform1f(uniform('uPower'), o.power);
264
+ gl.uniform1f(uniform('uGhosts'), Math.min(MAX_GHOSTS, Math.max(0, o.ghosts)));
265
+ gl.uniform1f(uniform('uDrift'), o.drift);
266
+ gl.uniform1f(uniform('uRate'), o.rate);
267
+ gl.uniform1f(uniform('uFlicker'), o.flicker);
268
+ gl.uniform1f(uniform('uGrain'), o.grain);
269
+ gl.uniform1f(uniform('uSeed'), o.seed);
270
+ gl.uniform4fv(uniform('uGhost[0]'), ghosts);
271
+ },
272
+ resize({ gl, uniform }) {
273
+ const w = Math.max(1, el.clientWidth);
274
+ const h = Math.max(1, el.clientHeight);
275
+ gl.uniform2f(uniform('uSrc'), o.source[0] * (w / h), o.source[1]);
276
+ gl.uniform4f(uniform('uQuiet'), ...quietUniform(config.quiet, w / h));
277
+ },
278
+ uniforms({ gl, uniform }, now) {
279
+ gl.uniform1f(uniform('uTime'), ((now - start) / 1000) * Math.max(0, o.speed));
280
+ },
281
+ });
282
+ return stop;
283
+ }
@@ -0,0 +1,89 @@
1
+ export interface PaintDripConfig {
2
+ /** The mark, as an image URL (a white SVG works; only its alpha is used). */
3
+ src?: string;
4
+ /** The paint. Default '#C8FF00'. */
5
+ color?: string;
6
+ /** The ground, painted everywhere. Default '#85857F'. */
7
+ background?: string;
8
+ /** Where the mark sits: its centre (0–1 from the top left) and its edge (a share of the height). Default { x: 0.5, y: 0.42, size: 0.5 }. */
9
+ box?: { x: number; y: number; size: number };
10
+ /** How many drips run. Default 3. */
11
+ drips?: number;
12
+ /** How much paint each drip carries (longer runs). Default 1. */
13
+ volume?: number;
14
+ /** No drip runs past this, a share of the height from the top (the name's room). Default 0.84. */
15
+ floor?: number;
16
+ /** How much the paint glows; 0 for none. Default 0.55. */
17
+ glow?: number;
18
+ /** How rough the sprayed edge is; 0 for a clean edge. Default 0.6. */
19
+ spray?: number;
20
+ /** Grain over the ground and the paint; 0 for none. Default 0.12. */
21
+ grain?: number;
22
+ /** Seconds the finished drips hold before they fade and run again. Default 2.6. */
23
+ hold?: number;
24
+ /** Which drips (where, how big, when), so two cards differ. Default 0. */
25
+ seed?: number;
26
+ /** Where the drips hang (from `dripAnchors` on the mark's coverage), when a still was made from them: the canvas then runs the same drips. Read off the image when not given. */
27
+ anchors?: DripAnchor[];
28
+ /** Plays the clock faster or slower; 0 for one still frame (every drip at full length). Default 1. */
29
+ speed?: number;
30
+ }
31
+
32
+ /** The settings' defaults. */
33
+ export declare const DRIP_DEFAULTS: Required<Omit<PaintDripConfig, 'src'>>;
34
+
35
+ /** The body's widths are kept this far apart, heights. */
36
+ export declare const DEPTH_STEP: number;
37
+
38
+ /** One drip from pooling to drying: its head's depth, bead radius and speed at each step (1/60 s), and its body's width along its path. */
39
+ export interface DripRun {
40
+ t0: number;
41
+ duration: number;
42
+ y: Float32Array;
43
+ r: Float32Array;
44
+ v: Float32Array;
45
+ w: Float32Array;
46
+ length: number;
47
+ }
48
+
49
+ /** Runs one drip: `paint` is its volume (about 0.5–1.6), `room` how far it can fall before it meets something (heights). */
50
+ export declare function dripRun(drip: { paint: number; room: number; t0?: number }): DripRun;
51
+
52
+ /** A drip's head at a time, seconds into the loop. */
53
+ export declare function dripAt(run: DripRun, t: number): { y: number; r: number; v: number; started: boolean; done: boolean };
54
+
55
+ /** A place paint drips from, in shares of the mark's box. */
56
+ export interface DripAnchor {
57
+ x: number;
58
+ y: number;
59
+ room: number;
60
+ open: boolean;
61
+ }
62
+
63
+ /** The places paint drips from, read off the mark's coverage (0–1, row by row): its lower edges, lower and gentler likelier. */
64
+ export declare function dripAnchors(alpha: ArrayLike<number>, w: number, h: number, count: number, seed: number): DripAnchor[];
65
+
66
+ /** Every drip's run for a mark, and the loop around them. */
67
+ export interface DripPlan {
68
+ drips: { x: number; y: number; room: number; run: DripRun }[];
69
+ cycle: number;
70
+ settled: number;
71
+ }
72
+
73
+ /** Plans the drips: where each hangs (the box in heights), how much paint it carries, when it starts. */
74
+ export declare function dripPlan(anchors: DripAnchor[], at: { left: number; top: number; size: number }, config: PaintDripConfig): DripPlan;
75
+
76
+ /** Seconds into the loop, and the drips' opacity (they fade at its end). */
77
+ export declare function dripClock(plan: DripPlan, time: number): { t: number; fade: number };
78
+
79
+ /** A drip's outline at a time, SVG path data in heights ('' before it starts): what the canvas fills and a still draws. */
80
+ export declare function dripPath(d: DripPlan['drips'][number], t: number): string;
81
+
82
+ /** Every drip at its full length (the loop's resting frame), one SVG path in heights. */
83
+ export declare function dripsAtRest(plan: DripPlan): string;
84
+
85
+ /** A CSS `background` that stands in for the ground before the canvas draws. */
86
+ export declare function dripStill(config: PaintDripConfig): string;
87
+
88
+ /** Starts the paint running on an element (its first canvas, or one in its place). Returns a function that stops it. */
89
+ export declare function paintDrip(el: HTMLElement, config: PaintDripConfig): () => void;