Bitmap Font Generator — C# source
Turn a TTF into a game-ready bitmap font sheet + BMFont .fnt — entirely in your browser. Nothing uploads.
This is the C# implementation — the same logic the interactive tool runs, in a shareable, citable form.
// bitmap-font-generator — charset parser + BMFont TEXT emitter. C# port of
// the pure half of src/lib/bitmap-font.ts: preset names, decimal and U+HEX
// range specs in, sorted codepoints out; BMFont TEXT documents out. The
// rasterizing half (opentype.js) has no C# browser story and the island owns
// it anyway — pure charset/font-geometry only.
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
// The C# twin of the TS FontError class ('invalid' is the only code).
public class FontError : Exception
{
public string Code { get; } = "invalid";
public FontError(string message) : base(message) { }
}
// One char entry in the emitted .fnt (geometry already scaled to pixels).
public sealed record FntChar(int Codepoint, int X, int Y, int W, int H, int Xoffset, int Yoffset, int Xadvance);
// One kerning pair in the emitted .fnt (pixel amount, may be negative).
public sealed record FntKerning(int First, int Second, int Amount);
// Mirrors the TS info block: padding is broadcast to all four sides.
public sealed record FntInfo(string Face, int Size, int Padding);
// Mirrors the TS common block.
public sealed record FntCommon(int LineHeight, int Base, int ScaleW, int ScaleH);
public static class BitmapFont
{
// Max valid Unicode scalar value.
public const int MaxCodepoint = 0x10ffff;
// Hex form: U+HEX or U+HEX-HEX (end may drop the U+ prefix). The decimal
// class is written [0-9] explicitly so \d's Unicode widening can't accept
// anything the TS regex would reject.
private static readonly Regex ReHex =
new(@"^u\+([0-9a-f]+)(?:-([0-9a-f]+))?$", RegexOptions.IgnoreCase);
// Decimal form: N or N-N.
private static readonly Regex ReDec = new(@"^([0-9]+)(?:-([0-9]+))?$");
// Inclusive [lo, hi] codepoint range expanded to a sorted list.
private static int[] Expand(int lo, int hi)
{
int[] cps = new int[hi - lo + 1];
for (int i = 0; i < cps.Length; i++) cps[i] = lo + i;
return cps;
}
// Parse a charset spec into a deduped, sorted codepoint list.
//
// Grammar (whitespace-tolerant, comma-separated items): `ascii`, `latin1`,
// `digits` presets; or items `A` / `A-B` where each side is decimal (`65`,
// `65-90`) or `U+HEX` (`U+41`, `U+4E00-9FFF`; the range end may drop the
// `U+` prefix when the start carries it).
public static int[] ParseCharset(string spec)
{
string trimmed = spec.Trim();
if (trimmed.Length == 0)
{
throw new FontError("Charset is empty — name a preset or list codepoint ranges.");
}
switch (trimmed.ToLowerInvariant())
{
case "ascii":
return Expand(32, 126);
case "latin1":
{
int[] head = Expand(32, 126), tail = Expand(160, 255);
int[] cps = new int[head.Length + tail.Length];
head.CopyTo(cps, 0);
tail.CopyTo(cps, head.Length);
return cps;
}
case "digits":
return Expand(48, 57);
}
var seen = new SortedSet<int>();
foreach (string raw in trimmed.Split(','))
{
string token = Regex.Replace(raw.Trim(), @"\s+", "");
(long lo, long hi) = ParseToken(token);
for (long cp = lo; cp <= hi; cp++) seen.Add((int)cp);
}
int[] outCps = new int[seen.Count];
seen.CopyTo(outCps);
return outCps;
}
/// Inclusive [lo, hi] codepoint bounds of one comma item.
private readonly record struct Bounds(long Lo, long Hi);
// One comma item → inclusive bounds, or FontError when garbage. The TS
// lib anchors two regexes here; the same two regexes run in this port.
private static Bounds ParseToken(string token)
{
Match hex = ReHex.Match(token);
Match dec = ReDec.Match(token);
if (!hex.Success && !dec.Success)
{
throw new FontError($"\"{token}\" is not a codepoint or range — use 65-90 or U+4E00-9FFF.");
}
Match m = hex.Success ? hex : dec;
int radix = hex.Success ? 16 : 10;
// The regex validated plain digits, so a failed conversion here can
// only be an overflow — the TS parseInt's Infinity, i.e. outside
// Unicode.
long lo = ParseLongOrMax(m.Groups[1].Value, radix);
long hi = m.Groups[2].Success ? ParseLongOrMax(m.Groups[2].Value, radix) : lo;
if (lo > MaxCodepoint || hi > MaxCodepoint)
{
throw new FontError($"\"{token}\" is outside Unicode (max U+10FFFF).");
}
if (lo > hi)
{
throw new FontError($"\"{token}\" runs backwards — put the smaller codepoint first.");
}
return new Bounds(lo, hi);
}
private static long ParseLongOrMax(string digits, int radix)
{
try
{
return Convert.ToInt64(digits, radix);
}
catch (Exception)
{
return long.MaxValue;
}
}
// Emit a BMFont TEXT-format document; pages are always 1 ("sheet.png").
public static string FntText(FntInfo info, FntCommon common, IReadOnlyList<FntChar> chars, IReadOnlyList<FntKerning> kernings)
{
int p = info.Padding;
var lines = new List<string>
{
"info face=\"" + info.Face + "\" size=" + info.Size +
" bold=0 italic=0 charset=\"\" unicode=1 stretchH=100 smooth=1 aa=1 padding=" +
p + "," + p + "," + p + "," + p + " spacing=1,1 outline=0",
"common lineHeight=" + common.LineHeight + " base=" + common.Base +
" scaleW=" + common.ScaleW + " scaleH=" + common.ScaleH +
" pages=1 packed=0 alphaChnl=0 redChnl=0 greenChnl=0 blueChnl=0",
"page id=0 file=\"sheet.png\"",
"chars count=" + chars.Count,
};
foreach (FntChar c in chars)
{
lines.Add("char id=" + c.Codepoint + " x=" + c.X + " y=" + c.Y + " width=" + c.W +
" height=" + c.H + " xoffset=" + c.Xoffset + " yoffset=" + c.Yoffset +
" xadvance=" + c.Xadvance + " page=0 chnl=15");
}
lines.Add("kernings count=" + kernings.Count);
foreach (FntKerning k in kernings)
{
lines.Add("kerning first=" + k.First + " second=" + k.Second + " amount=" + k.Amount);
}
return string.Join("\n", lines);
}
// Example:
// var info = new FntInfo("TestFace", 32, 1);
// var common = new FntCommon(38, 29, 128, 128);
// Console.WriteLine(BitmapFont.FntText(info, common, Array.Empty<FntChar>(), Array.Empty<FntKerning>()));
// // info face="TestFace" size=32 ... padding=1,1,1,1 spacing=1,1 outline=0
// // common lineHeight=38 base=29 scaleW=128 scaleH=128 pages=1 ...
// // page id=0 file="sheet.png"
// // chars count=0
// // kernings count=0
}
public static class Program
{
private static string Join(string label, int[] cps)
{
var b = new StringBuilder(label + " len=" + cps.Length);
foreach (int cp in cps) b.Append(' ').Append(cp);
return b.ToString();
}
private static void PrintSpec(string spec) => Console.WriteLine(Join(spec, BitmapFont.ParseCharset(spec)));
// Demo: the lib's canonical vectors (mirrors src/lib/bitmap-font.test.ts).
public static void Main()
{
Console.WriteLine(Join("ascii", BitmapFont.ParseCharset("ascii")));
int[] latin1 = BitmapFont.ParseCharset("latin1");
Console.WriteLine($"latin1 len={latin1.Length} c0={latin1[0]} c94={latin1[94]} c95={latin1[95]} c190={latin1[190]}");
int[] digits = BitmapFont.ParseCharset("digits");
Console.WriteLine($"digits first={digits[0]} last={digits[^1]} len={digits.Length}");
Console.WriteLine($"ascii-ws len={BitmapFont.ParseCharset(" ASCII ").Length}");
Console.WriteLine($"latin1-case c95={BitmapFont.ParseCharset("Latin1")[95]}");
Console.WriteLine($"digits-ws len={BitmapFont.ParseCharset("\tDigits\n").Length}");
int[] decRanges = BitmapFont.ParseCharset("65-90,97-122");
Console.WriteLine($"dec-ranges first={decRanges[0]} last={decRanges[^1]} len={decRanges.Length}");
PrintSpec("122,65,97");
PrintSpec("65-70,68,65");
PrintSpec("U+41");
PrintSpec("u+41");
int[] hexRange = BitmapFont.ParseCharset("U+4E00-9FFF");
Console.WriteLine($"U+4E00-9FFF first={hexRange[0]} last={hexRange[^1]} len={hexRange.Length}");
PrintSpec("65,U+42,67-68");
PrintSpec(" 65 - 67 , U+0041 ");
PrintSpec("0");
PrintSpec("U+10FFFF");
foreach (string spec in new[] { "", " ", "abc", "65-,90", "-5", "65,zz", "U+", "U+ZZ", "zz",
"1114112", "U+110000", "65-2000000", "90-65", "U+9FFF-4E00", "0-0x10FFFF" })
{
try
{
PrintSpec(spec);
Console.WriteLine($"ERR {spec} : NO-ERROR");
}
catch (FontError e)
{
Console.WriteLine($"ERR {spec} : {e.Code}");
}
}
var info = new FntInfo("TestFace", 32, 1);
var common = new FntCommon(38, 29, 128, 128);
var chars = new FntChar[]
{
new(65, 0, 0, 34, 36, 0, 0, 36),
new(66, 36, 0, 32, 36, 1, 2, 35),
};
var kernings = new FntKerning[] { new(65, 66, -1) };
Console.WriteLine("fntText");
Console.WriteLine(BitmapFont.FntText(info, common, chars, kernings));
Console.WriteLine("pad " + BitmapFont.FntText(new FntInfo("TestFace", 32, 4), common, chars, kernings).Split('\n')[0]);
string[] noKern = BitmapFont.FntText(info, common, chars, Array.Empty<FntKerning>()).Split('\n');
Console.WriteLine($"kern0 {noKern[6]} lines={noKern.Length}");
Console.WriteLine("zerochars lines=" + BitmapFont.FntText(info, common, Array.Empty<FntChar>(), Array.Empty<FntKerning>()).Split('\n').Length);
Console.WriteLine("bigcp " + BitmapFont.FntText(info, common,
new FntChar[] { new(19968, 0, 0, 32, 32, 0, 0, 32) }, Array.Empty<FntKerning>()).Split('\n')[4]);
}
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →