ultra-text 1.0.1 → 1.0.3

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 (237) hide show
  1. package/README.md +339 -1039
  2. package/dist/assets/cpuSdf.worker-Dy4P5_TI.js +466 -0
  3. package/dist/assets/cpuSdf.worker-Dy4P5_TI.js.map +1 -0
  4. package/dist/assets/traceOutline.worker-B5uVKmR4.js +1725 -0
  5. package/dist/assets/traceOutline.worker-B5uVKmR4.js.map +1 -0
  6. package/dist/atlas/appendAtlas.js +97 -31
  7. package/dist/atlas/appendAtlas.js.map +1 -1
  8. package/dist/atlas/buildAtlas.js +4 -3
  9. package/dist/atlas/buildAtlas.js.map +1 -1
  10. package/dist/atlas/colorGlyphs.d.ts +0 -10
  11. package/dist/atlas/colorGlyphs.js +97 -155
  12. package/dist/atlas/colorGlyphs.js.map +1 -1
  13. package/dist/atlas/colorTexture.d.ts +1 -0
  14. package/dist/atlas/colorTexture.js +64 -0
  15. package/dist/atlas/colorTexture.js.map +1 -0
  16. package/dist/atlas/cpuAtlas.d.ts +4 -1
  17. package/dist/atlas/cpuAtlas.js +14 -7
  18. package/dist/atlas/cpuAtlas.js.map +1 -1
  19. package/dist/atlas/cpuSdf.d.ts +1 -1
  20. package/dist/atlas/cpuSdf.js +235 -68
  21. package/dist/atlas/cpuSdf.js.map +1 -1
  22. package/dist/atlas/cpuWorker.d.ts +11 -3
  23. package/dist/atlas/cpuWorker.js +179 -22
  24. package/dist/atlas/cpuWorker.js.map +1 -1
  25. package/dist/atlas/gpuAtlas.js +188 -287
  26. package/dist/atlas/gpuAtlas.js.map +1 -1
  27. package/dist/atlas/gpuCommon.d.ts +257 -0
  28. package/dist/atlas/gpuCommon.js +845 -0
  29. package/dist/atlas/gpuCommon.js.map +1 -0
  30. package/dist/atlas/jfaWgsl.d.ts +1 -1
  31. package/dist/atlas/jfaWgsl.js +226 -249
  32. package/dist/atlas/jfaWgsl.js.map +1 -1
  33. package/dist/atlas/rasterize.d.ts +22 -0
  34. package/dist/atlas/rasterize.js +329 -158
  35. package/dist/atlas/rasterize.js.map +1 -1
  36. package/dist/atlas/shapeRaster.js +2 -1
  37. package/dist/atlas/shapeRaster.js.map +1 -1
  38. package/dist/atlas/vanillaBounds.d.ts +64 -0
  39. package/dist/atlas/vanillaBounds.js +42 -0
  40. package/dist/atlas/vanillaBounds.js.map +1 -0
  41. package/dist/atlas/vanillaCore.d.ts +100 -0
  42. package/dist/atlas/vanillaCore.js +1065 -0
  43. package/dist/atlas/vanillaCore.js.map +1 -0
  44. package/dist/atlas/vanillaCpuAtlas.d.ts +9 -0
  45. package/dist/atlas/vanillaCpuAtlas.js +72 -0
  46. package/dist/atlas/vanillaCpuAtlas.js.map +1 -0
  47. package/dist/atlas/vanillaExtras.d.ts +8 -0
  48. package/dist/atlas/vanillaExtras.js +167 -0
  49. package/dist/atlas/vanillaExtras.js.map +1 -0
  50. package/dist/atlas/vanillaGpuHelpers.d.ts +295 -0
  51. package/dist/atlas/vanillaGpuHelpers.js +354 -0
  52. package/dist/atlas/vanillaGpuHelpers.js.map +1 -0
  53. package/dist/dom/DomSdf.js +243 -297
  54. package/dist/dom/DomSdf.js.map +1 -1
  55. package/dist/dom/DomSlug.js +94 -165
  56. package/dist/dom/DomSlug.js.map +1 -1
  57. package/dist/dom/Text.d.ts +4 -1
  58. package/dist/dom/Text.js +5 -1
  59. package/dist/dom/Text.js.map +1 -1
  60. package/dist/dom/browserShaping.js +31 -14
  61. package/dist/dom/browserShaping.js.map +1 -1
  62. package/dist/dom/clusters.js +13 -2
  63. package/dist/dom/clusters.js.map +1 -1
  64. package/dist/dom/cssEffects.d.ts +4 -0
  65. package/dist/dom/cssEffects.js +72 -0
  66. package/dist/dom/cssEffects.js.map +1 -0
  67. package/dist/dom/domAnalytic.d.ts +53 -0
  68. package/dist/dom/domAnalytic.js +282 -0
  69. package/dist/dom/domAnalytic.js.map +1 -0
  70. package/dist/dom/domExtras.d.ts +27 -0
  71. package/dist/dom/domExtras.js +137 -0
  72. package/dist/dom/domExtras.js.map +1 -0
  73. package/dist/dom/fontCanvas.d.ts +16 -0
  74. package/dist/dom/fontCanvas.js +31 -13
  75. package/dist/dom/fontCanvas.js.map +1 -1
  76. package/dist/dom/layoutSignature.js +175 -57
  77. package/dist/dom/layoutSignature.js.map +1 -1
  78. package/dist/dom/markup.d.ts +10 -0
  79. package/dist/dom/markup.js +16 -1
  80. package/dist/dom/markup.js.map +1 -1
  81. package/dist/dom/pretextLayout.js +78 -28
  82. package/dist/dom/pretextLayout.js.map +1 -1
  83. package/dist/dom/snapshot.d.ts +4 -0
  84. package/dist/dom/snapshot.js +891 -484
  85. package/dist/dom/snapshot.js.map +1 -1
  86. package/dist/dom/snapshotsEqual.d.ts +7 -0
  87. package/dist/dom/snapshotsEqual.js +68 -0
  88. package/dist/dom/snapshotsEqual.js.map +1 -0
  89. package/dist/dom/svgCapture.d.ts +8 -1
  90. package/dist/dom/svgCapture.js +105 -28
  91. package/dist/dom/svgCapture.js.map +1 -1
  92. package/dist/dom/textTransform.d.ts +13 -1
  93. package/dist/dom/textTransform.js +31 -13
  94. package/dist/dom/textTransform.js.map +1 -1
  95. package/dist/dom/tone.js +91 -44
  96. package/dist/dom/tone.js.map +1 -1
  97. package/dist/index.js +4 -3
  98. package/dist/slug/SlugMaterial.d.ts +17 -3
  99. package/dist/slug/SlugMaterial.js +98 -26
  100. package/dist/slug/SlugMaterial.js.map +1 -1
  101. package/dist/slug/cff.d.ts +5 -0
  102. package/dist/slug/cff.js +780 -0
  103. package/dist/slug/cff.js.map +1 -0
  104. package/dist/slug/coverage.d.ts +19 -15
  105. package/dist/slug/coverage.js +380 -225
  106. package/dist/slug/coverage.js.map +1 -1
  107. package/dist/slug/preprocessCore.d.ts +6 -2
  108. package/dist/slug/preprocessCore.js +199 -148
  109. package/dist/slug/preprocessCore.js.map +1 -1
  110. package/dist/slug/runtime.d.ts +1 -0
  111. package/dist/slug/runtime.js +113 -74
  112. package/dist/slug/runtime.js.map +1 -1
  113. package/dist/slug/standaloneRuntime.d.ts +3 -2
  114. package/dist/slug/standaloneRuntime.js +112 -67
  115. package/dist/slug/standaloneRuntime.js.map +1 -1
  116. package/dist/slug/truetype.d.ts +14 -6
  117. package/dist/slug/truetype.js +356 -255
  118. package/dist/slug/truetype.js.map +1 -1
  119. package/dist/slug/vanillaCore.d.ts +410 -0
  120. package/dist/slug/vanillaCore.js +1630 -0
  121. package/dist/slug/vanillaCore.js.map +1 -0
  122. package/dist/slug-vanilla.d.ts +13 -364
  123. package/dist/slug-vanilla.js +7 -1454
  124. package/dist/slug.d.ts +2 -2
  125. package/dist/slug.js +7 -7
  126. package/dist/text/GlyphTextMaterial.d.ts +6 -1
  127. package/dist/text/GlyphTextMaterial.js +16 -12
  128. package/dist/text/GlyphTextMaterial.js.map +1 -1
  129. package/dist/text/RectMaterial.js +6 -10
  130. package/dist/text/RectMaterial.js.map +1 -1
  131. package/dist/text/SdfTextMaterial.d.ts +9 -3
  132. package/dist/text/SdfTextMaterial.js +125 -38
  133. package/dist/text/SdfTextMaterial.js.map +1 -1
  134. package/dist/text/decorations.d.ts +7 -2
  135. package/dist/text/decorations.js +187 -79
  136. package/dist/text/decorations.js.map +1 -1
  137. package/dist/text/geometry.d.ts +3 -22
  138. package/dist/text/geometryUtils.d.ts +16 -1
  139. package/dist/text/geometryUtils.js +83 -8
  140. package/dist/text/geometryUtils.js.map +1 -1
  141. package/dist/text/glyphGeometry.d.ts +9 -0
  142. package/dist/text/glyphGeometry.js +434 -0
  143. package/dist/text/glyphGeometry.js.map +1 -0
  144. package/dist/text/index.d.ts +2 -1
  145. package/dist/text/rectGeometry.d.ts +13 -0
  146. package/dist/text/rectGeometry.js +101 -0
  147. package/dist/text/rectGeometry.js.map +1 -0
  148. package/dist/text/reflow.d.ts +23 -1
  149. package/dist/text/reflow.js +223 -94
  150. package/dist/text/reflow.js.map +1 -1
  151. package/dist/text/snap.d.ts +15 -0
  152. package/dist/text/snap.js +26 -0
  153. package/dist/text/snap.js.map +1 -0
  154. package/dist/text/tone.js +2 -2
  155. package/dist/text/tone.js.map +1 -1
  156. package/dist/types.d.ts +23 -7
  157. package/dist/vanilla.d.ts +13 -363
  158. package/dist/vanilla.js +7 -1474
  159. package/dist/windfoil/WindfoilCompositeMaterial.d.ts +1 -1
  160. package/dist/windfoil/WindfoilCompositeMaterial.js +10 -3
  161. package/dist/windfoil/WindfoilCompositeMaterial.js.map +1 -1
  162. package/dist/windfoil/WindfoilMaterial.d.ts +12 -5
  163. package/dist/windfoil/WindfoilMaterial.js +71 -8
  164. package/dist/windfoil/WindfoilMaterial.js.map +1 -1
  165. package/dist/windfoil/compositeGeometry.js +12 -5
  166. package/dist/windfoil/compositeGeometry.js.map +1 -1
  167. package/dist/windfoil/coverage.d.ts +10 -2
  168. package/dist/windfoil/coverage.js +147 -59
  169. package/dist/windfoil/coverage.js.map +1 -1
  170. package/dist/windfoil/geometry.d.ts +17 -2
  171. package/dist/windfoil/geometry.js +220 -57
  172. package/dist/windfoil/geometry.js.map +1 -1
  173. package/dist/windfoil/layerGrid.js +8 -8
  174. package/dist/windfoil/layerGrid.js.map +1 -1
  175. package/dist/windfoil/mixed.d.ts +1 -0
  176. package/dist/windfoil/mixed.js +57 -29
  177. package/dist/windfoil/mixed.js.map +1 -1
  178. package/dist/windfoil/preprocess.js +2 -2
  179. package/dist/windfoil/preprocessCore.d.ts +2 -0
  180. package/dist/windfoil/preprocessCore.js +69 -37
  181. package/dist/windfoil/preprocessCore.js.map +1 -1
  182. package/dist/windfoil/requests.d.ts +1 -1
  183. package/dist/windfoil/requests.js +11 -4
  184. package/dist/windfoil/requests.js.map +1 -1
  185. package/dist/windfoil/resolveOutline.d.ts +9 -0
  186. package/dist/windfoil/resolveOutline.js +20 -0
  187. package/dist/windfoil/resolveOutline.js.map +1 -0
  188. package/dist/windfoil/runtime.d.ts +4 -1
  189. package/dist/windfoil/runtime.js +69 -63
  190. package/dist/windfoil/runtime.js.map +1 -1
  191. package/dist/windfoil/shapeGeometry.js +80 -34
  192. package/dist/windfoil/shapeGeometry.js.map +1 -1
  193. package/dist/windfoil/sizeSwitch.d.ts +1 -1
  194. package/dist/windfoil/sizeSwitch.js +13 -8
  195. package/dist/windfoil/sizeSwitch.js.map +1 -1
  196. package/dist/windfoil/storage.d.ts +78 -6
  197. package/dist/windfoil/storage.js +166 -11
  198. package/dist/windfoil/storage.js.map +1 -1
  199. package/dist/windfoil/svg/curves.d.ts +20 -0
  200. package/dist/windfoil/svg/curves.js +145 -42
  201. package/dist/windfoil/svg/curves.js.map +1 -1
  202. package/dist/windfoil/svg/document.js +10 -1
  203. package/dist/windfoil/svg/document.js.map +1 -1
  204. package/dist/windfoil/svg/pathConverter.js +66 -50
  205. package/dist/windfoil/svg/pathConverter.js.map +1 -1
  206. package/dist/windfoil/svg/pathData.d.ts +9 -0
  207. package/dist/windfoil/svg/pathData.js +142 -109
  208. package/dist/windfoil/svg/pathData.js.map +1 -1
  209. package/dist/windfoil/svg/winding.js +34 -10
  210. package/dist/windfoil/svg/winding.js.map +1 -1
  211. package/dist/windfoil/trace/contours.d.ts +5 -0
  212. package/dist/windfoil/trace/contours.js +256 -62
  213. package/dist/windfoil/trace/contours.js.map +1 -1
  214. package/dist/windfoil/trace/fit.d.ts +3 -1
  215. package/dist/windfoil/trace/fit.js +915 -265
  216. package/dist/windfoil/trace/fit.js.map +1 -1
  217. package/dist/windfoil/trace/outline.js +55 -30
  218. package/dist/windfoil/trace/outline.js.map +1 -1
  219. package/dist/windfoil/trace/traceOutline.worker.d.ts +24 -0
  220. package/dist/windfoil/trace/traceWorker.d.ts +13 -0
  221. package/dist/windfoil/trace/traceWorker.js +192 -0
  222. package/dist/windfoil/trace/traceWorker.js.map +1 -0
  223. package/dist/windfoil/trace/types.d.ts +10 -0
  224. package/dist/windfoil/tracedOutlines.d.ts +2 -0
  225. package/dist/windfoil/tracedOutlines.js +393 -103
  226. package/dist/windfoil/tracedOutlines.js.map +1 -1
  227. package/package.json +48 -29
  228. package/skills/ultra-text/SKILL.md +9 -10
  229. package/skills/ultra-text/references/frameworks.md +46 -2
  230. package/skills/ultra-text/references/three-tsl.md +27 -25
  231. package/skills/ultra-text/references/vanilla-webgpu.md +5 -2
  232. package/dist/assets/cpuSdf.worker-xS57yQbP.js +0 -322
  233. package/dist/assets/cpuSdf.worker-xS57yQbP.js.map +0 -1
  234. package/dist/slug-vanilla.js.map +0 -1
  235. package/dist/text/geometry.js +0 -348
  236. package/dist/text/geometry.js.map +0 -1
  237. package/dist/vanilla.js.map +0 -1
