@arraypress/effects-astro 0.13.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,355 @@
1
+ /**
2
+ * @module @arraypress/effects-astro/fluted-bokeh
3
+ *
4
+ * Coloured lights out of focus, seen through reeded glass: soft discs of
5
+ * colour drift slowly behind a pane of upright flutes (`mode: 'reeds'`) or
6
+ * a wall of square glass blocks (`mode: 'blocks'`). Each flute shows a
7
+ * narrow slice of what is behind it stretched across its width, red, green
8
+ * and blue each squeezed by a little more or less, so every seam carries a
9
+ * thin rainbow; what is behind is smeared a little upright, as light is
10
+ * through reeds, and each flute has a faint highlight on one seam and a
11
+ * shadow on the other. A block bends what is behind it toward its own
12
+ * centre, both ways, between dark joints.
13
+ *
14
+ * A sibling of `<FlutedGlow>` (one ring, orb or rise behind upright flutes)
15
+ * and `<FlutedGlass>` (slanted flutes over pointer-led blooms): several
16
+ * lights, dispersion at the seams, glass blocks, and no pointer, made to
17
+ * sit behind copy.
18
+ *
19
+ * Every clock is in seconds and nothing is kept between frames: the lights
20
+ * and the glass's slicing are here in plain JavaScript too (`bokehLights`,
21
+ * `bokehAt`, `reedSample`), so a still and a test see what the shader draws.
22
+ *
23
+ * Opaque: it paints its `background` (default near-black) everywhere.
24
+ * Without WebGL nothing is drawn; with prefers-reduced-motion it is one
25
+ * still frame.
26
+ */
27
+
28
+ import { createStage } from './stage.js';
29
+ import { GLSL_HASH33, hash33 } from './hash-noise.js';
30
+ import { parseColor, toHex, mixOklab } from './color.js';
31
+ import { GLSL_QUIET, quietUniform } from './glsl.js';
32
+ import { watchColors } from './mount.js';
33
+ import { pickColors } from './palettes.js';
34
+
35
+ /**
36
+ * @typedef {'reeds' | 'blocks'} BokehGlass
37
+ *
38
+ * @typedef {object} FlutedBokehConfig
39
+ * @property {string[]} [colors] Two to four CSS hex colours for the lights. Default coral, amber and ice blue.
40
+ * @property {string} [palette] A shared palette by name (PALETTES; any case), when there are no `colors`.
41
+ * @property {string} [background='#050608'] The ground, painted everywhere.
42
+ * @property {BokehGlass} [mode='reeds'] Upright flutes, or a wall of square glass blocks.
43
+ * @property {number} [flutes=28] Flutes across the width (blocks across, for `blocks`).
44
+ * @property {number} [squeeze=0.3] How much of what is behind a flute it shows across its width (lower stretches more).
45
+ * @property {number} [dispersion=0.35] How far red and blue part at the seams; 0 for none.
46
+ * @property {number} [streak=0.06] How far the light smears upright, a share of the height; 0 for none.
47
+ * @property {number} [lights=5] Lights behind the glass (1–8).
48
+ * @property {number} [size=0.22] The lights' radius, a share of the height.
49
+ * @property {number} [glow=1] How bright the lights are.
50
+ * @property {number} [drift=0.08] How far the lights wander, a share of the height.
51
+ * @property {number} [rate=0.04] How fast they wander, cycles a second.
52
+ * @property {number} [seams=0.3] How strong the seams' highlights and shadows (or the blocks' joints) are; 0 for none.
53
+ * @property {number} [grain=0.04] Fine grain over all of it; 0 for none.
54
+ * @property {number} [seed=0] Where the lights sit and start wandering, so two cards differ.
55
+ * @property {number} [speed=1] Plays every clock faster or slower; 0 for one still frame.
56
+ * @property {{ x?: number, y?: number, radius?: number, depth?: number } | null} [quiet=null]
57
+ * An area dimmed: centre (0–1 from the top left), radius (share of the height), depth (0–1).
58
+ */
59
+
60
+ /** The glass, in the order the shader numbers it. */
61
+ export const BOKEH_GLASS = /** @type {const} */ (['reeds', 'blocks']);
62
+
63
+ /** The most lights the shader draws. */
64
+ export const MAX_LIGHTS = 8;
65
+
66
+ /** The settings' defaults, shared by the shader and the JS twin. */
67
+ export const BOKEH_DEFAULTS = {
68
+ background: '#050608',
69
+ mode: /** @type {BokehGlass} */ ('reeds'),
70
+ flutes: 28,
71
+ squeeze: 0.3,
72
+ dispersion: 0.35,
73
+ streak: 0.06,
74
+ lights: 5,
75
+ size: 0.22,
76
+ glow: 1,
77
+ drift: 0.08,
78
+ rate: 0.04,
79
+ seams: 0.3,
80
+ grain: 0.04,
81
+ seed: 0,
82
+ };
83
+
84
+ /** The default colours: coral, amber and ice blue, after the owner's fluted-glass references. */
85
+ const STAGE = ['#ff4a2a', '#ffb347', '#4fc3ff'];
86
+
87
+ /**
88
+ * The settings, filled with the defaults, with the glass's number.
89
+ *
90
+ * @param {FlutedBokehConfig} config The settings.
91
+ * @returns {typeof BOKEH_DEFAULTS & { modeIndex: number, speed: number, count: number }} The settings.
92
+ */
93
+ function settings(config) {
94
+ const o = { ...BOKEH_DEFAULTS, speed: 1, ...config };
95
+ return { ...o, modeIndex: Math.max(0, BOKEH_GLASS.indexOf(o.mode)), count: Math.max(1, Math.min(MAX_LIGHTS, Math.round(o.lights))) };
96
+ }
97
+
98
+ /**
99
+ * The lights: where each sits (shares of the width and height), how big
100
+ * it is (a share of `size`), its colour (an index into the colours) and
101
+ * its own phase, all from the seed.
102
+ *
103
+ * @param {FlutedBokehConfig} config The settings.
104
+ * @returns {{ x: number, y: number, r: number, color: number, phase: number }[]} The lights.
105
+ */
106
+ export function bokehLights(config) {
107
+ const o = settings(config);
108
+ const n = pickColors(config, STAGE).length;
109
+ return Array.from({ length: o.count }, (_, i) => {
110
+ const h = hash33(i * 7.13 + o.seed, o.seed * 3.1 + 1.7, i * 1.31);
111
+ const g = hash33(i * 2.71 + 4.2, o.seed + 9.3, i * 5.9 + o.seed);
112
+ return { x: 0.08 + 0.84 * h[0], y: 0.1 + 0.8 * h[1], r: 0.55 + 0.9 * h[2], color: i % n, phase: g[0] * 6.2831853 };
113
+ });
114
+ }
115
+
116
+ /**
117
+ * GLSL for the lights: `vec3 bokehAt(vec2 s, float t)`, the light behind
118
+ * the glass at a point (shares of the width and height), the same sum as
119
+ * `bokehAt` below.
120
+ */
121
+ const GLSL_LIGHTS = `
122
+ uniform vec4 uLights[${MAX_LIGHTS}];
123
+ uniform vec3 uLightCol[${MAX_LIGHTS}];
124
+ uniform float uCount;
125
+ uniform float uSize;
126
+ uniform float uGlow;
127
+ uniform float uDrift;
128
+ uniform float uRate;
129
+ uniform float uAspect;
130
+ vec3 bokehAt(vec2 s, float t) {
131
+ vec3 c = vec3(0.0);
132
+ for (int i = 0; i < ${MAX_LIGHTS}; i++) {
133
+ if (float(i) >= uCount) break;
134
+ vec4 l = uLights[i];
135
+ float ph = 6.2831853 * t * uRate + l.w;
136
+ vec2 at = l.xy + uDrift * vec2(sin(ph * 0.9) / uAspect, cos(ph * 0.71));
137
+ vec2 d = vec2((s.x - at.x) * uAspect, s.y - at.y);
138
+ float r = uSize * l.z;
139
+ c += uLightCol[i] * exp(-dot(d, d) / (r * r) * 1.4);
140
+ }
141
+ return c * uGlow;
142
+ }
143
+ `;
144
+
145
+ const FRAG = `
146
+ precision highp float;
147
+ uniform vec2 uRes;
148
+ uniform float uTime;
149
+ uniform float uMode;
150
+ uniform float uFlutes;
151
+ uniform float uSqueeze;
152
+ uniform float uDisp;
153
+ uniform float uStreak;
154
+ uniform float uSeams;
155
+ uniform float uGrain;
156
+ uniform vec3 uBg;
157
+ ${GLSL_QUIET}
158
+ ${GLSL_HASH33}
159
+ ${GLSL_LIGHTS}
160
+
161
+ // Where in its cell a share sits (−1 to 1) and the cell's centre, for a cell count across.
162
+ vec2 cellOf(float x, float n) {
163
+ float w = 1.0 / n;
164
+ float i = floor(x / w);
165
+ return vec2((x / w - i) * 2.0 - 1.0, (i + 0.5) * w);
166
+ }
167
+
168
+ vec3 seen(vec2 s, float t) {
169
+ // the light smeared upright a little: three taps
170
+ return (bokehAt(s, t) * 0.5 + bokehAt(s + vec2(0.0, uStreak), t) * 0.25 + bokehAt(s - vec2(0.0, uStreak), t) * 0.25);
171
+ }
172
+
173
+ void main() {
174
+ vec2 px = vec2(gl_FragCoord.x, uRes.y - gl_FragCoord.y);
175
+ vec2 s = px / uRes;
176
+ vec2 cx = cellOf(s.x, uFlutes);
177
+ float hw = 0.5 / uFlutes;
178
+ vec3 col;
179
+ float seam;
180
+ if (uMode < 0.5) {
181
+ // each flute shows a squeezed slice about its centre; red and blue squeezed a little differently
182
+ float sr = cx.y + cx.x * hw * uSqueeze * (1.0 + uDisp);
183
+ float sg = cx.y + cx.x * hw * uSqueeze;
184
+ float sb = cx.y + cx.x * hw * uSqueeze * (1.0 - uDisp);
185
+ col = vec3(seen(vec2(sr, s.y), uTime).r, seen(vec2(sg, s.y), uTime).g, seen(vec2(sb, s.y), uTime).b);
186
+ seam = 1.0 - uSeams * 0.35 * (1.0 - cos(cx.x * 1.5707963));
187
+ seam += uSeams * 0.3 * smoothstep(-0.86, -1.0, cx.x);
188
+ seam -= uSeams * 0.35 * smoothstep(0.86, 1.0, cx.x);
189
+ } else {
190
+ // a glass block bends what is behind it toward its own centre, both ways, between dark joints
191
+ float rows = max(1.0, floor(uFlutes * uRes.y / uRes.x + 0.5));
192
+ vec2 cy = cellOf(s.y, rows);
193
+ float hy = 0.5 / rows;
194
+ vec2 k = vec2(cx.x, cy.x);
195
+ vec2 b = vec2(cx.y, cy.y) + k * vec2(hw, hy) * uSqueeze * 1.6;
196
+ vec2 off = k * vec2(hw, hy) * uSqueeze * uDisp * 0.8;
197
+ col = vec3(seen(b + off, uTime).r, seen(b, uTime).g, seen(b - off, uTime).b);
198
+ float edge = max(abs(k.x), abs(k.y));
199
+ seam = 1.0 - uSeams * 2.2 * smoothstep(0.82, 0.97, edge);
200
+ seam += uSeams * 0.35 * smoothstep(0.7, 0.9, -k.x - k.y) * (1.0 - smoothstep(0.9, 0.97, edge));
201
+ }
202
+ col = uBg + col * max(seam, 0.0);
203
+ vec2 q = vec2((s.x - 0.5) * uRes.x / uRes.y, 0.5 - s.y);
204
+ col = mix(uBg, col, mix(1.0 - uQuiet.w, 1.0, quietOpen(q)));
205
+ col += (hash33(vec3(px, floor(uTime * 24.0))).x - 0.5) * uGrain;
206
+ gl_FragColor = vec4(clamp(col, 0.0, 1.0), 1.0);
207
+ }
208
+ `;
209
+
210
+ /**
211
+ * The light behind the glass at a point (the shader's `bokehAt`), before
212
+ * the glass: red, green and blue, 0 and up.
213
+ *
214
+ * @param {FlutedBokehConfig} config The settings.
215
+ * @param {number} x A share of the width.
216
+ * @param {number} y A share of the height.
217
+ * @param {number} aspect Width over height.
218
+ * @param {number} [time=0] Seconds (already at its speed).
219
+ * @returns {[number, number, number]} The light.
220
+ */
221
+ export function bokehAt(config, x, y, aspect, time = 0) {
222
+ const o = settings(config);
223
+ const cols = bokehColors(config).map((c) => parseColor(c));
224
+ const c = [0, 0, 0];
225
+ for (const l of bokehLights(config)) {
226
+ const ph = 2 * Math.PI * time * o.rate + l.phase;
227
+ const ax = l.x + (o.drift * Math.sin(ph * 0.9)) / aspect;
228
+ const ay = l.y + o.drift * Math.cos(ph * 0.71);
229
+ const dx = (x - ax) * aspect;
230
+ const dy = y - ay;
231
+ const r = o.size * l.r;
232
+ const k = Math.exp(((-(dx * dx + dy * dy)) / (r * r)) * 1.4) * o.glow;
233
+ const col = cols[l.color];
234
+ for (let j = 0; j < 3; j++) c[j] += col[j] * k;
235
+ }
236
+ return /** @type {[number, number, number]} */ (c);
237
+ }
238
+
239
+ /**
240
+ * Where behind the reeds a point looks (the shader's slicing, the green
241
+ * channel): each flute shows a slice `squeeze` of its own width, stretched
242
+ * across it.
243
+ *
244
+ * @param {number} x The point, a share of the width (0–1).
245
+ * @param {number} flutes Flutes across the width.
246
+ * @param {number} squeeze The share of a flute's width it shows.
247
+ * @returns {{ x: number, local: number }} The share of the width it shows, and where in its flute it is (−1 to 1).
248
+ */
249
+ export function reedSample(x, flutes, squeeze) {
250
+ const w = 1 / flutes;
251
+ const i = Math.floor(x / w);
252
+ const local = (x / w - i) * 2 - 1;
253
+ return { x: (i + 0.5) * w + local * 0.5 * w * squeeze, local };
254
+ }
255
+
256
+ /**
257
+ * The lights' colours as the shader takes them: two to four.
258
+ *
259
+ * @param {FlutedBokehConfig} config The settings.
260
+ * @returns {string[]} The colours.
261
+ */
262
+ export function bokehColors(config) {
263
+ return pickColors(config, STAGE).slice(0, 4);
264
+ }
265
+
266
+ /**
267
+ * A CSS `background` that stands in for the lights before the shader
268
+ * starts and without WebGL: the lights as soft radial gradients, under
269
+ * upright stripes for the reeds or a grid for the blocks.
270
+ *
271
+ * @param {FlutedBokehConfig} config The settings (`colors`/`palette`, `background`, `mode`, `flutes`, `lights`, `size`, `seed`).
272
+ * @param {number} [aspect=0.8] The element's width over its height (a 4:5 card by default).
273
+ * @returns {string} The CSS background.
274
+ */
275
+ export function bokehStill(config, aspect = 0.8) {
276
+ const o = settings(config);
277
+ const cols = bokehColors(config);
278
+ const ground = toHex(parseColor(o.background));
279
+ const lights = bokehLights(config).map((l) => {
280
+ const c = toHex(mixOklab(parseColor(ground), parseColor(cols[l.color]), 0.85));
281
+ const rx = Math.round(((o.size * l.r) / aspect) * 100);
282
+ const ry = Math.round(o.size * l.r * 100);
283
+ return `radial-gradient(${rx}% ${ry}% at ${Math.round(l.x * 100)}% ${Math.round(l.y * 100)}%, ${c} 0%, transparent 100%)`;
284
+ });
285
+ const w = 100 / Math.max(1, o.flutes);
286
+ const reeds = `repeating-linear-gradient(90deg, rgba(255,255,255,0.07) 0, transparent ${(w * 0.15).toFixed(2)}%, transparent ${(w * 0.8).toFixed(2)}%, rgba(0,0,0,0.3) ${w.toFixed(2)}%)`;
287
+ const glass =
288
+ o.modeIndex === 1
289
+ ? [reeds, `repeating-linear-gradient(180deg, transparent 0, transparent ${(w * aspect * 0.9).toFixed(2)}%, rgba(0,0,0,0.45) ${(w * aspect).toFixed(2)}%)`]
290
+ : [reeds];
291
+ return [...glass, ...lights, ground].join(', ');
292
+ }
293
+
294
+ /**
295
+ * Starts the lights and the glass on an element: a canvas inside it (its
296
+ * first), at the stage's capped pixel ratio.
297
+ *
298
+ * @param {HTMLElement} el The element.
299
+ * @param {FlutedBokehConfig} config The settings.
300
+ * @returns {() => void} Stops it.
301
+ */
302
+ export function flutedBokeh(el, config) {
303
+ const o = settings(config);
304
+ const lights = bokehLights(config);
305
+ const rgb = (/** @type {string[]} */ cs) => lights.map((l) => parseColor(cs[l.color % cs.length]));
306
+ let colours = rgb(bokehColors(config));
307
+ const ground = parseColor(o.background);
308
+ const start = performance.now();
309
+ const pack = new Float32Array(MAX_LIGHTS * 4);
310
+ lights.forEach((l, i) => pack.set([l.x, l.y, l.r, l.phase], i * 4));
311
+
312
+ const { stage, stop } = createStage(el, {
313
+ fragment: FRAG,
314
+ alpha: false,
315
+ still: o.speed <= 0,
316
+ setup({ gl, uniform }) {
317
+ gl.uniform1f(uniform('uMode'), o.modeIndex);
318
+ gl.uniform1f(uniform('uFlutes'), Math.max(1, o.flutes));
319
+ gl.uniform1f(uniform('uSqueeze'), o.squeeze);
320
+ gl.uniform1f(uniform('uDisp'), o.dispersion);
321
+ gl.uniform1f(uniform('uStreak'), o.streak);
322
+ gl.uniform1f(uniform('uSeams'), o.seams);
323
+ gl.uniform1f(uniform('uGrain'), o.grain);
324
+ gl.uniform1f(uniform('uCount'), lights.length);
325
+ gl.uniform1f(uniform('uSize'), o.size);
326
+ gl.uniform1f(uniform('uGlow'), o.glow);
327
+ gl.uniform1f(uniform('uDrift'), o.drift);
328
+ gl.uniform1f(uniform('uRate'), o.rate);
329
+ gl.uniform3f(uniform('uBg'), ground[0], ground[1], ground[2]);
330
+ gl.uniform4fv(uniform('uLights[0]'), pack);
331
+ },
332
+ resize({ gl, uniform }) {
333
+ const w = Math.max(1, el.clientWidth);
334
+ const h = Math.max(1, el.clientHeight);
335
+ gl.uniform1f(uniform('uAspect'), w / h);
336
+ gl.uniform4f(uniform('uQuiet'), ...quietUniform(config.quiet, w / h));
337
+ },
338
+ uniforms({ gl, uniform }, now) {
339
+ gl.uniform1f(uniform('uTime'), ((now - start) / 1000) * Math.max(0, o.speed));
340
+ const flat = new Float32Array(MAX_LIGHTS * 3);
341
+ colours.forEach((c, i) => flat.set(c, i * 3));
342
+ gl.uniform3fv(uniform('uLightCol[0]'), flat);
343
+ },
344
+ });
345
+ if (!stage) return stop;
346
+
347
+ const unwatch = watchColors(el, (next) => {
348
+ colours = rgb(bokehColors({ colors: next.colors }));
349
+ if (stage.still) stage.redraw();
350
+ });
351
+ return () => {
352
+ stop();
353
+ unwatch();
354
+ };
355
+ }
@@ -53,6 +53,20 @@ export interface GlassDropConfig {
53
53
  loop?: boolean;
54
54
  /** With `loop`: seconds the logo rests before the next drop, 0–10. Default 1.6. */
55
55
  loopDelay?: number;
56
+ /** A photo behind the glass (same origin), covering the element; the glass is then clear and bends it. */
57
+ backdrop?: string;
58
+ /** How soft the backdrop is round the glass (a mip bias, 0–5); through the glass it stays sharp, as a lens brings it into focus. Default 0. */
59
+ soften?: number;
60
+ /** How bright the backdrop shows round the glass, 0–1. Default 0.82. */
61
+ dim?: number;
62
+ /** A slow swell over the glass's top, like liquid settling, 0–2; 0 for none. Default 0. */
63
+ flow?: number;
64
+ /** How much the glass's flat middle magnifies what is behind, 0–0.3. Default 0.05. */
65
+ magnify?: number;
66
+ /** The glass's shadow on what is behind, with light focused into it, 0–2; 0 for none. Default 0. */
67
+ shadow?: number;
68
+ /** How far the light swings about `lightAngle` over time, degrees; 0 holds it. Default 0. */
69
+ lightDrift?: number;
56
70
  /** How it ends: `flat`, the glass melted and the logo left on the ground, or `glass`, the glass held. Default `flat`. */
57
71
  rest?: 'flat' | 'glass';
58
72
  }
