@uxfront/scene 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  The scroll-driven WebGL particle scene behind the uxfront.com family of homepages (UXFront, Open Components, Unframework, Styleframe, Inkline). One GPU particle system turns into a new **formation** for each section of the page as you scroll. The package has no framework dependency: `@uxfront/ui` wraps it in Vue components, and any other page can drive it directly.
4
4
 
5
5
  - **A pipeline.** Morphs between formations under curl noise, an intro that rises from a floor line, a cursor lens, a click shockwave, a mirror floor, light trails, bloom and a filmic composite.
6
- - **A catalog.** Eight formations: `monolith`, `plates`, `prism`, `tokens`, `ink`, `corridor`, `stack` and `threshold`.
6
+ - **A catalog.** Ten formations: `monolith`, `plates`, `prism`, `tokens`, `ink`, `corridor`, `stack`, `threshold`, `outline` and `empty`.
7
7
  - **A controller.** `createExperience` maps the page's sections to formations, reveals copy, steps through highlights and pins DOM labels to the formations.
8
8
 
9
9
  Pages stay fast. The engine and each formation's GLSL are separate chunks, imported only once the page is idle. Shaders compile without blocking the main thread. Slow GPUs get fewer particles at a lower resolution, and without a capable GPU (no WebGL2, a software rasterizer, a lost context) the state switches to `"fallback"`, so the page can show a static image instead.
@@ -54,18 +54,55 @@ experience.destroy();
54
54
 
55
55
  ### Page contract
56
56
 
57
- | Markup | Effect |
58
- | -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
59
- | `[data-stage]` under `root` | One section per formation, in DOM order, about a screen tall. It holds its formation while it fills the screen, give or take `HOLD_MARGIN`. |
60
- | `data-steps="n"` on a section | While it holds its formation, the section gets `data-step="0…n-1"` as it is read, to highlight `[data-step-item]`s, each once it's on screen. |
61
- | `[data-reveal]` under `root` | Gets `.is-in` once scrolled into view. |
62
- | `[data-anchor="key:id"]` under `anchorRoots` | Positioned (`transform`, `opacity`, `visibility`) over the formation's anchor while it shows. |
63
- | `[data-progress]` under `root` | Gets `--ux-progress`: page scroll, 0 → 1. |
57
+ | Markup | Effect |
58
+ | -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
59
+ | `[data-stage]` under `root` | One section per formation, in DOM order, about a screen tall. It holds its formation while it fills the screen, give or take `HOLD_MARGIN`. |
60
+ | `data-steps="n"` on a section | While it holds its formation, the section gets `data-step="0…n-1"` as it is read, to highlight `[data-step-item]`s, each once it's on screen. |
61
+ | `[data-reveal]` under `root` | Gets `.is-in` once scrolled into view. |
62
+ | `[data-anchor="key:id"]` under `anchorRoots` | Positioned (`transform`, `opacity`, `visibility`) over the formation's anchor while it shows. |
63
+ | `[data-progress]` under `root` | Gets `--ux-progress`: page scroll, 0 → 1. |
64
+ | `[data-outline]` in an `outline` section | The element the `outline` formation's particles gather around. The outline follows the page's scroll each frame, so it stays on the element however fast you scroll. |
65
+ | `data-gather` on `[data-outline]` | Written by `outline`: how far the particles have gathered, 0 → 1. It reaches 1 only once every particle has arrived. |
66
+ | `--ux-reveal` on `[data-outline]` | Written by `outline`: 0 until the gather is complete, then 1 over the start of the hold. It's 1 at once without motion and in `"fallback"`. |
67
+
68
+ To fade an element's content in once the particles have gathered around it, read `--ux-reveal` with a fallback of 1, and only once the scene is `ready`, so the content shows without JavaScript, while the scene loads and in `"fallback"`:
69
+
70
+ ```html
71
+ <section data-stage>
72
+ <img data-outline src="/figma.png" alt="The Figma plugin beside a component's code" />
73
+ </section>
74
+ ```
75
+
76
+ ```ts
77
+ experience.subscribe(({ status }) => {
78
+ document.body.toggleAttribute("data-scene-ready", status === "ready");
79
+ });
80
+ ```
81
+
82
+ ```css
83
+ [data-scene-ready] [data-outline] {
84
+ opacity: var(--ux-reveal, 1);
85
+ }
86
+ ```
64
87
 
65
88
  Sections scroll freely, so don't pin them: the copy should move with the page. The scene holds a formation from a quarter of a screen (`HOLD_MARGIN`) before its section fills the screen until a quarter after, and morphs into the next formation in between, while both sections share the screen.
66
89
 
67
90
  Portrait, squarish and small screens use each formation's `mobile` framing, which leaves the top of the screen to the formation. Lay the copy out with the same breakpoints, exported as `STACKED_QUERY`.
68
91
 
92
+ ### The frame
93
+
94
+ On a screen wider than the page's frame, the copy sits in a centred column, and a formation drawn against the whole screen would drift away from it. So the scene reads the frame's width from `--ux-frame` on `root` when it measures, on load and on resize, and draws the layout it would draw on a screen as wide as the frame, centred, while the canvas still fills the screen. Anchors follow, since they're projected through the same camera.
95
+
96
+ The scene's frame is never squarer than 5:4 of the screen's height, since the formations' desktop views are built for that shape, and a view that reaches the frame's edge, like `plates`', would carry its labels past a narrower one. Up to 1536px tall, a `1920px` frame is the page's frame. On a taller screen, like a 4K screen at 100% scaling (3840 × 2030px), the scene draws a band 5:4 of the height wide instead, 2537px, still centred.
97
+
98
+ `--ux-frame` is a px length, like `1920px`, the default `@uxfront/ui` sets. Anything else, like `100vw` or no value at all, means no frame, and at or below the scene frame's width the camera is the same as without one. With `@uxfront/ui`, override it on `:root:has(.ux-site)`, so the gutter and the scene move together:
99
+
100
+ ```css
101
+ :root:has(.ux-site) {
102
+ --ux-frame: 1200px;
103
+ }
104
+ ```
105
+
69
106
  ## Catalog
70
107
 
71
108
  Every factory takes `{ label, key?, views?, look? }`. `label` is shown in the HUD. `views` overrides the framing, for example to put a formation on the other side of the copy: `tokens({ label, views: { desktop: { shift: [0.42, 0.02] } } })`. `key` is only needed to use the same formation twice.
@@ -80,6 +117,51 @@ Every factory takes `{ label, key?, views?, look? }`. `label` is shown in the HU
80
117
  | `corridor` | A corridor of streaking light with long trails. Suits a closing section. | None |
81
118
  | `stack` | Seven glass cards dealt as the chapter is read, one per rail, each holding the same component. `art` swaps it. | `stack:0`–`stack:6`, in the cards' headers |
82
119
  | `threshold` | The prism's seven beams cross a soap film of light and converge into one white stream. | `threshold:stream`, above the stream |
