@occluze/umber 0.2.0 → 0.2.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.
package/docs/AI.md ADDED
@@ -0,0 +1,2660 @@
1
+ <!-- Generated by scripts/docs.mjs from docs/ai/*.md and docs/snippets/. Edit those files, not this one. -->
2
+
3
+ # Umber: the full reference (for humans and AI assistants)
4
+
5
+ > Paste this whole file into your AI assistant before asking it to write code for a site that uses Umber. It is also the complete reference for humans.
6
+
7
+ Umber is a **DOM-to-WebGL engine**. You tag DOM elements (images, video, text, shader areas); Umber draws them as GPU planes on one canvas and keeps them lined up with the page while you scroll, resize or change pages. It also gives your own three.js scenes sizing, DPR, an on-demand loop, cleanup and DOM-to-3D maths.
8
+
9
+ Umber is a product of Occluze, a product of R—K.
10
+
11
+ **Umber needs nothing else.** No GSAP, no Lenis, no Barba: it has its own `requestAnimationFrame` loop (which sleeps when nothing moves) and its own small timing (duration, delay, cubic-bezier eases). It never reads `window.gsap`, `window.Lenis` or `window.barba`.
12
+
13
+ **It works next to them and controls none of them.** You set up Barba, Lenis and GSAP the way their own docs show. Umber never intercepts links, never touches history or scroll restoration, never creates a scroller and never changes a library's global settings. (The one opt-in exception: the `scroll` module is a smooth scroller, for sites that want one without a library; see "Smooth scrolling".) It finds page changes in the DOM itself (one `MutationObserver`), and the first page load takes exactly the same path. A Lenis instance can be passed in as a read-only scroll source.
14
+
15
+ **It is an engine, not an effects library.** Umber ships no effects. An effect is a few lines of GLSL you write and register with `gl.effect()`; the examples gallery (`examples/`) shows how, with reveals, a dissolve, a hover lens, a velocity bend, parallax and grain written as plain example code.
16
+
17
+ **The DOM stays the truth.** The real `<img alt>`, `<video>` and text stay in the page for search engines, screen readers and layout. Each turns invisible only after the GPU has painted the same pixels, and shows again whenever GL can't run (no WebGL2, a phone by default, Save-Data or a 2G connection, a lost context, a load that is too slow).
18
+
19
+ ## The 30-second setup
20
+
21
+ Webflow (**Site settings > Custom code**), or the same tags in any HTML page:
22
+
23
+ ```html
24
+ <!-- Head code: the GL handshake CSS -->
25
+ <link rel="stylesheet" href="https://umber.occluze.com/umber@0.2.1/umber.css">
26
+
27
+ <!-- Footer code. Umber needs no other library; your own Lenis / Barba / GSAP tags (if the
28
+ site uses them) can sit before or after it. -->
29
+ <script src="https://umber.occluze.com/umber@0.2.1/umber.js"></script>
30
+ <!-- Optional modules, only if the site uses them (always the same version as umber.js):
31
+ <script src="https://umber.occluze.com/umber@0.2.1/modules/scrub.js"></script> scroll-scrubbed video (data-gl-scrub)
32
+ <script src="https://umber.occluze.com/umber@0.2.1/modules/handoff.js"></script> image flights across page loads (data-gl-id, no router)
33
+ <script src="https://umber.occluze.com/umber@0.2.1/modules/router.js"></script> Umber's own page router with transitions (instead of Barba)
34
+ <script src="https://umber.occluze.com/umber@0.2.1/modules/input.js"></script> gl.drag, gl.trail, gl.press...
35
+ <script src="https://umber.occluze.com/umber@0.2.1/modules/scroll.js"></script> smooth scrolling (gl.scroll), instead of a scroll library
36
+ <script src="https://umber.occluze.com/umber@0.2.1/modules/debug.js"></script> HUD while you build; never on the live site -->
37
+ <script>
38
+ const gl = Umber.createGL(); // every device; { devices: "desktop" } or { media: "(min-width: 900px)" } turns some off
39
+ // gl.effect("dissolve", { ... }); // the effects this site uses: yours to write
40
+ </script>
41
+ ```
42
+
43
+ Umber needs no library. The examples load Lenis 1.3.23, @barba/core 2.10.3 and three.js 0.178.0 themselves; Umber only reads a Lenis instance and only sizes and calls the three.js renderer you hand it, so other Lenis 1.x, Barba 2.x and three.js versions work the same way. Pin exact versions on live sites.
44
+
45
+ Bundled sites (Vite, Astro, Next) install the private npm package instead:
46
+
47
+ ```js
48
+ // npm install @occluze/umber@0.2.1 (docs/npm.md)
49
+ import { createGL } from "@occluze/umber";
50
+ import "@occluze/umber/umber.css";
51
+ import { Scrub } from "@occluze/umber/scrub"; // optional module
52
+
53
+ const gl = createGL({ modules: [Scrub] }); // client code only; on the server it does nothing
54
+ ```
55
+
56
+ - `umber.js` is a plain script that sets `window.Umber = { version, createGL, math, use }`. It downloads no GL code until the device passes the checks **and** the page has a `[data-gl]` element (or the code calls `gl.renderer()`, `gl.view()`, `gl.target()` or `gl.preload()`); then it loads `chunks/gl.js` from its own folder (and, only when the page needs them, `chunks/shapes.js` for GL elements cut, turned or tilted by CSS or by an animation, `chunks/text.js` for `data-gl="text"`, `chunks/layers.js` for three.js on Umber's canvas, and the other chunks listed under Loading the engine). `gl.attach()` loads only `chunks/views.js`. `gl.inspect()` and some warnings load `chunks/inspect.js`.
57
+ - `umber.css` goes in `<head>` on every page: it holds the canvas host and the rules that hide a DOM image only once GL has drawn it. A page without it (a 404 template a router swaps in) keeps GL off, with a warning, until it is back; the canvas is hidden meanwhile, so it takes no room in that page.
58
+ - Load `umber.js` before the code that calls `Umber.createGL()`. Its place relative to Lenis, Barba or GSAP tags does not matter.
59
+ - Call `createGL()` **once per visit**, not per page. A second call warns and returns the first engine.
60
+
61
+ ## createGL(options)
62
+
63
+ ```js
64
+ const gl = Umber.createGL(); // zero config: window scroll, own loop, every device
65
+
66
+ const gl = Umber.createGL({ // every option is optional
67
+ scroll: lenis, // read-only scroll source: a Lenis instance, an element, { y, velocity }. Default: window (or <body> when it is the scroller)
68
+ loop: "auto", // "auto": Umber's own rAF loop, asleep when idle. false: call gl.render(time) yourself
69
+ devices: "all", // "all" | "desktop" (hover + fine pointer + >= 768px; or data-gl-devices="desktop" on <body>) | (env) => boolean | false (anything else: "desktop", with a warning)
70
+ media: "(min-width: 900px)", // optional: effects only where this CSS media query matches (or data-gl-media on <body>)
71
+ dpr: { high: 2, mid: 1.5, low: 1 }, // or a max (2), or [min, max]. Below the screen's own (a 3x phone at "mid" 1.5) GL text is softer than DOM text: speed over sharpness
72
+ pixelBudget: 12e6, // max canvas pixels (w * h * dpr^2)
73
+ adaptive: true, // lower the resolution only while the GPU can't keep up
74
+ reducedMotion: "static",// "static": draw without motion (uTime stands still); "off": GL off for reduced motion
75
+ respectSaveData: true, // GL off when the browser asks to save data (Save-Data, prefers-reduced-data), or on a 2G connection
76
+ layer: "over", // the canvas over the page ("over") or behind it ("under")
77
+ zIndex: 1, // z-index of the host Umber makes (default 1 over, -1 under)
78
+ host: "[data-gl-host]", // where the canvas goes (default: a [data-gl-host] already in the page, else a fixed host Umber makes)
79
+ designer: false, // run inside the Webflow Designer / Editor too
80
+ base: undefined, // folder the chunks (chunks/gl.js...) load from (default: next to umber.js)
81
+ modules: [], // optional modules: [Scrub], [[Scrub, { cacheMB: 64 }]]
82
+ busy: undefined, // a selector on <html> a router sets during a page change ("html.is-changing"): gl.transition() without hooks
83
+ debug: false, // true: debug notes in the console; { hud, outlines, markers, cost } for modules/debug.js
84
+ warnings: true, // false silences warnings (errors always show)
85
+ });
86
+ ```
87
+
88
+ ## Is GL on? (three ways to know)
89
+
90
+ - **Properties:** `await gl.ready` is `true` once GL draws this page's `[data-gl]` elements, `false` when it chose not to or the page has none. `gl.enabled` is `false` when GL is off for this visit, and `gl.reason` says why: `"device"`, `"no-webgl2"`, `"save-data"`, `"reduced-motion"`, `"forced-colors"`, `"editor"`, `"disabled"` (`devices: false`, `data-gl-disable` or `?umber=off`), `"context"`, `"load-failed"`, `"load-timeout"`, `"unlicensed"` (this domain isn't on an Umber licence: list it under Umber at occluze.com), `"context-lost"` (the WebGL context was lost too often), `"error"` (an error inside a GL frame), `"server"` or `"destroyed"`.
91
+ - **Events:** `gl.on("ready" | "lost" | "restored" | "destroy", fn)`. Every `on()` returns its `off()`. The same events also go to `document` as DOM events, with the payload as `event.detail`, for code that has no `gl` at hand: `document.addEventListener("umber:ready", (e) => ...)` (`umber:ready`, `umber:lost`, `umber:restored`, `umber:destroy`, `umber:off`, `umber:fallback`). `gl.on("off", ({ reason }) => ...)`: GL is off for this visit, from the start or later; `gl.on("fallback", ({ el, reason }) => ...)`: an element shows its DOM instead of GL (see "Reporting to your own analytics" in the debugging section). `gl.on("added", (roots) => ...)` hands over the roots of what entered the page, once per frame (a router's new page; `<html>` on the first scan): what `gl.drag(selector)` binds again on. Listening keeps the DOM watch on, also with GL off.
92
+ - **CSS hooks:** `html.has-gl` while GL may run; per element `data-gl-status="loading | ready | error"`. Elements Umber drew are `ready`; `error` means it gave up and the DOM shows.
93
+
94
+ ```js
95
+ const gl = Umber.createGL();
96
+ if (await gl.ready) console.log("GL is drawing");
97
+ else console.log("plain DOM:", gl.reason);
98
+ ```
99
+
100
+ ## The rules (read these first)
101
+
102
+ 1. **One engine per visit.** `createGL()` once, in code that runs once (not in a Barba hook). `gl.destroy()` only to start fresh.
103
+ 2. **Bring your own libraries.** Umber never loads Lenis, Barba, GSAP or three.js. Load them yourself, as their docs say. Pass a Lenis instance with `scroll: lenis` so planes follow its smooth position.
104
+ 3. **Mark elements, don't call Umber per page.** Planes appear when a `[data-gl]` element enters the DOM and go when it leaves. Barba, a CMS "load more", a framework re-render: all the same.
105
+ 4. **The page must look right without GL.** GL runs on every device by default (a site can keep it to desktops), and is off for Save-Data (or a 2G connection), no WebGL2 and High Contrast. Never hide content for an effect; GL draws over the real `<img>` and text.
106
+ 5. **Effects are yours.** `data-gl-effect="name"` needs `gl.effect("name", {...})`, written by you (see Writing effects). An unknown name warns and draws the plane without it.
107
+ 6. **Everything Umber exposes is a plain `{ value }`.** Tween uniforms with Umber's own `plane.tween()`, with GSAP, Motion or a line of your own code.
108
+ 7. **Read the warnings.** Every Umber message starts with `[umber]`, shows once, and says how to fix it. `gl.inspect(el)` tells you why one element is or is not drawn.
109
+
110
+ ---
111
+
112
+ ## With Barba and Lenis (plain code, nothing to hook)
113
+
114
+ Set up Lenis and Barba exactly as their own docs show. Start Umber once. That is the whole integration:
115
+
116
+ ```js
117
+ // site.js: plain Lenis, plain Barba, Umber next to them.
118
+ const lenis = new Lenis({ autoRaf: true }); // your Lenis, your loop
119
+ const gl = Umber.createGL({ scroll: lenis }); // read-only: position + velocity
120
+
121
+ gl.effect("dissolve", { /* your own effect (examples/effects/dissolve.js is one) */ });
122
+
123
+ barba.init({
124
+ transitions: [{
125
+ leave: ({ current }) => current.container.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 400, fill: "forwards" }).finished,
126
+ enter: ({ next }) => next.container.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 400 }).finished,
127
+ }],
128
+ });
129
+ barba.hooks.after(() => lenis.scrollTo(0, { immediate: true })); // Barba and Lenis are yours to wire
130
+
131
+ // Optional, only if you want them (examples/transitions/transition.js uses them):
132
+ // let release = () => {};
133
+ // barba.hooks.before(() => { release = gl.hold(); gl.live(true); });
134
+ // barba.hooks.after(() => { release(); gl.live(1); });
135
+ ```
136
+
137
+ What Umber does by itself, with no Barba hook:
138
+
139
+ - **Page swaps.** One `MutationObserver` sees Barba's new container arrive and the old one leave. New `[data-gl]` elements get planes; planes whose element left are destroyed and their GPU memory freed. The first page load takes the same path, so there is nothing to call on load either.
140
+ - **Moving containers.** For 1.5 s after planes arrive or leave, Umber measures every visible plane every frame, so a container that slides in by `transform` is followed. CSS transitions and animations on a plane's parents are followed for as long as they run, and a style or class change on a parent (a GSAP tween writes `style`) re-measures the planes inside it.
141
+ - **Lenis.** With `createGL({ scroll: lenis })` Umber reads the scroll position Lenis writes to the page (or to its wrapper) in each frame's measure phase, as an absolute position, plus Lenis's `velocity` and its `scroll` event. It never adds up scroll deltas, so it does not matter whose `requestAnimationFrame` runs first: Lenis's `autoRaf`, a `gsap.ticker` callback or Umber's own loop. Umber never calls `lenis.raf()`, `start()`, `stop()` or `scrollTo()`.
142
+ - **Lenis made later** (in Barba's `once()`, after a preloader): `createGL()` runs once, first, so it can't take the instance yet. Leave `scroll` out: Lenis scrolls the window itself, and Umber reads that and works out the speed. For Lenis's own velocity, pass getters over a variable you fill in later (Umber also wakes on the window's scroll by itself, which Lenis moves):
143
+
144
+ ```js
145
+ let lenis = null;
146
+ const gl = Umber.createGL({ scroll: { y: () => window.scrollY, velocity: () => (lenis ? lenis.velocity : 0) } });
147
+ barba.init({ transitions: [{ once() { lenis = new Lenis({ autoRaf: true }); } }] });
148
+ ```
149
+
150
+ - **Any scroller.** `scroll: document.querySelector(".scroller")` follows an element that scrolls instead of the window. `scroll: { y: () => myY, velocity: () => myV }` follows anything else (velocity is optional: Umber works it out). Umber can't hear such a source change unless the window scrolls too (Umber always listens to the window's scroll): call `gl.wake()` when your scroller moves, or use `createGL({ loop: false })` and call `gl.render(time)` from its loop.
151
+
152
+ ### Optional one-liners (only if you want them)
153
+
154
+ ```js
155
+ let release = () => {};
156
+ barba.hooks.before(() => {
157
+ release = gl.hold(); // the new page's plays (reveals) wait...
158
+ gl.live(true); // ...and every visible plane is measured every frame
159
+ });
160
+ barba.hooks.after(() => {
161
+ release(0.1); // ...until 0.1 s after the swap
162
+ gl.live(1); // one more second, then back to "measure on change"
163
+ });
164
+ ```
165
+
166
+ - `gl.hold()` holds every play (an effect's `play` uniform, such as a reveal) back and returns `release(delaySeconds?)`. Holds stack. `gl.hold(promise)` releases when the promise settles.
167
+ - `gl.live(true | false | seconds)` measures every visible plane every frame. Use it while something moves the page that Umber cannot see (a WebGL-driven layout, a `transform` set by your own rAF loop).
168
+ - **A new page that slides over the old one.** GL draws on one canvas above the page, so an old page's GL image shows through the new container while that container covers it (the DOM would hide it). A fade is fine (GL follows the container's opacity). For a cover transition, hand the old images back to the DOM when the cover starts: `barba.hooks.leave(({ current }) => gl.planes(current.container).forEach((p) => p.destroy()))`. The DOM image is then the one being covered, exactly as without GL.
169
+ - **Planes taking part in the transition:** `gl.planes(current.container)` lists the old page's planes. Play them back to 0 in `leave` and Barba waits for them, because `plane.play()` and `plane.tween()` return an awaitable tween. `examples/transitions/transition.js` does this.
170
+ - **The same image on both pages (`data-gl-id`).** Give it the same `data-gl-id` on both pages and it flies from its old place to its new one instead of fading out and in. It works without hooks. Barba adds the new container below the old one, and Umber flies only to an image on the first screen, so take the old page out of the layout once it has left, or stack the containers. The Barba recipe in the next section does both in four lines, with `gl.transition()` (it holds plays and measures live too, so it replaces the two hooks above). Options on the element you go to: `data-gl-morph-duration` (seconds, default 1) and `data-gl-morph-ease`, also as `--gl-morph-duration` / `--gl-morph-ease` in CSS (on `:root` for the whole site). Other routers: the next section.
171
+
172
+ ### With GSAP
173
+
174
+ GSAP is not needed, but it works with everything Umber exposes, because every uniform is a plain `{ value }`:
175
+
176
+ ```js
177
+ const uShow = gl.plane(el)?.uniforms.uShow; // null with GL off: guard it
178
+ if (uShow) gsap.to(uShow, { value: 1, duration: 1.2, ease: "expo.out" });
179
+ if (uShow) gsap.to(uShow, { value: 1, scrollTrigger: { trigger: el, scrub: true } });
180
+ ```
181
+
182
+ Driving Umber from `gsap.ticker` instead of its own loop (where you create it):
183
+
184
+ ```js
185
+ const gl = Umber.createGL({ loop: false });
186
+ gsap.ticker.add((time) => gl.render(time * 1000)); // ms, like requestAnimationFrame
187
+ ```
188
+
189
+ Umber never calls `gsap.ticker.lagSmoothing()`, `gsap.defaults()` or `CustomEase.create()`. Its own lag smoothing (a long gap between frames counts as 33 ms, so a reveal half-way when the tab was hidden is still half-way) lives in its own loop only.
190
+
191
+ ---
192
+
193
+ ## Any router: page transitions and flying images
194
+
195
+ Umber works next to any router: Barba, Swup, Taxi, Highway, Turbo, Astro's client router, htmx `hx-boost`, Next, Nuxt, or a page that swaps its own content inside `document.startViewTransition()`. It never hooks into one and never reads one: it sees the page change in the DOM. Set the router up the way its docs show and start Umber once. A site that has no router yet can use Umber's own instead (`modules/router.js`, next sections): it needs none of the lines below.
196
+
197
+ What Umber does by itself, with no hook:
198
+
199
+ - **The whole `<body>` replaced** (Turbo, Astro, Swup with `body` as its container) or **everything inside it** (htmx `hx-boost`). Umber's canvas leaves with the old body. Umber puts it back right in the `MutationObserver` callback, before that frame paints, and draws the new page in that same frame, so no frame shows the page without GL. A site's own `[data-gl-host]` on every page takes the canvas over; one that is missing on the new page is put back, with a warning that names the fix (`data-turbo-permanent`, `transition:persist`, `hx-preserve`).
200
+ - **Cached copies of a page** (Turbo's cache, htmx's history, a back button): they bring a blank copy of the canvas and Umber's old marks. The copy is removed (one canvas stays) and the marks are taken over by the new planes in the same frame.
201
+ - **`<html>`'s attributes wiped** (Astro copies the new page's): `has-gl` comes back.
202
+ - **The same image on both pages (`data-gl-id`).** It flies from its old place to its new one, whatever order the router swaps in:
203
+ - both pages in the DOM at once (Barba with `sync: true`, a Vue `<Transition>` with no `mode`): it flies from where it is. When the new page sits below the old one (not on the first screen yet), it flies only inside a page change (`gl.transition()` or `createGL({ busy })`): Umber then asks again once the old page leaves. With no hook it reveals on scroll as usual;
204
+ - one swap (Swup, Turbo, Astro, htmx, Next): from where it was last drawn; an image its page had already faded out flies in from transparent;
205
+ - the old page removed before the new one is in (Taxi, Nuxt `out-in`, a Next loading state, a filter grid re-ordered): an on-screen image whose element left waits 3 s for its id to come back (at most 8 wait; each keeps a texture), then is freed;
206
+ - the element it flies to replaced mid-flight (Turbo shows a cached copy, then the real page; a framework re-mounts it): the flight goes on from where it is.
207
+ - **Thumbnail to hero.** A small and a large copy of one picture (`srcset` candidates of the same image, or the same `src`) fly with the large copy's texture as soon as it is on the GPU: no upscaled thumbnail once the real one is there, and nothing pops when it lands.
208
+
209
+ Options on the element you go to: `data-gl-morph-duration` (seconds, default 1) and `data-gl-morph-ease`, also as `--gl-morph-duration` / `--gl-morph-ease` in CSS (on `:root` for the whole site). Only an element on the new page's first screen is flown to; one below it reveals on scroll as usual. While the image is frozen and its old element still shows, it moves with the page when the visitor scrolls (a wheel's momentum right after the click); on a fixed or sticky element it moves only as far as that element does.
210
+
211
+ ### gl.transition(): one line where the change starts, one where it ends
212
+
213
+ Optional (the recipes below show where it goes for each router). With it, Umber knows the page change from its start: plays (reveals) wait, every plane is measured every frame, and an image that will fly freezes as soon as the next page is known, instead of fading out with the old one.
214
+
215
+ ```js
216
+ let end = () => {};
217
+ // where the router starts a page change:
218
+ end = gl.transition(); // or gl.transition(next): the next page, when the router has it
219
+ // where it is done:
220
+ end(); // end(0.2): plays start 0.2 s later; end(promise): when it settles
221
+ await end(); // also: resolves once the image landed and the new page draws (4 s at most)
222
+ ```
223
+
224
+ - `next` is the next page in any form the router hands over: its HTML string, a parsed `Document`, its container element, Barba's cached `{ html }`, or a promise of one. A `Document` or element is matched exactly, and the `srcset` candidate the browser will pick there (its `sizes` at this screen and DPR) is fetched at once, so the hero's texture is ready when the image lands.
225
+ - A second `gl.transition(next)` while one runs adds the next page to it and returns the same `end`, so "start at the click, refine when the router has the page" is two calls to one function.
226
+ - An `end` that never comes: after 8 s Umber ends it with a warning. Calling `end` twice does nothing.
227
+ - `gl.hold()`, `gl.live()` and `gl.morph.capture(next)` / `gl.morph.settle()` stay as the lower-level parts.
228
+
229
+ ### Recipes, one per router
230
+
231
+ Each recipe is the few lines you add next to the router's own setup, which stays exactly as its docs show. `gl` is your engine, made once: `const gl = Umber.createGL()`, or `createGL()` from the npm package. The `gl.transition()` lines are optional: the image flies without them. With them Umber knows the page change from the click, so reveals wait and the image stops fading with the old page as soon as the router has the new one.
232
+
233
+ On the elements, the same for every router: give the image the same `data-gl-id` on both pages, inside the part the router swaps. Each id once per page. The image lands where the DOM shows its target: a target under another section (one with a z-index and a background over the canvas) ends the flight hidden, and Umber warns once at landing.
234
+
235
+ ```html
236
+ <!-- the list page -->
237
+ <a href="/work/dunes"><div data-gl="image" data-gl-id="dunes"><img src="dunes-480.jpg" alt="Sand dunes"></div></a>
238
+ <!-- the detail page -->
239
+ <div data-gl="image" data-gl-id="dunes"><img src="dunes.jpg" alt="Sand dunes"></div>
240
+ ```
241
+
242
+ #### Barba 2
243
+
244
+ ```js
245
+ let end = () => {};
246
+ barba.hooks.before((data) => { end = gl.transition(data.next.html); });
247
+ barba.hooks.afterLeave(({ current }) => { current.container.style.display = "none"; });
248
+ barba.hooks.after(() => { end(0.1); });
249
+ ```
250
+
251
+ - Next to your `barba.init()`. It replaces the `gl.hold()` / `gl.live()` pair: it holds reveals and measures every frame too. Reveals start 0.1 s after the swap.
252
+ - Barba adds the new container below the old one and removes the old one only after `enter`. Umber flies only to an image on the first screen, so the `afterLeave` line takes the faded-out page out of the layout, and the image flies as the new page comes in. Without it, Umber asks again when Barba removes the old container, and the image flies only then, after `enter`. With `sync: true` both pages show at once: leave that line out and stack the containers, so it flies at once:
253
+
254
+ ```css
255
+ [data-barba="wrapper"] { display: grid; }
256
+ [data-barba="container"] { grid-area: 1 / 1; }
257
+ ```
258
+
259
+ - Keep the braces in `after`. Barba waits for a promise a hook returns, and a click while it waits reloads the page.
260
+ - `data.next.html` is only filled in `before` with `sync: true`: then the image stops fading with the old page at the click. In Barba's default transition it is `""` there, which Umber reads as "not known yet".
261
+ - Elements: `data-gl-id` on the image inside `data-barba="container"`.
262
+ - Umber: with `sync: true` the image flies from where it is; otherwise from where it was last drawn (from transparent if your `leave` faded it out).
263
+
264
+ #### Swup 4 (tested on 4.8.2)
265
+
266
+ ```js
267
+ let end = () => {};
268
+ swup.hooks.on("visit:start", () => (end = gl.transition()));
269
+ swup.hooks.on("page:load", (visit, { page }) => gl.transition(page.html));
270
+ swup.hooks.on("visit:end", () => end());
271
+ ```
272
+
273
+ - After `const swup = new Swup()`. No hook at all: `Umber.createGL({ busy: "html.is-changing" })` instead.
274
+ - Elements: `data-gl-id` on the image inside Swup's container (`#swup`).
275
+ - Umber: Swup fades the container out, swaps it in one go and fades it in. The image stops fading once Swup has the page and flies from there. With `body` as the container, Umber puts its canvas back too.
276
+
277
+ #### Taxi
278
+
279
+ ```js
280
+ let end = () => {};
281
+ router.on("NAVIGATE_OUT", () => (end = gl.transition()));
282
+ router.on("NAVIGATE_END", () => end());
283
+ ```
284
+
285
+ - `router` is your `new Core()` from Taxi (`new taxi.Core()` from its script tag).
286
+ - Elements: `data-gl-id` on the image inside `data-taxi-view`.
287
+ - Umber: Taxi removes the old view before the new one comes, so for a moment there is no page. The image waits up to 3 s for its id and flies across the gap.
288
+
289
+ #### Highway
290
+
291
+ ```js
292
+ let end = () => {};
293
+ H.on("NAVIGATE_OUT", () => (end = gl.transition()));
294
+ H.on("NAVIGATE_END", () => end());
295
+ ```
296
+
297
+ - `H` is your `new Highway.Core()`.
298
+ - Elements: `data-gl-id` on the image inside `data-router-view`.
299
+ - Highway adds the new view below the old one. Remove `from` at the start of your `in` transition, as Highway's own examples do, so the new view starts on the first screen: Umber flies only to an image there.
300
+ - Umber: the image flies from where it was last drawn.
301
+
302
+ #### Turbo 8
303
+
304
+ ```html
305
+ <script data-turbo-eval="false">
306
+ const gl = Umber.createGL();
307
+ let end = () => {};
308
+ addEventListener("turbo:visit", () => (end = gl.transition()));
309
+ addEventListener("turbo:before-render", (e) => gl.transition(e.detail.newBody));
310
+ addEventListener("turbo:load", () => end());
311
+ </script>
312
+ ```
313
+
314
+ - Turbo runs the scripts in each new `<body>`: keep `data-turbo-eval="false"` on this tag (or put it in `<head>`), so the engine is made once. No hook at all: `Umber.createGL({ busy: 'html[aria-busy="true"]' })`.
315
+ - Elements: `data-gl-id` on the image, anywhere in `<body>`. Umber's canvas needs no `data-turbo-permanent`.
316
+ - Umber: Turbo replaces `<body>`, canvas and all. Umber puts the canvas back before the frame paints. When Turbo shows a cached copy and then the real page, the flight goes on to the real one.
317
+
318
+ #### htmx (`hx-boost`)
319
+
320
+ ```js
321
+ let end = () => {};
322
+ const on = (type, fn) => document.addEventListener(type, (e) => e.detail.boosted && fn(e.detail));
323
+ on("htmx:beforeRequest", () => (end = gl.transition()));
324
+ on("htmx:beforeSwap", (d) => gl.transition(d.serverResponse));
325
+ on("htmx:afterRequest", (d) => d.successful || end());
326
+ on("htmx:afterSettle", () => end());
327
+ ```
328
+
329
+ - In `<head>`, with `createGL()`: a boosted swap leaves `<head>` alone, so it runs once.
330
+ - `on()` listens to boosted navigations only: an `hx-get` partial or a poll is not a page change. A 404, a network error or an abort never settles, so `htmx:afterRequest` ends the change then (without it, Umber ends it after 8 s, with a warning).
331
+ - Elements: `data-gl-id` on the image, anywhere in `<body hx-boost="true">`.
332
+ - Umber: htmx replaces everything inside `<body>`. Umber puts its canvas back and flies the image. The back button restores htmx's saved copy with no request, so no hook runs: Umber drops the copy's blank canvas and the image flies anyway.
333
+
334
+ #### Astro (client router)
335
+
336
+ ```astro
337
+ <script>
338
+ import { createGL } from "@occluze/umber";
339
+ const gl = createGL();
340
+ let end = () => {};
341
+ document.addEventListener("astro:before-preparation", () => { end = gl.transition(); });
342
+ document.addEventListener("astro:before-swap", (e) => { gl.transition(e.newDocument); });
343
+ document.addEventListener("astro:page-load", () => { end(); });
344
+ </script>
345
+ ```
346
+
347
+ - In the layout that has `<ClientRouter />`. A bundled `<script>` runs once. No hook at all: `createGL({ busy: "html[data-astro-transition]" })`.
348
+ - **Without the npm package** (Umber's files from the CDN, or copied into `public/umber/`): link `umber.css` in the layout's `<head>`, load `umber.js` there too with `<script is:inline src="/umber/umber.js"></script>` (`is:inline`: Astro must not bundle it), and use `window.Umber.createGL(...)` in the bundled script above instead of the import. Self-hosting the npm build (`umber.mjs`) instead: `createGL({ base: "/umber/" })`, so its chunks load from that folder, not the CDN.
349
+ - Elements: `data-gl-id` on the image. It does not need `transition:name`; a `transition:name` makes the browser fly it instead (see View Transitions below).
350
+ - Umber: Astro swaps `<body>` and copies `<html>`'s attributes inside a View Transition. Umber puts its canvas and `has-gl` back and flies the image.
351
+
352
+ #### Next.js (App Router)
353
+
354
+ ```tsx
355
+ // app/umber.tsx: render <Umber /> once, in app/layout.tsx
356
+ "use client";
357
+ import { useEffect } from "react";
358
+ import { usePathname } from "next/navigation";
359
+ import { createGL } from "@occluze/umber";
360
+
361
+ const gl = createGL(); // module level: once, also in StrictMode; on the server it does nothing
362
+ let end = () => {};
363
+ const start = () => { end = gl.transition(); };
364
+ if (typeof window !== "undefined") {
365
+ addEventListener("click", (e) => {
366
+ const a = (e.target as Element).closest("a");
367
+ if (a && a.origin === location.origin && a.pathname !== location.pathname && !a.target && !e.metaKey && !e.ctrlKey && !e.shiftKey) start();
368
+ }, true);
369
+ addEventListener("popstate", start);
370
+ }
371
+
372
+ export function Umber() {
373
+ const pathname = usePathname();
374
+ useEffect(() => { end(); }, [pathname]);
375
+ return null;
376
+ }
377
+ ```
378
+
379
+ - The App Router has no navigation events, so the change starts at a link click or the back button, and ends once the new route has rendered. Import `@occluze/umber/umber.css` in `app/layout.tsx`.
380
+ - Elements: `data-gl-id` on the image in each page's JSX: `<div data-gl="image" data-gl-id={slug}>`.
381
+ - Umber: React swaps the page in one go and the image flies from where it was last drawn. Behind a `loading.tsx` state it waits up to 3 s for the page.
382
+
383
+ #### Nuxt
384
+
385
+ ```ts
386
+ // plugins/umber.client.ts: runs once, in the browser only
387
+ import { createGL } from "@occluze/umber";
388
+ import "@occluze/umber/umber.css";
389
+
390
+ export default defineNuxtPlugin((nuxtApp) => {
391
+ const gl = createGL();
392
+ let end = () => {};
393
+ useRouter().beforeEach((to, from) => { if (to.path !== from.path) end = gl.transition(); });
394
+ nuxtApp.hook("page:finish", () => { end(); });
395
+ return { provide: { gl } };
396
+ });
397
+ ```
398
+
399
+ - `to.path !== from.path`: a query or hash change on the same page is not a page change, so it starts nothing.
400
+ - Elements: `data-gl-id` on the image in each page's template: `<div data-gl="image" :data-gl-id="slug">`.
401
+ - Umber: with no page transition Vue swaps the page in one go, and the image flies from where it was last drawn. With `pageTransition: { mode: "out-in" }` the old page leaves first, and the image waits up to 3 s for the new one. With both pages in at once (no `mode`), stack them in CSS so the new one starts on the first screen; otherwise the image flies once the old page has left.
402
+
403
+ #### Your own View Transition
404
+
405
+ ```js
406
+ function go(swap) {
407
+ const end = gl.transition();
408
+ if (!document.startViewTransition) {
409
+ swap();
410
+ end();
411
+ return;
412
+ }
413
+ end(document.startViewTransition(swap).finished);
414
+ }
415
+ ```
416
+
417
+ - `swap` is your function that changes the page. Call `gl.transition()` before `startViewTransition()`, so the browser's snapshot is taken after Umber stepped aside.
418
+ - Elements: `data-gl-id` on an image Umber flies. An element with a `view-transition-name` is flown by the browser instead.
419
+ - Umber: GL flies the `data-gl-id` image, the browser cross-fades the rest, and reveals start once the browser's animation is over.
420
+
421
+ Working pages: `examples/transitions/swup.html`, `taxi.html`, `turbo.html`, `htmx.html` and `view-transition.html` (each has the lines above), and `barba.html` (Barba without `data-gl-id`). Highway, Astro, Next and Nuxt have no example page yet.
422
+
423
+ ### gl.leave(): the old page's GL over the new one
424
+
425
+ A page-change look drawn by the renderer, for any router. On every page change a copy of what the old page's GL drew is laid over the new page, and a few lines of your GLSL take it away:
426
+
427
+ ```js
428
+ gl.leave(`vec4 leave(vec2 uv) {
429
+ float edge = uProgress * 1.2 - 0.1;
430
+ return prev(uv) * smoothstep(edge - 0.1, edge, 1.0 - uv.y); // wiped off from the bottom
431
+ }`, { duration: 0.9, ease: "expo.inOut" });
432
+ ```
433
+
434
+ - `leave(uv)`: what to show at `uv`, (0, 0) the screen's top left. Premultiplied in and out, like the canvas. `prev(uv)` is the old page; `uProgress` runs 0 -> 1, eased; `uSize` (device px) and `uTime` are there, and your own `uniforms: { ... }` (a `{ value }` is read every frame: change the direction before each change).
435
+ - Without `next(uv)` your result is laid **over** the new page (return transparent where it should show). Call `next(uv)` and it **replaces** the canvas: `mix(prev(uv), next(uv), uProgress)` is a true cross-fade (the new page is copied every frame while it plays).
436
+ - It covers **GL content only**: the images, videos, GL text and shaders the old page drew. Its DOM (text, backgrounds) is the router's job, as always.
437
+ - When: the copy is armed by `gl.transition()` and (unless `links: false`) by pressing a same-origin link to another page (a link that only changes the hash, `#filters`, does not) or going back / forward. While armed, every frame the page draws anyway is copied; nothing is asked for while nothing is armed, and a still page stays at 0 frames a second. The copy freezes when the old page goes (GL elements leave or arrive, or inside `gl.transition()` fewer of them are drawn than the frame before, as when a router hides the old container), and plays out from `end()`. With no `gl.transition()` at all, it plays from the swap itself.
438
+ - `data-gl-id` images fly above it. With `data-gl-pass` on the page, the copy is the frame before the passes, drawn back under them: the passes run over the old page and the new one together, once, and the flying images keep their look. So give both pages the same `data-gl-pass` (on `<html>`, which routers leave alone); when it changes with the page, the old page leaves under the new page's passes (said once). Reduced motion: none. `gl.leave(null)` turns it off. Not the handoff module's cover pass (`gl.handoff.cover()`, a shader that closes over the page): this one is the old page's own GL.
439
+ - Start `gl.transition()` where the change starts (the click), as the recipes above do. With no copy yet (a key press, a router's own navigation), `gl.transition()` draws one frame right away and copies it, so a router that swaps in the same task still gets its leave.
440
+ - With `data-gl-pass` on the page, the copy is the frame before the passes, laid over the new page before them: the passes run over both, once.
441
+
442
+ ### Same page: gl.flip(), plane.lift(), plane.land()
443
+
444
+ A layout change on one page (a grid becomes a list, a card opens, a filter re-orders) flown on the GPU. The DOM jumps to its new layout at once; each GL element's copy flies from its old box to its new one, corners and all. Nothing in the DOM is animated, and the new place is measured once.
445
+
446
+ ```js
447
+ await gl.flip(".cards", () => cards.classList.toggle("is-list"), { duration: 0.8, ease: "expo.out", stagger: 0.03 });
448
+ ```
449
+
450
+ - `els`: a selector, an element or a list; every GL element inside flies. `change()` runs right away, before `gl.flip()` returns. Resolves once all have landed. A new `gl.flip()` mid-flight flies on from where they are.
451
+ - Only elements in both layouts fly (one that arrives reveals as usual) and only flat ones (a turned or tilted element jumps). Without GL, `change()` simply runs.
452
+ - **Next to GSAP's Flip plugin:** that one animates the DOM itself, and Umber already follows any element it moves, so GL stays on it with no extra code. Use `gl.flip()` when only the GL copy should move (the card's DOM can jump), and never both on the same element.
453
+ - **`plane.lift()`** resolves with the plane's rect, `{ x, y, width, height }` in viewport px, that you move with anything (GSAP, your own loop); it stays put on screen while the page scrolls. `plane.land({ duration })` flies it home to its element:
454
+
455
+ ```js
456
+ const plane = gl.plane(card.querySelector("[data-gl]"));
457
+ const r = await plane.lift();
458
+ await gsap.to(r, { x: 0, y: 0, width: innerWidth, height: innerHeight, duration: 0.7 });
459
+ // ... later
460
+ await plane.land({ duration: 0.6 });
461
+ ```
462
+
463
+ `gl.flip()`, `lift()` and `land()` are `chunks/flip.js`, fetched on the first call (the planes stay where they were meanwhile). Working page: `examples/transitions/renderer.html`.
464
+
465
+ ### createGL({ busy }): no hook at all
466
+
467
+ Many routers mark `<html>` while a page changes. Give Umber that selector and it acts as inside `gl.transition()` while `<html>` matches:
468
+
469
+ ```js
470
+ Umber.createGL({ busy: "html.is-changing" }); // Swup
471
+ Umber.createGL({ busy: 'html[aria-busy="true"]' }); // Turbo
472
+ Umber.createGL({ busy: "html[data-astro-transition]" }); // Astro's client router
473
+ ```
474
+
475
+ Off by default: a site that leaves such a flag on (a spinner's `aria-busy`) would keep Umber measuring every frame and holding reveals. So it also ends by itself after 8 s, and starts again only once `<html>` stopped matching in between.
476
+
477
+ ### View Transitions
478
+
479
+ A plain root cross-fade (Astro's default, Turbo 8's `<meta name="view-transition">`, `@view-transition`) needs nothing: the canvas is part of the page's snapshot. An element **with a `view-transition-name`** is snapshotted on its own: while a page change runs (`gl.transition()` or `busy`), a GL element with a name shows its own DOM and GL leaves it out, so the browser's snapshot of it is the image (drawn by GL it would be an empty box, and its GL pixels would stay behind at the old place). The browser flies it; Umber does not fly it too. GL takes it back with the usual handshake at `end()`: pass the transition's `finished` (`end(vt.finished)`) to wait for the browser's animation. Call `gl.transition()` before `startViewTransition()`, so the old snapshot is taken after Umber stepped aside.
480
+
481
+ A flight between two separate documents (a multi-page site with no router), the canvas over cross-document View Transitions and a cover pass: the handoff module, next section. Not yet: a flight to an element the router scrolls onto the first screen only after the swap.
482
+
483
+ ---
484
+
485
+ ## Across full page loads (module: `modules/handoff.js`): multi-page sites with no router
486
+
487
+ A site with no router (Webflow, plain HTML, any server-rendered site) loads a whole new document on every link. The handoff module makes a `data-gl-id` image fly across that load, the same flight as with a router: the old page writes where each image was, the new page flies it from there to its place. Load it on every page:
488
+
489
+ ```html
490
+ <script src="https://umber.occluze.com/umber@0.2.1/modules/handoff.js"></script> <!-- after or before umber.js -->
491
+ ```
492
+ ```js
493
+ import { Handoff } from "@occluze/umber/handoff"; // npm
494
+ gl.use(Handoff, { cover: "ink" }); // or createGL({ modules: [Handoff] })
495
+ // script build: options right after createGL()
496
+ gl.handoff.options.cover = "ink";
497
+ ```
498
+
499
+ And paste this into `<head>` on every page (Webflow: Site settings, Custom code, "Inside `<head>` tag"), before anything else that renders:
500
+
501
+ ```html
502
+ <script>(function(w,d){try{var r=JSON.parse(sessionStorage.getItem("umber:handoff")),n=performance.getEntriesByType("navigation")[0],h=d.documentElement,s=d.createElement("style");s.id="umber-handoff";if(!r||!(Date.now()-r.at<3e3)||n&&n.type=="reload"||r.to!=location.href.split("#")[0])return;s.textContent=(r.items.length?r.items.map(function(i){var k='[data-gl-id="'+i.id.replace(/["\\]/g,"\\$&")+'"]';return k+':is(img,video),'+k+' :is(img,video)'}).join()+"{opacity:0!important}":"")+"::view-transition-group(umber-gl){animation:none}::view-transition-old(umber-gl),::view-transition-new(umber-gl){mix-blend-mode:normal}::view-transition-new(umber-gl){animation:none}";d.head.appendChild(s);setTimeout(function(){h.hasAttribute("data-gl-handoff")||s.remove()},1500);w.addEventListener("pagereveal",function(e){var v=w.__umberReveal=e.viewTransition||null,g=d.querySelector("[data-gl-host]");if(v&&r.over){if(!g){g=d.createElement("div");g.setAttribute("data-gl-host","");g.style.zIndex=1;(d.body||h).prepend(g)}g.style.viewTransitionName="umber-gl"}})}catch(e){}})(window,document)</script>
503
+ ```
504
+
505
+ It runs before the first paint, which a script at the end of `<body>` cannot promise. On a page opened through a link with a flying image it hides exactly that image until Umber flies it (so the first paint never shows it at its new place), keeps the cross-document View Transition for the module, and lifts the canvas above it in time. If Umber has not taken over after 1.5 s, the image shows. Without the snippet everything still works; the first frame may show the image at its new place before it flies. The same string is `Handoff.headSnippet` in code.
506
+
507
+ Elements: nothing new. The same `data-gl-id` on the image on both pages, as with a router:
508
+
509
+ ```html
510
+ <!-- work.html --> <a href="dunes.html"><div data-gl="image" data-gl-id="dunes"><img src="dunes.jpg" alt="Dunes"></div></a>
511
+ <!-- dunes.html --> <div data-gl="image" data-gl-id="dunes" data-gl-morph-duration="1.2"><img src="dunes.jpg" alt="Dunes"></div>
512
+ ```
513
+
514
+ ### What happens
515
+
516
+ - **Leaving.** On the browser's `pageswap` (Chrome and Edge 124+, Safari 18.2+), or on `pagehide` after a same-origin link click where there is no `pageswap`, the page writes one sessionStorage record (`umber:handoff`): the URL it goes to, the click, and each `data-gl-id` image GL draws on screen (its last measured rect, its picture, its corners). No layout is read. Umber never stops the link or delays the load.
517
+ - **Arriving.** The next page reads the record once (then it is gone). It counts only for that URL (the `#hash` aside), for 3 s (`maxAge`), and never on a reload. Each image whose `data-gl-id` is on the new page's **first screen** gets a stand-in at the old rect: a plain `<img>` of the old picture (from the browser cache: the old page showed it) that the browser paints at once, and a GL plane. Once GL draws it, it flies to its target with the usual flight (`data-gl-morph-duration`, `data-gl-morph-ease`, corners, the target's sharper texture), and the target takes over.
518
+ - **Fails open.** No GL on this device: the stand-in flies in the DOM (an animation of its box), then the target shows. A stand-in that does not draw within 1.5 s, a target below the first screen, `prefers-reduced-motion`, a window of another width: no flight, the page shows as it loaded.
519
+ - **Back** (a history step to an earlier page) waits for the browser's own scroll restore (the `load` event, 1 s at most) before looking for targets. A forward step does not, except in a browser without the Navigation API, where any back/forward load counts as back. A page restored from the back/forward cache is the old page as it was; nothing flies.
520
+ - **Prerendered pages** (speculation rules) read the record when they are shown, not when they are prerendered. With prerender the target's texture is ready before the click, so the flight starts on the first frame.
521
+
522
+ ### Cross-document View Transitions
523
+
524
+ With `@view-transition { navigation: auto; }` in both pages' CSS, the browser cross-fades the two documents. With the module, the canvas is lifted out of the pages' snapshots (`view-transition-name: umber-gl`) and stays live and fully opaque on top, so the image flies, and the cover plays, during the browser's cross-fade. The old page's canvas picture fades out with its page (its GL images keep their effects; no empty boxes). It needs `layer: "over"` (the default); with `layer: "under"` the canvas cross-fades with the page and Umber warns once (`gl.use(Handoff, { vt: false })` silences it). `gl.handoff.viewTransition` is the browser's transition object on the new page (await its `finished`). To time the canvas's own fade:
525
+
526
+ ```css
527
+ ::view-transition-old(umber-gl) { animation-duration: 0.4s; }
528
+ ```
529
+
530
+ ### The cover pass: `gl.handoff.cover(shader, { phase })`
531
+
532
+ A full-screen pass of **your own shader** over the page while it changes. Umber ships no look: it puts one fixed, full-screen `data-gl="shader"` element over the page and moves its uniforms.
533
+
534
+ | Uniform | |
535
+ |---|---|
536
+ | `uCover` | 0 shows the page, 1 covers it. `phase: "cover"` plays 0 → 1 and stays; `"reveal"` plays 1 → 0 and removes it. |
537
+ | `uOrigin` | Where the visitor clicked, 0..1 of the screen, y down (like `vUv`). The centre when nothing was clicked (the back button). |
538
+ | `uDirection` | `1` forward (a link), `-1` back through history. |
539
+
540
+ ```js
541
+ import { Handoff } from "@occluze/umber/handoff"; // npm
542
+ gl.shader("ink", {
543
+ uniforms: { uCover: 0, uOrigin: [0.5, 0.5], uDirection: 1 },
544
+ fragment: `
545
+ float d = distance(vUv * uViewport / uViewport.y, uOrigin * uViewport / uViewport.y);
546
+ float edge = uCover * 1.6;
547
+ color = vec4(0.08, 0.08, 0.08, 1.0 - smoothstep(edge - 0.05, edge, d));
548
+ `,
549
+ });
550
+ gl.use(Handoff, { cover: "ink", coverDuration: 0.8 }); // plays "reveal" on every page reached through a link
551
+ // script build: gl.handoff.options.cover = "ink"; gl.handoff.options.coverDuration = 0.8;
552
+ ```
553
+
554
+ - Without a router the leaving page cannot wait, so the **next page plays the reveal half**, from the old page's click. With a router, play both halves yourself: `gl.handoff.cover("ink", { phase: "cover" })` where the change starts (await it before the swap if the cover should close first), `{ phase: "reveal" }` once the new page is in.
555
+ - Give `[data-gl-cover]` a background in your CSS (`[data-gl-cover] { background: #141414; }`): the page is covered by it until GL draws the shader, and without GL it fades instead.
556
+ - Declare the uniforms the shader reads; only `uCover` is required (Umber warns once without it). Flying images draw over the cover.
557
+ - Options: `duration`, `ease`, `origin` (viewport px), `direction`. Reduced motion: nothing plays.
558
+
559
+ ### Accessibility
560
+
561
+ - Nothing the module draws is focusable or read out: the stand-ins are `aria-hidden` (with an empty `alt`), the cover is `aria-hidden` and `inert`; the real `<img alt>` stays in the page.
562
+ - **Focus.** When the old page was left from the keyboard (Enter on a link), focus moves to the new page's first `h1` (option `focus`: any selector, or `false` for the browser's own), without scrolling.
563
+ - **Announcement.** A full page load is announced by the screen reader itself, so it is off by default (`announce: true` turns it on). With a router, call `gl.handoff.announce()` (the new `document.title`, or a text) and `gl.handoff.focus()` at the end of each swap.
564
+ - **Scroll.** A back step waits for the browser's scroll restore before anything flies. Umber never sets `history.scrollRestoration`.
565
+
566
+ | Option | Default | |
567
+ |---|---|---|
568
+ | `maxAge` | `3000` | ms a record stays good. The head snippet always uses 3 s: with a longer `maxAge`, an older record still flies, but its image may show at its new place on the first paint. |
569
+ | `vt` | `true` | Lift the canvas over a cross-document View Transition. |
570
+ | `cover` | `null` | A `gl.shader()` name played (`"reveal"`) on arrival. |
571
+ | `coverDuration` / `coverEase` | `0.8` / `"umber"` | That reveal's seconds and ease. |
572
+ | `focus` | `"h1"` | Where focus goes after a keyboard navigation; `false`: the browser's own. |
573
+ | `announce` | `false` | Say the new title on arrival. |
574
+
575
+ `gl.handoff`: `arrived` (the record, or null), `origin` (the click, viewport px), `direction` (1 or -1), `viewTransition`, `options`, `cover()`, `announce()`, `focus()`.
576
+
577
+ - Same origin only (sessionStorage is per tab and per origin). Images only: a `data-gl-id` video, text or layer loads anew on the next page.
578
+ - Working pages: `examples/transitions/mpa-list.html` and `mpa-detail.html` (plain links, no router).
579
+
580
+ ---
581
+
582
+ ## Umber's own router (module: `modules/router.js`)
583
+
584
+ An optional module that changes pages without a full page load, with transitions of your own or ready-made presets, so a site needs no separate page-transition router. `umber.js` never carries it. A site that keeps its own router (Barba, Swup, Taxi...) leaves this module out and works exactly as before: never load both (with Barba, Swup, Turbo, htmx `hx-boost`, Astro's or WordPress's router on the page, this one stays off and says so once in the console).
585
+
586
+ **Which page transitions to use.** Most sites: this router. A multi-page site that should stay plain page loads: `modules/handoff.js` (the `data-gl-id` image flies across the full load, with a cover). A site that already runs Barba, Swup or another router: keep it (the "Any router" recipes); never load two.
587
+
588
+ It does what a full page load would do, without the white flash: the address and history, the title and meta, the page's own stylesheets and scripts, scroll, focus and a screen-reader announcement. Umber's own parts come along by themselves: plays (reveals) wait for the transition, the new page's GL elements come up as it comes in, and a `data-gl-id` image flies between the pages with any transition.
589
+
590
+ ### Set up: attributes only (Webflow, plain HTML)
591
+
592
+ ```html
593
+ <!-- Footer code, every page, after umber.js (same version). router.js comes with the next
594
+ release: this URL works once it is published; until then use npm or your own copy of
595
+ dist/modules/router.js (and router-swap.js next to it). -->
596
+ <script src="https://umber.occluze.com/umber@0.2.1/modules/router.js"></script>
597
+
598
+ <!-- Custom attributes (Webflow: the element's settings, Custom attributes). A div around
599
+ what changes, on every page; the nav can stay outside it. The wrapper's
600
+ data-gl-transition is the site's default. -->
601
+ <div data-gl-router="wrapper" data-gl-transition="fade">
602
+ <main data-gl-router="container" data-gl-page="home">The page's content</main>
603
+ </div>
604
+
605
+ <!-- One link with its own transition and options: -->
606
+ <a href="/about" data-gl-transition="curtain" data-gl-transition-color="#111">About</a>
607
+
608
+ <!-- A link the router leaves alone (a full page load): -->
609
+ <a href="/shop" data-gl-router-prevent>Shop</a>
610
+ ```
611
+
612
+ Only the container is required; the wrapper is optional (its `data-gl-transition` is the site's default, else `fade`). Presets by attribute: `none`, `fade`, `slide`, `zoom`, `curtain`, `wipe`, `cover`, `dissolve` (table below). `cover` by attribute alone is a disc of `data-gl-transition-color` growing from the click; name a `gl.shader()` with `data-gl-transition-shader` for anything else.
613
+
614
+ `createGL()` stays as it is; the module registers itself. With npm: `import { Router } from "@occluze/umber/router"` and `createGL({ modules: [Router] })` (or `gl.use(Router, { transition: "slide" })`). Options with the script build go on `gl.router.options` right after `createGL()`:
615
+
616
+ ```js
617
+ const gl = Umber.createGL();
618
+ gl.router.options.transition = "curtain"; // the default when nothing else picks one
619
+ gl.router.options.prefetch = "viewport"; // also fetch links as they scroll into view
620
+ ```
621
+
622
+ The module is two files: `modules/router.js` (links, history, fetching; about 4.5 KB) and `modules/router-swap.js` (which transition, the steps, the head, the scripts, the swap and the presets; about 6 KB), which the first one loads by itself from the same folder when the browser is idle, or at the first click. Nothing to add for it. With npm your bundler splits it off.
623
+
624
+ **With Umber's scroll module** (`modules/scroll.js`, smooth scrolling), load both; they work as a pair with nothing to wire: the router stops the scroll module when a transition starts, carries the new page's `<body>` / `<html>` attributes (`data-gl-scroll`, `data-gl-scroll-offset`, `data-gl-scroll-lerp`...) before it measures the new page (`resize()`), lands it at once at the top, the `#hash` (with the same `data-gl-scroll-offset` chain as the module: the link's, the target's, the page's) or where that history entry was, measures again when the transition ends, and starts it. The module's own in-page `#links` stay its own; back and forward between them land where each was.
625
+
626
+ ### Attributes
627
+
628
+ | Attribute | On | What it does |
629
+ |---|---|---|
630
+ | `data-gl-router="container"` | the part of each page that changes | Required. The router swaps it for the next page's. A page without one is never changed in place: its links load normally, and a link to such a page loads it in full. |
631
+ | `data-gl-router="wrapper"` | an element around the container | Optional. The container is looked for inside it, and its `data-gl-transition` is the site's default. |
632
+ | `data-gl-page="work"` | the container | The page's name, for transitions `from` / `to` it. |
633
+ | `data-gl-transition="slide"` | a link (or a parent of links), a container, the wrapper | A preset or a transition you registered by `name`. On a link: for that link. On a container: for arriving on that page. On the wrapper: the site's default. |
634
+ | `data-gl-transition-duration="0.6"`, `-ease`, `-color`, `-shader`, `-above` | the element with `data-gl-transition` | The preset's options: seconds, a CSS easing, a CSS colour, a `gl.shader()` name, `above` (cover, dissolve: over a fixed nav too). |
635
+ | `data-gl-router-prevent` | a link or any parent; a `<script>` | The router leaves that link to the browser (a full page load) and never fetches it ahead, or never runs that script. |
636
+ | `data-gl-router-prefetch="false"` | a link or any parent | Changed in place when clicked, never fetched ahead (a link a GET may act on, a heavy page). |
637
+ | `data-gl-router-track` | an element in `<head>` (your site's script or stylesheet, with its version in the URL) | When it differs on the next page (a new build of the site), that change is a full page load, so the new code starts clean. |
638
+
639
+ Links the router never takes, whatever the attributes: with a modifier key or another mouse button, `target` other than `_self`, `download`, `rel="external"`, another origin or protocol (`mailto:`, `tel:`), a file (`.pdf`, `.zip`, images, video...), a `#hash` of the page you are on (the browser scrolls), a click a handler already `preventDefault()`ed, and anything `options.prevent(link, event)` returns true for. Forms are never taken.
640
+
641
+ ### Presets
642
+
643
+ | Name | What it looks like | Options (defaults) |
644
+ |---|---|---|
645
+ | `none` | The new page at once. | |
646
+ | `fade` | The old page fades out quickly, the new one in. The default. | `duration` 0.4, `ease` |
647
+ | `slide` | Both pages at once: the new page slides in over the old one from the side you go to, the old one drifts a third of the way the other way and dims (back: mirrored). `sync`. | `duration` 0.9, `ease` |
648
+ | `zoom` | The old page sinks back (scales down a little) and fades; the new one settles in from a little larger. | `duration` 0.5 / 0.7, `ease` |
649
+ | `curtain` | A panel rises over the page, the new page comes in under it, the panel goes on up (back: down). | `color` #111, `duration` 0.65, `ease` |
650
+ | `wipe` | The same panel, wiped in from the left and out to the right (back: mirrored). | `color` #111, `duration` 0.65, `ease` |
651
+ | `cover` | A full-screen shader drawn by Umber: your `shader` (a `gl.shader()` with a `uCover` uniform, 0 page, 1 covered; `uOrigin` and `uDirection` too if it declares them) or a disc of `color` that grows from the click and shrinks back into it. Without GL: the panel fades. | `shader`, `color` #111, `duration` 0.8, `ease` (any Umber ease), `above` |
652
+ | `dissolve` | A full-screen shader: the page dissolves into `color` in soft noise, then the new page out of it (the edge runs down the screen; back: up). Without GL: the panel fades. | `color` #111, `duration` 0.8, `ease`, `above` |
653
+
654
+ Every preset is a few lines of Web Animations on the containers or one panel, so nothing in the page needs a class. Under `prefers-reduced-motion` every preset is a 0.2 s cross-fade of the pages: no movement, no panel (your own transitions get `reducedMotion` and decide). A `data-gl-id` image flies between the pages with each of them. The `cover` shader is the same kind as the handoff module's cover, so one shader serves both:
655
+
656
+ ```js
657
+ gl.shader("ink", {
658
+ animate: false,
659
+ uniforms: { uCover: 0, uOrigin: [0.5, 0.5], uDirection: 1 },
660
+ fragment: `
661
+ vec2 p = vUv * uViewport / uViewport.y;
662
+ vec2 o = uOrigin * uViewport / uViewport.y;
663
+ color = vec4(0.08, 0.08, 0.08, 1.0 - smoothstep(uCover * 1.9 - 0.05, uCover * 1.9, distance(p, o)));
664
+ `,
665
+ });
666
+ ```
667
+
668
+ `cover` and `dissolve` are drawn on Umber's canvas: an element above the canvas (`data-gl-above`, a fixed nav with a higher `z-index`) stays above them. With `above` (`data-gl-transition-above` on the link, or `above: true`) the canvas is lifted over everything for the transition, so they cover the nav too; while it is lifted, the page's own GL images also draw over the nav. The panel presets (`curtain`, `wipe`) are DOM and cover everything.
669
+
670
+ ### Your own transitions
671
+
672
+ ```js
673
+ // Your own transition into every page named "work" (data-gl-page="work").
674
+ gl.router.transition({
675
+ name: "into-work",
676
+ to: "work",
677
+ // The old page goes; Umber waits for the promise.
678
+ leave: ({ current }) => current.container.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 400, fill: "forwards" }).finished,
679
+ // The new container is in the page (its scripts have not run yet): its first frame.
680
+ beforeEnter: ({ next }) => {
681
+ next.container.style.opacity = "0";
682
+ },
683
+ enter: ({ next, direction }) => {
684
+ next.container.style.opacity = "";
685
+ const from = direction === "back" ? "-40px" : "40px";
686
+ return next.container.animate([{ opacity: 0, transform: `translateY(${from})` }, { opacity: 1, transform: "none" }], { duration: 600, easing: "cubic-bezier(0.2, 0, 0, 1)" }).finished;
687
+ },
688
+ });
689
+
690
+ // A preset with your options, for links in the case-study grid.
691
+ gl.router.transition({ preset: "cover", links: ".case a", shader: "ink", duration: 0.8 });
692
+
693
+ // Every page change: analytics, your own components.
694
+ gl.router.on("after", ({ next }) => {
695
+ console.log("now on", next.page, next.url);
696
+ });
697
+ ```
698
+
699
+ `gl.router.transition(def)` registers one and returns its remover. Every step (and every hook) may return what the change waits for, by one rule: a promise or any thenable (followed once), an `async` function, a GSAP tween or timeline (done once it has finished or was killed; a `gsap.set()` is done at once, also with GSAP 3.12, whose `then()` never resolves for one), a Web Animation (its `finished`; cancelled counts as done), or a list of these. Anything else is done at once. A step that takes longer than `timeout` fails the change, and the warning names it: `leave of transition 'into-work' took over 6000 ms`, or `the "afterLeave" hooks took over 6000 ms`.
700
+
701
+ - **Steps**, in order: `beforeLeave`, `leave`, `afterLeave`, then the new page goes in, `beforeEnter`, `enter`, `afterEnter`. Without `sync` the old container is gone before the new one is in. With `sync: true` both are in the page together: the new one goes in first (its `beforeEnter`), then `leave` and `enter` run at once, and the old container goes when both are done. The old one is pinned where it shows (`position: fixed` at its place, also under a transformed parent), so the new page starts at the top and your CSS needs nothing.
702
+ - **`sync` and GL.** The new page is on top, for Umber's pictures too: Umber draws every GL element on one canvas above the page, so for the change the new container is lifted above the canvas (`data-gl-above`: its text over the old page's GL pictures, its own seen through it) or, when it has a background of its own, cuts the GL under it (`data-gl-occlude`). Both come off when the old page is gone. Its pictures start loading as it goes in, also while it is still off screen to the side.
703
+ - **`beforeEnter`** runs right as the new container is in the page, before its scripts run and before Webflow starts again: set the new page's first frame there (hidden, moved), so nothing flashes.
704
+ - **`once`**: the first page load (an intro). It goes to the best match that has one; `from` never matches then. Plays wait for it, for `timeout` at most: an intro that never ends is ended by the router, which says so (`once of transition 'intro' took over 6000 ms`). A transition with only `once` (no other step, no preset) is for that and never takes a page change.
705
+ - **GSAP**: a step may return a timeline or a tween (`leave: ({ current }) => gsap.to(current.container, { opacity: 0 })`, `beforeEnter: ({ next }) => gsap.set(...)`); the rule above says when it is done.
706
+ - **What each step gets**: `{ current, next, trigger, direction, origin, reducedMotion, transition }`. `current` and `next` are `{ container, page, url, document? }` (`next.document` is the parsed next page); `trigger` is the link clicked, `"popstate"` (back / forward), `"load"` (once) or go()'s trigger; `direction` is `"forward"` or `"back"`; `origin` is where the click was (viewport px; `null` from the keyboard or history).
707
+ - **`preset`** starts from a preset: its steps and your options (`duration`, `ease`, `color`, `shader`); your own steps replace its.
708
+
709
+ **Which one runs**, for each page change: the link's `data-gl-transition` (or `go(url, { transition })`); else the most specific registered transition whose conditions all hold; else the next page's container's `data-gl-transition`; else the wrapper's; else `options.transition`. The conditions:
710
+
711
+ | Condition | Matches | Weight |
712
+ |---|---|---|
713
+ | `from` | the page you leave | 1 |
714
+ | `to` | the page you go to | 2 |
715
+ | `links` | the link clicked: a selector (`".case a"`) or a function of the link | 4 |
716
+ | `custom` | a function of the change's data | 8 |
717
+
718
+ The highest total wins (`from` + `to` is 3, more than `to` alone); a tie goes to the one registered last. A transition with no condition matches every change: the site's default. `from` and `to` take a page name (`"work"`), a path (`"/work/*"`, `*` is anything; `"/work/dunes"`), a RegExp tested on the path, a function of `{ page, url, container }`, or a list of these. A container's `data-gl-transition` counts as a `to` (2): a registered `to` for that page wins.
719
+
720
+ ### Hooks for every page change
721
+
722
+ ```js
723
+ gl.router.on("before", (d) => {}); // the click: the next page is not fetched yet (d.next.container is null)
724
+ gl.router.on("beforeLeave", (d) => {}); // each step of the transition has hooks of its name, run with it:
725
+ gl.router.on("leave", (d) => {}); // beforeLeave, leave, afterLeave, beforeEnter, enter, afterEnter
726
+ gl.router.on("afterLeave", (d) => {});
727
+ gl.router.on("beforeEnter", (d) => {}); // the new container is in, its scripts have not run
728
+ gl.router.on("enter", (d) => {});
729
+ gl.router.on("afterEnter", (d) => {});
730
+ gl.router.on("after", (d) => {}); // all done: the new page is in, measured, its transition finished
731
+ gl.router.on("error", ({ error, url }) => {}); // the router gave up: url loads in full now
732
+ ```
733
+
734
+ Every hook but `after` may return what the change waits for (the rule above). Each `on()` returns its remover. An `after` hook that throws is logged; the page is in already.
735
+
736
+ ### Per-page code: views (init and destroy)
737
+
738
+ `gl.router.view(page, { beforeEnter, afterEnter, beforeLeave, afterLeave })` is one page's own code, for its `data-gl-page`: set it up as the page comes in (the first load too, as Barba's views do), take it down as it goes. It returns its remover. The pattern for GSAP ScrollTrigger, `gsap.context()` and Umber's `gl.scope()`: make everything of the page inside them on enter, revert them on leave, refresh once the page is in.
739
+
740
+ ```js
741
+ gsap.registerPlugin(ScrollTrigger);
742
+ const pages = {}; // the page shown: its gsap.context and gl.scope
743
+
744
+ function enter(name, setup) {
745
+ gl.router.view(name, {
746
+ // The page is in and measured (the first load too): make its ScrollTriggers, pins, GL views.
747
+ afterEnter({ next }) {
748
+ const root = next.container;
749
+ let ctx;
750
+ // gl.scope: what Umber makes in setup (gl.attach views, gl.add planes); gsap.context: its tweens and ScrollTriggers.
751
+ const scope = gl.scope(() => (ctx = gsap.context(() => setup(root), root)), root);
752
+ pages[name] = { ctx, scope };
753
+ ScrollTrigger.refresh(); // measure with the new page (pins, starts)
754
+ },
755
+ // Before the old page goes: kill its ScrollTriggers (pin spacers come off) and its GL views.
756
+ beforeLeave() {
757
+ pages[name]?.ctx.revert();
758
+ pages[name]?.scope.revert();
759
+ delete pages[name];
760
+ },
761
+ });
762
+ }
763
+
764
+ enter("home", (root) => {
765
+ gsap.to(root.querySelector(".track"), { xPercent: -50, scrollTrigger: { trigger: ".process", pin: true, scrub: 1 } });
766
+ });
767
+ enter("work", (root) => {
768
+ root.querySelectorAll("[data-reveal]").forEach((el) => gsap.from(el, { y: 60, opacity: 0, scrollTrigger: el }));
769
+ });
770
+ ```
771
+
772
+ - `afterEnter` runs once the new page is in its place and scrolled (and before the scroll module measures it again), so ScrollTrigger measures the page as it will stay; `ScrollTrigger.refresh()` there is enough. With a `sync` transition the old page is still pinned until both steps end: create pins in `afterEnter`, not `beforeEnter`.
773
+ - Reverting in `beforeLeave` puts pinned sections back in the flow before the leave animation, so the old page leaves as it looked unpinned; revert in `afterLeave` instead to keep a pin through the leave.
774
+ - For code that runs on every page (a cursor, a nav state), use the hooks above without a page name.
775
+
776
+ **Analytics.** Send the page view in `after`, once the new title is set. With GA4 (`gtag.js`), turn off Enhanced measurement's "Page changes based on browser history events" in the data stream (it would count the page at `pushState`, with the old title, and twice with this):
777
+
778
+ ```js
779
+ gl.router.on("after", ({ next }) => {
780
+ gtag("event", "page_view", { page_location: next.url, page_title: document.title });
781
+ });
782
+ ```
783
+
784
+ ### What a page change does
785
+
786
+ 1. **The click.** `<html>` gets `data-gl-router-busy` (and `gl.router.busy` is true) while the next page loads; the page stays as it is meanwhile, its address and its scroll its own. A loading cue in CSS: `html[data-gl-router-busy] { cursor: progress; }`, or a bar that shows only when it takes a while: `html[data-gl-router-busy] .loader { opacity: 1; transition: opacity 0.2s 0.3s; }`.
787
+ 2. **The fetch.** Often done already: the router fetches a page as the pointer rests on its link (65 ms), a touch starts or it gets focus (`prefetch: "hover"`, the default), and with `prefetch: "viewport"` also when a link scrolls into view and the browser is idle (not with Save-Data). Never ahead, by one rule (a GET must not act; Turbo's prefetch uses the same markers): the page shown, a link marked as an action (`data-method` other than get, `data-confirm`, `data-remote`), `data-gl-router-prefetch="false"` on it or a parent, a URL with a `?query` (`?action=logout`, `?add-to-cart=12`) or a sign-out path; those are fetched on click only. The last 10 pages stay in memory (`cache`); a page sent with `Cache-Control: no-store` is not kept. A click aborts other requests still running. Only an HTML page of this site counts: a redirect to another site, a download, a 204 or anything not HTML is the browser's (step 9).
788
+ 3. **The transition starts.** The URL goes into history (`pushState`, after a redirect the page's real URL; the page you leave keeps its scroll in its entry). Umber's `gl.transition()` starts with the next page: plays wait, every plane is measured every frame, a `data-gl-id` image freezes. The scroll module is stopped.
789
+ 4. **Leave**, then the swap, by one rule for everything outside the container: what a page's own HTML has is that page's, and is replaced by what the next page's HTML has; anything a script added (a font loader's stylesheet, `has-gl`, a menu's class, Umber's own) stays. So: every `<head>` element but scripts (title, meta, links, `<base>`...) is matched by its markup: the next page's go in, the old page's own that it lacks go, and an element the next page puts in the same place (one description, one canonical) replaces the old one. Stylesheets follow the same rule, timed: the next page's were fetched while the old page left, they go in now and the new container waits until they have loaded (3 s at most), so it never shows unstyled; the old page's own go once it is gone. `<html>` and `<body>` attributes and classes (`lang`, Webflow's `data-wf-page`, `data-gl-scroll`, a theme's `data-*`) are merged three ways: what changes between the two pages' HTML is applied, what both have is left as scripts made it (a `no-js` class a script turned into `js` stays `js`). The first page's own HTML is fetched once, at the first change (from the cache mostly; it is also what "back" to it shows); until it is in, nothing of the first page is removed but what the next page replaces. Fonts the new page starts using are waited for (1 s at most).
790
+ 5. **Scroll**: to the top, to the `#hash` (the element with that id; its `scroll-margin-top` and `data-gl-scroll-offset` count), or for back / forward to where that entry was.
791
+ 6. **Scripts**: every `<script>` in the new container runs, in page order (an external one is waited for, 3 s at most, unless `async`). Outside the container (`<head>`, the end of `<body>`), only a script the page you came from did not have: a file loads once per visit, never twice (jQuery, `webflow.js`, `umber.js`), and a page's own inline code runs again each time you come back to it from a page without it. JSON-LD and other non-script types never run; `data-gl-router-prevent` opts one out. One rule for a classic script this document ran before (inline code, or a file in the container, as when you come back to a page): it runs inside `{ }`, so a top-level `const` / `let` / `class` does not throw "already declared" (its names are then its own: read shared values from `window`), and a custom element it defines again keeps its first definition. A file is read for that from the HTTP cache (with its `integrity`) and runs inline, so `document.currentScript.src` is empty in that run; a file the browser cannot read that way (no CORS) goes in as it is. A first run is exactly the page's. Modules are the browser's: a module file runs once a visit.
792
+ 7. **Webflow**, where `window.Webflow` is: `Webflow.destroy()`, `Webflow.ready()`, `Webflow.require("ix2").init()` and a `readystatechange` event, so interactions, forms and tabs start on the new page; links outside the container get `w--current` (and every site gets `aria-current="page"` on them).
793
+ 8. **Enter**, then the new title is **announced** in a polite live region. For a visitor who navigates by keys (a keyboard, or a screen reader activating the link), **focus** moves to the new container's `<h1>` (`focus` option; without one, the container itself), without scrolling (it is focusable only until focus moves on), as a full page load would put them at the start of the page. After a mouse, touch or pen click, or `gl.router.go()` on its own, focus stays where it was: no focus ring appears that the visitor didn't ask for (nor in a video recorded of the site). `data.keyboard` tells a transition which it was.
794
+ 9. **After**: `gl.transition()` ends (plays start, the flying image lands; a change longer than 7 s ends it then and holds plays on until the end), the scroll module is measured again and starts, `after` hooks run, `go()` resolves.
795
+
796
+ A link to the page shown (a logo) scrolls back to the top. Back and forward between `#hash` entries of one page land where each was, else at the target.
797
+
798
+ Back and forward run the same with `direction: "back"` / `"forward"`. The router sets `history.scrollRestoration` to `"manual"` while the page lives (it restores scroll itself) and back to `"auto"` when the page is hidden, so a reload or a later visit gets the browser's own. It adds no `unload` listener, so pages stay in the back / forward cache.
799
+
800
+ ### On a domain that isn't on an Umber licence
801
+
802
+ The router is part of the Umber licence (no extra cost): on a domain not listed under Umber at occluze.com, links and back / forward work the way the browser does without a router, and so does every link before the answer comes in (asked once per page, `gl.licensed()`; the browser keeps a yes for a day). `localhost` and `*.test` always work.
803
+
804
+ ### When something goes wrong: a full page load
805
+
806
+ Any failure loads the URL the way the browser would without a router, with a warning: an answer that is not OK (404, 500), not HTML, a download or a 204, a redirect to another site, a page with no `data-gl-router="container"`, changed `data-gl-router-track` elements (a new build), a step or hook that throws, a fetch or step that takes longer than `timeout` (6000 ms), or `router-swap.js` that cannot load. The `error` hooks hear it first. A failure before the transition started leaves the page exactly as it was (a download or a 204 keeps you there, and the router keeps working); one during the transition loads the page in full. One page change runs at a time: a click while the next page is still loading replaces that change; a click, back or forward during the transition waits and runs after it, and only the last one waits. A page restored from the back / forward cache in the middle of a change reloads.
807
+
808
+ ### The API
809
+
810
+ | | |
811
+ |---|---|
812
+ | `gl.router.go(url, { transition?, trigger? })` | Change page from code. Resolves once the new page is in and its transition finished; rejects (after starting a full load) when the router can't. A URL that is not http(s) (`javascript:`, `data:`) is rejected and never followed. A link to the page shown resolves at once. |
813
+ | `gl.router.prefetch(url)` | Fetch a page ahead into the cache. Never rejects. |
814
+ | `gl.router.transition(def)` | Register a transition; returns its remover. |
815
+ | `gl.router.on(name, fn)` | A hook (`before`, `beforeLeave`, `leave`, `afterLeave`, `beforeEnter`, `enter`, `afterEnter`, `after`, `error`); returns its remover. |
816
+ | `gl.router.view(page, { beforeEnter, afterEnter, beforeLeave, afterLeave })` | One page's set-up and take-down (its `data-gl-page`), entered on the first load too; returns its remover. |
817
+ | `gl.router.busy` | `true` while a page change runs. |
818
+ | `gl.router.url`, `gl.router.page` | The page shown: its URL (no `#hash`) and its `data-gl-page`. |
819
+ | `gl.router.options` | The options below, live. |
820
+
821
+ Also at `window.__umber.engine.router`, for tools that drive the page (a screen recorder moves between pages with `go()`).
822
+
823
+ | Option | Default | |
824
+ |---|---|---|
825
+ | `transition` | `"fade"` | The transition when nothing else picks one: a preset or a registered name. |
826
+ | `prefetch` | `"hover"` | `"hover"` (rest, touch, focus), `"viewport"` (also links in view, when idle), `false` (on click only). Never a `?query` URL or one that may act (step 2). |
827
+ | `cache` | `10` | Pages kept in memory; `0`: none. |
828
+ | `timeout` | `6000` | ms a fetch or any step may take before the page loads in full instead. |
829
+ | `focus` | `"h1"` | Where focus goes in the new container after a keyboard (or screen reader) change (a selector; else the container); `false`: nowhere. |
830
+ | `announce` | `true` | Say the new title in a polite live region. |
831
+ | `scroll` | `true` | Scroll to the top, the `#hash`, or where the entry was. |
832
+ | `scripts` | `true` | Run the new page's scripts. |
833
+ | `head` | `true` | Title, meta, stylesheets, `<html>` and `<body>` classes and attributes. |
834
+ | `webflow` | `true` | Start Webflow again after each swap. |
835
+ | `prevent` | `null` | `(link, event) => boolean`: true leaves the link to the browser. |
836
+
837
+ ### With Umber
838
+
839
+ - **Plays and planes.** Each change runs inside `gl.transition()`, so you need none of the recipe lines of the "Any router" section. The new container's GL elements are made as it arrives (Umber sees it in the DOM) and drawn where their elements are while a container moves; their reveals start when the change ends.
840
+ - **Flying images.** Give the image the same `data-gl-id` on both pages, inside the container. Without `sync` the old page is gone before the new one is in, so the image flies to its new place on the first screen as the new page comes in. With `sync: true` the old page is pinned out of the flow, so the new one starts on the first screen too.
841
+ - **`gl.leave()`** works as with any router: the old page's GL is copied at the click and drawn over the new page by your GLSL.
842
+ - **Smooth scroll.** Umber's scroll module pairs by itself (see the top of this page). A site that runs its own Lenis instead stops and starts it in hooks: `gl.router.on("leave", () => lenis.stop())`, `gl.router.on("after", () => { lenis.resize(); lenis.start(); })`.
843
+
844
+ ### Coming from Barba
845
+
846
+ | Barba | Umber's router |
847
+ |---|---|
848
+ | `data-barba="wrapper"`, `data-barba="container"` | `data-gl-router="wrapper"`, `data-gl-router="container"` |
849
+ | `data-barba-namespace="home"` | `data-gl-page="home"` |
850
+ | `data-barba-prevent` | `data-gl-router-prevent` |
851
+ | `barba.init({ transitions: [a, b] })` | `gl.router.transition(a)`, `gl.router.transition(b)` |
852
+ | a rule's `namespace`, `route` or `custom` | `from` / `to` with a page name or a path, `custom` |
853
+ | `barba.hooks.after(fn)`, `barba.hooks.beforeEnter(fn)`... | `gl.router.on("after", fn)`, `gl.router.on("beforeEnter", fn)`... |
854
+ | `views: [{ namespace: "home", beforeEnter, afterLeave }]` | `gl.router.view("home", { beforeEnter, afterLeave })` |
855
+ | `barba.go(url)`, `barba.prefetch(url)` | `gl.router.go(url)`, `gl.router.prefetch(url)` |
856
+ | `@barba/prefetch` | built in (`prefetch: "hover"` or `"viewport"`) |
857
+
858
+ How it compares, in short: links, history and head handling follow what Turbo, Swup and Astro's client router settled on (a page cache with hover prefetch, `history.scrollRestoration = "manual"` with positions kept per entry, head elements merged by their markup with stylesheets waited for, scripts re-activated by copying them, `data-gl-router-track` like `data-turbo-track="reload"`), with Barba's per-page transitions and hooks on top. It uses the History API, not the Navigation API, which not every browser has yet.
859
+
860
+ Not included, on purpose: Barba's plugin system and logger, rule fields beyond the ones above, and code for old browsers (the router needs what Umber needs: `fetch`, `DOMParser`, Web Animations). Speculation Rules are not used: a page they prefetch goes to the browser's navigation cache, which `fetch()` can't read, so it would only help the full page loads the router falls back to.
861
+
862
+ Working pages: `examples/router/` (`index.html`, `dunes.html`, `about.html`, `site.js`): a transition of the site's own for one page with a flying image, `curtain` and `wipe` by attribute only, the `cover` with the page's own shader, `slide` from code, a page with its own stylesheet and script.
863
+
864
+ ---
865
+
866
+ ## Attributes (the DOM is the API)
867
+
868
+ Everything an attribute does, code can do too. Effect options also work as CSS custom properties, which Webflow can set per breakpoint on a class. They are read when the plane is built and again on a window resize or `gl.invalidate(el)`; `plane.set()` changes them from code.
869
+
870
+ | Attribute | On | What it does |
871
+ |---|---|---|
872
+ | `data-gl="image"` | a wrapper with an `<img>` inside, or the `<img>` itself | Draws the image as a plane. Webflow `srcset` works: Umber uses the candidate the browser picked. |
873
+ | `data-gl="video"` | a wrapper with a `<video>`, or the `<video>` | Draws the video. A frame is uploaded only when the video has a new one. Muted loop/autoplay videos pause while off screen and play again when back (`data-gl-video-autopause="false"` keeps them playing; videos with `controls` are never touched). |
874
+ | `data-gl="text"` | any text element | Paints the element's real text into a plane (see Planes: GL text). |
875
+ | `data-gl="shader"` + `data-gl-shader="name"` | any box | A surface drawn fully by `gl.shader("name", {...})`. Its own background hides once painted. |
876
+ | `data-gl="layer"` + `data-gl-layer="name"` | any box | Your own WebGL from `gl.layer("name", {...})`, on Umber's canvas (see three.js). |
877
+ | `data-gl="group"` | any box with GL planes inside | Draws the GL planes inside it as one image, through its own `data-gl-effect` (Groups and passes). |
878
+ | `data-gl-pass="a b"` | `<body>`, `<html>` or a group | Effects run over the whole GL frame, or over the group, in order. Per effect also `-blend`, `-opacity`, `-scale` (Groups and passes). |
879
+ | `data-gl-shader-<option>` / `data-gl-layer-<option>` | a shader or layer plane | One option of its `gl.shader()` / `gl.layer()`. Also `--gl-shader-<option>` / `--gl-layer-<option>` in CSS. A shader's number, boolean, array, colour and image-path options become uniforms `u` + Option (`data-gl-shader-speed` sets `uSpeed`); a layer reads them in `ctx.options`. |
880
+ | `data-gl-effect="a b"` | a plane | Effects from `gl.effect()`, applied in order. |
881
+ | `data-gl-<effect>-<option>="value"` | a plane | One effect option. Also `--gl-<effect>-<option>` in CSS. Numbers, booleans, arrays, CSS colours (a `vec4`) and image paths (a string with a `/`: a `sampler2D`) become uniforms: `data-gl-dissolve-scale="5"` sets `uDissolveScale`. |
882
+ | `data-gl-<effect>-trigger` | a plane | For effects with `play`: `auto` (default: on screen at once, further down on scroll), `scroll`, `load`, `manual` (`gl.plane(el)?.play()`), `hover` (0 to 1 while the pointer is over it or its closest link or button, back on leave). |
883
+ | `data-gl-<effect>-delay` / `-duration` / `-ease` / `-start` | a plane | The play's timing. `start` is `"<element edge> <screen line>"`, default `"top 90%"` (no offsets). |
884
+ | `data-gl-src="url"` | an image plane | Another texture than the `<img>` (for example a larger file). Changing it, or the `<img>`'s `src` / `srcset` (a framework reusing the tag), keeps the old picture drawn until the new one is on the GPU: no flash of the DOM. An effect that reads `uSwap` blends them (see Effects). |
885
+ | `data-gl-swap-duration` / `-ease` | an image plane whose effect reads `uSwap` | How long the old picture takes to give way after a new `src` (seconds, default 0.8; ease default `umber`). Also `--gl-swap-*` in CSS. |
886
+ | `data-gl-placeholder="..."` | an image plane | A tiny blurred preview (about 50 characters, made with `gl.placeholder(src)`) shown under the `<img>` until its file has loaded. See "Getting ready ahead". |
887
+ | `data-gl-fit="cover \| contain \| fill"` | a plane | Overrides the element's `object-fit`. From CSS, GL follows `contain`; everything else (`cover`, the default `fill`, `none`, `scale-down`) draws as `cover`, so an `<img>` with no object-fit is cropped, not stretched. Only `data-gl-fit="fill"` stretches. `object-position` is read from CSS: %, keywords and lengths (`20px 10px`, `1rem 0`; a length resolves once the image has loaded). |
888
+ | `data-gl-order="2"` | a plane | Draw order (lower first). |
889
+ | `data-gl-instances="64"` | a plane | Drawn many times in one draw call: `"64"` copies, `"tiles 24x16"`, `"chars"` / `"words"` / `"lines"` (GL text), `"echo 6"` (a trail), `"ink 3000"` (particles where it has ink). Its effects get `instance` and the mode's inputs (see Instances). |
890
+ | `data-gl-clip="false"` | a plane | Draw it without its parents' clips (`overflow`, `clip-path`, CSS masks). Its own `clip-path` still cuts it. Parents' clips are followed by default (see Planes). |
891
+ | `data-gl-wrap="x \| y"` | a track holding planes (or a plane) | Its planes wrap around it: when something moves the track (a drag, a tween, a scroll-driven animation), each is drawn moved by whole track lengths (its `offsetWidth`, or `offsetHeight` for `y`) so the track's own place on the page stays filled, an endless gallery with no copies in the DOM. Cards at rest are drawn where their DOM is, so a track below the fold stays below it. The track must be at least one card longer than the screen; give it its trailing gap as padding so the spacing repeats. Its planes load their images at once, hide their DOM once their pixels are ready (GL draws them wherever they wrap to), report `inView`, `"enter"` and `"leave"` where they are drawn, and are measured wherever their DOM went (a drag or a tween moving the track is followed like any moved parent). Flat planes only (a turned one keeps its own place). |
892
+ | `data-gl-live` | a plane | Measure every frame while on screen. Rarely needed: CSS animations and transitions, scroll-driven animations and the Web Animations API are followed by themselves while they run, inline styles (GSAP, Webflow Interactions) by the DOM watch, and sticky, fixed and pinned parents are detected (not a fixed element inside a transformed parent, or a sticky one in a box that never scrolls: the scroll doesn't move those). Use it for an element your own `requestAnimationFrame` loop moves some other way, or a paused animation it scrubs. |
893
+ | `data-gl-id="hero"` | a plane | The same id on two pages: the image flies across on a page change. On the element you go to, `data-gl-morph-duration` (seconds, default 1) and `data-gl-morph-ease` (also `--gl-morph-*` in CSS) time the flight. If the element it lands in sits inside a box that paints an opaque background over the canvas (a fixed next container with a z-index above the canvas's), Umber warns at landing: the image would be hidden under it. The same when another box (a sibling section with a z-index and a background) lies over the spot it lands on: the flight ends hidden there. Fly to an element that shows, or raise the canvas. |
894
+ | `data-gl-above` | any element | Keeps it above the canvas (`position: relative; z-index: 2`, zero specificity: your own position and z-index win). |
895
+ | `data-gl-host` | one element | Where the canvas goes (else Umber makes a fixed full-screen host). |
896
+ | `data-gl-devices="desktop"` | `<body>` or `<html>` | Effects only on desktops (hover, a fine pointer, at least 768px wide); phones and tablets show the plain page. Effects run on every device by default. Recommended when a page is heavy for phones. `createGL({ devices })` wins over it. |
897
+ | `data-gl-media="(min-width: 900px)"` | `<body>` | Effects only where this CSS media query matches, read when the page loads; elsewhere the plain page shows. Any size or device: `(min-width: 600px)` turns phones off, `(min-width: 1024px)` phones and most tablets, `(hover: hover)` every touch screen. `createGL({ media })` wins over it. |
898
+ | `data-gl-disable` | `<body>` | GL off from this page on, for the rest of the visit (a router's later pages keep their DOM). |
899
+ | `data-gl-scrub` (+ `-start`, `-end`, `-track`, `-smooth`, ...) | a `<video>` plane | Scroll-scrubbed video. Needs the scrub module (see Scrub). |
900
+
901
+ **Written by Umber** (style them, never set them): `html.has-gl`, `data-gl-status="loading | ready | error"`, `data-gl-media` (the `<img>` / `<video>` a plane mirrors), `data-gl-play` (has a playing effect: hidden while GL loads), `data-gl-morphing`, `data-gl-canvas` on the canvas (with `data-engine="umber <version>"`; GL text's hidden paint canvases in the host carry `data-gl-canvas="text"`), and `data-gl-view="loading | ready | off | error | lost"` on `gl.attach()` / `gl.view()` elements. The debug module's panel and overlay carry `data-umber-hud` and `data-umber-debug`.
902
+
903
+ **Layering.** The canvas sits **over** the page (z-index 1), with `pointer-events: none`, so every click still goes to the DOM. Its host is `<body>`'s first child, so the stacking rule is plain CSS:
904
+
905
+ - **A positioned element with `z-index: 1` or more and a background covers GL inside it.** It comes later in the page at the same or a higher z-index, so it paints over the canvas: the plane is `ready`, its DOM is hidden, and nothing shows. `gl.inspect(el)` says so (`... covers Umber's canvas`), and Umber warns once on pages that load `chunks/shapes.js` (anything cut, turned or tilted). Fixes: drop that element's `z-index` (or make it `auto`), move its background to a sibling or a `::before` behind the content, or give the canvas a higher `createGL({ zIndex })` and lift what must stay above it (navs, buttons) with `data-gl-above` or a higher z-index.
906
+ - **A router container made `position: fixed` or transformed during a swap** (a slide or cover transition) becomes its own stacking context; with a z-index it takes its content under or over the canvas for that moment. Give the container no z-index, or hand its planes back to the DOM for the transition (`gl.planes(container).forEach((p) => p.destroy())`).
907
+ - **A flight lands where the DOM puts its target.** If that spot is under another section (positioned, z-index 1 or more, a background), the image flies in and then vanishes under it, as its DOM would. Umber warns once at landing and names the section.
908
+ - `data-gl-clip="false"` only stops a parent from cutting the plane; it does not lift GL over a parent that paints over the canvas.
909
+ - Text or buttons over a GL image need `data-gl-above`.
910
+ - `data-gl-above` cannot escape a parent that is transformed, faded (opacity < 1) or filtered: the canvas then covers it. Animate the caption itself, or move it out of that wrapper. **Pinned sections** (GSAP ScrollTrigger `pin: true`, a sticky stack) are such a parent: the pin makes the section `position: fixed` and transforms it, so text inside it with `data-gl-above` stays under the canvas. Give the pinned section itself `position: relative; z-index: 2` (above the canvas's 1; no background on it, or its GL is hidden) instead of lifting what is inside. Umber says so once, naming both elements, when it sees a GL element in such a section.
911
+ - Never put `data-gl-above` on the element that holds the GL image: its background would cover the drawing.
912
+ - A fixed nav, menus and transition overlays need a z-index above 1 (for example 10).
913
+ - Prefer the canvas behind the page? `createGL({ layer: "under" })`; then sections over GL images need a transparent background.
914
+
915
+ **Hide a playing element from the first paint.** Elements whose effect has `play` stay hidden while GL loads, so a reveal never flashes the plain image first. `createGL()` marks the elements already on the page at once, and `gl.effect()` adds `data-gl-play` to the ones using a playing effect as it is defined; write `data-gl-play` in your HTML yourself too, so they stay hidden when the effect is defined later (an async import): GL leaves such an element undrawn until its effect is defined, 3 s at most. If GL is off or gives up (3 s on screen; time the page itself keeps the element hidden, at `opacity: 0` or `visibility: hidden`, does not count), they show.
916
+
917
+ ---
918
+
919
+ ## Planes
920
+
921
+ A plane is the GPU copy of one `[data-gl]` element. It follows the element's position, size, border-radius, object-fit (cover or contain; see `data-gl-fit`) and opacity (its own and its parents', up to the one that also holds Umber's canvas: a fade on `<body>` fades the canvas already), and it is cut by whatever cuts the element (below). Its own corners follow too, oval ones as well (`border-radius: 50%` on a box that is not square, `40px / 20px`), wherever the plane is drawn (a flight, a lift, a wrapped track, a group). Every rounded corner must have the same proportion across / down: corners of different shapes (one round, one oval) show its DOM, with a warning. The element stays the source of truth: change it with CSS, GSAP or Webflow Interactions and the plane follows.
922
+
923
+ **What Umber reads, and when.** A scroll over a still layout reads no layout and no styles: each plane is moved by the scroll position alone. Umber measures a plane (its rect, and the styles of it and its parents) only when:
924
+
925
+ - it comes near the screen (a quarter screen ahead, above or below; sideways only once it reaches the screen), once;
926
+ - it or a parent gets a style or class change (a GSAP tween writes `style` every frame it runs). A change on `<html>` or `<body>` (a theme or state class) measures only the planes near the screen; Lenis's own `lenis-scrolling` / `lenis-smooth` classes measure nothing;
927
+ - a CSS transition or animation, or a Web Animation, moves it, while it runs; it is fixed or sticky (every frame near the screen); or a page swap just happened (1.5 s);
928
+ - the window resizes, a stylesheet or font arrives, or you call `gl.invalidate()`.
929
+
930
+ Elements added or removed without a `[data-gl]` in them (a news ticker, a chat, a counter) wake nothing: a still page stays at 0 frames a second. Far planes are measured when they come near, and when `<html>` itself changes size (the page grew) Umber's ResizeObserver measures again. A shift that doesn't change `<html>`'s size is not seen: an item pushed into a flex row, a list that adds one and drops one, or a page whose `<body>` or `<main>` is the scroller (`height: 100%`). Call `gl.invalidate()` after those. An `<img>` put into an image or video `[data-gl]` is still news (the plane is built again).
931
+
932
+ After a plane was restyled, one look at its opacity a few frames later catches a fade no DOM change reports; then nothing more. `gl.info.busy` names what keeps the loop running (`dom-watch:<section#hero>`: that element was restyled).
933
+
934
+ ### What GL draws, and what cuts it
935
+
936
+ - **The box GL draws** is the `<img>` / `<video>` itself. With `data-gl` on a wrapper (a card) that holds the image, GL draws the image's own box, with the image's own corners and `object-fit` (cover or contain; see `data-gl-fit`): a hover zoom on the `<img>` shows in GL, and padding or a caption in the wrapper stays DOM. Text, shaders and layers draw the element's box.
937
+ - **Parents cut it like the DOM does.** A parent with `overflow: hidden | clip | auto | scroll` (with its rounded corners), `contain: paint`, or a `clip-path` (on the element or any parent) cuts the GL image exactly where it cuts the DOM image: sliders, marquees, rounded cards, line masks, clip-path reveals. The browser's own rules hold: an `absolute` image escapes a static parent's overflow, a `fixed` one escapes everything but a transformed, filtered or `contain: paint` parent, and `clip-path` reaches every child.
938
+ - **Drawable clip-paths:** `inset()`, `rect()`, `xywh()` (with `round`), `circle()`, `ellipse()`, `polygon()` (one per element, up to 8 points), on any reference box, animated by CSS, a class, GSAP or your own code. Corner radii may be elliptical (`50% / 20px`) when every corner has the same ratio.
939
+ - **Cost:** straight clips (a slider, a mask, an `inset()` wipe, a rectangle `polygon()`) are a GPU scissor: free per pixel. Rounded and shaped ones are tested per pixel, only on those elements (at most 2 per element). A rounded card that hugs its image is drawn as the image's own corners, as before. A scroll reads nothing for them: clips are measured with their element and moved with the scroll.
940
+ - **What falls back to the DOM** (the element shows its DOM image or text, with one `[umber]` warning that names the fix, and GL takes it back when the cause goes): `clip-path: path()`, `shape()`, `url()` or `min()` / `max()` / `clamp()` in a shape; a CSS `mask` / `mask-image` on the element or a parent; corners that mix radius ratios; more than 2 rounded or shaped clips on one element, a second polygon, or a nonzero polygon that crosses itself.
941
+ - **`data-gl-clip="false"`** (or `gl.add(el, { clip: false })`) draws the element without its parents' clips and masks; its own `clip-path` (and a wrapper's overflow on its own `<img>`) still cut it.
942
+ - A wrapper with `border-radius` but `overflow: visible` doesn't round its image in the DOM, so not in GL either: put `overflow: hidden` on it, or the radius on the `<img>`.
943
+ - **Opaque panels that slide over GL: `data-gl-occlude`.** Umber draws on one canvas (z-index 1). A panel positioned with a `z-index` of 1 or more and an opaque background paints over the canvas, so GL inside it is hidden (Umber warns). Stacked sticky sections and card decks need that z-index: raise the canvas above them with `createGL({ zIndex })` (under a fixed header that must stay on top). On one canvas, the earlier panels' GL would now show through the later ones. Put `data-gl-occlude` on each panel that slides over others: every GL element it paints over in the DOM is cut by its box, with its corners. That is every one before it in the page, and every one after it that sits in a lower `z-index` (content scrolling under a sticky bar). Not one that sits higher, like a fixed header's GL logo. GL elements inside the panel are drawn as usual. A `data-gl="shader"` backdrop that holds the panel is cut by it.
944
+
945
+ ```html
946
+ <section class="panel" style="position: sticky; top: 0; z-index: 1; background: #111">...</section>
947
+ <section class="panel" data-gl-occlude style="position: sticky; top: 0; z-index: 2; background: #111">...</section>
948
+ <script>Umber.createGL({ zIndex: 5 });</script> <!-- the canvas over the panels, under a z-index 10 header -->
949
+ ```
950
+
951
+ - **`data-gl-under="<selector>"`** on a GL element picks its panels instead (any order in the page); `data-gl-under="none"`: never cut. It is read when the element is measured: after changing it, call `gl.invalidate(el)`.
952
+ - **Cost:** a panel that misses an element costs nothing. One that covers it hides it (not drawn). One that slides over one of its edges, full width, cuts the scissor (free). Otherwise it takes one of the element's 2 per-pixel clip slots. With both taken by rounded parents, a panel spanning it still cuts it straight (wrong only at its rounded corners); one that doesn't is not cut there, with one warning. A three.js layer is only cut straight.
953
+ - A still panel is measured again when the DOM changes (a style or class on it or a parent, GSAP; an element put in it, a dropdown; `aria-expanded`, `open`, `data-state` or `hidden` on it or next to it, a menu's button) and moved by the scroll: no reads while scrolling. Text changed in it (a counter, a clock) and restyles inside it are looked at a quarter second later. A `:hover`, `:focus-within` or `:checked` rule that opens it is caught by the pointer, focus and input events by it. A sticky or fixed one, or one with `data-gl-live`, is read once a frame (its rect) while the loop runs and an element it may cut is near the screen. A CSS animation or transition that moves or fades the panel is followed while it runs (the elements under it are not measured for it).
954
+ - It needs an opaque background (a colour without transparency, or an image) and no fade: a see-through one cuts a hole where the page shows through it (one warning, still cut). It is its border box (`background-clip` and box shadows are not part of it), or its own `clip-path` when that is an `inset()`, `circle()` or `ellipse()`. What a parent's `overflow: hidden` hides of it cuts nothing (a closed mega menu in a header), and neither does a panel that is unseen: `visibility: hidden`, `opacity: 0`, or inside a closed `<details>` or `hidden="until-found"`.
955
+ - Panels (like GL elements) are found in the page's own DOM: one inside a shadow root (a web component) is not.
956
+ - It brings in `chunks/shapes.js`. With the canvas under the page (`createGL({ zIndex: -1 })`) the DOM already covers GL, and `data-gl-occlude` does nothing.
957
+ - A GL element inside an open modal `<dialog>` or popover (the browser's top layer, painted over the canvas whatever its `z-index`) shows its DOM, with one warning.
958
+ - A rotated, skewed or tilted parent cuts it through its own turned box (drawn per pixel). A three.js layer can't be cut by a rounded or shaped parent (it draws uncut and warns; straight clips do cut it).
959
+ - **Its own small file.** What cuts, turns or tilts an element, and following the animations that do, is `chunks/shapes.js` (about 14 KB brotli). The engine downloads it by itself, the first time an element on the page needs it: nothing to add or import. Until it arrives that element shows its DOM, as while its image loads (after 5 s it stays on its DOM with a warning; a late file is still used). What brings it in: any parent with `overflow` other than `visible` (the rounded card, the hover-zoom wrapper, a slider: they are there to cut), a `clip-path`, a CSS `mask`, `contain: paint` or `content-visibility: auto` on a parent, a legacy `clip: rect()`, `offset-path`, an element inside an `<svg>`, a rotation, skew, flip or 3D tilt (also a `translate` with a z or a `perspective`), and an animation that turns, clips or rounds a GL element, or one that is scroll-driven or paused (scrubbed). What does not: moves and positive scales (`translate`, `scale`, `transform: translate…() scale…()`), a fade (`opacity`, `visibility`), a size change, and animations that do only those; and `html, body { overflow-x: hidden }`, as long as the element sits inside `<body>`'s box.
960
+ - **Video has its own small file too.** A GL `<video>`, and an element a module feeds (`data-gl-scrub`), is drawn with `chunks/video.js` (about 3 KB brotli), downloaded by itself the first time the page has one (next to `chunks/gl.js` when the page already has it). Until it arrives that element shows its DOM.
961
+ - **One texture per image.** Elements that show the same image (the same `src`, or `data-gl-src`: a marquee's repeated slides, a thumbnail and its large view) share one GPU texture: it is fetched, decoded and uploaded once, and a later element with that image draws at once. It is freed when the last element showing it goes (or is far from the screen when GPU memory is full).
962
+
963
+ ### Turned, tilted and moving
964
+
965
+ - **Transforms are drawn like the DOM:** `rotate`, `skew`, mirrors (`scaleX(-1)`), the individual `rotate` / `scale` / `translate` properties, `transform-origin`, and 3D: `rotateX/Y`, `perspective()`, a parent's `perspective` and `perspective-origin`, `preserve-3d` and `backface-visibility: hidden` (a flip card draws only the face towards you), on the element or any parent. GL text inside them stays crisp: it is painted flat and turned by the GPU. Flat elements (no transform, or only translate and scale) take the same fast path as before, and a scroll still reads nothing for them: a turned element's matrix is measured once and only moved by the scroll.
966
+ - **Animations are followed by themselves.** Umber asks the browser which animations run (`document.getAnimations()`: CSS animations and transitions, `element.animate()`, scroll-driven `animation-timeline`) and measures only the elements they move, only while they run, once more when they end. An infinite one (a marquee) is followed while it is on screen, not once it scrolled away. A scroll-driven one is measured on the frames the page scrolls. Inline styles (GSAP, Webflow Interactions) are caught by the DOM watch, and drawn in the frame they are written: when your own `requestAnimationFrame` loop (or `gsap.ticker`) runs after Umber's and styles a GL element, Umber moves its next frame behind that loop, once, the way it follows Lenis, so only the first frame after it started shows the old value. A still page still draws 0 frames a second. `data-gl-live` is only for elements your own `requestAnimationFrame` loop moves.
967
+ - `element.animate()` fires no event, and neither do an animation's own controls, so Umber wraps the browser's `Element.prototype.animate` and `Animation.prototype` `play()`, `pause()`, `finish()`, `reverse()`, `cancel()`, `updatePlaybackRate()` and the `currentTime` / `startTime` / `playbackRate` setters while it runs: your call goes through untouched and returns the same thing; Umber only notes the animation and looks at it on the next frame. A Web Animation started from a timer, an `IntersectionObserver` or a library like Motion is followed from its first frame, also on a page that was asleep, and so is one built paused and started, finished, reversed or seeked later (a preloader done, a `setTimeout` intro). CSS animations and transitions share these methods. `gl.destroy()` puts the originals back.
968
+ - **Scrubbed animations:** a paused Web Animation whose time you set (`anim.pause(); anim.currentTime = x`, the usual way to scrub one from the scroll or a slider) is followed on the frame after each new time, from the scroll, an `input` event, a timer or your own `requestAnimationFrame` loop; one seen for the first time is measured once where it holds its element (built paused and seeked in one step).
969
+ - **Stylesheets are followed too:** a `<style>` added, removed or rewritten (a dev server, CSS-in-JS writing text), a `<link rel="stylesheet">` that loads late, or a stylesheet's `media` or `disabled` attribute changing measures every plane again. Rules added through the CSSOM (`sheet.insertRule()`, `adoptedStyleSheets`, what some CSS-in-JS libraries do in production) and a sheet turned off by script (`sheet.disabled = true`, `styleEl.disabled = true`) leave no trace in the DOM: call `gl.invalidate()` after them.
970
+ - Worth knowing: a scroll-driven animation in Chromium updates one frame after a `scrollTo()` made inside `requestAnimationFrame` (Lenis), so those elements trail by a frame there; Firefox has no scroll-driven animations (they don't run in the DOM either).
971
+ - **3D in Safari:** turned, skewed and masked elements match the DOM in Chromium, Firefox and WebKit. 3D tilts (`rotateX/Y` under `perspective`, flip cards, `preserve-3d`) match pixel by pixel in Chromium, Firefox and in what WebKit's compositor shows (99.96 % or more); WebKit's screenshots paint 3D without its perspective, so don't judge them from a WebKit screenshot. Not yet looked at by eye in real Safari (macOS and iOS): compare GL on against `?umber=off` there before you rely on 3D cards.
972
+ - **What falls back to the DOM** (with a warning that names the fix; GL takes it back when the cause goes): a tilt so strong that part of the element is behind the viewer (until it turns back); in WebKit browsers only (Safari, every iOS browser), a tilt whose `perspective` parent also cuts with `overflow` and `border-radius` (WebKit draws it flat: put the perspective on an inner element, or round the corners with `clip-path: inset(0 round …)`; seen in Playwright's WebKit build, not yet confirmed in real Safari); several GL elements facing you in one `preserve-3d` scene (a cube of GL images: GL can't depth-sort them; a flip card with hidden back faces is fine); `offset-path`; an element inside an `<svg>`; `zoom` on a turned element's parent (use `transform: scale()`); a box that doesn't match its transforms (seen almost edge-on). A three.js layer under a rotation is drawn upright in its box, with a warning (turn the camera instead). CSS `filter` on a parent is not drawn by GL (`gl.inspect()` notes it).
973
+ - **The canvas itself:** Umber's canvas is `position: fixed`. A `transform`, `filter`, `perspective`, `contain`, `will-change: transform` or `backdrop-filter` on `<body>` or `<html>` would make the canvas scroll or turn with the page, so GL turns off (the DOM shows) with a warning that names the property, until it goes: put it on a wrapper element inside `<body>` instead. A `filter` or `backdrop-filter` on `<html>` is fine (CSS exempts the root: a dark mode's `html { filter: invert(1) }` filters GL with the page). `zoom` on `<body>` is fine (the canvas moves out of `<body>`); on `<html>` it turns GL off too.
974
+
975
+ ```js
976
+ const plane = await gl.add(el, { type: "image", effects: ["dissolve"], options: { dissolve: { scale: 6 } } });
977
+ // a plane from code (resolves null with GL off); see below
978
+ const plane = gl.plane(el); // the element's plane, or null (GL off, not created yet)
979
+ gl.planes(); // every plane
980
+ gl.planes(container); // the planes inside an element (a Barba container)
981
+
982
+ plane.uniforms.uShow.value = 0.5; // a plain { value }: GSAP, Motion, your own code
983
+ plane.set("uShow", 0.5); // the same
984
+ plane.tween("uShow", { value: 1, duration: 1.2, delay: 0, ease: "expo.out" }); // Umber's own tween; await it
985
+ plane.play(); // run its effect's `play` uniform to 1, with that effect's options
986
+ plane.play({ value: 0, duration: 0.6 }); // ...or back to 0
987
+ plane.rect; // Float32Array [x, y, width, height]: this frame's viewport rect, CSS px (plane.rect[2] is the width).
988
+ // GL text: the padded quad its glyphs are painted in (descenders, italics: tens of px per side on large type), not the element's box: use el.getBoundingClientRect() or gl.track(el) for that
989
+ plane.inView; plane.progress; // on screen (the real screen, like gl.track()); 0 as its top enters at the bottom, 1 as its bottom leaves at the top
990
+ plane.status; // "loading" | "ready" | "error" (also "error" while a clip GL can't draw shows its DOM)
991
+ plane.effects; // [{ name, options }]
992
+ plane.kind; // "image" | "video" | "text" | "shader" | "layer" | "group"
993
+ plane.get("uShow"); // a uniform's value
994
+ plane.wake(); // draw at least one more frame (after changing an array uniform in place)
995
+ const off = plane.on("enter", (p) => {}); // also "ready", "leave", "resize", "error", "destroy", "text"; or plane.off(name, fn)
996
+ plane.text; // data-gl="text" only, once chunks/text.js is here: { lines, words, chars, version, progress() } (see GL text)
997
+ plane.destroy(); // the element shows as plain DOM again; gl.scan(el) brings it back
998
+ ```
999
+
1000
+ - **`gl.add(el, options)` writes the attributes** its options stand for (`type` -> `data-gl`, `effects` -> `data-gl-effect`, `options: { dissolve: { scale: 6 } }` -> `data-gl-dissolve-scale="6"`, plus `shader`, `layer`, `src`, `fit`, `order`, `live`, `clip` and `instances`) and builds the plane right away when GL is loaded. Same contract, written for you: the CSS handshake and the DOM watch key on those attributes. An element that has `data-gl` already resolves with its own plane. Inside `gl.scope()`, `revert()` removes the plane and puts the element's attributes back as they were.
1001
+ - `gl.plane(el)` works once `await gl.ready` resolved (or after the element's plane event `ready`). Before that, or with GL off, it is `null`: always write `gl.plane(el)?.play()`.
1002
+ - `plane.set("uX", v)` on a name no effect of that plane declares warns once (with the closest name it does have): nothing would read it.
1003
+ - A tween returns a promise-like `Tween` (`await`, `.pause()`, `.play()`, `.kill()`). A new tween on the same uniform replaces the old one, so two triggers never fight.
1004
+
1005
+ ### Plays: an effect's uniform that runs 0 → 1 by itself
1006
+
1007
+ An effect that names `play: "uShow"` gets the shared play options, set per element:
1008
+
1009
+ | Option | Default | Meaning |
1010
+ |---|---|---|
1011
+ | `trigger` | `"auto"` | `auto`: on screen when the plane is made, it plays at once; further down, when scrolled into view. `scroll`: always waits for the scroll. `load`: at once, wherever it is. `manual`: only `gl.plane(el)?.play()`. `hover`: 0 to 1 while the pointer is over the element (or its closest `a` or `button`), back to 0 when it leaves; `delay` counts on enter, reduced motion jumps without the tween. |
1012
+ | `delay` | `0` | Seconds, counted from the moment it may play. |
1013
+ | `duration` | `1.4` | Seconds (the effect's own `options.duration` overrides it). |
1014
+ | `ease` | `"umber"` | Any ease (below). |
1015
+ | `start` | `"top 90%"` | For scroll: `"<element edge> <screen line>"`. Edge: `top`, `center`, `bottom`. Line: `top`, `center`, `bottom`, `80%`, `600px`. A `center` or `bottom` edge works on elements taller than the screen too, and one already past the line plays at once. No offsets (`top+=100`): those are for `gl.progress()` and scrub. |
1016
+
1017
+ ```html
1018
+ <div data-gl="image" data-gl-effect="dissolve" data-gl-dissolve-trigger="scroll"
1019
+ data-gl-dissolve-delay="0.2" data-gl-dissolve-start="top 75%"><img src="a.jpg" alt=""></div>
1020
+ ```
1021
+
1022
+ - `gl.hold()` holds every play back until you release it (a transition overlay still covers the page). Under reduced motion, plays show at once.
1023
+ - **Eases** (plays, `plane.tween`, morphs): `"umber"` (the default, `cubic-bezier(0.625, 0.05, 0, 1)`), `"linear"`, the CSS keywords (`"ease-out"`...), `"cubic-bezier(a, b, c, d)"`, CSS `"linear(0, 0.6 40%, 1)"` (paste any spring or bounce exported for CSS), `"spring"` / `"spring(0.3)"`, `"<family>.in | .out | .inOut"` with `quad cubic quart quint sine expo circ` or `power1`..`power4`, or a function `(t) => number`.
1024
+ - **Springs:** `"spring(bounce)"`, bounce 0 (no overshoot) to 0.95, default 0.2; the duration is the time it takes to settle. In `plane.tween` and plays it runs as a real spring: it starts with the speed the value already had, so a hover reversed half-way turns round smoothly, and it ends (no more frames) once at rest: `el.onmouseleave = () => plane.tween("uHover", { value: 0, duration: 0.6, ease: "spring(0.3)" })`.
1025
+
1026
+ ### GL text (`data-gl="text"`)
1027
+
1028
+ The real text stays in the DOM: selectable, crawlable, read aloud, found by find-in-page. Umber asks the browser where it placed every glyph, paints them into a texture at those spots, and once the GPU drew them the DOM text turns transparent. Any effect then works on text.
1029
+
1030
+ The text painter is its own small file (`chunks/text.js`). The engine downloads it by itself, next to `chunks/gl.js`, only on pages with a `data-gl="text"` element: there is nothing to add or import for it, and until it arrives the DOM text simply shows.
1031
+
1032
+ - **Supported:** any loaded font, weight, style, size, a colour and an opacity per span (hover and theme changes to the colour, opacity, font, weight or spacing repaint), letter-spacing, text-transform (upper case in the text's `lang`: Turkish i becomes İ), small caps and condensed faces, several lines, inline children, emoji, right-to-left text, the hyphen the browser draws under `hyphens: auto` or at a soft hyphen (in every engine), and `-webkit-font-smoothing: antialiased` / `-moz-osx-font-smoothing: grayscale` on macOS (GL paints the same weight as the DOM: the text is painted in a hidden canvas inside Umber's host, `data-gl-canvas="text"`, which takes the element's font smoothing). Each line's baseline sits on the device-pixel grid, as the browser puts it. Words for `glyph()` come from the browser's word segmenter, so Japanese and Chinese have real words, not one word per line.
1033
+ - **Not supported** (Umber notices, marks it `error` and the DOM text stays): gradient or `background-clip` text, text strokes, `font-feature-settings` that changes glyphs (`kern`, `liga`, `clig` and `calt` are fine), `font-variation-settings`, `font-variant-numeric` and the other `font-variant-*` values, a `font-stretch` between the keyword widths (`80%`), underlines and other text decorations (line-through, overline), scripts that need letter shaping (Arabic, Indic, Thai), vertical `writing-mode`, `text-overflow: ellipsis` and line-clamp, `::before` / `::after` content and list markers, a styled `::first-letter` or `::first-line` (a drop cap, also on a paragraph inside the element), `text-shadow`, a `-webkit-text-fill-color` other than its `color`, discretionary or historical ligatures, `font-size-adjust`, `text-transform: full-width` or `full-size-kana`, and text that runs past its element's box (a `nowrap` line wider than it: let it wrap, or put `data-gl="text"` on an element as wide as its text; or lines below a box too short for them). Inside rotated, skewed or tilted parents it works (each glyph is placed back through the element's matrix).
1034
+ - **Inside the text element:** transforms are undone (a split unit pushed down, scaled or turned by a reveal is painted where the layout puts it, see Splitting text); 3D transforms are painted as drawn, with a warning. Clips (a line mask) are not painted: masks are free in GL, per line or word with `glyph()`, no wrapper elements needed. Screen-reader-only text (absolute, 1 x 1 px, overflow cut) is never painted. An inline `<svg>` icon is not text: it stays DOM and does not move with a GL effect.
1035
+ - **Text changes** (a split, a re-split on resize) repaint once the text was quiet for 100 ms and the size for 150 ms; the old texture shows until then. Text that is cleared draws nothing in GL (and `plane.text` is empty) until it comes back.
1036
+ - **Per line, word and character: `glyph(uv)`.** A text plane is one rectangle with one texture, so to tell lines apart an effect asks `glyph(vUv)` (see Writing effects). When an effect on a text plane calls it, Umber also paints a small glyph index while it paints the text (which line, word and character owns each pixel, and their boxes); text planes whose effects never call it pay nothing. `examples/text/lines.html` reveals one heading line by line and one paragraph word by word.
1037
+ - **Whole runs, like the page:** each stretch of text on one line is painted in one go, so ligatures, kerning and contextual letters match the DOM, and a long paragraph reads a few rects per line instead of one per letter. Where the painted width is not the page's (justified text) or the browser hyphenated, it paints letter by letter at the browser's own spots.
1038
+
1039
+ ### Lines, words and characters in JS: `plane.text`
1040
+
1041
+ Every text plane hands its units to JS (no extra layout read: they come from the paint):
1042
+
1043
+ ```js
1044
+ const plane = gl.plane(h1); // data-gl="text"
1045
+ const { lines, words, chars } = plane.text; // [] until the first paint; plane.text itself is undefined until chunks/text.js arrived (use plane.text?.lines)
1046
+ lines[1].text; // "second line" (white space collapsed)
1047
+ lines[1].box; // { x, y, w, h }: element CSS px at rest, from its top-left
1048
+ lines[1].words; lines[1].chars; // [first, last] word and character
1049
+ words[3].line; chars[9].word; // which line / word they are in
1050
+ plane.text.version; // +1 per paint that changed them
1051
+ plane.on("text", (p) => {}); // after a paint that changed them (a rewrap, new text); not after a colour-only repaint
1052
+ ```
1053
+
1054
+ - **Numbering:** the same as `glyph()` in GLSL, so `lines[i]` in JS is `g.line == i` in a shader. Where the site split its own lines (`[data-line]` elements), those are the lines.
1055
+ - **Four numbers per unit, `t`, `x`, `y`, `z`** (0 at first): plain properties, so GSAP, Motion or your own loop tween them (`gsap.to(plane.text.lines, { t: 1, stagger: 0.08 })`), or Umber's own: `lines[i].tween("t", { value: 1, delay: i * 0.08 })`. They mean whatever your code makes of them; Umber reads none itself. They are kept by index when the text rewraps (listen to `"text"` to start again on new lines). On planes whose effects call `glyph()` they also travel to the GPU with the glyph index: a shader reads them as `g.lineValue`, `g.wordValue` and `g.charValue` (`vec4(t, x, y, z)`; a write wakes one frame; a page that writes none stays idle).
1056
+ - **Scroll per line or word:** `plane.text.progress("lines" | "words", { start, end })` makes one `gl.progress()` per unit, with `start` / `end` measured from that unit's own edges (`"top 80%"`: this line's top at 80 % of the screen). Not for characters (thousands of trackers): use their word's. They are measured once like any `gl.progress()`; make them again after a `"text"` event.
1057
+ - **CSS counts:** the element gets `--gl-lines`, `--gl-words` and `--gl-chars` (in a rule of Umber's own stylesheet, not its style attribute), for a DOM fallback that sizes things by them: `.reveal { --step: calc(1s / var(--gl-lines, 1)); }`.
1058
+
1059
+ ```js
1060
+ // Each line's `t` follows that line's own scroll from 85 % to 55 % of the screen.
1061
+ const { lines } = plane.text;
1062
+ plane.text.progress("lines", { start: "top 85%", end: "top 55%" }).forEach((p, i) => p.on("change", () => (lines[i].t = p.value)));
1063
+ ```
1064
+
1065
+ ### Splitting text (your own spans, or GSAP's Split Text plugin)
1066
+
1067
+ A site may split the text of a `data-gl="text"` element into lines, words or characters itself, with its own spans or GSAP's Split Text plugin. It keeps working:
1068
+
1069
+ - **GL paints the rest pose.** If the reveal sets its first pose in the same task as the split (lines at `yPercent: 100`, characters at `scale: 0`), Umber undoes those transforms while painting, so the texture never bakes in a hidden pose. Opacity is painted as the page has it (a word at `opacity: 0` is painted transparent).
1070
+ - **A DOM tween on the units shows.** While a tween writes the units' inline styles (GSAP fading or raising words), or a CSS animation or transition moves or fades one, GL can't follow it frame by frame: the element shows its DOM (`data-gl-status="error"`, `gl.inspect()` says why; no warning and no `error` event: nothing failed), and GL takes it back, painted as the units ended, once they held still for 150 ms (its `ready` event comes again). GL effects on that element pause meanwhile. An animation that never ends (a blinking caret), one that runs with the scroll, or one on a `::before` / `::after` is not waited for: GL paints the units as they stand. Writing only custom properties on the units (`--line`) is not an animation. A class that only changes a unit's colour repaints instead.
1071
+ - **One repaint per split**, not one per mutation or per resize frame (see above). A split heading's characters that only inherit their colour are not watched for hover colour changes; the element itself, links and elements with their own colour are.
1072
+ - **Who animates what:** GL on and the plane `ready`: Umber (a `glyph()` effect). GL off (`html:not(.has-gl)`) or the plane `error`: the site's DOM reveal. GL still loading: nobody yet (hold the reveal with `gl.hold()` or a `trigger`).
1073
+
1074
+ The recipe: split for the DOM fallback only, let GL animate when it runs.
1075
+
1076
+ ```html
1077
+ <h2 class="reveal" data-gl="text" data-gl-effect="lines" data-gl-lines-trigger="manual">Real, crawlable text</h2>
1078
+ ```
1079
+
1080
+ ```js
1081
+ await document.fonts.ready;
1082
+ const el = document.querySelector(".reveal");
1083
+
1084
+ // 1. Split (GSAP's Split Text plugin with type "lines", or your own spans): one element per line, index in --line.
1085
+ split(el).lines.forEach((line, i) => line.style.setProperty("--line", i));
1086
+
1087
+ // 2. GL animates when it runs; CSS animates the split when it doesn't.
1088
+ gl.ready.then(() => gl.plane(el)?.play());
1089
+ ```
1090
+
1091
+ ```css
1092
+ /* DOM fallback only: GL is off, or this element fell back */
1093
+ html:not(.has-gl) .reveal .line,
1094
+ .reveal[data-gl-status="error"] .line {
1095
+ animation: rise 0.9s cubic-bezier(0.23, 1, 0.32, 1) both;
1096
+ animation-delay: calc(var(--line) * 80ms);
1097
+ }
1098
+ @keyframes rise { from { transform: translateY(100%); opacity: 0; } }
1099
+ ```
1100
+
1101
+ `lines` is the `glyph()` effect from Writing effects (`examples/effects/lines.js`). A GSAP timeline that already tweens the split's units can stay as it is: its DOM shows while it runs, and GL takes the text back once the units hold still. To keep GL effects running during the reveal, let GL animate it instead.
1102
+
1103
+ ### Engine controls (mostly escape hatches)
1104
+
1105
+ | Call | What it does |
1106
+ |---|---|
1107
+ | `gl.scan(root?)` | Look for `[data-gl]` now (normally automatic). |
1108
+ | `gl.prune()` | Destroy planes whose element left the page (normally automatic). |
1109
+ | `gl.destroy(el)` | Destroy one element's plane (the element stays and shows). `gl.destroy()` ends the whole engine; `gl.destroy(null)` (a selector that found nothing) ends nothing and warns. |
1110
+ | `gl.invalidate(el?)` | Measure every plane (or one) again on the next frame, and read its effect options again (after a CSSOM change: `insertRule()`, `adoptedStyleSheets`, or a `data-gl-<effect>-<option>` your code changed). |
1111
+ | `gl.live(true \| false \| seconds)` | Measure every visible plane every frame. |
1112
+ | `gl.wake(frames?)` | Draw at least that many more frames. |
1113
+ | `gl.pause()` / `gl.resume()` | Stop drawing and show the DOM, then draw again. A `pause()` before GL is ready holds too: it starts paused. |
1114
+ | `gl.info` | Numbers: state, planes, visible, draws, textures, `textureMB` (image, video and text textures on the GPU), `targetMB` (render targets: groups, passes, sims, `gl.leave` copies, your `gl.target`s; there once `chunks/fx.js` is), `gpuMB` (everything that counts against the device's GPU memory budget: textures, render targets, cached video frames and the canvas itself), programs, fps, renders per second, dpr, scale, `busy` (why it keeps drawing), `tier` (`high` / `mid` / `low`) and `gpu` (the GPU tier: `level` 0 to 5, `reason`, `renderer`...: [debug.md](debug.md)). |
1115
+ | `gl.canvas`, `gl.context` | The canvas and its WebGL2 context (null when GL is off). |
1116
+ | `gl.version`, `gl.destroyed`, `gl.off(name, fn)` | The engine's version; `true` after `gl.destroy()`; the other way to remove an `on()` listener. |
1117
+
1118
+ ---
1119
+
1120
+ ## Writing effects (the heart of "an engine, not a library")
1121
+
1122
+ An effect is a few lines of GLSL that Umber puts into named slots of its own shader. You never write a whole shader. You list uniforms as plain values and Umber writes their GLSL declarations. Register it once, any time after `createGL()` (before or after GL has loaded), and use it on any plane:
1123
+
1124
+ ```js
1125
+ gl.effect("tint", {
1126
+ uniforms: { uTint: [1, 0.4, 0.2] }, // vec3, declared for you
1127
+ fragment: { color: "color.rgb *= uTint;" },
1128
+ });
1129
+ ```
1130
+ ```html
1131
+ <div data-gl="image" data-gl-effect="tint"><img src="a.jpg" alt=""></div>
1132
+ ```
1133
+
1134
+ A plane waiting for an effect that is not defined yet is built again when it arrives. A typo warns: `data-gl-effect="tnit" on <div.card>: no effect with that name (did you mean "tint"?)`.
1135
+
1136
+ ### The shape
1137
+
1138
+ ```js
1139
+ gl.effect("name", {
1140
+ uniforms: { uShow: 0, uColor: [1, 1, 1], uNoise: "/noise.png" }, // number -> float, [..] -> vec2..4 (9 -> mat3, 16 -> mat4), URL -> sampler2D
1141
+ // ...or a Signal, followed live: { uStory: gl.progress(".story"), uPointer: gl.pointer } (see Utilities)
1142
+ // ...or a live texture from the input module: { uMask: gl.texture(canvas), uTouch: gl.touch() } (see Inputs)
1143
+ options: { strength: 1, duration: 1.2 }, // per element: data-gl-name-strength > --gl-name-strength > this
1144
+ reduced: { uWave: 0 }, // optional: these values instead, when the visitor prefers reduced motion
1145
+ play: "uShow", // optional: Umber plays it 0 -> 1 (trigger, delay, duration, ease, start)
1146
+ segments: 1, // > 1 when vertex.main bends the plane (24 is plenty)
1147
+ vertex: { head, main }, // main: change `pos` (vec3, px offset in its own axes) using `uv` (0..1)
1148
+ fragment: { head, uv, color, alpha }, // uv: before sampling · color: vec4 · alpha: float
1149
+ setup(ctx) { /* once per plane; return a cleanup */ },
1150
+ update(ctx) { /* every drawn frame while on screen (ctx.frame is set) */ },
1151
+ });
1152
+ ```
1153
+
1154
+ - **Options become uniforms.** Every number, boolean (0 or 1) or array option is also a uniform named `u` + Effect + Option: effect `dissolve`, option `scale` → `uDissolveScale`. Set it per element with `data-gl-dissolve-scale="6"` or per breakpoint with `--gl-dissolve-scale: 6`. Options are read when the plane is built and again when the window resizes (a new breakpoint) or you call `gl.invalidate(el)` (after your code changed a `data-gl-<effect>-<option>` or a class): only an option that changed reaches its uniform, so a value you set with `plane.set()` stays until then.
1155
+ - **Colours.** A CSS colour string, as a uniform, an option, an attribute, a `--gl-*` variable or in `plane.set()`, becomes a `vec4` [r, g, b, a] in sRGB (the page's own space): `uniforms: { uTint: "#ff3300" }`, `options: { color: "#fff" }` with `data-gl-tint-color="oklch(70% 0.15 30)"` or `data-gl-tint-color="var(--brand)"`. The browser converts it the way it converts the DOM's colours, so every CSS colour works (hex, rgb, hsl, oklch, `color(display-p3 ...)`, names); wide-gamut colours land where an sRGB screen shows them. `var()` is read from each element once, when the plane is built (or at `plane.set`), never per frame; `var(--brand, #0f0)` takes its fallback where `--brand` is not set. A `var()` that is not set and has no fallback is transparent, with a warning. A `uniform vec3` you declare yourself takes r, g, b. Give a colour option a colour default, so every element has the `vec4`.
1156
+ - **Uniforms you declare yourself** can be `float`, `vec2..4`, `mat2`, `mat3`, `mat4`, the non-square `mat2x3`..`mat4x3`, `int`, `ivec2..4`, `bool`, `bvec2..4`, `uint` or `uvec2..4`, and arrays of them: `uniform ivec2 uCell;` takes `[2, 3]`, `uniform float uWeights[5];` takes 5 numbers, `uniform mat3x2 uWarp;` takes 6 (a plain array or a `Float32Array`, column by column). Numbers that fit no type Umber declares (not 2, 3, 4, 9 or 16 of them) and that your GLSL reads without declaring warn: declare them, or make them a texture with `gl.texture()`. More numbers than a phone's uniforms hold (over 896) are data: Umber warns and names `gl.texture()`.
1157
+ - **Per-element images (maps).** A string option with a `/` in it is an image path, and its uniform a `sampler2D`: effect `depth`, `options: { map: "/img/blank.webp" }`, `data-gl-depth-map="/img/hero-depth.webp"` → `uDepthMap`. Sample it with the image's own crop, `texture(uDepthMap, fitUv(uv))`, and it stays in line with the image whatever `object-fit` and `object-position` do. Every element with the effect needs a path (give the option a default image), or its program has no `uDepthMap` and the element shows its DOM.
1158
+ - **`bleed`: drawing past the element.** An option named `bleed` (px) makes the plane's quad that much larger on every side (the largest `bleed` of its effects): glows, shadows, sparks. `uv` and `vUv` still run 0..1 on the element itself and go below 0 and above 1 in the bleed, where `sampleImage()` repeats the edge pixels: your effect decides what draws there (`alpha *= step(0.0, uv.x) * step(uv.x, 1.0) * ...` keeps only the box). Set it per element: `data-gl-glow-bleed="60"`. It is drawn while the element itself is on screen, and parents that clip still cut it (`data-gl-clip="false"` lifts that).
1159
+ - **Reduced motion, per effect.** `reduced: { uniform: value }` replaces those uniforms when the visitor prefers reduced motion (and `createGL({ reducedMotion })` is `"static"`, the default): keep a fade or a colour change, set a wave or a parallax to 0. `ctx.reducedMotion` says the same in `setup` and `update`. Plays still show at once under reduced motion.
1160
+ - **Slots run in their own `{ }` block**, so local names never clash between effects. To share a value between two slots of your effect, declare a global in `head`: `head: "float linesMask = 1.0;"`.
1161
+ - **Two effects may write a helper of the same name.** When two effects on one plane (or an effect and the shader) both declare the same name at the top of their `head` (a function, a `const`, a global, a `#define`), each effect's own is renamed (`e0_wave`, `e1_wave`) in all of that effect's code, so they stack without a compile error. A name only one of them declares stays as it is, so an effect may still call a helper another one declares. Function bodies, parameters and GLSL keywords are never renamed.
1162
+ - **Order matters:** `data-gl-effect="a b"` runs `a`'s uv slot, then `b`'s; then `a`'s color slot, then `b`'s; and so on.
1163
+
1164
+ ### What your GLSL can use (a fixed contract: only ever added to)
1165
+
1166
+ | | Name | Meaning |
1167
+ |---|---|---|
1168
+ | Coordinates | `vUv` | 0..1 inside the element, (0, 0) top-left (y down, like the DOM). In slots: `uv` (change it in `uv`). |
1169
+ | Inputs | `uSize`, `uViewport` | The element's and the viewport's size, CSS px. |
1170
+ | | `uRect` | x, y, width, height in viewport px. |
1171
+ | | `uPlaneMatrix` | `mat3`: the element's own px (0..`uSize`) to viewport px. A translation for a flat element; rotation, skew and perspective for a turned one (below). |
1172
+ | | `uMouse` | The pointer inside the element, 0..1 along its own edges (needs `ctx.trackMouse(true)`). |
1173
+ | | `uTime` | Seconds (only advances on drawn frames; stands still under reduced motion with `reducedMotion: "static"`). An effect reads it to move by itself: it draws every frame only while something asks (a play, `ctx.busy(true)`, a hover play that is on: below). |
1174
+ | | `uScrollVelocity` | Smoothed scroll speed: px per second / 3600, clamped to -1..1, so `gl.scroll.velocity / 60` (that is px per 60 Hz frame). A brisk wheel gives about 0.1 to 0.3, a fling 1. Multiply it in GLSL to taste (`uScrollVelocity * 4.0`). 0 under reduced motion. |
1175
+ | | `uProgress` | 0 as the element's top enters at the bottom of the screen, 1 as its bottom leaves at the top. |
1176
+ | | `uAlpha`, `uDpr` | The element's opacity (with its parents'), device px per CSS px. Fragment only. |
1177
+ | | `uImage`, `uImageSize` | The texture and its pixel size. Fragment only. |
1178
+ | | `uCanvas` | The size of what this draw goes into, device px: the canvas, or the texture of a group or `gl.snapshot()`. Fragment only. |
1179
+ | | `uSurface` | Where this draw goes, viewport CSS px: `vec4(x, y, width, height)`. On the canvas it is `(0, 0, uViewport)`. Inside a group's texture or a `gl.snapshot()` it is that window, with a negative height (the target's rows run up). Positions map through it, so `uViewport` keeps meaning the viewport whatever Umber draws into. |
1180
+ | | `uBleed` | Px the quad reaches past the element on every side (the `bleed` option; 0 without). |
1181
+ | | `uScreen` | `vec2`: the element's centre on the viewport, -1..1 on both axes (y down): 0, 0 in the middle of the screen. Rotating galleries, depth by distance from the centre. |
1182
+ | | `PI` | 3.14159... |
1183
+ | Helpers | `sampleImage(uv)` | The image or video pixel at `uv`, object-fit applied. Fragment only. |
1184
+ | Helpers | `sampleRaw(uv)` | `sampleImage(uv)` premultiplied: add these up for a blur, then make the sum straight once (`c.rgb /= max(c.a, 1e-5)`). Fragment only. Added when called. |
1185
+ | | `fitUv(uv)` | The image's own crop at `uv` (object-fit and object-position): `texture(uMap, fitUv(uv))` keeps a map in line with its image. Fragment only. |
1186
+ | | `roundedBox(p, size, radii)` | Signed distance (px) to a rounded box: `p` px from its top-left, `radii` a `vec4` per corner (top-left, top-right, bottom-right, bottom-left), e.g. `vec4(12.0)`. Corners follow CSS: two that add up to more than their side shrink (`vec4(1e4)` is a pill), and one bigger than half the box is drawn whole (a leaf). Fragment only. |
1187
+ | | `noise(vec2)`, `noise(vec3)` | Smooth value noise, 0..1. Added only when you call it (with `chunks/glsl.js`, below). |
1188
+ | | `fbm(vec2)` | Four octaves of noise, 0..1 (clouds, dissolves). Added when called. |
1189
+ | | `rotate2d(angle)` | A `mat2` that turns a `vec2`. Added when called. |
1190
+ | | `umberHash(vec2)`, `umberHash(vec3)` | A random-looking 0..1 per point (what `noise` is built on). Added when called. |
1191
+ | | `screenPx()` | This pixel's position on screen, viewport CSS px (y down), whatever turns or tilts the element. Fragment only. Added when called. Use it, not `uRect.xy + vUv * uRect.zw`, to compare with page positions like `gl.pointer`. Also right on a group's members, in a snapshot and in a `data-gl-pass` (there: this pixel of the pass's surface). |
1192
+ | | `screenUv()` | This pixel on screen, 0..1 over the viewport, (0, 0) top-left: `screenPx() / uViewport`. Fragment only. Added when called. For effects that need screen-space coordinates (a screen-sized pattern, a texture the size of the screen such as `uFlow` or `gl.touch()`). Also right on a group's members, in a snapshot and in a `data-gl-pass`. |
1193
+ | A new picture | `samplePrev(uv)` | The picture an image plane showed before its `src` changed (`data-gl-src`, or the `<img>`'s `src` / `srcset`), object-fit applied like `sampleImage`. Fragment only. Added when called. |
1194
+ | | `uSwap` | 0 -> 1 after a new picture is on the GPU (`data-gl-swap-duration`, default 0.8 s); 1 the rest of the time. `uPrev` / `uPrevSize` are the old texture and its size (`samplePrev` reads them). |
1195
+ | GL text | `glyph(uv)` | Which line, word and character `uv` is in: a `Glyph` (below). Added when called. |
1196
+ | Scrub planes | `uScrubProgress`, `uScrubVelocity` | Only on `data-gl-scrub` videos (see Scrub). |
1197
+
1198
+ **Rotated, skewed, mirrored or 3D-tilted elements** (by themselves or a parent) are drawn as their own quad, and your effect works in the element's own space: `vUv` runs along its own edges (perspective-correct), `pos` in `vertex.main` is a px offset along its own axes (a bend follows the tilt), `uMouse` is the pointer along its own edges. `uSize` is its layout size at its on-screen scale (for a rotation or a uniform scale: exactly its size along its edges; under a skew or a tilt, the layout's proportions, so `object-fit` and corners match the DOM), and `uRect` is its centre - `uSize` / 2 with `uSize`. A flat element (no transform, or only translate and scale) gets exactly what it got before: `uRect` is its rect and `uPlaneMatrix` a translation. `pos.z` still only feeds depth.
1199
+
1200
+ `vertex.main` sees `uViewport`, `uRect`, `uSize`, `uPlaneMatrix`, `uTime`, `uScrollVelocity`, `uMouse`, `uProgress`, the on-demand helpers and your own uniforms except textures (an instanced plane also declares the textures its vertex code names: see Instances). The ones marked "fragment only" are not declared there: using them in `vertex.main` is a compile error and the plane shows its DOM.
1201
+
1202
+ **`glyph(uv)` on `data-gl="text"` planes.** It returns a struct; boxes are `vec4(x, y, width, height)` in the plane's uv (0..1, y down), so you compare them with `vUv`:
1203
+
1204
+ ```glsl
1205
+ struct Glyph {
1206
+ float line, word, char; // 0-based: line in reading order; word and char over the whole element
1207
+ float lines, words, chars; // the counts (white space is not a character)
1208
+ vec4 lineBox, wordBox, charBox;
1209
+ float ink; // fragment shader: the painted text's coverage at uv, 0..1
1210
+ vec4 lineValue, wordValue, charValue; // plane.text's t, x, y, z of this line, word and character (0 until set)
1211
+ };
1212
+ ```
1213
+
1214
+ - Every pixel belongs to a character: the nearest one on its line, and lines split the space between them so that each glyph's own ink (a descender in tight leading) stays on its line. A word broken over two lines is two words.
1215
+ - Ask `glyph(vUv)` (where the pixel is), then move `uv`. To mask each line to itself, compare with the line of where you sample: `glyph(uv).line == g.line`.
1216
+ - It costs nothing unless an effect calls it: only then does the text plane paint its glyph index (an exact `R16UI` texture of about one texel per CSS px, plus a small `RGBA32F` table) and skip mipmaps (a per-line offset jumps between neighbouring pixels, which would pick the smallest mip level and draw a grey seam).
1217
+ - On any other plane, and on text before its index arrived, it answers "one line, one word, one character covering the whole element" (and warns once on non-text planes).
1218
+
1219
+ ```js
1220
+ gl.effect("lines", { // examples/effects/lines.js
1221
+ play: "uShow", uniforms: { uShow: 0 }, options: { duration: 1.8, ease: "linear", stagger: 0.5 },
1222
+ fragment: {
1223
+ head: "float linesT = 1.0; float linesMask = 1.0;",
1224
+ uv: `Glyph g = glyph(vUv);
1225
+ linesT = clamp(uShow * (1.0 + uLinesStagger) - g.line / max(g.lines - 1.0, 1.0) * uLinesStagger, 0.0, 1.0);
1226
+ float k = 1.0 - pow(1.0 - linesT, 4.0);
1227
+ uv.y -= (1.0 - k) * g.lineBox.w * 1.1; // each line slides up, eased on its own
1228
+ linesMask = glyph(uv).line == g.line ? 1.0 : 0.0;`, // out of its own mask
1229
+ alpha: "alpha *= linesMask * smoothstep(0.0, 0.25, linesT);",
1230
+ },
1231
+ });
1232
+ ```
1233
+
1234
+ Helpers you define yourself win: if your `head` has its own `float noise(vec2 p)`, Umber leaves its own out (for every effect on the plane; when two effects both define one, each calls its own, see above).
1235
+
1236
+ ### A new `src`: the old picture gives way
1237
+
1238
+ A plane whose picture changes (a slideshow writing `img.src`, a framework reusing the `<img>`, `data-gl-src` set from code) keeps drawing the old one until the new one is decoded and on the GPU, so the DOM never shows through. With no effect that asks, the new picture then replaces it. An effect that reads `uSwap` decides how the two meet (the tween is in `chunks/flip.js`, fetched with that effect's first plane; a swap before it is there, or under reduced motion, happens at once):
1239
+
1240
+ ```js
1241
+ gl.effect("crossfade", {
1242
+ fragment: { color: "color = mix(samplePrev(uv), color, uSwap);" },
1243
+ });
1244
+ // a wipe, left to right with a soft edge:
1245
+ // color = mix(samplePrev(uv), color, smoothstep(uv.x, uv.x + 0.15, uSwap * 1.15));
1246
+ ```
1247
+
1248
+ ```html
1249
+ <div data-gl="image" data-gl-effect="crossfade" data-gl-swap-duration="0.9"><img src="a.jpg" alt=""></div>
1250
+ <script>document.querySelector("[data-gl] img").src = "b.jpg";</script>
1251
+ ```
1252
+
1253
+ `color` is the new picture (`sampleImage`), `samplePrev(uv)` the old one with its own crop (the two may have different sizes). Both are straight alpha. Under reduced motion the new one simply replaces the old one. A second `src` while one blends: the old picture stays until the newest one is ready, then blends from there. Images only: a `<video>`'s new `src` shows its new frames as they come.
1254
+
1255
+ ### Shared GLSL: `gl.chunk()`
1256
+
1257
+ A chunk is a named piece of GLSL that any effect pulls in with a line of its own, in any slot (usually `head`):
1258
+
1259
+ ```js
1260
+ gl.chunk("sdf", `
1261
+ float sdCircle(vec2 p, float r) { return length(p) - r; }
1262
+ float sdBox(vec2 p, vec2 b) { vec2 d = abs(p) - b; return length(max(d, 0.0)) + min(max(d.x, d.y), 0.0); }
1263
+ `);
1264
+ gl.effect("ring", {
1265
+ fragment: {
1266
+ head: '#include "sdf"',
1267
+ alpha: "alpha *= 1.0 - smoothstep(0.0, 0.01, abs(sdCircle(uv - 0.5, 0.4)) - 0.02);",
1268
+ },
1269
+ });
1270
+ ```
1271
+
1272
+ - **Only included chunks are compiled**, once per program, however many effects include them: after Umber's helpers, before the effects' `head`s. A chunk may `#include` other chunks; they come first. Vertex code gets the chunks its vertex slots include, fragment code those of its fragment slots.
1273
+ - **A chunk is never renamed**, so every effect that includes it calls the same functions. It may call Umber's helpers (`noise`, `fbm`...).
1274
+ - **Any time, any order.** An element whose effect includes a chunk that is not defined yet shows its DOM (one warning: `#include "sdf": no chunk has that name... Define it with gl.chunk("sdf", glsl).`) and is built again when `gl.chunk()` defines it. Defining a chunk again rebuilds the planes that use it.
1275
+ - Includes, helper renaming and the helpers added when called (`noise`, `fbm`, `rotate2d`, `umberHash`, `screenPx`, `screenUv`, `uScreen`, `samplePrev`) come with `chunks/glsl.js`, fetched the first time a plane needs it (an `#include`, a helper call, or two effects with a `head` on one plane). That plane shows its DOM until then; pages that need none of it never download it. `glyph()` comes with `chunks/text.js` the same way. When your `alpha` slot runs, `alpha` already holds the element's opacity and its corners (CSS border-radius): multiply it (`alpha *= ...`), don't overwrite it. The output is premultiplied for you.
1276
+
1277
+ **After your `alpha` slot, Umber cuts the plane where its parents cut it in the DOM** (a rounded `overflow: hidden`, a `clip-path`; straight clips are a scissor). Whatever your effects do, nothing shows outside those clips, a bend in `vertex.main` included. Names starting with `uUmber` or `umber` are Umber's own: don't name your uniforms or functions that way.
1278
+
1279
+ ### The helper pack (eases, noise, shapes, blend, dither, Oklab)
1280
+
1281
+ More helpers, in the same contract: call one and it is there, with what it needs, once. They live in their own file (`chunks/glsl.js`, about 4.6 KB brotli): it downloads the first time an effect's code calls one, and a program carries only the helpers its code calls. A function of the same name in your own `head` wins. Each is also a `gl.chunk()` under its own name, so `#include "snoise"` works too (what it needs comes first, once); a `gl.chunk("snoise", ...)` of your own keeps that name for your code.
1282
+
1283
+ | Group | Helpers | What they give |
1284
+ |---|---|---|
1285
+ | Eases | `quadIn`, `quadOut`, `quadInOut`, and the same for `cubic`, `quart`, `quint`, `sine`, `expo`, `circ` | The curves plays use (`expoOut(t)` = `ease: "expo.out"`). `t` 0..1 (clamped), result 0..1. |
1286
+ | | `cubicBezier(t, vec4(x1, y1, x2, y2))`, `umberEase(t)` | Any CSS `cubic-bezier()`; Umber's default ease. |
1287
+ | | `stagger(progress, index, count, overlap)` | One item's own 0..1 when `count` items share one 0..1. `overlap` 0: one after another, 1: all at once. With `glyph()`: `stagger(uShow, g.word, g.words, 0.6)`. |
1288
+ | Noise | `snoise(vec2)`, `snoise(vec3)` | Simplex noise, about -1..1, no grid look at any scale. Time as the third axis animates it. |
1289
+ | | `pnoise(p, period, spin)` | Gradient noise that repeats every `period` cells (`pnoise(uv * 4.0, vec2(4.0), 0.0)` tiles the element seamlessly); `spin` turns it, a full turn (2 PI) loops seamlessly. |
1290
+ | | `cellular(vec2)`, `cellular(vec3)` | Distance to the nearest (`x`) and second-nearest (`y`) random point: cells `1.0 - c.x`, cracks `c.y - c.x`. |
1291
+ | Shapes | `sdCircle(p, r)`, `sdBox(p, halfSize)`, `sdSegment(p, a, b)` | Signed distance to a shape round the origin (negative inside), in the unit `p` is in. Move `p`: `sdCircle(uv - 0.5, 0.3)`. |
1292
+ | | `opRound(d, r)`, `opOnion(d, w)`, `opSmoothUnion(a, b, k)`, `opSmoothSubtract(a, b, k)`, `opSmoothIntersect(a, b, k)` | Grow, outline, and melt shapes together over `k`. |
1293
+ | | `aa(d)` | How much of this pixel the shape covers, 0..1, with a one-device-pixel soft edge. `d` in any unit (uv, CSS px...): it measures the edge with the screen derivatives (`length(vec2(dFdx(d), dFdy(d)))`). Fragment only. |
1294
+ | Blend | `blendNormal`, `blendAdd`, `blendScreen`, `blendMultiply` `(base, top, opacity)` | CSS `mix-blend-mode` on straight rgb. More modes (overlay, soft-light, difference...) are example code to paste: `examples/chunks/blend.js`. |
1295
+ | Dither | `bayer4(px)`, `bayer8(px)`, `blueNoise(px)` | A threshold 0..1 per pixel (`gl_FragCoord.xy`, or `screenPx()` for CSS-px dots): ordered, or blue noise (an even scatter, a 16 x 16 tile built into the shader, no texture). |
1296
+ | | `dither(color, threshold, levels)` | `color` rounded to `levels` steps per channel by the threshold. |
1297
+ | Colour | `mixOklab(a, b, t)` | From sRGB `a` to `b` through Oklab: gradients that do not go grey in the middle. |
1298
+ | | `srgbToLinear(c)`, `linearToSrgb(c)`, `linearToOklab(c)`, `oklabToLinear(c)` | The conversions behind it. |
1299
+
1300
+ ```js
1301
+ gl.effect("poster", { // 4 levels per channel, blue-noise dithered
1302
+ fragment: { color: "color.rgb = dither(color.rgb, blueNoise(gl_FragCoord.xy), 4.0);" },
1303
+ });
1304
+ gl.effect("words-in", { // each word eases in on its own
1305
+ play: "uShow", uniforms: { uShow: 0 }, options: { duration: 1.4, ease: "linear" },
1306
+ fragment: { alpha: "Glyph g = glyph(vUv); alpha *= expoOut(stagger(uShow, g.word, g.words, 0.7));" },
1307
+ });
1308
+ ```
1309
+
1310
+ Names starting with `umber` in the pack (`umberRand3`, `umberHash3u`...) are its building blocks: callable, but not part of the contract.
1311
+
1312
+ ### What `setup` and `update` get (`ctx`)
1313
+
1314
+ | Member | |
1315
+ |---|---|
1316
+ | `el`, `plane`, `engine`, `name` | The element, its plane, the engine, the effect's name. |
1317
+ | `options`, `uniforms` | The resolved options; the plane's `{ value }` uniforms. |
1318
+ | `reducedMotion`, `viewport`, `frame` | `frame` only during `update`: `{ time, dt, ratio, frame, scroll }`. |
1319
+ | `trackMouse(on)` | Follow the pointer in `uMouse` (smoothed). Turn it off when not needed: a still pointer then costs nothing. |
1320
+ | `busy(on)` | Draw every frame while on (a simulation). Otherwise Umber draws only when something changed. |
1321
+ | `wake(frames?)` | Draw at least one more frame (after changing an array uniform in place). |
1322
+ | `listen(target, { type: fn })` | `addEventListener` for each type; returns one cleanup, and runs it when the plane goes. |
1323
+
1324
+ ```js
1325
+ gl.effect("lens", {
1326
+ uniforms: { uOn: 0 },
1327
+ fragment: { uv: "vec2 d = uv - uMouse; uv -= d * exp(-dot(d, d) * 12.0) * 0.15 * uOn;" },
1328
+ setup(ctx) {
1329
+ const to = (value) => () => { ctx.trackMouse(true); ctx.plane.tween("uOn", { value, duration: 0.6 }); };
1330
+ return ctx.listen(ctx.el, { pointerenter: to(1), pointerleave: to(0) });
1331
+ },
1332
+ });
1333
+ ```
1334
+
1335
+ The hover part alone needs no JavaScript: name the uniform as `play` and give it the `hover` trigger. Umber tweens it to 1 on `pointerenter` (on the element, or its closest link or button) and back to 0 on `pointerleave`, with the play's `duration` and `ease`. Its `delay` counts on enter only. An effect whose GLSL also reads `uTime` (a ripple that keeps moving under the pointer) draws every frame while that hover play is above 0, and stops once it is back at 0: no `ctx.busy(true)` needed for that.
1336
+
1337
+ ```js
1338
+ gl.effect("lift", { uniforms: { uOn: 0 }, play: "uOn", options: { trigger: "hover", duration: 0.6 }, fragment: { color: "color.rgb *= 1.0 + 0.2 * uOn;" } });
1339
+ ```
1340
+
1341
+ ### Timing, three ways
1342
+
1343
+ ```js
1344
+ gl.plane(el)?.tween("uShow", { value: 1, duration: 1 }); // 1. Umber's own tween
1345
+ const u = gl.plane(el)?.uniforms.uShow; // 2. GSAP (null with GL off)
1346
+ if (u) gsap.to(u, { value: 1, scrollTrigger: { trigger: el, scrub: true } });
1347
+ gl.effect("x", { play: "uShow", ... }); // 3. Umber plays it on scroll
1348
+ ```
1349
+
1350
+ ### A scroll-velocity effect
1351
+
1352
+ `uScrollVelocity` is already smoothed and redraws the plane while the page moves: no JavaScript. A brisk wheel is about 0.2, so scale it up and clamp it:
1353
+
1354
+ ```js
1355
+ gl.effect("stretch", {
1356
+ segments: 24, // a bendable mesh for the vertex part
1357
+ options: { strength: 1 }, // data-gl-stretch-strength="1.6" per element (uStretchStrength)
1358
+ vertex: {
1359
+ main: "pos.y += sin(uv.x * PI) * clamp(uScrollVelocity * 4.0, -1.0, 1.0) * uStretchStrength * 40.0;",
1360
+ },
1361
+ fragment: {
1362
+ color: `
1363
+ float s = clamp(uScrollVelocity * 4.0, -1.0, 1.0) * 0.02 * uStretchStrength;
1364
+ color.r = sampleImage(uv + vec2(0.0, s)).r;
1365
+ color.b = sampleImage(uv - vec2(0.0, s)).b;
1366
+ `,
1367
+ },
1368
+ });
1369
+ ```
1370
+
1371
+ The same speed in JavaScript: `gl.velocity.value` (this one), or `gl.scroll.velocity` (px per 60 Hz frame, unsmoothed, from the scroll module) divided by 60.
1372
+
1373
+ ### Full custom surfaces (`gl.shader`)
1374
+
1375
+ ```js
1376
+ gl.shader("sky", {
1377
+ options: { speed: 0.2 }, // per element: data-gl-shader-speed > --gl-shader-speed > this; the uniform uSpeed
1378
+ fragment: "color = vec4(0.5 + 0.5 * cos(uTime * uSpeed + uv.xyx + vec3(0, 2, 4)), 1.0);",
1379
+ animate: true, // default: draw every frame while on screen (uses uTime; not under reduced motion "static": uTime stands still). false: only on change
1380
+ });
1381
+ ```
1382
+ ```html
1383
+ <div data-gl="shader" data-gl-shader="sky" data-gl-shader-speed="0.5" style="height: 60vh"></div>
1384
+ ```
1385
+
1386
+ The fragment sets `color` (vec4) from `uv`. `head` holds functions. `uniforms` work as for effects. Number, boolean and array `options` become uniforms named `u` + Option, with no shader name in it (`speed` → `uSpeed`), since one element has one shader. Effects stack on shader surfaces too.
1387
+
1388
+ ### Examples to read
1389
+
1390
+ Umber ships no effects. The examples gallery writes the ones it shows as plain example code: one definition per file in `examples/effects/`, which the page hands to `gl.effect()` (only `duotone` is written in its page, `examples/video/loop.html`). Read them, copy them, change them.
1391
+
1392
+ | Page | Effect | What it shows |
1393
+ |---|---|---|
1394
+ | `examples/text/reveal.html` | `rise` | GL text rising out of its own box with `play` (whole elements, staggered with `delay`). |
1395
+ | `examples/text/lines.html` | `lines`, `words` | One heading revealed line by line, one paragraph word by word, with `glyph()`. |
1396
+ | `examples/images/progress.html` | `reel` | A sticky reel of images wiping through, driven by `gl.progress()` as a uniform (no JS per frame, with Lenis). |
1397
+ | `examples/images/pointer.html` | `field` | Every image bending towards one page pointer, `gl.pointer` and its velocity as uniforms. |
1398
+ | `examples/images/drag.html` | `swing` | A strip dragged and thrown with `gl.drag()` (the input module); its velocity bends the planes as a uniform. |
1399
+ | `examples/scope/mount.html` | `dissolve`, `rise` | A component mounted from code with `gl.add()` in a `gl.scope()`, unmounted with one `revert()`. |
1400
+ | `examples/images/dissolve.html` | `dissolve`, `wipe` | A noise dissolve with a glowing edge (`fbm`), and a soft wipe with a slight zoom-out. |
1401
+ | `examples/images/hover.html` | `lens` | A liquid lens under the pointer with an RGB split (`setup`, `trackMouse`, `listen`). |
1402
+ | `examples/images/scroll.html` | `bend`, `drift` | The plane bending with scroll speed (vertex slot, `segments`), the image drifting in its frame (`uProgress`). |
1403
+ | `examples/video/loop.html` | `duotone` (in the page) | Two colours by brightness, its `uMix` tweened from buttons. |
1404
+ | `examples/video/scrub.html` | `grain` | Film grain on a scrubbed video, stronger while scrubbing fast (`uScrubVelocity`). |
1405
+ | `examples/transitions/barba.html` | `dissolve` | Planes taking part in a plain Barba transition (`transitions/transition.js`). |
1406
+ | `examples/three/behind-text.html` | | A three.js scene behind DOM text with `gl.attach()`. |
1407
+
1408
+ A fade is one line: `gl.effect("fade", { play: "uShow", uniforms: { uShow: 0 }, fragment: { alpha: "alpha *= uShow;" } })`.
1409
+
1410
+ ---
1411
+
1412
+ ## three.js
1413
+
1414
+ three.js is the only library Umber works **with**, and only the copy your site brings: Umber never imports or bundles it. Keep your own three.js code; Umber takes over the chores every scene writes by hand:
1415
+
1416
+ - sizing: `setPixelRatio` + `setSize` from the element's box, Umber's DPR range, a pixel budget and adaptive resolution (a `PerspectiveCamera`'s aspect follows);
1417
+ - drawing only while the element is on screen and the tab is visible, and only when something asked;
1418
+ - context loss and restore;
1419
+ - cleanup when the element leaves the page (a Barba swap included);
1420
+ - the maths between DOM pixels and 3D units.
1421
+
1422
+ ### gl.attach(): your renderer, your canvas (the drop-in)
1423
+
1424
+ ```js
1425
+ import * as THREE from "three";
1426
+
1427
+ // three.js throws when the browser gives it no WebGL (blocked, switched off, an old GPU):
1428
+ // make the renderer in a try, and attach only when there is one. The page stays as it is.
1429
+ let renderer = null;
1430
+ try {
1431
+ renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true });
1432
+ } catch {}
1433
+ const scene = new THREE.Scene();
1434
+ const camera = new THREE.PerspectiveCamera(35, 1, 0.1, 100);
1435
+
1436
+ if (renderer) gl.attach(".hero-gl", {
1437
+ renderer, scene, camera,
1438
+ devices: "all", // this scene runs on phones even if the site keeps planes to desktops
1439
+ dpr: [1, 2], // optional, default: the engine's dpr
1440
+ async setup({ renderer, scene, camera }) { // once, when the element comes near (1.5 screens)
1441
+ await renderer.compileAsync(scene, camera);
1442
+ return () => { /* your cleanup */ };
1443
+ },
1444
+ animate: (f) => { mesh.rotation.y += f.dt * 0.5; return true; }, // true = draw the next frame too
1445
+ resize: (f) => { /* after Umber sized it: f.width, f.height, f.dpr */ },
1446
+ render: (f) => renderer.render(scene, camera), // the default
1447
+ });
1448
+ ```
1449
+
1450
+ - **No WebGL at all:** `new THREE.WebGLRenderer()` throws before Umber is asked anything, so make it in a `try` as above (Umber's own `gl.enabled` / `gl.reason` are about its planes; a view has its own device rule, below). Put a still image or a CSS background in the element for that case.
1451
+ - The renderer's canvas goes into the element unless you placed it in the page yourself. It stays a normal DOM child, so CSS opacity, z-index and a `position: fixed` Barba container just work.
1452
+ - **When it draws:** the first frame, `view.wake()`, `view.busy(reason, true)`, a resize, and every frame `animate()` returns `true`. Scrolling never redraws it: the canvas moves with the page. Under reduced motion `animate()` still runs, but returning `true` no longer loops: call `view.wake()` when what it shows changes (a model that finished loading).
1453
+ - `f` (the view frame): `time`, `dt`, `ratio`, `frame`, `width`, `height` (CSS px), `dpr`, `rect`, `progress` (0 as the element enters at the bottom, 1 as it leaves at the top), `velocity` (px/s), `reducedMotion`, `renderer`, `scene`, `camera`, `view`.
1454
+ - **The view:** `view.status` (`loading | ready | off | error | lost | destroyed`, also `data-gl-view` on the element), `view.ready` (a promise), `view.enabled`, `view.reason`, `view.rect`, `view.inView`, `view.progress`, `view.width / height / dpr`, `view.wake(frames)`, `view.busy("drag", true)`, `view.on("ready" | "resize" | "enter" | "leave" | "lost" | "restored" | "error" | "destroy", fn)`, `view.rectToWorld(rect, out?)`, `view.worldToRect(point)`, `view.destroy()`.
1455
+ - `dispose: false` keeps your renderer when the view goes (a pool you reuse). By default Umber calls `renderer.dispose()` and frees the WebGL context.
1456
+ - More options: `aspect: false` (you set the camera's aspect yourself; by default a `PerspectiveCamera` follows the box), `pixelBudget` (max drawing pixels, default the engine's) and `adaptive` (lower the resolution only while frames are slow, default the engine's).
1457
+ - Views have their **own device rule**: with the engine on `devices: "desktop"` (planes off on phones; the default is `"all"`), `gl.attach(el, { devices: "all" })` still runs the scene on a phone. The engine does not even need `[data-gl]` on the page. GL turned off for the visit on purpose (`devices: false`, `?umber=off`, `data-gl-disable`, `"unlicensed"`, `"save-data"`...) is off for views too: `view.reason` says which. Umber's own failures (`"context"`, `"load-failed"`, `"load-timeout"`, `"context-lost"`, `"error"`) are not: `gl.attach()` brings your renderer, so it still runs (`gl.view()` draws on Umber's canvas, so it is off with it).
1458
+
1459
+ ### gl.renderer(THREE) + gl.view(): one canvas for planes and 3D (advanced)
1460
+
1461
+ ```js
1462
+ const renderer = await gl.renderer(THREE); // the ONE WebGLRenderer on Umber's own canvas (null when GL is off)
1463
+ gl.view(el, { scene, camera, animate: (f) => { mesh.rotation.y += f.dt; return true; } });
1464
+ ```
1465
+
1466
+ - DOM planes and 3D share one context, one canvas and one frame. The renderer lives for the whole visit, so three.js compiles each kind of material once and the next page compiles nothing.
1467
+ - The view is clipped to its element (`scissor: false` to draw outside it), fades with its opacity (`followOpacity: false` to opt out) and goes when it leaves the page. `aspect: false` works here too.
1468
+ - Never call `renderer.setSize()` here (Umber owns the canvas size) and use `scene.background` for a fill (`autoClear` is off: Umber clears once per frame).
1469
+ - Post-processing: size an `EffectComposer` to the box in device px inside `render(f)`: `composer.setSize(f.width * f.dpr, f.height * f.dpr); composer.render();`.
1470
+ - It needs GL on for this device (the engine's `devices`). On a phone with `devices: "desktop"` it warns and suggests `gl.attach()`.
1471
+ - three.js on Umber's canvas (`gl.renderer()`, `gl.view()`, `data-gl="layer"`) is its own small file, `chunks/layers.js`, which the engine downloads by itself on the first of them: `gl.renderer()` resolves once it is there, and a layer element keeps its DOM content until then.
1472
+
1473
+ `data-gl="layer"` + `gl.layer(name, { setup, render })` is the same shared-canvas idea from markup (for Webflow): `ctx.gl`, `ctx.canvas`, `ctx.rect`, `ctx.px` (device px), `ctx.three(renderer)` (viewport, scissor and state reset before you render), `ctx.state` for your objects. An `<img>` inside is a fallback, hidden once the layer draws.
1474
+
1475
+ ```js
1476
+ gl.layer("discs", {
1477
+ options: { speed: 1 }, // per element: data-gl-layer-speed > --gl-layer-speed > this, in ctx.options
1478
+ async setup(ctx) { /* once, when the element comes near; may return a cleanup */ },
1479
+ render(ctx) { /* draw; ctx.opacity, ctx.mouse, ctx.time, ctx.dpr are there too */ },
1480
+ resize(ctx) { /* the element or the screen changed size (before render) */ },
1481
+ animate: true, // default: draw every frame while visible (not under reduced motion "static": ctx.time stands still, and it draws when setup() resolves and on ctx.wake(): call it when a model loaded after setup lands). false: only on ctx.wake(), ctx.busy(true), resize, scroll
1482
+ scissor: true, // default: clip to the element box
1483
+ followOpacity: true, // default: fade with the element's (and its parents') opacity
1484
+ dpr: 1.5, // optional cap for a heavy scene: rendered smaller, upscaled into the box
1485
+ });
1486
+ ```
1487
+
1488
+ ### DOM ↔ 3D maths (pure functions, no engine needed)
1489
+
1490
+ ```js
1491
+ const { rectToWorld, worldToRect, pxPerWorld, fitCamera } = Umber.math; // or named imports from the npm package
1492
+
1493
+ rectToWorld(label.getBoundingClientRect(), camera, mesh.position); // a DOM box's centre on z = 0, and its size in world units
1494
+ worldToRect(mesh.position, camera); // a 3D point in viewport px: { x, y, visible }
1495
+ pxPerWorld(camera); // CSS px per world unit at z = 0
1496
+ fitCamera(camera, { width: innerWidth, height: innerHeight }); // 1 world unit = 1 CSS px at z = 0
1497
+ ```
1498
+
1499
+ On a view, `view.rectToWorld(rect)` and `view.worldToRect(point)` use that view's camera and box.
1500
+
1501
+ ---
1502
+
1503
+ ## Render targets: gl.target(), gl.snapshot(), uBackdrop
1504
+
1505
+ Offscreen textures on Umber's own WebGL context. All of it is its own small file, `chunks/fx.js`, which the engine downloads by itself on the first `gl.target()`, `gl.snapshot()` or effect that reads `uBackdrop`. A page without them never downloads it, and nothing changes on it.
1506
+
1507
+ ### uBackdrop: what is drawn behind a plane
1508
+
1509
+ An effect (or a `gl.shader()`) that reads `uBackdrop` gets a copy of what the canvas holds behind its plane: the GL planes drawn before it (by `data-gl-order`, then page order). Nothing to declare: Umber sees the name and adds the sampler. Sample it at this pixel on the canvas:
1510
+
1511
+ ```js
1512
+ gl.shader("glass", {
1513
+ animate: false,
1514
+ fragment: `
1515
+ vec4 b = texture(uBackdrop, gl_FragCoord.xy / uCanvas); // premultiplied
1516
+ color = vec4(b.rgb / max(b.a, 1e-5), 1.0); // un-premultiply in the color slot
1517
+ `,
1518
+ });
1519
+ ```
1520
+ ```html
1521
+ <div class="glass" data-gl="shader" data-gl-shader="glass" style="border-radius: 18px"></div>
1522
+ ```
1523
+
1524
+ - The copy covers the element plus about 32 px around it (plus its `bleed`), so a blur or a refraction can look a little outside. Offset `gl_FragCoord.xy` in device px (`* uDpr`).
1525
+ - It holds **GL pixels only**: the plain DOM behind the element (text, CSS backgrounds) is not in it. Put a GL image or shader surface behind the glass.
1526
+ - One copy per frame per backdrop plane (only the area around it). Planes that don't read `uBackdrop` cost nothing: once none draws (a page change), the canvas-sized copy goes back to the pool.
1527
+ - Until `chunks/fx.js` is here the plane is not drawn and its DOM shows (give it a CSS `backdrop-filter` as the fallback look).
1528
+
1529
+ ### gl.target(options): a texture you draw into
1530
+
1531
+ ```js
1532
+ const t = await gl.target({ width: 512, height: 512 }); // device px; null when GL is off
1533
+ t.draw(`vec4 color(vec2 uv) { return vec4(uv, 0.5, 1.0); }`); // one fullscreen pass
1534
+ gl.effect("pattern", {
1535
+ uniforms: { uPattern: t }, // any effect, any shader
1536
+ fragment: { color: "color.rgb *= texture(uPattern, uv).rgb;" },
1537
+ });
1538
+ ```
1539
+
1540
+ - **Options:** `width`, `height` (device px, default the canvas size; it never follows the canvas, call `resize()`), `type` (`"half"` default, `"float"`, `"u8"`), `msaa` (samples, 0 = off), `attachments` (1-4, MRT).
1541
+ - **`target.draw(glsl, uniforms?)`** replaces what it held. `glsl` defines `vec4 color(vec2 uv)` (straight alpha: Umber premultiplies), or its own `void main()` that writes `outColor` premultiplied (MRT: `layout(location = 1) out vec4 outNormal;` for the second attachment). Built in: `vUv`, `uSize` (the target in device px), `uTime`. Uniforms are declared for you: numbers, booleans, arrays (vec2..4, mat3, mat4), `{ value }` objects (read on each draw), anything with a `texture` (another target, a sim) as a sampler, and CSS colour strings as a `vec4` (`var()` read from `<html>`, once per string). Image URLs work in effects only. It draws right away (call it from an event or `gl.on("frame")` to animate) and asks for one frame, so the planes that read it redraw.
1542
+ - **Also:** `target.clear()`, `target.resize(w, h)`, `target.release()`, `target.texture`, `target.textures` (MRT), `target.framebuffer`, `target.width`, `target.height`, `target.type`, `target.msaa`, `target.version`.
1543
+
1544
+ **The contract (keep it in mind when you read a target):**
1545
+
1546
+ - **Premultiplied alpha**, like the canvas. In an effect's `color` slot (straight alpha) un-premultiply: `c.rgb /= max(c.a, 1e-5)`.
1547
+ - **Half-float where the GPU can render to it.** `type: "half"` (the default) is RGBA16F, and plain 8-bit where the GPU can't, without a word. An asked-for `"float"` or `"half"` the GPU can't render steps down the ladder (float → half → u8) and says so once; so does `msaa` it refuses.
1548
+ - **The first row is the top**, like images in Umber: sample a target with a plane's `uv` and it is the right way up.
1549
+ - **A resize gives NEW WebGLTextures** (and so does a restored WebGL context): `target.texture` changes and `target.version` goes up. A handle you read before is invalid; read `target.texture` again. As an effect uniform this is automatic.
1550
+ - **Freeing is deferred:** `release()` gives it back to a pool, and its GPU memory is freed after 5 s unused (by a timer, never the frame loop: a still page stays at 0 frames per second). A target released and asked for again with the same size meanwhile is the same memory.
1551
+ - **Context loss:** targets are made again when the context comes back, with new handles, and draw their last `draw()` (or snapshot) again.
1552
+
1553
+ ### gl.snapshot(el): a still copy of a plane
1554
+
1555
+ ```js
1556
+ const still = await gl.snapshot(".hero"); // a target ("u8", device px) or null
1557
+ gl.effect("echo", { uniforms: { uStill: still }, fragment: { color: "vec4 s = texture(uStill, uv); color = vec4(s.rgb / max(s.a, 1e-5), s.a);" } });
1558
+ ```
1559
+
1560
+ - What the plane draws right now, effects included, its parents' cuts (overflow, clip-path) not. The element or the plane (`gl.plane(el)`) both work.
1561
+ - It waits up to 5 s for the plane to be able to draw (its image loaded, its program compiled); a plane far below the fold starts loading now. Then `null` with a warning.
1562
+ - A turned or tilted plane is copied with MSAA (smooth edges), inside its bounding box.
1563
+
1564
+ ### Sharing a target with three.js (same canvas)
1565
+
1566
+ Only with `gl.renderer(THREE)` (three.js on Umber's own canvas and context): a texture from one WebGL context can't be used in another. Umber never imports three.js; this is your code, and it uses three.js internals (`renderer.properties`), so pin your three.js version.
1567
+
1568
+ ```js
1569
+ const renderer = await gl.renderer(THREE);
1570
+ const t = await gl.target({ width: 1024, height: 1024 });
1571
+ const map = new THREE.Texture();
1572
+ map.repeat.y = -1; map.offset.y = 1; // three.js reads row 0 as the bottom; a target's row 0 is its top
1573
+ let seen = -1;
1574
+ function adopt() { // again whenever t.version changed (resize, restored context)
1575
+ const p = renderer.properties.get(map);
1576
+ p.__webglTexture = t.texture;
1577
+ p.__webglInit = true;
1578
+ seen = t.version;
1579
+ }
1580
+ adopt();
1581
+ gl.view(".scene", { scene, camera, animate: () => { if (t.version !== seen) adopt(); return false; } });
1582
+ ```
1583
+
1584
+ The other way round, a three.js render target into an Umber effect: any object with a `texture` field is a sampler uniform, so `uniforms: { uScene: { get texture() { return renderer.properties.get(rt.texture).__webglTexture || null; } } }` works after three.js rendered `rt` once (call `gl.wake()` after each render).
1585
+
1586
+ ---
1587
+
1588
+ ## Groups and passes: data-gl="group", data-gl-pass
1589
+
1590
+ Both are in `chunks/fx.js`, which the engine downloads by itself on the first `data-gl="group"` or `data-gl-pass`. A page without them never downloads it.
1591
+
1592
+ **GL content only.** Groups and passes work on what Umber draws (images, video, GL text, shader surfaces, flights). The DOM the page shows itself, text that is not `data-gl="text"`, CSS backgrounds, buttons, stays as it is, under or over the canvas. A "grain over the whole page" pass grains the GL planes, not the DOM around them; for grain everywhere, use one fixed `data-gl="shader"` plane.
1593
+
1594
+ ### data-gl="group": many planes drawn as one
1595
+
1596
+ ```html
1597
+ <section data-gl="group" data-gl-effect="wave">
1598
+ <h2 data-gl="text">Three hills</h2>
1599
+ <div data-gl><img src="a.jpg" alt=""></div>
1600
+ <div data-gl><img src="b.jpg" alt=""></div>
1601
+ </section>
1602
+ ```
1603
+ ```js
1604
+ gl.effect("wave", { fragment: { uv: "uv.x += sin(uv.y * 9.0 + uTime) * 0.006;" } });
1605
+ ```
1606
+
1607
+ - Every GL plane inside the group (the closest group wins) is drawn into the group's own texture first, then the group draws that texture as its image, at its own place in the page's stacking, through its own `data-gl-effect`. One effect spans many planes (a wave over a heading and its photos, one blur over a gallery, a gooey merge), and applies to that group only.
1608
+ - In the group's effects `sampleImage(uv)` is the members, straight alpha like an image; `uv` runs over the group's box. `sampleRaw(uv)` is the same premultiplied: add those up for a blur (as in a pass, below), never `sampleImage()` taps, or every member gets a dark rim. It works in any plane effect. Everything else is a normal plane: options, `play`, `uProgress`, `uMouse`, its parents' clips, its border-radius.
1609
+ - From JS: `gl.add(el, { type: "group", effects: ["wave"] })`.
1610
+ - **The window.** The texture covers the part of the group on screen (plus 32 px and the effects' `bleed`), not the whole group: a group three screens tall costs one screen. Scrolling never makes a new texture.
1611
+ - **Members are drawn uncut**: their own parents' `overflow` and `clip-path` inside the group are not applied in the texture. Cut the group instead (it is a plane like any other).
1612
+ - three.js layers and planes that read `uBackdrop` draw on the canvas as usual, not in their group (said once).
1613
+ - A member moved into another group, or out of every group (a filter, a slider), is drawn where it now is. A `data-gl-id` image still landing and an element with a `view-transition-name` during `gl.transition()` are left out of their group, like on the canvas.
1614
+ - Groups inside groups work (inner first). A member's DOM hides when it is drawn into its group, by its own `data-gl-status`; the group itself mirrors no DOM.
1615
+ - Until `chunks/fx.js` is here, members draw on their own; while the group's program compiles they wait with it (their DOM shows).
1616
+
1617
+ **Two textures (scroll-blended sections).** Put two groups in one sticky screen; the second reads the first as `uBackdrop` (what is drawn behind it) and its own members as `sampleImage`:
1618
+
1619
+ ```js
1620
+ gl.effect("wipe", {
1621
+ uniforms: { uMix: gl.progress(".blend", { start: "top top", end: "bottom bottom" }) },
1622
+ fragment: { color: `
1623
+ vec4 from = texture(uBackdrop, gl_FragCoord.xy / uCanvas);
1624
+ from = vec4(from.rgb / max(from.a, 1e-5), from.a);
1625
+ color = mix(from, sampleImage(uv), smoothstep(uv.x - 0.01, uv.x + 0.01, uMix));
1626
+ ` },
1627
+ });
1628
+ ```
1629
+
1630
+ ### data-gl-pass: effects over the whole frame, or over one group
1631
+
1632
+ ```html
1633
+ <body data-gl-pass="trail grade grain smooth" data-gl-grain-blend="screen" data-gl-grain-opacity="0.5">
1634
+ <div data-gl="group" data-gl-pass="blur" data-gl-blur-scale="0.5">...</div>
1635
+ ```
1636
+
1637
+ - On `<body>` or `<html>`: the frame's GL planes are drawn into one canvas-sized texture, the listed effects run over it in order, and the result goes onto the canvas. On a group: over its members, before the group's own `data-gl-effect`.
1638
+ - **A pass is an effect** (`gl.effect`): the same slots and options (`data-gl-<effect>-<option>` on the element that lists it). Vertex code is left out (said once).
1639
+ - In a pass: `uv` / `vUv` run over the surface, (0,0) top-left; `sampleImage(uv)` is the step before (straight alpha); `uSize` is the surface in **device px** (`1.0 / uSize` is one pixel); `uTime`, `uViewport`, `uDpr`, `uCanvas`, `uScrollVelocity`, `uRect` (the surface, viewport px) and `uMouse` (0..1 over the surface; a pass that reads it wakes on pointer moves). `uProgress` is 0: pass `gl.progress(el)` as a uniform instead.
1640
+ - **`previous(uv)`**: what this pass wrote last frame at that point of the page, moved by the scroll (with Lenis or native scroll alike), so a trail stays on the content instead of smearing. Fixed elements leave their trail sliding.
1641
+ - **`toneMap(rgb)`** rolls light above 1.0 off smoothly; a chain that calls it runs in half float (values above 1 survive between passes).
1642
+ - **`fxaa(uv)`**: `sampleImage(uv)` with stair-stepped edges smoothed. Passes draw without the canvas's own antialiasing, so a turned plane's edges stair-step without it.
1643
+ - **`sampleRaw(uv)`**: the step before, premultiplied. Add these up for a blur, then make the sum straight once; averaging `sampleImage()` taps counts a transparent pixel's black and leaves a grey rim on every edge:
1644
+
1645
+ ```glsl
1646
+ vec2 px = 3.0 / uSize;
1647
+ vec4 s = vec4(0.0);
1648
+ for (int i = -1; i <= 1; i++) for (int j = -1; j <= 1; j++) s += sampleRaw(uv + vec2(i, j) * px);
1649
+ color = s / 9.0;
1650
+ color.rgb /= max(color.a, 1e-5);
1651
+ ```
1652
+ - Umber's GLSL helpers (`noise`, `fbm`, the pack) work in passes once `chunks/glsl.js` is on the page (any plane whose effect calls one brings it).
1653
+
1654
+ **Options every pass understands** (per effect): `-blend` (`normal`, `add`, `screen`, `multiply`: how its result goes over what came in), `-opacity` (0..1, the uniform `u<Effect>Opacity`) and `-scale` (0.25..1: its resolution; a blur at 0.5 costs a quarter).
1655
+
1656
+ **Auto-merge.** Effects in a row share one program (one fetch, one draw), unless one has to read pixels the one before wrote: it has a `uv` slot, it calls `sampleImage()`, `sampleRaw()` or `fxaa()`, it runs at another `scale`, or the one before called `previous()`. Merged or not, the pixels are the same.
1657
+
1658
+ **Frames.** Passes run only in frames Umber draws anyway: a still page stays at 0 frames per second. A `previous()` pass keeps drawing for 1.5 s after the last frame something else asked for, so a trail can fade, then sleeps too. Change `data-gl-pass` from code and call `gl.wake()`. If no element had one when Umber last scanned (at start or at `gl.scan()`), and nothing else has loaded `chunks/fx.js` yet, call `gl.scan()` once so it loads.
1659
+
1660
+ **Limits.** three.js layers draw straight to the canvas, under the page's passes. A plane that reads `uBackdrop` under page passes gets the frame so far, as without them. Passes add one texture the size of the canvas (two with more than one program, a pair per `previous()` pass): about 20 MB each at 2880 x 1800 in 8-bit, twice that in half float.
1661
+
1662
+ ---
1663
+
1664
+ ## Simulations: gl.sim(), gl.brush(), uFlow
1665
+
1666
+ A simulation is a few textures (fields) that your fragment shaders step forward on the GPU: trails, ripples, a fluid, particle positions. All of it is its own small file, `chunks/sim.js`, which the engine downloads by itself (through `chunks/fx.js`) on the first `gl.sim()`, `gl.flow()` or effect that reads `uFlow`. A page without them never downloads it.
1667
+
1668
+ Two rules make it fit a page that sleeps:
1669
+
1670
+ - **Fixed steps per second, on every screen.** A sim steps `hz` times a second (60 by default) whatever the refresh rate: a 144 Hz screen steps on 60 of its 144 frames, a 30 Hz one twice a frame. So `* 0.96` per step means the same on every screen, with no conversion.
1671
+ - **It sleeps.** A sim steps after an input (a brush stroke, the pointer when its passes read `uPointer`, `sim.set()`, `sim.wake()`) and stops once it says it is settled. Then it asks for no frames, and a still page goes back to 0 frames per second. It starts asleep too, unless it moves by itself: it has an `init`, a pass reads `uTime` or `uStep`, or `settle: false`. A sim whose passes make something out of empty fields without any of those: call `sim.wake()` once.
1672
+ - **It steps only where it is seen.** While every plane that reads it (a uniform holding the sim or one of its fields, or `uFlow`) is far from the screen (more than a quarter screen away), it does not step and asks for no frames, even with `settle: false` or the pointer moving; it goes on when one comes near. A sim no plane reads steps wherever it is, and so does one a pass reads (`data-gl-pass`, `target.draw()`) or while a layer is on screen (three.js, your own GL: what it samples can't be known), its planes far or not.
1673
+
1674
+ ### uFlow: the page's pointer flowmap
1675
+
1676
+ Any effect that names `uFlow` gets one small screen-shaped texture the pointer pushes around. Nothing to declare; sample it at the pixel's place on screen:
1677
+
1678
+ ```js
1679
+ gl.effect("flow", {
1680
+ fragment: { uv: "vec4 f = texture(uFlow, screenUv()); uv -= (f.rg * 2.0 - 1.0) * f.a * 0.06;" },
1681
+ });
1682
+ ```
1683
+
1684
+ - `rg * 2.0 - 1.0` is the way it was pushed (screen uv, y down), `a` how hard (0..1). It is the same encoding as the input module's `gl.touch()`, so code written for one reads the other.
1685
+ - One sim for the whole page, however many planes read it. It steps while the pointer moves and fades to exactly 0 about a second after it stops; then it sleeps.
1686
+ - `gl.flow({ size, radius, fade, motion })` changes it (or makes it before any plane reads it) and resolves to its sim. A new `size` makes its fields again, empty. Defaults: `size` `[32, 48, 64, 64, 96, 128]` texels across (one per GPU level), `radius` 8 % of the viewport width (CSS px), `fade` 0.92 per step, `motion` 0.04 per CSS px moved.
1687
+ - **Fallback:** a fade in 8 bits never reaches 0, so the flowmap needs half-float targets. Where the GPU can't render them, `uFlow` is the input module's `gl.touch()` texture (drawn on the CPU), when the input module is loaded; without it `uFlow` stays still and Umber says how to fix it. Until `chunks/sim.js` is here, `uFlow` is transparent (no push).
1688
+
1689
+ ### gl.sim(options)
1690
+
1691
+ ```js
1692
+ const trail = await gl.sim({
1693
+ size: 128, // texels across; or one per GPU level 0-5: [64, 64, 96, 128, 128, 192]
1694
+ next: `vec4 next(vec2 uv) { return texture(state, uv) * 0.95; }`, // one field, "state"
1695
+ });
1696
+ gl.brush(trail, { radius: 30, color: [1, 1, 1, 1] }); // paints where the pointer goes
1697
+ gl.effect("ink", { uniforms: { uInk: trail }, fragment: { color: "color.rgb = mix(color.rgb, vec3(0.0), texture(uInk, screenUv()).r);" } });
1698
+ ```
1699
+
1700
+ - **`next`** defines `vec4 next(vec2 uv)`: the field's next value at `uv`. The old value is `texture(state, uv)`. It is state, not colour: what you return is stored as it is (no premultiplying, no clamping on half and float).
1701
+ - **Built in:** `uDt` (seconds per step: 1 / hz), `uStep` (steps so far), `uPointer` (the pointer, 0..1 of the viewport, y down; -1 before it first moved), `uSize` (the field written, in texels), `uTime`, `vUv`. Your `uniforms` are declared for you: numbers, arrays, a `{ value }` read every step, and a target or another sim as a sampler. Colour strings and image URLs work in effects only.
1702
+ - **Options:** `size`, `shape` (`"screen"`, the default: the height follows the viewport's shape, and a new shape starts the sim again; `"square"`), `type` (`"half"` default, `"float"`, `"u8"`; where the GPU can't render it, the next one down: `"float"` runs in half where only half floats render, and 8-bit where neither does; `"float"` that renders but can't be filtered (no `OES_texture_float_linear`, many phones) samples the nearest texel with `texture()`, said once (`texelFetch()` reads are unaffected); an asked-for `"float"` that runs in half is said once, and any sim that ends up in 8 bits says so once (the default too; ask for `"u8"` to skip it)), `hz` (60), `init` (`vec4 init(vec2 uv)`, the first value; default 0), `uniforms`, `settle`.
1703
+ - **`settle`:** seconds after the last input before it sleeps (default 2), a function `(sim) => boolean` called after each frame's steps (`sim.steps`, `sim.idle` in seconds), or `false` (never sleeps: it asks for every frame, like a normal render loop). For a decay `k` per step, the last trace is gone after `log(1/255) / log(k)` steps: 0.95 takes 108 steps, 1.8 s.
1704
+ - **Several fields and passes:** each field is a sampler of its own name in every pass; each pass writes one field (`into`) and can read its old value. `iterations` runs a pass several times per step (a pressure solve), one number or one per GPU level. `output` is the field `sim.texture` gives.
1705
+
1706
+ ```js
1707
+ const sim = await gl.sim({
1708
+ fields: { velocity: {}, dye: { size: [128, 192, 256, 384, 512, 640] }, pressure: {} },
1709
+ output: "dye",
1710
+ passes: [
1711
+ { into: "pressure", next: "...", iterations: [6, 8, 12, 16, 20, 24] },
1712
+ { into: "velocity", next: "..." },
1713
+ { into: "dye", next: "..." },
1714
+ ],
1715
+ });
1716
+ ```
1717
+
1718
+ - **The sim object:** `sim.texture` (the output field now), `sim.field(name)` (a field as a uniform), `width`, `height`, `type`, `steps`, `idle`, `awake`, `set(name, value)` (a uniform; wakes it), `wake()`, `reset()` (every field as it started), `brush(options)`, `release()`.
1719
+ - **Its textures change every step** (each field is two targets, swapped after each pass, never copied). As an effect uniform that is automatic; elsewhere (three.js, your own GL) read `sim.texture` again each frame you draw.
1720
+ - A context that comes back makes the fields again and starts every sim from its `init`.
1721
+
1722
+ ### gl.brush(sim, options)
1723
+
1724
+ Soft round stamps into one field of a sim, up to 16 a step in one pass.
1725
+
1726
+ ```js
1727
+ const push = gl.brush(sim, { field: "velocity", radius: 40, color: [0, 0, 0, 0], motion: 8 }); // follows the pointer
1728
+ const dye = gl.brush(sim, { field: "dye", radius: 40, color: [0.07, 0.03, 0.01, 1] });
1729
+ dye.paint(200, 300); // one stamp at viewport CSS px 200, 300 at the next step (pointer: false brushes only paint here)
1730
+ ```
1731
+
1732
+ - `color` is added at the centre with a gaussian falloff of `radius` CSS px (`mode: "add"`, the default), or mixed towards by its alpha (`mode: "mix"`).
1733
+ - `motion`: the stroke's movement in CSS px times this is added to `.xy`, a push for a fluid or a flowmap.
1734
+ - `pointer: true` (default) stamps along the pointer's path while it moves, half a radius apart; a new touch starts a new stroke where it goes down, and so does the pointer coming back into the window. `brush.release()` stops it.
1735
+
1736
+ ### Quality per GPU
1737
+
1738
+ `size` and `iterations` take one value per GPU level, 0 (software) to 5 (`gl.info.gpu.level`, `?umber-gpu=` to try one), so a phone gets a smaller grid and fewer pressure iterations than a desktop. The gallery's fluid (`examples/sim/fluid.js`) shows the pattern: a 48-texel grid with 6 iterations at level 0, 160 with 24 at level 5.
1739
+
1740
+ ### Particles
1741
+
1742
+ Positions live in a sim (`shape: "square"`, `type: "float"`): one texel per particle, `xy` its position, `zw` its speed. Umber ships no particle renderer: draw the points yourself in a `data-gl="layer"` (raw WebGL or three.js on Umber's context) reading `sim.texture` with `texelFetch`, and `ctx.wake()` when `sim.steps` changed. `examples/sim/particles.html` does it in a dozen lines.
1743
+
1744
+ ---
1745
+
1746
+ ## Getting ready ahead: gl.preload(), gl.warm(), placeholders
1747
+
1748
+ A GL element shows its DOM until its texture is on the GPU and its program is compiled. On a fast page that is a frame or two; on a page change it can be a blank image, or a hitch on the first frame. These calls do that work earlier. All of it is its own small file, `chunks/warm.js`, which the engine downloads on the first call (or the first `data-gl-placeholder`); the offscreen draws also bring `chunks/fx.js`. Nothing here ever blocks the page: images decode off the main thread, uploads go in idle moments, and nothing rejects.
1749
+
1750
+ Both calls return a promise that is also the progress: `p.value` goes from 0 to 1 and never back (a Signal, so it can even be a uniform), and the optional `fn(v)` hears each step. With GL off they resolve at once with `value` 1: the DOM is the content.
1751
+
1752
+ ### gl.preload(what): the next page, before it is on the page
1753
+
1754
+ ```js
1755
+ gl.preload("/work/dunes"); // a page URL: fetched, read, its [data-gl] elements made ready
1756
+ gl.preload(["/img/a.jpg", "/img/b.jpg"]); // image URLs
1757
+ gl.preload(data.next.container); // a container (detached is fine)
1758
+ gl.preload(doc); // a parsed Document
1759
+ gl.preload(data.next); // Barba's next: { container }, { html } or { url }
1760
+ ```
1761
+
1762
+ For each `[data-gl]` element it finds, Umber:
1763
+
1764
+ - fetches and decodes its image and puts it on the GPU, under the key the element will ask for when it arrives: `data-gl-src` as written, else the `srcset` candidate the browser will pick at this screen and DPR (from `sizes`; the same pick a `data-gl-id` flight uses). In a `<picture>` with `<source>`s the browser may pick another file, so those are not guessed;
1765
+ - compiles the program its effects make (when they are defined already), and draws it once into a tiny offscreen target, so the driver finishes its work now and not on the first real frame;
1766
+ - shows its `data-gl-placeholder` preview right away (below).
1767
+
1768
+ When the elements arrive, their planes take the texture and the program that are waiting: no fetch, no upload, no compile on the swap frame. A texture nobody takes is freed after 20 s (it counts in the texture budget meanwhile). A page that is not shown yet has no layout, so an image found ahead is decoded for the screen at this DPR (or for its `<img>`'s `sizes` width, when it has one), not whole; once its plane is measured, a texture much bigger than it draws is decoded again, smaller, in an idle moment.
1769
+
1770
+ ### Hover intent (opt-in)
1771
+
1772
+ ```js
1773
+ gl.preload({ hover: true }); // every link to another page of this site
1774
+ gl.preload({ hover: "a.project-link" }); // only these
1775
+ gl.preload({ hover: false }); // off
1776
+ ```
1777
+
1778
+ When the pointer slows down over a link (it stays on it about 65 ms without crossing it fast), or a finger or pen touches one, that page is fetched and preloaded, once per URL. Off on Save-Data and 2g connections. Links you only pass over cost nothing.
1779
+
1780
+ ### Router recipe: preload in the leave hook
1781
+
1782
+ The next page's HTML is usually being fetched while the old page leaves. Preload there, and let the router wait for it only if you want to (the promise never rejects; return it only from a hook the router should wait on):
1783
+
1784
+ ```js
1785
+ // Barba: the leave animation and the preload run side by side (keep the braces: a hook
1786
+ // that returns the promise makes Barba wait for it).
1787
+ barba.hooks.leave((data) => { gl.preload(data.next.url.href); });
1788
+ // or, once Barba has the HTML: return the promise, so Barba waits before the swap
1789
+ // (until its images are downloaded and decoded: a download has no time limit).
1790
+ barba.hooks.beforeEnter((data) => gl.preload(data.next.container));
1791
+
1792
+ // Swup 4
1793
+ swup.hooks.on("visit:start", (visit) => gl.preload(visit.to.url));
1794
+ swup.hooks.on("page:load", (visit, { page }) => gl.preload(page.html ? { html: page.html } : null));
1795
+ ```
1796
+
1797
+ `gl.transition()` and `data-gl-id` flights work the same with or without it; a preloaded flight target simply lands on a sharp texture at once.
1798
+
1799
+ ### gl.warm(root?): this page, with progress (a preloader)
1800
+
1801
+ ```js
1802
+ const p = gl.warm(null, (v) => (bar.style.scale = `${v} 1`));
1803
+ await p; // every plane can draw (each waits 5 s at most)
1804
+ loader.remove();
1805
+ ```
1806
+
1807
+ Every plane in `root` (a selector or element; default: the whole page) loads its image or text even when far from the screen, compiles, and is drawn once offscreen. Use it behind a loading screen; without one, the normal "load what comes near" is the better default.
1808
+
1809
+ ### data-gl-placeholder: a blurred preview until the file is there
1810
+
1811
+ ```html
1812
+ <div data-gl="image" data-gl-placeholder="UF-rWpqZh3dVQ2..."><img src="dunes.jpg" alt="Dunes" width="1600" height="1000"></div>
1813
+ ```
1814
+
1815
+ The attribute holds a tiny picture (about 50 characters: a grid 6 cells on its long side (6 x 4 for a 3:2 picture), 4 bits per colour channel). Umber draws it, smoothly scaled, as the background of the `<img>` until the file has loaded; the image then paints over it. Make the string once, in the browser console of any page with Umber:
1816
+
1817
+ ```js
1818
+ await gl.placeholder("/img/dunes.jpg"); // "UF-rWpqZh3dVQ2..."
1819
+ ```
1820
+
1821
+ - It shows while GL is on (the preview is decoded by `chunks/warm.js`). With GL off the `<img>` loads as usual.
1822
+ - It is a background of the `<img>`: images with transparency show it through until it is removed on load. An element with a play effect (a reveal) stays hidden while it loads, as before.
1823
+
1824
+ ### Sizes and warnings that come with it
1825
+
1826
+ - An image file much bigger than it is drawn is decoded at the drawn size (its box at this DPR, with 25 % room for a zoom), not the file's: a 2400 px still shown at 460 px takes a twentieth of the GPU memory. When half or a quarter of the file is within a tenth below that size, that is taken instead (its mip levels are then the file's own, so a smaller element showing the same file looks as if the whole file were there). When a plane showing it grows past that (a resize, a bigger plane with the same `src`), it is decoded again, bigger, from the HTTP cache; the smaller one shows meanwhile.
1827
+ - A file bigger than the GPU can take is drawn shrunk, with an `[umber]` warning that names the file and the limit.
1828
+ - One GPU memory budget per device (`gl.info.gpu.textureBudget`) covers image textures, render targets (groups, passes, sims, snapshots, `gl.leave` copies, your `gl.target`s) and cached video frames (`data-gl-scrub`). Over it, Umber frees what it can make again, in this order: render targets released in the last 5 s, image textures far from the screen (their DOM image shows until the visitor scrolls back), then cached frames (a scrubbed video keeps fewer frames around the playhead from then on). Targets in use are never freed: the site made them. `gl.info.gpuMB` is the total.
1829
+ - When what is near the screen is still over the budget after that, one `[umber]` warning gives the images' and the targets' and frames' share, and names the largest images. Serve smaller files (`srcset` and `sizes`, or a smaller `data-gl-src`), and make targets smaller. Render targets alone past the budget have their own warning (`gl.info.targetMB`).
1830
+ - GL text far from the screen is painted in idle moments too (nearest first), so an anchor jump lands on text that is ready.
1831
+
1832
+ ---
1833
+
1834
+ ## Instances: one plane, drawn many times
1835
+
1836
+ `data-gl-instances` draws a plane many times in **one draw call**, and tells its effects which one they are drawing. Tiles that come apart, letters of real DOM text, copies that trail behind a plane, particles where it has ink. All of it is its own small file, `chunks/instances.js`, which the engine downloads by itself on the first element (or effect) that asks. Until it is here, that element shows its DOM. A page without instances never downloads it.
1837
+
1838
+ ```html
1839
+ <div data-gl="image" data-gl-instances="tiles 16x10" data-gl-effect="shatter"><img src="dunes.jpg" alt="Dunes"></div>
1840
+ ```
1841
+ ```js
1842
+ gl.effect("shatter", {
1843
+ play: "uApart",
1844
+ options: { trigger: "hover" },
1845
+ attributes: { aSeed: 3 }, // 3 random numbers per tile, stable across visits
1846
+ vertex: {
1847
+ main: `
1848
+ vec2 local = (uv - tileCenter) * uSize; // px from the tile's middle
1849
+ float a = (aSeed.x - 0.5) * 2.4 * uApart;
1850
+ pos.xy += mat2(cos(a), sin(a), -sin(a), cos(a)) * local - local
1851
+ + (tileCenter - 0.5) * uSize * 0.5 * uApart;
1852
+ `,
1853
+ },
1854
+ });
1855
+ ```
1856
+
1857
+ ### The modes
1858
+
1859
+ | `data-gl-instances` | What is drawn | GLSL inputs |
1860
+ |---|---|---|
1861
+ | `"64"` | 64 copies of the plane. Your vertex code places each. | `instance`, `uInstances` |
1862
+ | `"tiles 24x16"` | The plane cut into 24 x 16 tiles, each its own quad. At rest they are the image, seamless. | `tile` (vec4: column, row, columns, rows), `tileCenter` (vec2, uv) |
1863
+ | `"chars"`, `"words"`, `"lines"` | GL text (`data-gl="text"`) as one quad per character, word or line. | `unitValue` (vec4: the unit's t, x, y, z from `plane.text`; `.x` is t, as in `glyph()`'s `charValue`), `unitBox` (vec4: its box in uv) |
1864
+ | `"echo 6"`, `"echo 6 delay 0.05"` | The plane plus 5 copies where it was 0.05 s, 0.1 s... ago: a trail when it moves (scroll, an animation). Copies that caught up are not drawn. | `echoOffset` (vec2: px from the plane to this copy); `instance` 0 is the plane itself, drawn on top |
1865
+ | `"ink 3000"`, `"ink 3000 size 3 luma"` | 3000 particles, each a `size` px piece of the plane, seeded where it has ink: its alpha, or its brightness with `luma`. | `inkPoint` (vec4: uv x, uv y, ink 0..1, found) |
1866
+
1867
+ `instance` (0 .. `uInstances` - 1) and `uInstances` are there in every mode. Every input is there in vertex **and** fragment code. They are plain globals: a local of the same name in your code just hides it.
1868
+
1869
+ An effect can ask for instances itself, with the same words or an object. The element's own attribute wins:
1870
+
1871
+ ```js
1872
+ gl.effect("trail", {
1873
+ instances: { echo: 8, delay: 0.035 }, // or "echo 8 delay 0.035"
1874
+ fragment: { alpha: "if (instance > 0.5) alpha *= 0.4 * (1.0 - instance / uInstances);" },
1875
+ });
1876
+ ```
1877
+
1878
+ From JS, `gl.add(el, { instances: "tiles 12x8", effects: ["shatter"] })` writes the attribute.
1879
+
1880
+ ### Text units
1881
+
1882
+ `"chars"` reads the same units as `plane.text` (their boxes, and the four numbers `t`, `x`, `y`, `z` any library tweens). Write them with GSAP or Umber's own tween; the quads follow, and a still page stays at 0 frames per second:
1883
+
1884
+ ```js
1885
+ gl.effect("letters", {
1886
+ vertex: { main: "pos.y += (1.0 - unitValue.x) * uSize.y * 0.6;" }, // .x is t
1887
+ fragment: { alpha: "alpha *= unitValue.x;" },
1888
+ setup(ctx) {
1889
+ const go = () => ctx.plane.text.chars.forEach((c, i) => c.tween("t", { value: 1, delay: i * 0.05 }));
1890
+ if (ctx.plane.text?.chars.length) go();
1891
+ return ctx.plane.on("text", go); // painted (again): a rewrap keeps t by index
1892
+ },
1893
+ });
1894
+ ```
1895
+
1896
+ - Until the text is painted, the plane draws once, whole, so it never goes blank.
1897
+ - Each quad is exactly the unit's box. Ink that reaches outside it (an italic overhang) is cut.
1898
+
1899
+ ### Per-instance numbers: attributes and data textures
1900
+
1901
+ `attributes` declares `in` attributes of the vertex shader, one value per instance. A size (1-4) fills them with a stable random 0..1; a function fills them from the instance:
1902
+
1903
+ ```js
1904
+ gl.effect("fan", {
1905
+ attributes: { aSeed: 2, aTurn: (i, n) => (i - (n - 1) / 2) * 0.04 },
1906
+ vertex: { main: "pos.x += aSeed.x * 20.0; /* aTurn: float */" },
1907
+ });
1908
+ ```
1909
+
1910
+ Change them later through `plane.instances`; they go to the GPU on the next frame:
1911
+
1912
+ ```js
1913
+ const p = gl.plane(el);
1914
+ p.instances.set("aTurn", myFloat32Array); // count x size numbers
1915
+ p.instances.data("aSeed")[0] = 0.5; // or in place...
1916
+ p.instances.update("aSeed"); // ...then say so
1917
+ p.instances.count; p.instances.mode;
1918
+ ```
1919
+
1920
+ A **data texture** works too: any texture uniform (a `gl.target()`, the input module's `gl.texture({ data, width, height })`: numbers alone have no size and throw) that your vertex code names is declared in the vertex shader for you. Read one texel per instance:
1921
+
1922
+ ```js
1923
+ const positions = await gl.target({ width: 64, height: 64, type: "float" });
1924
+ // or numbers you fill yourself (input module): gl.texture({ data: new Float32Array(64 * 64 * 4), width: 64, height: 64 })
1925
+ gl.effect("swarm", {
1926
+ instances: 4096,
1927
+ uniforms: { uPositions: positions },
1928
+ vertex: { main: "vec4 p = texelFetch(uPositions, ivec2(int(instance) % 64, int(instance) / 64), 0); pos.xy += p.xy;" },
1929
+ });
1930
+ ```
1931
+
1932
+ ### What to know
1933
+
1934
+ - **One draw per plane**, at its place in the page's order. No sorting, no batching across planes: instances draw in their own order (echo: oldest first, the plane last).
1935
+ - **Drawn while its box is on screen**: it is drawn whenever its element's box overlaps the viewport, like a plane whose vertex code bends it. Instances that move past the box still draw there, but once the box itself leaves the screen nothing is drawn. Its parents' clips never skip it whole (its instances may move out of them), but they still cut what shows.
1936
+ - **Echo** keeps a short history of where the plane was, by time (the same trail at 60 and 120 Hz). Once every copy caught up, nothing is asked for: 0 frames per second.
1937
+ - **Ink** seeds once its pixels are there (one small pass of `chunks/fx.js`, a half-float texture of one texel per particle, picked on the GPU), and again when its pixels change (new text) or, with `object-fit: cover` or `contain`, when the plane's shape changes (another part of the image shows). Until then it draws once, whole. A shader surface has no pixels to read: it draws once, with a warning. At most 65536 particles (and instances in any mode); echo at most `"echo 64"` (the plane plus 63 copies).
1938
+ - Words it does not know make it say so (`[umber] data-gl-instances="...": ... so it draws once`) and the plane draws as without instances. `"chars"` on a plane that is not GL text does the same.
1939
+ - **Up to 13 attributes** per plane (vertex attribute slots).
1940
+
1941
+ ---
1942
+
1943
+ ## Scroll-scrubbed video (module: `modules/scrub.js`)
1944
+
1945
+ Mark a video as scrubbed and its frame follows the scroll. Umber decides which frame is on screen and decodes it itself where it can, so it never asks the browser's player to seek on every scroll event (which is what makes scrubbed video stutter).
1946
+
1947
+ ```html
1948
+ <script src="https://umber.occluze.com/umber@0.2.1/modules/scrub.js"></script> <!-- after or before umber.js -->
1949
+
1950
+ <video data-gl="video" data-gl-scrub src="/scrub.mp4" poster="/scrub.jpg"
1951
+ muted playsinline preload="none"></video>
1952
+ ```
1953
+ ```js
1954
+ import { createGL } from "@occluze/umber"; // npm
1955
+ import { Scrub } from "@occluze/umber/scrub";
1956
+ const gl = createGL({ modules: [Scrub] }); // or gl.use(Scrub, { cacheMB: 128, reducedMotion: "scrub" })
1957
+ ```
1958
+
1959
+ | Attribute (also `--gl-scrub-*` in CSS) | Default | |
1960
+ |---|---|---|
1961
+ | `data-gl-scrub` | `""` | `""`: the scroll drives it. `"manual"`: your code sets `progress`. |
1962
+ | `data-gl-scrub-start` / `-end` | `"top bottom"` / `"bottom top"` | `"<element edge> <viewport line>"`, like ScrollTrigger: `top`, `center`, `bottom`, `%` or px. |
1963
+ | `data-gl-scrub-track` | the video | The element whose position drives it: a selector, `"parent"` or `"closest section"` (a sticky video inside a tall section). |
1964
+ | `data-gl-scrub-smooth` | `0.12` (0 with Lenis) | Seconds to catch up. Lenis already smooths, so Umber doesn't do it twice: also a Lenis made after `createGL()`, by the `lenis` class it puts on `<html>` (a Lenis on its own wrapper element: set `data-gl-scrub-smooth="0"` yourself). Under reduced motion (with `data-gl-scrub-reduced="scrub"`) it is always 0, whatever you set. |
1965
+ | `data-gl-scrub-source` | `auto` | `decoder` (WebCodecs), `video` (steps the `<video>`), `frames` (an image sequence). |
1966
+ | `data-gl-scrub-src` / `-src-mobile` | the video's `src` | The scrub MP4; `-mobile` on phones and weak GPUs (any device tier but "high"). |
1967
+ | `data-gl-scrub-frames` / `-count` | | An image sequence: `"/seq/f_{0001}.webp"` and its length. |
1968
+ | `data-gl-scrub-fps` | the file's, else `30` | Frame rate of a sequence or of the `<video>` tier. The decoder tier reads it from the MP4; the `<video>` tier can't, so set it to the file's rate (`npm run scrub` encodes 30 unless `--fps`), or frame numbers differ between tiers. |
1969
+ | `data-gl-scrub-blend` | `true` | Mix the two neighbouring frames while scrolling slowly. |
1970
+ | `data-gl-scrub-cache` | by GPU tier: 128 (high), 48 (mid: phones), 32 (low: weak GPUs) | GPU frame cache, MB. |
1971
+ | `data-gl-scrub-reduced` | `"poster"` | Under reduced motion: the poster, or `"scrub"` (the visitor still drives it). |
1972
+
1973
+ The module options `cacheMB` and `reducedMotion` set the site-wide defaults for `data-gl-scrub-cache` and `data-gl-scrub-reduced`.
1974
+
1975
+ From code, the handle is on the plane, and every value is plain (tween it with anything):
1976
+
1977
+ ```js
1978
+ const s = gl.plane(video)?.scrub; // undefined with GL off: the poster and the DOM video show
1979
+ if (s) {
1980
+ s.progress = 0.4; // hands it to your code (drive becomes "manual"); s.drive = "scroll" gives it back
1981
+ s.time = 2.5; // seconds into the clip
1982
+ s.frame; s.frames; s.fps; s.duration;
1983
+ s.tier; // "loading" | "decoder" | "video" | "frames" | "poster"
1984
+ await s.ready; // true with the first frame, false when it fell back to the poster
1985
+ s.on("tier", fn); // also "ready", "error"
1986
+
1987
+ gsap.to(s, { progress: 1, scrollTrigger: { trigger: video, scrub: true } }); // GSAP drives it
1988
+ }
1989
+ ```
1990
+
1991
+ - **Tiers** are tried in order until one works: WebCodecs decoder → `<video>` seeking → image sequence → poster. Reduced motion, Save-Data, no WebGL, or GL off on this device show the poster and the DOM video.
1992
+ - **Storage:** on Android the decoder tier remembers per device whether hardware or software decoding is faster, in `localStorage` (key `umber:scrub-decode`, value `prefer-hardware` or `prefer-software`). Nothing else is stored. Mention it if the site's storage or consent policy lists what it keeps.
1993
+ - **Shaders** on scrubbed planes get `uScrubProgress` (0..1) and `uScrubVelocity` (progress per second): grain or a motion smear is just another effect (`examples/video/scrub.html` adds grain).
1994
+ - **Encode for it:** `npm run scrub -- input.mov` makes an H.264 MP4 with a keyframe on every frame (scrubbing back costs the same as forwards), no B-frames, faststart and a poster. `--width`, `--fps`, `--gop`, `--crf`, `--mobile`.
1995
+ - Other MP4s work too, slower to scrub back (keyframes far apart) or with a trim kept as an edit list (the trimmed clip is what scrubs). A file the decoder tier can't read itself scrubs from the next tier (seeking the `<video>`, which is choppier): a fragmented MP4 (its frames are indexed in fragments, not in its header), a codec other than H.264 (HEVC, AV1, VP9), or a file with no frame index. Each such file gets one `[umber]` warning, also without debug mode, that names the file and the fix: encode it with `npm run scrub`. When it's this browser's doing (no WebCodecs, or a codec it can't decode), only a debug note says so (`?umber-debug` or `createGL({ debug: true })`): nothing is wrong with the file.
1996
+ - Cross-origin files need CORS headers (`Access-Control-Allow-Origin`), like any GL video.
1997
+ - Not tested yet on real phones, iOS Low Power Mode or Firefox for Android.
1998
+
1999
+ ---
2000
+
2001
+ ## Inputs (module: `modules/input.js`): drag, velocity, trail, press, step, live textures
2002
+
2003
+ `gl.pointer` and `gl.progress()` are in the core. The input module adds more inputs, each a live `{ value }` (a Signal) that works as an effect's uniform as it is. Load it on the pages that need it, one way or the other:
2004
+
2005
+ ```html
2006
+ <!-- Script tags: it registers itself. There is no Input global and nothing to call: gl.drag etc. are just there. -->
2007
+ <script src="https://umber.occluze.com/umber@0.2.1/modules/input.js"></script> <!-- after or before umber.js -->
2008
+ ```
2009
+ ```js
2010
+ // npm: import it and hand it to the engine.
2011
+ import { Input } from "@occluze/umber/input";
2012
+ gl.use(Input); // or createGL({ modules: [Input] })
2013
+ ```
2014
+
2015
+ Types: with npm they come with the import. With script tags and TypeScript, copy `types/input.d.ts` next to `types/umber.d.ts`: it adds `gl.drag` and the rest to the `GL` type (`handoff.d.ts` and `scrub.d.ts` do the same for theirs).
2016
+
2017
+ Every one of them rides frames Umber runs anyway and asks for more only while it still moves. When the input rests, its velocity lands on **exactly 0** and the loop goes back to sleep (0 frames per second).
2018
+
2019
+ ### `gl.drag(el, options)`: a drag as a Signal
2020
+
2021
+ ```js
2022
+ const d = gl.drag(".slider", { axis: "x", bounds: { x: [-2400, 0] } });
2023
+ d.value; // [x, y] offset in px from where it started
2024
+ d.velocity.value; // [vx, vy] px per second, smoothed; 0 at rest
2025
+ d.pressed; // a finger or button is down on it
2026
+ d.target; // the element the last press went down on (a card, a link inside el)
2027
+ d.direction; // [-1 | 0 | 1, -1 | 0 | 1]: which way it last moved
2028
+ d.on("release", (d) => {}); // also "press", "tap", "change"; each on() returns its off()
2029
+ d.set(0); // jump (stops a glide)
2030
+ d.bounds = { x: [-1800, 0] }; // change the limits any time (on resize)
2031
+
2032
+ gl.effect("swing", { uniforms: { uDragSpeed: d.velocity }, ... });
2033
+ d.on("change", () => (track.style.transform = `translateX(${d.value[0]}px)`));
2034
+ ```
2035
+
2036
+ | Option | Default | |
2037
+ |---|---|---|
2038
+ | `axis` | `"both"` | `"x"`, `"y"` or `"both"`. |
2039
+ | `bounds` | none | `{ x: [min, max], y: [min, max] }` in px. Or a function of the element, `(el) => ({ x: [-(el.scrollWidth - el.clientWidth), 0] })`: run again on each rebind and resize. |
2040
+ | `inertia` | `0.92` | How much glide speed is kept per 60 fps frame after release. `0` stops dead. |
2041
+ | `rubber` | `0.35` | How far it gives past a bound while pressed. `0` is a hard stop. After release it springs back inside; pressed again on the way, it goes on from where it is. |
2042
+
2043
+ - It **writes nothing to the DOM**: move your own elements from `d.value` (on `"change"`), or use it in a shader. `"change"` comes before Umber reads the frame's DOM changes, so planes inside the element you move are drawn on it in that same frame (no `data-gl-live` needed).
2044
+ - The element gets the pointer events (the canvas has `pointer-events: none`). Give it `touch-action: pan-y` for a sideways drag (the page still scrolls), `pan-x` for an up-and-down one, `none` for both. Without it Umber warns once: with `auto` a finger scrolls the page instead of dragging.
2045
+ - The click right after a drag (moved more than 6 px) is swallowed, so links in a dragged slider do not open. Only that one: a later click, and Enter on a link, go through. A press and release without moving is a `"tap"` (a press the browser cancels, to scroll the page, is a `"release"` only), and its click goes through to what was pressed (`d.target`): the pointer is only captured once it moved 6 px, so a tap on a link inside the slider opens it.
2046
+ - **A selector follows a router** (Barba, Swup, Astro, htmx...). `gl.drag(".slider")` binds its first match, then the first match of each page that enters, so call it once, outside any router hook. It's one drag across pages: the same `d.velocity` (an effect registered once keeps reading it), `value` back to `[0, 0]` on each new page, `d.el` the element it is on now (a `"change"` follows each rebind). While both pages are in the DOM it takes the new one; when the page it is on leaves and another match is still there, it moves to that one. With no match (a page without a slider) it waits. Calling `gl.drag(".slider")` again replaces the older one, so a router hook that calls it on every page still has one drag. It binds one element at a time: two sliders on one page are two `gl.drag()` calls, with two selectors.
2047
+ - **An element** (`gl.drag(el)`) is that element only, and the drag ends when it leaves the page.
2048
+ - Inside `gl.scope(fn, container)` a selector looks only in the container (its first match, and later ones), each container has its own, and `revert()` ends the drag. A page swap in the middle of a press is a `"release"`. After an `await`, call it on the scope: `s.drag(".gallery")` (every call of this module is on the scope too: `s.velocityOf`, `s.trail`, `s.step`, `s.texture`...).
2049
+ - Either ends with its `gl.scope()` and the engine.
2050
+
2051
+ ```js
2052
+ const d = gl.drag(".slider", { axis: "x", bounds: (el) => ({ x: [-(el.scrollWidth - el.clientWidth), 0] }) });
2053
+ gl.effect("swing", { ...swing, uniforms: { uDragSpeed: d.velocity } }); // keeps working on every page
2054
+ d.on("change", () => (d.el.firstElementChild.style.transform = `translateX(${d.value[0]}px)`));
2055
+ ```
2056
+
2057
+ ### `gl.velocityOf(signal, options)`: the speed of any Signal
2058
+
2059
+ ```js
2060
+ const p = gl.progress(".story");
2061
+ const v = gl.velocityOf(p); // { value }: progress per second, 0 at rest
2062
+ const dv = gl.velocityOf(d, { smooth: 0.2 }); // arrays too: [vx, vy]
2063
+ gl.effect("smear", { uniforms: { uStorySpeed: v }, ... });
2064
+ ```
2065
+
2066
+ - `smooth` (default `0.25`) is a 60 fps lerp amount: lower is calmer. `rest` (default `0.001`, units per second) is where a resting value counts as stopped.
2067
+ - It samples `signal.value` on every frame Umber runs (scrolling, the pointer, drawing). A value **your own code** moves between frames needs `gl.wake()` when it changes.
2068
+ - **A slider library's progress**: wrap it in a getter, and wake Umber from the slider's own scroll event.
2069
+
2070
+ ```js
2071
+ const slider = { get value() { return mySlider.progress; } }; // whatever your slider exposes, 0..1
2072
+ const speed = gl.velocityOf(slider);
2073
+ mySlider.on("scroll", () => gl.wake());
2074
+ gl.effect("wave", { uniforms: { uSlide: slider, uSlideSpeed: speed }, ... });
2075
+ ```
2076
+
2077
+ ### `gl.trail(count, options)`: the pointer's path
2078
+
2079
+ ```js
2080
+ const t = gl.trail(16, { follow: 0.5 }); // follow: how fast each point catches the one before
2081
+ t.points[0].value; // [x, y]: the pointer, viewport px
2082
+ t.points[15].value; // the end of the tail
2083
+ gl.effect("ribbon", { uniforms: { uHead: t.points[0], uMid: t.points[7], uTail: t.points[15] }, ... });
2084
+ t.destroy();
2085
+ ```
2086
+
2087
+ Each point is a vec2 Signal. A shader cannot take the whole list as one array uniform yet: pass the points it needs.
2088
+
2089
+ ### `gl.press`: the last press anywhere on the page
2090
+
2091
+ ```js
2092
+ gl.press.value; // [x, y, time]: viewport px, and seconds in uTime's clock (-10000 before the first)
2093
+ gl.press.recent; // the last 4 presses, newest first, each a { value: [x, y, time] } vec3 Signal (a uniform takes one)
2094
+ gl.press.count;
2095
+ gl.press.on("press", (p) => {});
2096
+
2097
+ gl.effect("ripple", {
2098
+ uniforms: { uPress: gl.press },
2099
+ fragment: { uv: "vec2 d = uRect.xy + vUv * uRect.zw - uPress.xy; float age = uTime - uPress.z; uv += normalize(d + 0.001) * sin(length(d) * 0.05 - age * 12.0) * exp(-age * 3.0) * 0.01;" },
2100
+ update(ctx) { ctx.busy(ctx.frame.time - gl.press.value[2] < 1.5); }, // keep drawing while it ripples
2101
+ });
2102
+ ```
2103
+
2104
+ It listens to `pointerdown` (passive, on window) from the first time anything reads `gl.press`. A ripple animates with `uTime`, so keep the plane drawing while it runs (`ctx.busy(true)` in `update`, as above); the press itself only stamps the frame it happened on.
2105
+
2106
+ `gl.press` is one for the page and outlives page swaps, but a `gl.press.on()` made inside a `gl.scope()` goes with its `revert()`. Only one made before the scope's first `await` is recorded: after it, keep its `off()` and call it yourself. Like `gl.on()` (and `addEventListener`), the same function added twice is one listener, so the first `off()` or revert removes it.
2107
+
2108
+ ### `gl.step(px, fn)`: every N px the pointer travels
2109
+
2110
+ ```js
2111
+ const off = gl.step(80, ([x, y], n) => stamp(x, y, n)); // image trails, stamps
2112
+ off();
2113
+ ```
2114
+
2115
+ It reads `gl.pointer` on the frames it moves; the first move (from the screen's centre) does not count, nor a jump to a new press (a second finger) or back into the window. `at` is a new `[x, y]` each time, on the path where that step was reached, so it is yours to keep.
2116
+
2117
+ ### `gl.texture(source, options)`: a canvas, video or numbers as a `sampler2D`
2118
+
2119
+ ```js
2120
+ const canvas = document.querySelector("canvas.mask");
2121
+ const mask = gl.texture(canvas); // also an ImageBitmap, <video>, <img>, ImageData
2122
+ gl.effect("reveal", { uniforms: { uMask: mask }, fragment: { alpha: "alpha *= texture(uMask, vUv).r;" } });
2123
+ drawMyMask(canvas);
2124
+ mask.update(); // you drew on it: uploaded before the next draw
2125
+
2126
+ const field = new Float32Array(32 * 32); // numbers: 1, 2 or 4 per texel (R, RG, RGBA)
2127
+ const grid = gl.texture({ data: field, width: 32, height: 32 });
2128
+ field[5] = 1; grid.update();
2129
+ gl.effect("grid", { uniforms: { uGrid: grid }, fragment: { uv: "uv += texture(uGrid, uv).r * 0.02;" } });
2130
+ ```
2131
+
2132
+ - It is uploaded **only when you say it changed** (`update()`, or `update(newSource)`), and only once a plane that samples it is drawn: a still page uploads nothing and sleeps. A `<video>` uploads each new frame it shows while it plays (nothing while paused).
2133
+ - `options`: `filter: "nearest"` for crisp texels, `wrap: "repeat"` to tile it. Float data (`Float32Array`) is always sampled `nearest` and declared `highp` (exact numbers on phones too): read it at texel centres, or with `texelFetch(uGrid, ivec2(x, y), 0)`. 8-bit data (`Uint8Array`) reads 0..1 and is filtered.
2134
+ - One texture serves any number of planes and effects. Images from another origin need CORS, as every GL image does. `t.width`, `t.height`, `t.destroy()`. After a lost context it is made again by itself.
2135
+ - A raw canvas, video or typed array as a uniform (without `gl.texture()`) would sample nothing, and more than 896 numbers are more than a phone's uniforms hold: Umber warns and names this fix (numbers that fit no GLSL type: when the GLSL reads them without declaring them).
2136
+ - The pointer's whole trail in one uniform: `gl.texture({ data: xy, width: 16, height: 1 })` (a `Float32Array` of 32), refilled from `trail.points` and `update()`d on the frames it moves.
2137
+
2138
+ ### `gl.touch(options)`: the pointer's fading trail as a texture
2139
+
2140
+ ```js
2141
+ const touch = gl.touch({ size: 64, radius: 0.08, fade: 0.92 });
2142
+ gl.effect("smear", {
2143
+ uniforms: { uTouch: touch },
2144
+ fragment: { uv: "vec4 t = texture(uTouch, screenUv()); uv += (t.rg * 2.0 - 1.0) * t.a * 0.03;" },
2145
+ });
2146
+ ```
2147
+
2148
+ A small screen-shaped canvas (`size` px wide) where the pointer leaves soft dots: `a` is the ink (0..1), `rg` the way it moved (`rg * 2.0 - 1.0`, -1..1). Sample it at the pixel's place on screen, `screenUv()`, so one texture serves every plane. `fade` is how much ink stays per 60 fps frame; `radius` is a share of the width. It draws only on frames the pointer moved, fades to exactly empty, then stops asking for frames: a still page sleeps. `touch.canvas` is the canvas itself.
2149
+
2150
+ ### `gl.rects(selector)`: element rects as numbers a shader reads
2151
+
2152
+ ```js
2153
+ const cards = gl.rects(".card"); // N x 1 texels: x, y, width, height in viewport px per card
2154
+ gl.shader("glow", {
2155
+ uniforms: { uCards: cards },
2156
+ fragment: `
2157
+ vec2 p = screenPx();
2158
+ for (int i = 0; i < 64; i++) {
2159
+ if (i >= textureSize(uCards, 0).x) break;
2160
+ vec4 r = texelFetch(uCards, ivec2(i, 0), 0);
2161
+ color += vec4(0.1) * step(roundedBox(p - r.xy, r.zw, vec4(12.0)), 0.0);
2162
+ }`,
2163
+ });
2164
+ ```
2165
+
2166
+ One shader draws behind or through a whole grid. The rects come from `gl.track()` (no layout reads while scrolling) and are uploaded only on frames one of them moved. `cards.count`, `cards.rects` (the same numbers, 4 per element), `cards.destroy()`. It holds the elements the selector found at the call: call it again after a page change.
2167
+
2168
+ ### `gl.imageColor(el)`: the colour of an element's image
2169
+
2170
+ ```js
2171
+ const c = gl.imageColor(".hero"); // { value: [r, g, b, a] }: the average colour, sRGB 0..1
2172
+ await c.ready; // true once known (false: no CORS, no image)
2173
+ c.dominant; // the most common colour
2174
+ gl.effect("tint", { setup(ctx) { ctx.plane.set("uBg", gl.imageColor(ctx.el)); }, fragment: { color: "color.rgb = mix(uBg.rgb, color.rgb, color.a);" } });
2175
+ ```
2176
+
2177
+ Worked out once per image (`data-gl-src`, or the `<img>`'s current source) from a 16 x 16 copy that the browser decodes and shrinks off the main thread; `[0, 0, 0, 0]` until then. It is a vec4 Signal: a uniform as it is, which redraws when the colour arrives.
2178
+
2179
+ ---
2180
+
2181
+ ## Smooth scrolling (module: `modules/scroll.js`): `gl.scroll`, instead of a scroll library
2182
+
2183
+ Opt-in. Without it Umber scrolls nothing: the page scrolls natively, or with the site's own Lenis (`createGL({ scroll: lenis })`, as above), exactly as before. With it, the wheel eases the page's real scroll position on Umber's own loop, and GL planes stay on their elements to the pixel. Use the module **or** Lenis, never both.
2184
+
2185
+ ### Start
2186
+
2187
+ ```html
2188
+ <!-- Script tags: it registers itself. Nothing to call: gl.scroll is just there. -->
2189
+ <script src="https://umber.occluze.com/umber@0.2.1/umber.js"></script>
2190
+ <script src="https://umber.occluze.com/umber@0.2.1/modules/scroll.js"></script>
2191
+ <script>const gl = Umber.createGL();</script>
2192
+ ```
2193
+ ```js
2194
+ // npm: import it and hand it to the engine.
2195
+ import { Scroll } from "@occluze/umber/scroll";
2196
+ gl.use(Scroll, { lerp: 0.1 }); // or createGL({ modules: [[Scroll, { lerp: 0.1 }]] })
2197
+ ```
2198
+
2199
+ **Webflow:** put the two script tags in Site settings, Custom code, Footer code. That's the whole setup. Everything else is a Custom attribute on the **Body** (Page settings, or the Body element's settings):
2200
+
2201
+ | Body attribute | Value | What it does |
2202
+ |---|---|---|
2203
+ | `data-gl-scroll-offset` | `-80` | Every `#link` stops 80 px above its target (a fixed navbar 80 px tall). |
2204
+ | `data-gl-scroll` | `off` | This page scrolls natively (the module stays loaded for the others). |
2205
+ | `data-gl-scroll-lerp` | `0.08` | Floatier (lower) or snappier (higher). Default `0.1`. |
2206
+
2207
+ Types: with npm they come with the import. With script tags and TypeScript, copy `types/scroll.d.ts` next to `types/umber.d.ts`.
2208
+
2209
+ ### Recipes
2210
+
2211
+ ```js
2212
+ // Scroll to a section (a selector, an element, px, "top" or "bottom"), 80 px above it.
2213
+ gl.scroll.scrollTo("#contact", { offset: -80 });
2214
+
2215
+ // The same over exactly 1.2 s with your own ease; the wheel can't interrupt it.
2216
+ gl.scroll.scrollTo("#pricing", { duration: 1.2, easing: (t) => 1 - (1 - t) ** 3, lock: true });
2217
+
2218
+ // A modal: hold the page while it is open (its own list still scrolls).
2219
+ openButton.addEventListener("click", () => { modal.showModal(); gl.scroll.stop(); });
2220
+ modal.addEventListener("close", () => gl.scroll.start());
2221
+
2222
+ // A fixed header for every #link (the same as data-gl-scroll-offset="-80" on <body>).
2223
+ gl.scroll.options.anchors = { offset: -80 };
2224
+
2225
+ // A progress bar, and the scroll speed for an effect (or read gl.velocity, the engine's).
2226
+ gl.scroll.on("scroll", (s) => (bar.style.transform = `scaleX(${s.progress})`));
2227
+ gl.effect("stretch", { uniforms: { uSpeed: { value: 0 } } /* ...your GLSL... */ });
2228
+ gl.on("frame", () => gl.plane(hero)?.set("uSpeed", gl.scroll.velocity / 40));
2229
+
2230
+ // Turn smoothing off on one page from code (or data-gl-scroll="off" on its <body>).
2231
+ gl.scroll.options.wheel = false;
2232
+ ```
2233
+
2234
+ **With GSAP ScrollTrigger: nothing to add.** When the page has `ScrollTrigger`, every frame the module writes the scroll it calls `ScrollTrigger.update()` right away, so pins and scrubs move in the same frame as the page (measured: 0 px pin jitter, 0 px scrub lag in Chromium, Firefox and WebKit). Write your ScrollTriggers as for native scroll; no `scrollerProxy`, no `lenis.on("scroll", ScrollTrigger.update)` line.
2235
+
2236
+ ### How it works
2237
+
2238
+ - The wheel moves a **target**. Every frame of Umber's own loop, the drawn position eases toward it and is **written to the real scroll position** (the window's, or a wrapper's). Nothing is faked: the DOM, `position: sticky`, IntersectionObserver, CSS scroll-driven animations and other code's scroll listeners see a normal scroll.
2239
+ - It writes **before Umber reads the scroll** in the same frame, so planes and the DOM move together, 0 px apart, with no `createGL({ scroll })`. One loop: it adds no `requestAnimationFrame` of its own.
2240
+ - Each engine's wheel step is the distance that browser would scroll natively (they report it in px, kept 1:1), so a notch goes as far as it does without the module. The easing is time-based: the same curve at 30, 60, 120 or 144 Hz, and a slow frame catches up without overshooting.
2241
+ - At rest it asks for no frames: a still page runs 0 rAF/s. It keeps the loop running only while it moves, also with GL paused or off (a phone, Save-Data): smooth scrolling doesn't need GL.
2242
+ - `limit` follows a ResizeObserver on the content and `resize` events (lazy images, a list that grows, a phone's address bar): no layout read while it moves.
2243
+
2244
+ ### What stays native
2245
+
2246
+ The browser's own scrolling, untouched:
2247
+
2248
+ - **Keys** (arrows, Space, Page Up / Down, Home, End, Tab to a link below), the **scrollbar**, **find-in-page**, **focus** moving to an element off screen, **back / forward** scroll restoration, **middle-click** autoscroll, a **text selection** dragged past the edge. A key pressed mid-glide hands over to the browser's key scroll. Any scroll the module did not write is taken as the new position, also mid-glide (the glide ends there; `gl.scroll` follows it, `isScrolling` is `"native"`). Only when the page grew above (images loading) does the glide go on, shifted with the content.
2249
+ - **Ctrl / ⌘ + wheel** and trackpad pinch (zoom), **sideways** swipes and Shift + wheel (carousels, the back gesture).
2250
+ - **Touch**: phones and tablets scroll natively, with their own momentum, unless `touch: true`. The module then adds no touch listener at all, so the browser never waits for the page on a touch.
2251
+ - **`prefers-reduced-motion: reduce`**: the wheel is native and `scrollTo()` jumps.
2252
+ - **Elements that scroll by themselves** under the pointer (a menu, a modal's list, a code block, `overflow: auto`) scroll first, natively; at their end the page goes on, as native scroll chaining does (not past an `overscroll-behavior: contain` one). Iframes (video and map embeds) get their own wheel at rest; while the page glides they take no pointer events, so a glide passing over one goes on. `data-gl-scroll-prevent` keeps any element and its children native (and keeps its scroll in: `overscroll-behavior: contain`); `data-gl-scroll-prevent-wheel` / `-touch` only that input. Lenis's `data-lenis-prevent` (and `-wheel`, `-touch`) work the same, so a site moving from Lenis keeps its markup.
2253
+ - **CSS `scroll-snap`** on the scroller: the wheel stays native (so it snaps), and `scrollTo()` and `#links` use the browser's own smooth scroll (which snaps too).
2254
+ - **A page held by a scroll lock**: `overflow: hidden` on `<html>` or `<body>` (most modal libraries) or `position: fixed` on `<body>` (iOS-style locks): the wheel stays native and moves nothing.
2255
+ - **At the top going up, or the end going down**: the browser's own (overscroll bounce, a parent frame).
2256
+ - **Another smooth scroller** on the page (Lenis marks `<html class="lenis">`): it keeps the wheel, and Umber warns once.
2257
+ - **A domain that isn't on an Umber licence** (the domains listed under Umber at occluze.com): scrolling stays the browser's, and `scrollTo()` and `#links` use its own smooth scroll. The same holds while the answer is on its way (asked once per page, `gl.licensed()`; a yes is kept a day). `localhost` and `*.test` always work.
2258
+
2259
+ ### `gl.scroll`
2260
+
2261
+ The shape scroll libraries share (Lenis's), so tools that look for one find it at `window.__umber.engine.scroll`:
2262
+
2263
+ ```js
2264
+ gl.scroll.animatedScroll; // where the page is drawn now (px)
2265
+ gl.scroll.targetScroll; // where it is heading
2266
+ gl.scroll.limit; // the largest scroll (px)
2267
+ gl.scroll.velocity; // px per frame at 60 fps, + down; 0 at rest (an effect's uScrollVelocity is about this / 60, smoothed, -1..1)
2268
+ gl.scroll.direction; // 1 down, -1 up
2269
+ gl.scroll.progress; // 0..1 down the page
2270
+ gl.scroll.isScrolling; // "smooth" | "native" | false
2271
+ gl.scroll.isStopped; // after stop()
2272
+
2273
+ const off = gl.scroll.on("scroll", (s) => {}); // every frame it moves, and on native scrolls
2274
+ gl.scroll.stop(); // hold the page: no wheel, touch or keys (data-gl-scroll-state="stopped": overflow hidden; a
2275
+ // scrollbar that takes room keeps it, so nothing reflows)
2276
+ gl.scroll.start(); // ...and back (its own overflow restored)
2277
+ gl.scroll.resize(); // measure again now and take the real position (after a page swap)
2278
+ gl.scroll.raf(time); // only to step it from your own loop; Umber's loop does it otherwise
2279
+ ```
2280
+
2281
+ | `scrollTo()` option | Default | |
2282
+ |---|---|---|
2283
+ | `offset` | `0` | px added to the target's position. `-80` stops 80 px above it. An element's `scroll-margin-top` and the scroller's `scroll-padding-top` count too, as for a native `#link`. |
2284
+ | `immediate` | `false` | Land now, in this frame. It also lands while stopped (a page swap's jump to the top). Less than a screen counts as motion (`velocity`), so code that steps the page frame by frame moves velocity-driven effects. |
2285
+ | `jump` | `false` | With `immediate`: a jump, not motion (no `velocity`, no `direction`), however short: a page swap, a history step. |
2286
+ | `duration`, `easing` | the module's | Seconds and a `(t) => t` ease (instead of the lerp). |
2287
+ | `lerp` | the module's | This move's lerp. |
2288
+ | `lock` | `false` | Ignore the wheel, touch, the scroll keys and other animated `scrollTo()`s until it lands. |
2289
+ | `force` | `false` | Animate also while stopped or locked. |
2290
+ | `onComplete` | | When it lands (not when the wheel or a key interrupts it). |
2291
+
2292
+ The wheel interrupts a `scrollTo()` from where the page is drawn.
2293
+
2294
+ ### Options
2295
+
2296
+ `gl.use(Scroll, { ... })`. With the script build, set them on `gl.scroll.options` right after `createGL()` (each is read when it is used; `touch`, `wrapper`, `content` and `autoResize` only at the start), or use the attributes below. Who wins, for `lerp` and `duration`: the defaults, then the page's `data-gl-scroll-lerp` / `-duration` (each page of a router can have its own), then `gl.use()`'s options, then a write to `gl.scroll.options` (it stays: page changes don't undo it).
2297
+
2298
+ | Option | Default | |
2299
+ |---|---|---|
2300
+ | `lerp` | `0.1` | The share of the way it moves per 60 fps frame, the same at any refresh rate. Lower is floatier; `1` is no smoothing. |
2301
+ | `duration`, `easing` | `0`, expo out | Seconds a wheel move takes, with this ease, instead of the lerp. |
2302
+ | `wheelMultiplier` | `1` | Wheel distance times this. |
2303
+ | `wheel` | `true` | `false`: the wheel scrolls natively (`scrollTo()` and anchors still glide). |
2304
+ | `touch`, `touchMultiplier` | `false`, `1` | Smooth touch too: the page follows the finger 1:1, and a flick goes on at the finger's speed and slows down like a phone's own momentum (speed x 325 ms in all). Off, phones scroll natively, which is what most sites want. |
2305
+ | `wrapper` | `[data-gl-scroll-wrapper]`, else the window | An element that scrolls instead of the window (an app shell: `html, body { overflow: hidden }`, the wrapper `height: 100vh; overflow: auto`). Mark it `data-gl-scroll-wrapper`: Umber's engine then follows its scroll by itself. Keys scroll it only while focus is inside it (give it `tabindex="-1"` and focus it), as without the module. |
2306
+ | `content` | the wrapper's first child, or `<html>` | What grows (watched for `limit`). |
2307
+ | `anchors` | `true` | In-page `#id` links glide (and add a history entry like a native `#link`, and move focus when used from the keyboard). An object: `scrollTo()` options for them, like `{ offset: -80 }`. |
2308
+ | `autoResize` | `true` | `false`: call `gl.scroll.resize()` yourself. |
2309
+ | `prevent` | none | `(el) => boolean`: true keeps that element's wheel and touch native, like `data-gl-scroll-prevent`. |
2310
+ | `nested` | `true` | `false`: elements that scroll by themselves don't scroll first (only `data-gl-scroll-prevent` does). |
2311
+
2312
+ ### Attributes
2313
+
2314
+ | Attribute | On | |
2315
+ |---|---|---|
2316
+ | `data-gl-scroll="off"` | `<body>` or `<html>` | The wheel, touch and anchors stay native on this page (read on every wheel: a router's new body can carry it). `scrollTo()` still works. |
2317
+ | `data-gl-scroll="touch"` | `<body>` or `<html>` | Smooth touch too. |
2318
+ | `data-gl-scroll-lerp`, `data-gl-scroll-duration` | `<body>` or `<html>` | The options, for sites without code. Read again by `gl.scroll.resize()` (Umber's router calls it after each page change), so each page can have its own. Options given in `gl.use()` win. |
2319
+ | `data-gl-scroll-offset="-80"` | a `#link`, its target, or `<body>` | px for anchor links (the link's first, then the target's, then the page's). It adds to CSS `scroll-margin-top`: use one or the other. A page opened with a `#hash` in its URL is the browser's own jump, which only CSS (`scroll-margin-top`) moves. |
2320
+ | `data-gl-scroll-prevent` | any element | It and its children scroll natively (a menu, a modal, a map). `-wheel` / `-touch` for one input only. Lenis's `data-lenis-prevent` (and its `-wheel`, `-touch`) too. |
2321
+ | `data-gl-scroll-wrapper` | the scroller | The element that scrolls instead of the window. Umber's engine follows it too. |
2322
+
2323
+ ### With a router and with page flights
2324
+
2325
+ - **Umber's router** (`gl.router`) does it all by itself: it stops the scroll while a page changes, takes the new page to its top (or its `#hash`, or back to where you were on back / forward), and measures the new page.
2326
+ - **Another router** (Barba, Swup...): the same in its hooks:
2327
+
2328
+ ```js
2329
+ // When the old page starts to leave:
2330
+ gl.scroll.stop();
2331
+ // Once the new page is in:
2332
+ gl.scroll.scrollTo(0, { immediate: true }); // lands also while stopped
2333
+ gl.scroll.start();
2334
+ gl.scroll.resize();
2335
+ ```
2336
+
2337
+ - **`data-gl-id` flights** (with a router, or the handoff module across full page loads) work as with native scroll: a flight lands on its element wherever the scroll is, and the back button's restored position is taken as it is.
2338
+ - **Moving from Lenis:** take `new Lenis()` and `createGL({ scroll: lenis })` out and load the module. `lenis.scrollTo(...)` becomes `gl.scroll.scrollTo(...)`, `lenis.on("scroll", ...)` becomes `gl.scroll.on("scroll", ...)`, `lenis.stop()` / `start()` stay the same, `data-lenis-prevent` works as it is (or becomes `data-gl-scroll-prevent`), CSS on `html.lenis-stopped` / `.lenis-scrolling` becomes `[data-gl-scroll-state~="stopped"]` / `~="smooth"`, and the `ScrollTrigger.update` line goes (it is built in).
2339
+
2340
+ ### Good to know
2341
+
2342
+ - **`data-gl-scroll-state`** on `<html>` (or the wrapper) says what the module does: `smooth` while it glides, `stopped` after `stop()` (`stopped gutter` when a classic scrollbar keeps its room), nothing at rest. Style on it (`[data-gl-scroll-state~="smooth"] .cursor { opacity: .5 }`). The module's own rules for it come in a small stylesheet it adds itself: `umber.css` isn't needed, and `stop()` writes no inline style, so it composes with a modal library's own lock.
2343
+ - **Events like a native scroll:** one `scrollend` when a glide lands (not one per frame); a `#link` adds a history entry and fires `hashchange`. CSS `:target` doesn't follow a link the module glides to (only the browser's own jump sets it): a site that styles `:target` sets `anchors: false`.
2344
+
2345
+ - **Webflow's own smooth anchor scroll** (Webflow's scripts handle same-page `#links` themselves, with their fixed-header offset) runs first; the module steps aside for those clicks and follows the page as it moves. Legacy Webflow Interactions that read the scroll (IX2 "while scrolling") hear the browser's scroll event, which comes one frame after a write, as with any smooth scroller; GSAP-based interactions are in step (above).
2346
+ - **CSS scroll-driven animations** (`animation-timeline: scroll()`) are in step in Chromium; WebKit applies a write made during a frame on its next frame (the same for every smooth scroller).
2347
+ - Not in the module: horizontal-only and infinite scrolling, its own snapping (CSS `scroll-snap` is honoured, above), and framework wrappers.
2348
+
2349
+ ---
2350
+
2351
+ ## Utilities: tracking, the loop, maths
2352
+
2353
+ Small tools for the jobs GL work always needs. Umber does not copy `gsap.utils`.
2354
+
2355
+ ### gl.track(el): where an element is, every frame, without WebGL
2356
+
2357
+ ```js
2358
+ const t = gl.track(".card"); // works with GL off (phones, Save-Data) too
2359
+ t.rect; // { x, y, width, height } in viewport CSS px this frame, like getBoundingClientRect
2360
+ t.inView; // on screen
2361
+ t.near; // within 1.5 screens
2362
+ t.progress; // 0 as its top enters at the bottom, 1 as its bottom leaves at the top
2363
+ t.dpr;
2364
+ const off = t.on("enter", (t) => {}); // also "leave", "resize", "destroy"; on screen already: "enter" on the first frame
2365
+ t.destroy(); // automatic when the element leaves the page
2366
+ ```
2367
+
2368
+ A scroll over a still layout reads nothing: the element is measured once and moved with the absolute scroll position, like a plane (measured again on a resize, or a style or class change on it or a parent). `gl.track(el, { live: true })` measures it every frame (detected by itself for sticky, fixed and pinned parents).
2369
+
2370
+ ### Signals: live `{ value }` objects Umber keeps up to date
2371
+
2372
+ A Signal is a plain `{ value }` that Umber writes every frame it changes. Read it in your code, tween from it, or hand it to an effect **as a uniform**: Umber reads it on every drawn frame and redraws when it changed, so a scroll- or pointer-driven shader needs no JavaScript per frame.
2373
+
2374
+ ```js
2375
+ // 0..1 as an element scrolls through: "<element edge> <viewport line>", the same syntax as scrub
2376
+ const p = gl.progress(".story", { start: "top top", end: "bottom bottom" });
2377
+ p.value; // this frame's progress (works with GL off too)
2378
+ p.on("change", (p) => {}); // also "destroy"; each on() returns its off()
2379
+ p.destroy(); // automatic when the element leaves the page
2380
+
2381
+ gl.progress(el); // default: "top bottom" to "bottom top"
2382
+ gl.progress(el, { start: "top+=100 80%", end: "center center-=10%" }); // px and % offsets (not in a play's `start`)
2383
+ gl.progress(el, { start: "entry", end: "exit" }); // CSS view-timeline ranges: cover, contain, entry, exit, entry-crossing, exit-crossing ("entry 50%", "cover 50px")
2384
+ gl.progress(".hero", { css: "--hero" }); // also as a CSS variable on the element: opacity: calc(1 - var(--hero))
2385
+
2386
+ gl.pointer.value; // [x, y] viewport CSS px (mouse, pen, touch)
2387
+ gl.pointer.velocity.value; // [vx, vy] px per second, smoothed, 0 at rest
2388
+ gl.pointer.active; // false until it first moved (value is the viewport's centre)
2389
+
2390
+ gl.effect("story", { uniforms: { uStory: p, uPointer: gl.pointer, uSpeed: gl.pointer.velocity }, ... });
2391
+ gl.plane(el)?.set("uStory", gl.progress(el.closest("section"))); // per plane: set() links it too
2392
+ ```
2393
+
2394
+ - `gl.progress()` is a tracker underneath: measured once, then moved with the **absolute** scroll in the measure phase, so it is right with native scroll, a scrolling element (`createGL({ scroll: el })`) and a Lenis you passed in. It never keeps the loop awake; scrolling, resizes and DOM changes wake it, and that is when it changes.
2395
+ - `css: "--name"` writes the value (4 decimals) only when it changed, into a rule of Umber's own stylesheet that matches that element (it gets `data-gl-css="n"`), never its `style` attribute: no DOM change, so no layout read and no observer wakes. The property stays at its last value after the signal ends.
2396
+ - Range names follow CSS `animation-range`: `cover` is `top bottom` to `bottom top`; `contain` is the part where the element is fully on screen (or covers the whole screen, when taller); `entry` and `exit` are the parts where it comes in and goes out. A name alone is its 0% as a `start` and its 100% as an `end`.
2397
+ - `gl.pointer` attaches its passive listeners the first time anything reads it, and keeps the loop awake only while its velocity settles back to 0. To use it in GLSL, compare with the pixel's own viewport position: `vec2 d = screenPx() - uPointer;` (`screenPx()` is right also on a rotated or tilted element).
2398
+ - `gl.velocity` (scroll) is a Signal too. Any `{ value }` of your own works as a uniform; Umber reads it on frames it draws anyway, so call `gl.wake()` after changing it while nothing else moves.
2399
+ - More inputs (a drag, the speed of any Signal, the pointer's trail, presses, steps) come with the input module: see Inputs.
2400
+
2401
+ ### The loop
2402
+
2403
+ Umber runs one `requestAnimationFrame` loop with three phases per frame: **measure** (layout reads only), **update** (maths and writes) and **render** (WebGL). It sleeps when nothing changes: a still page runs no frames at all.
2404
+
2405
+ ```js
2406
+ const off = gl.on("frame", (f) => {
2407
+ // f = { time, dt, ratio, frame, woke, scroll: { x, y, velocity } }
2408
+ }, { phase: "update", order: 0 }); // keeps the loop running every frame while it is on
2409
+
2410
+ gl.on("frame", followPlanes, { phase: "render", always: false }); // only on frames Umber runs anyway
2411
+
2412
+ gl.velocity.value; // the scroll speed effects get as uScrollVelocity: px/s / 3600, clamped to -1..1 and smoothed (a plain { value })
2413
+ gl.wake(2); // run at least 2 more frames
2414
+
2415
+ const cancel = gl.nextFrame((f) => {}); // once, on the next frame (update phase)
2416
+ gl.nextFrame(() => readLayout(), { phase: "measure" }); // or in another phase
2417
+ ```
2418
+
2419
+ **Your own loop instead:** `createGL({ loop: false })`, then call `gl.render(time)` once per frame with the frame time in **ms**:
2420
+
2421
+ ```js
2422
+ const gl = Umber.createGL({ loop: false });
2423
+ gsap.ticker.add((t) => gl.render(t * 1000)); // GSAP's ticker
2424
+ renderer.setAnimationLoop((t) => { gl.render(t); }); // or three.js's loop
2425
+ ```
2426
+
2427
+ Calling `gl.render()` while Umber runs its own loop warns and does nothing (use `createGL({ loop: false })`). Calling it twice in one frame (two loops) warns.
2428
+
2429
+ ### Scopes: one revert() for everything a component made
2430
+
2431
+ ```js
2432
+ const scope = gl.scope((s) => {
2433
+ gl.effect("bulge", bulge); // definitions (revert brings the old one back, or none)
2434
+ gl.add(".media", { effects: ["bulge"] }); // planes from code; selectors look inside `card`
2435
+ const p = gl.progress(card); // trackers and signals
2436
+ gl.on("frame", () => (bar.style.width = `${p.value * 100}%`), { always: false }); // frame callbacks, events
2437
+ gl.attach(".scene", { renderer, scene, camera }); // three.js views; also gl.view, gl.nextFrame, nested scopes
2438
+ }, card);
2439
+
2440
+ scope.revert(); // all of it, newest first: planes go, Umber's attributes come off, effects unregister
2441
+ ```
2442
+
2443
+ - It records the Umber calls made **while fn runs**. After an `await`, call them on the scope itself (`s.add`, `s.track`, `s.progress`, `s.attach`, `s.view`, `s.effect`, `s.shader`, `s.layer`, `s.chunk`, `s.on`, `s.nextFrame`, `s.scope`, and `s.target`, `s.snapshot`, `s.sim`, `s.flow`, `s.brush`, `s.preload`, `s.warm`, `s.leave`, `s.flip`, plus every call a module adds: `s.drag`, `s.texture`...): those always belong to it.
2444
+ - What `revert()` does to the later calls: targets, snapshots, sims and brushes are released (a target asked for and reverted before it arrived is released when it does); `gl.leave()` goes back to the newest one still set (scopes may revert in any order; one set outside any scope stays), and a page change already holding or playing the old page finishes first; `gl.preload({ hover })` is turned off; a module's objects (`gl.drag`, `gl.trail`, `gl.texture`, `gl.touch`...) are destroyed and `gl.step()` stops. The page's one `gl.flow()` flowmap is released only by the scope whose call made it (one made before is shared: a scope that only tunes it with `gl.flow({ fade })` leaves it, with those options), and kept while a plane reads `uFlow`. `gl.warm()`, `gl.flip()` and a plain `gl.preload()` hold nothing to undo (images made ahead are freed after 20 s unless a plane claims them).
2445
+ - `revert()` while an async fn still awaits is safe: that run's calls through `s` then make nothing (`s.add()` resolves `null`), so a fast mount and unmount never leaks. `s.reverted` tells the rest of fn to stop.
2446
+ - `scope.run(fn)` runs more code in the scope later; `await scope.ready` waits for an async fn. A scope made inside another goes with it. A fn that throws is logged; what it made before stays in the scope.
2447
+ - Umber never reads GSAP, so it does not join a `gsap.context()`: call `scope.revert()` next to `ctx.revert()` (or inside your framework's unmount).
2448
+
2449
+ ### Maths (pure, no engine needed)
2450
+
2451
+ ```js
2452
+ const { damp, clamp, lerp, mapRange, smoothstep, rectProgress } = Umber.math; // npm: import { damp } from "@occluze/umber"
2453
+
2454
+ x = damp(x, target, 0.1, f.dt); // a lerp that moves the same at 30, 60, 120 and 144 Hz (amount 0..1, as at 60 Hz)
2455
+ clamp(v, 0, 1);
2456
+ lerp(a, b, t);
2457
+ mapRange(v, inMin, inMax, outMin, outMax);
2458
+ smoothstep(0.2, 0.8, v); // GLSL's: 0 below, 1 above, smooth between
2459
+ rectProgress(el.getBoundingClientRect(), "top bottom", "bottom top"); // gl.progress's maths on any rect
2460
+ ```
2461
+
2462
+ Plus the DOM ↔ 3D helpers in three.js: `rectToWorld`, `worldToRect`, `pxPerWorld`, `fitCamera`.
2463
+
2464
+ ### Modules
2465
+
2466
+ ```js
2467
+ import { createGL } from "@occluze/umber";
2468
+ import { Scrub } from "@occluze/umber/scrub";
2469
+ import { Debug } from "@occluze/umber/debug";
2470
+
2471
+ const gl = createGL({ modules: [[Scrub, { cacheMB: 128 }], Debug] }); // optional modules, from the start
2472
+ // or later, for this engine: gl.use(Scrub, { cacheMB: 128 }).use(Debug);
2473
+ ```
2474
+
2475
+ A module script (`modules/scrub.js`, `modules/debug.js`) registers itself (with `Umber.use()`: for the engine on the page and every later one); load it before or after `umber.js`, always from the **same version**. A module from another version warns: `modules/scrub.js 0.1.1 with umber.js 0.1.0: load both from the same version.` Any difference warns, even a patch (the full version strings are compared). An attribute of a module that is not loaded warns too: `data-gl-scrub on <video.hero>: no module "scrub". Load modules/scrub.js next to umber.js...`. A module's api lands on each plane it handles at `plane[module.name]` (`gl.plane(el).scrub`), so `gl.use()` refuses a module named like the plane's own members (`play`, `set`, `get`, `tween`, `on`, `destroy`... or any name starting with `_`) and warns: `module "play": plane.play is Umber's own. Rename the module.` A name that is one of the plane's inner fields (`mouse`, `texture`...) is only known once GL is loaded: the module still runs, its api stays off the plane, and Umber warns the same way.
2476
+
2477
+ ---
2478
+
2479
+ ## Debugging: warnings, gl.inspect, the debug module
2480
+
2481
+ ### Warnings that name the fix
2482
+
2483
+ Every message starts with `[umber]`, is shown **once**, and says what to change. After 100 messages Umber stays quiet for the visit. `createGL({ warnings: false })` silences warnings; errors (a shader that does not compile, a callback that threw) always show. Umber never throws at the page, with one exception: `gl.texture()` from the input module throws a TypeError naming the fix when it gets no source, or numbers without a size. Anywhere else, when something fails, that element's DOM shows.
2484
+
2485
+ | You did | Umber says (shortened) |
2486
+ |---|---|
2487
+ | `data-gl-effect="disolve"` | `data-gl-effect="disolve" on <div#typo>: no effect with that name (did you mean "dissolve"?). Define it first with gl.effect("disolve", {...}): Umber ships no effects...` |
2488
+ | `plane.set("uShw", 1)` | `plane.set("uShw") on <div.card>: no effect on this plane has a uniform "uShw", so no shader reads it (did you mean "uShow"?)...` |
2489
+ | a `data-gl` element that is hidden or has no size | `<div#hidden> has data-gl but is 0×0 px after 3 s, so it draws nothing: hidden (display: none), or it has no size yet...` |
2490
+ | `gl.render()` from two loops | `gl.render() was called twice in one frame (two loops call it?). Call it from one loop only...` |
2491
+ | `gl.render()` with Umber's own loop on | `gl.render() was called while Umber runs its own loop (two loops?). Use createGL({ loop: false })...` |
2492
+ | `createGL()` twice | `createGL() was called twice; returning the existing engine. Call gl.destroy() first to start fresh.` |
2493
+ | `umber.js` and a module from different versions | `modules/scrub.js 0.1.1 with umber.js 0.1.0: load both from the same version.` |
2494
+ | `data-gl-scrub` without the module | `data-gl-scrub on <video.hero>: no module "scrub". Load modules/scrub.js next to umber.js...` |
2495
+ | a video or image on another domain without CORS | `<video.hero>: the video at https://... is on another domain that sends no CORS headers, so it can't become a texture and the DOM video shows. Serve it with Access-Control-Allow-Origin...` |
2496
+ | a shader that does not compile | The GLSL error with numbered source lines around it. |
2497
+ | a `clip-path: path()` (or `url()`, `shape()`) on a GL element or a parent | `<img.hero>: clip-path path("M 0 0 ...") on <div.mask> can't be drawn in GL, so its DOM shows. Use inset(), rect(), xywh(), circle(), ellipse() or polygon(), or add data-gl-clip="false" to draw it uncut.` |
2498
+ | a CSS mask on a parent of a GL element | `<div.card>: GL can't draw the CSS mask on <div.marquee>, so its DOM shows. Move the mask off the parents of GL elements, or add data-gl-clip="false" to draw it unmasked.` |
2499
+ | three or more rounded / shaped clips on one element | `<div.card>: cut by too many rounded or shaped parents (<div.a>, <div.b>, <div.c>), so its DOM shows. Make one of them a straight overflow: hidden...` |
2500
+ | a 3D tilt that turns part of an element behind the viewer | `<div.card>: part of it turns behind the viewer (3D transform on <div.tilt>), so its DOM shows until it turns back. Lower the angle or raise the perspective.` |
2501
+ | in WebKit browsers (Safari, iOS), a tilt under a `perspective` parent that also has `overflow` and `border-radius` (WebKit draws that tilt flat; seen in Safari 26.6) | `<div.card>: WebKit draws a tilt flat when its perspective parent (<div.stage>) also has overflow and border-radius, so its DOM shows. Put the perspective on an inner element, or round the corners with clip-path: inset(0 round <radius>).` |
2502
+ | `chunks/shapes.js` missing on your server, or so slow it takes more than 5 s | `<div.card>: it is cut, turned or tilted by CSS, and chunks/shapes.js failed to load (or: took more than 5 s to load), so its DOM shows. Serve chunks/shapes.js next to chunks/gl.js.` If it still arrives, GL draws those elements from then on. |
2503
+ | `chunks/glsl.js`, `chunks/instances.js`, `chunks/video.js`, `chunks/text.js`, `chunks/layers.js` or `chunks/fx.js` missing on your server, or so slow it takes more than 5 s | `chunks/video.js failed to load; GL videos and module elements show their DOM. (no answer in 5 s)` (for text: `chunks/text.js took more than 5 s to load; data-gl="text" stays normal DOM text.`) The elements waiting for it show their DOM, a reveal too (for fx.js: planes that read `uBackdrop`; groups draw their members straight to the canvas). If it still arrives, GL takes it from then on and draws the elements that waited. |
2504
+ | several GL elements facing you in one `preserve-3d` scene | `<div.face>: GL can't depth-sort several GL elements in one preserve-3d scene (<div.cube>), so their DOM shows. Add backface-visibility: hidden to faces that turn away, or use transform-style: flat.` |
2505
+ | `offset-path` on a GL element or a parent | `<div.card>: offset-path on <div.x> moves it along a path GL does not follow, so its DOM shows. Animate transform instead.` |
2506
+ | `zoom` on a parent of a turned element | `<div.card>: zoom on <div.x> scales it in a way GL can't follow together with its transforms, so its DOM shows. Use transform: scale() instead of zoom.` |
2507
+ | a box that doesn't match its transforms (seen almost edge-on; while it animates only when it lasts 3 frames) | `<div.card>: its on-screen box doesn't match the transforms on <div.x> (turned almost edge-on?), so its DOM shows until they agree again...` |
2508
+ | a `transform`, `perspective`, `contain` or `will-change` on `<body>` / `<html>`, a `filter` on `<body>` (or `zoom` on `<html>`) | `<body> has transform: matrix(...), which makes Umber's fixed canvas scroll or turn with the page, so GL is off and the DOM shows. Move the transform to a wrapper element inside <body>.` |
2509
+ | a three.js layer under a rotation | `<div.scene>: a three.js layer is drawn upright; GL can't turn or tilt a layer's own drawing. Turn the camera in your scene instead.` |
2510
+
2511
+ ### gl.inspect(el): why is this element (not) drawn?
2512
+
2513
+ ```js
2514
+ gl.inspect(".hero img"); // or an element; one inside a plane (its <img>) reports that plane
2515
+ // [umber] inspect <div.hero>: not drawn: it is off screen (at 0, 2400 px; the screen is 1280×800)
2516
+ const report = await gl.inspect(".hero img");
2517
+ ```
2518
+
2519
+ "On screen" means the visible screen (`innerWidth` × `innerHeight`), as for `plane.inView`. It is async (what it reads comes with `chunks/inspect.js`, fetched on the first call): it prints, and resolves with one report: `kind`, `status`, `drawn`, `why` (every reason it is not drawn, in words), `notes` (worth knowing but not stopping it: an unknown effect name, which it draws without), `source` (the image or video URL), `tier` (device tier, plus the scrub tier), `effects` with their options, `uniforms` with their values and `used` (does the compiled shader read it), `program`, `rect`, `inView`, `near`, `texture`, `modules`, and `clips`: every parent (or the element itself) that cuts it, as `{ el, by: "overflow" | "clip-path" | "clip" | "occlude", shape, how }`, where `how` is `"scissor"` (a straight clip, free), `"shader"` (rounded or shaped, per pixel), `"corners"` (a rounded parent hugging the image: its corners), `"pruned"` (it holds the whole element: cuts nothing; a `data-gl-occlude` panel: it misses the element this frame), `"ignored"` (that parent turns past the viewer right now) or `"uncut"` (a `data-gl-occlude` panel over it, with no clip slot free: GL draws over the panel there); and `geometry`: `{ transform: "none" | "2d" | "3d", size, corners, live }`, where `corners` is the quad GL draws (viewport px) and `live` says what measures it every frame right now (`"CSS transition on <div.card>, 0.32 s left"`, `"infinite CSS animation on <div.track>"`, `"scroll-driven CSS animation on <div.reveal>"`, `"data-gl-live"`, `"a sticky or fixed parent"`, `"live mode (a page change, gl.live())"`, or `null`). `why` also says when its back faces you (`backface-visibility: hidden`), when its clips hide it entirely (`it is entirely cut off by overflow: hidden on <div.slider>`) or when its DOM shows because of a clip GL can't draw. With GL off it says why (`GL is off for this visit: not a desktop device...`).
2520
+
2521
+ ### The debug module (`modules/debug.js`): HUD, outlines, markers
2522
+
2523
+ Never on the live site: add it while you build.
2524
+
2525
+ ```html
2526
+ <script src="https://umber.occluze.com/umber@0.2.1/modules/debug.js"></script> <!-- the HUD -->
2527
+ <script src="https://umber.occluze.com/umber@0.2.1/modules/debug.js" data-outlines data-markers></script> <!-- all three -->
2528
+ ```
2529
+ ```js
2530
+ import { Debug } from "@occluze/umber/debug";
2531
+ gl.use(Debug, { hud: true, outlines: true, markers: true });
2532
+ ```
2533
+
2534
+ `?umber-debug=hud,outlines,markers` in the URL picks the parts too (a bare `?umber-debug` also turns on debug notes in the console). `cost` adds the cost meter (below): `?umber-debug=hud,cost`, `gl.use(Debug, { cost: true })`.
2535
+
2536
+ - **HUD** (bottom left; click its title to fold it, Ctrl/Cmd + Shift + H hides it): frame time and fps with a graph of the last 60 frames the loop ran, renders vs skipped frames, draw calls, planes on screen / all, shader programs, textures (how many, their MB, and the render targets' MB once groups, passes or sims run) and uploads, canvas size, DPR and adaptive scale, and **busy**: why it keeps drawing (`live`: a page change or `gl.live()`, `scroll`, `tween`, `upload`, `video`, `shader:name`, `dom-watch:<section#hero>`: the site restyled that element, which holds a plane, on that frame...). A still page should say `nothing (sleeping)`, and `gl.info.busy` is `[]` once the loop sleeps. The **gpu** row is the GPU tier: its level (0 to 5), why (`rule: <the part of the GPU's name that matched>` for levels 0 and 1, `default`, or `url` for `?umber-gpu`) and the GPU's name; the canvas row says `cut` when a weak GPU's wide window lowered the DPR.
2537
+ - **Outlines:** a box on every plane exactly where GL draws it, labelled with its kind, effects and status. Green ready, amber loading, red gave up (the DOM shows); dashed when not drawn right now. A box that is off its element means the plane is off too. A purple dashed box marks each parent that cuts a plane (its overflow or clip-path box), where GL cuts it.
2538
+ - **Markers:** for each effect that plays on scroll, a fixed line where its `start` sits on the screen and a dashed tick on the element edge that has to reach it; for each scrubbed video, its start and end lines.
2539
+ - **Cost** (`cost: true`): what each effect stack costs per frame, as rows in the HUD, costliest first (`dissolve+grain: 0.42 cpu · 0.31 gpu ms`). Planes are grouped by their effects (or their shader, or their kind). `cpu` works on every GPU: frames are timed from the start of Umber's render until the GPU finished it, with every plane and with one group switched off for a few frames, in turn; the difference is that group's cost. `gpu` is a timer per draw, only where the browser exposes `EXT_disjoint_timer_query_webgl2` (desktop Chrome, Edge, Firefox); on Apple GPUs and phones (tile GPUs, which defer the drawing) read `cpu`. While on, the loop keeps drawing and each group blinks off for a few frames now and then: turn it on to compare effects, then off.
2540
+
2541
+ The panel and overlays never keep the loop awake (the cost meter does, while on). They go when the engine does (`gl.destroy()`).
2542
+
2543
+ ### Devtools hooks
2544
+
2545
+ - The canvas carries `data-gl-canvas` and `data-engine="umber <version>"`.
2546
+ - `window.__umber = { version, engine, modules }`: the running engine (`__umber.engine.info`, `__umber.engine.inspect(el)`) from the console, on any site.
2547
+ - `?umber-debug` turns on debug notes: GL tier, render scale changes, why GL is off.
2548
+ - `?umber=off` keeps every element on its DOM for this visit (`gl.reason` is `"disabled"`, no chunk loads): compare a page with and without GL.
2549
+ - `?umber-gpu=<level>` forces a GPU tier for this visit, to see a site as a weaker or stronger device would (nothing is stored): `0` to `5` as a desktop, `m0` to `m5` as a phone, or `low` / `mid` / `high`. Anything else is ignored with a warning.
2550
+
2551
+ ### Reporting to your own analytics
2552
+
2553
+ Two engine events say what a visitor got, for the site's own analytics (Umber sends nothing anywhere). Both also go to `document` (`umber:off`, `umber:fallback`, the payload in `event.detail`), so a tag manager can listen without `gl`.
2554
+
2555
+ ```js
2556
+ const gl = Umber.createGL();
2557
+ // GL is off for this visit: at the start (a device it skips, ?umber=off) or later (a page with data-gl-disable, too many WebGL context losses, an error inside a GL frame).
2558
+ gl.on("off", ({ reason }) => track("umber_off", { reason }));
2559
+ // One element shows its DOM instead: `reason` is the warning's words, or null when something failed (a picture or video that didn't load, a shader that didn't compile).
2560
+ gl.on("fallback", ({ el, reason }) => track("umber_fallback", { id: el.id, reason }));
2561
+ gl.ready.then((on) => on && track("umber_on", { gpu: gl.info.tier }));
2562
+ ```
2563
+
2564
+ `gl.reason` is one of the codes in `GLReason`. Send codes and short strings, never the element itself.
2565
+
2566
+ ### Turning it off from the site (a remote off switch)
2567
+
2568
+ `?umber=off` turns GL off for one visit. To turn it off for everyone without a release (a campaign page, a bad device), read your own flag before `createGL()` and pass `devices: false`: the API stays the same (`gl.drag`, `gl.track`, `gl.progress` keep working), every element keeps its DOM, and no GL chunk loads (`gl.attach()` views stay off too, whatever their own `devices`).
2569
+
2570
+ ```js
2571
+ const flags = await fetch("/flags.json").then((r) => r.json()).catch(() => ({})); // your own, cached briefly
2572
+ const gl = Umber.createGL(flags.umberOff ? { devices: false } : {});
2573
+ ```
2574
+
2575
+ ### GPU tiers
2576
+
2577
+ When GL starts, Umber gives the device a level from its GPU's name (`gl.info.gpu`: `level`, `tier`, `mobile`, `renderer`, `reason`, `maxTexture`, `textureBudget`, `wide`):
2578
+
2579
+ | level | band (`gl.info.tier`) | who | max DPR | largest texture | image memory |
2580
+ |---|---|---|---|---|---|
2581
+ | 0 | low | software renderers (no GPU) | 1 | 2048 | 96 MB |
2582
+ | 1 | low | old or weak GPUs (Intel(R) HD 2000 to 5xxx, Mali-4xx / T, Adreno (TM) 2xx to 5xx, PowerVR) | 1 | 2048 | 96 MB |
2583
+ | 2 | mid | phones | 1.5 | 2048 | 96 MB |
2584
+ | 3 | mid | strong phones: only with `?umber-gpu=m3` | 1.5 | 2048 | 96 MB |
2585
+ | 4 | high | desktops, every one Umber finds itself (an Apple M Pro, Max or Ultra, an RTX card: all 4, reason `default`) | 2 | 4096 | 192 MB |
2586
+ | 5 | high | strong desktops: only with `?umber-gpu=5` | 2 | 4096 | 192 MB |
2587
+
2588
+ - The max DPR is per band, so `createGL({ dpr: { high, mid, low } })` still sets it.
2589
+ - Safari only says "Apple GPU": a Mac gets 4, an iPhone or iPad with a touch screen under 820 px gets 2.
2590
+ - A desktop at level 0 in a window wider than 1400 CSS px, or at level 1 wider than 1600, draws at DPR 0.8 from the first frame (a `[min, max]` dpr option's min still holds). Adaptive resolution still lowers it further when the GPU can't keep up.
2591
+ - Levels 3 and 5 draw exactly like 2 and 4 today, so Umber does not look for strong GPUs by name: a device lands on 0, 1, 2 or 4, and 3 and 5 are there for `?umber-gpu`.
2592
+ - Levels 0 and 1 are exactly the rule Umber always had (on the GPU name as the browser gives it), so the table changes no device's band or DPR.
2593
+ - The table ships inside `chunks/gl.js` (and `chunks/views.js`): no extra download.
2594
+ - **Frame-by-frame capture.** When Kovo (Occluze's recorder) exports a site's video frame by frame, it defines `window.occluzeCapture` before the page's scripts. Umber then draws at the screen's full `devicePixelRatio` (no tier cap, no pixel budget, no wide-window cut: only the GPU's own size limit, with a warning when it cuts), never lowers the resolution (adaptive is off), and holds each frame until what it shows is drawn: textures, GL text, a video's first frame, a scrub frame, a lazy chunk. A normal visitor never has that object, so none of this applies to them (`chunks/capture.js` is never downloaded). The full contract: `docs/kovo.md`.
2595
+
2596
+ ---
2597
+
2598
+ ## Loading the engine (hosting and versions)
2599
+
2600
+ Every site loads the engine from an **exact version**:
2601
+
2602
+ ```
2603
+ https://umber.occluze.com/umber@0.2.1/
2604
+ umber.js window.Umber (createGL, math, use). Small; loads chunks/gl.js lazily
2605
+ umber.mjs the same API as an ES module (the npm package's entry)
2606
+ umber.css the canvas host and the "hide once drawn" rules
2607
+ chunks/gl.js the GL runtime: downloaded once the device passes and the page has [data-gl], or on the first gl.renderer(), gl.view(), gl.target(), gl.snapshot(), gl.sim(), gl.flow(), gl.placeholder(), gl.preload() or gl.warm()
2608
+ chunks/shapes.js clips, turns and tilts: downloaded only when a GL element is cut, turned or tilted by CSS or by an animation
2609
+ chunks/text.js GL text: downloaded only when the page has data-gl="text" (nothing to add for it)
2610
+ chunks/layers.js three.js on Umber's canvas: downloaded on the first data-gl="layer", gl.renderer() or gl.view()
2611
+ chunks/morph.js data-gl-id flights: downloaded on the first data-gl-id
2612
+ chunks/video.js GL videos and module frames: downloaded on the first GL <video> or module element
2613
+ chunks/glsl.js gl.chunk() includes and helper renaming: downloaded on the first effect stack that needs them
2614
+ chunks/restore.js getting a lost WebGL context back: downloaded only when the browser returns it
2615
+ chunks/inspect.js gl.inspect() and the words of rare warnings: downloaded on the first call or warning only
2616
+ chunks/views.js the gl.attach() runtime: downloaded on the first gl.attach() only
2617
+ chunks/fx.js render targets (gl.target, gl.snapshot, uBackdrop, data-gl-pass, gl.leave): downloaded on the first of them
2618
+ chunks/sim.js gl.sim, gl.flow, gl.brush, uFlow: downloaded by chunks/fx.js on the first of them
2619
+ chunks/warm.js gl.preload(), gl.warm(), gl.placeholder(), data-gl-placeholder, hover prefetch: downloaded on the first of them
2620
+ chunks/flip.js gl.flip(), plane.lift()/land(), picture swaps (uPrev): downloaded on the first of them
2621
+ chunks/instances.js data-gl-instances: downloaded on the first plane with instances
2622
+ chunks/covers.js the check when a data-gl-id flight lands: downloaded by chunks/morph.js on the first landing
2623
+ modules/scrub.js scroll-scrubbed video (script; registers itself) modules/scrub.mjs (ES module)
2624
+ modules/debug.js HUD, outlines, markers, cost (script; registers itself) modules/debug.mjs (ES module)
2625
+ modules/input.js gl.drag, velocityOf, trail, press, step, textures (script; registers itself) modules/input.mjs (ES module)
2626
+ modules/handoff.js data-gl-id flights across full page loads, View Transitions, cover pass (script; registers itself) modules/handoff.mjs (ES module)
2627
+ modules/scroll.js smooth scrolling on Umber's own loop, gl.scroll (script; registers itself) modules/scroll.mjs (ES module)
2628
+ manifest.json the version and its file list
2629
+ ```
2630
+
2631
+ Rules:
2632
+
2633
+ - **Production sites always use an exact version**: `umber@0.2.1`. Those files never change.
2634
+ - **Every site uses exactly these URLs.** There is nothing per site to add.
2635
+ - **Don't set `referrerpolicy="no-referrer"` on the engine tags** (or a site-wide `no-referrer` policy). The CDN checks which site is asking; without the `Referer` the request is refused.
2636
+ - **Staging may use a channel:** `umber@0` is the newest 0.x.x, `umber@0.1` the newest 0.1.x. Channels redirect to an exact version and move as soon as a release is deployed. **Never `umber@latest`** on a real site. Pre-releases (like `0.2.0-beta.1`) never get a channel: load them by their exact URL.
2637
+ - **One version everywhere.** `umber.css`, `umber.js` and every `modules/*.js` must come from the same `umber@x.y.z/` folder. Never load `chunks/*.js` yourself: the engine loads them from its own folder.
2638
+ - **Don't add a `v`:** `umber@0.2.1`, not `umber@v0.2.1`.
2639
+ - **If GL doesn't start on a new domain** (`gl.reason` is `"unlicensed"`, and the console says the domain isn't on an Umber licence): the developer lists the domain under Umber in their occluze dashboard (occluze.com). Site code can't fix it. `localhost` always works. The same licence covers `gl.scroll` and `gl.router`: on a domain that isn't listed they stay native (the browser's scrolling, normal navigation). `await gl.licensed()` is the answer (`gl.licence` once it is in).
2640
+ - **npm** (bundled sites): the public package `@occluze/umber` has the same files, with `exports` for `.`, `./scrub`, `./debug`, `./input`, `./handoff`, `./scroll`, `./umber.css`, `./umber.js` and `./types`. Its GL chunks still load from the CDN folder of the same version; `createGL({ base })` or `window.UmberConfig = { base }` points them elsewhere. Setup: `docs/npm.md`.
2641
+
2642
+ To see which versions exist, open `https://umber.occluze.com/versions/` or `/versions.json`.
2643
+
2644
+ **What's breaking:** removing or renaming any attribute (`data-gl-*`), `createGL()` option, engine or plane method, GLSL slot, input or helper, CSS hook (`has-gl`, `data-gl-status`), or event; or changing a visible default. Deprecated names keep working (with one warning) until a later breaking release.
2645
+
2646
+ ---
2647
+
2648
+ ## Before you finish (checklist for AI assistants)
2649
+
2650
+ Go through this list before you hand over code for a site that uses Umber. Every line is a mistake that is easy to make and hard to see.
2651
+
2652
+ 1. **Tags and versions:** `umber.css` in `<head>`, `umber.js` before the code that calls `Umber.createGL()`, modules from the **same** `umber@x.y.z/` folder. Use the URLs from the setup above; never invent a version, never `umber@latest`, never load `chunks/*.js`.
2653
+ 2. **One engine:** `createGL()` once per visit, in code that runs once, never inside a Barba hook or a component's init. A component makes its Umber objects inside `gl.scope()` and calls `scope.revert()` on unmount.
2654
+ 3. **No Umber code per page:** no `gl.scan()` in router hooks and no cleanup on page leave; planes come and go with the DOM, with any router. `gl.transition()` (or `gl.hold()` / `gl.live()` / `gl.morph.*`) only when you want them, and every `gl.transition()` gets its `end()`.
2655
+ 4. **Libraries are yours:** set up Lenis and your router (Barba, Swup, Turbo...) the way their docs show, and pass the Lenis instance as `createGL({ scroll: lenis })` (or load `modules/scroll.js` instead of Lenis, never both). Umber never creates, drives or configures them, and never needs GSAP.
2656
+ 5. **Every effect is defined:** each name in `data-gl-effect` has a `gl.effect()` written for this site (Umber ships none). Options and uniforms use the names the effect declares (`data-gl-dissolve-scale` -> `uDissolveScale`).
2657
+ 6. **The page works without GL:** GL runs on every device unless the site turns some off (`devices: "desktop"` / `data-gl-devices="desktop"`, or a media query: `media` / `data-gl-media`), and is off for Save-Data (or a 2G connection), reduced-motion "off", no WebGL2 and High Contrast. Never hide real content for an effect; always write `gl.plane(el)?.`.
2658
+ 7. **Layering:** text or buttons over a GL image get `data-gl-above`; a fixed nav, menus and overlays get a z-index above 1. A section with `z-index` 1 or more and a background hides the GL inside it: `gl.inspect(el)` says so, and Umber warns only on pages that load `chunks/shapes.js` (see Layering). Cross-origin images and videos need CORS headers.
2659
+ 8. **gl.leave() and gl.flip() are GL only:** `gl.leave()` lays out the old page's GL, not its DOM; `gl.flip()` moves GL copies while the DOM jumps. Pair them with the router's or GSAP's own DOM animation, never both on one element.
2660
+ 9. **Test it:** one page change and back, a fast double click on a link, a narrow window, and the console: no `[umber]` warnings. `gl.inspect(el)` explains any element that is not drawn.