--!strict -- font/bmfont: AngelCode BMFont descriptors (.fnt) in all three encodings: text, XML and binary (version 3), read and -- written. Decodes to the standard Font (a bitmap font: glyphIndex / advance / kern work, outline is nil, rasterize -- crops the glyph from its page as alpha8). Pages are image files named by the descriptor (meta.pageFiles); they are -- loaded lazily through font:loadPages(loader) or the loader the api attaches (opts.loadPage(file) -> Image, or the -- files next to the .fnt on hosts with a file system). Bmfont.bake(font, opts) renders any outline Font (ttf / otf / -- woff) into a packed bitmap font with its pages. Written from the BMFont documentation. -- Not supported: packed multi-channel glyphs (chnl other than one channel or all: read as alpha). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") local Parse = require("@formats/font/bmfont/Parse") -- ------------------------------------------------------------------------------------------------ contract local Bmfont = { name = "bmfont", category = "font", extensions = { "fnt" }, mime = { "application/x-bmfont" }, deps = { "core/Err", "core/Bytes", "Types" }, caps = { decode = true, encode = true, bitmap = true, variants = { "text", "xml", "binary" }, extraFiles = true }, } export type DecodeOptions = { pages: { Types.Image }?, -- the page images, if the caller has them already (page id 0 first) loadPage: ((file: string, page: number) -> any)?, -- loader for lazy pages: file -> Image (the api passes one) } export type EncodeOptions = { variant: ("text" | "xml" | "binary")?, -- default: the variant it was read from, else "text" px: number?, -- fonts without a BMFont description are baked first (see bake) chars: (string | { number })?, file: string?, -- baking: the page file name prefix (default: opts.name without its extension, else "font") name: string?, -- the destination's file name (set by the api) files: { [string]: any }?, -- the page images are written here, encoded by opts.encodeImage (the api passes -- both): files[page file name] = PNG bytes, for the baked pages or a BMFont's loaded pages encodeImage: ((img: any, format: string) -> (buffer?, any))?, } export type BakeOptions = { px: number?, -- pixels per em (default 32) chars: (string | { number })?, -- code points to include (default printable ASCII 32..126) pageSize: number?, -- page width = height (default: the smallest power of two that fits, up to 4096) padding: number?, -- empty pixels around each glyph (default 1) file: string?, -- page file name prefix (default "font"): pages are _.png } -- ------------------------------------------------------------------------------------------------ sniff function Bmfont.sniff(r: Bytes.Reader): number local head = r:peek(64) if string.sub(head, 1, 4) == "BMF\3" then return 1 end if string.match(head, "^info%s+face=") or string.match(head, "^info%s+") and string.find(head, "size=", 1, true) then return 0.9 end if string.find(head, "", 1, true) or (string.find(head, "", 1, true)) then return if string.find(r:peek(512), " true | nil, Err: loader(file, pageIndex) -> Image (rgba8) | nil function Face.loadPages(self: any, loader: any?): (boolean?, Err.Err?) local load = loader or self.meta.pageLoader if type(load) ~= "function" then return nil, Err.new(Err.ARG, "no page loader (pass font:loadPages(function(file) return image end))") end local pages = {} for i, file in self.meta.pageFiles do local ok, img, err = pcall(load, file, i - 1) if not ok or type(img) ~= "table" or type(img.pixels) ~= "buffer" then return nil, if Err.is(err) then err else Err.new(Err.IO, "page " .. file .. ": " .. tostring(if ok then err else img)) end pages[i] = img end self.pages = pages return true, nil end local CHANNEL = { [1] = 2, [2] = 1, [4] = 0, [8] = 3 } -- chnl bit -> byte in rgba8 -- rasterize(g, px?) -> alpha8 Image cropped from the glyph's page (px is ignored: bitmap fonts have one size; -- meta.scale = px / size tells the caller how much to scale). nil when the pages are not loaded / available. function Face.rasterize(self: any, g: number, px: number?): Types.Image? local c = self._chars[g] if not c then return nil end if not self.pages and self.meta.pageLoader then self:loadPages() end local page = self.pages and self.pages[c.page + 1] local img = Types.Image.new(c.width, c.height, "alpha8") img.meta.left = c.xoffset img.meta.top = (self.meta.base or 0) - c.yoffset img.meta.advance = c.xadvance img.meta.glyph = g img.meta.scale = if type(px) == "number" and self.unitsPerEm > 0 then px / self.unitsPerEm else 1 if not page then return nil end local pw, ph = page.width, page.height local bpp = Types.Image.bpp(page.format) or 4 local ch = if page.format == "rgba8" then CHANNEL[c.chnl] or 3 else 0 if page.format == "graya8" then ch = 1 end for y = 0, c.height - 1 do local sy = c.y + y for x = 0, c.width - 1 do local sx = c.x + x if sx >= 0 and sy >= 0 and sx < pw and sy < ph then buffer.writeu8(img.pixels, y * c.width + x, buffer.readu8(page.pixels, (sy * pw + sx) * bpp + math.min(ch, bpp - 1))) end end end return img end -- the Font value of a description local function face(d: Parse.Desc, variant: string): any local f: any = setmetatable({ kind = "font", info = { family = d.info.face, style = if (d.info.bold or 0) ~= 0 and (d.info.italic or 0) ~= 0 then "Bold Italic" elseif (d.info.bold or 0) ~= 0 then "Bold" elseif (d.info.italic or 0) ~= 0 then "Italic" else "Regular", fullName = d.info.face, }, unitsPerEm = math.abs(d.info.size or 0), ascent = d.common.base or 0, descent = (d.common.base or 0) - (d.common.lineHeight or 0), lineGap = 0, numGlyphs = #d.chars + 1, pages = nil, meta = { bmfont = d, variant = variant, pageFiles = d.pages, lineHeight = d.common.lineHeight, base = d.common.base, source = { format = "bmfont", variant = variant }, }, _chars = {}, _index = {}, _kern = {}, }, Face) for i, c in d.chars do f._chars[i] = c if f._index[c.id] == nil then f._index[c.id] = i end end for _, k in d.kernings do f._kern[k[1] * 2097152 + k[2]] = k[3] end return f end function Bmfont.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local d, err, variant if r:peek(3) == "BMF" then d, err = Parse.binary(r:sub(0)) variant = "binary" else local s = r:peek(r:size()) if string.find(string.sub(s, 1, 512), " 255 or c.chnl < 0 or c.chnl > 255 then return false end end for _, k in d.kernings do if type(k) ~= "table" or type(k[1]) ~= "number" or type(k[2]) ~= "number" or type(k[3]) ~= "number" then return false end end for _, p in d.pages do if type(p) ~= "string" then return false end end return true end function Bmfont.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) if type(font) ~= "table" or font.kind ~= "font" then return nil, Err.new(Err.ARG, "expected a Font") end local d = type(font.meta) == "table" and font.meta.bmfont or nil local pages = font.pages if d == nil then -- page names: opts.file, else the destination's base name (the api passes opts.name), else "font" local file = opts and opts.file if file == nil and opts and type(opts.name) == "string" then file = string.match(opts.name, "([^/\\]-)%.[^./\\]*$") or string.match(opts.name, "([^/\\]+)$") if file == "" then file = nil end end local baked, err = Bmfont.bake(font, { px = opts and opts.px, chars = opts and opts.chars, file = file }) if not baked then return nil, err end d = baked.meta.bmfont pages = baked.pages end if not validDesc(d) then return nil, Err.new(Err.ARG, "bad BMFont description in font.meta.bmfont") end -- the page images into opts.files, under the names the descriptor gives them local files = opts and opts.files local encodeImage = opts and opts.encodeImage if type(files) == "table" and type(encodeImage) == "function" and type(pages) == "table" then for i, name in d.pages do local img = pages[i] if type(img) == "table" and type(name) == "string" and name ~= "" then local ext = string.lower(string.match(name, "%.([%w]+)$") or "png") local bytes, eerr = encodeImage(img, ext) if not bytes then return nil, Err.new(Err.ARG, "page " .. (i - 1) .. " (" .. name .. "): " .. tostring(eerr and eerr.message or eerr)) end files[name] = bytes end end end local variant = (opts and opts.variant) or (font.meta and font.meta.variant) or "text" if variant == "text" then return buffer.fromstring(Parse.writeText(d)), nil elseif variant == "xml" then return buffer.fromstring(Parse.writeXml(d)), nil elseif variant == "binary" then return Parse.writeBinary(d), nil end return nil, Err.new(Err.ARG, "variant must be text, xml or binary") end -- ------------------------------------------------------------------------------------------------ extras local function codepoints(chars: any): { number } local out = {} if type(chars) == "string" then for _, c in utf8.codes(chars) do table.insert(out, c) end elseif type(chars) == "table" then for _, c in chars do if type(c) == "number" then table.insert(out, c) end end else for c = 32, 126 do table.insert(out, c) end end return out end -- bake(font, opts?) -> a BMFont Font (pages: rgba8 Images, white with the coverage as alpha) | nil, Err. Glyphs are -- rasterized with font:rasterize and packed in rows (tallest first); kerning pairs between the baked characters are -- kept (rounded to pixels). function Bmfont.bake(font: any, opts: BakeOptions?): (any, Err.Err?) if type(font) ~= "table" or type(font.rasterize) ~= "function" or type(font.glyphIndex) ~= "function" then return nil, Err.new(Err.ARG, "bake: expected an outline Font") end local o: BakeOptions = opts or {} local px = if type(o.px) == "number" and o.px > 0 and o.px <= 1024 then o.px else 32 local pad = if type(o.padding) == "number" and o.padding >= 0 then math.floor(o.padding) else 1 local scale = px / font.unitsPerEm local glyphs: { { cp: number, g: number, img: Types.Image } } = {} local area = 0 local seen = {} for _, cp in codepoints(o.chars) do local g = (font :: any):glyphIndex(cp) if (g ~= 0 or cp == 0) and not seen[cp] then seen[cp] = true local img: Types.Image? = (font :: any):rasterize(g, px) if img then table.insert(glyphs, { cp = cp, g = g, img = img }) area += (img.width + pad) * (img.height + pad) end end end local size: number if type(o.pageSize) == "number" then size = o.pageSize else size = 64 while size * size < area * 1.3 and size < 4096 do size *= 2 end end local order = table.clone(glyphs) table.sort(order, function(a: any, b: any): boolean if a.img.height ~= b.img.height then return a.img.height > b.img.height end return a.cp < b.cp end) local ascent = math.ceil(font.ascent * scale) local lineHeight = math.ceil((font.ascent - font.descent + (font.lineGap or 0)) * scale) local prefix = o.file or "font" local d: Parse.Desc = { info = { face = font.info and font.info.family or "font", size = px, bold = 0, italic = 0, charset = "", unicode = 1, stretchH = 100, smooth = 1, aa = 1, padding = { 0, 0, 0, 0 }, spacing = { pad, pad }, outline = 0, }, common = { lineHeight = lineHeight, base = ascent, scaleW = size, scaleH = size, pages = 0, packed = 0, alphaChnl = 0, redChnl = 4, greenChnl = 4, blueChnl = 4 }, pages = {}, chars = {}, kernings = {}, } local pages: { Types.Image } = {} local page: Types.Image? = nil local x, y, rowH = pad, pad, 0 local placed: { [number]: Parse.Char } = {} for _, gl in order do local w, h = gl.img.width, gl.img.height if w + 2 * pad > size or h + 2 * pad > size then return nil, Err.new(Err.LIMIT, "bake: glyph larger than the page") end if x + w + pad > size then x, y, rowH = pad, y + rowH + pad, 0 end if not page or y + h + pad > size then page = Types.Image.new(size, size) table.insert(pages, page :: Types.Image) table.insert(d.pages, string.format("%s_%d.png", prefix, #pages - 1)) x, y, rowH = pad, pad, 0 end local pg = page :: Types.Image for yy = 0, h - 1 do for xx = 0, w - 1 do local a = buffer.readu8(gl.img.pixels, yy * w + xx) buffer.writeu32(pg.pixels, ((y + yy) * size + x + xx) * 4, 0x00FFFFFF + a * 16777216) end end local c: Parse.Char = { id = gl.cp, x = x, y = y, width = w, height = h, xoffset = gl.img.meta.left, yoffset = ascent - gl.img.meta.top, xadvance = math.floor(gl.img.meta.advance + 0.5), page = #pages - 1, chnl = 15, } placed[gl.cp] = c x += w + pad rowH = math.max(rowH, h) end for _, gl in glyphs do table.insert(d.chars, placed[gl.cp]) end d.common.pages = #pages if type(font.kern) == "function" then for _, a in glyphs do for _, b in glyphs do local k = font:kern(a.g, b.g) if k ~= 0 then local v = math.floor(k * scale + 0.5) if v ~= 0 then table.insert(d.kernings, { a.cp, b.cp, v }) end end end end end local f = face(d, "text") f.pages = pages return f, nil end return Bmfont