@occluze/umber 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +126 -50
  3. package/THIRD-PARTY-NOTICES.md +33 -0
  4. package/dist/chunks/badge.js +2 -0
  5. package/dist/chunks/basis.js +2 -0
  6. package/dist/chunks/basis_transcoder.js +2 -0
  7. package/dist/chunks/basis_transcoder.wasm +0 -0
  8. package/dist/chunks/batches.js +2 -0
  9. package/dist/chunks/capture.js +2 -2
  10. package/dist/chunks/covers.js +2 -2
  11. package/dist/chunks/curves.js +2 -0
  12. package/dist/chunks/flip.js +2 -2
  13. package/dist/chunks/fx.js +2 -102
  14. package/dist/chunks/gl.js +2 -180
  15. package/dist/chunks/glsl.js +2 -239
  16. package/dist/chunks/glyphs.js +2 -0
  17. package/dist/chunks/inspect.js +2 -6
  18. package/dist/chunks/instances.js +2 -93
  19. package/dist/chunks/layers.js +2 -21
  20. package/dist/chunks/licence.js +2 -2
  21. package/dist/chunks/morph.js +2 -2
  22. package/dist/chunks/pace.js +2 -0
  23. package/dist/chunks/patch.js +2 -0
  24. package/dist/chunks/prepared.js +2 -0
  25. package/dist/chunks/profiler.js +2 -0
  26. package/dist/chunks/recheck.js +2 -0
  27. package/dist/chunks/resize.js +2 -0
  28. package/dist/chunks/restore.js +2 -2
  29. package/dist/chunks/shapes.js +2 -2
  30. package/dist/chunks/sim.js +2 -22
  31. package/dist/chunks/text.js +2 -52
  32. package/dist/chunks/video.js +2 -2
  33. package/dist/chunks/vocabulary.js +2 -0
  34. package/dist/chunks/warm.js +2 -2
  35. package/dist/modules/debug.js +2 -36
  36. package/dist/modules/debug.mjs +2 -36
  37. package/dist/modules/handoff.js +2 -2
  38. package/dist/modules/handoff.mjs +2 -2
  39. package/dist/modules/input.js +2 -2
  40. package/dist/modules/input.mjs +2 -2
  41. package/dist/modules/scrollfx.js +2 -0
  42. package/dist/modules/scrollfx.mjs +2 -0
  43. package/dist/modules/scrub.js +2 -8
  44. package/dist/modules/scrub.mjs +2 -8
  45. package/dist/modules/three.js +2 -0
  46. package/dist/modules/three.mjs +2 -0
  47. package/dist/node/assets.mjs +11 -0
  48. package/dist/node/astro.mjs +55 -0
  49. package/dist/node/cli.mjs +162 -0
  50. package/dist/node/shared-P6KINBNR.mjs +2113 -0
  51. package/dist/node/shared-VQKZUUXF.mjs +289 -0
  52. package/dist/node/vite.mjs +14 -0
  53. package/dist/prepared.mjs +2 -0
  54. package/dist/umber.css +2 -2
  55. package/dist/umber.js +2 -2
  56. package/dist/umber.mjs +2 -2
  57. package/docs/AI-quick.md +104 -86
  58. package/docs/AI.md +2299 -1692
  59. package/docs/npm.md +40 -32
  60. package/package.json +176 -24
  61. package/types/assets.d.ts +192 -0
  62. package/types/astro.d.ts +40 -0
  63. package/types/debug.d.ts +18 -17
  64. package/types/esm.d.ts +13 -17
  65. package/types/global.d.ts +17 -0
  66. package/types/handoff.d.ts +26 -25
  67. package/types/input.d.ts +63 -55
  68. package/types/loop.d.ts +87 -0
  69. package/types/module.d.ts +106 -0
  70. package/types/scrollfx.d.ts +44 -0
  71. package/types/scrub.d.ts +33 -32
  72. package/types/three.d.ts +251 -0
  73. package/types/umber.d.ts +705 -432
  74. package/types/vite.d.ts +33 -0
  75. package/dist/chunks/views.js +0 -2
  76. package/dist/modules/router-swap.js +0 -13
  77. package/dist/modules/router.js +0 -2
  78. package/dist/modules/router.mjs +0 -2
  79. package/dist/modules/scroll.js +0 -2
  80. package/dist/modules/scroll.mjs +0 -2
  81. package/types/router.d.ts +0 -181
  82. package/types/scroll.d.ts +0 -132
package/types/umber.d.ts CHANGED
@@ -1,67 +1,79 @@
1
- // -----------------------------------------
2
- // UMBER: PUBLIC TYPES FOR SITE CODE
3
- // -----------------------------------------
4
-
5
- // Editor autocomplete and type checks for site code (VS Code, Astro, Vite, TS or
6
- // checkJs projects). Nothing here runs.
7
- //
8
- // <script src=".../umber@x.y.z/umber.js"> -> window.Umber: { version, createGL, math, use }
9
- // import { createGL } from "@occluze/umber" (types/esm.d.ts)
10
- //
11
- // For the <script> tag: copy this file into your project (e.g. src/types/umber.d.ts) and
12
- // list it in tsconfig/jsconfig "include", or add /// <reference path="./types/umber.d.ts" />.
13
- //
14
- // Hand-written on purpose: one readable file, also the most compact exact API reference
15
- // to paste into an AI assistant. Keep it in step with src/types.ts and src/core/create.ts
16
- // (test/types.test.ts checks the members of Umber and of the engine).
17
- //
18
- // ATTRIBUTE CHEAT SHEET (the DOM is the API)
19
- //
20
- // data-gl="image | video | text | shader | layer | group" make this element a GPU plane
21
- // (group: draws the GL planes inside it as one, through
22
- // its own data-gl-effect; docs/ai/groups.md)
23
- // data-gl-pass="grade grain" effects run over the whole GL frame (on <html> or <body>)
24
- // or over one group; per effect -blend, -opacity, -scale
25
- // data-gl-effect="ripple tint" effects (defined with gl.effect), applied in order
26
- // data-gl-<effect>-<option>="1.2" an effect option (also --gl-<effect>-<option> in CSS)
27
- // data-gl-<effect>-trigger auto (default) | scroll | load | manual | hover, for effects with `play`
28
- // data-gl-<effect>-delay / -duration / -ease / -start the play's timing ("top 90%")
29
- // data-gl-shader="name" with data-gl="shader": the gl.shader() it draws
30
- // data-gl-layer="name" with data-gl="layer": the gl.layer() it runs
31
- // data-gl-src="url" another image than the <img> inside
32
- // data-gl-fit="cover|contain|fill" object-fit for the texture
33
- // data-gl-live measure every frame (sticky, fixed or transformed parents)
34
- // data-gl-clip="false" draw it without its parents' clips (overflow, clip-path, masks)
35
- // data-gl-wrap="x | y" on a track: its planes wrap around it (an endless gallery)
36
- // data-gl-order="1" draw order
37
- // data-gl-instances="64" drawn many times in one call: "64", "tiles 24x16",
38
- // "chars" | "words" | "lines" (GL text), "echo 6", "ink 3000"
39
- // data-gl-placeholder="UF…" a blurred preview until the image loads (chunks/warm.js;
40
- // make it with gl.placeholder(src))
41
- // data-gl-id="hero" the same id on two pages: the image flies across (morph),
42
- // with any router (gl.transition() makes it tighter)
43
- // data-gl-morph-duration="1" / -ease on the element you go to: the flight's timing
44
- // (also --gl-morph-duration / --gl-morph-ease in CSS)
45
- // data-gl-shader-<option> / data-gl-layer-<option> a gl.shader() / gl.layer() option
46
- // data-gl-above a DOM element that must sit on top of the canvas
47
- // data-gl-disable (on <body>) GL off for this page
48
- // data-gl-host where the canvas goes (else Umber makes one)
49
- // data-gl-video-autopause="false" keep a muted loop video playing off screen
50
- // data-gl-scrub (+ -start, -end, -track, -smooth, -source, -frames...) scroll-scrubbed
51
- // video: needs the scrub module (types/scrub.d.ts)
52
- // Modules (same version as umber.js): modules/scrub.js (types/scrub.d.ts) and
53
- // modules/debug.js, the HUD, outlines and markers (types/debug.d.ts).
54
- // gl.inspect(el) prints why an element is (not) drawn.
55
- // Events also go to document: umber:ready (detail = the engine), umber:lost,
56
- // umber:restored, umber:destroy.
57
- // From JS: gl.add(el, { type, effects, options }) writes these attributes for you.
58
- // Written by Umber: html.has-gl, data-gl-status="loading|ready|error", data-gl-media,
59
- // data-gl-play, data-gl-morphing, data-gl-canvas on the canvas, and
60
- // data-gl-view="loading|ready|off|error|lost" on gl.attach() / gl.view() elements.
1
+ /**
2
+ * Umber's public types for site code.
3
+ *
4
+ * Editor autocomplete and type checks for site code (VS Code, Astro, Vite, TS or
5
+ * checkJs projects). Nothing here runs.
6
+ *
7
+ * <script src=".../umber@x.y.z/umber.js"> -> window.Umber: { version, createUmber, math, use }
8
+ * import { createUmber } from "@occluze/umber" (types/esm.d.ts)
9
+ *
10
+ * For the <script> tag: copy this file and global.d.ts (window.Umber and the global
11
+ * `Umber`) into your project (e.g. src/types/) and list both in tsconfig/jsconfig
12
+ * "include", or add /// <reference path="./types/global.d.ts" />. With the npm package
13
+ * installed: /// <reference types="@occluze/umber/global" />. An `import` from
14
+ * "@occluze/umber" gets no window.Umber: the npm build never sets it.
15
+ *
16
+ * Hand-written on purpose: one readable file, also the most compact exact API reference
17
+ * to paste into an AI assistant. Keep it in step with src/types.ts and src/core/create.ts
18
+ * (test/types/types.test.ts checks the members of Umber and of the engine).
19
+ *
20
+ * Attribute cheat sheet (the DOM is the API). An element says what it is, how it behaves,
21
+ * and what it's set to: data-umber="<kind> <behaviours>", then one attribute per setting.
22
+ *
23
+ * kinds, one: image | video | text | shader | layer | model | group (a GPU plane)
24
+ * scroller (the element that scrolls)
25
+ * behaviours: above, pin, horizontal, inview (scrollfx)
26
+ * with a value, the long form only: data-umber-pin="80px", data-umber-inview="shown"
27
+ *
28
+ * data-umber="group" draws the GL planes inside it as one, through its
29
+ * own data-umber-effect (docs/ai/groups.md)
30
+ * data-umber-pass="grade grain" effects run over the whole GL frame (on <html> or <body>)
31
+ * or over one group; per effect -blend, -opacity, -scale
32
+ * data-umber-effect="ripple tint" effects (defined with umber.effect), applied in order
33
+ * data-umber-<effect>-<option>="1.2" an effect option (also --umber-<effect>-<option> in CSS)
34
+ * data-umber-<effect>-trigger auto (default) | scroll | load | manual | hover, for effects with `play`
35
+ * data-umber-<effect>-delay / -duration / -ease / -start the play's timing ("top 90%")
36
+ * data-umber-<effect>-repeat "reverse" | "true": plays again
37
+ * data-umber-<effect>-hide="false" a play that does not hide its element while GL loads
38
+ * data-umber-shader="name" with data-umber="shader": the umber.shader() it draws
39
+ * data-umber-layer="name" with data-umber="layer": the umber.layer() it runs
40
+ * data-umber-src="url" another image than the <img> inside
41
+ * data-umber-fit="cover|contain|fill" object-fit for the texture
42
+ * data-umber-live measure every frame (sticky, fixed or transformed parents)
43
+ * data-umber-clip="false" draw it without its parents' clips (overflow, clip-path, masks)
44
+ * data-umber-wrap="x | y" on a track: its planes wrap around it (an endless gallery)
45
+ * data-umber-order="1" draw order
46
+ * data-umber-instances="64" drawn many times in one call: "64", "tiles 24x16",
47
+ * "chars" | "words" | "lines" (GL text), "echo 6", "ink 3000",
48
+ * "points 20000"
49
+ * data-umber-placeholder="UF…" a blurred preview until the image loads (chunks/warm.js;
50
+ * make it with umber.placeholder(src))
51
+ * data-umber-id="hero" the same id on two pages: the image flies across (morph),
52
+ * with any router (umber.transition() makes it tighter)
53
+ * data-umber-morph-duration="1" / -ease on the element you go to: the flight's timing
54
+ * (also --umber-morph-duration / --umber-morph-ease in CSS)
55
+ * data-umber-shader-<option> / data-umber-layer-<option> a umber.shader() / umber.layer() option
56
+ * data-umber="above" a DOM element that must sit on top of the canvas
57
+ * data-umber-disable (on <body>) GL off for this page
58
+ * data-umber-host where the canvas goes (else Umber makes one)
59
+ * data-umber-video-autopause="false" keep a muted loop video playing off screen
60
+ * data-umber-scrub (+ -start, -end, -track, -smooth, -source, -frames...) scroll-scrubbed
61
+ * video: needs the scrub module (types/scrub.d.ts)
62
+ * Modules (same version as umber.js): modules/scrub.js (types/scrub.d.ts) and
63
+ * modules/debug.js, the HUD, outlines and markers (types/debug.d.ts).
64
+ * umber.inspect(el) prints why an element is (not) drawn.
65
+ * Events also go to document (payload in event.detail): umber:ready (the engine), umber:lost,
66
+ * umber:restored, umber:destroy, umber:added (the roots that entered the page),
67
+ * umber:off ({ reason }) and umber:fallback ({ el, reason }).
68
+ * From JS: umber.add(el, { type, effects, options }) writes these attributes for you.
69
+ * Written by Umber: html.has-umber, data-umber-status="loading|ready|error", data-umber-media,
70
+ * data-umber-play, data-umber-morphing, data-umber-canvas on the canvas, and
71
+ * data-umber-view="loading|ready|off|error|lost" on umber.view() elements.
72
+ */
61
73
 
62
74
  /**
63
75
  * The next page, as a router hands it over: its HTML, a parsed Document, its container
64
- * (or a fragment), Barba's cached { html }, or a promise of any of them. "" or null: not
76
+ * (or a fragment), a router's cached { html }, or a promise of any of them. "" or null: not
65
77
  * known yet.
66
78
  */
67
79
  export type NextPage =
@@ -70,28 +82,30 @@ export type NextPage =
70
82
  | { html?: string }
71
83
  | null
72
84
  | undefined
73
- | PromiseLike<string | ParentNode | { html?: string } | null | undefined | void>;
85
+ | PromiseLike<string | ParentNode | { html?: string } | null | undefined>;
74
86
 
