@arraypress/effects-astro 0.11.0 → 0.12.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,91 @@
1
+ import type { PaletteName } from './palettes.js';
2
+
3
+ /** The gradient's shapes. */
4
+ export type GradientShape = 'wave' | 'band' | 'swirl' | 'pinwheel' | 'steps';
5
+
6
+ export interface DitherGradientConfig {
7
+ /** Two CSS hex colours: the dim one where the tone is low and the bright one where it is full. Default a plum and a hot pink. */
8
+ colors?: string[];
9
+ /** A shared palette by name (`PALETTES`, any case), when there are no `colors`: its first and last colours. */
10
+ palette?: PaletteName | (string & {});
11
+ /** A CSS hex colour to fill behind the dots; none leaves the canvas clear there. */
12
+ background?: string;
13
+ /** The gradient's shape. Default 'wave'. */
14
+ shape?: GradientShape;
15
+ /** Square dots an ordered dither thins out, or round dots that shrink. Default 'bayer'. */
16
+ mode?: 'bayer' | 'halftone';
17
+ /** The dots' grid, in CSS px. Default 4. */
18
+ dot?: number;
19
+ /** Share of its cell a full dot covers (below 1 leaves a gap between dots). Default 1. */
20
+ fill?: number;
21
+ /** How soft the gradient is: the edge's width in widths (wave, band, steps), a share of a turn (swirl, pinwheel). Default 0.35. */
22
+ soft?: number;
23
+ /** Which way the wave, band and steps rise from, degrees: 0 from the bottom, 90 from the left. Default 0. */
24
+ angle?: number;
25
+ /** Where the wave's horizon, the band's middle and the steps' line sit, widths below the centre (along `angle`). Default 0.12. */
26
+ level?: number;
27
+ /** The swirl's and pinwheel's arms. Default 3. */
28
+ arms?: number;
29
+ /** How tightly the swirl winds and the pinwheel bends. Default 2. */
30
+ twist?: number;
31
+ /** How fast it moves, cycles a second. Default 0.03. */
32
+ rate?: number;
33
+ /** The steps' block, in dots. Default 6. */
34
+ block?: number;
35
+ /** Colour bands from dim to bright; 0 blends smoothly. Default 0. */
36
+ steps?: number;
37
+ /** The swirl's and pinwheel's centre, and the wave's and band's pivot, 0–1 from the top left. Default [0.5, 0.5]. */
38
+ centre?: [number, number];
39
+ /** Where the shapes' noise starts, so two cards differ. Default [0, 0]. */
40
+ offset?: [number, number];
41
+ /** Plays the clock faster or slower; 0 for one still frame. Default 1. */
42
+ speed?: number;
43
+ /** An area kept empty: centre (0–1 from the top left), radius (share of the height), depth (0–1). Its opening is squared. */
44
+ quiet?: { x?: number; y?: number; radius?: number; depth?: number } | null;
45
+ }
46
+
47
+ /** The shapes, in the order the shader numbers them. */
48
+ export declare const GRADIENT_SHAPES: readonly ['wave', 'band', 'swirl', 'pinwheel', 'steps'];
49
+
50
+ /** The settings' defaults, shared by the shader and the JS twin. */
51
+ export declare const GRADIENT_DEFAULTS: {
52
+ shape: GradientShape;
53
+ mode: 'bayer' | 'halftone';
54
+ dot: number;
55
+ fill: number;
56
+ soft: number;
57
+ angle: number;
58
+ level: number;
59
+ arms: number;
60
+ twist: number;
61
+ rate: number;
62
+ block: number;
63
+ steps: number;
64
+ centre: [number, number];
65
+ };
66
+
67
+ /** The settings filled with the defaults, as the shader takes them. */
68
+ export type GradientSettings = Required<Omit<DitherGradientConfig, 'colors' | 'palette' | 'background' | 'quiet'>> & {
69
+ shapeIndex: number;
70
+ modeIndex: number;
71
+ rad: number;
72
+ blockW: number;
73
+ };
74
+
75
+ /** The settings as the shader takes them, for a target `cols` dots wide (the steps' block is in dots). */
76
+ export declare function gradientSettings(config: DitherGradientConfig, cols: number): GradientSettings;
77
+
78
+ /** The tone 0–1 at a point (widths from the top left; `H` the height in widths), before the quiet area. */
79
+ export declare function gradientTone(s: GradientSettings, x: number, y: number, H: number, time?: number): number;
80
+
81
+ /** One frame dot for dot on a target exactly `cols` by `rows` dots: each dot's tone after the quiet area, and whether a bayer dot is lit. */
82
+ export declare function gradientDots(config: DitherGradientConfig, cols: number, rows: number, time?: number): { tone: number; lit: boolean }[][];
83
+
84
+ /** The two colours as the shader takes them: the dim one and the bright one. */
85
+ export declare function gradientColors(config: DitherGradientConfig): [string, string];
86
+
87
+ /** A CSS `background` that stands in for the gradient before the shader starts and without WebGL. */
88
+ export declare function gradientStill(config: DitherGradientConfig): string;
89
+
90
+ /** Starts the gradient on an element (its first canvas). Returns a function that stops it. */
91
+ export declare function ditherGradient(el: HTMLElement, config: DitherGradientConfig): () => void;
@@ -0,0 +1,410 @@
1
+ /**
2
+ * @module @arraypress/effects-astro/dither-gradient
3
+ *
4
+ * A soft colour gradient drawn only in dots: the tone of a slow, smooth
5
+ * shape (a wavy horizon, a glowing band, a swirl, a pinwheel, or stepped
6
+ * columns falling) decides at each dot of a fixed grid whether it shows
7
+ * (`mode: 'bayer'`, an 8×8 ordered dither: square dots that thin out as the
8
+ * tone falls) or how big it is (`mode: 'halftone'`: round dots that shrink),
9
+ * its colour blended from a dim one to a bright one in Oklab. The dots keep
10
+ * their size in CSS px; the shapes are measured in widths, so a 330 px card
11
+ * and a 1280 px hero show the same picture.
12
+ *
13
+ * Every clock is in seconds and nothing is kept between frames: each shape
14
+ * is a function of where and when, here in GLSL and in plain JavaScript
15
+ * (`gradientTone`, `gradientDots`) alike, so a still and a test see what the
16
+ * shader draws.
17
+ *
18
+ * Clear where there are no dots (or the `background` colour), so it lays
19
+ * over any ground. A `quiet` area empties it behind copy. Without WebGL
20
+ * nothing is drawn; with prefers-reduced-motion it is one still frame.
21
+ */
22
+
23
+ import { createStage } from './stage.js';
24
+ import { GLSL_GRADIENT_NOISE, GLSL_HASH33, gnoise, hash33 } from './hash-noise.js';
25
+ import { GLSL_BAYER, bayer } from './bayer.js';
26
+ import { GLSL_OKLAB, parseColor, toOklab, mixOklab, toHex } from './color.js';
27
+ import { GLSL_QUIET, quietUniform } from './glsl.js';
28
+ import { watchColors } from './mount.js';
29
+ import { pickColors } from './palettes.js';
30
+
31
+ /**
32
+ * @typedef {'wave' | 'band' | 'swirl' | 'pinwheel' | 'steps'} GradientShape
33
+ *
34
+ * @typedef {object} DitherGradientConfig
35
+ * @property {string[]} [colors] Two CSS hex colours: the dim one where the tone is low and the bright one where it is full. Default a plum and a hot pink.
36
+ * @property {string} [palette] A shared palette by name (PALETTES; any case), when there are no `colors`: its first and last colours.
37
+ * @property {string} [background] A CSS hex colour to fill behind the dots; none leaves the canvas clear there.
38
+ * @property {GradientShape} [shape='wave'] The gradient's shape.
39
+ * @property {'bayer' | 'halftone'} [mode='bayer'] Square dots an ordered dither thins out, or round dots that shrink.
40
+ * @property {number} [dot=4] The dots' grid, in CSS px.
41
+ * @property {number} [fill=1] Share of its cell a full dot covers (below 1 leaves a gap between dots).
42
+ * @property {number} [soft=0.35] How soft the gradient is: the edge's width, in widths for the wave, band and steps, a share of a turn for the swirl and pinwheel.
43
+ * @property {number} [angle=0] Which way the wave, band and steps rise from, degrees: 0 from the bottom, 90 from the left.
44
+ * @property {number} [level=0.12] Where the wave's horizon, the band's middle and the steps' line sit, widths below the centre (along `angle`).
45
+ * @property {number} [arms=3] The swirl's and pinwheel's arms.
46
+ * @property {number} [twist=2] How tightly the swirl winds (per e-fold of radius) and the pinwheel bends (turns per width).
47
+ * @property {number} [rate=0.03] How fast it moves, cycles a second.
48
+ * @property {number} [block=6] The steps' block, in dots.
49
+ * @property {number} [steps=0] Colour bands from dim to bright; 0 blends smoothly.
50
+ * @property {[number, number]} [centre=[0.5, 0.5]] The swirl's and pinwheel's centre, and the wave's and band's pivot, 0–1 from the top left.
51
+ * @property {[number, number]} [offset=[0, 0]] Where the shapes' noise starts, so two cards differ.
52
+ * @property {number} [speed=1] Plays the clock faster or slower; 0 for one still frame.
53
+ * @property {{ x?: number, y?: number, radius?: number, depth?: number } | null} [quiet=null]
54
+ * An area kept empty: centre (0–1 from the top left), radius (share of the height), depth (0–1).
55
+ */
56
+
57
+ /** The shapes, in the order the shader numbers them. */
58
+ export const GRADIENT_SHAPES = /** @type {const} */ (['wave', 'band', 'swirl', 'pinwheel', 'steps']);
59
+
60
+ /** The settings' defaults, shared by the shader and the JS twin. */
61
+ export const GRADIENT_DEFAULTS = {
62
+ shape: /** @type {GradientShape} */ ('wave'),
63
+ mode: /** @type {'bayer' | 'halftone'} */ ('bayer'),
64
+ dot: 4,
65
+ fill: 1,
66
+ soft: 0.35,
67
+ angle: 0,
68
+ level: 0.12,
69
+ arms: 3,
70
+ twist: 2,
71
+ rate: 0.03,
72
+ block: 6,
73
+ steps: 0,
74
+ centre: /** @type {[number, number]} */ ([0.5, 0.5]),
75
+ };
76
+
77
+ /** The default colours: a plum and a hot pink. */
78
+ const PINK = ['#3a0f3a', '#ff1f8f'];
79
+
80
+ /**
81
+ * GLSL: `float gradientTone(vec2 c, float H, float t)`, the tone 0–1 at a
82
+ * point (in widths from the top left; H the height in widths) at a time:
83
+ * `gradientTone` below is the same in JavaScript.
84
+ */
85
+ const GLSL_TONE = `
86
+ uniform float uShape;
87
+ uniform float uSoft;
88
+ uniform float uAngle;
89
+ uniform float uLevel;
90
+ uniform float uArms;
91
+ uniform float uTwist;
92
+ uniform float uRate;
93
+ uniform float uBlock;
94
+ uniform vec2 uCentre;
95
+ uniform vec2 uOffset;
96
+ float gradientTone(vec2 c, float H, float t) {
97
+ vec2 p = c - vec2(uCentre.x, uCentre.y * H);
98
+ float s = sin(uAngle), k = cos(uAngle);
99
+ float u = p.x * k + p.y * s;
100
+ float v = p.y * k - p.x * s;
101
+ float ph = t * uRate;
102
+ if (uShape < 0.5) {
103
+ float h = uLevel + 0.07 * sin(6.2831853 * (u * 1.1 + ph)) + 0.22 * (gnoise(vec2(u * 2.2 + uOffset.x, ph * 0.8 + uOffset.y)) - 0.5);
104
+ return smoothstep(-uSoft * 0.5, uSoft * 0.5, v - h);
105
+ }
106
+ if (uShape < 1.5) {
107
+ float d = v - uLevel - 0.22 * sin(6.2831853 * ph) - 0.18 * (gnoise(vec2(u * 1.6 + uOffset.x, ph + uOffset.y)) - 0.5);
108
+ float w = max(uSoft * 0.5, 0.02);
109
+ return exp(-(d * d) / (w * w));
110
+ }
111
+ float r = length(p);
112
+ float a = atan(p.y, p.x);
113
+ if (uShape < 3.5) {
114
+ float wind = uShape < 2.5 ? log(max(r, 0.001)) * uTwist : r * uTwist;
115
+ float wave = 0.5 + 0.5 * cos(6.2831853 * (a / 6.2831853 * uArms + wind - ph));
116
+ float e = clamp(uSoft, 0.02, 1.0) * 0.5;
117
+ return smoothstep(0.6 - e, 0.6 + e, wave) * (0.5 + 0.5 * smoothstep(0.15, 0.8, r)) * smoothstep(0.08, 0.42, r);
118
+ }
119
+ float bw = uBlock;
120
+ float col = floor(u / bw);
121
+ vec3 hc = hash33(vec3(col, uOffset.x, uOffset.y));
122
+ float line = uLevel + (hc.x - 0.5) * 0.16 + 0.06 * sin(6.2831853 * (ph + hc.y));
123
+ float y = floor(v / bw) * bw;
124
+ return clamp((y - line) / max(uSoft * 0.6, 0.02), 0.0, 1.0);
125
+ }
126
+ `;
127
+
128
+ const FRAG = `
129
+ precision highp float;
130
+ uniform vec2 uRes;
131
+ uniform vec2 uSize;
132
+ uniform float uPitch;
133
+ uniform float uTime;
134
+ uniform float uMode;
135
+ uniform float uFill;
136
+ uniform float uSteps;
137
+ uniform vec3 uLow;
138
+ uniform vec3 uHigh;
139
+ uniform vec4 uBg;
140
+ ${GLSL_OKLAB}
141
+ ${GLSL_QUIET}
142
+ ${GLSL_HASH33}
143
+ ${GLSL_GRADIENT_NOISE}
144
+ ${GLSL_BAYER}
145
+ ${GLSL_TONE}
146
+
147
+ void main() {
148
+ // Canvas pixels from the top left, the dot under them, and where in it (−0.5 to 0.5).
149
+ vec2 px = vec2(gl_FragCoord.x, uRes.y - gl_FragCoord.y);
150
+ vec2 cell = floor(px / uPitch);
151
+ vec2 local = px / uPitch - cell - 0.5;
152
+ vec2 c = (cell + 0.5) / uSize.x;
153
+ float H = uSize.y / uSize.x;
154
+ float tone = clamp(gradientTone(c, H, uTime), 0.0, 1.0);
155
+
156
+ vec2 q = vec2(c.x - 0.5, (0.5 * uSize.y - (cell.y + 0.5)) / uSize.x) * uSize.x / uSize.y;
157
+ // squared, so a smooth tone clears well inside the radius (a ramp alone leaves half-tone dots behind copy)
158
+ float open = mix(1.0 - uQuiet.w, 1.0, quietOpen(q));
159
+ tone *= open * open;
160
+
161
+ float lit;
162
+ if (uMode < 0.5) {
163
+ float inside = step(max(abs(local.x), abs(local.y)), uFill * 0.5);
164
+ lit = step(bayer8(cell), tone - 0.5 / 64.0) * inside;
165
+ } else {
166
+ float aa = 0.75 / uPitch;
167
+ float r = 0.7071 * sqrt(tone) * uFill;
168
+ lit = (1.0 - smoothstep(r - aa, r + aa, length(local))) * step(0.004, tone);
169
+ }
170
+
171
+ float tq = uSteps > 0.5 ? floor(tone * uSteps + 0.5) / uSteps : tone;
172
+ vec3 col = fromOklab(mix(uLow, uHigh, tq));
173
+ gl_FragColor = vec4(col * lit + uBg.rgb * uBg.a * (1.0 - lit), lit + uBg.a * (1.0 - lit));
174
+ }
175
+ `;
176
+
177
+ /**
178
+ * Hermite smoothing between two edges (GLSL's `smoothstep`).
179
+ *
180
+ * @param {number} e0 Where it starts rising.
181
+ * @param {number} e1 Where it reaches 1.
182
+ * @param {number} x The value.
183
+ * @returns {number} 0–1.
184
+ */
185
+ const smooth = (e0, e1, x) => {
186
+ const t = Math.min(1, Math.max(0, (x - e0) / (e1 - e0)));
187
+ return t * t * (3 - 2 * t);
188
+ };
189
+
190
+ /** A clamp to 0–1. */
191
+ const unit = (/** @type {number} */ n) => Math.min(1, Math.max(0, n));
192
+
193
+ /**
194
+ * The settings, filled with the defaults, as the shader takes them: the
195
+ * shape's number, the angle in radians and the block in widths.
196
+ *
197
+ * @param {DitherGradientConfig} config The settings.
198
+ * @param {number} cols The target's width in dots (the steps' block is in dots).
199
+ * @returns {Required<Omit<DitherGradientConfig, 'colors' | 'palette' | 'background' | 'quiet' | 'shape' | 'mode'>> & { shapeIndex: number, modeIndex: number, rad: number, blockW: number }} The settings.
200
+ */
201
+ export function gradientSettings(config, cols) {
202
+ const o = { ...GRADIENT_DEFAULTS, offset: /** @type {[number, number]} */ ([0, 0]), speed: 1, ...config };
203
+ const shapeIndex = Math.max(0, GRADIENT_SHAPES.indexOf(o.shape));
204
+ return {
205
+ ...o,
206
+ shapeIndex,
207
+ modeIndex: o.mode === 'halftone' ? 1 : 0,
208
+ rad: (o.angle * Math.PI) / 180,
209
+ blockW: Math.max(1, o.block) / Math.max(1, cols),
210
+ };
211
+ }
212
+
213
+ /**
214
+ * The tone at a point (the shader's `gradientTone`), before the quiet area.
215
+ *
216
+ * @param {ReturnType<typeof gradientSettings>} s The settings, as `gradientSettings` gives them.
217
+ * @param {number} x Widths from the left.
218
+ * @param {number} y Widths from the top.
219
+ * @param {number} H The height in widths.
220
+ * @param {number} [time=0] Seconds (already at its speed).
221
+ * @returns {number} 0–1.
222
+ */
223
+ export function gradientTone(s, x, y, H, time = 0) {
224
+ const px = x - s.centre[0];
225
+ const py = y - s.centre[1] * H;
226
+ const sn = Math.sin(s.rad);
227
+ const k = Math.cos(s.rad);
228
+ const u = px * k + py * sn;
229
+ const v = py * k - px * sn;
230
+ const ph = time * s.rate;
231
+ const [ox, oy] = s.offset;
232
+ if (s.shapeIndex === 0) {
233
+ const h = s.level + 0.07 * Math.sin(2 * Math.PI * (u * 1.1 + ph)) + 0.22 * (gnoise(u * 2.2 + ox, ph * 0.8 + oy) - 0.5);
234
+ return smooth(-s.soft * 0.5, s.soft * 0.5, v - h);
235
+ }
236
+ if (s.shapeIndex === 1) {
237
+ const d = v - s.level - 0.22 * Math.sin(2 * Math.PI * ph) - 0.18 * (gnoise(u * 1.6 + ox, ph + oy) - 0.5);
238
+ const w = Math.max(s.soft * 0.5, 0.02);
239
+ return Math.exp(-(d * d) / (w * w));
240
+ }
241
+ const r = Math.hypot(px, py);
242
+ const a = Math.atan2(py, px);
243
+ if (s.shapeIndex <= 3) {
244
+ const wind = s.shapeIndex === 2 ? Math.log(Math.max(r, 0.001)) * s.twist : r * s.twist;
245
+ const wave = 0.5 + 0.5 * Math.cos(2 * Math.PI * ((a / (2 * Math.PI)) * s.arms + wind - ph));
246
+ const e = Math.min(1, Math.max(0.02, s.soft)) * 0.5;
247
+ return smooth(0.6 - e, 0.6 + e, wave) * (0.5 + 0.5 * smooth(0.15, 0.8, r)) * smooth(0.08, 0.42, r);
248
+ }
249
+ const col = Math.floor(u / s.blockW);
250
+ const hc = hash33(col, ox, oy);
251
+ const line = s.level + (hc[0] - 0.5) * 0.16 + 0.06 * Math.sin(2 * Math.PI * (ph + hc[1]));
252
+ const yq = Math.floor(v / s.blockW) * s.blockW;
253
+ return unit((yq - line) / Math.max(s.soft * 0.6, 0.02));
254
+ }
255
+
256
+ /**
257
+ * One frame dot for dot, as the shader draws it on a target exactly `cols`
258
+ * by `rows` dots: each dot's tone after the quiet area (0 where none
259
+ * shows), and whether a bayer dot is lit there.
260
+ *
261
+ * @param {DitherGradientConfig} config The settings (the same as the shader's).
262
+ * @param {number} cols Dots across.
263
+ * @param {number} rows Dots down.
264
+ * @param {number} [time=0] Seconds, as the shader's clock (already at its speed).
265
+ * @returns {{ tone: number, lit: boolean }[][]} Each row's dots.
266
+ */
267
+ export function gradientDots(config, cols, rows, time = 0) {
268
+ const s = gradientSettings(config, cols);
269
+ const H = rows / cols;
270
+ const [qx, qy, radius, depth] = quietUniform(config.quiet, cols / rows);
271
+ return Array.from({ length: rows }, (_, r) =>
272
+ Array.from({ length: cols }, (_, k) => {
273
+ let tone = unit(gradientTone(s, (k + 0.5) / cols, (r + 0.5) / cols, H, time));
274
+ if (radius > 0) {
275
+ const qd = Math.hypot(((k + 0.5) / cols - 0.5) * (cols / rows) - qx, (0.5 * rows - (r + 0.5)) / rows - qy);
276
+ const open = 1 - depth + depth * smooth(radius * 0.06, radius, qd);
277
+ tone *= open * open;
278
+ }
279
+ return { tone, lit: tone - 0.5 / 64 > bayer(k, r) };
280
+ }),
281
+ );
282
+ }
283
+
284
+ /**
285
+ * The two colours as the shader takes them.
286
+ *
287
+ * @param {DitherGradientConfig} config The settings.
288
+ * @returns {[string, string]} The dim colour and the bright one.
289
+ */
290
+ export function gradientColors(config) {
291
+ const colors = pickColors(config, PINK);
292
+ return [colors[0], colors[colors.length - 1]];
293
+ }
294
+
295
+ /**
296
+ * The shape as a CSS gradient layer (under the dot screen of the still).
297
+ *
298
+ * @param {DitherGradientConfig} config The settings.
299
+ * @param {string} low The dim colour.
300
+ * @param {string} mid Halfway, in Oklab.
301
+ * @param {string} high The bright colour.
302
+ * @returns {string} One CSS background layer.
303
+ */
304
+ function shapeLayer(config, low, mid, high) {
305
+ const o = { ...GRADIENT_DEFAULTS, ...config };
306
+ const [cx, cy] = o.centre;
307
+ const at = `${Math.round(cx * 100)}% ${Math.round(cy * 100)}%`;
308
+ // CSS angles point where a gradient runs to: 0deg starts at the bottom, as `angle` 0 rises from it
309
+ const to = Math.round(o.angle);
310
+ if (o.shape === 'band') return `linear-gradient(${to}deg, transparent 22%, ${low} 36%, ${high} 50%, ${low} 64%, transparent 78%)`;
311
+ if (o.shape === 'swirl' || o.shape === 'pinwheel') {
312
+ const arm = 360 / Math.max(1, Math.round(o.arms));
313
+ return `repeating-conic-gradient(from 0deg at ${at}, ${high} 0deg, ${low} ${(arm * 0.3).toFixed(1)}deg, transparent ${(arm * 0.5).toFixed(1)}deg, transparent ${arm.toFixed(1)}deg)`;
314
+ }
315
+ return `linear-gradient(${to}deg, ${high} 0%, ${mid} 22%, ${low} 36%, transparent 52%)`;
316
+ }
317
+
318
+ /**
319
+ * A CSS `background` that stands in for the gradient before the shader
320
+ * starts and without WebGL: the shape as a CSS gradient seen through a
321
+ * screen of the ground (a dot checker for bayer, round holes for
322
+ * halftone), and the quiet area left to the ground.
323
+ *
324
+ * @param {DitherGradientConfig} config The settings (`colors`/`palette`, `background`, `shape`, `mode`, `dot`, `angle`, `arms`, `centre`, `quiet`).
325
+ * @returns {string} The CSS background.
326
+ */
327
+ export function gradientStill(config) {
328
+ const [low, high] = gradientColors(config).map(parseColor);
329
+ const ground = config.background ?? '#000000';
330
+ const dot = Math.max(1, config.dot ?? GRADIENT_DEFAULTS.dot);
331
+ const mid = toHex(mixOklab(low, high, 0.5));
332
+ const pc = (/** @type {number} */ n) => `${Math.round(n * 100)}%`;
333
+ const quiet = config.quiet;
334
+ const r = pc((quiet?.radius ?? 0.8) * 0.55);
335
+ const screen =
336
+ config.mode === 'halftone'
337
+ ? `radial-gradient(circle, transparent 34%, ${ground} 38%) 0 0 / ${dot}px ${dot}px`
338
+ : `repeating-conic-gradient(${ground} 0 25%, transparent 0 50%) 0 0 / ${dot * 2}px ${dot * 2}px`;
339
+ return [
340
+ quiet ? `radial-gradient(${r} ${r} at ${pc(quiet.x ?? 0.5)} ${pc(quiet.y ?? 0.5)}, ${ground} 55%, transparent 100%)` : '',
341
+ screen,
342
+ shapeLayer(config, toHex(low), mid, toHex(high)),
343
+ ground,
344
+ ]
345
+ .filter(Boolean)
346
+ .join(', ');
347
+ }
348
+
349
+ /**
350
+ * Starts the gradient on an element: a canvas inside it (its first), at
351
+ * the stage's capped pixel ratio, the dots worked out a pixel at a time.
352
+ *
353
+ * @param {HTMLElement} el The element.
354
+ * @param {DitherGradientConfig} config The settings.
355
+ * @returns {() => void} Stops it.
356
+ */
357
+ export function ditherGradient(el, config) {
358
+ const speed = config.speed ?? 1;
359
+ const lab = (/** @type {string} */ c) => toOklab(parseColor(c));
360
+ let [low, high] = gradientColors(config).map(lab);
361
+ const bg = config.background ? [...parseColor(config.background), 1] : [0, 0, 0, 0];
362
+ const dot = Math.max(1, config.dot ?? GRADIENT_DEFAULTS.dot);
363
+ const start = performance.now();
364
+
365
+ const { stage, stop } = createStage(el, {
366
+ fragment: FRAG,
367
+ still: speed <= 0,
368
+ // The dots are drawn at the canvas's own pixels: a lower resolution would blur them.
369
+ adaptive: false,
370
+ setup({ gl, uniform }) {
371
+ gl.uniform4f(uniform('uBg'), bg[0], bg[1], bg[2], bg[3]);
372
+ },
373
+ resize({ gl, uniform, ratio }) {
374
+ const cols = Math.max(1, el.clientWidth / dot);
375
+ const rows = Math.max(1, el.clientHeight / dot);
376
+ const s = gradientSettings(config, cols);
377
+ gl.uniform2f(uniform('uSize'), cols, rows);
378
+ gl.uniform1f(uniform('uPitch'), dot * ratio);
379
+ gl.uniform1f(uniform('uShape'), s.shapeIndex);
380
+ gl.uniform1f(uniform('uMode'), s.modeIndex);
381
+ gl.uniform1f(uniform('uFill'), s.fill);
382
+ gl.uniform1f(uniform('uSteps'), s.steps);
383
+ gl.uniform1f(uniform('uSoft'), s.soft);
384
+ gl.uniform1f(uniform('uAngle'), s.rad);
385
+ gl.uniform1f(uniform('uLevel'), s.level);
386
+ gl.uniform1f(uniform('uArms'), s.arms);
387
+ gl.uniform1f(uniform('uTwist'), s.twist);
388
+ gl.uniform1f(uniform('uRate'), s.rate);
389
+ gl.uniform1f(uniform('uBlock'), s.blockW);
390
+ gl.uniform2f(uniform('uCentre'), s.centre[0], s.centre[1]);
391
+ gl.uniform2f(uniform('uOffset'), s.offset[0], s.offset[1]);
392
+ gl.uniform4f(uniform('uQuiet'), ...quietUniform(config.quiet, cols / rows));
393
+ },
394
+ uniforms({ gl, uniform }, now) {
395
+ gl.uniform1f(uniform('uTime'), ((now - start) / 1000) * Math.max(0, speed));
396
+ gl.uniform3f(uniform('uLow'), low[0], low[1], low[2]);
397
+ gl.uniform3f(uniform('uHigh'), high[0], high[1], high[2]);
398
+ },
399
+ });
400
+ if (!stage) return stop;
401
+
402
+ const unwatch = watchColors(el, (next) => {
403
+ [low, high] = gradientColors({ colors: next.colors }).map(lab);
404
+ if (stage.still) stage.redraw();
405
+ });
406
+ return () => {
407
+ stop();
408
+ unwatch();
409
+ };
410
+ }
@@ -0,0 +1,79 @@
1
+ import type { PaletteName } from './palettes.js';
2
+
3
+ /** The light behind the glass. */
4
+ export type GlowShape = 'ring' | 'orb' | 'rise';
5
+
6
+ export interface FlutedGlowConfig {
7
+ /** Three CSS hex colours, the light from its edge in: deep, mid and hot. Default a violet ring's. */
8
+ colors?: string[];
9
+ /** A shared palette by name (`PALETTES`, any case), when there are no `colors`. */
10
+ palette?: PaletteName | (string & {});
11
+ /** The ground, painted everywhere. Default '#08070c'. */
12
+ background?: string;
13
+ /** The light behind the glass. Default 'ring'. */
14
+ shape?: GlowShape;
15
+ /** Flutes across the width. Default 14. */
16
+ flutes?: number;
17
+ /** How much of what is behind a flute it shows across its width (lower stretches more). Default 0.35. */
18
+ squeeze?: number;
19
+ /** The ring's radius or the orb's, a share of the height; how high the rise reaches. Default 0.3. */
20
+ size?: number;
21
+ /** The ring's soft width, a share of the height. Default 0.09. */
22
+ thickness?: number;
23
+ /** How bright the light is. Default 1. */
24
+ glow?: number;
25
+ /** How far the light swells and shrinks, a share of its size. Default 0.06. */
26
+ breathe?: number;
27
+ /** How far its centre wanders, a share of the height. Default 0.04. */
28
+ drift?: number;
29
+ /** How fast it breathes and wanders, cycles a second. Default 0.05. */
30
+ rate?: number;
31
+ /** How strong the flutes' shadows and highlights are; 0 for none. Default 0.35. */
32
+ seams?: number;
33
+ /** Fine grain over all of it; 0 for none. Default 0.05. */
34
+ grain?: number;
35
+ /** The ring's or orb's centre, 0–1 from the top left. Default [0.5, 0.5]. */
36
+ centre?: [number, number];
37
+ /** Where its wandering starts, so two cards differ. Default 0. */
38
+ seed?: number;
39
+ /** Plays every clock faster or slower; 0 for one still frame. Default 1. */
40
+ speed?: number;
41
+ /** An area dimmed: centre (0–1 from the top left), radius (share of the height), depth (0–1). */
42
+ quiet?: { x?: number; y?: number; radius?: number; depth?: number } | null;
43
+ }
44
+
45
+ /** The shapes, in the order the shader numbers them. */
46
+ export declare const GLOW_SHAPES: readonly ['ring', 'orb', 'rise'];
47
+
48
+ /** The settings' defaults, shared by the shader and the JS twin. */
49
+ export declare const GLOW_DEFAULTS: {
50
+ background: string;
51
+ shape: GlowShape;
52
+ flutes: number;
53
+ squeeze: number;
54
+ size: number;
55
+ thickness: number;
56
+ glow: number;
57
+ breathe: number;
58
+ drift: number;
59
+ rate: number;
60
+ seams: number;
61
+ grain: number;
62
+ centre: [number, number];
63
+ seed: number;
64
+ };
65
+
66
+ /** How bright the light behind the glass is at a point (heights from the top left; `aspect` width over height), before the flutes and the quiet area. */
67
+ export declare function glowAt(config: FlutedGlowConfig, x: number, y: number, aspect: number, time?: number): number;
68
+
69
+ /** Where behind the glass a point looks: the share of the width it shows, and where in its flute it is (−1 to 1). */
70
+ export declare function fluteSample(fx: number, flutes: number, squeeze: number): { x: number; local: number };
71
+
72
+ /** The light's three colours as the shader takes them: deep, mid and hot. */
73
+ export declare function glowColors(config: FlutedGlowConfig): [string, string, string];
74
+
75
+ /** A CSS `background` that stands in for the light before the shader starts and without WebGL (`aspect`, width over height, default 0.8). */
76
+ export declare function glowStill(config: FlutedGlowConfig, aspect?: number): string;
77
+
78
+ /** Starts the light on an element (its first canvas). Returns a function that stops it. */
79
+ export declare function flutedGlow(el: HTMLElement, config: FlutedGlowConfig): () => void;