Gum tool font generation

From vchelaru/Gum · View interactive version

Gum tool font generation is an AI agent skill from the GitHub repository vchelaru/Gum. Gum bitmap font generation — tool converts font properties into .fnt/.png via bmfont.exe or KernSmith. Triggers: BmfcSave, HeadlessFontGenerationService, FontManager, FontFileGeneratorSelector, KernSmithFileGenerator, BmfcTemplate.bmfc, texture size estimation, dropshadow.

How to use this skill

Skill file

Font Generation Pipeline

Gum generates BMFont-format bitmap fonts (.fnt + .png atlas). Pipeline: collect font properties → build BmfcSave → pick a generator backend → produce .fnt + .png. Two interchangeable IFontFileGenerator backends exist, chosen per-project via GumProjectSave.FontGenerator (FontGeneratorType.BmFont, the default for back-compat, or .KernSmith):

FontFileGeneratorSelector picks between them at generation time (project isn't loaded yet when DI wires services up, so selection can't happen at construction).

Architecture

FontManager (tool facade)
  └─ HeadlessFontGenerationService (core logic, headless)
       ├─ BmfcSave (data model + .bmfc serialization)
       │    └─ BmfcTemplate.bmfc (template file with placeholders, bmfont.exe only)
       └─ FontFileGeneratorSelector → BmFontExeFileGenerator | KernSmithFileGenerator

FontManager is the tool-facing entry point. It wires IFontGenerationCallbacks (UI output, spinner, file-watch suppression) and delegates all real work to HeadlessFontGenerationService via IHeadlessFontGenerationService.

HeadlessFontGenerationService is platform-checked for the bmfont.exe backend only (throws PlatformNotSupportedException off-Windows when FontGeneratorType.BmFont is selected). It owns:

Texture-size estimation is bmfont.exe-specific and does not run for KernSmith. EstimateBlocksNeeded's heuristic (and the dropshadow blindness that falls out of it) only matters for BmFontExeFileGenerator. IFontFileGenerator.RequiresSizeEstimation (false on KernSmithFileGenerator, true on BmFontExeFileGenerator) gates the whole AssignEstimatedNeededSizeOn call in HeadlessFontGenerationService — KernSmith instead sizes its own atlas via FontGeneratorOptions.AutofitTexture.

BmfcSave holds the six font properties (FontName, FontSize, OutlineThickness, UseSmoothing, IsItalic, IsBold) plus ranges, spacing, and output dimensions. Its Save() method loads BmfcTemplate.bmfc and does string replacement to produce the .bmfc file that bmfont.exe consumes. It also owns FontCacheFileName which determines the output path.

Generation Flow

  1. Property collection: FontReferenceCollector.BuildBmfcSave (GumCommon/Bundle/FontReferenceCollector.cs) reads font properties through a getValue callback and returns a BmfcSave or null. It is the single source of truth for building a BmfcSave from variables - don't add a second copy alongside it. For direct Text instances a plain state lookup is enough, but for component instances containing Text, CollectFontsFromNestedTextInstances recursively descends using RecursiveVariableFinder to resolve font properties through exposed variables, inheritance, and categorized states a container assigns through an exposed variable (e.g. StyleCategoryState). A conditional VariableReferences row on a component instance that drives a font variable inside the component has every branch collected (CollectFontsFromNestedTextInstancesAllBranches).
  2. Deduplication: CollectRequiredFonts iterates all elements/states/instances and deduplicates by FontCacheFileName (a deterministic name encoding all font parameters).
  3. Size estimation: Before generating, AssignEstimatedNeededSizeOn either runs a binary-search optimization (GetOptimizedSizeFor, controlled by AutoSizeFontOutputs project setting) or uses a heuristic lookup table (EstimateBlocksNeeded) based on effective font size.
  4. Template expansion: BmfcSave.Save() loads Content/BmfcTemplate.bmfc, replaces placeholders, and writes the .bmfc file alongside the target .fnt path.
  5. bmfont.exe invocation: CreateBitmapFontFilesIfNecessaryAsync launches bmfont.exe -c "<bmfc>" -o "<fnt>" via Process.Start with UseShellExecute = true. The process is awaited async (WaitForExitAsync) or synchronously depending on createTask.
  6. File-watch suppression: Before writing, all expected output paths (.bmfc, .fnt, .png pages) are registered with IFontGenerationCallbacks.OnIgnoreFileChange so the file watcher doesn't trigger reloads.

