Skip to content

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.
#include <cctype>
#include <cstdint>
#include <cstdio>
#include <regex>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>

// Max valid Unicode scalar value.
constexpr uint32_t kMaxCodepoint = 0x10ffff;

// The C++ twin of the TS FontError class ('invalid' is the only code).
class FontError : public std::runtime_error {
public:
    explicit FontError(const std::string& message) : std::runtime_error(message), code("invalid") {}
    std::string code;
};

namespace {

// Hex form: U+HEX or U+HEX-HEX (end may drop the U+ prefix).
const std::regex& reHex() {
    static const std::regex r("^u\\+([0-9a-f]+)(?:-([0-9a-f]+))?$", std::regex::icase);
    return r;
}

// Decimal form: N or N-N.
const std::regex& reDec() {
    static const std::regex r("^(\\d+)(?:-(\\d+))?$");
    return r;
}

// Inclusive [lo, hi] codepoint range expanded to a sorted list.
std::vector<uint32_t> codepointRange(uint32_t lo, uint32_t hi) {
    std::vector<uint32_t> out;
    out.reserve(hi - lo + 1);
    for (uint32_t cp = lo; cp <= hi; cp++) out.push_back(cp);
    return out;
}

// Digits only in the given radix; std::stoull overflows to an exception, which
// saturates to UINT64_MAX so oversized digit strings still land in the
// "outside Unicode" branch (the TS parseInt overflows to Infinity likewise).
uint64_t parseDigits(const std::string& s, int radix) {
    try {
        return std::stoull(s, nullptr, radix);
    } catch (const std::exception&) {
        return UINT64_MAX;
    }
}

// One comma item → inclusive bounds, or FontError when garbage. The TS lib
// anchors two regexes here; the same two regexes run in this port.
std::pair<uint32_t, uint32_t> parseToken(const std::string& token) {
    std::smatch hex, dec;
    std::regex_match(token, hex, reHex());
    std::regex_match(token, dec, reDec());
    if (hex.empty() && dec.empty()) {
        throw FontError("\"" + token + "\" is not a codepoint or range — use 65-90 or U+4E00-9FFF.");
    }
    const std::smatch& m = hex.empty() ? dec : hex;
    const int radix = hex.empty() ? 10 : 16;
    const uint64_t lo = parseDigits(m[1], radix);
    const uint64_t hi = m[2].matched ? parseDigits(m[2], radix) : lo;
    if (lo > kMaxCodepoint || hi > kMaxCodepoint) {
        throw FontError("\"" + token + "\" is outside Unicode (max U+10FFFF).");
    }
    if (lo > hi) throw FontError("\"" + token + "\" runs backwards — put the smaller codepoint first.");
    return {static_cast<uint32_t>(lo), static_cast<uint32_t>(hi)};
}

}  // namespace

// 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).
std::vector<uint32_t> parseCharset(const std::string& spec) {
    static const std::set<uint32_t> kPresetsNotUsed;  // presets expand eagerly below
    const std::string trimmed = [&] {
        size_t b = 0, e = spec.size();
        while (b < e && std::isspace(static_cast<unsigned char>(spec[b]))) b++;
        while (e > b && std::isspace(static_cast<unsigned char>(spec[e - 1]))) e--;
        return spec.substr(b, e - b);
    }();
    if (trimmed.empty()) throw FontError("Charset is empty — name a preset or list codepoint ranges.");

    std::string lower = trimmed;
    for (char& c : lower) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));

    // Named charsets, as documented in the tool docs.
    if (lower == "ascii") return codepointRange(32, 126);
    if (lower == "latin1") {
        std::vector<uint32_t> cps = codepointRange(32, 126);
        const std::vector<uint32_t> tail = codepointRange(160, 255);
        cps.insert(cps.end(), tail.begin(), tail.end());
        return cps;
    }
    if (lower == "digits") return codepointRange(48, 57);

    std::set<uint32_t> seen;
    size_t start = 0;
    while (true) {
        const size_t comma = trimmed.find(',', start);
        const std::string raw = trimmed.substr(start, comma == std::string::npos ? std::string::npos : comma - start);
        std::string token;
        token.reserve(raw.size());
        for (const char c : raw) {
            if (!std::isspace(static_cast<unsigned char>(c))) token.push_back(c);
        }
        const auto [lo, hi] = parseToken(token);
        for (uint32_t cp = lo; cp <= hi; cp++) seen.insert(cp);
        if (comma == std::string::npos) break;
        start = comma + 1;
    }
    return std::vector<uint32_t>(seen.begin(), seen.end());
}

// One char entry in the emitted .fnt (geometry already scaled to pixels).
struct FntChar {
    int codepoint, x, y, w, h, xoffset, yoffset, xadvance;
};

// One kerning pair in the emitted .fnt (pixel amount, may be negative).
struct FntKerning {
    int first, second, amount;
};

// Mirrors the TS info block: padding is broadcast to all four sides.
struct FntInfo {
    std::string face;
    int size, padding;
};

// Mirrors the TS common block.
struct FntCommon {
    int lineHeight, base, scaleW, scaleH;
};

