Skip to content

Bitmap Font Generator — Go source

Turn a TTF into a game-ready bitmap font sheet + BMFont .fnt — entirely in your browser. Nothing uploads.

This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.

// bitmap-font-generator — charset parser + BMFont TEXT emitter (Go port).
// Go 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 Go browser story and the
// island owns it anyway — this snippet covers the pure charset/font-geometry
// half only.
package bitmapfont

import (
	"fmt"
	"regexp"
	"sort"
	"strconv"
	"strings"
)

// FontError is the Go twin of the TS FontError class ('invalid' is the only code).
type FontError struct {
	Message string
}

func (e *FontError) Error() string { return e.Message }

// Max valid Unicode scalar value.
const maxCodepoint = 0x10ffff

var (
	// Hex form: U+HEX or U+HEX-HEX (end may drop the U+ prefix).
	reHex = regexp.MustCompile(`(?i)^u\+([0-9a-f]+)(?:-([0-9a-f]+))?$`)
	// Decimal form: N or N-N.
	reDec = regexp.MustCompile(`^(\d+)(?:-(\d+))?$`)
	// Inner whitespace is stripped from every comma item before parsing.
	reSpace = regexp.MustCompile(`\s+`)
)

// Inclusive [lo, hi] codepoint range expanded to a sorted list.
func codepointRange(lo, hi int) []rune {
	out := make([]rune, 0, hi-lo+1)
	for cp := lo; cp <= hi; cp++ {
		out = append(out, rune(cp))
	}
	return out
}

// Named charsets, as documented in the tool docs (fresh copies per call —
// callers may mutate the returned slice).
func presets() map[string][]rune {
	return map[string][]rune{
		"ascii":  codepointRange(32, 126),
		"latin1": append(codepointRange(32, 126), codepointRange(160, 255)...),
		"digits": codepointRange(48, 57),
	}
}

// ParseCharset parses a charset spec into a deduped, sorted codepoint list.
func ParseCharset(spec string) ([]rune, error) {
	trimmed := strings.TrimSpace(spec)
	if trimmed == "" {
		return nil, &FontError{"Charset is empty — name a preset or list codepoint ranges."}
	}
	if preset, ok := presets()[strings.ToLower(trimmed)]; ok {
		out := make([]rune, len(preset))
		copy(out, preset)
		return out, nil
	}

	seen := map[rune]bool{}
	for _, raw := range strings.Split(trimmed, ",") {
		token := reSpace.ReplaceAllString(strings.TrimSpace(raw), "")
		lo, hi, err := parseToken(token)
		if err != nil {
			return nil, err
		}
		for cp := lo; cp <= hi; cp++ {
			seen[rune(cp)] = true
		}
	}
	out := make([]rune, 0, len(seen))
	for cp := range seen {
		out = append(out, cp)
	}
	sort.Slice(out, func(i, j int) bool { return out[i] < out[j] })
	return out, nil
}

// parseToken maps one comma item to inclusive bounds, or FontError when garbage.
func parseToken(token string) (int, int, error) {
	invalid := func() error {
		return &FontError{fmt.Sprintf("%q is not a codepoint or range — use 65-90 or U+4E00-9FFF.", token)}
	}
	base := 10
	m := reDec.FindStringSubmatch(token)
	if hm := reHex.FindStringSubmatch(token); hm != nil {
		base = 16
		m = hm
	}
	if m == nil {
		return 0, 0, invalid()
	}
	lo, err := strconv.ParseInt(m[1], base, 64)
	if err != nil {
		// Digits past int64 overflow — the TS parseInt yields Infinity here,
		// which lands in the "outside Unicode" branch below.
		return 0, 0, &FontError{fmt.Sprintf("%q is outside Unicode (max U+10FFFF).", token)}
	}
	hi := lo
	if m[2] != "" {
		hi, err = strconv.ParseInt(m[2], base, 64)
		if err != nil {
			return 0, 0, &FontError{fmt.Sprintf("%q is outside Unicode (max U+10FFFF).", token)}
		}
	}
	if lo > maxCodepoint || hi > maxCodepoint {
		return 0, 0, &FontError{fmt.Sprintf("%q is outside Unicode (max U+10FFFF).", token)}
	}
	if lo > hi {
		return 0, 0, &FontError{fmt.Sprintf("%q runs backwards — put the smaller codepoint first.", token)}
	}
	return int(lo), int(hi), nil
}

// FntChar is one char entry in the emitted .fnt (geometry already scaled to pixels).
type FntChar struct {
	Codepoint int
	X, Y      int
	W, H      int
	Xoffset   int
	Yoffset   int
	Xadvance  int
}

// FntKerning is one kerning pair in the emitted .fnt (pixel amount, may be negative).
type FntKerning struct {
	First  int
	Second int
	Amount int
}

// FntInfo mirrors the TS info block: padding is broadcast to all four sides.
type FntInfo struct {
	Face    string
	Size    int
	Padding int
}

// FntCommon mirrors the TS common block.
type FntCommon struct {
	LineHeight int
	Base       int
	ScaleW     int
	ScaleH     int
}

// FntText emits a BMFont TEXT-format document
// (https://www.angelcode.com/products/bmfont/doc/font_file_format.html).
// Pages are always 1 ("sheet.png").
func FntText(info FntInfo, common FntCommon, chars []FntChar, kernings []FntKerning) string {
	p := info.Padding
	lines := []string{
		fmt.Sprintf(`info face=%q 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),
		fmt.Sprintf("common lineHeight=%d base=%d scaleW=%d scaleH=%d pages=1 packed=0 alphaChnl=0 redChnl=0 greenChnl=0 blueChnl=0",
			common.LineHeight, common.Base, common.ScaleW, common.ScaleH),
		`page id=0 file="sheet.png"`,
		fmt.Sprintf("chars count=%d", len(chars)),
	}
	for _, c := range chars {
		lines = append(lines, fmt.Sprintf(
			"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))
	}
	lines = append(lines, fmt.Sprintf("kernings count=%d", len(kernings)))
	for _, k := range kernings {
		lines = append(lines, fmt.Sprintf("kerning first=%d second=%d amount=%d", k.First, k.Second, k.Amount))
	}
	return strings.Join(lines, "\n")
}

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 →