Font Cache Naming

BmfcSave.FontCacheFileName produces paths like FontCache/Font18Arial.fnt. The name encodes all parameters that affect output:

This means two elements with identical font settings share one cached file.

A font file adds _ttf, then, only when GumProjectSave.UsesPathHashedFontCacheNames (project Version 6 or later), an 8-digit FNV-1a hash of the path as the Text typed it (BmfcSave.GetPathHash, slashes normalized), so same-named files in different folders get separate atlases. Older projects keep the unhashed name because their shipped .fnt files use it, so the runtime never checks two names. Every place that builds a name or a BmfcSave must pass the project's flag (BmfcSave.IncludePathHashInCacheName; CustomSetPropertyOnRenderable.ApplyFontCacheNaming does it for the runtime paths). BmfcSave.FontFile is often already resolved to an absolute path by then, so the hash comes from FontFileAsReferenced, the typed path; hashing the absolute path makes the tool bake a name the runtime never looks up and makes the same project generate different names on each machine (HeadlessFontGenerationService resolves FontFile after collection and records the typed path first). The Forms theme templates ship pre-baked file fonts in FontCache, named with the hash.

Channel Behavior (Outline vs No-Outline)

When OutlineThickness is 0: alpha=0, RGB channels=4 (glyph in alpha channel).

When OutlineThickness > 0: alpha=1, RGB channels=0 (outline uses color channels).

Texture Size Optimization

GetOptimizedSizeFor does a binary search over AvailableSizes (32x32 up to 8192x8192) to find the smallest texture that keeps the font on a single page. Each probe generates the font to a temp directory and parses the pages= line from the resulting .fnt file.

The heuristic fallback (EstimateBlocksNeeded) uses a lookup table mapping effective font size to a number of 256-pixel blocks, then factors the block count into width x height.

Character Ranges

Re-baking When Ranges Change

The cache file name does not encode ranges, so existence alone can't say a .fnt is current. After either generator succeeds, HeadlessFontGenerationService appends one line to the text .fnt recording the requested ranges (gum ranges="32-126,160-255", FontRangesStamp). CreateBitmapFontFilesIfNecessaryAsync re-bakes an existing file when the recorded codepoints differ from the ranges asked for now (compared as sets, so spelling doesn't matter). A .fnt with no line (older bakes, bmfont.exe output, XML/binary format) is treated as current, unless the font's ranges came from its own FontRangeEntries entry (BmfcSave.RangesAreFontSpecific, set from GumProjectSave.GetFontRanges(font, out isFontSpecific)): a per-font entry is newer than any unstamped bake, so that file can't have used it and re-bakes once. ParsedFontFile skips the unknown gum tag, as it does KernSmith's own trailing kernsmith line; the page scan matches the text page id= anywhere in the file, so never put that in a stamped value. The glyph ids in the file can't stand in for the requested ranges, since a font that lacks a glyph omits it.

Embedded Resources

bmfont.exe and BmfcTemplate.bmfc are embedded in the Gum.ProjectServices assembly and extracted on first use by EnsureToolsExtracted into FileManager.UserApplicationDataForThisApplication/FontTools, never the install folder (it may be read-only). The template uses placeholder tokens like FontNameVariable, FontSizeVariable, {UseSmoothing}, etc.

Standalone CLI

GumProjectFontGenerator is a standalone console app that loads a .gumx project and generates all missing fonts. It uses HeadlessFontGenerationService directly with no callbacks.

Font Creation Paths

All font generation now routes through HeadlessFontGenerationService. There are two call sites:

On-demand: CustomSetPropertyOnRenderable resolves IFontManager via DI (Builder.Get<IFontManager>()) and calls CreateFontIfNecessary(BmfcSave) when a font property changes. The BBCode path (GetAndCreateFontIfNecessary) uses the same pattern for inline font tags.

Bulk (tool-only): CreateAllMissingFontFiles scans the entire project on load or "regenerate fonts" and generates all missing font files in parallel.