@@ -14,6 +14,12 @@
14
14
  * a circle, a rounded square or the logo's own field, mixed as the drop
15
15
  * spreads — lit by the shared studio (./glass-optics.js).
16
16
  *
17
+ * Over a `backdrop` photo it is clear glass: the photo shows through it,
18
+ * magnified in its flat middle and bent hard at its bevel, the colours
19
+ * parting there, darker in a band inside the rim, tinted the logo's colour
20
+ * as light through tinted glass is, casting a shadow with a caustic in it.
21
+ * `flow` swells its top slowly, like liquid, and `lightDrift` moves the light.
22
+ *
17
23
  * Opaque: it paints its `background` everywhere. Without WebGL the canvas
18
24
  * goes and the element's background shows. With reduced motion it is one
19
25
  * still frame: the final state (the logo at rest, or the glass held).
@@ -24,6 +30,7 @@ import { drawShape, distanceField, blurField } from './shape.js';
24
30
  import { parseColor } from './color.js';
25
31
  import { GLSL_STUDIO, lightVector } from './glass-optics.js';
26
32
  import { DROP_SIZE, dropAt, dropLayout } from './glass-drop-plan.js';
33
+ import { loadImage, imageTexture, coverScale } from './image.js';
27
34
 
28
35
  /**
29
36
  * @typedef {import('./glass-drop.js').GlassDropConfig} GlassDropConfig
@@ -61,6 +68,17 @@ uniform float uBloom;
61
68
  uniform float uRipples;
62
69
  uniform float uTint;
63
70
  uniform vec2 uLightDir;
71
+ uniform sampler2D uPhoto;
72
+ uniform float uHasPhoto;
73
+ uniform float uAspect;
74
+ uniform vec2 uCover;
75
+ uniform float uDim;
76
+ uniform float uSoft;
77
+ // the mip bias the backdrop is read at: soft round the glass, sharp through it (a lens brings what is behind into focus)
78
+ float gBias = 0.0;
79
+ uniform float uFlow;
80
+ uniform float uMagnify;
81
+ uniform float uShadow;
64
82
  ${GLSL_STUDIO}
65
83
 
66
84
  // The logo's coverage at p (heights from the glass's middle), its box 'box' high.
@@ -105,9 +123,22 @@ float heightAt(float g, float b) {
105
123
  return sqrt(s * (2.0 - s));
106
124
  }
107
125
 
126
+ // A slow swell over the glass's top, like liquid still settling: a height to add inside the bevel.
127
+ float flowAt(vec2 p) {
128
+ if (uFlow <= 0.0) return 0.0;
129
+ float t = uTime;
130
+ return uFlow * 0.05 * (sin(p.x * 17.0 + t * 0.9) * cos(p.y * 13.0 - t * 0.7) + 0.6 * sin((p.x + p.y) * 23.0 - t * 1.3));
131
+ }
132
+
108
133
  // The ground: its colour, a faint pool of light about the middle, and the rings the drop sent out.
109
134
  vec3 ground(vec2 p) {
110
135
  vec3 col = uGround + (uLight - uGround) * 0.03 * uGlass * exp(-dot(p, p) * 5.0);
136
+ if (uHasPhoto > 0.5) {
137
+ // a photo behind the glass, covering the element as CSS 'cover' does, dimmed so the glass reads over it
138
+ vec2 sp = p + uCentre;
139
+ vec2 uv = (vec2(sp.x / uAspect, 1.0 - sp.y) - 0.5) * uCover + 0.5;
140
+ col = texture2D(uPhoto, clamp(uv, 0.001, 0.999), gBias).rgb * uDim;
141
+ }
111
142
  if (uRipple > 0.0) {
112
143
  float r = length(p);
113
144
  for (int k = 0; k < 3; k++) {
@@ -140,6 +171,8 @@ void main() {
140
171
  float hx = heightAt(glassField(p + e.xy), b) - heightAt(glassField(p - e.xy), b);
141
172
  float hy = heightAt(glassField(p + e.yx), b) - heightAt(glassField(p - e.yx), b);
142
173
  vec2 slope = vec2(hx, hy) / (2.0 * e.x) * b;
174
+ float inGlass = smoothstep(0.0, b, g);
175
+ slope += vec2(flowAt(p + e.xy) - flowAt(p - e.xy), flowAt(p + e.yx) - flowAt(p - e.yx)) / (2.0 * e.x) * b * inGlass;
143
176
  float h = heightAt(g, b);
144
177
  vec3 n = normalize(vec3(-slope * uDepth * 0.55 * uGlass, 1.0));
145
178
  vec2 outward = length(slope) > 1e-5 ? -normalize(slope) : vec2(0.0);
@@ -148,9 +181,11 @@ void main() {
148
181
  float plate = uForm < 0.5 ? cover : 0.0;
149
182
 
150
183
  // Through the glass: magnified a little, bent at the rim, the colours parting there.
151
- vec2 rim = n.xy * uDepth * 0.06;
152
- vec2 lens = p * (1.0 - h * uDepth * 0.05 * uGlass);
153
- float split = uDispersion * 0.3;
184
+ // (over a photo the bend is stronger, so it visibly bends and magnifies what is behind; the colours part as far as it bends)
185
+ vec2 rim = n.xy * uDepth * mix(0.06, 0.11, uHasPhoto);
186
+ vec2 lens = p * (1.0 - h * uMagnify * uGlass);
187
+ float split = uDispersion * mix(0.3, 0.45, uHasPhoto);
188
+ gBias = 0.0;
154
189
  vec3 through = vec3(
155
190
  scene(lens - rim * (1.0 + split), plate).r,
156
191
  scene(lens - rim, plate).g,
@@ -158,8 +193,16 @@ void main() {
158
193
  );
159
194
  if (uForm > 0.5) {
160
195
  // The logo made of glass: the ground through it, tinted the logo's colour, deepest where it is thickest.
161
- float tint = mix(1.0, uTint * (0.75 + 0.25 * h), uGlass);
162
- through = mix(through, uInk * (0.82 + 0.18 * h + 0.12 * (1.0 - uGlass)), tint);
196
+ if (uHasPhoto > 0.5) {
197
+ // clear glass over a photo: the photo through it, taking the logo's colour as light does through tinted glass
198
+ // (deeper where it is thicker), lifted, as glass gathers light from the room round it: over a dark part of the
199
+ // photo it still glows a little, never a black hole
200
+ vec3 absorb = pow(max(uInk, vec3(0.02)), vec3((0.35 + 0.9 * h) * uTint));
201
+ through = through * mix(vec3(1.0), absorb, uGlass) * (1.0 + 0.3 * uGlass) + mix(uLight, uInk, 0.35) * 0.07 * uGlass;
202
+ } else {
203
+ float tint = mix(1.0, uTint * (0.75 + 0.25 * h), uGlass);
204
+ through = mix(through, uInk * (0.82 + 0.18 * h + 0.12 * (1.0 - uGlass)), tint);
205
+ }
163
206
  }
164
207
 
165
208
  // What the glass mirrors: the studio, along the bevels as they turn toward it.
@@ -167,7 +210,17 @@ void main() {
167
210
  vec3 mirrored = studio(reflect(view, n), uLightDir, uLight);
168
211
  float fres = schlick(n.z, 0.04);
169
212
  vec3 col = through * (1.0 - fres * 0.6) + mirrored * (0.25 + fres * 1.6) * uHighlights * uGlass;
213
+ if (uHasPhoto > 0.5) {
214
+ // the room the glass mirrors on its face too: a soft window of light swept across it from the light's side, and a
215
+ // faint lit inner edge all round, so the glass reads even over the darkest part of the photo
216
+ float across = dot(p, uLightDir) / max(uMarkBox, 1e-4);
217
+ float window = smoothstep(-0.1, 0.45, across) * (1.0 - smoothstep(0.45, 0.75, across));
218
+ col += uLight * window * (0.07 + 0.18 * h) * uHighlights * uGlass;
219
+ col += mix(uLight, uInk, 0.4) * 0.16 * uGlass * smoothstep(b * 0.7, b * 0.05, g) * smoothstep(0.0, px * 2.0, g);
220
+ }
170
221
 
222
+ // Thick glass goes dark in a band just inside its rim, where the view inside reflects back off the far wall.
223
+ col *= 1.0 - 0.26 * uHasPhoto * uGlass * smoothstep(b * 0.85, b * 0.2, g) * smoothstep(0.0, px * 2.5, g);
171
224
  // The lip: a hairline brightest facing the light; light gathered just inside the rim on the far side.
172
225
  float facing = dot(outward, uLightDir);
173
226
  float lip = exp(-pow(g / (px * 1.3), 2.0));
@@ -176,12 +229,22 @@ void main() {
176
229
  col += mix(uLight, uInk, 0.5) * inner * max(-facing, 0.0) * 0.32 * uCaustics * uGlass;
177
230
 
178
231
  // Outside: the ground, the light the glass focuses onto it on the side away from the light, and a soft bloom.
232
+ gBias = uSoft * uHasPhoto;
179
233
  vec3 outside = scene(p, 0.0);
180
234
  // (the logo's own field stops a little way out, so its glow stays closer)
181
235
  float reach = uForm < 0.5 ? uEdge : uMarkBox * 0.4;
182
236
  float near = exp(min(g, 0.0) / (reach * 0.05 + 1e-4));
183
237
  outside += mix(uLight, uInk, 0.6) * near * max(-facing, 0.0) * 0.14 * uCaustics * uGlass;
184
238
  outside += mix(uLight, uInk, 0.5) * exp(min(g, 0.0) / (reach * 0.09 + 1e-4)) * 0.12 * uBloom * uGlass;
239
+ if (uShadow > 0.0) {
240
+ // its shadow on what is behind, cast away from the light, and the light the glass focuses into it
241
+ float gs = glassField(p + uLightDir * reach * 0.07);
242
+ float shade = smoothstep(-reach * 0.05, reach * 0.03, gs);
243
+ outside *= 1.0 - 0.5 * uShadow * shade * uGlass;
244
+ float gc = glassField(p + uLightDir * reach * 0.035);
245
+ float focus = exp(-pow(gc / (reach * 0.012 + 1e-4), 2.0)) * step(g, 0.0);
246
+ outside += mix(uLight, uInk, 0.45) * focus * 0.35 * uShadow * uCaustics * uGlass;
247
+ }
185
248
 
186
249
  gl_FragColor = vec4(mix(outside, col, cover), 1.0);
187
250
  }
@@ -203,6 +266,12 @@ const DEFAULTS = Object.freeze({
203
266
  ripples: 1,
204
267
  tint: 0.88,
205
268
  lightAngle: 125,
269
+ dim: 0.82,
270
+ flow: 0,
271
+ magnify: 0.05,
272
+ shadow: 0,
273
+ lightDrift: 0,
274
+ soften: 0,
206
275
  });
207
276
 
208
277
  /** The finest the logo's mask and field are drawn, in pixels across. */
