ultra-text 1.0.1 → 1.0.2

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 (150) hide show
  1. package/README.md +224 -1002
  2. package/dist/assets/{cpuSdf.worker-xS57yQbP.js → cpuSdf.worker--X1Qpmdp.js} +136 -47
  3. package/dist/assets/cpuSdf.worker--X1Qpmdp.js.map +1 -0
  4. package/dist/atlas/appendAtlas.js +67 -25
  5. package/dist/atlas/appendAtlas.js.map +1 -1
  6. package/dist/atlas/buildAtlas.js +3 -2
  7. package/dist/atlas/buildAtlas.js.map +1 -1
  8. package/dist/atlas/cpuAtlas.d.ts +4 -1
  9. package/dist/atlas/cpuAtlas.js +8 -6
  10. package/dist/atlas/cpuAtlas.js.map +1 -1
  11. package/dist/atlas/cpuSdf.js +152 -40
  12. package/dist/atlas/cpuSdf.js.map +1 -1
  13. package/dist/atlas/cpuWorker.d.ts +5 -3
  14. package/dist/atlas/cpuWorker.js +119 -12
  15. package/dist/atlas/cpuWorker.js.map +1 -1
  16. package/dist/atlas/gpuAtlas.js +100 -276
  17. package/dist/atlas/gpuAtlas.js.map +1 -1
  18. package/dist/atlas/gpuCommon.d.ts +135 -0
  19. package/dist/atlas/gpuCommon.js +223 -0
  20. package/dist/atlas/gpuCommon.js.map +1 -0
  21. package/dist/atlas/jfaWgsl.js +47 -241
  22. package/dist/atlas/jfaWgsl.js.map +1 -1
  23. package/dist/atlas/rasterize.js +103 -58
  24. package/dist/atlas/rasterize.js.map +1 -1
  25. package/dist/atlas/shapeRaster.js +2 -1
  26. package/dist/atlas/shapeRaster.js.map +1 -1
  27. package/dist/atlas/vanillaBounds.d.ts +64 -0
  28. package/dist/atlas/vanillaBounds.js +42 -0
  29. package/dist/atlas/vanillaBounds.js.map +1 -0
  30. package/dist/atlas/vanillaCore.d.ts +100 -0
  31. package/dist/atlas/vanillaCore.js +1012 -0
  32. package/dist/atlas/vanillaCore.js.map +1 -0
  33. package/dist/atlas/vanillaCpuAtlas.d.ts +9 -0
  34. package/dist/atlas/vanillaCpuAtlas.js +87 -0
  35. package/dist/atlas/vanillaCpuAtlas.js.map +1 -0
  36. package/dist/atlas/vanillaExtras.d.ts +8 -0
  37. package/dist/atlas/vanillaExtras.js +166 -0
  38. package/dist/atlas/vanillaExtras.js.map +1 -0
  39. package/dist/atlas/vanillaGpuHelpers.d.ts +232 -0
  40. package/dist/atlas/vanillaGpuHelpers.js +119 -0
  41. package/dist/atlas/vanillaGpuHelpers.js.map +1 -0
  42. package/dist/dom/DomSdf.js +224 -284
  43. package/dist/dom/DomSdf.js.map +1 -1
  44. package/dist/dom/DomSlug.js +75 -151
  45. package/dist/dom/DomSlug.js.map +1 -1
  46. package/dist/dom/domAnalytic.d.ts +54 -0
  47. package/dist/dom/domAnalytic.js +282 -0
  48. package/dist/dom/domAnalytic.js.map +1 -0
  49. package/dist/dom/domExtras.d.ts +27 -0
  50. package/dist/dom/domExtras.js +137 -0
  51. package/dist/dom/domExtras.js.map +1 -0
  52. package/dist/dom/fontCanvas.js +27 -9
  53. package/dist/dom/fontCanvas.js.map +1 -1
  54. package/dist/dom/layoutSignature.js +150 -48
  55. package/dist/dom/layoutSignature.js.map +1 -1
  56. package/dist/dom/pretextLayout.js +55 -13
  57. package/dist/dom/pretextLayout.js.map +1 -1
  58. package/dist/dom/snapshot.js +369 -204
  59. package/dist/dom/snapshot.js.map +1 -1
  60. package/dist/dom/svgCapture.d.ts +8 -1
  61. package/dist/dom/svgCapture.js +75 -1
  62. package/dist/dom/svgCapture.js.map +1 -1
  63. package/dist/dom/tone.js +76 -36
  64. package/dist/dom/tone.js.map +1 -1
  65. package/dist/index.js +4 -3
  66. package/dist/slug/SlugMaterial.d.ts +11 -3
  67. package/dist/slug/SlugMaterial.js +54 -10
  68. package/dist/slug/SlugMaterial.js.map +1 -1
  69. package/dist/slug/coverage.d.ts +16 -12
  70. package/dist/slug/coverage.js +194 -221
  71. package/dist/slug/coverage.js.map +1 -1
  72. package/dist/slug/preprocessCore.d.ts +5 -1
  73. package/dist/slug/preprocessCore.js +118 -87
  74. package/dist/slug/preprocessCore.js.map +1 -1
  75. package/dist/slug/runtime.d.ts +1 -0
  76. package/dist/slug/runtime.js +90 -44
  77. package/dist/slug/runtime.js.map +1 -1
  78. package/dist/slug/standaloneRuntime.d.ts +3 -2
  79. package/dist/slug/standaloneRuntime.js +75 -40
  80. package/dist/slug/standaloneRuntime.js.map +1 -1
  81. package/dist/slug/truetype.js +166 -193
  82. package/dist/slug/truetype.js.map +1 -1
  83. package/dist/slug/vanillaCore.d.ts +340 -0
  84. package/dist/slug/vanillaCore.js +1621 -0
  85. package/dist/slug/vanillaCore.js.map +1 -0
  86. package/dist/slug-vanilla.d.ts +13 -364
  87. package/dist/slug-vanilla.js +5 -1453
  88. package/dist/slug.d.ts +1 -1
  89. package/dist/slug.js +6 -6
  90. package/dist/text/GlyphTextMaterial.d.ts +1 -1
  91. package/dist/text/GlyphTextMaterial.js +5 -5
  92. package/dist/text/GlyphTextMaterial.js.map +1 -1
  93. package/dist/text/SdfTextMaterial.js +7 -5
  94. package/dist/text/SdfTextMaterial.js.map +1 -1
  95. package/dist/text/decorations.js +36 -19
  96. package/dist/text/decorations.js.map +1 -1
  97. package/dist/text/geometry.d.ts +3 -22
  98. package/dist/text/geometryUtils.d.ts +11 -1
  99. package/dist/text/geometryUtils.js +22 -1
  100. package/dist/text/geometryUtils.js.map +1 -1
  101. package/dist/text/glyphGeometry.d.ts +9 -0
  102. package/dist/text/glyphGeometry.js +353 -0
  103. package/dist/text/glyphGeometry.js.map +1 -0
  104. package/dist/text/index.d.ts +2 -1
  105. package/dist/text/rectGeometry.d.ts +13 -0
  106. package/dist/text/rectGeometry.js +97 -0
  107. package/dist/text/rectGeometry.js.map +1 -0
  108. package/dist/text/reflow.d.ts +18 -1
  109. package/dist/text/reflow.js +108 -38
  110. package/dist/text/reflow.js.map +1 -1
  111. package/dist/text/snap.d.ts +1 -0
  112. package/dist/text/snap.js +26 -0
  113. package/dist/text/snap.js.map +1 -0
  114. package/dist/vanilla.d.ts +13 -363
  115. package/dist/vanilla.js +6 -1473
  116. package/dist/windfoil/geometry.d.ts +2 -2
  117. package/dist/windfoil/geometry.js +113 -40
  118. package/dist/windfoil/geometry.js.map +1 -1
  119. package/dist/windfoil/mixed.d.ts +1 -0
  120. package/dist/windfoil/mixed.js +44 -25
  121. package/dist/windfoil/mixed.js.map +1 -1
  122. package/dist/windfoil/preprocess.js +2 -2
  123. package/dist/windfoil/preprocessCore.d.ts +1 -0
  124. package/dist/windfoil/preprocessCore.js +9 -4
  125. package/dist/windfoil/preprocessCore.js.map +1 -1
  126. package/dist/windfoil/runtime.d.ts +3 -1
  127. package/dist/windfoil/runtime.js +62 -40
  128. package/dist/windfoil/runtime.js.map +1 -1
  129. package/dist/windfoil/storage.d.ts +60 -2
  130. package/dist/windfoil/storage.js +142 -6
  131. package/dist/windfoil/storage.js.map +1 -1
  132. package/dist/windfoil/trace/contours.d.ts +5 -0
  133. package/dist/windfoil/trace/contours.js +167 -43
  134. package/dist/windfoil/trace/contours.js.map +1 -1
  135. package/dist/windfoil/trace/fit.d.ts +3 -1
  136. package/dist/windfoil/trace/fit.js +471 -175
  137. package/dist/windfoil/trace/fit.js.map +1 -1
  138. package/dist/windfoil/trace/outline.js +55 -30
  139. package/dist/windfoil/trace/outline.js.map +1 -1
  140. package/dist/windfoil/trace/types.d.ts +10 -0
  141. package/dist/windfoil/tracedOutlines.js +59 -34
  142. package/dist/windfoil/tracedOutlines.js.map +1 -1
  143. package/package.json +11 -11
  144. package/skills/ultra-text/references/three-tsl.md +2 -2
  145. package/skills/ultra-text/references/vanilla-webgpu.md +3 -2
  146. package/dist/assets/cpuSdf.worker-xS57yQbP.js.map +0 -1
  147. package/dist/slug-vanilla.js.map +0 -1
  148. package/dist/text/geometry.js +0 -348
  149. package/dist/text/geometry.js.map +0 -1
  150. package/dist/vanilla.js.map +0 -1
package/README.md CHANGED
@@ -14,59 +14,40 @@
14
14
 
