ultra-text 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/README.md +267 -962
  2. package/THIRD_PARTY_NOTICES.md +3 -0
  3. package/dist/assets/{cpuSdf.worker-Du9o8q4p.js → cpuSdf.worker--X1Qpmdp.js} +148 -57
  4. package/dist/assets/cpuSdf.worker--X1Qpmdp.js.map +1 -0
  5. package/dist/atlas/appendAtlas.js +69 -26
  6. package/dist/atlas/appendAtlas.js.map +1 -1
  7. package/dist/atlas/buildAtlas.js +5 -15
  8. package/dist/atlas/buildAtlas.js.map +1 -1
  9. package/dist/atlas/cpuAtlas.d.ts +4 -1
  10. package/dist/atlas/cpuAtlas.js +8 -6
  11. package/dist/atlas/cpuAtlas.js.map +1 -1
  12. package/dist/atlas/cpuSdf.js +164 -50
  13. package/dist/atlas/cpuSdf.js.map +1 -1
  14. package/dist/atlas/cpuWorker.d.ts +5 -3
  15. package/dist/atlas/cpuWorker.js +119 -12
  16. package/dist/atlas/cpuWorker.js.map +1 -1
  17. package/dist/atlas/gpuAtlas.d.ts +7 -6
  18. package/dist/atlas/gpuAtlas.js +206 -247
  19. package/dist/atlas/gpuAtlas.js.map +1 -1
  20. package/dist/atlas/gpuCommon.d.ts +135 -0
  21. package/dist/atlas/gpuCommon.js +223 -0
  22. package/dist/atlas/gpuCommon.js.map +1 -0
  23. package/dist/atlas/jfaWgsl.js +59 -125
  24. package/dist/atlas/jfaWgsl.js.map +1 -1
  25. package/dist/atlas/rasterize.d.ts +2 -0
  26. package/dist/atlas/rasterize.js +104 -144
  27. package/dist/atlas/rasterize.js.map +1 -1
  28. package/dist/atlas/shapeRaster.js +2 -1
  29. package/dist/atlas/shapeRaster.js.map +1 -1
  30. package/dist/atlas/vanillaBounds.d.ts +64 -0
  31. package/dist/atlas/vanillaBounds.js +42 -0
  32. package/dist/atlas/vanillaBounds.js.map +1 -0
  33. package/dist/atlas/vanillaCore.d.ts +100 -0
  34. package/dist/atlas/vanillaCore.js +1012 -0
  35. package/dist/atlas/vanillaCore.js.map +1 -0
  36. package/dist/atlas/vanillaCpuAtlas.d.ts +9 -0
  37. package/dist/atlas/vanillaCpuAtlas.js +87 -0
  38. package/dist/atlas/vanillaCpuAtlas.js.map +1 -0
  39. package/dist/atlas/vanillaExtras.d.ts +8 -0
  40. package/dist/atlas/vanillaExtras.js +166 -0
  41. package/dist/atlas/vanillaExtras.js.map +1 -0
  42. package/dist/atlas/vanillaGpuHelpers.d.ts +232 -0
  43. package/dist/atlas/vanillaGpuHelpers.js +119 -0
  44. package/dist/atlas/vanillaGpuHelpers.js.map +1 -0
  45. package/dist/dom/DomSdf.js +263 -272
  46. package/dist/dom/DomSdf.js.map +1 -1
  47. package/dist/dom/DomSlug.d.ts +26 -0
  48. package/dist/dom/DomSlug.js +564 -0
  49. package/dist/dom/DomSlug.js.map +1 -0
  50. package/dist/dom/SlugText.d.ts +18 -0
  51. package/dist/dom/SlugText.js +94 -0
  52. package/dist/dom/SlugText.js.map +1 -0
  53. package/dist/dom/Text.js +4 -67
  54. package/dist/dom/Text.js.map +1 -1
  55. package/dist/dom/domAnalytic.d.ts +54 -0
  56. package/dist/dom/domAnalytic.js +282 -0
  57. package/dist/dom/domAnalytic.js.map +1 -0
  58. package/dist/dom/domExtras.d.ts +27 -0
  59. package/dist/dom/domExtras.js +137 -0
  60. package/dist/dom/domExtras.js.map +1 -0
  61. package/dist/dom/fontCanvas.d.ts +2 -0
  62. package/dist/dom/fontCanvas.js +119 -0
  63. package/dist/dom/fontCanvas.js.map +1 -0
  64. package/dist/dom/layoutSignature.js +156 -27
  65. package/dist/dom/layoutSignature.js.map +1 -1
  66. package/dist/dom/pretextLayout.js +55 -13
  67. package/dist/dom/pretextLayout.js.map +1 -1
  68. package/dist/dom/snapshot.js +563 -243
  69. package/dist/dom/snapshot.js.map +1 -1
  70. package/dist/dom/svgCapture.d.ts +8 -1
  71. package/dist/dom/svgCapture.js +75 -1
  72. package/dist/dom/svgCapture.js.map +1 -1
  73. package/dist/dom/textHost.d.ts +11 -0
  74. package/dist/dom/textHost.js +68 -0
  75. package/dist/dom/textHost.js.map +1 -0
  76. package/dist/dom/tone.js +76 -36
  77. package/dist/dom/tone.js.map +1 -1
  78. package/dist/index.js +4 -3
  79. package/dist/slug/SlugMaterial.d.ts +13 -4
  80. package/dist/slug/SlugMaterial.js +82 -12
  81. package/dist/slug/SlugMaterial.js.map +1 -1
  82. package/dist/slug/coverage.d.ts +17 -13
  83. package/dist/slug/coverage.js +195 -222
  84. package/dist/slug/coverage.js.map +1 -1
  85. package/dist/slug/preprocessCore.d.ts +6 -3
  86. package/dist/slug/preprocessCore.js +149 -95
  87. package/dist/slug/preprocessCore.js.map +1 -1
  88. package/dist/slug/runtime.d.ts +1 -0
  89. package/dist/slug/runtime.js +94 -46
  90. package/dist/slug/runtime.js.map +1 -1
  91. package/dist/slug/standaloneRuntime.d.ts +40 -0
  92. package/dist/slug/standaloneRuntime.js +175 -0
  93. package/dist/slug/standaloneRuntime.js.map +1 -0
  94. package/dist/slug/truetype.d.ts +22 -0
  95. package/dist/slug/truetype.js +467 -0
  96. package/dist/slug/truetype.js.map +1 -0
  97. package/dist/slug/vanillaCore.d.ts +340 -0
  98. package/dist/slug/vanillaCore.js +1621 -0
  99. package/dist/slug/vanillaCore.js.map +1 -0
  100. package/dist/slug-vanilla.d.ts +13 -0
  101. package/dist/slug-vanilla.js +13 -0
  102. package/dist/slug.d.ts +21 -0
  103. package/dist/slug.js +19 -0
  104. package/dist/text/GlyphTextMaterial.d.ts +11 -11
  105. package/dist/text/GlyphTextMaterial.js +102 -33
  106. package/dist/text/GlyphTextMaterial.js.map +1 -1
  107. package/dist/text/SdfTextMaterial.d.ts +5 -4
  108. package/dist/text/SdfTextMaterial.js +29 -9
  109. package/dist/text/SdfTextMaterial.js.map +1 -1
  110. package/dist/text/decorations.js +36 -19
  111. package/dist/text/decorations.js.map +1 -1
  112. package/dist/text/geometry.d.ts +3 -22
  113. package/dist/text/geometryUtils.d.ts +11 -1
  114. package/dist/text/geometryUtils.js +22 -1
  115. package/dist/text/geometryUtils.js.map +1 -1
  116. package/dist/text/glyphGeometry.d.ts +9 -0
  117. package/dist/text/glyphGeometry.js +353 -0
  118. package/dist/text/glyphGeometry.js.map +1 -0
  119. package/dist/text/index.d.ts +2 -1
  120. package/dist/text/rectGeometry.d.ts +13 -0
  121. package/dist/text/rectGeometry.js +97 -0
  122. package/dist/text/rectGeometry.js.map +1 -0
  123. package/dist/text/reflow.d.ts +18 -1
  124. package/dist/text/reflow.js +108 -38
  125. package/dist/text/reflow.js.map +1 -1
  126. package/dist/text/snap.d.ts +1 -0
  127. package/dist/text/snap.js +26 -0
  128. package/dist/text/snap.js.map +1 -0
  129. package/dist/types.d.ts +63 -14
  130. package/dist/vanilla.d.ts +13 -360
  131. package/dist/vanilla.js +8 -1402
  132. package/dist/windfoil/WindfoilMaterial.d.ts +2 -1
  133. package/dist/windfoil/WindfoilMaterial.js +8 -1
  134. package/dist/windfoil/WindfoilMaterial.js.map +1 -1
  135. package/dist/windfoil/abortable.d.ts +2 -0
  136. package/dist/windfoil/abortable.js +26 -0
  137. package/dist/windfoil/abortable.js.map +1 -0
  138. package/dist/windfoil/color.js +2 -1
  139. package/dist/windfoil/color.js.map +1 -1
  140. package/dist/windfoil/coverage.d.ts +3 -20
  141. package/dist/windfoil/coverage.js +7 -20
  142. package/dist/windfoil/coverage.js.map +1 -1
  143. package/dist/windfoil/emoji.js +1 -1
  144. package/dist/windfoil/emoji.js.map +1 -1
  145. package/dist/windfoil/emojiMetrics.js +1 -1
  146. package/dist/windfoil/emojiMetrics.js.map +1 -1
  147. package/dist/windfoil/geometry.d.ts +2 -2
  148. package/dist/windfoil/geometry.js +204 -64
  149. package/dist/windfoil/geometry.js.map +1 -1
  150. package/dist/windfoil/layerGrid.js +14 -10
  151. package/dist/windfoil/layerGrid.js.map +1 -1
  152. package/dist/windfoil/layerNormalization.d.ts +1 -1
  153. package/dist/windfoil/layerNormalization.js +1 -1
  154. package/dist/windfoil/layerNormalization.js.map +1 -1
  155. package/dist/windfoil/mixed.d.ts +1 -0
  156. package/dist/windfoil/mixed.js +44 -25
  157. package/dist/windfoil/mixed.js.map +1 -1
  158. package/dist/windfoil/outlineValidation.d.ts +86 -0
  159. package/dist/windfoil/outlineValidation.js +65 -0
  160. package/dist/windfoil/outlineValidation.js.map +1 -0
  161. package/dist/windfoil/preprocess.js +3 -2
  162. package/dist/windfoil/preprocess.js.map +1 -1
  163. package/dist/windfoil/preprocessCore.d.ts +5 -85
  164. package/dist/windfoil/preprocessCore.js +218 -209
  165. package/dist/windfoil/preprocessCore.js.map +1 -1
  166. package/dist/windfoil/requests.js +1 -1
  167. package/dist/windfoil/requests.js.map +1 -1
  168. package/dist/windfoil/runtime.d.ts +5 -2
  169. package/dist/windfoil/runtime.js +63 -40
  170. package/dist/windfoil/runtime.js.map +1 -1
  171. package/dist/windfoil/shapeResources.js +2 -1
  172. package/dist/windfoil/shapeResources.js.map +1 -1
  173. package/dist/windfoil/shapes.js +1 -1
  174. package/dist/windfoil/skirt.d.ts +22 -0
  175. package/dist/windfoil/skirt.js +20 -0
  176. package/dist/windfoil/skirt.js.map +1 -0
  177. package/dist/windfoil/storage.d.ts +62 -4
  178. package/dist/windfoil/storage.js +143 -28
  179. package/dist/windfoil/storage.js.map +1 -1
  180. package/dist/windfoil/trace/contours.d.ts +3 -3
  181. package/dist/windfoil/trace/contours.js +228 -137
  182. package/dist/windfoil/trace/contours.js.map +1 -1
  183. package/dist/windfoil/trace/fit.d.ts +3 -7
  184. package/dist/windfoil/trace/fit.js +668 -376
  185. package/dist/windfoil/trace/fit.js.map +1 -1
  186. package/dist/windfoil/trace/outline.js +60 -35
  187. package/dist/windfoil/trace/outline.js.map +1 -1
  188. package/dist/windfoil/trace/types.d.ts +15 -3
  189. package/dist/windfoil/tracedOutlines.d.ts +37 -1
  190. package/dist/windfoil/tracedOutlines.js +228 -64
  191. package/dist/windfoil/tracedOutlines.js.map +1 -1
  192. package/package.json +60 -11
  193. package/skills/ultra-text/SKILL.md +114 -0
  194. package/skills/ultra-text/references/frameworks.md +43 -0
  195. package/skills/ultra-text/references/three-tsl.md +78 -0
  196. package/skills/ultra-text/references/vanilla-webgpu.md +96 -0
  197. package/dist/assets/cpuSdf.worker-Du9o8q4p.js.map +0 -1
  198. package/dist/text/geometry.js +0 -348
  199. package/dist/text/geometry.js.map +0 -1
  200. package/dist/vanilla.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"jfaWgsl.js","names":[],"sources":["../../src/atlas/jfaWgsl.ts"],"sourcesContent":["/**\n * @internal The atlas passes in WGSL, run on three's device by `gpuAtlas.ts` and on a raw\n * `GPUDevice` by the Three-free entry (`vanilla.ts`): boundary seeds (`seedMain`), one jump\n * flood step (`jumpMain`) and the resolve into an r8unorm atlas (`fullscreenVert`,\n * `resolveFrag`). Each pass binds 16 bytes of `Params` at binding 0:\n * the size, then the raster's row stride in words for the seeds or the step for a jump, then\n * 1 / pxRange for the resolve. The seed and resolve passes read the raster and the seeds from\n * storage buffers (one rgba8unorm texel per word, alpha in its top byte), never a texture: on\n * an M3 Max that cut their pipelines' native compile from\n * ~120 to ~20 ms each, in Chrome and in WebKit. Every real seed coordinate is >= 0; x is\n * biased by +2 so that the sign of seed.x carries the texel's inside/outside state across the\n * ping-pong, and 32768 marks no seed. The neighbours are visited in one order everywhere, so\n * ties and sums, and with them the bytes, do not depend on the device.\n */\nexport const JFA_WGSL = /* wgsl */ `\nstruct Params {\n width: i32,\n height: i32,\n stride: i32,\n invPxRange: f32,\n}\n\n@group(0) @binding(0) var<uniform> params: Params;\n@group(0) @binding(1) var<storage, read> rasterWords: array<u32>;\n@group(0) @binding(1) var<storage, read> inputSeeds: array<vec2f>;\n@group(0) @binding(2) var<storage, read_write> outputSeeds: array<vec2f>;\n\nfn inAtlas(x: i32, y: i32) -> bool {\n return x >= 0 && y >= 0 && x < params.width && y < params.height;\n}\n\nfn alphaAt(x: i32, y: i32) -> u32 {\n return rasterWords[y * params.stride + x] >> 24u;\n}\n\n@compute @workgroup_size(8, 8)\nfn seedMain(@builtin(global_invocation_id) id: vec3u) {\n let x = i32(id.x);\n let y = i32(id.y);\n if (!inAtlas(x, y)) {\n return;\n }\n let index = y * params.width + x;\n let here = alphaAt(x, y);\n if (here < 128u) {\n outputSeeds[index] = vec2f(32768.0);\n return;\n }\n let excess = f32(here) - 127.5;\n var sum = vec2f(0.0);\n var count = 0.0;\n for (var dy = -1; dy <= 1; dy++) {\n for (var dx = -1; dx <= 1; dx++) {\n if ((dx != 0 || dy != 0) && inAtlas(x + dx, y + dy)) {\n let neighbor = alphaAt(x + dx, y + dy);\n if (neighbor < 128u) {\n let crossing = excess / f32(here - neighbor);\n sum += vec2f(crossing * f32(dx), crossing * f32(dy));\n count += 1.0;\n }\n }\n }\n }\n if (count > 0.0) {\n let seeded = vec2f(f32(x), f32(y)) + sum / count;\n outputSeeds[index] = vec2f(-(seeded.x + 2.0), seeded.y);\n } else {\n outputSeeds[index] = vec2f(-32768.0, 32768.0);\n }\n}\n\n@compute @workgroup_size(8, 8)\nfn jumpMain(@builtin(global_invocation_id) id: vec3u) {\n let x = i32(id.x);\n let y = i32(id.y);\n if (!inAtlas(x, y)) {\n return;\n }\n let index = y * params.width + x;\n let biasedPos = vec2f(f32(x) + 2.0, f32(y));\n let here = inputSeeds[index];\n var best = vec2f(abs(here.x), here.y);\n var bestDistance = 3.402823e38;\n if (best.x < 20002.0) {\n let delta = best - biasedPos;\n bestDistance = dot(delta, delta);\n }\n for (var dy = -1; dy <= 1; dy++) {\n for (var dx = -1; dx <= 1; dx++) {\n let nx = x + params.stride * dx;\n let ny = y + params.stride * dy;\n if ((dx != 0 || dy != 0) && inAtlas(nx, ny)) {\n let seed = inputSeeds[ny * params.width + nx];\n let candidate = vec2f(abs(seed.x), seed.y);\n if (candidate.x < 20002.0) {\n let delta = candidate - biasedPos;\n let distance = dot(delta, delta);\n if (distance < bestDistance) {\n bestDistance = distance;\n best = candidate;\n }\n }\n }\n }\n }\n outputSeeds[index] = vec2f(select(best.x, -best.x, here.x < 0.0), best.y);\n}\n\n@vertex\nfn fullscreenVert(@builtin(vertex_index) vid: u32) -> @builtin(position) vec4f {\n let x = f32((vid << 1u) & 2u);\n let y = f32(vid & 2u);\n return vec4f(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0);\n}\n\n@fragment\nfn resolveFrag(@builtin(position) pos: vec4f) -> @location(0) vec4f {\n let pixelPos = floor(pos.xy - vec2f(0.5));\n let pixel = vec2i(pixelPos);\n let rawSeed = inputSeeds[pixel.y * params.width + pixel.x];\n let inside = rawSeed.x < 0.0;\n let absX = abs(rawSeed.x);\n if (absX >= 20002.0) {\n return vec4f(select(0.0, 1.0, inside), 0.0, 0.0, 1.0);\n }\n let dist = length(vec2f(absX - 2.0, rawSeed.y) - pixelPos);\n let signedDist = select(dist, -dist, inside);\n return vec4f(clamp(0.5 - signedDist * params.invPxRange, 0.0, 1.0), 0.0, 0.0, 1.0);\n}\n`\n\n/** @internal The mip blit (`mipVert`, `mipFrag`) the Three-free entry appends to `JFA_WGSL`. */\nexport const MIP_WGSL = /* wgsl */ `\n@group(0) @binding(0) var mipSrc: texture_2d<f32>;\n@group(0) @binding(1) var mipSampler: sampler;\n\nstruct MipVarying {\n @builtin(position) pos: vec4f,\n @location(0) uv: vec2f,\n}\n\n@vertex\nfn mipVert(@builtin(vertex_index) vid: u32) -> MipVarying {\n let x = f32((vid << 1u) & 2u);\n let y = f32(vid & 2u);\n var out: MipVarying;\n out.pos = vec4f(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0);\n out.uv = vec2f(x, y);\n return out;\n}\n\n@fragment\nfn mipFrag(in: MipVarying) -> @location(0) vec4f {\n return textureSampleLevel(mipSrc, mipSampler, in.uv, 0.0);\n}\n`\n"],"mappings":";;;;;;;;;;;;;;;AAcA,IAAa,WAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsHnC,IAAa,WAAsB"}
