@arraypress/effects-astro 0.4.0 → 0.6.1

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.
@@ -8,6 +8,11 @@
8
8
  * pointer and the text knits back together behind it. Faster movement adds
9
9
  * more heat.
10
10
  *
11
+ * The slip is each hot cell's own by default; with `tear: 'row'` a whole
12
+ * row tears at once, now and then, by its hottest cell (the Logomarks
13
+ * site's footer). With `ghost`, a copy of the blocks in that colour sits
14
+ * nudged 3px right behind them, an accent under the break.
15
+ *
11
16
  * With `stroke` set, the text at rest is a hollow outline of that width and
12
17
  * the pixels it breaks into fill the letters solid, so the pointer lights
13
18
  * the word up as it passes. The outline is one shape for the whole word
@@ -42,7 +47,46 @@ import { textNodes } from './text.js';
42
47
  * @property {number} [block=22] The pixel block size at full heat, CSS px.
43
48
  * @property {number} [shift=16] How far the hottest rows slip sideways, CSS px.
44
49
  * @property {number} [stroke=0] With a width (CSS px), the text at rest is an outline that the pixels fill.
50
+ * @property {'cell' | 'row'} [tear='cell'] What slips: each hot cell on its own, or a whole row at once.
51
+ * @property {string} [ghost] A colour for a copy of the blocks, nudged right behind them (none by default).
52
+ */
53
+
54
+ /** How far the ghost sits right of its block, CSS px. */
55
+ const GHOST_OFFSET = 3;
56
+
57
+ /** The heat a block needs to cast its ghost. */
58
+ const GHOST_HEAT = 0.3;
59
+
60
+ /** A row's hottest cell must pass this for the row to tear… */
61
+ const TEAR_HEAT = 0.45;
62
+
63
+ /** …and then it tears on this share of frames. */
64
+ const TEAR_CHANCE = 0.35;
65
+
66
+ /** The heat a cell needs to slip on its own (`tear: 'cell'`). */
67
+ const SLIP_HEAT = 0.55;
68
+
69
+ /**
70
+ * How far each row of a heat grid tears this frame: rows whose hottest
71
+ * cell passes TEAR_HEAT tear on some frames, by up to half of `shift`
72
+ * either way (scaled by that heat), and the rest stay put.
73
+ *
74
+ * @param {Float32Array} heat The grid, row by row.
75
+ * @param {number} cols Cells a row.
76
+ * @param {number} rows Rows.
77
+ * @param {number} shift The most a row slips, at full heat, CSS px (end to end).
78
+ * @param {() => number} [random=Math.random] Random values, 0–1.
79
+ * @returns {Float32Array} Each row's slip, whole CSS px.
45
80
  */
81
+ export function rowTears(heat, cols, rows, shift, random = Math.random) {
82
+ const tear = new Float32Array(rows);
83
+ for (let row = 0; row < rows; row++) {
84
+ let h = 0;
85
+ for (let col = 0; col < cols; col++) h = Math.max(h, heat[row * cols + col]);
86
+ tear[row] = h > TEAR_HEAT && random() < TEAR_CHANCE ? Math.round((random() - 0.5) * h * shift) : 0;
87
+ }
88
+ return tear;
89
+ }
46
90
 
47
91
  /** The 16 directions the outline's erosion looks in, as unit vectors. */
48
92
  const AROUND = Array.from({ length: 16 }, (_, k) => [Math.cos((k / 16) * Math.PI * 2), Math.sin((k / 16) * Math.PI * 2)]);
@@ -97,6 +141,8 @@ export function pixelGlitch(el, config) {
97
141
  const MAX_BLOCK = config.block ?? 22;
98
142
  const SHIFT = config.shift ?? 16;
99
143
  const STROKE = config.stroke ?? 0;
144
+ const ROWS = config.tear === 'row';
145
+ const GHOST = config.ghost || '';
100
146
 
101
147
  const canvas = document.createElement('canvas');
102
148
  canvas.className = 'effect-pixel-glitch-canvas';
@@ -148,6 +194,7 @@ export function pixelGlitch(el, config) {
148
194
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
149
195
  ctx.fillStyle = g.ink;
150
196
  let hot = false;
197
+ const tears = ROWS ? rowTears(g.heat, g.cols, g.rows, SHIFT) : null;
151
198
  for (let row = 0; row < g.rows; row++) {
152
199
  for (let col = 0; col < g.cols; col++) {
153
200
  const i = row * g.cols + col;
@@ -162,17 +209,24 @@ export function pixelGlitch(el, config) {
162
209
  // Wipe the cell, then fill it with blocks sampled from the filled text.
163
210
  ctx.clearRect(x0, y0, CELL, CELL);
164
211
  const block = Math.max(3, Math.round(3 + heat * (MAX_BLOCK - 3)));
165
- // The hottest cells also slip sideways: the glitch.
166
- const shift = heat > 0.55 ? Math.round((Math.random() - 0.5) * heat * SHIFT) : 0;
212
+ // The hottest cells (or rows) also slip sideways: the glitch.
213
+ const shift = tears ? tears[row] : heat > SLIP_HEAT ? Math.round((Math.random() - 0.5) * heat * SHIFT) : 0;
167
214
  const bx0 = Math.floor(x0 / block) * block;
168
215
  const by0 = Math.floor(y0 / block) * block;
169
216
  for (let by = by0; by < y0 + CELL; by += block) {
170
217
  for (let bx = bx0; bx < x0 + CELL; bx += block) {
171
218
  if (!inked(bx + block / 2, by + block / 2)) continue;
172
219
  // Clipped to the cell, so neighbours tile cleanly.
220
+ const x = Math.max(bx, x0) + shift;
221
+ const y = Math.max(by, y0);
173
222
  const w = Math.min(bx + block, x0 + CELL) - Math.max(bx, x0);
174
223
  const h = Math.min(by + block, y0 + CELL) - Math.max(by, y0);
175
- ctx.fillRect(Math.max(bx, x0) + shift, Math.max(by, y0), w, h);
224
+ if (GHOST && heat > GHOST_HEAT) {
225
+ ctx.fillStyle = GHOST;
226
+ ctx.fillRect(x + GHOST_OFFSET, y, w, h);
227
+ ctx.fillStyle = g.ink;
228
+ }
229
+ ctx.fillRect(x, y, w, h);
176
230
  }
177
231
  }
178
232
  g.heat[i] = heat * DECAY;
@@ -1,2 +1,14 @@
1
+ /** A seeded generator's name: `mulberry32` (well mixed from any seed) or `park-miller` (the minimal standard, × 16807 mod 2³¹ − 1). */
2
+ export type RandomName = 'mulberry32' | 'park-miller';
3
+
1
4
  /** A seeded generator (mulberry32): the same seed gives the same sequence of values, 0 (inclusive) to 1 (exclusive). */
2
5
  export function seededRandom(seed: number): () => number;
6
+
7
+ /** A Park–Miller minimal standard generator (× 16807 mod 2³¹ − 1): the same seed gives the same sequence, over 0 and under 1. A seed that comes to 0 is moved into range. */
8
+ export function parkMiller(seed: number): () => number;
9
+
10
+ /** The generators by name. */
11
+ export const RANDOMS: Readonly<Record<RandomName, (seed: number) => () => number>>;
12
+
13
+ /** Makes a generator by name (default `mulberry32`). Throws a TypeError for an unknown name. */
14
+ export function randomFrom(name: RandomName | undefined, seed: number): () => number;
@@ -1,10 +1,19 @@
1
1
  /**
2
2
  * @module @arraypress/effects-astro/random
3
3
  *
4
- * A small seeded random generator (mulberry32), for effects that build
5
- * something from a `seed` and must build the same thing on every load.
4
+ * Small seeded random generators, for effects that build something from a
5
+ * `seed` and must build the same thing on every load: mulberry32 (the
6
+ * default, well mixed from any seed) and the Park–Miller minimal standard
7
+ * (a multiplicative generator, × 16807 mod 2³¹ − 1), kept so a sky first
8
+ * drawn with it can be drawn again exactly.
6
9
  */
7
10
 
11
+ /** Park–Miller's modulus, 2³¹ − 1. */
12
+ const PM_MODULUS = 2147483647;
13
+
14
+ /** Park–Miller's multiplier (the minimal standard's). */
15
+ const PM_MULTIPLIER = 16807;
16
+
8
17
  /**
9
18
  * Makes a seeded generator: the same seed gives the same sequence.
10
19
  *
@@ -20,3 +29,35 @@ export function seededRandom(seed) {
20
29
  return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
21
30
  };
22
31
  }
32
+
33
+ /**
34
+ * Makes a Park–Miller generator: the state times 16807, mod 2³¹ − 1, read
35
+ * as a fraction of the modulus. Exact in double precision. A seed that
36
+ * comes to 0 (or a multiple of the modulus) would stick at 0, so it is
37
+ * moved into range first.
38
+ *
39
+ * @param {number} seed Any number; its integer part is used.
40
+ * @returns {() => number} The next value, over 0 and under 1.
41
+ */
42
+ export function parkMiller(seed) {
43
+ let s = Math.floor(seed) % PM_MODULUS;
44
+ if (s <= 0) s += PM_MODULUS - 1;
45
+ return () => (s = (s * PM_MULTIPLIER) % PM_MODULUS) / PM_MODULUS;
46
+ }
47
+
48
+ /** The generators by name, for an effect's `rng` setting. */
49
+ export const RANDOMS = Object.freeze({ mulberry32: seededRandom, 'park-miller': parkMiller });
50
+
51
+ /**
52
+ * Makes a generator by name.
53
+ *
54
+ * @param {string | undefined} name `mulberry32` (the default) or `park-miller`.
55
+ * @param {number} seed The seed.
56
+ * @returns {() => number} The generator.
57
+ * @throws {TypeError} When the name is not one of RANDOMS.
58
+ */
59
+ export function randomFrom(name, seed) {
60
+ const key = /** @type {keyof typeof RANDOMS} */ (name ?? 'mulberry32');
61
+ if (!Object.hasOwn(RANDOMS, key)) throw new TypeError(`Unknown random generator: ${name} (use ${Object.keys(RANDOMS).join(' or ')})`);
62
+ return RANDOMS[key](seed);
63
+ }
@@ -0,0 +1,58 @@
1
+ import type { SceneOptions } from '@logomarks/shaders';
2
+ import type { PaletteName } from './palettes.js';
3
+
4
+ /** A scene's name: one of `@logomarks/shaders`' scenes. */
5
+ export type SceneName =
6
+ | 'marble'
7
+ | 'frosted'
8
+ | 'ribs'
9
+ | 'tiles'
10
+ | 'blob'
11
+ | 'chrome'
12
+ | 'glitter'
13
+ | 'foil'
14
+ | 'ribbon'
15
+ | 'spiral'
16
+ | 'swirl'
17
+ | 'arches'
18
+ | 'spheres'
19
+ | 'spheres2'
20
+ | 'strands'
21
+ | 'rings'
22
+ | 'ink-water'
23
+ | 'topo'
24
+ | 'oil-bubbles'
25
+ | 'melting-hologram';
26
+
27
+ /** A `<Scene>`'s settings, as its element carries them. */
28
+ export interface SceneConfig {
29
+ /** The scene. */
30
+ name: SceneName;
31
+ /** A named palette (PALETTES). */
32
+ palette?: PaletteName | (string & {});
33
+ /** One to three colours (hex), over the palette's. */
34
+ colors?: string[];
35
+ /** The highlight colour (hex). */
36
+ glint?: string;
37
+ /** The scene's own settings by key. */
38
+ params?: Record<string, number>;
39
+ speed?: number;
40
+ hue?: number;
41
+ sat?: number;
42
+ exposure?: number;
43
+ tint?: string;
44
+ tintAmount?: number;
45
+ zoom?: number;
46
+ angle?: number;
47
+ grain?: number;
48
+ fps?: number;
49
+ scale?: number;
50
+ /** The component's `lazy`: hold a context only while near the screen (true, or a CSS length). Default true. */
51
+ near?: boolean | string;
52
+ }
53
+
54
+ /** A `<Scene>`'s settings as `@logomarks/shaders`' options: the palette found by name, `near` as `lazy`. */
55
+ export function sceneSettings(config: SceneConfig): { name: SceneName; options: SceneOptions };
56
+
57
+ /** Starts a scene on an element's canvas; returns a function that stops it. */
58
+ export function scene(el: HTMLElement, config: SceneConfig): () => void;
@@ -0,0 +1,80 @@
1
+ /**
2
+ * @module @arraypress/effects-astro/scene
3
+ *
4
+ * A scene from `@logomarks/shaders` on an effect's canvas: liquid marble,
5
+ * frosted glass, glossy tiles, chrome, glitter, holographic foil, ink in
6
+ * water and the rest, recoloured by a palette and shaped by the scene's own
7
+ * settings. `<Scene>` is the component.
8
+ *
9
+ * The scene is loaded by name, each in its own chunk, so a page ships only
10
+ * the shaders it shows. Its laziness is the package's own, not mount()'s:
11
+ * it holds a WebGL context only while near the screen and gives it back
12
+ * four seconds after it leaves, on a fresh canvas, and it caps its frame
13
+ * rate, adapts its resolution, pauses off screen and draws one still frame
14
+ * with reduced motion. `setColors` recolours it live.
15
+ */
16
+
17
+ import { scene as run, LOOK } from '@logomarks/shaders/core';
18
+ import { load } from '@logomarks/shaders/load';
19
+ import { findPalette } from './palettes.js';
20
+ import { watchColors } from './mount.js';
21
+
22
+ /**
23
+ * @typedef {import('./scene.js').SceneConfig} SceneConfig
24
+ * @typedef {import('@logomarks/shaders').SceneOptions} SceneOptions
25
+ */
26
+
27
+ /** The settings a `<Scene>` hands to its scene as they are: the look, the colours, the params, the frame rate and resolution. */
28
+ const OPTIONS = /** @type {(keyof SceneConfig)[]} */ ([...Object.keys(LOOK), 'colors', 'glint', 'params', 'fps', 'scale']);
29
+
30
+ /**
31
+ * A `<Scene>`'s settings as the package's options: its palette found by
32
+ * name (an unknown one is warned about and the scene's own colours kept),
33
+ * `near` as `lazy`, and the rest as they are.
34
+ *
35
+ * @param {SceneConfig} config The component's settings.
36
+ * @returns {{ name: SceneConfig['name'], options: SceneOptions }} The scene and its options.
37
+ */
38
+ export function sceneSettings(config) {
39
+ const { name, palette, near = true } = config;
40
+ // Only the scene's own options: anything else a component is handed (Astro's `slot`, say) is not the scene's.
41
+ /** @type {Record<string, unknown>} */
42
+ const options = Object.fromEntries(OPTIONS.filter((k) => config[k] !== undefined).map((k) => [k, config[k]]));
43
+ if (palette) {
44
+ const found = findPalette(palette);
45
+ if (found) options.palette = found;
46
+ else console.warn('[effects-astro]', `No palette "${palette}"`);
47
+ }
48
+ options.lazy = near;
49
+ return { name, options: /** @type {SceneOptions} */ (options) };
50
+ }
51
+
52
+ /**
53
+ * Starts a scene on an element's canvas.
54
+ *
55
+ * @param {HTMLElement} el The element (its first canvas is drawn on).
56
+ * @param {SceneConfig} config The scene and its settings.
57
+ * @returns {() => void} Stops it.
58
+ */
59
+ export function scene(el, config) {
60
+ const canvas = el.querySelector('canvas');
61
+ if (!canvas) return () => {};
62
+ const { name, options } = sceneSettings(config);
63
+ let stopped = false;
64
+ /** @type {import('@logomarks/shaders').SceneHandle | null} */
65
+ let handle = null;
66
+ let unwatch = () => {};
67
+ load(name)
68
+ .then((def) => {
69
+ if (stopped) return;
70
+ const h = run(canvas, def, options);
71
+ handle = h;
72
+ unwatch = watchColors(el, (next) => h.set({ colors: next.colors.slice(0, 3), ...(next.glint ? { glint: next.glint } : {}) }));
73
+ })
74
+ .catch((error) => console.warn('[effects-astro]', error?.message ?? error));
75
+ return () => {
76
+ stopped = true;
77
+ unwatch();
78
+ handle?.stop();
79
+ };
80
+ }