// Emit a BMFont TEXT-format document; pages are always 1 ("sheet.png").
std::string fntText(const FntInfo& info, const FntCommon& common,
                    const std::vector<FntChar>& chars, const std::vector<FntKerning>& kernings) {
    std::ostringstream out;
    out << "info face=\"" << info.face << "\" size=" << info.size
        << " bold=0 italic=0 charset=\"\" unicode=1 stretchH=100 smooth=1 aa=1 padding="
        << info.padding << ',' << info.padding << ',' << info.padding << ',' << info.padding
        << " spacing=1,1 outline=0\n";
    out << "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\n";
    out << "page id=0 file=\"sheet.png\"\n";
    out << "chars count=" << chars.size() << "\n";
    for (const FntChar& c : chars) {
        out << "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\n";
    }
    out << "kernings count=" << kernings.size() << "\n";
    for (const FntKerning& k : kernings) {
        out << "kerning first=" << k.first << " second=" << k.second << " amount=" << k.amount << "\n";
    }
    std::string doc = out.str();
    doc.pop_back();  // drop the trailing newline the per-line appends added
    return doc;
}

// ---- demo: the lib's canonical vectors (mirrors src/lib/bitmap-font.test.ts) ----

namespace {

std::string joinCps(const std::vector<uint32_t>& cps) {
    std::string out;
    for (const uint32_t cp : cps) out += " " + std::to_string(cp);
    return out;
}

void printList(const std::string& label, const std::vector<uint32_t>& cps) {
    std::printf("%s len=%zu%s\n", label.c_str(), cps.size(), joinCps(cps).c_str());
}

void printEnds(const std::string& label, const std::vector<uint32_t>& cps) {
    std::printf("%s first=%u last=%u len=%zu\n", label.c_str(), cps.front(), cps.back(), cps.size());
}

void printSpec(const std::string& spec) {
    try {
        printList(spec, parseCharset(spec));
    } catch (const FontError&) {
        std::printf("ERR %s : invalid\n", spec.c_str());
    }
}

std::vector<std::string> splitLines(const std::string& doc) {
    std::vector<std::string> lines;
    size_t start = 0;
    while (true) {
        const size_t nl = doc.find('\n', start);
        if (nl == std::string::npos) { lines.push_back(doc.substr(start)); break; }
        lines.push_back(doc.substr(start, nl - start));
        start = nl + 1;
    }
    return lines;
}

}  // namespace

int main() {
    printList("ascii", parseCharset("ascii"));
    {
        const std::vector<uint32_t> l1 = parseCharset("latin1");
        std::printf("latin1 len=%zu c0=%u c94=%u c95=%u c190=%u\n", l1.size(), l1[0], l1[94], l1[95], l1[190]);
    }
    printEnds("digits", parseCharset("digits"));
    std::printf("ascii-ws len=%zu\n", parseCharset("  ASCII ").size());
    std::printf("latin1-case c95=%u\n", parseCharset("Latin1")[95]);
    std::printf("digits-ws len=%zu\n", parseCharset("\tDigits\n").size());
    {
        const std::vector<uint32_t> r = parseCharset("65-90,97-122");
        std::printf("dec-ranges first=%u last=%u len=%zu\n", r.front(), r.back(), r.size());
    }
    printSpec("122,65,97");
    printSpec("65-70,68,65");
    printSpec("U+41");
    printSpec("u+41");
    printEnds("U+4E00-9FFF", parseCharset("U+4E00-9FFF"));
    printSpec("65,U+42,67-68");
    printSpec(" 65 - 67 , U+0041 ");
    printSpec("0");
    printSpec("U+10FFFF");

    for (const std::string spec : {"", "   ", "abc", "65-,90", "-5", "65,zz", "U+", "U+ZZ", "zz",
                                   "1114112", "U+110000", "65-2000000", "90-65", "U+9FFF-4E00", "0-0x10FFFF"}) {
        try {
            printList(spec, parseCharset(spec));
            std::printf("ERR %s : NO-ERROR\n", spec.c_str());
        } catch (const FontError&) {
            std::printf("ERR %s : invalid\n", spec.c_str());
        }
    }

    const FntInfo info{"TestFace", 32, 1};
    const FntCommon common{38, 29, 128, 128};
    const std::vector<FntChar> chars{
        {65, 0, 0, 34, 36, 0, 0, 36},
        {66, 36, 0, 32, 36, 1, 2, 35},
    };
    const std::vector<FntKerning> kernings{{65, 66, -1}};

    std::printf("fntText\n");
    std::printf("%s\n", fntText(info, common, chars, kernings).c_str());
    std::printf("pad %s\n", splitLines(fntText({"TestFace", 32, 4}, common, chars, kernings))[0].c_str());
    {
        const std::vector<std::string> lines = splitLines(fntText(info, common, chars, {}));
        std::printf("kern0 %s lines=%zu\n", lines[6].c_str(), lines.size());
    }
    {
        const std::vector<std::string> lines = splitLines(fntText(info, common, {}, {}));
        std::printf("zerochars lines=%zu\n", lines.size());
    }
    std::printf("bigcp %s\n",
                splitLines(fntText(info, common, {{19968, 0, 0, 32, 32, 0, 0, 32}}, {}))[4].c_str());
    return 0;
}

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 →