1
+ {"version":3,"file":"jfaWgsl.js","names":[],"sources":["../../src/atlas/jfaWgsl.ts"],"sourcesContent":["const NEIGHBORS = [\n [-1, -1],\n [0, -1],\n [1, -1],\n [-1, 0],\n [1, 0],\n [-1, 1],\n [0, 1],\n [1, 1],\n] as const\n\nfunction buildSeedBody(): string {\n return NEIGHBORS.map(([dx, dy], i) => {\n const upd =\n dx && dy\n ? `sum+=vec2f(${dx < 0 ? '-c' : 'c'},${dy < 0 ? '-c' : 'c'});`\n : `${dx ? 'sum.x' : 'sum.y'}${(dx || dy) < 0 ? '-=' : '+='}c;`\n return `if(w${i}<0x80000000u){let c=excess/f32(here-(w${i}>>24u));${upd}count+=1.0;}`\n }).join('')\n}\n\nfunction buildJumpBody(stepVar: string, offsetExpr: string, updatePos: boolean): string {\n const row0 = stepVar === '1' ? 'index-wi' : `(y-${stepVar})*wi+x`\n const row2 = stepVar === '1' ? 'index+wi' : `(y+${stepVar})*wi+x`\n const taps = NEIGHBORS.map(([dx, dy], i) => {\n const cx = dx ? `((rs<<16u)>>17u)${dx < 0 ? '-' : '+'}${offsetExpr}` : '(rs<<16u)>>17u'\n const cy = dy ? `(rs>>16u)${dy < 0 ? '-' : '+'}${offsetExpr}` : 'rs>>16u'\n return `if((n${i}|1u)!=UNSEEDED_IN){let rs=bitcast<i32>(n${i});let cx=${cx};let cy=${cy};let d=u32(cx*cx+cy*cy);if(d<bestDist){bestDist=d;${updatePos ? 'bestX=cx;bestY=cy;' : ''}}}`\n }).join('')\n const ny = stepVar === '1' ? 'y+dy' : `y+${stepVar}*dy`\n const nx = stepVar === '1' ? 'x+dx' : `x+${stepVar}*dx`\n return (\n `if(x>=${stepVar}&&x+${stepVar}<wi&&y>=${stepVar}&&y+${stepVar}<hi){` +\n `let r0=${row0};let r2=${row2};` +\n `let n0=inputSeeds[r0-${stepVar}];let n1=inputSeeds[r0];let n2=inputSeeds[r0+${stepVar}];` +\n `let n3=inputSeeds[index-${stepVar}];let n4=inputSeeds[index+${stepVar}];` +\n `let n5=inputSeeds[r2-${stepVar}];let n6=inputSeeds[r2];let n7=inputSeeds[r2+${stepVar}];` +\n `let andN=n0&n1&n2&n3&n4&n5&n6&n7;let orN=n0|n1|n2|n3|n4|n5|n6|n7;` +\n `if((((andN^UNSEEDED_IN)|(orN^UNSEEDED_IN))&0xfffffffeu)!=0u){${taps}}` +\n `}else{` +\n `for(var dy=-1;dy<=1;dy++){let ny=${ny};if(u32(ny)<h){let row=ny*wi;let offY=dy*${offsetExpr};` +\n `for(var dx=-1;dx<=1;dx++){let nx=${nx};if((dx!=0||dy!=0)&&u32(nx)<w){let raw=inputSeeds[row+nx];` +\n `if((raw|1u)!=UNSEEDED_IN){let rs=bitcast<i32>(raw);let cx=((rs<<16u)>>17u)+dx*${offsetExpr};let cy=(rs>>16u)+offY;let dist=u32(cx*cx+cy*cy);` +\n `if(dist<bestDist){bestDist=dist;${updatePos ? 'bestX=cx;bestY=cy;' : ''}}}}}}}` +\n `}`\n )\n}\n\nfunction buildTiledSeed(aw: number): string {\n return NEIGHBORS.map(([dx, dy], i) => {\n const upd =\n dx && dy\n ? `sum+=vec2f(${dx < 0 ? '-c' : 'c'},${dy < 0 ? '-c' : 'c'});`\n : `${dx ? 'sum.x' : 'sum.y'}${(dx || dy) < 0 ? '-=' : '+='}c;`\n return `if(w${i}<128u){let c=excess/f32(here-w${i});${upd}count+=1.0;}`\n })\n .join('')\n .replace(\n /^/,\n `let w0=wgA[aIdx-${aw + 1}];let w1=wgA[aIdx-${aw}];let w2=wgA[aIdx-${aw - 1}];` +\n `let w3=wgA[aIdx-1];let w4=wgA[aIdx+1];` +\n `let w5=wgA[aIdx+${aw - 1}];let w6=wgA[aIdx+${aw}];let w7=wgA[aIdx+${aw + 1}];` +\n `if((w0&w1&w2&w3&w4&w5&w6&w7&128u)==0u){let excess=f32(here)-127.5;var sum=vec2f(0.0);var count=0.0;`,\n )\n .concat(\n `let scale=128.0/count;wgB[idx]=packSeed(i32(round(sum.x*scale)),i32(round(sum.y*scale)),true);}else{wgB[idx]=UNSEEDED_IN;}`,\n )\n}\n\nfunction buildTiledStep(\n inArr: 'wgA' | 'wgB',\n outArr: 'wgA' | 'wgB',\n inW: number,\n outW: number,\n outCount: number,\n step: number,\n offQ: number,\n threads: number,\n): string {\n const outOff = step - 1\n return (\n `for(var idx=lid;idx<${outCount}u;idx+=${threads}u){` +\n `let sx=i32(idx%${outW}u);let sy=i32(idx/${outW}u);` +\n `let gx=baseX+sx-${outOff};let gy=baseY+sy-${outOff};` +\n `if(u32(gx)>=w||u32(gy)>=h){${outArr}[idx]=UNSEEDED_OUT;continue;}` +\n `let src=(sy+${step})*${inW}+(sx+${step});let here=${inArr}[src];let inside=(here&1u)!=0u;var bx=0;var by=0;var bd=0xffffffffu;` +\n `if((here|1u)!=UNSEEDED_IN){let hs=bitcast<i32>(here);bx=(hs<<16u)>>17u;by=hs>>16u;bd=u32(bx*bx+by*by);}` +\n `for(var dy=-1;dy<=1;dy++){let r=src+dy*${step * inW};let oy=dy*${offQ};` +\n `for(var dx=-1;dx<=1;dx++){if(dx!=0||dy!=0){let raw=${inArr}[r+dx*${step}];` +\n `if((raw|1u)!=UNSEEDED_IN){let rs=bitcast<i32>(raw);let cx=((rs<<16u)>>17u)+dx*${offQ};let cy=(rs>>16u)+oy;let d=u32(cx*cx+cy*cy);if(d<bd){bd=d;bx=cx;by=cy;}}}}}` +\n `${outArr}[idx]=select(packSeed(bx,by,inside),select(UNSEEDED_OUT,UNSEEDED_IN,inside),bd==0xffffffffu);}` +\n `workgroupBarrier();`\n )\n}\n\nfunction buildTiledStoreWgsl(workgroupSize: 8 | 16): string {\n const wg = `${workgroupSize},${workgroupSize}`\n const threads = workgroupSize * workgroupSize\n const aw = workgroupSize + 16\n const aCount = aw * aw\n const sw = workgroupSize + 14\n const sCount = sw * sw\n const w4 = workgroupSize + 6\n const n4 = w4 * w4\n const w2 = workgroupSize + 2\n const n2 = w2 * w2\n const lxExpr = aw === 32 ? 'idx&31u' : `idx%${aw}u`\n const lyExpr = aw === 32 ? 'idx>>5u' : `idx/${aw}u`\n return (\n `var<workgroup> wgA:array<u32,${aCount}>;var<workgroup> wgB:array<u32,${sCount}>;` +\n `var<workgroup> tileFlags:atomic<u32>;var<workgroup> tileFlagsUniform:u32;\\n` +\n `@compute @workgroup_size(${wg}) fn tiledStoreMain(@builtin(global_invocation_id) id:vec3u,@builtin(workgroup_id) wid:vec3u,@builtin(local_invocation_index) lid:u32){\\n` +\n `let w=u32(params.width);let h=u32(params.height);let st=params.stride;` +\n `let baseX=i32(wid.x)*${workgroupSize};let baseY=i32(wid.y)*${workgroupSize};var localFlags=0u;` +\n `for(var idx=lid;idx<${aCount}u;idx+=${threads}u){` +\n `let lx=i32(${lxExpr});let ly=i32(${lyExpr});let gx=baseX+lx-8;let gy=baseY+ly-8;var val=0x180u;` +\n `if(u32(gx)<w&&u32(gy)<h){let a=rasterWords[gy*st+gx]>>24u;val=a;localFlags|=select(2u,1u,a>=128u);}` +\n `wgA[idx]=val;}` +\n `if(localFlags!=0u){atomicOr(&tileFlags,localFlags);}workgroupBarrier();` +\n `if(lid==0u){tileFlagsUniform=atomicLoad(&tileFlags);}let flags=workgroupUniformLoad(&tileFlagsUniform);` +\n `if(flags!=3u){if(id.x<w&&id.y<h){textureStore(outAtlas,vec2i(id.xy),vec4f(select(0.0,1.0,flags==1u),0.0,0.0,1.0));}return;}` +\n `for(var idx=lid;idx<${sCount}u;idx+=${threads}u){` +\n `let sx=i32(idx%${sw}u);let sy=i32(idx/${sw}u);let aIdx=(sy+1)*${aw}+(sx+1);let here=wgA[aIdx];` +\n `if((here^128u)>=128u){wgB[idx]=UNSEEDED_OUT;continue;}${buildTiledSeed(aw)}}workgroupBarrier();` +\n buildTiledStep('wgB', 'wgA', sw, w4, n4, 4, 512, threads) +\n buildTiledStep('wgA', 'wgB', w4, w2, n2, 2, 256, threads) +\n `if(id.x<w&&id.y<h){let lx=i32(id.x)-baseX;let ly=i32(id.y)-baseY;let src=(ly+1)*${w2}+(lx+1);` +\n `let here=wgB[src];let inside=(here&1u)!=0u;var bd=0xffffffffu;` +\n `if((here|1u)!=UNSEEDED_IN){let hs=bitcast<i32>(here);let bx=(hs<<16u)>>17u;let by=hs>>16u;bd=u32(bx*bx+by*by);}` +\n `for(var dy=-1;dy<=1;dy++){let r=src+dy*${w2};let oy=dy*128;` +\n `for(var dx=-1;dx<=1;dx++){if(dx!=0||dy!=0){let raw=wgB[r+dx];` +\n `if((raw|1u)!=UNSEEDED_IN){let rs=bitcast<i32>(raw);let cx=((rs<<16u)>>17u)+dx*128;let cy=(rs>>16u)+oy;let d=u32(cx*cx+cy*cy);if(d<bd){bd=d;}}}}}` +\n `var encoded=select(0.0,1.0,inside);if(bd!=0xffffffffu){let dist=sqrt(f32(bd));let scale=params.invPxRange*select(-0.0078125,0.0078125,inside);encoded=clamp(fma(dist,scale,0.5),0.0,1.0);}` +\n `textureStore(outAtlas,vec2i(id.xy),vec4f(encoded,0.0,0.0,1.0));}}`\n )\n}\n\n/**\n * @internal Builds the WGSL atlas passes for a given compute workgroup dimension (`8` for\n * 128-invocation compatibility mode, `16` for 256-invocation core devices) and output tier:\n * - Core WebGPU 1.0 (`directStore = false`): `seedMain` + `jumpMain` over 4-byte packed\n * fixed-point relative seeds (`u32`, `1/128` texel precision in `s15` + `s16` + 1-bit inside\n * flag, halving seed storage traffic vs `vec2f`), followed by `fullscreenVert` + `resolveFrag`\n * into an `r8unorm` render target.\n * - Optional `'texture-formats-tier1'` (`directStore = true`): replaces the final `step = 1`\n * jump write + render pass with `jumpStoreMain`, writing the resolved distance directly into\n * `texture_storage_2d<r8unorm, write>` inside the compute pass.\n *\n * Neighbours are visited in identical row-major order on interior and boundary paths alike so\n * ties and sums remain deterministic across devices and workgroup sizes.\n */\nexport function buildJfaWgsl(workgroupSize: 8 | 16, directStore: boolean): string {\n const wg = `${workgroupSize},${workgroupSize}`\n const coordHeader =\n 'let w=u32(params.width);let h=u32(params.height);if(id.x>=w||id.y>=h){return;}' +\n 'let x=i32(id.x);let y=i32(id.y);let wi=params.width;let hi=params.height;'\n return (\n `struct Params{width:i32,height:i32,stride:i32,invPxRange:f32}\\n` +\n `@group(0) @binding(0) var<uniform> params:Params;\\n` +\n `@group(0) @binding(1) var<storage,read> rasterWords:array<u32>;\\n` +\n `@group(0) @binding(1) var<storage,read> inputSeeds:array<u32>;\\n` +\n `@group(0) @binding(2) var<storage,read_write> outputSeeds:array<u32>;\\n` +\n (directStore\n ? '@group(0) @binding(2) var outAtlas:texture_storage_2d<r8unorm, write>;\\n'\n : '') +\n `const UNSEEDED_OUT:u32=0x7ffffffeu;\\nconst UNSEEDED_IN:u32=0x7fffffffu;\\n` +\n `fn packSeed(qx:i32,qy:i32,inside:bool)->u32{return(u32(qy)<<16u)|((u32(qx)&0x7fffu)<<1u)|select(0u,1u,inside);}\\n` +\n `@compute @workgroup_size(${wg}) fn seedMain(@builtin(global_invocation_id) id:vec3u){\\n` +\n coordHeader +\n `let index=id.y*w+id.x;let st=params.stride;let word=rasterWords[y*st+x];` +\n `if(word<0x80000000u){outputSeeds[index]=UNSEEDED_OUT;return;}` +\n `var sum=vec2f(0.0);var count=0.0;` +\n `if(x>=1&&x+1<wi&&y>=1&&y+1<hi){` +\n `let r0=(y-1)*st+x;let r1=y*st+x;let r2=(y+1)*st+x;` +\n `let w0=rasterWords[r0-1];let w1=rasterWords[r0];let w2=rasterWords[r0+1];` +\n `let w3=rasterWords[r1-1];let w4=rasterWords[r1+1];` +\n `let w5=rasterWords[r2-1];let w6=rasterWords[r2];let w7=rasterWords[r2+1];` +\n `if((w0&w1&w2&w3&w4&w5&w6&w7)<0x80000000u){let here=word>>24u;let excess=f32(here)-127.5;${buildSeedBody()}}` +\n `}else{let here=word>>24u;let excess=f32(here)-127.5;` +\n `for(var dy=-1;dy<=1;dy++){let ny=y+dy;if(u32(ny)<h){let row=ny*st+x;` +\n `for(var dx=-1;dx<=1;dx++){if((dx!=0||dy!=0)&&u32(x+dx)<w){let nw=rasterWords[row+dx];` +\n `if(nw<0x80000000u){let c=excess/f32(here-(nw>>24u));sum+=vec2f(c*f32(dx),c*f32(dy));count+=1.0;}}}}}}` +\n `if(count>0.0){let scale=128.0/count;outputSeeds[index]=packSeed(i32(round(sum.x*scale)),i32(round(sum.y*scale)),true);}` +\n `else{outputSeeds[index]=UNSEEDED_IN;}}\\n` +\n `@compute @workgroup_size(${wg}) fn jumpMain(@builtin(global_invocation_id) id:vec3u){\\n` +\n coordHeader +\n `let index=y*wi+x;let here=inputSeeds[index];let inside=(here&1u)!=0u;var bestX=0;var bestY=0;var bestDist=0xffffffffu;` +\n `if((here|1u)!=UNSEEDED_IN){let hs=bitcast<i32>(here);bestX=(hs<<16u)>>17u;bestY=hs>>16u;bestDist=u32(bestX*bestX+bestY*bestY);}` +\n `let s=params.stride;let stepQ=s<<7u;${buildJumpBody('s', 'stepQ', true)}` +\n `if(bestDist==0xffffffffu){outputSeeds[index]=select(UNSEEDED_OUT,UNSEEDED_IN,inside);}` +\n `else{outputSeeds[index]=packSeed(bestX,bestY,inside);}}\\n` +\n (directStore\n ? `@compute @workgroup_size(${wg}) fn jumpStoreMain(@builtin(global_invocation_id) id:vec3u){\\n` +\n coordHeader +\n `let index=y*wi+x;let here=inputSeeds[index];let inside=(here&1u)!=0u;var bestDist=0xffffffffu;` +\n `if((here|1u)!=UNSEEDED_IN){let hs=bitcast<i32>(here);let bx=(hs<<16u)>>17u;let by=hs>>16u;bestDist=u32(bx*bx+by*by);}` +\n buildJumpBody('1', '128', false) +\n `var encoded=select(0.0,1.0,inside);` +\n `if(bestDist!=0xffffffffu){let dist=sqrt(f32(bestDist));let scale=params.invPxRange*select(-0.0078125,0.0078125,inside);encoded=clamp(fma(dist,scale,0.5),0.0,1.0);}` +\n `textureStore(outAtlas,vec2i(x,y),vec4f(encoded,0.0,0.0,1.0));}\\n` +\n buildTiledStoreWgsl(workgroupSize)\n : `@vertex fn fullscreenVert(@builtin(vertex_index) vid:u32)->@builtin(position) vec4f{\\n` +\n `let x=f32((vid<<1u)&2u);let y=f32(vid&2u);return vec4f(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0);}\\n` +\n `@fragment fn resolveFrag(@builtin(position) pos:vec4f)->@location(0) vec4f{\\n` +\n `let pixel=vec2i(pos.xy);let raw=inputSeeds[pixel.y*params.width+pixel.x];let inside=(raw&1u)!=0u;` +\n `if((raw|1u)==UNSEEDED_IN){return vec4f(select(0.0,1.0,inside),0.0,0.0,1.0);}` +\n `let rs=bitcast<i32>(raw);let qx=(rs<<16u)>>17u;let qy=rs>>16u;` +\n `let dist=sqrt(f32(qx*qx+qy*qy));let scale=params.invPxRange*select(-0.0078125,0.0078125,inside);` +\n `return vec4f(clamp(fma(dist, scale, 0.5), 0.0, 1.0), 0.0, 0.0, 1.0);}`)\n )\n}\n\n/** @internal Default compatibility-mode (`8×8`, Core WebGPU 1.0) WGSL atlas shader. */\nexport const JFA_WGSL = buildJfaWgsl(8, false)\n\n/** @internal The mip blit (`mipVert`, `mipFrag`) the Three-free entry appends to `JFA_WGSL`. */\nexport const MIP_WGSL = /* wgsl */ `\n@group(0) @binding(0) var mipSrc: texture_2d<f32>;\n@group(0) @binding(1) var mipSampler: sampler;\n\nstruct MipVarying {\n @builtin(position) pos: vec4f,\n @location(0) uv: vec2f,\n}\n\n@vertex\nfn mipVert(@builtin(vertex_index) vid: u32) -> MipVarying {\n let x = f32((vid << 1u) & 2u);\n let y = f32(vid & 2u);\n var out: MipVarying;\n out.pos = vec4f(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0);\n out.uv = vec2f(x, y);\n return out;\n}\n\n@fragment\nfn mipFrag(in: MipVarying) -> @location(0) vec4f {\n return textureSampleLevel(mipSrc, mipSampler, in.uv, 0.0);\n}\n`\n"],"mappings":"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"}
@@ -1,4 +1,6 @@
1
1
  import type { ColorGlyphMode, GlyphRequest, RasterAtlas } from '../types.js';