15
15
  [![The ultra-text WebGPU gallery](https://ultra-text.makio.io/og.png)](https://ultra-text.makio.io/)
16
16
 
17
- `ultra-text` measures marked HTML or a styled text string with the browser and returns a retained
18
- `THREE.Group`. The default path bakes a distance-field atlas; the optional experimental
19
- Windfoil path retains quadratic outlines instead.
20
-
21
- - Browser-native layout and line breaking
22
- - Static instanced glyph and rectangle geometry
23
- - GPU SDF baking with an exact CPU fallback, or analytic quadratic outlines
24
- - TSL motion, clipping, antialiasing, and shadow masks
25
- - Text weight [matched to the browser's](#matching-the-browser) own blending, on by default
26
- - Custom TSL fill and vertex hooks, outlines and hard drop shadows on every text backend, and solid
27
- CSS text decorations
28
- - Transactional rebuilds with no DOM reads in the render loop
29
- - Enforced bundle budget: the public entry stays at or under 35 kB min+brotli
30
- (size-limit, excluding Three.js, Pretext, and separately budgeted optional feature chunks)
31
-
32
- The optional CPU builder has a separate 3 kB budget, plus 2.5 kB for its worker asset.
17
+ `ultra-text` measures marked HTML or a CSS-styled string with the browser and returns a retained
18
+ `THREE.Group` (or packed typed arrays via `ultra-text/vanilla`). Default rendering bakes a
19
+ single-channel SDF atlas; experimental `windfoil` and `slug` backends retain quadratic curves.
20
+
21
+ - Browser-native layout and line breaking (`Range`, or lazy Pretext Canvas layout)
22
+ - Retained instanced geometry with zero DOM reads in the render loop
23
+ - Single-pass tiled GPU SDF baking (with exact CPU worker fallback) or analytic quadratic outlines
24
+ - TSL motion, clipping, antialiasing, custom `fill`/`vertex` hooks, `outline`, `dropShadow`,
25
+ solid CSS decorations, and [browser-matched ink weight](#matching-the-browser) (`tone`)
26
+ - Tree-shaken `DomText + Text`: **41.1 kB** min+gzip (**36.6 kB** brotli; Vite build). Enforced
27
+ `size-limit` IIFE budget: **44.1 kB** min+brotli (limit 46 kB, excluding Three.js and lazy chunks),
28
+ plus **3.6 kB** CPU fallback (limit 4.5 kB) and **2.2 kB** worker asset (limit 2.5 kB).
33
29
 
34
30
  > [!NOTE]
35
- > The baked atlas uses a **single-channel SDF** (not MSDF).
36
- > Windfoil is a separate text backend, not an atlas mode. See
37
- > [Limitations](#limitations) before using either path for demanding typography.
31
+ > The SDF atlas is single-channel (not MSDF). Analytic backends (`slug`, `windfoil`) are WebGPU-only
32
+ > and experimental. See [Limitations](#limitations).
38
33
 
39
34
  ## Requirements and install
40
35
 
41
- - ESM only; `require()` is not supported.
42
- - Three.js `WebGPURenderer`; the classic `WebGLRenderer` is not supported.
43
- - Three.js r187. The peer range is `>=0.187.0 <0.188.0`.
44
- - Canvas 2D and the browser font-loading APIs. The default layout engine also needs DOM
45
- `Range`.
46
- - `ResizeObserver` and `MutationObserver` unless `observe: false` is used.
47
-
48
- `atlasMode: 'gpu'` requires a real WebGPU backend. The default `auto` mode can fall back to
49
- the CPU atlas when `WebGPURenderer` is using its WebGL2 backend, or when the WebGPU device
50
- cannot run the GPU passes.
51
- The Windfoil and Slug paths require WebGPU and quadratic font outlines, from an app-supplied
52
- resolver or, without one, traced from the browser's own glyphs. With `fallback: 'sdf'`,
53
- selecting them can instead degrade the whole capture to SDF when WebGPU or an outline is
54
- unavailable.
36
+ - ESM only (`require()` unsupported), Canvas 2D, font-loading APIs, `Range`, and
37
+ `ResizeObserver`/`MutationObserver` (unless `observe: false`).
38
+ - Three.js r187 (`>=0.187.0 <0.188.0`) with `WebGPURenderer` (classic `WebGLRenderer` is
39
+ unsupported). Three-free engines use `ultra-text/vanilla` or `ultra-text/slug-vanilla` (`three`
40
+ optional).
41
+ - `atlasMode: 'auto'` falls back to CPU EDT on WebGL2 or unsupported GPU limits; `windfoil`/`slug`
42
+ require WebGPU unless `fallback: 'sdf'` is set.
55
43
 
56
44
  ```sh
57
45
  npm install ultra-text three@0.187
46
+ npm install --save-dev @types/three@0.187 # TypeScript declarations
58
47
  ```
59
48
 
60
- TypeScript projects also need matching Three.js declarations:
61
-
62
- ```sh
63
- npm install --save-dev @types/three@0.187
64
- ```
65
-
66
- The package has one runtime dependency, `@chenglou/pretext` (`^1.0.0`). It is installed for
67
- every consumer but never loaded eagerly: `collectDomSnapshot` imports the
68
- `@chenglou/pretext/rich-inline` subpath dynamically, only when `layoutEngine: 'pretext'` is
69
- requested, which loads about 38 kB min+brotli more. The default Range engine never touches it.
49
+ `@chenglou/pretext` (`^1.0.0`) is the only runtime dependency, loaded dynamically (~38 kB
50
+ min+brotli) only when `layoutEngine: 'pretext'` is requested.
70
51
 
71
52
  ## Quick start
72
53
 
@@ -136,61 +117,43 @@ scene.remove(text)
136
117
  text.dispose()
137
118
  ```
138
119
 
139
- `css` accepts a property object or a CSS declaration string, such as
140
- `'font-size: 48px; color: #ffcc00; width: 320px'`. Object keys can use camelCase, kebab-case,
141
- or custom properties such as `'--accent'`. Numeric length values become pixels; unitless
142
- properties such as `lineHeight` and `opacity` keep their numeric values. Use strings for
143
- other units, for example `fontSize: '2rem'`.
144
-
145
- `cssClass` applies classes from your app's stylesheets. Supply a space-separated string, an
146
- array such as `['headline', 'accent']`, or a conditional map such as
147
- `{ headline: true, muted: false }`. Sass, SCSS, and Stylus work through stylesheets compiled
148
- by your app's build tool: pass the resulting class names to `cssClass`. Runtime `css` strings
149
- use standard CSS declaration syntax.
150
-
151
- `Text` owns a visually clipped, measurable DOM source whose content is literal text, including
152
- HTML-looking strings. Its source is attached to `document.body` by default; pass a connected
153
- `parent` element to inherit its CSS and match selectors scoped beneath it. The initial build
154
- waits for fonts. The same [CSS capture limitations](#limitations) and `DomText` rendering
155
- options apply, including `observe: false` for manual updates. A `Text` cannot see what your
156
- scene draws behind it: name that colour as `tone: { backdrop }` so light text is weighted for
157
- it; see [Matching the browser](#matching-the-browser).
120
+ `css` accepts a camelCase/kebab-case style object or CSS string (numeric lengths default to `px`;
121
+ unitless properties like `lineHeight`/`opacity` stay numeric; custom properties like `'--accent'`
122
+ and strings like `'2rem'` work). `cssClass` takes a string, array, or conditional map for
123
+ compiled stylesheet / Sass / SCSS classes.
124
+
125
+ `Text` mounts a visually clipped hidden source on `document.body` (or `parent`) with literal text
126
+ content and shares all `DomText` options and [limitations](#limitations). Pass `tone: { backdrop }`
127
+ so light text weights correctly against your scene; see [Matching the browser](#matching-the-browser).
158
128
 
159
129
  ```ts
160
130
  text.text = 'Updated text'
161
- text.setCss({ fontSize: 36, color: 'tomato' }) // Replace the inline CSS.
162
- text.setClass(['headline', 'compact']) // Replace the classes.
163
- await text.rebuild() // Await the updated capture; required with observe: false.
131
+ text.setCss({ fontSize: 36, color: 'tomato' }) // replaces inline CSS
132
+ text.setClass(['headline', 'compact']) // replaces classes
133
+ await text.rebuild() // required only with observe: false or external stylesheet edits
164
134
  ```
165
135
 
166
- Default observers schedule updates when the text, inline style, or classes change. Call
167
- `rebuild()` after external stylesheet changes that leave the source and its size unchanged.
168
- `dispose()` aborts pending work, releases the rendered resources, and removes the owned DOM
169
- source. `TextOptions`, `TextCss`, and `TextClass` are available as package-root type exports.
136
+ Default observers auto-rebuild on text, inline style, or class changes. Call `dispose()` to clean
137
+ up GPU resources, observers, and the owned DOM node. Types `TextOptions`, `TextCss`, and
138
+ `TextClass` are exported at the root.
170
139
 
171
140
  ## TresJS, React Three Fiber, Mini3, and Vanilla JS
172
141
 
173
- Copy the starter components once, then render `<UltraText source={source} />` in React,
174
- `<UltraText :source="source" />` in Vue, or `await UltraText.create(renderer, source)` in Mini3.
175
- They handle WebGPU setup, fonts, DOM updates and cleanup.
176
-
177
- - [TresJS guide](https://ultra-text.makio.io/docs-tres) — verified with TresJS 5.10.0 and Vue 3.5.44.
178
- - [React Three Fiber guide](https://ultra-text.makio.io/docs-r3f) — verified with R3F 9.8.2 and React 19.3.1,
179
- with a separate starter for the R3F 10 alpha.
180
- - [Mini3 & Vanilla JS guide](https://ultra-text.makio.io/docs-mini3) — verified with Mini3 0.1.0-alpha.0 and `ultra-text/vanilla`.
181
- - [Agent skills](https://ultra-text.makio.io/skills) — progressive `skills/ultra-text/` (`npx skills add Makio64/ultra-text` or `npx skills add ultra-text`), also included in the npm package.
182
-
183
- With TresJS and React Three Fiber, install a Three.js release within the package's peer range.
184
- Mini3 and custom WebGPU/Canvas engines import from `ultra-text/vanilla`, which has zero
185
- Three.js runtime dependencies (`three` is an optional peer dependency). These starter
186
- components are MIT consumer components to copy into your app, including with a coding agent;
187
- they are not additional framework npm entry points. See the
142
+ Copy a starter once, then use `<UltraText source={source} />` (React/Vue) or
143
+ `await UltraText.create(renderer, source)` (Mini3):
144
+
145
+ - [TresJS guide](https://ultra-text.makio.io/docs-tres) — TresJS 5.10.0 · Vue 3.5.44
146
+ - [React Three Fiber guide](https://ultra-text.makio.io/docs-r3f) — R3F 9.8.2 · React 19.3.1 (plus R3F 10 alpha)
147
+ - [Mini3 & Vanilla JS guide](https://ultra-text.makio.io/docs-mini3) — Mini3 0.1.0-alpha.0 · `ultra-text/vanilla`
148
+ - [Agent skills](https://ultra-text.makio.io/skills) — `npx skills add Makio64/ultra-text` (`skills/ultra-text/` in git and npm)
149
+
150
+ Starters are MIT copyable source, not framework subpaths. Keep one Three.js copy in the peer range,
151
+ or zero Three.js with `ultra-text/vanilla`; see
188
152
  [agent instructions](https://ultra-text.makio.io/integrations/AGENTS.md).
189
153
 
190
154
  ### Engine-agnostic Vanilla JS (`ultra-text/vanilla`)
191
155
 
192
- Import from `ultra-text/vanilla` when using Mini3 or any custom WebGPU/Canvas renderer without
193
- Three.js:
156
+ No Three.js dependency (`31.7 kB` min+gzip / `28.4 kB` brotli for `DomText + Text`):
194
157
 
195
158
  ```ts
196
159
  import { DomText } from 'ultra-text/vanilla'
@@ -205,26 +168,24 @@ const domText = await DomText.create(source, gpuDevice, {
205
168
  })
206
169
  ```
207
170
 
208
- `ultra-text/vanilla` exports `DomText` (`DomSdf`, `VanillaDomText`), `Text` (`VanillaText`),
209
- `collectDomSnapshot`, `reflowSnapshot`, `rasterizeGlyphAtlas`, `buildVanillaSdfAtlas`
210
- (`buildSdfAtlas`), `buildVanillaGpuSdfAtlas`, `buildVanillaCpuSdfAtlas`,
211
- `packGlyphInstances`, `packRectInstances`, `packDecorationInstances`, and
212
- `resolveDomTextTone`.
171
+ Exports `DomText` (`DomSdf`, `VanillaDomText`), `Text` (`VanillaText`), `collectDomSnapshot`,
172
+ `reflowSnapshot`, `rasterizeGlyphAtlas`, `buildVanillaSdfAtlas` (`buildSdfAtlas`),
173
+ `buildVanillaGpuSdfAtlas`, `buildVanillaCpuSdfAtlas`, `packGlyphInstances`, `packRectInstances`,
174
+ `packDecorationInstances`, and `resolveDomTextTone`.
213
175
 
214
176
  ### Slug-only entries (`ultra-text/slug` and `ultra-text/slug-vanilla`)
215
177
 
216
- WebGPU-only apps that always render analytic quadratic curves—zoomable canvases, CAD/map labels,
217
- hero 3D typography, or VRAM-constrained scenes (`0.17 MiB` vs `0.64–2.04 MiB`)—can import from
218
- `ultra-text/slug` (Three.js `WebGPURenderer` + TSL, 40.2 kB min+brotli) or
219
- `ultra-text/slug-vanilla` (Three.js-free raw WebGPU, 34.4 kB min+brotli):
178
+ Dedicated WebGPU curve entries with zero SDF/JFA/worker code and `0.17 MiB` paragraph VRAM:
179
+ `ultra-text/slug` (`40.9 kB` gz / `36.1 kB` br) and Three-free `ultra-text/slug-vanilla` (`33.7 kB`
180
+ gz / `30.1 kB` br):
220
181
 
221
182
  ```ts
222
183
  import { DomText, Text, createTrueTypeOutlineProvider } from 'ultra-text/slug'
223
184
 
224
- // Zero-config: traces any loaded WOFF2/OTF/TTF/system webfont via Canvas 2D in one boot chunk
185
+ // Zero-config: lazily traces loaded fonts via Canvas 2D
225
186
  const traced = await DomText.create(renderer, source)
226
187
 
227
- // Exact font curves from a .ttf ArrayBuffer (or family -> ArrayBuffer map)
188
+ // Exact outlines from an uncompressed .ttf ArrayBuffer
228
189
  const ttfBuffer = await fetch('/fonts/Inter-Regular.ttf').then((r) => r.arrayBuffer())
229
190
  const exact = new Text('Infinite zoom, zero SDF atlas', {
230
191
  renderer,
@@ -234,15 +195,11 @@ const exact = new Text('Infinite zoom, zero SDF atlas', {
234
195
  await exact.ready
235
196
  ```
236
197
 
237
- For Mini3 or custom WebGPU engines without Three.js, `ultra-text/slug-vanilla` provides retained
238
- `DomText`/`Text` (`VanillaDomSlug`/`VanillaSlugText`), `buildVanillaSlugAtlas`,
239
- `packSlugGlyphInstances`, `SLUG_WGSL`, and `createVanillaSlugPipeline` to draw Slug curves
240
- directly on a `GPUDevice` and `GPURenderPassEncoder`.
241
-
242
- Both Slug-only entries omit all SDF rasterization, GPU JFA, CPU EDT worker, and SDF material code.
243
- In exchange, they require WebGPU (no WebGL2 or CPU atlas fallback) and omit the SDF companion used
244
- on the main entry for bitmap colour emoji and `outline`/`dropShadow` underlays; supply vector
245
- emoji artwork through `createSvgEmojiOutlineProvider` when needed.
198
+ `ultra-text/slug-vanilla` exports `DomText`/`Text` (`VanillaDomSlug`/`VanillaSlugText`),
199
+ `buildVanillaSlugAtlas`, `packSlugGlyphInstances`, `SLUG_WGSL`, and `createVanillaSlugPipeline`.
200
+ Note: Slug-only entries omit the SDF companion used on `ultra-text` for bitmap emoji and
201
+ `outline`/`dropShadow` underlays; supply vector emoji with `createSvgEmojiOutlineProvider` when
202
+ needed.
246
203
 
247
204
  ## Markup contract
248
205
 
@@ -266,53 +223,35 @@ build without adding `aria-hidden`. Keep a separate semantic copy for any UI tha
266
223
 
267
224
  ## Coordinates and lifecycle
268
225
 
269
- Generated content uses the root's bottom-left corner as local `(0, 0)`. X and Y are CSS
270
- pixels divided by `pixelsPerUnit`; Z is not scaled. `width` and `height` expose the current
271
- local dimensions.
226
+ Local `(0, 0)` sits at the root's bottom-left corner. X/Y divide CSS px by `pixelsPerUnit`; Z is
227
+ unscaled. `width` and `height` expose local bounds.
272
228
 
273
229
  ```ts
274
230
  domSdf.setMotion({ enabled: true, mode: 'slide-up', speed: 0.8 })
275
231
 
276
- await domSdf.rebuild() // Re-read layout; reuse retained text data when possible.
277
- await domSdf.rebuild({ atlas: true }) // Force fresh SDF/Windfoil data.
232
+ await domSdf.rebuild() // Re-read DOM; reuse retained data when possible.
233
+ await domSdf.rebuild({ atlas: true }) // Force fresh SDF/Windfoil/Slug data.
278
234
 
279
235
  console.table(domSdf.stats)
280
236
  console.log(domSdf.width, domSdf.height, domSdf.atlasTexture)
281
237
  ```
282
238
 
283
- Text that never moves keeps the motion graph out of its shaders. `DomText`/`DomSdf` read the
284
- live motion mode at every build: with `mode: 'none'` they build static materials, whose vertex
285
- stage has no clock, waves or slide timeline, and `createWindfoilShapes` is static by default.
286
- The first `setMotion()` that sets another mode builds animated materials once, synchronously,
287
- and swaps them in (the meshes stay; edits made to the old materials by hand are not carried
288
- over), and the next frame compiles their pipelines. After that every motion change, `'none'`
289
- included, is a uniform write again, until a capture made with mode `'none'` builds static
290
- materials again. A standalone `SdfTextMaterial` takes `motion: false` for the same static graph:
291
- `animated` is then false, `setMotion()` throws and `clone()` stays static. Text and unlit DOM
292
- rects are unlit: scene lights, and ambient occlusion a render pass supplies, never reach their
293
- shaders, so adding or changing lights never rebuilds them; shadow receivers stay lit.
294
-
295
- By default, a root `ResizeObserver`, a subtree `MutationObserver`, and font-loading events
296
- schedule coalesced rebuilds. Attribute-only mutation storms (a CSS transition, a JS tween)
297
- are debounced, and a re-read that captures identical content stops before rebuilding
298
- any geometry. Change detection hashes capture values directly, avoiding a serialized copy of
299
- the entire layout. Set `observe: false` for manual control. Awaited builds reject normally;
300
- `onError` receives errors from observer-scheduled rebuilds.
301
-
302
- Rebuilds are atomic. A newer build aborts superseded work, and the previous rendered content
303
- stays live until the replacement is ready. When retained text data and mesh structure are unchanged, a
304
- rebuild reuses the compiled materials and meshes and only refreshes geometry; a capture that
305
- is byte-identical to the current content stops right after the DOM read.
306
- Rectangle and decoration replacements are staged with the text: an allocation failure
307
- releases the replacements and preserves the previous meshes and material uniforms.
308
-
309
- `dispose()` is idempotent. It cancels builds, disconnects observers, and releases every
310
- geometry, material, texture, and render target created by the instance. The renderer, scene,
311
- source HTML, lights, and cameras remain yours.
239
+ - **Static-first materials**: `mode: 'none'` (and `createWindfoilShapes`) omits motion graphs from
240
+ shaders. The first `setMotion()` to another mode compiles animated materials once; subsequent
241
+ changes (`'none'` included) update uniforms only. Text and unlit rects never compile light/AO
242
+ graphs; shadow-receiving rects stay lit.
243
+ - **Observers & atomic rebuilds**: root `ResizeObserver`, `MutationObserver`, and `document.fonts`
244
+ coalesce updates (pass `observe: false` for manual `rebuild()`). Rebuilds hash snapshots directly,
245
+ skip identical content after DOM read, abort superseded work, stage replacements safely, and swap
246
+ only when ready (`onError` catches observer errors).
247
+ - **Idempotent `dispose()`**: cancels in-flight work, disconnects observers, and frees owned
248
+ resources without touching renderer, scene, DOM, or `sharedAtlas`.
312
249
 
313
250
  ## Dynamic text and reflow
314
251
 
315
- Reserve characters that may appear later so counters and readouts can reuse retained text data:
252
+ Reserve future glyphs for dynamic readouts so rebuilds never re-bake the atlas (`rebuild()` still
253
+ reuses retained data whenever the glyph set is a subset, or you can share one `sharedAtlas` across
254
+ instances — each falls back to a private atlas only on a missing glyph):
316
255
 
317
256
  ```ts
318
257
  const domSdf = await DomSdf.create(renderer, source, {
@@ -320,87 +259,40 @@ const domSdf = await DomSdf.create(renderer, source, {
320
259
  })
321
260
 
322
261
  readout.textContent = `${ms.toFixed(1)} ms`
323
- await domSdf.rebuild() // stats.atlasBuildMs remains 0 when text data is reused.
262
+ await domSdf.rebuild() // stats.atlasBuildMs === 0 while glyphs match
324
263
  ```
325
264
 
326
- Rebuilds also reuse retained data when the requested font/glyph set is a subset of what is
327
- already available. Removing text and restoring those glyphs does not rebake. A new text glyph
328
- is usually drawn into the SDF atlas in place (see below); a new font, or a glyph that cannot be
329
- patched in, rebuilds the data for the current capture. `extraGlyphs` keeps future characters
330
- reserved.
331
- They are reserved as written, so list capitals for `text-transform: uppercase` copy.
332
- Use `rebuild({ atlas: true })` to regenerate or compact the retained data explicitly.
333
-
334
- `extraGlyphs` prevents rebaking. A rebuild whose glyph count and attribute layout match the
335
- retained geometry writes the new rects, UVs, colours and depth into those buffers instead of
336
- allocating replacements. A count change still replaces the geometry. The DOM read and the GPU
337
- upload of the changed attributes remain. Coalesce and await manual rebuilds for low-cadence copy,
338
- and always handle awaited or observed errors.
339
-
340
- Several groups can share one atlas. Build it once, pass it as `sharedAtlas`, and dispose it
341
- yourself after the instances are gone. An instance whose capture needs a glyph the atlas does
342
- not contain builds a private atlas instead of mutating the shared one.
343
-
344
- For fast width-only changes, retain the capture and re-wrap from its measured advances:
265
+ For fast width-only re-wrapping without reading the DOM, baking, or reallocating buffers:
345
266
 
346
267
  ```ts
347
268
  const domSdf = await DomSdf.create(renderer, source, { reflowable: true })
348
269
  domSdf.reflow(560)
349
270
  ```
350
271
 
351
- `reflow()` does no DOM read, font measurement, or backend work. It updates the existing glyph
352
- geometry attributes in place without reallocating GPU buffers and renumbers the per-line motion
353
- stagger for the new line breaks. Each line follows the block's captured `text-align` and
354
- `text-align-last`: left, center, right or justify, with `start`/`end` resolved by the block's
355
- CSS direction and the `-webkit-` values of `<center>` and `align=` read as their plain sides.
356
- Words wrap and align by their own width inside the block's content box, so a trailing space
357
- hangs as in CSS, and no-break spaces never break a line. A justified line spreads its slack over
358
- its word spaces (and `cjkLineBreaking` breaks), never around an inline SVG glued to a word; the
359
- last line and lines before a `<br>` follow `text-align-last`. Captured at 320 px and reflowed to
360
- 200–560 px in headless Chrome 156 on an Apple M3 Max (Noto Sans, Arial, Helvetica Neue, Georgia,
361
- Courier New, Times New Roman), glyphs land within 0.04 px of a fresh capture for left, center,
362
- right, start and end, and within 0.06 px for justify, with the same line breaks.
363
-
364
- It is a block-flow model, not a full CSS engine. It does not recompute `text-indent`, mixed font
365
- sizes on one line (one line pitch per block), hyphenation, bidi reordering within a line,
366
- floats, media queries, or captured rectangle geometry. In justified blocks each word space is
367
- one Canvas space plus letter- and word-spacing, so inline padding, tabs and other space
368
- characters are off by a few pixels there; a line that fills to within about 0.03 px can break
369
- differently from the browser, and with `pixelSnap` a right-aligned or justified line can move
370
- one quarter-pixel snap step. RTL scripts need `rtlReflow: true`. A capture made without
371
- `OffscreenCanvas` (jsdom) records no natural word spaces, so its justified blocks reflow at their
372
- measured spacing. Use `rebuild()` when CSS layout must be measured again.
373
-
374
- A rebuild that adds text glyphs to an instance's own SDF atlas draws them into its free text rows
375
- in place instead of baking a new atlas. Only the new glyphs are measured, drawn and encoded, with
376
- the atlas's own encoder (the GPU jump flood for a GPU atlas, the exact CPU transform for a CPU
377
- atlas); they are then copied into the live texture and its mipmaps are regenerated, so the
378
- texture and the compiled materials stay. Patched glyphs match a full build exactly on a CPU atlas
379
- and within one 8-bit step on a GPU atlas. After its first new glyph, an instance builds its
380
- atlas with headroom: free rows of max(tallest text slot, a
381
- quarter of the text rows) above any shapes and colour glyphs, in an atlas at least two widest
382
- glyphs wide, which makes short texts' atlases 1.5–2.6 times larger. Glyphs that classify as
383
- colour, SVG shapes, `rebuild({ atlas: true })` and webfont loads, Windfoil and Slug companions, a
384
- caller's `sharedAtlas`, a lowered adaptive bake size, more than 2¹⁸ new texels, and glyphs that
385
- do not fit rebuild the atlas in full; glyphs the text no longer uses stay until such a full
386
- build. `ultra-text/vanilla` always rebuilds in full. On a 188-glyph text gaining one character
387
- per rebuild (headless Chrome 156, Apple M3 Max, shared GPU, n = 50), the median time from
388
- `rebuild()` to the first frame went from 9.0 to 6.7 ms with a GPU atlas and from 11.0 to 2.9 ms
389
- with a CPU atlas; the first new glyph after a capture is still a full rebuild.
390
-
391
- Reflow creates a new CPU snapshot with one shared clipping rectangle per block and places
392
- words as it measures them, without retaining an intermediate word list.
272
+ `reflow()` preserves `text-align` and `text-align-last` (`left`, `center`, `right`, `justify`,
273
+ `start`/`end`), matches Chrome within 0.04 px (`0.06 px` justify) across 200–560 px tests, and
274
+ recomputes stagger in place (`0.041 ms` standalone CPU median at 1,000 glyphs / `0.326 ms` at
275
+ 10,000 glyphs on Apple M3 Max, `2026-11-23`). It is a
276
+ block-flow pass: it skips `text-indent`, mixed line sizes, hyphenation, mixed bidi (RTL needs
277
+ `rtlReflow: true`, CJK `cjkLineBreaking: true`), floats, and rect geometry; call `rebuild()` when
278
+ CSS changes.
279
+
280
+ Both SDF (`DomSdf`/`DomText`) and analytic (`slug`/`windfoil`) instances patch new unseen glyphs
281
+ in-place after their first miss:
282
+
283
+ - On the first miss, SDF atlases allocate headroom (`1.5–2.6×` on small texts) and append new text
284
+ glyphs into free rows (`6.7 ms` vs `9.0 ms` GPU, `2.9 ms` vs `11.0 ms` CPU on 188 glyphs in
285
+ Chrome 156); full rebuilds occur on new fonts, colour/SVG glyphs, overflow (`rebuild({ atlas: true })`),
286
+ or `ultra-text/vanilla`.
287
+ - Analytic instances allocate tight cold buffers (`0.17 MiB` paragraph) and add headroom on the
288
+ first miss, cutting unseen-glyph Slug rebuilds from `8.61 → 2.89 ms` (TTF) and `10.91 → 4.14 ms`
289
+ (traced) in `2026-11-19` `vs-ecosystem`.
393
290
 
394
291
  ## Layout engines
395
292
 
396
- - `range` is the default. It reads the browser's rendered glyph boxes for the highest CSS
397
- fidelity and returns synchronously from `collectDomSnapshot()`.
398
- - `pretext` lazily loads `@chenglou/pretext`, measures through Canvas, and returns a promise.
399
- It avoids one DOM geometry read per glyph, but models `white-space: normal`. It aligns and
400
- justifies inside its own line pass, following `text-align-last`. Prefer `range` for `<br>`,
401
- bidi-sensitive placement, floats, indentation, vertical writing, or exact CSS parity. On a
402
- display scale other than 1 it reads up to 16 glyph boxes per capture, to learn which pixel the
403
- browser rounds on.
293
+ - `range` (default): synchronous DOM `Range` capture for exact CSS placement and wrapping.
294
+ - `pretext`: async dynamic `@chenglou/pretext` Canvas pass (faster DOM read, models
295
+ `white-space: normal`; prefer `range` for `<br>`, bidi, floats, indent, vertical text, or exact CSS).
404
296
 
405
297
  ```ts
406
298
  import { collectDomSnapshot } from 'ultra-text'
@@ -409,29 +301,12 @@ const exact = collectDomSnapshot(source)
409
301
  const fast = await collectDomSnapshot(source, { layoutEngine: 'pretext' })
410
302
  ```
411
303
 
412
- A capture also records where the browser's layout put each font's baseline. A browser sets
413
- it with the font's descent rounded to whole layout pixels (device pixels on a real display,
414
- CSS pixels under device emulation), so it can sit half a pixel from the font's own descent
415
- scaled to the size. Each glyph carries that rounded descent as `baselineOffset`, and both text
416
- backends draw from it. Range captures and browser-shaped runs measure it through Canvas and
417
- keep it only when it reproduces the text box the DOM reports; otherwise a Range glyph falls
418
- back to the atlas or outline descent, and a shaped run to the descent Canvas reports at its
419
- CSS size. Pretext builds its lines from the same rounded metrics, rounds the half-leading down
420
- as the browser does, and takes a `normal` line height from the font's ascent plus descent.
421
-
422
- Capture caches font metrics, glyph keys, and hidden/decoration ancestry within each read;
423
- later captures refresh them so CSS and loaded-font changes stay visible. The glyph loops
424
- avoid temporary object copies and redundant font assignments; layout-change detection hashes
425
- each distinct glyph-key string once per capture. Browser shaping shares its Range, grapheme
426
- segmenter, and Canvas context across blocks, and reuses descents for identical text at the
427
- same font and size within a capture. The Range engine still measures each visible glyph for
428
- exact placement. For width-only updates, use
429
- `reflowable: true` and `reflow(width)` to avoid DOM capture entirely.
304
+ Both engines record browser baseline rounding (`baselineOffset` from rounded descent) and reuse
305
+ metrics/scratch caches within a capture.
430
306
 
431
307
  ### Optional language support
432
308
 
433
- Language extensions are off by default. For joined scripts, ligatures, combining marks, and
434
- mixed-direction text, enable native browser shaping:
309
+ For joined scripts, ligatures, combining marks, and mixed bidi, opt into lazy `textShaping: 'browser'`:
435
310
 
436
311
  ```ts
437
312
  const text = await DomText.create(renderer, source, {
@@ -439,165 +314,53 @@ const text = await DomText.create(renderer, source, {
439
314
  })
440
315
  ```
441
316
 
442
- This lazily loaded path preserves complete rendered runs, including Arabic/Persian joining,
443
- Indic conjuncts, Hebrew marks, and grapheme sequences. Equivalent inline markup shares shaping
444
- context. It uses Range layout and SDF; Windfoil needs `fallback: 'sdf'`. No shaping dependency
445
- or font is bundled. Supply fonts that cover your text.
446
-
447
- Requested shaping and SVG rasterization modules load alongside font preparation. A capture
448
- requesting both SVG and browser shaping also loads those modules together. These imports
449
- remain conditional; the default glyph path does not load them.
450
-
451
- Shaping, animation, and atlas reuse operate per run; wide runs use atlas tiles. Resize through
452
- `rebuild()` (automatic with observation), not `reflow(width)`. Low-level `collectDomSnapshot()`
453
- returns a promise; pass the same `textShaping` option to `SdfTextMaterial`. Run masks can use
454
- more atlas memory than reusable glyphs. Changes in font or paint style split shaping context.
455
- Emoji sequences (ZWJ, skin tone, flags, keycaps, tags and presentation selectors) stay whole
456
- with both layout engines, without requiring browser shaping. SDF emoji retain the browser's
457
- colours, including within mixed shaped runs; `colorGlyphs: 'none'` restores silhouettes.
458
- Arbitrary OpenType feature settings remain unsupported.
459
-
460
- For the default glyph path, `cjkLineBreaking: true` enables basic CJK reflow punctuation rules,
461
- and `rtlReflow: true` enables uniform RTL word reflow. Neither implements mixed bidi reordering.
462
- The legacy `reshape(text)` hook receives text after CSS `text-transform`. It must preserve code
463
- point boundaries and whitespace with Range, and cannot be combined with browser shaping.
464
- `adaptiveBakeSize: true` separately allows lowering SDF resolution on atlas overflow. All three
465
- booleans default to `false`.
466
-
467
- ## Matching the browser
468
-
469
- A browser blends its glyph mask on sRGB-encoded values; a scene blends coverage in linear
470
- light. The same glyph therefore reads differently in the two: in linear light, dark text on a
471
- light background comes out lighter and thinner than in the page, and light text on a dark
472
- background heavier. `tone` converts the coverage of text ink so that the linear-light result
473
- lands on the pixel the browser shows. It is on by default for both text backends, and it is
474
- arithmetic on coverage the shader already has: no extra texture read and no extra draw.
317
+ Uses Range layout + SDF (Windfoil requires `fallback: 'sdf'`) with no bundled shaper or fonts; wide runs use atlas tiles. Emoji sequences stay whole on both layout engines; SDF emoji keep browser colours (`colorGlyphs: 'none'` for silhouettes). Vertical writing and arbitrary OpenType features are unsupported; resize via `rebuild()`, not `reflow()`.
475
318
 
476
- ```ts
477
- // The page behind `source` is white, but the scene shows this text on a dark wall.
478
- const label = await DomText.create(renderer, source, {
479
- tone: { backdrop: '#101418' },
480
- })
319
+ Opt-in booleans (all default `false`): `cjkLineBreaking`, `rtlReflow`, and `adaptiveBakeSize` (shrinks SDF bake size on overflow instead of rejecting). Legacy `reshape(text)` cannot be combined with browser shaping.
481
320
 
482
- // The font's own outline at exact coverage, with the conversion left out of the shaders.
483
- const exact = await DomText.create(renderer, source, { tone: false })
484
- ```
321
+ ## Matching the browser
485
322
 
486
- | `tone` field | Default | Meaning |
487
- | ------------ | -------- | --------------------------------------------------------------------------------------------- |
488
- | `backdrop` | `'auto'` | Colour the text is read against: a hex value, a colour name, comma-separated `rgb()`/`hsl()`. |
489
- | `model` | `'auto'` | Rasterizer to imitate: `'outline'`, `'macos'` or `'windows'`. |
490
- | `strength` | `1` | From `0` to `1`: how much of the conversion applies. |
491
-
492
- Each capture resolves the `'auto'` values from the page, never in the render loop:
493
-
494
- - **Model.** The platform and the source element's computed CSS decide. macOS with default
495
- font smoothing gives `'macos'`: CoreGraphics smoothing, which also grows every outline by
496
- min(0.0058 em, 0.30 px) to either side and twice that upwards, below 256 device pixels per
497
- em. macOS with `-webkit-font-smoothing: antialiased` or `none`,
498
- `-moz-osx-font-smoothing: grayscale` or `text-rendering: geometricPrecision` gives
499
- `'outline'`, exact outline coverage. Windows gives `'windows'`, Skia's contrast table.
500
- Linux, Android, iOS and iPadOS give `'outline'`.
501
- - **Backdrop.** What the capture draws behind the text (its rectangles and root background),
502
- over the nearest opaque CSS background colour behind the source element. One backdrop
503
- serves a whole capture: the one behind most of its text.
504
- - **Unknown backdrop.** Where nothing can tell (no opaque background colour behind the
505
- source, a background image in front of it, a `Text`, whose source is hidden, or a material
506
- you build yourself), dark text gets the weight it has on a white page and light text keeps
507
- its exact coverage: it is neither thinned nor lifted.
508
-
509
- Set `tone.backdrop` to the colour your scene shows behind the text whenever that is not the
510
- page's: text captured from a white page and shown on a dark wall, a `Text`, a standalone
511
- `SdfTextMaterial`, or your own backdrop mesh on a transparent canvas. A `Text` whose CSS
512
- gives it an opaque `background` of its own already knows its backdrop.
323
+ Because browsers blend glyph coverage on sRGB values while 3D scenes blend in linear light, `tone` (on by default across all backends) adjusts coverage arithmetically in shader with zero extra texture reads or draws:
513
324
 
514
325
  ```ts
515
- const title = new Text('Hello, WebGPU!', {
516
- renderer,
517
- css: { fontSize: 48, color: '#ffffff' },
518
- tone: { backdrop: '#101418' },
519
- })
326
+ const label = await DomText.create(renderer, source, { tone: { backdrop: '#101418' } })
327
+ const exact = await DomText.create(renderer, source, { tone: false }) // exact font outline coverage
520
328
  ```
521
329
 
522
- The conversion applies where the frame itself holds what the text is drawn over: an opaque
523
- canvas or clear colour, a scene background, a rectangle the capture draws, or a `backdrop`
524
- you name. On Three's default transparent canvas laid over the page, the browser blends the
525
- canvas with the page, so text over nothing keeps its exact coverage there. Translucent text
526
- (colour alpha, CSS `opacity`) is converted as the browser blends it; SDF text with an
527
- `outline` or `dropShadow` converts as opaque ink. Emoji and other colour glyphs, SVG paint,
528
- outline rings, drop shadows and shadow masks keep their exact coverage. `strength` scales
529
- the conversion, not the `'macos'` model's outline growth: use `tone: false` or the
530
- `'outline'` model for the font's own outline.
330
+ | `tone` field | Default | Meaning |
331
+ | ------------ | -------- | ------------------------------------------------------------------ |
332
+ | `backdrop` | `'auto'` | Background colour behind text (hex, name, comma `rgb()`/`hsl()`). |
333
+ | `model` | `'auto'` | Platform rasterizer model: `'outline'`, `'macos'`, or `'windows'`. |
334
+ | `strength` | `1` | Weight scaling `0..1` (does not scale `'macos'` outline dilation). |
531
335
 
532
- SDF text draws from the same starting point as Windfoil. The atlas bakes the font's own
533
- outline, without the platform's smoothing, and the contour sits on it (`threshold: 0.5`, no
534
- `stemDarkening`); the weight comes from `tone` alone.
336
+ - **`model` resolution**: macOS default smoothing → `'macos'` (CoreGraphics weight + min(0.0058 em, 0.30 px) sideways / 2× upwards below 256 device px/em); macOS `antialiased`/`none` or `geometricPrecision`, Linux, Android, iOS → `'outline'`; Windows → `'windows'` (Skia contrast table).
337
+ - **`backdrop` resolution**: uses captured rects / opaque ancestor background; falls back to black-on-white defaults on transparent canvas overlays, `Text`, or `SdfTextMaterial` unless `tone.backdrop` is set. Translucent ink weights as browser-blended; colour glyphs, SVG paints, outlines, and shadows keep exact coverage. SDF text bakes the font outline (`threshold: 0.5`, `stemDarkening: 0`) so weight comes from `tone` alone.
535
338
 
536
339
  ### Pixel snapping
537
340
 
538
- A capture keeps layout positions, which can lie between pixels. A browser paints each line of
539
- upright text on a whole pixel row, and each glyph origin on a quarter of a device pixel while
540
- the glyph is under 162 device pixels per em. `pixelSnap: true` moves captured lines and glyph
541
- origins there, with no extra DOM read:
542
-
543
- ```ts
544
- const overlay = await DomText.create(renderer, source, { pixelSnap: true })
545
- ```
546
-
547
- Use it for text shown flat, unscaled and pixel-aligned over the page it was captured from.
548
- It holds for the element's position at capture: capture again once the element has moved by a
549
- fraction of a pixel. Under any other transform it only gives up the layout positions, so it
550
- is off by default. `reflow()` snaps the re-wrapped layout again; browser-shaped runs take the
551
- rows only, and inline SVG shapes are not moved.
341
+ `pixelSnap: true` (default `false`) aligns captured lines to whole device pixel rows and glyph origins to quarter pixels below 162 device px/em for flat 1:1 DOM overlays (`reflow()` re-snaps; recapture if moved sub-pixel).
552
342
 
553
343
  ### Multisampled targets
554
344
 
555
- Windfoil pads each glyph quad for the sample count of the pass being drawn, so a 4×
556
- multisampled canvas or render target keeps the coverage of its edge samples. There is
557
- nothing to set, and single-sampled passes keep the tighter quad. A 4× pass shades more
558
- fragments per glyph for it: 30% more at 8 px per em and 4.5% more at 64 (Noto Sans, counted
559
- on the GPU).
345
+ Windfoil automatically pads glyph quads on 4× MSAA targets to keep edge sample coverage (+30% fragments at 8 px/em, +4.5% at 64 px/em on Noto Sans).
560
346
 
561
347
  ### Measured limits
562
348
 
563
- Measured on 2026-10-08 in headless Chromium 153 on macOS 15 (Apple M3 Max), at a display
564
- scale of 1 and of 2, with Lato and Noto Sans Regular in four colour pairs, against a screenshot of the
565
- same DOM element at its layout position. The mean difference over edge pixels is in 8-bit
566
- sRGB levels (lower is closer); ink is the library's over Chrome's.
567
-
568
- | Text, default options | `geometricPrecision` page, 1× / 2× | Default smoothing, 1× / 2× | Ink |
569
- | ------------------------------------ | ---------------------------------- | -------------------------- | --------- |
570
- | SDF, 9–24 CSS px | 15.5 / 13.7 | 16.9 / 14.0 | 0.95–1.06 |
571
- | Windfoil, under 162 device px per em | 12.3 / 12.6 | 11.2 / 11.3 | 0.98–1.02 |
572
- | Windfoil, 162–255 device px per em | 47.6 / 49.0 | 16.0 / 16.9 | 0.95–1.01 |
573
- | Windfoil, from 256 device px per em | 17.7 / 16.7 | 17.7 / 16.7 | 1.00 |
574
-
575
- With `tone: false`, the same Windfoil text at 64 and 128 px measured 44–47 levels where the
576
- defaults measure 14–16 (Noto Sans, black and white, 1×, `geometricPrecision`). With
577
- `pixelSnap`, 13, 16 and 24 CSS px text laid out between pixels went from 29–36 levels to 8–20.
578
-
579
- - Only Chrome on macOS was measured. The `'windows'` model and the choices for Linux and
580
- Android follow Chromium's and Skia's source and were not run; Safari and Firefox were not
581
- measured.
582
- - From 162 to 255 device pixels per em, Chrome on macOS draws smoothed text whatever
583
- `text-rendering: geometricPrecision` or `-webkit-font-smoothing: antialiased` ask for. The
584
- library keeps the exact outline on such pages, so text in that band carries about 0.95 of
585
- Chrome's ink (third row). A capture whose text all lies in the band can set
586
- `tone: { model: 'macos' }`.
587
- - At whole-pixel font sizes below about 18 device pixels, Chrome fits glyph heights to whole
588
- pixels at some sizes: Lato capitals by up to 0.8 px between 9 and 17 px. The library draws
589
- the font's outline at every size, as Chrome does at fractional sizes.
590
- - At 16 CSS px and below, some sizes sit 1/8 to 1/4 px from Chrome vertically (52 of 416
591
- measured cells), which costs up to 4.9 levels.
592
- - From 256 device pixels per em, Chrome draws glyphs as paths with four coverage samples per
593
- pixel. Exact coverage stays 16–21 levels from that on edge pixels, at equal ink.
594
- - One backdrop serves a capture. Text of one capture that stands on several backgrounds is
595
- toned for the one behind most of it; capture such regions separately for an exact match.
596
- - With Windfoil, an inline SVG layer painted with the text colour is toned like the text.
597
- Solid and gradient paints keep their exact coverage.
598
- - The `'macos'` outline growth is approximate on a CPU-built atlas (0.26 px sideways and
599
- 0.28 px upwards at 96 px per em, where a GPU atlas gives 0.30 and 0.57), and is cut short
600
- below about 10 device pixels per em at the default `bakeSize` and `padding`.
349
+ Measured 2026-10-08 in headless Chromium 153 on macOS 15 (Apple M3 Max) vs Chrome screenshots (mean 8-bit sRGB edge diff, lower is closer; ink ratio vs Chrome):
350
+
351
+ | Text, default options | `geometricPrecision`, 1× / 2× | Default smoothing, 1× / 2× | Ink |
352
+ | ------------------------------------ | ----------------------------- | -------------------------- | --------- |
353
+ | SDF, 9–24 CSS px | 15.5 / 13.7 | 16.9 / 14.0 | 0.95–1.06 |
354
+ | Windfoil, under 162 device px per em | 12.3 / 12.6 | 11.2 / 11.3 | 0.98–1.02 |
355
+ | Windfoil, 162–255 device px per em | 47.6 / 49.0 | 16.0 / 16.9 | 0.95–1.01 |
356
+ | Windfoil, from 256 device px per em | 17.7 / 16.7 | 17.7 / 16.7 | 1.00 |
357
+
358
+ (`tone: false` scored 44–47 vs 14–16 at 64–128 px; `pixelSnap` dropped 13–24 px sub-pixel overlays from 29–36 to 8–20.)
359
+
360
+ - Only Chrome/macOS was measured (Windows/Linux/Android follow Chromium/Skia source; Safari/Firefox unmeasured).
361
+ - 162–255 device px/em triggers macOS smoothing even under `geometricPrecision` (`tone: { model: 'macos' }` overrides).
362
+ - Chrome hints glyph heights below ~18 device px (`9–17 px`); ultra-text always uses true outline proportions.
363
+ - One backdrop serves the whole capture; split regions over distinct backgrounds. `'macos'` CPU-atlas dilation is approximate and clips below ~10 device px/em at default padding.
601
364
 
602
365
  ## Options
603
366
 
@@ -661,20 +424,11 @@ not a copy with defaults filled in.
661
424
 
662
425
  </details>
663
426
 
664
- Text shown near 1:1 is closest to the browser with the defaults: `quality: 'standard'`, the
665
- baked `threshold`, no `stemDarkening`, and its weight left to [`tone`](#matching-the-browser).
666
- `quality: 'high'` is for minified or steeply angled SDF text, where its four taps and mipmaps
667
- steady the edges; at 1:1 its wider filter draws small text lighter than the browser does. Raise
668
- `bakeSize` and `padding` together for unusually large or oblique text, and adjust `threshold`
669
- only slightly around its default. `threshold`, `stemDarkening` and `quality` are ignored by
670
- active Windfoil coverage but still configure a requested whole-capture SDF fallback and the
671
- SDF companion of `fallback: 'sdf-glyphs'` and `sdfBelowPx`; `tone` applies to every backend.
427
+ `quality: 'standard'` matches 1:1 DOM text closest; `'high'` (4-tap sampling + mipmaps + anisotropy) steadies minified/oblique SDF text. Raise `bakeSize` and `padding` together for oversized/tilted display copy.
672
428
 
673
429
  ### Text effects, custom fills, and vertex hooks
674
430
 
675
- `DomText.create()` (`DomSdf.create()`), `Text`, `SdfTextMaterial`, and `createWindfoilShapes`
676
- accept custom TSL `fill` and `vertex` callbacks; all but `createWindfoilShapes` also take SDF
677
- `outline` and `dropShadow` effects:
431
+ `DomText.create()`, `Text`, `SdfTextMaterial`, and `createWindfoilShapes` accept TSL `fill` and `vertex` hooks (`outline` and `dropShadow` work on all text backends; they never execute per frame on CPU):
678
432
 
679
433
  ```ts
680
434
  import { mix, sin, time, vec3, vec4 } from 'three/tsl'
@@ -695,94 +449,20 @@ const text = await DomText.create(renderer, source, {
695
449
  })
696
450
  ```
697
451
 
698
- Both callbacks run only while TSL graphs are built, never in the animation loop: `fill` once for
699
- each material, including clones and the animated twin a `setMotion()` upgrade creates, and
700
- `vertex` each time three builds a pipeline from one, shadow passes included.
701
-
702
- `fill` receives `uv` (normalized glyph quad coordinates),
703
- `position` (animated capture-local position), `color` (per-pixel linear RGB), `colorWeight`
704
- (0 for CSS-tinted ink, 1 for baked colour ink), and `glyphIndex`
705
- (the drawable index, which can change after a rebuild; layered Windfoil and its SDF companion
706
- share a capture-order ordinal, so it stays continuous across `sdfBelowPx`). It is a whole number
707
- at each pixel of a glyph, so `array.element(int(glyphIndex))` reads that glyph's entry. Return a `vec4`
708
- containing linear RGB and an opacity multiplier. Glyph coverage, DOM opacity, motion, and block
709
- clipping remain applied. Custom opacity also masks scene shadows. Use TSL `time`, uniforms, noise,
710
- or `texture(myTexture, uv)` for animated, procedural, or textured letters; the caller owns
711
- those uniforms and textures. SDF UVs include the glyph's baked padding. The fill hook works
712
- with SDF, Windfoil, and Slug; it does not shade decorations, outlines, or drop shadows. With
713
- [`tone`](#matching-the-browser) on, filled ink is weighted for the fill's own colour at each
714
- pixel; pass `tone: false` when a fill paints artwork, such as a texture, rather than ink. On SDF,
715
- style text while retaining emoji colours with `vec4(mix(myGradient, color, colorWeight), 1)`;
716
- a fill that ignores `color` also recolours those emoji. Windfoil and Slug apply the fill to
717
- foreground layers; fixed solid and gradient paints retain their own colours and alpha. CSS text alpha
718
- and effective opacity multiply SDF colour glyphs once; outline, drop-shadow and scene-shadow
719
- colours use the SDF silhouette.
720
-
721
- `vertex` receives `position` (the rendered local `vec3` corner after built-in motion, `sdfTrim`
722
- tightening, `outline`/`dropShadow` padding, and Windfoil/Slug edge skirts), `center` (un-animated
723
- local `vec2` glyph anchor, shared across shaped runs, paint layers, companions, and decorations),
724
- `uv` (corner UV in `0..1`, including SDF trim or effect padding when active), `glyphIndex`
725
- (drawable instance index), `sequence` (per-line stagger index), `rect` (`[x0, y0, x1, y1]` glyph
726
- bounding box in capture-local coordinates), and `clip` (`[x0, y0, x1, y1]` block clip rectangle in
727
- capture-local coordinates). Return the final local `vec3` corner position. Block clipping reads the
728
- pre-hook position, so 3D waves, twists, and Z-extrusions are not clipped at a block's static
729
- bounds; size-switch rejected quads collapse after the hook. `vertex` runs on SDF, Windfoil, Slug,
730
- their SDF companion and effect underlays, `DomText`/`DomSdf` text decorations, and
731
- `createWindfoilShapes`.
732
-
733
- Outlines and drop shadows are drawn from an SDF on every text backend. On `'windfoil'` and
734
- `'slug'`, glyphs drawn from outlines keep their analytic fill and take their ring and shadow from
735
- an SDF underlay: those glyphs are also baked into the SDF companion atlas, and one extra draw at
736
- the text's own render order lays the ring and shadow under the fill, blended to match
737
- single-pass SDF text (no light seam inside the ring, no gap at concave corners, no shadow through
738
- see-through ink; exact without `tone`, and for opaque ink with it). Glyphs without outlines and
739
- size-switched glyphs below `sdfBelowPx` are plain SDF text with their effects. The ring keeps SDF
740
- edges under magnification, and an outline of width or opacity 0, or a shadow of opacity 0, draws
741
- and bakes nothing. For a 77-glyph paragraph (headless Chrome 156, Apple M3 Max), Windfoil alone
742
- holds no atlas and 45,840 bytes in one draw; with an outline it adds a 1072×472 companion atlas,
743
- for 551,824 bytes in two draws. The underlay sorts with its own text, but the colour and fallback
744
- parts of separate texts sort by render order rather than depth, and with
745
- `renderer.sortObjects = false` the underlay draws over its fill. Width and offsets use local units (CSS pixels divided by `pixelsPerUnit`); positive Y points up.
746
- An empty `outline` uses a black, fully opaque, 1-unit outline. An empty `dropShadow` uses
747
- black at 0.5 opacity with offsets `(2, -2)`. Opacity is clamped to `0..1`; widths must be
748
- non-negative and all numeric effect options must be finite. Effects remain clipped to the
749
- marked text block, so leave room around its content when an effect should extend outward.
750
-
751
- The outline expands outward and is limited to slightly less than half the atlas pixel
752
- range, scaled to the glyph size. Increase `padding` to bake a wider usable field. Sampling
753
- is clamped to each atlas cell to keep shifted lookups within that glyph. Drop
754
- shadows are hard silhouettes with antialiased edges, without blur. They appear in the text
755
- plane; `castShadow` still controls scene shadow casting independently.
756
-
757
- Use `quality: 'high'` to apply the same four-sample antialiasing to fills, outlines, and drop
758
- shadows. Thin outlines expose the baked contour more readily than plain fills; for large
759
- display text, start with `bakeSize: 192` and `padding: 24`, as in the text lab. A denser bake
760
- uses more atlas memory and takes longer to build. CPU and GPU fields can still differ in
761
- their contour reconstruction; increasing canvas resolution alone does not remove atlas steps.
762
-
763
- Solid CSS `underline`, `overline`, and `line-through` decorations are captured automatically,
764
- including ancestor decorations, color, thickness, and underline offset. They use a separate
765
- instanced batch, share glyph clipping and motion, and follow `reflow()`. Default/from-font
766
- thickness and line positions use font-metric approximations; skip-ink, wavy, dotted, dashed,
767
- and double decorations are not reproduced. The captured decoration metadata is available
768
- on `GlyphLayout` for lower-level renderers; `DomSdf` owns the automatic decoration batch.
769
-
770
- Open the interactive [text lab](https://ultra-text.makio.io/text-effects) to compare
771
- worker/main-thread CPU baking with WebGPU and toggle each visual effect.
452
+ - **`fill({ uv, position, color, colorWeight, glyphIndex })`** → linear RGBA `vec4`. Coverage, DOM opacity, clipping, motion, and shadow masking remain applied. Pass `tone: false` for textured/painted fills; on SDF, mix via `colorWeight` to keep emoji colours.
453
+ - **`vertex({ position, center, uv, glyphIndex, sequence, rect, clip })`** → displaced local `vec3`. Clipping runs pre-hook so Z waves do not get clipped; runs across beauty, shadow passes, decorations, and companions.
454
+ - **Outlines & drop shadows**: rendered from SDF on every backend (analytic backends add an SDF companion underlay batch in 2 draws: e.g. 45,840 B in 1 draw vs 551,824 B in 2 draws on 77 glyphs in Chrome 156 / M3 Max). Outlines cap below half `padding`; drop shadows are hard silhouettes (no blur). Empty `outline` defaults to black `1` unit; empty `dropShadow` to black `0.5` opacity at `(2, -2)`.
455
+ - **Decorations**: solid CSS `underline`, `overline`, and `line-through` capture into an instanced batch that tracks `reflow()` and motion (wavy/dotted/double/skip-ink omitted). See the [text effects lab](https://ultra-text.makio.io/text-effects).
772
456
 
773
457
  ### Experimental Windfoil and Slug backends
774
458
 
775
- Browsers expose the selected CSS font description, not its outline bytes. Supply an app-owned
776
- resolver that returns OpenType-style, Y-up quadratic outlines, or omit it to trace the browser's
777
- own glyphs:
459
+ Supply OpenType Y-up closed quadratic outlines (`outlineProvider`), or omit it to trace browser glyphs at 256 px/em (~0.006 em accuracy, ~0.5–0.6 ms Latin / 1.1–1.2 ms CJK on main thread in ~8 ms slices, cached per instance):
778
460
 
779
461
  ```ts
780
462
  import { DomText, type WindfoilOutlineProvider } from 'ultra-text'
781
463
 
782
- // No outlineProvider: outlines traced from the browser's own glyphs at 256 px per em
783
464
  const traced = await DomText.create(renderer, source, { textBackend: 'slug' })
784
465
 
785
- // Exact outlines from an app-owned resolver
786
466
  const outlineProvider: WindfoilOutlineProvider = (request, signal) =>
787
467
  myFontRegistry.resolveQuadraticOutline(request, signal)
788
468
 
@@ -792,55 +472,7 @@ const domText = await DomText.create(renderer, source, {
792
472
  })
793
473
  ```
794
474
 
795
- Without an `outlineProvider`, each `DomSdf` traces its glyphs from the browser's own rendering.
796
- Once `document.fonts.load()` resolves, a glyph is drawn at 256 px per em on the SDF bake's
797
- in-document canvas (the captured canvas font with its stretch and kerning, no font smoothing),
798
- and its half-coverage contour is fitted with quadratic curves. Against Noto Sans Regular's own
799
- outlines (94 printable ASCII glyphs, headless Chrome 156 on macOS, Apple M3 Max), traced outlines
800
- stay within 0.006 em (mean deviation 0.0002 em), keep every glyph's contour count and winding,
801
- and hold 1.3 times the font's curves (Slug buffers of 381 kB against 180 kB from exact outlines).
802
- Edges stay analytic under magnification but follow that raster, not the font file; supply a
803
- provider for exact edges. Font-variation and feature settings are not applied, `fallback`
804
- defaults to `'sdf-glyphs'`, and colour glyphs, fonts the canvas rejects and glyphs whose ink
805
- overflows their box are drawn by the SDF companion. Tracing runs on the main thread in slices of
806
- about 8 ms, about 0.5–0.6 ms per Latin glyph and 1.1–1.2 ms per CJK glyph, and is cached per
807
- instance; `rebuild({ atlas: true })` and webfont loads trace again. Other rasterizers and
808
- browsers are unmeasured. A provider that is not a function rejects before anything is allocated.
809
-
810
- `textBackend: 'slug'` uses an extrema-split dual-ray Slug evaluator (`slug` options, or `windfoil`
811
- options if `slug` is omitted) with endpoint-first `[p1, p3, p2]` storage, orthogonal degenerate
812
- segment culling, convex-hull winding bypass, and fine-grained single-word band headers (`targetPiecesPerBand: 2`
813
- by default). It shares the same outline provider contract, `fallback` modes, `sdfBelowPx` size
814
- switch, colour layers, tone weighting, outline and drop-shadow underlay, and Pretext/Range
815
- reflow as `'windfoil'`.
816
-
817
- The provider owns font fallback and variation mapping. It must emit every closed contour edge,
818
- promote lines and convert cubics to quadratics, preserve contour/hole winding for the nonzero
819
- fill rule, and return the glyph ink bounding box in the same font-unit coordinates. The main
820
- `ultra-text` entry keeps font parsing external to stay small, while `ultra-text/slug` and
821
- `ultra-text/slug-vanilla` export `createTrueTypeOutlineProvider` (`parseTrueTypeFont`) for
822
- uncompressed `.ttf` buffers alongside eager `createTracedOutlineProvider`. Windfoil
823
- keeps read-only curve/row buffers instead of a coverage texture. Each row band stores its curves
824
- twice, sorted from either side, so a fragment integrates only the curves on its own side of the
825
- band; `textStorageBytes` includes both copies. Adjacent band windows share their rounded
826
- boundary and include neighbouring bands when necessary, keeping solid interiors continuous
827
- under extreme magnification. Already monotone curves bypass temporary subdivision arrays
828
- during preparation. A null outline either rejects or falls the whole capture back to SDF;
829
- `fallback: 'sdf-glyphs'` (the default without an `outlineProvider`) retains available outlines
830
- and adds one SDF companion for missing glyphs, whose colour emoji follow `colorGlyphs`. Lower
831
- `targetPiecesPerBand` values trade more duplicated storage and preprocessing for less fragment
832
- curve work; higher values do the reverse. Cache resolved outlines, honor the abort signal, and
833
- avoid per-glyph network fetches. Requests using automatic optical sizing are separated by CSS font
834
- size. Upstream describes the algorithm as novel and advises adopters to assess patent risk; see
835
- [texel-org/windfoil](https://github.com/texel-org/windfoil) and the included
836
- [third-party notice](./THIRD_PARTY_NOTICES.md).
837
-
838
- The mixed mode paints its SDF companion above Windfoil, with decorations on top. Overlapping
839
- glyphs or SVG paints split across those batches can therefore change painter order; use
840
- whole-capture `fallback: 'sdf'` when that ordering must match the source exactly.
841
-
842
- Windfoil text takes the same [`tone`](#matching-the-browser) as SDF text; `tone: false`
843
- draws the exact outline area.
475
+ `ultra-text/slug` and `ultra-text/slug-vanilla` export `createTrueTypeOutlineProvider` (uncompressed `.ttf`) and `createTracedOutlineProvider`. Missing/colour outlines use whole-capture `fallback: 'sdf'` or per-glyph `'sdf-glyphs'` companion (companion paints above vectors). Lower `targetPiecesPerBand` trades more storage for less fragment work. Windfoil upstream advises assessing patent risk ([texel-org/windfoil](https://github.com/texel-org/windfoil), [Apache-2.0 notice](./THIRD_PARTY_NOTICES.md)).
844
476
 
845
477
  #### Size switch: SDF while small (experimental)
846
478
 
@@ -851,37 +483,11 @@ const domText = await DomText.create(renderer, source, {
851
483
  })
852
484
  ```
853
485
 
854
- `windfoil.sdfBelowPx` keeps small text on the cheaper SDF path and draws a glyph with
855
- analytic Windfoil coverage once it is shown large. Plain single-paint outline glyphs, including
856
- filled SVG paint layers, are also baked into the SDF companion atlas. For every glyph and every
857
- render pass, the GPU measures the projected em: the font size times the largest stretch of the
858
- local-to-pixel mapping at the glyph's centre, in render-target (device) pixels, so a 48 CSS px
859
- heading at DPR 2 seen 1:1 measures 96. Below `sdfBelowPx` the glyph comes from the atlas; at or
860
- above it, from Windfoil. Nothing runs on the CPU per frame, and shadow maps and other passes
861
- decide with their own camera and resolution. `fallback` only governs glyphs without an outline,
862
- and a value that is not a positive finite number rejects the build.
863
-
864
- Setting it to `bakeSize` (96 by default) never magnifies the atlas beyond one texel per pixel;
865
- lower both together, including with `adaptiveBakeSize`. The switch is immediate. Both sides
866
- draw the font's own outline under the same tone, so little moves at the threshold: with Lato
867
- and Noto Sans at the default bake, in Chromium 153 on an Apple M3 Max, the SDF companion
868
- carried 0.99–1.00 of Windfoil's ink at 24 and 32 CSS px (1× and 2×), and its edges sat within
869
- about 0.1 px of Windfoil's at 96 px per em.
870
-
871
- Colour and layered glyphs and emoji always use Windfoil; glyphs without an outline always use
872
- the companion, as `fallback` allows. Fills keyed on `uv` change at the switch, so key them on
873
- `position` or `glyphIndex`. The companion costs one more atlas bake (about 1.1 MiB for
874
- printable ASCII at the default bake) and one more draw per pass, and very large glyph sets can
875
- exceed `maxAtlasSize` and reject the rebuild. The outline provider must return the face the
876
- browser renders, or the switch shows a different design. Glyphs split between the two batches
877
- follow the painter-order caveat above.
486
+ Per-frame GPU size test switches glyphs below `sdfBelowPx` device px/em to the SDF companion (~1.1 MiB for printable ASCII, 1 extra draw; colour/layer glyphs always stay vector). Set near `bakeSize`; key `fill` on `position` or `glyphIndex` rather than `uv`.
878
487
 
879
488
  ### SVG shapes (experimental)
880
489
 
881
- `svgToWindfoilOutlines` converts SVG markup, a live SVG element, SVG path records, or the
882
- structural result of Three's `SVGLoader.parse()` into closed quadratic outlines. It is
883
- synchronous and tree-shaken when unused. The smaller `windfoilOutlineFromSvgPaths` accepts
884
- DOM-free path records in workers and Node without `DOMParser`.
490
+ `svgToWindfoilOutlines` (and DOM-free `windfoilOutlineFromSvgPaths`) convert SVG paths/shapes/gradients into quadratic outlines for `createWindfoilShapes`:
885
491
 
886
492
  ```ts
887
493
  import { svgToWindfoilOutlines, createWindfoilShapes } from 'ultra-text'
@@ -890,305 +496,41 @@ const converted = svgToWindfoilOutlines(
890
496
  '<svg viewBox="0 0 24 24"><path d="M12 2L22 22H2Z"/></svg>',
891
497
  { onWarning: (warning) => console.warn(warning.code, warning.message) },
892
498
  )
893
- const outlines = { triangle: converted.outline }
894
- const shapes = await createWindfoilShapes(renderer, outlines, [
499
+ const shapes = await createWindfoilShapes(renderer, { triangle: converted.outline }, [
895
500
  { shape: 'triangle', x: 20, y: 20, size: 64, color: '#fc0' },
896
501
  ])
897
502
  scene.add(shapes)
898
503
  shapes.setInstances([{ shape: 'triangle', x: 40, y: 20, size: 96 }])
899
- // Later: remove it from the scene and release its geometry, materials and storage.
900
- shapes.dispose()
504
+ // shapes.dispose()
901
505
  ```
902
506
 
903
- Instance `x` places outline x = 0, and `y` places its descender line (outline y = `descent`)
904
- in local units. The scale is `size / unitsPerEm`.
905
- `setInstances()` changes positions, colours, clipping and counts while keeping preprocessed
906
- outlines. It validates the complete input before updating and reuses geometry buffers when
907
- the expanded paint-layer count is unchanged.
908
- Shapes are static by default (mode `'none'`): `setMotion()` updates uniforms, and the first other
909
- mode swaps in an animated material once. The handle is a `Group` with `mesh` and frozen
910
- `stats`; disposal is idempotent. It requires WebGPU and does not allocate an SDF atlas.
911
- Instance `clip` rectangles work in both compositing modes; outline `clipBox` requires
912
- `compositing: 'shader'`.
913
-
914
- Separate calls using the same outlines record or `Map`, renderer, compositing mode and band
915
- setting share prepared curves, layer indexes and GPU storage while any handle remains alive.
916
- Keep the outlines container to reuse that work; newly allocated containers build independently.
917
- Each call checks the outline contents, so edits build a new resource set while existing handles
918
- retain their original artwork. Geometry, materials and motion remain independent. Disposing the
919
- last handle releases the shared resources. A reuse reports `stats.preprocessMs: 0`;
920
- `stats.storageBytes` reports each handle's full logical storage, including shared buffers, so
921
- adding those values does not measure unique GPU allocation.
922
-
923
- Shape handles accept `compositing: 'shader'`: one quad per instance composites its paint layers
924
- top-down in the fragment shader and stops once a pixel is opaque, instead of blending one quad per
925
- layer. Each artwork also gets an adaptive layer index: a quadtree whose cells list, top-down, only
926
- the layers that can change a pixel there, classified exactly against the curves the shader
927
- integrates. A pixel walks the deepest cell its footprint fits, so close zoom uses small cells. It
928
- skips layers whose fill cannot reach the cell, takes full coverage without integrating from a layer
929
- that covers the whole cell, and stops below the first such opaque one. The result matches walking
930
- every layer, within 1/255 where a covering layer's integral would return 1 − ε. Composited layers
931
- that a pixel crosses in fewer pieces along columns, typically wide and short ones, are integrated in
932
- vertical bands. Outlines may hold up to 1024 layers, so large artwork composites in one quad.
933
-
934
- Prefer shader compositing for densely layered or magnified artwork. On one Apple M3 Max whose GPU was
935
- shared with other work, as ranges over four timing estimators and two sessions:
936
-
937
- - On the 304-layer Ghostscript tiger in a 2048² frame, it took 1.5–2.2× less GPU time than the
938
- previous 16×16 cell index at every size from 256 to 16384 px tall (2.02 against 4.24 ms at the
939
- largest). Against upstream windfoil at its best band setting it was 2.2–5.5× faster from 1024 px
940
- up, and level at 256 px.
941
- - On the demo owl it took 1.0–1.5× less time than that index.
942
-
943
- Per-layer quads (`'layers'`) still draw a thumbnail of detailed artwork faster: 1.3–1.6× on the tiger at
944
- 256 px. There, few pixels each walk several exact integrals in sequence, while per-layer quads run
945
- them in parallel.
946
-
947
- The index is built once per outline on the main thread, and the larger fragment shader compiles
948
- more slowly. On the demo, switching to the three animals cost about 80 ms more for their indexes
949
- (about 110 kB each) than with the previous grid. A cold first view also compiled 80–160 ms longer, on
950
- top of the shader-compositing pipeline already costing about 90 ms more than per-layer quads. That was
951
- measured on the same machine while other work loaded its CPU and GPU. Colour glyphs in DOM text get a
952
- much smaller index. A table past the device's storage-binding limit falls back to one cell per glyph.
953
-
954
- With shader compositing, instance opacity applies to the whole artwork, layers blend in encoded sRGB,
955
- plain outlines draw as one foreground layer, and `stats.instances` counts drawn instances rather than
956
- layers.
957
-
958
- Conversion supports all SVG path commands, basic shapes, transforms, same-document
959
- `use`/`symbol`, nested viewports, and nonzero/evenodd contour winding. Curves are approximated
960
- within `tolerance` (default `unitsPerEm / 4000`), with bounded subdivision and warnings when
961
- that bound cannot be met. Connected SVG elements can use `computedStyle: true`; markup does
962
- not load stylesheets or network resources. `layers` preserves painter order and solid,
963
- foreground, and supported gradient paints. `outline` is the merged monochrome result.
964
- Self-intersecting evenodd contours warn and fall back to nonzero; pre-resolve them with an
965
- SVG simplifier when exact parity is required. Stroke expansion, masks, filters, patterns and
966
- arbitrary clipping are not supported by this converter; inspect `warnings` or use
967
- `unsupported: 'error'` and `strokes: 'error'`.
507
+ Identical outline containers share GPU buffers across calls; `compositing: 'shader'` builds an adaptive quadtree layer index (up to 1024 layers/artwork in 1 quad: 1.5–2.2× less GPU time on the 304-layer tiger from 256–16384 px than the old 16×16 grid, 2.02 vs 4.24 ms at max size on M3 Max, at the cost of +80 ms CPU index build / +80–160 ms cold shader compile vs per-layer `'layers'` quads).
968
508
 
969
509
  ### Inline SVG
970
510
 
971
- ```ts
972
- const text = await DomSdf.create(renderer, root, {
973
- svg: { unsupported: 'error', maxPathData: 1_000_000 },
974
- motion: { enabled: false, mode: 'none' },
975
- })
976
- ```
977
-
978
- `svg: true` opts in to SVGs inside text blocks and standalone SVGs inside the capture root.
979
- The object form also accepts a `selector` (default `svg`). It requires Range layout and makes
980
- `collectDomSnapshot` asynchronous. SVG paint layers share the text atlas, clipping, shadows
981
- and motion; every layer of one icon moves together. CSS colours, fills, strokes, basic shapes
982
- and element transforms are captured at rebuild time. SVG text and foreign content, external
983
- references, filters, masks and arbitrary clip paths are not reproduced. `unsupported` defaults
984
- to `'skip'`; `'error'` reports unsupported content. CSS/SMIL animation requires explicit
985
- rebuilds. Root rotation/skew is rejected or skipped because capture layout is axis-aligned.
986
-
987
- The SDF route uses native `Path2D` for exact fill rules, strokes, joins and dashes. Filled SVGs
988
- can use Windfoil; stroke layers or ambiguous evenodd outlines follow `windfoil.fallback`.
989
- `svg: { render: 'bitmap' }` stores all authored paint colours in a single SDF slot per SVG.
990
- `images: true` also captures decoded images that pass a canvas taint probe; the library never
991
- fetches their URLs. Capture images after loading them. Bitmap shapes remain colour candidates
992
- regardless of the text `colorGlyphs` option. Bitmap capture composites nested SVG opacity
993
- groups before rasterization, then applies root and DOM opacity once. Baked paint alpha still
994
- uses the SDF silhouette: alpha below 50% is discarded, and interior alpha is hardened.
995
-
996
- `stats.glyphs` counts text glyphs, `stats.shapes` counts SVG paint-layer instances, and
997
- `stats.fallbackGlyphs` counts text glyphs without a Windfoil outline, drawn by the SDF
998
- companion, and `stats.switchableGlyphs` counts instances the size switch can draw either way.
999
- Atlas dimensions and `atlasTexture` describe that companion in mixed mode. `textStorageBytes`
1000
- includes curve, paint, composite-layer and companion texture storage. No GPU work runs on a steady frame
1001
- except rendering; capture and rasterization happen during rebuilds.
511
+ `svg: true` (or `{ render: 'bitmap', images: true, unsupported: 'error', maxPathData }`) captures inline SVGs alongside text (requires Range layout; SVG text/filters/masks/arbitrary clips are omitted).
1002
512
 
1003
513
  ### Colour layers and SVG emoji
1004
514
 
1005
- A `WindfoilGlyphOutline` can contain up to 1024 `layers`, each with closed `quadratics`, an
1006
- optional tight `bbox`, and a `paint`. `{ type: 'foreground' }` uses the captured CSS colour;
1007
- `{ type: 'solid', color: [r, g, b, a] }` uses sRGBA components in 0–1. Nonempty top-level
1008
- quadratics form an initial foreground layer. All layers share one glyph's motion and
1009
- stagger index. Layer opacity multiplies captured text alpha once. In the default
1010
- `compositing: 'layers'` mode they use ordinary painter-order blending; overlapping partially
1011
- transparent layers apply opacity separately and abutting antialiased edges may show seams.
1012
-
1013
- ```ts
1014
- import { createSvgEmojiOutlineProvider } from 'ultra-text'
1015
-
1016
- const outlineProvider = createSvgEmojiOutlineProvider({
1017
- text: fontOutlineProvider,
1018
- resolve: async (cluster, signal) => loadAppEmojiSvg(cluster, signal),
1019
- em: { unitsPerEm: 1000, ascent: 800, descent: -200 },
1020
- })
1021
- const text = await DomSdf.create(renderer, root, {
1022
- textBackend: 'windfoil',
1023
- windfoil: { outlineProvider, fallback: 'sdf-glyphs' },
1024
- })
1025
- ```
1026
-
1027
- The application owns the art and loading. `resolve` receives the original complete cluster
1028
- and returns SVG text or `null`; no artwork or network client ships in the library. The helper
1029
- caches converted emoji, centres them in the measured platform advance, and respects aborts.
1030
- Its cache uses Twemoji's filename convention: remove FE0F only for clusters without ZWJ,
1031
- then join lowercase hexadecimal code points with hyphens. FE0E requests use the text font.
1032
- Provide `em.descent` to select the reference baseline explicitly, or let the text provider
1033
- supply its metrics. That baseline sits on the captured text baseline; where a capture has
1034
- none, the bottom of the em box sits on the bottom of the text box. Keep emoji artwork
1035
- licences and attribution with your assets.
1036
- Translucent SVG groups containing multiple paints cannot be flattened faithfully into layers;
1037
- the helper returns `null` for those SVGs so the configured fallback can render them.
1038
-
1039
- The demo's emoji comparison preserves the platform font instead of substituting SVG
1040
- artwork. For Windfoil it vectorises each native emoji bitmap in the browser: regions of
1041
- smoothly varying colour become layers with curve-fitted outlines, flat regions use solid
1042
- paints, and `fill` paints the shaded ones from colour sheets cut from the same bitmap, with
1043
- matching layout and glyph metrics. The first frame shows the traced bitmap; the layers
1044
- replace it once the page is idle. Hard edges are analytic at any zoom, while gradients,
1045
- glows, see-through artwork and detail about two texels wide keep the bitmap's softness.
1046
- No traced artwork ships with the package.
1047
-
1048
- Windfoil also accepts `linear`, `radial` and `sweep` gradient paints. Stops contain `offset`
1049
- and sRGBA `color`; `extend` is `'pad'`, `'repeat'` or `'reflect'`. Paint coordinates are in
1050
- outline font units; an optional affine transform maps the gradient into those units.
1051
- Linear gradients use `p0`, `p1` and optional `p2`; radial gradients use `c0`, `r0`, `c1`, `r1`;
1052
- sweeps use `center`, `startAngle` and `endAngle` in degrees. SVG linear/radial gradients are
1053
- imported, including stop opacity and gradient transforms. Sweep gradients are authored through
1054
- the paint API because SVG has no native sweep-gradient element. Gradient interpolation and
1055
- shader layer compositing use encoded sRGB, then convert the resulting colour to linear RGB.
1056
-
1057
- Opt-in `windfoil: { outlineProvider, compositing: 'shader' }` composites all layers of each
1058
- colour glyph before applying text alpha. It gives correct whole-glyph group opacity and walks
1059
- only the layers that can reach each pixel, stopping once it is opaque; nested SVG opacity groups
1060
- are not represented.
1061
- A glyph-local `clipBox: [xMin, yMin, xMax, yMax]` uses analytic
1062
- rectangle coverage in `DomSdf` and automatically selects this composite path for that glyph, including
1063
- base-only outlines and captures using `compositing: 'layers'`. Colour glyphs use their own instanced
1064
- batch, and ordinary glyphs retain their simpler shader. The default remains `'layers'`;
1065
- measure both modes on your target hardware for dense or large artwork. Shape handles support
1066
- layer paints and gradients and accept the same `compositing` option.
1067
-
1068
- An application adapting COLRv1 data must expand `PaintColrLayers` and `PaintColrGlyph` into
1069
- ordered layers, bake outline transforms into the paths, and put paint-only transforms in
1070
- the paint's `transform`. Only source-over composition is supported; map a font ClipBox to
1071
- the outline's `clipBox`. Other composite modes, arbitrary clip paths, masks, filters and
1072
- variable paints need an application fallback. Coincident antialiased edges can show seams;
1073
- gradient output is not dithered.
515
+ `WindfoilGlyphOutline` supports up to 1024 solid, foreground, `linear`, `radial`, or `sweep` gradient layers with optional `clipBox`. Wrap your text provider with `createSvgEmojiOutlineProvider` (Twemoji hyphenated hex cache, app-owned SVG files) to draw vector emoji on analytic backends.
1074
516
 
1075
517
  ## Text backends and atlas modes
1076
518
 
1077
- SDF colour glyphs use an optional sRGB RGBA band beside the single-channel distance field.
1078
- Canvas extraction runs once during the atlas rebuild on the main thread and works with GPU,
1079
- CPU, CPU Worker and WebGL2 fallback atlas generation. The band uses about 80 KB per emoji at
1080
- `bakeSize: 96`, plus roughly one third for `quality: 'high'` mipmaps. Mixed shaped runs also
1081
- place their text in the band. `stats.textStorageBytes` includes these GPU texels; the retained
1082
- CPU upload copy is excluded. Captures without verified colour ink keep the original shader.
1083
- `stats.colorGlyphs` counts captured text glyphs with colour ink, so a mixed browser run counts
1084
- once. Low-level callers pass `atlas.colorLayer`, `atlas.bakeSize` and `atlas.shapeTop` to
1085
- `SdfTextMaterial` and dispose the full atlas. `shapeTop` marks the atlas rows of monochrome SVG
1086
- shapes, which keep their exact coverage while text takes the tone: keep it with the other
1087
- fields wherever an atlas is copied or restored from stored bytes.
1088
- Apple Color Emoji is a bitmap font whose largest strike is 160 px. In Chrome on macOS, a larger
1089
- `bakeSize` resamples that bitmap and ripples emoji edges once magnified; bake large emoji at 160.
1090
-
1091
- Colour extraction uses a byte visitation grid and dilates from the ink boundary. Temporary
1092
- classification/queue arrays use five bytes per band texel, in addition to the four-byte RGBA
1093
- output.
1094
-
1095
- An atlas made with `colorGlyphs: 'none'` or an older library version has untested slots.
1096
- Such an atlas is not reused for colour candidates: the capture builds a private atlas.
1097
- Rebuild atlases stored by an earlier version: the bake no longer carries the platform's font
1098
- smoothing, and the colour band's alpha now tells colour ink (1) from text ink (0).
1099
- Whole emoji sequences use different keys from their former components, so rebuild shared
1100
- atlases that were prepared per code point. Each sequence needs roughly a 1.2 em square slot.
1101
-
1102
- `textBackend` chooses retained coverage. `atlasMode` only changes SDF generation:
1103
-
1104
- `DOM → layout snapshot → Canvas glyph mask → SDF atlas → instanced geometry + TSL materials`
1105
-
1106
- The transient mask uses deterministic shelf and skyline candidates across a bounded search
1107
- of aligned widths. Glyphs are never rotated, and the smallest tested used area is retained.
1108
-
1109
- - `gpu` requires a real `WebGPUBackend` and fails if one is unavailable, if the device's
1110
- limits cannot hold the passes (workgroup size, storage buffers per stage, two of them in the
1111
- fragment stage, the atlas's jump-flood buffers at 8 bytes per texel and its glyph-mask copy
1112
- at 4 bytes per texel in 256-byte rows, or its largest 2D texture), if the backend cannot copy
1113
- the mask into a buffer, or if the device reports an error for them. The passes read the mask
1114
- from that buffer, so none of their pipelines samples a texture. It runs on
1115
- compatibility-mode devices as well as core ones. The passes are WGSL compute and render
1116
- passes on the renderer's own device, compiled once per device, and the atlas texture is an
1117
- `ExternalTexture` the atlas owns.
1118
- - `cpu` runs an exact Euclidean distance transform and uploads an R8 `DataTexture`.
1119
- By default the transform runs in a short-lived module Worker; `cpuWorker: false` runs it
1120
- on the main thread. Both modes produce identical bytes.
1121
- - `auto` tries the GPU path first, then falls back to the CPU path in each of those
1122
- cases, including when an atlas is too large for the GPU path.
1123
- - `textBackend: 'windfoil'` resolves quadratic outlines, splits them into monotone pieces,
1124
- files horizontal row bands, and evaluates analytic coverage per fragment. Beauty and
1125
- shadow masks reject fragments outside the block before integrating curves.
1126
-
1127
- Both SDF modes consume the same Canvas glyph mask and produce the same retained atlas.
1128
- Windfoil has a separate lifecycle. It reports no atlas texture unless the opt-in mixed mode or size switch has an SDF companion.
1129
-
1130
- Plain text glyphs draw only the part of their quad where the distance field is not empty:
1131
- `rasterizeGlyphAtlas` records that box as `GlyphSlot.support`, `createGlyphGeometry` writes it
1132
- per glyph as the `sdfTrim` attribute, and `SdfTextMaterial` shrinks each quad to it, which
1133
- leaves about 60% fewer fragments for the same ink. Quads stay whole with outlines or drop
1134
- shadows, with run motion, and over mipmapped atlases (`quality: 'high'` DomSdf captures). A
1135
- custom position graph that places corners from `positionGeometry` itself should delete
1136
- `sdfTrim` from its geometry; code that rewrites `sdfUvRect` to show another glyph keeps whole
1137
- quads for those instances unless it rewrites `sdfTrim` with it.
1138
-
1139
- The HTML/3D demo's SDF mode explicitly uses CPU atlases to reduce first-use GPU compilation for its
1140
- small document; `?atlas=gpu` compares the GPU path. The package default remains `auto`.
1141
-
1142
- A GPU bake records the upload, the seed and jump-flood compute passes (ending in a shared-memory
1143
- tiled `step = 2, 1` tail) and the resolve in one command buffer; when the adapter offers
1144
- `texture-formats-tier1`, the resolve writes directly to the `r8unorm` atlas storage texture with no
1145
- render pass. The shader module, its pipelines and per-step uniform slots are made on the device's
1146
- first atlas and kept for the device's lifetime, so later bakes and atlas patches only allocate their
1147
- seed buffers, which they destroy once the device has accepted the submission; a `DomSdf` makes them
1148
- before it reads the DOM, and the device compiles them meanwhile. When only a WebGPU atlas will read
1149
- the glyph mask (no colour candidates, `atlasMode` other than `'cpu'`, an initialized WebGPU
1150
- backend), the mask is drawn on a GPU-backed canvas, which skips the software canvas's set-up on a
1151
- page's first bake and is copied on the GPU; the CPU fallback of a failed GPU bake then reads it
1152
- back slowly. On Apple M3 Max with headless Chrome 157 (the comparison benchmark below, `--full`), a
1153
- 1,000-glyph paragraph reaches GPU completion of its first frame in 39.3 ms (200 labels in 45.3 ms),
1154
- edits 10 known letters in 2.8 ms, and bakes plus draws a never-seen letter in 4.1 ms on the GPU
1155
- atlas.
1156
-
1157
- `stats.textStorageBytes` is retained backend payload only. It excludes geometry, Canvas backing
1158
- stores, pipelines, provider caches, and transient bake memory; GPU SDF seeds use 8 bytes per atlas
1159
- texel (`u32` packed `(x + 1) | ((y + 1) << 16)` across two ping-pong buffers) while a bake is
1160
- active, and the mask's `rgba8unorm` upload texture (4 bytes per texel) lives only until the seed
1161
- pass reads it. CPU
1162
- encoding uses one 4-byte-per-texel working grid plus `28 × height + 8` bytes of column scratch,
1163
- excluding the RGBA input, its alpha and the R8 output. DOM capture and the Canvas mask still
1164
- run on the main thread, and so does the mask's `getImageData` readback for colour candidates and
1165
- CPU atlases. CPU workers receive the mask's RGBA
1166
- pixels, take their alpha and transfer the encoded bytes back; they terminate on completion or
1167
- cancellation and preserve the previous content during transactional rebuilds. If Workers are unavailable or blocked by
1168
- CSP, baking falls back to the synchronous CPU encoder. A cancellation never starts that
1169
- fallback. Ship the generated worker asset with the package and allow it in `worker-src`.
1170
- The GPU path is unchanged and does not create a CPU worker. Latency- and memory-constrained
1171
- apps should cap `maxAtlasSize`, prefer strict `atlasMode: 'gpu'`, reserve known characters,
1172
- and retain native UI if WebGPU initialization fails:
519
+ - **SDF (`textBackend: 'sdf'`, default)**: `DOM → layout snapshot → Canvas glyph mask → SDF atlas → instanced geometry + TSL materials`.
520
+ - GPU bake (`atlasMode: 'gpu'` / `'auto'`): writes mask once into a buffer, runs a **single tiled compute pass** (`tiledStoreMain`) directly to the `r8unorm` storage texture on `texture-formats-tier1` when `padding <= 12` (**1 lazily compiled compute pipeline** instead of 4; multi-pass `seed`/`jump`/`resolve` compile lazily only for larger `padding` or non-tier1 fallback). On Apple M3 Max / Chrome 157: **4.56 ms** GPU bake (`2026-11-22` W5; `5.35 ms` in `2026-11-19` `33.9 ms` cold full run), **`5.3 MiB`** peak VRAM (`0.64 MiB` resident). `sdfTrim` trims empty quad padding (~60% fewer fragments).
521
+ - CPU bake (`atlasMode: 'cpu'` or automatic fallback): exact EDT in a cancellable Worker (`cpuWorker: true`), uploading the identical R8 `DataTexture`.
522
+ - Colour glyphs (`colorGlyphs: 'emoji'` / `'all'`) share an optional sRGB RGBA band (~80 KB/emoji at `bakeSize: 96`; Apple Color Emoji max strike is 160 px on macOS).
523
+ - **Analytic (`'slug'` / `'windfoil'`)**: monotone-split curve buffers (`0.17 MiB` TTF / `0.21 MiB` traced for 1,000 glyphs); no atlas texture unless `outline`, `dropShadow`, or `sdf-glyphs` creates an SDF companion.
1173
524
 
1174
- ```ts
1175
- const hud = await DomSdf.create(renderer, source, {
1176
- atlasMode: 'gpu',
1177
- maxAtlasSize: 1024,
1178
- extraGlyphs: '0123456789.%+-/ms',
1179
- observe: false,
1180
- castShadow: false,
1181
- motion: { enabled: false, mode: 'none' },
1182
- })
1183
- ```
525
+ Perf-sensitive HUDs should set `atlasMode: 'gpu'`, `maxAtlasSize: 1024`, `extraGlyphs`, `observe: false`, `castShadow: false`, and `motion: { enabled: false, mode: 'none' }`.
1184
526
 
1185
527
  ## Public API
1186
528
 
1187
- Import only from the package root; deep imports are not part of the supported API.
529
+ Import from `ultra-text`, `ultra-text/slug`, `ultra-text/vanilla`, or `ultra-text/slug-vanilla` only; deep imports are unsupported.
1188
530
  [`src/index.ts`](https://github.com/Makio64/ultra-text/blob/main/src/index.ts)
1189
- defines that boundary, and
531
+ defines the root boundary, and
1190
532
  [`src/types.ts`](https://github.com/Makio64/ultra-text/blob/main/src/types.ts)
1191
- defines its public data contracts.
533
+ defines public contracts.
1192
534
 
1193
535
  | Export | Purpose |
1194
536
  | --------------------- | ----------------------------------------------------------------------------------------------- |
@@ -1202,18 +544,7 @@ defines its public data contracts.
1202
544
  | `createRectMaterial` | Build the lit or unlit TSL rounded-rectangle material; `DoubleSide` draws in one pass. |
1203
545
  | `reflowSnapshot` | Re-wrap a retained snapshot without reading the DOM. |
1204
546
 
1205
- `DomText` (and its backward-compatible alias `DomSdf`) extends `THREE.Group` and exposes `width`,
1206
- `height`, `stats`, and `atlasTexture`, plus `setMotion()`, `reflow()`, `rebuild()`, and `dispose()`.
1207
- `stats.textBackend` reports the active path. `atlasMode` is null for pure Windfoil; mixed mode reports its companion atlas, and
1208
- `textStorageBytes` estimates retained texture or curve/row storage. `atlasTexture` is also
1209
- null under pure Windfoil.
1210
-
1211
- The package root also exports all matching TypeScript types. Callers own resources returned
1212
- by the lower-level atlas, geometry, and material APIs.
1213
-
1214
- The root also exports `svgToWindfoilOutlines`, `windfoilOutlineFromSvgPaths`,
1215
- `createWindfoilShapes`, and `createSvgEmojiOutlineProvider`. All are imported from
1216
- `'ultra-text'`; internal modules are not public package subpaths.
547
+ `DomText` (`DomSdf`) extends `THREE.Group` and exposes `width`, `height`, `stats`, `atlasTexture`, `setMotion()`, `reflow()`, `rebuild()`, and `dispose()`. Under pure Windfoil/Slug, `atlasTexture` and `atlasMode` are `null` (`textStorageBytes` reports curve/row storage). Callers own resources returned by lower-level helpers and types exported alongside `svgToWindfoilOutlines`, `windfoilOutlineFromSvgPaths`, `createWindfoilShapes`, and `createSvgEmojiOutlineProvider`.
1217
548
 
1218
549
  ### Exported types
1219
550
 
@@ -1274,98 +605,29 @@ Additional SVG/vector contracts are exported as types:
1274
605
 
1275
606
  ## Limitations
1276
607
 
1277
- This is a selective visual reconstruction, not a general DOM renderer.
1278
-
1279
- - SDF silhouettes remain single-channel, without true-MSDF corner reconstruction. Colour
1280
- glyphs use the canvas default palette; `font-palette` and `font-variant-emoji` are not
1281
- captured. Interior raster alpha below 50% is outside the SDF silhouette. Colour detail
1282
- magnifies at the baked resolution, while the silhouette retains its SDF edge.
1283
- - Windfoil and Slug are experimental, WebGPU-only and nonzero-fill, and their edges are only as
1284
- exact as their outlines: app-owned font outlines are exact, while traced outlines (no
1285
- `outlineProvider`) follow the browser's raster at 256 px per em to about 0.006 em and cost
1286
- main-thread time, about 1.2 ms per CJK glyph. They do not add shaping or CSS fidelity. Their
1287
- antialiasing box is axis-aligned in glyph space and sized to each pixel's footprint, so rotated
1288
- or sheared text approximates, rather than equals, an exact screen-pixel filter.
1289
- - By default, glyphs are rasterized by code point, except whole emoji sequences. Emoji
1290
- sequences split across text nodes require browser shaping. Combining marks (U+0301 and friends) are
1291
- approximated, not shaped: a zero-width mark is anchored at the caret after its base glyph
1292
- using canvas metrics, which covers common accents but is not full shaping.
1293
- - Browser shaping, CJK reflow, RTL reflow, and legacy reshaping are [opt-in](#optional-language-support).
1294
- Browser shaping retains ligatures and emoji ZWJ sequences as run masks. Vertical writing
1295
- remains unsupported.
1296
- - `selectable: true` adds a CSS class only. The app must align and style the native DOM
1297
- overlay for selection and copying.
1298
- - Form controls: interactive input elements (`<input>`, `<textarea>`, `<select>`, and
1299
- `contenteditable`) should remain native DOM elements rather than converted to SDF blocks, as
1300
- IME composition, caret navigation, and form state are native browser responsibilities.
1301
- - CSS `text-transform` follows Chrome's rules: `uppercase` and `lowercase` honour `lang` only
1302
- for Turkish, Azerbaijani, Greek and Lithuanian, and `capitalize` ignores it. `full-width`
1303
- applies where the browser computes it (Firefox, Safari); `full-size-kana`, `math-auto` and
1304
- `::first-letter`/`::first-line` styles are not applied. With Range, a character that maps to
1305
- several (ß → SS) splits its source box by advance, and their marks (ǰ → J̌) are approximated
1306
- like other combining marks. A text node whose mapping cannot be split back per character maps
1307
- each character alone, without context rules such as Lithuanian dot insertion.
1308
- - Strokes, shadows, gradients, filters, blend modes, masks, and CSS-transformed text are not
1309
- reproduced. Use the explicit `outline`, `dropShadow`, and `fill` options for supported GPU
1310
- text effects.
1311
- - Rectangles support a solid background, effective opacity, and one uniform radius. Borders,
1312
- per-corner radii, images, CSS shadows, transforms, and clip paths are not reproduced.
1313
- - Text uses a finite rectangular clip per marked block. On axes with CSS `overflow: visible`,
1314
- it includes the captured text boxes so tight line heights keep their descenders. Other
1315
- overflow values keep the block bounds; arbitrary ancestor clipping is not reproduced.
1316
- - A captured line keeps its layout position. The browser paints each line with its top rounded
1317
- to a whole layout pixel, so text laid out between pixel rows (a `1.4` line height at 16 px,
1318
- a block centred on a half pixel) can sit up to half a layout pixel from the painted DOM in a
1319
- 1:1 overlay. Whole-pixel line heights and offsets match the DOM exactly, and the opt-in
1320
- [`pixelSnap`](#pixel-snapping) applies the browser's rounding to a flat 1:1 overlay.
1321
- - Text weight follows the browser through `tone`, measured against Chrome on macOS only; see
1322
- the [measured limits](#measured-limits).
1323
- - Hidden, transparent, disconnected, or zero-size source content is skipped or rejected.
1324
- - Creation and rebuilds perform real layout and atlas work; very large dynamic documents can
1325
- be expensive.
1326
-
1327
- Use native DOM text or a shaping-aware true-MSDF pipeline when exact shaping, sharp
1328
- high-contrast corners, or full CSS fidelity is required.
1329
-
1330
- ## Browser support
608
+ Selective visual reconstruction, not a general DOM renderer:
1331
609
 
1332
- | Browser | Status | Notes |
1333
- | ------------------- | ------------------ | ------------------------------------------------------------------------------------------------------- |
1334
- | Chrome / Edge 128+ | Tested | Chromium WebGPU end-to-end suite of the development repository. |
1335
- | Safari 26+ | Expected, untested | Ships WebGPU by default; not covered by automated tests. |
1336
- | Firefox 141+ | Expected, untested | Ships WebGPU; not covered by automated tests. |
1337
- | Non-WebGPU browsers | SDF only, untested | `WebGPURenderer` may fall back to WebGL2 with `atlasMode: 'auto'` or `'cpu'`; Windfoil and Slug cannot. |
610
+ - Single-channel SDF (no true-MSDF corners); colour detail magnifies at `bakeSize` (interior alpha < 50% outside silhouette).
611
+ - Analytic `windfoil`/`slug` follow outline fidelity (~0.006 em if traced on main thread; ~1.2 ms/CJK glyph) with axis-aligned glyph-space AA boxes.
612
+ - Code-point glyphs by default (zero-width marks approximated; vertical writing unsupported). Full shaping/ligatures/bidi need opt-in `textShaping: 'browser'`.
613
+ - Keep interactive form controls (`<input>`, `<textarea>`, `<select>`, `contenteditable`) and selectable text (`selectable: true` CSS overlay) in native DOM.
614
+ - CSS strokes, gradients, filters, blend modes, masks, borders, images on boxes, CSS transforms, `::first-letter`/`::first-line`, and ancestor non-block clips are omitted.
615
+ - Half-pixel line placement without `pixelSnap: true`; `tone` calibrated against Chrome on macOS only.
1338
616
 
1339
- In production, serve over HTTPS, await `WebGPURenderer.init()`, and inspect the initialized
1340
- backend instead of relying on `navigator.gpu` alone.
617
+ ## Browser support
1341
618
 
1342
- The [gallery](https://ultra-text.makio.io/) automatically tries WebGL2 if WebGPU initialization fails, and its SDF atlases
1343
- can fall back to CPU generation when GPU baking fails. A failed startup shows the actual
1344
- error, phase and backend, with retry links and **Copy diagnostics** for browser, URL,
1345
- secure-context and stack details. An available WebGPU API alone does not guarantee a usable
1346
- adapter or a successful scene build.
619
+ | Browser | Status | Notes |
620
+ | ------------------- | ------------------ | ---------------------------------------------------------------------------------------------------- |
621
+ | Chrome / Edge 128+ | Tested | Chromium WebGPU end-to-end suite (local and manual CI). |
622
+ | Safari 26+ | Expected, untested | Ships WebGPU by default; not automated. |
623
+ | Firefox 141+ | Expected, untested | Ships WebGPU; not automated. |
624
+ | Non-WebGPU browsers | SDF only, untested | `WebGPURenderer` falls back to WebGL2 with `atlasMode: 'auto'` or `'cpu'`; Windfoil and Slug cannot. |
1347
625
 
1348
- The package is browser-only at runtime. Guard `DomSdf.create()` during SSR.
626
+ Serve over HTTPS in production, await `renderer.init()`, guard SSR (`DomSdf.create()` is browser-only), and inspect the active backend.
1349
627
 
1350
628
  ## Comparison with other 3D web text libraries
1351
629
 
1352
- ultra-text renders the HTML you already have, with the fonts the page already loaded: there is
1353
- no font file to fetch or bake, layout and line breaking come from the browser, colour emoji keep
1354
- their colours, and one capture draws a whole subtree. Both its single-channel SDF backend (GPU
1355
- JFA) and its analytic Slug vector backend render faster per frame and hold less GPU memory than
1356
- their distance-field and vector peers on an ASCII bake (0.64 MiB vs 1.44–2.04 MiB and 0.17 MiB vs
1357
- 0.24 MiB, tying glyph Slug at 0.17 MiB if subsetted to the paragraph's 49 characters), while
1358
- `reflow()` re-wraps 1,000 glyphs faster than any other engine. Editing characters already in the atlas lands within half a millisecond across all
1359
- three libraries (2.4–2.9 ms); adding an unbaked glyph on the spot or rebuilding 200 DOM nodes at
1360
- once remains faster in libraries that skip the DOM read or pre-bake every glyph.
1361
-
1362
- The numbers below come from one browser benchmark kept with the development sources (not part
1363
- of this repository; `--full` run on 2026-11-15): each library on the three.js renderer it supports, in the same
1364
- headless Chrome 157, on an Apple M3 Max (macOS 15.8), with `three` `0.188.0-dev.29c99f4` on every
1365
- page, the same font (Noto Sans Regular), the same 1,000-glyph paragraph or 200 HUD labels, and a
1366
- shared 3200×2400 RGBA8 sRGB render target. Cells report medians across 10 cold loads, 30 dynamic
1367
- edits, 32 width changes and 8 Williams-balanced steady-state rounds on a shared developer machine
1368
- (read timings as ranges). three-mesh-ui and drei `<Html>` were not measured.
630
+ `ultra-text` renders browser HTML/CSS and loaded fonts directly—zero offline bake or font-file fetch—in 1 draw call per subtree. Compared head-to-head on [the online benchmark summary](https://ultra-text.makio.io/docs#comparison) (headless Chrome 157, Apple M3 Max / macOS 15.8, `three` `0.188.0-dev.29c99f4`, Noto Sans Regular, 1,000-glyph paragraph & 200 HUD labels, `3200×2400` RGBA8 sRGB): steady frames from the uncontended `2026-11-15` `--full` baseline (`U-sdf` A/A within ±1% `E2`), cold/update/relayout from `2026-11-19` `--full` (`n=10/30/32`, W4 `P-tilt`/`D-160` had external load so `2026-11-15` holds steady cells), GPU memory from `2026-11-22` (`ultimate-perf-1122` W5), and payloads/reflow CPU from `2026-11-23`. `three-mesh-ui` and drei `<Html>` were not measured.
1369
631
 
1370
632
  ```text
1371
633
  Steady frame · 200 HUD labels (3200×2400, E1 ms/frame — lower is faster)
@@ -1382,11 +644,11 @@ Steady frame · 1,000-glyph paragraph (3200×2400, E1 ms/frame — lower is fast
1382
644
  @pmndrs/glyph Slug (vector) ████████████████████████ 0.206 ms · 2 draws
1383
645
 
1384
646
  Width relayout · 1,000 glyphs (480–720 px cycle — lower is faster)
1385
- ultra-text reflow() ██████████ 1.51 ms
647
+ ultra-text reflow() █████████ 1.46 ms
1386
648
  @pmndrs/glyph MSDF █████████████ 1.95 ms
1387
- troika Text ████████████████ 2.52 ms
1388
- @pmndrs/glyph Slug ████████████████ 2.54 ms
1389
- ultra-text CSS + rebuild() ████████████████████████ 3.74 ms
649
+ @pmndrs/glyph Slug ███████████████ 2.31 ms
650
+ troika Text ███████████████ 2.37 ms
651
+ ultra-text CSS + rebuild() ████████████████████████ 3.71 ms
1390
652
 
1391
653
  Resident GPU memory · 1,000-glyph paragraph (lower is leaner)
1392
654
  ultra-text Slug (TTF) ██ 0.17 MiB
@@ -1396,103 +658,63 @@ Resident GPU memory · 1,000-glyph paragraph (lower is leaner)
1396
658
  troika Text (slab + canvas) ████████████████████████ 2.04 MiB
1397
659
  ```
1398
660
 
1399
- | | `ultra-text` 0.1 (SDF) | `ultra-text` 0.1 (Slug) | `@pmndrs/glyph` 0.1.0 | `troika-three-text` 0.53.1 (drei `<Text>`) |
1400
- | :------------------------------------- | :----------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------- |
1401
- | three.js renderer | `WebGPURenderer`; raw WebGPU through `ultra-text/vanilla` | `WebGPURenderer`; raw WebGPU through `ultra-text/slug-vanilla` | `WebGPURenderer` (classic `WebGLRenderer` unsupported) | classic `WebGLRenderer` only (GLSL through `onBeforeCompile`) |
1402
- | Fonts | whatever the page loaded (WOFF2, variable, system fonts, colour emoji); no bake step | runtime font outlines or zero-file Canvas 2D glyph trace; no offline bake step | a `.font.glb` from its CLI (Noto Sans ASCII, 132 glyphs: 3.1 s, 1.55 MB, 295 kB brotli) or a runtime bake of TTF/OTF; no WOFF/WOFF2 or variable fonts | a `.ttf`/`.otf`/`.woff` URL (`.woff2` throws); missing characters load from a CDN |
1403
- | Layout | the browser's own CSS layout (Range) or Pretext | the browser's own CSS layout (Range) or Pretext | its own shaping and layout (HarfRust in Wasm) | its own layout in a worker |
1404
- | First frame, 1,000-glyph paragraph [1] | 39.3 ms (GPU), 63.8 ms (CPU) | 43.3 ms (TTF), 91.5 ms (traced) | 50.2 ms (MSDF), 56.8 ms (Slug) | **23.9 ms** |
1405
- | First frame, 200 labels [1] | 45.3 ms (one capture) | one capture over all 200 | 76.0 ms | 39.0 ms (200 `Text`), **25.8 ms** (`BatchedText`) |
1406
- | Edit 10 letters already drawn [2] | 2.8 ms | 3.0 ms (traced), 3.1 ms (TTF) | 2.9 ms (MSDF & Slug) | **2.4 ms** |
1407
- | Edit adding a never-drawn letter [2] | 4.1 ms (GPU atlas), 3.6 ms (CPU atlas), 2.8 ms with `extraGlyphs` | 8.6 ms (TTF), 10.9 ms (traced) | **2.5 ms** MSDF, 2.8 ms Slug (baked ahead) | 3.0 ms |
1408
- | Width change, 1,000 glyphs [2] | **1.51 ms** with `reflow()`; 3.7 ms with CSS + `rebuild()` | 3.6–3.7 ms with CSS + `rebuild()` | 1.95 ms (MSDF), 2.54 ms (Slug) | 2.52 ms |
1409
- | Frame, 1,000 glyphs / 160 px [3] | **0.075 ms** / **0.087 ms** | 0.158 ms / 0.168 ms (0.053 ms net GPU at 160 px) | 0.129 / 0.156 ms (MSDF); 0.206 / 0.213 ms (Slug) | 0.144 ms / 0.142 ms |
1410
- | Frame, 200 labels [3] | **0.074 ms** | 1 draw per subtree | 0.211 ms | 1.69 ms (200 `Text`), 0.153 ms (`BatchedText`) |
1411
- | Draw calls, paragraph / 200 labels | **1 / 1** | **1 / 1** | 2 / 2 (double-sided text in two passes) | 1 / 200 (1 with `BatchedText`) |
1412
- | GPU memory, paragraph [4] | **0.64 MiB** (10.0 MiB while the GPU atlas bakes; 0.64 MiB peak on CPU) | **0.17 MiB** TTF (0.28 MiB traced) | 1.44 MiB MSDF, 0.24 MiB Slug for ASCII bake (0.85 / 0.17 MiB for the paragraph's 49 chars) | 2.04 MiB (1.04 MiB 256-glyph RGBA slab & buffers + 1.00 MiB SDF generator canvas) |
1413
- | Zoom 10× / 100× [5] | sharp / soft SDF stems (`textBackend: 'windfoil'` also analytic) | **exact quadratic curves** at 100× | MSDF keeps corners; Slug exact | sharp / corners round |
1414
- | Outline and drop shadow | on every backend | on every backend (SDF underlay) | MSDF only | outline with blur and offset, inner stroke |
1415
- | Colour emoji | **yes**, the browser's own | **yes**, SDF colour companion | not yet (roadmap) | monochrome |
1416
- | JS + Wasm, min+gzip | **39.0 kB** `DomText + Text` (34.9 kB brotli; 51.2 kB gzip with SVG shape helpers) | +12.0 kB lazy chunk (+10.9 kB brotli; standalone `ultra-text/slug`: 43.8 kB, 38.8 kB brotli) | 122.3 kB JS + 501.0 kB shaper Wasm (623.3 kB; 494.6 kB brotli) | 42.2 kB `Text` (36.6 kB brotli; 44.3 kB with `BatchedText` + `preloadFont`) |
1417
-
1418
- 1. From the first authoring call to GPU completion of the first frame, with the font already
1419
- loaded through each library's own API and warm native shader caches (`n = 10` Williams-balanced
1420
- rounds). ultra-text spends 10.7 ms of its 39.3 ms SDF first frame baking the 96 px R8 atlas on
1421
- the GPU (9.7 ms packing Slug curves in `U-slug`), 6.6 ms reading DOM layout and 13.8 ms in the
1422
- first render, where three builds the text material's shaders; troika typesets in a worker and
1423
- generates 64 px glyph SDFs with WebGL as they are first used.
1424
- 2. From the mutation call to GPU completion of the next frame (`n = 30` edits, `n = 32` width
1425
- changes). `rebuild()` reads the DOM again; `reflow()` re-wraps the retained capture in 0.61 ms
1426
- of main-thread JS without reading the DOM. A never-drawn letter is rasterized from CSS and
1427
- patched into the live atlas (see [Dynamic text and reflow](#dynamic-text-and-reflow)); glyph
1428
- only switches among glyphs baked ahead into its `.font.glb`.
1429
- 3. Whole frames at 3200×2400 by batch completion (`E1`, `n = 8` Williams-balanced rounds),
1430
- including each renderer's clear and store of the target; GPU pass timestamps (`E2`) and
1431
- per-process `ioreg` GPU time (`E3`) rank them the same way (`troika ÷ ultra-text` 1.67–2.02 on
1432
- the paragraph, `glyph MSDF ÷ ultra-text` 1.10–1.73, `glyph Slug ÷ ultra-text SDF` 2.06–2.76;
1433
- comparing vector backends directly on 160 px display text, `ultra-text` Slug costs 0.053 ms net
1434
- GPU time against `glyph` Slug's 0.090 ms). An empty frame costs about 0.13–0.14 ms on
1435
- `WebGLRenderer` and 0.058–0.060 ms on `WebGPURenderer`: net of the empty frame on the paragraph,
1436
- text costs 0.010 ms (`E2`) to 0.016 ms (`E1`) on `ultra-text` SDF, 0.008 ms on `troika`, and
1437
- 0.017–0.071 ms on `glyph` MSDF (two passes + per-frame `glyph.shape()`). 200 troika `Text`
1438
- objects are CPU-bound (1.68 ms of CPU per frame vs 0.012 ms for one `ultra-text` capture and
1439
- 0.208 ms for 200 `glyph` texts).
1440
- 4. Textures and buffers each library allocates after renderer baseline, estimated at the API.
1441
- glyph's `1.44 MiB` MSDF and `0.24 MiB` Slug figures are for the 132-glyph ASCII bake (subsetting
1442
- to the paragraph's 49 code points yields `0.85 MiB` MSDF and `0.17 MiB` Slug); troika allocates a
1443
- pre-sized `2048×128` RGBA8 256-glyph atlas slab + scratch/geometry buffers (`1.04 MiB`, 19%
1444
- occupied at the paragraph's 48 unique glyphs) plus its persistent `preserveDrawingBuffer`
1445
- auxiliary SDF generator canvas (`1.00 MiB`).
1446
- 5. Verified on the `shots/zoom-grid.png` contact sheet of each run (1×, 10× and 100× magnification
1447
- of `"Rag Kerning quartz 0.5% Ж"` at 18 px beside Chrome's own DOM text).
1448
-
1449
- Bundle and Wasm download sizes (`JS + Wasm, min+gzip`) are measured locally under identical settings
1450
- (Vite 8, `es2022`, `NODE_ENV=production`, `three/*`
1451
- external, `gzip -9` and `brotli`, decimal `1 kB = 1,000 B`). Qualitative facts not measured here
1452
- come from each project's documentation and source, checked on 2026-11-15:
1453
- [glyph's README](https://github.com/pmndrs/glyph) (renderers, formats, effects, emoji roadmap) and
1454
- [troika's README](https://github.com/protectwise/troika/tree/main/packages/troika-three-text)
1455
- (renderer, font formats, CDN fallback, effects).
661
+ | | `ultra-text` 1.0 (SDF) | `ultra-text` 1.0 (Slug) | `@pmndrs/glyph` 0.1.0 | `troika-three-text` 0.53.1 (drei `<Text>`) |
662
+ | :------------------------------------- | :----------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------ | :---------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------- |
663
+ | three.js renderer | `WebGPURenderer`; raw WebGPU through `ultra-text/vanilla` | `WebGPURenderer`; raw WebGPU through `ultra-text/slug-vanilla` | `WebGPURenderer` (classic `WebGLRenderer` unsupported) | classic `WebGLRenderer` only (GLSL through `onBeforeCompile`) |
664
+ | Fonts | whatever the page loaded (WOFF2, variable, system fonts, colour emoji); no bake step | runtime font outlines or zero-file Canvas 2D glyph trace; no offline bake step | a `.font.glb` from its CLI (Noto Sans ASCII, 132 glyphs: 3.1 s, 1.55 MB, 295 kB brotli) or a runtime bake of TTF/OTF; no WOFF/WOFF2 or variable fonts | a `.ttf`/`.otf`/`.woff` URL (`.woff2` throws); missing characters load from a CDN |
665
+ | Layout | the browser's own CSS layout (Range) or Pretext | the browser's own CSS layout (Range) or Pretext | its own shaping and layout (HarfRust in Wasm) | its own layout in a worker |
666
+ | First frame, 1,000-glyph paragraph [1] | 33.9 ms (GPU), 58.9 ms (CPU) | 35.7 ms (TTF), 74.8 ms (traced) | 48.8 ms (MSDF), 56.4 ms (Slug) | **23.4 ms** |
667
+ | First frame, 200 labels [1] | 39.7 ms (one capture) | one capture over all 200 | 75.5 ms | 39.1 ms (200 `Text`), **26.2 ms** (`BatchedText`) |
668
+ | Edit 10 letters already drawn [2] | 3.0 ms (GPU), **2.4 ms** (CPU) | 2.7 ms (TTF), 2.8 ms (traced) | 2.5 ms MSDF, 2.8 ms Slug | 2.5 ms |
669
+ | Edit adding a never-drawn letter [2] | 4.3 ms (GPU atlas), 3.1 ms (CPU atlas), 2.6 ms with `extraGlyphs` | **2.9 ms** (TTF, `#ga` in-place), 4.1 ms (traced) | **2.2 ms** MSDF, 2.7 ms Slug (baked ahead) | 3.0 ms |
670
+ | Width change, 1,000 glyphs [2] | **1.46 ms** with `reflow()` (0.041 ms CPU only); 3.7 ms with CSS + `rebuild()` | 3.5–3.6 ms with CSS + `rebuild()` | 1.95 ms (MSDF), 2.31 ms (Slug) | 2.37 ms |
671
+ | Frame, 1,000 glyphs / 160 px [3] | **0.075 ms** / **0.087 ms** | 0.158 ms / 0.168 ms (0.053 ms net GPU at 160 px) | 0.129 / 0.156 ms (MSDF); 0.206 / 0.213 ms (Slug) | 0.144 ms / 0.142 ms |
672
+ | Frame, 200 labels [3] | **0.074 ms** | 1 draw per subtree | 0.211 ms | 1.69 ms (200 `Text`), 0.153 ms (`BatchedText`) |
673
+ | Draw calls, paragraph / 200 labels | **1 / 1** | **1 / 1** | 2 / 2 (double-sided text in two passes) | 1 / 200 (1 with `BatchedText`) |
674
+ | GPU memory, paragraph [4] | **0.64 MiB** (5.3 MiB GPU JFA peak; 0.64 MiB CPU peak) | **0.17 MiB** TTF (0.21 MiB traced) | 1.44 MiB MSDF, 0.24 MiB Slug for ASCII bake (0.85 / 0.17 MiB for the paragraph's 49 chars) | 2.04 MiB (1.04 MiB 256-glyph RGBA slab & buffers + 1.00 MiB SDF generator canvas) |
675
+ | Zoom 10× / 100× [5] | sharp / soft SDF stems (`textBackend: 'windfoil'` also analytic) | **exact quadratic curves** at 100× | MSDF keeps corners; Slug exact | sharp / corners round |
676
+ | Outline and drop shadow | on every backend | on every backend (SDF underlay) | MSDF only | outline with blur and offset, inner stroke |
677
+ | Colour emoji | **yes**, the browser's own | **yes**, SDF colour companion | not yet (roadmap) | monochrome |
678
+ | JS + Wasm, min+gzip | **41.1 kB** `DomText + Text` (36.6 kB brotli; 56.3 kB gzip full root; **31.7 kB** vanilla) | +17.1 kB lazy (+15.5 kB brotli; `ultra-text/slug`: 40.9 kB, 36.1 kB brotli; vanilla: 33.7 kB, 30.1 kB brotli) | 122.3 kB JS + 501.0 kB shaper Wasm (623.3 kB; 494.6 kB brotli) | 42.2 kB `Text` (36.6 kB brotli; 44.3 kB with `BatchedText` + `preloadFont`) |
679
+
680
+ 1. Cold authoring call → first frame GPU completion, fonts preloaded, warm shader cache (`n = 10`). `ultra-text` SDF builds in `5.35 ms` GPU (`4.56 ms` in `2026-11-22` W5) + `6.66 ms` layout + `13.3 ms` first submit (`4.30 / 5.89 / 15.1 ms` on Slug TTF).
681
+ 2. Mutation → GPU completion (`n = 30` edits, `n = 32` width changes). `reflow()` avoids DOM reads (**`0.041 ms`** standalone CPU median on Apple M3 Max, `2026-11-23`; **`1.46 ms`** end-to-end). Headroom-on-first-miss cuts unseen-glyph Slug rebuilds to `2.89 ms` (TTF) and `4.14 ms` (traced).
682
+ 3. Whole `3200×2400` frame batches (`E1`, `n = 8`), `E2` GPU timestamps, `E3` `ioreg` (`troika ÷ ultra-text` `1.67–2.02`, `glyph MSDF ÷ ultra-text` `1.10–1.73`, `glyph Slug ÷ ultra-text SDF` `2.06–2.76`; 160 px net GPU Slug `0.053 ms` vs `glyph` `0.090 ms`). Net text cost over empty frame: `0.010–0.016 ms` (`ultra-text` SDF) vs `0.008 ms` (`troika`) vs `0.017–0.071 ms` (`glyph` MSDF). 200 `troika Text` calls are CPU-bound (`1.68 ms` CPU/frame vs `0.012 ms`).
683
+ 4. Post-renderer GPU allocations: `glyph` ASCII bake `1.44 / 0.24 MiB` (`0.85 / 0.17 MiB` at 49 chars); `troika` allocates `2048×128` 256-glyph RGBA slab + buffers (`1.04 MiB`) + auxiliary generator canvas (`1.00 MiB`).
684
+ 5. Verified on the `shots/zoom-grid.png` contact sheet (`"Rag Kerning quartz 0.5% Ж"` at 1×/10×/100× vs Chrome DOM).
685
+
686
+ Payloads (Vite 8, `es2022`, `NODE_ENV=production`, `three/*` external, `1 kB = 1,000 B`, run `2026-11-23`). Qualitative notes checked `2026-11-15` in [glyph](https://github.com/pmndrs/glyph) and [troika](https://github.com/protectwise/troika/tree/main/packages/troika-three-text).
1456
687
 
1457
688
  ## Demo and documentation
1458
689
 
1459
- - [Documentation](https://ultra-text.makio.io/docs), with the TresJS, React Three Fiber and
1460
- Mini3 guides linked [above](#tresjs-react-three-fiber-mini3-and-vanilla-js).
1461
- - [HTML/3D demo](https://ultra-text.makio.io/demo): live HTML beside its retained WebGPU copy,
1462
- with colour emoji and SVG exhibits.
690
+ - [Documentation](https://ultra-text.makio.io/docs), with the TresJS, React Three Fiber, and Mini3 guides linked [above](#tresjs-react-three-fiber-mini3-and-vanilla-js).
691
+ - [HTML/3D demo](https://ultra-text.makio.io/demo): live HTML beside its retained WebGPU copy, with colour emoji and SVG exhibits.
1463
692
  - [Gallery](https://ultra-text.makio.io/): a WebGPU exhibition built with the library.
1464
693
 
1465
694
  This repository holds the library only; the demo and gallery sources are not part of it.
1466
695
 
1467
696
  ## Development
1468
697
 
1469
- The repository uses Node 22.23.2 (`.node-version`) and pnpm 12.3.4 (`packageManager`).
1470
- TypeScript 7 runs type checks and declaration builds through `tsc`; the `typescript`
1471
- dependency aliases the TypeScript 6 compatibility package required by typescript-eslint.
698
+ Node 22.23.2 (`.node-version`), pnpm 12.3.4, TypeScript 7 (`typescript` aliases TS 6 for eslint).
1472
699
 
1473
700
  ```sh
1474
- pnpm install --frozen-lockfile
1475
- pnpm test
701
+ pnpm install --frozen-lockfile && pnpm test
1476
702
  ```
1477
703
 
1478
- | Command | Purpose |
1479
- | ---------------- | ------------------------------------------------------------------- |
1480
- | `pnpm test` | Run the Vitest unit suite. |
1481
- | `pnpm typecheck` | Type-check browser and Node configurations. |
1482
- | `pnpm lint` | Run ESLint with zero warnings allowed. |
1483
- | `pnpm build` | Build ESM modules and TypeScript declarations into `dist/`. |
1484
- | `pnpm check` | Run formatting, lint, types, coverage, build, size, and package QA. |
1485
-
1486
- The unit suite runs in jsdom: it checks CPU logic, generated shader text, graph wiring,
1487
- lifecycle and public behavior, but does not render. Pull requests and pushes to `main` run
1488
- `pnpm check`.
704
+ | Command | Purpose |
705
+ | ---------------- | ----------------------------------------------------------------- |
706
+ | `pnpm test` | Run the Vitest unit suite in jsdom. |
707
+ | `pnpm typecheck` | Type-check browser and Node configs. |
708
+ | `pnpm lint` | Run ESLint (`--max-warnings 0`). |
709
+ | `pnpm build` | Build ESM modules + `.d.ts` into `dist/`. |
710
+ | `pnpm check` | Run formatting, lint, types, coverage, builds, size & package QA. |
1489
711
 
1490
- [`CONTRIBUTING.md`](./CONTRIBUTING.md) covers pull requests, and [`AGENTS.md`](./AGENTS.md)
1491
- maps the repository and its invariants for contributors and coding agents.
712
+ The unit suite does not render; prefer local WebGPU hardware for rendering checks. See
713
+ [`CONTRIBUTING.md`](./CONTRIBUTING.md) and [`AGENTS.md`](./AGENTS.md).
1492
714
 
1493
715
  ## License
1494
716
 
1495
- [MIT](./LICENSE) © David Ronai. Windfoil-derived preprocessing and shader portions are
1496
- Apache-2.0, and the Glyph-derived SDF effect composition and the Slug-derived coverage evaluator
1497
- keep their upstream MIT notices; see [third-party notices](./THIRD_PARTY_NOTICES.md), which also
1498
- lists the licensed test fixtures.
717
+ [MIT](./LICENSE) © David Ronai. Windfoil-derived preprocessing and shader portions are Apache-2.0,
718
+ and the Glyph-derived SDF effect composition and Slug-derived coverage evaluator keep their
719
+ upstream MIT notices; see [third-party notices](./THIRD_PARTY_NOTICES.md), which also lists the
720
+ licensed test fixtures.