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.
- package/README.md +168 -85
- package/THIRD_PARTY_NOTICES.md +3 -0
- package/dist/assets/{cpuSdf.worker-Du9o8q4p.js → cpuSdf.worker-xS57yQbP.js} +13 -11
- package/dist/assets/cpuSdf.worker-xS57yQbP.js.map +1 -0
- package/dist/atlas/appendAtlas.js +2 -1
- package/dist/atlas/appendAtlas.js.map +1 -1
- package/dist/atlas/buildAtlas.js +3 -14
- package/dist/atlas/buildAtlas.js.map +1 -1
- package/dist/atlas/cpuSdf.js +12 -10
- package/dist/atlas/cpuSdf.js.map +1 -1
- package/dist/atlas/cpuWorker.js +1 -1
- package/dist/atlas/cpuWorker.js.map +1 -1
- package/dist/atlas/gpuAtlas.d.ts +7 -6
- package/dist/atlas/gpuAtlas.js +280 -145
- package/dist/atlas/gpuAtlas.js.map +1 -1
- package/dist/atlas/jfaWgsl.js +201 -73
- package/dist/atlas/jfaWgsl.js.map +1 -1
- package/dist/atlas/rasterize.d.ts +2 -0
- package/dist/atlas/rasterize.js +2 -87
- package/dist/atlas/rasterize.js.map +1 -1
- package/dist/dom/DomSdf.js +66 -15
- package/dist/dom/DomSdf.js.map +1 -1
- package/dist/dom/DomSlug.d.ts +26 -0
- package/dist/dom/DomSlug.js +640 -0
- package/dist/dom/DomSlug.js.map +1 -0
- package/dist/dom/SlugText.d.ts +18 -0
- package/dist/dom/SlugText.js +94 -0
- package/dist/dom/SlugText.js.map +1 -0
- package/dist/dom/Text.js +4 -67
- package/dist/dom/Text.js.map +1 -1
- package/dist/dom/fontCanvas.d.ts +2 -0
- package/dist/dom/fontCanvas.js +101 -0
- package/dist/dom/fontCanvas.js.map +1 -0
- package/dist/dom/layoutSignature.js +29 -2
- package/dist/dom/layoutSignature.js.map +1 -1
- package/dist/dom/snapshot.js +251 -96
- package/dist/dom/snapshot.js.map +1 -1
- package/dist/dom/textHost.d.ts +11 -0
- package/dist/dom/textHost.js +68 -0
- package/dist/dom/textHost.js.map +1 -0
- package/dist/slug/SlugMaterial.d.ts +3 -2
- package/dist/slug/SlugMaterial.js +28 -2
- package/dist/slug/SlugMaterial.js.map +1 -1
- package/dist/slug/coverage.d.ts +1 -1
- package/dist/slug/coverage.js +1 -1
- package/dist/slug/coverage.js.map +1 -1
- package/dist/slug/preprocessCore.d.ts +1 -2
- package/dist/slug/preprocessCore.js +39 -16
- package/dist/slug/preprocessCore.js.map +1 -1
- package/dist/slug/runtime.js +6 -4
- package/dist/slug/runtime.js.map +1 -1
- package/dist/slug/standaloneRuntime.d.ts +39 -0
- package/dist/slug/standaloneRuntime.js +140 -0
- package/dist/slug/standaloneRuntime.js.map +1 -0
- package/dist/slug/truetype.d.ts +22 -0
- package/dist/slug/truetype.js +494 -0
- package/dist/slug/truetype.js.map +1 -0
- package/dist/slug-vanilla.d.ts +364 -0
- package/dist/slug-vanilla.js +1461 -0
- package/dist/slug-vanilla.js.map +1 -0
- package/dist/slug.d.ts +21 -0
- package/dist/slug.js +19 -0
- package/dist/text/GlyphTextMaterial.d.ts +11 -11
- package/dist/text/GlyphTextMaterial.js +98 -29
- package/dist/text/GlyphTextMaterial.js.map +1 -1
- package/dist/text/SdfTextMaterial.d.ts +5 -4
- package/dist/text/SdfTextMaterial.js +22 -4
- package/dist/text/SdfTextMaterial.js.map +1 -1
- package/dist/types.d.ts +63 -14
- package/dist/vanilla.d.ts +3 -0
- package/dist/vanilla.js +132 -59
- package/dist/vanilla.js.map +1 -1
- package/dist/windfoil/WindfoilMaterial.d.ts +2 -1
- package/dist/windfoil/WindfoilMaterial.js +8 -1
- package/dist/windfoil/WindfoilMaterial.js.map +1 -1
- package/dist/windfoil/abortable.d.ts +2 -0
- package/dist/windfoil/abortable.js +26 -0
- package/dist/windfoil/abortable.js.map +1 -0
- package/dist/windfoil/color.js +2 -1
- package/dist/windfoil/color.js.map +1 -1
- package/dist/windfoil/coverage.d.ts +3 -20
- package/dist/windfoil/coverage.js +7 -20
- package/dist/windfoil/coverage.js.map +1 -1
- package/dist/windfoil/emoji.js +1 -1
- package/dist/windfoil/emoji.js.map +1 -1
- package/dist/windfoil/emojiMetrics.js +1 -1
- package/dist/windfoil/emojiMetrics.js.map +1 -1
- package/dist/windfoil/geometry.js +100 -33
- package/dist/windfoil/geometry.js.map +1 -1
- package/dist/windfoil/layerGrid.js +14 -10
- package/dist/windfoil/layerGrid.js.map +1 -1
- package/dist/windfoil/layerNormalization.d.ts +1 -1
- package/dist/windfoil/layerNormalization.js +1 -1
- package/dist/windfoil/layerNormalization.js.map +1 -1
- package/dist/windfoil/outlineValidation.d.ts +86 -0
- package/dist/windfoil/outlineValidation.js +65 -0
- package/dist/windfoil/outlineValidation.js.map +1 -0
- package/dist/windfoil/preprocess.js +3 -2
- package/dist/windfoil/preprocess.js.map +1 -1
- package/dist/windfoil/preprocessCore.d.ts +4 -85
- package/dist/windfoil/preprocessCore.js +210 -206
- package/dist/windfoil/preprocessCore.js.map +1 -1
- package/dist/windfoil/requests.js +1 -1
- package/dist/windfoil/requests.js.map +1 -1
- package/dist/windfoil/runtime.d.ts +2 -1
- package/dist/windfoil/runtime.js +3 -2
- package/dist/windfoil/runtime.js.map +1 -1
- package/dist/windfoil/shapeResources.js +2 -1
- package/dist/windfoil/shapeResources.js.map +1 -1
- package/dist/windfoil/shapes.js +1 -1
- package/dist/windfoil/skirt.d.ts +22 -0
- package/dist/windfoil/skirt.js +20 -0
- package/dist/windfoil/skirt.js.map +1 -0
- package/dist/windfoil/storage.d.ts +2 -2
- package/dist/windfoil/storage.js +1 -22
- package/dist/windfoil/storage.js.map +1 -1
- package/dist/windfoil/trace/contours.d.ts +0 -5
- package/dist/windfoil/trace/contours.js +81 -114
- package/dist/windfoil/trace/contours.js.map +1 -1
- package/dist/windfoil/trace/fit.d.ts +0 -6
- package/dist/windfoil/trace/fit.js +304 -308
- package/dist/windfoil/trace/fit.js.map +1 -1
- package/dist/windfoil/trace/outline.js +10 -10
- package/dist/windfoil/trace/outline.js.map +1 -1
- package/dist/windfoil/trace/types.d.ts +5 -3
- package/dist/windfoil/tracedOutlines.d.ts +37 -1
- package/dist/windfoil/tracedOutlines.js +172 -33
- package/dist/windfoil/tracedOutlines.js.map +1 -1
- package/package.json +57 -8
- package/skills/ultra-text/SKILL.md +114 -0
- package/skills/ultra-text/references/frameworks.md +43 -0
- package/skills/ultra-text/references/three-tsl.md +78 -0
- package/skills/ultra-text/references/vanilla-webgpu.md +95 -0
- package/dist/assets/cpuSdf.worker-Du9o8q4p.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"appendAtlas.js","names":[],"sources":["../../src/atlas/appendAtlas.ts"],"sourcesContent":["import {\n Box2,\n DataTexture,\n RedFormat,\n UnsignedByteType,\n Vector2,\n type Texture,\n type WebGPURenderer,\n} from 'three/webgpu'\n\nimport type { DomSdfOptions, GlyphRequest, SdfAtlas } from '../types.js'\nimport { alphaOfRgba, encodeSdfFromAlpha } from './cpuSdf.js'\nimport { atlasDevice, encodeGpuSdf, generateAtlasMips, type AtlasGpuTexture } from './gpuAtlas.js'\nimport {\n appendCursors,\n createCanvas,\n glyphPainter,\n isColorCandidate,\n measureGlyph,\n packShelves,\n slotOf,\n waitForFonts,\n type MeasuredGlyph,\n} from './rasterize.js'\n\n/**\n * A larger patch is left to a full rebuild, which spreads its work better: the patch's exact\n * transform runs on the page's thread, where 2^18 texels (about twenty 96 px glyphs) take a\n * few milliseconds.\n */\nconst PATCH_TEXELS = 1 << 18\n\n/** The new glyphs of one atlas row and where they go: never a box that spans two rows. */\ninterface Run {\n readonly x: number\n readonly y: number\n /** First row of the run on the patch canvas, where the runs are stacked. */\n readonly top: number\n width: number\n height: number\n readonly glyphs: MeasuredGlyph[]\n}\n\n/**\n * @internal Draws the text glyphs of a `capture` that `atlas` lacks into the free text rows of\n * its live texture, so a rebuild keeps the texture and every material that samples it. Only\n * the new glyphs are measured and drawn, row by row of the atlas, on one small canvas, by the\n * full build's rules and slot formulas (`glyphPainter`, `slotOf`). Their distance field comes\n * from the atlas's own encoder, a jump flood of the patch alone for a GPU atlas and the exact\n * transform for a CPU one, so the new slots hold the bytes a full build would give them; each\n * row's box is then copied into the texture, whose mipmaps three regenerates, and a CPU\n * atlas's bytes follow.\n *\n * Resolves with the next wrapper: the same texture, colour layer, shape rows and `dispose`,\n * with the old slots and the new ones; its own cursor is recorded under its glyph map, so it\n * becomes the live one only when the caller commits that wrapper. Slots the capture no longer\n * uses stay in the texture until the next full build compacts it. Resolves `null`, having\n * written nothing the caller must undo, when the caller must rebuild in full instead: a shape,\n * a glyph that classifies as colour, an atlas without a cursor or with a lowered adaptive bake\n * size, a patch past its texel budget, or glyphs that do not fit. What an aborted patch already\n * copied lies in rows no slot samples, and the next patch overwrites it.\n */\nexport async function appendGlyphs(\n renderer: WebGPURenderer,\n document: Document,\n atlas: SdfAtlas,\n capture: readonly GlyphRequest[],\n options: Pick<DomSdfOptions, 'colorGlyphs' | 'bakeSize'>,\n signal: AbortSignal,\n): Promise<SdfAtlas | null> {\n const cursor = appendCursors.get(atlas.glyphs)\n const colorGlyphs = options.colorGlyphs ?? 'emoji'\n const requests = capture.filter((request) => !atlas.glyphs.has(request.key))\n if (\n cursor?.bakeSize !== (options.bakeSize ?? 96) ||\n cursor.colorGlyphs !== colorGlyphs ||\n cursor.width !== atlas.width ||\n cursor.height !== atlas.height ||\n !requests.length ||\n requests.some((request) => request.shape !== undefined)\n )\n return null\n const [, shapingModule] = await Promise.all([\n waitForFonts(document, requests, signal),\n requests.some((request) => request.shaping) ? import('../dom/browserShaping.js') : undefined,\n ])\n signal.throwIfAborted()\n const shaping = shapingModule?.setShapingContext\n const { width, height, bakeSize, pxRange: padding } = cursor\n const canvas = createCanvas(document)\n try {\n // A GPU patch reads at most a tiny candidate scratch pack and uploads the patch texture.\n const context = canvas.getContext('2d', {\n willReadFrequently: atlas.mode !== 'gpu',\n })\n if (!context) return null\n let lastFont: GlyphRequest['font'] | null = null\n const fresh = requests.map((request) => {\n const [glyph, font] = measureGlyph(\n context,\n request,\n padding,\n shaping,\n isColorCandidate(request, colorGlyphs),\n lastFont,\n )\n lastFont = font\n return glyph\n })\n fresh.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 // The patch stacks its glyphs' rows, so it is never smaller than their summed area: a batch\n // past the budget is refused before its colour candidates are drawn and read back.\n let area = 0\n for (const glyph of fresh) area += glyph.width * glyph.height\n if (area > PATCH_TEXELS) return null\n const painter = glyphPainter(context, shaping, signal)\n\n // Colour candidates are classified as in a full build, on a pack of their own: one that\n // keeps its colour needs the colour band, which only a full build can grow.\n const candidates = fresh.filter((glyph) => isColorCandidate(glyph.request, colorGlyphs))\n if (candidates.length) {\n const scratch = packShelves(candidates, width, 1 << 14)\n if (!scratch) return null\n const { encodeColorBand } = await import('./colorGlyphs.js')\n signal.throwIfAborted()\n canvas.width = scratch.width\n canvas.height = scratch.height\n painter.reset()\n const paint = (fill: string): Uint8ClampedArray => {\n context.clearRect(0, 0, scratch.width, scratch.height)\n for (const glyph of candidates) painter.draw(glyph, false, fill)\n return context.getImageData(0, 0, scratch.width, scratch.height).data\n }\n const dark = paint('#000')\n const { colored } = encodeColorBand(\n paint('#fff'),\n dark,\n scratch.width,\n scratch.height,\n 0,\n candidates,\n )\n if (colored.some(Boolean)) return null\n }\n\n // The full build's shelf, continued from its last text row.\n let { x, y, rowHeight } = cursor\n const runs: Run[] = []\n let patchWidth = 0\n let patchHeight = 0\n for (const glyph of fresh) {\n if (x + glyph.width > width) {\n x = 0\n y += rowHeight\n rowHeight = 0\n }\n if (glyph.width > width || y + glyph.height > cursor.bottom) return null\n let run = runs.at(-1)\n if (run?.y !== y) {\n if (run) patchHeight += run.height\n runs.push((run = { x, y, top: patchHeight, width: 0, height: 0, glyphs: [] }))\n }\n glyph.x = x\n glyph.y = y\n run.glyphs.push(glyph)\n x += glyph.width\n run.width = x - run.x\n if (glyph.height > run.height) run.height = glyph.height\n if (glyph.height > rowHeight) rowHeight = glyph.height\n if (run.width > patchWidth) patchWidth = run.width\n }\n patchHeight += runs.at(-1)!.height\n if (patchWidth * patchHeight > PATCH_TEXELS) return null\n\n canvas.width = patchWidth\n canvas.height = patchHeight\n painter.reset()\n context.clearRect(0, 0, patchWidth, patchHeight)\n for (const run of runs) {\n for (const glyph of run.glyphs) {\n painter.draw({ ...glyph, x: glyph.x - run.x, y: glyph.y - run.y + run.top }, true)\n }\n }\n\n const target: Texture & { mipmapsAutoUpdate?: boolean; sourceTexture?: unknown } = atlas.texture\n if (atlas.mode === 'gpu') {\n // A patch takes the encoder its atlas was baked with. The jump flood and the exact\n // transform disagree by up to 25/255 of the range even at the edge, so a CPU patch\n // in a GPU atlas would draw its glyphs a shade off a full build's. The patch's field\n // and its copies into the live texture go out in one submission on the device's cached\n // passes, then three regenerates the texture's mips. A device that fails here leaves\n // the full build to fall back, as `auto` does, or to throw.\n const live = target.sourceTexture as AtlasGpuTexture | null | undefined\n if (!live) return null\n const field = await encodeGpuSdf(\n atlasDevice(renderer),\n { canvas, width: patchWidth, height: patchHeight, pxRange: padding },\n 1,\n (encoder, patch) => {\n for (const run of runs) {\n encoder.copyTextureToTexture(\n { texture: patch, origin: [0, run.top] },\n { texture: live, origin: [run.x, run.y] },\n [run.width, run.height],\n )\n }\n },\n ).catch(() => null)\n if (!field) return null\n field.destroy()\n try {\n if (live.mipLevelCount > 1) await generateAtlasMips(renderer, target)\n } catch {\n return null\n }\n signal.throwIfAborted()\n } else {\n // A CPU atlas keeps its bytes, which a later upload sends whole: they take the patch too.\n // (`mipmapsAutoUpdate` is r187's; r186 regenerates the mipmaps after every copy.)\n const image = target.image as { data?: unknown } | null\n const bytes =\n image?.data instanceof Uint8Array && image.data.length === width * height\n ? image.data\n : undefined\n const pixels = context.getImageData(0, 0, patchWidth, patchHeight).data\n const field = encodeSdfFromAlpha(\n alphaOfRgba(pixels, patchWidth * patchHeight),\n patchWidth,\n patchHeight,\n padding,\n )\n signal.throwIfAborted()\n\n // Everything from here on is synchronous, so a newer build cannot interleave its own patch.\n if (bytes) {\n for (const run of runs) {\n for (let row = 0; row < run.height; row++) {\n const from = (run.top + row) * patchWidth\n bytes.set(field.subarray(from, from + run.width), (run.y + row) * width + run.x)\n }\n }\n }\n const patch = new DataTexture(field, patchWidth, patchHeight, RedFormat, UnsignedByteType)\n patch.needsUpdate = true\n const autoMipmaps = target.mipmapsAutoUpdate\n try {\n runs.forEach((run, index) => {\n // Each copy regenerates the whole mip chain: only the last needs to.\n if (autoMipmaps) target.mipmapsAutoUpdate = index === runs.length - 1\n renderer.copyTextureToTexture(\n patch,\n target,\n new Box2(new Vector2(0, run.top), new Vector2(run.width, run.top + run.height)),\n new Vector2(run.x, run.y),\n )\n })\n } catch {\n // A renderer that cannot copy between textures uploads the atlas's bytes again, whole.\n if (!bytes) return null\n target.needsUpdate = true\n } finally {\n if (autoMipmaps) target.mipmapsAutoUpdate = true\n patch.dispose()\n }\n }\n\n const glyphs = new Map(atlas.glyphs)\n for (const glyph of fresh) {\n glyphs.set(\n glyph.request.key,\n slotOf(\n glyph,\n padding,\n bakeSize,\n width,\n height,\n false,\n isColorCandidate(glyph.request, colorGlyphs),\n ),\n )\n }\n appendCursors.set(glyphs, { ...cursor, x, y, rowHeight })\n return { ...atlas, glyphs }\n } finally {\n canvas.remove()\n }\n}\n"],"mappings":";;;;;;;;;;AA8BA,IAAM,eAAe,KAAK;;;;;;;;;;;;;;;;;;;;AAgC1B,eAAsB,aACpB,UACA,UACA,OACA,SACA,SACA,QAC0B;CAC1B,MAAM,SAAS,cAAc,IAAI,MAAM,MAAM;CAC7C,MAAM,cAAc,QAAQ,eAAe;CAC3C,MAAM,WAAW,QAAQ,QAAQ,YAAY,CAAC,MAAM,OAAO,IAAI,QAAQ,GAAG,CAAC;CAC3E,IACE,QAAQ,cAAc,QAAQ,YAAY,OAC1C,OA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nsignedByteType,\n Vector2,\n type Texture,\n type WebGPURenderer,\n} from 'three/webgpu'\n\nimport type { DomSdfOptions, GlyphRequest, SdfAtlas } from '../types.js'\nimport { alphaOfRgba, encodeSdfFromAlpha } from './cpuSdf.js'\nimport { atlasDevice, encodeGpuSdf, generateAtlasMips, type AtlasGpuTexture } from './gpuAtlas.js'\nimport {\n appendCursors,\n createCanvas,\n glyphPainter,\n isColorCandidate,\n measureGlyph,\n packShelves,\n slotOf,\n waitForFonts,\n type MeasuredGlyph,\n} from './rasterize.js'\n\n/**\n * A larger patch is left to a full rebuild, which spreads its work better: the patch's exact\n * transform runs on the page's thread, where 2^18 texels (about twenty 96 px glyphs) take a\n * few milliseconds.\n */\nconst PATCH_TEXELS = 1 << 18\n\n/** The new glyphs of one atlas row and where they go: never a box that spans two rows. */\ninterface Run {\n readonly x: number\n readonly y: number\n /** First row of the run on the patch canvas, where the runs are stacked. */\n readonly top: number\n width: number\n height: number\n readonly glyphs: MeasuredGlyph[]\n}\n\n/**\n * @internal Draws the text glyphs of a `capture` that `atlas` lacks into the free text rows of\n * its live texture, so a rebuild keeps the texture and every material that samples it. Only\n * the new glyphs are measured and drawn, row by row of the atlas, on one small canvas, by the\n * full build's rules and slot formulas (`glyphPainter`, `slotOf`). Their distance field comes\n * from the atlas's own encoder, a jump flood of the patch alone for a GPU atlas and the exact\n * transform for a CPU one, so the new slots hold the bytes a full build would give them; each\n * row's box is then copied into the texture, whose mipmaps three regenerates, and a CPU\n * atlas's bytes follow.\n *\n * Resolves with the next wrapper: the same texture, colour layer, shape rows and `dispose`,\n * with the old slots and the new ones; its own cursor is recorded under its glyph map, so it\n * becomes the live one only when the caller commits that wrapper. Slots the capture no longer\n * uses stay in the texture until the next full build compacts it. Resolves `null`, having\n * written nothing the caller must undo, when the caller must rebuild in full instead: a shape,\n * a glyph that classifies as colour, an atlas without a cursor or with a lowered adaptive bake\n * size, a patch past its texel budget, or glyphs that do not fit. What an aborted patch already\n * copied lies in rows no slot samples, and the next patch overwrites it.\n */\nexport async function appendGlyphs(\n renderer: WebGPURenderer,\n document: Document,\n atlas: SdfAtlas,\n capture: readonly GlyphRequest[],\n options: Pick<DomSdfOptions, 'colorGlyphs' | 'bakeSize'>,\n signal: AbortSignal,\n): Promise<SdfAtlas | null> {\n const cursor = appendCursors.get(atlas.glyphs)\n const colorGlyphs = options.colorGlyphs ?? 'emoji'\n const requests = capture.filter((request) => !atlas.glyphs.has(request.key))\n if (\n cursor?.bakeSize !== (options.bakeSize ?? 96) ||\n cursor.colorGlyphs !== colorGlyphs ||\n cursor.width !== atlas.width ||\n cursor.height !== atlas.height ||\n !requests.length ||\n requests.some((request) => request.shape !== undefined)\n )\n return null\n const [, shapingModule] = await Promise.all([\n waitForFonts(document, requests, signal),\n requests.some((request) => request.shaping) ? import('../dom/browserShaping.js') : undefined,\n ])\n signal.throwIfAborted()\n const shaping = shapingModule?.setShapingContext\n const { width, height, bakeSize, pxRange: padding } = cursor\n const canvas = createCanvas(document)\n try {\n // A GPU patch reads at most a tiny candidate scratch pack and uploads the patch texture.\n const context = canvas.getContext('2d', {\n willReadFrequently: atlas.mode !== 'gpu',\n })\n if (!context) return null\n let lastFont: GlyphRequest['font'] | null = null\n const fresh = requests.map((request) => {\n const [glyph, font] = measureGlyph(\n context,\n request,\n padding,\n shaping,\n isColorCandidate(request, colorGlyphs),\n lastFont,\n )\n lastFont = font\n return glyph\n })\n fresh.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 // The patch stacks its glyphs' rows, so it is never smaller than their summed area: a batch\n // past the budget is refused before its colour candidates are drawn and read back.\n let area = 0\n for (const glyph of fresh) area += glyph.width * glyph.height\n if (area > PATCH_TEXELS) return null\n const painter = glyphPainter(context, shaping, signal)\n\n // Colour candidates are classified as in a full build, on a pack of their own: one that\n // keeps its colour needs the colour band, which only a full build can grow.\n const candidates = fresh.filter((glyph) => isColorCandidate(glyph.request, colorGlyphs))\n if (candidates.length) {\n const scratch = packShelves(candidates, width, 1 << 14)\n if (!scratch) return null\n const { encodeColorBand } = await import('./colorGlyphs.js')\n signal.throwIfAborted()\n canvas.width = scratch.width\n canvas.height = scratch.height\n painter.reset()\n const paint = (fill: string): Uint8ClampedArray => {\n context.clearRect(0, 0, scratch.width, scratch.height)\n for (const glyph of candidates) painter.draw(glyph, false, fill)\n return context.getImageData(0, 0, scratch.width, scratch.height).data\n }\n const dark = paint('#000')\n const { colored } = encodeColorBand(\n paint('#fff'),\n dark,\n scratch.width,\n scratch.height,\n 0,\n candidates,\n )\n if (colored.some(Boolean)) return null\n }\n\n // The full build's shelf, continued from its last text row.\n let { x, y, rowHeight } = cursor\n const runs: Run[] = []\n let patchWidth = 0\n let patchHeight = 0\n for (const glyph of fresh) {\n if (x + glyph.width > width) {\n x = 0\n y += rowHeight\n rowHeight = 0\n }\n if (glyph.width > width || y + glyph.height > cursor.bottom) return null\n let run = runs.at(-1)\n if (run?.y !== y) {\n if (run) patchHeight += run.height\n runs.push((run = { x, y, top: patchHeight, width: 0, height: 0, glyphs: [] }))\n }\n glyph.x = x\n glyph.y = y\n run.glyphs.push(glyph)\n x += glyph.width\n run.width = x - run.x\n if (glyph.height > run.height) run.height = glyph.height\n if (glyph.height > rowHeight) rowHeight = glyph.height\n if (run.width > patchWidth) patchWidth = run.width\n }\n patchHeight += runs.at(-1)!.height\n if (patchWidth * patchHeight > PATCH_TEXELS) return null\n\n canvas.width = patchWidth\n canvas.height = patchHeight\n painter.reset()\n context.clearRect(0, 0, patchWidth, patchHeight)\n for (const run of runs) {\n for (const glyph of run.glyphs) {\n painter.draw({ ...glyph, x: glyph.x - run.x, y: glyph.y - run.y + run.top }, true)\n }\n }\n\n const target: Texture & { mipmapsAutoUpdate?: boolean; sourceTexture?: unknown } = atlas.texture\n if (atlas.mode === 'gpu') {\n // A patch takes the encoder its atlas was baked with. The jump flood and the exact\n // transform disagree by up to 25/255 of the range even at the edge, so a CPU patch\n // in a GPU atlas would draw its glyphs a shade off a full build's. The patch's field\n // and its copies into the live texture go out in one submission on the device's cached\n // passes, then three regenerates the texture's mips. A device that fails here leaves\n // the full build to fall back, as `auto` does, or to throw.\n const live = target.sourceTexture as AtlasGpuTexture | null | undefined\n if (!live) return null\n const field = await encodeGpuSdf(\n atlasDevice(renderer),\n { canvas, width: patchWidth, height: patchHeight, pxRange: padding },\n 1,\n (encoder, patch) => {\n for (const run of runs) {\n encoder.copyTextureToTexture(\n { texture: patch, origin: [0, run.top] },\n { texture: live, origin: [run.x, run.y] },\n [run.width, run.height],\n )\n }\n },\n ).catch(() => null)\n if (!field) return null\n field.destroy()\n try {\n if (live.mipLevelCount > 1) await generateAtlasMips(renderer, target)\n } catch {\n return null\n }\n signal.throwIfAborted()\n } else {\n // A CPU atlas keeps its bytes, which a later upload sends whole: they take the patch too.\n // (`mipmapsAutoUpdate` is r187's; r186 regenerates the mipmaps after every copy.)\n const image = target.image as { data?: unknown } | null\n const bytes =\n image?.data instanceof Uint8Array && image.data.length === width * height\n ? image.data\n : undefined\n const pixels = context.getImageData(0, 0, patchWidth, patchHeight).data\n const field = encodeSdfFromAlpha(\n alphaOfRgba(pixels, patchWidth * patchHeight),\n patchWidth,\n patchHeight,\n padding,\n )\n signal.throwIfAborted()\n\n // Everything from here on is synchronous, so a newer build cannot interleave its own patch.\n if (bytes) {\n for (const run of runs) {\n for (let row = 0; row < run.height; row++) {\n const from = (run.top + row) * patchWidth\n bytes.set(field.subarray(from, from + run.width), (run.y + row) * width + run.x)\n }\n }\n }\n const patch = new DataTexture(field, patchWidth, patchHeight, RedFormat, UnsignedByteType)\n patch.needsUpdate = true\n const autoMipmaps = target.mipmapsAutoUpdate\n try {\n runs.forEach((run, index) => {\n // Each copy regenerates the whole mip chain: only the last needs to.\n if (autoMipmaps) target.mipmapsAutoUpdate = index === runs.length - 1\n renderer.copyTextureToTexture(\n patch,\n target,\n new Box2(new Vector2(0, run.top), new Vector2(run.width, run.top + run.height)),\n new Vector2(run.x, run.y),\n )\n })\n } catch {\n // A renderer that cannot copy between textures uploads the atlas's bytes again, whole.\n if (!bytes) return null\n target.needsUpdate = true\n } finally {\n if (autoMipmaps) target.mipmapsAutoUpdate = true\n patch.dispose()\n }\n }\n\n const glyphs = new Map(atlas.glyphs)\n for (const glyph of fresh) {\n glyphs.set(\n glyph.request.key,\n slotOf(\n glyph,\n padding,\n bakeSize,\n width,\n height,\n false,\n isColorCandidate(glyph.request, colorGlyphs),\n ),\n )\n }\n appendCursors.set(glyphs, { ...cursor, x, y, rowHeight })\n return { ...atlas, glyphs }\n } finally {\n canvas.remove()\n }\n}\n"],"mappings":";;;;;;;;;;;AA8BA,IAAM,eAAe,KAAK;;;;;;;;;;;;;;;;;;;;AAgC1B,eAAsB,aACpB,UACA,UACA,OACA,SACA,SACA,QAC0B;CAC1B,MAAM,SAAS,cAAc,IAAI,MAAM,MAAM;CAC7C,MAAM,cAAc,QAAQ,eAAe;CAC3C,MAAM,WAAW,QAAQ,QAAQ,YAAY,CAAC,MAAM,OAAO,IAAI,QAAQ,GAAG,CAAC;CAC3E,IACE,QAAQ,cAAc,QAAQ,YAAY,OAC1C,OAAO,gBAAgB,eACvB,OAAO,UAAU,MAAM,SACvB,OAAO,WAAW,MAAM,UACxB,CAAC,SAAS,UACV,SAAS,MAAM,YAAY,QAAQ,UAAU,KAAA,CAAS,GAEtD,OAAO;CACT,MAAM,GAAG,iBAAiB,MAAM,QAAQ,IAAI,CAC1C,aAAa,UAAU,UAAU,MAAM,GACvC,SAAS,MAAM,YAAY,QAAQ,OAAO,IAAI,OAAO,8BAA8B,KAAA,CACrF,CAAC;CACD,OAAO,eAAe;CACtB,MAAM,UAAU,eAAe;CAC/B,MAAM,EAAE,OAAO,QAAQ,UAAU,SAAS,YAAY;CACtD,MAAM,SAAS,aAAa,QAAQ;CACpC,IAAI;EAEF,MAAM,UAAU,OAAO,WAAW,MAAM,EACtC,oBAAoB,MAAM,SAAS,MACrC,CAAC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AI,KAAK,IAAI,QAAQ,GAAG,IAAI,GAAG,GAAG,IAAI,QAAQ,IAAI,OAAO,IAAI,MAAM,IAAI,MAAM,CAAC,GAC9E,IAAI,QAAQ,IAAI,GAAG,IAAI,CAAC,CAC1B;IACF,CAAC;GACH,QAAQ;IAEN,IAAI,CAAC,OAAO,OAAO;IACnB,OAAO,cAAc;GACvB,UAAU;IACR,IAAI,aAAa,OAAO,oBAAoB;IAC5C,MAAM,QAAQ;GAChB;EACF;EAEA,MAAM,SAAS,IAAI,IAAI,MAAM,MAAM;EACnC,KAAK,MAAM,SAAS,OAClB,OAAO,IACL,MAAM,QAAQ,KACd,OACE,OACA,SACA,UACA,OACA,QACA,OACA,iBAAiB,MAAM,SAAS,WAAW,CAC7C,CACF;EAEF,cAAc,IAAI,QAAQ;GAAE,GAAG;GAAQ;GAAG;GAAG;EAAU,CAAC;EACxD,OAAO;GAAE,GAAG;GAAO;EAAO;CAC5B,UAAU;EACR,OAAO,OAAO;CAChB;AACF"}
|
package/dist/atlas/buildAtlas.js
CHANGED
|
@@ -39,19 +39,7 @@ async function withColorLayer(atlas, raster, renderer, options) {
|
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
41
|
var warnedGpuFallback = false;
|
|
42
|
-
|
|
43
|
-
* Builds the retained single-channel SDF atlas from a packed glyph mask.
|
|
44
|
-
*
|
|
45
|
-
* `mode: 'gpu'` runs the WebGPU compute encoder and rethrows if a real WebGPU
|
|
46
|
-
* backend is unavailable, if the device's limits cannot hold the passes, or if
|
|
47
|
-
* the device reports an error for them; `'cpu'` runs the exact Euclidean
|
|
48
|
-
* distance transform; the default `'auto'` tries the GPU path first and falls
|
|
49
|
-
* back to the CPU encoder, warning once per page because the fallback is
|
|
50
|
-
* 10-100× slower.
|
|
51
|
-
* An aborted `signal` rejects with the abort reason and disposes any atlas
|
|
52
|
-
* that was already produced. The caller owns the returned atlas.
|
|
53
|
-
*/
|
|
54
|
-
async function buildSdfAtlas(renderer, raster, options = {}) {
|
|
42
|
+
async function buildSdfAtlas(renderer, raster, options = {}, provisional) {
|
|
55
43
|
const mode = options.mode;
|
|
56
44
|
options.signal?.throwIfAborted();
|
|
57
45
|
const buildCpu = async () => {
|
|
@@ -62,8 +50,9 @@ async function buildSdfAtlas(renderer, raster, options = {}) {
|
|
|
62
50
|
let atlas;
|
|
63
51
|
if (mode === "cpu") atlas = await buildCpu();
|
|
64
52
|
else try {
|
|
65
|
-
atlas = retainAtlas(await buildGpuSdfAtlas(renderer, raster, options), options.signal);
|
|
53
|
+
atlas = retainAtlas(provisional && !raster.colorBand && !options.mipmaps ? await buildGpuSdfAtlas(renderer, raster, options, (candidate) => provisional.stage(candidate)) : await buildGpuSdfAtlas(renderer, raster, options), options.signal);
|
|
66
54
|
} catch (error) {
|
|
55
|
+
provisional?.rollback();
|
|
67
56
|
if (mode === "gpu") throw error;
|
|
68
57
|
options.signal?.throwIfAborted();
|
|
69
58
|
if (!warnedGpuFallback) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buildAtlas.js","names":[],"sources":["../../src/atlas/buildAtlas.ts"],"sourcesContent":["import type { WebGPURenderer } from 'three/webgpu'\n\nimport type { BuildSdfAtlasOptions, RasterAtlas, SdfAtlas } from '../types.js'\nimport { buildGpuSdfAtlas } from './gpuAtlas.js'\n\nfunction retainAtlas(atlas: SdfAtlas, signal?: AbortSignal): SdfAtlas {\n if (signal?.aborted) {\n atlas.dispose()\n signal.throwIfAborted()\n }\n return atlas\n}\n\nasync function withColorLayer(\n atlas: SdfAtlas,\n raster: RasterAtlas,\n renderer: WebGPURenderer,\n options: BuildSdfAtlasOptions,\n): Promise<SdfAtlas> {\n if (!raster.colorBand) return atlas\n let colorLayer: SdfAtlas['colorLayer']\n try {\n const { createColorLayer } = await import('./colorGlyphs.js')\n options.signal?.throwIfAborted()\n colorLayer = createColorLayer(\n raster.colorBand,\n raster.width,\n options,\n renderer.getMaxAnisotropy(),\n )\n options.signal?.throwIfAborted()\n let disposed = false\n return {\n ...atlas,\n colorLayer,\n dispose() {\n if (disposed) return\n disposed = true\n try {\n atlas.dispose()\n } finally {\n colorLayer!.texture.dispose()\n }\n },\n }\n } catch (error) {\n try {\n atlas.dispose()\n } finally {\n colorLayer?.texture.dispose()\n }\n throw error\n }\n}\n\nlet warnedGpuFallback = false\n\n/**\n * Builds the retained single-channel SDF atlas from a packed glyph mask.\n *\n * `mode: 'gpu'` runs the WebGPU compute encoder and rethrows if a real WebGPU\n * backend is unavailable, if the device's limits cannot hold the passes, or if\n * the device reports an error for them; `'cpu'` runs the exact Euclidean\n * distance transform; the default `'auto'` tries the GPU path first and falls\n * back to the CPU encoder, warning once per page because the fallback is\n * 10-100× slower.\n * An aborted `signal` rejects with the abort reason and disposes any atlas\n * that was already produced. The caller owns the returned atlas.\n */\nexport async function buildSdfAtlas(\n renderer: WebGPURenderer,\n raster: RasterAtlas,\n options: BuildSdfAtlasOptions = {},\n): Promise<SdfAtlas> {\n const mode = options.mode\n options.signal?.throwIfAborted()\n\n const buildCpu = async (): Promise<SdfAtlas> => {\n const { buildCpuSdfAtlas } = await import('./cpuAtlas.js')\n options.signal?.throwIfAborted()\n return retainAtlas(await buildCpuSdfAtlas(raster, options), options.signal)\n }\n let atlas: SdfAtlas\n if (mode === 'cpu') atlas = await buildCpu()\n else {\n try {\n
|
|
1
|
+
{"version":3,"file":"buildAtlas.js","names":[],"sources":["../../src/atlas/buildAtlas.ts"],"sourcesContent":["import type { WebGPURenderer } from 'three/webgpu'\n\nimport type { BuildSdfAtlasOptions, RasterAtlas, SdfAtlas } from '../types.js'\nimport { buildGpuSdfAtlas } from './gpuAtlas.js'\n\nfunction retainAtlas(atlas: SdfAtlas, signal?: AbortSignal): SdfAtlas {\n if (signal?.aborted) {\n atlas.dispose()\n signal.throwIfAborted()\n }\n return atlas\n}\n\nasync function withColorLayer(\n atlas: SdfAtlas,\n raster: RasterAtlas,\n renderer: WebGPURenderer,\n options: BuildSdfAtlasOptions,\n): Promise<SdfAtlas> {\n if (!raster.colorBand) return atlas\n let colorLayer: SdfAtlas['colorLayer']\n try {\n const { createColorLayer } = await import('./colorGlyphs.js')\n options.signal?.throwIfAborted()\n colorLayer = createColorLayer(\n raster.colorBand,\n raster.width,\n options,\n renderer.getMaxAnisotropy(),\n )\n options.signal?.throwIfAborted()\n let disposed = false\n return {\n ...atlas,\n colorLayer,\n dispose() {\n if (disposed) return\n disposed = true\n try {\n atlas.dispose()\n } finally {\n colorLayer!.texture.dispose()\n }\n },\n }\n } catch (error) {\n try {\n atlas.dispose()\n } finally {\n colorLayer?.texture.dispose()\n }\n throw error\n }\n}\n\nlet warnedGpuFallback = false\n\n/** @internal Hook for overlapping GPU SDF validation with downstream geometry creation. */\nexport interface ProvisionalAtlasHook {\n stage(atlas: SdfAtlas): void\n rollback(): void\n}\n\n/**\n * Builds the retained single-channel SDF atlas from a packed glyph mask.\n *\n * `mode: 'gpu'` runs the WebGPU compute encoder and rethrows if a real WebGPU\n * backend is unavailable, if the device's limits cannot hold the passes, or if\n * the device reports an error for them; `'cpu'` runs the exact Euclidean\n * distance transform; the default `'auto'` tries the GPU path first and falls\n * back to the CPU encoder, warning once per page because the fallback is\n * 10-100× slower.\n * An aborted `signal` rejects with the abort reason and disposes any atlas\n * that was already produced. The caller owns the returned atlas.\n */\nexport function buildSdfAtlas(\n renderer: WebGPURenderer,\n raster: RasterAtlas,\n options?: BuildSdfAtlasOptions,\n): Promise<SdfAtlas>\n/** @internal */\nexport function buildSdfAtlas(\n renderer: WebGPURenderer,\n raster: RasterAtlas,\n options: BuildSdfAtlasOptions | undefined,\n provisional: ProvisionalAtlasHook | undefined,\n): Promise<SdfAtlas>\nexport async function buildSdfAtlas(\n renderer: WebGPURenderer,\n raster: RasterAtlas,\n options: BuildSdfAtlasOptions = {},\n provisional?: ProvisionalAtlasHook,\n): Promise<SdfAtlas> {\n const mode = options.mode\n options.signal?.throwIfAborted()\n\n const buildCpu = async (): Promise<SdfAtlas> => {\n const { buildCpuSdfAtlas } = await import('./cpuAtlas.js')\n options.signal?.throwIfAborted()\n return retainAtlas(await buildCpuSdfAtlas(raster, options), options.signal)\n }\n let atlas: SdfAtlas\n if (mode === 'cpu') atlas = await buildCpu()\n else {\n try {\n const built =\n provisional && !raster.colorBand && !options.mipmaps\n ? await buildGpuSdfAtlas(renderer, raster, options, (candidate) =>\n provisional.stage(candidate),\n )\n : await buildGpuSdfAtlas(renderer, raster, options)\n atlas = retainAtlas(built, options.signal)\n } catch (error) {\n provisional?.rollback()\n if (mode === 'gpu') throw error\n options.signal?.throwIfAborted()\n if (!warnedGpuFallback) {\n warnedGpuFallback = true\n console.warn('ultra-text: falling back to CPU SDF', error)\n }\n atlas = await buildCpu()\n }\n }\n // `SdfAtlas.shapeTop` names the rows of the monochrome shapes. The texture repeats it for\n // a material that is handed the texture without that field.\n if (atlas.shapeTop !== undefined) atlas.texture.userData['ultraShapeTop'] = atlas.shapeTop\n return withColorLayer(atlas, raster, renderer, options)\n}\n"],"mappings":";;AAKA,SAAS,YAAY,OAAiB,QAAgC;CACpE,IAAI,QAAQ,SAAS;EACnB,MAAM,QAAQ;EACd,OAAO,eAAe;CACxB;CACA,OAAO;AACT;AAEA,eAAe,eACb,OACA,QACA,UACA,SACmB;CACnB,IAAI,CAAC,OAAO,WAAW,OAAO;CAC9B,IAAI;CACJ,IAAI;EACF,MAAM,EAAE,qBAAqB,MAAM,OAAO;EAC1C,QAAQ,QAAQ,eAAe;EAC/B,aAAa,iBACX,OAAO,WACP,OAAO,OACP,SACA,SAAS,iBAAiB,CAC5B;EACA,QAAQ,QAAQ,eAAe;EAC/B,IAAI,WAAW;EACf,OAAO;GACL,GAAG;GACH;GACA,UAAU;IACR,IAAI,UAAU;IACd,WAAW;IACX,IAAI;KACF,MAAM,QAAQ;IAChB,UAAU;KACR,WAAY,QAAQ,QAAQ;IAC9B;GACF;EACF;CACF,SAAS,OAAO;EACd,IAAI;GACF,MAAM,QAAQ;EAChB,UAAU;GACR,YAAY,QAAQ,QAAQ;EAC9B;EACA,MAAM;CACR;AACF;AAEA,IAAI,oBAAoB;AAgCxB,eAAsB,cACpB,UACA,QACA,UAAgC,CAAC,GACjC,aACmB;CACnB,MAAM,OAAO,QAAQ;CACrB,QAAQ,QAAQ,eAAe;CAE/B,MAAM,WAAW,YAA+B;EAC9C,MAAM,EAAE,qBAAqB,MAAM,OAAO;EAC1C,QAAQ,QAAQ,eAAe;EAC/B,OAAO,YAAY,MAAM,iBAAiB,QAAQ,OAAO,GAAG,QAAQ,MAAM;CAC5E;CACA,IAAI;CACJ,IAAI,SAAS,OAAO,QAAQ,MAAM,SAAS;MAEzC,IAAI;EAOF,QAAQ,YALN,eAAe,CAAC,OAAO,aAAa,CAAC,QAAQ,UACzC,MAAM,iBAAiB,UAAU,QAAQ,UAAU,cACjD,YAAY,MAAM,SAAS,CAC7B,IACA,MAAM,iBAAiB,UAAU,QAAQ,OAAO,GAC3B,QAAQ,MAAM;CAC3C,SAAS,OAAO;EACd,aAAa,SAAS;EACtB,IAAI,SAAS,OAAO,MAAM;EAC1B,QAAQ,QAAQ,eAAe;EAC/B,IAAI,CAAC,mBAAmB;GACtB,oBAAoB;GACpB,QAAQ,KAAK,uCAAuC,KAAK;EAC3D;EACA,QAAQ,MAAM,SAAS;CACzB;CAIF,IAAI,MAAM,aAAa,KAAA,GAAW,MAAM,QAAQ,SAAS,mBAAmB,MAAM;CAClF,OAAO,eAAe,OAAO,QAAQ,UAAU,OAAO;AACxD"}
|
package/dist/atlas/cpuSdf.js
CHANGED
|
@@ -73,20 +73,20 @@ function edt1d(grid, startSeed, endSeed, outStart, outEnd, clampSqDist, maxRadiu
|
|
|
73
73
|
cost = grid[q];
|
|
74
74
|
} else if (cost === grid[q - 1]) while (q < endSeed && grid[q + 1] === cost) q++;
|
|
75
75
|
const costPlusQSquared = cost + q * q;
|
|
76
|
-
while (envelopeEnd > 0 &&
|
|
77
|
-
const
|
|
76
|
+
while (envelopeEnd > 0 && costPlusQSquared - parabolaOffsets[envelopeEnd] <= boundaries[envelopeEnd] * (q - parabolaIndices[envelopeEnd])) envelopeEnd--;
|
|
77
|
+
const twiceIntersection = (costPlusQSquared - parabolaOffsets[envelopeEnd]) / (q - parabolaIndices[envelopeEnd]);
|
|
78
78
|
envelopeEnd++;
|
|
79
79
|
parabolaIndices[envelopeEnd] = q;
|
|
80
80
|
parabolaCosts[envelopeEnd] = cost;
|
|
81
81
|
parabolaOffsets[envelopeEnd] = costPlusQSquared;
|
|
82
|
-
boundaries[envelopeEnd] =
|
|
82
|
+
boundaries[envelopeEnd] = twiceIntersection;
|
|
83
83
|
}
|
|
84
84
|
const minOut = first - maxRadius > outStart ? first - maxRadius : outStart;
|
|
85
85
|
const lastSeed = parabolaIndices[envelopeEnd];
|
|
86
86
|
const maxOut = lastSeed + maxRadius < outEnd ? lastSeed + maxRadius : outEnd;
|
|
87
87
|
let b0 = minOut;
|
|
88
88
|
for (let e = 0; e <= envelopeEnd; e++) {
|
|
89
|
-
const b1 = e === envelopeEnd ? maxOut : Math.floor(boundaries[e + 1]);
|
|
89
|
+
const b1 = e === envelopeEnd ? maxOut : Math.floor(boundaries[e + 1] * .5);
|
|
90
90
|
if (b1 >= b0) {
|
|
91
91
|
const nearest = parabolaIndices[e];
|
|
92
92
|
const cost = parabolaCosts[e];
|
|
@@ -111,7 +111,8 @@ function edt1d(grid, startSeed, endSeed, outStart, outEnd, clampSqDist, maxRadiu
|
|
|
111
111
|
}
|
|
112
112
|
var SEED_COST = Float32Array.from({ length: 256 }, (_, coverage) => {
|
|
113
113
|
const edgeOffset = .5 - coverage / 255;
|
|
114
|
-
|
|
114
|
+
const sq = Math.fround(edgeOffset * edgeOffset);
|
|
115
|
+
return coverage < 128 ? sq : -sq;
|
|
115
116
|
});
|
|
116
117
|
var scratchDistances = /* @__PURE__ */ new Float32Array(0);
|
|
117
118
|
var scratchParabolaIndices = /* @__PURE__ */ new Int32Array(0);
|
|
@@ -140,15 +141,17 @@ function horizontalRowDistances(alpha, alphaRow, distances, distRow, width, firs
|
|
|
140
141
|
const sign = isZero ? 1 : -1;
|
|
141
142
|
const lCov = a > 0 ? alpha[alphaRow + a - 1] : -1;
|
|
142
143
|
const rCov = x + 1 < width ? alpha[alphaRow + x + 1] : -1;
|
|
143
|
-
const
|
|
144
|
-
const
|
|
144
|
+
const lSc = lCov < 0 ? FAR_DISTANCE_SQUARED : sign * SEED_COST[lCov];
|
|
145
|
+
const rSc = rCov < 0 ? FAR_DISTANCE_SQUARED : sign * SEED_COST[rCov];
|
|
146
|
+
const lCost = lSc > 0 ? lSc : 0;
|
|
147
|
+
const rCost = rSc > 0 ? rSc : 0;
|
|
145
148
|
const mid = rCov < 0 ? x : lCov < 0 ? a - 1 : a + x - (rCost < lCost ? 1 : 0) >> 1;
|
|
146
149
|
const lEnd = lCov < 0 ? a - 1 : mid < a + maxRadius - 1 ? mid : a + maxRadius - 1;
|
|
147
150
|
const rStart = rCov < 0 ? x + 1 : mid + 1 > x - maxRadius + 1 ? mid + 1 : x - maxRadius + 1;
|
|
148
151
|
for (let p = a, d = 1; p <= lEnd; p++, d++) distances[distRow + p] = sign * (d * d + lCost);
|
|
149
152
|
if (lEnd + 1 < rStart) distances.fill(sign * FAR_DISTANCE_SQUARED, distRow + lEnd + 1, distRow + rStart);
|
|
150
153
|
for (let p = rStart, d = x + 1 - rStart; p <= x; p++, d--) distances[distRow + p] = sign * (d * d + rCost);
|
|
151
|
-
} else distances[distRow + x] =
|
|
154
|
+
} else distances[distRow + x] = SEED_COST[coverage];
|
|
152
155
|
}
|
|
153
156
|
return lastNonZero;
|
|
154
157
|
}
|
|
@@ -272,10 +275,9 @@ function encodeSdfFromAlpha(alpha, width, height, pxRange) {
|
|
|
272
275
|
negCount++;
|
|
273
276
|
}
|
|
274
277
|
}
|
|
275
|
-
const hasPositive = negCount < bandHeight;
|
|
276
278
|
let yStart = bandMinY;
|
|
277
279
|
let yEnd = bandMaxY;
|
|
278
|
-
if (
|
|
280
|
+
if (negCount < bandHeight) {
|
|
279
281
|
edt1d(inside, firstInSeed, lastInSeed, bandMinY, bandMaxY, clampSqDist, maxRadius);
|
|
280
282
|
yStart = edtMinOut;
|
|
281
283
|
yEnd = edtMaxOut;
|
package/dist/atlas/cpuSdf.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cpuSdf.js","names":[],"sources":["../../src/atlas/cpuSdf.ts"],"sourcesContent":["/**\n * A finite stand-in for infinity in the squared-distance grids.\n *\n * Keeping the sentinel finite avoids `Infinity - Infinity` while constructing\n * the lower envelope of parabolas. Its square root is far beyond any practical\n * atlas extent, so missing inside/outside pixels still saturate at the correct\n * encoded endpoint.\n */\nconst FAR_DISTANCE_SQUARED = 1e20\n\ntype AlphaPixels = Uint8Array | Uint8ClampedArray\n\n/** The alpha byte of each RGBA pixel, as the encoder reads coverage. */\nexport function alphaOfRgba(rgba: Uint8ClampedArray, pixelCount: number): Uint8Array {\n const alpha = new Uint8Array(pixelCount)\n for (let source = 3, target = 0; target < pixelCount; source += 4, target++) {\n alpha[target] = rgba[source]!\n }\n return alpha\n}\n\nfunction assertInputs(alpha: AlphaPixels, width: number, height: number, pxRange: number): number {\n if (!(alpha instanceof Uint8Array) && !(alpha instanceof Uint8ClampedArray)) {\n throw new TypeError('encodeSdfFromAlpha: alpha must be a Uint8Array or Uint8ClampedArray')\n }\n if (!Number.isInteger(width) || width <= 0) {\n throw new RangeError('encodeSdfFromAlpha: width must be a positive integer')\n }\n if (!Number.isInteger(height) || height <= 0) {\n throw new RangeError('encodeSdfFromAlpha: height must be a positive integer')\n }\n\n const pixelCount = width * height\n if (!Number.isSafeInteger(pixelCount)) {\n throw new RangeError('encodeSdfFromAlpha: width * height exceeds the safe integer range')\n }\n if (alpha.length !== pixelCount) {\n throw new RangeError(\n `encodeSdfFromAlpha: alpha length ${alpha.length} does not match width * height (${pixelCount})`,\n )\n }\n if (!Number.isFinite(pxRange) || pxRange <= 0) {\n throw new RangeError('encodeSdfFromAlpha: pxRange must be a positive finite number')\n }\n\n return pixelCount\n}\n\nlet edtMinOut = 0\nlet edtMaxOut = -1\n\n/**\n * Exact one-dimensional squared Euclidean distance transform.\n *\n * This is the lower-envelope algorithm from Felzenszwalb and Huttenlocher. It\n * runs in O(length), performs no allocations, and accepts non-zero seed costs\n * so fractional alpha coverage can place the glyph edge between pixel centres.\n * The envelope retains the original costs before writing back into the grid,\n * avoiding a copy of each column in both directions.\n */\nfunction edt1d(\n grid: Float32Array,\n startSeed: number,\n endSeed: number,\n outStart: number,\n outEnd: number,\n clampSqDist: number,\n maxRadius: number,\n): void {\n let first = startSeed\n while (first <= endSeed && grid[first]! >= clampSqDist) first++\n if (first > endSeed) {\n edtMinOut = outEnd + 1\n edtMaxOut = outStart - 1\n return\n }\n\n const firstCost = grid[first]!\n if (first === outStart) {\n let different = first + 1\n if (firstCost <= 1) {\n while (different <= endSeed && grid[different]! <= 1) different++\n } else {\n while (different <= endSeed && grid[different] === firstCost) different++\n }\n // A constant line or a line of immediate seeds (cost <= 1) is already its own distance transform.\n if (different > endSeed && endSeed >= outEnd) {\n edtMinOut = outStart\n edtMaxOut = outEnd\n return\n }\n }\n\n const parabolaIndices = scratchParabolaIndices\n const parabolaCosts = scratchParabolaCosts\n const parabolaOffsets = scratchParabolaOffsets\n const boundaries = scratchBoundaries\n let envelopeEnd = 0\n parabolaIndices[0] = first\n parabolaCosts[0] = firstCost\n parabolaOffsets[0] = firstCost + first * first\n\n for (let q = first + 1; q <= endSeed; q++) {\n let cost = grid[q]!\n if (cost >= clampSqDist) {\n while (q < endSeed && grid[q + 1]! >= clampSqDist) q++\n continue\n }\n if (cost <= 1 && grid[q - 1]! <= 1) {\n while (q < endSeed && grid[q + 1]! <= 1) q++\n cost = grid[q]!\n } else if (cost === grid[q - 1]!) {\n while (q < endSeed && grid[q + 1] === cost) q++\n }\n const costPlusQSquared = cost + q * q\n while (\n envelopeEnd > 0 &&\n (costPlusQSquared - parabolaOffsets[envelopeEnd]!) * 0.5 <=\n boundaries[envelopeEnd]! * (q - parabolaIndices[envelopeEnd]!)\n ) {\n envelopeEnd--\n }\n const intersection =\n ((costPlusQSquared - parabolaOffsets[envelopeEnd]!) * 0.5) /\n (q - parabolaIndices[envelopeEnd]!)\n\n envelopeEnd++\n parabolaIndices[envelopeEnd] = q\n parabolaCosts[envelopeEnd] = cost\n parabolaOffsets[envelopeEnd] = costPlusQSquared\n boundaries[envelopeEnd] = intersection\n }\n\n const minOut = first - maxRadius > outStart ? first - maxRadius : outStart\n const lastSeed = parabolaIndices[envelopeEnd]!\n const maxOut = lastSeed + maxRadius < outEnd ? lastSeed + maxRadius : outEnd\n let b0 = minOut\n for (let e = 0; e <= envelopeEnd; e++) {\n const b1 = e === envelopeEnd ? maxOut : Math.floor(boundaries[e + 1]!)\n if (b1 >= b0) {\n const nearest = parabolaIndices[e]!\n const cost = parabolaCosts[e]!\n const r0 = nearest - maxRadius\n const r1 = nearest + maxRadius\n const s1 = maxOut < b1 ? maxOut : b1\n const segStart = b0 > r0 ? b0 : r0\n const segEnd = s1 < r1 ? s1 : r1\n for (let q = segStart; q <= segEnd; q++) {\n const cur = grid[q]!\n if (cur <= 1) continue\n const delta = q - nearest\n const d = delta * delta + cost\n if (d < cur) grid[q] = d\n }\n b0 = b1 + 1\n if (b0 > maxOut) break\n }\n }\n edtMinOut = minOut\n edtMaxOut = maxOut\n}\n\nconst SEED_COST = Float32Array.from({ length: 256 }, (_, coverage) => {\n const edgeOffset = 0.5 - coverage / 255\n return Math.fround(edgeOffset * edgeOffset)\n})\n\nlet scratchDistances = new Float32Array(0)\nlet scratchParabolaIndices = new Int32Array(0)\nlet scratchParabolaCosts = new Float32Array(0)\nlet scratchParabolaOffsets = new Float64Array(0)\nlet scratchBoundaries = new Float64Array(0)\nlet scratchInside = new Float32Array(0)\nlet scratchOutside = new Float32Array(0)\nlet scratchActiveRows = new Int32Array(0)\n\n/**\n * Alpha seeds cost less than 0.25. A closer seed therefore always beats a\n * farther seed in the same direction (squared integer distances differ by at\n * least one). Each empty or solid run is bounded by at most one seed on each\n * side, so one pass splits each run at its midpoint and fills both ends.\n */\nfunction horizontalRowDistances(\n alpha: AlphaPixels,\n alphaRow: number,\n distances: Float32Array,\n distRow: number,\n width: number,\n firstNonZero: number,\n maxRadius: number,\n): number {\n let lastNonZero = width - 1\n for (let x = 0; x < width; x++) {\n const coverage = alpha[alphaRow + x]!\n if (coverage === 0 || coverage === 255) {\n const a = x\n if (x === 0 && firstNonZero > 0) x = firstNonZero - 1\n else while (x + 1 < width && alpha[alphaRow + x + 1] === coverage) x++\n const isZero = coverage === 0\n if (isZero && x === width - 1) lastNonZero = a - 1\n const sign = isZero ? 1 : -1\n const lCov = a > 0 ? alpha[alphaRow + a - 1]! : -1\n const rCov = x + 1 < width ? alpha[alphaRow + x + 1]! : -1\n const lCost =\n lCov < 0 ? FAR_DISTANCE_SQUARED : (isZero ? lCov < 128 : lCov >= 128) ? SEED_COST[lCov]! : 0\n const rCost =\n rCov < 0 ? FAR_DISTANCE_SQUARED : (isZero ? rCov < 128 : rCov >= 128) ? SEED_COST[rCov]! : 0\n const mid = rCov < 0 ? x : lCov < 0 ? a - 1 : (a + x - (rCost < lCost ? 1 : 0)) >> 1\n const lEnd = lCov < 0 ? a - 1 : mid < a + maxRadius - 1 ? mid : a + maxRadius - 1\n const rStart = rCov < 0 ? x + 1 : mid + 1 > x - maxRadius + 1 ? mid + 1 : x - maxRadius + 1\n for (let p = a, d = 1; p <= lEnd; p++, d++) {\n distances[distRow + p] = sign * (d * d + lCost)\n }\n if (lEnd + 1 < rStart) {\n distances.fill(sign * FAR_DISTANCE_SQUARED, distRow + lEnd + 1, distRow + rStart)\n }\n for (let p = rStart, d = x + 1 - rStart; p <= x; p++, d--) {\n distances[distRow + p] = sign * (d * d + rCost)\n }\n } else {\n distances[distRow + x] = coverage < 128 ? SEED_COST[coverage]! : -SEED_COST[coverage]!\n }\n }\n return lastNonZero\n}\n\n/**\n * Encode an alpha coverage mask as a single-channel signed distance field.\n *\n * The returned byte uses the conventional SDF encoding:\n *\n * - the edge is 0.5 (the nearest byte representation is 128),\n * - inside pixels are greater than 0.5,\n * - outside pixels are less than 0.5,\n * - `pxRange` pixels of signed distance span one encoded unit.\n *\n * Fractional source alpha is retained as a sub-pixel seed cost rather than\n * thresholded away. The two exact Euclidean distance transforms are O(width *\n * height); temporary storage is one grid plus O(height) scratch.\n */\nexport function encodeSdfFromAlpha(\n alpha: AlphaPixels,\n width: number,\n height: number,\n pxRange: number,\n): Uint8Array {\n const pixelCount = assertInputs(alpha, width, height, pxRange)\n const encoded = new Uint8Array(pixelCount)\n const scale255 = 255 / pxRange\n const clampSqDist = 0.25 * pxRange * pxRange * (1 + 1e-6)\n const skipEmptyRows = clampSqDist <= FAR_DISTANCE_SQUARED\n const maxRadius = skipEmptyRows ? Math.ceil(0.5 * pxRange + 1) : width > height ? width : height\n // Pad power-of-two widths by one 64-byte cache line (16 floats) so vertical\n // column gathers do not alias onto the same L1 cache set on every row.\n const distStride = (width & 63) === 0 ? width + 16 : width\n const requiredDistances = distStride * height\n if (scratchDistances.length < requiredDistances) {\n scratchDistances = new Float32Array(requiredDistances)\n }\n if (scratchParabolaIndices.length < height) {\n scratchParabolaIndices = new Int32Array(height)\n scratchParabolaCosts = new Float32Array(height)\n scratchParabolaOffsets = new Float64Array(height)\n scratchBoundaries = new Float64Array(height)\n scratchInside = new Float32Array(height)\n scratchOutside = new Float32Array(height)\n scratchActiveRows = new Int32Array(height)\n }\n const distances = scratchDistances\n const activeRows = scratchActiveRows\n const inside = scratchInside\n const outside = scratchOutside\n const sentinel = skipEmptyRows ? FAR_DISTANCE_SQUARED : clampSqDist\n inside.fill(sentinel, 0, height)\n outside.fill(0, 0, height)\n const lastRow = height - 1\n const u32 =\n (alpha.byteOffset & 3) === 0\n ? new Uint32Array(alpha.buffer, alpha.byteOffset, alpha.byteLength >>> 2)\n : null\n\n let anyNonZero = false\n let scanY = 0\n while (scanY < height) {\n let bandCount = 0\n let bandMinX = width\n let bandMaxX = -1\n let lastActiveY = -1\n for (; scanY < height; scanY++) {\n const alphaRow = scanY * width\n let firstNonZero = 0\n if (u32 !== null && (alphaRow & 3) === 0) {\n const wStart = alphaRow >>> 2\n const wEnd = wStart + (width >>> 2)\n let w = wStart\n while (w < wEnd && u32[w] === 0) w++\n firstNonZero = (w - wStart) << 2\n }\n while (firstNonZero < width && alpha[alphaRow + firstNonZero] === 0) firstNonZero++\n if (firstNonZero === width) {\n if (!skipEmptyRows) {\n const distRow = bandCount * distStride\n distances.fill(FAR_DISTANCE_SQUARED, distRow, distRow + width)\n activeRows[bandCount++] = scanY\n lastActiveY = scanY\n } else if (bandCount > 0 && scanY - lastActiveY >= 2 * maxRadius) {\n scanY++\n break\n }\n continue\n }\n anyNonZero = true\n const distRow = bandCount * distStride\n const lastNonZero = horizontalRowDistances(\n alpha,\n alphaRow,\n distances,\n distRow,\n width,\n firstNonZero,\n maxRadius,\n )\n activeRows[bandCount++] = scanY\n lastActiveY = scanY\n if (firstNonZero < bandMinX) bandMinX = firstNonZero\n if (lastNonZero > bandMaxX) bandMaxX = lastNonZero\n }\n\n if (bandCount === 0) break\n if (!anyNonZero) {\n const byte = 128 - Math.sqrt(FAR_DISTANCE_SQUARED) * scale255\n const fillByte = byte <= 0 ? 0 : byte | 0\n if (fillByte !== 0) encoded.fill(fillByte)\n if (scratchDistances.length > 4_500_000) scratchDistances = new Float32Array(0)\n return encoded\n }\n\n const firstActiveY = activeRows[0]!\n const bandMinY = skipEmptyRows ? (firstActiveY > maxRadius ? firstActiveY - maxRadius : 0) : 0\n const bandMaxY = skipEmptyRows\n ? lastActiveY + maxRadius < lastRow\n ? lastActiveY + maxRadius\n : lastRow\n : lastRow\n const bandHeight = bandMaxY - bandMinY + 1\n const colStart = skipEmptyRows ? (bandMinX > maxRadius ? bandMinX - maxRadius : 0) : 0\n const colEnd = skipEmptyRows\n ? bandMaxX + maxRadius < width - 1\n ? bandMaxX + maxRadius\n : width - 1\n : width - 1\n\n for (let x = colStart; x <= colEnd; x++) {\n // Transform contiguous columns in scratch instead of repeatedly traversing\n // two atlas-sized grids at a cache-unfriendly stride.\n let r = 0\n let offset = x\n while (r < bandCount && distances[offset]! >= clampSqDist) {\n r++\n offset += distStride\n }\n if (r === bandCount) continue\n const firstInSeed = activeRows[r]!\n let lastInSeed = firstInSeed\n let firstNeg = -1\n let lastNeg = -1\n let negCount = 0\n for (; r < bandCount; r++, offset += distStride) {\n const distance = distances[offset]!\n if (distance >= clampSqDist) continue\n const y = activeRows[r]!\n lastInSeed = y\n if (distance >= 0) {\n inside[y] = distance\n } else {\n inside[y] = 0\n outside[y] = -distance\n if (firstNeg < 0) firstNeg = y\n lastNeg = y\n negCount++\n }\n }\n const hasPositive = negCount < bandHeight\n let yStart = bandMinY\n let yEnd = bandMaxY\n if (hasPositive) {\n edt1d(inside, firstInSeed, lastInSeed, bandMinY, bandMaxY, clampSqDist, maxRadius)\n yStart = edtMinOut\n yEnd = edtMaxOut\n }\n const pureInEnd = firstNeg < 0 ? yEnd : firstNeg - 1\n let y = yStart\n let idx = y * width + x\n for (; y <= pureInEnd; y++, idx += width) {\n const inSq = inside[y]!\n if (inSq < clampSqDist) encoded[idx] = (128 - Math.sqrt(inSq) * scale255) | 0\n }\n if (firstNeg >= 0) {\n edt1d(\n outside,\n firstNeg > 0 ? firstNeg - 1 : 0,\n lastNeg < lastRow ? lastNeg + 1 : lastRow,\n firstNeg,\n lastNeg,\n clampSqDist,\n maxRadius,\n )\n for (; y <= lastNeg; y++, idx += width) {\n const inSq = inside[y]!\n if (inSq > 0) {\n if (inSq < clampSqDist) encoded[idx] = (128 - Math.sqrt(inSq) * scale255) | 0\n } else {\n const outSq = outside[y]!\n encoded[idx] = outSq >= clampSqDist ? 255 : (128 + Math.sqrt(outSq) * scale255) | 0\n }\n }\n for (; y <= yEnd; y++, idx += width) {\n const inSq = inside[y]!\n if (inSq < clampSqDist) encoded[idx] = (128 - Math.sqrt(inSq) * scale255) | 0\n }\n outside.fill(0, firstNeg, lastNeg + 1)\n }\n inside.fill(sentinel, yStart, yEnd + 1)\n }\n }\n\n if (scratchDistances.length > 4_500_000) scratchDistances = new Float32Array(0)\n return encoded\n}\n"],"mappings":";;;;;;;;;AAQA,IAAM,uBAAuB;;AAK7B,SAAgB,YAAY,MAAyB,YAAgC;CACnF,MAAM,QAAQ,IAAI,WAAW,UAAU;CACvC,KAAK,IAAI,SAAS,GAAG,SAAS,GAAG,SAAS,YAAY,UAAU,GAAG,UACjE,MAAM,UAAU,KAAK;CAEvB,OAAO;AACT;AAEA,SAAS,aAAa,OAAoB,OAAe,QAAgB,SAAyB;CAChG,IAAI,EAAE,iBAAiB,eAAe,EAAE,iBAAiB,oBACvD,MAAM,IAAI,UAAU,qEAAqE;CAE3F,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,SAAS,GACvC,MAAM,IAAI,WAAW,sDAAsD;CAE7E,IAAI,CAAC,OAAO,UAAU,MAAM,KAAK,UAAU,GACzC,MAAM,IAAI,WAAW,uDAAuD;CAG9E,MAAM,aAAa,QAAQ;CAC3B,IAAI,CAAC,OAAO,cAAc,UAAU,GAClC,MAAM,IAAI,WAAW,mEAAmE;CAE1F,IAAI,MAAM,WAAW,YACnB,MAAM,IAAI,WACR,oCAAoC,MAAM,OAAO,kCAAkC,WAAW,EAChG;CAEF,IAAI,CAAC,OAAO,SAAS,OAAO,KAAK,WAAW,GAC1C,MAAM,IAAI,WAAW,8DAA8D;CAGrF,OAAO;AACT;AAEA,IAAI,YAAY;AAChB,IAAI,YAAY;;;;;;;;;;AAWhB,SAAS,MACP,MACA,WACA,SACA,UACA,QACA,aACA,WACM;CACN,IAAI,QAAQ;CACZ,OAAO,SAAS,WAAW,KAAK,UAAW,aAAa;CACxD,IAAI,QAAQ,SAAS;EACnB,YAAY,SAAS;EACrB,YAAY,WAAW;EACvB;CACF;CAEA,MAAM,YAAY,KAAK;CACvB,IAAI,UAAU,UAAU;EACtB,IAAI,YAAY,QAAQ;EACxB,IA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F;IACF;IACA,OAAO,KAAK,MAAM,KAAK,OAAO,OAAO;KACnC,MAAM,OAAO,OAAO;KACpB,IAAI,OAAO,aAAa,QAAQ,OAAQ,MAAM,KAAK,KAAK,IAAI,IAAI,WAAY;IAC9E;IACA,QAAQ,KAAK,GAAG,UAAU,UAAU,CAAC;GACvC;GACA,OAAO,KAAK,UAAU,QAAQ,OAAO,CAAC;EACxC;CACF;CAEA,IAAI,iBAAiB,SAAS,MAAW,mCAAmB,IAAI,aAAa,CAAC;CAC9E,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"cpuSdf.js","names":[],"sources":["../../src/atlas/cpuSdf.ts"],"sourcesContent":["/**\n * A finite stand-in for infinity in the squared-distance grids.\n *\n * Keeping the sentinel finite avoids `Infinity - Infinity` while constructing\n * the lower envelope of parabolas. Its square root is far beyond any practical\n * atlas extent, so missing inside/outside pixels still saturate at the correct\n * encoded endpoint.\n */\nconst FAR_DISTANCE_SQUARED = 1e20\n\ntype AlphaPixels = Uint8Array | Uint8ClampedArray\n\n/** The alpha byte of each RGBA pixel, as the encoder reads coverage. */\nexport function alphaOfRgba(rgba: Uint8ClampedArray, pixelCount: number): Uint8Array {\n const alpha = new Uint8Array(pixelCount)\n for (let source = 3, target = 0; target < pixelCount; source += 4, target++) {\n alpha[target] = rgba[source]!\n }\n return alpha\n}\n\nfunction assertInputs(alpha: AlphaPixels, width: number, height: number, pxRange: number): number {\n if (!(alpha instanceof Uint8Array) && !(alpha instanceof Uint8ClampedArray)) {\n throw new TypeError('encodeSdfFromAlpha: alpha must be a Uint8Array or Uint8ClampedArray')\n }\n if (!Number.isInteger(width) || width <= 0) {\n throw new RangeError('encodeSdfFromAlpha: width must be a positive integer')\n }\n if (!Number.isInteger(height) || height <= 0) {\n throw new RangeError('encodeSdfFromAlpha: height must be a positive integer')\n }\n\n const pixelCount = width * height\n if (!Number.isSafeInteger(pixelCount)) {\n throw new RangeError('encodeSdfFromAlpha: width * height exceeds the safe integer range')\n }\n if (alpha.length !== pixelCount) {\n throw new RangeError(\n `encodeSdfFromAlpha: alpha length ${alpha.length} does not match width * height (${pixelCount})`,\n )\n }\n if (!Number.isFinite(pxRange) || pxRange <= 0) {\n throw new RangeError('encodeSdfFromAlpha: pxRange must be a positive finite number')\n }\n\n return pixelCount\n}\n\nlet edtMinOut = 0\nlet edtMaxOut = -1\n\n/**\n * Exact one-dimensional squared Euclidean distance transform.\n *\n * This is the lower-envelope algorithm from Felzenszwalb and Huttenlocher. It\n * runs in O(length), performs no allocations, and accepts non-zero seed costs\n * so fractional alpha coverage can place the glyph edge between pixel centres.\n * The envelope retains the original costs before writing back into the grid,\n * avoiding a copy of each column in both directions.\n */\nfunction edt1d(\n grid: Float32Array,\n startSeed: number,\n endSeed: number,\n outStart: number,\n outEnd: number,\n clampSqDist: number,\n maxRadius: number,\n): void {\n let first = startSeed\n while (first <= endSeed && grid[first]! >= clampSqDist) first++\n if (first > endSeed) {\n edtMinOut = outEnd + 1\n edtMaxOut = outStart - 1\n return\n }\n\n const firstCost = grid[first]!\n if (first === outStart) {\n let different = first + 1\n if (firstCost <= 1) {\n while (different <= endSeed && grid[different]! <= 1) different++\n } else {\n while (different <= endSeed && grid[different] === firstCost) different++\n }\n // A constant line or a line of immediate seeds (cost <= 1) is already its own distance transform.\n if (different > endSeed && endSeed >= outEnd) {\n edtMinOut = outStart\n edtMaxOut = outEnd\n return\n }\n }\n\n const parabolaIndices = scratchParabolaIndices\n const parabolaCosts = scratchParabolaCosts\n const parabolaOffsets = scratchParabolaOffsets\n const boundaries = scratchBoundaries\n let envelopeEnd = 0\n parabolaIndices[0] = first\n parabolaCosts[0] = firstCost\n parabolaOffsets[0] = firstCost + first * first\n\n for (let q = first + 1; q <= endSeed; q++) {\n let cost = grid[q]!\n if (cost >= clampSqDist) {\n while (q < endSeed && grid[q + 1]! >= clampSqDist) q++\n continue\n }\n if (cost <= 1 && grid[q - 1]! <= 1) {\n while (q < endSeed && grid[q + 1]! <= 1) q++\n cost = grid[q]!\n } else if (cost === grid[q - 1]!) {\n while (q < endSeed && grid[q + 1] === cost) q++\n }\n const costPlusQSquared = cost + q * q\n while (\n envelopeEnd > 0 &&\n costPlusQSquared - parabolaOffsets[envelopeEnd]! <=\n boundaries[envelopeEnd]! * (q - parabolaIndices[envelopeEnd]!)\n ) {\n envelopeEnd--\n }\n const twiceIntersection =\n (costPlusQSquared - parabolaOffsets[envelopeEnd]!) / (q - parabolaIndices[envelopeEnd]!)\n\n envelopeEnd++\n parabolaIndices[envelopeEnd] = q\n parabolaCosts[envelopeEnd] = cost\n parabolaOffsets[envelopeEnd] = costPlusQSquared\n boundaries[envelopeEnd] = twiceIntersection\n }\n\n const minOut = first - maxRadius > outStart ? first - maxRadius : outStart\n const lastSeed = parabolaIndices[envelopeEnd]!\n const maxOut = lastSeed + maxRadius < outEnd ? lastSeed + maxRadius : outEnd\n let b0 = minOut\n for (let e = 0; e <= envelopeEnd; e++) {\n const b1 = e === envelopeEnd ? maxOut : Math.floor(boundaries[e + 1]! * 0.5)\n if (b1 >= b0) {\n const nearest = parabolaIndices[e]!\n const cost = parabolaCosts[e]!\n const r0 = nearest - maxRadius\n const r1 = nearest + maxRadius\n const s1 = maxOut < b1 ? maxOut : b1\n const segStart = b0 > r0 ? b0 : r0\n const segEnd = s1 < r1 ? s1 : r1\n for (let q = segStart; q <= segEnd; q++) {\n const cur = grid[q]!\n if (cur <= 1) continue\n const delta = q - nearest\n const d = delta * delta + cost\n if (d < cur) grid[q] = d\n }\n b0 = b1 + 1\n if (b0 > maxOut) break\n }\n }\n edtMinOut = minOut\n edtMaxOut = maxOut\n}\n\nconst SEED_COST = Float32Array.from({ length: 256 }, (_, coverage) => {\n const edgeOffset = 0.5 - coverage / 255\n const sq = Math.fround(edgeOffset * edgeOffset)\n return coverage < 128 ? sq : -sq\n})\n\nlet scratchDistances = new Float32Array(0)\nlet scratchParabolaIndices = new Int32Array(0)\nlet scratchParabolaCosts = new Float32Array(0)\nlet scratchParabolaOffsets = new Float64Array(0)\nlet scratchBoundaries = new Float64Array(0)\nlet scratchInside = new Float32Array(0)\nlet scratchOutside = new Float32Array(0)\nlet scratchActiveRows = new Int32Array(0)\n\n/**\n * Alpha seeds cost less than 0.25. A closer seed therefore always beats a\n * farther seed in the same direction (squared integer distances differ by at\n * least one). Each empty or solid run is bounded by at most one seed on each\n * side, so one pass splits each run at its midpoint and fills both ends.\n */\nfunction horizontalRowDistances(\n alpha: AlphaPixels,\n alphaRow: number,\n distances: Float32Array,\n distRow: number,\n width: number,\n firstNonZero: number,\n maxRadius: number,\n): number {\n let lastNonZero = width - 1\n for (let x = 0; x < width; x++) {\n const coverage = alpha[alphaRow + x]!\n if (coverage === 0 || coverage === 255) {\n const a = x\n if (x === 0 && firstNonZero > 0) x = firstNonZero - 1\n else while (x + 1 < width && alpha[alphaRow + x + 1] === coverage) x++\n const isZero = coverage === 0\n if (isZero && x === width - 1) lastNonZero = a - 1\n const sign = isZero ? 1 : -1\n const lCov = a > 0 ? alpha[alphaRow + a - 1]! : -1\n const rCov = x + 1 < width ? alpha[alphaRow + x + 1]! : -1\n const lSc = lCov < 0 ? FAR_DISTANCE_SQUARED : sign * SEED_COST[lCov]!\n const rSc = rCov < 0 ? FAR_DISTANCE_SQUARED : sign * SEED_COST[rCov]!\n const lCost = lSc > 0 ? lSc : 0\n const rCost = rSc > 0 ? rSc : 0\n const mid = rCov < 0 ? x : lCov < 0 ? a - 1 : (a + x - (rCost < lCost ? 1 : 0)) >> 1\n const lEnd = lCov < 0 ? a - 1 : mid < a + maxRadius - 1 ? mid : a + maxRadius - 1\n const rStart = rCov < 0 ? x + 1 : mid + 1 > x - maxRadius + 1 ? mid + 1 : x - maxRadius + 1\n for (let p = a, d = 1; p <= lEnd; p++, d++) {\n distances[distRow + p] = sign * (d * d + lCost)\n }\n if (lEnd + 1 < rStart) {\n distances.fill(sign * FAR_DISTANCE_SQUARED, distRow + lEnd + 1, distRow + rStart)\n }\n for (let p = rStart, d = x + 1 - rStart; p <= x; p++, d--) {\n distances[distRow + p] = sign * (d * d + rCost)\n }\n } else {\n distances[distRow + x] = SEED_COST[coverage]!\n }\n }\n return lastNonZero\n}\n\n/**\n * Encode an alpha coverage mask as a single-channel signed distance field.\n *\n * The returned byte uses the conventional SDF encoding:\n *\n * - the edge is 0.5 (the nearest byte representation is 128),\n * - inside pixels are greater than 0.5,\n * - outside pixels are less than 0.5,\n * - `pxRange` pixels of signed distance span one encoded unit.\n *\n * Fractional source alpha is retained as a sub-pixel seed cost rather than\n * thresholded away. The two exact Euclidean distance transforms are O(width *\n * height); temporary storage is one grid plus O(height) scratch.\n */\nexport function encodeSdfFromAlpha(\n alpha: AlphaPixels,\n width: number,\n height: number,\n pxRange: number,\n): Uint8Array {\n const pixelCount = assertInputs(alpha, width, height, pxRange)\n const encoded = new Uint8Array(pixelCount)\n const scale255 = 255 / pxRange\n const clampSqDist = 0.25 * pxRange * pxRange * (1 + 1e-6)\n const skipEmptyRows = clampSqDist <= FAR_DISTANCE_SQUARED\n const maxRadius = skipEmptyRows ? Math.ceil(0.5 * pxRange + 1) : width > height ? width : height\n // Pad power-of-two widths by one 64-byte cache line (16 floats) so vertical\n // column gathers do not alias onto the same L1 cache set on every row.\n const distStride = (width & 63) === 0 ? width + 16 : width\n const requiredDistances = distStride * height\n if (scratchDistances.length < requiredDistances) {\n scratchDistances = new Float32Array(requiredDistances)\n }\n if (scratchParabolaIndices.length < height) {\n scratchParabolaIndices = new Int32Array(height)\n scratchParabolaCosts = new Float32Array(height)\n scratchParabolaOffsets = new Float64Array(height)\n scratchBoundaries = new Float64Array(height)\n scratchInside = new Float32Array(height)\n scratchOutside = new Float32Array(height)\n scratchActiveRows = new Int32Array(height)\n }\n const distances = scratchDistances\n const activeRows = scratchActiveRows\n const inside = scratchInside\n const outside = scratchOutside\n const sentinel = skipEmptyRows ? FAR_DISTANCE_SQUARED : clampSqDist\n inside.fill(sentinel, 0, height)\n outside.fill(0, 0, height)\n const lastRow = height - 1\n const u32 =\n (alpha.byteOffset & 3) === 0\n ? new Uint32Array(alpha.buffer, alpha.byteOffset, alpha.byteLength >>> 2)\n : null\n\n let anyNonZero = false\n let scanY = 0\n while (scanY < height) {\n let bandCount = 0\n let bandMinX = width\n let bandMaxX = -1\n let lastActiveY = -1\n for (; scanY < height; scanY++) {\n const alphaRow = scanY * width\n let firstNonZero = 0\n if (u32 !== null && (alphaRow & 3) === 0) {\n const wStart = alphaRow >>> 2\n const wEnd = wStart + (width >>> 2)\n let w = wStart\n while (w < wEnd && u32[w] === 0) w++\n firstNonZero = (w - wStart) << 2\n }\n while (firstNonZero < width && alpha[alphaRow + firstNonZero] === 0) firstNonZero++\n if (firstNonZero === width) {\n if (!skipEmptyRows) {\n const distRow = bandCount * distStride\n distances.fill(FAR_DISTANCE_SQUARED, distRow, distRow + width)\n activeRows[bandCount++] = scanY\n lastActiveY = scanY\n } else if (bandCount > 0 && scanY - lastActiveY >= 2 * maxRadius) {\n scanY++\n break\n }\n continue\n }\n anyNonZero = true\n const distRow = bandCount * distStride\n const lastNonZero = horizontalRowDistances(\n alpha,\n alphaRow,\n distances,\n distRow,\n width,\n firstNonZero,\n maxRadius,\n )\n activeRows[bandCount++] = scanY\n lastActiveY = scanY\n if (firstNonZero < bandMinX) bandMinX = firstNonZero\n if (lastNonZero > bandMaxX) bandMaxX = lastNonZero\n }\n\n if (bandCount === 0) break\n if (!anyNonZero) {\n const byte = 128 - Math.sqrt(FAR_DISTANCE_SQUARED) * scale255\n const fillByte = byte <= 0 ? 0 : byte | 0\n if (fillByte !== 0) encoded.fill(fillByte)\n if (scratchDistances.length > 4_500_000) scratchDistances = new Float32Array(0)\n return encoded\n }\n\n const firstActiveY = activeRows[0]!\n const bandMinY = skipEmptyRows ? (firstActiveY > maxRadius ? firstActiveY - maxRadius : 0) : 0\n const bandMaxY = skipEmptyRows\n ? lastActiveY + maxRadius < lastRow\n ? lastActiveY + maxRadius\n : lastRow\n : lastRow\n const bandHeight = bandMaxY - bandMinY + 1\n const colStart = skipEmptyRows ? (bandMinX > maxRadius ? bandMinX - maxRadius : 0) : 0\n const colEnd = skipEmptyRows\n ? bandMaxX + maxRadius < width - 1\n ? bandMaxX + maxRadius\n : width - 1\n : width - 1\n\n for (let x = colStart; x <= colEnd; x++) {\n let r = 0\n let offset = x\n while (r < bandCount && distances[offset]! >= clampSqDist) {\n r++\n offset += distStride\n }\n if (r === bandCount) continue\n const firstInSeed = activeRows[r]!\n let lastInSeed = firstInSeed\n let firstNeg = -1\n let lastNeg = -1\n let negCount = 0\n for (; r < bandCount; r++, offset += distStride) {\n const distance = distances[offset]!\n if (distance >= clampSqDist) continue\n const y = activeRows[r]!\n lastInSeed = y\n if (distance >= 0) {\n inside[y] = distance\n } else {\n inside[y] = 0\n outside[y] = -distance\n if (firstNeg < 0) firstNeg = y\n lastNeg = y\n negCount++\n }\n }\n let yStart = bandMinY\n let yEnd = bandMaxY\n if (negCount < bandHeight) {\n edt1d(inside, firstInSeed, lastInSeed, bandMinY, bandMaxY, clampSqDist, maxRadius)\n yStart = edtMinOut\n yEnd = edtMaxOut\n }\n const pureInEnd = firstNeg < 0 ? yEnd : firstNeg - 1\n let y = yStart\n let idx = y * width + x\n for (; y <= pureInEnd; y++, idx += width) {\n const inSq = inside[y]!\n if (inSq < clampSqDist) encoded[idx] = (128 - Math.sqrt(inSq) * scale255) | 0\n }\n if (firstNeg >= 0) {\n edt1d(\n outside,\n firstNeg > 0 ? firstNeg - 1 : 0,\n lastNeg < lastRow ? lastNeg + 1 : lastRow,\n firstNeg,\n lastNeg,\n clampSqDist,\n maxRadius,\n )\n for (; y <= lastNeg; y++, idx += width) {\n const inSq = inside[y]!\n if (inSq > 0) {\n if (inSq < clampSqDist) encoded[idx] = (128 - Math.sqrt(inSq) * scale255) | 0\n } else {\n const outSq = outside[y]!\n encoded[idx] = outSq >= clampSqDist ? 255 : (128 + Math.sqrt(outSq) * scale255) | 0\n }\n }\n for (; y <= yEnd; y++, idx += width) {\n const inSq = inside[y]!\n if (inSq < clampSqDist) encoded[idx] = (128 - Math.sqrt(inSq) * scale255) | 0\n }\n outside.fill(0, firstNeg, lastNeg + 1)\n }\n inside.fill(sentinel, yStart, yEnd + 1)\n }\n }\n\n if (scratchDistances.length > 4_500_000) scratchDistances = new Float32Array(0)\n return encoded\n}\n"],"mappings":";;;;;;;;;AAQA,IAAM,uBAAuB;;AAK7B,SAAgB,YAAY,MAAyB,YAAgC;CACnF,MAAM,QAAQ,IAAI,WAAW,UAAU;CACvC,KAAK,IAAI,SAAS,GAAG,SAAS,GAAG,SAAS,YAAY,UAAU,GAAG,UACjE,MAAM,UAAU,KAAK;CAEvB,OAAO;AACT;AAEA,SAAS,aAAa,OAAoB,OAAe,QAAgB,SAAyB;CAChG,IAAI,EAAE,iBAAiB,eAAe,EAAE,iBAAiB,oBACvD,MAAM,IAAI,UAAU,qEAAqE;CAE3F,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,SAAS,GACvC,MAAM,IAAI,WAAW,sDAAsD;CAE7E,IAAI,CAAC,OAAO,UAAU,MAAM,KAAK,UAAU,GACzC,MAAM,IAAI,WAAW,uDAAuD;CAG9E,MAAM,aAAa,QAAQ;CAC3B,IAAI,CAAC,OAAO,cAAc,UAAU,GAClC,MAAM,IAAI,WAAW,mEAAmE;CAE1F,IAAI,MAAM,WAAW,YACnB,MAAM,IAAI,WACR,oCAAoC,MAAM,OAAO,kCAAkC,WAAW,EAChG;CAEF,IAAI,CAAC,OAAO,SAAS,OAAO,KAAK,WAAW,GAC1C,MAAM,IAAI,WAAW,8DAA8D;CAGrF,OAAO;AACT;AAEA,IAAI,YAAY;AAChB,IAAI,YAAY;;;;;;;;;;AAWhB,SAAS,MACP,MACA,WACA,SACA,UACA,QACA,aACA,WACM;CACN,IAAI,QAAQ;CACZ,OAAO,SAAS,WAAW,KAAK,UAAW,aAAa;CACxD,IAAI,QAAQ,SAAS;EACnB,YAAY,SAAS;EACrB,YAAY,WAAW;EACvB;CACF;CAEA,MAAM,YAAY,KAA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AO,SAAS,cAAc,MAAO,MAAM,KAAK,KAAK,KAAK,IAAI,WAAY;KACpF;IACF;IACA,OAAO,KAAK,MAAM,KAAK,OAAO,OAAO;KACnC,MAAM,OAAO,OAAO;KACpB,IAAI,OAAO,aAAa,QAAQ,OAAQ,MAAM,KAAK,KAAK,IAAI,IAAI,WAAY;IAC9E;IACA,QAAQ,KAAK,GAAG,UAAU,UAAU,CAAC;GACvC;GACA,OAAO,KAAK,UAAU,QAAQ,OAAO,CAAC;EACxC;CACF;CAEA,IAAI,iBAAiB,SAAS,MAAW,mCAAmB,IAAI,aAAa,CAAC;CAC9E,OAAO;AACT"}
|
package/dist/atlas/cpuWorker.js
CHANGED
|
@@ -8,7 +8,7 @@ function encodeInWorker(rgba, width, height, pxRange, signal) {
|
|
|
8
8
|
return new Promise((resolve, reject) => {
|
|
9
9
|
const worker = new Worker(new URL(
|
|
10
10
|
/* @vite-ignore */
|
|
11
|
-
new URL("../assets/cpuSdf.worker-
|
|
11
|
+
new URL("../assets/cpuSdf.worker-xS57yQbP.js", import.meta.url).href,
|
|
12
12
|
"" + import.meta.url
|
|
13
13
|
), { type: "module" });
|
|
14
14
|
let settled = false;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cpuWorker.js","names":["import.meta.
|
|
1
|
+
{"version":3,"file":"cpuWorker.js","names":["import.meta.ROLLDOWN_FILE_URL_S56VmzbjS7pAQy$YWm43JA"],"sources":["../../src/atlas/cpuWorker.ts"],"sourcesContent":["/**\n * One short-lived worker per bake: termination also cancels a synchronous EDT. The canvas's\n * RGBA pixels are transferred, so the caller no longer owns them; the worker takes their alpha.\n */\nexport function encodeInWorker(\n rgba: Uint8ClampedArray,\n width: number,\n height: number,\n pxRange: number,\n signal?: AbortSignal,\n): Promise<Uint8Array> {\n signal?.throwIfAborted()\n return new Promise((resolve, reject) => {\n const worker = new Worker(new URL('./cpuSdf.worker.js', import.meta.url), { type: 'module' })\n let settled = false\n const finish = (error?: unknown, result?: Uint8Array): void => {\n if (settled) return\n settled = true\n signal?.removeEventListener('abort', abort)\n worker.terminate()\n if (result) resolve(result)\n // AbortSignal.reason is caller-owned and can be any value.\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n else reject(error)\n }\n const abort = (): void => finish(signal?.reason)\n signal?.addEventListener('abort', abort, { once: true })\n worker.onmessage = (event: MessageEvent<unknown>) => {\n const result = event.data\n if (!(result instanceof Uint8Array) || result.length !== width * height) {\n finish(new Error('Invalid CPU SDF worker result'))\n } else finish(undefined, result)\n }\n worker.onerror = (event) => {\n event.preventDefault()\n finish(new Error(event.message || 'CPU SDF worker failed'))\n }\n worker.onmessageerror = () => finish(new Error('CPU SDF worker transfer failed'))\n try {\n worker.postMessage({ rgba, width, height, pxRange }, [rgba.buffer as ArrayBuffer])\n } catch (error) {\n finish(error)\n }\n })\n}\n"],"mappings":";;;;;AAIA,SAAgB,eACd,MACA,OACA,QACA,SACA,QACqB;CACrB,QAAQ,eAAe;CACvB,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,MAAM,SAAS,IAAI,OAAO,IAAA;;GAAA,IAAA,IAAA,uCAAA,YAAA,GAAA,CAAA,CAAAA;GAAA,KAAA,YAAA;EAAA,GAAgD,EAAE,MAAM,SAAS,CAAC;EAC5F,IAAI,UAAU;EACd,MAAM,UAAU,OAAiB,WAA8B;GAC7D,IAAI,SAAS;GACb,UAAU;GACV,QAAQ,oBAAoB,SAAS,KAAK;GAC1C,OAAO,UAAU;GACjB,IAAI,QAAQ,QAAQ,MAAM;QAGrB,OAAO,KAAK;EACnB;EACA,MAAM,cAAoB,OAAO,QAAQ,MAAM;EAC/C,QAAQ,iBAAiB,SAAS,OAAO,EAAE,MAAM,KAAK,CAAC;EACvD,OAAO,aAAa,UAAiC;GACnD,MAAM,SAAS,MAAM;GACrB,IAAI,EAAE,kBAAkB,eAAe,OAAO,WAAW,QAAQ,QAC/D,uBAAO,IAAI,MAAM,+BAA+B,CAAC;QAC5C,OAAO,KAAA,GAAW,MAAM;EACjC;EACA,OAAO,WAAW,UAAU;GAC1B,MAAM,eAAe;GACrB,OAAO,IAAI,MAAM,MAAM,WAAW,uBAAuB,CAAC;EAC5D;EACA,OAAO,uBAAuB,uBAAO,IAAI,MAAM,gCAAgC,CAAC;EAChF,IAAI;GACF,OAAO,YAAY;IAAE;IAAM;IAAO;IAAQ;GAAQ,GAAG,CAAC,KAAK,MAAqB,CAAC;EACnF,SAAS,OAAO;GACd,OAAO,KAAK;EACd;CACF,CAAC;AACH"}
|
package/dist/atlas/gpuAtlas.d.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { type WebGPURenderer } from 'three/webgpu';
|
|
2
2
|
import type { BuildSdfAtlasOptions, RasterAtlas, SdfAtlas } from '../types.js';
|
|
3
3
|
/**
|
|
4
|
-
* Generates a compact R8 runtime SDF on the renderer's WebGPU device: boundary seeding and
|
|
5
|
-
*
|
|
6
|
-
* texture is
|
|
7
|
-
*
|
|
8
|
-
* the passes, the backend lacks the calls, or the device reports an error for them.
|
|
4
|
+
* Generates a compact R8 runtime SDF on the renderer's WebGPU device: boundary seeding and
|
|
5
|
+
* 4-byte relative fixed-point jump flooding in compute passes, writing directly into `r8unorm`
|
|
6
|
+
* when `'texture-formats-tier1'` is active on the device or resolving via a fullscreen render
|
|
7
|
+
* pass on Core WebGPU 1.0 devices.
|
|
9
8
|
*/
|
|
10
|
-
export declare function buildGpuSdfAtlas(renderer: WebGPURenderer, raster: RasterAtlas, options?: Pick<BuildSdfAtlasOptions, 'mipmaps' | 'anisotropy'
|
|
9
|
+
export declare function buildGpuSdfAtlas(renderer: WebGPURenderer, raster: RasterAtlas, options?: Pick<BuildSdfAtlasOptions, 'mipmaps' | 'anisotropy'>,
|
|
10
|
+
/** @internal */
|
|
11
|
+
onProvisional?: (atlas: SdfAtlas) => void): Promise<SdfAtlas>;
|