Bitmap Font Generator — Zig source
Turn a TTF into a game-ready bitmap font sheet + BMFont .fnt — entirely in your browser. Nothing uploads.
This is the Zig implementation — the same logic the interactive tool runs, in a shareable, citable form.
// bitmap-font-generator — charset parser + BMFont TEXT emitter. Zig 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 Zig browser story and the island owns
// it anyway — pure charset/font-geometry only. Every allocation is
// caller-owned: free `codepoints`, `err.message`, and the fnt_text return
// with the same allocator.
const std = @import("std");
const Allocator = std.mem.Allocator;
/// Max valid Unicode scalar value.
pub const MAX_CODEPOINT: u64 = 0x10ffff;
/// The Zig twin of the TS FontError class ('invalid' is the only code).
pub const FontError = struct {
code: []const u8 = "invalid",
message: []u8,
};
/// Inclusive [lo, hi] codepoint bounds from one comma item.
const Bounds = struct { lo: u64, hi: u64 };
/// Result of parse_charset: sorted, deduped codepoints, or a FontError.
pub const CharsetResult = union(enum) {
codepoints: []u32,
err: FontError,
};
/// Digits only, in the given radix, saturating at u64 max so oversized digit
/// strings still land in the "outside Unicode" branch (the TS parseInt
/// overflows to Infinity, which trips the same check).
fn parseDigits(s: []const u8, radix: u64) ?u64 {
if (s.len == 0) return null;
var v: u64 = 0;
for (s) |c| {
const d: u64 = switch (c) {
'0'...'9' => c - '0',
'a'...'f' => if (radix == 16) c - 'a' + 10 else return null,
'A'...'F' => if (radix == 16) c - 'A' + 10 else return null,
else => return null,
};
if (v > (std.math.maxInt(u64) - d) / radix) {
v = std.math.maxInt(u64);
} else {
v = v * radix + d;
}
}
return v;
}
/// One comma item → inclusive bounds, or a FontError message. The TS lib
/// anchors two regexes here; this is the same grammar hand-rolled: hex form
/// U+HEX or U+HEX-HEX (end may drop the U+ prefix), decimal N or N-N. Neither
/// radix allows '-' inside a number, so the split is safe. The message (when
/// set) is allocated with `a` and owned by the caller.
fn parseToken(a: Allocator, token: []const u8) !union(enum) { bounds: Bounds, err: FontError } {
var hex = false;
var body = token;
if (body.len >= 2 and (body[0] == 'u' or body[0] == 'U') and body[1] == '+') {
hex = true;
body = body[2..];
}
const radix: u64 = if (hex) 16 else 10;
const dash = std.mem.indexOfScalar(u8, body, '-');
const lo_raw = if (dash) |i| body[0..i] else body;
const hi_raw: ?[]const u8 = if (dash) |i| body[i + 1 ..] else null;
const lo_opt = parseDigits(lo_raw, radix);
const hi_opt: ?u64 = if (hi_raw) |hr| parseDigits(hr, radix) else lo_opt;
if (lo_opt == null or hi_opt == null) {
return .{ .err = .{ .message = try std.fmt.allocPrint(
a,
"\"{s}\" is not a codepoint or range — use 65-90 or U+4E00-9FFF.",
.{token},
) } };
}
const lo = lo_opt.?;
const hi = hi_opt.?;
if (lo > MAX_CODEPOINT or hi > MAX_CODEPOINT) {
return .{ .err = .{ .message = try std.fmt.allocPrint(
a,
"\"{s}\" is outside Unicode (max U+10FFFF).",
.{token},
) } };
}
if (lo > hi) {
return .{ .err = .{ .message = try std.fmt.allocPrint(
a,
"\"{s}\" runs backwards — put the smaller codepoint first.",
.{token},
) } };
}
return .{ .bounds = .{ .lo = lo, .hi = hi } };
}
fn boundsLessThan(_: void, x: Bounds, y: Bounds) bool {
return x.lo < y.lo;
}
/// Inclusive [lo, hi] codepoint range expanded to a sorted list.
fn codepointRange(a: Allocator, lo: u64, hi: u64) ![]u32 {
const out = try a.alloc(u32, @intCast(hi - lo + 1));
for (0..out.len) |i| out[i] = @intCast(lo + i);
return out;
}
/// 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). The returned codepoints slice (or
/// the error message) is allocated with `a` and owned by the caller.
pub fn parseCharset(a: Allocator, spec: []const u8) !CharsetResult {
const ws = " \t\n\r\x0b\x0c";
const trimmed = std.mem.trim(u8, spec, ws);
if (trimmed.len == 0) {
return .{ .err = .{ .message = try a.dupe(u8, "Charset is empty — name a preset or list codepoint ranges.") } };
}
// Named charsets, as documented in the tool docs.
if (std.ascii.eqlIgnoreCase(trimmed, "ascii")) return .{ .codepoints = try codepointRange(a, 32, 126) };
if (std.ascii.eqlIgnoreCase(trimmed, "latin1")) {
var cps = std.ArrayList(u32).empty;
try cps.appendSlice(a, try codepointRange(a, 32, 126));
try cps.appendSlice(a, try codepointRange(a, 160, 255));
return .{ .codepoints = try cps.toOwnedSlice(a) };
}
if (std.ascii.eqlIgnoreCase(trimmed, "digits")) return .{ .codepoints = try codepointRange(a, 48, 57) };
// One pass collects each comma item's bounds; sorting by lo then merging
// gives the same deduped, sorted expansion as the TS set.
var bounds = std.ArrayList(Bounds).empty;
defer bounds.deinit(a);
var it = std.mem.splitScalar(u8, trimmed, ',');
while (it.next()) |raw| {
var token = std.ArrayList(u8).empty;
defer token.deinit(a);
for (raw) |c| {
if (!std.ascii.isWhitespace(c)) try token.append(a, c);
}
const res = try parseToken(a, token.items);
switch (res) {
.bounds => |b| try bounds.append(a, b),
.err => |e| return .{ .err = e },
}
}
std.mem.sort(Bounds, bounds.items, {}, boundsLessThan);
var seen = std.ArrayList(u32).empty;
var covered: u64 = 0;
for (bounds.items, 0..) |b, i| {
var lo = b.lo;
if (i > 0 and lo <= covered) lo = covered + 1;
var cp = lo;
while (cp <= b.hi) : (cp += 1) try seen.append(a, @intCast(cp));
if (i == 0 or b.hi > covered) covered = b.hi;
}
return .{ .codepoints = try seen.toOwnedSlice(a) };
}
/// One char entry in the emitted .fnt (geometry already scaled to pixels).
pub const FntChar = struct {
codepoint: i32,
x: i32,
y: i32,
w: i32,
h: i32,
xoffset: i32,
yoffset: i32,
xadvance: i32,
};
/// One kerning pair in the emitted .fnt (pixel amount, may be negative).
pub const FntKerning = struct {
first: i32,
second: i32,
amount: i32,
};
/// Mirrors the TS info block: padding is broadcast to all four sides.
pub const FntInfo = struct {
face: []const u8,
size: i32,
padding: i32,
};
/// Mirrors the TS common block.
pub const FntCommon = struct {
line_height: i32,
base: i32,
scale_w: i32,
scale_h: i32,
};
/// Emit a BMFont TEXT-format document; pages are always 1 ("sheet.png").
/// Caller owns the returned buffer.
pub fn fntText(
a: Allocator,
info: FntInfo,
common: FntCommon,
chars: []const FntChar,
kernings: []const FntKerning,
) ![]u8 {
var doc = std.ArrayList(u8).empty;
errdefer doc.deinit(a);
const p = info.padding;
try appendFmt(&doc, a, "info face=\"{s}\" size={d} bold=0 italic=0 charset=\"\" unicode=1" ++
" stretchH=100 smooth=1 aa=1 padding={d},{d},{d},{d} spacing=1,1 outline=0", .{ info.face, info.size, p, p, p, p });
try appendFmt(&doc, a, "common lineHeight={d} base={d} scaleW={d} scaleH={d}" ++
" pages=1 packed=0 alphaChnl=0 redChnl=0 greenChnl=0 blueChnl=0", .{ common.line_height, common.base, common.scale_w, common.scale_h });
try appendFmt(&doc, a, "page id=0 file=\"sheet.png\"", .{});
try appendFmt(&doc, a, "chars count={d}", .{chars.len});
for (chars) |c| {
try appendFmt(&doc, a, "char id={d} x={d} y={d} width={d} height={d}" ++
" xoffset={d} yoffset={d} xadvance={d} page=0 chnl=15", .{ c.codepoint, c.x, c.y, c.w, c.h, c.xoffset, c.yoffset, c.xadvance });
}
try appendFmt(&doc, a, "kernings count={d}", .{kernings.len});
for (kernings) |k| {
try appendFmt(&doc, a, "kerning first={d} second={d} amount={d}", .{ k.first, k.second, k.amount });
}
return doc.toOwnedSlice(a);
}
fn appendFmt(doc: *std.ArrayList(u8), a: Allocator, comptime fmt: []const u8, args: anytype) !void {
if (doc.items.len > 0) try doc.append(a, '\n');
const line = try std.fmt.allocPrint(a, fmt, args);
defer a.free(line);
try doc.appendSlice(a, line);
}
// Example:
// var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
// const a = arena.allocator();
// const fnt = try fntText(a, .{ .face = "TestFace", .size = 32, .padding = 1 },
// .{ .line_height = 38, .base = 29, .scale_w = 128, .scale_h = 128 }, &.{}, &.{});
// // 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
fn printList(label: []const u8, r: CharsetResult) !void {
const cps = r.codepoints;
std.debug.print("{s} len={d}", .{ label, cps.len });
for (cps) |cp| std.debug.print(" {d}", .{cp});
std.debug.print("\n", .{});
}
fn printSpec(a: Allocator, spec: []const u8) !void {
const r = try parseCharset(a, spec);
switch (r) {
.codepoints => try printList(spec, r),
.err => |e| {
std.debug.print("ERR {s} : {s}\n", .{ spec, e.code });
a.free(e.message);
},
}
}
fn endsOf(r: CharsetResult) struct { first: u32, last: u32, len: usize } {
const cps = r.codepoints;
return .{ .first = cps[0], .last = cps[cps.len - 1], .len = cps.len };
}
/// Demo: the lib's canonical vectors (mirrors src/lib/bitmap-font.test.ts).
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const a = arena.allocator();
try printList("ascii", try parseCharset(a, "ascii"));
{
const l1 = (try parseCharset(a, "latin1")).codepoints;
std.debug.print("latin1 len={d} c0={d} c94={d} c95={d} c190={d}\n", .{ l1.len, l1[0], l1[94], l1[95], l1[190] });
}
{
const d = endsOf(try parseCharset(a, "digits"));
std.debug.print("digits first={d} last={d} len={d}\n", .{ d.first, d.last, d.len });
}
std.debug.print("ascii-ws len={d}\n", .{(try parseCharset(a, " ASCII ")).codepoints.len});
std.debug.print("latin1-case c95={d}\n", .{(try parseCharset(a, "Latin1")).codepoints[95]});
std.debug.print("digits-ws len={d}\n", .{(try parseCharset(a, "\tDigits\n")).codepoints.len});
{
const d = endsOf(try parseCharset(a, "65-90,97-122"));
std.debug.print("dec-ranges first={d} last={d} len={d}\n", .{ d.first, d.last, d.len });
}
try printSpec(a, "122,65,97");
try printSpec(a, "65-70,68,65");
try printSpec(a, "U+41");
try printSpec(a, "u+41");
{
const d = endsOf(try parseCharset(a, "U+4E00-9FFF"));
std.debug.print("U+4E00-9FFF first={d} last={d} len={d}\n", .{ d.first, d.last, d.len });
}
try printSpec(a, "65,U+42,67-68");
try printSpec(a, " 65 - 67 , U+0041 ");
try printSpec(a, "0");
try printSpec(a, "U+10FFFF");
const bad = [_][]const u8{ "", " ", "abc", "65-,90", "-5", "65,zz", "U+", "U+ZZ", "zz", "1114112", "U+110000", "65-2000000", "90-65", "U+9FFF-4E00", "0-0x10FFFF" };
for (bad) |spec| {
const r = try parseCharset(a, spec);
switch (r) {
.codepoints => {
std.debug.print("ERR {s} : NO-ERROR\n", .{spec});
},
.err => |e| std.debug.print("ERR {s} : {s}\n", .{ spec, e.code }),
}
}
const info = FntInfo{ .face = "TestFace", .size = 32, .padding = 1 };
const common = FntCommon{ .line_height = 38, .base = 29, .scale_w = 128, .scale_h = 128 };
const chars = [_]FntChar{
.{ .codepoint = 65, .x = 0, .y = 0, .w = 34, .h = 36, .xoffset = 0, .yoffset = 0, .xadvance = 36 },
.{ .codepoint = 66, .x = 36, .y = 0, .w = 32, .h = 36, .xoffset = 1, .yoffset = 2, .xadvance = 35 },
};
const kernings = [_]FntKerning{.{ .first = 65, .second = 66, .amount = -1 }};
std.debug.print("fntText\n", .{});
{
const fnt = try fntText(a, info, common, &chars, &kernings);
std.debug.print("{s}\n", .{fnt});
}
{
const fnt = try fntText(a, .{ .face = "TestFace", .size = 32, .padding = 4 }, common, &chars, &kernings);
const nl = std.mem.indexOfScalar(u8, fnt, '\n') orelse fnt.len;
std.debug.print("pad {s}\n", .{fnt[0..nl]});
}
{
const fnt = try fntText(a, info, common, &chars, &.{});
var n: usize = 1;
for (fnt) |c| {
if (c == '\n') n += 1;
}
const tail = std.mem.lastIndexOfScalar(u8, fnt, '\n').? + 1;
std.debug.print("kern0 {s} lines={d}\n", .{ fnt[tail..], n });
}
{
const fnt = try fntText(a, info, common, &.{}, &.{});
var n: usize = 1;
for (fnt) |c| {
if (c == '\n') n += 1;
}
std.debug.print("zerochars lines={d}\n", .{n});
}
{
const big = [_]FntChar{.{ .codepoint = 19968, .x = 0, .y = 0, .w = 32, .h = 32, .xoffset = 0, .yoffset = 0, .xadvance = 32 }};
const fnt = try fntText(a, info, common, &big, &.{});
var i: usize = 0;
var line: usize = 0;
while (line < 4) : (i += 1) {
if (fnt[i] == '\n') line += 1;
}
const nl = std.mem.indexOfScalarPos(u8, fnt, i, '\n') orelse fnt.len;
std.debug.print("bigcp {s}\n", .{fnt[i..nl]});
}
}
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 →