UNPKG

pixi.js

Version:

<p align="center"> <a href="https://pixijs.com" target="_blank" rel="noopener noreferrer"> <img height="150" src="https://files.pixijs.download/branding/pixijs-logo-transparent-dark.svg?v=1" alt="PixiJS logo"> </a> </p> <br/> <p align="center">

1 lines 18.4 kB
{"version":3,"file":"BitmapFontManager.mjs","sources":["../../../src/scene/text-bitmap/BitmapFontManager.ts"],"sourcesContent":["import { Cache } from '../../assets/cache/Cache';\nimport { type TextureStyle, type TextureStyleOptions } from '../../rendering/renderers/shared/texture/TextureStyle';\nimport { deprecation, v8_0_0 } from '../../utils/logging/deprecation';\nimport { warn } from '../../utils/logging/warn';\nimport { CanvasTextMetrics } from '../text/canvas/CanvasTextMetrics';\nimport { TextStyle } from '../text/TextStyle';\nimport { DynamicBitmapFont } from './DynamicBitmapFont';\nimport { getBitmapTextLayout } from './utils/getBitmapTextLayout';\nimport { resolveCharacters } from './utils/resolveCharacters';\n\nimport type { TextStyleOptions } from '../text/TextStyle';\nimport type { BitmapFont } from './BitmapFont';\nimport type { BitmapTextLayoutData } from './utils/getBitmapTextLayout';\n\nlet fontCount = 0;\n\n/**\n * The options for installing a new BitmapFont. Once installed, the font will be available\n * for use in BitmapText objects through the fontFamily property of TextStyle.\n * @example\n * ```ts\n * import { BitmapFont, BitmapText } from 'pixi.js';\n *\n * // Basic font installation\n * BitmapFont.install({\n * name: 'BasicFont',\n * style: {\n * fontFamily: 'Arial',\n * fontSize: 24,\n * fill: '#ffffff'\n * }\n * });\n *\n * // Advanced font installation\n * BitmapFont.install({\n * name: 'AdvancedFont',\n * style: {\n * fontFamily: 'Arial',\n * fontSize: 32,\n * fill: '#ff0000',\n * stroke: { color: '#000000', width: 2 }\n * },\n * // Include specific character ranges\n * chars: [\n * ['a', 'z'], // lowercase letters\n * ['A', 'Z'], // uppercase letters\n * ['0', '9'], // numbers\n * '!@#$%^&*()_+-=[]{}' // symbols\n * ],\n * resolution: 2, // High-DPI support\n * padding: 4, // Glyph padding\n * skipKerning: false, // Enable kerning\n * textureStyle: {\n * scaleMode: 'linear',\n * premultiplyAlpha: true\n * }\n * });\n *\n * // Using the installed font\n * const text = new BitmapText({\n * text: 'Hello World',\n * style: {\n * fontFamily: 'AdvancedFont',\n * fontSize: 48\n * }\n * });\n * ```\n * @category text\n * @standard\n */\nexport interface BitmapFontInstallOptions\n{\n /**\n * The name of the font. This will be used as the fontFamily in text styles to access this font.\n * Must be unique across all installed bitmap fonts.\n * @example\n * ```ts\n * BitmapFont.install({\n * name: 'MyCustomFont',\n * style: { fontFamily: 'Arial' }\n * });\n * ```\n */\n name?: string;\n\n /**\n * Characters included in the font set. You can specify individual characters or ranges.\n * Don't forget to include spaces ' ' in your character set!\n * @default BitmapFont.ALPHANUMERIC\n * @example\n * ```ts\n * // Different ways to specify characters\n * BitmapFont.install({\n * name: 'RangeFont',\n * chars: [\n * ['a', 'z'], // Range of characters\n * '0123456789', // String of characters\n * [['0', '9'], ['A', 'Z']] // Multiple ranges\n * ]\n * });\n * ```\n */\n chars?: string | (string | string[])[];\n\n /**\n * Render resolution for glyphs. Higher values create sharper text at the cost of memory.\n * Useful for supporting high-DPI displays.\n * @default 1\n * @example\n * ```ts\n * BitmapFont.install({\n * name: 'HiDPIFont',\n * resolution: window.devicePixelRatio || 2\n * });\n * ```\n */\n resolution?: number;\n\n /**\n * Padding between glyphs on texture atlas. Balances visual quality with texture space.\n * - Lower values: More compact, but may have visual artifacts\n * - Higher values: Better quality, but uses more texture space\n * @default 4\n * @example\n * ```ts\n * BitmapFont.install({\n * name: 'PaddedFont',\n * padding: 8 // More padding for better quality\n * });\n * ```\n */\n padding?: number;\n\n /**\n * Skip generation of kerning information for the BitmapFont.\n * - true: Faster generation, but text may have inconsistent spacing\n * - false: Better text appearance, but slower generation\n * @default false\n * @example\n * ```ts\n * BitmapFont.install({\n * name: 'FastFont',\n * skipKerning: true // Prioritize performance\n * });\n * ```\n */\n skipKerning?: boolean;\n\n /**\n * Style options to render the BitmapFont with.\n * Supports all TextStyle properties including fill, stroke, and shadow effects.\n * @example\n * ```ts\n * BitmapFont.install({\n * name: 'StyledFont',\n * style: {\n * fontFamily: 'Arial',\n * fontSize: 32,\n * fill: ['#ff0000', '#00ff00'], // Gradient\n * stroke: { color: '#000000', width: 2 },\n * dropShadow: {\n * color: '#000000',\n * blur: 2,\n * distance: 3\n * }\n * }\n * });\n * ```\n */\n style?: TextStyle | TextStyleOptions;\n\n /**\n * Optional texture style to use when creating the font textures.\n * Controls how the font textures are rendered and filtered.\n * @example\n * ```ts\n * BitmapFont.install({\n * name: 'CrispFont',\n * textureStyle: {\n * scaleMode: 'nearest',\n * resolution: 2,\n * format: 'rgba8unorm'\n * }\n * });\n * ```\n */\n textureStyle?: TextureStyle | TextureStyleOptions;\n}\n\n/** @advanced */\nclass BitmapFontManagerClass\n{\n /**\n * This character set includes all the letters in the alphabet (both lower- and upper- case).\n * @type {string[][]}\n * @example\n * BitmapFont.from('ExampleFont', style, { chars: BitmapFont.ALPHA })\n */\n public readonly ALPHA = [['a', 'z'], ['A', 'Z'], ' '];\n\n /**\n * This character set includes all decimal digits (from 0 to 9).\n * @type {string[][]}\n * @example\n * BitmapFont.from('ExampleFont', style, { chars: BitmapFont.NUMERIC })\n */\n public readonly NUMERIC = [['0', '9']];\n\n /**\n * This character set is the union of `BitmapFont.ALPHA` and `BitmapFont.NUMERIC`.\n * @type {string[][]}\n */\n public readonly ALPHANUMERIC = [['a', 'z'], ['A', 'Z'], ['0', '9'], ' '];\n\n /**\n * This character set consists of all the ASCII table.\n * @type {string[][]}\n * @see http://www.asciitable.com/\n */\n public readonly ASCII = [[' ', '~']];\n\n /** Default options for installing a new BitmapFont. */\n public defaultOptions: Omit<BitmapFontInstallOptions, 'style'> = {\n chars: this.ALPHANUMERIC,\n resolution: 1,\n padding: 4,\n skipKerning: false,\n textureStyle: null,\n };\n\n /**\n * Get a font for the specified text and style.\n * @param text - The text to get the font for\n * @param style - The style to use\n */\n public getFont(text: string, style: TextStyle): BitmapFont\n {\n let fontFamilyKey = `${style.fontFamily as string}-bitmap`;\n let overrideFill = true;\n\n // assuming there is no texture we can use a tint!\n if (style._fill.fill && !style._stroke)\n {\n fontFamilyKey += style._fill.fill.styleKey;\n overrideFill = false;\n }\n else if (style._stroke || style.dropShadow)\n {\n // if there is a stoke, we need to use the style key as this the font generated cannot be tinted\n // due to the fact the font has at least two colors.\n let key = style.styleKey;\n\n // remove the font size..\n key = key.substring(0, key.lastIndexOf('-'));\n\n fontFamilyKey = `${key}-bitmap`;\n overrideFill = false;\n }\n\n // first get us the the right font...\n if (!Cache.has(fontFamilyKey))\n {\n const fnt = new DynamicBitmapFont({\n style,\n overrideFill,\n overrideSize: true,\n ...this.defaultOptions,\n });\n\n fontCount++;\n\n // warn users if they have created too many dynamic fonts\n if (fontCount > 50)\n {\n // eslint-disable-next-line max-len\n warn('BitmapText', `You have dynamically created ${fontCount} bitmap fonts, this can be inefficient. Try pre installing your font styles using \\`BitmapFont.install({name:\"style1\", style})\\``);\n }\n\n fnt.once('destroy', () =>\n {\n fontCount--;\n Cache.remove(fontFamilyKey);\n });\n\n Cache.set(\n fontFamilyKey as string,\n fnt\n );\n }\n\n const dynamicFont = Cache.get(fontFamilyKey);\n\n (dynamicFont as DynamicBitmapFont).ensureCharacters?.(text);\n\n return dynamicFont;\n }\n\n /**\n * Get the layout of a text for the specified style.\n * @param text - The text to get the layout for\n * @param style - The style to use\n * @param trimEnd - Whether to ignore whitespaces at the end of each line\n */\n public getLayout(text: string, style: TextStyle, trimEnd: boolean = true): BitmapTextLayoutData\n {\n const bitmapFont = this.getFont(text, style);\n\n const segments = CanvasTextMetrics.graphemeSegmenter(text);\n\n return getBitmapTextLayout(segments, style, bitmapFont, trimEnd);\n }\n\n /**\n * Measure the text using the specified style.\n * @param text - The text to measure\n * @param style - The style to use\n * @param trimEnd - Whether to ignore whitespaces at the end of each line\n */\n public measureText(\n text: string,\n style: TextStyle,\n trimEnd: boolean = true\n ): { width: number; height: number; scale: number; offsetY: number }\n {\n return this.getLayout(text, style, trimEnd);\n }\n\n /**\n * Generates a bitmap-font for the given style and character set\n * @param options - Setup options for font generation.\n * @returns Font generated by style options.\n * @example\n * import { BitmapFontManager, BitmapText } from 'pixi.js';\n *\n * BitmapFontManager.install('TitleFont', {\n * fontFamily: 'Arial',\n * fontSize: 12,\n * strokeThickness: 2,\n * fill: 'purple',\n * });\n *\n * const title = new BitmapText({ text: 'This is the title', fontFamily: 'TitleFont' });\n */\n public install(options: BitmapFontInstallOptions): BitmapFont;\n /** @deprecated since 7.0.0 */\n public install(name: string, style?: TextStyle | TextStyleOptions, options?: BitmapFontInstallOptions): BitmapFont;\n // eslint-disable-next-line max-len\n public install(...args: [string | BitmapFontInstallOptions, (TextStyle | TextStyleOptions)?, BitmapFontInstallOptions?]): BitmapFont\n {\n let options = args[0] as BitmapFontInstallOptions;\n\n if (typeof options === 'string')\n {\n options = {\n name: options,\n style: args[1],\n chars: args[2]?.chars,\n resolution: args[2]?.resolution,\n padding: args[2]?.padding,\n skipKerning: args[2]?.skipKerning,\n } as BitmapFontInstallOptions;\n\n // #if _DEBUG\n // eslint-disable-next-line max-len\n deprecation(v8_0_0, 'BitmapFontManager.install(name, style, options) is deprecated, use BitmapFontManager.install({name, style, ...options})');\n // #endif\n }\n\n const name = options?.name;\n\n if (!name)\n {\n throw new Error('[BitmapFontManager] Property `name` is required.');\n }\n\n options = { ...this.defaultOptions, ...options };\n\n const textStyle = options.style;\n\n const style = textStyle instanceof TextStyle ? textStyle : new TextStyle(textStyle);\n const overrideFill = style._fill.fill !== null && style._fill.fill !== undefined;\n const font = new DynamicBitmapFont({\n style,\n overrideFill,\n skipKerning: options.skipKerning,\n padding: options.padding,\n resolution: options.resolution,\n overrideSize: false,\n textureStyle: options.textureStyle,\n });\n\n const flatChars = resolveCharacters(options.chars);\n\n font.ensureCharacters(flatChars.join(''));\n\n Cache.set(`${name}-bitmap`, font);\n\n font.once('destroy', () => Cache.remove(`${name}-bitmap`));\n\n return font;\n }\n\n /**\n * Uninstalls a bitmap font from the cache.\n * @param {string} name - The name of the bitmap font to uninstall.\n */\n public uninstall(name: string)\n {\n const cacheKey = `${name}-bitmap`;\n const font = Cache.get<BitmapFont>(cacheKey);\n\n if (font)\n {\n font.destroy();\n }\n }\n}\n\n/**\n * The BitmapFontManager is a helper that exists to install and uninstall fonts\n * into the cache for BitmapText objects.\n * @category text\n * @advanced\n * @class\n * @example\n * import { BitmapFontManager, BitmapText } from 'pixi.js';\n *\n * BitmapFontManager.install({\n * name: 'TitleFont',\n * style: {}\n * });\n *\n * const title = new BitmapText({ text: 'This is the title', style: { fontFamily: 'TitleFont' }});\n */\nexport const BitmapFontManager = new BitmapFontManagerClass();\n"],"names":[],"mappings":";;;;;;;;;;AAcA,IAAI,SAAY,GAAA,CAAA,CAAA;AAgLhB,MAAM,sBACN,CAAA;AAAA,EADA,WAAA,GAAA;AAQI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAgB,IAAA,CAAA,KAAA,GAAQ,CAAC,CAAC,GAAK,EAAA,GAAG,GAAG,CAAC,GAAA,EAAK,GAAG,CAAA,EAAG,GAAG,CAAA,CAAA;AAQpD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAA,IAAA,CAAgB,OAAU,GAAA,CAAC,CAAC,GAAA,EAAK,GAAG,CAAC,CAAA,CAAA;AAMrC;AAAA;AAAA;AAAA;AAAA,IAAA,IAAA,CAAgB,YAAe,GAAA,CAAC,CAAC,GAAA,EAAK,GAAG,CAAG,EAAA,CAAC,GAAK,EAAA,GAAG,CAAG,EAAA,CAAC,GAAK,EAAA,GAAG,GAAG,GAAG,CAAA,CAAA;AAOvE;AAAA;AAAA;AAAA;AAAA;AAAA,IAAA,IAAA,CAAgB,KAAQ,GAAA,CAAC,CAAC,GAAA,EAAK,GAAG,CAAC,CAAA,CAAA;AAGnC;AAAA,IAAA,IAAA,CAAO,cAA0D,GAAA;AAAA,MAC7D,OAAO,IAAK,CAAA,YAAA;AAAA,MACZ,UAA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