75
- /** A plain { value } anyone can animate (GSAP, Motion, your own code) or read. */
76
- export interface Signal<T = number> {
77
- value: T;
78
- }
79
-
80
- export interface LenisLike {
81
- animatedScroll?: number;
82
- scroll?: number;
83
- velocity?: number;
84
- isHorizontal?: boolean;
85
- options?: { wrapper?: Window | Element; orientation?: string };
86
- on(event: "scroll", fn: (...args: any[]) => void): unknown;
87
- off?(event: "scroll", fn: (...args: any[]) => void): unknown;
87
+ /** umber.transition()'s second argument: what the site knows about the page change. */
88
+ export interface TransitionOptions {
89
+ /**
90
+ * The container that is leaving, while the next page is in the document with it. From
91
+ * the call that names it until end(), GL draws nothing of it and its elements show their
92
+ * DOM: when the new page's DOM lies over the old page's, the old page's GL is no longer
93
+ * drawn over the new page. Give it in the first call, or in a later one at the moment
94
+ * the old page should hand over (a second call adds to the change that runs).
95
+ */
96
+ leaving?: Element | null;
97
+ /**
98
+ * How long the change may run with no end(), in seconds, before Umber ends it with a
99
+ * warning. For a site whose page changes take longer than the default. Read in the call
100
+ * that starts the change.
101
+ * @default 8
102
+ */
103
+ timeout?: number;
88
104
  }
89
105
 
90
- export interface ScrollObject {
91
- x?: number | (() => number);
92
- y?: number | (() => number);
93
- /** px per frame, like Lenis. Omit it to let Umber work it out from the position. */
94
- velocity?: number | (() => number);
106
+ /** A plain { value } anyone can animate (an animation library, your own code) or read. */
107
+ export interface Signal<T = number> {
108
+ value: T;
95
109
  }
96
110
 
97
111
  export interface Env {
@@ -104,47 +118,57 @@ export interface Env {
104
118
  readonly designer: boolean;
105
119
  }
106
120
 
107
- export interface GLOptions {
121
+ export interface UmberOptions {
122
+ /** Your account's public key, from your occluze dashboard. Also data-umber-key on the umber.js tag. */
123
+ key?: string;
108
124
  /**
109
- * Where Umber reads scroll from, read-only: it never creates, drives or configures it.
110
- * The default also follows <body> when it is the page's scroller (html { overflow: hidden }).
125
+ * What scrolls, when it is not the window: the element whose own scroll position moves
126
+ * (also data-umber="scroller" on that element). Read-only: Umber never creates, drives or
127
+ * configures a scroller, and a smooth scroller needs no option, since Umber reads where it
128
+ * puts the page. The default also follows <body> when it is the page's scroller
129
+ * (html { overflow: hidden }).
111
130
  * @default window
112
- * @example createGL({ scroll: lenis }) // your Lenis instance
113
- * @example createGL({ scroll: document.querySelector(".scroller") })
114
- * @example createGL({ scroll: { y: () => myScroll.y } }) // anything else
115
- */
116
- scroll?: Window | Element | LenisLike | ScrollObject | null;
117
- /**
118
- * "auto": Umber runs its own requestAnimationFrame loop, which sleeps when nothing moves.
119
- * false: nothing runs until you call gl.render(time) from your own loop.
120
- * @default "auto"
121
- * @example createGL({ loop: false }); gsap.ticker.add((t) => gl.render(t * 1000));
131
+ * @example createUmber({ scroll: document.querySelector(".scroller") })
132
+ */
133
+ scroll?: Window | Element | null;
134
+ /**
135
+ * One clock for the whole page: the page's own requestAnimationFrame loops (a smooth
136
+ * scroller, an animation library's ticker, a 3D renderer, minified code) run inside Umber's
137
+ * frame, one requestAnimationFrame per frame: the page's loops first, then Umber reads the
138
+ * page and draws. Any library fits that asks the page's requestAnimationFrame for its
139
+ * frames after the patch: none is known by name. The loop still sleeps when nothing asks
140
+ * for frames, and while only the page's loops ask, Umber's own part of the frame rests.
141
+ * Best without code: data-umber-patch on umber.js's script tag, placed before the other
142
+ * libraries' tags (patched as the script runs, so every loop started after it is caught).
143
+ * @default false
144
+ * @example <script src="umber.js" data-umber-patch></script>
145
+ * @example createUmber({ patch: true })
122
146
  */
123
- loop?: "auto" | false;
147
+ patch?: boolean;
124
148
  /**
125
149
  * Which devices draw DOM planes in GL (the rest keep the plain DOM, and nothing downloads).
126
150
  * "desktop" = hover + fine pointer + at least 768 px wide. Anything else is "desktop", with a warning.
127
151
  * @default "all"
128
- * @example createGL({ devices: "desktop" })
129
- * @example createGL({ devices: (env) => !env.isTouch })
152
+ * @example createUmber({ devices: "desktop" })
153
+ * @example createUmber({ devices: (env) => !env.isTouch })
130
154
  */
131
155
  devices?: "all" | "desktop" | false | ((env: Env) => boolean);
132
156
  /**
133
- * Effects only where this CSS media query matches, read when the page loads. Without code: data-gl-media on <body>.
134
- * @example createGL({ media: "(min-width: 900px)" }) // off in narrower windows
135
- * @example createGL({ media: "(min-width: 600px)" }) // off on phones
157
+ * Effects only where this CSS media query matches, read when the page loads. Without code: data-umber-media on <body>.
158
+ * @example createUmber({ media: "(min-width: 900px)" }) // off in narrower windows
159
+ * @example createUmber({ media: "(min-width: 600px)" }) // off on phones
136
160
  */
137
161
  media?: string;
138
162
  /**
139
163
  * Device pixel ratio: a max, [min, max], or a max per device tier.
140
164
  * @default { high: 2, mid: 1.5, low: 1 }
141
- * @example createGL({ dpr: [1, 1.5] })
165
+ * @example createUmber({ dpr: [1, 1.5] })
142
166
  */
143
167
  dpr?: number | [number, number] | { high?: number; mid?: number; low?: number };
144
168
  /**
145
169
  * Max canvas pixels (width × height × dpr²); the DPR drops to stay under it.
146
170
  * @default 12e6
147
- * @example createGL({ pixelBudget: 8e6 })
171
+ * @example createUmber({ pixelBudget: 8e6 })
148
172
  */
149
173
  pixelBudget?: number;
150
174
  /**
@@ -164,6 +188,12 @@ export interface GLOptions {
164
188
  * @default true
165
189
  */
166
190
  respectSaveData?: boolean;
191
+ /**
192
+ * Run where WebGL draws on the processor (SwiftShader, llvmpipe, Microsoft Basic Render: no usable GPU), where every
193
+ * frame costs the page its smoothness. Also `data-umber-software` on `<html>` or `<body>`. Off, `umber.reason` is "software".
194
+ * @default false
195
+ */
196
+ software?: boolean;
167
197
  /**
168
198
  * Run inside the Webflow Designer / Editor too (normally the DOM shows there).
169
199
  * @default false
@@ -171,8 +201,8 @@ export interface GLOptions {
171
201
  designer?: boolean;
172
202
  /**
173
203
  * The element the canvas goes in: an element or a selector.
174
- * @default [data-gl-host], or a fixed full-screen host Umber makes as the first child of <body> (next to it when <body> has a zoom)
175
- * @example createGL({ host: ".gl-host" })
204
+ * @default [data-umber-host], or a fixed full-screen host Umber makes as the first child of <body> (next to it when <body> has a zoom)
205
+ * @example createUmber({ host: ".gl-host" })
176
206
  */
177
207
  host?: string | HTMLElement;
178
208
  /**
@@ -187,41 +217,40 @@ export interface GLOptions {
187
217
  zIndex?: number;
188
218
  /**
189
219
  * A selector <html> matches while your router changes the page: meanwhile Umber acts as
190
- * inside gl.transition() (plays held, planes measured every frame, data-gl-id images
220
+ * inside umber.transition() (plays held, planes measured every frame, data-umber-id images
191
221
  * noted), with no hook to write. Off by default (a flag a site forgets to clear would
192
222
  * keep Umber measuring); it ends by itself after 8 s and starts again only once <html>
193
223
  * stopped matching in between.
194
- * @example createGL({ busy: "html.is-changing" }) // Swup
195
- * @example createGL({ busy: 'html[aria-busy="true"]' }) // Turbo
196
- * @example createGL({ busy: "html[data-astro-transition]" }) // Astro's client router
224
+ * @example createUmber({ busy: "html.is-changing" }) // a class the router sets
225
+ * @example createUmber({ busy: 'html[aria-busy="true"]' }) // an attribute it sets
197
226
  */
198
227
  busy?: string;
199
228
  /**
200
- * The folder the engine's chunks (chunks/gl.js, chunks/shapes.js, chunks/text.js, chunks/layers.js, chunks/morph.js, chunks/video.js, chunks/views.js) load from.
229
+ * The folder the engine's chunks (chunks/gl.js and the rest) load from.
201
230
  * @default the folder umber.js came from (npm: this version's CDN folder, or window.UmberConfig.base)
202
- * @example createGL({ base: "/vendor/umber/" })
231
+ * @example createUmber({ base: "/vendor/umber/" })
203
232
  */
204
233
  base?: string;
205
234
  /**
206
235
  * true: debug notes in the console (also ?umber-debug in the URL). An object also sets
207
236
  * what the debug module shows, once it is loaded (modules/debug.js).
208
237
  * @default false
209
- * @example createGL({ debug: true })
210
- * @example createGL({ modules: [Debug], debug: { outlines: true, markers: true } })
238
+ * @example createUmber({ debug: true })
239
+ * @example createUmber({ modules: [Debug], debug: { outlines: true, markers: true } })
211
240
  */
212
241
  debug?: boolean | DebugOptions;
213
242
  /**
214
243
  * false silences warnings. Errors (a shader that does not compile, a callback that threw)
215
244
  * always show.
216
- * @default true
245
+ * @default true on localhost and with debug on, false on a live site
217
246
  */
218
247
  warnings?: boolean;
219
248
  /**
220
- * Optional modules from the start, as gl.use() would take them.
221
- * @example createGL({ modules: [Scrub] }) // import { Scrub } from "@occluze/umber/scrub"
222
- * @example createGL({ modules: [[Scrub, { cacheMB: 64 }]] })
249
+ * Optional modules from the start, as umber.use() would take them.
250
+ * @example createUmber({ modules: [Scrub] }) // import { Scrub } from "@occluze/umber/scrub"
251
+ * @example createUmber({ modules: [[Scrub, { cacheMB: 64 }]] })
223
252
  */
224
- modules?: Array<UmberModule | [UmberModule, Record<string, unknown>]>;
253
+ modules?: (UmberModule | [UmberModule, Record<string, unknown>])[];
225
254
  }
226
255
 
227
256
  /** What the debug module (modules/debug.js) shows. */
@@ -240,9 +269,11 @@ export interface DebugOptions {
240
269
  * @default false
241
270
  */
242
271
  cost?: boolean;
272
+ /** The frame callbacks' costs against the frame's budget (umber.loop.profile(), chunks/profiler.js). ?umber-debug=profiler. @default false */
273
+ profiler?: boolean;
243
274
  }
244
275
 
245
- /** gl.inspect(el): one plane, and every reason it is not drawn on the visible screen right now. */
276
+ /** umber.inspect(el): one plane, and every reason it is not drawn on the visible screen right now. */
246
277
  export interface InspectReport {
247
278
  el: Element;
248
279
  kind: "image" | "video" | "shader" | "layer" | "text" | "group" | null;
@@ -257,7 +288,7 @@ export interface InspectReport {
257
288
  source?: string;
258
289
  /** The device tier ("high" | "mid" | "low"), plus the scrub tier on scrubbed video. */
259
290
  tier?: string;
260
- effects?: Array<{ name: string; options: Record<string, unknown> }>;
291
+ effects?: { name: string; options: Record<string, unknown> }[];
261
292
  /** used: the compiled shader reads it (null while it compiles). */
262
293
  uniforms?: Record<string, { value: unknown; used: boolean | null }>;
263
294
  program?: { key: string; ready: boolean } | null;
@@ -270,10 +301,15 @@ export interface InspectReport {
270
301
  * Every parent (or the element itself) that cuts it, and how GL draws the cut: "scissor"
271
302
  * (straight: free), "shader" (rounded, shaped or turned: per pixel), "corners" (a rounded
272
303
  * parent hugging the image), "pruned" (cuts nothing), "ignored" (that parent turns past
273
- * the viewer right now). A data-gl-occlude panel over it is `by: "occlude"`; "uncut": it
304
+ * the viewer right now). A data-umber-occlude panel over it is `by: "occlude"`; "uncut": it
274
305
  * overlaps, but no shader slot was free, so GL draws over it there this frame.
275
306
  */
276
- clips?: Array<{ el: Element; by: "overflow" | "clip-path" | "clip" | "occlude"; shape: string; how: "scissor" | "shader" | "corners" | "pruned" | "ignored" | "uncut" }>;
307
+ clips?: {
308
+ el: Element;
309
+ by: "overflow" | "clip-path" | "clip" | "occlude";
310
+ shape: string;
311
+ how: "scissor" | "shader" | "corners" | "pruned" | "ignored" | "uncut";
312
+ }[];
277
313
  /** Where GL draws it (null when it has no plane). */
278
314
  geometry?: {
279
315
  /** "none": flat (translate / scale at most); "2d": rotated, skewed or mirrored; "3d": tilted (perspective). */
@@ -281,32 +317,55 @@ export interface InspectReport {
281
317
  /** uSize: its size on screen (for a turned element: its layout proportions at its on-screen scale). */
282
318
  size: [number, number];
283
319
  /** The drawn quad, viewport px: top-left, top-right, bottom-right, bottom-left of the element's own box. */
284
- corners: Array<[number, number]>;
320
+ corners: [number, number][];
285
321
  /**
286
322
  * What measures it every frame right now, or null: "CSS transition on <div.card>, 0.32 s
287
323
  * left", "infinite CSS animation on <div.track>", "scroll-driven CSS animation on ...",
288
- * "data-gl-live", "a sticky or fixed parent", "live mode (a page change, gl.live())".
324
+ * "data-umber-live", "a sticky or fixed parent", "live mode (a page change, umber.live())".
289
325
  */
290
326
  live: string | null;
291
327
  } | null;
292
328
  }
293
329
 
330
+ /** What a setup callback may return: run when what it set up goes. */
331
+ export type Cleanup = () => void;
332
+
333
+ /**
334
+ * A setup callback: it returns nothing, or `R`, a cleanup (an async setup: a promise of
335
+ * one). Two signatures, so a setup with no return statement is one too.
336
+ */
337
+ export type Setup<C, R = Cleanup> = ((ctx: C) => void) | ((ctx: C) => R);
338
+
339
+ /** The console an add-on prints through, behind the engine's switch (createUmber({ warnings })). */
340
+ export interface ModuleLog {
341
+ warn(...args: unknown[]): void;
342
+ error(...args: unknown[]): void;
343
+ }
344
+
294
345
  /**
295
346
  * An optional Umber module (modules/scrub.js, @occluze/umber/scrub). Elements with
296
- * data-gl-<name> are handed to it; its handle is at plane[name] (gl.plane(el)?.scrub).
297
- * Writing your own is possible but the plane hooks are advanced (see src/types.ts).
347
+ * data-umber-<name> are handed to it; its handle is at plane[name] (umber.plane(el)?.scrub).
348
+ * Writing your own is possible; the plane hooks for that are in types/module.d.ts.
298
349
  */
299
350
  export interface UmberModule {
300
351
  name: string;
301
352
  version?: string;
302
- /** Attributes it owns, without "data-gl-". @default [name] */
353
+ /** Attributes it owns, without "data-umber-". @default [name] */
303
354
  attributes?: string[];
304
- /** `keep(off)` records an undo in the gl.scope() running when it is called, and returns it. `root()`: that scope's container, else document. */
305
- install?(engine: GL, options: Record<string, unknown>, keep: <T>(made: T) => T, root: () => ParentNode): void;
306
- plane?(ctx: any): any;
355
+ /**
356
+ * `keep(off)` records an undo in the umber.scope() running when it is called, and returns it. `root()`: that scope's container, else document.
357
+ * `log`: the console behind the engine's switch (quiet on a live site, createUmber({ warnings })); print through it.
358
+ */
359
+ install?(
360
+ engine: Umber,
361
+ options: Record<string, unknown>,
362
+ keep: <T>(made: T) => T,
363
+ root: () => ParentNode,
364
+ log: ModuleLog,
365
+ ): void;
307
366
  }
308
367
 
309
- export type GLReason =
368
+ export type UmberReason =
310
369
  | "disabled"
311
370
  | "no-webgl2"
312
371
  | "device"
@@ -314,17 +373,26 @@ export type GLReason =
314
373
  | "forced-colors"
315
374
  | "reduced-motion"
316
375
  | "save-data"
376
+ | "software"
317
377
  | "context"
318
378
  | "load-failed"
319
379
  | "load-timeout"
320
- | "unlicensed"
380
+ | "blocked"
321
381
  | "context-lost"
322
382
  | "error"
323
383
  | "server"
324
384
  | "destroyed";
325
385
 
386
+ /**
387
+ * Where in Umber's part of the frame a umber.on("frame") callback runs: "measure" (layout
388
+ * reads), "update" (math and writes), "render" (drawing). What moves the page runs before
389
+ * all three, in umber.on("step").
390
+ */
326
391
  export type TickPhase = "measure" | "update" | "render";
327
392
 
393
+ export type { FrameOptions, Loop, ProfileLine, Profiler, ProfilerOptions, StepOptions } from "./loop.js";
394
+ import type { FrameOptions, Loop, StepOptions } from "./loop.js";
395
+
328
396
  export interface Frame {
329
397
  /** Seconds since the engine started, lag-smoothed. */
330
398
  time: number;
@@ -337,6 +405,12 @@ export interface Frame {
337
405
  woke: boolean;
338
406
  /** px; velocity in px per second. */
339
407
  scroll: { x: number; y: number; velocity: number };
408
+ /**
409
+ * ms left before this frame takes longer than the screen's frame time: heavy work can
410
+ * skip a frame, or stop and go on in the next one. Live: call it again after some work.
411
+ * @example umber.on("frame", (f) => { while (jobs.length && f.budget() > 2) jobs.shift()!(); });
412
+ */
413
+ budget(): number;
340
414
  }
341
415
 
342
416
  /**
@@ -375,7 +449,7 @@ export type PlaneEvent = "ready" | "enter" | "leave" | "resize" | "error" | "des
375
449
  * One line, word or character of a GL text (plane.text). `t`, `x`, `y`, `z` are four
376
450
  * plain numbers per unit (0 at first) that any library can tween; their meaning is the
377
451
  * effect's. They are kept by index when the text rewraps.
378
- * @example gsap.to(gl.plane(h1).text.lines, { t: 1, stagger: 0.08 })
452
+ * @example umber.plane(h1).text.lines.forEach((line, i) => line.tween("t", { value: 1, delay: i * 0.08 }))
379
453
  */
380
454
  export interface TextUnit {
381
455
  /** 0-based, in reading order: the same numbers as glyph() in GLSL. */
@@ -407,10 +481,10 @@ export interface TextChar extends TextUnit {
407
481
  }
408
482
 
409
483
  /**
410
- * plane.text on data-gl="text" planes (undefined on others, and until chunks/text.js
484
+ * plane.text on data-umber="text" planes (undefined on others, and until chunks/text.js
411
485
  * arrived): its lines, words and characters, empty until the first paint. Where the site
412
486
  * split its own lines ([data-line] elements), those are the lines. The counts also reach
413
- * CSS on the element: var(--gl-lines), var(--gl-words), var(--gl-chars).
487
+ * CSS on the element: var(--umber-lines), var(--umber-words), var(--umber-chars).
414
488
  */
415
489
  export interface PlaneText {
416
490
  readonly lines: TextLine[];
@@ -419,7 +493,7 @@ export interface PlaneText {
419
493
  /** +1 per paint that changed the units. */
420
494
  readonly version: number;
421
495
  /**
422
- * One gl.progress() per line or word (not characters): `start` / `end` written as for
496
+ * One umber.progress() per line or word (not characters): `start` / `end` written as for
423
497
  * the element, measured from each unit's own edges ("top 80%": this line's top at 80 %
424
498
  * of the screen). Make them again after a "text" event.
425
499
  * @example plane.text.progress("lines", { start: "top 85%", end: "top 55%" }).forEach((p, i) => p.on("change", () => (lines[i].t = p.value)))
@@ -427,6 +501,18 @@ export interface PlaneText {
427
501
  progress(level: "lines" | "words", options?: ProgressOptions): ProgressSignal[];
428
502
  }
429
503
 
504
+ /** The indices below each fixed length Umber hands out arrays of. */
505
+ interface Below {
506
+ 4: 0 | 1 | 2 | 3;
507
+ }
508
+
509
+ /**
510
+ * A Float32Array made with N entries, which it keeps: each index below N reads as a
511
+ * number, also under noUncheckedIndexedAccess (plane.rect[2] is a number, not
512
+ * number | undefined).
513
+ */
514
+ export type Float32s<N extends keyof Below> = Float32Array & Record<Below[N], number>;
515
+
430
516
  export interface Plane {
431
517
  readonly id: number;
432
518
  readonly el: HTMLElement;
@@ -434,23 +520,30 @@ export interface Plane {
434
520
  /** "loading" | "ready" | "error" */
435
521
  readonly status: string;
436
522
  /** This frame's viewport rect as [x, y, width, height] (CSS px): rect[2] is the width. */
437
- readonly rect: Float32Array;
438
- /** On screen (the real viewport, like gl.track()); "enter" / "leave" fire as it changes. */
523
+ readonly rect: Float32s<4>;
524
+ /**
525
+ * [x, y] CSS px your code moves the element by this frame with the CSS `translate`
526
+ * property (set it in the measure phase, where the scrollfx module sets its parallax and
527
+ * lag): the plane is drawn that far over in the same frame, and measuring leaves it out, so
528
+ * it needs no measure per frame. null: none.
529
+ */
530
+ offset: [number, number] | null;
531
+ /** On screen (the real viewport, like umber.track()); "enter" / "leave" fire as it changes. */
439
532
  readonly inView: boolean;
440
533
  /** 0 as the element's top enters at the bottom of the screen, 1 as its bottom leaves at the top. */
441
534
  readonly progress: number;
442
- readonly effects: Array<{ name: string; options: Record<string, any> }>;
443
- /** data-gl="text": its lines, words and characters, as data and tweenable numbers. */
535
+ readonly effects: { name: string; options: Record<string, unknown> }[];
536
+ /** data-umber="text": its lines, words and characters, as data and tweenable numbers. */
444
537
  readonly text?: PlaneText;
445
- /** data-gl-instances (or an effect's `instances`): its count and per-instance data. Undefined without. */
538
+ /** data-umber-instances (or an effect's `instances`): its count and per-instance data. Undefined without. */
446
539
  readonly instances?: PlaneInstances;
447
540
  /** Plain { value } objects: animate them with anything. */
448
- readonly uniforms: Record<string, Signal<any>>;
541
+ readonly uniforms: Record<string, Signal<unknown>>;
449
542
  /**
450
- * Set a uniform. A Signal (gl.progress(el), gl.pointer, any { value }) links it: the
543
+ * Set a uniform. A Signal (umber.progress(el), umber.pointer, any { value }) links it: the
451
544
  * uniform follows that Signal from then on. A CSS colour string ("#f30", "oklch(...)",
452
545
  * "var(--brand)") becomes [r, g, b, a] in sRGB (var() read from the element now).
453
- * @example plane.set("uStory", gl.progress(el.closest("section")))
546
+ * @example plane.set("uStory", umber.progress(el.closest("section")))
454
547
  */
455
548
  set(name: string, value: unknown): Plane;
456
549
  get(name: string): unknown;
@@ -460,9 +553,9 @@ export interface Plane {
460
553
  play(vars?: Partial<TweenVars> & { uniform?: string }): Tween | null;
461
554
  /**
462
555
  * Let go of its element (chunks/flip.js): resolves with its rect, viewport CSS px, to
463
- * move with anything (GSAP...). It stays put on screen while the page scrolls, and its
556
+ * move with anything (your own tween, an animation library). It stays put on screen while the page scrolls, and its
464
557
  * element's own DOM stays hidden. land() flies it home.
465
- * @example const r = await plane.lift(); gsap.to(r, { x: 0, y: 0, width: innerWidth, height: innerHeight });
558
+ * @example const r = await plane.lift(); Object.assign(r, { x: 0, y: 0, width: innerWidth, height: innerHeight });
466
559
  */
467
560
  lift(): Promise<FreeRect | null>;
468
561
  /** Fly home to its element from wherever it is drawn (after lift()). */
@@ -470,49 +563,49 @@ export interface Plane {
470
563
  on(event: PlaneEvent, fn: (plane: Plane) => void): () => void;
471
564
  off(event: PlaneEvent, fn: (plane: Plane) => void): void;
472
565
  wake(frames?: number): void;
473
- /** The element shows as normal DOM again. gl.scan(el) brings it back. */
566
+ /** The element shows as normal DOM again. umber.scan(el) brings it back. */
474
567
  destroy(): void;
475
568
  revert(): void;
476
569
  }
477
570
 
478
- /** gl.add(el, options): the attributes it writes, as options (the same contract). */
571
+ /** umber.add(el, options): the attributes it writes, as options (the same contract). */
479
572
  export interface AddOptions {
480
- /** data-gl. @default "image" (or "video" for a <video>) */
573
+ /** data-umber. @default "image" (or "video" for a <video>) */
481
574
  type?: "image" | "video" | "text" | "shader" | "layer" | "group";
482
- /** data-gl-effect: effect names, applied in order. @example effects: ["dissolve"] */
575
+ /** data-umber-effect: effect names, applied in order. @example effects: ["dissolve"] */
483
576
  effects?: string[] | string;
484
- /** data-gl-<effect>-<option>, per effect. @example options: { dissolve: { scale: 6, trigger: "manual" } } */
577
+ /** data-umber-<effect>-<option>, per effect. @example options: { dissolve: { scale: 6, trigger: "manual" } } */
485
578
  options?: Record<string, Record<string, unknown>>;
486
- /** data-gl-shader (with type "shader"). */
579
+ /** data-umber-shader (with type "shader"). */
487
580
  shader?: string;
488
- /** data-gl-layer (with type "layer"). */
581
+ /** data-umber-layer (with type "layer"). */
489
582
  layer?: string;
490
- /** data-gl-src: another image than the <img> inside. */
583
+ /** data-umber-src: another image than the <img> inside. */
491
584
  src?: string;
492
- /** data-gl-fit. */
585
+ /** data-umber-fit. */
493
586
  fit?: "cover" | "contain" | "fill";
494
- /** data-gl-order: draw order. */
587
+ /** data-umber-order: draw order. */
495
588
  order?: number;
496
- /** data-gl-live: measure every frame. */
589
+ /** data-umber-live: measure every frame. */
497
590
  live?: boolean;
498
591
  /**
499
- * data-gl-clip: false draws it without its parents' clips (overflow, clip-path, CSS masks).
592
+ * data-umber-clip: false draws it without its parents' clips (overflow, clip-path, CSS masks).
500
593
  * Its own clip-path still cuts it. @default true
501
594
  */
502
595
  clip?: boolean;
503
- /** data-gl-instances: "64", "tiles 24x16", "chars", "echo 6", "ink 3000". */
596
+ /** data-umber-instances: "64", "tiles 24x16", "chars", "echo 6", "ink 3000", "points 20000". */
504
597
  instances?: string | number;
505
598
  }
506
599
 
507
600
  /**
508
- * plane.instances on a plane drawn as instances (data-gl-instances, or an effect's
601
+ * plane.instances on a plane drawn as instances (data-umber-instances, or an effect's
509
602
  * `instances`): the per-instance numbers of the attributes its effects declare.
510
603
  * @example const seeds = plane.instances.data("aSeed"); seeds[0] = 0.5; plane.instances.update("aSeed");
511
604
  */
512
605
  export interface PlaneInstances {
513
606
  /** How many are drawn (text: its characters, words or lines). */
514
607
  readonly count: number;
515
- readonly mode: "count" | "tiles" | "chars" | "words" | "lines" | "echo" | "ink";
608
+ readonly mode: "count" | "tiles" | "chars" | "words" | "lines" | "echo" | "ink" | "points";
516
609
  /** An attribute's numbers (count x its size), to change in place; then update(name). null when no effect declares it. */
517
610
  data(name: string): Float32Array | null;
518
611
  /** Replace an attribute's numbers (count x its size); sent to the GPU on the next frame. */
@@ -521,13 +614,35 @@ export interface PlaneInstances {
521
614
  update(name?: string): void;
522
615
  }
523
616
 
524
- export interface EffectContext {
617
+ /** A definition's options (umber.effect, umber.shader, umber.layer): each with its default. */
618
+ export type OptionDefaults = Record<string, unknown>;
619
+
620
+ /**
621
+ * One option as an element gives it (data-umber-<name>-<option> > --umber-<name>-<option> > the
622
+ * default), read as its default's type: a number, a boolean or a string; a list default
623
+ * reads an attribute as its words.
624
+ */
625
+ export type OptionValue<T> = T extends number
626
+ ? number
627
+ : T extends boolean
628
+ ? boolean
629
+ : T extends string
630
+ ? string
631
+ : T extends readonly unknown[]
632
+ ? T | string[]
633
+ : T | string;
634
+
635
+ /** A definition's options as one element resolved them (ctx.options). */
636
+ export type ResolvedOptions<O extends OptionDefaults> = { [K in keyof O]: OptionValue<O[K]> };
637
+
638
+ /** `O`: the effect's (or shader's) option defaults, which type ctx.options. */
639
+ export interface EffectContext<O extends OptionDefaults = OptionDefaults> {
525
640
  name: string;
526
641
  el: HTMLElement;
527
642
  plane: Plane;
528
- engine: GL;
529
- options: Record<string, any>;
530
- uniforms: Record<string, Signal<any>>;
643
+ engine: Umber;
644
+ options: ResolvedOptions<O>;
645
+ uniforms: Record<string, Signal<unknown>>;
531
646
  readonly reducedMotion: boolean;
532
647
  viewport: { width: number; height: number };
533
648
  /** Only set during update(). */
@@ -542,14 +657,19 @@ export interface EffectContext {
542
657
  /**
543
658
  * An effect: GLSL snippets for named slots plus uniforms. The slots, inputs and helpers
544
659
  * are a fixed contract (src/gl/shaders.ts; names are only ever added):
545
- * vertex.head / vertex.main (change `pos`, px offset in the element's own axes, using `uv`)
660
+ * vertex.head / vertex.main (change `pos`, px offset in the element's own axes, using `uv`;
661
+ * every uniform is declared there too, textures included: textureLod(uMap, at, 0.0))
546
662
  * fragment.head / uv / color (vec4) / alpha (float)
547
663
  * inputs: vUv, uSize, uViewport, uRect, uMouse, uTime, uScrollVelocity, uProgress,
548
664
  * uPlaneMatrix (mat3: own px -> viewport px; a translation when flat),
549
- * uSurface (vec4: where this draw goes, viewport px x, y, w, h; today the
550
- * canvas: 0, 0, uViewport), uBleed (px the quad reaches past the element:
551
- * the `bleed` option; vUv then runs below 0 and above 1 there);
552
- * fragment only: uAlpha, uDpr, uImage, uImageSize, uCanvas
665
+ * uSurface (vec4: where this draw goes, viewport px x, y, w, h: the canvas,
666
+ * 0, 0, uViewport, or the window of a group's texture or a snapshot, with a
667
+ * negative height), uBleed (vec4: px the quad reaches past the element at its
668
+ * top, right, bottom and left: the `bleed` option; vUv then runs below 0 and
669
+ * above 1 there), PI;
670
+ * fragment only: uAlpha, uDpr, uImage, uImageSize, uCanvas;
671
+ * a new picture (fragment only): uSwap (0 -> 1 once a new src is on the GPU),
672
+ * samplePrev(uv) (the picture before it, added when called)
553
673
  * a rotated, skewed or 3D-tilted element: vUv, uMouse and `pos` follow its own edges;
554
674
  * uSize is its layout size at its on-screen scale; uRect = centre - uSize / 2, uSize
555
675
  * helpers, fragment only: sampleImage(uv), sampleRaw(uv) (premultiplied: what a blur
@@ -562,82 +682,119 @@ export interface EffectContext {
562
682
  * rotate2d(angle), umberHash(vec2 | vec3), glyph(uv), screenPx() (fragment
563
683
  * only: this pixel on screen, viewport CSS px, whatever turns the element),
564
684
  * screenUv() (fragment only: this pixel on screen, 0..1 over the viewport,
565
- * y down), uScreen (vec2: the element's centre on the viewport, -1..1, y down)
566
- * #include "name" on a line of its own, in any slot: the gl.chunk() of that name, added
567
- * once per program (only included chunks are compiled)
685
+ * y down), screenPx(uv) / screenUv(uv) (vertex only: where the element's own uv
686
+ * is on screen), uScreen (vec2: the element's centre on the viewport, -1..1,
687
+ * y down), textureSmooth(tex, uv) (tex through a cubic B-spline over 16 texels:
688
+ * no texel steps in a small field's slopes; textureSmooth(tex, uv, dx, dy) also
689
+ * writes its slope per unit of uv into your vec4s), flowSmooth(uv) and
690
+ * flowSmooth(uv, dx, dy) (uFlow that way)
691
+ * #include "name" on a line of its own, in any slot: the umber.chunk() of that name, added
692
+ * once per program (only included chunks are compiled); what a chunk names
693
+ * (uFlow, a helper) counts as the effect's own, on a plane and in a data-umber-pass
568
694
  * two effects on one plane that declare the same top-level name in their heads (a
569
695
  * function, const, global or #define) each get their own (renamed e<N>_name)
570
696
  * glyph(uv), GL text: Glyph { float line, word, char, lines, words, chars;
571
- * vec4 lineBox, wordBox, charBox (x, y, width, height in uv); float ink }
697
+ * vec4 lineBox, wordBox, charBox (x, y, width, height in uv); float ink;
698
+ * vec4 lineValue, wordValue, charValue (plane.text's t, x, y, z; 0 until set) }
572
699
  * after the alpha slot, Umber cuts the plane where its parents cut it in the DOM
573
700
  * (overflow, clip-path); names starting with uUmber / umber are reserved
574
701
  */
575
- export interface EffectDef {
702
+ export interface EffectDef<O extends OptionDefaults = OptionDefaults> {
576
703
  /**
577
704
  * Uniforms it adds, with their first value; Umber writes the GLSL declarations.
578
705
  * number -> float, [x, y(, z, w)] -> vec2..4, 9 numbers -> mat3, 16 -> mat4, a URL
579
706
  * string -> sampler2D (fragment only), and a Signal
580
- * ({ value }: gl.progress(el), gl.pointer, gl.velocity, your own) is followed live. A CSS
707
+ * ({ value }: umber.progress(el), umber.pointer, umber.velocity, your own) is followed live. A CSS
581
708
  * colour string ("#ff3300", "oklch(70% 0.15 30)", "var(--brand)") -> vec4 [r, g, b, a]
582
709
  * in sRGB, converted by the browser (var() read from each element once). Anything
583
- * holding a `texture` (the input module's gl.texture(), gl.touch(), gl.rects()) ->
710
+ * holding a `texture` (the input module's umber.texture(), umber.touch(), umber.rects()) ->
584
711
  * highp sampler2D; a raw canvas, video, a typed array other than Float32Array, or more
585
- * than 896 numbers (more than a phone's uniforms hold) warns: wrap it in gl.texture()
712
+ * than 896 numbers (more than a phone's uniforms hold) warns: wrap it in umber.texture()
586
713
  * (numbers that fit no type above warn only when the GLSL reads them undeclared).
587
714
  * @example uniforms: { uShow: 0, uTint: [1, 0.4, 0.2], uNoise: "/noise.png" }
588
715
  * @example uniforms: { uTint: "var(--brand)" }
589
- * @example uniforms: { uStory: gl.progress(".story"), uPointer: gl.pointer }
716
+ * @example uniforms: { uStory: umber.progress(".story"), uPointer: umber.pointer }
590
717
  */
591
718
  uniforms?: Record<string, unknown>;
592
719
  /**
593
- * Options read per element: data-gl-<effect>-<key> > --gl-<effect>-<key> (CSS) > this
720
+ * Options read per element: data-umber-<effect>-<key> > --umber-<effect>-<key> (CSS) > this
594
721
  * default. Number, boolean, array and CSS colour options become uniforms too: effect
595
722
  * "ripple", option "strength" -> uRippleStrength. Give a colour option a colour default
596
723
  * ({ color: "#fff" }) so every element has the vec4. A string with a "/" is an image
597
- * path -> sampler2D (a per-element map: data-gl-depth-map="/img/a-depth.webp" ->
724
+ * path -> sampler2D (a per-element map: data-umber-depth-map="/img/a-depth.webp" ->
598
725
  * uDepthMap; give it a default path). `bleed` (px) draws the plane that much past its
599
- * element on every side (uBleed: the largest of its effects).
726
+ * element on every side; four numbers ("0 0 560 0" or [0, 0, 560, 0]) are its top, right,
727
+ * bottom and left (uBleed, a vec4: per side the largest of its effects). `reach` (px, one
728
+ * number or [top, right, bottom, left]) is the same room round each letter of a
729
+ * data-umber-instances="chars" text, past the letter's ink. `perspective` (px
730
+ * from the eye to the plane) draws what vertex.main moves along pos.z in perspective, about
731
+ * `perspectiveOrigin` (vec2, px in the element's own space; its centre unless vertex.main
732
+ * sets it): pos.z below 0 goes back, as CSS translateZ. At pos.z 0 nothing moves.
733
+ * setup() and update() read them as ctx.options, typed from these defaults.
600
734
  * @example options: { strength: 1, duration: 1.2, ease: "expo.out" }
601
735
  * @example options: { map: "/img/blank.webp", bleed: 40 }
736
+ * @example options: { bleed: "0 0 560 0" } // only below: an effect that drops its element
737
+ * @example options: { perspective: 800 }
602
738
  */
603
- options?: Record<string, unknown>;
739
+ options?: O;
604
740
  /**
605
741
  * Uniform values used instead when the visitor prefers reduced motion (and
606
- * createGL({ reducedMotion }) is "static", the default): keep a fade, still a wave.
742
+ * createUmber({ reducedMotion }) is "static", the default): keep a fade, still a wave.
607
743
  * @example reduced: { uWave: 0 }
608
744
  */
609
745
  reduced?: Record<string, unknown>;
610
746
  /**
611
747
  * A uniform Umber plays 0 -> 1 by itself, with the trigger options every playable
612
748
  * effect understands: trigger (auto | scroll | load | manual | hover), delay, duration, ease,
613
- * start ("top 90%").
749
+ * start ("top 90%"), repeat ("" once | "reverse" | "true": again each time it scrolls in),
750
+ * hide (true: the element is hidden while GL loads; false: its plain DOM shows until GL has drawn it).
614
751
  * @example play: "uShow"
615
752
  */
616
753
  play?: string;
617
754
  /**
618
- * Grid segments per side: more than 1 when vertex.main bends the plane.
755
+ * Grid segments per side: more than 1 when vertex.main bends the plane (24 is plenty for a
756
+ * bend; a dent a few dozen px wide wants 48).
619
757
  * @default 1
620
758
  */
621
759
  segments?: number;
622
760
  /**
623
761
  * Draw the plane many times in ONE draw call (chunks/instances.js). The element's own
624
- * data-gl-instances wins. GLSL then has `instance` (0..uInstances - 1) and `uInstances`,
762
+ * data-umber-instances wins. GLSL then has `instance` (0..uInstances - 1) and `uInstances`,
625
763
  * plus per mode:
626
764
  * "64" (or { count: 64 }) copies: place each with `instance` in vertex.main
627
765
  * "tiles 24x16" one quad per tile: `tile` (vec4 column, row, columns, rows),
628
766
  * `tileCenter` (vec2, uv); move tiles apart with `pos`
629
767
  * "chars" | "words" | "lines" GL text, one quad per unit: `unitValue` (vec4: its t, x, y, z from
630
- * plane.text, what GSAP writes; .x is t), `unitBox` (vec4, its box in uv)
768
+ * plane.text, what a tween writes; .x is t), `unitBox` (vec4, its box in uv).
769
+ * "chars" draws each letter's quad round its ink, from that letter alone:
770
+ * `unitInk` (vec4, its ink box in uv), and in vertex.main `unitScale`,
771
+ * `unitTurn` (radians) and `unitAlpha` to write (at 0 the letter is not drawn)
631
772
  * "echo 6" ("echo 6 delay 0.05") 5 copies where the plane was 0.05 s, 0.1 s... ago (a trail):
632
773
  * `echoOffset` (vec2 px); instance 0 is the plane, drawn on top;
633
774
  * copies that caught up are not drawn
634
775
  * "ink 3000" ("size 3", "luma") 3000 particles seeded where the plane has ink (alpha, or
635
776
  * brightness), each a `size` px piece of the plane:
636
777
  * `inkPoint` (vec4: uv, ink 0..1, found)
778
+ * "points 20000" ("size 3") 20000 particles spread evenly at random over the plane, placed
779
+ * on the GPU (no seed pass): `point` (vec4: uv, two random
780
+ * numbers 0..1), `pointUv` (vec2: 0..1 across the particle)
637
781
  * Every input is there in vertex and fragment code; your attributes in vertex code only.
638
782
  * @example instances: "tiles 16x10", vertex: { main: "pos.xy += (tileCenter - 0.5) * uSize * uSpread;" }
639
783
  */
640
- instances?: number | string | { count?: number; tiles?: string | [number, number]; units?: "chars" | "words" | "lines"; echo?: number; delay?: number; ink?: number; size?: number; source?: "alpha" | "luma" };
784
+ instances?:
785
+ | number
786
+ | string
787
+ | {
788
+ count?: number;
789
+ tiles?: string | [number, number];
790
+ units?: "chars" | "words" | "lines";
791
+ echo?: number;
792
+ delay?: number;
793
+ ink?: number;
794
+ points?: number;
795
+ size?: number;
796
+ source?: "alpha" | "luma";
797
+ };
641
798
  /**
642
799
  * Per-instance numbers, as `in` attributes of the vertex shader (declared for you): a size
643
800
  * (1-4: a stable random 0..1 per instance and component) or a function of the instance
@@ -651,32 +808,33 @@ export interface EffectDef {
651
808
  * fragment.uv changes `uv` before the image is sampled; color changes `color` (vec4);
652
809
  * alpha changes `alpha` (float, already the element's opacity and corners: multiply it).
653
810
  * head holds functions and globals shared between slots, and #include "name" lines
654
- * (gl.chunk()).
811
+ * (umber.chunk()).
655
812
  * Helpers: sampleImage(uv), sampleRaw(uv), roundedBox(p, size, vec4 radii), noise(vec2 | vec3), fbm(vec2),
656
813
  * rotate2d(a), umberHash(vec2 | vec3), screenPx(), screenUv().
657
814
  * @example fragment: { color: "color.rgb *= uTint;" }
658
815
  */
659
816
  fragment?: { head?: string; uv?: string; color?: string; alpha?: string };
660
- /** Once per plane. Return a cleanup (also: ctx.listen() cleans up by itself). */
661
- setup?: (ctx: EffectContext) => void | (() => void);
817
+ /** Once per plane. Return a cleanup (also: ctx.listen() cleans up by itself), or nothing. */
818
+ setup?: Setup<EffectContext<O>>;
662
819
  /** Every drawn frame while the plane is on screen (ctx.frame is set). */
663
- update?: (ctx: EffectContext) => void;
820
+ update?(ctx: EffectContext<O>): void;
664
821
  }
665
822
 
666
- export interface ShaderDef {
823
+ export interface ShaderDef<O extends OptionDefaults = OptionDefaults> {
667
824
  /** Set `color` (vec4) from `uv`. */
668
825
  fragment: string;
669
826
  head?: string;
670
827
  uniforms?: Record<string, unknown>;
671
828
  /**
672
- * Options read per element: data-gl-shader-<key> > --gl-shader-<key> > this default.
829
+ * Options read per element: data-umber-shader-<key> > --umber-shader-<key> > this default.
673
830
  * Number, boolean and array options become uniforms named u + Option (speed -> uSpeed).
674
831
  */
675
- options?: Record<string, unknown>;
832
+ options?: O;
676
833
  /** Keep drawing every frame while visible (not under reduced motion with reducedMotion "static": uTime stands still). @default true */
677
834
  animate?: boolean;
678
- setup?: (ctx: EffectContext) => void | (() => void);
679
- update?: (ctx: EffectContext) => void;
835
+ /** Once per element. Return a cleanup, or nothing. */
836
+ setup?: Setup<EffectContext<O>>;
837
+ update?(ctx: EffectContext<O>): void;
680
838
  }
681
839
 
682
840
  export interface LayerRect {
@@ -686,14 +844,25 @@ export interface LayerRect {
686
844
  height: number;
687
845
  }
688
846
 
689
- export interface LayerContext {
847
+ /** What ctx.three() sets on a THREE.WebGLRenderer (a method it lacks is skipped). */
848
+ export interface LayerRendererLike {
849
+ autoClear: boolean;
850
+ resetState?(): void;
851
+ setViewport?(x: number, y: number, width: number, height: number): void;
852
+ setScissor?(x: number, y: number, width: number, height: number): void;
853
+ setScissorTest?(on: boolean): void;
854
+ }
855
+
856
+ /** `O`: the layer's option defaults (ctx.options). `S`: what you keep in ctx.state: umber.layer<O, S>(name, def). */
857
+ export interface LayerContext<O extends OptionDefaults = OptionDefaults, S extends object = Record<string, unknown>> {
690
858
  name: string;
691
859
  el: HTMLElement;
692
860
  gl: WebGL2RenderingContext;
693
861
  canvas: HTMLCanvasElement;
694
- options: Record<string, any>;
695
- state: Record<string, any>;
696
- engine: GL;
862
+ options: ResolvedOptions<O>;
863
+ /** Your own storage for this element's layer (renderer, scene, meshes...): empty when setup() starts, filled by it. */
864
+ state: S;
865
+ engine: Umber;
697
866
  rect: LayerRect;
698
867
  px: LayerRect;
699
868
  viewport: { width: number; height: number };
@@ -707,18 +876,22 @@ export interface LayerContext {
707
876
  /** Draw at least `frames` more frames. Under reduced motion ("static") an animating layer draws only on this (and when setup() resolves): call it when a model loaded after setup lands. */
708
877
  wake(frames?: number): void;
709
878
  busy(on: boolean): void;
710
- three(renderer: any): void;
879
+ /** three.js: resetState, autoClear off, viewport + scissor to this element. */
880
+ three(renderer: LayerRendererLike): void;
711
881
  }
712
882
 
713
- export interface LayerDef {
714
- /** Read per element into ctx.options: data-gl-layer-<key> > --gl-layer-<key> > this default. */
715
- options?: Record<string, unknown>;
716
- /** Once, when the element comes near the screen. May be async; return a cleanup. */
717
- setup?: (ctx: LayerContext) => void | (() => void) | Promise<void | (() => void)>;
883
+ export interface LayerDef<O extends OptionDefaults = OptionDefaults, S extends object = Record<string, unknown>> {
884
+ /** Read per element into ctx.options: data-umber-layer-<key> > --umber-layer-<key> > this default. */
885
+ options?: O;
886
+ /**
887
+ * Once, when the element comes near the screen; render() and resize() wait for it. May be
888
+ * async; return (or resolve to) a cleanup, or nothing. ctx.state starts empty: fill it here.
889
+ */
890
+ setup?: Setup<LayerContext<O, Partial<S>>, Cleanup | Promise<Cleanup | undefined>>;
718
891
  /** Draw (ctx.three(renderer) first for three.js). */
719
- render: (ctx: LayerContext) => void;
892
+ render(ctx: LayerContext<O, S>): void;
720
893
  /** The element or the screen changed size (before render). */
721
- resize?: (ctx: LayerContext) => void;
894
+ resize?(ctx: LayerContext<O, S>): void;
722
895
  /** Draw every frame while visible (not under reduced motion with reducedMotion "static": ctx.time stands still, and it draws on ctx.wake()). false: only on wake(), busy(true), resize and scroll. @default true */
723
896
  animate?: boolean;
724
897
  /** Clip drawing to the element box. @default true */
@@ -727,12 +900,14 @@ export interface LayerDef {
727
900
  followOpacity?: boolean;
728
901
  /** Max device px per CSS px for this layer (a heavy scene renders smaller, upscaled). @default the canvas's */
729
902
  dpr?: number;
903
+ /**
904
+ * Under the page's passes (data-umber-pass on <body>), like Umber's own planes: drawn alone, copied, and the copy
905
+ * drawn in its place (one copy of its box per frame while the page has passes). false: straight to the canvas,
906
+ * under the passes. @default false (data-umber="model" and the three module's scenes: true)
907
+ */
908
+ passes?: boolean;
730
909
  }
731
910
 
732
- // -----------------------------------------
733
- // Tracking, three.js views and DOM <-> world maths
734
- // -----------------------------------------
735
-
736
911
  export interface TrackRect {
737
912
  x: number;
738
913
  y: number;
@@ -747,7 +922,7 @@ export interface TrackOptions {
747
922
  live?: boolean;
748
923
  }
749
924
 
750
- /** gl.track(el): where an element is, every frame, without layout reads or WebGL. */
925
+ /** umber.track(el): where an element is, every frame, without layout reads or WebGL. */
751
926
  export interface Tracker {
752
927
  readonly el: Element;
753
928
  /** Viewport CSS px this frame (y down), like getBoundingClientRect. */
@@ -779,30 +954,33 @@ export interface ProgressOptions {
779
954
  /**
780
955
  * Also write the value (4 decimals, only when it changed) to this CSS custom property on
781
956
  * the element, through a rule of Umber's own stylesheet (not its style attribute).
782
- * @example gl.progress(".hero", { css: "--hero" }) // .hero img { opacity: calc(1 - var(--hero)) }
957
+ * @example umber.progress(".hero", { css: "--hero" }) // .hero img { opacity: calc(1 - var(--hero)) }
783
958
  */
784
959
  css?: string;
785
960
  /** Measure every frame (a parent moved by transforms). @default auto (sticky, fixed or pinned parents) */
786
961
  live?: boolean;
962
+ /** "x": along the screen's width, for a page that scrolls sideways (edges: left / right, or top / bottom read as them). @default "y" */
963
+ axis?: "x" | "y";
787
964
  }
788
965
 
789
- /** gl.progress(el): a live 0..1 as el scrolls from `start` to `end`. Usable as a uniform. */
790
- export interface ProgressSignal extends Signal<number> {
966
+ /** umber.progress(el): a live 0..1 as el scrolls from `start` to `end`. Usable as a uniform. */
967
+ export interface ProgressSignal extends Signal {
791
968
  readonly el: Element;
792
969
  readonly start: string;
793
970
  readonly end: string;
794
971
  readonly destroyed: boolean;
795
972
  on(event: "change" | "destroy", fn: (p: ProgressSignal) => void): () => void;
796
973
  off(event: "change" | "destroy", fn: (p: ProgressSignal) => void): void;
797
- /** Automatic when el leaves the page. */
974
+ /** Automatic when el leaves the page. With `css`, the variable keeps its last value while el is on the page. */
798
975
  destroy(): void;
976
+ /** As destroy(), and with `css` the variable is taken off el. */
799
977
  revert(): void;
800
978
  }
801
979
 
802
980
  /**
803
- * gl.pointer: the pointer (mouse, pen or touch). Usable as a uniform (vec2).
804
- * More inputs (gl.drag, gl.velocityOf any Signal, gl.trail, gl.press, gl.step) come with
805
- * the input module: gl.use(Input) from "@occluze/umber/input" (types/input.d.ts).
981
+ * umber.pointer: the pointer (mouse, pen or touch). Usable as a uniform (vec2).
982
+ * More inputs (umber.drag, umber.velocityOf any Signal, umber.trail, umber.press, umber.step) come with
983
+ * the input module: umber.use(Input) from "@occluze/umber/input" (types/input.d.ts).
806
984
  */
807
985
  export interface PointerSignal {
808
986
  /** [x, y] in viewport CSS px (y down). The viewport's centre until the pointer first moves. */
@@ -813,11 +991,22 @@ export interface PointerSignal {
813
991
  readonly active: boolean;
814
992
  }
815
993
 
994
+ /** What a scope makes with the engine's own calls (s.add...), and the definitions and other calls it carries as they are. */
995
+ type ScopeMakes = "add" | "track" | "progress" | "view" | "target" | "snapshot" | "sim" | "flow" | "brush";
996
+ type ScopeCarries =
997
+ "effect" | "shader" | "layer" | "chunk" | "on" | "nextFrame" | "scope" | "preload" | "warm" | "leave" | "flip";
998
+
816
999
  /**
817
- * gl.scope(fn, container): everything Umber made inside fn, undone with revert(). The
818
- * scope has gl's creating methods: after an await, call them on the scope (s.add, s.track...).
1000
+ * umber.scope(fn, container): everything Umber made inside fn, undone with revert(). The
1001
+ * scope has the engine's creating methods: after an await, call them on the scope (s.add, s.track...).
1002
+ * An add-on's methods join them (types/input.d.ts: s.drag, s.texture...). On revert():
1003
+ * targets, snapshots, sims and brushes are released (the shared umber.flow() flowmap only when
1004
+ * this scope's call made it and no plane reads uFlow; options a scope set on it stay);
1005
+ * umber.preload({ hover }) is turned off (what it fetched is freed unclaimed after 20 s); this
1006
+ * scope's umber.leave() comes out, and the newest one left (or none) is on again, once a page
1007
+ * change that holds or plays it ends.
819
1008
  */
820
- export interface Scope {
1009
+ export interface Scope extends Pick<Umber, ScopeMakes | ScopeCarries> {
821
1010
  /** Where selector strings resolve inside the scope (null: the document). */
822
1011
  readonly container: Element | null;
823
1012
  readonly reverted: boolean;
@@ -828,61 +1017,40 @@ export interface Scope {
828
1017
  /** Destroy everything made in the scope, newest first; previous definitions come back. */
829
1018
  revert(): void;
830
1019
  destroy(): void;
831
- add(el: string | Element, options?: AddOptions): Promise<Plane | null>;
832
- track(el: string | Element, options?: TrackOptions): Tracker;
833
- progress(el: string | Element, options?: ProgressOptions): ProgressSignal;
834
- attach(el: string | Element, options: AttachOptions): View;
835
- view(el: string | Element, options?: SharedViewOptions): View;
836
- effect(name: string, def: EffectDef): void;
837
- shader(name: string, def: ShaderDef): void;
838
- layer(name: string, def: LayerDef): void;
839
- chunk(name: string, glsl: string): void;
840
- on(name: "frame", fn: (frame: Frame) => void, opts?: { phase?: TickPhase; order?: number; always?: boolean }): () => void;
841
- on(name: "ready" | "lost" | "restored" | "destroy", fn: (payload?: any) => void): () => void;
842
- /** The roots of the subtrees that entered the page (a router's new page), once per frame; <html> on the first scan. */
843
- on(name: "added", fn: (roots: Element[]) => void): () => void;
844
- /**
845
- * GL is off for this visit, from the start (a device it skips, ?umber=off) or later (a new
846
- * page with data-gl-disable): `reason` is gl.reason. Also on document as "umber:off". For
847
- * the site's own analytics.
848
- */
849
- on(name: "off", fn: (e: { reason: GLReason }) => void): () => void;
850
- /**
851
- * A plane shows its DOM instead of GL: `reason` is the warning's words (what GL can't draw,
852
- * or GL text that stays DOM text), or null when something failed (a picture or video that
853
- * could not load, a shader that did not compile: the console says why). Also on document
854
- * as "umber:fallback".
855
- */
856
- on(name: "fallback", fn: (e: { el: Element; reason: string | null }) => void): () => void;
857
- nextFrame(fn: (frame: Frame) => void, opts?: { phase?: TickPhase; order?: number }): () => void;
858
- scope(fn?: (scope: Scope) => unknown, container?: string | Element | null): Scope;
859
- /** Released on revert() (the shared gl.flow() flowmap only when this scope's call made it and no plane reads uFlow; options a scope set on it stay). */
860
- target: GL["target"];
861
- snapshot: GL["snapshot"];
862
- sim: GL["sim"];
863
- flow: GL["flow"];
864
- brush: GL["brush"];
865
- /** gl.preload({ hover }) is turned off on revert(); what it fetched is freed unclaimed after 20 s. */
866
- preload: GL["preload"];
867
- warm: GL["warm"];
868
- /** revert() takes this scope's gl.leave() out: the newest one left (or none) is on again, once a page change that holds or plays it ends. */
869
- leave: GL["leave"];
870
- flip: GL["flip"];
871
1020
  }
872
1021
 
873
- /** What Umber calls on a THREE.WebGLRenderer (Umber never imports three.js). */
874
- export interface ThreeRendererLike {
875
- domElement?: HTMLCanvasElement;
1022
+ /** What Umber sets and calls on the one renderer umber.renderer(THREE) makes on its canvas. */
1023
+ export interface SharedRendererLike extends LayerRendererLike {
876
1024
  setSize?(width: number, height: number, updateStyle?: boolean): void;
877
1025
  setPixelRatio?(ratio: number): void;
878
- render?(scene: any, camera: any): void;
879
- getContext?(): WebGLRenderingContext | WebGL2RenderingContext;
880
1026
  dispose?(): void;
881
- [key: string]: any;
1027
+ /** The default render(): renderer.render(scene, camera), with the view's scene and camera. */
1028
+ render(scene: unknown, camera: unknown): void;
1029
+ /** three.js's own: the scene's shaders compiled, resolved when they are ready. A view waits for it before its first draw. */
1030
+ compileAsync?(scene: unknown, camera: unknown): Promise<unknown>;
882
1031
  }
883
1032
 
884
- /** The object a view's animate / render / resize get. */
885
- export interface ViewFrame {
1033
+ /** What umber.renderer(THREE) needs of the three.js module: its WebGLRenderer, made on Umber's canvas and context. */
1034
+ export interface ThreeModuleLike<R extends SharedRendererLike> {
1035
+ WebGLRenderer: new (params: { canvas: HTMLCanvasElement; context: WebGL2RenderingContext }) => R;
1036
+ }
1037
+
1038
+ /**
1039
+ * A view's camera: what Umber reads of it. A PerspectiveCamera's aspect follows the box
1040
+ * (isPerspectiveCamera, aspect, updateProjectionMatrix), and view.rectToWorld() /
1041
+ * view.worldToRect() map with its matrices (they throw without a camera).
1042
+ */
1043
+ export type ViewCameraLike = Partial<CameraLike>;
1044
+
1045
+ /**
1046
+ * The object a view's animate / render / resize get. `S`, `C`, `R`: your scene, camera
1047
+ * and renderer types, from the options you passed.
1048
+ */
1049
+ export interface ViewFrame<
1050
+ S = unknown,
1051
+ C extends ViewCameraLike | undefined = ViewCameraLike | undefined,
1052
+ R = unknown,
1053
+ > {
886
1054
  time: number;
887
1055
  dt: number;
888
1056
  ratio: number;
@@ -898,31 +1066,40 @@ export interface ViewFrame {
898
1066
  velocity: number;
899
1067
  /** prefers-reduced-motion: animate() still runs, but returning true no longer loops. */
900
1068
  reducedMotion: boolean;
901
- renderer: any;
902
- scene: any;
903
- camera: any;
1069
+ renderer: R;
1070
+ scene: S;
1071
+ camera: C;
904
1072
  view: View;
905
1073
  }
906
1074
 
907
- export interface ViewSetupContext {
1075
+ export interface ViewSetupContext<
1076
+ S = unknown,
1077
+ C extends ViewCameraLike | undefined = ViewCameraLike | undefined,
1078
+ R = unknown,
1079
+ > {
908
1080
  el: HTMLElement;
909
- renderer: any;
910
- scene: any;
911
- camera: any;
1081
+ renderer: R;
1082
+ scene: S;
1083
+ camera: C;
912
1084
  view: View;
913
1085
  }
914
1086
 
915
- export interface ViewOptions {
916
- scene?: any;
917
- camera?: any;
1087
+ /** `S`, `C`, `R`: the scene, camera and renderer the callbacks get (umber.view(): the shared renderer, null until umber.renderer() resolved). */
1088
+ export interface ViewOptions<
1089
+ S = unknown,
1090
+ C extends ViewCameraLike | undefined = ViewCameraLike | undefined,
1091
+ R = unknown,
1092
+ > {
1093
+ scene?: S;
1094
+ camera?: C;
918
1095
  /** Draw yourself. @default renderer.render(scene, camera) */
919
- render?: (f: ViewFrame) => void;
920
- /** Before every drawn frame. Return true to draw the next frame too. */
921
- animate?: (f: ViewFrame) => boolean | void;
922
- /** Once, when the element comes near the screen. May be async (compileAsync) and return a cleanup. */
923
- setup?: (ctx: ViewSetupContext) => void | (() => void) | Promise<void | (() => void)>;
1096
+ render?: (f: ViewFrame<S, C, R>) => void;
1097
+ /** Before every drawn frame. Return true to draw the next frame too; anything else draws again only on wake(), busy() or a resize. */
1098
+ animate?: (f: ViewFrame<S, C, R>) => boolean | undefined;
1099
+ /** Once, when the element comes near the screen. May be async (compileAsync); return (or resolve to) a cleanup, or nothing. */
1100
+ setup?: Setup<ViewSetupContext<S, C, R>, Cleanup | Promise<Cleanup | undefined>>;
924
1101
  /** After Umber sized the drawing (a PerspectiveCamera's aspect is already set). */
925
- resize?: (f: ViewFrame) => void;
1102
+ resize?: (f: ViewFrame<S, C, R>) => void;
926
1103
  /** Devices this view runs on, instead of the engine's. @example "all" (phones on for this scene only) */
927
1104
  devices?: "all" | "desktop" | false | ((env: Env) => boolean);
928
1105
  /** A max DPR or [min, max] for this view. @default the engine's dpr */
@@ -931,31 +1108,26 @@ export interface ViewOptions {
931
1108
  aspect?: boolean;
932
1109
  }
933
1110
 
934
- export interface AttachOptions extends ViewOptions {
935
- /** Your THREE.WebGLRenderer. Its canvas goes into the element unless it is in the page already. */
936
- renderer: ThreeRendererLike;
937
- /** Max drawing pixels (w * h * dpr^2). @default the engine's pixelBudget, else 12e6 */
938
- pixelBudget?: number;
939
- /** Lower the resolution only when frames get slow. @default the engine's adaptive */
940
- adaptive?: boolean;
941
- /** renderer.dispose() and free its WebGL context when the view goes. false for a renderer you reuse. @default true */
942
- dispose?: boolean;
943
- }
944
-
945
- export interface SharedViewOptions extends ViewOptions {
1111
+ /** `R`: the renderer umber.renderer(THREE) made (null in the callbacks until it resolved). */
1112
+ export interface SharedViewOptions<
1113
+ S = unknown,
1114
+ C extends ViewCameraLike | undefined = ViewCameraLike | undefined,
1115
+ R extends SharedRendererLike = SharedRendererLike,
1116
+ > extends ViewOptions<S, C, R | null> {
946
1117
  /** Fade with the element's (and its parents') opacity. @default true */
947
1118
  followOpacity?: boolean;
948
1119
  /** Clip drawing to the element box. @default true */
949
1120
  scissor?: boolean;
1121
+ /** Under the page's passes (data-umber-pass), like Umber's own planes (see LayerDef.passes). @default false */
1122
+ passes?: boolean;
950
1123
  }
951
1124
 
952
1125
  export type ViewStatus = "loading" | "ready" | "off" | "error" | "lost" | "destroyed";
953
1126
  export type ViewEvent = "ready" | "resize" | "enter" | "leave" | "lost" | "restored" | "error" | "destroy";
954
1127
 
955
- /** gl.attach() / gl.view(): your three.js scene tied to an element. */
1128
+ /** umber.view(): your three.js scene tied to an element. */
956
1129
  export interface View {
957
1130
  readonly el: HTMLElement;
958
- readonly kind: "attach" | "view";
959
1131
  readonly status: ViewStatus;
960
1132
  /** false when it is not drawn on this device, failed, or was destroyed. */
961
1133
  readonly enabled: boolean;
@@ -1039,16 +1211,8 @@ export interface ScreenPoint {
1039
1211
  visible: boolean;
1040
1212
  }
1041
1213
 
1042
- /** Pure helpers: Umber.math, or named imports from the npm package. `frame` = the canvas box in viewport px (default: the viewport). */
1214
+ /** Pure helpers: Umber.math, or named imports from the npm package. */
1043
1215
  export interface UmberMath {
1044
- /** CSS px per world unit at `distance` (default: the camera's distance to z = 0) on a picture `heightPx` tall (default: the viewport). */
1045
- pxPerWorld(camera: CameraLike, distance?: number, heightPx?: number): number;
1046
- /** Aim the camera so it sees exactly `size` at z = 0, `unit` CSS px per world unit (default 1). */
1047
- fitCamera<C extends CameraLike>(camera: C, size: { width: number; height: number }, unit?: number): C;
1048
- /** A DOM rect's centre on the plane z (default 0) and its size there; writes x, y, z into `out`. */
1049
- rectToWorld(rect: RectLike, camera: CameraLike, out?: Partial<Vec3Like> | null, options?: { z?: number; frame?: RectLike }): WorldBox;
1050
- /** A world point in viewport CSS px. */
1051
- worldToRect(point: Vec3Like, camera: CameraLike, frame?: RectLike): ScreenPoint;
1052
1216
  /** Lerp that feels the same at 60, 120 and 144 Hz: damp(current, target, 0.1, f.dt). */
1053
1217
  damp(current: number, target: number, amount: number, dt: number): number;
1054
1218
  clamp(v: number, min?: number, max?: number): number;
@@ -1057,136 +1221,170 @@ export interface UmberMath {
1057
1221
  /** GLSL's smoothstep: 0 below edge0, 1 above edge1, smooth between. */
1058
1222
  smoothstep(edge0: number, edge1: number, x: number): number;
1059
1223
  /**
1060
- * 0..1 as a rect scrolls from start to end, written like gl.progress().
1224
+ * 0..1 as a rect scrolls from start to end, written like umber.progress().
1061
1225
  * @example rectProgress(el.getBoundingClientRect(), "top bottom", "bottom top")
1062
1226
  */
1063
- rectProgress(rect: { top?: number; y?: number; height: number }, start?: string, end?: string, viewportHeight?: number): number;
1227
+ rectProgress(
1228
+ rect: { top?: number; y?: number; height: number },
1229
+ start?: string,
1230
+ end?: string,
1231
+ viewportHeight?: number,
1232
+ ): number;
1064
1233
  }
1065
1234
 
1066
- /** What createGL() returns. */
1067
- export interface GL {
1235
+ /** umber.on(name, fn): what each event hands fn. Each but "frame" and "step" also goes to document as a DOM event, "umber:<name>" (payload in detail). */
1236
+ export interface UmberEvents {
1237
+ /** Every frame the loop runs (umber.on("frame") adds fn to the loop). */
1238
+ frame: Frame;
1239
+ /** Every frame the loop runs, first: before Umber reads the page (umber.on("step") adds fn to the loop). */
1240
+ step: Frame;
1241
+ /** GL draws this page's [data-umber] elements: the engine. */
1242
+ ready: Umber;
1243
+ /** The WebGL context was lost. */
1244
+ lost: undefined;
1245
+ /** The WebGL context is back. */
1246
+ restored: undefined;
1247
+ /** umber.destroy(): the engine is gone. */
1248
+ destroy: undefined;
1249
+ /** The roots of the subtrees that entered the page (a router's new page), once per frame; <html> on the first scan. */
1250
+ added: Element[];
1251
+ /**
1252
+ * GL is off for this visit, from the start (a device it skips, ?umber=off) or later (a new
1253
+ * page with data-umber-disable): `reason` is umber.reason. For the site's own analytics.
1254
+ */
1255
+ off: { reason: UmberReason };
1256
+ /**
1257
+ * A plane shows its DOM instead of GL: `reason` is the warning's words (what GL can't draw,
1258
+ * or GL text that stays DOM text), or null when something failed (a picture or video that
1259
+ * could not load, a shader that did not compile: the console says why).
1260
+ */
1261
+ fallback: { el: Element; reason: string | null };
1262
+ }
1263
+
1264
+ /** What createUmber() returns. */
1265
+ export interface Umber {
1068
1266
  readonly version: string;
1069
- /** true once GL draws this page's [data-gl] elements; false when GL is off or the page has none. */
1267
+ /** true once GL draws this page's [data-umber] elements; false when GL is off or the page has none. */
1070
1268
  readonly ready: Promise<boolean>;
1071
1269
  readonly enabled: boolean;
1072
- readonly reason: GLReason | null;
1270
+ readonly reason: UmberReason | null;
1073
1271
  readonly destroyed: boolean;
1074
1272
  /** Smoothed scroll velocity, roughly -1..1. */
1075
1273
  readonly velocity: Signal;
1076
1274
  /**
1077
1275
  * The pointer: { value: [x, y] } viewport px, velocity.value [vx, vy] px/s. Its passive
1078
1276
  * listeners attach the first time it is read. Usable as a uniform.
1079
- * @example gl.effect("lens", { uniforms: { uPointer: gl.pointer }, fragment: { ... } })
1277
+ * @example umber.effect("lens", { uniforms: { uPointer: umber.pointer }, fragment: { ... } })
1080
1278
  */
1081
1279
  readonly pointer: PointerSignal;
1082
1280
  /**
1083
- * "ready" | "lost" | "restored" | "destroy", or "frame" (adds fn to the loop). Returns off().
1084
- * A "frame" callback keeps the loop running every frame; { always: false } only rides
1085
- * along on frames Umber runs anyway. The four state events are also sent on document as
1086
- * DOM events (umber:ready, umber:lost, umber:restored, umber:destroy; payload in detail).
1087
- * @example const off = gl.on("frame", (f) => { mesh.rotation.y += f.dt; }, { phase: "update" });
1281
+ * An event (UmberEvents says what fn gets), or "frame" or "step": fn joins the loop.
1282
+ * Returns off(). A "frame" callback keeps the loop running every frame; { always: false }
1283
+ * only rides along on frames Umber runs anyway. "step" is the place to step a scroller of
1284
+ * your own: it runs every frame before Umber reads the page, and Umber measures and draws
1285
+ * only in the frames it moved the page in. The other events are also sent on document as
1286
+ * DOM events (umber:ready, umber:off...; payload in detail).
1287
+ * @example const off = umber.on("frame", (f) => { mesh.rotation.y += f.dt; }, { phase: "update" });
1288
+ * @example umber.on("step", (f) => scroller.step(f.dt));
1289
+ * @example umber.on("fallback", ({ el, reason }) => analytics.track("umber-fallback", { reason }));
1088
1290
  * @example document.addEventListener("umber:ready", (e) => console.log(e.detail));
1089
1291
  */
1090
- on(name: "frame", fn: (frame: Frame) => void, opts?: { phase?: TickPhase; order?: number; always?: boolean }): () => void;
1091
- on(name: "ready" | "lost" | "restored" | "destroy", fn: (payload?: any) => void): () => void;
1092
- /** The roots of the subtrees that entered the page (a router's new page), once per frame; <html> on the first scan. */
1093
- on(name: "added", fn: (roots: Element[]) => void): () => void;
1094
- /**
1095
- * GL is off for this visit, from the start (a device it skips, ?umber=off) or later (a new
1096
- * page with data-gl-disable): `reason` is gl.reason. Also on document as "umber:off". For
1097
- * the site's own analytics.
1098
- */
1099
- on(name: "off", fn: (e: { reason: GLReason }) => void): () => void;
1100
- /**
1101
- * A plane shows its DOM instead of GL: `reason` is the warning's words (what GL can't draw,
1102
- * or GL text that stays DOM text), or null when something failed (a picture or video that
1103
- * could not load, a shader that did not compile: the console says why). Also on document
1104
- * as "umber:fallback".
1105
- */
1106
- on(name: "fallback", fn: (e: { el: Element; reason: string | null }) => void): () => void;
1107
- off(name: string, fn: (payload?: any) => void): void;
1108
- effect(name: string, def: EffectDef): void;
1109
- shader(name: string, def: ShaderDef): void;
1110
- layer(name: string, def: LayerDef): void;
1292
+ on(name: "frame", fn: (frame: Frame, off: () => void) => void, opts?: FrameOptions): () => void;
1293
+ on(name: "step", fn: (frame: Frame, off: () => void) => void, opts?: StepOptions): () => void;
1294
+ on<E extends keyof UmberEvents>(name: E, fn: (payload: UmberEvents[E]) => void): () => void;
1295
+ off(name: "frame" | "step", fn: (frame: Frame, off: () => void) => void): void;
1296
+ off<E extends keyof UmberEvents>(name: E, fn: (payload: UmberEvents[E]) => void): void;
1297
+ /** `O`: the option defaults, which type ctx.options in setup() and update(). */
1298
+ effect<O extends OptionDefaults>(name: string, def: EffectDef<O>): void;
1299
+ shader<O extends OptionDefaults>(name: string, def: ShaderDef<O>): void;
1300
+ /** `S`: what the layer keeps in ctx.state: umber.layer<{ speed: number }, { scene: THREE.Scene }>("discs", { ... }). */
1301
+ layer<O extends OptionDefaults, S extends object = Record<string, unknown>>(name: string, def: LayerDef<O, S>): void;
1111
1302
  /**
1112
1303
  * A named piece of GLSL an effect pulls in with a line of its own in any slot:
1113
1304
  * #include "name". Only included chunks are compiled, once per program, after Umber's
1114
1305
  * helpers and before the effects' heads; a chunk may include others (added first) and is
1115
1306
  * never renamed. Defined again: the planes using it are rebuilt. An element whose effect
1116
1307
  * includes an unknown name shows its DOM (one [umber] warning) until it is defined.
1117
- * @example gl.chunk("sdf", "float sdCircle(vec2 p, float r) { return length(p) - r; }")
1118
- * @example gl.effect("ring", { fragment: { head: '#include "sdf"', alpha: "alpha *= step(sdCircle(uv - 0.5, 0.4), 0.0);" } })
1308
+ * @example umber.chunk("sdf", "float sdCircle(vec2 p, float r) { return length(p) - r; }")
1309
+ * @example umber.effect("ring", { fragment: { head: '#include "sdf"', alpha: "alpha *= step(sdCircle(uv - 0.5, 0.4), 0.0);" } })
1119
1310
  */
1120
1311
  chunk(name: string, glsl: string): void;
1121
1312
  /**
1122
1313
  * Use an optional module (before or after GL loads). A module script does this itself.
1123
- * @example gl.use(Scrub, { cacheMB: 128 })
1314
+ * @example umber.use(Scrub, { cacheMB: 128 })
1124
1315
  */
1125
- use(module: UmberModule, options?: Record<string, unknown>): GL;
1316
+ use(module: UmberModule, options?: Record<string, unknown>): Umber;
1126
1317
  /**
1127
1318
  * Whether this page's domain is on an Umber licence (the domains listed at occluze.com).
1128
- * Asked once per page, by GL or by a module that needs it (gl.scroll, gl.router: they stay
1129
- * native until the answer is yes). Yes on your own computer (localhost, *.test), and when
1130
- * the check can't be reached.
1319
+ * Asked once per page, by GL or any add-on, and nothing waits
1320
+ * for it: Umber runs at once, and a site that isn't licensed runs with a small Occluze badge.
1321
+ * Yes on your own computer and network (localhost, *.localhost, *.test, a private IP address); no when the check can't be reached:
1322
+ * only a clear yes counts. A site Occluze blocked loses GL (umber.reason "blocked"), as does a page
1323
+ * that keeps removing or hiding the badge.
1131
1324
  */
1132
1325
  licensed(): Promise<boolean>;
1133
- /** gl.licensed()'s answer once it is in; null while it is asked (or before anything asked). */
1326
+ /** umber.licensed()'s answer once it is in; null while it is asked (or before anything asked). */
1134
1327
  readonly licence: boolean | null;
1135
1328
  /**
1136
1329
  * A plane from code: writes the attributes `options` stand for and builds the plane
1137
1330
  * (now when GL is loaded). Resolves with the plane, or null when GL is off. An element
1138
- * with data-gl already resolves with its own plane.
1139
- * @example const plane = await gl.add(img, { effects: ["dissolve"], options: { dissolve: { trigger: "manual" } } })
1331
+ * with data-umber already resolves with its own plane.
1332
+ * @example const plane = await umber.add(img, { effects: ["dissolve"], options: { dissolve: { trigger: "manual" } } })
1140
1333
  */
1141
1334
  add(el: string | Element, options?: AddOptions): Promise<Plane | null>;
1142
1335
  /**
1143
- * Record every Umber object made inside fn (planes from gl.add, views, trackers,
1336
+ * Record every Umber object made inside fn (planes from umber.add, views, trackers,
1144
1337
  * progress signals, frame callbacks, events, nextFrame, definitions, nested scopes,
1145
- * targets, snapshots, sims, brushes, gl.leave, and what a module's calls make: gl.drag,
1146
- * gl.texture...); scope.revert() undoes them all. Selector strings resolve inside `container`.
1147
- * @example const scope = gl.scope(() => { gl.add(".card img", { effects: ["lens"] }); }, card); scope.revert();
1338
+ * targets, snapshots, sims, brushes, umber.leave, and what a module's calls make: umber.drag,
1339
+ * umber.texture...); scope.revert() undoes them all. Selector strings resolve inside `container`.
1340
+ * @example const scope = umber.scope(() => { umber.add(".card img", { effects: ["lens"] }); }, card); scope.revert();
1148
1341
  */
1149
1342
  scope(fn?: (scope: Scope) => unknown, container?: string | Element | null): Scope;
1150
1343
  /**
1151
- * A live 0..1 as el scrolls from `start` to `end`, from the measure phase (native
1152
- * scroll, a scroll container or Lenis alike; also with GL off). Usable as a uniform.
1344
+ * A live 0..1 as el scrolls from `start` to `end`, from the measure phase (the window,
1345
+ * a scroll container, under any scroller; also with GL off). Usable as a uniform.
1153
1346
  * Ends when el leaves the page.
1154
- * @example gl.effect("story", { uniforms: { uStory: gl.progress(".story", { start: "top top", end: "bottom bottom" }) } })
1347
+ * @example umber.effect("story", { uniforms: { uStory: umber.progress(".story", { start: "top top", end: "bottom bottom" }) } })
1155
1348
  */
1156
1349
  progress(el: string | Element, options?: ProgressOptions): ProgressSignal;
1157
1350
  /** fn(frame) once, on the next frame (update phase unless `phase`). Returns a cancel. */
1158
1351
  nextFrame(fn: (frame: Frame) => void, opts?: { phase?: TickPhase; order?: number }): () => void;
1159
- /** Look for [data-gl] in root now (normally automatic). */
1352
+ /** Look for [data-umber] in root now (normally automatic). */
1160
1353
  scan(root?: ParentNode): void;
1161
1354
  /** Destroy planes whose element left the page (normally automatic). */
1162
1355
  prune(): void;
1163
- /** gl.destroy(): the whole engine. gl.destroy(el): that element's plane only. */
1164
- destroy(el?: Element): void;
1356
+ /** umber.destroy(): the whole engine. umber.destroy(el): that element's plane only (null, a selector that found nothing: nothing, with a warning). */
1357
+ destroy(el?: Element | null): void;
1165
1358
  /** Measure every plane (or el's) again on the next frame, and read its effect options again (a CSSOM change, an option attribute set from code). */
1166
1359
  invalidate(el?: Element): void;
1167
1360
  /** Measure every visible plane every frame: true, false, or for `seconds`. */
1168
1361
  live(on: boolean | number): void;
1169
1362
  wake(frames?: number): void;
1363
+ /** GL lets the DOM show and holds its planes until resume(). umber.loop.pause() stops the clock instead. */
1170
1364
  pause(): void;
1171
1365
  resume(): void;
1366
+ /**
1367
+ * Umber's clock: pause(), play() and restart() every frame callback at once (the page's
1368
+ * own loops too, with patch), its measured fps, and a profiler.
1369
+ * @example umber.loop.pause();
1370
+ */
1371
+ readonly loop: Loop;
1172
1372
  plane(el: Element | null | undefined): Plane | null;
1173
1373
  /**
1174
1374
  * Print one plane to the console (kind, source, tier, effects, uniforms, program) with
1175
1375
  * every reason it is not drawn, and resolve with the same report. An element inside a
1176
- * plane (the <img> in a data-gl wrapper) reports that plane. null when nothing matches.
1376
+ * plane (the <img> in a data-umber wrapper) reports that plane. null when nothing matches.
1177
1377
  * Async: what it reads comes with chunks/inspect.js, fetched on the first call.
1178
- * @example const report = await gl.inspect(".hero img")
1378
+ * @example const report = await umber.inspect(".hero img")
1179
1379
  */
1180
1380
  inspect(el: string | Element): Promise<InspectReport | null>;
1181
1381
  planes(container?: ParentNode): Plane[];
1182
1382
  /** Hold every play back. Returns release(delaySeconds?); hold(promise) releases when it settles. */
1183
1383
  hold(until?: PromiseLike<unknown>): (delay?: number) => void;
1184
- /** One frame from your own loop (with loop: false). time in ms, like requestAnimationFrame. */
1185
- render(time?: number): void;
1186
1384
  /**
1187
1385
  * A page change, for any router: call it in the hook where a change starts, and the
1188
1386
  * function it returns in the hook where it is done. Plays are held and planes measured
1189
- * every frame until then, data-gl-id images on screen are noted to fly, and an element
1387
+ * every frame until then, data-umber-id images on screen are noted to fly, and an element
1190
1388
  * with a view-transition-name shows its DOM (the browser snapshots it). Optional:
1191
1389
  * planes, swaps and flights also work without it. A second call while one runs gives it
1192
1390
  * the next page and returns the same end. Ends by itself after 8 s (with a warning).
@@ -1194,73 +1392,83 @@ export interface GL {
1194
1392
  * next: the next page when the router has it (HTML, a parsed Document, its container,
1195
1393
  * or a promise of one): a matching image freezes at once instead of fading with its page.
1196
1394
  *
1395
+ * options: { leaving } names the container that goes while both pages are in the
1396
+ * document (GL draws none of it from then on: its elements show their DOM); { timeout }
1397
+ * gives a change more than 8 s.
1398
+ *
1197
1399
  * end(after?): after = seconds before plays start, or a promise (a View Transition's
1198
1400
  * `finished`). Resolves once the image landed and the new page's planes on screen draw
1199
1401
  * (4 s at most), so a router hook can await it.
1200
1402
  * @example let end = () => {};
1201
- * swup.hooks.on("visit:start", () => (end = gl.transition()));
1202
- * swup.hooks.on("page:load", (visit, { page }) => gl.transition(page.html)); // Swup 4
1203
- * swup.hooks.on("visit:end", () => end());
1403
+ * router.on("start", () => (end = umber.transition()));
1404
+ * router.on("loaded", (page) => umber.transition(page.html));
1405
+ * router.on("end", () => end());
1406
+ * @example umber.transition(next.container, { leaving: current.container, timeout: 20 });
1204
1407
  */
1205
- transition(next?: NextPage): (after?: number | PromiseLike<unknown>) => Promise<void>;
1408
+ transition(next?: NextPage, options?: TransitionOptions): (after?: number | PromiseLike<unknown>) => Promise<void>;
1206
1409
  /**
1207
1410
  * The page-change look (chunks/fx.js): on every page change, a copy of the old page's
1208
1411
  * GL is laid over the new page and your GLSL takes it away. Define
1209
1412
  * `vec4 leave(vec2 uv)` ((0,0) = top left; premultiplied in and out); prev(uv) is the
1210
1413
  * old page, next(uv) the new one (calling it makes leave() replace the canvas instead
1211
- * of drawing over it), uProgress runs 0 -> 1 from gl.transition()'s end() (or from the
1212
- * swap, with no gl.transition()). GL content only: the DOM is the router's. Copies are
1213
- * taken only while a change may start (gl.transition(), a same-origin link pressed, a
1214
- * back / forward), from frames the page draws anyway. null turns it off.
1215
- * @example gl.leave("vec4 leave(vec2 uv) { return prev(uv) * step(uProgress, uv.y); }", { duration: 0.9 });
1414
+ * of drawing over it), uProgress runs 0 -> 1 from umber.transition()'s end() (or from the
1415
+ * swap, with no umber.transition()). GL content only: the DOM is the router's. Copies are
1416
+ * taken only while a change may start (umber.transition(), a same-origin link pressed, a
1417
+ * back / forward), from frames the page draws anyway. null turns it off. Resolves (with
1418
+ * null) once it is set, or at once when GL is off.
1419
+ * @example umber.leave("vec4 leave(vec2 uv) { return prev(uv) * step(uProgress, uv.y); }", { duration: 0.9 });
1216
1420
  */
1217
- leave(glsl: string | null, options?: LeaveOptions): Promise<void>;
1421
+ leave(glsl: string | null, options?: LeaveOptions): Promise<null>;
1218
1422
  /**
1219
1423
  * A same-page layout change, flown on the GPU (chunks/flip.js): the GL elements inside
1220
1424
  * `els` are noted where they are drawn, `change()` runs (at once, before this returns),
1221
1425
  * and each flies from its old rect and corners to its new ones. The DOM jumps; only
1222
1426
  * the GL copies move. Resolves once all landed. Without GL, change() simply runs.
1223
- * @example await gl.flip(".card", () => grid.classList.toggle("is-list"), { duration: 0.8, stagger: 0.03 });
1427
+ * @example await umber.flip(".card", () => grid.classList.toggle("is-list"), { duration: 0.8, stagger: 0.03 });
1224
1428
  */
1225
1429
  flip(els: string | Element | ArrayLike<Element>, change?: () => void, options?: FlipOptions): Promise<void>;
1226
1430
  /**
1227
- * The lower-level parts of gl.transition() for data-gl-id flights. capture(next): a
1431
+ * The lower-level parts of umber.transition() for data-umber-id flights. capture(next): a
1228
1432
  * navigation starts; when the next page is known the matching image freezes where it is
1229
1433
  * ("" or nothing = not known yet). settle(): the swap is done.
1230
- * @example barba.hooks.before((data) => gl.morph.capture(data.next.html)); barba.hooks.after(() => gl.morph.settle());
1434
+ * @example router.on("leave", (next) => umber.morph.capture(next.html)); router.on("done", () => umber.morph.settle());
1231
1435
  */
1232
1436
  morph: { capture(next?: NextPage): void; settle(): void };
1233
1437
  /** Where an element is, every frame, without WebGL (works with GL off). Ends when el leaves the page. */
1234
1438
  track(el: string | Element, options?: TrackOptions): Tracker;
1235
1439
  /**
1236
- * Your three.js scene in its own canvas (the drop-in mode). Umber sizes the renderer,
1237
- * draws only while el is on screen and something asked, and cleans up when el leaves.
1238
- * @example gl.attach(el, { renderer, scene, camera, devices: "all", animate: (f) => { mesh.rotation.y += f.dt; return true; } })
1440
+ * A scene drawn into Umber's own canvas, next to the DOM planes, with the one
1441
+ * renderer from umber.renderer(THREE). Clipped to el, fades with it, goes when el leaves.
1442
+ * @example const renderer = await umber.renderer(THREE); umber.view(el, { scene, camera });
1239
1443
  */
1240
- attach(el: string | Element, options: AttachOptions): View;
1444
+ view<S, C extends ViewCameraLike | undefined, R extends SharedRendererLike = SharedRendererLike>(
1445
+ el: string | Element,
1446
+ options?: SharedViewOptions<S, C, R>,
1447
+ ): View;
1241
1448
  /**
1242
- * Advanced: a scene drawn into Umber's own canvas, next to the DOM planes, with the one
1243
- * renderer from gl.renderer(THREE). Clipped to el, fades with it, goes when el leaves.
1244
- * @example const renderer = await gl.renderer(THREE); gl.view(el, { scene, camera });
1449
+ * Advanced: the one THREE.WebGLRenderer on Umber's canvas for the whole visit (compiled
1450
+ * programs survive page changes), made with `params` plus Umber's canvas and context.
1451
+ * Resolves with the renderer three's module makes; null when GL is off.
1245
1452
  */
1246
- view(el: string | Element, options?: SharedViewOptions): View;
1247
- /** Advanced: the one THREE.WebGLRenderer on Umber's canvas for the whole visit (compiled programs survive page changes). null when GL is off. */
1248
- renderer(three: any, params?: Record<string, unknown>): Promise<any>;
1453
+ renderer<R extends SharedRendererLike>(
1454
+ three: ThreeModuleLike<R>,
1455
+ params?: Record<string, unknown>,
1456
+ ): Promise<R | null>;
1249
1457
  /**
1250
1458
  * An offscreen render target on Umber's context (its own file, chunks/fx.js, fetched on
1251
1459
  * the first call). Draw into it with target.draw(glsl), read it in any effect as a
1252
1460
  * uniform, or hand target.texture to three.js on Umber's canvas. Holds premultiplied
1253
1461
  * alpha; "half" (RGBA16F) by default where the GPU can render to it. null when GL is off.
1254
- * @example const t = await gl.target({ width: 512, height: 512 });
1462
+ * @example const t = await umber.target({ width: 512, height: 512 });
1255
1463
  * t.draw("vec4 color(vec2 uv) { return vec4(uv, 0.5, 1.0); }");
1256
- * gl.effect("show", { uniforms: { uPattern: t }, fragment: { color: "color = texture(uPattern, uv);" } });
1464
+ * umber.effect("show", { uniforms: { uPattern: t }, fragment: { color: "color = texture(uPattern, uv);" } });
1257
1465
  */
1258
1466
  target(options?: TargetOptions): Promise<Target | null>;
1259
1467
  /**
1260
1468
  * A still copy of what one plane draws right now (its effects included, its parents'
1261
1469
  * cuts not), as a target: device px, "u8". Waits up to 5 s for the plane to be able to
1262
1470
  * draw. null when there is no plane, GL is off, or it never drew.
1263
- * @example const still = await gl.snapshot(".hero img"); gl.effect("echo", { uniforms: { uStill: still }, ... });
1471
+ * @example const still = await umber.snapshot(".hero img"); umber.effect("echo", { uniforms: { uStill: still }, ... });
1264
1472
  */
1265
1473
  snapshot(el: string | Element | Plane): Promise<Target | null>;
1266
1474
  /**
@@ -1269,9 +1477,9 @@ export interface GL {
1269
1477
  * screen. It steps after an input (a brush, the pointer, set(), wake()) and sleeps once
1270
1478
  * settled, so a still page asks for no frames. Read it in any effect as a uniform.
1271
1479
  * null when GL is off.
1272
- * @example const sim = await gl.sim({ size: 128, next: "vec4 next(vec2 uv) { return texture(state, uv) * 0.95; }" });
1273
- * gl.brush(sim, { radius: 40 }); // paints where the pointer goes
1274
- * gl.effect("ink", { uniforms: { uInk: sim }, fragment: { color: "color.rgb += texture(uInk, screenUv()).r;" } });
1480
+ * @example const sim = await umber.sim({ size: 128, next: "vec4 next(vec2 uv) { return texture(state, uv) * 0.95; }" });
1481
+ * umber.brush(sim, { radius: 40 }); // paints where the pointer goes
1482
+ * umber.effect("ink", { uniforms: { uInk: sim }, fragment: { color: "color.rgb += texture(uInk, screenUv()).r;" } });
1275
1483
  */
1276
1484
  sim(options: SimOptions): Promise<Sim | null>;
1277
1485
  /**
@@ -1279,59 +1487,122 @@ export interface GL {
1279
1487
  * (`vec4 f = texture(uFlow, screenUv()); vec2 push = (f.rg * 2.0 - 1.0) * f.a;`). Made on
1280
1488
  * the first plane that reads uFlow, or here. Called again with options, it changes them.
1281
1489
  * null when GL is off, or where half-float targets can't be rendered (uFlow then uses
1282
- * the input module's gl.touch(), when it is loaded).
1490
+ * the input module's umber.touch(), when it is loaded).
1283
1491
  */
1284
1492
  flow(options?: FlowOptions): Promise<Sim | null>;
1285
1493
  /**
1286
1494
  * Soft round stamps into one field of a sim: along the pointer's path while it moves,
1287
1495
  * and wherever brush.paint(x, y) says. null when `sim` is null.
1288
- * @example const dye = gl.brush(sim, { field: "dye", radius: 30, color: [1, 0.4, 0.2, 1] });
1496
+ * @example const dye = umber.brush(sim, { field: "dye", radius: 30, color: [1, 0.4, 0.2, 1] });
1289
1497
  */
1290
1498
  brush(sim: Sim | null, options?: BrushOptions): Brush | null;
1291
1499
  /**
1292
1500
  * Get the NEXT page ready before it is on the page (its own file, chunks/warm.js): the
1293
- * images its [data-gl] elements show fetched, decoded and on the GPU (keyed the way the
1294
- * element will ask: data-gl-src, or the srcset candidate the browser will pick), their
1295
- * programs compiled, and each drawn once offscreen. When the elements arrive they claim
1296
- * all of it: the first frame does no work. Never blocks the page (uploads go in idle
1297
- * moments) and never rejects. The promise is also the progress: p.value 0 -> 1, a Signal
1298
- * (fn(v) hears each step). With GL off it resolves at once with value 1.
1501
+ * images its first screen's [data-umber] elements show fetched, decoded and on the GPU
1502
+ * (keyed the way the element will ask: data-umber-src, or the srcset candidate the browser
1503
+ * will pick), every element's program compiled, and each drawn once offscreen. When the
1504
+ * elements arrive they claim all of it: the first frame does no work. The first screen is
1505
+ * the pictures that come first in the page, until their boxes (sizes, width and height)
1506
+ * would fill the screen; the rest load as they come near, as on any page. Nothing is put
1507
+ * on the GPU past its memory budget. Never blocks the page (uploads go in idle moments)
1508
+ * and never rejects. The promise is also the progress: p.value 0 -> 1, a Signal (fn(v)
1509
+ * hears each step). With GL off it resolves at once with value 1.
1299
1510
  *
1300
1511
  * what: image URLs, a page URL (fetched and read), an element or container (detached is
1301
- * fine), a parsed Document, Barba's data.next ({ container } / { html } / { url }), or a
1302
- * list of these. { hover: true | "selector" }: from now on, a link's page is preloaded
1512
+ * fine), a parsed Document, a router's next page ({ container } / { html } / { url }), or
1513
+ * a list of these. { hover: true | "selector" }: from now on, a link's page is preloaded
1303
1514
  * when the pointer slows down over it (off on Save-Data; { hover: false } stops it).
1304
- * @example barba.hooks.leave((data) => { gl.preload(data.next.url.href); }); // braces: Barba waits for a returned promise
1305
- * @example gl.preload({ hover: "a.project-link" });
1515
+ * @example router.on("leave", (next) => { umber.preload(next.url); });
1516
+ * @example umber.preload({ hover: "a.project-link" });
1306
1517
  */
1307
- preload(what: PreloadSource | PreloadSource[] | { hover: boolean | string }, fn?: (progress: number) => void): Loading;
1518
+ preload(
1519
+ what: PreloadSource | PreloadSource[] | { hover: boolean | string },
1520
+ fn?: (progress: number) => void,
1521
+ ): Loading;
1308
1522
  /**
1309
1523
  * Get THIS page ready (chunks/warm.js): every plane in root (default: the page) loads its
1310
1524
  * image or text even when far from the screen, compiles, and is drawn once offscreen.
1311
1525
  * Resolves when all of them can draw (each plane waits 5 s at most, once chunks/fx.js is in); p.value is a 0..1 progress for a
1312
1526
  * preloader. With GL off it resolves at once with value 1.
1313
- * @example const p = gl.warm(null, (v) => (bar.style.scale = `${v} 1`)); await p; loader.remove();
1527
+ * @example const p = umber.warm(null, (v) => (bar.style.scale = `${v} 1`)); await p; loader.remove();
1314
1528
  */
1315
1529
  warm(root?: string | ParentNode | null, fn?: (progress: number) => void): Loading;
1316
1530
  /**
1317
- * The data-gl-placeholder string for an image (about 50 characters: a preview 6 cells on
1531
+ * The data-umber-placeholder string for an image (about 50 characters: a preview 6 cells on
1318
1532
  * its long side, 4 bits per channel). Run it once (the console will do) and paste the string into the
1319
1533
  * element's attribute. null when GL is off or the file can't be read.
1320
- * @example await gl.placeholder("/img/dunes.jpg") // "UF..."
1534
+ * @example await umber.placeholder("/img/dunes.jpg") // "UF..."
1321
1535
  */
1322
1536
  placeholder(src: string | Element): Promise<string | null>;
1323
- readonly info: Record<string, unknown>;
1537
+ readonly info: UmberInfo;
1324
1538
  readonly canvas: HTMLCanvasElement | null;
1325
1539
  readonly context: WebGL2RenderingContext | null;
1326
1540
  }
1327
1541
 
1328
- /** What gl.preload() takes: an image or page URL, an element or container, a parsed Document, or a router's next page. */
1329
- export type PreloadSource = string | URL | ParentNode | { container?: ParentNode; html?: string; url?: string | { href?: string } } | null | undefined;
1542
+ /** umber.info.gpu: the device's GPU level, read once when GL starts. */
1543
+ export interface GpuInfo {
1544
+ /** 0 (software) to 5 (strong desktop GPU). */
1545
+ level: number;
1546
+ tier: "high" | "mid" | "low";
1547
+ mobile: boolean;
1548
+ renderer: string;
1549
+ /** "rule: <what matched>", "default" or "url" (?umber-gpu). */
1550
+ reason: string;
1551
+ maxTexture: number;
1552
+ /** Max bytes of image textures kept on the GPU: the one in use now (a desktop's grows the first time a page fills it). */
1553
+ textureBudget: number;
1554
+ /** Above this CSS width the canvas DPR is cut (createUmber dpr aside); Infinity: never. */
1555
+ wide: number;
1556
+ }
1557
+
1558
+ /** umber.info while GL runs: what the last frame did, and what the GPU holds. */
1559
+ export interface UmberStats {
1560
+ state:
1561
+ "dormant" | "asleep" | "idle" | "active" | "paused" | "off (canvas host)" | "off (context lost)" | "off (error)";
1562
+ backend: "webgl2";
1563
+ tier: "high" | "mid" | "low";
1564
+ /** null until it is read. */
1565
+ gpu: GpuInfo | null;
1566
+ fps: number;
1567
+ frameMs: number;
1568
+ renders: number;
1569
+ skipped: number;
1570
+ rendersPerSec: number;
1571
+ draws: number;
1572
+ planes: number;
1573
+ visible: number;
1574
+ textures: number;
1575
+ textureMB: number;
1576
+ gpuMB: number;
1577
+ /** What every render target holds on the GPU (absent until chunks/fx.js is here). */
1578
+ targetMB?: number;
1579
+ uploads: number;
1580
+ programs: number;
1581
+ /** Why the loop keeps drawing; [] once it sleeps. */
1582
+ busy: string[];
1583
+ dpr: number;
1584
+ scale: number;
1585
+ width: number;
1586
+ height: number;
1587
+ }
1588
+
1589
+ /** umber.info: UmberStats while GL runs; only its state before GL started; once GL went off, the last numbers it had. */
1590
+ export type UmberInfo =
1591
+ UmberStats | (Partial<Omit<UmberStats, "state">> & { state: "dormant" | `off (${UmberReason})` });
1592
+
1593
+ /** What umber.preload() takes: an image or page URL, an element or container, a parsed Document, or a router's next page. */
1594
+ export type PreloadSource =
1595
+ | string
1596
+ | URL
1597
+ | ParentNode
1598
+ | { container?: ParentNode; html?: string; url?: string | { href?: string } }
1599
+ | null
1600
+ | undefined;
1330
1601
 
1331
- /** gl.preload() / gl.warm(): resolves when ready; value is the 0..1 progress (a Signal: usable as a uniform). */
1332
- export type Loading = Promise<void> & Signal<number>;
1602
+ /** umber.preload() / umber.warm(): resolves when ready; value is the 0..1 progress (a Signal: usable as a uniform). */
1603
+ export type Loading = Promise<void> & Signal;
1333
1604
 
1334
- /** gl.leave(glsl, options). */
1605
+ /** umber.leave(glsl, options). */
1335
1606
  export interface LeaveOptions {
1336
1607
  /** Seconds uProgress takes from 0 to 1. @default 1 */
1337
1608
  duration?: number;
@@ -1339,11 +1610,11 @@ export interface LeaveOptions {
1339
1610
  ease?: Ease;
1340
1611
  /** Your own uniforms (a { value } is read every frame). uPrev, uNext and uProgress are Umber's. */
1341
1612
  uniforms?: Record<string, unknown>;
1342
- /** Arm on a pointerdown on a same-origin link and on back / forward, also with no gl.transition(). @default true */
1613
+ /** Arm on a pointerdown on a same-origin link and on back / forward, also with no umber.transition(). @default true */
1343
1614
  links?: boolean;
1344
1615
  }
1345
1616
 
1346
- /** gl.flip(els, change, options) and plane.land(options). */
1617
+ /** umber.flip(els, change, options) and plane.land(options). */
1347
1618
  export interface FlipOptions {
1348
1619
  /** Seconds. @default 0.8 */
1349
1620
  duration?: number;
@@ -1361,7 +1632,7 @@ export interface FreeRect {
1361
1632
  height: number;
1362
1633
  }
1363
1634
 
1364
- /** gl.target(options). Sizes in device px. */
1635
+ /** umber.target(options). Sizes in device px. */
1365
1636
  export interface TargetOptions {
1366
1637
  /** Default: the canvas width (device px). The target never follows the canvas: call resize(). */
1367
1638
  width?: number;
@@ -1388,7 +1659,7 @@ export interface Target {
1388
1659
  /** The first attachment's texture (null once released or while the context is lost). */
1389
1660
  readonly texture: WebGLTexture | null;
1390
1661
  /** Every attachment's texture (MRT). */
1391
- readonly textures: ReadonlyArray<WebGLTexture | null>;
1662
+ readonly textures: readonly (WebGLTexture | null)[];
1392
1663
  /** Its resolved framebuffer (for readPixels, or another library's reads). */
1393
1664
  readonly framebuffer: WebGLFramebuffer | null;
1394
1665
  readonly width: number;
@@ -1404,7 +1675,10 @@ export interface Target {
1404
1675
  * `vec4 color(vec2 uv)` (straight alpha: Umber premultiplies), or its own `void main()`
1405
1676
  * writing `outColor` (premultiplied; more attachments: layout(location = 1) out vec4 ...).
1406
1677
  * Built in: vUv, uSize (device px), uTime. Uniforms are declared for you; a target or a
1407
- * texture holder is a sampler. Drawn again after a resize and a restored context.
1678
+ * texture holder is a sampler, a CSS colour string a vec4, and any other string a picture's
1679
+ * address: a sampler, and the pass is drawn once every picture it reads has loaded. Drawn
1680
+ * again after a resize and a restored context.
1681
+ * @example target.draw("vec4 color(vec2 uv) { return texture(uPortrait, uv); }", { uPortrait: "/img/portrait.webp" });
1408
1682
  */
1409
1683
  draw(glsl: string, uniforms?: Record<string, unknown>): Target;
1410
1684
  /** Transparent again. */
@@ -1415,10 +1689,10 @@ export interface Target {
1415
1689
  release(): void;
1416
1690
  }
1417
1691
 
1418
- /** A size in texels: one number, or one per GPU level 0-5 (gl.info.gpu.level). */
1692
+ /** A size in texels: one number, or one per GPU level 0-5 (umber.info.gpu.level). */
1419
1693
  export type SimSize = number | number[];
1420
1694
 
1421
- /** gl.sim(options). Give `next` (one field, "state") or `fields` + `passes`. */
1695
+ /** umber.sim(options). Give `next` (one field, "state") or `fields` + `passes`. */
1422
1696
  export interface SimOptions {
1423
1697
  /** Texels across (or one per GPU level 0-5). @default 128 */
1424
1698
  size?: SimSize;
@@ -1439,7 +1713,7 @@ export interface SimOptions {
1439
1713
  /** Named fields: each is a sampler of its name in every pass. */
1440
1714
  fields?: Record<string, { size?: SimSize; type?: "u8" | "half" | "float"; init?: string }>;
1441
1715
  /** In order, every step: `next` writes field `into` (its old value still readable); `iterations` per step (or one per GPU level). */
1442
- passes?: Array<{ into: string; next: string; iterations?: number | number[] }>;
1716
+ passes?: { into: string; next: string; iterations?: number | number[] }[];
1443
1717
  /** The field sim.texture is. @default the first */
1444
1718
  output?: string;
1445
1719
  /** Your uniforms for every pass (numbers, arrays, targets, textures). Change them with sim.set(). */
@@ -1479,7 +1753,7 @@ export interface Sim {
1479
1753
  release(): void;
1480
1754
  }
1481
1755
 
1482
- /** gl.brush(sim, options). */
1756
+ /** umber.brush(sim, options). */
1483
1757
  export interface BrushOptions {
1484
1758
  /** The field it paints. @default the first */
1485
1759
  field?: string;
@@ -1501,7 +1775,7 @@ export interface Brush {
1501
1775
  release(): void;
1502
1776
  }
1503
1777
 
1504
- /** gl.flow(options). */
1778
+ /** umber.flow(options). */
1505
1779
  export interface FlowOptions {
1506
1780
  /** Texels across (or one per GPU level 0-5). @default [32, 48, 64, 64, 96, 128] */
1507
1781
  size?: SimSize;
@@ -1516,7 +1790,7 @@ export interface FlowOptions {
1516
1790
  /** window.Umber (the <script> build). */
1517
1791
  export interface UmberGlobal {
1518
1792
  readonly version: string;
1519
- createGL(options?: GLOptions): GL;
1793
+ createUmber(options?: UmberOptions): Umber;
1520
1794
  /** DOM <-> three.js maths and frame-rate-free smoothing. No engine needed. */
1521
1795
  readonly math: UmberMath;
1522
1796
  /** An optional module for the engine on the page and every later one (module scripts call it themselves). */
@@ -1525,8 +1799,7 @@ export interface UmberGlobal {
1525
1799
 
1526
1800
  declare global {
1527
1801
  interface Window {
1528
- Umber: UmberGlobal;
1802
+ /** The npm build's chunk folder, set before createUmber() (createUmber({ base }) wins). umber.js loads from its own folder. */
1529
1803
  UmberConfig?: { base?: string };
1530
1804
  }
1531
- const Umber: UmberGlobal;
1532
1805
  }