@@ -1,1461 +1,14 @@
1
1
  import { backdropCurve, resolveDomTextTone, resolveTextTone, srgbEncode, toneCoverage, toneLightness } from "./dom/tone.js";
2
- import { reflowSnapshot, snapGlyph } from "./text/reflow.js";
2
+ import { snapGlyph } from "./text/snap.js";
3
3
  import { collectDomSnapshot } from "./dom/snapshot.js";
4
- import { layoutSignatureOf } from "./dom/layoutSignature.js";
5
- import { classNames, copyTextOptions, createTextSource, cssDeclarations } from "./dom/textHost.js";
4
+ import { reflowSnapshot } from "./text/reflow.js";
6
5
  import { windfoilOutlineFromSvgPaths } from "./windfoil/svg/pathConverter.js";
7
6
  import { svgToWindfoilOutlines } from "./windfoil/svg/convert.js";
8
7
  import { createSvgEmojiOutlineProvider } from "./windfoil/emoji.js";
8
+ import { layoutSignatureOf } from "./dom/layoutSignature.js";
9
+ import { packDecorationInstances, updateDecorationInstances } from "./atlas/vanillaExtras.js";
9
10
  import { preprocessSlugGlyphs } from "./slug/preprocessCore.js";
11
+ import { createFontOutlineProvider, createTrueTypeOutlineProvider, parseFont, parseTrueTypeFont } from "./slug/truetype.js";
10
12
  import { createTracedOutlineProvider } from "./windfoil/tracedOutlines.js";