BBCode runs. The tool generates fonts for BBCode runs when the wireframe draws a Text: ApplyFontVariables resolves each run's font stack and calls IFontManager.CreateFontIfNecessary. The bulk collection (FontReferenceCollector, CollectRequiredFonts, gumcli fonts) replays the same stack model through the shared helper BbCodeFontStacks (GumRuntime/BbCodeFontStacks.cs), seeded from the Text's own font, over every state's Text value. A change to which tags affect the font goes in that helper so both paths change together.

Both delegate to HeadlessFontGenerationService. Legacy IRuntimeFontService, GenerateMissingFontsForReferencingElements, and the embedded bmfont.exe in RenderingLibrary have been removed.

The two paths overlap at project load. The bulk pass runs on background tasks while the wireframe resolves fonts synchronously on the UI thread. HeadlessFontGenerationService.TryCreateFontFor keeps one in-flight generation per target .fnt (_inFlight): an async caller joins it, a sync caller gets FontFileStatus.Generating (it cannot block, the in-flight continuations need the UI thread) and GetOrCreateBakedFont then returns null without caching or blacklisting. FontCacheLogic reloads wireframe content once the bulk pass reports it generated anything, so text that resolved mid-flight picks the files up.

Key Files

| File | Purpose |

|------|---------|

| Tools/Gum.Presentation/Services/Fonts/IFontManager.cs | Interface for the tool-facing font manager |

| Tools/Gum.Presentation/Services/Fonts/FontManager.cs | Tool facade — delegates to headless service via DI |

| Tools/Gum.ProjectServices/FontGeneration/HeadlessFontGenerationService.cs | Core generation logic — collection, size estimation, bmfont.exe invocation |

| Tools/Gum.ProjectServices/FontGeneration/IHeadlessFontGenerationService.cs | Interface for the headless service |

| Tools/Gum.ProjectServices/FontGeneration/IFontGenerationCallbacks.cs | Callback interface (output, spinner, file-watch ignore) |

| Tools/Gum.Presentation/Services/Fonts/ToolFontGenerationCallbacks.cs | Tool-specific callback implementation |

| RenderingLibrary/Graphics/Fonts/BmfcSave.cs | Font data model, .bmfc serialization, cache file naming, range utilities |

| GumCommon/Bundle/FontReferenceCollector.cs | Builds every BmfcSave a project needs from its variables |

| Tools/Gum.Presentation/Plugins/InternalPlugins/FontsPlugin/ | The Fonts settings page's FontsViewModel (ranges table plus generation settings), FontsChangeLogic, and its rows in SettingsWindow/FontsRows.cs; the plugin and page view are Avalonia-head only (Tool/Gum.Avalonia/Plugins/Fonts/, Settings/FontsSettingsPageView.cs, FontRangesDisplay.cs), so the frozen WPF head has no Fonts settings page |

| Gum/Content/BmfcTemplate.bmfc | Template with placeholders for bmfont.exe config |

| GumProjectFontGenerator/Program.cs | Standalone CLI for batch font generation |

Off Windows: BmFont requests resolve to KernSmith

bmfont.exe only runs on Windows, but GumProjectSave.FontGenerator defaults to BmFont for back-compat. FontGeneratorResolver (Gum.ProjectServices) maps the requested type to the effective one: BmFont on macOS/Linux becomes KernSmith; everything else passes through. FontFileGeneratorSelector and the CLI fonts command both go through it, and the selector takes an optional isBmFontSupported delegate so tests can exercise the substitution on any OS. Packages published for macOS/Linux do not embed bmfont.exe at all: the release workflow passes -p:EmbedBmFont=false for non-win-* RIDs (the SDK strips RuntimeIdentifier from library references, so a custom global property is the channel), and FontGeneratorResolver.IsBmFontSupported also requires BmFontExeFileGenerator.IsEmbeddedInThisAssembly. BmFontEmbeddingTests (RepoHygiene) pins the csproj condition; smoke-test-package.sh checks each packaged Gum.ProjectServices.dll. Plain dotnet build/test keeps the resource.

KernSmith output differs slightly from bmfont output, so a project generated on Windows and then on macOS will have different .fnt/.png bytes unless it already uses KernSmith.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.