Skip to content

Bitmap Font Generator — Swift source

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

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

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

import Foundation

// Max valid Unicode scalar value.
let MAX_CODEPOINT = 0x10ffff

// The Swift twin of the TS FontError class ('invalid' is the only code).
struct FontError: Error {
  let code = "invalid"
  let message: String
}

// Hex form: U+HEX or U+HEX-HEX (end may drop the U+ prefix). ICU \d and the
// hex classes are written ASCII-explicit so the grammar matches the TS
// regexes exactly.
let RE_HEX = try! NSRegularExpression(pattern: "^u\\+([0-9a-f]+)(?:-([0-9a-f]+))?$", options: [.caseInsensitive])
// Decimal form: N or N-N.
let RE_DEC = try! NSRegularExpression(pattern: "^([0-9]+)(?:-([0-9]+))?$")

// Inclusive [lo, hi] codepoint range expanded to a sorted list.
func codepointRange(_ lo: Int, _ hi: Int) -> [Int] { Array(lo...hi) }

// Named charsets, as documented in the tool docs.
let PRESETS: [String: [Int]] = [
  "ascii": codepointRange(32, 126),
  "latin1": codepointRange(32, 126) + codepointRange(160, 255),
  "digits": codepointRange(48, 57),
]

// 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).
func parseCharset(_ spec: String) throws -> [Int] {
  let trimmed = spec.trimmingCharacters(in: .whitespacesAndNewlines)
  if trimmed.isEmpty {
    throw FontError(message: "Charset is empty — name a preset or list codepoint ranges.")
  }
  if let preset = PRESETS[trimmed.lowercased()] { return preset }

  var seen = Set<Int>()
  for raw in trimmed.split(separator: ",", omittingEmptySubsequences: false) {
    // Inner whitespace is stripped from every comma item before parsing.
    let token = String(raw.filter { !$0.isWhitespace })
    let (lo, hi) = try parseToken(token)
    for cp in lo...hi { seen.insert(cp) }
  }
  return seen.sorted()
}

// One comma item → inclusive bounds, or FontError when garbage. The TS lib
// anchors two regexes here; the same two regexes run in this port. Int.init
// (radix:) returns nil on overflow — the TS parseInt's Infinity, i.e. the
// "outside Unicode" branch.
func parseToken(_ token: String) throws -> (lo: Int, hi: Int) {
  let full = NSRange(token.startIndex..., in: token)
  let hex = RE_HEX.firstMatch(in: token, range: full)
  let dec = RE_DEC.firstMatch(in: token, range: full)
  guard let m = hex ?? dec else {
    throw FontError(message: "\"\(token)\" is not a codepoint or range — use 65-90 or U+4E00-9FFF.")
  }
  let radix = hex != nil ? 16 : 10
  func group(_ i: Int) -> String? {
    guard let r = Range(m.range(at: i), in: token) else { return nil }
    return String(token[r])
  }
  let lo = group(1).flatMap { Int($0, radix: radix) }
  let hi: Int?
  if let hiRaw = group(2) {
    hi = Int(hiRaw, radix: radix)
  } else {
    hi = lo
  }
  guard let loV = lo, let hiV = hi else {
    throw FontError(message: "\"\(token)\" is outside Unicode (max U+10FFFF).")
  }
  if loV > MAX_CODEPOINT || hiV > MAX_CODEPOINT {
    throw FontError(message: "\"\(token)\" is outside Unicode (max U+10FFFF).")
  }
  if loV > hiV {
    throw FontError(message: "\"\(token)\" runs backwards — put the smaller codepoint first.")
  }
  return (loV, hiV)
}

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

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

// Mirrors the TS info block: padding is broadcast to all four sides.
struct FntInfo {
  let face: String
  let size: Int, padding: Int
}

// Mirrors the TS common block.
struct FntCommon {
  let lineHeight: Int, base: Int, scaleW: Int, scaleH: Int
}

