ultra-text 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +168 -85
  2. package/THIRD_PARTY_NOTICES.md +3 -0
  3. package/dist/assets/{cpuSdf.worker-Du9o8q4p.js → cpuSdf.worker-xS57yQbP.js} +13 -11
  4. package/dist/assets/cpuSdf.worker-xS57yQbP.js.map +1 -0
  5. package/dist/atlas/appendAtlas.js +2 -1
  6. package/dist/atlas/appendAtlas.js.map +1 -1
  7. package/dist/atlas/buildAtlas.js +3 -14
  8. package/dist/atlas/buildAtlas.js.map +1 -1
  9. package/dist/atlas/cpuSdf.js +12 -10
  10. package/dist/atlas/cpuSdf.js.map +1 -1
  11. package/dist/atlas/cpuWorker.js +1 -1
  12. package/dist/atlas/cpuWorker.js.map +1 -1
  13. package/dist/atlas/gpuAtlas.d.ts +7 -6
  14. package/dist/atlas/gpuAtlas.js +280 -145
  15. package/dist/atlas/gpuAtlas.js.map +1 -1
  16. package/dist/atlas/jfaWgsl.js +201 -73
  17. package/dist/atlas/jfaWgsl.js.map +1 -1
  18. package/dist/atlas/rasterize.d.ts +2 -0
  19. package/dist/atlas/rasterize.js +2 -87
  20. package/dist/atlas/rasterize.js.map +1 -1
  21. package/dist/dom/DomSdf.js +66 -15
  22. package/dist/dom/DomSdf.js.map +1 -1
  23. package/dist/dom/DomSlug.d.ts +26 -0
  24. package/dist/dom/DomSlug.js +640 -0
  25. package/dist/dom/DomSlug.js.map +1 -0
  26. package/dist/dom/SlugText.d.ts +18 -0
  27. package/dist/dom/SlugText.js +94 -0
  28. package/dist/dom/SlugText.js.map +1 -0
  29. package/dist/dom/Text.js +4 -67
  30. package/dist/dom/Text.js.map +1 -1
  31. package/dist/dom/fontCanvas.d.ts +2 -0
  32. package/dist/dom/fontCanvas.js +101 -0
  33. package/dist/dom/fontCanvas.js.map +1 -0
  34. package/dist/dom/layoutSignature.js +29 -2
  35. package/dist/dom/layoutSignature.js.map +1 -1
  36. package/dist/dom/snapshot.js +251 -96
  37. package/dist/dom/snapshot.js.map +1 -1
  38. package/dist/dom/textHost.d.ts +11 -0
  39. package/dist/dom/textHost.js +68 -0
  40. package/dist/dom/textHost.js.map +1 -0
  41. package/dist/slug/SlugMaterial.d.ts +3 -2
  42. package/dist/slug/SlugMaterial.js +28 -2
  43. package/dist/slug/SlugMaterial.js.map +1 -1
  44. package/dist/slug/coverage.d.ts +1 -1
  45. package/dist/slug/coverage.js +1 -1
  46. package/dist/slug/coverage.js.map +1 -1
  47. package/dist/slug/preprocessCore.d.ts +1 -2
  48. package/dist/slug/preprocessCore.js +39 -16
  49. package/dist/slug/preprocessCore.js.map +1 -1
  50. package/dist/slug/runtime.js +6 -4
  51. package/dist/slug/runtime.js.map +1 -1
  52. package/dist/slug/standaloneRuntime.d.ts +39 -0
  53. package/dist/slug/standaloneRuntime.js +140 -0
  54. package/dist/slug/standaloneRuntime.js.map +1 -0
  55. package/dist/slug/truetype.d.ts +22 -0
  56. package/dist/slug/truetype.js +494 -0
  57. package/dist/slug/truetype.js.map +1 -0
  58. package/dist/slug-vanilla.d.ts +364 -0
  59. package/dist/slug-vanilla.js +1461 -0
  60. package/dist/slug-vanilla.js.map +1 -0
  61. package/dist/slug.d.ts +21 -0
  62. package/dist/slug.js +19 -0
  63. package/dist/text/GlyphTextMaterial.d.ts +11 -11
  64. package/dist/text/GlyphTextMaterial.js +98 -29
  65. package/dist/text/GlyphTextMaterial.js.map +1 -1
  66. package/dist/text/SdfTextMaterial.d.ts +5 -4
  67. package/dist/text/SdfTextMaterial.js +22 -4
  68. package/dist/text/SdfTextMaterial.js.map +1 -1
  69. package/dist/types.d.ts +63 -14
  70. package/dist/vanilla.d.ts +3 -0
  71. package/dist/vanilla.js +132 -59
  72. package/dist/vanilla.js.map +1 -1
  73. package/dist/windfoil/WindfoilMaterial.d.ts +2 -1
  74. package/dist/windfoil/WindfoilMaterial.js +8 -1
  75. package/dist/windfoil/WindfoilMaterial.js.map +1 -1
  76. package/dist/windfoil/abortable.d.ts +2 -0
  77. package/dist/windfoil/abortable.js +26 -0
  78. package/dist/windfoil/abortable.js.map +1 -0
  79. package/dist/windfoil/color.js +2 -1
  80. package/dist/windfoil/color.js.map +1 -1
  81. package/dist/windfoil/coverage.d.ts +3 -20
  82. package/dist/windfoil/coverage.js +7 -20
  83. package/dist/windfoil/coverage.js.map +1 -1
  84. package/dist/windfoil/emoji.js +1 -1
  85. package/dist/windfoil/emoji.js.map +1 -1
  86. package/dist/windfoil/emojiMetrics.js +1 -1
  87. package/dist/windfoil/emojiMetrics.js.map +1 -1
  88. package/dist/windfoil/geometry.js +100 -33
  89. package/dist/windfoil/geometry.js.map +1 -1
  90. package/dist/windfoil/layerGrid.js +14 -10
  91. package/dist/windfoil/layerGrid.js.map +1 -1
  92. package/dist/windfoil/layerNormalization.d.ts +1 -1
  93. package/dist/windfoil/layerNormalization.js +1 -1
  94. package/dist/windfoil/layerNormalization.js.map +1 -1
  95. package/dist/windfoil/outlineValidation.d.ts +86 -0
  96. package/dist/windfoil/outlineValidation.js +65 -0
  97. package/dist/windfoil/outlineValidation.js.map +1 -0
  98. package/dist/windfoil/preprocess.js +3 -2
  99. package/dist/windfoil/preprocess.js.map +1 -1
  100. package/dist/windfoil/preprocessCore.d.ts +4 -85
  101. package/dist/windfoil/preprocessCore.js +210 -206
  102. package/dist/windfoil/preprocessCore.js.map +1 -1
  103. package/dist/windfoil/requests.js +1 -1
  104. package/dist/windfoil/requests.js.map +1 -1
  105. package/dist/windfoil/runtime.d.ts +2 -1
  106. package/dist/windfoil/runtime.js +3 -2
  107. package/dist/windfoil/runtime.js.map +1 -1
  108. package/dist/windfoil/shapeResources.js +2 -1
  109. package/dist/windfoil/shapeResources.js.map +1 -1
  110. package/dist/windfoil/shapes.js +1 -1
  111. package/dist/windfoil/skirt.d.ts +22 -0
  112. package/dist/windfoil/skirt.js +20 -0
  113. package/dist/windfoil/skirt.js.map +1 -0
  114. package/dist/windfoil/storage.d.ts +2 -2
  115. package/dist/windfoil/storage.js +1 -22
  116. package/dist/windfoil/storage.js.map +1 -1
  117. package/dist/windfoil/trace/contours.d.ts +0 -5
  118. package/dist/windfoil/trace/contours.js +81 -114
  119. package/dist/windfoil/trace/contours.js.map +1 -1
  120. package/dist/windfoil/trace/fit.d.ts +0 -6
  121. package/dist/windfoil/trace/fit.js +304 -308
  122. package/dist/windfoil/trace/fit.js.map +1 -1
  123. package/dist/windfoil/trace/outline.js +10 -10
  124. package/dist/windfoil/trace/outline.js.map +1 -1
  125. package/dist/windfoil/trace/types.d.ts +5 -3
  126. package/dist/windfoil/tracedOutlines.d.ts +37 -1
  127. package/dist/windfoil/tracedOutlines.js +172 -33
  128. package/dist/windfoil/tracedOutlines.js.map +1 -1
  129. package/package.json +57 -8
  130. package/skills/ultra-text/SKILL.md +114 -0
  131. package/skills/ultra-text/references/frameworks.md +43 -0
  132. package/skills/ultra-text/references/three-tsl.md +78 -0
  133. package/skills/ultra-text/references/vanilla-webgpu.md +95 -0
  134. package/dist/assets/cpuSdf.worker-Du9o8q4p.js.map +0 -1
@@ -1,15 +1,11 @@
1
1
  import { isEmojiCandidate, isEmojiGrapheme } from "../dom/clusters.js";
2
+ import { createCanvas, isColorCandidate, setFontContext, waitForFonts } from "../dom/fontCanvas.js";
2
3
  // src/atlas/rasterize.ts
3
4
  /**
4
5
  * @internal The cursors of the rasters built with `appendable`, keyed by their glyph map, which
5
6
  * every `SdfAtlas` built from the raster shares. A few numbers each: no canvas is kept.
6
7
  */
7
8
  var appendCursors = /* @__PURE__ */ new WeakMap();
8
- /** @internal Shared atlas compatibility and raster candidacy rule. */
9
- function isColorCandidate(request, mode = "emoji") {
10
- if (request.shape) return request.shape.bitmap === true;
11
- return mode === "all" || mode === "emoji" && isEmojiCandidate(request.character);
12
- }
13
9
  function throwIfAborted(signal) {
14
10
  if (signal?.aborted) throw signal.reason ?? new DOMException("The atlas build was aborted", "AbortError");
15
11
  }
