Skip to content

Bitmap Font Generator — Rust source

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

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

//! bitmap-font-generator — charset parser + BMFont TEXT emitter (std only).
//! Rust 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 Rust browser
//! story and the island owns it anyway — pure charset/font-geometry only.

use std::fmt;

/// The Rust twin of the TS FontError class ('invalid' is the only code).
#[derive(Debug, Clone)]
pub struct FontError(pub String);

impl fmt::Display for FontError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl std::error::Error for FontError {}

/// Max valid Unicode scalar value.
const MAX_CODEPOINT: u32 = 0x10ffff;

/// Inclusive [lo, hi] codepoint range expanded to a sorted list.
fn codepoint_range(lo: u32, hi: u32) -> Vec<u32> {
    (lo..=hi).collect()
}

/// Named charsets, as documented in the tool docs.
fn preset(name: &str) -> Option<Vec<u32>> {
    match name {
        "ascii" => Some(codepoint_range(32, 126)),
        "latin1" => {
            let mut cps = codepoint_range(32, 126);
            cps.extend(codepoint_range(160, 255));
            Some(cps)
        }
        "digits" => Some(codepoint_range(48, 57)),
        _ => None,
    }
}

/// 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).
pub fn parse_charset(spec: &str) -> Result<Vec<u32>, FontError> {
    let trimmed = spec.trim();
    if trimmed.is_empty() {
        return Err(FontError("Charset is empty — name a preset or list codepoint ranges.".into()));
    }
    if let Some(p) = preset(&trimmed.to_ascii_lowercase()) {
        return Ok(p);
    }

    let mut seen: Vec<u32> = Vec::new();
    for raw in trimmed.split(',') {
        let token: String = raw.chars().filter(|c| !c.is_whitespace()).collect();
        let (lo, hi) = parse_token(&token)?;
        for cp in lo..=hi {
            if !seen.contains(&cp) {
                seen.push(cp);
            }
        }
    }
    seen.sort_unstable();
    Ok(seen)
}

/// One comma item → inclusive bounds, or FontError when garbage. The TS lib
/// anchors two regexes here; this is the same grammar hand-rolled on std.
fn parse_token(token: &str) -> Result<(u32, u32), FontError> {
    let invalid = || {
        FontError(format!(
            "\"{}\" is not a codepoint or range — use 65-90 or U+4E00-9FFF.",
            token
        ))
    };
    let (hex, body) = if token.len() >= 2 && (&token[..2].eq_ignore_ascii_case("u+")) {
        (true, &token[2..])
    } else {
        (false, token)
    };
    let (lo_raw, hi_raw) = match body.split_once('-') {
        Some((a, b)) => (a, Some(b)),
        None => (body, None),
    };
    let radix = if hex { 16 } else { 10 };
    let lo = parse_u32(lo_raw, radix).ok_or_else(invalid)?;
    let hi = match hi_raw {
        Some(s) => parse_u32(s, radix).ok_or_else(invalid)?,
        None => lo,
    };
    if lo > MAX_CODEPOINT || hi > MAX_CODEPOINT {
        return Err(FontError(format!(
            "\"{}\" is outside Unicode (max U+10FFFF).",
            token
        )));
    }
    if lo > hi {
        return Err(FontError(format!(
            "\"{}\" runs backwards — put the smaller codepoint first.",
            token
        )));
    }
    Ok((lo, hi))
}

/// Digits only, in the given radix (from_str_radix would also accept a sign).
fn parse_u32(s: &str, radix: u32) -> Option<u32> {
    if s.is_empty() || !s.bytes().all(|b| b.is_ascii_alphanumeric()) {
        return None;
    }
    if s.starts_with('+') || s.starts_with('-') {
        return None;
    }
    u32::from_str_radix(s, radix).ok()
}

/// One char entry in the emitted .fnt (geometry already scaled to pixels).
#[derive(Debug, Clone, Copy)]
pub struct FntChar {
    pub codepoint: i32,
    pub x: i32,
    pub y: i32,
    pub w: i32,
    pub h: i32,
    pub xoffset: i32,
    pub yoffset: i32,
    pub xadvance: i32,
}

/// One kerning pair in the emitted .fnt (pixel amount, may be negative).
#[derive(Debug, Clone, Copy)]
pub struct FntKerning {
    pub first: i32,
    pub second: i32,
    pub amount: i32,
}

/// Mirrors the TS info block: padding is broadcast to all four sides.
#[derive(Debug, Clone)]
pub struct FntInfo {
    pub face: String,
    pub size: i32,
    pub padding: i32,
}

/// Mirrors the TS common block.
#[derive(Debug, Clone, Copy)]
pub struct FntCommon {
    pub line_height: i32,
    pub base: i32,
    pub scale_w: i32,
    pub scale_h: i32,
}

/// Emit a BMFont TEXT-format document; pages are always 1 ("sheet.png").
pub fn fnt_text(info: &FntInfo, common: &FntCommon, chars: &[FntChar], kernings: &[FntKerning]) -> String {
    let p = info.padding;
    let mut lines = vec![
        format!(
            "info face=\"{}\" size={} bold=0 italic=0 charset=\"\" unicode=1 stretchH=100 smooth=1 aa=1 padding={},{},{},{} spacing=1,1 outline=0",
            info.face, info.size, p, p, p, p
        ),
        format!(
            "common lineHeight={} base={} scaleW={} scaleH={} pages=1 packed=0 alphaChnl=0 redChnl=0 greenChnl=0 blueChnl=0",
            common.line_height, common.base, common.scale_w, common.scale_h
        ),
        "page id=0 file=\"sheet.png\"".to_string(),
        format!("chars count={}", chars.len()),
    ];
    for c in chars {
        lines.push(format!(
            "char id={} x={} y={} width={} height={} xoffset={} yoffset={} xadvance={} page=0 chnl=15",
            c.codepoint, c.x, c.y, c.w, c.h, c.xoffset, c.yoffset, c.xadvance
        ));
    }
    lines.push(format!("kernings count={}", kernings.len()));
    for k in kernings {
        lines.push(format!("kerning first={} second={} amount={}", k.first, k.second, k.amount));
    }
    lines.join("\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 →