Files
rosetta/src/Formats/font/bmfont/Parse.luau
T

458 lines
13 KiB
Luau

--!strict
-- font/bmfont/Parse: the three AngelCode BMFont descriptor encodings (text, XML, binary version 3) to and from one
-- description table { info, common, pages, chars, kernings }. Written from the BMFont documentation
-- (angelcode.com/products/bmfont/doc/file_format.html). The XML reader only scans elements and attributes (the
-- descriptor has no nesting that matters, no text content).
--
-- Never throws on bad input: parse functions return nil, message.
local Bytes = require("@formats/core/Bytes")
local Parse = {}
export type Char = {
id: number,
x: number,
y: number,
width: number,
height: number,
xoffset: number,
yoffset: number,
xadvance: number,
page: number,
chnl: number,
}
export type Desc = {
info: { [string]: any }, -- face, size, bold, italic, charset, unicode, stretchH, smooth, aa, padding {4}, spacing {2}, outline
common: { [string]: any }, -- lineHeight, base, scaleW, scaleH, pages, packed, alphaChnl, redChnl, greenChnl, blueChnl
pages: { string }, -- file names, by page id (1-based: page id 0 is pages[1])
chars: { Char },
kernings: { { number } }, -- { first, second, amount }
}
local LIMIT = 1000000 -- chars / kernings
local INFO_NUM = { "size", "bold", "italic", "unicode", "stretchH", "smooth", "aa", "outline" }
local COMMON_NUM = { "lineHeight", "base", "scaleW", "scaleH", "pages", "packed", "alphaChnl", "redChnl", "greenChnl", "blueChnl" }
local CHAR_NUM = { "id", "x", "y", "width", "height", "xoffset", "yoffset", "xadvance", "page", "chnl" }
local function list(s: string?, n: number): { number }
local out = table.create(n, 0)
if s then
local i = 1
for v in string.gmatch(s, "-?%d+") do
if i > n then
break
end
out[i] = tonumber(v) or 0
i += 1
end
end
return out
end
local function new(): Desc
return { info = {}, common = {}, pages = {}, chars = {}, kernings = {} }
end
-- one tag's attributes (already split into key -> string) into the description
local function apply(d: Desc, tag: string, a: { [string]: string }): string?
if tag == "info" then
d.info.face = a.face or ""
d.info.charset = a.charset or ""
for _, k in INFO_NUM do
d.info[k] = tonumber(a[k]) or 0
end
d.info.padding = list(a.padding, 4)
d.info.spacing = list(a.spacing, 2)
elseif tag == "common" then
for _, k in COMMON_NUM do
d.common[k] = tonumber(a[k]) or 0
end
elseif tag == "page" then
local id = tonumber(a.id)
if not id or id < 0 or id > 4096 or id % 1 ~= 0 then
return "bad page id"
end
d.pages[id + 1] = a.file or ""
elseif tag == "char" then
if #d.chars >= LIMIT then
return "too many chars"
end
local c: any = {}
for _, k in CHAR_NUM do
c[k] = tonumber(a[k]) or 0
end
table.insert(d.chars, c)
elseif tag == "kerning" then
if #d.kernings >= LIMIT then
return "too many kerning pairs"
end
table.insert(d.kernings, { tonumber(a.first) or 0, tonumber(a.second) or 0, tonumber(a.amount) or 0 })
end
return nil
end
local function fill(d: Desc)
for i = 1, #d.pages do
d.pages[i] = d.pages[i] or ""
end
end
-- ------------------------------------------------------------------------------------------------ text
function Parse.text(s: string): (Desc?, string?)
local d = new()
for line in string.gmatch(s, "[^\r\n]+") do
local tag, rest = string.match(line, "^%s*(%a+)(.*)$")
if tag then
local a: { [string]: string } = {}
-- key=value, key="quoted value"
local i = 1
while i <= #(rest :: string) do
local k, q, e = string.match(rest :: string, '^%s*([%w_]+)="([^"]*)"()', i)
if k then
a[k] = q
i = e
else
local k2, v2, e2 = string.match(rest :: string, "^%s*([%w_]+)=(%S*)()", i)
if not k2 then
break
end
a[k2] = v2
i = e2
end
end
local err = apply(d, tag, a)
if err then
return nil, err
end
end
end
if not d.common.lineHeight then
return nil, "no common line"
end
fill(d)
return d, nil
end
-- ------------------------------------------------------------------------------------------------ XML
local ENTITIES: { [string]: string } = { quot = '"', amp = "&", lt = "<", gt = ">", apos = "'" }
local function unescape(s: string): string
return (
string.gsub(s, "&(#?x?%w+);", function(e: string): string?
if ENTITIES[e] then
return ENTITIES[e]
end
local n = if string.sub(e, 1, 2) == "#x" then tonumber(string.sub(e, 3), 16) elseif string.sub(e, 1, 1) == "#" then tonumber(string.sub(e, 2)) else nil
if n and n >= 0 and n <= 0x10FFFF then
return utf8.char(n)
end
return nil
end)
)
end
function Parse.xml(s: string): (Desc?, string?)
local d = new()
local seenFont = false
for tag, attrs in string.gmatch(s, "<(%a+)([^>]*)>") do
if tag == "font" then
seenFont = true
end
local a: { [string]: string } = {}
for k, q, v in string.gmatch(attrs :: string, "([%w_]+)%s*=%s*([\"'])(.-)%2") do
a[k] = unescape(v :: string)
local _ = q
end
local err = apply(d, tag, a)
if err then
return nil, err
end
end
if not seenFont or not d.common.lineHeight then
return nil, "not a BMFont XML descriptor"
end
fill(d)
return d, nil
end
-- ------------------------------------------------------------------------------------------------ binary
function Parse.binary(r: Bytes.Reader): (Desc?, string?)
if not r:match("BMF") then
return nil, "bad signature"
end
local version = r:u8()
if version ~= 3 then
return nil, "unsupported binary version " .. version
end
local d = new()
while not r:eof() do
local kind = r:u8()
local size = r:u32le()
if r.err then
return nil, "truncated block header"
end
local b = r:slice(size)
if r.err then
return nil, "block past the end"
end
if kind == 1 then
d.info.size = b:i16le()
local bits = b:u8()
d.info.smooth = bit32.band(bits, 0x80) ~= 0 and 1 or 0
d.info.unicode = bit32.band(bits, 0x40) ~= 0 and 1 or 0
d.info.italic = bit32.band(bits, 0x20) ~= 0 and 1 or 0
d.info.bold = bit32.band(bits, 0x10) ~= 0 and 1 or 0
d.info.fixedHeight = bit32.band(bits, 0x08) ~= 0 and 1 or 0
d.info.charsetId = b:u8()
d.info.charset = ""
d.info.stretchH = b:u16le()
d.info.aa = b:u8()
d.info.padding = { b:u8(), b:u8(), b:u8(), b:u8() }
d.info.spacing = { b:u8(), b:u8() }
d.info.outline = b:u8()
d.info.face = b:cstring()
elseif kind == 2 then
d.common.lineHeight = b:u16le()
d.common.base = b:u16le()
d.common.scaleW = b:u16le()
d.common.scaleH = b:u16le()
d.common.pages = b:u16le()
d.common.packed = if bit32.band(b:u8(), 1) ~= 0 then 1 else 0
d.common.alphaChnl = b:u8()
d.common.redChnl = b:u8()
d.common.greenChnl = b:u8()
d.common.blueChnl = b:u8()
elseif kind == 3 then
while not b:eof() and #d.pages < 4096 do
table.insert(d.pages, b:cstring())
end
elseif kind == 4 then
local n = size // 20
if n > LIMIT then
return nil, "too many chars"
end
for _ = 1, n do
table.insert(d.chars, {
id = b:u32le(),
x = b:u16le(),
y = b:u16le(),
width = b:u16le(),
height = b:u16le(),
xoffset = b:i16le(),
yoffset = b:i16le(),
xadvance = b:i16le(),
page = b:u8(),
chnl = b:u8(),
})
end
elseif kind == 5 then
local n = size // 10
if n > LIMIT then
return nil, "too many kerning pairs"
end
for _ = 1, n do
table.insert(d.kernings, { b:u32le(), b:u32le(), b:i16le() })
end
end
if b.err then
return nil, "truncated block " .. kind
end
end
if not d.common.lineHeight then
return nil, "no common block"
end
return d, nil
end
-- ------------------------------------------------------------------------------------------------ writers
local function num(v: any): string
return string.format("%d", math.floor(tonumber(v) or 0))
end
local function textLines(d: Desc, quote: (string) -> string): { { any } }
local i, c = d.info, d.common
local pad, sp = i.padding or { 0, 0, 0, 0 }, i.spacing or { 0, 0 }
local lines: { { any } } = {
{
"info",
{
{ "face", quote(i.face or "") },
{ "size", num(i.size) },
{ "bold", num(i.bold) },
{ "italic", num(i.italic) },
{ "charset", quote(i.charset or "") },
{ "unicode", num(i.unicode) },
{ "stretchH", num(i.stretchH or 100) },
{ "smooth", num(i.smooth) },
{ "aa", num(i.aa) },
{ "padding", table.concat({ num(pad[1]), num(pad[2]), num(pad[3]), num(pad[4]) }, ",") },
{ "spacing", num(sp[1]) .. "," .. num(sp[2]) },
{ "outline", num(i.outline) },
},
},
}
local cf = {}
for _, k in COMMON_NUM do
table.insert(cf, { k, num(c[k]) })
end
table.insert(lines, { "common", cf })
return lines
end
function Parse.writeText(d: Desc): string
local out = {}
local function q(s: string): string
return '"' .. string.gsub(s, '"', "") .. '"'
end
for _, l in textLines(d, q) do
local parts = { l[1] }
for _, kv in l[2] do
table.insert(parts, kv[1] .. "=" .. kv[2])
end
table.insert(out, table.concat(parts, " "))
end
for id, file in d.pages do
table.insert(out, string.format('page id=%d file="%s"', id - 1, (string.gsub(file, '"', ""))))
end
table.insert(out, "chars count=" .. #d.chars)
for _, c in d.chars do
local parts = { "char" }
for _, k in CHAR_NUM do
table.insert(parts, k .. "=" .. num((c :: any)[k]))
end
table.insert(out, table.concat(parts, " "))
end
if #d.kernings > 0 then
table.insert(out, "kernings count=" .. #d.kernings)
for _, k in d.kernings do
table.insert(out, string.format("kerning first=%s second=%s amount=%s", num(k[1]), num(k[2]), num(k[3])))
end
end
return table.concat(out, "\n") .. "\n"
end
local function esc(s: string): string
return (string.gsub(s, '[&<>"]', { ["&"] = "&amp;", ["<"] = "&lt;", [">"] = "&gt;", ['"'] = "&quot;" }))
end
function Parse.writeXml(d: Desc): string
local out = { '<?xml version="1.0"?>', "<font>" }
for _, l in textLines(d, function(s: string): string
return s
end) do
local parts = { " <" .. l[1] }
for _, kv in l[2] do
table.insert(parts, kv[1] .. '="' .. esc(kv[2]) .. '"')
end
table.insert(out, table.concat(parts, " ") .. "/>")
end
table.insert(out, " <pages>")
for id, file in d.pages do
table.insert(out, string.format(' <page id="%d" file="%s"/>', id - 1, esc(file)))
end
table.insert(out, " </pages>")
table.insert(out, string.format(' <chars count="%d">', #d.chars))
for _, c in d.chars do
local parts = { " <char" }
for _, k in CHAR_NUM do
table.insert(parts, k .. '="' .. num((c :: any)[k]) .. '"')
end
table.insert(out, table.concat(parts, " ") .. "/>")
end
table.insert(out, " </chars>")
if #d.kernings > 0 then
table.insert(out, string.format(' <kernings count="%d">', #d.kernings))
for _, k in d.kernings do
table.insert(out, string.format(' <kerning first="%s" second="%s" amount="%s"/>', num(k[1]), num(k[2]), num(k[3])))
end
table.insert(out, " </kernings>")
end
table.insert(out, "</font>")
return table.concat(out, "\n") .. "\n"
end
function Parse.writeBinary(d: Desc): buffer
local w = Bytes.writer(64 + #d.chars * 20 + #d.kernings * 10)
w:string("BMF")
w:u8(3)
local i, c = d.info, d.common
local face = i.face or ""
w:u8(1)
w:u32le(14 + #face + 1)
w:u16le((tonumber(i.size) or 0) % 65536)
local bits = 0
if (tonumber(i.smooth) or 0) ~= 0 then
bits += 0x80
end
if (tonumber(i.unicode) or 0) ~= 0 then
bits += 0x40
end
if (tonumber(i.italic) or 0) ~= 0 then
bits += 0x20
end
if (tonumber(i.bold) or 0) ~= 0 then
bits += 0x10
end
if (tonumber(i.fixedHeight) or 0) ~= 0 then
bits += 0x08
end
w:u8(bits)
w:u8(tonumber(i.charsetId) or 0)
w:u16le(tonumber(i.stretchH) or 100)
w:u8(tonumber(i.aa) or 1)
local pad, sp = i.padding or { 0, 0, 0, 0 }, i.spacing or { 0, 0 }
for k = 1, 4 do
w:u8(pad[k] or 0)
end
w:u8(sp[1] or 0)
w:u8(sp[2] or 0)
w:u8(tonumber(i.outline) or 0)
w:cstring(face)
w:u8(2)
w:u32le(15)
for _, k in { "lineHeight", "base", "scaleW", "scaleH", "pages" } do
w:u16le((tonumber(c[k]) or 0) % 65536)
end
w:u8(if (tonumber(c.packed) or 0) ~= 0 then 1 else 0)
for _, k in { "alphaChnl", "redChnl", "greenChnl", "blueChnl" } do
w:u8(tonumber(c[k]) or 0)
end
if #d.pages > 0 then
local len = 0
for _, p in d.pages do
len += #p + 1
end
w:u8(3)
w:u32le(len)
for _, p in d.pages do
w:cstring(p)
end
end
w:u8(4)
w:u32le(#d.chars * 20)
for _, ch in d.chars do
w:u32le(ch.id)
w:u16le(ch.x)
w:u16le(ch.y)
w:u16le(ch.width)
w:u16le(ch.height)
w:u16le(ch.xoffset % 65536)
w:u16le(ch.yoffset % 65536)
w:u16le(ch.xadvance % 65536)
w:u8(ch.page)
w:u8(ch.chnl)
end
if #d.kernings > 0 then
w:u8(5)
w:u32le(#d.kernings * 10)
for _, k in d.kernings do
w:u32le(k[1])
w:u32le(k[2])
w:u16le(k[3] % 65536)
end
end
return w:finish()
end
return Parse