// Emit a BMFont TEXT-format document; pages are always 1 ("sheet.png").
func fntText(_ info: FntInfo, _ common: FntCommon, _ chars: [FntChar], _ kernings: [FntKerning]) -> String {
  let p = info.padding
  var lines = [
    "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)",
  ]
  for c in chars {
    lines.append(
      "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.append("kernings count=\(kernings.count)")
  for k in kernings {
    lines.append("kerning first=\(k.first) second=\(k.second) amount=\(k.amount)")
  }
  return lines.joined(separator: "\n")
}

// Example:
//   let info = FntInfo(face: "TestFace", size: 32, padding: 1)
//   let common = FntCommon(lineHeight: 38, base: 29, scaleW: 128, scaleH: 128)
//   print(fntText(info, common, [], []))
//   // 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

func joinCps(_ label: String, _ cps: [Int]) -> String {
  label + " len=\(cps.count)" + cps.reduce(into: "") { $0 += " \($1)" }
}

func printSpec(_ spec: String) {
  print(joinCps(spec, try! parseCharset(spec)))
}

// Demo: the lib's canonical vectors (mirrors src/lib/bitmap-font.test.ts).
print(joinCps("ascii", try! parseCharset("ascii")))
do {
  let l1 = try parseCharset("latin1")
  print("latin1 len=\(l1.count) c0=\(l1[0]) c94=\(l1[94]) c95=\(l1[95]) c190=\(l1[190])")
  let d = try parseCharset("digits")
  print("digits first=\(d.first!) last=\(d.last!) len=\(d.count)")
  print("ascii-ws len=\(try parseCharset("  ASCII ").count)")
  print("latin1-case c95=\(try parseCharset("Latin1")[95])")
  print("digits-ws len=\(try parseCharset("\tDigits\n").count)")
  let dr = try parseCharset("65-90,97-122")
  print("dec-ranges first=\(dr.first!) last=\(dr.last!) len=\(dr.count)")
  printSpec("122,65,97")
  printSpec("65-70,68,65")
  printSpec("U+41")
  printSpec("u+41")
  let hr = try parseCharset("U+4E00-9FFF")
  print("U+4E00-9FFF first=\(hr.first!) last=\(hr.last!) len=\(hr.count)")
  printSpec("65,U+42,67-68")
  printSpec(" 65 - 67 , U+0041 ")
  printSpec("0")
  printSpec("U+10FFFF")
}

for spec in ["", "   ", "abc", "65-,90", "-5", "65,zz", "U+", "U+ZZ", "zz",
             "1114112", "U+110000", "65-2000000", "90-65", "U+9FFF-4E00", "0-0x10FFFF"] {
  do {
    print(joinCps(spec, try parseCharset(spec)))
    print("ERR \(spec) : NO-ERROR")
  } catch let e as FontError {
    print("ERR \(spec) : \(e.code)")
  } catch {
    print("ERR \(spec) : WRONG-ERROR-TYPE")
  }
}

let info = FntInfo(face: "TestFace", size: 32, padding: 1)
let common = FntCommon(lineHeight: 38, base: 29, scaleW: 128, scaleH: 128)
let chars = [
  FntChar(codepoint: 65, x: 0, y: 0, w: 34, h: 36, xoffset: 0, yoffset: 0, xadvance: 36),
  FntChar(codepoint: 66, x: 36, y: 0, w: 32, h: 36, xoffset: 1, yoffset: 2, xadvance: 35),
]
let kernings = [FntKerning(first: 65, second: 66, amount: -1)]

print("fntText")
print(fntText(info, common, chars, kernings))
print("pad " + fntText(FntInfo(face: "TestFace", size: 32, padding: 4), common, chars, kernings)
  .split(separator: "\n")[0])
do {
  let noKern = fntText(info, common, chars, []).split(separator: "\n")
  print("kern0 \(noKern[6]) lines=\(noKern.count)")
  print("zerochars lines=\(fntText(info, common, [], []).split(separator: "\n").count)")
  let big = fntText(info, common,
    [FntChar(codepoint: 19968, x: 0, y: 0, w: 32, h: 32, xoffset: 0, yoffset: 0, xadvance: 32)], [])
    .split(separator: "\n")
  print("bigcp \(big[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 →