@@ -261,6 +330,11 @@ export function glassDrop(el, config) {
261
330
  /** The shape's textures, made in setup. */
262
331
  let mask = /** @type {WebGLTexture | null} */ (null);
263
332
  let sdf = /** @type {WebGLTexture | null} */ (null);
333
+ /** The backdrop photo's texture, its aspect, and the element's, once known. */
334
+ let photo = /** @type {WebGLTexture | null} */ (null);
335
+ let photoAspect = 1;
336
+ let boxAspect = 1;
337
+ let alive = true;
264
338
 
265
339
  const { stage, stop } = createStage(el, {
266
340
  fragment: FRAG,
@@ -285,9 +359,20 @@ export function glassDrop(el, config) {
285
359
  gl.uniform3fv(uniform('uInk'), parseColor(c.color));
286
360
  gl.uniform3fv(uniform('uPlate'), parseColor(c.plate));
287
361
  gl.uniform3fv(uniform('uLight'), parseColor(c.light));
362
+ gl.uniform1i(uniform('uPhoto'), 2);
363
+ gl.uniform1f(uniform('uHasPhoto'), 0);
364
+ gl.uniform1f(uniform('uDim'), c.dim);
365
+ gl.uniform1f(uniform('uSoft'), Math.max(0, Math.min(5, c.soften)));
366
+ gl.uniform1f(uniform('uFlow'), Math.max(0, Math.min(2, c.flow)));
367
+ gl.uniform1f(uniform('uMagnify'), c.magnify);
368
+ gl.uniform1f(uniform('uShadow'), Math.max(0, Math.min(2, c.shadow)));
369
+ return () => gl.deleteTexture(photo);
288
370
  },
289
371
  resize({ gl, uniform, canvas }) {
290
372
  const aspect = canvas.width / canvas.height;
373
+ boxAspect = aspect;
374
+ gl.uniform1f(uniform('uAspect'), aspect);
375
+ gl.uniform2fv(uniform('uCover'), coverScale(photoAspect, aspect));
291
376
  const layout = dropLayout(c, aspect);
292
377
  gl.uniform2f(uniform('uCentre'), layout.centre.x * aspect, 1 - layout.centre.y);
293
378
  tile = layout.tile;
@@ -325,7 +410,32 @@ export function glassDrop(el, config) {
325
410
  gl.uniform1f(uniform('uMarkIn'), s.markIn);
326
411
  gl.uniform1f(uniform('uGlass'), s.glass);
327
412
  gl.uniform1f(uniform('uScale'), s.scale);
413
+ // the light drifts slowly about its angle, so the glass's rims and reflections move
414
+ const drift = still || !c.lightDrift ? 0 : Math.sin(seconds * 0.23) * c.lightDrift * 0.7 + Math.sin(seconds * 0.11 + 1.3) * c.lightDrift * 0.3;
415
+ gl.uniform2fv(uniform('uLightDir'), lightVector(c.lightAngle + drift));
416
+ if (photo) {
417
+ gl.activeTexture(gl.TEXTURE2);
418
+ gl.bindTexture(gl.TEXTURE_2D, photo);
419
+ }
328
420
  },
329
421
  });
330
- return stop;
422
+ if (stage && c.backdrop) {
423
+ loadImage(c.backdrop)
424
+ .then((image) => {
425
+ if (!alive) return;
426
+ const { gl, uniform, program } = stage;
427
+ gl.activeTexture(gl.TEXTURE2);
428
+ photo = imageTexture(gl, image, { mipmap: true });
429
+ photoAspect = image.naturalWidth / image.naturalHeight;
430
+ gl.useProgram(program);
431
+ gl.uniform1f(uniform('uHasPhoto'), 1);
432
+ gl.uniform2fv(uniform('uCover'), coverScale(photoAspect, boxAspect));
433
+ stage.redraw();
434
+ })
435
+ .catch((error) => console.warn('[effects-astro]', error));
436
+ }
437
+ return () => {
438
+ alive = false;
439
+ stop();
440
+ };
331
441
  }
@@ -0,0 +1,63 @@
1
+ export interface GlassPlatesConfig {
2
+ /** An image (an SVG logo) to cut the plates from. */
3
+ src?: string;
4
+ /** A character or word instead of an image. */
5
+ text?: string;
6
+ /** Its CSS font, without the size. */
7
+ font?: string;
8
+ /** Where the stack sits, each 0–1 from the top left. Default all of the element. */
9
+ area?: { x: number; y: number; width: number; height: number };
10
+ /** The logo's box, a share of the area's shorter side. Default 0.7. */
11
+ logoScale?: number;
12
+ /** The plates' tints, back to front (blended between). Default pale blues. */
13
+ colors?: string[];
14
+ /** The colour of the glass seen through its edge. Default `#5FD6B8`. */
15
+ edge?: string;
16
+ /** How many plates, 2–4. Default 3. */
17
+ plates?: number;
18
+ /** The step between plates, a share of the box. Default 0.07. */
19
+ spread?: number;
20
+ /** How thick each plate's edge shows, a share of the box. Default 0.045. */
21
+ thickness?: number;
22
+ /** How wide each face's bevel is, a share of the box. Default 0.035. */
23
+ bevel?: number;
24
+ /** How deep the tints are (they deepen where plates overlap). Default 0.6. */
25
+ density?: number;
26
+ /** How hard a face bends the photo, in heights. Default 0.022. */
27
+ bend?: number;
28
+ /** How far the colours part where it bends, 0–1. Default 0.35. */
29
+ dispersion?: number;
30
+ /** The streak of reflected light across each face, 0–2. Default 1. */
31
+ streak?: number;
32
+ /** The stack's shadow on the photo, 0–2. Default 0.6. */
33
+ shadow?: number;
34
+ /** A photo behind (same origin), covering the element. */
35
+ backdrop?: string;
36
+ /** How bright the photo shows, 0–1. Default 0.75. */
37
+ dim?: number;
38
+ /** How soft the photo is round the plates (a mip bias, 0–5); through them it is sharp. Default 2. */
39
+ soften?: number;
40
+ /** The ground without a photo. Default `#0b0b0b`. */
41
+ background?: string;
42
+ /** The studio light. Default `#ffffff`. */
43
+ light?: string;
44
+ /** Where the light comes from, degrees (0 right, 90 top). Default 120. */
45
+ lightAngle?: number;
46
+ /** How much the plates and the light drift, 0–2; 0 holds them. Default 1. */
47
+ drift?: number;
48
+ /** Slide the plates apart when it first shows. Default true. */
49
+ intro?: boolean;
50
+ /** Seconds the plates take to slide apart. Default 1.4. */
51
+ introDuration?: number;
52
+ /** Seconds before it starts. Default 0. */
53
+ delay?: number;
54
+ }
55
+
56
+ /** The plates' tints, back to front, blended in Oklab (RGB 0–1). */
57
+ export declare function plateTints(colors: string[], plates: number): Array<[number, number, number]>;
58
+
59
+ /** Where plate `k` of `n` sits: its offset from the stack's middle, a share of the box (x right, y down). */
60
+ export declare function plateOffset(k: number, n: number, spread: number): { x: number; y: number };
61
+
62
+ /** Starts the glass plates on an element (its first canvas). Returns a function that stops it. */
63
+ export declare function glassPlates(el: HTMLElement, config: GlassPlatesConfig): () => void;