11
- import { createTrueTypeOutlineProvider, parseTrueTypeFont } from "./slug/truetype.js";
12
- // src/slug-vanilla.ts
13
- function resolveSlugGpuDevice(source) {
14
- if (!source) return null;
15
- if ("createBuffer" in source && typeof source.createBuffer === "function") return source;
16
- return "device" in source ? source.device ?? null : null;
17
- }
18
- var DEFAULT_BUF_USAGE = {
19
- COPY_SRC: 4,
20
- COPY_DST: 8,
21
- INDEX: 16,
22
- VERTEX: 32,
23
- UNIFORM: 64,
24
- STORAGE: 128
25
- };
26
- var bufUsageOf = () => globalThis.GPUBufferUsage ?? DEFAULT_BUF_USAGE;
27
- function align4Bytes(byteLength) {
28
- return Math.max(16, byteLength + 3 & -4);
29
- }
30
- function createStorageBuffer(device, label, data) {
31
- const usage = bufUsageOf();
32
- const byteLength = align4Bytes(data.byteLength);
33
- const buffer = device.createBuffer({
34
- label,
35
- size: byteLength,
36
- usage: usage.STORAGE | usage.COPY_DST
37
- });
38
- if (data.byteLength > 0) device.queue.writeBuffer(buffer, 0, data);
39
- return buffer;
40
- }
41
- function makeAbortError(message = "The Slug operation was aborted") {
42
- if (typeof DOMException !== "undefined") return new DOMException(message, "AbortError");
43
- const error = new Error(message);
44
- error.name = "AbortError";
45
- return error;
46
- }
47
- function isAbortError(error) {
48
- return error instanceof Error && error.name === "AbortError";
49
- }
50
- async function buildVanillaSlugAtlas(deviceOrRenderer, requests, options = {}) {
51
- const signal = options.signal ?? new AbortController().signal;
52
- signal.throwIfAborted();
53
- const device = resolveSlugGpuDevice(deviceOrRenderer);
54
- let provider = options.outlineProvider;
55
- if (provider !== void 0 && typeof provider !== "function") throw new TypeError("buildVanillaSlugAtlas: outlineProvider must be a function");
56
- if (!provider) {
57
- const doc = options.document ?? (typeof globalThis.document === "undefined" ? void 0 : globalThis.document);
58
- if (!doc) throw new Error("buildVanillaSlugAtlas: provide an outlineProvider (e.g. createTrueTypeOutlineProvider) or a DOM document");
59
- provider = createTracedOutlineProvider(doc, {
60
- ...options.colorGlyphs === void 0 ? {} : { colorGlyphs: options.colorGlyphs },
61
- ...options.traceSize === void 0 ? {} : { size: options.traceSize },
62
- ...options.traceTolerance === void 0 ? {} : { tolerance: options.traceTolerance }
63
- }).provider;
64
- }
65
- const hasShapes = requests.some((request) => request.shape !== void 0);
66
- const resolved = [];
67
- for (const request of requests) {
68
- signal.throwIfAborted();
69
- if (request.shape) {
70
- const shape = request.shape;
71
- if (shape.bitmap || shape.paths.some((path) => path.stroke ?? path.clip)) resolved.push({
72
- request,
73
- outline: null
74
- });
75
- else {
76
- const svg = svgToWindfoilOutlines(shape.paths, {
77
- em: {
78
- unitsPerEm: 1e3,
79
- ascent: shape.box[1],
80
- descent: 0,
81
- advance: shape.box[0]
82
- },
83
- viewBox: [
84
- 0,
85
- 0,
86
- shape.box[0],
87
- shape.box[1]
88
- ],
89
- preserveAspectRatio: "none"
90
- });
91
- resolved.push({
92
- request,
93
- outline: svg.warnings.some((w) => w.code === "evenodd-ambiguous") ? null : svg.outline
94
- });
95
- }
96
- continue;
97
- }
98
- const out = await provider(request, signal);
99
- resolved.push({
100
- request,
101
- outline: out
102
- });
103
- }
104
- signal.throwIfAborted();
105
- const missing = resolved.filter((item) => item.outline === null);
106
- const missingMode = options.missingGlyphs ?? (options.outlineProvider ? "error" : "skip");
107
- if (missing.length > 0 && missingMode === "error") throw new Error(`buildVanillaSlugAtlas: outlineProvider returned null for ${JSON.stringify(missing[0].request.character)} in ${missing[0].request.font.family}`);
108
- const skippedKeys = new Set(missing.map((item) => item.request.key));
109
- const layerModule = resolved.some((item) => item.outline?.layers !== void 0 || item.outline?.clipBox !== void 0) ? await import("./windfoil/layerNormalization.js") : null;
110
- signal.throwIfAborted();
111
- if (hasShapes) {}
112
- const prepared = preprocessSlugGlyphs(resolved.filter((item) => item.outline !== null), {
113
- signal,
114
- ...layerModule ? { normalizeLayers: layerModule.normalizeLayers } : {},
115
- ...options.targetPiecesPerBand === void 0 ? {} : { targetPiecesPerBand: options.targetPiecesPerBand }
116
- });
117
- let curvesBuffer;
118
- let rowsBuffer;
119
- if (device) try {
120
- curvesBuffer = createStorageBuffer(device, "ultra-slug-curves", prepared.curves);
121
- rowsBuffer = createStorageBuffer(device, "ultra-slug-rows", prepared.rows);
122
- } catch (error) {
123
- curvesBuffer?.destroy();
124
- rowsBuffer?.destroy();
125
- throw error;
126
- }
127
- let disposed = false;
128
- const byteLength = prepared.curves.byteLength + prepared.rows.byteLength;
129
- return {
130
- curves: prepared.curves,
131
- rows: prepared.rows,
132
- ...curvesBuffer ? { curvesBuffer } : {},
133
- ...rowsBuffer ? { rowsBuffer } : {},
134
- glyphs: prepared.glyphs,
135
- skippedKeys,
136
- layered: prepared.layered,
137
- stats: prepared.stats,
138
- byteLength,
139
- covers(key) {
140
- return prepared.glyphs.has(key) || skippedKeys.has(key);
141
- },
142
- dispose() {
143
- if (disposed) return;
144
- disposed = true;
145
- curvesBuffer?.destroy();
146
- rowsBuffer?.destroy();
147
- }
148
- };
149
- }
150
- var UNIT_QUAD_POSITIONS = new Float32Array([
151
- 0,
152
- 0,
153
- 0,
154
- 1,
155
- 0,
156
- 0,
157
- 1,
158
- 1,
159
- 0,
160
- 0,
161
- 1,
162
- 0
163
- ]);
164
- var UNIT_QUAD_NORMALS = new Float32Array([
165
- 0,
166
- 0,
167
- 1,
168
- 0,
169
- 0,
170
- 1,
171
- 0,
172
- 0,
173
- 1,
174
- 0,
175
- 0,
176
- 1
177
- ]);
178
- var UNIT_QUAD_INDICES = new Uint16Array([
179
- 0,
180
- 1,
181
- 2,
182
- 0,
183
- 2,
184
- 3
185
- ]);
186
- function computeInstanceBounds(width, height, padding = 0, minZ = 0, maxZ = 0) {
187
- const minX = -padding;
188
- const minY = -padding;
189
- const minBoundZ = minZ - padding;
190
- const maxX = width + padding;
191
- const maxY = height + padding;
192
- const maxBoundZ = maxZ + padding;
193
- const cx = (minX + maxX) * .5;
194
- const cy = (minY + maxY) * .5;
195
- const cz = (minBoundZ + maxBoundZ) * .5;
196
- const dx = maxX - cx;
197
- const dy = maxY - cy;
198
- const dz = maxBoundZ - cz;
199
- return {
200
- min: [
201
- minX,
202
- minY,
203
- minBoundZ
204
- ],
205
- max: [
206
- maxX,
207
- maxY,
208
- maxBoundZ
209
- ],
210
- center: [
211
- cx,
212
- cy,
213
- cz
214
- ],
215
- radius: Math.sqrt(dx * dx + dy * dy + dz * dz)
216
- };
217
- }
218
- function byte(value) {
219
- if (value <= 0) return 0;
220
- if (value >= 1) return 255;
221
- return value * 255 + .5 | 0;
222
- }
223
- function metaSize(snapshot) {
224
- return snapshot.sizeSwitched || snapshot.glyphs.some((glyph) => glyph.switchEm !== void 0) ? 3 : 2;
225
- }
226
- var scratchSlugRect = [
227
- 0,
228
- 0,
229
- 0,
230
- 0
231
- ];
232
- function fillSlugGlyphRect(glyph, header, out = scratchSlugRect) {
233
- const scale = glyph.fontSize / header.unitsPerEm;
234
- const baseline = glyph.lineBottom + (glyph.baselineOffset ?? -header.descent * scale);
235
- const bbox = header.bbox;
236
- out[0] = glyph.originX + bbox[0] * scale;
237
- out[1] = baseline + bbox[1] * scale;
238
- out[2] = glyph.originX + bbox[2] * scale;
239
- out[3] = baseline + bbox[3] * scale;
240
- return out;
241
- }
242
- function writeSlugLayer(glyph, header, layer, index, ordinal, target, glyphRect) {
243
- const offset = index * 4;
244
- const scale = glyph.fontSize / header.unitsPerEm;
245
- const baseline = glyph.lineBottom + (glyph.baselineOffset ?? -header.descent * scale);
246
- const ox = glyph.originX;
247
- const lBox = layer.bbox;
248
- const b0 = lBox[0], b1 = lBox[1], b2 = lBox[2], b3 = lBox[3];
249
- const rects = target.rects;
250
- rects[offset] = ox + b0 * scale;
251
- rects[offset + 1] = baseline + b1 * scale;
252
- rects[offset + 2] = ox + b2 * scale;
253
- rects[offset + 3] = baseline + b3 * scale;
254
- const clips = target.clips;
255
- const clip = glyph.clip;
256
- clips[offset] = clip[0];
257
- clips[offset + 1] = clip[1];
258
- clips[offset + 2] = clip[2];
259
- clips[offset + 3] = clip[3];
260
- const paint = "paintKind" in layer ? layer : null;
261
- const rgb = paint?.paintKind === 1 ? paint.rgba : glyph.color;
262
- const colors = target.colors;
263
- colors[offset] = byte(rgb[0]);
264
- colors[offset + 1] = byte(rgb[1]);
265
- colors[offset + 2] = byte(rgb[2]);
266
- colors[offset + 3] = byte(glyph.color[3] * (paint ? paint.rgba[3] : 1));
267
- const metaOffset = index * target.metaItemSize;
268
- target.metadata[metaOffset] = glyph.sequence;
269
- if (target.metaItemSize > 1) target.metadata[metaOffset + 1] = glyph.z;
270
- if (target.metaItemSize === 3) target.metadata[metaOffset + 2] = glyph.switchEm ?? 0;
271
- const bounds = target.glyphBounds;
272
- bounds[offset] = b0;
273
- bounds[offset + 1] = b1;
274
- bounds[offset + 2] = b2;
275
- bounds[offset + 3] = b3;
276
- const bands = target.bands;
277
- bands[offset] = layer.rowBase;
278
- bands[offset + 1] = layer.bandCount;
279
- bands[offset + 2] = layer.bandH;
280
- bands[offset + 3] = layer.invH;
281
- const layers = target.layers;
282
- if (layers) {
283
- const rect = glyphRect ?? fillSlugGlyphRect(glyph, header, scratchSlugRect);
284
- const mo = glyph.motionOrigin;
285
- layers[offset] = mo ? mo[0] : (rect[0] + rect[2]) * .5;
286
- layers[offset + 1] = mo ? mo[1] : (rect[1] + rect[3]) * .5;
287
- layers[offset + 2] = ordinal;
288
- layers[offset + 3] = paint?.paintKind === 2 ? 2 + (paint.paintIndex ?? 0) : paint?.paintKind ?? 0;
289
- }
290
- }
291
- function countSlugLayout(snapshot, glyphs, layered) {
292
- let instances = 0;
293
- let drawable = 0;
294
- for (const glyph of snapshot.glyphs) {
295
- const header = glyphs.get(glyph.glyphKey);
296
- if (header?.monotonePieceCount) {
297
- drawable++;
298
- instances += layered ? header.layers?.length ?? 1 : 1;
299
- }
300
- }
301
- return {
302
- instances,
303
- drawable
304
- };
305
- }
306
- function populateSlugInstances(snapshot, glyphs, target) {
307
- let instance = 0;
308
- let drawable = 0;
309
- let maxSequence = 0;
310
- let minZ = 0;
311
- let maxZ = 0;
312
- for (const glyph of snapshot.glyphs) {
313
- const header = glyphs.get(glyph.glyphKey);
314
- if (!header?.monotonePieceCount) continue;
315
- const ordinal = glyph.motionOrigin?.[2] ?? drawable;
316
- const rect = fillSlugGlyphRect(glyph, header, scratchSlugRect);
317
- const rectOffset = drawable * 4;
318
- target.glyphRects[rectOffset] = rect[0];
319
- target.glyphRects[rectOffset + 1] = rect[1];
320
- target.glyphRects[rectOffset + 2] = rect[2];
321
- target.glyphRects[rectOffset + 3] = rect[3];
322
- if (target.layers && header.layers) for (const layer of header.layers) writeSlugLayer(glyph, header, layer, instance++, ordinal, target, rect);
323
- else writeSlugLayer(glyph, header, header.layers?.[0] ?? header, instance++, ordinal, target, rect);
324
- drawable++;
325
- if (glyph.sequence > maxSequence) maxSequence = glyph.sequence;
326
- if (glyph.z < minZ) minZ = glyph.z;
327
- if (glyph.z > maxZ) maxZ = glyph.z;
328
- }
329
- return {
330
- maxSequence,
331
- minZ,
332
- maxZ
333
- };
334
- }
335
- function packSlugGlyphInstances(snapshot, atlas, motionPadding = 0) {
336
- const layered = atlas.layered || snapshot.glyphs.some((glyph) => !!glyph.motionOrigin);
337
- const { instances: count, drawable } = countSlugLayout(snapshot, atlas.glyphs, layered);
338
- const metaItemSize = metaSize(snapshot);
339
- const out = {
340
- count,
341
- drawableCount: drawable,
342
- layered,
343
- maxSequence: 0,
344
- rects: new Float32Array(count * 4),
345
- clips: new Float32Array(count * 4),
346
- colors: new Uint8Array(count * 4),
347
- metadata: new Float32Array(count * metaItemSize),
348
- metaItemSize,
349
- glyphBounds: new Float32Array(count * 4),
350
- bands: new Float32Array(count * 4),
351
- layers: layered ? new Float32Array(count * 4) : null,
352
- glyphRects: new Float32Array(drawable * 4),
353
- bounds: computeInstanceBounds(snapshot.width, snapshot.height, motionPadding, 0, 0)
354
- };
355
- const { maxSequence, minZ, maxZ } = populateSlugInstances(snapshot, atlas.glyphs, out);
356
- out.maxSequence = maxSequence;
357
- out.bounds = computeInstanceBounds(snapshot.width, snapshot.height, motionPadding, minZ, maxZ);
358
- return out;
359
- }
360
- function updateSlugGlyphInstances(instances, snapshot, atlas, motionPadding = 0) {
361
- const layered = atlas.layered || snapshot.glyphs.some((glyph) => !!glyph.motionOrigin);
362
- if (layered !== instances.layered || metaSize(snapshot) !== instances.metaItemSize) return null;
363
- const { instances: count, drawable } = countSlugLayout(snapshot, atlas.glyphs, layered);
364
- if (count !== instances.count || drawable !== instances.drawableCount) return null;
365
- const { maxSequence, minZ, maxZ } = populateSlugInstances(snapshot, atlas.glyphs, instances);
366
- instances.maxSequence = maxSequence;
367
- instances.bounds = computeInstanceBounds(snapshot.width, snapshot.height, motionPadding, minZ, maxZ);
368
- return maxSequence;
369
- }
370
- function rectCountFor(snapshot, receiveShadow) {
371
- let count = 0;
372
- for (const rect of snapshot.rects) if (rect.receiveShadow === receiveShadow) count++;
373
- return count;
374
- }
375
- function writeRectBatch(snapshot, receiveShadow, rects, colors, radii, depths) {
376
- let index = 0;
377
- let minZ = 0;
378
- let maxZ = 0;
379
- for (const item of snapshot.rects) {
380
- if (item.receiveShadow !== receiveShadow) continue;
381
- const offset = index * 4;
382
- rects[offset] = item.rect[0];
383
- rects[offset + 1] = item.rect[1];
384
- rects[offset + 2] = item.rect[2];
385
- rects[offset + 3] = item.rect[3];
386
- colors[offset] = byte(item.color[0]);
387
- colors[offset + 1] = byte(item.color[1]);
388
- colors[offset + 2] = byte(item.color[2]);
389
- colors[offset + 3] = byte(item.color[3]);
390
- radii[index] = item.radius;
391
- depths[index] = item.z;
392
- if (item.z < minZ) minZ = item.z;
393
- if (item.z > maxZ) maxZ = item.z;
394
- index++;
395
- }
396
- return [minZ, maxZ];
397
- }
398
- function packRectInstances(snapshot, receiveShadow = false) {
399
- const count = rectCountFor(snapshot, receiveShadow);
400
- if (count === 0) return null;
401
- const rects = new Float32Array(count * 4);
402
- const colors = new Uint8Array(count * 4);
403
- const radii = new Float32Array(count);
404
- const depths = new Float32Array(count);
405
- const [minZ, maxZ] = writeRectBatch(snapshot, receiveShadow, rects, colors, radii, depths);
406
- return {
407
- count,
408
- receiveShadow,
409
- rects,
410
- colors,
411
- radii,
412
- depths,
413
- bounds: computeInstanceBounds(snapshot.width, snapshot.height, 0, minZ, maxZ)
414
- };
415
- }
416
- function updateRectInstances(instances, snapshot, receiveShadow = instances.receiveShadow) {
417
- if (rectCountFor(snapshot, receiveShadow) !== instances.count) return false;
418
- const [minZ, maxZ] = writeRectBatch(snapshot, receiveShadow, instances.rects, instances.colors, instances.radii, instances.depths);
419
- instances.bounds = computeInstanceBounds(snapshot.width, snapshot.height, 0, minZ, maxZ);
420
- return true;
421
- }
422
- function sameDecoration(a, b) {
423
- return a.line === b.line && a.offset === b.offset && a.thickness === b.thickness && a.color.every((v, i) => v === b.color[i]);
424
- }
425
- function decorationRecords(snapshot, drawable) {
426
- const glyphs = snapshot.glyphs;
427
- const records = [];
428
- if (!glyphs.some((glyph) => glyph.decorations?.length)) return records;
429
- let glyphIndex = 0;
430
- let motionIndex = -1;
431
- let previousGroup;
432
- for (let index = 0; index < glyphs.length; index++) {
433
- const glyph = glyphs[index];
434
- if (!drawable(glyph.glyphKey)) continue;
435
- if (glyph.shapeGroup === void 0 || glyph.shapeGroup !== previousGroup) motionIndex++;
436
- previousGroup = glyph.shapeGroup;
437
- const decorations = glyph.decorations;
438
- if (decorations) for (const decoration of decorations) {
439
- if (decoration.thickness <= 0 || decoration.color[3] <= 0) continue;
440
- const next = glyphs[index + 1];
441
- let right = glyph.originX + (glyph.decorationWidth ?? Math.abs(glyph.advance));
442
- if (next?.block === glyph.block && next.lineBottom === glyph.lineBottom && next.decorations?.some((candidate) => sameDecoration(decoration, candidate))) right = Math.max(right, next.originX);
443
- const y = glyph.lineBottom + decoration.offset;
444
- records.push([
445
- [
446
- glyph.originX,
447
- y - decoration.thickness / 2,
448
- right,
449
- y + decoration.thickness / 2
450
- ],
451
- glyphIndex,
452
- glyph.motionOrigin?.[2] ?? motionIndex,
453
- decoration.color,
454
- glyph.clip,
455
- glyph.sequence,
456
- glyph.z,
457
- glyph.motionOrigin ?? null
458
- ]);
459
- }
460
- glyphIndex++;
461
- }
462
- return records;
463
- }
464
- function writeDecorationBatch(records, sourceRects, rects, strokes, indices, colors, clips, metadata, runMotion) {
465
- let minZ = 0;
466
- let maxZ = 0;
467
- for (let index = 0; index < records.length; index++) {
468
- const [stroke, rectIndex, motionIndex, color, clip, sequence, z, motionOrigin] = records[index];
469
- const offset = index * 4;
470
- const srcOffset = rectIndex * 4;
471
- rects[offset] = sourceRects[srcOffset] ?? 0;
472
- rects[offset + 1] = sourceRects[srcOffset + 1] ?? 0;
473
- rects[offset + 2] = sourceRects[srcOffset + 2] ?? 0;
474
- rects[offset + 3] = sourceRects[srcOffset + 3] ?? 0;
475
- strokes.set(stroke, offset);
476
- clips.set(clip, offset);
477
- indices[index] = motionIndex;
478
- colors[offset] = byte(color[0]);
479
- colors[offset + 1] = byte(color[1]);
480
- colors[offset + 2] = byte(color[2]);
481
- colors[offset + 3] = byte(color[3]);
482
- metadata[index * 2] = sequence;
483
- metadata[index * 2 + 1] = z;
484
- if (runMotion && motionOrigin) runMotion.set(motionOrigin, index * 3);
485
- if (z < minZ) minZ = z;
486
- if (z > maxZ) maxZ = z;
487
- }
488
- return [minZ, maxZ];
489
- }
490
- function packDecorationInstances(snapshot, sourceGlyphRects, drawable, motionPadding = 0) {
491
- const records = decorationRecords(snapshot, drawable);
492
- const count = records.length;
493
- if (count === 0) return null;
494
- const rects = new Float32Array(count * 4);
495
- const decorationRects = new Float32Array(count * 4);
496
- const decorationIndices = new Float32Array(count);
497
- const colors = new Uint8Array(count * 4);
498
- const clips = new Float32Array(count * 4);
499
- const metadata = new Float32Array(count * 2);
500
- const runMotion = records.some((record) => record[7] !== null) ? new Float32Array(count * 3) : null;
501
- const [minZ, maxZ] = writeDecorationBatch(records, sourceGlyphRects, rects, decorationRects, decorationIndices, colors, clips, metadata, runMotion);
502
- return {
503
- count,
504
- rects,
505
- decorationRects,
506
- decorationIndices,
507
- colors,
508
- clips,
509
- metadata,
510
- runMotion,
511
- bounds: computeInstanceBounds(snapshot.width, snapshot.height, motionPadding, minZ, maxZ)
512
- };
513
- }
514
- function updateDecorationInstances(instances, snapshot, sourceGlyphRects, drawable, motionPadding = 0) {
515
- const records = decorationRecords(snapshot, drawable);
516
- if (records.length === 0 || records.length !== instances.count) return false;
517
- if (records.some((record) => record[7] !== null) !== (instances.runMotion !== null)) return false;
518
- const [minZ, maxZ] = writeDecorationBatch(records, sourceGlyphRects, instances.rects, instances.decorationRects, instances.decorationIndices, instances.colors, instances.clips, instances.metadata, instances.runMotion);
519
- instances.bounds = computeInstanceBounds(snapshot.width, snapshot.height, motionPadding, minZ, maxZ);
520
- return true;
521
- }
522
- /**
523
- * Standalone WGSL vertex + fragment shader implementing Ultra-Text's dual-ray
524
- * SoA GPU Slug evaluator (`slugVert` + `slugFrag`) with perspective-safe
525
- * Jacobian quad skirting, single-word packed band headers, De Casteljau clipped
526
- * endpoint early-out, and Lengyel ray reliability weighting.
527
- *
528
- * Bind group 0 layout:
529
- * - `@binding(0) var<uniform> slugUniforms: SlugUniforms` (96 bytes: `mvp`, `viewportAndSkirt`, `tintAndFlags`)
530
- * - `@binding(1) var<storage, read> slugCurves: array<vec2f>`
531
- * - `@binding(2) var<storage, read> slugRows: array<u32>`
532
- *
533
- * Draw call: `pass.draw(6, instances.count)` (6 vertices generated procedurally per instance).
534
- */
535
- var SLUG_WGSL = `
536
- struct SlugUniforms {
537
- mvp: mat4x4f,
538
- viewportAndSkirt: vec4f,
539
- tintAndFlags: vec4f,
540
- }
541
-
542
- @group(0) @binding(0) var<uniform> slugUniforms: SlugUniforms;
543
- @group(0) @binding(1) var<storage, read> slugCurves: array<vec2f>;
544
- @group(0) @binding(2) var<storage, read> slugRows: array<u32>;
545
-
546
- struct SlugVSIn {
547
- @builtin(vertex_index) vertexIndex: u32,
548
- @location(0) rect: vec4f,
549
- @location(1) clip: vec4f,
550
- @location(2) color: vec4f,
551
- @location(3) glyphBounds: vec4f,
552
- @location(4) rawBand: vec4f,
553
- @location(5) sdfMeta: vec4f,
554
- }
555
-
556
- struct SlugVSOut {
557
- @builtin(position) position: vec4f,
558
- @location(0) glyphPos: vec2f,
559
- @location(1) localPos: vec2f,
560
- @location(2) @interpolate(flat, either) clip: vec4f,
561
- @location(3) @interpolate(flat, either) color: vec4f,
562
- @location(4) @interpolate(flat, either) band: vec4f,
563
- @location(5) @interpolate(flat, either) bandOrigin: vec4f,
564
- }
565
-
566
- fn slug_vertex_skirt(
567
- mvp: mat4x4f,
568
- viewport: vec2f,
569
- quad: vec2f,
570
- position: vec2f,
571
- depth: f32,
572
- skirt: f32,
573
- ) -> vec2f {
574
- let colX = mvp[0];
575
- let colY = mvp[1];
576
- let clip = mvp * vec4f(position, depth, 1.0);
577
- let safeW = max(clip.w, 1e-6);
578
- let sx = (colX.xy * safeW - clip.xy * colX.w) * viewport;
579
- let sy = (colY.xy * safeW - clip.xy * colY.w) * viewport;
580
- let absDet = max(abs(fma(sx.x, sy.y, -sx.y * sy.x)), 1e-20);
581
- let u = fma(quad, vec2f(2.0), vec2f(-1.0)) * vec2f(length(sy), length(sx)) * (skirt * 2.0 * safeW * safeW);
582
- let mult = max(clip.w, 0.0) / max(fma(-u.x, colX.w, fma(-u.y, colY.w, absDet * clip.w)), absDet * safeW * 0.0625);
583
- return u * mult;
584
- }
585
-
586
- @vertex
587
- fn slugVert(input: SlugVSIn) -> SlugVSOut {
588
- let vi = input.vertexIndex;
589
- let quad = vec2f(
590
- select(0.0, 1.0, (vi == 1u) || (vi == 2u) || (vi == 4u)),
591
- select(0.0, 1.0, (vi >= 2u) && (vi != 3u)),
592
- );
593
- let baseLocal = mix(input.rect.xy, input.rect.zw, quad);
594
- let depth = input.sdfMeta.y;
595
- let viewport = max(slugUniforms.viewportAndSkirt.xy, vec2f(1.0));
596
- let skirt = slugUniforms.viewportAndSkirt.z;
597
- let localOffset = slug_vertex_skirt(slugUniforms.mvp, viewport, quad, baseLocal, depth, skirt);
598
- let expandedLocal = baseLocal + localOffset;
599
- let localSize = max(input.rect.zw - input.rect.xy, vec2f(1e-6));
600
- let boundsSize = input.glyphBounds.zw - input.glyphBounds.xy;
601
-
602
- let packedCounts = u32(input.rawBand.y);
603
- let hBandCount = packedCounts & 255u;
604
- let vBandCount = packedCounts >> 8u;
605
-
606
- var out: SlugVSOut;
607
- out.position = slugUniforms.mvp * vec4f(expandedLocal, depth, 1.0);
608
- out.glyphPos = input.glyphBounds.xy + boundsSize * (quad + localOffset / localSize);
609
- out.localPos = expandedLocal;
610
- out.clip = input.clip;
611
- out.color = vec4f(input.color.rgb * slugUniforms.tintAndFlags.rgb, input.color.a * slugUniforms.viewportAndSkirt.w);
612
- out.band = vec4f(input.rawBand.x, input.rawBand.x + f32(hBandCount), input.rawBand.z, input.rawBand.w);
613
- out.bandOrigin = vec4f(
614
- -input.glyphBounds.y * input.rawBand.w,
615
- input.glyphBounds.z * input.rawBand.z,
616
- f32(max(hBandCount, 1u) - 1u),
617
- f32(max(vBandCount, 1u) - 1u),
618
- );
619
- return out;
620
- }
621
-
622
- fn slug_pixel_metrics_auto(p: vec2f) -> vec4f {
623
- let dx = dpdx(p);
624
- let dy = dpdy(p);
625
- let lenSq = max(vec2f(fma(dx.x, dx.x, dy.x * dy.x), fma(dx.y, dx.y, dy.y * dy.y)), vec2f(1e-18));
626
- let inv = inverseSqrt(lenSq);
627
- return vec4f(lenSq * (inv * 0.5), inv);
628
- }
629
-
630
- fn slug_band_active(packedRow: u32, span: vec2f) -> bool {
631
- return (packedRow & 63u) > 0u && span.x > f32((packedRow >> 6u) & 15u) && span.y > f32((packedRow >> 10u) & 3u);
632
- }
633
-
634
- fn slug_solve_straddle(c1: vec2f, c2: vec2f, c3: vec2f, xLo: f32, dy1: f32, s: f32, invDiam: f32) -> vec2f {
635
- let b = c1 - c2;
636
- let a = (c3 - c2) + b;
637
- let d = sqrt(max(fma(-a.y, dy1, b.y * b.y), 1e-24));
638
- let t = dy1 / fma(s, d, b.y);
639
- let u = saturate(fma(fma(a.x, t, -2.0 * b.x), t, c1.x - xLo) * invDiam);
640
- return vec2f(s * u, fma(-u, u, u));
641
- }
642
-
643
- fn slug_gather_ray(
644
- rowBase: u32,
645
- maxBand: f32,
646
- bf: f32,
647
- uSpan: vec2f,
648
- rc: vec2f,
649
- halfPx: f32,
650
- invDiam: f32,
651
- ) -> vec2f {
652
- var cw = vec2f(0.0);
653
- if (bf >= -1e-4 && bf <= maxBand + 1.0001) {
654
- let bi = u32(clamp(bf, 0.0, maxBand));
655
- let packedRow = slugRows[rowBase + bi];
656
- if (slug_band_active(packedRow, uSpan)) {
657
- let count = packedRow & 63u;
658
- let start = packedRow >> 12u;
659
- let c2Base = start + (count << 1u);
660
- let xLo = rc.x - halfPx;
661
- let xHi = rc.x + halfPx;
662
- for (var i = 0u; i < count; i++) {
663
- let base = start + (i << 1u);
664
- let c1 = slugCurves[base];
665
- let c3 = slugCurves[base + 1u];
666
- if (max(c1.x, c3.x) <= xLo) {
667
- break;
668
- }
669
- let dy1 = c1.y - rc.y;
670
- let dy3 = c3.y - rc.y;
671
- let u1 = bitcast<u32>(dy1);
672
- let u3 = bitcast<u32>(dy3);
673
- if ((u1 ^ u3) < 0x80000000u) {
674
- continue;
675
- }
676
- let s = bitcast<f32>((u1 & 0x80000000u) | 0x3f800000u);
677
- if (min(c1.x, c3.x) >= xHi) {
678
- cw.x += s;
679
- continue;
680
- }
681
- let c2 = slugCurves[c2Base + i];
682
- let hit = slug_solve_straddle(c1, c2, c3, xLo, dy1, s, invDiam);
683
- cw.x += hit.x;
684
- cw.y = max(cw.y, hit.y);
685
- }
686
- }
687
- }
688
- return cw;
689
- }
690
-
691
- fn slug_combine_rays(xc: vec2f, yc: vec2f) -> f32 {
692
- let ax = abs(xc.x);
693
- let ay = abs(yc.x);
694
- let wx = xc.y * xc.y;
695
- let wy = yc.y * yc.y;
696
- let weighted = fma(ax, wx, ay * wy) / max(wx + wy, 1e-12);
697
- return saturate(max(weighted, min(ax, ay)));
698
- }
699
-
700
- @fragment
701
- fn slugFrag(input: SlugVSOut) -> @location(0) vec4f {
702
- if (
703
- input.localPos.x < input.clip.x ||
704
- input.localPos.x > input.clip.z ||
705
- input.localPos.y < input.clip.y ||
706
- input.localPos.y > input.clip.w
707
- ) {
708
- discard;
709
- }
710
- let metrics = slug_pixel_metrics_auto(input.glyphPos);
711
- let center = input.glyphPos;
712
- let bf = vec2f(
713
- fma(center.y, input.band.w, input.bandOrigin.x),
714
- input.bandOrigin.y - center.x * input.band.z,
715
- );
716
- let totalBands = input.bandOrigin.zw + vec2f(1.0);
717
- let scale4 = vec2f(4.0) / totalBands;
718
- let halfBand = vec2f(metrics.y * input.band.w, metrics.x * input.band.z) + vec2f(1e-4);
719
- let spanA = (bf + halfBand) * scale4;
720
- let spanB = (totalBands - bf + halfBand) * scale4;
721
- let xc = slug_gather_ray(
722
- u32(input.band.x),
723
- input.bandOrigin.z,
724
- bf.x,
725
- vec2f(spanB.y * 4.0, spanA.y),
726
- center,
727
- metrics.x,
728
- metrics.z,
729
- );
730
- let yc = slug_gather_ray(
731
- u32(input.band.y),
732
- input.bandOrigin.w,
733
- bf.y,
734
- vec2f(spanA.x * 4.0, spanB.x),
735
- vec2f(center.y, -center.x),
736
- metrics.y,
737
- metrics.w,
738
- );
739
- let coverage = slug_combine_rays(xc, yc);
740
- let alpha = coverage * input.color.a;
741
- if (alpha < 0.001953125) {
742
- discard;
743
- }
744
- return vec4f(input.color.rgb * alpha, alpha);
745
- }
746
- `;
747
- /** Uploads packed `VanillaSlugGlyphInstances` into 6 instanced `GPUBuffer`s for `SLUG_WGSL`. */
748
- function uploadSlugGlyphBuffers(device, instances) {
749
- const usage = bufUsageOf();
750
- const vtxUsage = usage.VERTEX | usage.COPY_DST;
751
- const make = (label, view) => {
752
- const buffer = device.createBuffer({
753
- label,
754
- size: align4Bytes(view.byteLength),
755
- usage: vtxUsage
756
- });
757
- if (view.byteLength > 0) device.queue.writeBuffer(buffer, 0, view);
758
- return buffer;
759
- };
760
- const expandMeta = (src) => {
761
- if (src.metaItemSize >= 2) return src.metadata;
762
- const padded = new Float32Array(src.count * 2);
763
- for (let i = 0; i < src.count; i++) padded[i * 2] = src.metadata[i] ?? 0;
764
- return padded;
765
- };
766
- const rects = make("ultra-slug-rects", instances.rects);
767
- const clips = make("ultra-slug-clips", instances.clips);
768
- const colors = make("ultra-slug-colors", instances.colors);
769
- const glyphBounds = make("ultra-slug-bounds", instances.glyphBounds);
770
- const bands = make("ultra-slug-bands", instances.bands);
771
- const metadata = make("ultra-slug-meta", expandMeta(instances));
772
- let count = instances.count;
773
- let disposed = false;
774
- return {
775
- get count() {
776
- return count;
777
- },
778
- rects,
779
- clips,
780
- colors,
781
- glyphBounds,
782
- bands,
783
- metadata,
784
- update(next) {
785
- if (disposed) return;
786
- count = next.count;
787
- if (next.rects.byteLength > 0) device.queue.writeBuffer(rects, 0, next.rects);
788
- if (next.clips.byteLength > 0) device.queue.writeBuffer(clips, 0, next.clips);
789
- if (next.colors.byteLength > 0) device.queue.writeBuffer(colors, 0, next.colors);
790
- if (next.glyphBounds.byteLength > 0) device.queue.writeBuffer(glyphBounds, 0, next.glyphBounds);
791
- if (next.bands.byteLength > 0) device.queue.writeBuffer(bands, 0, next.bands);
792
- const nextMeta = expandMeta(next);
793
- if (nextMeta.byteLength > 0) device.queue.writeBuffer(metadata, 0, nextMeta);
794
- },
795
- dispose() {
796
- if (disposed) return;
797
- disposed = true;
798
- rects.destroy();
799
- clips.destroy();
800
- colors.destroy();
801
- glyphBounds.destroy();
802
- bands.destroy();
803
- metadata.destroy();
804
- }
805
- };
806
- }
807
- /** Creates a ready-to-draw premultiplied-alpha WebGPU render pipeline for `SLUG_WGSL`. */
808
- function createVanillaSlugPipeline(device, options = {}) {
809
- const usage = bufUsageOf();
810
- const format = options.format ?? "bgra8unorm";
811
- const metaStride = (options.metaItemSize ?? 2) * 4;
812
- const module = device.createShaderModule({
813
- label: "ultra-slug-wgsl",
814
- code: SLUG_WGSL
815
- });
816
- const pipeline = device.createRenderPipeline({
817
- label: "ultra-slug-pipeline",
818
- layout: "auto",
819
- vertex: {
820
- module,
821
- entryPoint: "slugVert",
822
- buffers: [
823
- {
824
- arrayStride: 16,
825
- stepMode: "instance",
826
- attributes: [{
827
- shaderLocation: 0,
828
- offset: 0,
829
- format: "float32x4"
830
- }]
831
- },
832
- {
833
- arrayStride: 16,
834
- stepMode: "instance",
835
- attributes: [{
836
- shaderLocation: 1,
837
- offset: 0,
838
- format: "float32x4"
839
- }]
840
- },
841
- {
842
- arrayStride: 4,
843
- stepMode: "instance",
844
- attributes: [{
845
- shaderLocation: 2,
846
- offset: 0,
847
- format: "unorm8x4"
848
- }]
849
- },
850
- {
851
- arrayStride: 16,
852
- stepMode: "instance",
853
- attributes: [{
854
- shaderLocation: 3,
855
- offset: 0,
856
- format: "float32x4"
857
- }]
858
- },
859
- {
860
- arrayStride: 16,
861
- stepMode: "instance",
862
- attributes: [{
863
- shaderLocation: 4,
864
- offset: 0,
865
- format: "float32x4"
866
- }]
867
- },
868
- {
869
- arrayStride: metaStride,
870
- stepMode: "instance",
871
- attributes: [{
872
- shaderLocation: 5,
873
- offset: 0,
874
- format: options.metaItemSize === 1 ? "float32" : "float32x2"
875
- }]
876
- }
877
- ]
878
- },
879
- fragment: {
880
- module,
881
- entryPoint: "slugFrag",
882
- targets: [{
883
- format,
884
- blend: {
885
- color: {
886
- srcFactor: "one",
887
- dstFactor: "one-minus-src-alpha",
888
- operation: "add"
889
- },
890
- alpha: {
891
- srcFactor: "one",
892
- dstFactor: "one-minus-src-alpha",
893
- operation: "add"
894
- }
895
- }
896
- }]
897
- },
898
- primitive: {
899
- topology: "triangle-list",
900
- cullMode: options.cullMode ?? "none"
901
- },
902
- ...options.depthFormat ? { depthStencil: {
903
- format: options.depthFormat,
904
- depthWriteEnabled: options.depthWriteEnabled ?? false,
905
- depthCompare: options.depthCompare ?? "less-equal"
906
- } } : {},
907
- ...options.sampleCount === void 0 ? {} : { multisample: { count: options.sampleCount } }
908
- });
909
- const uniformData = /* @__PURE__ */ new Float32Array(24);
910
- const uniformBuffer = device.createBuffer({
911
- label: "ultra-slug-uniforms",
912
- size: uniformData.byteLength,
913
- usage: usage.UNIFORM | usage.COPY_DST
914
- });
915
- let disposed = false;
916
- return {
917
- pipeline,
918
- uniformBuffer,
919
- writeUniforms(uniforms) {
920
- if (disposed) return;
921
- for (let i = 0; i < 16; i++) uniformData[i] = uniforms.mvp[i] ?? 0;
922
- uniformData[16] = uniforms.viewportWidth;
923
- uniformData[17] = uniforms.viewportHeight;
924
- uniformData[18] = uniforms.skirtPx ?? .75;
925
- uniformData[19] = uniforms.opacity ?? 1;
926
- uniformData[20] = uniforms.tint?.[0] ?? 1;
927
- uniformData[21] = uniforms.tint?.[1] ?? 1;
928
- uniformData[22] = uniforms.tint?.[2] ?? 1;
929
- uniformData[23] = 0;
930
- device.queue.writeBuffer(uniformBuffer, 0, uniformData);
931
- },
932
- createBindGroup(atlas) {
933
- if (!atlas.curvesBuffer || !atlas.rowsBuffer) throw new Error("createVanillaSlugPipeline.createBindGroup: atlas has no GPU storage buffers; pass a GPUDevice to buildVanillaSlugAtlas");
934
- return device.createBindGroup({
935
- label: "ultra-slug-bind-group",
936
- layout: pipeline.getBindGroupLayout(0),
937
- entries: [
938
- {
939
- binding: 0,
940
- resource: { buffer: uniformBuffer }
941
- },
942
- {
943
- binding: 1,
944
- resource: { buffer: atlas.curvesBuffer }
945
- },
946
- {
947
- binding: 2,
948
- resource: { buffer: atlas.rowsBuffer }
949
- }
950
- ]
951
- });
952
- },
953
- draw(pass, bindGroup, gpuInstances) {
954
- if (gpuInstances.count === 0) return;
955
- pass.setPipeline(pipeline);
956
- pass.setBindGroup(0, bindGroup);
957
- pass.setVertexBuffer(0, gpuInstances.rects);
958
- pass.setVertexBuffer(1, gpuInstances.clips);
959
- pass.setVertexBuffer(2, gpuInstances.colors);
960
- pass.setVertexBuffer(3, gpuInstances.glyphBounds);
961
- pass.setVertexBuffer(4, gpuInstances.bands);
962
- pass.setVertexBuffer(5, gpuInstances.metadata);
963
- pass.draw(6, gpuInstances.count);
964
- },
965
- dispose() {
966
- if (disposed) return;
967
- disposed = true;
968
- uniformBuffer.destroy();
969
- }
970
- };
971
- }
972
- function nowMs() {
973
- return typeof performance !== "undefined" ? performance.now() : Date.now();
974
- }
975
- function linkAbortSignals(...signals) {
976
- const controller = new AbortController();
977
- const active = signals.filter((signal) => signal !== void 0);
978
- for (const signal of active) if (signal.aborted) {
979
- controller.abort(signal.reason ?? makeAbortError());
980
- return [controller, () => void 0];
981
- }
982
- const listeners = active.map((signal) => {
983
- const onAbort = () => {
984
- controller.abort(signal.reason ?? makeAbortError());
985
- };
986
- signal.addEventListener("abort", onAbort, { once: true });
987
- return [signal, onAbort];
988
- });
989
- return [controller, () => {
990
- for (const [signal, onAbort] of listeners) signal.removeEventListener("abort", onAbort);
991
- }];
992
- }
993
- async function waitForDocumentFonts(document, signal) {
994
- signal?.throwIfAborted();
995
- const fonts = document.fonts;
996
- if (!fonts) return;
997
- if (!signal) {
998
- await Promise.resolve(fonts.ready);
999
- return;
1000
- }
1001
- await new Promise((resolve, reject) => {
1002
- const onAbort = () => {
1003
- reject(signal.reason instanceof Error ? signal.reason : makeAbortError(String(signal.reason ?? "")));
1004
- };
1005
- signal.addEventListener("abort", onAbort, { once: true });
1006
- Promise.resolve(fonts.ready).then(() => {
1007
- signal.removeEventListener("abort", onAbort);
1008
- resolve();
1009
- }, (error) => {
1010
- signal.removeEventListener("abort", onAbort);
1011
- reject(error instanceof Error ? error : new Error(String(error)));
1012
- });
1013
- });
1014
- }
1015
- var VanillaDomSlug = class VanillaDomSlug {
1016
- element;
1017
- device;
1018
- options;
1019
- glyphs;
1020
- plainRects = null;
1021
- litRects = null;
1022
- decorations = null;
1023
- tone = null;
1024
- motion;
1025
- #a;
1026
- #s = null;
1027
- #as = "";
1028
- #ls = "";
1029
- #o = true;
1030
- #st;
1031
- #to = null;
1032
- #ro = null;
1033
- #mo = null;
1034
- #uf = null;
1035
- #f = null;
1036
- #ac = null;
1037
- #rv = 0;
1038
- #av = 0;
1039
- #sel = false;
1040
- #d = false;
1041
- #cbs = /* @__PURE__ */ new Set();
1042
- constructor(element, deviceOrRenderer, options) {
1043
- this.element = element;
1044
- this.device = resolveSlugGpuDevice(deviceOrRenderer);
1045
- this.options = Object.freeze({ ...options });
1046
- this.motion = {
1047
- enabled: options.motion?.enabled ?? true,
1048
- mode: options.motion?.mode ?? "slide-up",
1049
- strength: Math.max(0, options.motion?.strength ?? 18),
1050
- speed: Math.max(0, options.motion?.speed ?? 1.35),
1051
- stagger: Math.max(0, options.motion?.stagger ?? .045)
1052
- };
1053
- if (options.onChange) this.#cbs.add(options.onChange);
1054
- }
1055
- static async create(element, deviceOrRenderer, options = {}) {
1056
- if (!element.isConnected) throw new Error("VanillaDomSlug.create requires a connected HTMLElement");
1057
- options.signal?.throwIfAborted();
1058
- const instance = new VanillaDomSlug(element, deviceOrRenderer, options);
1059
- try {
1060
- instance.applySelectableAttribute();
1061
- await instance.rebuild(options.signal ? { signal: options.signal } : {});
1062
- instance.setupObservers();
1063
- instance.notify("create");
1064
- return instance;
1065
- } catch (error) {
1066
- instance.dispose();
1067
- throw error;
1068
- }
1069
- }
1070
- get atlas() {
1071
- return this.#a;
1072
- }
1073
- /** Alias for `element` matching `DomSlug.source`. */
1074
- get source() {
1075
- return this.element;
1076
- }
1077
- get stats() {
1078
- return this.#st;
1079
- }
1080
- get snapshot() {
1081
- return this.#s;
1082
- }
1083
- get width() {
1084
- return this.#s?.width ?? 0;
1085
- }
1086
- get height() {
1087
- return this.#s?.height ?? 0;
1088
- }
1089
- get isDisposed() {
1090
- return this.#d;
1091
- }
1092
- subscribe(listener) {
1093
- this.#cbs.add(listener);
1094
- return () => {
1095
- this.#cbs.delete(listener);
1096
- };
1097
- }
1098
- reflow(width) {
1099
- if (this.#d) throw new Error("Cannot reflow a disposed VanillaDomSlug instance");
1100
- if (this.options.reflowable !== true || !this.#s) throw new Error("VanillaDomSlug.reflow requires { reflowable: true } at creation time");
1101
- if (!Number.isFinite(width) || width <= 0) throw new RangeError("VanillaDomSlug.reflow: width must be a positive finite number");
1102
- const geometryStart = nowMs();
1103
- const nextSnapshot = reflowSnapshot(this.#s, width);
1104
- const motionPadding = Math.max(0, this.motion.strength);
1105
- if (updateSlugGlyphInstances(this.glyphs, nextSnapshot, this.#a, motionPadding) === null) this.glyphs = packSlugGlyphInstances(nextSnapshot, this.#a, motionPadding);
1106
- if (this.decorations) {
1107
- const drawable = (key) => (this.#a.glyphs.get(key)?.monotonePieceCount ?? 0) > 0;
1108
- if (!updateDecorationInstances(this.decorations, nextSnapshot, this.glyphs.glyphRects, drawable, motionPadding)) this.decorations = packDecorationInstances(nextSnapshot, this.glyphs.glyphRects, drawable, motionPadding);
1109
- }
1110
- const geometryBuildMs = nowMs() - geometryStart;
1111
- this.#s = nextSnapshot;
1112
- this.#ls = "";
1113
- const draws = (this.plainRects ? 1 : 0) + (this.litRects ? 1 : 0) + (this.glyphs.count > 0 ? 1 : 0) + (this.decorations ? 1 : 0);
1114
- this.#st = Object.freeze({
1115
- ...this.#st,
1116
- atlasBuildMs: 0,
1117
- layoutReadMs: 0,
1118
- geometryBuildMs,
1119
- lines: nextSnapshot.lineCount,
1120
- draws
1121
- });
1122
- this.notify("reflow");
1123
- return this;
1124
- }
1125
- setMotion(motion) {
1126
- if (this.#d) return this;
1127
- const previousStrength = this.motion.strength;
1128
- this.motion = {
1129
- enabled: motion.enabled ?? this.motion.enabled,
1130
- mode: motion.mode ?? this.motion.mode,
1131
- strength: Math.max(0, motion.strength ?? this.motion.strength),
1132
- speed: Math.max(0, motion.speed ?? this.motion.speed),
1133
- stagger: Math.max(0, motion.stagger ?? this.motion.stagger)
1134
- };
1135
- if (this.motion.strength !== previousStrength && this.#s) {
1136
- let minZ = 0;
1137
- let maxZ = 0;
1138
- for (const glyph of this.#s.glyphs) {
1139
- if (glyph.z < minZ) minZ = glyph.z;
1140
- if (glyph.z > maxZ) maxZ = glyph.z;
1141
- }
1142
- this.glyphs.bounds = computeInstanceBounds(this.#s.width, this.#s.height, this.motion.strength, minZ, maxZ);
1143
- }
1144
- this.notify("motion");
1145
- return this;
1146
- }
1147
- async rebuild(rebuildOptions = {}) {
1148
- if (this.#d) throw new Error("Cannot rebuild a disposed VanillaDomSlug instance");
1149
- if (!this.element.isConnected) throw new Error("Cannot rebuild VanillaDomSlug when the source element is disconnected");
1150
- const version = ++this.#rv;
1151
- this.#ac?.abort(makeAbortError());
1152
- const [controller, unlinkSignals] = linkAbortSignals(this.options.signal, rebuildOptions.signal);
1153
- this.#ac = controller;
1154
- const { signal } = controller;
1155
- const forceOutlines = rebuildOptions.outlines === true || rebuildOptions.atlas === true;
1156
- let nextAtlas;
1157
- let nextOwnsAtlas = true;
1158
- try {
1159
- await waitForDocumentFonts(this.element.ownerDocument, signal);
1160
- signal.throwIfAborted();
1161
- const opts = this.options;
1162
- const sharedAtlas = opts.sharedAtlas;
1163
- const currentAtlas = this.#a;
1164
- const layoutStart = nowMs();
1165
- const snapshotOptions = {
1166
- ...opts.colorGlyphs === void 0 ? {} : { colorGlyphs: opts.colorGlyphs },
1167
- ...opts.svg === void 0 ? {} : { svg: opts.svg },
1168
- ...opts.tone === void 0 ? {} : { tone: opts.tone },
1169
- ...opts.layoutEngine === void 0 ? {} : { layoutEngine: opts.layoutEngine },
1170
- ...opts.textSelector === void 0 ? {} : { textSelector: opts.textSelector },
1171
- ...opts.rectSelector === void 0 ? {} : { rectSelector: opts.rectSelector },
1172
- ...opts.ignoreSelector === void 0 ? {} : { ignoreSelector: opts.ignoreSelector },
1173
- ...opts.includeRootBackground === void 0 ? {} : { includeRootBackground: opts.includeRootBackground },
1174
- ...opts.extraGlyphs === void 0 ? {} : { extraGlyphs: opts.extraGlyphs },
1175
- ...opts.pixelsPerUnit === void 0 ? {} : { pixelsPerUnit: opts.pixelsPerUnit },
1176
- ...opts.pixelSnap === void 0 ? {} : { pixelSnap: opts.pixelSnap },
1177
- ...opts.textDepth === void 0 ? {} : { textDepth: opts.textDepth },
1178
- ...opts.rectDepth === void 0 ? {} : { rectDepth: opts.rectDepth },
1179
- ...opts.panelDepth === void 0 ? {} : { panelDepth: opts.panelDepth },
1180
- ...opts.cjkLineBreaking === void 0 ? {} : { cjkLineBreaking: opts.cjkLineBreaking },
1181
- ...opts.rtlReflow === void 0 ? {} : { rtlReflow: opts.rtlReflow },
1182
- ...opts.reshape === void 0 ? {} : { reshape: opts.reshape },
1183
- ...opts.reflowable === void 0 ? {} : { reflowable: opts.reflowable },
1184
- signal
1185
- };
1186
- const snapshot = await collectDomSnapshot(this.element, snapshotOptions);
1187
- const layoutReadMs = nowMs() - layoutStart;
1188
- signal.throwIfAborted();
1189
- const nextTone = this.resolveCaptureTone(snapshot);
1190
- const canUseSharedAtlas = Boolean(!forceOutlines && sharedAtlas && snapshot.requests.every((r) => sharedAtlas.covers(r.key)));
1191
- const canReusePrivateAtlas = Boolean(!forceOutlines && !canUseSharedAtlas && currentAtlas && this.#o && (this.#as === snapshot.atlasSignature || snapshot.requests.every((r) => currentAtlas.covers(r.key))));
1192
- const nextLayoutSignature = layoutSignatureOf(snapshot);
1193
- if (this.#ls === "" && this.#s) this.#ls = layoutSignatureOf(this.#s);
1194
- if ((canUseSharedAtlas || canReusePrivateAtlas) && this.#ls !== "" && nextLayoutSignature === this.#ls) {
1195
- if (version !== this.#rv || this.#d) throw makeAbortError();
1196
- this.tone = nextTone;
1197
- this.#s = snapshot;
1198
- this.#st = Object.freeze({
1199
- ...this.#st,
1200
- atlasBuildMs: 0,
1201
- layoutReadMs,
1202
- geometryBuildMs: 0
1203
- });
1204
- this.notify("rebuild");
1205
- return this;
1206
- }
1207
- const atlasStart = nowMs();
1208
- if (canUseSharedAtlas && sharedAtlas) {
1209
- nextAtlas = sharedAtlas;
1210
- nextOwnsAtlas = false;
1211
- } else if (canReusePrivateAtlas && currentAtlas) {
1212
- nextAtlas = currentAtlas;
1213
- nextOwnsAtlas = true;
1214
- } else {
1215
- let provider = opts.outlineProvider;
1216
- if (!provider) {
1217
- if (!this.#to) this.#to = createTracedOutlineProvider(this.element.ownerDocument, {
1218
- ...opts.colorGlyphs === void 0 ? {} : { colorGlyphs: opts.colorGlyphs },
1219
- ...opts.traceSize === void 0 ? {} : { size: opts.traceSize },
1220
- ...opts.traceTolerance === void 0 ? {} : { tolerance: opts.traceTolerance }
1221
- });
1222
- else if (forceOutlines) this.#to.clear();
1223
- provider = this.#to.provider;
1224
- }
1225
- nextAtlas = await buildVanillaSlugAtlas(this.device, snapshot.requests, {
1226
- outlineProvider: provider,
1227
- missingGlyphs: opts.missingGlyphs ?? (opts.outlineProvider ? "error" : "skip"),
1228
- ...opts.targetPiecesPerBand === void 0 ? {} : { targetPiecesPerBand: opts.targetPiecesPerBand },
1229
- signal
1230
- });
1231
- nextOwnsAtlas = true;
1232
- }
1233
- const atlasBuildMs = canUseSharedAtlas || canReusePrivateAtlas ? 0 : nowMs() - atlasStart;
1234
- signal.throwIfAborted();
1235
- if (version !== this.#rv || this.#d) throw makeAbortError();
1236
- const resolvedAtlas = nextAtlas;
1237
- const geometryStart = nowMs();
1238
- const motionPadding = Math.max(0, this.motion.strength);
1239
- const drawable = (key) => (resolvedAtlas.glyphs.get(key)?.monotonePieceCount ?? 0) > 0;
1240
- const currentGlyphs = this.glyphs;
1241
- if (!currentGlyphs || updateSlugGlyphInstances(currentGlyphs, snapshot, resolvedAtlas, motionPadding) === null) this.glyphs = packSlugGlyphInstances(snapshot, resolvedAtlas, motionPadding);
1242
- if (!this.plainRects || !updateRectInstances(this.plainRects, snapshot, false)) this.plainRects = packRectInstances(snapshot, false);
1243
- if (!this.litRects || !updateRectInstances(this.litRects, snapshot, true)) this.litRects = packRectInstances(snapshot, true);
1244
- if (!this.decorations || !updateDecorationInstances(this.decorations, snapshot, this.glyphs.glyphRects, drawable, motionPadding)) this.decorations = packDecorationInstances(snapshot, this.glyphs.glyphRects, drawable, motionPadding);
1245
- const geometryBuildMs = nowMs() - geometryStart;
1246
- const previousAtlas = this.#a;
1247
- const previousOwnsAtlas = this.#o;
1248
- this.#a = resolvedAtlas;
1249
- this.#o = nextOwnsAtlas;
1250
- this.tone = nextTone;
1251
- this.#s = snapshot;
1252
- if (!canUseSharedAtlas && !canReusePrivateAtlas) this.#as = snapshot.atlasSignature;
1253
- this.#ls = nextLayoutSignature;
1254
- this.#av = version;
1255
- this.#to?.retain(snapshot.requests.map((request) => request.key));
1256
- let textGlyphs = 0;
1257
- let shapes = 0;
1258
- let skipped = 0;
1259
- for (const glyph of snapshot.glyphs) if (glyph.shapeGroup !== void 0) shapes++;
1260
- else {
1261
- textGlyphs++;
1262
- if (resolvedAtlas.skippedKeys.has(glyph.glyphKey)) skipped++;
1263
- }
1264
- const draws = (this.plainRects ? 1 : 0) + (this.litRects ? 1 : 0) + (this.glyphs.count > 0 ? 1 : 0) + (this.decorations ? 1 : 0);
1265
- this.#st = Object.freeze({
1266
- colorGlyphs: 0,
1267
- shapes,
1268
- fallbackGlyphs: skipped,
1269
- switchableGlyphs: 0,
1270
- atlasBuildMs,
1271
- layoutReadMs,
1272
- geometryBuildMs,
1273
- glyphs: textGlyphs,
1274
- rects: snapshot.rects.length,
1275
- lines: snapshot.lineCount,
1276
- draws,
1277
- atlasWidth: 0,
1278
- atlasHeight: 0,
1279
- textBackend: "slug",
1280
- atlasMode: null,
1281
- textStorageBytes: resolvedAtlas.byteLength
1282
- });
1283
- if (previousAtlas && previousOwnsAtlas && previousAtlas !== resolvedAtlas) previousAtlas.dispose();
1284
- if (this.#av > 1) this.notify("rebuild");
1285
- return this;
1286
- } catch (error) {
1287
- if (nextAtlas && nextOwnsAtlas && nextAtlas !== this.#a) nextAtlas.dispose();
1288
- throw error;
1289
- } finally {
1290
- unlinkSignals();
1291
- if (this.#ac === controller) this.#ac = null;
1292
- }
1293
- }
1294
- dispose() {
1295
- if (this.#d) return;
1296
- this.#d = true;
1297
- this.#ac?.abort(makeAbortError());
1298
- this.#ac = null;
1299
- if (this.#f !== null && typeof cancelAnimationFrame === "function") {
1300
- cancelAnimationFrame(this.#f);
1301
- this.#f = null;
1302
- }
1303
- this.#ro?.disconnect();
1304
- this.#ro = null;
1305
- this.#mo?.disconnect();
1306
- this.#mo = null;
1307
- this.#uf?.();
1308
- this.#uf = null;
1309
- this.#to?.clear();
1310
- this.#to = null;
1311
- if (this.#sel) {
1312
- this.element.classList.remove("sdf-selectable");
1313
- this.#sel = false;
1314
- }
1315
- const currentAtlas = this.#a;
1316
- if (currentAtlas && this.#o) currentAtlas.dispose();
1317
- this.#s = null;
1318
- this.notify("dispose");
1319
- this.#cbs.clear();
1320
- }
1321
- resolveCaptureTone(snapshot) {
1322
- return resolveDomTextTone(this.element, this.options.tone, {
1323
- glyphs: snapshot.glyphs,
1324
- rects: snapshot.rects,
1325
- rootRect: this.options.includeRootBackground !== false
1326
- });
1327
- }
1328
- notify(reason) {
1329
- for (const listener of this.#cbs) listener(this, reason);
1330
- }
1331
- applySelectableAttribute() {
1332
- if (this.options.selectable !== true) return;
1333
- if (!this.element.classList.contains("sdf-selectable")) {
1334
- this.element.classList.add("sdf-selectable");
1335
- this.#sel = true;
1336
- }
1337
- }
1338
- setupObservers() {
1339
- if (this.options.observe === false || this.#d) return;
1340
- const schedule = (forceOutlines = false) => {
1341
- if (this.#d || this.#f !== null) return;
1342
- if (typeof requestAnimationFrame === "function") this.#f = requestAnimationFrame(() => {
1343
- this.#f = null;
1344
- if (this.#d || !this.element.isConnected) return;
1345
- this.rebuild(forceOutlines ? { outlines: true } : {}).catch((error) => {
1346
- if (!isAbortError(error)) this.options.onError?.(error);
1347
- });
1348
- });
1349
- };
1350
- if (typeof ResizeObserver !== "undefined") {
1351
- this.#ro = new ResizeObserver(() => schedule(false));
1352
- this.#ro.observe(this.element);
1353
- }
1354
- if (typeof MutationObserver !== "undefined") {
1355
- this.#mo = new MutationObserver(() => schedule(false));
1356
- this.#mo.observe(this.element, {
1357
- subtree: true,
1358
- childList: true,
1359
- characterData: true,
1360
- attributes: true,
1361
- attributeFilter: [
1362
- "style",
1363
- "class",
1364
- "dir",
1365
- "lang",
1366
- "data-text-depth",
1367
- "data-sdf-depth"
1368
- ]
1369
- });
1370
- }
1371
- const fonts = this.element.ownerDocument.fonts;
1372
- if (fonts && typeof fonts.addEventListener === "function") {
1373
- const onFonts = () => {
1374
- this.#to?.clear();
1375
- schedule(true);
1376
- };
1377
- fonts.addEventListener("loadingdone", onFonts);
1378
- this.#uf = () => {
1379
- fonts.removeEventListener("loadingdone", onFonts);
1380
- };
1381
- }
1382
- }
1383
- };
1384
- function stripTextOnlyOptions(options) {
1385
- const domOptions = { ...options };
1386
- delete domOptions.css;
1387
- delete domOptions.cssClass;
1388
- delete domOptions.parent;
1389
- delete domOptions.device;
1390
- delete domOptions.renderer;
1391
- return domOptions;
1392
- }
1393
- var VanillaSlugText = class VanillaSlugText extends VanillaDomSlug {
1394
- ready;
1395
- #host;
1396
- #t;
1397
- constructor(text, options = {}) {
1398
- options.signal?.throwIfAborted();
1399
- const [parent, host, source] = createTextSource(text, options);
1400
- parent.append(host);
1401
- try {
1402
- super(source, options.device ?? options.renderer, stripTextOnlyOptions(copyTextOptions(options)));
1403
- } catch (error) {
1404
- host.remove();
1405
- throw error;
1406
- }
1407
- this.#host = host;
1408
- this.#t = text;
1409
- this.ready = this.#p(options.signal);
1410
- }
1411
- async #p(signal) {
1412
- try {
1413
- await this.rebuild(signal ? { signal } : {});
1414
- this.setupObservers();
1415
- this.notify("create");
1416
- return this;
1417
- } catch (error) {
1418
- this.dispose();
1419
- throw error;
1420
- }
1421
- }
1422
- static async create(textOrElement, optionsOrDevice, maybeOptions) {
1423
- if (typeof textOrElement === "string") return new VanillaSlugText(textOrElement, optionsOrDevice ?? {}).ready;
1424
- return super.create(textOrElement, optionsOrDevice, maybeOptions);
1425
- }
1426
- get text() {
1427
- return this.#t;
1428
- }
1429
- set text(value) {
1430
- this.#t = value;
1431
- if (!this.isDisposed) this.element.textContent = value;
1432
- }
1433
- async setText(value, options) {
1434
- this.text = value;
1435
- return this.rebuild(options);
1436
- }
1437
- async setCss(css, options) {
1438
- if (!this.isDisposed) this.element.style.cssText = css === void 0 ? "" : cssDeclarations(this.element.ownerDocument, css);
1439
- return this.rebuild(options);
1440
- }
1441
- async setClass(cssClass, options) {
1442
- if (!this.isDisposed) this.element.className = cssClass === void 0 ? "" : classNames(cssClass);
1443
- return this.rebuild(options);
1444
- }
1445
- dispose() {
1446
- const wasDisposed = this.isDisposed;
1447
- super.dispose();
1448
- if (!wasDisposed) this.#host.remove();
1449
- }
1450
- resolveCaptureTone(snapshot) {
1451
- return resolveDomTextTone(this.element, this.options.tone, {
1452
- glyphs: snapshot.glyphs,
1453
- rects: snapshot.rects,
1454
- rootRect: this.options.includeRootBackground !== false,
1455
- page: false
1456
- });
1457
- }
1458
- };
1459
- export { VanillaDomSlug as DomSlug, VanillaDomSlug as DomText, VanillaDomSlug, VanillaDomSlug as VanillaDomText, SLUG_WGSL, VanillaSlugText as SlugText, VanillaSlugText as Text, VanillaSlugText, VanillaSlugText as VanillaText, UNIT_QUAD_INDICES, UNIT_QUAD_NORMALS, UNIT_QUAD_POSITIONS, backdropCurve, buildVanillaSlugAtlas as buildSlugAtlas, buildVanillaSlugAtlas, collectDomSnapshot, computeInstanceBounds, createSvgEmojiOutlineProvider, createTracedOutlineProvider, createTrueTypeOutlineProvider, createVanillaSlugPipeline, layoutSignatureOf, packDecorationInstances, packRectInstances, packSlugGlyphInstances, parseTrueTypeFont, preprocessSlugGlyphs, reflowSnapshot, resolveDomTextTone, resolveTextTone, snapGlyph, srgbEncode, svgToWindfoilOutlines, toneCoverage, toneLightness, updateDecorationInstances, updateRectInstances, updateSlugGlyphInstances, uploadSlugGlyphBuffers, windfoilOutlineFromSvgPaths };
1460
-
1461
- //# sourceMappingURL=slug-vanilla.js.map
13
+ import { DomSlug as VanillaDomSlug, SLUG_WGSL, SlugText as VanillaSlugText, UNIT_QUAD_INDICES, UNIT_QUAD_NORMALS, UNIT_QUAD_POSITIONS, buildSlugAtlas as buildVanillaSlugAtlas, computeInstanceBounds, createVanillaSlugPipeline, packRectInstances, packSlugGlyphInstances, updateRectInstances, updateSlugGlyphInstances, uploadSlugGlyphBuffers } from "./slug/vanillaCore.js";
14
+ export { VanillaDomSlug as DomSlug, VanillaDomSlug as DomText, SLUG_WGSL, VanillaSlugText as SlugText, VanillaSlugText as Text, UNIT_QUAD_INDICES, UNIT_QUAD_NORMALS, UNIT_QUAD_POSITIONS, VanillaDomSlug, VanillaDomSlug as VanillaDomText, VanillaSlugText, VanillaSlugText as VanillaText, backdropCurve, buildVanillaSlugAtlas as buildSlugAtlas, buildVanillaSlugAtlas, collectDomSnapshot, computeInstanceBounds, createFontOutlineProvider, createSvgEmojiOutlineProvider, createTracedOutlineProvider, createTrueTypeOutlineProvider, createVanillaSlugPipeline, layoutSignatureOf, packDecorationInstances, packRectInstances, packSlugGlyphInstances, parseFont, parseTrueTypeFont, preprocessSlugGlyphs, reflowSnapshot, resolveDomTextTone, resolveTextTone, snapGlyph, srgbEncode, svgToWindfoilOutlines, toneCoverage, toneLightness, updateDecorationInstances, updateRectInstances, updateSlugGlyphInstances, uploadSlugGlyphBuffers, windfoilOutlineFromSvgPaths };