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":"tracedOutlines.js","names":[],"sources":["../../src/windfoil/tracedOutlines.ts"],"sourcesContent":["import { createCanvas, isColorCandidate, setFontContext, waitForFonts } from '../atlas/rasterize.js'\nimport type {\n ColorGlyphMode,\n FontStyleSnapshot,\n GlyphRequest,\n WindfoilGlyphOutline,\n WindfoilOutlineProvider,\n} from '../types.js'\nimport { createTraceScratch, traceCoverage } from './trace/outline.js'\n\n/** @internal Options of the built-in outline tracer. */\nexport interface TracedOutlineOptions {\n /** Trace resolution in pixels per em, also each outline's `unitsPerEm`. Defaults to `256`. */\n readonly size?: number\n /** Furthest, in trace pixels, a fitted curve may stray from its contour. Defaults to `0.25`. */\n readonly tolerance?: number\n /** Which glyphs to test for colour ink, as `DomSdfOptions.colorGlyphs`. Defaults to `'emoji'`. */\n readonly colorGlyphs?: ColorGlyphMode\n}\n\n/** @internal A `WindfoilOutlineProvider` that traces the browser's own glyphs, and its cache. */\nexport interface TracedOutlines {\n readonly provider: WindfoilOutlineProvider\n /** Forgets every traced outline, as after a webfont load; work in flight is not kept. */\n clear(): void\n /** Forgets the outlines of every glyph key not listed. */\n retain(keys: Iterable<string>): void\n}\n\n/** A batch yields to the page once it has traced for this long. */\nconst SLICE_MS = 8\n/** A font assignment the canvas rejects leaves this one in place. */\nconst SENTINEL_FONT = '1px serif'\nconst SIZE_TOKEN = /[\\d.]+px/\n\n/** The requests one task made with one signal, traced together. */\ninterface Batch {\n readonly signal: AbortSignal\n readonly requests: Map<string, GlyphRequest>\n readonly done: Promise<ReadonlyMap<string, WindfoilGlyphOutline | null>>\n}\n\n/** One glyph between measuring and tracing, in trace pixels; y grows downwards. */\ninterface Measured {\n readonly request: GlyphRequest\n readonly ascent: number\n readonly descent: number\n /** How far the ink box and the font box reach from the pen: left, right, up and down. */\n readonly reach: readonly [number, number, number, number]\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n if (signal.aborted) {\n throw signal.reason ?? new DOMException('The outline trace was aborted', 'AbortError')\n }\n}\n\n/**\n * A task after the page's own: a message is not clamped to 4 ms as a nested timer is, and it\n * does not run ahead of rendering as a `scheduler.yield()` continuation does, which held frames\n * back for 100 ms at a time in Chrome 156.\n */\nfunction nextTask(): Promise<void> {\n return new Promise((resolve) => {\n if (typeof MessageChannel !== 'function') {\n setTimeout(resolve, 0)\n return\n }\n const { port1, port2 } = new MessageChannel()\n port1.onmessage = () => {\n port1.close()\n resolve()\n }\n port2.postMessage(null)\n })\n}\n\n/** Canvas box of a glyph with `margin` pixels around its reach: pen position and size. */\nfunction boxOf(\n reach: Measured['reach'],\n margin: number,\n): [originX: number, baselineY: number, width: number, height: number] {\n const originX = margin + Math.ceil(reach[0])\n const baselineY = margin + Math.ceil(reach[2])\n return [\n originX,\n baselineY,\n originX + Math.ceil(reach[1]) + margin,\n baselineY + Math.ceil(reach[3]) + margin,\n ]\n}\n\n/** Whether any texel on the edge of a `width` x `height` RGBA read holds ink. */\nfunction touchesEdge(rgba: Uint8ClampedArray, width: number, height: number): boolean {\n for (let x = 0; x < width; x++) {\n if (rgba[x * 4 + 3]! > 0 || rgba[((height - 1) * width + x) * 4 + 3]! > 0) return true\n }\n for (let y = 0; y < height; y++) {\n if (rgba[y * width * 4 + 3]! > 0 || rgba[((y + 1) * width - 1) * 4 + 3]! > 0) return true\n }\n return false\n}\n\n/**\n * @internal The outline provider `DomSdf` uses for Windfoil and Slug text when the caller gives\n * none. Each glyph is drawn as the SDF rasterizer draws it (the captured canvas font with its\n * stretch and kerning, an in-document canvas without font smoothing, exact geometry, a neutral\n * grey), at `size` pixels per em, then traced at half coverage and fitted with quadratics. The\n * outline follows that raster, not the font file: font-variation and feature settings are not\n * applied, as on any canvas. Colour glyphs, glyphs of a font the canvas rejects and shaped runs\n * resolve to `null`, for the SDF companion; a glyph without ink to an empty outline. Without a\n * 2D canvas every glyph is `null`, so the whole capture falls back to SDF. `descent` is the SDF\n * slot's, measured at the captured font's own size, so analytic and SDF glyphs share a baseline.\n * Ink the metrics miss is drawn again with half an em more room all round; a glyph whose ink\n * still reaches the edge of its box resolves to `null` too, rather than trace clipped.\n *\n * Calls made in one task with one signal trace as one batch, in slices of about 8 ms between\n * which the page runs and the signal is checked. Each batch has its own working memory, which\n * goes with it. Outlines stay cached per instance until `clear()` or `retain()` drops them; one\n * traced while `document.fonts.check()` still reported its font as not ready is never cached.\n */\nexport function createTracedOutlineProvider(\n document: Document,\n options: TracedOutlineOptions = {},\n): TracedOutlines {\n const size = options.size ?? 256\n const tolerance = options.tolerance ?? 0.25\n const colorGlyphs = options.colorGlyphs ?? 'emoji'\n const cache = new Map<string, WindfoilGlyphOutline | null>()\n let epoch = 0\n /** The batches still open to requests of this task, by signal. */\n const open = new Map<AbortSignal, Batch>()\n\n const run = async (\n signal: AbortSignal,\n requests: ReadonlyMap<string, GlyphRequest>,\n started: number,\n ): Promise<ReadonlyMap<string, WindfoilGlyphOutline | null>> => {\n const results = new Map<string, WindfoilGlyphOutline | null>()\n // Each font of the batch, as captured and as traced: the captured canvas font with only\n // its size rewritten, as an adaptive SDF bake does.\n const groups = new Map<string, [GlyphRequest[], FontStyleSnapshot]>()\n for (const request of requests.values()) {\n // Shapes resolve elsewhere; a shaped run is one tile of a line, which no outline covers.\n if (request.shape || request.shaping) {\n results.set(request.key, null)\n continue\n }\n const group = groups.get(request.font.key)\n if (group) group[0].push(request)\n else {\n const font = request.font\n groups.set(font.key, [\n [request],\n { ...font, canvasFont: font.canvasFont.replace(SIZE_TOKEN, `${size}px`) },\n ])\n }\n }\n const traced = (request: GlyphRequest): GlyphRequest => ({\n ...request,\n font: groups.get(request.font.key)![1],\n })\n await waitForFonts(\n document,\n [...groups.values()].flatMap(([list]) => list.map(traced)),\n signal,\n )\n throwIfAborted(signal)\n\n const fonts = document.fonts as FontFaceSet | undefined\n const keep = (request: GlyphRequest, outline: WindfoilGlyphOutline | null): void => {\n results.set(request.key, outline)\n let ready = epoch === started\n try {\n ready &&= fonts?.check(traced(request).font.canvasFont, request.character) ?? true\n } catch {\n ready = false\n }\n if (ready) cache.set(request.key, outline)\n }\n\n const canvas = createCanvas(document)\n try {\n const context = canvas.getContext('2d', { willReadFrequently: true })\n if (!context) {\n // Not cached: the whole capture falls back to SDF, and a later build may try again.\n for (const [list] of groups.values())\n for (const request of list) results.set(request.key, null)\n return results\n }\n let current: FontStyleSnapshot | null = null\n const accepted = new Map<FontStyleSnapshot, boolean>()\n /** Applies a request's font as the rasterizer does; false when the canvas rejected it. */\n const use = (request: GlyphRequest): boolean => {\n if (current !== request.font) {\n context.font = SENTINEL_FONT\n const sentinel = context.font\n setFontContext(context, request, undefined, null)\n current = request.font\n accepted.set(request.font, context.font !== sentinel)\n }\n return accepted.get(request.font)!\n }\n\n // Measure every glyph first: sizing the canvas resets its context.\n const margin = Math.max(4, Math.ceil(size / 32))\n const measured: Measured[] = []\n let canvasWidth = 1\n let canvasHeight = 1\n for (const [list] of groups.values()) {\n throwIfAborted(signal)\n const bake = Number.parseFloat(SIZE_TOKEN.exec(list[0]!.font.canvasFont)?.[0] ?? '')\n if (!(bake > 0) || !use(list[0]!)) {\n for (const request of list) keep(request, null)\n continue\n }\n // The SDF slot's metrics, measured at the captured font's own size.\n const scale = size / bake\n const slots = list.map((request) => {\n const slot = context.measureText(request.character)\n return [\n Math.max(1, slot.fontBoundingBoxAscent || slot.actualBoundingBoxAscent) * scale,\n Math.max(1, slot.fontBoundingBoxDescent || slot.actualBoundingBoxDescent) * scale,\n ] as const\n })\n if (!use(traced(list[0]!))) {\n for (const request of list) keep(request, null)\n continue\n }\n list.forEach((request, index) => {\n const [ascent, descent] = slots[index]!\n // Ink can only be found in the ink box and the font box.\n const metrics = context.measureText(request.character)\n const reach = [\n Math.max(0, metrics.actualBoundingBoxLeft || 0),\n Math.max(metrics.width || 0, metrics.actualBoundingBoxRight || 0),\n Math.max(ascent, metrics.actualBoundingBoxAscent || 0),\n Math.max(descent, metrics.actualBoundingBoxDescent || 0),\n ] as const\n const [, , width, height] = boxOf(reach, margin)\n if (!(width <= 8 * size && height <= 8 * size)) {\n keep(request, null)\n return\n }\n canvasWidth = Math.max(canvasWidth, width)\n canvasHeight = Math.max(canvasHeight, height)\n measured.push({ request: traced(request), ascent, descent, reach })\n })\n }\n const resize = (width: number, height: number): void => {\n if (width <= canvas.width && height <= canvas.height) return\n canvas.width = Math.max(width, canvas.width)\n canvas.height = Math.max(height, canvas.height)\n current = null\n }\n resize(canvasWidth, canvasHeight)\n\n const exact = 'textRendering' in context\n const draw = (\n glyph: Measured,\n [originX, baselineY, width, height]: ReturnType<typeof boxOf>,\n fill: string,\n rendering: CanvasTextRendering,\n ): Uint8ClampedArray => {\n resize(width, height)\n use(glyph.request)\n context.fillStyle = fill\n if (exact) context.textRendering = rendering\n context.clearRect(0, 0, width, height)\n context.fillText(glyph.request.character, originX, baselineY)\n return context.getImageData(0, 0, width, height).data\n }\n const colorModule = measured.some((glyph) => isColorCandidate(glyph.request, colorGlyphs))\n ? await import('../atlas/colorGlyphs.js')\n : null\n throwIfAborted(signal)\n // This batch's working memory, grown to fit its largest glyph (about 1 MB at 256 px per\n // em) and released with the batch, so an idle tracer holds none.\n const scratch = createTraceScratch()\n let sliceStart = performance.now()\n for (const glyph of measured) {\n throwIfAborted(signal)\n let box = boxOf(glyph.reach, margin)\n const [, , width, height] = box\n // A candidate the font draws in the fill colour alone is text, as in the SDF bake: only\n // ink that ignores the fill goes to the companion.\n const colored =\n colorModule !== null &&\n isColorCandidate(glyph.request, colorGlyphs) &&\n colorModule.encodeColorBand(\n draw(glyph, box, '#fff', 'auto'),\n draw(glyph, box, '#000', 'auto'),\n width,\n height,\n 0,\n [{ x: 0, y: 0, width, height }],\n ).colored[0] === true\n let outline: WindfoilGlyphOutline | null = null\n if (!colored) {\n // The SDF bake's text rendering: exact geometry, the neutral middle of a contrast table.\n let rgba = draw(glyph, box, '#606060', 'geometricPrecision')\n let clipped = touchesEdge(rgba, box[2], box[3])\n if (clipped) {\n // The metrics missed some ink: once more with half an em of room all round.\n box = boxOf(glyph.reach, margin + size / 2)\n rgba = draw(glyph, box, '#606060', 'geometricPrecision')\n clipped = touchesEdge(rgba, box[2], box[3])\n }\n // Ink past even that room would trace clipped: the SDF companion draws the glyph.\n if (!clipped) {\n const { quadratics, bbox } = traceCoverage(\n {\n alpha: rgba,\n width: box[2],\n height: box[3],\n stride: 4,\n offset: 3,\n originX: box[0],\n baselineY: box[1],\n },\n tolerance,\n scratch,\n )\n outline = {\n unitsPerEm: size,\n ascent: glyph.ascent,\n descent: -glyph.descent,\n bbox,\n quadratics,\n }\n }\n }\n keep(requests.get(glyph.request.key)!, outline)\n if (performance.now() - sliceStart > SLICE_MS) {\n await nextTask()\n throwIfAborted(signal)\n sliceStart = performance.now()\n }\n }\n return results\n } finally {\n // Release the backing store now: Safari counts a detached canvas against its canvas\n // memory until it is collected.\n canvas.width = 0\n canvas.height = 0\n canvas.remove()\n }\n }\n\n const provider: WindfoilOutlineProvider = (request, signal) => {\n throwIfAborted(signal)\n const cached = cache.get(request.key)\n if (cached !== undefined) return cached\n let batch = open.get(signal)\n if (!batch) {\n const requests = new Map<string, GlyphRequest>()\n // Everything this task asks for with this signal joins before the batch starts. What a\n // clear() before then would drop is not cached either.\n const started = epoch\n const next: Batch = {\n signal,\n requests,\n done: Promise.resolve().then(() => {\n if (open.get(signal) === next) open.delete(signal)\n return run(signal, requests, started)\n }),\n }\n open.set(signal, (batch = next))\n }\n batch.requests.set(request.key, request)\n return batch.done.then((results) => results.get(request.key) ?? null)\n }\n\n return {\n provider,\n clear() {\n epoch++\n cache.clear()\n },\n retain(keys) {\n const live = new Set(keys)\n for (const key of cache.keys()) if (!live.has(key)) cache.delete(key)\n },\n }\n}\n"],"mappings":";;;;AA8BA,IAAM,WAAW;;AAEjB,IAAM,gBAAgB;AACtB,IAAM,aAAa;AAkBnB,SAAS,eAAe,QAA2B;CACjD,IAAI,OAAO,SACT,MAAM,OAAO,UAAU,IAAI,aAAa,iCAAiC,YAAY;AAEzF;;;;;;AAOA,SAAS,WAA0B;CACjC,OAAO,IAAI,SAAS,YAAY;EAC9B,IAAI,OAAO,mBAAmB,YAAY;GACxC,WAAW,SAAS,CAAC;GACrB;EACF;EACA,MAAM,EAAE,OAAO,UAAU,IAAI,eAAe;EAC5C,MAAM,kBAAkB;GACtB,MAAM,MAAM;GACZ,QAAQ;EACV;EACA,MAAM,YAAY,IAAI;CACxB,CAAC;AACH;;AAGA,SAAS,MACP,OACA,QACqE;CACrE,MAAM,UAAU,SAAS,KAAK,KAAK,MAAM,EAAE;CAC3C,MAAM,YAAY,SAAS,KAAK,KAAK,MAAM,EAAE;CAC7C,OAAO;EACL;EACA;EACA,UAAU,KAAK,KAAK,MAAM,EAAE,IAAI;EAChC,YAAY,KAAK,KAAK,MAAM,EAAE,IAAI;CACpC;AACF;;AAGA,SAAS,YAAY,MAAyB,OAAe,QAAyB;CACpF,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,KACzB,IAAI,KAAK,IAAI,IAAI,KAAM,KAAK,OAAO,SAAS,KAAK,QAAQ,KAAK,IAAI,KAAM,GAAG,OAAO;CAEpF,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,KAC1B,IAAI,KAAK,IAAI,QAAQ,IAAI,KAAM,KAAK,OAAO,IAAI,KAAK,QAAQ,KAAK,IAAI,KAAM,GAAG,OAAO;CAEvF,OAAO;AACT;;;;;;;;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FontsLoaded,\n createCanvas,\n isColorCandidate,\n setFontContext,\n waitForFonts,\n} from '../dom/fontCanvas.js'\nimport type {\n ColorGlyphMode,\n FontStyleSnapshot,\n GlyphRequest,\n WindfoilGlyphOutline,\n WindfoilOutlineProvider,\n} from '../types.js'\nimport { createTraceScratch, traceCoverage } from './trace/outline.js'\n\n/** Options of the built-in Canvas 2D outline tracer. */\nexport interface TracedOutlineOptions {\n /** Trace resolution in pixels per em, also each outline's `unitsPerEm`. Defaults to `256`. */\n readonly size?: number\n /** Furthest, in trace pixels, a fitted curve may stray from its contour. Defaults to `0.25`. */\n readonly tolerance?: number\n /** Which glyphs to test for colour ink, as `DomSdfOptions.colorGlyphs`. Defaults to `'emoji'`. */\n readonly colorGlyphs?: ColorGlyphMode\n}\n\n/** A `WindfoilOutlineProvider` that traces the browser's own glyphs, and its cache. */\nexport interface TracedOutlines {\n readonly provider: WindfoilOutlineProvider\n /** Forgets every traced outline, as after a webfont load; work in flight is not kept. */\n clear(): void\n /** Forgets the outlines of every glyph key not listed. */\n retain(keys: Iterable<string>): void\n}\n\n/** A batch yields to the page once it has traced for this long. */\nconst SLICE_MS = 8\n/** A font assignment the canvas rejects leaves this one in place. */\nconst SENTINEL_FONT = '1px serif'\nconst SIZE_TOKEN = /[\\d.]+px/\n\n/** The requests one task made with one signal, traced together. */\ninterface Batch {\n readonly signal: AbortSignal\n readonly requests: Map<string, GlyphRequest>\n readonly done: Promise<ReadonlyMap<string, WindfoilGlyphOutline | null>>\n}\n\n/** One glyph between measuring and tracing, in trace pixels; y grows downwards. */\ninterface Measured {\n readonly request: GlyphRequest\n readonly ascent: number\n readonly descent: number\n /** How far the ink box and the font box reach from the pen: left, right, up and down. */\n readonly reach: readonly [number, number, number, number]\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n if (signal.aborted) {\n throw signal.reason ?? new DOMException('The outline trace was aborted', 'AbortError')\n }\n}\n\n/**\n * A task after the page's own: a message is not clamped to 4 ms as a nested timer is, and it\n * does not run ahead of rendering as a `scheduler.yield()` continuation does, which held frames\n * back for 100 ms at a time in Chrome 156.\n */\nfunction nextTask(): Promise<void> {\n return new Promise((resolve) => {\n if (typeof MessageChannel !== 'function') {\n setTimeout(resolve, 0)\n return\n }\n const { port1, port2 } = new MessageChannel()\n port1.onmessage = () => {\n port1.close()\n resolve()\n }\n port2.postMessage(null)\n })\n}\n\n/** Canvas box of a glyph with `margin` pixels around its reach: pen position and size. */\nfunction boxOf(\n reach: Measured['reach'],\n margin: number,\n): [originX: number, baselineY: number, width: number, height: number] {\n const originX = margin + Math.ceil(reach[0])\n const baselineY = margin + Math.ceil(reach[2])\n return [\n originX,\n baselineY,\n originX + Math.ceil(reach[1]) + margin,\n baselineY + Math.ceil(reach[3]) + margin,\n ]\n}\n\n/** Whether any texel on the edge of a `width` x `height` RGBA read holds ink. */\nfunction touchesEdge(\n rgba: Uint8ClampedArray,\n width: number,\n height: number,\n rowStride = width * 4,\n baseOffset = 0,\n): boolean {\n for (let x = 0; x < width; x++) {\n if (\n rgba[baseOffset + x * 4 + 3]! > 0 ||\n rgba[baseOffset + (height - 1) * rowStride + x * 4 + 3]! > 0\n ) {\n return true\n }\n }\n for (let y = 0; y < height; y++) {\n const row = baseOffset + y * rowStride\n if (rgba[row + 3]! > 0 || rgba[row + (width - 1) * 4 + 3]! > 0) return true\n }\n return false\n}\n\nconst MAX_SHEET = 2048\nconst SHEET_GAP = 1\n\n/**\n * The outline provider `DomSdf` and `DomSlug` use for Windfoil and Slug text when the caller gives\n * none. Each glyph is drawn as the SDF rasterizer draws it (the captured canvas font with its\n * stretch and kerning, an in-document canvas without font smoothing, exact geometry, a neutral\n * grey), at `size` pixels per em, then traced at half coverage and fitted with quadratics. The\n * outline follows that raster, not the font file: font-variation and feature settings are not\n * applied, as on any canvas. Colour glyphs, glyphs of a font the canvas rejects and shaped runs\n * resolve to `null`, for the SDF companion; a glyph without ink to an empty outline. Without a\n * 2D canvas every glyph is `null`, so the whole capture falls back to SDF. `descent` is the SDF\n * slot's, measured at the captured font's own size, so analytic and SDF glyphs share a baseline.\n * Ink the metrics miss is drawn again with half an em more room all round; a glyph whose ink\n * still reaches the edge of its box resolves to `null` too, rather than trace clipped.\n *\n * Calls made in one task with one signal trace as one batch, in slices of about 8 ms between\n * which the page runs and the signal is checked. Each batch has its own working memory, which\n * goes with it. Outlines stay cached per instance until `clear()` or `retain()` drops them; one\n * traced while `document.fonts.check()` still reported its font as not ready is never cached.\n */\nexport function createTracedOutlineProvider(\n document: Document,\n options: TracedOutlineOptions = {},\n): TracedOutlines {\n const size = options.size ?? 256\n const tolerance = options.tolerance ?? 0.25\n const colorGlyphs = options.colorGlyphs ?? 'emoji'\n const cache = new Map<string, WindfoilGlyphOutline | null>()\n let epoch = 0\n /** The batches still open to requests of this task, by signal. */\n const open = new Map<AbortSignal, Batch>()\n\n const run = async (\n signal: AbortSignal,\n requests: ReadonlyMap<string, GlyphRequest>,\n started: number,\n ): Promise<ReadonlyMap<string, WindfoilGlyphOutline | null>> => {\n const results = new Map<string, WindfoilGlyphOutline | null>()\n // Each font of the batch, as captured and as traced: the captured canvas font with only\n // its size rewritten, as an adaptive SDF bake does.\n const groups = new Map<string, [GlyphRequest[], FontStyleSnapshot]>()\n for (const request of requests.values()) {\n // Shapes resolve elsewhere; a shaped run is one tile of a line, which no outline covers.\n if (request.shape || request.shaping) {\n results.set(request.key, null)\n continue\n }\n const group = groups.get(request.font.key)\n if (group) group[0].push(request)\n else {\n const font = request.font\n groups.set(font.key, [\n [request],\n { ...font, canvasFont: font.canvasFont.replace(SIZE_TOKEN, `${size}px`) },\n ])\n }\n }\n const traced = (request: GlyphRequest): GlyphRequest => ({\n ...request,\n font: groups.get(request.font.key)![1],\n })\n await waitForFonts(\n document,\n [...groups.values()].flatMap(([list]) => list.map(traced)),\n signal,\n )\n throwIfAborted(signal)\n\n const preloaded = allFontsLoaded(document)\n const fonts = document.fonts as FontFaceSet | undefined\n const keep = (request: GlyphRequest, outline: WindfoilGlyphOutline | null): void => {\n results.set(request.key, outline)\n let ready = epoch === started\n if (ready && !preloaded) {\n try {\n ready = fonts?.check(traced(request).font.canvasFont, request.character) ?? true\n } catch {\n ready = false\n }\n }\n if (ready) cache.set(request.key, outline)\n }\n\n const canvas = createCanvas(document)\n try {\n const context = canvas.getContext('2d', { willReadFrequently: true })\n if (!context) {\n // Not cached: the whole capture falls back to SDF, and a later build may try again.\n for (const [list] of groups.values())\n for (const request of list) results.set(request.key, null)\n return results\n }\n let current: FontStyleSnapshot | null = null\n const accepted = new Map<FontStyleSnapshot, boolean>()\n /** Applies a request's font as the rasterizer does; false when the canvas rejected it. */\n const use = (request: GlyphRequest): boolean => {\n if (current !== request.font) {\n context.font = SENTINEL_FONT\n const sentinel = context.font\n setFontContext(context, request, undefined, null)\n current = request.font\n accepted.set(request.font, context.font !== sentinel)\n }\n return accepted.get(request.font)!\n }\n\n // Measure every glyph first: sizing the canvas resets its context.\n const margin = Math.max(4, Math.ceil(size / 32))\n const measured: Measured[] = []\n let canvasWidth = 1\n let canvasHeight = 1\n for (const [list] of groups.values()) {\n throwIfAborted(signal)\n const bake = Number.parseFloat(SIZE_TOKEN.exec(list[0]!.font.canvasFont)?.[0] ?? '')\n if (!(bake > 0) || !use(list[0]!)) {\n for (const request of list) keep(request, null)\n continue\n }\n // The SDF slot's metrics, measured at the captured font's own size.\n const scale = size / bake\n const slots = list.map((request) => {\n const slot = context.measureText(request.character)\n return [\n Math.max(1, slot.fontBoundingBoxAscent || slot.actualBoundingBoxAscent) * scale,\n Math.max(1, slot.fontBoundingBoxDescent || slot.actualBoundingBoxDescent) * scale,\n ] as const\n })\n if (!use(traced(list[0]!))) {\n for (const request of list) keep(request, null)\n continue\n }\n list.forEach((request, index) => {\n const [ascent, descent] = slots[index]!\n // Ink can only be found in the ink box and the font box.\n const metrics = context.measureText(request.character)\n const reach = [\n Math.max(0, metrics.actualBoundingBoxLeft || 0),\n Math.max(metrics.width || 0, metrics.actualBoundingBoxRight || 0),\n Math.max(ascent, metrics.actualBoundingBoxAscent || 0),\n Math.max(descent, metrics.actualBoundingBoxDescent || 0),\n ] as const\n const [, , width, height] = boxOf(reach, margin)\n if (!(width <= 8 * size && height <= 8 * size)) {\n keep(request, null)\n return\n }\n canvasWidth = Math.max(canvasWidth, width)\n canvasHeight = Math.max(canvasHeight, height)\n measured.push({ request: traced(request), ascent, descent, reach })\n })\n }\n const resize = (width: number, height: number): void => {\n if (width <= canvas.width && height <= canvas.height) return\n canvas.width = Math.max(width, canvas.width)\n canvas.height = Math.max(height, canvas.height)\n current = null\n }\n resize(canvasWidth, canvasHeight)\n\n const exact = 'textRendering' in context\n const draw = (\n glyph: Measured,\n [originX, baselineY, width, height]: ReturnType<typeof boxOf>,\n fill: string,\n rendering: CanvasTextRendering,\n ): Uint8ClampedArray => {\n resize(width, height)\n use(glyph.request)\n context.fillStyle = fill\n if (exact) context.textRendering = rendering\n context.clearRect(0, 0, width, height)\n context.fillText(glyph.request.character, originX, baselineY)\n return context.getImageData(0, 0, width, height).data\n }\n const colorModule = measured.some((glyph) => isColorCandidate(glyph.request, colorGlyphs))\n ? await import('../atlas/colorGlyphs.js')\n : null\n throwIfAborted(signal)\n // This batch's working memory, grown to fit its largest glyph (about 1 MB at 256 px per\n // em) and released with the batch, so an idle tracer holds none.\n const scratch = createTraceScratch()\n let sliceStart = performance.now()\n const view = document.defaultView\n const getContextFn = view\n ? (Object.getOwnPropertyDescriptor(view.HTMLCanvasElement.prototype, 'getContext')\n ?.value as object | undefined)\n : undefined\n const mockedCanvas = !getContextFn || 'mock' in getContextFn\n const finishGlyph = async (\n glyph: Measured,\n box: ReturnType<typeof boxOf>,\n retried: boolean,\n ): Promise<void> => {\n // The SDF bake's text rendering: exact geometry, the neutral middle of a contrast table.\n let currentBox = box\n let rgba = draw(glyph, currentBox, '#606060', 'geometricPrecision')\n let clipped = touchesEdge(rgba, currentBox[2], currentBox[3])\n if (clipped && !retried) {\n // The metrics missed some ink: once more with half an em of room all round.\n currentBox = boxOf(glyph.reach, margin + size / 2)\n rgba = draw(glyph, currentBox, '#606060', 'geometricPrecision')\n clipped = touchesEdge(rgba, currentBox[2], currentBox[3])\n }\n // Ink past even that room would trace clipped: the SDF companion draws the glyph.\n let outline: WindfoilGlyphOutline | null = null\n if (!clipped) {\n const { quadratics, bbox } = traceCoverage(\n {\n alpha: rgba,\n width: currentBox[2],\n height: currentBox[3],\n stride: 4,\n offset: 3,\n originX: currentBox[0],\n baselineY: currentBox[1],\n },\n tolerance,\n scratch,\n )\n outline = {\n unitsPerEm: size,\n ascent: glyph.ascent,\n descent: -glyph.descent,\n bbox,\n quadratics,\n }\n }\n keep(requests.get(glyph.request.key)!, outline)\n if (performance.now() - sliceStart > SLICE_MS) {\n await nextTask()\n throwIfAborted(signal)\n sliceStart = performance.now()\n }\n }\n\n if (mockedCanvas || measured.length < 2) {\n for (const glyph of measured) {\n throwIfAborted(signal)\n const box = boxOf(glyph.reach, margin)\n const [, , width, height] = box\n // A candidate the font draws in the fill colour alone is text, as in the SDF bake:\n // only ink that ignores the fill goes to the companion.\n const colored =\n colorModule !== null &&\n isColorCandidate(glyph.request, colorGlyphs) &&\n colorModule.encodeColorBand(\n draw(glyph, box, '#fff', 'auto'),\n draw(glyph, box, '#000', 'auto'),\n width,\n height,\n 0,\n [{ x: 0, y: 0, width, height }],\n ).colored[0] === true\n if (colored) {\n keep(requests.get(glyph.request.key)!, null)\n if (performance.now() - sliceStart > SLICE_MS) {\n await nextTask()\n throwIfAborted(signal)\n sliceStart = performance.now()\n }\n continue\n }\n await finishGlyph(glyph, box, false)\n }\n } else {\n interface Tile {\n readonly glyph: Measured\n readonly box: ReturnType<typeof boxOf>\n readonly x: number\n readonly y: number\n }\n const plain: { readonly glyph: Measured; readonly box: ReturnType<typeof boxOf> }[] = []\n const oversized: { readonly glyph: Measured; readonly box: ReturnType<typeof boxOf> }[] = []\n const retries: Measured[] = []\n for (const glyph of measured) {\n throwIfAborted(signal)\n const box = boxOf(glyph.reach, margin)\n const [, , width, height] = box\n const colored =\n colorModule !== null &&\n isColorCandidate(glyph.request, colorGlyphs) &&\n colorModule.encodeColorBand(\n draw(glyph, box, '#fff', 'auto'),\n draw(glyph, box, '#000', 'auto'),\n width,\n height,\n 0,\n [{ x: 0, y: 0, width, height }],\n ).colored[0] === true\n if (colored) {\n keep(requests.get(glyph.request.key)!, null)\n continue\n }\n if (width > MAX_SHEET || height > MAX_SHEET) oversized.push({ glyph, box })\n else plain.push({ glyph, box })\n }\n\n const flushSheet = async (sheet: Tile[], sheetW: number, sheetH: number): Promise<void> => {\n resize(sheetW, sheetH)\n context.clearRect(0, 0, sheetW, sheetH)\n context.fillStyle = '#606060'\n if (exact) context.textRendering = 'geometricPrecision'\n for (const item of sheet) {\n throwIfAborted(signal)\n use(item.glyph.request)\n context.fillText(\n item.glyph.request.character,\n item.x + item.box[0],\n item.y + item.box[1],\n )\n }\n const rgba = context.getImageData(0, 0, sheetW, sheetH).data\n const rowStride = sheetW * 4\n for (const item of sheet) {\n throwIfAborted(signal)\n const [originX, baselineY, width, height] = item.box\n const tileOffset = (item.y * sheetW + item.x) * 4\n if (touchesEdge(rgba, width, height, rowStride, tileOffset)) {\n retries.push(item.glyph)\n continue\n }\n const { quadratics, bbox } = traceCoverage(\n {\n alpha: rgba,\n width,\n height,\n stride: 4,\n offset: tileOffset + 3,\n rowStride,\n originX,\n baselineY,\n },\n tolerance,\n scratch,\n )\n keep(requests.get(item.glyph.request.key)!, {\n unitsPerEm: size,\n ascent: item.glyph.ascent,\n descent: -item.glyph.descent,\n bbox,\n quadratics,\n })\n if (performance.now() - sliceStart > SLICE_MS) {\n await nextTask()\n throwIfAborted(signal)\n sliceStart = performance.now()\n }\n }\n }\n\n if (plain.length < 2) {\n for (const item of plain) {\n throwIfAborted(signal)\n await finishGlyph(item.glyph, item.box, false)\n }\n } else {\n let sheet: Tile[] = []\n let packX = 0\n let packY = 0\n let rowH = 0\n let sheetW = 0\n let sheetH = 0\n for (const { glyph, box } of plain) {\n const width = box[2]\n const height = box[3]\n if (packX > 0 && packX + width > MAX_SHEET) {\n packX = 0\n packY += rowH + SHEET_GAP\n rowH = 0\n }\n if (packY + height > MAX_SHEET) {\n await flushSheet(sheet, sheetW, sheetH)\n sheet = []\n packX = 0\n packY = 0\n rowH = 0\n sheetW = 0\n sheetH = 0\n }\n sheet.push({ glyph, box, x: packX, y: packY })\n sheetW = Math.max(sheetW, packX + width)\n sheetH = Math.max(sheetH, packY + height)\n packX += width + SHEET_GAP\n rowH = Math.max(rowH, height)\n }\n if (sheet.length > 0) await flushSheet(sheet, sheetW, sheetH)\n }\n for (const item of oversized) {\n throwIfAborted(signal)\n await finishGlyph(item.glyph, item.box, false)\n }\n for (const glyph of retries) {\n throwIfAborted(signal)\n await finishGlyph(glyph, boxOf(glyph.reach, margin + size / 2), true)\n }\n }\n return results\n } finally {\n // Release the backing store now: Safari counts a detached canvas against its canvas\n // memory until it is collected.\n canvas.width = 0\n canvas.height = 0\n canvas.remove()\n }\n }\n\n const provider: WindfoilOutlineProvider = (request, signal) => {\n throwIfAborted(signal)\n const cached = cache.get(request.key)\n if (cached !== undefined) return cached\n let batch = open.get(signal)\n if (!batch) {\n const requests = new Map<string, GlyphRequest>()\n // Everything this task asks for with this signal joins before the batch starts. What a\n // clear() before then would drop is not cached either.\n const started = epoch\n const next: Batch = {\n signal,\n requests,\n done: Promise.resolve().then(() => {\n if (open.get(signal) === next) open.delete(signal)\n return run(signal, requests, started)\n }),\n }\n open.set(signal, (batch = next))\n }\n batch.requests.set(request.key, request)\n return batch.done.then((results) => results.get(request.key) ?? null)\n }\n\n return {\n provider,\n clear() {\n epoch++\n cache.clear()\n },\n retain(keys) {\n const live = new Set(keys)\n for (const key of cache.keys()) if (!live.has(key)) cache.delete(key)\n },\n }\n}\n"],"mappings":";;;;AAoCA,IAAM,WAAW;;AAEjB,IAAM,gBAAgB;AACtB,IAAM,aAAa;AAkBnB,SAAS,eAAe,QAA2B;CACjD,IAAI,OAAO,SACT,M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ACA,MAAM,QAAQ,QAAQ,CAAC,CAAC,WAAW;KACjC,IAAI,KAAK,IAAI,MAAM,MAAM,MAAM,KAAK,OAAO,MAAM;KACjD,OAAO,IAAI,QAAQ,UAAU,OAAO;IACtC,CAAC;GACH;GACA,KAAK,IAAI,QAAS,QAAQ,IAAK;EACjC;EACA,MAAM,SAAS,IAAI,QAAQ,KAAK,OAAO;EACvC,OAAO,MAAM,KAAK,MAAM,YAAY,QAAQ,IAAI,QAAQ,GAAG,KAAK,IAAI;CACtE;CAEA,OAAO;EACL;EACA,QAAQ;GACN;GACA,MAAM,MAAM;EACd;EACA,OAAO,MAAM;GACX,MAAM,OAAO,IAAI,IAAI,IAAI;GACzB,KAAK,MAAM,OAAO,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,GAAG,GAAG,MAAM,OAAO,GAAG;EACtE;CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ultra-text",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.1",
|
|
4
4
|
"description": "DOM to WebGPU/TSL: real HTML, laid out by the browser, rendered as live 3D text (Three.js, R3F, TresJS, Mini3, and vanilla JS).",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"three",
|
|
@@ -23,7 +23,9 @@
|
|
|
23
23
|
"mini3",
|
|
24
24
|
"emoji",
|
|
25
25
|
"svg",
|
|
26
|
-
"vanilla"
|
|
26
|
+
"vanilla",
|
|
27
|
+
"slug",
|
|
28
|
+
"agent-skills"
|
|
27
29
|
],
|
|
28
30
|
"homepage": "https://ultra-text.makio.io/docs",
|
|
29
31
|
"bugs": {
|
|
@@ -42,6 +44,7 @@
|
|
|
42
44
|
"sideEffects": false,
|
|
43
45
|
"files": [
|
|
44
46
|
"dist",
|
|
47
|
+
"skills",
|
|
45
48
|
"LICENSE",
|
|
46
49
|
"README.md",
|
|
47
50
|
"THIRD_PARTY_NOTICES.md",
|
|
@@ -60,6 +63,14 @@
|
|
|
60
63
|
"types": "./dist/vanilla.d.ts",
|
|
61
64
|
"import": "./dist/vanilla.js"
|
|
62
65
|
},
|
|
66
|
+
"./slug": {
|
|
67
|
+
"types": "./dist/slug.d.ts",
|
|
68
|
+
"import": "./dist/slug.js"
|
|
69
|
+
},
|
|
70
|
+
"./slug-vanilla": {
|
|
71
|
+
"types": "./dist/slug-vanilla.d.ts",
|
|
72
|
+
"import": "./dist/slug-vanilla.js"
|
|
73
|
+
},
|
|
63
74
|
"./package.json": "./package.json"
|
|
64
75
|
},
|
|
65
76
|
"packageManager": "pnpm@12.3.4",
|
|
@@ -123,7 +134,7 @@
|
|
|
123
134
|
{
|
|
124
135
|
"name": "public entry",
|
|
125
136
|
"path": "dist/index.js",
|
|
126
|
-
"limit": "
|
|
137
|
+
"limit": "38.5 kB",
|
|
127
138
|
"ignore": [
|
|
128
139
|
"three",
|
|
129
140
|
"@chenglou/pretext",
|
|
@@ -152,7 +163,7 @@
|
|
|
152
163
|
{
|
|
153
164
|
"name": "vanilla entry (Three-free)",
|
|
154
165
|
"path": "dist/vanilla.js",
|
|
155
|
-
"limit": "
|
|
166
|
+
"limit": "31 kB",
|
|
156
167
|
"ignore": [
|
|
157
168
|
"@chenglou/pretext",
|
|
158
169
|
"./dist/dom/browserShaping.js",
|
|
@@ -164,6 +175,44 @@
|
|
|
164
175
|
"./dist/windfoil/svg/pathConverter.js"
|
|
165
176
|
]
|
|
166
177
|
},
|
|
178
|
+
{
|
|
179
|
+
"name": "slug entry (Three.js)",
|
|
180
|
+
"path": "dist/slug.js",
|
|
181
|
+
"limit": "44 kB",
|
|
182
|
+
"ignore": [
|
|
183
|
+
"three",
|
|
184
|
+
"@chenglou/pretext",
|
|
185
|
+
"./dist/dom/browserShaping.js",
|
|
186
|
+
"./dist/dom/pretextLayout.js",
|
|
187
|
+
"./dist/dom/svgCapture.js",
|
|
188
|
+
"./dist/atlas/colorGlyphs.js",
|
|
189
|
+
"./dist/windfoil/requests.js",
|
|
190
|
+
"./dist/windfoil/layerNormalization.js",
|
|
191
|
+
"./dist/windfoil/color.js",
|
|
192
|
+
"./dist/windfoil/svg/convert.js",
|
|
193
|
+
"./dist/windfoil/svg/pathConverter.js",
|
|
194
|
+
"./dist/windfoil/emoji.js",
|
|
195
|
+
"./dist/windfoil/emojiMetrics.js"
|
|
196
|
+
]
|
|
197
|
+
},
|
|
198
|
+
{
|
|
199
|
+
"name": "slug-vanilla entry (Three-free)",
|
|
200
|
+
"path": "dist/slug-vanilla.js",
|
|
201
|
+
"limit": "38 kB",
|
|
202
|
+
"ignore": [
|
|
203
|
+
"@chenglou/pretext",
|
|
204
|
+
"./dist/dom/browserShaping.js",
|
|
205
|
+
"./dist/dom/pretextLayout.js",
|
|
206
|
+
"./dist/dom/svgCapture.js",
|
|
207
|
+
"./dist/atlas/colorGlyphs.js",
|
|
208
|
+
"./dist/windfoil/requests.js",
|
|
209
|
+
"./dist/windfoil/layerNormalization.js",
|
|
210
|
+
"./dist/windfoil/svg/convert.js",
|
|
211
|
+
"./dist/windfoil/svg/pathConverter.js",
|
|
212
|
+
"./dist/windfoil/emoji.js",
|
|
213
|
+
"./dist/windfoil/emojiMetrics.js"
|
|
214
|
+
]
|
|
215
|
+
},
|
|
167
216
|
{
|
|
168
217
|
"name": "optional Pretext layout",
|
|
169
218
|
"path": "dist/dom/pretextLayout.js",
|
|
@@ -182,7 +231,7 @@
|
|
|
182
231
|
{
|
|
183
232
|
"name": "optional Windfoil backend",
|
|
184
233
|
"path": "dist/windfoil/runtime.js",
|
|
185
|
-
"limit": "16 kB",
|
|
234
|
+
"limit": "16.5 kB",
|
|
186
235
|
"ignore": [
|
|
187
236
|
"three",
|
|
188
237
|
"@chenglou/pretext",
|
|
@@ -233,7 +282,7 @@
|
|
|
233
282
|
{
|
|
234
283
|
"name": "optional Windfoil shapes",
|
|
235
284
|
"path": "dist/windfoil/shapes.js",
|
|
236
|
-
"limit": "
|
|
285
|
+
"limit": "18.5 kB",
|
|
237
286
|
"ignore": [
|
|
238
287
|
"three",
|
|
239
288
|
"@chenglou/pretext",
|
|
@@ -354,7 +403,7 @@
|
|
|
354
403
|
{
|
|
355
404
|
"name": "optional atlas append",
|
|
356
405
|
"path": "dist/atlas/appendAtlas.js",
|
|
357
|
-
"limit": "4 kB",
|
|
406
|
+
"limit": "4.5 kB",
|
|
358
407
|
"ignore": [
|
|
359
408
|
"three",
|
|
360
409
|
"./dist/atlas/rasterize.js",
|
|
@@ -366,7 +415,7 @@
|
|
|
366
415
|
{
|
|
367
416
|
"name": "optional traced outlines",
|
|
368
417
|
"path": "dist/windfoil/tracedOutlines.js",
|
|
369
|
-
"limit": "
|
|
418
|
+
"limit": "8.5 kB",
|
|
370
419
|
"ignore": [
|
|
371
420
|
"three",
|
|
372
421
|
"./dist/atlas/rasterize.js",
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: ultra-text
|
|
3
|
+
description: >-
|
|
4
|
+
Guides coding agents integrating ultra-text for runtime DOM-to-WebGPU 3D text in Three.js
|
|
5
|
+
WebGPURenderer, TSL shaders, React Three Fiber (R3F), TresJS (Vue), Mini3, and vanilla WebGPU
|
|
6
|
+
engines. Use when installing, configuring, styling, reflowing, animating, or debugging
|
|
7
|
+
ultra-text, ultra-text/slug, ultra-text/vanilla, or ultra-text/slug-vanilla.
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
<!-- SPDX-License-Identifier: MIT -->
|
|
11
|
+
|
|
12
|
+
# ultra-text
|
|
13
|
+
|
|
14
|
+
`ultra-text` captures real HTML/CSS laid out by the browser and renders it as retained WebGPU instanced geometry—either from a compact single-channel SDF atlas or analytic Slug/Windfoil quadratic outlines—with zero DOM reads in the render loop.
|
|
15
|
+
|
|
16
|
+
## Choose the right entry point
|
|
17
|
+
|
|
18
|
+
Never import internal module paths or `THREE.WebGLRenderer` (unsupported). Do not invent framework subpaths like `ultra-text/r3f`, `ultra-text/tres`, or `ultra-text/mini3`.
|
|
19
|
+
|
|
20
|
+
| Entry point | Stack | Renderer / device | Coverage backend |
|
|
21
|
+
| ------------------------- | --------------------------- | --------------------------------- | -------------------------------------------------------------- |
|
|
22
|
+
| `ultra-text` | Three.js / R3F / TresJS | `WebGPURenderer` (`three/webgpu`) | SDF (GPU JFA / CPU EDT), plus optional `windfoil` or `slug` |
|
|
23
|
+
| `ultra-text/slug` | Three.js Slug-only apps | `WebGPURenderer` (`three/webgpu`) | Pure analytic Slug (zero SDF code, `DomSlug` / `SlugText`) |
|
|
24
|
+
| `ultra-text/vanilla` | Mini3 & custom engines | `GPUDevice` (Three.js-free) | SDF atlas + packed typed-array instance buffers |
|
|
25
|
+
| `ultra-text/slug-vanilla` | Mini3 & custom Slug engines | `GPUDevice` (Three.js-free) | Pure analytic Slug + `SLUG_WGSL` / `createVanillaSlugPipeline` |
|
|
26
|
+
|
|
27
|
+
- Install Three.js within `ultra-text`'s peer range (`three` `>=0.187.0 <0.188.0`) and keep a single Three.js instance across the app.
|
|
28
|
+
- For Three-free engines, `three` is an optional peer dependency and does not need to be installed.
|
|
29
|
+
|
|
30
|
+
## Non-negotiable DOM & lifecycle invariants
|
|
31
|
+
|
|
32
|
+
1. **Await renderer init and fonts before capture**: run `await renderer.init()` and `await document.fonts.ready` so CSS faces and line metrics settle before reading the DOM.
|
|
33
|
+
2. **Keep the source connected, accessible, and measurable**: pass a real element with a non-zero layout box. Never use `display: none` or the `hidden` attribute on the captured source; keep semantic HTML in the accessibility tree and mark the WebGPU `<canvas aria-hidden="true">`.
|
|
34
|
+
3. **Mark only what crosses into 3D**:
|
|
35
|
+
- `data-text-block` — capture text and inline descendants (legacy `data-sdf-block` also works)
|
|
36
|
+
- `data-text-rect` — capture solid background, opacity, box, and uniform border radius (`data-sdf-rect`)
|
|
37
|
+
- `data-text-ignore` — exclude a subtree (`data-sdf-ignore`)
|
|
38
|
+
- `data-text-depth="n"` — inherited Z depth (`data-sdf-depth`)
|
|
39
|
+
- `data-text-receive-shadow` — put the rectangle in the shadow-receiving batch (`data-sdf-receive-shadow`)
|
|
40
|
+
4. **Never capture or rebuild inside the frame loop**: `DomText` observes DOM text, style, and resize changes by default (`observe: true`). Call `await copy.rebuild()` only after external stylesheet changes, or pass `{ reflowable: true }` and call `copy.reflow(widthPx)` for fast width-only re-wrapping without DOM reads.
|
|
41
|
+
5. **Respect `DomText.create` argument order**:
|
|
42
|
+
- Three.js entries (`ultra-text`, `ultra-text/slug`): `DomText.create(renderer, source, options)`
|
|
43
|
+
- Vanilla entries (`ultra-text/vanilla`, `ultra-text/slug-vanilla`): `DomText.create(source, gpuDevice, options)`
|
|
44
|
+
6. **Handle origin, scale, cancellation, and disposal**:
|
|
45
|
+
- Local `(0, 0)` is the bottom-left corner; center with `copy.position.set(-copy.width / 2, -copy.height / 2, 0)`.
|
|
46
|
+
- `pixelsPerUnit` divides X/Y positions, **not** Z depths or motion strength (`18 / pixelsPerUnit`, `panelDepth: -1 / pixelsPerUnit`).
|
|
47
|
+
- Pass an `AbortSignal` in async components; dispose late results if aborted after `await`, and call idempotent `copy.dispose()` on unmount (never dispose shared caller renderers, scenes, or `sharedAtlas`).
|
|
48
|
+
- In SSR frameworks (Next.js, Nuxt, Astro), guard browser capture and mount the WebGPU canvas on the client only.
|
|
49
|
+
|
|
50
|
+
## Minimal Three.js WebGPU quickstart
|
|
51
|
+
|
|
52
|
+
### Capture existing DOM (`DomText.create`)
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
import { PerspectiveCamera, Scene, WebGPURenderer } from 'three/webgpu'
|
|
56
|
+
import { DomText } from 'ultra-text'
|
|
57
|
+
|
|
58
|
+
const renderer = new WebGPURenderer({ antialias: true })
|
|
59
|
+
renderer.setPixelRatio(devicePixelRatio)
|
|
60
|
+
renderer.setSize(innerWidth, innerHeight)
|
|
61
|
+
renderer.domElement.setAttribute('aria-hidden', 'true')
|
|
62
|
+
document.body.append(renderer.domElement)
|
|
63
|
+
await renderer.init()
|
|
64
|
+
|
|
65
|
+
const scene = new Scene()
|
|
66
|
+
const camera = new PerspectiveCamera(40, innerWidth / innerHeight, 0.1, 5000)
|
|
67
|
+
camera.position.z = 900
|
|
68
|
+
|
|
69
|
+
await document.fonts.ready
|
|
70
|
+
const source = document.querySelector<HTMLElement>('#profile')
|
|
71
|
+
if (!source) throw new Error('Missing #profile')
|
|
72
|
+
|
|
73
|
+
const copy = await DomText.create(renderer, source, { quality: 'high' })
|
|
74
|
+
copy.position.set(-copy.width / 2, -copy.height / 2, 0)
|
|
75
|
+
scene.add(copy)
|
|
76
|
+
|
|
77
|
+
renderer.setAnimationLoop(() => renderer.render(scene, camera))
|
|
78
|
+
// Cleanup: scene.remove(copy); copy.dispose()
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### Direct string text (`Text`)
|
|
82
|
+
|
|
83
|
+
Use `Text` (in `ultra-text`) when there is no existing HTML block to mirror:
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
import { Text } from 'ultra-text'
|
|
87
|
+
|
|
88
|
+
const label = new Text('Hello, WebGPU!', {
|
|
89
|
+
renderer,
|
|
90
|
+
css: { fontFamily: 'sans-serif', fontSize: 48, color: '#ffcc00', width: 320 },
|
|
91
|
+
cssClass: 'headline',
|
|
92
|
+
})
|
|
93
|
+
await label.ready
|
|
94
|
+
scene.add(label)
|
|
95
|
+
|
|
96
|
+
label.text = 'Updated text'
|
|
97
|
+
await label.rebuild()
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Note: `ultra-text` exports `new Text(message, options)` (`await label.ready`); `ultra-text/slug` (`SlugText`), `ultra-text/vanilla`, and `ultra-text/slug-vanilla` support both `new Text(...)` and `Text.create(...)`.
|
|
101
|
+
|
|
102
|
+
## Read deeper references by task
|
|
103
|
+
|
|
104
|
+
Load only the reference matching the user's stack:
|
|
105
|
+
|
|
106
|
+
- Three.js options, SDF vs Slug vs Windfoil, TSL `fill`/`vertex` hooks, `motion`, `outline`, `dropShadow`, SVG/emoji, and shared-atlas stages: [Three.js & TSL reference](./references/three-tsl.md)
|
|
107
|
+
- React Three Fiber (v9 & v10 alpha), TresJS (Vue), and Mini3 copy-once starter components and lifecycle rules: [Framework integration reference](./references/frameworks.md)
|
|
108
|
+
- Zero-Three.js typed-array packers, GPU/CPU SDF builders, and raw WebGPU `SLUG_WGSL` pipelines: [Vanilla WebGPU & Mini3 reference](./references/vanilla-webgpu.md)
|
|
109
|
+
|
|
110
|
+
## Verification checklist & licensing
|
|
111
|
+
|
|
112
|
+
- Confirm `tsc --noEmit` (or `vue-tsc`) passes with matching Three.js types.
|
|
113
|
+
- In a WebGPU-capable browser, verify initial render, normal DOM text edit, source swap, mobile viewport layout, and unmount cleanup (including React Strict Mode double-mount).
|
|
114
|
+
- `ultra-text`, its docs, and the starter components under `/integrations/` are **MIT licensed**. The showcase scenes on `ultra-text.makio.io` (`/`, `/demo`, `/konami`, `/text-effects`) are **all rights reserved**—never clone or port them; build original scenes with the library.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
<!-- SPDX-License-Identifier: MIT -->
|
|
2
|
+
|
|
3
|
+
# Framework Integration Reference (R3F, TresJS, Mini3)
|
|
4
|
+
|
|
5
|
+
Starter components are **copy-once consumer source files** licensed under **MIT**—not npm subpaths (`ultra-text/r3f`, `ultra-text/tres`, or `ultra-text/mini3` do not exist). Always import runtime code from `ultra-text`, `ultra-text/slug`, `ultra-text/vanilla`, or `ultra-text/slug-vanilla`.
|
|
6
|
+
|
|
7
|
+
## Starter files (download or copy from the docs site)
|
|
8
|
+
|
|
9
|
+
| Framework | Starter file(s) | Library entry | Notes |
|
|
10
|
+
| ----------------------------- | ------------------------------------------------------------------------------------- | -------------------- | ---------------------------------------------------------------------------------- |
|
|
11
|
+
| React Three Fiber v9 (stable) | `https://ultra-text.makio.io/integrations/r3f/UltraText.tsx` | `ultra-text` | Uses `gl={async ({ canvas }) => ...}` and `useThree((s) => s.gl)`. |
|
|
12
|
+
| React Three Fiber v10 (alpha) | `https://ultra-text.makio.io/integrations/r3f/v10/UltraText.tsx` | `ultra-text` | Uses `renderer={async ({ canvas }) => ...}` and `useThree((s) => s.renderer)`. |
|
|
13
|
+
| TresJS / Vue 3 | `https://ultra-text.makio.io/integrations/tres/UltraText.vue` & `UltraTextCanvas.vue` | `ultra-text` | Add `vue({ ...templateCompilerOptions })` from `@tresjs/core` in `vite.config.ts`. |
|
|
14
|
+
| Mini3 | `https://ultra-text.makio.io/integrations/mini3/UltraText.ts` | `ultra-text/vanilla` | Zero Three.js dependency; adopts the WebGPU `GPUTexture` into a Mini3 `Texture`. |
|
|
15
|
+
|
|
16
|
+
Canonical integration guide for coding agents: `https://ultra-text.makio.io/integrations/AGENTS.md`
|
|
17
|
+
|
|
18
|
+
## Lifecycle & correctness rules for frameworks
|
|
19
|
+
|
|
20
|
+
1. **Keep source HTML outside the canvas**: render normal semantic HTML (`<article ref={setSource}>`) in the DOM, mark blocks with `data-text-block` (or `data-sdf-block`), and never apply `hidden` or `display: none`.
|
|
21
|
+
2. **Await initialization + fonts inside the async effect**:
|
|
22
|
+
- Wait for `await renderer.init()` (or `Promise.all([gpuRenderer.init(), document.fonts.ready])` in TresJS) before calling `DomText.create`.
|
|
23
|
+
- Always pass `{ signal: controller.signal }`, check `if (controller.signal.aborted)` before and after every `await`, and call `next.dispose()` immediately if aborted before state assignment (critical for React Strict Mode double-mounting and fast prop swaps).
|
|
24
|
+
3. **Clean up on unmount or source change**:
|
|
25
|
+
- Abort the in-flight `AbortController`.
|
|
26
|
+
- Detach (`owned?.removeFromParent()`) and dispose (`owned?.dispose()`) the `DomText` instance.
|
|
27
|
+
- Keep `renderer.dispose()` owned by the canvas wrapper—never dispose the shared renderer from a text component.
|
|
28
|
+
4. **Keep `options` reference-stable**: declare `const textOptions = { quality: 'high' } as const` outside the component or wrap in `useMemo`, because a new `options` object identity triggers a full teardown and rebuild.
|
|
29
|
+
5. **Account for `pixelsPerUnit: 100` in 3D scenes**: the framework starters default to `100` CSS pixels per world unit so a 600 px card is `6` units wide. Scale Z depths and motion strength accordingly:
|
|
30
|
+
```ts
|
|
31
|
+
const pixelsPerUnit = options?.pixelsPerUnit ?? 100
|
|
32
|
+
// e.g. panelDepth: -1 / pixelsPerUnit, motion: { enabled: false, strength: 18 / pixelsPerUnit }
|
|
33
|
+
```
|
|
34
|
+
6. **Continuous vs on-demand render loop**: keep `frameloop="always"` (R3F) or `render-mode="always"` (TresJS) when observing live DOM changes or TSL `motion`. If using an on-demand loop, invalidate the frame when mutations or `rebuild()` complete.
|
|
35
|
+
7. **SSR frameworks (Next.js, Nuxt, SvelteKit, Astro)**: DOM measurement and WebGPU require a browser. Guard capture and mount `<UltraTextCanvas>` only on the client.
|
|
36
|
+
|
|
37
|
+
## Verified baselines
|
|
38
|
+
|
|
39
|
+
- **Three.js**: `>=0.187.0 <0.188.0` (matches `package.json` peer dependency; use one Three.js copy).
|
|
40
|
+
- **R3F v9**: `@react-three/fiber` 9.8.2 + React 19.3.1.
|
|
41
|
+
- **R3F v10 alpha**: `@react-three/fiber` 10.0.0-alpha.6 + React 19.3.1 (prerelease APIs subject to change).
|
|
42
|
+
- **TresJS**: `@tresjs/core` 5.10.0 + Vue 3.5.44.
|
|
43
|
+
- **Mini3**: `0.1.0-alpha.0` with `ultra-text/vanilla`.
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
<!-- SPDX-License-Identifier: MIT -->
|
|
2
|
+
|
|
3
|
+
# Three.js & TSL Reference (`ultra-text` and `ultra-text/slug`)
|
|
4
|
+
|
|
5
|
+
Target runtime: ESM with `three` (`>=0.187.0 <0.188.0`), `WebGPURenderer` from `three/webgpu`, and nodes from `three/tsl`.
|
|
6
|
+
|
|
7
|
+
## Core options (`DomTextOptions` / `DomSdfOptions`)
|
|
8
|
+
|
|
9
|
+
| Option | Default | Notes |
|
|
10
|
+
| ---------------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
11
|
+
| `textBackend` | `'sdf'` | `'sdf'` (atlas), `'slug'` (dual-ray curves), or `'windfoil'` (row-band curves). |
|
|
12
|
+
| `atlasMode` | `'auto'` | SDF only: `'auto'` (GPU JFA with CPU fallback), `'gpu'`, or `'cpu'`. |
|
|
13
|
+
| `quality` | `'standard'` | SDF only: `'standard'` (1 tap, smallest) or `'high'` (4-tap sampling + mipmaps + up to 4× anisotropy). |
|
|
14
|
+
| `bakeSize / padding` | `96 / 12` | SDF texel size and field range (`maxAtlasSize` defaults to `2048`; enable `adaptiveBakeSize` near overflow). |
|
|
15
|
+
| `layoutEngine` | `'range'` | Browser `Range` fidelity, or lazy `'pretext'` Canvas layout. |
|
|
16
|
+
| `tone` | on | Matches browser ink weight; pass `{ backdrop: '#0b0b0d' }` when light text sits over a dark 3D scene, or `false` for exact coverage. |
|
|
17
|
+
| `extraGlyphs` | `—` | Pre-bake dynamic digits/symbols/emoji sequences so live edits repack instances without rebuilding the atlas. |
|
|
18
|
+
| `outline / dropShadow` | `—` | Local-unit outline (`width`, `color`, `opacity`) and hard shadow (`offsetX`, `offsetY`, `color`, `opacity`). Supported on all backends (uses an SDF underlay under Windfoil/Slug). |
|
|
19
|
+
| `motion` | `'slide-up'` | `{ enabled, mode, strength, speed, stagger }`. `mode: 'none'` omits the motion shader graph until upgraded via `setMotion()`. |
|
|
20
|
+
| `fill / vertex` | `—` | Build-time TSL callbacks (`TextFill`, `TextVertex`) evaluated only while constructing materials. |
|
|
21
|
+
| `observe / reflowable` | `true / false` | Automatic DOM/Resize observation; `reflowable: true` retains metrics for width-only `reflow(width)` without reading the DOM. |
|
|
22
|
+
| `pixelsPerUnit` | `1` | Scales captured X/Y coordinates (`textDepth: 1`, `rectDepth: 0`, `panelDepth: -1` are unscaled). |
|
|
23
|
+
| `pixelSnap` | `false` | Snaps lines/glyph origins to browser pixel grids for crisp flat 1:1 overlays. |
|
|
24
|
+
| `castShadow / side` | `true / FrontSide` | Set `castShadow: false` to skip shadow-map draws; `DoubleSide` for two-sided text. |
|
|
25
|
+
| `signal / onError` | `—` | Abort builds cleanly; handle errors from observer-triggered async rebuilds. |
|
|
26
|
+
|
|
27
|
+
## TSL custom `fill` and `vertex` hooks
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
import { mix, sin, time, vec3, vec4 } from 'three/tsl'
|
|
31
|
+
import { DomText } from 'ultra-text'
|
|
32
|
+
|
|
33
|
+
const copy = await DomText.create(renderer, source, {
|
|
34
|
+
padding: 24,
|
|
35
|
+
outline: { width: 1.2, color: '#cafae2', opacity: 0.8 },
|
|
36
|
+
dropShadow: { offsetX: 5, offsetY: -6, color: '#030c09', opacity: 1 },
|
|
37
|
+
fill: ({ position }) => {
|
|
38
|
+
const wave = sin(position.x.mul(0.02).add(time)).mul(0.5).add(0.5)
|
|
39
|
+
return vec4(mix(vec3(0.1, 0.8, 0.5), vec3(1, 0.25, 0.08), wave), 1)
|
|
40
|
+
},
|
|
41
|
+
vertex: ({ position, center, sequence }) => {
|
|
42
|
+
const bob = sin(time.mul(2).add(sequence.mul(0.35))).mul(2)
|
|
43
|
+
return position.add(vec3(0, bob, sin(center.x.mul(0.015).add(time)).mul(4)))
|
|
44
|
+
},
|
|
45
|
+
})
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
- `fill` receives `{ uv, position, color, colorWeight, glyphIndex }` and returns linear RGBA `Node<'vec4'>`; coverage, `tone`, DOM opacity, and scene shadows still apply.
|
|
49
|
+
- `vertex` receives `{ position, center, uv, glyphIndex, sequence, rect, clip }` after built-in motion and returns displaced local `Node<'vec3'>` (runs on both beauty and shadow passes; block `clip` is computed beforehand so Z waves do not clip).
|
|
50
|
+
|
|
51
|
+
## Analytic Slug & Windfoil outlines
|
|
52
|
+
|
|
53
|
+
- **Pure Slug bundle (`ultra-text/slug`)**: exports `DomSlug` (aliased `DomText`), `SlugText` (aliased `Text`), `SlugMaterial`, `createTrueTypeOutlineProvider`, `parseTrueTypeFont`, `createTracedOutlineProvider`, `createSvgEmojiOutlineProvider`, and omits all SDF rasterizer/JFA/worker code.
|
|
54
|
+
- **No `.ttf` file needed by default**: if `outlineProvider` is omitted, `DomSlug` / `textBackend: 'slug'` / `'windfoil'` traces the browser's rendered glyphs on Canvas 2D (`traceSize: 256`, `traceTolerance: 0.25`). Colour glyphs use an SDF companion on `ultra-text` (`fallback: 'sdf-glyphs'`) or `missingGlyphs: 'skip' | 'error'` on `ultra-text/slug`.
|
|
55
|
+
- **Exact TTF curves**: when bundling an uncompressed `.ttf` font, parse it once and reuse the provider:
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
import { DomSlug, createTrueTypeOutlineProvider } from 'ultra-text/slug'
|
|
59
|
+
|
|
60
|
+
const ttfBytes = await fetch('/fonts/inter.ttf').then((r) => r.arrayBuffer())
|
|
61
|
+
const outlineProvider = createTrueTypeOutlineProvider(ttfBytes)
|
|
62
|
+
const copy = await DomSlug.create(renderer, source, { outlineProvider })
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
- Note on Windfoil: `textBackend: 'windfoil'` adapts upstream Windfoil (Apache-2.0); upstream notes patent considerations to evaluate for commercial use.
|
|
66
|
+
|
|
67
|
+
## SVG capture, standalone shapes, and vector emoji
|
|
68
|
+
|
|
69
|
+
- `svg: true` (or `{ render: 'bitmap', images: true, unsupported: 'error', maxPathData }`) captures inline `<svg>` elements using Range layout; shapes count in `stats.shapes`.
|
|
70
|
+
- For scene-authored shapes, import `svgToWindfoilOutlines`, `windfoilOutlineFromSvgPaths`, and `createWindfoilShapes` from `ultra-text`.
|
|
71
|
+
- For vector emoji on analytic backends, wrap your font provider with `createSvgEmojiOutlineProvider({ text, resolve, em })` and supply app-owned SVG artwork.
|
|
72
|
+
|
|
73
|
+
## Runtime updates & shared atlases
|
|
74
|
+
|
|
75
|
+
- Motion uniforms update without rebuilding shaders or DOM: `copy.setMotion({ mode: 'offset', speed: 0.8 })`.
|
|
76
|
+
- Width-only re-wrap: create with `{ reflowable: true }`, then call `copy.reflow(widthPx)` (`1.51 ms` median on 1,000 glyphs vs full DOM `rebuild()`).
|
|
77
|
+
- Force rebuild: `await copy.rebuild()` (re-reads DOM, reuses retained atlas if glyph signature matches) or `await copy.rebuild({ atlas: true })`.
|
|
78
|
+
- Lower-level SDF stages (`collectDomSnapshot`, `rasterizeGlyphAtlas`, `buildSdfAtlas`, `createGlyphGeometry`, `SdfTextMaterial`, `createRectGeometry`, `createRectMaterial`, `reflowSnapshot`) let multiple meshes share one `SdfAtlas`; pass `sharedAtlas` (matching `quality` and `colorGlyphs` mode) and dispose `sharedAtlas` only after every consumer has been disposed.
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
<!-- SPDX-License-Identifier: MIT -->
|
|
2
|
+
|
|
3
|
+
# Vanilla WebGPU & Mini3 Reference (`ultra-text/vanilla` and `ultra-text/slug-vanilla`)
|
|
4
|
+
|
|
5
|
+
Both vanilla entry points run DOM capture, Pretext/Range layout, `reflow()`, observers, and GPU preprocessing with **zero Three.js dependency** and **zero `@webgpu/types` dependency** (structural `GPUDevice` / `GPUTexture` / `GPUBuffer` interfaces).
|
|
6
|
+
|
|
7
|
+
## SDF controller (`ultra-text/vanilla`)
|
|
8
|
+
|
|
9
|
+
Note the argument order: `DomText.create(element, gpuDevice, options)` takes the HTML element **first** and the `GPUDevice` (or `{ device }` object) **second**.
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { DomText } from 'ultra-text/vanilla'
|
|
13
|
+
|
|
14
|
+
await document.fonts.ready
|
|
15
|
+
const source = document.querySelector<HTMLElement>('#card')!
|
|
16
|
+
|
|
17
|
+
const domText = await DomText.create(source, gpuDevice, {
|
|
18
|
+
quality: 'high',
|
|
19
|
+
reflowable: true,
|
|
20
|
+
onChange(instance, reason) {
|
|
21
|
+
// reason: 'create' | 'rebuild' | 'reflow' | 'motion' | 'dispose'
|
|
22
|
+
// instance.glyphs -> VanillaGlyphInstances (positions, uvs, colors, sdfParams, ...)
|
|
23
|
+
// instance.plainRects -> VanillaRectInstances | null
|
|
24
|
+
// instance.litRects -> VanillaRectInstances | null
|
|
25
|
+
// instance.decorations -> VanillaDecorationInstances | null
|
|
26
|
+
// instance.atlas -> VanillaSdfAtlas (gpuTexture on GPU, data Uint8Array on CPU)
|
|
27
|
+
},
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
// Fast width-only relayout: fires onChange(instance, 'reflow')
|
|
31
|
+
domText.reflow(560)
|
|
32
|
+
// Cleanup:
|
|
33
|
+
domText.dispose()
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
- **String helper**: `Text` (`VanillaText`) supports `await Text.create('Hello', { device: gpuDevice, css, cssClass, onChange })` as well as `setText()`, `setCss()`, and `setClass()`.
|
|
37
|
+
- **Lower-level exports**: `collectDomSnapshot`, `reflowSnapshot`, `buildVanillaSdfAtlas` (`buildSdfAtlas`), `buildVanillaGpuSdfAtlas`, `buildVanillaCpuSdfAtlas`, `rasterizeGlyphAtlas`, `packGlyphInstances`, `updateGlyphInstances`, `updateGlyphContentInstances`, `packRectInstances`, `updateRectInstances`, `packDecorationInstances`, `updateDecorationInstances`, `computeInstanceBounds`, `resolveDomTextTone`, `UNIT_QUAD_POSITIONS`, `UNIT_QUAD_NORMALS`, `UNIT_QUAD_INDICES`.
|
|
38
|
+
|
|
39
|
+
## Pure Slug WebGPU pipeline (`ultra-text/slug-vanilla`)
|
|
40
|
+
|
|
41
|
+
`ultra-text/slug-vanilla` omits all SDF/JFA/CPU-EDT code and ships `SLUG_WGSL`, `createVanillaSlugPipeline`, and `uploadSlugGlyphBuffers` for immediate rendering in any raw `GPURenderPassEncoder`:
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
import {
|
|
45
|
+
createVanillaSlugPipeline,
|
|
46
|
+
DomSlug,
|
|
47
|
+
uploadSlugGlyphBuffers,
|
|
48
|
+
type VanillaSlugGpuInstances,
|
|
49
|
+
} from 'ultra-text/slug-vanilla'
|
|
50
|
+
|
|
51
|
+
await document.fonts.ready
|
|
52
|
+
|
|
53
|
+
const pipeline = createVanillaSlugPipeline(gpuDevice, {
|
|
54
|
+
format: navigator.gpu.getPreferredCanvasFormat(),
|
|
55
|
+
depthFormat: 'depth24plus', // optional
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
let gpuInstances: VanillaSlugGpuInstances | null = null
|
|
59
|
+
let bindGroup: unknown = null
|
|
60
|
+
|
|
61
|
+
const domSlug = await DomSlug.create(source, gpuDevice, {
|
|
62
|
+
// Optional: outlineProvider: createTrueTypeOutlineProvider(ttfBuffer)
|
|
63
|
+
onChange(instance, reason) {
|
|
64
|
+
if (reason === 'dispose') {
|
|
65
|
+
gpuInstances?.dispose()
|
|
66
|
+
gpuInstances = null
|
|
67
|
+
bindGroup = null
|
|
68
|
+
return
|
|
69
|
+
}
|
|
70
|
+
bindGroup = pipeline.createBindGroup(instance.atlas)
|
|
71
|
+
if (!gpuInstances) {
|
|
72
|
+
gpuInstances = uploadSlugGlyphBuffers(gpuDevice, instance.glyphs)
|
|
73
|
+
} else {
|
|
74
|
+
gpuInstances.update(instance.glyphs)
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
// Inside render pass:
|
|
80
|
+
pipeline.writeUniforms({
|
|
81
|
+
mvp, // column-major 4x4 Float32Array
|
|
82
|
+
viewportWidth: canvas.width,
|
|
83
|
+
viewportHeight: canvas.height,
|
|
84
|
+
})
|
|
85
|
+
if (bindGroup && gpuInstances) {
|
|
86
|
+
pipeline.draw(pass, bindGroup, gpuInstances) // calls pass.draw(6, gpuInstances.count)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Cleanup:
|
|
90
|
+
domSlug.dispose()
|
|
91
|
+
pipeline.dispose()
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
- **Buffer caution on rebuilds**: `gpuInstances.update(next)` calls `writeBuffer` into the existing vertex buffers; if a rebuild increases glyph capacity beyond the initial buffer sizes, recreate `gpuInstances = uploadSlugGlyphBuffers(gpuDevice, next)` after disposing the old one.
|
|
95
|
+
- **Standalone lower-level Slug exports**: `buildVanillaSlugAtlas` (`buildSlugAtlas`), `packSlugGlyphInstances`, `updateSlugGlyphInstances`, `preprocessSlugGlyphs`, `createTrueTypeOutlineProvider`, `parseTrueTypeFont`, `createTracedOutlineProvider`, `createSvgEmojiOutlineProvider`, `svgToWindfoilOutlines`, `windfoilOutlineFromSvgPaths`, `SLUG_WGSL`.
|