diff --git a/src/Formats/font/ttf/init.luau b/src/Formats/font/ttf/init.luau new file mode 100644 index 0000000..2e81f06 --- /dev/null +++ b/src/Formats/font/ttf/init.luau @@ -0,0 +1,52 @@ +--!strict +-- font/ttf: TrueType and OpenType fonts (.ttf, .otf with CFF outlines) and collections (.ttc / .otc), read into the +-- standard Font (Types.Font) by codecs/TrueType: metrics, names, cmap, outlines (glyf or CFF), kerning ('kern' table, +-- GPOS pair kerning) and rasterize(glyph, px) through codecs/Raster. Ported from stb_truetype 1.26 (public domain / +-- MIT) via imgui-luau's imstb_truetype.lua; see codecs/TrueType. opts.index picks the font of a collection. +-- Not supported: hinting, variable fonts, bitmap / colour glyphs, GSUB, writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local TrueType = require("@formats/codecs/TrueType") + +-- ------------------------------------------------------------------------------------------------ contract +local Ttf = { + name = "ttf", + category = "font", + extensions = { "ttf", "otf", "ttc", "otc" }, + mime = { "font/ttf", "font/otf", "font/collection" }, + deps = { "core/Err", "core/Bytes", "codecs/TrueType" }, + caps = { decode = true, encode = false, outlines = { "truetype", "cff" }, collection = true, kerning = true }, +} + +export type DecodeOptions = { + index: number?, -- the font of a collection (default 0) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ttf.sniff(r: Bytes.Reader): number + local m = r:peek(4) + if m == "\0\1\0\0" or m == "OTTO" or m == "ttcf" or m == "true" then + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ttf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local font, err = TrueType.font(r.buf, r.base, r.limit - r.base, opts) + if not font then + return nil, err + end + font.meta.source = { format = "ttf", outlines = font.meta.outlines, sfnt = font.meta.sfnt } + return font, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- count(r) -> the number of fonts in the file (1 unless a collection) +function Ttf.count(r: Bytes.Reader): number + return TrueType.count(r.buf, r.base) +end + +return Ttf diff --git a/tests/font/ttf.luau b/tests/font/ttf.luau new file mode 100644 index 0000000..5d78823 --- /dev/null +++ b/tests/font/ttf.luau @@ -0,0 +1,237 @@ +-- font/ttf tests (and codecs/TrueType, codecs/Cff): for the imgui-luau TrueType fonts, Source Sans 3 (CFF), a +-- 'kern'-table font and a collection: metrics, names, cmap samples, advances / side bearings, outline control boxes and +-- areas against fontTools; kerning against HarfBuzz (GPOS) and FreeType ('kern'); rasterize() against FreeType's +-- unhinted renders (PSNR); the api; errors; the fuzz pass. Fixtures: tools/fixtures/fonts.py. +local T = require("@tests/T") +local F = require("@formats") +local Ttf = require("@formats/font/ttf") +local Raster = require("@formats/codecs/Raster") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/fonts") + +local t = T.suite("ttf") + +t:eq(Ttf.name, "ttf", "name") +t:check(table.find(Ttf.extensions, "otf") and table.find(Ttf.extensions, "ttc"), "extensions") + +-- shoelace area of the flattened outline (font units) +local function area(cmds: any): number + local polys = Raster.flatten(cmds, nil, 0.02) + local a = 0 + for _, p in polys do + local n = #p + local x0, y0 = p[n - 1], p[n] + for i = 1, n - 1, 2 do + a += x0 * p[i + 1] - p[i] * y0 + x0, y0 = p[i], p[i + 1] + end + end + return a / 2 +end + +local function psnr(img: any, r: any): (number, number) + -- union of both bitmaps, aligned on the pen position + local ax0, ay0 = img.meta.left, -img.meta.top + local bx0, by0 = r.left, -r.top + local x0, y0 = math.min(ax0, bx0), math.min(ay0, by0) + local x1, y1 = math.max(ax0 + img.width, bx0 + r.w), math.max(ay0 + img.height, by0 + r.h) + local se, n, ink = 0, 0, 0 + for y = y0, y1 - 1 do + for x = x0, x1 - 1 do + local a, b = 0, 0 + local ix, iy = x - ax0, y - ay0 + if ix >= 0 and iy >= 0 and ix < img.width and iy < img.height then + a = buffer.readu8(img.pixels, iy * img.width + ix) + end + local jx, jy = x - bx0, y - by0 + if jx >= 0 and jy >= 0 and jx < r.w and jy < r.h then + b = string.byte(r.pixels, jy * r.w + jx + 1) + end + se += (a - b) * (a - b) + ink += b + n += 1 + end + end + if n == 0 or se == 0 then + return 99, ink + end + return 10 * math.log10(255 * 255 / (se / n)), ink +end + +local fonts: { [string]: any } = {} +local worstPsnr, sumPsnr, nPsnr = 99, 0, 0 +for _, c in Fx.fonts do + local font, err = Ttf.decode(Bytes.reader(buffer.fromstring(c.data)), { index = c.index }) + t:check(font, c.name .. ": decode: " .. tostring(err)) + fonts[c.name] = font + t:eq(font.kind, "font", c.name .. ": kind") + t:eq(font.unitsPerEm, c.upem, c.name .. ": unitsPerEm") + t:eq(font.ascent, c.ascent, c.name .. ": ascent") + t:eq(font.descent, c.descent, c.name .. ": descent") + t:eq(font.lineGap, c.lineGap, c.name .. ": lineGap") + t:eq(font.numGlyphs, c.numGlyphs, c.name .. ": numGlyphs") + t:eq(font.info.family, c.family, c.name .. ": family") + t:eq(font.info.style, c.style, c.name .. ": style") + t:eq(font.info.fullName, c.fullName, c.name .. ": fullName") + t:eq(font.meta.outlines, if c.cff then "cff" else "truetype", c.name .. ": outlines") + if c.weight > 0 then + t:eq(font.meta.os2.weightClass, c.weight, c.name .. ": weight") + end + for _, m in c.cmap do + t:eq(font:glyphIndex(m[1]), m[2], string.format("%s: cmap U+%04X", c.name, m[1])) + end + local maxAreaErr = 0 + for _, g in c.glyphs do + local gid = g.gid + t:eq(font:advance(gid), g.adv, c.name .. ": advance " .. gid) + if not c.cff then + t:eq(font:leftSideBearing(gid), g.lsb, c.name .. ": lsb " .. gid) + end + local cmds = font:outline(gid) + t:check(cmds, c.name .. ": outline " .. gid .. ": " .. tostring(font.meta.lastError)) + local x0, y0, x1, y1 = font:bounds(gid) + if g.box then + t:check(x0 ~= nil, c.name .. ": glyph " .. gid .. " has bounds") + local b = g.box + local ok = math.abs(x0 - b[1]) < 1e-6 and math.abs(y0 - b[2]) < 1e-6 and math.abs(x1 - b[3]) < 1e-6 and math.abs(y1 - b[4]) < 1e-6 + t:check(ok, string.format("%s: glyph %d control box %g %g %g %g, want %g %g %g %g", c.name, gid, x0 or 0, y0, x1, y1, b[1], b[2], b[3], b[4])) + local a = area(cmds) + -- fontTools' AreaPen: positive for counter-clockwise contours, as the shoelace here + local d = math.abs(a - g.area) / math.max(1, math.abs(g.area)) + maxAreaErr = math.max(maxAreaErr, d) + t:check(d < 0.002 or math.abs(a - g.area) < 2, string.format("%s: glyph %d area %.1f, want %.1f", c.name, gid, a, g.area)) + else + t:check(x0 == nil, c.name .. ": empty glyph " .. gid) + end + end + for _, k in c.kern do + t:eq(font:kern(k[1], k[2]), k[3], string.format("%s: kern %d %d", c.name, k[1], k[2])) + end + local worst = 99 + for _, r in c.renders do + local img = font:rasterize(r.gid, r.px) + t:check(img and img.format == "alpha8", c.name .. ": rasterize " .. r.gid) + local p, ink = psnr(img, r) + worst = math.min(worst, p) + sumPsnr += p + nPsnr += 1 + t:check(p > 28 or ink == 0, string.format("%s: glyph %d at %d px: PSNR %.1f dB vs FreeType", c.name, r.gid, r.px, p)) + t:check(math.abs(img.meta.advance - font:advance(r.gid) * r.px / font.unitsPerEm) < 1e-9, "advance in pixels") + end + worstPsnr = math.min(worstPsnr, worst) + t:note("%-20s %4d glyphs, %3d cmap, %3d kern pairs, area err %.5f, worst PSNR %.1f dB", c.name, #c.glyphs, #c.cmap, #c.kern, maxAreaErr, worst) +end +t:note("rasterize vs FreeType: mean PSNR %.1f dB, worst %.1f dB over %d renders", sumPsnr / nPsnr, worstPsnr, nPsnr) + +-- kerning is non-trivial in at least the GPOS and 'kern' fonts +do + local nz = 0 + for _, c in Fx.fonts do + for _, k in c.kern do + if k[3] ~= 0 then + nz += 1 + end + end + end + t:check(nz > 20, "fixtures have non-zero kerning pairs: " .. nz) +end + +-- collections +if Fx.ttc then + local b = buffer.fromstring(Fx.ttc.data) + t:eq(Ttf.count(Bytes.reader(b)), Fx.ttc.count, "collection count") + local f0 = Ttf.decode(Bytes.reader(b)) + t:check(f0 and f0.meta.collection and f0.meta.collection.count == 2, "collection font 0") + local _, e = Ttf.decode(Bytes.reader(b), { index = 5 }) + t:check(e and e.code == Err.ARG, "collection index out of range") + local f1 = F.load(b, { index = 1 }) + t:check(f1 and f1.info.family == fonts["collection-1"].info.family, "F.load with opts.index") +end + +-- the api: detection by content, the font facade +do + local c = Fx.fonts[1] + t:eq(F.detect(c.data), "ttf", "F.detect") + local f = F.font.load(c.data) + t:check(f and f.kind == "font" and f.meta.source.format == "ttf", "F.font.load") + local g = f:glyphIndex(65) + t:check(g > 0 and f:advance(g) > 0, "glyph A") + t:eq(f:glyphIndex(-1), 0, "negative code point") + t:eq(f:glyphIndex(0.5), 0, "fractional code point") + t:check(f:outline(-1) == nil and f:outline(1e9) == nil and f:rasterize(g, -3) == nil, "bad glyph / size") + local sp = f:rasterize(f:glyphIndex(32), 20) + t:check(sp and sp.width == 0, "space rasterizes to an empty image") + local _, e = F.save(f, nil, { format = "ttf" }) + t:check(e and e.code == Err.UNSUPPORTED, "ttf is read-only") +end + +-- errors +do + local _, e1 = Ttf.decode(Bytes.reader(buffer.fromstring("OTTO"))) + t:check(e1 and e1.code == Err.TRUNCATED, "short file: " .. tostring(e1)) + local _, e2 = Ttf.decode(Bytes.reader(buffer.fromstring("\0\1\0\0\0\0\0\0\0\0\0\0"))) + t:check(e2 and e2.code == Err.CORRUPT, "no tables: " .. tostring(e2)) + t:eq(Ttf.sniff(Bytes.reader(buffer.fromstring("wOFF"))), 0, "sniff rejects woff") +end + +-- fuzz: whole-font mutations, then glyph access on whatever still parses +do + local samples = {} + for _, c in Fx.fonts do + if #c.data < 60000 then + table.insert(samples, c.data) + end + end + local rand = T.rng(99) + t:fuzz("decode + glyphs", function(b: buffer) + local f = Ttf.decode(Bytes.reader(b)) + if f then + for _ = 1, 12 do + local g = rand(f.numGlyphs + 2) + f:outline(g) + f:advance(g) + f:kern(g, rand(f.numGlyphs + 1)) + f:glyphIndex(rand(70000)) + f:rasterize(g, 9) + end + end + return f + end, samples, { mutations = 30, garbage = 200 }) + -- mutations inside the glyph data only (the header survives, so the outline parsers see the damage) + local hits = 0 + local cff = Fx.fonts[#Fx.fonts - 2] -- (any font: the loop below picks the CFF one) + for _, c in Fx.fonts do + if c.cff then + cff = c + end + end + local tries = 0 + for _, c in { Fx.fonts[1], cff } do + local base = buffer.fromstring(c.data) + local n = buffer.len(base) + for _ = 1, 40 do + local b = buffer.create(n) + buffer.copy(b, 0, base) + for _ = 1, 20 do + local p = n // 4 + rand(n - n // 4) + buffer.writeu8(b, p, rand(256)) + end + tries += 1 + local ok = pcall(function() + local f = Ttf.decode(Bytes.reader(b)) + if f then + for g = 0, math.min(f.numGlyphs, 300) - 1 do + f:outline(g) + f:rasterize(g, 8) + end + hits += 1 + end + end) + t:check(ok, c.name .. ": glyph-data mutation threw") + end + end + t:note("glyph-data mutations: %d fonts (%d parsed), every glyph outlined + rasterized, none threw", tries, hits) +end + +t:done() diff --git a/tools/fixtures/fonts.py b/tools/fixtures/fonts.py new file mode 100644 index 0000000..0e90cee --- /dev/null +++ b/tools/fixtures/fonts.py @@ -0,0 +1,35 @@ +# Font fixtures (tools/fixtures.py): the imgui-luau fonts (TrueType: Cousine, DroidSans, Karla, Proggy*, Roboto, read +# from ~/dev/luau/imgui/imgui-luau/fonts or $IMGUI_FONTS; skipped if missing) and Source Sans 3 (CFF OpenType, nixpkgs +# source-sans), plus a copy of ProggyClean with a 'kern' table and a two-font collection, both made with fontTools. +# Reference values come from tools/fixtures/_font_reference.py: fontTools (metrics, names, cmap, hmtx, control boxes, +# areas, WOFF / WOFF2), HarfBuzz (GPOS kerning), FreeType (kern tables, unhinted renders). +# tests/gen/fonts.luau { fonts = { { name, data, upem, ..., cmap, glyphs, kern, renders } }, woff = { ... }, ttc } +import base64, glob, json, os, subprocess + +FONTS = os.environ.get("IMGUI_FONTS", os.path.expanduser("~/dev/luau/imgui/imgui-luau/fonts")) +PICK = ["Cousine-Regular", "DroidSans", "Karla-Regular", "ProggyClean", "Roboto-Medium"] + + +def generate(ctx): + specs = [] + for name in PICK: + p = os.path.join(FONTS, name + ".ttf") + if os.path.exists(p): + specs.append({"name": name, "b64": base64.b64encode(open(p, "rb").read()).decode()}) + out = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#source-sans"], capture_output=True, + check=True, text=True).stdout.strip().split("\n")[-1] + otf = os.path.join(out, "share", "fonts", "opentype", "SourceSans3-Regular.otf") + specs.append({"name": "SourceSans3-Regular", "b64": base64.b64encode(open(otf, "rb").read()).decode()}) + code = open(os.path.join(ctx.root, "tools", "fixtures", "_font_reference.py")).read() + raw = ctx.python(["fonttools", "freetype-py", "uharfbuzz", "brotli"], code, input=json.dumps(specs).encode()) + res = json.loads(raw) + d = base64.b64decode + for f in res["fonts"]: + f["data"] = d(f["data"]) + for r in f["renders"]: + r["pixels"] = d(r["pixels"]) + for w in res["woff"]: + w["woff"], w["woff2"] = d(w["woff"]), d(w["woff2"]) + if "ttc" in res: + res["ttc"]["data"] = d(res["ttc"]["data"]) + ctx.emit("fonts", res)