@@ -19,40 +15,6 @@ function nextPowerOfTwo(value) {
19
15
  function align4(value) {
20
16
  return Math.max(4, Math.ceil(value / 4) * 4);
21
17
  }
22
- var CANVAS_FONT_STRETCHES = [
23
- ["ultra-condensed", 50],
24
- ["extra-condensed", 62.5],
25
- ["condensed", 75],
26
- ["semi-condensed", 87.5],
27
- ["normal", 100],
28
- ["semi-expanded", 112.5],
29
- ["expanded", 125],
30
- ["extra-expanded", 150],
31
- ["ultra-expanded", 200]
32
- ];
33
- function canvasFontStretch(value) {
34
- if (value === "100%" || value === "normal") return "normal";
35
- const percentage = Number.parseFloat(value);
36
- if (!Number.isFinite(percentage)) return CANVAS_FONT_STRETCHES.find(([name]) => name === value)?.[0] ?? "normal";
37
- return CANVAS_FONT_STRETCHES.reduce((a, b) => Math.abs(b[1] - percentage) < Math.abs(a[1] - percentage) ? b : a)[0];
38
- }
39
- /** @internal The bake canvas's font state for a request, shared with the outline tracer. */
40
- function setFontContext(context, request, shaping, lastFont) {
41
- const { font } = request;
42
- if (lastFont !== font) {
43
- const extended = context;
44
- context.font = font.canvasFont;
45
- if (!lastFont) {
46
- context.textAlign = "left";
47
- context.textBaseline = "alphabetic";
48
- }
49
- if ("fontKerning" in extended) extended.fontKerning = font.kerning;
50
- if ("fontStretch" in extended) extended.fontStretch = canvasFontStretch(font.stretch);
51
- if ("fontVariantCaps" in extended) extended.fontVariantCaps = /\b(?:(?:all-)?(?:small|petite)-caps|unicase|titling-caps)\b/.exec(font.variant)?.[0] ?? "normal";
52
- }
53
- shaping?.(context, request);
54
- return font;
55
- }
56
18
  /** @internal Measures one text glyph's slot; `appendAtlas.ts` shares it with the cold build. */
57
19
  function measureGlyph(context, request, padding, shaping, candidate = false, lastFont = null) {
58
20
  const nextFont = setFontContext(context, request, shaping, lastFont);
@@ -366,53 +328,6 @@ function isBetterPacking(candidate, current) {
366
328
  return (candidate.width * candidate.height - current.width * current.height || Math.max(candidate.width, candidate.height) - Math.max(current.width, current.height) || candidate.width - current.width) < 0;
367
329
  }
368
330
  /**
369
- * The bake canvas. Font smoothing follows the canvas element's computed style, and only while
370
- * the element is in a document: there it is turned off, in every engine, so a mask is the
371
- * outline itself. Everything else a page would hand down (spacing, font features and
372
- * variations, direction, language) is cut off, so the mask stays what a detached canvas draws.
373
- * The caller takes it out of the document again.
374
- * @internal Shared with the atlas append path and the outline tracer.
375
- */
376
- function createCanvas(document) {
377
- const canvas = document.createElement("canvas");
378
- canvas.width = 1;
379
- canvas.height = 1;
380
- for (const [property, value] of [
381
- ["all", "initial"],
382
- ["display", "none"],
383
- ["direction", "ltr"],
384
- ["-webkit-font-smoothing", "antialiased"],
385
- ["-moz-osx-font-smoothing", "grayscale"]
386
- ]) canvas.style.setProperty(property, value, "important");
387
- canvas.dir = "ltr";
388
- canvas.lang = "";
389
- document.documentElement.append(canvas);
390
- return canvas;
391
- }
392
- /** @internal Loads every face the text requests draw with; shared with the outline tracer. */
393
- async function waitForFonts(document, requests, signal) {
394
- const fonts = document.fonts;
395
- if (!fonts) return;
396
- const byFont = /* @__PURE__ */ new Map();
397
- for (const request of requests) {
398
- if (request.shape) continue;
399
- const current = byFont.get(request.font.key);
400
- if (current) current.text += request.character;
401
- else byFont.set(request.font.key, {
402
- font: request.font.canvasFont,
403
- text: request.character
404
- });
405
- }
406
- const ok = fonts.status === "loaded" && !("mock" in fonts.load);
407
- await Promise.all(Array.from(byFont.values(), (i) => {
408
- try {
409
- if (ok && fonts.check(i.font, i.text)) return;
410
- } catch {}
411
- return fonts.load(i.font, i.text);
412
- }));
413
- throwIfAborted(signal);
414
- }
415
- /**
416
331
  * Rasterizes every required font-face/character or emoji-sequence pair into one tightly packed
417
332
  * alpha atlas. The output is a transient mask; the retained texture is a
418
333
  * single-channel distance field produced by the CPU or WebGPU compute backend.
@@ -570,7 +485,7 @@ async function rasterizeGlyphAtlas(document, requests, options = {}) {
570
485
  canvas.width = best.width;
571
486
  canvas.height = best.height;
572
487
  painter.reset();
573
- context.clearRect(0, 0, canvas.width, canvas.height);
488
+ if (scratch) context.clearRect(0, 0, canvas.width, canvas.height);
574
489
  const bandTop = band.length ? topOf(band) : 0;
575
490
  const bandHeight = canvas.height - bandTop;
576
491
  let black;
@@ -1 +1 @@
1
- {"version":3,"file":"rasterize.js","names":[],"sources":["../../src/atlas/rasterize.ts"],"sourcesContent":["import type {\n ColorGlyphMode,\n GlyphRequest,\n GlyphSlot,\n RasterAtlas,\n RasterColorBand,\n} from '../types.js'\nimport { isEmojiCandidate, isEmojiGrapheme } from '../dom/clusters.js'\nimport type { setShapingContext } from '../dom/browserShaping.js'\n\ntype ShapingContext = typeof setShapingContext\n\n/** @internal Shared measured slot used by the lazy shape rasterizer. */\nexport interface MeasuredGlyph {\n readonly request: GlyphRequest\n readonly width: number\n readonly height: number\n readonly planeX0: number\n readonly planeY0: number\n readonly planeX1: number\n readonly planeY1: number\n readonly descent: number\n readonly advance: number\n readonly drawOffsetX: number\n /**\n * The ink box of a text glyph in plane units (x0, y0, x1, y1, y up from the baseline), from\n * the canvas's own metrics; absent where the slot is drawn whole.\n */\n readonly ink?: readonly [number, number, number, number]\n x: number\n y: number\n}\n\n/**\n * @internal The first atlas row of the monochrome shapes, when the raster holds any. They are\n * packed below the text so that a material can tell them from text by their place in the atlas.\n */\nexport interface ShapeRows {\n readonly shapeTop?: number\n}\n\n/**\n * @internal Where later text glyphs fit in an atlas without moving any slot: a shelf cursor\n * over its text rows, which end at `bottom`, the first row of its shapes or colour band (or its\n * height). Every slot that reaches row `y` or below ends left of `x`; below `y + rowHeight`\n * the text rows are free.\n */\nexport interface AppendCursor {\n readonly width: number\n readonly height: number\n readonly bakeSize: number\n readonly pxRange: number\n readonly colorGlyphs: ColorGlyphMode\n readonly bottom: number\n readonly x: number\n readonly y: number\n readonly rowHeight: number\n}\n\n/**\n * @internal The cursors of the rasters built with `appendable`, keyed by their glyph map, which\n * every `SdfAtlas` built from the raster shares. A few numbers each: no canvas is kept.\n */\nexport const appendCursors = new WeakMap<ReadonlyMap<string, GlyphSlot>, AppendCursor>()\n\ninterface PackedGlyphs {\n width: number\n height: number\n}\n\ninterface CanvasFontContext extends CanvasRenderingContext2D {\n fontKerning: CanvasFontKerning\n fontStretch: CanvasFontStretch\n fontVariantCaps: CanvasFontVariantCaps\n letterSpacing: string\n wordSpacing: string\n}\n\nexport interface RasterizeOptions {\n /** Colour-glyph detection; defaults to 'emoji'. */\n colorGlyphs?: ColorGlyphMode\n /** Canvas font raster size in pixels; must be at least `16`. Defaults to `96`. */\n bakeSize?: number\n /**\n * Retry overflowing atlases at a smaller bake size, down to 16px.\n * Defaults to `false`; fitting atlases keep their requested resolution.\n */\n adaptiveBakeSize?: boolean\n /**\n * Glyph slot padding in texels; must be at least `2`. Defaults to `12`. The\n * padding doubles as the SDF pixel range (`RasterAtlas.pxRange`).\n */\n padding?: number\n /**\n * Maximum atlas dimension in texels; must be an integer of at least `64`.\n * Defaults to `2048`. Glyphs that cannot pack reject instead of dropping. Text, monochrome\n * shapes and colour glyphs take rows of their own, one kind below the other.\n */\n maxAtlasSize?: number\n /** Aborts the rasterization between font waits and glyph draws. */\n signal?: AbortSignal\n /**\n * An atlas built earlier for the same fonts, with this `bakeSize` and `padding`\n * (`pxRange`): a colour candidate whose slot there already carries `GlyphSlot.color` keeps\n * that classification, instead of being drawn twice on a scratch canvas and read back.\n * Bitmap SVG shapes and glyphs it lacks are classified as usual, and every glyph is still\n * measured, packed and drawn: only the classification is reused. Omit it after a webfont\n * swap. `DomSdf` passes its retained atlas when a capture's new glyphs rebuild it in full.\n */\n previousAtlas?: Pick<RasterAtlas, 'glyphs' | 'bakeSize' | 'pxRange'> | undefined\n /**\n * @internal Set by `DomSdf` for its own SDF atlases. The raster then records its\n * `AppendCursor` in `appendCursors`, so that `appendAtlas.ts` can draw later text glyphs\n * into the live texture. `'headroom'` also leaves free text rows for them, within\n * `maxAtlasSize`: a tallest text slot, or a quarter of the text rows when more, between\n * the text and the shapes and colour band, which therefore keep their rows across appends,\n * in an atlas at least two of its widest text glyphs wide. DomSdf asks for it once an\n * instance has gained glyphs; a capture that never gains any stays tight.\n */\n appendable?: boolean | 'headroom' | undefined\n /**\n * @internal Set by `DomSdf` when only a WebGPU atlas uploads the raster. Without colour\n * candidates, which are read back, the bake canvas is then GPU-backed (no\n * `willReadFrequently`): its first draw on a page skips the software canvas's set-up, 7 to\n * 12 ms on an M3 Max, and the atlas copies it on the GPU. Reading such a canvas back takes\n * hundreds of milliseconds, which only the CPU fallback of a failed GPU build pays.\n */\n gpuUpload?: boolean | undefined\n}\n\n/** @internal Shared atlas compatibility and raster candidacy rule. */\nexport function isColorCandidate(request: GlyphRequest, mode: ColorGlyphMode = 'emoji'): boolean {\n if (request.shape) return request.shape.bitmap === true\n return mode === 'all' || (mode === 'emoji' && isEmojiCandidate(request.character))\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) {\n throw signal.reason ?? new DOMException('The atlas build was aborted', 'AbortError')\n }\n}\n\nfunction nextPowerOfTwo(value: number): number {\n return 2 ** Math.ceil(Math.log2(Math.max(1, value)))\n}\n\nfunction align4(value: number): number {\n return Math.max(4, Math.ceil(value / 4) * 4)\n}\n\nconst CANVAS_FONT_STRETCHES = [\n ['ultra-condensed', 50],\n ['extra-condensed', 62.5],\n ['condensed', 75],\n ['semi-condensed', 87.5],\n ['normal', 100],\n ['semi-expanded', 112.5],\n ['expanded', 125],\n ['extra-expanded', 150],\n ['ultra-expanded', 200],\n] as const satisfies readonly (readonly [CanvasFontStretch, number])[]\n\nfunction canvasFontStretch(value: string): CanvasFontStretch {\n if (value === '100%' || value === 'normal') return 'normal'\n const percentage = Number.parseFloat(value)\n if (!Number.isFinite(percentage)) {\n return CANVAS_FONT_STRETCHES.find(([name]) => name === value)?.[0] ?? 'normal'\n }\n return CANVAS_FONT_STRETCHES.reduce((a, b) =>\n Math.abs(b[1] - percentage) < Math.abs(a[1] - percentage) ? b : a,\n )[0]\n}\n\n/** @internal The bake canvas's font state for a request, shared with the outline tracer. */\nexport function setFontContext(\n context: CanvasRenderingContext2D,\n request: GlyphRequest,\n shaping: ShapingContext | undefined,\n lastFont: GlyphRequest['font'] | null,\n): GlyphRequest['font'] {\n const { font } = request\n if (lastFont !== font) {\n const extended: CanvasFontContext = context\n context.font = font.canvasFont\n if (!lastFont) {\n context.textAlign = 'left'\n context.textBaseline = 'alphabetic'\n }\n if ('fontKerning' in extended) extended.fontKerning = font.kerning as CanvasFontKerning\n if ('fontStretch' in extended) extended.fontStretch = canvasFontStretch(font.stretch)\n if ('fontVariantCaps' in extended)\n extended.fontVariantCaps =\n (/\\b(?:(?:all-)?(?:small|petite)-caps|unicase|titling-caps)\\b/.exec(font.variant)?.[0] ??\n 'normal') as CanvasFontVariantCaps\n }\n shaping?.(context, request)\n return font\n}\n\n/** @internal Measures one text glyph's slot; `appendAtlas.ts` shares it with the cold build. */\nexport function measureGlyph(\n context: CanvasRenderingContext2D,\n request: GlyphRequest,\n padding: number,\n shaping: ShapingContext | undefined,\n candidate = false,\n lastFont: GlyphRequest['font'] | null = null,\n): [MeasuredGlyph, GlyphRequest['font']] {\n const nextFont = setFontContext(context, request, shaping, lastFont)\n const metrics = context.measureText(request.character)\n const slice = request.shaping?.slice\n const from = slice?.[0] ?? 0\n const to = slice?.[1] ?? 1\n const advance = metrics.width * (to - from)\n const left = from === 0 ? Math.max(0, metrics.actualBoundingBoxLeft) : 0\n const right = slice\n ? advance + (to === 1 ? Math.max(0, metrics.actualBoundingBoxRight - metrics.width) : 0)\n : Math.max(metrics.width, metrics.actualBoundingBoxRight)\n const ascent = Math.max(1, metrics.fontBoundingBoxAscent || metrics.actualBoundingBoxAscent)\n const descent = Math.max(1, metrics.fontBoundingBoxDescent || metrics.actualBoundingBoxDescent)\n // A canvas draws text on a whole pixel row and, across, on a quarter pixel at best, whatever\n // origin it is given. The slot's origin is therefore a whole pixel: ink left of the origin\n // or taller than the font box was otherwise baked up to half a texel off, and the tiles of\n // a sliced run a quarter texel off each other.\n const drawOffsetX = metrics.width * from\n const planeX0 = -Math.ceil(left + padding - drawOffsetX) - drawOffsetX\n const planeX1 = right + padding\n const inkBounds =\n request.shaping !== undefined || candidate || isEmojiCandidate(request.character)\n const planeY0 = -Math.max(descent, inkBounds ? metrics.actualBoundingBoxDescent : 0) - padding\n const planeY1 = Math.ceil(\n Math.max(ascent, inkBounds ? metrics.actualBoundingBoxAscent : 0) + padding,\n )\n // Only whole, plain text glyphs trim their quads: a tile of a shaped line is clipped to its\n // slice, and colour candidates are bitmaps whose ink the metrics need not bound.\n const ink: MeasuredGlyph['ink'] =\n inkBounds || slice\n ? undefined\n : [\n -metrics.actualBoundingBoxLeft,\n -metrics.actualBoundingBoxDescent,\n metrics.actualBoundingBoxRight,\n metrics.actualBoundingBoxAscent,\n ]\n\n return [\n {\n request,\n width: Math.max(2, Math.ceil(planeX1 - planeX0) + 2),\n height: Math.max(2, Math.ceil(planeY1 - planeY0) + 2),\n planeX0,\n planeY0,\n planeX1,\n planeY1,\n descent,\n advance,\n drawOffsetX,\n ...(ink?.every(Number.isFinite) ? { ink } : {}),\n x: 0,\n y: 0,\n },\n nextFont,\n ]\n}\n\n/**\n * @internal The slot of a glyph drawn at (glyph.x, glyph.y) of a `width`×`height` atlas. The\n * full build and an append patch both take their slots from here, so they cannot drift apart.\n * A `banded` glyph is a colour candidate in the band; an `uncoloured` one a candidate that\n * classified as text.\n */\nexport function slotOf(\n glyph: MeasuredGlyph,\n padding: number,\n bakeSize: number,\n width: number,\n height: number,\n banded: boolean,\n uncoloured: boolean,\n): GlyphSlot {\n // The sampled window must follow the drawn plane box, not the shelf slot:\n // the slot is `ceil(extent) + 2` texels wide and the glyph origin above is\n // offset by one, so the plane spans texels 1 .. 1 + extent. Both bounds move\n // inward by half a texel so bilinear filtering cannot reach a neighbour.\n const slice = glyph.request.shaping?.slice\n const planeX0 = glyph.planeX0 + (slice && slice[0] > 0 ? -glyph.planeX0 : 0.5)\n const planeY0 = glyph.planeY0 + 0.5\n const planeX1 = glyph.planeX1 - (slice && slice[1] < 1 ? glyph.planeX1 - glyph.advance : 0.5)\n const planeY1 = glyph.planeY1 - 0.5\n const uv = (x0: number, y0: number, x1: number, y1: number) => ({\n u0: (glyph.x + 1 + x0 - glyph.planeX0) / width,\n v0: (glyph.y + 1 + glyph.planeY1 - y1) / height,\n u1: (glyph.x + 1 + x1 - glyph.planeX0) / width,\n v1: (glyph.y + 1 + glyph.planeY1 - y0) / height,\n })\n const ink = banded ? undefined : glyph.ink\n const reach = padding / 2 + 2 + 0.006 * bakeSize\n const sx0 = ink ? Math.max(planeX0, Math.floor(ink[0] - reach)) : 0\n const sy0 = ink ? Math.max(planeY0, Math.floor(ink[1] - reach)) : 0\n const sx1 = ink ? Math.min(planeX1, Math.ceil(ink[2] + reach)) : 0\n const sy1 = ink ? Math.min(planeY1, Math.ceil(ink[3] + reach)) : 0\n return {\n ...(uncoloured ? { color: false } : {}),\n key: glyph.request.key,\n character: glyph.request.character,\n fontKey: glyph.request.font.key,\n ...uv(planeX0, planeY0, planeX1, planeY1),\n planeX0,\n planeY0,\n planeX1,\n planeY1,\n descent: glyph.descent,\n advance: glyph.advance,\n ...(ink && sx1 > sx0 && sy1 > sy0 ? { support: uv(sx0, sy0, sx1, sy1) } : {}),\n }\n}\n\n/**\n * @internal Draws glyphs into their slots of one canvas, by the rules of the full build and of\n * an append patch alike. `reset()` forgets the context state cached here: call it whenever\n * the canvas is resized, which resets that state.\n */\nexport function glyphPainter(\n context: CanvasRenderingContext2D,\n shaping: ShapingContext | undefined,\n signal: AbortSignal | undefined,\n drawShape?: (glyph: MeasuredGlyph) => void,\n): { draw(glyph: MeasuredGlyph, text: boolean, fill?: string): void; reset(): void } {\n // A text mask must be the outline itself on every platform. The bake canvas has font\n // smoothing off; where the engine has the property, text also asks for exact geometry,\n // and it takes a mid grey fill, the neutral middle of a rasterizer's contrast table.\n // Colour glyphs keep the default rendering and the fills their classification compares;\n // shapes are paths, which none of this affects.\n const exactText = 'textRendering' in context\n let lastFont: GlyphRequest['font'] | null = null\n let lastFill = ''\n let lastTextRendering = ''\n return {\n reset() {\n lastFont = null\n lastFill = ''\n lastTextRendering = ''\n },\n draw(glyph, text, fill = '#fff') {\n throwIfAborted(signal)\n const targetFill = text ? '#606060' : fill\n if (lastFill !== targetFill) {\n context.fillStyle = targetFill\n lastFill = targetFill\n }\n if (glyph.request.shape) {\n drawShape!(glyph)\n lastFill = ''\n return\n }\n lastFont = setFontContext(context, glyph.request, shaping, lastFont)\n if (exactText) {\n const targetRendering = text ? 'geometricPrecision' : 'auto'\n if (lastTextRendering !== targetRendering) {\n context.textRendering = targetRendering\n lastTextRendering = targetRendering\n }\n }\n const originX = glyph.x - glyph.planeX0 + 1\n const baselineY = glyph.y + glyph.planeY1 + 1\n if (glyph.request.shaping?.slice) {\n context.save()\n context.beginPath()\n context.rect(\n glyph.x + 1,\n glyph.y + 1,\n glyph.planeX1 - glyph.planeX0,\n glyph.planeY1 - glyph.planeY0,\n )\n context.clip()\n context.fillText(glyph.request.character, originX - glyph.drawOffsetX, baselineY)\n context.restore()\n } else context.fillText(glyph.request.character, originX, baselineY)\n },\n }\n}\n\n/** The first row of a non-empty run of packed glyphs. */\nfunction topOf(rows: readonly MeasuredGlyph[]): number {\n return rows.reduce((top, glyph) => (glyph.y < top ? glyph.y : top), rows[0]!.y)\n}\n\nlet lastOverflowWidth = Infinity\n\n/** @internal Row-major shelf packing; also lays out the colour candidates of an append. */\nexport function packShelves(\n glyphs: MeasuredGlyph[],\n width: number,\n maxSize: number,\n): { width: number; height: number } | null {\n let x = 0\n let y = 0\n let rowHeight = 0\n let usedWidth = 0\n\n for (const glyph of glyphs) {\n const gw = glyph.width\n const gh = glyph.height\n if (gw > width) {\n if (gw < lastOverflowWidth) lastOverflowWidth = gw\n return null\n }\n if (gh > maxSize) return null\n if (x + gw > width) {\n if (x + gw < lastOverflowWidth) lastOverflowWidth = x + gw\n x = 0\n y += rowHeight\n rowHeight = 0\n }\n if (y + gh > maxSize) return null\n glyph.x = x\n glyph.y = y\n x += gw\n if (gh > rowHeight) rowHeight = gh\n if (x > usedWidth) usedWidth = x\n }\n\n return {\n width: align4(usedWidth),\n height: align4(y + rowHeight),\n }\n}\n\nlet skylineX = new Int32Array(256)\nlet skylineY = new Int32Array(256)\nlet skylineW = new Int32Array(256)\n\n/** Bottom-left skyline packing fills the vertical gaps that fixed-height shelves leave behind. */\nfunction packSkyline(\n glyphs: MeasuredGlyph[],\n width: number,\n maxSize: number,\n): { width: number; height: number } | null {\n const needed = glyphs.length + 2\n if (skylineX.length < needed) {\n skylineX = new Int32Array(needed)\n skylineY = new Int32Array(needed)\n skylineW = new Int32Array(needed)\n }\n const sx = skylineX\n const sy = skylineY\n const sw = skylineW\n sx[0] = 0\n sy[0] = 0\n sw[0] = width\n let skylineLen = 1\n let usedWidth = 0\n let usedHeight = 0\n const shift = (to: number, from: number): void => {\n sx.copyWithin(to, from, skylineLen)\n sy.copyWithin(to, from, skylineLen)\n sw.copyWithin(to, from, skylineLen)\n }\n\n const minH = glyphs[glyphs.length - 1]!.height\n let wasteBudget = width * maxSize\n const over = (): null => (\n (lastOverflowWidth = Math.min(lastOverflowWidth, width + Math.ceil(-wasteBudget / maxSize))),\n null\n )\n for (const g of glyphs) wasteBudget -= g.width * g.height\n if (wasteBudget < 0) return over()\n\n for (const glyph of glyphs) {\n const gw = glyph.width\n const gh = glyph.height\n if (gh > maxSize) return null\n let bestIndex = -1\n let bestBottom = Infinity\n let bestWaste = Infinity\n const tail = skylineLen - 1\n let maxAllowedY = sw[tail]! >= gw && sy[tail]! < maxSize - gh ? sy[tail]! : maxSize - gh\n\n for (let index = 0; index < skylineLen; index++) {\n const firstY = sy[index]!\n if (firstY > maxAllowedY) continue\n const x = sx[index]!\n if (x + gw > width) {\n if (x + gw < lastOverflowWidth) lastOverflowWidth = x + gw\n break\n }\n\n let remaining = gw - sw[index]!\n let y = firstY\n let waste = 0\n if (remaining > 0) {\n let coveredArea = sw[index]! * firstY\n for (let cursor = index + 1; ; cursor++) {\n const nodeY = sy[cursor]!\n if (nodeY > maxAllowedY) {\n index = cursor\n remaining = 1\n break\n }\n if (nodeY > y) y = nodeY\n const nodeW = sw[cursor]!\n coveredArea += (remaining < nodeW ? remaining : nodeW) * nodeY\n if ((remaining -= nodeW) <= 0) break\n }\n if (remaining > 0) continue\n waste = y * gw - coveredArea\n }\n const bottom = y + gh\n if (bottom < bestBottom || waste < bestWaste) {\n bestIndex = index\n bestBottom = bottom\n bestWaste = waste\n maxAllowedY = waste === 0 ? y - 1 : y\n if (maxAllowedY < 0) break\n }\n }\n if (maxAllowedY >= 0 && usedWidth + gw < lastOverflowWidth) lastOverflowWidth = usedWidth + gw\n\n if (\n bestIndex < 0 ||\n (wasteBudget -= bestWaste + (bestBottom > maxSize - minH ? gw * (maxSize - bestBottom) : 0)) <\n 0\n )\n return bestIndex < 0 ? null : over()\n const gx = sx[bestIndex]!\n const right = gx + gw\n glyph.x = gx\n glyph.y = bestBottom - gh\n let cursor = bestIndex\n while (cursor < skylineLen && sx[cursor]! + sw[cursor]! <= right) cursor++\n if (cursor < skylineLen && sx[cursor]! < right) {\n sw[cursor] = sx[cursor]! + sw[cursor]! - right\n sx[cursor] = right\n }\n let newCount = 1\n if (bestIndex > 0 && sy[bestIndex - 1] === bestBottom) {\n sw[bestIndex - 1] = sw[bestIndex - 1]! + gw\n newCount = 0\n if (cursor < skylineLen && sy[cursor] === bestBottom) {\n sw[bestIndex - 1] = sw[bestIndex - 1]! + sw[cursor]!\n cursor++\n }\n } else if (cursor < skylineLen && sy[cursor] === bestBottom) {\n sx[cursor] = gx\n sw[cursor] = sw[cursor]! + gw\n newCount = 0\n }\n const delta = newCount - (cursor - bestIndex)\n if (delta !== 0 && cursor < skylineLen) shift(cursor + delta, cursor)\n skylineLen += delta\n if (newCount) {\n sx[bestIndex] = gx\n sy[bestIndex] = bestBottom\n sw[bestIndex] = gw\n }\n\n if (right > usedWidth) usedWidth = right\n if (bestBottom > usedHeight) usedHeight = bestBottom\n }\n\n return { width: align4(usedWidth), height: align4(usedHeight) }\n}\n\n/** Packs each group into rows of its own, one group below the other. */\nfunction packStacked(\n groups: readonly MeasuredGlyph[][],\n width: number,\n limit: number,\n pack: typeof packShelves,\n): { width: number; height: number } | null {\n let packedWidth = 0\n let height = 0\n for (const group of groups) {\n const packed = pack(group, width, limit - height)\n if (!packed || height + packed.height > limit) return null\n for (const glyph of group) glyph.y += height\n packedWidth = Math.max(packedWidth, packed.width)\n height += packed.height\n }\n return { width: packedWidth, height }\n}\n\nfunction rememberPacking(\n glyphs: readonly MeasuredGlyph[],\n size: { width: number; height: number },\n positions: Int32Array,\n): PackedGlyphs {\n for (let index = 0; index < glyphs.length; index++) {\n const glyph = glyphs[index]!\n positions[index * 2] = glyph.x\n positions[index * 2 + 1] = glyph.y\n }\n return { width: size.width, height: size.height }\n}\n\nfunction isBetterPacking(\n candidate: Pick<PackedGlyphs, 'width' | 'height'>,\n current: PackedGlyphs,\n): boolean {\n return (\n (candidate.width * candidate.height - current.width * current.height ||\n Math.max(candidate.width, candidate.height) - Math.max(current.width, current.height) ||\n candidate.width - current.width) < 0\n )\n}\n\n/**\n * The bake canvas. Font smoothing follows the canvas element's computed style, and only while\n * the element is in a document: there it is turned off, in every engine, so a mask is the\n * outline itself. Everything else a page would hand down (spacing, font features and\n * variations, direction, language) is cut off, so the mask stays what a detached canvas draws.\n * The caller takes it out of the document again.\n * @internal Shared with the atlas append path and the outline tracer.\n */\nexport function createCanvas(document: Document): HTMLCanvasElement {\n const canvas = document.createElement('canvas')\n canvas.width = 1\n canvas.height = 1\n for (const [property, value] of [\n ['all', 'initial'],\n ['display', 'none'],\n ['direction', 'ltr'],\n ['-webkit-font-smoothing', 'antialiased'],\n ['-moz-osx-font-smoothing', 'grayscale'],\n ] as const)\n canvas.style.setProperty(property, value, 'important')\n canvas.dir = 'ltr'\n canvas.lang = ''\n document.documentElement.append(canvas)\n return canvas\n}\n\n/** @internal Loads every face the text requests draw with; shared with the outline tracer. */\nexport async function waitForFonts(\n document: Document,\n requests: readonly GlyphRequest[],\n signal?: AbortSignal,\n): Promise<void> {\n const fonts = document.fonts as FontFaceSet | undefined\n if (!fonts) return\n const byFont = new Map<string, { font: string; text: string }>()\n for (const request of requests) {\n if (request.shape) continue\n const current = byFont.get(request.font.key)\n if (current) current.text += request.character\n else byFont.set(request.font.key, { font: request.font.canvasFont, text: request.character })\n }\n const ok = fonts.status === 'loaded' && !('mock' in (fonts as { load: object }).load)\n await Promise.all(\n Array.from(byFont.values(), (i) => {\n try {\n if (ok && fonts.check(i.font, i.text)) return\n } catch {\n // Load below when check rejects an uncommon font shorthand.\n }\n return fonts.load(i.font, i.text)\n }) as Promise<unknown>[],\n )\n throwIfAborted(signal)\n}\n\n/**\n * Rasterizes every required font-face/character or emoji-sequence pair into one tightly packed\n * alpha atlas. The output is a transient mask; the retained texture is a\n * single-channel distance field produced by the CPU or WebGPU compute backend.\n */\nexport async function rasterizeGlyphAtlas(\n document: Document,\n requests: readonly GlyphRequest[],\n options: RasterizeOptions = {},\n): Promise<RasterAtlas> {\n const bakeSize = options.bakeSize ?? 96\n const padding = options.padding ?? 12\n const maxAtlasSize = options.maxAtlasSize ?? 2048\n if (!Number.isFinite(bakeSize) || bakeSize < 16) {\n throw new RangeError('rasterizeGlyphAtlas: bakeSize must be at least 16')\n }\n if (!Number.isFinite(padding) || padding < 2) {\n throw new RangeError('rasterizeGlyphAtlas: padding must be at least 2')\n }\n if (!Number.isInteger(maxAtlasSize) || maxAtlasSize < 64) {\n throw new RangeError('rasterizeGlyphAtlas: maxAtlasSize must be an integer of at least 64')\n }\n\n throwIfAborted(options.signal)\n const [, shapingModule, shapes] = await Promise.all([\n waitForFonts(document, requests, options.signal),\n requests.some((request) => request.shaping) ? import('../dom/browserShaping.js') : undefined,\n requests.some((request) => request.shape) ? import('./shapeRaster.js') : undefined,\n ])\n const shaping = shapingModule?.setShapingContext\n throwIfAborted(options.signal)\n\n const canvas = createCanvas(document)\n try {\n // A glyph a matching previous atlas has classified keeps its classification. A bitmap\n // shape always keeps its place in the band, as on a cold build: never history-dependent.\n const previous =\n options.previousAtlas?.bakeSize === bakeSize && options.previousAtlas.pxRange === padding\n ? options.previousAtlas.glyphs\n : undefined\n const context = canvas.getContext('2d', {\n willReadFrequently:\n !options.gpuUpload ||\n requests.some(\n (request) =>\n isColorCandidate(request, options.colorGlyphs) &&\n (request.shape !== undefined ||\n ((options.colorGlyphs === 'all' || isEmojiGrapheme(request.character)) &&\n previous?.get(request.key)?.color !== false)),\n ),\n })\n if (!context) throw new Error('rasterizeGlyphAtlas: Canvas 2D is unavailable')\n\n const packingLimit = maxAtlasSize - (maxAtlasSize % 4)\n let lastFont: GlyphRequest['font'] | null = null\n const measured = requests.map((request) => {\n if (request.shape) return shapes!.measureShape(request, bakeSize, padding)\n const [glyph, nextFont] = measureGlyph(\n context,\n request,\n padding,\n shaping,\n isColorCandidate(request, options.colorGlyphs),\n lastFont,\n )\n lastFont = nextFont\n return glyph\n })\n measured.sort(\n (a, b) =>\n b.height - a.height ||\n b.width - a.width ||\n (a.request.key < b.request.key ? -1 : a.request.key > b.request.key ? 1 : 0),\n )\n\n const banded = new Set<MeasuredGlyph>()\n const uncoloured = new Set<MeasuredGlyph>()\n const tested: MeasuredGlyph[] = []\n for (const glyph of measured) {\n if (!isColorCandidate(glyph.request, options.colorGlyphs)) continue\n const known = glyph.request.shape ? undefined : previous?.get(glyph.request.key)?.color\n if (known === false) uncoloured.add(glyph)\n else {\n banded.add(glyph)\n if (!glyph.request.shape && known === undefined) tested.push(glyph)\n }\n }\n const painter = glyphPainter(context, shaping, options.signal, (glyph) => {\n shapes!.drawShapeSlot(context, glyph, bakeSize)\n })\n const drawGlyph = (glyph: MeasuredGlyph, fill?: string): void => {\n painter.draw(glyph, !glyph.request.shape && !banded.has(glyph), fill)\n }\n\n // A candidate the font draws in the fill colour alone is text, whatever Unicode lists it\n // as: a copyright sign, an arrow, the tiles of a shaped line beside the one that holds\n // its emoji. Each font candidate is drawn in black and in white on a pack of their own,\n // and only one with ink that ignores the fill keeps its place in the band; the others are\n // baked, packed and flagged with the text.\n const colorGlyphs = banded.size ? await import('./colorGlyphs.js') : undefined\n throwIfAborted(options.signal)\n const scratch = tested.length ? packShelves(tested, packingLimit, packingLimit) : null\n if (scratch) {\n canvas.width = scratch.width\n canvas.height = scratch.height\n painter.reset()\n const paint = (fill: string): Uint8ClampedArray => {\n context.clearRect(0, 0, canvas.width, canvas.height)\n for (const glyph of tested) drawGlyph(glyph, fill)\n return context.getImageData(0, 0, canvas.width, canvas.height).data\n }\n const dark = paint('#000')\n const { colored } = colorGlyphs!.encodeColorBand(\n paint('#fff'),\n dark,\n canvas.width,\n canvas.height,\n 0,\n tested,\n )\n tested.forEach((glyph, index) => {\n if (colored[index]) return\n banded.delete(glyph)\n uncoloured.add(glyph)\n })\n }\n\n // Three kinds of rows, top to bottom: text, monochrome shapes, colour.\n const textRows: MeasuredGlyph[] = []\n const shapeRows: MeasuredGlyph[] = []\n const band: MeasuredGlyph[] = []\n let totalArea = 0\n let widestGlyph = 4\n let exceedsLimit = false\n for (const glyph of measured) {\n totalArea += glyph.width * glyph.height\n if (glyph.width > widestGlyph) widestGlyph = glyph.width\n if (glyph.width > packingLimit || glyph.height > packingLimit) exceedsLimit = true\n if (banded.has(glyph)) band.push(glyph)\n else if (glyph.request.shape) shapeRows.push(glyph)\n else textRows.push(glyph)\n }\n const groups = [textRows, shapeRows, band].filter((group) => group.length)\n const packGlyphs = (pack: typeof packShelves, width: number, limit: number) =>\n groups.length > 1 ? packStacked(groups, width, limit, pack) : pack(measured, width, limit)\n const impossible = totalArea > packingLimit * packingLimit || exceedsLimit\n const bestPositions = new Int32Array(measured.length * 2)\n let shelfWidth = Math.min(packingLimit, Math.max(64, nextPowerOfTwo(Math.sqrt(totalArea))))\n let packed = impossible ? null : packGlyphs(packShelves, shelfWidth, packingLimit)\n while (!packed && shelfWidth < packingLimit) {\n shelfWidth = Math.min(packingLimit, shelfWidth * 2)\n packed = packGlyphs(packShelves, shelfWidth, packingLimit)\n }\n let best = packed && !impossible ? rememberPacking(measured, packed, bestPositions) : null\n\n if (!impossible && measured.length > 0) {\n const minRequiredLimit = groups.reduce((sum, g) => sum + align4(g[0]!.height), 0)\n const minimumWidth = Math.min(\n packingLimit,\n align4(Math.max(widestGlyph, Math.ceil(totalArea / packingLimit))),\n )\n // Search at most about 64 aligned widths. Trying both the shelf and skyline\n // heuristic keeps the old pack as a no-regression candidate while allowing\n // short glyphs to occupy holes below taller neighbours.\n const widthStep = align4(Math.max(4, Math.ceil((packingLimit - minimumWidth) / 64)))\n const maxHeightFor = (width: number): number =>\n best ? Math.min(packingLimit, Math.floor((best.width * best.height) / width)) : packingLimit\n const nextW = [minimumWidth, minimumWidth]\n for (let width = minimumWidth; ; width = Math.min(packingLimit, width + widthStep)) {\n throwIfAborted(options.signal)\n if (maxHeightFor(width) < minRequiredLimit) break\n const minH = align4(Math.max(minRequiredLimit, Math.ceil(totalArea / width)))\n for (let i = 0; i < 2; i++) {\n if (width < nextW[i]!) continue\n const maxCandidateHeight = maxHeightFor(width)\n if (minH > maxCandidateHeight) break\n lastOverflowWidth = Infinity\n const candidate = packGlyphs(i ? packSkyline : packShelves, width, maxCandidateHeight)\n nextW[i] = lastOverflowWidth\n if (candidate && (!best || isBetterPacking(candidate, best))) {\n best = rememberPacking(measured, candidate, bestPositions)\n }\n }\n if (width === packingLimit) break\n }\n }\n\n if (!best) {\n if (options.adaptiveBakeSize === true && bakeSize > 16) {\n const nextSize = Math.max(16, Math.floor(bakeSize * 0.8))\n const scaled = requests.map((request) => ({\n ...request,\n font: {\n ...request.font,\n canvasFont: request.font.canvasFont.replace(\n /[\\d.]+px/,\n (size) => `${(Number.parseFloat(size) * nextSize) / bakeSize}px`,\n ),\n },\n }))\n return await rasterizeGlyphAtlas(document, scaled, { ...options, bakeSize: nextSize })\n }\n throw new Error(\n `rasterizeGlyphAtlas: ${requests.length} glyphs exceed the ${maxAtlasSize}×${maxAtlasSize} atlas limit`,\n )\n }\n for (let index = 0; index < measured.length; index++) {\n measured[index]!.x = bestPositions[index * 2]!\n measured[index]!.y = bestPositions[index * 2 + 1]!\n }\n\n // The text rows, packed first, end where the shapes or else the colour band begin. Headroom\n // for later appends goes there, so the rows below move down once, now, never on an append.\n let textBottom = !textRows.length ? 0 : groups.length > 1 ? topOf(groups[1]!) : best.height\n if (options.appendable === 'headroom' && textRows.length) {\n // Rows of at least two of the widest text glyphs: a one-column atlas has no row that\n // takes a glyph wider than its own.\n let widestText = 0\n for (const glyph of textRows) if (glyph.width > widestText) widestText = glyph.width\n best.width = Math.min(packingLimit, Math.max(best.width, align4(2 * widestText)))\n const room = Math.min(\n packingLimit - best.height,\n align4(Math.max(textRows[0]!.height, textBottom / 4)),\n )\n if (room > 0) {\n for (const glyph of measured) if (glyph.y >= textBottom) glyph.y += room\n best.height += room\n textBottom += room\n }\n }\n\n canvas.width = best.width\n canvas.height = best.height\n painter.reset()\n context.clearRect(0, 0, canvas.width, canvas.height)\n const bandTop = band.length ? topOf(band) : 0\n const bandHeight = canvas.height - bandTop\n let black: Uint8ClampedArray | undefined\n if (band.length) {\n for (const glyph of band) drawGlyph(glyph, '#000')\n black = context.getImageData(0, bandTop, canvas.width, bandHeight).data\n context.clearRect(0, bandTop, canvas.width, bandHeight)\n }\n const glyphSlots = new Map<string, GlyphSlot>()\n for (const glyph of measured) {\n drawGlyph(glyph)\n glyphSlots.set(\n glyph.request.key,\n slotOf(\n glyph,\n padding,\n bakeSize,\n canvas.width,\n canvas.height,\n banded.has(glyph),\n uncoloured.has(glyph),\n ),\n )\n }\n\n let colorBand: RasterColorBand | undefined\n if (black) {\n const white = context.getImageData(0, bandTop, canvas.width, bandHeight).data\n const encoded = colorGlyphs!.encodeColorBand(\n white,\n black,\n canvas.width,\n bandHeight,\n padding,\n band.map((glyph) => ({ ...glyph, y: glyph.y - bandTop })),\n )\n for (const [index, glyph] of band.entries()) {\n const slot = glyphSlots.get(glyph.request.key)!\n glyphSlots.set(glyph.request.key, { ...slot, color: encoded.colored[index]! })\n }\n if (encoded.colored.some(Boolean))\n colorBand = { top: bandTop, height: bandHeight, data: encoded.data }\n }\n const shapeTop = shapeRows.length ? topOf(shapeRows) : undefined\n if (options.appendable) {\n // The last text row is the one the lowest-starting slot begins on; whatever reaches\n // that row or below bounds where the cursor starts and how far the row runs down.\n let x = 0\n let y = 0\n let rowHeight = 0\n for (const glyph of textRows)\n if (glyph.y > y && glyph.y + textRows[0]!.height <= textBottom) y = glyph.y\n for (const glyph of textRows) {\n const reach = glyph.y + glyph.height - y\n if (reach > 0) {\n if (glyph.x + glyph.width > x) x = glyph.x + glyph.width\n if (reach > rowHeight) rowHeight = reach\n }\n }\n appendCursors.set(glyphSlots, {\n width: canvas.width,\n height: canvas.height,\n bakeSize,\n pxRange: padding,\n colorGlyphs: options.colorGlyphs ?? 'emoji',\n bottom: textBottom,\n x,\n y,\n rowHeight,\n })\n }\n return {\n ...(colorBand ? { colorBand } : {}),\n ...(shapeTop !== undefined ? { shapeTop } : {}),\n canvas,\n width: canvas.width,\n height: canvas.height,\n bakeSize,\n pxRange: padding,\n glyphs: glyphSlots,\n }\n } finally {\n canvas.remove()\n }\n}\n"],"mappings":";;;;;;AA+DA,IAAa,gCAAgB,IAAI,QAAsD;;AAoEvF,SAAgB,iBAAiB,SAAuB,OAAuB,SAAkB;CAC/F,IAAI,QAAQ,OAAO,OAAO,QAAQ,MAAM,WAAW;CACnD,OAAO,SAAS,SAAU,SAAS,WAAW,iBAAiB,QAAQ,SAAS;AAClF;AAEA,SAAS,eAAe,QAA4B;CAClD,IAAI,QAAQ,SACV,MAAM,OAAO,UAAU,IAAI,aAAa,+BAA+B,YAAY;AAEvF;AAEA,SAAS,eAAe,OAAuB;CAC7C,OAAO,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,IAAI,GAAG,KAAK,CAAC,CAAC;AACrD;AAEA,SAAS,OAAO,OAAuB;CACrC,OAAO,KAAK,IAAI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OAAO;IACf;IACA,SAAS;IACT,aAAa,QAAQ,eAAe;IACpC,QAAQ;IACR;IACA;IACA;GACF,CAAC;EACH;EACA,OAAO;GACL,GAAI,YAAY,EAAE,UAAU,IAAI,CAAC;GACjC,GAAI,aAAa,KAAA,IAAY,EAAE,SAAS,IAAI,CAAC;GAC7C;GACA,OAAO,OAAO;GACd,QAAQ,OAAO;GACf;GACA,SAAS;GACT,QAAQ;EACV;CACF,UAAU;EACR,OAAO,OAAO;CAChB;AACF"}
1
+ {"version":3,"file":"rasterize.js","names":[],"sources":["../../src/atlas/rasterize.ts"],"sourcesContent":["import type {\n ColorGlyphMode,\n GlyphRequest,\n GlyphSlot,\n RasterAtlas,\n RasterColorBand,\n} from '../types.js'\nimport { isEmojiCandidate, isEmojiGrapheme } from '../dom/clusters.js'\nimport {\n createCanvas,\n isColorCandidate,\n setFontContext,\n waitForFonts,\n type ShapingContext,\n} from '../dom/fontCanvas.js'\n\nexport { createCanvas, isColorCandidate, setFontContext, waitForFonts }\n\n/** @internal Shared measured slot used by the lazy shape rasterizer. */\nexport interface MeasuredGlyph {\n readonly request: GlyphRequest\n readonly width: number\n readonly height: number\n readonly planeX0: number\n readonly planeY0: number\n readonly planeX1: number\n readonly planeY1: number\n readonly descent: number\n readonly advance: number\n readonly drawOffsetX: number\n /**\n * The ink box of a text glyph in plane units (x0, y0, x1, y1, y up from the baseline), from\n * the canvas's own metrics; absent where the slot is drawn whole.\n */\n readonly ink?: readonly [number, number, number, number]\n x: number\n y: number\n}\n\n/**\n * @internal The first atlas row of the monochrome shapes, when the raster holds any. They are\n * packed below the text so that a material can tell them from text by their place in the atlas.\n */\nexport interface ShapeRows {\n readonly shapeTop?: number\n}\n\n/**\n * @internal Where later text glyphs fit in an atlas without moving any slot: a shelf cursor\n * over its text rows, which end at `bottom`, the first row of its shapes or colour band (or its\n * height). Every slot that reaches row `y` or below ends left of `x`; below `y + rowHeight`\n * the text rows are free.\n */\nexport interface AppendCursor {\n readonly width: number\n readonly height: number\n readonly bakeSize: number\n readonly pxRange: number\n readonly colorGlyphs: ColorGlyphMode\n readonly bottom: number\n readonly x: number\n readonly y: number\n readonly rowHeight: number\n}\n\n/**\n * @internal The cursors of the rasters built with `appendable`, keyed by their glyph map, which\n * every `SdfAtlas` built from the raster shares. A few numbers each: no canvas is kept.\n */\nexport const appendCursors = new WeakMap<ReadonlyMap<string, GlyphSlot>, AppendCursor>()\n\ninterface PackedGlyphs {\n width: number\n height: number\n}\n\nexport interface RasterizeOptions {\n /** Colour-glyph detection; defaults to 'emoji'. */\n colorGlyphs?: ColorGlyphMode\n /** Canvas font raster size in pixels; must be at least `16`. Defaults to `96`. */\n bakeSize?: number\n /**\n * Retry overflowing atlases at a smaller bake size, down to 16px.\n * Defaults to `false`; fitting atlases keep their requested resolution.\n */\n adaptiveBakeSize?: boolean\n /**\n * Glyph slot padding in texels; must be at least `2`. Defaults to `12`. The\n * padding doubles as the SDF pixel range (`RasterAtlas.pxRange`).\n */\n padding?: number\n /**\n * Maximum atlas dimension in texels; must be an integer of at least `64`.\n * Defaults to `2048`. Glyphs that cannot pack reject instead of dropping. Text, monochrome\n * shapes and colour glyphs take rows of their own, one kind below the other.\n */\n maxAtlasSize?: number\n /** Aborts the rasterization between font waits and glyph draws. */\n signal?: AbortSignal\n /**\n * An atlas built earlier for the same fonts, with this `bakeSize` and `padding`\n * (`pxRange`): a colour candidate whose slot there already carries `GlyphSlot.color` keeps\n * that classification, instead of being drawn twice on a scratch canvas and read back.\n * Bitmap SVG shapes and glyphs it lacks are classified as usual, and every glyph is still\n * measured, packed and drawn: only the classification is reused. Omit it after a webfont\n * swap. `DomSdf` passes its retained atlas when a capture's new glyphs rebuild it in full.\n */\n previousAtlas?: Pick<RasterAtlas, 'glyphs' | 'bakeSize' | 'pxRange'> | undefined\n /**\n * @internal Set by `DomSdf` for its own SDF atlases. The raster then records its\n * `AppendCursor` in `appendCursors`, so that `appendAtlas.ts` can draw later text glyphs\n * into the live texture. `'headroom'` also leaves free text rows for them, within\n * `maxAtlasSize`: a tallest text slot, or a quarter of the text rows when more, between\n * the text and the shapes and colour band, which therefore keep their rows across appends,\n * in an atlas at least two of its widest text glyphs wide. DomSdf asks for it once an\n * instance has gained glyphs; a capture that never gains any stays tight.\n */\n appendable?: boolean | 'headroom' | undefined\n /**\n * @internal Set by `DomSdf` when only a WebGPU atlas uploads the raster. Without colour\n * candidates, which are read back, the bake canvas is then GPU-backed (no\n * `willReadFrequently`): its first draw on a page skips the software canvas's set-up, 7 to\n * 12 ms on an M3 Max, and the atlas copies it on the GPU. Reading such a canvas back takes\n * hundreds of milliseconds, which only the CPU fallback of a failed GPU build pays.\n */\n gpuUpload?: boolean | undefined\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) {\n throw signal.reason ?? new DOMException('The atlas build was aborted', 'AbortError')\n }\n}\n\nfunction nextPowerOfTwo(value: number): number {\n return 2 ** Math.ceil(Math.log2(Math.max(1, value)))\n}\n\nfunction align4(value: number): number {\n return Math.max(4, Math.ceil(value / 4) * 4)\n}\n\n/** @internal Measures one text glyph's slot; `appendAtlas.ts` shares it with the cold build. */\nexport function measureGlyph(\n context: CanvasRenderingContext2D,\n request: GlyphRequest,\n padding: number,\n shaping: ShapingContext | undefined,\n candidate = false,\n lastFont: GlyphRequest['font'] | null = null,\n): [MeasuredGlyph, GlyphRequest['font']] {\n const nextFont = setFontContext(context, request, shaping, lastFont)\n const metrics = context.measureText(request.character)\n const slice = request.shaping?.slice\n const from = slice?.[0] ?? 0\n const to = slice?.[1] ?? 1\n const advance = metrics.width * (to - from)\n const left = from === 0 ? Math.max(0, metrics.actualBoundingBoxLeft) : 0\n const right = slice\n ? advance + (to === 1 ? Math.max(0, metrics.actualBoundingBoxRight - metrics.width) : 0)\n : Math.max(metrics.width, metrics.actualBoundingBoxRight)\n const ascent = Math.max(1, metrics.fontBoundingBoxAscent || metrics.actualBoundingBoxAscent)\n const descent = Math.max(1, metrics.fontBoundingBoxDescent || metrics.actualBoundingBoxDescent)\n // A canvas draws text on a whole pixel row and, across, on a quarter pixel at best, whatever\n // origin it is given. The slot's origin is therefore a whole pixel: ink left of the origin\n // or taller than the font box was otherwise baked up to half a texel off, and the tiles of\n // a sliced run a quarter texel off each other.\n const drawOffsetX = metrics.width * from\n const planeX0 = -Math.ceil(left + padding - drawOffsetX) - drawOffsetX\n const planeX1 = right + padding\n const inkBounds =\n request.shaping !== undefined || candidate || isEmojiCandidate(request.character)\n const planeY0 = -Math.max(descent, inkBounds ? metrics.actualBoundingBoxDescent : 0) - padding\n const planeY1 = Math.ceil(\n Math.max(ascent, inkBounds ? metrics.actualBoundingBoxAscent : 0) + padding,\n )\n // Only whole, plain text glyphs trim their quads: a tile of a shaped line is clipped to its\n // slice, and colour candidates are bitmaps whose ink the metrics need not bound.\n const ink: MeasuredGlyph['ink'] =\n inkBounds || slice\n ? undefined\n : [\n -metrics.actualBoundingBoxLeft,\n -metrics.actualBoundingBoxDescent,\n metrics.actualBoundingBoxRight,\n metrics.actualBoundingBoxAscent,\n ]\n\n return [\n {\n request,\n width: Math.max(2, Math.ceil(planeX1 - planeX0) + 2),\n height: Math.max(2, Math.ceil(planeY1 - planeY0) + 2),\n planeX0,\n planeY0,\n planeX1,\n planeY1,\n descent,\n advance,\n drawOffsetX,\n ...(ink?.every(Number.isFinite) ? { ink } : {}),\n x: 0,\n y: 0,\n },\n nextFont,\n ]\n}\n\n/**\n * @internal The slot of a glyph drawn at (glyph.x, glyph.y) of a `width`×`height` atlas. The\n * full build and an append patch both take their slots from here, so they cannot drift apart.\n * A `banded` glyph is a colour candidate in the band; an `uncoloured` one a candidate that\n * classified as text.\n */\nexport function slotOf(\n glyph: MeasuredGlyph,\n padding: number,\n bakeSize: number,\n width: number,\n height: number,\n banded: boolean,\n uncoloured: boolean,\n): GlyphSlot {\n // The sampled window must follow the drawn plane box, not the shelf slot:\n // the slot is `ceil(extent) + 2` texels wide and the glyph origin above is\n // offset by one, so the plane spans texels 1 .. 1 + extent. Both bounds move\n // inward by half a texel so bilinear filtering cannot reach a neighbour.\n const slice = glyph.request.shaping?.slice\n const planeX0 = glyph.planeX0 + (slice && slice[0] > 0 ? -glyph.planeX0 : 0.5)\n const planeY0 = glyph.planeY0 + 0.5\n const planeX1 = glyph.planeX1 - (slice && slice[1] < 1 ? glyph.planeX1 - glyph.advance : 0.5)\n const planeY1 = glyph.planeY1 - 0.5\n const uv = (x0: number, y0: number, x1: number, y1: number) => ({\n u0: (glyph.x + 1 + x0 - glyph.planeX0) / width,\n v0: (glyph.y + 1 + glyph.planeY1 - y1) / height,\n u1: (glyph.x + 1 + x1 - glyph.planeX0) / width,\n v1: (glyph.y + 1 + glyph.planeY1 - y0) / height,\n })\n const ink = banded ? undefined : glyph.ink\n const reach = padding / 2 + 2 + 0.006 * bakeSize\n const sx0 = ink ? Math.max(planeX0, Math.floor(ink[0] - reach)) : 0\n const sy0 = ink ? Math.max(planeY0, Math.floor(ink[1] - reach)) : 0\n const sx1 = ink ? Math.min(planeX1, Math.ceil(ink[2] + reach)) : 0\n const sy1 = ink ? Math.min(planeY1, Math.ceil(ink[3] + reach)) : 0\n return {\n ...(uncoloured ? { color: false } : {}),\n key: glyph.request.key,\n character: glyph.request.character,\n fontKey: glyph.request.font.key,\n ...uv(planeX0, planeY0, planeX1, planeY1),\n planeX0,\n planeY0,\n planeX1,\n planeY1,\n descent: glyph.descent,\n advance: glyph.advance,\n ...(ink && sx1 > sx0 && sy1 > sy0 ? { support: uv(sx0, sy0, sx1, sy1) } : {}),\n }\n}\n\n/**\n * @internal Draws glyphs into their slots of one canvas, by the rules of the full build and of\n * an append patch alike. `reset()` forgets the context state cached here: call it whenever\n * the canvas is resized, which resets that state.\n */\nexport function glyphPainter(\n context: CanvasRenderingContext2D,\n shaping: ShapingContext | undefined,\n signal: AbortSignal | undefined,\n drawShape?: (glyph: MeasuredGlyph) => void,\n): { draw(glyph: MeasuredGlyph, text: boolean, fill?: string): void; reset(): void } {\n // A text mask must be the outline itself on every platform. The bake canvas has font\n // smoothing off; where the engine has the property, text also asks for exact geometry,\n // and it takes a mid grey fill, the neutral middle of a rasterizer's contrast table.\n // Colour glyphs keep the default rendering and the fills their classification compares;\n // shapes are paths, which none of this affects.\n const exactText = 'textRendering' in context\n let lastFont: GlyphRequest['font'] | null = null\n let lastFill = ''\n let lastTextRendering = ''\n return {\n reset() {\n lastFont = null\n lastFill = ''\n lastTextRendering = ''\n },\n draw(glyph, text, fill = '#fff') {\n throwIfAborted(signal)\n const targetFill = text ? '#606060' : fill\n if (lastFill !== targetFill) {\n context.fillStyle = targetFill\n lastFill = targetFill\n }\n if (glyph.request.shape) {\n drawShape!(glyph)\n lastFill = ''\n return\n }\n lastFont = setFontContext(context, glyph.request, shaping, lastFont)\n if (exactText) {\n const targetRendering = text ? 'geometricPrecision' : 'auto'\n if (lastTextRendering !== targetRendering) {\n context.textRendering = targetRendering\n lastTextRendering = targetRendering\n }\n }\n const originX = glyph.x - glyph.planeX0 + 1\n const baselineY = glyph.y + glyph.planeY1 + 1\n if (glyph.request.shaping?.slice) {\n context.save()\n context.beginPath()\n context.rect(\n glyph.x + 1,\n glyph.y + 1,\n glyph.planeX1 - glyph.planeX0,\n glyph.planeY1 - glyph.planeY0,\n )\n context.clip()\n context.fillText(glyph.request.character, originX - glyph.drawOffsetX, baselineY)\n context.restore()\n } else context.fillText(glyph.request.character, originX, baselineY)\n },\n }\n}\n\n/** The first row of a non-empty run of packed glyphs. */\nfunction topOf(rows: readonly MeasuredGlyph[]): number {\n return rows.reduce((top, glyph) => (glyph.y < top ? glyph.y : top), rows[0]!.y)\n}\n\nlet lastOverflowWidth = Infinity\n\n/** @internal Row-major shelf packing; also lays out the colour candidates of an append. */\nexport function packShelves(\n glyphs: MeasuredGlyph[],\n width: number,\n maxSize: number,\n): { width: number; height: number } | null {\n let x = 0\n let y = 0\n let rowHeight = 0\n let usedWidth = 0\n\n for (const glyph of glyphs) {\n const gw = glyph.width\n const gh = glyph.height\n if (gw > width) {\n if (gw < lastOverflowWidth) lastOverflowWidth = gw\n return null\n }\n if (gh > maxSize) return null\n if (x + gw > width) {\n if (x + gw < lastOverflowWidth) lastOverflowWidth = x + gw\n x = 0\n y += rowHeight\n rowHeight = 0\n }\n if (y + gh > maxSize) return null\n glyph.x = x\n glyph.y = y\n x += gw\n if (gh > rowHeight) rowHeight = gh\n if (x > usedWidth) usedWidth = x\n }\n\n return {\n width: align4(usedWidth),\n height: align4(y + rowHeight),\n }\n}\n\nlet skylineX = new Int32Array(256)\nlet skylineY = new Int32Array(256)\nlet skylineW = new Int32Array(256)\n\n/** Bottom-left skyline packing fills the vertical gaps that fixed-height shelves leave behind. */\nfunction packSkyline(\n glyphs: MeasuredGlyph[],\n width: number,\n maxSize: number,\n): { width: number; height: number } | null {\n const needed = glyphs.length + 2\n if (skylineX.length < needed) {\n skylineX = new Int32Array(needed)\n skylineY = new Int32Array(needed)\n skylineW = new Int32Array(needed)\n }\n const sx = skylineX\n const sy = skylineY\n const sw = skylineW\n sx[0] = 0\n sy[0] = 0\n sw[0] = width\n let skylineLen = 1\n let usedWidth = 0\n let usedHeight = 0\n const shift = (to: number, from: number): void => {\n sx.copyWithin(to, from, skylineLen)\n sy.copyWithin(to, from, skylineLen)\n sw.copyWithin(to, from, skylineLen)\n }\n\n const minH = glyphs[glyphs.length - 1]!.height\n let wasteBudget = width * maxSize\n const over = (): null => (\n (lastOverflowWidth = Math.min(lastOverflowWidth, width + Math.ceil(-wasteBudget / maxSize))),\n null\n )\n for (const g of glyphs) wasteBudget -= g.width * g.height\n if (wasteBudget < 0) return over()\n\n for (const glyph of glyphs) {\n const gw = glyph.width\n const gh = glyph.height\n if (gh > maxSize) return null\n let bestIndex = -1\n let bestBottom = Infinity\n let bestWaste = Infinity\n const tail = skylineLen - 1\n let maxAllowedY = sw[tail]! >= gw && sy[tail]! < maxSize - gh ? sy[tail]! : maxSize - gh\n\n for (let index = 0; index < skylineLen; index++) {\n const firstY = sy[index]!\n if (firstY > maxAllowedY) continue\n const x = sx[index]!\n if (x + gw > width) {\n if (x + gw < lastOverflowWidth) lastOverflowWidth = x + gw\n break\n }\n\n let remaining = gw - sw[index]!\n let y = firstY\n let waste = 0\n if (remaining > 0) {\n let coveredArea = sw[index]! * firstY\n for (let cursor = index + 1; ; cursor++) {\n const nodeY = sy[cursor]!\n if (nodeY > maxAllowedY) {\n index = cursor\n remaining = 1\n break\n }\n if (nodeY > y) y = nodeY\n const nodeW = sw[cursor]!\n coveredArea += (remaining < nodeW ? remaining : nodeW) * nodeY\n if ((remaining -= nodeW) <= 0) break\n }\n if (remaining > 0) continue\n waste = y * gw - coveredArea\n }\n const bottom = y + gh\n if (bottom < bestBottom || waste < bestWaste) {\n bestIndex = index\n bestBottom = bottom\n bestWaste = waste\n maxAllowedY = waste === 0 ? y - 1 : y\n if (maxAllowedY < 0) break\n }\n }\n if (maxAllowedY >= 0 && usedWidth + gw < lastOverflowWidth) lastOverflowWidth = usedWidth + gw\n\n if (\n bestIndex < 0 ||\n (wasteBudget -= bestWaste + (bestBottom > maxSize - minH ? gw * (maxSize - bestBottom) : 0)) <\n 0\n )\n return bestIndex < 0 ? null : over()\n const gx = sx[bestIndex]!\n const right = gx + gw\n glyph.x = gx\n glyph.y = bestBottom - gh\n let cursor = bestIndex\n while (cursor < skylineLen && sx[cursor]! + sw[cursor]! <= right) cursor++\n if (cursor < skylineLen && sx[cursor]! < right) {\n sw[cursor] = sx[cursor]! + sw[cursor]! - right\n sx[cursor] = right\n }\n let newCount = 1\n if (bestIndex > 0 && sy[bestIndex - 1] === bestBottom) {\n sw[bestIndex - 1] = sw[bestIndex - 1]! + gw\n newCount = 0\n if (cursor < skylineLen && sy[cursor] === bestBottom) {\n sw[bestIndex - 1] = sw[bestIndex - 1]! + sw[cursor]!\n cursor++\n }\n } else if (cursor < skylineLen && sy[cursor] === bestBottom) {\n sx[cursor] = gx\n sw[cursor] = sw[cursor]! + gw\n newCount = 0\n }\n const delta = newCount - (cursor - bestIndex)\n if (delta !== 0 && cursor < skylineLen) shift(cursor + delta, cursor)\n skylineLen += delta\n if (newCount) {\n sx[bestIndex] = gx\n sy[bestIndex] = bestBottom\n sw[bestIndex] = gw\n }\n\n if (right > usedWidth) usedWidth = right\n if (bestBottom > usedHeight) usedHeight = bestBottom\n }\n\n return { width: align4(usedWidth), height: align4(usedHeight) }\n}\n\n/** Packs each group into rows of its own, one group below the other. */\nfunction packStacked(\n groups: readonly MeasuredGlyph[][],\n width: number,\n limit: number,\n pack: typeof packShelves,\n): { width: number; height: number } | null {\n let packedWidth = 0\n let height = 0\n for (const group of groups) {\n const packed = pack(group, width, limit - height)\n if (!packed || height + packed.height > limit) return null\n for (const glyph of group) glyph.y += height\n packedWidth = Math.max(packedWidth, packed.width)\n height += packed.height\n }\n return { width: packedWidth, height }\n}\n\nfunction rememberPacking(\n glyphs: readonly MeasuredGlyph[],\n size: { width: number; height: number },\n positions: Int32Array,\n): PackedGlyphs {\n for (let index = 0; index < glyphs.length; index++) {\n const glyph = glyphs[index]!\n positions[index * 2] = glyph.x\n positions[index * 2 + 1] = glyph.y\n }\n return { width: size.width, height: size.height }\n}\n\nfunction isBetterPacking(\n candidate: Pick<PackedGlyphs, 'width' | 'height'>,\n current: PackedGlyphs,\n): boolean {\n return (\n (candidate.width * candidate.height - current.width * current.height ||\n Math.max(candidate.width, candidate.height) - Math.max(current.width, current.height) ||\n candidate.width - current.width) < 0\n )\n}\n\n/**\n * Rasterizes every required font-face/character or emoji-sequence pair into one tightly packed\n * alpha atlas. The output is a transient mask; the retained texture is a\n * single-channel distance field produced by the CPU or WebGPU compute backend.\n */\nexport async function rasterizeGlyphAtlas(\n document: Document,\n requests: readonly GlyphRequest[],\n options: RasterizeOptions = {},\n): Promise<RasterAtlas> {\n const bakeSize = options.bakeSize ?? 96\n const padding = options.padding ?? 12\n const maxAtlasSize = options.maxAtlasSize ?? 2048\n if (!Number.isFinite(bakeSize) || bakeSize < 16) {\n throw new RangeError('rasterizeGlyphAtlas: bakeSize must be at least 16')\n }\n if (!Number.isFinite(padding) || padding < 2) {\n throw new RangeError('rasterizeGlyphAtlas: padding must be at least 2')\n }\n if (!Number.isInteger(maxAtlasSize) || maxAtlasSize < 64) {\n throw new RangeError('rasterizeGlyphAtlas: maxAtlasSize must be an integer of at least 64')\n }\n\n throwIfAborted(options.signal)\n const [, shapingModule, shapes] = await Promise.all([\n waitForFonts(document, requests, options.signal),\n requests.some((request) => request.shaping) ? import('../dom/browserShaping.js') : undefined,\n requests.some((request) => request.shape) ? import('./shapeRaster.js') : undefined,\n ])\n const shaping = shapingModule?.setShapingContext\n throwIfAborted(options.signal)\n\n const canvas = createCanvas(document)\n try {\n // A glyph a matching previous atlas has classified keeps its classification. A bitmap\n // shape always keeps its place in the band, as on a cold build: never history-dependent.\n const previous =\n options.previousAtlas?.bakeSize === bakeSize && options.previousAtlas.pxRange === padding\n ? options.previousAtlas.glyphs\n : undefined\n const context = canvas.getContext('2d', {\n willReadFrequently:\n !options.gpuUpload ||\n requests.some(\n (request) =>\n isColorCandidate(request, options.colorGlyphs) &&\n (request.shape !== undefined ||\n ((options.colorGlyphs === 'all' || isEmojiGrapheme(request.character)) &&\n previous?.get(request.key)?.color !== false)),\n ),\n })\n if (!context) throw new Error('rasterizeGlyphAtlas: Canvas 2D is unavailable')\n\n const packingLimit = maxAtlasSize - (maxAtlasSize % 4)\n let lastFont: GlyphRequest['font'] | null = null\n const measured = requests.map((request) => {\n if (request.shape) return shapes!.measureShape(request, bakeSize, padding)\n const [glyph, nextFont] = measureGlyph(\n context,\n request,\n padding,\n shaping,\n isColorCandidate(request, options.colorGlyphs),\n lastFont,\n )\n lastFont = nextFont\n return glyph\n })\n measured.sort(\n (a, b) =>\n b.height - a.height ||\n b.width - a.width ||\n (a.request.key < b.request.key ? -1 : a.request.key > b.request.key ? 1 : 0),\n )\n\n const banded = new Set<MeasuredGlyph>()\n const uncoloured = new Set<MeasuredGlyph>()\n const tested: MeasuredGlyph[] = []\n for (const glyph of measured) {\n if (!isColorCandidate(glyph.request, options.colorGlyphs)) continue\n const known = glyph.request.shape ? undefined : previous?.get(glyph.request.key)?.color\n if (known === false) uncoloured.add(glyph)\n else {\n banded.add(glyph)\n if (!glyph.request.shape && known === undefined) tested.push(glyph)\n }\n }\n const painter = glyphPainter(context, shaping, options.signal, (glyph) => {\n shapes!.drawShapeSlot(context, glyph, bakeSize)\n })\n const drawGlyph = (glyph: MeasuredGlyph, fill?: string): void => {\n painter.draw(glyph, !glyph.request.shape && !banded.has(glyph), fill)\n }\n\n // A candidate the font draws in the fill colour alone is text, whatever Unicode lists it\n // as: a copyright sign, an arrow, the tiles of a shaped line beside the one that holds\n // its emoji. Each font candidate is drawn in black and in white on a pack of their own,\n // and only one with ink that ignores the fill keeps its place in the band; the others are\n // baked, packed and flagged with the text.\n const colorGlyphs = banded.size ? await import('./colorGlyphs.js') : undefined\n throwIfAborted(options.signal)\n const scratch = tested.length ? packShelves(tested, packingLimit, packingLimit) : null\n if (scratch) {\n canvas.width = scratch.width\n canvas.height = scratch.height\n painter.reset()\n const paint = (fill: string): Uint8ClampedArray => {\n context.clearRect(0, 0, canvas.width, canvas.height)\n for (const glyph of tested) drawGlyph(glyph, fill)\n return context.getImageData(0, 0, canvas.width, canvas.height).data\n }\n const dark = paint('#000')\n const { colored } = colorGlyphs!.encodeColorBand(\n paint('#fff'),\n dark,\n canvas.width,\n canvas.height,\n 0,\n tested,\n )\n tested.forEach((glyph, index) => {\n if (colored[index]) return\n banded.delete(glyph)\n uncoloured.add(glyph)\n })\n }\n\n // Three kinds of rows, top to bottom: text, monochrome shapes, colour.\n const textRows: MeasuredGlyph[] = []\n const shapeRows: MeasuredGlyph[] = []\n const band: MeasuredGlyph[] = []\n let totalArea = 0\n let widestGlyph = 4\n let exceedsLimit = false\n for (const glyph of measured) {\n totalArea += glyph.width * glyph.height\n if (glyph.width > widestGlyph) widestGlyph = glyph.width\n if (glyph.width > packingLimit || glyph.height > packingLimit) exceedsLimit = true\n if (banded.has(glyph)) band.push(glyph)\n else if (glyph.request.shape) shapeRows.push(glyph)\n else textRows.push(glyph)\n }\n const groups = [textRows, shapeRows, band].filter((group) => group.length)\n const packGlyphs = (pack: typeof packShelves, width: number, limit: number) =>\n groups.length > 1 ? packStacked(groups, width, limit, pack) : pack(measured, width, limit)\n const impossible = totalArea > packingLimit * packingLimit || exceedsLimit\n const bestPositions = new Int32Array(measured.length * 2)\n let shelfWidth = Math.min(packingLimit, Math.max(64, nextPowerOfTwo(Math.sqrt(totalArea))))\n let packed = impossible ? null : packGlyphs(packShelves, shelfWidth, packingLimit)\n while (!packed && shelfWidth < packingLimit) {\n shelfWidth = Math.min(packingLimit, shelfWidth * 2)\n packed = packGlyphs(packShelves, shelfWidth, packingLimit)\n }\n let best = packed && !impossible ? rememberPacking(measured, packed, bestPositions) : null\n\n if (!impossible && measured.length > 0) {\n const minRequiredLimit = groups.reduce((sum, g) => sum + align4(g[0]!.height), 0)\n const minimumWidth = Math.min(\n packingLimit,\n align4(Math.max(widestGlyph, Math.ceil(totalArea / packingLimit))),\n )\n // Search at most about 64 aligned widths. Trying both the shelf and skyline\n // heuristic keeps the old pack as a no-regression candidate while allowing\n // short glyphs to occupy holes below taller neighbours.\n const widthStep = align4(Math.max(4, Math.ceil((packingLimit - minimumWidth) / 64)))\n const maxHeightFor = (width: number): number =>\n best ? Math.min(packingLimit, Math.floor((best.width * best.height) / width)) : packingLimit\n const nextW = [minimumWidth, minimumWidth]\n for (let width = minimumWidth; ; width = Math.min(packingLimit, width + widthStep)) {\n throwIfAborted(options.signal)\n if (maxHeightFor(width) < minRequiredLimit) break\n const minH = align4(Math.max(minRequiredLimit, Math.ceil(totalArea / width)))\n for (let i = 0; i < 2; i++) {\n if (width < nextW[i]!) continue\n const maxCandidateHeight = maxHeightFor(width)\n if (minH > maxCandidateHeight) break\n lastOverflowWidth = Infinity\n const candidate = packGlyphs(i ? packSkyline : packShelves, width, maxCandidateHeight)\n nextW[i] = lastOverflowWidth\n if (candidate && (!best || isBetterPacking(candidate, best))) {\n best = rememberPacking(measured, candidate, bestPositions)\n }\n }\n if (width === packingLimit) break\n }\n }\n\n if (!best) {\n if (options.adaptiveBakeSize === true && bakeSize > 16) {\n const nextSize = Math.max(16, Math.floor(bakeSize * 0.8))\n const scaled = requests.map((request) => ({\n ...request,\n font: {\n ...request.font,\n canvasFont: request.font.canvasFont.replace(\n /[\\d.]+px/,\n (size) => `${(Number.parseFloat(size) * nextSize) / bakeSize}px`,\n ),\n },\n }))\n return await rasterizeGlyphAtlas(document, scaled, { ...options, bakeSize: nextSize })\n }\n throw new Error(\n `rasterizeGlyphAtlas: ${requests.length} glyphs exceed the ${maxAtlasSize}×${maxAtlasSize} atlas limit`,\n )\n }\n for (let index = 0; index < measured.length; index++) {\n measured[index]!.x = bestPositions[index * 2]!\n measured[index]!.y = bestPositions[index * 2 + 1]!\n }\n\n // The text rows, packed first, end where the shapes or else the colour band begin. Headroom\n // for later appends goes there, so the rows below move down once, now, never on an append.\n let textBottom = !textRows.length ? 0 : groups.length > 1 ? topOf(groups[1]!) : best.height\n if (options.appendable === 'headroom' && textRows.length) {\n // Rows of at least two of the widest text glyphs: a one-column atlas has no row that\n // takes a glyph wider than its own.\n let widestText = 0\n for (const glyph of textRows) if (glyph.width > widestText) widestText = glyph.width\n best.width = Math.min(packingLimit, Math.max(best.width, align4(2 * widestText)))\n const room = Math.min(\n packingLimit - best.height,\n align4(Math.max(textRows[0]!.height, textBottom / 4)),\n )\n if (room > 0) {\n for (const glyph of measured) if (glyph.y >= textBottom) glyph.y += room\n best.height += room\n textBottom += room\n }\n }\n\n canvas.width = best.width\n canvas.height = best.height\n painter.reset()\n if (scratch) context.clearRect(0, 0, canvas.width, canvas.height)\n const bandTop = band.length ? topOf(band) : 0\n const bandHeight = canvas.height - bandTop\n let black: Uint8ClampedArray | undefined\n if (band.length) {\n for (const glyph of band) drawGlyph(glyph, '#000')\n black = context.getImageData(0, bandTop, canvas.width, bandHeight).data\n context.clearRect(0, bandTop, canvas.width, bandHeight)\n }\n const glyphSlots = new Map<string, GlyphSlot>()\n for (const glyph of measured) {\n drawGlyph(glyph)\n glyphSlots.set(\n glyph.request.key,\n slotOf(\n glyph,\n padding,\n bakeSize,\n canvas.width,\n canvas.height,\n banded.has(glyph),\n uncoloured.has(glyph),\n ),\n )\n }\n\n let colorBand: RasterColorBand | undefined\n if (black) {\n const white = context.getImageData(0, bandTop, canvas.width, bandHeight).data\n const encoded = colorGlyphs!.encodeColorBand(\n white,\n black,\n canvas.width,\n bandHeight,\n padding,\n band.map((glyph) => ({ ...glyph, y: glyph.y - bandTop })),\n )\n for (const [index, glyph] of band.entries()) {\n const slot = glyphSlots.get(glyph.request.key)!\n glyphSlots.set(glyph.request.key, { ...slot, color: encoded.colored[index]! })\n }\n if (encoded.colored.some(Boolean))\n colorBand = { top: bandTop, height: bandHeight, data: encoded.data }\n }\n const shapeTop = shapeRows.length ? topOf(shapeRows) : undefined\n if (options.appendable) {\n // The last text row is the one the lowest-starting slot begins on; whatever reaches\n // that row or below bounds where the cursor starts and how far the row runs down.\n let x = 0\n let y = 0\n let rowHeight = 0\n for (const glyph of textRows)\n if (glyph.y > y && glyph.y + textRows[0]!.height <= textBottom) y = glyph.y\n for (const glyph of textRows) {\n const reach = glyph.y + glyph.height - y\n if (reach > 0) {\n if (glyph.x + glyph.width > x) x = glyph.x + glyph.width\n if (reach > rowHeight) rowHeight = reach\n }\n }\n appendCursors.set(glyphSlots, {\n width: canvas.width,\n height: canvas.height,\n bakeSize,\n pxRange: padding,\n colorGlyphs: options.colorGlyphs ?? 'emoji',\n bottom: textBottom,\n x,\n y,\n rowHeight,\n })\n }\n return {\n ...(colorBand ? { colorBand } : {}),\n ...(shapeTop !== undefined ? { shapeTop } : {}),\n canvas,\n width: canvas.width,\n height: canvas.height,\n bakeSize,\n pxRange: padding,\n glyphs: glyphSlots,\n }\n } finally {\n canvas.remove()\n }\n}\n"],"mappings":";;;;;;;AAqEA,IAAa,gCAAgB,IAAI,QAA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QAAQ;IAAQ,CAAC;GAC/E;GACA,IAAI,QAAQ,QAAQ,KAAK,OAAO,GAC9B,YAAY;IAAE,KAAK;IAAS,QAAQ;IAAY,MAAM,QAAQ;GAAK;EACvE;EACA,MAAM,WAAW,UAAU,SAAS,MAAM,SAAS,IAAI,KAAA;EACvD,IAAI,QAAQ,YAAY;GAGtB,IAAI,IAAI;GACR,IAAI,IAAI;GACR,IAAI,YAAY;GAChB,KAAK,MAAM,SAAS,UAClB,IAAI,MAAM,IAAI,KAAK,MAAM,IAAI,SAAS,EAAE,CAAE,UAAU,YAAY,IAAI,MAAM;GAC5E,KAAK,MAAM,SAAS,UAAU;IAC5B,MAAM,QAAQ,MAAM,IAAI,MAAM,SAAS;IACvC,IAAI,QAAQ,GAAG;KACb,IAAI,MAAM,IAAI,MAAM,QAAQ,GAAG,IAAI,MAAM,IAAI,MAAM;KACnD,IAAI,QAAQ,WAAW,YAAY;IACrC;GACF;GACA,cAAc,IAAI,YAAY;IAC5B,OAAO,OAAO;IACd,QAAQ,OAAO;IACf;IACA,SAAS;IACT,aAAa,QAAQ,eAAe;IACpC,QAAQ;IACR;IACA;IACA;GACF,CAAC;EACH;EACA,OAAO;GACL,GAAI,YAAY,EAAE,UAAU,IAAI,CAAC;GACjC,GAAI,aAAa,KAAA,IAAY,EAAE,SAAS,IAAI,CAAC;GAC7C;GACA,OAAO,OAAO;GACd,QAAQ,OAAO;GACf;GACA,SAAS;GACT,QAAQ;EACV;CACF,UAAU;EACR,OAAO,OAAO;CAChB;AACF"}
@@ -1,6 +1,7 @@
1
1
  import { prepareAtlasPasses } from "../atlas/gpuAtlas.js";
2
2
  import { buildSdfAtlas } from "../atlas/buildAtlas.js";
3
- import { isColorCandidate, rasterizeGlyphAtlas } from "../atlas/rasterize.js";
3
+ import { isColorCandidate } from "./fontCanvas.js";
4
+ import { rasterizeGlyphAtlas } from "../atlas/rasterize.js";
4
5
  import { resolveDomTextTone } from "./tone.js";
5
6
  import { isAnimatedMotion } from "../text/GlyphTextMaterial.js";
6
7
  import { createRectMaterial } from "../text/RectMaterial.js";
@@ -486,6 +487,11 @@ var DomSdf = class DomSdf extends Group {
486
487
  let ownsNextRetained = false;
487
488
  let appended = false;
488
489
  let nextContent = null;
490
+ const staged = {
491
+ content: null,
492
+ atlas: null,
493
+ ms: 0
494
+ };
489
495
  try {
490
496
  await Promise.resolve();
491
497
  throwIfAborted(controller.signal);
@@ -495,6 +501,12 @@ var DomSdf = class DomSdf extends Group {
495
501
  const backendKind = opts.textBackend;
496
502
  const isAnalyticOption = backendKind === "windfoil" || backendKind === "slug";
497
503
  if (gpuUpload && !isAnalyticOption && !this.#r) prepareAtlasPasses(this.renderer);
504
+ let preloadBackend = null;
505
+ let preloadTraced = null;
506
+ if (isAnalyticOption && opts.textShaping !== "browser") {
507
+ preloadBackend = (backendKind === "slug" ? import("../slug/runtime.js") : import("../windfoil/runtime.js")).catch(() => null);
508
+ if (!((backendKind === "slug" ? opts.slug ?? opts.windfoil : opts.windfoil) ?? {}).outlineProvider && !this.#to) preloadTraced = import("../windfoil/tracedOutlines.js").catch(() => null);
509
+ }
498
510
  const layoutStarted = now();
499
511
  const snapshot = await collectDomSnapshot(this.source, opts);
500
512
  const tone = resolveDomTextTone(this.source, opts.tone, {
@@ -515,7 +527,7 @@ var DomSdf = class DomSdf extends Group {
515
527
  };
516
528
  const retained = this.#r;
517
529
  const canReuseRetainedText = rebuildOptions.atlas !== true && retained !== null && (this.#as === snapshot.atlasSignature || (isWindfoilBackend(retained) ? snapshot.requests.every((request) => retained.covers(request.key)) : atlasCovers(retained)));
518
- const signature = layoutSignatureOf(snapshot);
530
+ let signature = canReuseRetainedText && this.#c !== null && this.#cm ? layoutSignatureOf(snapshot) : void 0;
519
531
  if (canReuseRetainedText && this.#c !== null && this.#cm && signature === this.#ls && generation === this.#g && this.#c.st(tone)) {
520
532
  this.#st = Object.freeze({
521
533
  ...this.#st,
@@ -543,7 +555,7 @@ var DomSdf = class DomSdf extends Group {
543
555
  appended = !!nextRetained;
544
556
  }
545
557
  const previousAtlas = rebuildOptions.atlas !== true && retained !== null && !isWindfoilBackend(retained) && retained !== opts.sharedAtlas ? retained : void 0;
546
- const buildAtlas = async (requests, signal, appendable) => {
558
+ const buildAtlas = async (requests, signal, appendable, allowProvisional = false) => {
547
559
  const def = (...ks) => Object.fromEntries(ks.flatMap((k) => opts[k] === void 0 ? [] : [[k, opts[k]]]));
548
560
  const raster = await rasterizeGlyphAtlas(this.source.ownerDocument, requests, {
549
561
  signal,
@@ -552,13 +564,36 @@ var DomSdf = class DomSdf extends Group {
552
564
  ...gpuUpload ? { gpuUpload } : {},
553
565
  ...def("colorGlyphs", "bakeSize", "padding", "maxAtlasSize", "adaptiveBakeSize")
554
566
  });
555
- return buildSdfAtlas(this.renderer, raster, {
567
+ const atlasOptions = {
556
568
  signal,
557
569
  mipmaps: opts.quality === "high",
558
570
  anisotropy: opts.quality === "high" ? 4 : 1,
559
571
  ...opts.atlasMode === void 0 ? {} : { mode: opts.atlasMode },
560
572
  ...def("cpuWorker")
573
+ };
574
+ if (allowProvisional && gpuUpload && opts.quality !== "high") return buildSdfAtlas(this.renderer, raster, atlasOptions, {
575
+ stage: (provisionalAtlas) => {
576
+ if (signal.aborted || generation !== this.#g || staged.content) return;
577
+ const geometryT0 = now();
578
+ try {
579
+ signature ??= layoutSignatureOf(snapshot);
580
+ staged.content = createContent(snapshot, provisionalAtlas, opts, this.#m, tone);
581
+ staged.atlas = provisionalAtlas;
582
+ staged.ms = now() - geometryT0;
583
+ } catch {
584
+ staged.content = null;
585
+ staged.atlas = null;
586
+ staged.ms = 0;
587
+ }
588
+ },
589
+ rollback: () => {
590
+ staged.content?.d();
591
+ staged.content = null;
592
+ staged.atlas = null;
593
+ staged.ms = 0;
594
+ }
561
595
  });
596
+ return buildSdfAtlas(this.renderer, raster, atlasOptions);
562
597
  };
563
598
  if (!appended && isAnalyticOption && opts.textShaping !== "browser") {
564
599
  const analytic = (backendKind === "slug" ? opts.slug ?? opts.windfoil : opts.windfoil) ?? {};
@@ -571,7 +606,7 @@ var DomSdf = class DomSdf extends Group {
571
606
  };
572
607
  else {
573
608
  if (!this.#to) {
574
- const { createTracedOutlineProvider } = await import("../windfoil/tracedOutlines.js");
609
+ const { createTracedOutlineProvider } = await preloadTraced ?? await import("../windfoil/tracedOutlines.js");
575
610
  throwIfAborted(controller.signal);
576
611
  this.#to ??= createTracedOutlineProvider(this.source.ownerDocument, opts.colorGlyphs === void 0 ? {} : { colorGlyphs: opts.colorGlyphs });
577
612
  } else if (rebuildOptions.atlas === true) this.#to.clear();
@@ -581,28 +616,43 @@ var DomSdf = class DomSdf extends Group {
581
616
  outlineProvider: this.#to.provider
582
617
  };
583
618
  }
584
- nextRetained = await (backendKind === "slug" ? (await import("../slug/runtime.js")).buildSlugBackend : (await import("../windfoil/runtime.js")).buildWindfoilBackend)(this.renderer, snapshot.requests, resolved, controller.signal, {
619
+ nextRetained = await (backendKind === "slug" ? (await preloadBackend ?? await import("../slug/runtime.js")).buildSlugBackend : (await preloadBackend ?? await import("../windfoil/runtime.js")).buildWindfoilBackend)(this.renderer, snapshot.requests, resolved, controller.signal, {
585
620
  build: buildAtlas,
586
621
  effects: opts
587
622
  });
588
623
  }
589
624
  if (!appended) {
590
- nextRetained ??= await buildAtlas(snapshot.requests, controller.signal, this.#ga ? "headroom" : true);
625
+ nextRetained ??= await buildAtlas(snapshot.requests, controller.signal, this.#ga ? "headroom" : true, true);
591
626
  ownsNextRetained = true;
592
627
  }
593
- atlasBuildMs = now() - atlasStarted;
628
+ atlasBuildMs = Math.max(0, now() - atlasStarted - staged.ms);
594
629
  }
595
630
  throwIfAborted(controller.signal);
596
631
  if (generation !== this.#g || !nextRetained) throw abortError("Superseded by a newer DOM SDF build");
597
- const geometryStarted = now();
598
- if (isWindfoilBackend(nextRetained)) nextRetained.setGlyphEm(!!tone?.dilationPx);
599
- if (!((canReuseRetainedText || appended) && (this.#c?.u(snapshot, nextRetained, this.#m, tone) ?? false))) {
600
- const extra = isWindfoilBackend(nextRetained) && (nextRetained.companion || nextRetained.color) ? await import("../windfoil/mixed.js") : void 0;
601
- throwIfAborted(controller.signal);
602
- nextContent = createContent(snapshot, nextRetained, opts, this.#m, tone, extra?.createExtraTextParts);
632
+ let geometryBuildMs = 0;
633
+ if (staged.content !== null && staged.atlas === nextRetained && !isWindfoilBackend(nextRetained)) {
634
+ nextContent = staged.content;
635
+ staged.content = null;
636
+ staged.atlas = null;
637
+ geometryBuildMs = staged.ms;
638
+ } else {
639
+ if (staged.content) {
640
+ staged.content.d();
641
+ staged.content = null;
642
+ staged.atlas = null;
643
+ staged.ms = 0;
644
+ }
645
+ const geometryStarted = now();
646
+ if (isWindfoilBackend(nextRetained)) nextRetained.setGlyphEm(!!tone?.dilationPx);
647
+ if (!((canReuseRetainedText || appended) && (this.#c?.u(snapshot, nextRetained, this.#m, tone) ?? false))) {
648
+ const extra = isWindfoilBackend(nextRetained) && (nextRetained.companion || nextRetained.color) ? await import("../windfoil/mixed.js") : void 0;
649
+ throwIfAborted(controller.signal);
650
+ nextContent = createContent(snapshot, nextRetained, opts, this.#m, tone, extra?.createExtraTextParts);
651
+ }
652
+ geometryBuildMs = now() - geometryStarted;
603
653
  }
604
- const geometryBuildMs = now() - geometryStarted;
605
654
  throwIfAborted(controller.signal);
655
+ signature ??= layoutSignatureOf(snapshot);
606
656
  const oldContent = this.#c;
607
657
  const oldRetained = this.#r;
608
658
  let activeContent;
@@ -668,6 +718,7 @@ var DomSdf = class DomSdf extends Group {
668
718
  if (oldContent && oldContent !== activeContent) oldContent.d();
669
719
  if (oldRetained && oldRetained !== nextRetained && ownedPrevious && !appended) oldRetained.dispose();
670
720
  } catch (error) {
721
+ staged.content?.d();
671
722
  nextContent?.d();
672
723
  if (ownsNextRetained) nextRetained?.dispose();
673
724
  throw error;