//! pardes's glyph atlas: its faces (a primary and fallbacks over vendor/font.c, //! FreeType and HarfBuzz), one 2048x2048 R8 stage filled pen-style a cell row //! at a time, the slot of every glyph drawn, and the rows drawn since the //! last upload; moved from pardes's gui.zig as it was. CPU only: uploading the //! rows is the owner's. `c` is the embedder's translation of vendor/font.h, //! so the embedder's FreeType and HarfBuzz are the ones linked, and the //! embedder exports ui_malloc and friends (font.h) over its allocator. //! What a glyph is drawn at (the sizes, a centred glyph's cells, the line //! thickness) is the caller's, passed to each `cachedGlyph`. const Atlas = @This(); const std = @import("std"); const c = @import("c"); pub const atlas_w: u32 = 2048; pub const atlas_h: u32 = 2048; pub const Slot = struct { u: u32, v: u32 }; /// An atlas entry is a glyph of a face (0 the primary font, i the fallback /// i - 1) at a role's size, drawn `span` cells wide with its own cell `lead` /// cells in: a ligature is one strip whose cells sample their own slices. /// Packed, so the atlas map hashes one word instead of walking fields. pub const Key = packed struct(u64) { face: u8, glyph: u32, role: Role, decoration: Decoration = .{}, centered: bool = false, lead: u4 = 0, span: u4 = 1, /// A light box-drawing rule (`ruleArms`), drawn edge to edge rather /// than from the font; `glyph` is its codepoint. rule: bool = false, _: u1 = 0, }; /// The size a glyph is drawn at: the body's, or the tagline's (pardes's /// FontRole, in its order). pub const Role = enum(u8) { body, tagline }; /// pardes's CellStyle.ul, in its order. pub const Underline = enum(u3) { off, single, double, curly, dotted, dashed }; pub const Decoration = packed struct(u5) { bold: bool = false, underline: Underline = .off, strikethrough: bool = false, }; /// A role's raster size: the face's pixel size, the width of its cell, the /// height of its band and its baseline from the band's top. pub const Size = struct { px: f32, cell_w: u32, height: u32, baseline: i32 }; /// The light box-drawing rules drawn by hand, as Ghostty and kitty draw /// them: a logical pixel thick through the cell's middle, out to its edges, /// so a markdown table's `|` (Tables.zig) joins the rows above and below it /// and its delimiter row is one line across, at any line height a font's /// own glyph would leave gaps in. The arms each one has: left, right, up, down. pub fn ruleArms(cp: u32) ?[4]bool { return switch (cp) { 0x2500 => .{ true, true, false, false }, // ─ 0x2502 => .{ false, false, true, true }, // │ 0x250c => .{ false, true, false, true }, // ┌ 0x2510 => .{ true, false, false, true }, // ┐ 0x2514 => .{ false, true, true, false }, // └ 0x2518 => .{ true, false, true, false }, // ┘ 0x251c => .{ false, true, true, true }, // ├ 0x2524 => .{ true, false, true, true }, // ┤ 0x252c => .{ true, true, false, true }, // ┬ 0x2534 => .{ true, true, true, false }, // ┴ 0x253c => .{ true, true, true, true }, // ┼ else => null, }; } /// `line_px`: the rule's thickness, the caller's logical pixel (pardes: dp(1)). fn drawRule(out: [*]u8, stride: usize, width: usize, height: usize, arms: [4]bool, line_px: usize) void { if (width == 0 or height == 0) return; const t: usize = @min(@max(1, line_px), @min(width, height)); const mx = (width - t) / 2; const my = (height - t) / 2; for (0..height) |y| @memset(out[y * stride ..][0..width], 0); if (arms[0] or arms[1]) for (0..t) |k| { const from: usize = if (arms[0]) 0 else mx; const to: usize = if (arms[1]) width else mx + t; @memset(out[(my + k) * stride + from ..][0 .. to - from], 255); }; if (arms[2] or arms[3]) { const from: usize = if (arms[2]) 0 else my; const to: usize = if (arms[3]) height else my + t; for (from..to) |y| @memset(out[y * stride + mx ..][0..t], 255); } } pub const InkBounds = struct { min_x: usize, min_y: usize, max_x: usize, max_y: usize }; pub fn inkBounds(bitmap: []const u8, stride: usize, w: usize, h: usize) ?InkBounds { var bounds: ?InkBounds = null; for (0..h) |y| for (0..w) |x| { if (bitmap[y * stride + x] == 0) continue; if (bounds) |*b| { b.min_x = @min(b.min_x, x); b.min_y = @min(b.min_y, y); b.max_x = @max(b.max_x, x); b.max_y = @max(b.max_y, y); } else bounds = .{ .min_x = x, .min_y = y, .max_x = x, .max_y = y }; }; return bounds; } pub const max_fallbacks = 15; pub const LoadedFallback = struct { face: *c.UIFont, bytes: []u8 = &.{}, }; /// The primary face (Key.face 0) and its bytes, the atlas's when not empty. font: *c.UIFont, font_bytes: []u8 = &.{}, fallbacks: [max_fallbacks]?LoadedFallback = @splat(null), fallback_count: usize = 0, atlas_stage: []u8, glyphs: std.AutoHashMap(Key, Slot), pen_x: u32 = 0, pen_y: u32 = 0, /// The atlas rows drawn into since the last upload, [top, bottom): the /// whole atlas at first, since the texture starts undefined. atlas_dirty_top: u32 = 0, atlas_dirty_bottom: u32 = atlas_h, space_slot: Slot = .{ .u = 0, .v = 0 }, /// An atlas over the primary face in `bytes`, borrowed for the face's life, /// its stage cleared; `reset` puts the pen after the space slot. pub fn init(gpa: std.mem.Allocator, bytes: []const u8) !Atlas { const font = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse return error.FontInit; errdefer c.ui_font_free(font); const atlas_stage = try gpa.alloc(u8, atlas_w * atlas_h); @memset(atlas_stage, 0); return .{ .font = font, .atlas_stage = atlas_stage, .glyphs = std.AutoHashMap(Key, Slot).init(gpa) }; } pub fn deinit(a: *Atlas, gpa: std.mem.Allocator) void { for (a.fallbacks[0..a.fallback_count]) |loaded| { const fallback = loaded.?; c.ui_font_free(fallback.face); if (fallback.bytes.len != 0) gpa.free(fallback.bytes); } c.ui_font_free(a.font); if (a.font_bytes.len != 0) gpa.free(a.font_bytes); a.glyphs.deinit(); gpa.free(a.atlas_stage); } /// The primary face from `bytes`, made with `gpa` and now the atlas's /// (FreeType borrows them for the face lifetime): false, and `bytes` freed, /// when FreeType refuses them. What was drawn stays until `reset`. pub fn setFont(a: *Atlas, gpa: std.mem.Allocator, bytes: []u8) bool { const font = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse { gpa.free(bytes); return false; }; c.ui_font_free(a.font); if (a.font_bytes.len != 0) gpa.free(a.font_bytes); a.font = font; a.font_bytes = bytes; // FreeType borrows them for the face lifetime return true; } /// The next fallback face, from `bytes`: borrowed, or the atlas's to free /// with `gpa` when `owned`. False (owned bytes freed) when FreeType refuses /// them or every fallback is taken. pub fn addFallback(a: *Atlas, gpa: std.mem.Allocator, bytes: []const u8, owned: bool) bool { const len = std.math.cast(c_int, bytes.len); const face = if (a.fallback_count < a.fallbacks.len and len != null) c.ui_font_new(bytes.ptr, len.?) else null; if (face == null) { if (owned) gpa.free(bytes); return false; } a.fallbacks[a.fallback_count] = .{ .face = face.?, .bytes = if (owned) @constCast(bytes) else &.{} }; a.fallback_count += 1; return true; } /// HarfBuzz's process-wide objects, made with the primary face (font.h's /// ui_font_prime): the caller says what allocates them. pub fn prime(a: *Atlas) void { c.ui_font_prime(a.font); } /// The primary face's PostScript name, else its family's (font.h). pub fn fontName(a: *const Atlas) [*c]const u8 { return c.ui_font_name(a.font); } /// The primary face's cell at `px`: its width, height and ascent (font.h). pub fn cellMetrics(a: *const Atlas, px: f32, cell_w: *c_int, cell_h: *c_int, ascent: *c_int) void { c.ui_font_cell_metrics(a.font, px, cell_w, cell_h, ascent); } pub const FaceGlyph = struct { face: u8, glyph: u32 }; /// The face and glyph that draw `cp`, the face as a Key face: 0 is the /// primary font and i the fallback i - 1. A codepoint no face has draws the /// primary's .notdef. pub fn glyphForCodepoint(a: *const Atlas, cp: u32) FaceGlyph { const primary = c.ui_font_glyph(a.font, @intCast(cp)); if (primary != 0) return .{ .face = 0, .glyph = primary }; for (a.fallbacks[0..a.fallback_count], 1..) |loaded, face| { const glyph = c.ui_font_glyph(loaded.?.face, @intCast(cp)); if (glyph != 0) return .{ .face = @intCast(face), .glyph = glyph }; } return .{ .face = 0, .glyph = 0 }; } /// Whether shaping could replace `glyph` of the face `face` (a Key face): /// font.h's ui_font_substitutes. pub fn substitutes(a: *const Atlas, face: u8, glyph: u32) bool { const font = if (face == 0) a.font else a.fallbacks[face - 1].?.face; return c.ui_font_substitutes(font, glyph) != 0; } /// A run of codepoints all of the face `face`, one cell each, shaped at `px` /// on a grid `cell_w` wide into `out`: font.h's ui_font_shape. pub fn shape(a: *const Atlas, face: u8, px: f32, cell_w: u32, cps: []const u32, out: []c.UIShapedCell) void { const font = if (face == 0) a.font else a.fallbacks[face - 1].?.face; c.ui_font_shape(font, px, @intCast(cell_w), cps.ptr, @intCast(cps.len), out.ptr); } // The first cell of the cleared atlas stays blank: the space slot, `cell_w` // wide (the body's). pub fn reset(a: *Atlas, cell_w: u32) void { a.glyphs.clearRetainingCapacity(); @memset(a.atlas_stage, 0); a.space_slot = .{ .u = 0, .v = 0 }; a.pen_x = cell_w; a.pen_y = 0; a.atlas_dirty_top = 0; a.atlas_dirty_bottom = atlas_h; } /// The atlas slot of `key`, rasterized on first use at `body`'s or /// `tagline`'s size (Key.role). A strip is `span` cells wide (a grip glyph /// `centered_cells` cells, centered); a cell samples its slice of it. Pen /// rows are `body`'s cell tall. Rules and decorations are `line_px` thick. /// Null when the atlas is full. pub fn cachedGlyph(a: *Atlas, key: Key, body: Size, tagline: Size, centered_cells: u32, line_px: usize) ?Slot { if (a.glyphs.get(key)) |s| return s; const slot_w = body.cell_w * (if (key.centered) centered_cells else key.span); if (a.pen_x + slot_w > atlas_w) { a.pen_x = 0; a.pen_y += body.height; } if (a.pen_y + body.height > atlas_h) return null; // atlas full: fall back const s = Slot{ .u = a.pen_x, .v = a.pen_y }; const out = a.atlas_stage.ptr + @as(usize, s.v) * atlas_w + s.u; const face = if (key.face == 0) a.font else a.fallbacks[key.face - 1].?.face; const px = if (key.role == .tagline) tagline.px else body.px; const baseline = if (key.role == .tagline) tagline.baseline else body.baseline; const cell_w = if (key.role == .tagline) tagline.cell_w else body.cell_w; const raster_w = if (key.centered) slot_w else cell_w * key.span; const raster_h = if (key.role == .tagline) tagline.height else body.height; const bold = @intFromBool(key.decoration.bold); if (key.rule) { drawRule(out, atlas_w, raster_w, raster_h, ruleArms(key.glyph).?, line_px); } else if (key.centered) { _ = c.ui_font_raster_centered(face, px, key.glyph, bold, out, @intCast(atlas_w), @intCast(raster_w), @intCast(raster_h)); } else { _ = c.ui_font_raster(face, px, key.glyph, bold, out, @intCast(atlas_w), @intCast(raster_w), @intCast(raster_h), @intCast(cell_w * key.lead), @intCast(cell_w), baseline); } decorateLine(out, atlas_w, raster_w, raster_h, baseline, key.decoration, line_px); if (key.centered) centerGlyphInk(out, raster_w, raster_h); a.atlas_dirty_top = @min(a.atlas_dirty_top, s.v); a.atlas_dirty_bottom = @max(a.atlas_dirty_bottom, s.v + raster_h); a.glyphs.put(key, s) catch return null; a.pen_x += slot_w; return s; } // Run once when a grip glyph enters the atlas, after decorations. Copy only // visible ink so bearings, empty bitmap margins and bold all share one center. fn centerGlyphInk(out: [*]u8, width: usize, height: usize) void { const b = inkBounds(out[0 .. (height - 1) * atlas_w + width], atlas_w, width, height) orelse return; const w = b.max_x - b.min_x + 1; const h = b.max_y - b.min_y + 1; const left = (width - w) / 2; const top = (height - h) / 2; var scratch: [atlas_w]u8 = undefined; for (0..h) |step| { const row = if (top > b.min_y) h - 1 - step else step; const source = (b.min_y + row) * atlas_w + b.min_x; const target = (top + row) * atlas_w; @memcpy(scratch[0..w], out[source..][0..w]); @memset(out[target..][0..width], 0); @memcpy(out[target + left ..][0..w], scratch[0..w]); } for (0..height) |row| { if (row < top or row >= top + h) @memset(out[row * atlas_w ..][0..width], 0); } } // Underline and strikethrough stay inside the existing atlas slot, so text // advance, caret and selection geometry are identical to the regular glyph. // The cached mask keeps this work out of steady-state rendering and also // decorates terminal spaces. Bold is not drawn here: the rasterizer emboldens // the outline. fn decorateLine(out: [*]u8, stride: usize, width: usize, height: usize, baseline: i32, decoration: Decoration, line_px: usize) void { if (width == 0 or height == 0) return; // A line is a logical pixel thick, its dots and waves as long: the same // weight at any density (`line_px`, pardes's dp(1)). const t: usize = line_px; if (decoration.underline != .off) { const base: usize = @intCast(@max(0, baseline)); const row = @min(base + 1, height -| t); for (0..width) |x| { const top = switch (decoration.underline) { .off => unreachable, .single => row, .double => { const upper = @min(base + 1, height -| 3 * t); for (0..t) |k| { out[@min(upper + k, height - 1) * stride + x] = 255; out[@min(upper + 2 * t + k, height - 1) * stride + x] = 255; } continue; }, .curly => row -| @as(usize, if (x % (4 * t) < 2 * t) t else 0), .dotted => if (x % (3 * t) < t) row else continue, .dashed => if (x % (6 * t) < 4 * t) row else continue, }; for (0..t) |k| out[@min(top + k, height - 1) * stride + x] = 255; } } if (decoration.strikethrough) { const row = @min(height -| t, @as(usize, @intCast(@max(0, baseline))) * 2 / 3); for (0..t) |k| @memset(out[@min(row + k, height - 1) * stride ..][0..width], 255); } } /// ui_malloc and friends for this file's own test binary, which has no /// embedder to export them: C's heap. A test that reaches FreeType or /// HarfBuzz names it, so only that binary exports them. const TestHeap = struct { fn malloc(size: usize) callconv(.c) ?*anyopaque { return std.c.malloc(size); } fn calloc(count: usize, size: usize) callconv(.c) ?*anyopaque { return std.c.calloc(count, size); } fn realloc(block: ?*anyopaque, size: usize) callconv(.c) ?*anyopaque { return std.c.realloc(block, size); } fn free(block: ?*anyopaque) callconv(.c) void { std.c.free(block); } comptime { @export(&malloc, .{ .name = "ui_malloc" }); @export(&calloc, .{ .name = "ui_calloc" }); @export(&realloc, .{ .name = "ui_realloc" }); @export(&free, .{ .name = "ui_free" }); } }; test "FreeType atlas raster is grayscale, bounded, and clears blank cells" { _ = TestHeap; const font_ttf = @embedFile("AdwaitaMono-Regular.ttf"); const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; defer c.ui_font_free(font); const h = c.ui_font_glyph(font, 'H'); try std.testing.expect(h != 0); try std.testing.expectEqual(@as(u32, 0), c.ui_font_glyph(font, 0x10ffff)); const size: f32 = 13.0; var cell_w: c_int = 0; var cell_h: c_int = 0; var ascent: c_int = 0; c.ui_font_cell_metrics(font, size, &cell_w, &cell_h, &ascent); try std.testing.expect(cell_w > 0 and cell_w <= 128); try std.testing.expect(cell_h > 0 and cell_h <= 128); const stride: c_int = 128; var bitmap: [128 * 128]u8 = @splat(0xaa); try std.testing.expectEqual( @as(c_int, 1), c.ui_font_raster(font, size, h, 0, &bitmap, stride, cell_w, cell_h, 0, cell_w, ascent), ); var ink: usize = 0; var soft: usize = 0; var regular_coverage: usize = 0; for (0..@intCast(cell_h)) |y| { for (0..@intCast(cell_w)) |x| { const coverage = bitmap[y * @as(usize, @intCast(stride)) + x]; if (coverage > 0) ink += 1; if (coverage > 0 and coverage < 255) soft += 1; regular_coverage += coverage; } } try std.testing.expect(ink > 0); try std.testing.expect(soft > 0); // Synthetic bold thickens the outline inside the same cell. try std.testing.expectEqual( @as(c_int, 1), c.ui_font_raster(font, size, h, 1, &bitmap, stride, cell_w, cell_h, 0, cell_w, ascent), ); var bold_coverage: usize = 0; for (0..@intCast(cell_h)) |y| { for (0..@intCast(cell_w)) |x| bold_coverage += bitmap[y * @as(usize, @intCast(stride)) + x]; for (bitmap[y * @as(usize, @intCast(stride)) + @as(usize, @intCast(cell_w)) ..][0..@intCast(stride - cell_w)]) |guard| try std.testing.expectEqual(@as(u8, 0xaa), guard); } try std.testing.expect(bold_coverage > regular_coverage); try std.testing.expectEqual( @as(c_int, 0), c.ui_font_raster(font, size, c.ui_font_glyph(font, ' '), 0, &bitmap, stride, cell_w, cell_h, 0, cell_w, ascent), ); for (0..@intCast(cell_h)) |y| for (0..@intCast(cell_w)) |x| try std.testing.expectEqual( @as(u8, 0), bitmap[y * @as(usize, @intCast(stride)) + x], ); } test "a box-drawing rule reaches its cell's edges, and only its arms do" { const stride = 12; const width = 9; const height = 15; var mask: [stride * height]u8 = @splat(0xa5); drawRule(&mask, stride, width, height, ruleArms(0x253c).?, 1); // ┼: ink on all four edges, none in the corners, nothing past the slot. try std.testing.expectEqual(@as(u8, 255), mask[0 * stride + width / 2]); try std.testing.expectEqual(@as(u8, 255), mask[(height - 1) * stride + width / 2]); try std.testing.expectEqual(@as(u8, 255), mask[(height / 2) * stride]); try std.testing.expectEqual(@as(u8, 255), mask[(height / 2) * stride + width - 1]); try std.testing.expectEqual(@as(u8, 0), mask[0]); for (0..height) |y| for (mask[y * stride + width ..][0 .. stride - width]) |guard| try std.testing.expectEqual(@as(u8, 0xa5), guard); drawRule(&mask, stride, width, height, ruleArms(0x2502).?, 1); try std.testing.expectEqual(@as(u8, 0), mask[(height / 2) * stride]); try std.testing.expectEqual(@as(u8, 255), mask[0 * stride + width / 2]); try std.testing.expect(ruleArms('|') == null); } test "glyph decorations render spaces and stay inside their atlas slot" { const stride = 9; const width = 5; const height = 7; for ([_]Decoration{ .{ .underline = .single }, .{ .underline = .double }, .{ .underline = .curly }, .{ .underline = .dotted }, .{ .underline = .dashed }, .{ .strikethrough = true }, }) |decoration| { var mask: [stride * (height + 1)]u8 = @splat(0xa5); for (0..height) |y| @memset(mask[y * stride ..][0..width], 0); decorateLine(&mask, stride, width, height, 5, decoration, 1); try std.testing.expect(inkBounds(&mask, stride, width, height) != null); for (0..height) |y| for (mask[y * stride + width ..][0 .. stride - width]) |guard| try std.testing.expectEqual(@as(u8, 0xa5), guard); for (mask[stride * height ..]) |guard| try std.testing.expectEqual(@as(u8, 0xa5), guard); } } test "the atlas's dirty rows hold every row a new glyph draws into, and a reset dirties them all" { _ = TestHeap; var a = try Atlas.init(std.testing.allocator, @embedFile("AdwaitaMono-Regular.ttf")); defer a.deinit(std.testing.allocator); // The body at 18 px, the tagline at 14 px in the body's cell (pardes // sizes it so, at its tagline percent). var cell_w: c_int = 0; var cell_h: c_int = 0; var ascent: c_int = 0; a.cellMetrics(18, &cell_w, &cell_h, &ascent); const body: Size = .{ .px = 18, .cell_w = @intCast(cell_w), .height = @intCast(cell_h), .baseline = ascent }; a.cellMetrics(14, &cell_w, &cell_h, &ascent); const tagline: Size = .{ .px = 14, .cell_w = @intCast(@min(cell_w, body.cell_w)), .height = @intCast(@min(cell_h, body.height)), .baseline = @min(ascent, cell_h) }; a.reset(body.cell_w); // The texture as an upload of the dirty rows leaves it, which starts undefined. const texture = try std.testing.allocator.alloc(u8, atlas_w * atlas_h); defer std.testing.allocator.free(texture); @memset(texture, 0xa5); var glyph: u32 = 0; for (0..40) |frame| { if (frame == 30) a.reset(body.cell_w); // a font change // Plain glyphs, strips, taglines, grip glyphs and decorations. for (0..25) |_| { glyph += 1; const span: u4 = @intCast(1 + glyph % 3); _ = a.cachedGlyph(.{ .face = 0, .glyph = glyph, .role = if (glyph % 4 == 0) .tagline else .body, .decoration = .{ .bold = glyph % 2 == 0, .underline = if (glyph % 5 == 0) .curly else .off, .strikethrough = glyph % 11 == 0 }, .centered = glyph % 13 == 0, .lead = @intCast(glyph % span), .span = span, }, body, tagline, 2, 1) orelse return error.AtlasFull; } for (0..atlas_h) |row| { const stage = a.atlas_stage[row * atlas_w ..][0..atlas_w]; const uploaded = texture[row * atlas_w ..][0..atlas_w]; if (row >= a.atlas_dirty_top and row < a.atlas_dirty_bottom) @memcpy(uploaded, stage) else try std.testing.expect(std.mem.eql(u8, stage, uploaded)); } a.atlas_dirty_top = atlas_h; a.atlas_dirty_bottom = 0; } try std.testing.expect(a.pen_y >= 2 * body.height); }