@excaliburjs/plugin-sdf-text 0.0.0-stage → 1.0.0

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"excalibur-sdf-text.js","names":["fragmentSource"],"sources":["../node_modules/@mapbox/tiny-sdf/index.js","../src/sdf-font.ts","../src/sdf-text-renderer.ts","../src/sdf-text.ts","../src/sdf-text-plugin.ts"],"sourcesContent":["const INF = 1e20;\n\nexport default class TinySDF {\n constructor({\n fontSize = 24,\n buffer = 3,\n radius = 8,\n cutoff = 0.25,\n fontFamily = 'sans-serif',\n fontWeight = 'normal',\n fontStyle = 'normal',\n lang = null\n } = {}) {\n this.buffer = buffer;\n this.cutoff = cutoff;\n this.radius = radius;\n this.lang = lang;\n\n // make the canvas size big enough to both have the specified buffer around the glyph\n // for \"halo\", and account for some glyphs possibly being larger than their font size\n const size = this.size = fontSize + buffer * 4;\n\n const canvas = this._createCanvas(size);\n const ctx = this.ctx = canvas.getContext('2d', {willReadFrequently: true});\n ctx.font = `${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`;\n\n ctx.textBaseline = 'alphabetic';\n ctx.textAlign = 'left'; // Necessary so that RTL text doesn't have different alignment\n ctx.fillStyle = 'black';\n\n // temporary arrays for the distance transform\n this.gridOuter = new Float64Array(size * size);\n this.gridInner = new Float64Array(size * size);\n this.f = new Float64Array(size);\n this.z = new Float64Array(size + 1);\n this.v = new Uint16Array(size);\n }\n\n _createCanvas(size) {\n const canvas = document.createElement('canvas');\n canvas.width = canvas.height = size;\n return canvas;\n }\n\n draw(char) {\n const {\n width: glyphAdvance,\n actualBoundingBoxAscent,\n actualBoundingBoxDescent,\n actualBoundingBoxLeft,\n actualBoundingBoxRight\n } = this.ctx.measureText(char);\n\n // The integer/pixel part of the top alignment is encoded in metrics.glyphTop\n // The remainder is implicitly encoded in the rasterization\n const glyphTop = Math.ceil(actualBoundingBoxAscent);\n const glyphLeft = 0;\n\n // If the glyph overflows the canvas size, it will be clipped at the bottom/right\n const glyphWidth = Math.max(0, Math.min(this.size - this.buffer, Math.ceil(actualBoundingBoxRight - actualBoundingBoxLeft)));\n const glyphHeight = Math.min(this.size - this.buffer, glyphTop + Math.ceil(actualBoundingBoxDescent));\n\n const width = glyphWidth + 2 * this.buffer;\n const height = glyphHeight + 2 * this.buffer;\n\n const len = Math.max(width * height, 0);\n const data = new Uint8ClampedArray(len);\n const glyph = {data, width, height, glyphWidth, glyphHeight, glyphTop, glyphLeft, glyphAdvance};\n if (glyphWidth === 0 || glyphHeight === 0) return glyph;\n\n const {ctx, buffer, gridInner, gridOuter} = this;\n if (this.lang) ctx.lang = this.lang;\n ctx.clearRect(buffer, buffer, glyphWidth, glyphHeight);\n ctx.fillText(char, buffer, buffer + glyphTop);\n const imgData = ctx.getImageData(buffer, buffer, glyphWidth, glyphHeight);\n\n // Initialize grids outside the glyph range to alpha 0\n gridOuter.fill(INF, 0, len);\n gridInner.fill(0, 0, len);\n\n for (let y = 0; y < glyphHeight; y++) {\n for (let x = 0; x < glyphWidth; x++) {\n const a = imgData.data[4 * (y * glyphWidth + x) + 3] / 255; // alpha value\n if (a === 0) continue; // empty pixels\n\n const j = (y + buffer) * width + x + buffer;\n\n if (a === 1) { // fully drawn pixels\n gridOuter[j] = 0;\n gridInner[j] = INF;\n\n } else { // aliased pixels\n const d = 0.5 - a;\n gridOuter[j] = d > 0 ? d * d : 0;\n gridInner[j] = d < 0 ? d * d : 0;\n }\n }\n }\n\n edt(gridOuter, 0, 0, width, height, width, this.f, this.v, this.z);\n edt(gridInner, buffer, buffer, glyphWidth, glyphHeight, width, this.f, this.v, this.z);\n\n for (let i = 0; i < len; i++) {\n const d = Math.sqrt(gridOuter[i]) - Math.sqrt(gridInner[i]);\n data[i] = Math.round(255 - 255 * (d / this.radius + this.cutoff));\n }\n\n return glyph;\n }\n}\n\n// 2D Euclidean squared distance transform by Felzenszwalb & Huttenlocher https://cs.brown.edu/~pff/papers/dt-final.pdf\nfunction edt(data, x0, y0, width, height, gridSize, f, v, z) {\n for (let x = x0; x < x0 + width; x++) edt1d(data, y0 * gridSize + x, gridSize, height, f, v, z);\n for (let y = y0; y < y0 + height; y++) edt1d(data, y * gridSize + x0, 1, width, f, v, z);\n}\n\n// 1D squared distance transform\nfunction edt1d(grid, offset, stride, length, f, v, z) {\n v[0] = 0;\n z[0] = -INF;\n z[1] = INF;\n f[0] = grid[offset];\n\n for (let q = 1, k = 0, s = 0; q < length; q++) {\n f[q] = grid[offset + q * stride];\n const q2 = q * q;\n do {\n const r = v[k];\n s = (f[q] - f[r] + q2 - r * r) / (q - r) / 2;\n } while (s <= z[k] && --k > -1);\n\n k++;\n v[k] = q;\n z[k] = s;\n z[k + 1] = INF;\n }\n\n for (let q = 0, k = 0; q < length; q++) {\n while (z[k + 1] < q) k++;\n const r = v[k];\n const qr = q - r;\n grid[offset + q * stride] = f[r] + qr * qr;\n }\n}\n","import TinySDF from '@mapbox/tiny-sdf';\nimport type { TinySDFOptions } from '@mapbox/tiny-sdf';\nimport { BoundingBox, Color, FontSource, ImageFiltering, ImageSource, ImageSourceAttributeConstants, Resource, Vector } from 'excalibur';\nimport type { HTMLImageSource, Loadable } from 'excalibur';\n\nexport type UnicodeCodePointRange = [startCodePoint: number, endCodePoint: number];\n\nexport type SDFTextAlign = 'left' | 'center' | 'right';\n\n/**\n * tiny-sdf's default cutoff: the fraction of the distance radius that lies outside the glyph edge\n */\nconst SDF_CUTOFF = 0.25;\n\n/**\n * Placement of one glyph on the atlas, as produced by tiny-sdf\n */\nexport interface SDFGlyph {\n /**\n * x pixel coordinate on the SDF atlas image\n */\n x: number;\n /**\n * y pixel coordinate on the SDF atlas image\n */\n y: number;\n /**\n * SDF image data width on the atlas (includes non-glyph buffer space)\n */\n width: number;\n /**\n * SDF image data height on the atlas (includes non-glyph buffer space)\n */\n height: number;\n /**\n * Actual glyph width\n */\n glyphWidth: number;\n /**\n * Actual glyph height (ascent from baseline + descent from baseline)\n */\n glyphHeight: number;\n /**\n * Top of the glyph, ascent above the baseline in pixels\n */\n glyphTop: number;\n /**\n * Left of the glyph relative to the pen position\n */\n glyphLeft: number;\n /**\n * Amount the glyph advances the pen while writing\n */\n glyphAdvance: number;\n}\n\n/**\n * Glyph metadata plus the raw grayscale SDF pixels, before they are placed on the atlas\n */\nexport interface SDFGlyphData extends Omit<SDFGlyph, 'x' | 'y'> {\n data: Uint8ClampedArray;\n}\n\n/**\n * JSON written next to a pre-generated atlas image, see the `ex-generate-sdf` CLI\n */\nexport interface SDFMetadata {\n /**\n * Atlas image path, relative to the metadata file\n */\n atlas: string;\n color: string;\n alphabet: string;\n fontSize: number;\n buffer: number;\n /**\n * Max ascent above the baseline of any glyph, in atlas pixels\n */\n ascent: number;\n halo: number;\n gamma: number;\n glyphs: Record<string, SDFGlyph>;\n}\n\nexport function getCharactersFromUnicodeRanges(ranges: UnicodeCodePointRange[]) {\n return ranges.flatMap(([start, end]) => Array.from({ length: end - start + 1 }, (_, i) => String.fromCodePoint(start + i))).join('');\n}\n\n/**\n * Everything the renderer needs to lay out and draw text from an SDF atlas. Implemented by\n * {@link SDFFont} (atlas generated in the browser at load time) and {@link SDFAtlas} (pre-generated).\n */\nexport abstract class SDFSource {\n /**\n * Code point to glyph placement on the atlas\n */\n public readonly glyphs: Map<string, SDFGlyph> = new Map();\n\n /**\n * The atlas image, uploaded to the GPU by the renderer\n */\n public abstract get atlas(): HTMLImageSource;\n\n public abstract get isLoaded(): boolean;\n\n /**\n * Default text color when an {@link SDFText} does not specify one\n */\n public color: Color = Color.Black;\n\n /**\n * Font size the atlas was generated at, text is scaled relative to this\n */\n public fontSize: number = 16;\n\n /**\n * Padding around every glyph on the atlas in pixels\n */\n public buffer: number = 2;\n\n /**\n * Max ascent above the baseline of any glyph in atlas pixels, used to place the first line\n */\n public ascent: number = 0;\n\n /**\n * Normalized distance at which a pixel counts as inside a glyph (0..1). tiny-sdf encodes the\n * edge at `1 - cutoff`, with the default cutoff of 0.25 that is 0.75.\n */\n public halo: number = 1 - SDF_CUTOFF;\n\n /**\n * Antialiasing ramp width around the glyph edge\n */\n public gamma: number = 0.1;\n\n private _cachedText?: string;\n private _cachedSize?: number;\n private _cachedMaxWidth?: number;\n private _cachedLines: string[] = [];\n\n /**\n * Split text into lines, honoring explicit newlines and wrapping at `maxWidth` pixels (when given)\n */\n public getLines(text: string, size: number, maxWidth?: number): string[] {\n if (this._cachedText === text && this._cachedSize === size && this._cachedMaxWidth === maxWidth) {\n return this._cachedLines;\n }\n const lines: string[] = [];\n for (const paragraph of text.split('\\n')) {\n if (maxWidth == null || this.measureLine(paragraph, size) <= maxWidth) {\n lines.push(paragraph);\n continue;\n }\n // wrap on spaces, falling back to breaking a word that does not fit on a line by itself\n let line = '';\n for (const word of paragraph.split(' ')) {\n const candidate = line ? line + ' ' + word : word;\n if (this.measureLine(candidate, size) <= maxWidth) {\n line = candidate;\n } else {\n if (line) {\n lines.push(line);\n }\n line = word;\n while (this.measureLine(line, size) > maxWidth && line.length > 1) {\n let fit = line.length - 1;\n while (fit > 1 && this.measureLine(line.slice(0, fit), size) > maxWidth) {\n fit--;\n }\n lines.push(line.slice(0, fit));\n line = line.slice(fit);\n }\n }\n }\n lines.push(line);\n }\n this._cachedText = text;\n this._cachedSize = size;\n this._cachedMaxWidth = maxWidth;\n this._cachedLines = lines;\n return lines;\n }\n\n /**\n * Width in pixels of a single line of text at `size`\n */\n public measureLine(line: string, size: number): number {\n const scale = size / this.fontSize;\n let width = 0;\n for (const char of line) {\n const glyph = this.glyphs.get(char);\n if (glyph) {\n width += glyph.glyphAdvance * scale;\n }\n }\n return width;\n }\n\n /**\n * Bounds of a block of text at `size`, every line is `size * lineHeight` tall\n */\n public measureText(text: string, size: number, maxWidth?: number, lineHeight: number = 1.2): BoundingBox {\n if (!this.isLoaded) {\n throw new Error(`Cannot measureText(\"${text}\") on an SDF source that is not loaded yet`);\n }\n const lines = this.getLines(text, size, maxWidth);\n let width = 0;\n for (const line of lines) {\n width = Math.max(width, this.measureLine(line, size));\n }\n return BoundingBox.fromDimension(width, lines.length * size * lineHeight, Vector.Zero);\n }\n\n protected _computeAscent() {\n let ascent = 0;\n for (const glyph of this.glyphs.values()) {\n ascent = Math.max(ascent, glyph.glyphTop);\n }\n this.ascent = ascent;\n }\n}\n\nexport type SDFCanvas = HTMLCanvasElement & {\n getContext(context: '2d'): any;\n width: number;\n height: number;\n};\n\nexport interface SDFImageData {\n data: any;\n}\n\nexport interface SDFFontOptions {\n /**\n * Font family to rasterize, either a system font or the family name of `fontFile`\n */\n fontFamily: string;\n /**\n * Optional font file (ttf/otf/woff) to load before generating, registered as `fontFamily`\n */\n fontFile?: string;\n /**\n * Default black\n */\n color?: Color;\n /**\n * Default 400\n */\n fontWeight?: number | string;\n /**\n * Default 'normal'\n */\n fontStyle?: string;\n /**\n * Glyphs to bake into the atlas, a string or a list of unicode code point ranges.\n * Default: ASCII printable characters (0x20-0x7E)\n */\n alphabet?: string | UnicodeCodePointRange[];\n /**\n * Font size the atlas is generated at. Roughly pick the \"biggest\" size your text will be drawn at,\n * smaller text scales down cleanly. Default 48.\n */\n fontSize?: number;\n\n // Providers exist so the same code can run headless (see the CLI, which swaps in skia-canvas)\n sdfProvider?: (options: TinySDFOptions) => TinySDF;\n canvasProvider?: (width: number, height: number) => SDFCanvas;\n imageDataProvider?: (width: number, height: number) => SDFImageData;\n fontSourceLoader?: (fontFile: string, fontFamily: string) => Promise<void>;\n}\n\n/**\n * Generates an SDF atlas when loaded, in the browser or headless. To ship a pre-generated atlas\n * instead use {@link SDFAtlas}.\n */\nexport class SDFFont extends SDFSource implements Loadable<SDFCanvas> {\n public readonly atlas: SDFCanvas;\n private _atlasCtx: CanvasRenderingContext2D;\n\n public get data() {\n return this.atlas;\n }\n\n private _isLoaded = false;\n public get isLoaded(): boolean {\n return this._isLoaded;\n }\n\n private _sdfProvider: (options: TinySDFOptions) => TinySDF = (options) => new TinySDF(options);\n private _canvasProvider: (width: number, height: number) => SDFCanvas = (width, height) => {\n const canvas = document.createElement('canvas');\n canvas.width = width;\n canvas.height = height;\n return canvas;\n };\n private _imageDataProvider: (width: number, height: number) => SDFImageData = (width, height) => new ImageData(width, height);\n private _fontSourceLoader: (font: string, family: string) => Promise<void> = async (file, family) => {\n await new FontSource(file, family).load();\n };\n\n public readonly fontFamily: string;\n public readonly fontFile?: string;\n public readonly fontWeight: string;\n public readonly fontStyle: string;\n public readonly alphabet: string;\n /**\n * Distance field radius in pixels\n */\n public readonly radius: number;\n\n constructor(options: SDFFontOptions) {\n super();\n this._sdfProvider = options.sdfProvider ?? this._sdfProvider;\n this._canvasProvider = options.canvasProvider ?? this._canvasProvider;\n this._imageDataProvider = options.imageDataProvider ?? this._imageDataProvider;\n this._fontSourceLoader = options.fontSourceLoader ?? this._fontSourceLoader;\n\n this.color = options.color ?? Color.Black;\n this.fontFile = options.fontFile;\n this.fontFamily = options.fontFamily;\n this.fontSize = options.fontSize ?? 48;\n this.fontWeight = options.fontWeight?.toString() ?? '400';\n this.fontStyle = options.fontStyle ?? 'normal';\n this.alphabet = Array.isArray(options.alphabet)\n ? getCharactersFromUnicodeRanges(options.alphabet)\n : (options.alphabet ?? getCharactersFromUnicodeRanges([[0x0020, 0x007e]]));\n\n this.buffer = Math.ceil(this.fontSize / 8);\n this.radius = Math.ceil(this.fontSize / 3);\n this.gamma = (2 * 1.4142) / this.fontSize;\n\n const cell = this.fontSize + this.buffer * 2;\n const dimension = Math.ceil(Math.sqrt([...this.alphabet].length)) * cell;\n this.atlas = this._canvasProvider(dimension, dimension);\n if (!this.atlas) {\n throw new Error('Cannot build the SDF atlas canvas');\n }\n // Distance fields must be sampled with linear filtering or the edges go jagged\n this.atlas.setAttribute?.(ImageSourceAttributeConstants.Filtering, ImageFiltering.Blended);\n const ctx = this.atlas.getContext('2d') as CanvasRenderingContext2D | null;\n if (!ctx) {\n throw new Error('Cannot build the SDF atlas 2D context');\n }\n this._atlasCtx = ctx;\n }\n\n private _toRGBAImageData(alphaChannel: Uint8ClampedArray, width: number, height: number) {\n const imageData = this._imageDataProvider(width, height);\n for (let i = 0; i < alphaChannel.length; i++) {\n imageData.data[4 * i + 0] = alphaChannel[i];\n imageData.data[4 * i + 1] = alphaChannel[i];\n imageData.data[4 * i + 2] = alphaChannel[i];\n imageData.data[4 * i + 3] = 255;\n }\n return imageData;\n }\n\n async load(): Promise<SDFCanvas> {\n if (this._isLoaded) {\n return this.atlas;\n }\n if (this.fontFile) {\n await this._fontSourceLoader(this.fontFile, this.fontFamily);\n }\n\n const tinySdf = this._sdfProvider({\n fontSize: this.fontSize,\n fontFamily: this.fontFamily,\n fontStyle: this.fontStyle,\n fontWeight: this.fontWeight,\n buffer: this.buffer,\n radius: this.radius,\n cutoff: SDF_CUTOFF\n } satisfies TinySDFOptions);\n\n // Rasterize every glyph into a distance field, then pack them left to right, top to bottom\n const glyphs: [string, SDFGlyphData][] = [];\n for (const char of this.alphabet) {\n glyphs.push([char, tinySdf.draw(char)]);\n }\n let x = 0;\n let y = 0;\n let rowHeight = 0;\n for (const [char, glyph] of glyphs) {\n if (x + glyph.width > this.atlas.width) {\n x = 0;\n y += rowHeight;\n rowHeight = 0;\n }\n if (y + glyph.height > this.atlas.height) {\n throw new Error(`SDF atlas is too small for the alphabet of \"${this.fontFamily}\", this is a bug`);\n }\n this._atlasCtx.putImageData(this._toRGBAImageData(glyph.data, glyph.width, glyph.height) as any, x, y);\n const { data, ...placement } = glyph;\n this.glyphs.set(char, { ...placement, x, y });\n x += glyph.width;\n rowHeight = Math.max(rowHeight, glyph.height);\n }\n this._computeAscent();\n this._isLoaded = true;\n return this.atlas;\n }\n\n /**\n * Metadata describing this atlas, write it next to the atlas image to load later with {@link SDFAtlas}\n */\n public toMetadata(atlasPath: string): SDFMetadata {\n const glyphs: Record<string, SDFGlyph> = {};\n for (const [char, glyph] of this.glyphs) {\n glyphs[char] = glyph;\n }\n return {\n atlas: atlasPath,\n color: this.color.toHex(),\n alphabet: this.alphabet,\n fontSize: this.fontSize,\n buffer: this.buffer,\n ascent: this.ascent,\n halo: this.halo,\n gamma: this.gamma,\n glyphs\n };\n }\n}\n\nexport interface SDFAtlasOptions {\n /**\n * Path to the atlas image file\n */\n atlasPath: string;\n /**\n * Path to the JSON glyph metadata written by the CLI\n */\n metadataPath: string;\n}\n\n/**\n * Loads a pre-generated SDF atlas (image + JSON metadata), see the `ex-generate-sdf` CLI\n */\nexport class SDFAtlas extends SDFSource implements Loadable<ImageSource> {\n public readonly data: ImageSource;\n public readonly metadata: Resource<SDFMetadata>;\n\n public get atlas(): HTMLImageElement {\n return this.data.image;\n }\n\n public get isLoaded(): boolean {\n return this.data.isLoaded && this.metadata.isLoaded;\n }\n\n constructor(options: SDFAtlasOptions) {\n super();\n this.data = new ImageSource(options.atlasPath, { filtering: ImageFiltering.Blended });\n this.metadata = new Resource<SDFMetadata>(options.metadataPath, 'json');\n }\n\n async load(): Promise<ImageSource> {\n const [, metadata] = await Promise.all([this.data.load(), this.metadata.load()]);\n for (const [char, glyph] of Object.entries(metadata.glyphs)) {\n this.glyphs.set(char, glyph);\n }\n this.color = Color.fromHex(metadata.color);\n this.halo = metadata.halo;\n this.gamma = metadata.gamma;\n this.fontSize = metadata.fontSize;\n this.buffer = metadata.buffer;\n if (metadata.ascent != null) {\n this.ascent = metadata.ascent;\n } else {\n this._computeAscent();\n }\n return this.data;\n }\n}\n","import { Color, QuadIndexBuffer, Shader, VertexBuffer, VertexLayout } from 'excalibur';\nimport type { ExcaliburGraphicsContextWebGL, HTMLImageSource, RendererPlugin, Vector } from 'excalibur';\nimport fragmentSource from './shaders/sdf-text.frag.glsl?raw';\nimport vertexSource from './shaders/sdf-text.vert.glsl?raw';\nimport type { SDFSource, SDFTextAlign } from './sdf-font';\n\n/**\n * Per draw options for {@link SDFTextRenderer.draw}\n */\nexport interface SDFDrawOptions {\n /**\n * Only draw the first n characters, handy for typewriter effects. Default all.\n */\n visibleCharacters?: number;\n /**\n * Text color, defaults to the source's color\n */\n color?: Color;\n /**\n * Alignment of lines within the text block. Default 'left'.\n */\n textAlign?: SDFTextAlign;\n /**\n * Wrap lines longer than this many pixels\n */\n maxWidth?: number;\n /**\n * Line height as a multiple of `size`. Default 1.2.\n */\n lineHeight?: number;\n}\n\n/**\n * Finds how many `if` branches the fragment shader can hold on this GPU, which bounds how many\n * atlases a batch can reference\n */\nexport function getMaxShaderComplexity(gl: WebGL2RenderingContext, numIfs: number): number {\n const assembleTestShader = (numIfs: number) => {\n const testShader = `#version 300 es\n precision mediump float;\n out vec4 fragColor;\n void main() {\n float index = 1.01;\n %%complexity%%\n }`;\n let testComplexity = '';\n for (let i = 0; i < numIfs; i++) {\n testComplexity += i === 0 ? `if (index <= ${i}.5) {\\n` : ` else if (index <= ${i}.5) {\\n`;\n testComplexity += ` fragColor = vec4(1.0);\\n`;\n testComplexity += ` }\\n`;\n }\n return testShader.replace('%%complexity%%', testComplexity);\n };\n\n let canCompile = false;\n do {\n const shader = gl.createShader(gl.FRAGMENT_SHADER)!;\n gl.shaderSource(shader, assembleTestShader(numIfs));\n gl.compileShader(shader);\n canCompile = gl.getShaderParameter(shader, gl.COMPILE_STATUS);\n gl.deleteShader(shader);\n if (!canCompile) {\n numIfs = (numIfs / 2) | 0;\n }\n } while (!canCompile && numIfs > 0);\n return Math.max(numIfs, 1);\n}\n\n/**\n * Name the renderer is registered under on the graphics context\n */\nexport const SDF_TEXT_RENDERER = 'ex.sdf-text-renderer' as const;\n\nconst FLOATS_PER_VERTEX = 9; // position (2) + uv (2) + texture index (1) + color (4)\n\n/**\n * Batched WebGL renderer for SDF text. Register it on the graphics context with\n * {@link SDFTextPlugin}, or by hand with `context.lazyRegister('ex.sdf-text-renderer', () => new SDFTextRenderer())`.\n *\n * Every glyph is one textured quad; quads from any number of {@link SDFText} draws are batched into\n * a single draw call until the vertex buffer or the texture slots fill up.\n */\nexport class SDFTextRenderer implements RendererPlugin {\n public readonly type = SDF_TEXT_RENDERER;\n public priority: number = 0;\n\n private _gl!: WebGL2RenderingContext;\n private _context!: ExcaliburGraphicsContextWebGL;\n private _shader!: Shader;\n private _buffer!: VertexBuffer;\n private _quads!: QuadIndexBuffer;\n private _layout!: VertexLayout;\n\n private _maxGlyphs: number = 10922; // max(uint16) / 6 indices per quad\n private _glyphCount: number = 0;\n private _vertexIndex: number = 0;\n\n private _maxTextures: number = 1;\n private _textures: WebGLTexture[] = [];\n private _textureToIndex = new Map<WebGLTexture, number>();\n private _images = new Set<HTMLImageSource>();\n\n private _gamma: number = 0;\n private _halo: number = 0;\n private _quad = [0, 0, 0, 0, 0, 0, 0, 0];\n\n initialize(gl: WebGL2RenderingContext, context: ExcaliburGraphicsContextWebGL): void {\n this._gl = gl;\n this._context = context;\n const maxTextureUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);\n this._maxTextures = Math.min(maxTextureUnits, getMaxShaderComplexity(gl, maxTextureUnits));\n\n this._shader = new Shader({\n name: 'ex.sdf-text-renderer',\n graphicsContext: context,\n vertexSource,\n fragmentSource: this._transformFragmentSource(fragmentSource, this._maxTextures)\n });\n this._shader.compile();\n this._shader.use();\n this._shader.setUniformMatrix('u_matrix', context.ortho);\n // Texture slots are [0, 1, 2, ... maxTextures - 1]\n this._shader.setUniformIntArray(\n 'u_textures',\n [...Array(this._maxTextures)].map((_, i) => i)\n );\n\n this._buffer = new VertexBuffer({\n gl,\n size: FLOATS_PER_VERTEX * 4 * this._maxGlyphs,\n type: 'dynamic'\n });\n this._layout = new VertexLayout({\n gl,\n shader: this._shader,\n vertexBuffer: this._buffer,\n attributes: [\n ['a_position', 2],\n ['a_uv', 2],\n ['a_textureIndex', 1],\n ['a_color', 4]\n ]\n });\n this._quads = new QuadIndexBuffer(gl, this._maxGlyphs, true);\n }\n\n private _transformFragmentSource(source: string, maxTextures: number): string {\n let texturePicker = '';\n for (let i = 0; i < maxTextures; i++) {\n texturePicker += i === 0 ? `if (v_textureIndex <= ${i}.5) {\\n` : ` else if (v_textureIndex <= ${i}.5) {\\n`;\n texturePicker += ` dist = texture(u_textures[${i}], v_uv).r;\\n`;\n texturePicker += ` }\\n`;\n }\n return source.replace('%%count%%', maxTextures.toString()).replace('%%texture_picker%%', texturePicker);\n }\n\n /**\n * Upload the atlas once (the engine's texture loader caches it) and reserve a slot in this batch\n */\n private _addAtlasTexture(image: HTMLImageSource): number {\n const texture = this._context.textureLoader.load(image, undefined, image.getAttribute('forceUpload') === 'true')!;\n image.removeAttribute('forceUpload');\n let index = this._textureToIndex.get(texture);\n if (index === undefined) {\n index = this._textures.length;\n this._textures.push(texture);\n this._textureToIndex.set(texture, index);\n this._images.add(image);\n }\n return index;\n }\n\n private _isFull(): boolean {\n return this._glyphCount >= this._maxGlyphs || this._textures.length >= this._maxTextures;\n }\n\n /**\n * Queue a block of text. `pos` is the top left of the text block, `size` the font size in pixels.\n */\n draw(source: SDFSource, text: string, pos: Vector, size: number, options?: SDFDrawOptions): void {\n if (!source.isLoaded) {\n return;\n }\n const { visibleCharacters = Infinity, textAlign = 'left', maxWidth, lineHeight = 1.2 } = options ?? {};\n const color = options?.color ?? source.color;\n\n // The edge uniforms are per atlas, a change means a new batch\n if (this._gamma !== source.gamma || this._halo !== source.halo) {\n this.flush();\n this._gamma = source.gamma;\n this._halo = source.halo;\n }\n if (this._isFull() && !this._images.has(source.atlas)) {\n this.flush();\n }\n\n const atlas = source.atlas;\n const textureId = this._addAtlasTexture(atlas);\n const atlasWidth = atlas.width;\n const atlasHeight = atlas.height;\n const transform = this._context.getTransform();\n const vertices = this._layout.vertexBuffer.bufferData;\n\n const scale = size / source.fontSize;\n const lines = source.getLines(text, size, maxWidth);\n const blockWidth = maxWidth ?? Math.max(...lines.map((line) => source.measureLine(line, size)));\n const alignFactor = textAlign === 'center' ? 0.5 : textAlign === 'right' ? 1 : 0;\n\n let drawn = 0;\n for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {\n const line = lines[lineIndex];\n let penX = pos.x + (blockWidth - source.measureLine(line, size)) * alignFactor;\n const baseline = pos.y + source.ascent * scale + lineIndex * size * lineHeight;\n\n for (const char of line) {\n if (drawn >= visibleCharacters) {\n return;\n }\n drawn++;\n const glyph = source.glyphs.get(char);\n if (!glyph) {\n continue;\n }\n if (this._isFull()) {\n // flush keeps the current atlas resident so the texture index stays valid\n const resident = atlas;\n this.flush();\n this._addAtlasTexture(resident);\n }\n\n // tiny-sdf rasterizes each glyph at (buffer, buffer + glyphTop) inside its cell\n const x = penX + (glyph.glyphLeft - source.buffer) * scale;\n const y = baseline - (glyph.glyphTop + source.buffer) * scale;\n const w = glyph.width * scale;\n const h = glyph.height * scale;\n penX += glyph.glyphAdvance * scale;\n\n const quad = this._quad;\n quad[0] = x;\n quad[1] = y;\n quad[2] = x + w;\n quad[3] = y;\n quad[4] = x;\n quad[5] = y + h;\n quad[6] = x + w;\n quad[7] = y + h;\n transform.multiplyQuadInPlace(quad);\n\n const u0 = glyph.x / atlasWidth;\n const v0 = glyph.y / atlasHeight;\n const u1 = (glyph.x + glyph.width) / atlasWidth;\n const v1 = (glyph.y + glyph.height) / atlasHeight;\n\n this._pushVertex(vertices, quad[0], quad[1], u0, v0, textureId, color);\n this._pushVertex(vertices, quad[4], quad[5], u0, v1, textureId, color);\n this._pushVertex(vertices, quad[2], quad[3], u1, v0, textureId, color);\n this._pushVertex(vertices, quad[6], quad[7], u1, v1, textureId, color);\n this._glyphCount++;\n }\n }\n }\n\n private _pushVertex(vertices: Float32Array, x: number, y: number, u: number, v: number, textureId: number, color: Color) {\n vertices[this._vertexIndex++] = x;\n vertices[this._vertexIndex++] = y;\n vertices[this._vertexIndex++] = u;\n vertices[this._vertexIndex++] = v;\n vertices[this._vertexIndex++] = textureId;\n vertices[this._vertexIndex++] = color.r / 255;\n vertices[this._vertexIndex++] = color.g / 255;\n vertices[this._vertexIndex++] = color.b / 255;\n vertices[this._vertexIndex++] = color.a;\n }\n\n public get hasPendingDraws(): boolean {\n return this._glyphCount !== 0;\n }\n\n flush(): void {\n if (this._glyphCount === 0) {\n return;\n }\n const gl = this._gl;\n this._shader.use();\n this._layout.use(true, FLOATS_PER_VERTEX * 4 * this._glyphCount);\n this._shader.setUniformMatrix('u_matrix', this._context.ortho);\n this._shader.setUniformFloat('u_gamma', this._gamma);\n this._shader.setUniformFloat('u_buffer', this._halo);\n\n for (let i = 0; i < this._maxTextures; i++) {\n gl.activeTexture(gl.TEXTURE0 + i);\n gl.bindTexture(gl.TEXTURE_2D, this._textures[i] || this._textures[0]);\n }\n\n this._quads.bind();\n gl.drawElements(gl.TRIANGLES, this._glyphCount * 6, this._quads.bufferGlType, 0);\n\n this._glyphCount = 0;\n this._vertexIndex = 0;\n this._textures.length = 0;\n this._textureToIndex.clear();\n this._images.clear();\n }\n\n dispose(): void {\n this._buffer.dispose();\n this._quads.dispose();\n this._shader.dispose();\n this._textures.length = 0;\n this._context = null as any;\n this._gl = null as any;\n }\n}\n","import { Color, ExcaliburGraphicsContextWebGL, Graphic, vec } from 'excalibur';\nimport type { ExcaliburGraphicsContext, GraphicOptions } from 'excalibur';\nimport type { SDFSource, SDFTextAlign } from './sdf-font';\nimport { SDF_TEXT_RENDERER } from './sdf-text-renderer';\nimport type { SDFTextRenderer } from './sdf-text-renderer';\n\nexport interface SDFTextOptions extends GraphicOptions {\n /**\n * The {@link SDFFont} or {@link SDFAtlas} to draw with\n */\n sdf: SDFSource;\n text: string;\n /**\n * Font size in pixels, any size works, the atlas is a distance field. Default is the source's `fontSize`.\n */\n size?: number;\n /**\n * Defaults to the source's color\n */\n color?: Color;\n /**\n * Draw only the first n characters, for typewriter effects. Default all.\n */\n visibleCharacters?: number;\n /**\n * Alignment of lines within the block. Default 'left'.\n */\n textAlign?: SDFTextAlign;\n /**\n * Wrap lines longer than this many pixels\n */\n maxWidth?: number;\n /**\n * Line height as a multiple of `size`. Default 1.2.\n */\n lineHeight?: number;\n}\n\n/**\n * A text {@link Graphic} drawn from a signed distance field atlas by the {@link SDFTextRenderer}.\n * Crisp at any size, rotation or zoom, and batched with other SDF text in the same frame.\n */\nexport class SDFText extends Graphic {\n public sdf: SDFSource;\n public size: number;\n public color?: Color;\n public visibleCharacters: number;\n public textAlign: SDFTextAlign;\n public maxWidth?: number;\n public lineHeight: number;\n\n private _text: string;\n private _measuredFor?: string;\n\n constructor(options: SDFTextOptions) {\n super(options);\n this.sdf = options.sdf;\n this._text = options.text;\n this.size = options.size ?? options.sdf.fontSize;\n this.color = options.color;\n this.visibleCharacters = options.visibleCharacters ?? Infinity;\n this.textAlign = options.textAlign ?? 'left';\n this.maxWidth = options.maxWidth;\n this.lineHeight = options.lineHeight ?? 1.2;\n this._calculateDimension();\n }\n\n public get text(): string {\n return this._text;\n }\n\n public set text(value: string) {\n this._text = value;\n this._calculateDimension();\n }\n\n public override get width(): number {\n this._calculateDimension();\n return super.width;\n }\n\n public override set width(value: number) {\n super.width = value;\n }\n\n public override get height(): number {\n this._calculateDimension();\n return super.height;\n }\n\n public override set height(value: number) {\n super.height = value;\n }\n\n private _calculateDimension() {\n if (!this.sdf.isLoaded) {\n return;\n }\n const key = `${this._text}|${this.size}|${this.maxWidth}|${this.lineHeight}`;\n if (this._measuredFor === key) {\n return;\n }\n this._measuredFor = key;\n const { width, height } = this.sdf.measureText(this._text, this.size, this.maxWidth, this.lineHeight);\n super.width = width;\n super.height = height;\n }\n\n protected _drawImage(ex: ExcaliburGraphicsContext, x: number, y: number): void {\n if (ex instanceof ExcaliburGraphicsContextWebGL) {\n ex.draw<SDFTextRenderer>(SDF_TEXT_RENDERER, this.sdf, this._text, vec(x, y), this.size, {\n visibleCharacters: this.visibleCharacters,\n color: this.color,\n textAlign: this.textAlign,\n maxWidth: this.maxWidth,\n lineHeight: this.lineHeight\n });\n }\n }\n\n clone(): SDFText {\n return new SDFText({\n ...this.cloneGraphicOptions(),\n sdf: this.sdf,\n text: this._text,\n size: this.size,\n color: this.color,\n visibleCharacters: this.visibleCharacters,\n textAlign: this.textAlign,\n maxWidth: this.maxWidth,\n lineHeight: this.lineHeight\n });\n }\n}\n","import { ExcaliburGraphicsContextWebGL, Plugin } from 'excalibur';\nimport type { ExcaliburGraphicsContext } from 'excalibur';\nimport { SDF_TEXT_RENDERER, SDFTextRenderer } from './sdf-text-renderer';\n\n/**\n * Installs the {@link SDFTextRenderer} on the engine's WebGL graphics context.\n *\n * ```typescript\n * const game = new ex.Engine({ plugins: [new SDFTextPlugin()] });\n * ```\n */\nexport class SDFTextPlugin extends Plugin {\n constructor() {\n super('sdf-text');\n }\n\n override onGraphicsPostInitialize(context: ExcaliburGraphicsContext): void {\n if (context instanceof ExcaliburGraphicsContextWebGL) {\n // Lazy: the renderer compiles its shader the first time an SDFText is drawn\n context.lazyRegister(SDF_TEXT_RENDERER, () => new SDFTextRenderer());\n }\n }\n}\n"],"ignoreList":[0],"mappings":";;AAAA,IAAM,MAAM;AAEZ,IAAqB,UAArB,MAA6B;CACzB,YAAY,EACR,WAAW,IACX,SAAS,GACT,SAAS,GACT,SAAS,KACT,aAAa,cACb,aAAa,UACb,YAAY,UACZ,OAAO,SACP,CAAC,GAAG;EACJ,KAAK,SAAS;EACd,KAAK,SAAS;EACd,KAAK,SAAS;EACd,KAAK,OAAO;EAIZ,MAAM,OAAO,KAAK,OAAO,WAAW,SAAS;EAE7C,MAAM,SAAS,KAAK,cAAc,IAAI;EACtC,MAAM,MAAM,KAAK,MAAM,OAAO,WAAW,MAAM,EAAC,oBAAoB,KAAI,CAAC;EACzE,IAAI,OAAO,GAAG,UAAU,GAAG,WAAW,GAAG,SAAS,KAAK;EAEvD,IAAI,eAAe;EACnB,IAAI,YAAY;EAChB,IAAI,YAAY;EAGhB,KAAK,YAAY,IAAI,aAAa,OAAO,IAAI;EAC7C,KAAK,YAAY,IAAI,aAAa,OAAO,IAAI;EAC7C,KAAK,IAAI,IAAI,aAAa,IAAI;EAC9B,KAAK,IAAI,IAAI,aAAa,OAAO,CAAC;EAClC,KAAK,IAAI,IAAI,YAAY,IAAI;CACjC;CAEA,cAAc,MAAM;EAChB,MAAM,S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GAAG,CAAC,GAAG,KAAK,MAAM;GACtF,mBAAmB,KAAK;GACxB,OAAO,KAAK;GACZ,WAAW,KAAK;GAChB,UAAU,KAAK;GACf,YAAY,KAAK;EACnB,CAAC;CAEL;CAEA,QAAiB;EACf,OAAO,IAAI,QAAQ;GACjB,GAAG,KAAK,oBAAoB;GAC5B,KAAK,KAAK;GACV,MAAM,KAAK;GACX,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,mBAAmB,KAAK;GACxB,WAAW,KAAK;GAChB,UAAU,KAAK;GACf,YAAY,KAAK;EACnB,CAAC;CACH;AACF;;;;;;;;;AC1HA,IAAa,gBAAb,cAAmC,OAAO;CACxC,cAAc;EACZ,MAAM,UAAU;CAClB;CAEA,yBAAkC,SAAyC;EACzE,IAAI,mBAAmB,+BAErB,QAAQ,aAAa,yBAAyB,IAAI,gBAAgB,CAAC;CAEvE;AACF"}
@@ -0,0 +1,498 @@
1
+ import { BoundingBox as N, Color as L, ExcaliburGraphicsContextWebGL as H, FontSource as j, Graphic as Q, ImageFiltering as $, ImageSource as Z, ImageSourceAttributeConstants as J, Plugin as K, QuadIndexBuffer as Y, Resource as tt, Shader as et, Vector as it, VertexBuffer as st, VertexLayout as at, vec as rt } from "excalibur";
2
+ var C = 1e20, ht = class {
3
+ constructor({ fontSize: t = 24, buffer: e = 3, radius: i = 8, cutoff: s = 0.25, fontFamily: a = "sans-serif", fontWeight: r = "normal", fontStyle: h = "normal", lang: o = null } = {}) {
4
+ this.buffer = e, this.cutoff = s, this.radius = i, this.lang = o;
5
+ const n = this.size = t + e * 4, l = this._createCanvas(n), c = this.ctx = l.getContext("2d", { willReadFrequently: !0 });
6
+ c.font = `${h} ${r} ${t}px ${a}`, c.textBaseline = "alphabetic", c.textAlign = "left", c.fillStyle = "black", this.gridOuter = new Float64Array(n * n), this.gridInner = new Float64Array(n * n), this.f = new Float64Array(n), this.z = new Float64Array(n + 1), this.v = new Uint16Array(n);
7
+ }
8
+ _createCanvas(t) {
9
+ const e = document.createElement("canvas");
10
+ return e.width = e.height = t, e;
11
+ }
12
+ draw(t) {
13
+ const { width: e, actualBoundingBoxAscent: i, actualBoundingBoxDescent: s, actualBoundingBoxLeft: a, actualBoundingBoxRight: r } = this.ctx.measureText(t), h = Math.ceil(i), o = 0, n = Math.max(0, Math.min(this.size - this.buffer, Math.ceil(r - a))), l = Math.min(this.size - this.buffer, h + Math.ceil(s)), c = n + 2 * this.buffer, f = l + 2 * this.buffer, y = Math.max(c * f, 0), F = new Uint8ClampedArray(y), T = {
14
+ data: F,
15
+ width: c,
16
+ height: f,
17
+ glyphWidth: n,
18
+ glyphHeight: l,
19
+ glyphTop: h,
20
+ glyphLeft: o,
21
+ glyphAdvance: e
22
+ };
23
+ if (n === 0 || l === 0) return T;
24
+ const { ctx: m, buffer: d, gridInner: p, gridOuter: b } = this;
25
+ this.lang && (m.lang = this.lang), m.clearRect(d, d, n, l), m.fillText(t, d, d + h);
26
+ const D = m.getImageData(d, d, n, l);
27
+ b.fill(C, 0, y), p.fill(0, 0, y);
28
+ for (let _ = 0; _ < l; _++) for (let x = 0; x < n; x++) {
29
+ const S = D.data[4 * (_ * n + x) + 3] / 255;
30
+ if (S === 0) continue;
31
+ const w = (_ + d) * c + x + d;
32
+ if (S === 1)
33
+ b[w] = 0, p[w] = C;
34
+ else {
35
+ const v = 0.5 - S;
36
+ b[w] = v > 0 ? v * v : 0, p[w] = v < 0 ? v * v : 0;
37
+ }
38
+ }
39
+ W(b, 0, 0, c, f, c, this.f, this.v, this.z), W(p, d, d, n, l, c, this.f, this.v, this.z);
40
+ for (let _ = 0; _ < y; _++) {
41
+ const x = Math.sqrt(b[_]) - Math.sqrt(p[_]);
42
+ F[_] = Math.round(255 - 255 * (x / this.radius + this.cutoff));
43
+ }
44
+ return T;
45
+ }
46
+ };
47
+ function W(t, e, i, s, a, r, h, o, n) {
48
+ for (let l = e; l < e + s; l++) q(t, i * r + l, r, a, h, o, n);
49
+ for (let l = i; l < i + a; l++) q(t, l * r + e, 1, s, h, o, n);
50
+ }
51
+ function q(t, e, i, s, a, r, h) {
52
+ r[0] = 0, h[0] = -1e20, h[1] = C, a[0] = t[e];
53
+ for (let o = 1, n = 0, l = 0; o < s; o++) {
54
+ a[o] = t[e + o * i];
55
+ const c = o * o;
56
+ do {
57
+ const f = r[n];
58
+ l = (a[o] - a[f] + c - f * f) / (o - f) / 2;
59
+ } while (l <= h[n] && --n > -1);
60
+ n++, r[n] = o, h[n] = l, h[n + 1] = C;
61
+ }
62
+ for (let o = 0, n = 0; o < s; o++) {
63
+ for (; h[n + 1] < o; ) n++;
64
+ const l = r[n], c = o - l;
65
+ t[e + o * i] = a[l] + c * c;
66
+ }
67
+ }
68
+ var nt = 0.25;
69
+ function G(t) {
70
+ return t.flatMap(([e, i]) => Array.from({ length: i - e + 1 }, (s, a) => String.fromCodePoint(e + a))).join("");
71
+ }
72
+ var k = class {
73
+ glyphs = /* @__PURE__ */ new Map();
74
+ color = L.Black;
75
+ fontSize = 16;
76
+ buffer = 2;
77
+ ascent = 0;
78
+ halo = 0.75;
79
+ gamma = 0.1;
80
+ _cachedText;
81
+ _cachedSize;
82
+ _cachedMaxWidth;
83
+ _cachedLines = [];
84
+ getLines(t, e, i) {
85
+ if (this._cachedText === t && this._cachedSize === e && this._cachedMaxWidth === i) return this._cachedLines;
86
+ const s = [];
87
+ for (const a of t.split(`
88
+ `)) {
89
+ if (i == null || this.measureLine(a, e) <= i) {
90
+ s.push(a);
91
+ continue;
92
+ }
93
+ let r = "";
94
+ for (const h of a.split(" ")) {
95
+ const o = r ? r + " " + h : h;
96
+ if (this.measureLine(o, e) <= i) r = o;
97
+ else
98
+ for (r && s.push(r), r = h; this.measureLine(r, e) > i && r.length > 1; ) {
99
+ let n = r.length - 1;
100
+ for (; n > 1 && this.measureLine(r.slice(0, n), e) > i; ) n--;
101
+ s.push(r.slice(0, n)), r = r.slice(n);
102
+ }
103
+ }
104
+ s.push(r);
105
+ }
106
+ return this._cachedText = t, this._cachedSize = e, this._cachedMaxWidth = i, this._cachedLines = s, s;
107
+ }
108
+ measureLine(t, e) {
109
+ const i = e / this.fontSize;
110
+ let s = 0;
111
+ for (const a of t) {
112
+ const r = this.glyphs.get(a);
113
+ r && (s += r.glyphAdvance * i);
114
+ }
115
+ return s;
116
+ }
117
+ measureText(t, e, i, s = 1.2) {
118
+ if (!this.isLoaded) throw new Error(`Cannot measureText("${t}") on an SDF source that is not loaded yet`);
119
+ const a = this.getLines(t, e, i);
120
+ let r = 0;
121
+ for (const h of a) r = Math.max(r, this.measureLine(h, e));
122
+ return N.fromDimension(r, a.length * e * s, it.Zero);
123
+ }
124
+ _computeAscent() {
125
+ let t = 0;
126
+ for (const e of this.glyphs.values()) t = Math.max(t, e.glyphTop);
127
+ this.ascent = t;
128
+ }
129
+ }, ft = class extends k {
130
+ atlas;
131
+ _atlasCtx;
132
+ get data() {
133
+ return this.atlas;
134
+ }
135
+ _isLoaded = !1;
136
+ get isLoaded() {
137
+ return this._isLoaded;
138
+ }
139
+ _sdfProvider = (t) => new ht(t);
140
+ _canvasProvider = (t, e) => {
141
+ const i = document.createElement("canvas");
142
+ return i.width = t, i.height = e, i;
143
+ };
144
+ _imageDataProvider = (t, e) => new ImageData(t, e);
145
+ _fontSourceLoader = async (t, e) => {
146
+ await new j(t, e).load();
147
+ };
148
+ fontFamily;
149
+ fontFile;
150
+ fontWeight;
151
+ fontStyle;
152
+ alphabet;
153
+ radius;
154
+ constructor(t) {
155
+ super(), this._sdfProvider = t.sdfProvider ?? this._sdfProvider, this._canvasProvider = t.canvasProvider ?? this._canvasProvider, this._imageDataProvider = t.imageDataProvider ?? this._imageDataProvider, this._fontSourceLoader = t.fontSourceLoader ?? this._fontSourceLoader, this.color = t.color ?? L.Black, this.fontFile = t.fontFile, this.fontFamily = t.fontFamily, this.fontSize = t.fontSize ?? 48, this.fontWeight = t.fontWeight?.toString() ?? "400", this.fontStyle = t.fontStyle ?? "normal", this.alphabet = Array.isArray(t.alphabet) ? G(t.alphabet) : t.alphabet ?? G([[32, 126]]), this.buffer = Math.ceil(this.fontSize / 8), this.radius = Math.ceil(this.fontSize / 3), this.gamma = 2.8284 / this.fontSize;
156
+ const e = this.fontSize + this.buffer * 2, i = Math.ceil(Math.sqrt([...this.alphabet].length)) * e;
157
+ if (this.atlas = this._canvasProvider(i, i), !this.atlas) throw new Error("Cannot build the SDF atlas canvas");
158
+ this.atlas.setAttribute?.(J.Filtering, $.Blended);
159
+ const s = this.atlas.getContext("2d");
160
+ if (!s) throw new Error("Cannot build the SDF atlas 2D context");
161
+ this._atlasCtx = s;
162
+ }
163
+ _toRGBAImageData(t, e, i) {
164
+ const s = this._imageDataProvider(e, i);
165
+ for (let a = 0; a < t.length; a++)
166
+ s.data[4 * a + 0] = t[a], s.data[4 * a + 1] = t[a], s.data[4 * a + 2] = t[a], s.data[4 * a + 3] = 255;
167
+ return s;
168
+ }
169
+ async load() {
170
+ if (this._isLoaded) return this.atlas;
171
+ this.fontFile && await this._fontSourceLoader(this.fontFile, this.fontFamily);
172
+ const t = this._sdfProvider({
173
+ fontSize: this.fontSize,
174
+ fontFamily: this.fontFamily,
175
+ fontStyle: this.fontStyle,
176
+ fontWeight: this.fontWeight,
177
+ buffer: this.buffer,
178
+ radius: this.radius,
179
+ cutoff: nt
180
+ }), e = [];
181
+ for (const r of this.alphabet) e.push([r, t.draw(r)]);
182
+ let i = 0, s = 0, a = 0;
183
+ for (const [r, h] of e) {
184
+ if (i + h.width > this.atlas.width && (i = 0, s += a, a = 0), s + h.height > this.atlas.height) throw new Error(`SDF atlas is too small for the alphabet of "${this.fontFamily}", this is a bug`);
185
+ this._atlasCtx.putImageData(this._toRGBAImageData(h.data, h.width, h.height), i, s);
186
+ const { data: o, ...n } = h;
187
+ this.glyphs.set(r, {
188
+ ...n,
189
+ x: i,
190
+ y: s
191
+ }), i += h.width, a = Math.max(a, h.height);
192
+ }
193
+ return this._computeAscent(), this._isLoaded = !0, this.atlas;
194
+ }
195
+ toMetadata(t) {
196
+ const e = {};
197
+ for (const [i, s] of this.glyphs) e[i] = s;
198
+ return {
199
+ atlas: t,
200
+ color: this.color.toHex(),
201
+ alphabet: this.alphabet,
202
+ fontSize: this.fontSize,
203
+ buffer: this.buffer,
204
+ ascent: this.ascent,
205
+ halo: this.halo,
206
+ gamma: this.gamma,
207
+ glyphs: e
208
+ };
209
+ }
210
+ }, _t = class extends k {
211
+ data;
212
+ metadata;
213
+ get atlas() {
214
+ return this.data.image;
215
+ }
216
+ get isLoaded() {
217
+ return this.data.isLoaded && this.metadata.isLoaded;
218
+ }
219
+ constructor(t) {
220
+ super(), this.data = new Z(t.atlasPath, { filtering: $.Blended }), this.metadata = new tt(t.metadataPath, "json");
221
+ }
222
+ async load() {
223
+ const [, t] = await Promise.all([this.data.load(), this.metadata.load()]);
224
+ for (const [e, i] of Object.entries(t.glyphs)) this.glyphs.set(e, i);
225
+ return this.color = L.fromHex(t.color), this.halo = t.halo, this.gamma = t.gamma, this.fontSize = t.fontSize, this.buffer = t.buffer, t.ascent != null ? this.ascent = t.ascent : this._computeAscent(), this.data;
226
+ }
227
+ }, ot = `#version 300 es
228
+ precision mediump float;
229
+
230
+ in vec2 v_uv;
231
+ in vec4 v_color;
232
+ in lowp float v_textureIndex;
233
+
234
+ // Atlases in the current batch
235
+ uniform sampler2D u_textures[%%count%%];
236
+
237
+ // Distance at which a pixel counts as "inside" the glyph (0..1, atlas dependent)
238
+ uniform float u_buffer;
239
+ // Width of the antialiasing ramp around that edge
240
+ uniform float u_gamma;
241
+
242
+ out vec4 fragColor;
243
+
244
+ void main(){
245
+ float dist = 1.0;
246
+
247
+ // GLSL is templated out to pick the right texture by index
248
+ %%texture_picker%%
249
+
250
+ float alpha = smoothstep(u_buffer - u_gamma, u_buffer + u_gamma, dist);
251
+ fragColor = vec4(v_color.rgb, alpha * v_color.a);
252
+ // Excalibur expects premultiplied alpha
253
+ fragColor.rgb *= fragColor.a;
254
+ }
255
+ `, lt = `#version 300 es
256
+ in vec2 a_position;
257
+
258
+ in vec2 a_uv;
259
+ out vec2 v_uv;
260
+
261
+ in vec4 a_color;
262
+ out vec4 v_color;
263
+
264
+ in lowp float a_textureIndex;
265
+ out lowp float v_textureIndex;
266
+
267
+ uniform mat4 u_matrix;
268
+
269
+ void main(){
270
+ gl_Position = u_matrix * vec4(a_position, 0., 1.);
271
+ v_uv = a_uv;
272
+ v_color = a_color;
273
+ v_textureIndex = a_textureIndex;
274
+ }
275
+ `;
276
+ function ct(t, e) {
277
+ const i = (a) => {
278
+ const r = `#version 300 es
279
+ precision mediump float;
280
+ out vec4 fragColor;
281
+ void main() {
282
+ float index = 1.01;
283
+ %%complexity%%
284
+ }`;
285
+ let h = "";
286
+ for (let o = 0; o < a; o++)
287
+ h += o === 0 ? `if (index <= ${o}.5) {
288
+ ` : ` else if (index <= ${o}.5) {
289
+ `, h += ` fragColor = vec4(1.0);
290
+ `, h += ` }
291
+ `;
292
+ return r.replace("%%complexity%%", h);
293
+ };
294
+ let s = !1;
295
+ do {
296
+ const a = t.createShader(t.FRAGMENT_SHADER);
297
+ t.shaderSource(a, i(e)), t.compileShader(a), s = t.getShaderParameter(a, t.COMPILE_STATUS), t.deleteShader(a), s || (e = e / 2 | 0);
298
+ } while (!s && e > 0);
299
+ return Math.max(e, 1);
300
+ }
301
+ var M = "ex.sdf-text-renderer", dt = class {
302
+ type = M;
303
+ priority = 0;
304
+ _gl;
305
+ _context;
306
+ _shader;
307
+ _buffer;
308
+ _quads;
309
+ _layout;
310
+ _maxGlyphs = 10922;
311
+ _glyphCount = 0;
312
+ _vertexIndex = 0;
313
+ _maxTextures = 1;
314
+ _textures = [];
315
+ _textureToIndex = /* @__PURE__ */ new Map();
316
+ _images = /* @__PURE__ */ new Set();
317
+ _gamma = 0;
318
+ _halo = 0;
319
+ _quad = [
320
+ 0,
321
+ 0,
322
+ 0,
323
+ 0,
324
+ 0,
325
+ 0,
326
+ 0,
327
+ 0
328
+ ];
329
+ initialize(t, e) {
330
+ this._gl = t, this._context = e;
331
+ const i = t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS);
332
+ this._maxTextures = Math.min(i, ct(t, i)), this._shader = new et({
333
+ name: "ex.sdf-text-renderer",
334
+ graphicsContext: e,
335
+ vertexSource: lt,
336
+ fragmentSource: this._transformFragmentSource(ot, this._maxTextures)
337
+ }), this._shader.compile(), this._shader.use(), this._shader.setUniformMatrix("u_matrix", e.ortho), this._shader.setUniformIntArray("u_textures", [...Array(this._maxTextures)].map((s, a) => a)), this._buffer = new st({
338
+ gl: t,
339
+ size: 36 * this._maxGlyphs,
340
+ type: "dynamic"
341
+ }), this._layout = new at({
342
+ gl: t,
343
+ shader: this._shader,
344
+ vertexBuffer: this._buffer,
345
+ attributes: [
346
+ ["a_position", 2],
347
+ ["a_uv", 2],
348
+ ["a_textureIndex", 1],
349
+ ["a_color", 4]
350
+ ]
351
+ }), this._quads = new Y(t, this._maxGlyphs, !0);
352
+ }
353
+ _transformFragmentSource(t, e) {
354
+ let i = "";
355
+ for (let s = 0; s < e; s++)
356
+ i += s === 0 ? `if (v_textureIndex <= ${s}.5) {
357
+ ` : ` else if (v_textureIndex <= ${s}.5) {
358
+ `, i += ` dist = texture(u_textures[${s}], v_uv).r;
359
+ `, i += ` }
360
+ `;
361
+ return t.replace("%%count%%", e.toString()).replace("%%texture_picker%%", i);
362
+ }
363
+ _addAtlasTexture(t) {
364
+ const e = this._context.textureLoader.load(t, void 0, t.getAttribute("forceUpload") === "true");
365
+ t.removeAttribute("forceUpload");
366
+ let i = this._textureToIndex.get(e);
367
+ return i === void 0 && (i = this._textures.length, this._textures.push(e), this._textureToIndex.set(e, i), this._images.add(t)), i;
368
+ }
369
+ _isFull() {
370
+ return this._glyphCount >= this._maxGlyphs || this._textures.length >= this._maxTextures;
371
+ }
372
+ draw(t, e, i, s, a) {
373
+ if (!t.isLoaded) return;
374
+ const { visibleCharacters: r = 1 / 0, textAlign: h = "left", maxWidth: o, lineHeight: n = 1.2 } = a ?? {}, l = a?.color ?? t.color;
375
+ (this._gamma !== t.gamma || this._halo !== t.halo) && (this.flush(), this._gamma = t.gamma, this._halo = t.halo), this._isFull() && !this._images.has(t.atlas) && this.flush();
376
+ const c = t.atlas, f = this._addAtlasTexture(c), y = c.width, F = c.height, T = this._context.getTransform(), m = this._layout.vertexBuffer.bufferData, d = s / t.fontSize, p = t.getLines(e, s, o), b = o ?? Math.max(...p.map((x) => t.measureLine(x, s))), D = h === "center" ? 0.5 : h === "right" ? 1 : 0;
377
+ let _ = 0;
378
+ for (let x = 0; x < p.length; x++) {
379
+ const S = p[x];
380
+ let w = i.x + (b - t.measureLine(S, s)) * D;
381
+ const v = i.y + t.ascent * d + x * s * n;
382
+ for (const O of S) {
383
+ if (_ >= r) return;
384
+ _++;
385
+ const g = t.glyphs.get(O);
386
+ if (!g) continue;
387
+ if (this._isFull()) {
388
+ const X = c;
389
+ this.flush(), this._addAtlasTexture(X);
390
+ }
391
+ const A = w + (g.glyphLeft - t.buffer) * d, I = v - (g.glyphTop + t.buffer) * d, P = g.width * d, E = g.height * d;
392
+ w += g.glyphAdvance * d;
393
+ const u = this._quad;
394
+ u[0] = A, u[1] = I, u[2] = A + P, u[3] = I, u[4] = A, u[5] = I + E, u[6] = A + P, u[7] = I + E, T.multiplyQuadInPlace(u);
395
+ const B = g.x / y, z = g.y / F, R = (g.x + g.width) / y, U = (g.y + g.height) / F;
396
+ this._pushVertex(m, u[0], u[1], B, z, f, l), this._pushVertex(m, u[4], u[5], B, U, f, l), this._pushVertex(m, u[2], u[3], R, z, f, l), this._pushVertex(m, u[6], u[7], R, U, f, l), this._glyphCount++;
397
+ }
398
+ }
399
+ }
400
+ _pushVertex(t, e, i, s, a, r, h) {
401
+ t[this._vertexIndex++] = e, t[this._vertexIndex++] = i, t[this._vertexIndex++] = s, t[this._vertexIndex++] = a, t[this._vertexIndex++] = r, t[this._vertexIndex++] = h.r / 255, t[this._vertexIndex++] = h.g / 255, t[this._vertexIndex++] = h.b / 255, t[this._vertexIndex++] = h.a;
402
+ }
403
+ get hasPendingDraws() {
404
+ return this._glyphCount !== 0;
405
+ }
406
+ flush() {
407
+ if (this._glyphCount === 0) return;
408
+ const t = this._gl;
409
+ this._shader.use(), this._layout.use(!0, 36 * this._glyphCount), this._shader.setUniformMatrix("u_matrix", this._context.ortho), this._shader.setUniformFloat("u_gamma", this._gamma), this._shader.setUniformFloat("u_buffer", this._halo);
410
+ for (let e = 0; e < this._maxTextures; e++)
411
+ t.activeTexture(t.TEXTURE0 + e), t.bindTexture(t.TEXTURE_2D, this._textures[e] || this._textures[0]);
412
+ this._quads.bind(), t.drawElements(t.TRIANGLES, this._glyphCount * 6, this._quads.bufferGlType, 0), this._glyphCount = 0, this._vertexIndex = 0, this._textures.length = 0, this._textureToIndex.clear(), this._images.clear();
413
+ }
414
+ dispose() {
415
+ this._buffer.dispose(), this._quads.dispose(), this._shader.dispose(), this._textures.length = 0, this._context = null, this._gl = null;
416
+ }
417
+ }, xt = class V extends Q {
418
+ sdf;
419
+ size;
420
+ color;
421
+ visibleCharacters;
422
+ textAlign;
423
+ maxWidth;
424
+ lineHeight;
425
+ _text;
426
+ _measuredFor;
427
+ constructor(e) {
428
+ super(e), this.sdf = e.sdf, this._text = e.text, this.size = e.size ?? e.sdf.fontSize, this.color = e.color, this.visibleCharacters = e.visibleCharacters ?? 1 / 0, this.textAlign = e.textAlign ?? "left", this.maxWidth = e.maxWidth, this.lineHeight = e.lineHeight ?? 1.2, this._calculateDimension();
429
+ }
430
+ get text() {
431
+ return this._text;
432
+ }
433
+ set text(e) {
434
+ this._text = e, this._calculateDimension();
435
+ }
436
+ get width() {
437
+ return this._calculateDimension(), super.width;
438
+ }
439
+ set width(e) {
440
+ super.width = e;
441
+ }
442
+ get height() {
443
+ return this._calculateDimension(), super.height;
444
+ }
445
+ set height(e) {
446
+ super.height = e;
447
+ }
448
+ _calculateDimension() {
449
+ if (!this.sdf.isLoaded) return;
450
+ const e = `${this._text}|${this.size}|${this.maxWidth}|${this.lineHeight}`;
451
+ if (this._measuredFor === e) return;
452
+ this._measuredFor = e;
453
+ const { width: i, height: s } = this.sdf.measureText(this._text, this.size, this.maxWidth, this.lineHeight);
454
+ super.width = i, super.height = s;
455
+ }
456
+ _drawImage(e, i, s) {
457
+ e instanceof H && e.draw(M, this.sdf, this._text, rt(i, s), this.size, {
458
+ visibleCharacters: this.visibleCharacters,
459
+ color: this.color,
460
+ textAlign: this.textAlign,
461
+ maxWidth: this.maxWidth,
462
+ lineHeight: this.lineHeight
463
+ });
464
+ }
465
+ clone() {
466
+ return new V({
467
+ ...this.cloneGraphicOptions(),
468
+ sdf: this.sdf,
469
+ text: this._text,
470
+ size: this.size,
471
+ color: this.color,
472
+ visibleCharacters: this.visibleCharacters,
473
+ textAlign: this.textAlign,
474
+ maxWidth: this.maxWidth,
475
+ lineHeight: this.lineHeight
476
+ });
477
+ }
478
+ }, gt = class extends K {
479
+ constructor() {
480
+ super("sdf-text");
481
+ }
482
+ onGraphicsPostInitialize(t) {
483
+ t instanceof H && t.lazyRegister(M, () => new dt());
484
+ }
485
+ };
486
+ export {
487
+ _t as SDFAtlas,
488
+ ft as SDFFont,
489
+ k as SDFSource,
490
+ xt as SDFText,
491
+ gt as SDFTextPlugin,
492
+ dt as SDFTextRenderer,
493
+ M as SDF_TEXT_RENDERER,
494
+ G as getCharactersFromUnicodeRanges,
495
+ ct as getMaxShaderComplexity
496
+ };
497
+
498
+ //# sourceMappingURL=excalibur-sdf-text.min.js.map