120
+ | `outline` | Gathers around the section's `[data-outline]` element, like an image or a code panel. `lines` draws its code. | None |
121
+ | `empty` | Nothing, for a section without a formation. It frames the camera as `corridor` does. | None |
122
+
123
+ `empty` gives a section its place in the scene without drawing anything, since the scene needs one formation per section. Give each repeat its own `key`, like `empty({ label: "Pricing", key: "pricing" })`.
124
+
125
+ `outline` places its particles on the element itself, so it doesn't need `views`. With `lines: true`, it also draws the text lines of the `pre` blocks inside the element, scattering particles along each line's characters, before the code fades in. Its look turns `streak` off, so the outline stays crisp while the page scrolls. In the page's first section, which holds from the top, `--ux-reveal` is 1 at rest.
126
+
127
+ ### Reusing a formation
128
+
129
+ Three helpers change a catalog formation in ways its options don't cover. They rely only on the shader contract (`$main`, and `$name` identifiers), so they work on any formation, yours included.
130
+
131
+ | Helper | Effect |
132
+ | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
133
+ | `hold(formation, local)` | Holds the formation at a fixed `local`, whatever the scroll. Its GLSL, `update()` and anchors' `place()` and `render()` all see that `local`. |
134
+ | `wrapMain(formation, inner, body)` | Renames the formation's `$main` to `$<inner>` and adds a `$main` with `body`, which can call `$<inner>(id, sel, f)` and change its particle. |
135
+ | `editShader(formation, edit)` | Runs `edit` on the formation's shader once it loads, to change its GLSL or its `update()`. |
136
+
137
+ `hold` suits a hero. The first section starts at the top of the page, so it only gets a quarter screen of scroll (`HOLD_MARGIN`): a formation that moves with `local`, like `plates`, would rush to its end state the moment the page scrolls. Held, it stays put while it morphs into the next formation.
138
+
139
+ ```ts
140
+ import { hold, wrapMain } from "@uxfront/scene";
141
+ import { monolith, plates } from "@uxfront/scene/formations";
142
+
143
+ const hero = hold(plates({ label: "Open Components" }), 1);
144
+ // Dims the monolith to half its brightness.
145
+ const dimmed = wrapMain(
146
+ monolith({ label: "Foundation" }),
147
+ "lit",
148
+ ` Particle P = $lit(id, sel, f);
149
+ P.col *= 0.5;
150
+ return P;`,
151
+ );
152
+ ```
153
+
154
+ ### Look
155
+
156
+ `look` tunes the post-processing for one formation, and the scene blends it across the morphs on either side.
157
+
158
+ | Key | Default | Effect |
159
+ | ---------- | ------- | ------------------------------------------------------------------------------------------------------------------------------ |
160
+ | `bloom` | `1` | Strength of the glow around bright particles. |
161
+ | `trail` | `0` | How long light trails persist, 0 (none) to 1. |
162
+ | `exposure` | `1` | Overall brightness. |
163
+ | `reflect` | `0` | Strength of the mirror-floor reflection. |
164
+ | `streak` | `1` | How much scrolling between formations lengthens the trail and widens the colour fringe, 0 (none) to 1. `outline` sets it to 0. |
83
165
 
84
166
  ## Writing a formation
85
167
 
@@ -128,7 +210,9 @@ Particle $main(uint id, float sel, Frame f) {
128
210
  - Shared helpers: `hashU`, `rnd`, `seedOf`, `gauss`, `noised`, `curl`, `bitangent`, `bezier3`, `rrectPoint`, `shapePoint`, `PI`, `TAU` and `FLOOR_Y`.
129
211
  - `glslFloat`, `glslVec` and `glslArray` write numbers into the GLSL as constants. `packShapes` packs line art (segments, rounded rectangles, circles, discs and fills) into rows for `shapePoint`, which places a particle on it. `stack` and `plates` draw their art this way.
130
212
  - A formation that follows the prism can take its `RAILS` and `SPECTRUM` from `@uxfront/scene/formations`, so rail `i` keeps its colour.
131
- - `setup` uploads uniforms once. `update(uniforms, frame)` runs every frame with the formation's `local`, `approach`, `presence`, `time`, `dt`, `motion` and `scrolled`.
213
+ - `setup(uniforms, scene)` uploads uniforms once, and can start observers and listeners. `scene` holds the formation's `index` and the scene's `root`, so its section is `root.querySelectorAll("[data-stage]")[index]`. Measure the page there, on resize, since the frame loop must never force a layout.
214
+ - `update(uniforms, frame)` runs every frame with the formation's `index` (its place in the scene, and its section's), `local`, `approach`, `presence`, `time`, `dt`, `motion`, `scrolled` and `scrollY`. `scrollY` is the page's scroll position, read before the scene writes anything in the frame. Use it rather than `window.scrollY`, which makes the browser restyle the page after those writes.
215
+ - `teardown()` stops what `setup` started. The scene calls it when it's destroyed, and when it loses its WebGL context, before it loads the shaders again for a restored one.
132
216
  - `anchors` pin DOM labels: `place(progress, out)` writes a world position and returns extra visibility, and `render(el, progress)` can update the label's content.
133
217
 
134
218
  `composeParticleShader` builds the complete vertex shader, handy for testing a formation's GLSL.
@@ -29,6 +29,13 @@ function pageTop(el) {
29
29
  for (let node = el; node instanceof HTMLElement; node = node.offsetParent) top += node.offsetTop;
30
30
  return top;
31
31
  }
32
+ const PX = /^\s*(\d+(?:\.\d+)?|\.\d+)px\s*$/;
33
+ /** `--ux-frame` in CSS pixels, or null for anything but a px length, like `100vw`. */
34
+ function frameOf(value) {
35
+ const match = PX.exec(value);
36
+ const frame = match ? Number(match[1]) : 0;
37
+ return frame > 0 ? frame : null;
38
+ }
32
39
  function detectQuality() {
33
40
  if (Math.min(screen.width, screen.height) < 700) return "low";
34
41
  if (matchMedia("(pointer: coarse)").matches) return "medium";
@@ -72,7 +79,14 @@ function createExperience({ root, canvas, formations, anchorRoots = [] }) {
72
79
  let maxScroll = 1;
73
80
  let canvasWidth = 1;
74
81
  let canvasHeight = 1;
82
+ let frame = null;
75
83
  const html = document.documentElement;
84
+ const fallBack = () => {
85
+ set({ status: "fallback" });
86
+ root.querySelectorAll("[data-outline]").forEach((el) => {
87
+ el.style.setProperty("--ux-reveal", "1");
88
+ });
89
+ };
76
90
  const setMotion = (on) => set({ motion: on });
77
91
  const onReducedChange = () => setMotion(!reducedQuery.matches);
78
92
  reducedQuery.addEventListener("change", onReducedChange);
@@ -94,6 +108,8 @@ function createExperience({ root, canvas, formations, anchorRoots = [] }) {
94
108
  ...sectionSpan(rect.top + scrollY, rect.height, viewport, maxScroll)
95
109
  };
96
110
  });
111
+ frame = frameOf(getComputedStyle(root).getPropertyValue("--ux-frame"));
112
+ engine?.setFrame(frame);
97
113
  engine?.resize();
98
114
  };
99
115
  const resizeObserver = new ResizeObserver(measure);
