Bitmap Font Generator — PHP source
Turn a TTF into a game-ready bitmap font sheet + BMFont .fnt — entirely in your browser. Nothing uploads.
This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
/**
* bitmap-font-generator — charset parser + BMFont TEXT emitter (stdlib only).
* PHP 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 PHP browser story and the island
* owns it anyway — pure charset/font-geometry only.
*/
declare(strict_types=1);
/** The PHP twin of the TS FontError class ('invalid' is the only code). */
final class FontError extends RuntimeException {}
/** Max valid Unicode scalar value. */
const MAX_CODEPOINT = 0x10FFFF;
/**
* Named charsets, as documented in the tool docs.
* @return array<string, list<int>>
*/
function fontPresets(): array
{
return [
'ascii' => range(32, 126),
'latin1' => array_merge(range(32, 126), range(160, 255)),
'digits' => range(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).
*
* @return list<int>
*/
function parseCharset(string $spec): array
{
$trimmed = trim($spec);
if ($trimmed === '') {
throw new FontError('Charset is empty — name a preset or list codepoint ranges.');
}
$preset = fontPresets()[strtolower($trimmed)] ?? null;
if ($preset !== null) {
return $preset;
}
$seen = [];
foreach (explode(',', $trimmed) as $raw) {
$token = preg_replace('/\s+/', '', trim($raw));
[$lo, $hi] = parseToken($token);
for ($cp = $lo; $cp <= $hi; $cp++) {
$seen[$cp] = true;
}
}
$out = array_keys($seen);
sort($out);
return $out;
}
/**
* One comma item → inclusive bounds, or FontError when garbage.
* @return array{0: int, 1: int}
*/
function parseToken(string $token): array
{
$invalid = fn () => new FontError("\"{$token}\" is not a codepoint or range — use 65-90 or U+4E00-9FFF.");
if (preg_match('/^u\+([0-9a-f]+)(?:-([0-9a-f]+))?$/i', $token, $m) === 1) {
$base = 16; // Hex form: U+HEX or U+HEX-HEX (end may drop the U+ prefix).
} elseif (preg_match('/^(\d+)(?:-(\d+))?$/', $token, $m) === 1) {
$base = 10; // Decimal form: N or N-N.
} else {
throw $invalid();
}
$lo = intval($m[1], $base);
$hi = isset($m[2]) ? intval($m[2], $base) : $lo;
if ($lo > MAX_CODEPOINT || $hi > MAX_CODEPOINT) {
throw new FontError("\"{$token}\" is outside Unicode (max U+10FFFF).");
}
if ($lo > $hi) {
throw new FontError("\"{$token}\" runs backwards — put the smaller codepoint first.");
}
return [$lo, $hi];
}
/** Mirrors the TS info block: padding is broadcast to all four sides. */
final class FntInfo
{
public function __construct(
public readonly string $face,
public readonly int $size,
public readonly int $padding,
) {}
}
/** Mirrors the TS common block. */
final class FntCommon
{
public function __construct(
public readonly int $lineHeight,
public readonly int $base,
public readonly int $scaleW,
public readonly int $scaleH,
) {}
}
/** One char entry in the emitted .fnt (geometry already scaled to pixels). */
final class FntChar
{
public function __construct(
public readonly int $codepoint,
public readonly int $x,
public readonly int $y,
public readonly int $w,
public readonly int $h,
public readonly int $xoffset,
public readonly int $yoffset,
public readonly int $xadvance,
) {}
}
/** One kerning pair in the emitted .fnt (pixel amount, may be negative). */
final class FntKerning
{
public function __construct(
public readonly int $first,
public readonly int $second,
public readonly int $amount,
) {}
}
/**
* Emit a BMFont TEXT-format document; pages are always 1 ("sheet.png").
*
* @param list<FntChar> $chars
* @param list<FntKerning> $kernings
*/
function fntText(FntInfo $info, FntCommon $common, array $chars, array $kernings): string
{
$p = $info->padding;
$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=' . count($chars),
];
foreach ($chars as $c) {
$lines[] = "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[] = 'kernings count=' . count($kernings);
foreach ($kernings as $k) {
$lines[] = "kerning first={$k->first} second={$k->second} amount={$k->amount}";
}
return implode("\n", $lines);
}
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 →