2
+ import { createCanvas, isColorCandidate, setFontContext, waitForFonts } from '../dom/fontCanvas.js';
3
+ export { createCanvas, isColorCandidate, setFontContext, waitForFonts };
2
4
  export interface RasterizeOptions {
3
5
  /** Colour-glyph detection; defaults to 'emoji'. */
4
6
  colorGlyphs?: ColorGlyphMode;
@@ -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,43 +15,9 @@ 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
- const nextFont = setFontContext(context, request, shaping, lastFont);
20
+ setFontContext(context, request, shaping, lastFont);
59
21
  const metrics = context.measureText(request.character);
60
22
  const slice = request.shaping?.slice;
61
23
  const from = slice?.[0] ?? 0;
@@ -77,7 +39,7 @@ function measureGlyph(context, request, padding, shaping, candidate = false, las
77
39
  metrics.actualBoundingBoxRight,
78
40
  metrics.actualBoundingBoxAscent
79
41
  ];
80
- return [{
42
+ return {
81
43
  request,
82
44
  width: Math.max(2, Math.ceil(planeX1 - planeX0) + 2),
83
45
  height: Math.max(2, Math.ceil(planeY1 - planeY0) + 2),
@@ -90,8 +52,9 @@ function measureGlyph(context, request, padding, shaping, candidate = false, las
90
52
  drawOffsetX,
91
53
  ...ink?.every(Number.isFinite) ? { ink } : {},
92
54
  x: 0,
93
- y: 0
94
- }, nextFont];
55
+ y: 0,
56
+ flags: 0
57
+ };
95
58
  }
96
59
  /**
97
60
  * @internal The slot of a glyph drawn at (glyph.x, glyph.y) of a `width`×`height` atlas. The
@@ -105,31 +68,41 @@ function slotOf(glyph, padding, bakeSize, width, height, banded, uncoloured) {
105
68
  const planeY0 = glyph.planeY0 + .5;
106
69
  const planeX1 = glyph.planeX1 - (slice && slice[1] < 1 ? glyph.planeX1 - glyph.advance : .5);
107
70
  const planeY1 = glyph.planeY1 - .5;
108
- const uv = (x0, y0, x1, y1) => ({
109
- u0: (glyph.x + 1 + x0 - glyph.planeX0) / width,
110
- v0: (glyph.y + 1 + glyph.planeY1 - y1) / height,
111
- u1: (glyph.x + 1 + x1 - glyph.planeX0) / width,
112
- v1: (glyph.y + 1 + glyph.planeY1 - y0) / height
113
- });
71
+ const baseU = glyph.x + 1 - glyph.planeX0;
72
+ const baseV = glyph.y + 1 + glyph.planeY1;
73
+ const invW = 1 / width;
74
+ const invH = 1 / height;
114
75
  const ink = banded ? void 0 : glyph.ink;
115
- const reach = padding / 2 + 2 + .006 * bakeSize;
116
- const sx0 = ink ? Math.max(planeX0, Math.floor(ink[0] - reach)) : 0;
117
- const sy0 = ink ? Math.max(planeY0, Math.floor(ink[1] - reach)) : 0;
118
- const sx1 = ink ? Math.min(planeX1, Math.ceil(ink[2] + reach)) : 0;
119
- const sy1 = ink ? Math.min(planeY1, Math.ceil(ink[3] + reach)) : 0;
76
+ let support;
77
+ if (ink) {
78
+ const reach = padding / 2 + 2 + .006 * bakeSize;
79
+ const sx0 = Math.max(planeX0, Math.floor(ink[0] - reach));
80
+ const sy0 = Math.max(planeY0, Math.floor(ink[1] - reach));
81
+ const sx1 = Math.min(planeX1, Math.ceil(ink[2] + reach));
82
+ const sy1 = Math.min(planeY1, Math.ceil(ink[3] + reach));
83
+ if (sx1 > sx0 && sy1 > sy0) support = {
84
+ u0: (baseU + sx0) * invW,
85
+ v0: (baseV - sy1) * invH,
86
+ u1: (baseU + sx1) * invW,
87
+ v1: (baseV - sy0) * invH
88
+ };
89
+ }
120
90
  return {
121
91
  ...uncoloured ? { color: false } : {},
122
92
  key: glyph.request.key,
123
93
  character: glyph.request.character,
124
94
  fontKey: glyph.request.font.key,
125
- ...uv(planeX0, planeY0, planeX1, planeY1),
95
+ u0: (baseU + planeX0) * invW,
96
+ v0: (baseV - planeY1) * invH,
97
+ u1: (baseU + planeX1) * invW,
98
+ v1: (baseV - planeY0) * invH,
126
99
  planeX0,
127
100
  planeY0,
128
101
  planeX1,
129
102
  planeY1,
130
103
  descent: glyph.descent,
131
104
  advance: glyph.advance,
132
- ...ink && sx1 > sx0 && sy1 > sy0 ? { support: uv(sx0, sy0, sx1, sy1) } : {}
105
+ ...support ? { support } : {}
133
106
  };
134
107
  }
135
108
  /**
@@ -221,6 +194,15 @@ function packShelves(glyphs, width, maxSize) {
221
194
  var skylineX = /* @__PURE__ */ new Int32Array(256);
222
195
  var skylineY = /* @__PURE__ */ new Int32Array(256);
223
196
  var skylineW = /* @__PURE__ */ new Int32Array(256);
197
+ function shiftSkyline(to, from, len) {
198
+ skylineX.copyWithin(to, from, len);
199
+ skylineY.copyWithin(to, from, len);
200
+ skylineW.copyWithin(to, from, len);
201
+ }
202
+ function recordSkylineOverflow(width, maxSize, wasteBudget) {
203
+ lastOverflowWidth = Math.min(lastOverflowWidth, width + Math.ceil(-wasteBudget / maxSize));
204
+ return null;
205
+ }
224
206
  /** Bottom-left skyline packing fills the vertical gaps that fixed-height shelves leave behind. */
225
207
  function packSkyline(glyphs, width, maxSize) {
226
208
  const needed = glyphs.length + 2;
@@ -238,16 +220,10 @@ function packSkyline(glyphs, width, maxSize) {
238
220
  let skylineLen = 1;
239
221
  let usedWidth = 0;
240
222
  let usedHeight = 0;
241
- const shift = (to, from) => {
242
- sx.copyWithin(to, from, skylineLen);
243
- sy.copyWithin(to, from, skylineLen);
244
- sw.copyWithin(to, from, skylineLen);
245
- };
246
223
  const minH = glyphs[glyphs.length - 1].height;
247
224
  let wasteBudget = width * maxSize;
248
- const over = () => (lastOverflowWidth = Math.min(lastOverflowWidth, width + Math.ceil(-wasteBudget / maxSize)), null);
249
225
  for (const g of glyphs) wasteBudget -= g.width * g.height;
250
- if (wasteBudget < 0) return over();
226
+ if (wasteBudget < 0) return recordSkylineOverflow(width, maxSize, wasteBudget);
251
227
  for (const glyph of glyphs) {
252
228
  const gw = glyph.width;
253
229
  const gh = glyph.height;
@@ -295,7 +271,7 @@ function packSkyline(glyphs, width, maxSize) {
295
271
  }
296
272
  }
297
273
  if (maxAllowedY >= 0 && usedWidth + gw < lastOverflowWidth) lastOverflowWidth = usedWidth + gw;
298
- if (bestIndex < 0 || (wasteBudget -= bestWaste + (bestBottom > maxSize - minH ? gw * (maxSize - bestBottom) : 0)) < 0) return bestIndex < 0 ? null : over();
274
+ if (bestIndex < 0 || (wasteBudget -= bestWaste + (bestBottom > maxSize - minH ? gw * (maxSize - bestBottom) : 0)) < 0) return bestIndex < 0 ? null : recordSkylineOverflow(width, maxSize, wasteBudget);
299
275
  const gx = sx[bestIndex];
300
276
  const right = gx + gw;
301
277
  glyph.x = gx;
@@ -320,7 +296,7 @@ function packSkyline(glyphs, width, maxSize) {
320
296
  newCount = 0;
321
297
  }
322
298
  const delta = newCount - (cursor - bestIndex);
323
- if (delta !== 0 && cursor < skylineLen) shift(cursor + delta, cursor);
299
+ if (delta !== 0 && cursor < skylineLen) shiftSkyline(cursor + delta, cursor, skylineLen);
324
300
  skylineLen += delta;
325
301
  if (newCount) {
326
302
  sx[bestIndex] = gx;
@@ -366,53 +342,6 @@ function isBetterPacking(candidate, current) {
366
342
  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
343
  }
368
344
  /**
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
345
  * Rasterizes every required font-face/character or emoji-sequence pair into one tightly packed
417
346
  * alpha atlas. The output is a transient mask; the retained texture is a
418
347
  * single-channel distance field produced by the CPU or WebGPU compute backend.
@@ -433,28 +362,30 @@ async function rasterizeGlyphAtlas(document, requests, options = {}) {
433
362
  const shaping = shapingModule?.setShapingContext;
434
363
  throwIfAborted(options.signal);
435
364
  const canvas = createCanvas(document);
365
+ let returned = false;
436
366
  try {
437
367
  const previous = options.previousAtlas?.bakeSize === bakeSize && options.previousAtlas.pxRange === padding ? options.previousAtlas.glyphs : void 0;
438
- const context = canvas.getContext("2d", { willReadFrequently: !options.gpuUpload || requests.some((request) => isColorCandidate(request, options.colorGlyphs) && (request.shape !== void 0 || (options.colorGlyphs === "all" || isEmojiGrapheme(request.character)) && previous?.get(request.key)?.color !== false)) });
368
+ const willReadFrequently = !options.gpuUpload || requests.some((request) => isColorCandidate(request, options.colorGlyphs) && (request.shape !== void 0 || (options.colorGlyphs === "all" || isEmojiGrapheme(request.character)) && previous?.get(request.key)?.color !== false));
369
+ const context = canvas.getContext("2d", { willReadFrequently });
439
370
  if (!context) throw new Error("rasterizeGlyphAtlas: Canvas 2D is unavailable");
440
371
  const packingLimit = maxAtlasSize - maxAtlasSize % 4;
441
372
  let lastFont = null;
442
373
  const measured = requests.map((request) => {
443
374
  if (request.shape) return shapes.measureShape(request, bakeSize, padding);
444
- const [glyph, nextFont] = measureGlyph(context, request, padding, shaping, isColorCandidate(request, options.colorGlyphs), lastFont);
445
- lastFont = nextFont;
375
+ const glyph = measureGlyph(context, request, padding, shaping, isColorCandidate(request, options.colorGlyphs), lastFont);
376
+ lastFont = request.font;
446
377
  return glyph;
447
378
  });
448
379
  measured.sort((a, b) => b.height - a.height || b.width - a.width || (a.request.key < b.request.key ? -1 : a.request.key > b.request.key ? 1 : 0));
449
- const banded = /* @__PURE__ */ new Set();
450
- const uncoloured = /* @__PURE__ */ new Set();
380
+ let bandedCount = 0;
451
381
  const tested = [];
452
382
  for (const glyph of measured) {
453
383
  if (!isColorCandidate(glyph.request, options.colorGlyphs)) continue;
454
384
  const known = glyph.request.shape ? void 0 : previous?.get(glyph.request.key)?.color;
455
- if (known === false) uncoloured.add(glyph);
385
+ if (known === false) glyph.flags = 2;
456
386
  else {
457
- banded.add(glyph);
387
+ glyph.flags = 1;
388
+ bandedCount++;
458
389
  if (!glyph.request.shape && known === void 0) tested.push(glyph);
459
390
  }
460
391
  }
@@ -462,27 +393,39 @@ async function rasterizeGlyphAtlas(document, requests, options = {}) {
462
393
  shapes.drawShapeSlot(context, glyph, bakeSize);
463
394
  });
464
395
  const drawGlyph = (glyph, fill) => {
465
- painter.draw(glyph, !glyph.request.shape && !banded.has(glyph), fill);
396
+ painter.draw(glyph, !glyph.request.shape && (glyph.flags & 1) === 0, fill);
466
397
  };
467
- const colorGlyphs = banded.size ? await import("./colorGlyphs.js") : void 0;
398
+ const colorGlyphs = bandedCount ? await import("./colorGlyphs.js") : void 0;
468
399
  throwIfAborted(options.signal);
469
400
  const scratch = tested.length ? packShelves(tested, packingLimit, packingLimit) : null;
470
401
  if (scratch) {
471
- canvas.width = scratch.width;
472
- canvas.height = scratch.height;
473
- painter.reset();
474
- const paint = (fill) => {
475
- context.clearRect(0, 0, canvas.width, canvas.height);
476
- for (const glyph of tested) drawGlyph(glyph, fill);
477
- return context.getImageData(0, 0, canvas.width, canvas.height).data;
478
- };
479
- const dark = paint("#000");
480
- const { colored } = colorGlyphs.encodeColorBand(paint("#fff"), dark, canvas.width, canvas.height, 0, tested);
481
- tested.forEach((glyph, index) => {
482
- if (colored[index]) return;
483
- banded.delete(glyph);
484
- uncoloured.add(glyph);
485
- });
402
+ const scratchCanvas = willReadFrequently ? null : createCanvas(document);
403
+ try {
404
+ const targetCanvas = scratchCanvas ?? canvas;
405
+ targetCanvas.width = scratch.width;
406
+ targetCanvas.height = scratch.height;
407
+ const targetContext = scratchCanvas ? scratchCanvas.getContext("2d", { willReadFrequently: true }) : context;
408
+ if (!targetContext) throw new Error("rasterizeGlyphAtlas: Canvas 2D is unavailable");
409
+ const targetPainter = scratchCanvas ? glyphPainter(targetContext, shaping, options.signal) : painter;
410
+ targetPainter.reset();
411
+ const paint = (fill) => {
412
+ targetContext.clearRect(0, 0, scratch.width, scratch.height);
413
+ for (const glyph of tested) targetPainter.draw(glyph, false, fill);
414
+ return targetContext.getImageData(0, 0, scratch.width, scratch.height).data;
415
+ };
416
+ const dark = paint("#000");
417
+ const { colored } = colorGlyphs.encodeColorBand(paint("#fff"), dark, scratch.width, scratch.height, 0, tested);
418
+ tested.forEach((glyph, index) => {
419
+ if (colored[index]) return;
420
+ glyph.flags = 2;
421
+ });
422
+ } finally {
423
+ if (scratchCanvas) {
424
+ scratchCanvas.width = 0;
425
+ scratchCanvas.height = 0;
426
+ scratchCanvas.remove();
427
+ }
428
+ }
486
429
  }
487
430
  const textRows = [];
488
431
  const shapeRows = [];
@@ -494,7 +437,7 @@ async function rasterizeGlyphAtlas(document, requests, options = {}) {
494
437
  totalArea += glyph.width * glyph.height;
495
438
  if (glyph.width > widestGlyph) widestGlyph = glyph.width;
496
439
  if (glyph.width > packingLimit || glyph.height > packingLimit) exceedsLimit = true;
497
- if (banded.has(glyph)) band.push(glyph);
440
+ if (glyph.flags & 1) band.push(glyph);
498
441
  else if (glyph.request.shape) shapeRows.push(glyph);
499
442
  else textRows.push(glyph);
500
443
  }
@@ -516,14 +459,14 @@ async function rasterizeGlyphAtlas(document, requests, options = {}) {
516
459
  if (!impossible && measured.length > 0) {
517
460
  const minRequiredLimit = groups.reduce((sum, g) => sum + align4(g[0].height), 0);
518
461
  const minimumWidth = Math.min(packingLimit, align4(Math.max(widestGlyph, Math.ceil(totalArea / packingLimit))));
519
- const widthStep = align4(Math.max(4, Math.ceil((packingLimit - minimumWidth) / 64)));
462
+ const packerCount = groups.some((g) => g[0].height !== g[g.length - 1].height) ? 2 : 1;
520
463
  const maxHeightFor = (width) => best ? Math.min(packingLimit, Math.floor(best.width * best.height / width)) : packingLimit;
521
464
  const nextW = [minimumWidth, minimumWidth];
522
- for (let width = minimumWidth;; width = Math.min(packingLimit, width + widthStep)) {
465
+ for (let width = minimumWidth; width <= packingLimit; width += 4) {
523
466
  throwIfAborted(options.signal);
524
467
  if (maxHeightFor(width) < minRequiredLimit) break;
525
468
  const minH = align4(Math.max(minRequiredLimit, Math.ceil(totalArea / width)));
526
- for (let i = 0; i < 2; i++) {
469
+ for (let i = 0; i < packerCount; i++) {
527
470
  if (width < nextW[i]) continue;
528
471
  const maxCandidateHeight = maxHeightFor(width);
529
472
  if (minH > maxCandidateHeight) break;
@@ -532,7 +475,6 @@ async function rasterizeGlyphAtlas(document, requests, options = {}) {
532
475
  nextW[i] = lastOverflowWidth;
533
476
  if (candidate && (!best || isBetterPacking(candidate, best))) best = rememberPacking(measured, candidate, bestPositions);
534
477
  }
535
- if (width === packingLimit) break;
536
478
  }
537
479
  }
538
480
  if (!best) {
@@ -570,7 +512,7 @@ async function rasterizeGlyphAtlas(document, requests, options = {}) {
570
512
  canvas.width = best.width;
571
513
  canvas.height = best.height;
572
514
  painter.reset();
573
- context.clearRect(0, 0, canvas.width, canvas.height);
515
+ if (scratch && willReadFrequently) context.clearRect(0, 0, canvas.width, canvas.height);
574
516
  const bandTop = band.length ? topOf(band) : 0;
575
517
  const bandHeight = canvas.height - bandTop;
576
518
  let black;
@@ -580,10 +522,23 @@ async function rasterizeGlyphAtlas(document, requests, options = {}) {
580
522
  context.clearRect(0, bandTop, canvas.width, bandHeight);
581
523
  }
582
524
  const glyphSlots = /* @__PURE__ */ new Map();
525
+ const byFont = /* @__PURE__ */ new Map();
526
+ const shapeGlyphs = [];
583
527
  for (const glyph of measured) {
584
- drawGlyph(glyph);
585
- glyphSlots.set(glyph.request.key, slotOf(glyph, padding, bakeSize, canvas.width, canvas.height, banded.has(glyph), uncoloured.has(glyph)));
528
+ if (glyph.request.shape) {
529
+ shapeGlyphs.push(glyph);
530
+ continue;
531
+ }
532
+ let group = byFont.get(glyph.request.font.key);
533
+ if (!group) byFont.set(glyph.request.font.key, group = []);
534
+ group.push(glyph);
586
535
  }
536
+ const drawAndRecord = (glyph) => {
537
+ drawGlyph(glyph);
538
+ glyphSlots.set(glyph.request.key, slotOf(glyph, padding, bakeSize, canvas.width, canvas.height, (glyph.flags & 1) !== 0, (glyph.flags & 2) !== 0));
539
+ };
540
+ for (const group of byFont.values()) for (const glyph of group) drawAndRecord(glyph);
541
+ for (const glyph of shapeGlyphs) drawAndRecord(glyph);
587
542
  let colorBand;
588
543
  if (black) {
589
544
  const white = context.getImageData(0, bandTop, canvas.width, bandHeight).data;
@@ -629,6 +584,7 @@ async function rasterizeGlyphAtlas(document, requests, options = {}) {
629
584
  rowHeight
630
585
  });
631
586
  }
587
+ returned = true;
632
588
  return {
633
589
  ...colorBand ? { colorBand } : {},
634
590
  ...shapeTop !== void 0 ? { shapeTop } : {},
@@ -640,6 +596,10 @@ async function rasterizeGlyphAtlas(document, requests, options = {}) {
640
596
  glyphs: glyphSlots
641
597
  };
642
598
  } finally {
599
+ if (!returned) {
600
+ canvas.width = 0;
601
+ canvas.height = 0;
602
+ }
643
603
  canvas.remove();
644
604
  }
645
605
  }