@@ -221,6 +237,7 @@ function createExperience({ root, canvas, formations, anchorRoots = [] }) {
221
237
  engine.render({
222
238
  stage: clamp(stage, 0, formations.length - 1),
223
239
  local,
240
+ scrollY,
224
241
  scrolled,
225
242
  pointerX,
226
243
  pointerY,
@@ -242,7 +259,7 @@ function createExperience({ root, canvas, formations, anchorRoots = [] }) {
242
259
  const boot = async () => {
243
260
  if (disposed) return;
244
261
  if (typeof WebGL2RenderingContext === "undefined") {
245
- set({ status: "fallback" });
262
+ fallBack();
246
263
  return;
247
264
  }
248
265
  set({ status: "loading" });
@@ -250,14 +267,16 @@ function createExperience({ root, canvas, formations, anchorRoots = [] }) {
250
267
  const [{ createEngine }, shaders] = await Promise.all([import("./gl/engine.js"), Promise.all(formations.map((formation) => formation.shader()))]);
251
268
  if (disposed) return;
252
269
  const created = await createEngine(canvas, {
270
+ root,
253
271
  formations,
254
272
  shaders,
255
273
  quality: detectQuality(),
256
274
  reducedMotion: !state.motion,
275
+ frame,
257
276
  onContextLost: () => {
258
277
  engine?.destroy();
259
278
  engine = null;
260
- set({ status: "fallback" });
279
+ fallBack();
261
280
  }
262
281
  });
263
282
  if (disposed) {
@@ -265,7 +284,7 @@ function createExperience({ root, canvas, formations, anchorRoots = [] }) {
265
284
  return;
266
285
  }
267
286
  if (!created) {
268
- set({ status: "fallback" });
287
+ fallBack();
269
288
  return;
270
289
  }
271
290
  engine = created;
@@ -275,7 +294,7 @@ function createExperience({ root, canvas, formations, anchorRoots = [] }) {
275
294
  });
276
295
  } catch (error) {
277
296
  console.warn(error);
278
- set({ status: "fallback" });
297
+ fallBack();
279
298
  }
280
299
  };
281
300
  const onContextRestored = () => void boot();
@@ -0,0 +1,10 @@
1
+ import { Formation, FormationOptions } from "../../gl/types.js";
2
+ //#region src/formations/empty/index.d.ts
3
+ /**
4
+ * Draws nothing, for a section that holds no formation. The scene needs one
5
+ * formation per section, so give each repeat its own `key`. It frames the
6
+ * camera as `corridor` does, so the camera holds still into a closing
7
+ * corridor.
8
+ */
9
+ export declare function empty(options: FormationOptions): Formation;
10
+ //#endregion
@@ -0,0 +1,50 @@
1
+ import { defineFormation, mergeViews } from "../../gl/formation.js";
2
+ //#region src/formations/empty/index.ts
3
+ /**
4
+ * Draws nothing, for a section that holds no formation. The scene needs one
5
+ * formation per section, so give each repeat its own `key`. It frames the
6
+ * camera as `corridor` does, so the camera holds still into a closing
7
+ * corridor.
8
+ */
9
+ function empty(options) {
10
+ return defineFormation({
11
+ key: options.key ?? "empty",
12
+ label: options.label,
13
+ views: mergeViews({
14
+ desktop: {
15
+ eye: [
16
+ 0,
17
+ 0,
18
+ 7
19
+ ],
20
+ target: [
21
+ 0,
22
+ 0,
23
+ -12
24
+ ],
25
+ fov: 56,
26
+ span: [0, 0],
27
+ shift: [0, 0]
28
+ },
29
+ mobile: {
30
+ eye: [
31
+ 0,
32
+ 0,
33
+ 7
34
+ ],
35
+ target: [
36
+ 0,
37
+ 0,
38
+ -12
39
+ ],
40
+ fov: 64,
41
+ span: [0, 0],
42
+ shift: [0, 0]
43
+ }
44
+ }, options.views),
45
+ look: { ...options.look },
46
+ shader: () => import("./shader.js").then((m) => m.shader)
47
+ });
48
+ }
49
+ //#endregion
50
+ export { empty };
@@ -0,0 +1,10 @@
1
+ //#region src/formations/empty/shader.ts
2
+ const shader = { glsl: `
3
+ Particle $main(uint id, float sel, Frame f) {
4
+ Particle P = blank();
5
+ P.pos = vec3(0.0, 0.0, -1000.0);
6
+ return P;
7
+ }
8
+ ` };
9
+ //#endregion
10
+ export { shader };
@@ -1,6 +1,8 @@
1
1
  import { corridor } from "./corridor/index.js";
2
+ import { empty } from "./empty/index.js";
2
3
  import { ink } from "./ink/index.js";
3
4
  import { monolith } from "./monolith/index.js";
5
+ import { OutlineOptions, outline } from "./outline/index.js";
4
6
  import { OPEN_COMPONENTS_ART, PlateShape, circle, disc, fill, plateBorder, rrect, seg } from "./plates/art.js";
5
7
  import { PlatesOptions, plates } from "./plates/index.js";
6
8
  import { PLATE } from "./plates/geometry.js";
@@ -13,4 +15,4 @@ import { CARD, CARD_NAME } from "./stack/geometry.js";
13
15
  import { threshold } from "./threshold/index.js";
14
16
  import { THEMES, Theme } from "./tokens/geometry.js";
15
17
  import { TokensFormation, tokens } from "./tokens/index.js";
16
- export { CARD, CARD_NAME, CARD_ROLE, type CardRole, type CardShape, KNOB_TRAVEL, OPEN_COMPONENTS_ART, PLATE, type PlateShape, type PlatesOptions, RAILS, SIGN_UP_FORM_ART, SPECTRUM, type StackOptions, THEMES, type Theme, type TokensFormation, circle, corridor, disc, fill, ink, monolith, plateBorder, plates, prism, rrect, seg, stack, threshold, tokens };
18
+ export { CARD, CARD_NAME, CARD_ROLE, type CardRole, type CardShape, KNOB_TRAVEL, OPEN_COMPONENTS_ART, type OutlineOptions, PLATE, type PlateShape, type PlatesOptions, RAILS, SIGN_UP_FORM_ART, SPECTRUM, type StackOptions, THEMES, type Theme, type TokensFormation, circle, corridor, disc, empty, fill, ink, monolith, outline, plateBorder, plates, prism, rrect, seg, stack, threshold, tokens };
@@ -1,6 +1,8 @@
1
1
  import { corridor } from "./corridor/index.js";
2
+ import { empty } from "./empty/index.js";
2
3
  import { ink } from "./ink/index.js";
3
4
  import { monolith } from "./monolith/index.js";
5
+ import { outline } from "./outline/index.js";
4
6
  import { PLATE } from "./plates/geometry.js";
5
7
  import { plates } from "./plates/index.js";
6
8
  import { OPEN_COMPONENTS_ART, circle, disc, fill, plateBorder, rrect, seg } from "./plates/art.js";
@@ -13,4 +15,4 @@ import { CARD_ROLE, KNOB_TRAVEL, SIGN_UP_FORM_ART } from "./stack/art.js";
13
15
  import { threshold } from "./threshold/index.js";
14
16
  import { THEMES } from "./tokens/geometry.js";
15
17
  import { tokens } from "./tokens/index.js";
16
- export { CARD, CARD_NAME, CARD_ROLE, KNOB_TRAVEL, OPEN_COMPONENTS_ART, PLATE, RAILS, SIGN_UP_FORM_ART, SPECTRUM, THEMES, circle, corridor, disc, fill, ink, monolith, plateBorder, plates, prism, rrect, seg, stack, threshold, tokens };
18
+ export { CARD, CARD_NAME, CARD_ROLE, KNOB_TRAVEL, OPEN_COMPONENTS_ART, PLATE, RAILS, SIGN_UP_FORM_ART, SPECTRUM, THEMES, circle, corridor, disc, empty, fill, ink, monolith, outline, plateBorder, plates, prism, rrect, seg, stack, threshold, tokens };
@@ -0,0 +1,15 @@
1
+ import { Formation, FormationOptions } from "../../gl/types.js";
2
+ //#region src/formations/outline/index.d.ts
3
+ export interface OutlineOptions extends FormationOptions {
4
+ /** Also draws the text lines of the `pre` blocks inside the element, like a code sample. */
5
+ lines?: boolean;
6
+ }
7
+ /**
8
+ * Particles that gather into the outline of an element on the page, the one
9
+ * marked `data-outline` in the formation's `[data-stage]` section, as the
10
+ * section scrolls in. The outline stays on the element at any scroll speed,
11
+ * and the scene writes `data-gather` and `--ux-reveal` on it, so the page can
12
+ * fade the element's content in once the particles have gathered.
13
+ */
14
+ export declare function outline(options: OutlineOptions): Formation;
15
+ //#endregion
@@ -0,0 +1,42 @@
1
+ import { defineFormation, mergeViews } from "../../gl/formation.js";
2
+ //#region src/formations/outline/index.ts
3
+ const VIEW = {
4
+ eye: [
5
+ 0,
6
+ 0,
7
+ 8
8
+ ],
9
+ target: [
10
+ 0,
11
+ 0,
12
+ 0
13
+ ],
14
+ fov: 40,
15
+ span: [0, 0],
16
+ shift: [0, 0]
17
+ };
18
+ /**
19
+ * Particles that gather into the outline of an element on the page, the one
20
+ * marked `data-outline` in the formation's `[data-stage]` section, as the
21
+ * section scrolls in. The outline stays on the element at any scroll speed,
22
+ * and the scene writes `data-gather` and `--ux-reveal` on it, so the page can
23
+ * fade the element's content in once the particles have gathered.
24
+ */
25
+ function outline(options) {
26
+ const lines = options.lines ?? false;
27
+ return defineFormation({
28
+ key: options.key ?? "outline",
29
+ label: options.label,
30
+ views: mergeViews({
31
+ desktop: VIEW,
32
+ mobile: VIEW
33
+ }, options.views),
34
+ look: {
35
+ streak: 0,
36
+ ...options.look
37
+ },
38
+ shader: () => import("./shader.js").then((m) => m.createShader(lines))
39
+ });
40
+ }
41
+ //#endregion
42
+ export { outline };
@@ -0,0 +1,308 @@
1
+ import { clamp, smoothstep } from "../../gl/math.js";
2
+ import { sectionSpan } from "../../gl/stage.js";
3
+ //#region src/formations/outline/shader.ts
4
+ /** Text lines the particles draw, at most: four to a `vec4`. */
5
+ const MAX_LINES = 48;
6
+ /** How far the page scrolls while the content fades in, in screen heights. */
7
+ const FADE = .08;
8
+ /**
9
+ * How far the particles have gathered into the outline, 0 → 1. The engine
10
+ * moves them in from the formation before until `approach` reaches 1, so the
11
+ * gather is only complete then, whatever `$main`'s own schedule.
12
+ */
13
+ const gatherOf = (approach) => clamp(approach, 0, 1);
14
+ /** The gather as `data-gather` shows it: floored, so it reads 1 only at 1. */
15
+ const gatherText = (approach) => (Math.floor(gatherOf(approach) * 1e3) / 1e3).toFixed(3);
16
+ /**
17
+ * How far the content has faded in: nothing until the gather is complete,
18
+ * then in over the first `span` of the section's hold (`local`).
19
+ */
20
+ const revealOf = (approach, local, span) => {
21
+ if (approach < 1) return 0;
22
+ return span > 0 ? smoothstep(0, span, local) : 1;
23
+ };
24
+ const glsl = `
25
+ const int $MAX_LINES = ${MAX_LINES};
26
+
27
+ // The element in the canvas's CSS pixels: left, top, width, height.
28
+ uniform vec4 $rect;
29
+ // The canvas's size in CSS pixels.
30
+ uniform vec2 $screen;
31
+ // The element's corner radius in CSS pixels.
32
+ uniform float $radius;
33
+ // The text inside the element: its left and its first line's top (from the
34
+ // element's corner), the line height and the width of a character.
35
+ uniform vec4 $text;
36
+ // The text's width, past which a line is cut.
37
+ uniform float $clip;
38
+ // How far the content has faded in (revealOf).
39
+ uniform float $reveal;
40
+ // Each line, packed as indent + 64 * length + 8192 * row, in characters and
41
+ // rows of the line height.
42
+ uniform vec4 $lines[${MAX_LINES / 4}];
43
+ uniform float $count;
44
+ uniform float $chars;
45
+
46
+ const float $DEPTH = 8.0;
47
+ const float $OUTSET = 3.0;
48
+
49
+ // A point on pixel px of the canvas, depth in front of the camera: it stays on
50
+ // that pixel however the camera sways, so it keeps to the element.
51
+ vec3 $place(vec2 px, float depth) {
52
+ vec2 ndc = vec2(px.x / $screen.x * 2.0 - 1.0, 1.0 - px.y / $screen.y * 2.0);
53
+ vec3 right = vec3(uView[0][0], uView[1][0], uView[2][0]);
54
+ vec3 up = vec3(uView[0][1], uView[1][1], uView[2][1]);
55
+ vec3 forward = -vec3(uView[0][2], uView[1][2], uView[2][2]);
56
+ float x = (ndc.x + uProjection[2][0]) / uProjection[0][0];
57
+ float y = (ndc.y + uProjection[2][1]) / uProjection[1][1];
58
+ return uRayOrigin + (forward + right * x + up * y) * depth;
59
+ }
60
+
61
+ // Character k of the text, counted over every line: its line's packed value
62
+ // and the character's place in it.
63
+ vec2 $char(float k) {
64
+ float left = k;
65
+ for (int i = 0; i < $MAX_LINES; i++) {
66
+ if (float(i) >= $count) break;
67
+ float packed = $lines[i / 4][i % 4];
68
+ float len = mod(floor(packed / 64.0), 128.0);
69
+ if (left < len || float(i) >= $count - 1.0) return vec2(packed, min(left, len));
70
+ left -= len;
71
+ }
72
+ return vec2(0.0);
73
+ }
74
+
75
+ Particle $main(uint id, float sel, Frame f) {
76
+ uint s = seedOf(id, 0x0071E5u);
77
+ float a = rnd(s);
78
+ float b = rnd(s);
79
+ float c = rnd(s);
80
+ float d = rnd(s);
81
+ float e = rnd(s);
82
+ Particle P = blank();
83
+
84
+ // Gathered as the section comes in, each particle on its own beat; then
85
+ // the content fades in over them, and they dim.
86
+ float gather = smoothstep(d * 0.2, d * 0.2 + 0.5, f.approach);
87
+ float settle = $reveal;
88
+ // Without text, the outline takes the text's share of the particles.
89
+ float edge = $count > 0.0 ? 0.3 : 0.8;
90
+
91
+ vec2 size = $rect.zw;
92
+ vec2 px;
93
+ vec3 col;
94
+ if (sel < edge) {
95
+ // The outline, just outside the element, which hides what's behind it.
96
+ px = size * 0.5 + rrectPoint(vec4(0.0, 0.0, size * 0.5 + $OUTSET), $radius + $OUTSET, a);
97
+ px += (vec2(c, e) - 0.5) * 1.5;
98
+ col = vec3(0.85, 0.88, 0.96) * mix(0.09, 0.025, settle) * (0.3 / edge);
99
+ } else if (sel < 0.8) {
100
+ // The text, a character at a time.
101
+ vec2 ch = $char(floor(a * $chars));
102
+ float indent = mod(ch.x, 64.0);
103
+ float row = floor(ch.x / 8192.0);
104
+ float x = (indent + ch.y + b) * $text.w;
105
+ px = vec2($text.x + min(x, $clip), $text.y + (row + 0.3 + c * 0.4) * $text.z);
106
+ col = vec3(0.6, 0.86, 0.94) * 0.08 * (1.0 - settle);
107
+ } else {
108
+ // Dust that never settles, drifting around the element.
109
+ px = vec2(a, b) * size;
110
+ gather = 0.0;
111
+ col = vec3(0.7, 0.75, 0.95) * 0.006;
112
+ }
113
+
114
+ // Loose: scattered around its place, nearer or deeper, in a slow current.
115
+ vec2 spread = gauss(c, e) * size * 0.15;
116
+ vec2 drift = curl(vec3(px * 0.004, f.time * 0.05 + d)).xy * 40.0;
117
+ vec2 loose = px + spread + drift;
118
+ float depth = $DEPTH * (1.0 + (e - 0.5) * 0.8);
119
+
120
+ P.pos = $place($rect.xy + mix(loose, px, gather), mix(depth, $DEPTH, gather));
121
+ P.col = col * mix(0.35, 1.0, gather);
122
+ P.size = 0.8;
123
+ return P;
124
+ }
125
+ `;
126
+ /** A corner radius in pixels; a percentage is of the shorter side. */
127
+ const radiusOf = (value, width, height) => {
128
+ const radius = Number.parseFloat(value) || 0;
129
+ return value.endsWith("%") ? radius * Math.min(width, height) / 100 : radius;
130
+ };
131
+ /**
132
+ * The element's box on screen, less the rise of the reveals it's in: once
133
+ * the element has risen into place, the outline is already there. Only a
134
+ * reveal's children are taken back, since they settle at `transform: none`;
135
+ * any other transform stays, as the element keeps it at rest.
136
+ */
137
+ const layoutBox = (el) => {
138
+ const box = el.getBoundingClientRect();
139
+ let x = 0;
140
+ let y = 0;
141
+ for (let node = el; node; node = node.parentElement) {
142
+ if (!node.parentElement?.hasAttribute("data-reveal")) continue;
143
+ const transform = getComputedStyle(node).transform;
144
+ if (!transform || transform === "none") continue;
145
+ const m = transform.slice(transform.indexOf("(") + 1, -1).split(",").map(Number);
146
+ const flat = transform.startsWith("matrix(");
147
+ x += m[flat ? 4 : 12] ?? 0;
148
+ y += m[flat ? 5 : 13] ?? 0;
149
+ }
150
+ return {
151
+ left: box.left - x,
152
+ top: box.top - y,
153
+ width: box.width,
154
+ height: box.height
155
+ };
156
+ };
157
+ /** A block's text, one entry per line. */
158
+ const linesOf = (pre) => (pre.textContent ?? "").replace(/\n$/, "").split("\n");
159
+ /** Packs the text lines of the `pre` blocks in the element, null without any. */
160
+ const measureText = (element, box) => {
161
+ const blocks = Array.from(element.querySelectorAll("pre"));
162
+ const first = blocks[0];
163
+ if (!first) return null;
164
+ const style = getComputedStyle(first);
165
+ const fontSize = Number.parseFloat(style.fontSize);
166
+ const padding = Number.parseFloat(style.paddingTop);
167
+ const pitch = Number.parseFloat(style.lineHeight) || (first.clientHeight - 2 * padding) / linesOf(first).length;
168
+ const inset = Number.parseFloat(style.paddingLeft);
169
+ const firstBox = first.getBoundingClientRect();
170
+ const top = firstBox.top - box.top + padding;
171
+ const packed = [];
172
+ let chars = 0;
173
+ for (const pre of blocks) {
174
+ const rect = pre === first ? firstBox : pre.getBoundingClientRect();
175
+ const firstRow = Math.round((rect.top - box.top + padding - top) / pitch);
176
+ const rows = Math.round((pre.clientHeight - 2 * padding) / pitch);
177
+ linesOf(pre).slice(0, rows).forEach((line, i) => {
178
+ const row = firstRow + i;
179
+ const indent = Math.min(63, line.length - line.trimStart().length);
180
+ const length = Math.min(127, line.trim().length);
181
+ if (length === 0 || row > 63 || packed.length >= MAX_LINES) return;
182
+ packed.push(indent + 64 * length + 8192 * row);
183
+ chars += length;
184
+ });
185
+ }
186
+ return {
187
+ text: [
188
+ firstBox.left - box.left + inset,
189
+ top,
190
+ pitch,
191
+ fontSize * .6
192
+ ],
193
+ clip: first.clientWidth - 2 * inset,
194
+ lines: Float32Array.from({ length: MAX_LINES }, (_, i) => packed[i] ?? 0),
195
+ count: packed.length,
196
+ chars
197
+ };
198
+ };
199
+ /**
200
+ * The GPU half of `outline`. It measures the element and its section when
201
+ * the page resizes, never per frame. Each frame, it moves the outline by the
202
+ * scroll position the scene read for the frame, which the page renders with,
203
+ * so the outline can't trail the element, and writes the gather and the
204
+ * reveal on the element.
205
+ */
206
+ function createShader(lines) {
207
+ const layout = {
208
+ element: null,
209
+ span: 0,
210
+ left: 0,
211
+ top: 0,
212
+ width: 0,
213
+ height: 0,
214
+ screen: [0, 0],
215
+ radius: 0,
216
+ text: null
217
+ };
218
+ let measured = false;
219
+ let gather = "";
220
+ let reveal = "";
221
+ let stop = null;
222
+ const measure = (canvas, root, index) => {
223
+ if (!("getBoundingClientRect" in canvas)) return;
224
+ measured = true;
225
+ layout.screen = [canvas.clientWidth, canvas.clientHeight];
226
+ const section = root.querySelectorAll("[data-stage]")[index];
227
+ const element = section?.querySelector("[data-outline]");
228
+ if (!section || !element) return;
229
+ const viewport = window.innerHeight;
230
+ const maxScroll = Math.max(1, document.documentElement.scrollHeight - viewport);
231
+ const rect = section.getBoundingClientRect();
232
+ const hold = sectionSpan(rect.top + window.scrollY, rect.height, viewport, maxScroll);
233
+ const length = hold.end - hold.start;
234
+ layout.span = index > 0 && length > 0 ? Math.min(1, FADE * viewport / length) : 0;
235
+ if (element !== layout.element) gather = reveal = "";
236
+ const screen = canvas.getBoundingClientRect();
237
+ const place = layoutBox(element);
238
+ Object.assign(layout, {
239
+ element,
240
+ left: place.left - screen.left,
241
+ top: place.top - screen.top + window.scrollY,
242
+ width: place.width,
243
+ height: place.height
244
+ });
245
+ const corner = getComputedStyle(element).borderTopLeftRadius;
246
+ layout.radius = radiusOf(corner, place.width, place.height);
247
+ layout.text = lines ? measureText(element, element.getBoundingClientRect()) : null;
248
+ };
249
+ const upload = ({ gl, get }) => {
250
+ gl.uniform2f(get("screen"), ...layout.screen);
251
+ gl.uniform1f(get("radius"), layout.radius);
252
+ const { text } = layout;
253
+ if (!text) {
254
+ gl.uniform1f(get("count"), 0);
255
+ return;
256
+ }
257
+ gl.uniform4f(get("text"), ...text.text);
258
+ gl.uniform1f(get("clip"), text.clip);
259
+ gl.uniform4fv(get("lines"), text.lines);
260
+ gl.uniform1f(get("count"), text.count);
261
+ gl.uniform1f(get("chars"), text.chars);
262
+ };
263
+ return {
264
+ glsl,
265
+ setup({ gl }, scene) {
266
+ if (!scene) return;
267
+ const observer = new ResizeObserver(() => measure(gl.canvas, scene.root, scene.index));
268
+ observer.observe(document.body);
269
+ const onResize = () => {
270
+ observer.unobserve(document.body);
271
+ observer.observe(document.body);
272
+ };
273
+ window.addEventListener("resize", onResize);
274
+ stop = () => {
275
+ observer.disconnect();
276
+ window.removeEventListener("resize", onResize);
277
+ };
278
+ },
279
+ teardown() {
280
+ stop?.();
281
+ stop = null;
282
+ },
283
+ update(uniforms, frame) {
284
+ const { gl, get } = uniforms;
285
+ if (measured) {
286
+ measured = false;
287
+ upload(uniforms);
288
+ }
289
+ gl.uniform4f(get("rect"), layout.left, layout.top - (frame.scrollY ?? 0), layout.width, layout.height);
290
+ const amount = frame.motion ? revealOf(frame.approach, frame.local, layout.span) : 1;
291
+ gl.uniform1f(get("reveal"), amount);
292
+ const { element } = layout;
293
+ if (!element) return;
294
+ const nextGather = gatherText(frame.approach);
295
+ const nextReveal = amount.toFixed(3);
296
+ if (nextGather !== gather) {
297
+ gather = nextGather;
298
+ element.dataset.gather = gather;
299
+ }
300
+ if (nextReveal !== reveal) {
301
+ reveal = nextReveal;
302
+ element.style.setProperty("--ux-reveal", reveal);
303
+ }
304
+ }
305
+ };
306
+ }
307
+ //#endregion
308
+ export { createShader, gatherOf, gatherText, revealOf };
package/dist/gl/engine.js CHANGED
@@ -3,6 +3,7 @@ import { approachOf, localOf, presenceOf } from "./stage.js";
3
3
  import { BASE_PARTICLES } from "./constants.js";
4
4
  import { BLOOM_DOWN_FRAG, BLOOM_PREFILTER_FRAG, BLOOM_UP_FRAG, COMPOSITE_FRAG, PARTICLE_FRAG, QUAD_VERT, TRAIL_FRAG } from "./glsl.js";
5
5
  import { composeParticleShader } from "./compose.js";
6
+ import { DEFAULT_LOOK } from "./formation.js";
6
7
  import { STACKED_QUERY } from "../layout.js";
7
8
  //#region src/gl/engine.ts
8
9
  const PARTICLES = {
@@ -61,6 +62,39 @@ function fitEye(stageView, aspect, out) {
61
62
  out[2] = stageView.target[2] + dz * k;
62
63
  return out;
63
64
  }
65
+ /**
66
+ * The squarest frame the desktop views are built for: `STACKED_QUERY` keeps
67
+ * them on screens no squarer than 5:4.
68
+ */
69
+ const MIN_FRAME_ASPECT = 5 / 4;
70
+ /**
71
+ * Fits a view to a canvas `aspect` wide. On a canvas wider than the frame
72
+ * (`frameAspect`, the frame's width over the canvas's height, and at least
73
+ * 5:4), it fits the view to the frame instead and narrows the lens shift to
74
+ * match, so the formation lands where a canvas as wide as the frame would
75
+ * draw it, centred. The vertical field of view stays, since the canvas is as
76
+ * tall as the frame.
77
+ */
78
+ function frameView(stageView, aspect, frameAspect, out) {
79
+ const scene = Math.max(frameAspect, MIN_FRAME_ASPECT);
80
+ const framed = aspect > scene;
81
+ fitEye(stageView, framed ? scene : aspect, out.eye);
82
+ out.shift[0] = framed ? stageView.shift[0] * scene / aspect : stageView.shift[0];
83
+ out.shift[1] = stageView.shift[1];
84
+ return out;
85
+ }
86
+ /**
87
+ * The trail's decay and the composite's colour fringe for a frame. Scrolling
88
+ * between formations lengthens the trail and widens the fringe by `boost`, as
89
+ * far as the look's `streak` lets it, and the intro rises through a long trail.
90
+ */
91
+ function trailOf(look, boost, intro) {
92
+ const speed = boost * look.streak;
93
+ return {
94
+ decay: Math.max(look.trail, speed, (1 - intro) * .75),
95
+ aberration: .012 + speed * .03
96
+ };
97
+ }
64
98
  const nextFrame = () => new Promise((resolve) => requestAnimationFrame(resolve));
65
99
  /**
66
100
  * Waits for the driver to finish compiling without ever blocking the main
@@ -138,7 +172,10 @@ async function createEngine(canvas, options) {
138
172
  get: (name) => uniform(particleProgram, `${formation.key}_${name}`)
139
173
  }));
140
174
  gl.useProgram(particleProgram.program);
141
- formationShaders.forEach((shader, i) => shader.setup?.(formationUniforms[i]));
175
+ formationShaders.forEach((shader, i) => shader.setup?.(formationUniforms[i], {
176
+ index: i,
177
+ root: options.root
178
+ }));
142
179
  const vao = gl.createVertexArray();
143
180
  gl.bindVertexArray(vao);
144
181
  gl.disable(gl.DEPTH_TEST);
@@ -174,6 +211,8 @@ async function createEngine(canvas, options) {
174
211
  deleteTarget(probe);
175
212
  }
176
213
  let quality = options.quality;
214
+ let frameWidth = options.frame;
215
+ let canvasHeight = 1;
177
216
  let particleCount = PARTICLES[quality];
178
217
  let renderScale = 1;
179
218
  let scene = null;
@@ -183,6 +222,7 @@ async function createEngine(canvas, options) {
183
222
  const dpr = Math.min(window.devicePixelRatio || 1, PIXEL_RATIO[quality]) * renderScale;
184
223
  const cssWidth = Math.max(1, canvas.clientWidth);
185
224
  const cssHeight = Math.max(1, canvas.clientHeight);
225
+ canvasHeight = cssHeight;
186
226
  const fit = Math.min(1, maxBuffer / Math.max(cssWidth * dpr, cssHeight * dpr));
187
227
  const width = Math.max(1, Math.round(cssWidth * dpr * fit));
188
228
  const height = Math.max(1, Math.round(cssHeight * dpr * fit));
@@ -217,16 +257,22 @@ async function createEngine(canvas, options) {
217
257
  0,
218
258
  0
219
259
  ];
220
- const eyeA = [
221
- 0,
222
- 0,
223
- 0
224
- ];
225
- const eyeB = [
226
- 0,
227
- 0,
228
- 0
229
- ];
260
+ const viewA = {
261
+ eye: [
262
+ 0,
263
+ 0,
264
+ 0
265
+ ],
266
+ shift: [0, 0]
267
+ };
268
+ const viewB = {
269
+ eye: [
270
+ 0,
271
+ 0,
272
+ 0
273
+ ],
274
+ shift: [0, 0]
275
+ };
230
276
  const rayDir = [
231
277
  0,
232
278
  0,
@@ -285,7 +331,8 @@ async function createEngine(canvas, options) {
285
331
  const blendLook = (stage, key) => {
286
332
  const a = Math.min(Math.floor(stage), stageCount - 1);
287
333
  const b = Math.min(a + 1, stageCount - 1);
288
- return lerp(formations[a].look[key], formations[b].look[key], smoothstep(0, 1, stage - a));
334
+ const valueOf = (k) => formations[k].look[key] ?? DEFAULT_LOOK[key];
335
+ return lerp(valueOf(a), valueOf(b), smoothstep(0, 1, stage - a));
289
336
  };
290
337
  const updateCamera = (stage, motion) => {
291
338
  const aspect = canvas.width / canvas.height;
@@ -295,13 +342,14 @@ async function createEngine(canvas, options) {
295
342
  const e = smoothstep(0, 1, stage - a);
296
343
  const va = stacked ? formations[a].views.mobile : formations[a].views.desktop;
297
344
  const vb = stacked ? formations[b].views.mobile : formations[b].views.desktop;
298
- fitEye(va, aspect, eyeA);
299
- fitEye(vb, aspect, eyeB);
300
- lerp3(eye, eyeA, eyeB, e);
345
+ const frameAspect = frameWidth === null ? Infinity : frameWidth / canvasHeight;
346
+ frameView(va, aspect, frameAspect, viewA);
347
+ frameView(vb, aspect, frameAspect, viewB);
348
+ lerp3(eye, viewA.eye, viewB.eye, e);
301
349
  lerp3(target, va.target, vb.target, e);
302
350
  fov = lerp(va.fov, vb.fov, e);
303
- shift[0] = lerp(va.shift[0], vb.shift[0], e);
304
- shift[1] = lerp(va.shift[1], vb.shift[1], e);
351
+ shift[0] = lerp(viewA.shift[0], viewB.shift[0], e);
352
+ shift[1] = lerp(viewA.shift[1], viewB.shift[1], e);
305
353
  const yaw = (motion ? Math.sin(time * .11) * .06 : 0) + pointerX * .1;
306
354
  const pitch = (motion ? Math.sin(time * .07) * .02 : 0) + pointerY * .05;
307
355
  let ox = eye[0] - target[0];
@@ -418,6 +466,7 @@ async function createEngine(canvas, options) {
418
466
  const shader = formationShaders[k];
419
467
  if (!shader.update) continue;
420
468
  const frame = {
469
+ index: k,
421
470
  stage,
422
471
  local: localOf(k, stage, local),
423
472
  approach: approachOf(k, stage),
@@ -425,6 +474,7 @@ async function createEngine(canvas, options) {
425
474
  time,
426
475
  dt,
427
476
  motion,
477
+ scrollY: input.scrollY,
428
478
  scrolled: input.scrolled
429
479
  };
430
480
  shader.update(formationUniforms[k], frame);
@@ -436,7 +486,10 @@ async function createEngine(canvas, options) {
436
486
  gl.drawArrays(gl.POINTS, 0, particleCount);
437
487
  }
438
488
  gl.disable(gl.BLEND);
439
- const decay = motion ? Math.max(blendLook(stage, "trail"), trailBoost, (1 - intro) * .75) : 0;
489
+ const { decay, aberration } = trailOf({
490
+ trail: blendLook(stage, "trail"),
491
+ streak: blendLook(stage, "streak")
492
+ }, trailBoost, intro);
440
493
  const previous = trails[current];
441
494
  current = 1 - current;
442
495
  const trail = trails[current];
@@ -446,7 +499,7 @@ async function createEngine(canvas, options) {
446
499
  bindTexture(1, previous.tex);
447
500
  gl.uniform1i(uniform(trailProgram, "uScene"), 0);
448
501
  gl.uniform1i(uniform(trailProgram, "uPrevious"), 1);
449
- gl.uniform1f(uniform(trailProgram, "uDecay"), decay);
502
+ gl.uniform1f(uniform(trailProgram, "uDecay"), motion ? decay : 0);
450
503
  drawQuad();
451
504
  const threshold = .55;
452
505
  const knee = .45;
@@ -487,7 +540,7 @@ async function createEngine(canvas, options) {
487
540
  gl.uniform1f(uniform(compositeProgram, "uBloomStrength"), .55 * blendLook(stage, "bloom"));
488
541
  gl.uniform1f(uniform(compositeProgram, "uExposure"), blendLook(stage, "exposure"));
489
542
  gl.uniform1f(uniform(compositeProgram, "uTime"), time);
490
- gl.uniform1f(uniform(compositeProgram, "uAberration"), .012 + trailBoost * .03);
543
+ gl.uniform1f(uniform(compositeProgram, "uAberration"), aberration);
491
544
  gl.uniform1f(uniform(compositeProgram, "uFade"), smoothstep(0, 1, fade));
492
545
  gl.uniform3fv(uniform(compositeProgram, "uBackground"), BACKGROUND);
493
546
  drawQuad();
@@ -526,6 +579,9 @@ async function createEngine(canvas, options) {
526
579
  },
527
580
  viewProjection,
528
581
  render,
582
+ setFrame(frame) {
583
+ frameWidth = frame;
584
+ },
529
585
  resize,
530
586
  shock(ndcX, ndcY) {
531
587
  if (lost) return;
@@ -543,6 +599,7 @@ async function createEngine(canvas, options) {
543
599
  },
544
600
  destroy() {
545
601
  canvas.removeEventListener("webglcontextlost", onLost);
602
+ formationShaders.forEach((shader) => shader.teardown?.());
546
603
  if (gl.isContextLost()) return;
547
604
  for (const p of programs) {
548
605
  p.shaders.forEach((s) => gl.deleteShader(s));
@@ -556,4 +613,4 @@ async function createEngine(canvas, options) {
556
613
  };
557
614
  }
558
615
  //#endregion
559
- export { createEngine, fitEye };
616
+ export { createEngine, fitEye, frameView, trailOf };
@@ -4,7 +4,8 @@ const DEFAULT_LOOK = {
4
4
  bloom: 1,
5
5
  trail: 0,
6
6
  exposure: 1,
7
- reflect: 0
7
+ reflect: 0,
8
+ streak: 1
8
9
  };
9
10
  /** Checks a formation and fills in its defaults. Anchor ids become `key:id`. */
10
11
  function defineFormation(def) {
@@ -36,4 +37,4 @@ function mergeViews(base, override) {
36
37
  };
37
38
  }
38
39
  //#endregion
39
- export { defineFormation, mergeViews };
40
+ export { DEFAULT_LOOK, defineFormation, mergeViews };
@@ -24,6 +24,12 @@ export interface FormationLook {
24
24
  exposure: number;
25
25
  /** Strength of the mirror-floor reflection. */
26
26
  reflect: number;
27
+ /**
28
+ * How much scrolling between formations lengthens the trail and widens the
29
+ * colour fringe, 0 (none) to 1. A formation pinned to the page turns it off,
30
+ * so a fast scroll leaves no ghost copies of it behind. Defaults to 1.
31
+ */
32
+ streak?: number;
27
33
  }
28
34
  /** Where a formation stands in the scroll. */
29
35
  export interface FormationProgress {
@@ -39,6 +45,19 @@ export interface FormationProgress {
39
45
  time: number;
40
46
  }
41
47
  export interface FormationFrame extends FormationProgress {
48
+ /**
49
+ * The formation's place in the scene, which is also its `[data-stage]`
50
+ * section's. The engine always sets it; it's optional so frames written
51
+ * by hand, in tests, still type-check.
52
+ */
53
+ index?: number;
54
+ /**
55
+ * The page's scroll position, which the scene reads before it writes
56
+ * anything in the frame. Read it here rather than from `window.scrollY`,
57
+ * which forces the browser to restyle the page after those writes. The
58
+ * engine always sets it, like `index`.
59
+ */
60
+ scrollY?: number;
42
61
  /** Seconds since the last frame, whether or not motion is enabled. */
43
62
  dt: number;
44
63
  motion: boolean;
@@ -70,10 +89,25 @@ export interface FormationShader {
70
89
  * [0, 1) across the particles, to split them between the parts of a formation.
71
90
  */
72
91
  glsl: string;
73
- /** Uploads uniforms that never change. The particle program is bound. */
74
- setup?(uniforms: Uniforms): void;
92
+ /**
93
+ * Uploads uniforms that never change, and starts anything the formation
94
+ * listens to. The particle program is bound. `scene` holds the formation's
95
+ * `index` and the scene's `root`, so its section is
96
+ * `root.querySelectorAll("[data-stage]")[index]`. The engine always passes
97
+ * it; it's optional so calls written by hand, in tests, still type-check.
98
+ */
99
+ setup?(uniforms: Uniforms, scene?: {
100
+ index: number;
101
+ root: HTMLElement;
102
+ }): void;
75
103
  /** Uploads per-frame uniforms. The particle program is bound. */
76
104
  update?(uniforms: Uniforms, frame: FormationFrame): void;
105
+ /**
106
+ * Stops what `setup` started, like observers and listeners. The scene
107
+ * calls it when it's destroyed and when it loses its WebGL context, before
108
+ * it loads the shaders again for a restored one.
109
+ */
110
+ teardown?(): void;
77
111
  }
78
112
  export interface FormationDef {
79
113
  /** Unique within a scene. Letters and digits only: it namespaces GLSL identifiers. */
@@ -0,0 +1,21 @@
1
+ import { Formation, FormationShader } from "./types.js";
2
+ //#region src/gl/wrap.d.ts
3
+ /** Changes a formation's shader once it loads, like the GLSL or its `update()`. */
4
+ export declare const editShader: (formation: Formation, edit: (shader: FormationShader) => FormationShader) => Formation;
5
+ /**
6
+ * Renames the formation's `$main` to `$<inner>` and appends a new `$main`
7
+ * with the given body, which calls `$<inner>(id, sel, f)`.
8
+ */
9
+ export declare const wrapMain: (formation: Formation, inner: string, body: string) => Formation;
10
+ /**
11
+ * Holds a formation at a fixed `local` progress, whatever the scroll.
12
+ *
13
+ * A section plays its formation through (`local` 0 → 1) while it fills the
14
+ * screen, give or take `HOLD_MARGIN`. The hero starts at the top of the page,
15
+ * so it only gets the first quarter screen of scroll: a formation that moves
16
+ * with `local`, like `plates`, would rush to its end state the moment the
17
+ * page scrolls. Held, it stays put while it morphs into the next formation.
18
+ * Anchors and `update()` see the same `local`.
19
+ */
20
+ export declare function hold(formation: Formation, local: number): Formation;
21
+ //#endregion
@@ -0,0 +1,54 @@
1
+ import { glslFloat } from "./glsl.js";
2
+ //#region src/gl/wrap.ts
3
+ const MAIN = /\bParticle\s+\$main\s*\(/;
4
+ /** Changes a formation's shader once it loads, like the GLSL or its `update()`. */
5
+ const editShader = (formation, edit) => ({
6
+ ...formation,
7
+ shader: () => formation.shader().then(edit)
8
+ });
9
+ /**
10
+ * Renames the formation's `$main` to `$<inner>` and appends a new `$main`
11
+ * with the given body, which calls `$<inner>(id, sel, f)`.
12
+ */
13
+ const wrapMain = (formation, inner, body) => editShader(formation, (shader) => {
14
+ if (!MAIN.test(shader.glsl)) throw new Error(`Formation "${formation.key}" has no Particle $main() to wrap.`);
15
+ return {
16
+ ...shader,
17
+ glsl: `${shader.glsl.replace(MAIN, `Particle $${inner}(`)}
18
+ Particle $main(uint id, float sel, Frame f) {
19
+ ${body}
20
+ }
21
+ `
22
+ };
23
+ });
24
+ /**
25
+ * Holds a formation at a fixed `local` progress, whatever the scroll.
26
+ *
27
+ * A section plays its formation through (`local` 0 → 1) while it fills the
28
+ * screen, give or take `HOLD_MARGIN`. The hero starts at the top of the page,
29
+ * so it only gets the first quarter screen of scroll: a formation that moves
30
+ * with `local`, like `plates`, would rush to its end state the moment the
31
+ * page scrolls. Held, it stays put while it morphs into the next formation.
32
+ * Anchors and `update()` see the same `local`.
33
+ */
34
+ function hold(formation, local) {
35
+ const at = (progress) => ({
36
+ ...progress,
37
+ local
38
+ });
39
+ const held = wrapMain(formation, "held", ` f.local = ${glslFloat(local)};
40
+ return $held(id, sel, f);`);
41
+ return {
42
+ ...editShader(held, (shader) => shader.update ? {
43
+ ...shader,
44
+ update: (uniforms, frame) => shader.update?.(uniforms, at(frame))
45
+ } : shader),
46
+ anchors: formation.anchors.map((anchor) => ({
47
+ ...anchor,
48
+ place: (progress, out) => anchor.place(at(progress), out),
49
+ ...anchor.render && { render: (el, progress) => anchor.render?.(el, at(progress)) }
50
+ }))
51
+ };
52
+ }
53
+ //#endregion
54
+ export { editShader, hold, wrapMain };
package/dist/index.d.ts CHANGED
@@ -7,5 +7,6 @@ import { BASE_PARTICLES, FLOOR_Y } from "./gl/constants.js";
7
7
  import { defineFormation, mergeViews } from "./gl/formation.js";
8
8
  import { glslArray, glslFloat, glslVec } from "./gl/glsl.js";
9
9
  import { HOLD_MARGIN, SectionSpan, approachOf, localOf, presenceOf, progressOf, sectionSpan, stageAt, stepAt } from "./gl/stage.js";
10
+ import { editShader, hold, wrapMain } from "./gl/wrap.js";
10
11
  import { STACKED_QUERY } from "./layout.js";
11
- export { type AnchorDef, BASE_PARTICLES, type Experience, type ExperienceOptions, type ExperienceState, FLOOR_Y, type Formation, type FormationDef, type FormationFrame, type FormationLook, type FormationOptions, type FormationProgress, type FormationShader, type FormationViews, type GlStatus, HOLD_MARGIN, type Mat4, type PackedShapes, STACKED_QUERY, type SectionSpan, type ShaderPart, type Shape, type StageView, type Uniforms, type Vec2, type Vec3, type Vec4, approachOf, clamp, composeParticleShader, createExperience, damp, defineFormation, glslArray, glslFloat, glslVec, initialExperienceState, lerp, lerp3, localOf, mergeViews, namespaceGlsl, packShapes, presenceOf, progressOf, projectToScreen, sectionSpan, smoothstep, stageAt, stepAt };
12
+ export { type AnchorDef, BASE_PARTICLES, type Experience, type ExperienceOptions, type ExperienceState, FLOOR_Y, type Formation, type FormationDef, type FormationFrame, type FormationLook, type FormationOptions, type FormationProgress, type FormationShader, type FormationViews, type GlStatus, HOLD_MARGIN, type Mat4, type PackedShapes, STACKED_QUERY, type SectionSpan, type ShaderPart, type Shape, type StageView, type Uniforms, type Vec2, type Vec3, type Vec4, approachOf, clamp, composeParticleShader, createExperience, damp, defineFormation, editShader, glslArray, glslFloat, glslVec, hold, initialExperienceState, lerp, lerp3, localOf, mergeViews, namespaceGlsl, packShapes, presenceOf, progressOf, projectToScreen, sectionSpan, smoothstep, stageAt, stepAt, wrapMain };
package/dist/index.js CHANGED
@@ -6,5 +6,6 @@ import { packShapes } from "./gl/shapes.js";
6
6
  import { glslArray, glslFloat, glslVec } from "./gl/glsl.js";
7
7
  import { composeParticleShader, namespaceGlsl } from "./gl/compose.js";
8
8
  import { defineFormation, mergeViews } from "./gl/formation.js";
9
+ import { editShader, hold, wrapMain } from "./gl/wrap.js";
9
10
  import { STACKED_QUERY } from "./layout.js";
10
- export { BASE_PARTICLES, FLOOR_Y, HOLD_MARGIN, STACKED_QUERY, approachOf, clamp, composeParticleShader, createExperience, damp, defineFormation, glslArray, glslFloat, glslVec, initialExperienceState, lerp, lerp3, localOf, mergeViews, namespaceGlsl, packShapes, presenceOf, progressOf, projectToScreen, sectionSpan, smoothstep, stageAt, stepAt };
11
+ export { BASE_PARTICLES, FLOOR_Y, HOLD_MARGIN, STACKED_QUERY, approachOf, clamp, composeParticleShader, createExperience, damp, defineFormation, editShader, glslArray, glslFloat, glslVec, hold, initialExperienceState, lerp, lerp3, localOf, mergeViews, namespaceGlsl, packShapes, presenceOf, progressOf, projectToScreen, sectionSpan, smoothstep, stageAt, stepAt, wrapMain };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uxfront/scene",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "The scroll-driven WebGL particle scene behind the uxfront.com family of homepages: a pluggable formation pipeline, a formation catalog and a framework-agnostic scroll controller.",
5
5
  "keywords": [
6
6
  "particles",