summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--build.zig70
-rw-r--r--docs/typ/building.typ2
-rw-r--r--shaders/decor.frag.glsl26
-rw-r--r--shaders/image.frag.glsl17
-rw-r--r--shaders/image.vert.glsl33
-rw-r--r--shaders/overlay.frag.glsl17
-rw-r--r--shaders/overlay.vert.glsl11
-rw-r--r--shaders/prebuilt/decor.frag.spvbin2176 -> 0 bytes
-rw-r--r--shaders/prebuilt/image.frag.spvbin1344 -> 0 bytes
-rw-r--r--shaders/prebuilt/image.vert.spvbin3152 -> 0 bytes
-rw-r--r--shaders/prebuilt/overlay.frag.spvbin1008 -> 0 bytes
-rw-r--r--shaders/prebuilt/overlay.vert.spvbin1040 -> 0 bytes
-rw-r--r--shaders/prebuilt/ui.frag.spvbin3184 -> 0 bytes
-rw-r--r--shaders/prebuilt/ui.vert.spvbin3848 -> 0 bytes
-rw-r--r--shaders/ui.frag.glsl39
-rw-r--r--shaders/ui.vert.glsl53
-rw-r--r--src/gui/font.c471
-rw-r--r--src/gui/font.h98
-rw-r--r--src/gui/gui.zig1656
-rw-r--r--test/process.zig22
-rw-r--r--test/process/window.zig393
-rw-r--r--test/veil.zig37
22 files changed, 831 insertions, 2114 deletions
diff --git a/build.zig b/build.zig
index afc4e4f3..100f2026 100644
--- a/build.zig
+++ b/build.zig
@@ -161,19 +161,12 @@ pub fn build(b: *std.Build) void {
const tracy = b.option([]const u8, "tracy", "enable Tracy profiling; supply the path to a Tracy source checkout");
const macos_sdk = b.option([]const u8, "macos-sdk", "the macOS SDK a gui built for macOS from another system takes SDL's headers and frameworks from");
const macos_identity = b.option([]const u8, "macos-identity", "codesigning identity for pardes.app (default: ad-hoc)") orelse "-";
- const prebuilt_shaders = b.option(bool, "prebuilt-shaders", "embed the committed shaders/prebuilt/*.spv instead of running glslc (default: on for a bare `zig build`, off when -Dplatform names a shell)") orelse also_gui;
+ const prebuilt_shaders = b.option(bool, "prebuilt-shaders", "embed sketchbook's committed src/gpu/shaders/prebuilt/*.spv instead of running glslc over its GLSL (default: on for a bare `zig build`, off when -Dplatform names a shell)") orelse also_gui;
const mupdf_check = b.step("mupdf-check", "the pdf addon's check: MuPDF compiles, links, renders and searches docs/design.pdf, and its script runs");
const pdf_pointer_bench_step = b.step("pdf-pointer-bench", "time PDF hover and selection gestures and prove their pixels (-Doptimize=ReleaseFast -- [--label L] [--reps N] [--path FILE] [--cell WxH])");
const pdf_scroll_bench_step = b.step("pdf-scroll-bench", "benchmark fast continuous-strip PDF scrolling in ReleaseFast (-Doptimize=ReleaseFast -- [--json] [--reps N] [--warmup N] [--path FILE])");
- const shaders_step = b.step("shaders", "refresh the committed shaders/prebuilt/*.spv (glslc)");
- const update_shaders = b.addUpdateSourceFiles();
- for (gui_shaders) |name| {
- update_shaders.addCopyFileToSource(compileGlsl(b, name), b.fmt("shaders/prebuilt/{s}.spv", .{name}));
- }
- shaders_step.dependOn(&update_shaders.step);
-
// build-time IO: slurps the grammars' highlights.scm queries, and reads
// vendor/themes to find the theme sources
var threaded: std.Io.Threaded = .init(b.allocator, .{});
@@ -462,6 +455,7 @@ pub fn build(b: *std.Build) void {
const addon_mod = b.createModule(.{ .root_source_file = b.path("src/kinds/addon.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "pardes_addon", .module = kind_mod }} });
const snake_shader_step = b.step("snake-shader", "build the optional GPU snake addon into zig-out/lib");
var snake_shader_lib: ?*std.Build.Step.Compile = null;
+ const veil_step = b.step("veil", "build the frame corpus's translucent GPU test addon (test/veil.zig) into zig-out/lib");
if (b.lazyDependency("sketchbook", .{ .@"gpu-only" = true })) |sb| {
const files = b.addWriteFiles();
for ([_][]const u8{ "vert", "frag", "post.frag" }) |stage| {
@@ -476,6 +470,9 @@ pub fn build(b: *std.Build) void {
snake_shader_lib = lib;
snake_shader_step.dependOn(&b.addInstallArtifact(lib, .{}).step);
snake_shader_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module })).step);
+ // The frame corpus's translucent addon (test/veil.zig), into lib/ beside the snake.
+ const veil = b.addLibrary(.{ .name = "veil", .linkage = .dynamic, .root_module = b.createModule(.{ .root_source_file = b.path("test/veil.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "addon", .module = addon_mod }, .{ .name = "gpu_scene", .module = sb.module("gpu_scene") } } }) });
+ veil_step.dependOn(&b.addInstallArtifact(veil, .{}).step);
}
// The PDF addon (addons/pdf/pdf.zig over MuPDF through pdf_bridge.c), built
// and installed as the image addon is: compiled only for a step that
@@ -927,7 +924,13 @@ pub fn build(b: *std.Build) void {
const gui_shell_mods: [2]?*std.Build.Module = .{ gui_shell_mod, if (platform == .gui) static_mod else null };
// SDL's headers, for the macOS trackpad adapter's test after the loop.
var sdl_include: ?std.Build.LazyPath = null;
+ // sketchbook's Cells.zig's own tests (the instance ABI), for unit-test.
+ var cells_test: ?*std.Build.Step.Compile = null;
+ // sketchbook's Atlas.zig's own tests, for unit-test.
+ var atlas_test: ?*std.Build.Step.Compile = null;
for (gui_shell_mods) |gui_shell_entry| if (gui_shell_entry) |gm| {
+ // This shell's `c`, for the Atlas's tests below.
+ var font_c: ?*std.Build.Module = null;
// SDL's build asks a cross build for macOS for the SDK's paths.
const sdk: ?std.Build.LazyPath = if (macos_sdk) |p| .{ .cwd_relative = p } else null;
const sdl_dep = b.lazyDependency("sdl", .{ .target = target, .optimize = optimize, .sanitize_c = .off, .preferred_linkage = .static, .system_include_path = if (sdk) |p| p.path(b, "usr/include") else null, .system_framework_path = if (sdk) |p| p.path(b, "System/Library/Frameworks") else null, .library_path = if (sdk) |p| p.path(b, "usr/lib") else null });
@@ -951,10 +954,31 @@ pub fn build(b: *std.Build) void {
gui_c.addIncludePath(dep.path("include"));
gui_c.addIncludePath(b.path("src/gui"));
const gui_c_mod = gui_c.createModule();
+ font_c = gui_c_mod;
gm.addImport("gui_c", gui_c_mod);
if (b.lazyDependency("sketchbook", .{ .@"gpu-only" = true })) |sb| {
const gpu = b.createModule(.{ .root_source_file = sb.path("src/gpu/Executor.zig"), .imports = &.{ .{ .name = "abi", .module = sb.module("abi") }, .{ .name = "c", .module = gui_c_mod } } });
gm.addImport("sketch_gpu", gpu);
+ // The glyph atlas (src/font/Atlas.zig) over the font shim
+ // (vendor/font.{c,h}), compiled below against pardes's
+ // FreeType and HarfBuzz.
+ const atlas_mod = b.createModule(.{ .root_source_file = sb.path("src/font/Atlas.zig"), .imports = &.{.{ .name = "c", .module = gui_c_mod }} });
+ gm.addImport("font_atlas", atlas_mod);
+ // pardes's renderer, moved to sketchbook (src/gpu/), compiled
+ // against pardes's SDL; its tests run with unit-test. Its
+ // SPIR-V is sketchbook's GLSL through glslc, or the prebuilt
+ // copies with -Dprebuilt-shaders.
+ const cells_mod = b.createModule(.{ .root_source_file = sb.path("src/gpu/Cells.zig"), .imports = &.{ .{ .name = "c", .module = gui_c_mod }, .{ .name = "font_atlas", .module = atlas_mod } } });
+ for (gui_shaders) |name| cells_mod.addAnonymousImport(b.fmt("{s}.spv", .{name}), .{
+ .root_source_file = if (prebuilt_shaders)
+ sb.path(b.fmt("src/gpu/shaders/prebuilt/{s}.spv", .{name}))
+ else
+ compileGlsl(b, sb.path(b.fmt("src/gpu/shaders/{s}.glsl", .{name})), name),
+ });
+ gm.addImport("gpu_cells", cells_mod);
+ gm.addImport("gpu_present", b.createModule(.{ .root_source_file = sb.path("src/gpu/Present.zig"), .imports = &.{ .{ .name = "c", .module = gui_c_mod }, .{ .name = "gpu_cells", .module = cells_mod } } }));
+ if (cells_test == null) cells_test = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = sb.path("src/gpu/Cells.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "c", .module = gui_c_mod }, .{ .name = "font_atlas", .module = atlas_mod } } }), .filters = test_filters });
+ gui_c.addIncludePath(sb.path("vendor"));
gm.addImport("gpu_scene", sb.module("gpu_scene"));
}
sdl_include = dep.path("include");
@@ -1011,22 +1035,26 @@ pub fn build(b: *std.Build) void {
});
gm.linkLibrary(harfbuzz);
gm.addIncludePath(upstream.path("src"));
+ // The Atlas's own tests, over the same FreeType, HarfBuzz and
+ // shim, the embedded face theirs to draw.
+ if (atlas_test == null) if (font_c) |fc| if (b.lazyDependency("sketchbook", .{ .@"gpu-only" = true })) |sb| {
+ const atlas_mod = b.createModule(.{ .root_source_file = sb.path("src/font/Atlas.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "c", .module = fc }} });
+ atlas_mod.linkLibrary(ft);
+ atlas_mod.linkLibrary(harfbuzz);
+ atlas_mod.addIncludePath(upstream.path("src"));
+ atlas_mod.addCSourceFile(.{ .file = sb.path("vendor/font.c") });
+ atlas_mod.addAnonymousImport("AdwaitaMono-Regular.ttf", .{ .root_source_file = b.path("assets/AdwaitaMono-Regular.ttf") });
+ atlas_test = b.addTest(.{ .root_module = atlas_mod, .filters = test_filters });
+ };
}
if (target.result.os.tag.isDarwin())
gm.addRPath(.{ .cwd_relative = "/usr/local/lib" });
- gm.addIncludePath(b.path("src/gui"));
- gm.addCSourceFile(.{ .file = b.path("src/gui/font.c") });
+ if (b.lazyDependency("sketchbook", .{ .@"gpu-only" = true })) |sb| gm.addCSourceFile(.{ .file = sb.path("vendor/font.c") });
// the embedded UI font: provided as a build import since assets/ lives
// outside the src/ module root (@embedFile can't escape it)
gm.addAnonymousImport("AdwaitaMono-Regular.ttf", .{
.root_source_file = b.path("assets/AdwaitaMono-Regular.ttf"),
});
- for (gui_shaders) |name| gm.addAnonymousImport(b.fmt("{s}.spv", .{name}), .{
- .root_source_file = if (prebuilt_shaders)
- b.path(b.fmt("shaders/prebuilt/{s}.spv", .{name}))
- else
- compileGlsl(b, name),
- });
};
if (target.result.os.tag == .macos) if (sdl_include) |include| {
const adapter_test = b.addSystemCommand(&.{ "xcrun", "clang", "-fobjc-arc", "-O1", "-framework", "Cocoa", "-I" });
@@ -1617,6 +1645,8 @@ pub fn build(b: *std.Build) void {
// The perf and fs bench programs' own tests: they compile no editor.
_ = units.add(b, perf_tests, null);
_ = units.add(b, fs_bench_test, null);
+ if (cells_test) |t| _ = units.add(b, t, null);
+ if (atlas_test) |t| _ = units.add(b, t, null);
const core_test = b.addTest(.{ .root_module = core_lean, .filters = test_filters });
const run_core_test = b.addRunArtifact(core_test);
run_core_test.has_side_effects = true;
@@ -2068,12 +2098,12 @@ fn reindexed(b: *std.Build, archive: std.Build.LazyPath, index: usize) std.Build
return run.addOutputFileArg(b.fmt("{d}.a", .{index}));
}
-/// glslc shaders/<name>.glsl -fshader-stage=<vertex|fragment> -o <name>.spv,
-/// returned as a LazyPath for @embedFile. The stage is the name's own suffix.
-fn compileGlsl(b: *std.Build, name: []const u8) std.Build.LazyPath {
+/// glslc <glsl> -fshader-stage=<vertex|fragment> -o <name>.spv, returned as
+/// a LazyPath for @embedFile. The stage is the name's own suffix.
+fn compileGlsl(b: *std.Build, glsl: std.Build.LazyPath, name: []const u8) std.Build.LazyPath {
const stage = if (std.mem.endsWith(u8, name, ".vert")) "vertex" else "fragment";
const cmd = b.addSystemCommand(&.{ "glslc", b.fmt("-fshader-stage={s}", .{stage}) });
- cmd.addFileArg(b.path(b.fmt("shaders/{s}.glsl", .{name})));
+ cmd.addFileArg(glsl);
cmd.addArg("-o");
return cmd.addOutputFileArg(b.fmt("{s}.spv", .{name}));
}
diff --git a/docs/typ/building.typ b/docs/typ/building.typ
index 543acfa5..f14c466b 100644
--- a/docs/typ/building.typ
+++ b/docs/typ/building.typ
@@ -65,7 +65,7 @@ must share with its session; `pardes --help` lists every flag.
[`-Dtheme-animation`], [bool, `true`],
[`-Dworkspace-tag`], [bool: draw the workspace tag row; on except for macOS, whose menu bar carries it],
[`-Dmacos-sdk`], [path: the macOS SDK SDL's headers and frameworks come from, for a gui built for macOS elsewhere],
- [`-Dprebuilt-shaders`], [bool: embed the committed SPIR-V; on for a bare `zig build`, off with `-Dplatform`; `zig build shaders` refreshes it with glslc],
+ [`-Dprebuilt-shaders`], [bool: embed the committed SPIR-V; on for a bare `zig build`, off with `-Dplatform`; the shaders are sketchbook's (`src/gpu/shaders/`), and its `zig build shaders` refreshes the SPIR-V with glslc],
[`-Dtracy`], [path to a Tracy checkout; off],
[`-Dmacos-identity`], [codesigning identity for `pardes.app`; `-` (ad hoc)],
[`-Dtest-filter`], [run only tests whose name contains it; a filter that matches nothing fails],
diff --git a/shaders/decor.frag.glsl b/shaders/decor.frag.glsl
deleted file mode 100644
index 71bb12e3..00000000
--- a/shaders/decor.frag.glsl
+++ /dev/null
@@ -1,26 +0,0 @@
-#version 450
-
-// Decor, drawn by ui.vert.glsl like a cell, and blended as the overlay
-// pipeline blends (backgroundLayerBlend). Ink (a cursor) is drawn with the
-// opacity uniform at 1.
-//
-// A hard-edged fill (a rule, a rail, a grip mark, a bar cursor): its colour
-// rides in the cell's ground (a_bg), its coverage in a_fg.r, so the result
-// is the overlay pipeline's exactly.
-
-layout(std140, set = 3, binding = 0) uniform UiUniforms {
- float background_opacity;
-} u_ui;
-
-layout(location = 1) in vec3 v_fg;
-layout(location = 2) in vec3 v_bg;
-layout(location = 5) flat in vec4 v_clip;
-
-layout(location = 0) out vec4 o_col;
-
-void main() {
- if (v_clip.z >= v_clip.x && (gl_FragCoord.x < v_clip.x || gl_FragCoord.x >= v_clip.z ||
- gl_FragCoord.y < v_clip.y || gl_FragCoord.y >= v_clip.w)) discard;
- float opacity = clamp(u_ui.background_opacity, 0.0, 1.0);
- o_col = vec4(v_bg * opacity, v_fg.r);
-}
diff --git a/shaders/image.frag.glsl b/shaders/image.frag.glsl
deleted file mode 100644
index 38a95da6..00000000
--- a/shaders/image.frag.glsl
+++ /dev/null
@@ -1,17 +0,0 @@
-#version 450
-
-layout(set = 2, binding = 0) uniform sampler2D u_image;
-layout(std140, set = 3, binding = 0) uniform UiUniforms {
- float background_opacity;
-} u_ui;
-
-layout(location = 0) in vec2 v_uv;
-layout(location = 0) out vec4 o_col;
-
-void main() {
- vec4 source = texture(u_image, v_uv);
- // Keep source coverage for destination subtraction; the pipeline scales
- // source alpha by the same opacity through its alpha blend constant.
- source.rgb *= clamp(u_ui.background_opacity, 0.0, 1.0);
- o_col = source;
-}
diff --git a/shaders/image.vert.glsl b/shaders/image.vert.glsl
deleted file mode 100644
index ace55a53..00000000
--- a/shaders/image.vert.glsl
+++ /dev/null
@@ -1,33 +0,0 @@
-#version 450
-
-// One instance per Surface image attachment. The CPU has already converted
-// the pane's cell rectangle and the aspect-preserving contain fit to NDC.
-layout(location = 0) in vec4 a_rect; // x0, y0, x1, y1
-layout(location = 1) in vec4 a_uv_rect; // u0, v0, u1, v1
-
-layout(location = 0) out vec2 v_uv;
-
-void main() {
- vec2 pos;
- int corner = gl_VertexIndex % 6;
- if (corner == 0) {
- pos = vec2(a_rect.x, a_rect.y);
- v_uv = vec2(a_uv_rect.x, a_uv_rect.y);
- } else if (corner == 1) {
- pos = vec2(a_rect.z, a_rect.y);
- v_uv = vec2(a_uv_rect.z, a_uv_rect.y);
- } else if (corner == 2) {
- pos = vec2(a_rect.z, a_rect.w);
- v_uv = vec2(a_uv_rect.z, a_uv_rect.w);
- } else if (corner == 3) {
- pos = vec2(a_rect.x, a_rect.y);
- v_uv = vec2(a_uv_rect.x, a_uv_rect.y);
- } else if (corner == 4) {
- pos = vec2(a_rect.z, a_rect.w);
- v_uv = vec2(a_uv_rect.z, a_uv_rect.w);
- } else {
- pos = vec2(a_rect.x, a_rect.w);
- v_uv = vec2(a_uv_rect.x, a_uv_rect.w);
- }
- gl_Position = vec4(pos, 0.0, 1.0);
-}
diff --git a/shaders/overlay.frag.glsl b/shaders/overlay.frag.glsl
deleted file mode 100644
index b5ac8d5a..00000000
--- a/shaders/overlay.frag.glsl
+++ /dev/null
@@ -1,17 +0,0 @@
-#version 450
-
-layout(std140, set = 3, binding = 0) uniform UiUniforms {
- float background_opacity;
-} u_ui;
-
-layout(location = 0) in vec4 v_color;
-
-layout(location = 0) out vec4 o_col;
-
-void main() {
- // Preserve shape coverage for destination subtraction. The pipeline uses
- // the matching opacity blend constant for source alpha, so graphics laid
- // over a background with the same opacity do not accumulate opaque seams.
- // Text/cursor draw groups bind opacity 1 instead.
- o_col = vec4(v_color.rgb * clamp(u_ui.background_opacity, 0.0, 1.0), v_color.a);
-}
diff --git a/shaders/overlay.vert.glsl b/shaders/overlay.vert.glsl
deleted file mode 100644
index 5f6be593..00000000
--- a/shaders/overlay.vert.glsl
+++ /dev/null
@@ -1,11 +0,0 @@
-#version 450
-
-layout(location = 0) in vec2 a_pos;
-layout(location = 1) in vec4 a_color;
-
-layout(location = 0) out vec4 v_color;
-
-void main() {
- v_color = a_color;
- gl_Position = vec4(a_pos, 0.0, 1.0);
-}
diff --git a/shaders/prebuilt/decor.frag.spv b/shaders/prebuilt/decor.frag.spv
deleted file mode 100644
index 0d5af9d2..00000000
--- a/shaders/prebuilt/decor.frag.spv
+++ /dev/null
Binary files differ
diff --git a/shaders/prebuilt/image.frag.spv b/shaders/prebuilt/image.frag.spv
deleted file mode 100644
index d663ed80..00000000
--- a/shaders/prebuilt/image.frag.spv
+++ /dev/null
Binary files differ
diff --git a/shaders/prebuilt/image.vert.spv b/shaders/prebuilt/image.vert.spv
deleted file mode 100644
index 1105bae2..00000000
--- a/shaders/prebuilt/image.vert.spv
+++ /dev/null
Binary files differ
diff --git a/shaders/prebuilt/overlay.frag.spv b/shaders/prebuilt/overlay.frag.spv
deleted file mode 100644
index e296e99e..00000000
--- a/shaders/prebuilt/overlay.frag.spv
+++ /dev/null
Binary files differ
diff --git a/shaders/prebuilt/overlay.vert.spv b/shaders/prebuilt/overlay.vert.spv
deleted file mode 100644
index a518c576..00000000
--- a/shaders/prebuilt/overlay.vert.spv
+++ /dev/null
Binary files differ
diff --git a/shaders/prebuilt/ui.frag.spv b/shaders/prebuilt/ui.frag.spv
deleted file mode 100644
index 91022fe2..00000000
--- a/shaders/prebuilt/ui.frag.spv
+++ /dev/null
Binary files differ
diff --git a/shaders/prebuilt/ui.vert.spv b/shaders/prebuilt/ui.vert.spv
deleted file mode 100644
index ad132bf9..00000000
--- a/shaders/prebuilt/ui.vert.spv
+++ /dev/null
Binary files differ
diff --git a/shaders/ui.frag.glsl b/shaders/ui.frag.glsl
deleted file mode 100644
index 7f70629a..00000000
--- a/shaders/ui.frag.glsl
+++ /dev/null
@@ -1,39 +0,0 @@
-#version 450
-
-// Sample the glyph atlas (R = coverage 0..1) and mix the cell's bg up to its fg
-// by that coverage. Output is PREMULTIPLIED: an opaque cell is unchanged.
-// WindowOpacity changes only the ground's coverage, never the glyph's ink.
-
-layout(set = 2, binding = 0) uniform sampler2D u_atlas;
-layout(std140, set = 3, binding = 0) uniform UiUniforms {
- float background_opacity;
-} u_ui;
-
-layout(location = 0) in vec2 v_uv;
-layout(location = 1) in vec3 v_fg;
-layout(location = 2) in vec3 v_bg;
-layout(location = 4) flat in uint v_effect;
-layout(location = 5) flat in vec4 v_clip;
-
-layout(location = 0) out vec4 o_col;
-
-void main() {
- if (v_clip.z >= v_clip.x && (gl_FragCoord.x < v_clip.x || gl_FragCoord.x >= v_clip.z ||
- gl_FragCoord.y < v_clip.y || gl_FragCoord.y >= v_clip.w)) discard;
- float a = texture(u_atlas, v_uv).r;
- // A block cursor is foreground chrome even though its fill occupies the
- // cell background: keep it visible at WindowOpacity 0. Otherwise the
- // ground's coverage is the setting's. The flag is shared with
- // ui.vert.glsl and src/gui/gui.zig.
- float bgA = (v_effect & 0x20000000u) != 0u ? 1.0 : clamp(u_ui.background_opacity, 0.0, 1.0);
-
- // Ink over ground, both premultiplied: v_fg*a + (v_bg*bgA)*(1-a), which is
- // mix() with the ground already premultiplied. At bgA = 1 that is exactly
- // the mix(v_bg, v_fg, a) at alpha 1 this shader always wrote.
- vec4 under = vec4(v_bg * bgA, bgA);
- vec4 cell = vec4(mix(under.rgb, v_fg, a), mix(under.a, 1.0, a));
-
- // FreeType's hinted grayscale bitmap is already the intended coverage.
- // Preserve it exactly; weight-changing gamma hacks blur small stems.
- o_col = cell;
-}
diff --git a/shaders/ui.vert.glsl b/shaders/ui.vert.glsl
deleted file mode 100644
index e3532e68..00000000
--- a/shaders/ui.vert.glsl
+++ /dev/null
@@ -1,53 +0,0 @@
-#version 450
-
-// Terminal cell renderer. The CPU uploads one instance per visible cell; this
-// shader expands each instance into a two-triangle quad with gl_VertexIndex.
-// The fragment shader mixes fg/bg by the atlas's alpha (a glyph mask in the R
-// channel), so background fills and glyph foregrounds draw in a single pass.
-
-layout(location = 0) in vec4 a_rect; // x0, y0, x1, y1
-layout(location = 1) in vec4 a_uv_rect; // u0, v0, u1, v1
-layout(location = 2) in vec3 a_fg;
-layout(location = 3) in vec3 a_bg;
-// Flags, the high bits: an opaque block-cursor fill (ui.frag.glsl).
-layout(location = 4) in uint a_effect;
-// A clip rectangle in target pixels (x0, y0, x1, y1): the fragment shader
-// drops what lies outside it. x1 < x0 is none.
-layout(location = 5) in vec4 a_clip;
-
-layout(location = 0) out vec2 v_uv;
-layout(location = 1) out vec3 v_fg;
-layout(location = 2) out vec3 v_bg;
-layout(location = 4) flat out uint v_effect;
-layout(location = 5) flat out vec4 v_clip;
-
-void main() {
- vec2 pos;
- vec2 uv;
- int corner = gl_VertexIndex % 6;
- if (corner == 0) {
- pos = vec2(a_rect.x, a_rect.y);
- uv = vec2(a_uv_rect.x, a_uv_rect.y);
- } else if (corner == 1) {
- pos = vec2(a_rect.z, a_rect.y);
- uv = vec2(a_uv_rect.z, a_uv_rect.y);
- } else if (corner == 2) {
- pos = vec2(a_rect.z, a_rect.w);
- uv = vec2(a_uv_rect.z, a_uv_rect.w);
- } else if (corner == 3) {
- pos = vec2(a_rect.x, a_rect.y);
- uv = vec2(a_uv_rect.x, a_uv_rect.y);
- } else if (corner == 4) {
- pos = vec2(a_rect.z, a_rect.w);
- uv = vec2(a_uv_rect.z, a_uv_rect.w);
- } else {
- pos = vec2(a_rect.x, a_rect.w);
- uv = vec2(a_uv_rect.x, a_uv_rect.w);
- }
- v_uv = uv;
- v_fg = a_fg;
- v_bg = a_bg;
- v_effect = a_effect;
- v_clip = a_clip;
- gl_Position = vec4(pos, 0.0, 1.0);
-}
diff --git a/src/gui/font.c b/src/gui/font.c
deleted file mode 100644
index aebe26e6..00000000
--- a/src/gui/font.c
+++ /dev/null
@@ -1,471 +0,0 @@
-// FreeType and HarfBuzz wrapper for gui.zig. The policy intentionally follows
-// Ghostty's FreeType backend: native hinting enabled, the auto-hinter available
-// as a fallback, and the light target for shape-preserving grayscale text.
-// HarfBuzz only picks glyphs (liga, calt); the grid, not the font's advances,
-// places them.
-#include "font.h"
-#include <freetype-zig.h>
-#include <freetype/ftbitmap.h>
-#include <freetype/ftmodapi.h>
-#include <hb-ft.h>
-#include <hb-ot.h>
-#include <hb.h>
-
-#include <string.h>
-
-struct UIFont {
- // FreeType allocates through ui_malloc and friends: the library holds a
- // pointer to this for its lifetime, which the UIFont outlives.
- struct FT_MemoryRec_ memory;
- FT_Library library;
- FT_Face face;
- FT_F26Dot6 size;
- // The charmap's answer for ASCII, which is most of every screen: a word the
- // renderer has not seen before looks up each of its cells.
- uint32_t ascii[128];
- // HarfBuzz state, made by the first ui_font_substitutes question (most
- // fallback faces are never asked).
- hb_font_t *hb;
- hb_buffer_t *buffer;
- FT_F26Dot6 hb_size;
- // Every glyph a lookup of a ligature feature could replace. Nothing else
- // can change a glyph, so a cell outside it is its nominal glyph without
- // shaping: every cell, in a font without ligatures.
- hb_set_t *substitutes;
- // ui_font_shape's per-cell scratch, grown to the longest run seen
- uint32_t *own;
- uint8_t *state;
- int32_t scratch;
-};
-
-static FT_F26Dot6 size_26_6(float px) {
- if (px < 1.0f)
- px = 1.0f;
- return (FT_F26Dot6)(px * 64.0f + 0.5f);
-}
-
-static int set_size(UIFont *f, float px) {
- const FT_F26Dot6 size = size_26_6(px);
- if (f->size == size)
- return 1;
- if (FT_Set_Char_Size(f->face, 0, size, 72, 72) != 0)
- return 0;
- f->size = size;
- return 1;
-}
-
-static int ceil_26_6(FT_Pos value) { return (int)((value + 63) >> 6); }
-
-static FT_Int32 load_flags(void) {
- // Hinting is on because FT_LOAD_NO_HINTING is absent. Likewise, leaving
- // FT_LOAD_NO_AUTOHINT absent lets FreeType fall back to its auto-hinter
- // when the face has no native instructions. This is Ghostty's default.
- return FT_LOAD_DEFAULT | FT_LOAD_TARGET_LIGHT;
-}
-
-static void *ft_alloc(FT_Memory memory, long size) {
- (void)memory;
- return ui_malloc((size_t)size);
-}
-
-static void ft_free(FT_Memory memory, void *block) {
- (void)memory;
- ui_free(block);
-}
-
-static void *ft_realloc(FT_Memory memory, long cur_size, long new_size,
- void *block) {
- (void)memory;
- (void)cur_size;
- return ui_realloc(block, (size_t)new_size);
-}
-
-UIFont *ui_font_new(const uint8_t *data, int32_t len) {
- if (!data || len <= 0)
- return NULL;
-
- UIFont *f = (UIFont *)ui_calloc(1, sizeof(UIFont));
- if (!f)
- return NULL;
- // FT_Init_FreeType is exactly FT_New_Library over FT_New_Memory's malloc
- // manager, then the default modules and properties: the same, over ours.
- f->memory = (struct FT_MemoryRec_){NULL, ft_alloc, ft_free, ft_realloc};
- if (FT_New_Library(&f->memory, &f->library) != 0) {
- ui_free(f);
- return NULL;
- }
- FT_Add_Default_Modules(f->library);
- FT_Set_Default_Properties(f->library);
- if (FT_New_Memory_Face(f->library, data, (FT_Long)len, 0, &f->face) != 0) {
- FT_Done_Library(f->library);
- ui_free(f);
- return NULL;
- }
- // Some symbol fonts do not expose a Unicode charmap. FreeType already
- // selects a usable default for those, so failure here is non-fatal.
- (void)FT_Select_Charmap(f->face, FT_ENCODING_UNICODE);
- for (uint32_t cp = 0; cp < 128; cp++)
- f->ascii[cp] = FT_Get_Char_Index(f->face, cp);
- return f;
-}
-
-// HarfBuzz reads this same face (and its charmap) through FreeType, so shaping
-// and rasterizing agree on glyph ids. None of these calls returns NULL: a
-// failure is an inert empty object, and shaping then yields nominal glyphs.
-static void start_harfbuzz(UIFont *f) {
- f->hb = hb_ft_font_create_referenced(f->face);
- f->buffer = hb_buffer_create();
- f->substitutes = hb_set_create();
- static const hb_tag_t features[] = {
- HB_TAG('l', 'i', 'g', 'a'), HB_TAG('c', 'a', 'l', 't'),
- HB_TAG('c', 'l', 'i', 'g'), HB_TAG('r', 'l', 'i', 'g'),
- HB_TAG('r', 'c', 'l', 't'), HB_TAG_NONE};
- hb_face_t *face = hb_font_get_face(f->hb);
- hb_set_t *lookups = hb_set_create();
- hb_ot_layout_collect_lookups(face, HB_OT_TAG_GSUB, NULL, NULL, features,
- lookups);
- hb_codepoint_t lookup = HB_SET_VALUE_INVALID;
- while (hb_set_next(lookups, &lookup))
- hb_ot_layout_lookup_collect_glyphs(face, HB_OT_TAG_GSUB, lookup, NULL,
- f->substitutes, NULL, NULL);
- hb_set_destroy(lookups);
-}
-
-const char *ui_font_name(UIFont *f) {
- if (!f || !f->face)
- return NULL;
- const char *postscript = FT_Get_Postscript_Name(f->face);
- if (postscript && postscript[0])
- return postscript;
- if (f->face->family_name && f->face->family_name[0])
- return f->face->family_name;
- return NULL;
-}
-
-uint32_t ui_font_glyph(UIFont *f, int32_t cp) {
- if (!f || cp < 0)
- return 0;
- if (cp < 128)
- return f->ascii[cp];
- return FT_Get_Char_Index(f->face, (FT_ULong)(uint32_t)cp);
-}
-
-void ui_font_free(UIFont *f) {
- if (!f)
- return;
- // The HarfBuzz font holds a reference on the face: release it first. (All
- // three accept NULL, a face that never shaped.)
- hb_set_destroy(f->substitutes);
- hb_buffer_destroy(f->buffer);
- hb_font_destroy(f->hb);
- if (f->face)
- FT_Done_Face(f->face);
- if (f->library)
- FT_Done_Library(f->library);
- ui_free(f->own);
- ui_free(f->state);
- ui_free(f);
-}
-
-void ui_font_prime(UIFont *f) {
- if (!f)
- return;
- hb_font_destroy(hb_ft_font_create_referenced(f->face));
- hb_buffer_t *buffer = hb_buffer_create();
- hb_buffer_add_utf8(buffer, "a", 1, 0, 1);
- hb_buffer_guess_segment_properties(buffer);
- hb_buffer_destroy(buffer);
-}
-
-void ui_font_cell_metrics(UIFont *f, float px, int32_t *cell_w, int32_t *cell_h,
- int32_t *ascent) {
- if (!f || !cell_w || !cell_h || !ascent || !set_size(f, px)) {
- if (cell_w)
- *cell_w = 1;
- if (cell_h)
- *cell_h = 1;
- if (ascent)
- *ascent = 1;
- return;
- }
-
- const FT_Size_Metrics metrics = f->face->size->metrics;
- const int asc = ceil_26_6(metrics.ascender);
- const int desc = ceil_26_6(-metrics.descender);
- int height = ceil_26_6(metrics.height);
- if (height < asc + desc)
- height = asc + desc;
-
- int width = ceil_26_6(metrics.max_advance);
- const FT_UInt m = FT_Get_Char_Index(f->face, 'M');
- if (FT_Load_Glyph(f->face, m, load_flags()) == 0) {
- const int advance = ceil_26_6(f->face->glyph->advance.x);
- if (advance > 0)
- width = advance;
- }
-
- *cell_w = width > 0 ? width : 1;
- *cell_h = height > 0 ? height : 1;
- *ascent = asc > 0 ? asc : 1;
-}
-
-static int raster(UIFont *f, float px, uint32_t glyph_index, int bold,
- uint8_t *out, int32_t stride, int32_t width, int32_t height,
- int32_t cell_x, int32_t cell_w, int32_t ascent,
- int centered) {
- if (!f || !out || stride < width || width <= 0 || height <= 0)
- return 0;
- for (int y = 0; y < height; y++)
- memset(out + (size_t)y * (size_t)stride, 0, (size_t)width);
- if (!set_size(f, px))
- return 0;
-
- if (FT_Load_Glyph(f->face, glyph_index, load_flags()) != 0)
- return 0;
- if (bold) {
- // Synthetic bold thickens the hinted outline before it is rendered, so
- // the wider stems are rasterized as one shape and keep hinted edges; the
- // advance is untouched, as the cell grid requires. Strength is Ghostty's
- // heuristic: 1/32 of the line height in 26.6, rounded up (one pixel at a
- // 32 px line). A bitmap strike has no outline: widen it by one whole pixel,
- // the classic overstrike, which keeps its pixels sharp.
- FT_GlyphSlot slot = f->face->glyph;
- if (slot->format == FT_GLYPH_FORMAT_OUTLINE) {
- const FT_Pos height = f->face->size->metrics.height;
- FT_Outline_Embolden(&slot->outline, (height + 31) / 32);
- } else if (slot->format == FT_GLYPH_FORMAT_BITMAP &&
- FT_GlyphSlot_Own_Bitmap(slot) == 0) {
- FT_Bitmap_Embolden(f->library, &slot->bitmap, 64, 0);
- }
- }
- if (FT_Render_Glyph(f->face->glyph, FT_RENDER_MODE_NORMAL) != 0)
- return 0;
-
- const FT_GlyphSlot glyph = f->face->glyph;
- const FT_Bitmap *bitmap = &glyph->bitmap;
- if (!bitmap->buffer || bitmap->width == 0 || bitmap->rows == 0)
- return 0;
-
- const int advance = ceil_26_6(glyph->advance.x);
- // Fallbacks may be proportional. Center their advance in the primary face's
- // fixed cell, exactly as Ghostty centers a narrower fallback face.
- const int gx = centered
- ? (width - (int)bitmap->width) / 2
- : cell_x + glyph->bitmap_left + (cell_w - advance) / 2;
- const int gy =
- centered ? (height - (int)bitmap->rows) / 2 : ascent - glyph->bitmap_top;
- const int pitch = bitmap->pitch;
- const int row_bytes = pitch < 0 ? -pitch : pitch;
-
- for (unsigned int y = 0; y < bitmap->rows; y++) {
- const int dy = gy + (int)y;
- if (dy < 0 || dy >= height)
- continue;
- const unsigned int source_y = pitch < 0 ? bitmap->rows - 1 - y : y;
- const uint8_t *src = bitmap->buffer + (size_t)source_y * (size_t)row_bytes;
-
- for (unsigned int x = 0; x < bitmap->width; x++) {
- const int dx = gx + (int)x;
- if (dx < 0 || dx >= width)
- continue;
-
- uint8_t coverage;
- if (bitmap->pixel_mode == FT_PIXEL_MODE_MONO) {
- coverage = (src[x >> 3] & (0x80u >> (x & 7))) ? 255 : 0;
- } else if (bitmap->pixel_mode == FT_PIXEL_MODE_GRAY) {
- coverage = src[x];
- if (bitmap->num_grays > 1 && bitmap->num_grays != 256)
- coverage = (uint8_t)((unsigned int)coverage * 255u /
- (bitmap->num_grays - 1u));
- } else {
- continue;
- }
- out[(size_t)dy * (size_t)stride + (size_t)dx] = coverage;
- }
- }
- return 1;
-}
-
-int ui_font_raster(UIFont *f, float px, uint32_t glyph, int bold, uint8_t *out,
- int32_t stride, int32_t width, int32_t height,
- int32_t cell_x, int32_t cell_w, int32_t ascent) {
- return raster(f, px, glyph, bold, out, stride, width, height, cell_x, cell_w,
- ascent, 0);
-}
-
-int ui_font_raster_centered(UIFont *f, float px, uint32_t glyph, int bold,
- uint8_t *out, int32_t stride, int32_t width,
- int32_t height) {
- return raster(f, px, glyph, bold, out, stride, width, height, 0, width, 0, 1);
-}
-
-// The horizontal ink of `glyph` placed as ui_font_raster places it in a cell
-// `cell` wide (26.6), relative to the cell's left edge. 0 when it has no ink.
-static int ink(UIFont *f, uint32_t glyph, FT_Pos cell, FT_Pos *left,
- FT_Pos *right) {
- if (FT_Load_Glyph(f->face, glyph, load_flags()) != 0)
- return 0;
- const FT_GlyphSlot slot = f->face->glyph;
- if (slot->metrics.width <= 0 || slot->metrics.height <= 0)
- return 0;
- const FT_Pos origin =
- (FT_Pos)(((int)(cell >> 6) - ceil_26_6(slot->advance.x)) / 2) * 64;
- *left = origin + slot->metrics.horiBearingX;
- *right = *left + slot->metrics.width;
- return 1;
-}
-
-// ui_font_shape's per-cell marks: no glyph of its own, keep the nominal glyph,
-// drawn as a slice of another cell's glyph.
-#define NONE UINT32_MAX
-#define PLAIN 1
-#define CLAIMED 2
-
-int ui_font_substitutes(UIFont *f, uint32_t glyph) {
- if (!f)
- return 0;
- if (!f->hb)
- start_harfbuzz(f);
- return hb_set_has(f->substitutes, glyph);
-}
-
-// The GSUB features shaping leaves on are the ligature ones; the others
-// HarfBuzz would apply (glyph composition, local forms, fractions around
-// U+2044, ...) are off, so a cell is either its nominal glyph, as the renderer
-// always drew it, or part of a ligature. Positioning is untouched: the grid
-// ignores advances and keeps nominal glyphs where marks would move.
-static const hb_feature_t shaping_features[] = {
- {HB_TAG('c', 'c', 'm', 'p'), 0, 0, (unsigned int)-1},
- {HB_TAG('l', 'o', 'c', 'l'), 0, 0, (unsigned int)-1},
- {HB_TAG('r', 'v', 'r', 'n'), 0, 0, (unsigned int)-1},
- {HB_TAG('l', 't', 'r', 'a'), 0, 0, (unsigned int)-1},
- {HB_TAG('l', 't', 'r', 'm'), 0, 0, (unsigned int)-1},
- {HB_TAG('r', 'a', 'n', 'd'), 0, 0, (unsigned int)-1},
- {HB_TAG('f', 'r', 'a', 'c'), 0, 0, (unsigned int)-1},
- {HB_TAG('n', 'u', 'm', 'r'), 0, 0, (unsigned int)-1},
- {HB_TAG('d', 'n', 'o', 'm'), 0, 0, (unsigned int)-1},
-};
-
-void ui_font_shape(UIFont *f, float px, int32_t cell_w, const uint32_t *cps,
- int32_t n, UIShapedCell *out) {
- if (!f || !cps || !out || n <= 0)
- return;
- for (int32_t i = 0; i < n; i++)
- out[i] = (UIShapedCell){ui_font_glyph(f, (int32_t)cps[i]), 0, 1, 0};
- if (!f->hb)
- start_harfbuzz(f);
- int substitutable = 0;
- for (int32_t i = 0; i < n && !substitutable; i++)
- substitutable = hb_set_has(f->substitutes, out[i].glyph);
- if (!substitutable || cell_w <= 0 || !set_size(f, px))
- return;
- if (n > f->scratch) {
- uint32_t *own = (uint32_t *)ui_realloc(f->own, (size_t)n * sizeof *own);
- if (!own)
- return;
- f->own = own;
- uint8_t *state = (uint8_t *)ui_realloc(f->state, (size_t)n);
- if (!state)
- return;
- f->state = state;
- f->scratch = n;
- }
- // hb-ft reads the FreeType size when told; positions are only consulted
- // for being nonzero, but a zero scale would hide exactly that.
- if (f->hb_size != f->size) {
- hb_ft_font_changed(f->hb);
- f->hb_size = f->size;
- }
- hb_buffer_clear_contents(f->buffer);
- // One codepoint per cell, so a cluster value IS a cell index.
- hb_buffer_add_codepoints(f->buffer, cps, n, 0, n);
- hb_buffer_set_direction(f->buffer, HB_DIRECTION_LTR);
- hb_buffer_guess_segment_properties(f->buffer);
- hb_shape(f->hb, f->buffer, shaping_features,
- sizeof shaping_features / sizeof shaping_features[0]);
- unsigned int count = 0;
- const hb_glyph_info_t *info = hb_buffer_get_glyph_infos(f->buffer, &count);
- const hb_glyph_position_t *pos =
- hb_buffer_get_glyph_positions(f->buffer, &count);
-
- // Each cell's own glyph is the one HarfBuzz left in its cluster. A cell a
- // ligature merged into an earlier cluster has NONE. A cluster the grid
- // cannot place (several glyphs, a positioned mark) is PLAIN, and so are the
- // cells merged into it: they keep their nominal glyphs.
- uint32_t *own = f->own;
- uint8_t *state = f->state;
- for (int32_t i = 0; i < n; i++) {
- own[i] = NONE;
- state[i] = 0;
- }
- for (unsigned int k = 0; k < count; k++) {
- const uint32_t cluster = info[k].cluster;
- if (cluster >= (uint32_t)n)
- continue;
- if (own[cluster] != NONE || pos[k].x_offset != 0 || pos[k].y_offset != 0)
- state[cluster] = PLAIN;
- else
- own[cluster] = info[k].codepoint;
- }
- for (int32_t i = 1; i < n; i++)
- if (own[i] == NONE && (state[i - 1] & PLAIN))
- state[i] = PLAIN;
-
- // A substituted glyph (or one whose cluster swallowed cells) may reach over
- // its neighbours: it claims those that draw nothing of their own, nearest
- // first, and each draws its slice of the one strip. Ink past a cell edge by
- // half a pixel or less is noise.
- const FT_Pos cell = (FT_Pos)cell_w * 64;
- for (int32_t i = 0; i < n; i++) {
- if ((state[i] & (PLAIN | CLAIMED)) || own[i] == NONE)
- continue;
- int32_t merged = 0;
- while (i + 1 + merged < n && own[i + 1 + merged] == NONE &&
- !(state[i + 1 + merged] & PLAIN))
- merged++;
- if (own[i] == out[i].glyph && merged == 0)
- continue;
- FT_Pos left = 0, right = 0;
- if (!ink(f, own[i], cell, &left, &right))
- continue; // a spacer: claimed, never claiming
- int32_t want_left =
- left < -32 ? (int32_t)((-left - 32 + cell - 1) / cell) : 0;
- int32_t want_right = right > cell + 32
- ? (int32_t)((right - cell - 32 + cell - 1) / cell)
- : 0;
- if (want_right < merged)
- want_right = merged;
- int32_t lead = 0, trail = 0;
- while (lead < want_left && 1 + lead + trail < UI_MAX_SPAN) {
- const int32_t j = i - lead - 1;
- FT_Pos l, r;
- if (j < 0 || (state[j] & (PLAIN | CLAIMED)) ||
- (own[j] != NONE &&
- (own[j] == out[j].glyph || ink(f, own[j], cell, &l, &r))))
- break;
- lead++;
- }
- while (trail < want_right && 1 + lead + trail < UI_MAX_SPAN) {
- const int32_t j = i + trail + 1;
- FT_Pos l, r;
- if (j >= n || (state[j] & (PLAIN | CLAIMED)) ||
- (own[j] != NONE &&
- (own[j] == out[j].glyph || ink(f, own[j], cell, &l, &r))))
- break;
- trail++;
- }
- for (int32_t j = i - lead; j <= i + trail; j++) {
- out[j] =
- (UIShapedCell){own[i], (uint8_t)lead, (uint8_t)(1 + lead + trail),
- (uint8_t)(j - (i - lead))};
- state[j] |= CLAIMED;
- }
- }
- // The rest draw their own glyph; a merged cell nothing claimed draws blank.
- const uint32_t space = f->ascii[' '];
- for (int32_t i = 0; i < n; i++) {
- if (state[i] & (PLAIN | CLAIMED))
- continue;
- out[i].glyph = own[i] == NONE ? space : own[i];
- }
-}
diff --git a/src/gui/font.h b/src/gui/font.h
deleted file mode 100644
index db964fb0..00000000
--- a/src/gui/font.h
+++ /dev/null
@@ -1,98 +0,0 @@
-// Tiny C shim over FreeType and HarfBuzz, so gui.zig only imports the stable
-// renderer API. The implementation owns FreeType's library and face objects
-// and HarfBuzz's font and buffer, and keeps the caller's font bytes borrowed
-// for the face lifetime.
-#ifndef UI_FONT_H
-#define UI_FONT_H
-#include <stddef.h>
-#include <stdint.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef struct UIFont UIFont;
-
-// Every allocation FreeType, HarfBuzz and this shim make: C's malloc, calloc,
-// realloc and free, implemented by gui.zig over a Zig allocator. HarfBuzz is
-// compiled to call them (hb_malloc_impl and friends); FreeType gets them as
-// each library's memory manager.
-void *ui_malloc(size_t size);
-void *ui_calloc(size_t count, size_t size);
-void *ui_realloc(void *block, size_t size);
-void ui_free(void *block);
-
-// Parse the first face in an in-memory font. `data` must stay alive for the
-// lifetime of the font. Returns NULL on failure.
-UIFont *ui_font_new(const uint8_t *data, int32_t len);
-
-// The face FreeType actually accepted. Prefer its PostScript name (the same
-// identity the macOS shell reports); fall back to the family name when the
-// font has no PostScript table. Borrowed for the UIFont lifetime.
-const char *ui_font_name(UIFont *f);
-
-// The glyph the selected Unicode charmap maps `cp` to. Glyph zero is the
-// face's .notdef box: the codepoint is missing, which is what fallback choice
-// asks.
-uint32_t ui_font_glyph(UIFont *f, int32_t cp);
-
-// `px` is the pixel height. Metrics and rasterization both configure FreeType
-// at that size, so hinted advances, baseline and bitmaps stay in step.
-void ui_font_cell_metrics(UIFont *f, float px, int32_t *cell_w, int32_t *cell_h,
- int32_t *ascent);
-
-// What one grid cell draws: `slice` of the glyph `glyph` rasterized across
-// `span` cells with its own cell `lead` cells from the left. A plain cell is
-// its own glyph, lead 0, span 1, slice 0.
-typedef struct {
- uint32_t glyph;
- uint8_t lead;
- uint8_t span;
- uint8_t slice;
-} UIShapedCell;
-
-// The longest glyph strip a ligature may claim, in cells.
-#define UI_MAX_SPAN 8
-
-// Whether a lookup of the font's ligature features (liga, calt, clig, rlig,
-// rclt) could replace `glyph`. When it cannot, shaping leaves the glyph alone
-// and its cell needs no shaping at all.
-int ui_font_substitutes(UIFont *f, uint32_t glyph);
-
-// One cell per codepoint of `cps`, all in this face, shaped by HarfBuzz with
-// the font's ligature features (a run with no glyph ui_font_substitutes
-// reports comes back nominal without it). A substituted glyph whose ink
-// reaches over neighbouring cells that draw nothing of their own (a
-// ligature's spacers, or the cells a merged cluster swallowed) claims them as
-// a strip. Otherwise, and for anything the grid cannot place (several glyphs
-// in one cell, positioned marks), each cell is its nominal glyph.
-void ui_font_shape(UIFont *f, float px, int32_t cell_w, const uint32_t *cps,
- int32_t n, UIShapedCell *out);
-
-// Rasterize `glyph` into `out` as a hinted grayscale mask of `width` x
-// `height` (`stride` bytes per row). The glyph's advance is centered in the
-// `cell_w` pixels that start at `cell_x`, and its baseline is `ascent` pixels
-// from the top; ink outside the mask is clipped. `bold` emboldens the outline
-// before rendering (synthetic bold, same advance). Returns 1 when the glyph
-// produced coverage, 0 for blank/error.
-int ui_font_raster(UIFont *f, float px, uint32_t glyph, int bold, uint8_t *out,
- int32_t stride, int32_t width, int32_t height,
- int32_t cell_x, int32_t cell_w, int32_t ascent);
-
-// Center bitmap ink bounds, independent of advance and baseline bearings.
-int ui_font_raster_centered(UIFont *f, float px, uint32_t glyph, int bold,
- uint8_t *out, int32_t stride, int32_t width,
- int32_t height);
-
-void ui_font_free(UIFont *f);
-
-// HarfBuzz makes a few process-wide objects on first use and keeps them for
-// the life of the process (the default Unicode functions, the locale's
-// language, hb-ft's font functions). Making them here, with `f`'s face, lets
-// the caller hand them an allocator that does not count them as leaks.
-void ui_font_prime(UIFont *f);
-
-#ifdef __cplusplus
-}
-#endif
-#endif
diff --git a/src/gui/gui.zig b/src/gui/gui.zig
index d4603bec..aa6fc92b 100644
--- a/src/gui/gui.zig
+++ b/src/gui/gui.zig
@@ -1,4 +1,7 @@
const SketchGpu = @import("sketch_gpu");
+const Cells = @import("gpu_cells"); // sketchbook's src/gpu/Cells.zig
+const Atlas = @import("font_atlas"); // sketchbook's src/font/Atlas.zig
+const Present = @import("gpu_present"); // sketchbook's src/gpu/Present.zig
const GpuScene = @import("gpu_scene");
const filesystem = @import("../fs.zig");
const std = @import("std");
@@ -38,13 +41,6 @@ const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ"))
const log = std.log.scoped(.gui);
const font_ttf = @embedFile("AdwaitaMono-Regular.ttf");
-const vert_spv = @embedFile("ui.vert.spv");
-const frag_spv = @embedFile("ui.frag.spv");
-const decor_frag_spv = @embedFile("decor.frag.spv");
-const overlay_vert_spv = @embedFile("overlay.vert.spv");
-const overlay_frag_spv = @embedFile("overlay.frag.spv");
-const image_vert_spv = @embedFile("image.vert.spv");
-const image_frag_spv = @embedFile("image.frag.spv");
const bg_default = [3]u8{ 18, 18, 18 };
const fg_default = [3]u8{ 204, 204, 204 };
@@ -85,66 +81,11 @@ const p9_arrow_mask = blk: {
break :blk m;
};
-const atlas_w: u32 = 2048;
-const atlas_h: u32 = 2048;
-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.
-const GlyphKey = packed struct(u64) {
- face: u8,
- glyph: u32,
- role: pardes.FontRole,
- decoration: GlyphDecoration = .{},
- 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 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.
-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,
- };
-}
-
-fn drawRule(out: [*]u8, stride: usize, width: usize, height: usize, arms: [4]bool) void {
- if (width == 0 or height == 0) return;
- const t: usize = @min(@max(1, @as(usize, @intFromFloat(dp(1)))), @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);
- }
-}
+const atlas_w = Atlas.atlas_w;
+const atlas_h = Atlas.atlas_h;
+const Slot = Atlas.Slot;
+const GlyphKey = Atlas.Key;
+const ruleArms = Atlas.ruleArms;
const GlyphDecoration = packed struct(u5) {
bold: bool = false,
@@ -161,6 +102,19 @@ const GlyphDecoration = packed struct(u5) {
}
};
+// The atlas's Key holds a GlyphDecoration and a FontRole as its own
+// Decoration and Role (@bitCast, @enumFromInt): the same bits, so the same
+// slots.
+comptime {
+ std.debug.assert(@bitSizeOf(GlyphDecoration) == @bitSizeOf(Atlas.Decoration));
+ for (.{ .{ @FieldType(pardes.CellStyle, "ul"), Atlas.Underline }, .{ pardes.FontRole, Atlas.Role } }) |pair| {
+ const ours = @typeInfo(pair[0]).@"enum";
+ const its = @typeInfo(pair[1]).@"enum";
+ std.debug.assert(ours.tag_type == its.tag_type and ours.field_names.len == its.field_names.len);
+ for (ours.field_names, its.field_names, ours.field_values, its.field_values) |a, b, x, y| std.debug.assert(std.mem.eql(u8, a, b) and x == y);
+ }
+}
+
const TaglineRaster = struct {
px: f32,
width: u32,
@@ -168,12 +122,12 @@ const TaglineRaster = struct {
height: u32,
};
-fn taglineRaster(font: *c.UIFont, body_px: f32, body_cell_w: u32, body_cell_h: u32, percent: u8) TaglineRaster {
+fn taglineRaster(atlas: *const Atlas, body_px: f32, body_cell_w: u32, body_cell_h: u32, percent: u8) TaglineRaster {
const px = body_px * @as(f32, @floatFromInt(percent)) / 100.0;
var own_w: c_int = 1;
var own_h: c_int = 1;
var own_ascent: c_int = 1;
- c.ui_font_cell_metrics(font, px, &own_w, &own_h, &own_ascent);
+ atlas.cellMetrics(px, &own_w, &own_h, &own_ascent);
const fixed_w: c_int = @intCast(body_cell_w);
const fixed_h: c_int = @intCast(body_cell_h);
const band_h = std.math.clamp(own_h, 1, fixed_h);
@@ -207,10 +161,9 @@ var sdl_allocator: std.mem.Allocator = undefined;
const sdl_heap = c_heap.Heap(&sdl_allocator);
const max_fallback_fonts = 1 + fonts.fallback_names.len;
-const LoadedFallback = struct {
- face: *c.UIFont,
- bytes: []u8 = &.{},
-};
+comptime {
+ std.debug.assert(max_fallback_fonts <= Atlas.max_fallbacks);
+}
const max_touch_points: usize = 16;
const touch_scroll_tick: f32 = 0.02;
@@ -223,69 +176,13 @@ const font_px_step: f32 = 2.0;
const font_px_min: f32 = 8.0;
const font_px_max: f32 = 72.0;
-const InkBounds = struct { min_x: usize, min_y: usize, max_x: usize, max_y: usize };
-
-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;
-}
+const CellInstance = Cells.CellInstance;
+const OverlayVertex = Cells.OverlayVertex;
+const ImageInstance = Cells.ImageInstance;
+const opaque_bg_bit = Cells.opaque_bg_bit;
-const CellInstance = extern struct {
- x0: f32,
- y0: f32,
- x1: f32,
- y1: f32,
- u0: f32,
- v0: f32,
- u1: f32,
- v1: f32,
- fr: f32,
- fg: f32,
- fb: f32,
- br: f32,
- bg: f32,
- bb: f32,
- /// The flags (the high bits, ui.vert.glsl).
- effect: u32 = 0,
- /// A clip rectangle in target pixels; x1 < x0 is none (ui.vert.glsl).
- clip_x0: f32 = 0,
- clip_y0: f32 = 0,
- clip_x1: f32 = -1,
- clip_y1: f32 = -1,
-};
-
-const OverlayVertex = extern struct {
- x: f32,
- y: f32,
- r: f32,
- g: f32,
- b: f32,
- a: f32,
-};
const OverlayColor = struct { r: f32, g: f32, b: f32, a: f32 };
-const ImageInstance = extern struct {
- x0: f32,
- y0: f32,
- x1: f32,
- y1: f32,
- u0: f32,
- v0: f32,
- u1: f32,
- v1: f32,
-};
-
-const opaque_bg_bit: u32 = 0x2000_0000;
-
const PreparedImage = struct {
premultiplied: bool = false,
place: pardes.Placement,
@@ -523,29 +420,15 @@ const Gui = struct {
addon_hash: [pardes.MAX_PANES]u64 = @splat(0),
addon_serial: [pardes.MAX_PANES]u32 = @splat(0),
addon_failed: [pardes.MAX_PANES]u64 = @splat(0),
- addon_pipeline: ?*c.SDL_GPUGraphicsPipeline = null,
window: *c.SDL_Window,
- device: *c.SDL_GPUDevice,
- swapchain_format: c.SDL_GPUTextureFormat,
- pipeline: *c.SDL_GPUGraphicsPipeline,
- decor_pipeline: *c.SDL_GPUGraphicsPipeline,
- overlay_pipeline: *c.SDL_GPUGraphicsPipeline,
- image_pipeline: *c.SDL_GPUGraphicsPipeline,
- atlas_tex: *c.SDL_GPUTexture,
- atlas_sampler: *c.SDL_GPUSampler,
- linear_sampler: *c.SDL_GPUSampler,
- atlas_xfer: *c.SDL_GPUTransferBuffer,
- vbuf: ?*c.SDL_GPUBuffer = null,
- vxfer: ?*c.SDL_GPUTransferBuffer = null,
- vbuf_cells: u32 = 0,
- overlay_vbuf: *c.SDL_GPUBuffer,
- overlay_vxfer: *c.SDL_GPUTransferBuffer,
+ /// The device, the window's claim or soft presenter, the frame's target
+ /// and the capture's read back (runNative owns it).
+ present: *Present,
+ /// The pipelines, the atlas's texture, the pictures' textures and the
+ /// buffers the frame is drawn from, on present's device (runNative owns
+ /// it).
+ cells: *Cells,
overlay_vertices: []OverlayVertex,
- image_vbuf: ?*c.SDL_GPUBuffer = null,
- image_vxfer: ?*c.SDL_GPUTransferBuffer = null,
- image_capacity: u32 = 0,
- /// The textures of the placements shown, by key.
- native_images: std.AutoHashMapUnmanaged(u64, *c.SDL_GPUTexture) = .empty,
prepared_images: std.ArrayListUnmanaged(PreparedImage) = .empty,
/// The glyph art of the placements whose panes ask for it (Petscii
/// on), and the frame copy it is drawn into.
@@ -556,15 +439,13 @@ const Gui = struct {
/// renderFrame's decor instances, group by group (buildDecor).
decor: std.ArrayListUnmanaged(CellInstance) = .empty,
- font: *c.UIFont,
- font_bytes: []u8 = &.{},
+ /// The faces and the glyphs drawn from them.
+ atlas: Atlas,
font_name: [255]u8 = @splat(0),
font_name_len: u8 = 0,
/// A replica client's: the session's font request it last followed
/// (syncReplicaFont), as a hash of the request.
remote_font_request: ?u64 = null,
- fallbacks: [max_fallback_fonts]?LoadedFallback = @splat(null),
- fallback_count: usize = 0,
px: f32,
tagline_px: f32,
tagline_percent: u8,
@@ -575,15 +456,6 @@ const Gui = struct {
ascent: i32,
tagline_baseline: i32,
- atlas_stage: []u8,
- glyphs: std.AutoHashMap(GlyphKey, 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 },
words: Words = .{},
touch: Touch = .{},
@@ -655,7 +527,6 @@ const Gui = struct {
/// null attached, where the session's tag is another process's.
hit_core: ?*pardes.Pardes = null,
- capture: bool = false,
/// Pixels the capture holds past the grid (PARDES_TEST_PAD).
capture_pad: u32 = 0,
capture_dir: []const u8 = "",
@@ -663,27 +534,15 @@ const Gui = struct {
/// frame series to look at.
capture_series: bool = false,
captured: u32 = 0,
- capture_tex: ?*c.SDL_GPUTexture = null,
- capture_tex_w: u32 = 0,
- capture_tex_h: u32 = 0,
- capture_xfer: ?*c.SDL_GPUTransferBuffer = null,
- capture_xfer_size: u32 = 0,
- soft_present: bool = false,
- surface_opacity: bool = false,
applied_window_opacity: u8 = 100,
- soft_renderer: ?*c.SDL_Renderer = null,
- soft_texture: ?*c.SDL_Texture = null,
/// What a window is opened again with (reopenWindow): the flags (not
- /// hidden), the present mode, its size when it was closed.
+ /// hidden), its size when it was closed (present keeps its present mode).
win_flags: c.SDL_WindowFlags = 0,
- present_mode: c.SDL_GPUPresentMode = c.SDL_GPU_PRESENTMODE_VSYNC,
window_w: c_int = 1120,
window_h: c_int = 720,
/// The window runNative destroys at the end: the one open then, if any.
window_slot: ?*?*c.SDL_Window = null,
- soft_tex_w: u32 = 0,
- soft_tex_h: u32 = 0,
gamepad: ?*c.SDL_Gamepad = null,
pad_x: f32 = 0,
@@ -695,15 +554,13 @@ const Gui = struct {
/// What a window held of its own let go (closeWindow lets the window go).
fn releaseWindowParts(g: *Gui, gpa: std.mem.Allocator) void {
- if (g.capture_tex) |texture| c.SDL_ReleaseGPUTexture(g.device, texture);
- if (g.capture_xfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(g.device, transfer);
g.glide.deinit(gpa);
gpa.free(g.scroll_edge);
g.prepared_images.deinit(gpa);
}
fn setGuiFontName(g: *Gui, fallback: []const u8) void {
- const name = if (c.ui_font_name(g.font)) |name_z| std.mem.span(name_z) else fallback;
+ const name = if (g.atlas.fontName()) |name_z| std.mem.span(name_z) else fallback;
const len = @min(name.len, g.font_name.len);
@memcpy(g.font_name[0..len], name[0..len]);
g.font_name_len = @intCast(len);
@@ -741,14 +598,7 @@ fn syncReplicaFont(g: *Gui, core: *const pardes.Pardes, gpa: std.mem.Allocator)
return false;
};
const bytes = filesystem.readFile(gpa, face.path) catch return false;
- const font = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse {
- gpa.free(bytes);
- return false;
- };
- c.ui_font_free(g.font);
- if (g.font_bytes.len != 0) gpa.free(g.font_bytes);
- g.font = font;
- g.font_bytes = bytes; // FreeType borrows them for the face lifetime
+ if (!g.atlas.setFont(gpa, bytes)) return false;
if (f.requested_size_hundredths != 0)
g.px = @as(f32, @floatFromInt(f.requested_size_hundredths)) / 100;
setGuiFontName(g, face.name);
@@ -757,52 +607,17 @@ fn syncReplicaFont(g: *Gui, core: *const pardes.Pardes, gpa: std.mem.Allocator)
}
fn loadFallbackFonts(g: *Gui, gpa: std.mem.Allocator) void {
- if (c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len))) |face| {
- g.fallbacks[0] = .{ .face = face };
- g.fallback_count = 1;
- }
+ _ = g.atlas.addFallback(gpa, font_ttf, false);
var arena_state = std.heap.ArenaAllocator.init(gpa);
defer arena_state.deinit();
for (fonts.fallbacks(arena_state.allocator())) |candidate| {
- if (g.fallback_count == g.fallbacks.len) break;
+ if (g.atlas.fallback_count == max_fallback_fonts) break;
const bytes = filesystem.readFile(gpa, candidate.path) catch continue;
- const len = std.math.cast(c_int, bytes.len) orelse {
- gpa.free(bytes);
- continue;
- };
- const face = c.ui_font_new(bytes.ptr, len) orelse {
- gpa.free(bytes);
- continue;
- };
- g.fallbacks[g.fallback_count] = .{ .face = face, .bytes = bytes };
- g.fallback_count += 1;
+ _ = g.atlas.addFallback(gpa, bytes, true);
}
}
-fn deinitFallbackFonts(g: *Gui, gpa: std.mem.Allocator) void {
- for (g.fallbacks[0..g.fallback_count]) |loaded| {
- const fallback = loaded.?;
- c.ui_font_free(fallback.face);
- if (fallback.bytes.len != 0) gpa.free(fallback.bytes);
- }
-}
-
-const FaceGlyph = struct { face: u8, glyph: u32 };
-
-/// The face and glyph that draw `cp`, the face as a GlyphKey face: 0 is the
-/// primary font and i the fallback i - 1. A codepoint no face has draws the
-/// primary's .notdef.
-fn glyphForCodepoint(g: *const Gui, cp: u32) FaceGlyph {
- const primary = c.ui_font_glyph(g.font, @intCast(cp));
- if (primary != 0) return .{ .face = 0, .glyph = primary };
- for (g.fallbacks[0..g.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 };
-}
-
const CellLayout = struct { w: f32, h: f32, x_off: f32, y_off: f32 };
const MouseCell = struct { col: u16, row: u16, body_hit: ?pardes.Mouse.BodyHit = null, tag_hit: ?pardes.TagHit = null, rule_above: bool = false };
@@ -856,16 +671,7 @@ fn fixedCellLayout(g: *const Gui) CellLayout {
return .{ .w = @floatFromInt(g.cell_w), .h = @floatFromInt(g.cell_h), .x_off = 0, .y_off = 0 };
}
-/// What one group draws, in this order: its cells, its images, then its
-/// decor.
-const Group = struct {
- cell_start: u32 = 0,
- cell_count: u32 = 0,
- image_start: u32 = 0,
- image_count: u32 = 0,
- decor_start: u32 = 0,
- decor_count: u32 = 0,
-};
+const Group = Cells.Group;
/// The frame's draw groups, bottom to top: the page and the panes, the
/// notices floating over them, the debug box the core paints over those,
@@ -1066,49 +872,18 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di
if (arrow_cursor) |cur| {
_ = c.SDL_SetCursor(cur);
} else log.err("SDL_CreateCursor: {s}", .{c.SDL_GetError()});
- const device = c.SDL_CreateGPUDevice(c.SDL_GPU_SHADERFORMAT_SPIRV, true, null) orelse {
- log.err("SDL_CreateGPUDevice: {s}", .{c.SDL_GetError()});
- return error.SdlInit;
- };
- defer c.SDL_DestroyGPUDevice(device);
- var soft_present = false;
- var soft_renderer: ?*c.SDL_Renderer = null;
- if (surface_opacity or !c.SDL_ClaimWindowForGPUDevice(device, window)) {
- if (surface_opacity)
- log.info("transparent window: the GPU API will not claim one, presenting through SDL_Renderer", .{})
- else
- log.warn("ClaimWindowForGPUDevice: {s}; presenting in software", .{c.SDL_GetError()});
- soft_renderer = c.SDL_CreateRenderer(window, null) orelse {
- log.err("SDL_CreateRenderer: {s}", .{c.SDL_GetError()});
- return error.SdlInit;
- };
- soft_present = true;
- }
- const present_mode: c.SDL_GPUPresentMode = blk: {
- if (soft_present) break :blk c.SDL_GPU_PRESENTMODE_VSYNC;
- for ([_]c.SDL_GPUPresentMode{ c.SDL_GPU_PRESENTMODE_IMMEDIATE, c.SDL_GPU_PRESENTMODE_MAILBOX, c.SDL_GPU_PRESENTMODE_VSYNC }) |mode| {
- if (c.SDL_WindowSupportsGPUPresentMode(device, window, mode)) break :blk mode;
- }
- break :blk c.SDL_GPU_PRESENTMODE_VSYNC;
- };
- if (!test_mode) _ = c.SDL_SetGPUAllowedFramesInFlight(device, 1);
- if (!soft_present) {
- _ = c.SDL_SetGPUSwapchainParameters(device, window, c.SDL_GPU_SWAPCHAINCOMPOSITION_SDR, present_mode);
- }
- const swapchain_format = if (soft_present)
- softTargetFormat(device)
- else
- c.SDL_GetGPUSwapchainTextureFormat(device, window);
+ var presenter = try Present.init(window, test_mode, surface_opacity);
+ defer presenter.deinit();
font_allocator = gpa;
- const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)) orelse {
- log.err("ui_font_new failed", .{});
- return error.FontInit;
+ var atlas = Atlas.init(gpa, font_ttf) catch |err| {
+ log.err("the font atlas: {t}", .{err});
+ return err;
};
// HarfBuzz's process-wide objects are made once and never freed: made
// from the default heap, they stay out of a Debug build's leak report.
font_allocator = std.heap.smp_allocator;
- c.ui_font_prime(font);
+ atlas.prime();
font_allocator = gpa;
// A harness forcing a density (PARDES_TEST_SCALE) draws the text as a
// person on that display would size it, so its chrome is seen at the
@@ -1117,10 +892,10 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di
var cw: c_int = 10;
var chh: c_int = 20;
var asc: c_int = 16;
- c.ui_font_cell_metrics(font, px, &cw, &chh, &asc);
+ atlas.cellMetrics(px, &cw, &chh, &asc);
const cell_w: u32 = @intCast(@max(cw, 1));
const cell_h: u32 = @intCast(@max(chh, 1));
- const tagline = taglineRaster(font, px, cell_w, cell_h, config.gui_tagline_font_percent);
+ const tagline = taglineRaster(&atlas, px, cell_w, cell_h, config.gui_tagline_font_percent);
if (test_mode) {
const cols = envU16(env, "PARDES_TEST_COLS") orelse 80;
const rows = envU16(env, "PARDES_TEST_ROWS") orelse 24;
@@ -1130,38 +905,11 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di
_ = c.SDL_SyncWindow(window);
}
- const atlas_tex = texture2d(device, c.SDL_GPU_TEXTUREFORMAT_R8_UNORM, c.SDL_GPU_TEXTUREUSAGE_SAMPLER, atlas_w, atlas_h) orelse return error.GpuCreate;
-
- var samp_info = std.mem.zeroes(c.SDL_GPUSamplerCreateInfo);
- samp_info.min_filter = c.SDL_GPU_FILTER_NEAREST;
- samp_info.mag_filter = c.SDL_GPU_FILTER_NEAREST;
- samp_info.mipmap_mode = c.SDL_GPU_FILTER_NEAREST;
- samp_info.address_mode_u = c.SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
- samp_info.address_mode_v = c.SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
- samp_info.address_mode_w = c.SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
- const atlas_sampler = c.SDL_CreateGPUSampler(device, &samp_info) orelse return error.GpuCreate;
- samp_info.min_filter = c.SDL_GPU_FILTER_LINEAR;
- samp_info.mag_filter = c.SDL_GPU_FILTER_LINEAR;
- samp_info.mipmap_mode = c.SDL_GPU_FILTER_LINEAR;
- const linear_sampler = c.SDL_CreateGPUSampler(device, &samp_info) orelse return error.GpuCreate;
-
- var ax_info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = atlas_w * atlas_h, .props = 0 };
- const atlas_xfer = c.SDL_CreateGPUTransferBuffer(device, &ax_info) orelse return error.GpuCreate;
-
- const pipeline = try makePipeline(device, swapchain_format, vert_spv, frag_spv, 1, 1, cell_input, std.mem.zeroes(c.SDL_GPUColorTargetBlendState));
- const decor_pipeline = try makePipeline(device, swapchain_format, vert_spv, decor_frag_spv, 0, 1, cell_input, backgroundLayerBlend());
- const overlay_pipeline = try makePipeline(device, swapchain_format, overlay_vert_spv, overlay_frag_spv, 0, 1, overlay_input, backgroundLayerBlend());
- const image_pipeline = try makePipeline(device, swapchain_format, image_vert_spv, image_frag_spv, 1, 1, image_input, backgroundLayerBlend());
+ var cells = try Cells.init(presenter.device, presenter.swapchain_format, max_overlay_vertices);
+ // The pipelines, textures and buffers it holds, whatever they were
+ // regrown to, before the device (presenter's defer).
+ defer cells.deinit(gpa);
- const overlay_buffer_size: u32 = @intCast(max_overlay_vertices * @sizeOf(OverlayVertex));
- var ovb_info = c.SDL_GPUBufferCreateInfo{ .usage = c.SDL_GPU_BUFFERUSAGE_VERTEX, .size = overlay_buffer_size, .props = 0 };
- const overlay_vbuf = c.SDL_CreateGPUBuffer(device, &ovb_info) orelse return error.GpuCreate;
- var ovx_info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = overlay_buffer_size, .props = 0 };
- const overlay_vxfer = c.SDL_CreateGPUTransferBuffer(device, &ovx_info) orelse return error.GpuCreate;
-
- const atlas_stage = try gpa.alloc(u8, atlas_w * atlas_h);
- defer gpa.free(atlas_stage);
- @memset(atlas_stage, 0);
const overlay_vertices = try gpa.alloc(OverlayVertex, max_overlay_vertices);
defer gpa.free(overlay_vertices);
@@ -1170,20 +918,10 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di
.arrow_cursor = arrow_cursor,
.link_cursor = link_cursor,
.box_cursor = box_cursor,
- .device = device,
- .swapchain_format = swapchain_format,
- .pipeline = pipeline,
- .decor_pipeline = decor_pipeline,
- .overlay_pipeline = overlay_pipeline,
- .image_pipeline = image_pipeline,
- .atlas_tex = atlas_tex,
- .atlas_sampler = atlas_sampler,
- .linear_sampler = linear_sampler,
- .atlas_xfer = atlas_xfer,
- .overlay_vbuf = overlay_vbuf,
- .overlay_vxfer = overlay_vxfer,
+ .present = &presenter,
+ .cells = &cells,
.overlay_vertices = overlay_vertices,
- .font = font,
+ .atlas = atlas,
.px = px,
.tagline_px = tagline.px,
.tagline_percent = config.gui_tagline_font_percent,
@@ -1193,62 +931,29 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di
.cell_h = cell_h,
.ascent = asc,
.tagline_baseline = tagline.baseline,
- .atlas_stage = atlas_stage,
- .glyphs = std.AutoHashMap(GlyphKey, Slot).init(gpa),
- .capture = test_mode,
.capture_pad = if (test_mode) envU16(env, "PARDES_TEST_PAD") orelse 0 else 0,
.capture_series = test_mode and env.get("PARDES_TEST_SERIES") != null,
.capture_dir = capture_dir orelse "",
- .soft_present = soft_present,
.demo = if (env.get("PARDES_FRAMES_DEMO")) |path| try pardes.FrameStats.readScript(init.arena.allocator(), init.io, path) else &.{},
.demo_next = if (env.get("PARDES_FRAMES_DEMO") != null) 0 else null,
- .surface_opacity = surface_opacity,
- .soft_renderer = soft_renderer,
.win_flags = reopen_flags,
- .present_mode = present_mode,
.window_w = want_w,
.window_h = want_h,
.window_slot = &window_slot,
};
- // The pipelines, textures and buffers the Gui holds, whatever they were
- // regrown to; the image ones are released below.
- defer {
- c.SDL_ReleaseGPUGraphicsPipeline(device, g.pipeline);
- c.SDL_ReleaseGPUGraphicsPipeline(device, g.decor_pipeline);
- c.SDL_ReleaseGPUGraphicsPipeline(device, g.overlay_pipeline);
- c.SDL_ReleaseGPUTexture(device, g.atlas_tex);
- c.SDL_ReleaseGPUSampler(device, g.atlas_sampler);
- c.SDL_ReleaseGPUSampler(device, g.linear_sampler);
- c.SDL_ReleaseGPUTransferBuffer(device, g.atlas_xfer);
- c.SDL_ReleaseGPUBuffer(device, g.overlay_vbuf);
- c.SDL_ReleaseGPUTransferBuffer(device, g.overlay_vxfer);
- if (g.vbuf) |buffer| c.SDL_ReleaseGPUBuffer(device, buffer);
- if (g.vxfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(device, transfer);
- if (g.image_vbuf) |buffer| c.SDL_ReleaseGPUBuffer(device, buffer);
- if (g.image_vxfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(device, transfer);
- if (g.capture_tex) |texture| c.SDL_ReleaseGPUTexture(device, texture);
- if (g.capture_xfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(device, transfer);
- if (g.gamepad) |pad| c.SDL_CloseGamepad(pad);
- }
+ defer if (g.gamepad) |pad| c.SDL_CloseGamepad(pad);
setGuiFontName(&g, "Adwaita Mono");
loadFallbackFonts(&g, gpa);
- defer deinitFallbackFonts(&g, gpa);
- defer g.glyphs.deinit();
+ defer g.atlas.deinit(gpa);
defer g.words.deinit(gpa);
defer {
if (g.addon_gpu) |*gpu| gpu.deinit();
- if (g.addon_pipeline) |pipeline_| c.SDL_ReleaseGPUGraphicsPipeline(device, pipeline_);
- clearNativeImages(&g);
- g.native_images.deinit(gpa);
g.prepared_images.deinit(gpa);
g.art.deinit(gpa);
if (g.art_arena) |*arena| arena.deinit();
g.cover.deinit(gpa);
g.decor.deinit(gpa);
}
- defer c.SDL_ReleaseGPUGraphicsPipeline(device, image_pipeline);
- defer if (g.font_bytes.len != 0) gpa.free(g.font_bytes); // set by Font, if it ran
- defer c.ui_font_free(g.font);
defer gpa.free(g.scroll_edge); // grown on demand by stepScroll
defer g.glide.deinit(gpa);
resetGlyphAtlas(&g);
@@ -1266,14 +971,7 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di
fn closeWindow(g: *Gui) void {
_ = c.SDL_GetWindowSize(g.window, &g.window_w, &g.window_h);
_ = c.SDL_StopTextInput(g.window);
- if (g.soft_renderer) |renderer| {
- if (g.soft_texture) |texture| c.SDL_DestroyTexture(texture);
- g.soft_texture = null;
- g.soft_tex_w = 0;
- g.soft_tex_h = 0;
- c.SDL_DestroyRenderer(renderer);
- g.soft_renderer = null;
- } else c.SDL_ReleaseWindowFromGPUDevice(g.device, g.window);
+ g.present.detach(g.window);
c.SDL_DestroyWindow(g.window);
if (g.window_slot) |slot| if (slot.* == g.window) {
slot.* = null;
@@ -1285,17 +983,9 @@ fn closeWindow(g: *Gui) void {
fn reopenWindow(g: *Gui) bool {
const window = c.SDL_CreateWindow("pardes", g.window_w, g.window_h, g.win_flags) orelse return false;
if (comptime builtin.os.tag == .macos) c.ui_macos_trackpad_attach(window);
- if (g.soft_present) {
- g.soft_renderer = c.SDL_CreateRenderer(window, null) orelse {
- c.SDL_DestroyWindow(window);
- return false;
- };
- } else {
- if (!c.SDL_ClaimWindowForGPUDevice(g.device, window)) {
- c.SDL_DestroyWindow(window);
- return false;
- }
- _ = c.SDL_SetGPUSwapchainParameters(g.device, window, c.SDL_GPU_SWAPCHAINCOMPOSITION_SDR, g.present_mode);
+ if (!g.present.attach(window)) {
+ c.SDL_DestroyWindow(window);
+ return false;
}
g.window = window;
if (g.window_slot) |slot| slot.* = window;
@@ -1303,7 +993,7 @@ fn reopenWindow(g: *Gui) bool {
// ponytail: another view's window asks the hit test of whichever
// window's share the Gui holds then (the workspace tag sits in the same
// place in every view); a test per window if one moves it.
- if (!g.capture) _ = c.SDL_SetWindowHitTest(window, hitTest, g);
+ if (!g.present.capture) _ = c.SDL_SetWindowHitTest(window, hitTest, g);
_ = c.SDL_StartTextInput(window);
return true;
}
@@ -1469,7 +1159,7 @@ fn localSession(
// One view, the window's (host_io.restoreCore).
shell.gview = 0;
shell.stopPtys();
- clearNativeImages(g);
+ g.cells.clearImages();
g.prepared_images.clearRetainingCapacity();
nc.view().frontend.native_images = true;
nc.view().frontend.native_image_patches = true;
@@ -3292,16 +2982,11 @@ fn pollFrame(ctx: ?*anyopaque) void {
core.rejectFont();
break :blk;
};
- const nf = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse {
+ if (!g.atlas.setFont(s.gpa, bytes)) {
log.err("ui_font_new failed: {s}", .{path});
- s.gpa.free(bytes);
core.rejectFont();
break :blk;
- };
- c.ui_font_free(g.font);
- if (g.font_bytes.len != 0) s.gpa.free(g.font_bytes);
- g.font = nf;
- g.font_bytes = bytes; // FreeType borrows them for the face lifetime
+ }
if (core.settings.font.requested_size_hundredths != 0)
g.px = @as(f32, @floatFromInt(core.settings.font.requested_size_hundredths)) / 100;
setGuiFontName(g, core.settings.font.requested_name.get());
@@ -3325,7 +3010,8 @@ fn pollFrame(ctx: ?*anyopaque) void {
var frame_capture_dir: ?[]const u8 = null;
var frame_capture_count: u32 = 0;
-fn captureSeries(dir: []const u8, pixels: []const u8, w: u32, h: u32) void {
+fn captureSeries(pixels: []const u8, w: u32, h: u32) void {
+ const dir = frame_capture_dir orelse return;
var path_buf: [4096]u8 = undefined;
const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/{d:0>6}.bgra", .{ dir, frame_capture_count }, 0) catch return;
const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644));
@@ -3482,7 +3168,7 @@ fn syncWindowOpacity(g: *Gui, core: *pardes.Pardes) void {
if (!core.settings.window_opacity_pending) return;
// Offscreen captures also support per-pixel alpha. Never approximate this
// with SDL_SetWindowOpacity: that would make foreground text translucent.
- finishWindowOpacity(core, &g.applied_window_opacity, if (g.surface_opacity or g.capture or core.settings.window_opacity == 100)
+ finishWindowOpacity(core, &g.applied_window_opacity, if (g.present.surface_opacity or g.present.capture or core.settings.window_opacity == 100)
null
else
"background transparency requires a native Wayland or alpha-capable SDL window");
@@ -4200,17 +3886,6 @@ fn scrollScissor(g: *const Gui, layout: CellLayout, sw: u32, sh: u32) c.SDL_Rect
return .{ .x = x0, .y = y0, .w = x1 - x0, .h = y1 - y0 };
}
-fn releaseNativeImage(g: *Gui, key: u64) void {
- if (g.native_images.fetchRemove(key)) |removed|
- c.SDL_ReleaseGPUTexture(g.device, removed.value);
-}
-
-fn clearNativeImages(g: *Gui) void {
- var iterator = g.native_images.valueIterator();
- while (iterator.next()) |texture| c.SDL_ReleaseGPUTexture(g.device, texture.*);
- g.native_images.clearRetainingCapacity();
-}
-
/// A placement the window shows as a texture: pixels, not glyph art.
fn texturePlacement(place: pardes.Placement) bool {
return !place.art.glyph and validImageBytes(place) != null;
@@ -4249,72 +3924,13 @@ fn uploadNativeTexture(
place: pardes.Placement,
) !void {
const byte_len = validImageBytes(place) orelse return error.BadImage;
- const key = place.key;
- if (g.native_images.contains(key)) return;
const r = place.raster;
- const row = r.stride;
- if (place.dirty) |dirty| dirty: {
- // The core changed only these rows since a picture we still hold:
- // write them into that texture rather than sending the whole page.
- if (dirty.y + dirty.h > r.h) break :dirty;
- const texture = g.native_images.get(dirty.from) orelse break :dirty;
- try uploadTextureRows(g, cmd, texture, r.bytes()[dirty.y * row ..][0 .. dirty.h * row], r.w, dirty.y, dirty.h);
- try g.native_images.put(gpa, key, texture);
- _ = g.native_images.remove(dirty.from);
- return;
- }
-
- const texture = texture2d(g.device, c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, c.SDL_GPU_TEXTUREUSAGE_SAMPLER, r.w, r.h) orelse return error.GpuCreate;
- errdefer c.SDL_ReleaseGPUTexture(g.device, texture);
- try uploadTextureRows(g, cmd, texture, r.bytes()[0..byte_len], r.w, 0, r.h);
- try g.native_images.put(gpa, key, texture);
-}
-
-/// Copy `rows` rows of RGBA, `width` pixels each, into `texture` at row `y`.
-fn uploadTextureRows(
- g: *Gui,
- cmd: *c.SDL_GPUCommandBuffer,
- texture: *c.SDL_GPUTexture,
- rgba: []const u8,
- width: usize,
- y: usize,
- rows: usize,
-) !void {
- var xf_info = c.SDL_GPUTransferBufferCreateInfo{
- .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD,
- .size = @intCast(rgba.len),
- .props = 0,
- };
- const transfer = c.SDL_CreateGPUTransferBuffer(g.device, &xf_info) orelse return error.GpuCreate;
- defer c.SDL_ReleaseGPUTransferBuffer(g.device, transfer);
- const mapped: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, transfer, false) orelse return error.GpuMap);
- @memcpy(mapped[0..rgba.len], rgba);
- c.SDL_UnmapGPUTransferBuffer(g.device, transfer);
-
- const copy = c.SDL_BeginGPUCopyPass(cmd);
- const src = c.SDL_GPUTextureTransferInfo{
- .transfer_buffer = transfer,
- .offset = 0,
- .pixels_per_row = @intCast(width),
- .rows_per_layer = @intCast(rows),
- };
- const dst = c.SDL_GPUTextureRegion{
- .texture = texture,
- .mip_level = 0,
- .layer = 0,
- .x = 0,
- .y = @intCast(y),
- .z = 0,
- .w = @intCast(width),
- .h = @intCast(rows),
- .d = 1,
- };
- c.SDL_UploadToGPUTexture(copy, &src, &dst, false);
- c.SDL_EndGPUCopyPass(copy);
+ const dirty: ?Cells.Dirty = if (place.dirty) |d| .{ .from = d.from, .y = d.y, .h = d.h } else null;
+ try g.cells.image(gpa, cmd, place.key, r.bytes()[0..byte_len], r.w, r.h, r.stride, dirty);
}
fn appendPreparedImage(g: *Gui, gpa: std.mem.Allocator, place: pardes.Placement) void {
- const texture = g.native_images.get(place.key) orelse return;
+ const texture = g.cells.native_images.get(place.key) orelse return;
if (nativePlaceGeometry(g, place) == null) return;
g.prepared_images.append(gpa, .{ .place = place, .texture = texture }) catch {};
}
@@ -4373,14 +3989,14 @@ fn prepareNativeImages(
while (true) {
var stale: [pardes.MAX_PANES]u64 = undefined;
var stale_len: usize = 0;
- var iterator = g.native_images.iterator();
+ var iterator = g.cells.native_images.iterator();
while (iterator.next()) |entry| {
if (surfaceHasNativeKey(surface, entry.key_ptr.*)) continue;
stale[stale_len] = entry.key_ptr.*;
stale_len += 1;
if (stale_len == stale.len) break;
}
- for (stale[0..stale_len]) |key| releaseNativeImage(g, key);
+ for (stale[0..stale_len]) |key| g.cells.releaseImage(key);
if (stale_len < stale.len) break;
}
@@ -4394,25 +4010,18 @@ fn prepareNativeImages(
const capacity = std.math.cast(u32, g.prepared_images.items.len) orelse return false;
if (capacity == 0) return true;
- growInstances(g, &g.image_vbuf, &g.image_vxfer, &g.image_capacity, capacity, @sizeOf(ImageInstance)) catch return false;
-
- const ptr: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, g.image_vxfer.?, false) orelse return false);
- const instances: [*]ImageInstance = @ptrCast(@alignCast(ptr));
+ const instances = g.cells.mapImages(gpa, capacity) orelse return false;
const win_w: f32 = @floatFromInt(sw);
const win_h: f32 = @floatFromInt(sh);
var idx: u32 = 0;
for (g.prepared_images.items) |prepared| {
+ // Drawn in this order, instance by instance (Cells.drawImages).
+ g.cells.images.appendAssumeCapacity(.{ .premultiplied = prepared.premultiplied, .texture = prepared.texture, .clip = imageScissor(g, prepared.place) });
if (!emitPreparedImage(g, surface, &instances[idx], prepared, win_w, win_h)) continue;
idx += 1;
}
- c.SDL_UnmapGPUTransferBuffer(g.device, g.image_vxfer.?);
std.debug.assert(idx == capacity);
-
- const copy = c.SDL_BeginGPUCopyPass(cmd);
- const src = c.SDL_GPUTransferBufferLocation{ .transfer_buffer = g.image_vxfer.?, .offset = 0 };
- const dst = c.SDL_GPUBufferRegion{ .buffer = g.image_vbuf.?, .offset = 0, .size = idx * @sizeOf(ImageInstance) };
- c.SDL_UploadToGPUBuffer(copy, &src, &dst, false);
- c.SDL_EndGPUCopyPass(copy);
+ g.cells.uploadImages(cmd, idx);
return true;
}
@@ -4425,35 +4034,6 @@ fn imageScissor(g: *const Gui, place: pardes.Placement) c.SDL_Rect {
};
}
-fn drawNativeImagesGpu(
- g: *Gui,
- rp: ?*c.SDL_GPURenderPass,
- batch: Group,
- whole: c.SDL_Rect,
-) void {
- const pass = rp orelse return;
- c.SDL_BindGPUGraphicsPipeline(pass, g.image_pipeline);
- var idx = batch.image_start;
- const end = batch.image_start + batch.image_count;
- for (g.prepared_images.items[batch.image_start..end]) |prepared| {
- c.SDL_BindGPUGraphicsPipeline(pass, if (prepared.premultiplied) g.addon_pipeline.? else g.image_pipeline);
- const clip = imageScissor(g, prepared.place);
- if (clip.w > 0 and clip.h > 0) {
- c.SDL_SetGPUScissor(pass, &clip);
- const sampler = c.SDL_GPUTextureSamplerBinding{ .texture = prepared.texture, .sampler = g.linear_sampler };
- c.SDL_BindGPUFragmentSamplers(pass, 0, &sampler, 1);
- const binding = c.SDL_GPUBufferBinding{ .buffer = g.image_vbuf.?, .offset = idx * @sizeOf(ImageInstance) };
- c.SDL_BindGPUVertexBuffers(pass, 0, &binding, 1);
- c.SDL_DrawGPUPrimitives(pass, 6, 1, 0, 0);
- }
- idx += 1;
- }
- std.debug.assert(idx == batch.image_start + batch.image_count);
- // Back to the whole target: what draws after a picture may run on past
- // the grid, as a rule and a band do.
- c.SDL_SetGPUScissor(pass, &whole);
-}
-
fn renderFrame(
g: *Gui,
gpa: std.mem.Allocator,
@@ -4475,14 +4055,14 @@ fn renderFrame(
if (cursor) |value| _ = c.SDL_SetCursor(value);
}
g.words.memo = .{}; // positional, and this frame's cells are new
- const cmd = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return false;
+ const cmd = g.cells.begin() orelse return false;
var command_consumed = false;
defer if (!command_consumed) {
- _ = c.SDL_SubmitGPUCommandBuffer(cmd);
+ Cells.submit(cmd);
};
- const frame_target = try acquireTarget(g, cmd, @as(u32, surface.cols) * g.cell_w + g.capture_pad, @as(u32, surface.rows) * g.cell_h + g.capture_pad) orelse {
+ const frame_target = try g.present.acquireTarget(cmd, g.window, @as(u32, surface.cols) * g.cell_w + g.capture_pad, @as(u32, surface.rows) * g.cell_h + g.capture_pad) orelse {
command_consumed = true;
- _ = c.SDL_SubmitGPUCommandBuffer(cmd);
+ Cells.submit(cmd);
return false;
};
const target = frame_target.texture;
@@ -4523,7 +4103,7 @@ fn renderFrame(
core.frames.caret = caretRow(g, surface, now) orelse 0;
const cursors_shown = !quad_mode;
var overlay_count = buildOverlay(g, core.settings.pet, core.settings.jump_trail, surface, now, sw, sh);
- if (overlay_count != 0 and !uploadOverlayGpu(g, cmd, overlay_count))
+ if (overlay_count != 0 and !g.cells.uploadOverlay(cmd, g.overlay_vertices[0..overlay_count]))
overlay_count = 0;
if (!prepareNativeImages(g, gpa, cmd, surface, &groups, sw, sh)) {
g.prepared_images.clearRetainingCapacity();
@@ -4542,16 +4122,12 @@ fn renderFrame(
const page = chrome.page orelse bg_default;
const background_opacity = backgroundOpacity(g.applied_window_opacity);
- var color_target = std.mem.zeroes(c.SDL_GPUColorTargetInfo);
- color_target.texture = target;
- color_target.clear_color = .{
+ const clear: c.SDL_FColor = .{
.r = @as(f32, @floatFromInt(page[0])) / 255.0 * background_opacity,
.g = @as(f32, @floatFromInt(page[1])) / 255.0 * background_opacity,
.b = @as(f32, @floatFromInt(page[2])) / 255.0 * background_opacity,
.a = background_opacity,
};
- color_target.load_op = c.SDL_GPU_LOADOP_CLEAR;
- color_target.store_op = c.SDL_GPU_STOREOP_STORE;
var shifted: u32 = 0;
var row: u16 = 0;
@@ -4590,14 +4166,11 @@ fn renderFrame(
// The shifted rows of a scroll: its body, a glide's rows past it, and
// a body layer's rows past the grid's.
const capacity = std.math.add(u32, cell_total, 3 * cells + decor_len) catch return error.GpuCapacity;
- try growInstances(g, &g.vbuf, &g.vxfer, &g.vbuf_cells, capacity, @sizeOf(CellInstance));
-
- const vptr: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, g.vxfer.?, false) orelse {
+ const instances = try g.cells.mapCells(capacity) orelse {
command_consumed = true;
- _ = c.SDL_SubmitGPUCommandBuffer(cmd);
+ Cells.submit(cmd);
return false;
- });
- const instances: [*]CellInstance = @ptrCast(@alignCast(vptr));
+ };
const cursor_idx: u32 = if (surface.cursor) |cu| @as(u32, cu.y) * surface.cols + cu.x else cells;
const cursor_bar = if (surface.cursor) |cu| cu.bar else false;
row = 0;
@@ -4648,98 +4221,36 @@ fn renderFrame(
const held: u16 = if (scrolling) |id| if (core.panes[id]) |pane| pane.context_rows else 0 else 0;
shifted = emitScrollRows(g, instances, cell_total, surface, layout, win_w, win_h, page, held);
@memcpy(instances[cell_total + shifted ..][0..decor_len], g.decor.items);
- c.SDL_UnmapGPUTransferBuffer(g.device, g.vxfer.?);
-
- if (g.atlas_dirty_top < g.atlas_dirty_bottom) uploadAtlas(g, cmd);
-
- const copy = c.SDL_BeginGPUCopyPass(cmd);
- const src = c.SDL_GPUTransferBufferLocation{ .transfer_buffer = g.vxfer.?, .offset = 0 };
- const dst = c.SDL_GPUBufferRegion{ .buffer = g.vbuf.?, .offset = 0, .size = (cell_total + shifted + decor_len) * @sizeOf(CellInstance) };
- c.SDL_UploadToGPUBuffer(copy, &src, &dst, false);
- c.SDL_EndGPUCopyPass(copy);
+ g.cells.uploadCells(cmd, cell_total + shifted + decor_len, &g.atlas);
}
build_zone.end();
building = false;
if (frame_probe) |probe| probe.zone(.gui_build, probe_build);
- const rp = c.SDL_BeginGPURenderPass(cmd, &color_target, 1, null);
- pushLayerOpacity(cmd, rp, background_opacity);
- const whole = c.SDL_Rect{ .x = 0, .y = 0, .w = @intCast(sw), .h = @intCast(sh) };
- const decor_base = cell_total + shifted;
- for (groups.items[0..groups.len], 0..) |group, index| {
- const has_shifted = index == 0 and shifted != 0;
- if ((group.cell_count != 0 or has_shifted) and g.vbuf != null) {
- c.SDL_BindGPUGraphicsPipeline(rp, g.pipeline);
- const samp_binding = c.SDL_GPUTextureSamplerBinding{ .texture = g.atlas_tex, .sampler = g.atlas_sampler };
- c.SDL_BindGPUFragmentSamplers(rp, 0, &samp_binding, 1);
- if (group.cell_count != 0) {
- const binding = c.SDL_GPUBufferBinding{ .buffer = g.vbuf.?, .offset = group.cell_start * @sizeOf(CellInstance) };
- c.SDL_BindGPUVertexBuffers(rp, 0, &binding, 1);
- c.SDL_DrawGPUPrimitives(rp, 6, group.cell_count, 0, 0);
- }
- if (has_shifted) {
- const clip = scrollScissor(g, layout, sw, sh);
- c.SDL_SetGPUScissor(rp, &clip);
- const binding = c.SDL_GPUBufferBinding{ .buffer = g.vbuf.?, .offset = cell_total * @sizeOf(CellInstance) };
- c.SDL_BindGPUVertexBuffers(rp, 0, &binding, 1);
- c.SDL_DrawGPUPrimitives(rp, 6, shifted, 0, 0);
- c.SDL_SetGPUScissor(rp, &whole);
- }
- }
- if (group.image_count != 0) drawNativeImagesGpu(g, rp, group, whole);
- if (group.decor_count != 0 and g.vbuf != null) {
- c.SDL_BindGPUGraphicsPipeline(rp, g.decor_pipeline);
- // Ink keeps its colour at any WindowOpacity.
- pushLayerOpacity(cmd, rp, if (index == groups.ink) 1 else background_opacity);
- const binding = c.SDL_GPUBufferBinding{ .buffer = g.vbuf.?, .offset = (decor_base + group.decor_start) * @sizeOf(CellInstance) };
- c.SDL_BindGPUVertexBuffers(rp, 0, &binding, 1);
- c.SDL_DrawGPUPrimitives(rp, 6, group.decor_count, 0, 0);
- }
- }
- drawOverlayGpu(g, cmd, rp, overlay_count);
- c.SDL_EndGPURenderPass(rp);
+ // Drawn only over a scroll's shifted rows (scrollScissor asks a scroll).
+ const scroll_clip = if (shifted != 0) scrollScissor(g, layout, sw, sh) else std.mem.zeroes(c.SDL_Rect);
+ g.cells.record(cmd, target, sw, sh, clear, background_opacity, groups.items[0..groups.len], groups.ink, cell_total, shifted, scroll_clip, overlay_count);
command_consumed = true;
return finishFrame(g, gpa, cmd, frame_target);
}
-const Target = struct { texture: *c.SDL_GPUTexture, w: u32, h: u32 };
-
-/// What this frame draws into: the capture texture in test mode (the grid's
-/// size plus PARDES_TEST_PAD) or with a soft presenter, else the swapchain's
-/// image; null when there is none to be had this time.
-fn acquireTarget(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, capture_w: u32, capture_h: u32) !?Target {
- if (g.capture) {
- if (capture_w == 0 or capture_h == 0) return null;
- try ensureCaptureTexture(g, capture_w, capture_h);
- return .{ .texture = g.capture_tex.?, .w = capture_w, .h = capture_h };
- }
- if (g.soft_present) {
- var pw: c_int = 0;
- var ph: c_int = 0;
- if (!c.SDL_GetWindowSizeInPixels(g.window, &pw, &ph) or pw <= 0 or ph <= 0) return null;
- try ensureCaptureTexture(g, @intCast(pw), @intCast(ph));
- return .{ .texture = g.capture_tex.?, .w = @intCast(pw), .h = @intCast(ph) };
- }
- var swap_tex: ?*c.SDL_GPUTexture = null;
- var sw: u32 = 0;
- var sh: u32 = 0;
- if (!c.SDL_AcquireGPUSwapchainTexture(cmd, g.window, &swap_tex, &sw, &sh)) return null;
- // A busy swapchain skips the frame.
- return .{ .texture = swap_tex orelse return null, .w = sw, .h = sh };
-}
-
/// Submits the frame: captured, handed to the soft presenter, or presented.
-fn finishFrame(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer, target: Target) !bool {
- if (g.capture) {
+fn finishFrame(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer, target: Present.Target) !bool {
+ if (g.present.capture) {
try captureFrame(g, gpa, cmd, target.texture, target.w, target.h);
return true;
}
- if (g.soft_present) {
- try softPresentFrame(g, cmd, target.texture, target.w, target.h);
- return true;
- }
- return c.SDL_SubmitGPUCommandBuffer(cmd);
+ var took: Present.Timings = .{};
+ const presented = try g.present.finishFrame(cmd, target, &captureSeries, &took);
+ // A soft present's wait for the GPU, its upload of the frame and its flip.
+ if (g.present.soft_present) if (frame_probe) |probe| {
+ const now = monoNs();
+ probe.zone(.gui_wait, now -| took.wait_ns);
+ probe.zone(.gui_upload, now -| took.upload_ns);
+ probe.zone(.gui_flip, now -| took.flip_ns);
+ };
+ return presented;
}
const ResolvedCell = struct {
@@ -5016,9 +4527,9 @@ fn emitSurfaceCell(
if (grip) {
// A grip is one glyph centered across the gutter, not text: it is
// looked up by its codepoint's glyph, never shaped.
- const drawn = glyphForCodepoint(g, cellCodepoint(glyph));
- const cached = cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .tagline, .decoration = GlyphDecoration.fromCell(glyph), .centered = true });
- const slot = cached orelse g.space_slot;
+ const drawn = g.atlas.glyphForCodepoint(cellCodepoint(glyph));
+ const cached = cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .tagline, .decoration = @bitCast(GlyphDecoration.fromCell(glyph)), .centered = true });
+ const slot = cached orelse g.atlas.space_slot;
const b = button.?;
const center = (b[0] + b[2]) / 2 - @as(f32, @floatFromInt(col - offset)) * body_layout.w;
const shift: f32 = if (cached != null) @as(f32, @floatFromInt(@as(u32, offset) * g.cell_w)) + @as(f32, @floatFromInt(config.GUTTER * g.cell_w)) / 2 - center else 0;
@@ -5053,10 +4564,10 @@ fn emitSurfaceCell(
// Over it, only its own glyph; the band round it and the ring
// are decor (gripDecor).
if (here.pane_grip and !grip) {
- instances[next.*].u0 = @as(f32, @floatFromInt(g.space_slot.u)) / atlas_w;
+ instances[next.*].u0 = @as(f32, @floatFromInt(g.atlas.space_slot.u)) / atlas_w;
instances[next.*].u1 = instances[next.*].u0 + @as(f32, @floatFromInt(g.cell_w)) / atlas_w;
- instances[next.*].v0 = @as(f32, @floatFromInt(g.space_slot.v)) / atlas_h;
- instances[next.*].v1 = @as(f32, @floatFromInt(g.space_slot.v + g.tagline_height)) / atlas_h;
+ instances[next.*].v0 = @as(f32, @floatFromInt(g.atlas.space_slot.v)) / atlas_h;
+ instances[next.*].v1 = @as(f32, @floatFromInt(g.atlas.space_slot.v + g.tagline_height)) / atlas_h;
}
// Its ground is the fill again.
instances[next.*].br = base.br;
@@ -5150,11 +4661,11 @@ fn refitFont(g: *Gui, core: ?*pardes.Pardes) void {
var cw: c_int = 10;
var chh: c_int = 20;
var asc: c_int = 16;
- c.ui_font_cell_metrics(g.font, g.px, &cw, &chh, &asc);
+ g.atlas.cellMetrics(g.px, &cw, &chh, &asc);
g.cell_w = @intCast(@max(cw, 1));
g.cell_h = @intCast(@max(chh, 1));
g.ascent = @intCast(@max(asc, 1));
- const tagline = taglineRaster(g.font, g.px, g.cell_w, g.cell_h, g.tagline_percent);
+ const tagline = taglineRaster(&g.atlas, g.px, g.cell_w, g.cell_h, g.tagline_percent);
g.tagline_px = tagline.px;
g.tagline_width = tagline.width;
g.tagline_baseline = tagline.baseline;
@@ -5172,14 +4683,8 @@ fn refitFont(g: *Gui, core: ?*pardes.Pardes) void {
// The first cell of the cleared atlas stays blank: the space slot.
fn resetGlyphAtlas(g: *Gui) void {
- g.glyphs.clearRetainingCapacity();
+ g.atlas.reset(g.cell_w);
g.words.clear();
- @memset(g.atlas_stage, 0);
- g.space_slot = .{ .u = 0, .v = 0 };
- g.pen_x = g.cell_w;
- g.pen_y = 0;
- g.atlas_dirty_top = 0;
- g.atlas_dirty_bottom = atlas_h;
}
fn syncTaglineFont(g: *Gui, core: *pardes.Pardes) void {
@@ -5192,7 +4697,7 @@ fn syncTaglineFont(g: *Gui, core: *pardes.Pardes) void {
fn fitTaglineFont(g: *Gui, percent: u8) bool {
if (percent == g.tagline_percent) return false;
g.tagline_percent = percent;
- const tagline = taglineRaster(g.font, g.px, g.cell_w, g.cell_h, percent);
+ const tagline = taglineRaster(&g.atlas, g.px, g.cell_w, g.cell_h, percent);
g.tagline_px = tagline.px;
g.tagline_width = tagline.width;
g.tagline_baseline = tagline.baseline;
@@ -5289,19 +4794,18 @@ fn cellSlot(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role:
return words.slots.items[memo.slots + at - memo.start];
var here = wordCell(&line[at]);
// An underlined or struck-out space is a glyph of its own: it draws its line.
- if (here.cp == ' ' and !here.decoration.drawsBlank()) return g.space_slot;
+ if (here.cp == ' ' and !here.decoration.drawsBlank()) return g.atlas.space_slot;
if (ruleArms(here.cp) != null)
- return cachedGlyph(g, .{ .face = 0, .glyph = here.cp, .role = role, .rule = true }) orelse g.space_slot;
- const gpa = g.glyphs.allocator;
+ return cachedGlyph(g, .{ .face = 0, .glyph = here.cp, .role = @fromBackingInt(@intCast(@backingInt(role))), .rule = true }) orelse g.atlas.space_slot;
+ const gpa = g.atlas.glyphs.allocator;
const cell_key: Words.CellKey = .{ .cp = @intCast(here.cp), .role = role, .decoration = here.decoration };
- const known = words.cells.getOrPut(gpa, cell_key) catch return g.space_slot;
+ const known = words.cells.getOrPut(gpa, cell_key) catch return g.atlas.space_slot;
if (!known.found_existing) {
- const drawn = glyphForCodepoint(g, here.cp);
- const font = if (drawn.face == 0) g.font else g.fallbacks[drawn.face - 1].?.face;
- known.value_ptr.* = if (role == .body and c.ui_font_substitutes(font, drawn.glyph) != 0)
+ const drawn = g.atlas.glyphForCodepoint(here.cp);
+ known.value_ptr.* = if (role == .body and g.atlas.substitutes(drawn.face, drawn.glyph))
Words.shape_slot
else
- cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = role, .decoration = here.decoration }) orelse g.space_slot;
+ cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = @fromBackingInt(@intCast(@backingInt(role))), .decoration = @bitCast(here.decoration) }) orelse g.atlas.space_slot;
}
const plain = known.value_ptr.*;
if (!std.meta.eql(plain, Words.shape_slot)) return plain;
@@ -5319,7 +4823,7 @@ fn cellSlot(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role:
const text_start = words.text.items.len;
var end = start;
while (true) {
- words.text.append(gpa, here.cp) catch return g.space_slot;
+ words.text.append(gpa, here.cp) catch return g.atlas.space_slot;
end += 1;
if (end == line.len) break;
const next = wordCell(&line[end]);
@@ -5349,27 +4853,26 @@ fn cellSlot(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role:
const n = text.len;
words.slots.ensureUnusedCapacity(gpa, n) catch {
words.text.shrinkRetainingCapacity(text_start);
- return g.space_slot;
+ return g.atlas.space_slot;
};
words.shaped.resize(gpa, n) catch {
words.text.shrinkRetainingCapacity(text_start);
- return g.space_slot;
+ return g.atlas.space_slot;
};
const shaped = words.shaped.items;
var run_start: usize = 0;
- var face = glyphForCodepoint(g, text[0]).face;
+ var face = g.atlas.glyphForCodepoint(text[0]).face;
while (run_start < n) {
var run_end = run_start + 1;
var next_face = face;
while (run_end < n) : (run_end += 1) {
- next_face = glyphForCodepoint(g, text[run_end]).face;
+ next_face = g.atlas.glyphForCodepoint(text[run_end]).face;
if (next_face != face) break;
}
- const run_font = if (face == 0) g.font else g.fallbacks[face - 1].?.face;
- c.ui_font_shape(run_font, g.px, @intCast(g.cell_w), text[run_start..].ptr, @intCast(run_end - run_start), shaped[run_start..].ptr);
+ g.atlas.shape(face, g.px, g.cell_w, text[run_start..run_end], shaped[run_start..]);
for (shaped[run_start..run_end]) |cell| {
- const key: GlyphKey = .{ .face = face, .glyph = cell.glyph, .role = .body, .decoration = decoration, .lead = @intCast(cell.lead), .span = @intCast(cell.span) };
- const slot: Slot = if (cachedGlyph(g, key)) |strip| .{ .u = strip.u + g.cell_w * cell.slice, .v = strip.v } else g.space_slot;
+ const key: GlyphKey = .{ .face = face, .glyph = cell.glyph, .role = .body, .decoration = @bitCast(decoration), .lead = @intCast(cell.lead), .span = @intCast(cell.span) };
+ const slot: Slot = if (cachedGlyph(g, key)) |strip| .{ .u = strip.u + g.cell_w * cell.slice, .v = strip.v } else g.atlas.space_slot;
words.slots.appendAssumeCapacity(slot);
}
run_start = run_end;
@@ -5386,20 +4889,10 @@ fn cellSlot(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role:
fn testGui(cell_w: u32, cell_h: u32, tagline_width: u32, tagline_height: u32) Gui {
return .{
.window = undefined,
- .device = undefined,
- .swapchain_format = undefined,
- .pipeline = undefined,
- .decor_pipeline = undefined,
- .overlay_pipeline = undefined,
- .image_pipeline = undefined,
- .atlas_tex = undefined,
- .atlas_sampler = undefined,
- .linear_sampler = undefined,
- .atlas_xfer = undefined,
- .overlay_vbuf = undefined,
- .overlay_vxfer = undefined,
+ .present = undefined,
+ .cells = undefined,
.overlay_vertices = &.{},
- .font = undefined,
+ .atlas = .{ .font = undefined, .atlas_stage = &.{}, .glyphs = undefined },
.px = 0,
.tagline_px = 0,
.tagline_percent = 0,
@@ -5409,377 +4902,26 @@ fn testGui(cell_w: u32, cell_h: u32, tagline_width: u32, tagline_height: u32) Gu
.cell_h = cell_h,
.ascent = 0,
.tagline_baseline = 0,
- .atlas_stage = &.{},
- .glyphs = undefined,
};
}
-/// The atlas slot of `key`, rasterized on first use. A strip is `span` cells
-/// wide (a grip glyph GUTTER cells, centered); a cell samples its slice of it.
+/// The atlas slot of `key` (Atlas.cachedGlyph), rasterized on first use at
+/// the window's sizes, a grip glyph GUTTER cells wide, its rules and
+/// decorations a logical pixel thick (dp): a raster is the frame probe's.
/// Null when the atlas is full.
fn cachedGlyph(g: *Gui, key: GlyphKey) ?Slot {
- if (g.glyphs.get(key)) |s| return s;
- const slot_w = g.cell_w * @as(u32, if (key.centered) config.GUTTER else key.span);
- if (g.pen_x + slot_w > atlas_w) {
- g.pen_x = 0;
- g.pen_y += g.cell_h;
- }
- if (g.pen_y + g.cell_h > atlas_h) return null; // atlas full: fall back
+ if (g.atlas.glyphs.get(key)) |s| return s;
const probe_raster = monoNs();
- defer if (frame_probe) |probe| {
+ const body: Atlas.Size = .{ .px = g.px, .cell_w = g.cell_w, .height = g.cell_h, .baseline = g.ascent };
+ const tagline: Atlas.Size = .{ .px = g.tagline_px, .cell_w = g.tagline_width, .height = g.tagline_height, .baseline = g.tagline_baseline };
+ const s = g.atlas.cachedGlyph(key, body, tagline, config.GUTTER, @intFromFloat(dp(1))) orelse return null;
+ if (frame_probe) |probe| {
probe.zone(.gui_raster, probe_raster);
probe.rastered +|= 1;
- };
- const s = Slot{ .u = g.pen_x, .v = g.pen_y };
- const out = g.atlas_stage.ptr + @as(usize, s.v) * atlas_w + s.u;
- const face = if (key.face == 0) g.font else g.fallbacks[key.face - 1].?.face;
- const px = if (key.role == .tagline) g.tagline_px else g.px;
- const baseline = if (key.role == .tagline) g.tagline_baseline else g.ascent;
- const cell_w = if (key.role == .tagline) g.tagline_width else g.cell_w;
- const raster_w = if (key.centered) slot_w else cell_w * key.span;
- const raster_h = if (key.role == .tagline) g.tagline_height else g.cell_h;
- const bold = @intFromBool(key.decoration.bold);
- if (key.rule) {
- drawRule(out, atlas_w, raster_w, raster_h, ruleArms(key.glyph).?);
- } 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);
- if (key.centered) centerGlyphInk(out, raster_w, raster_h);
- g.atlas_dirty_top = @min(g.atlas_dirty_top, s.v);
- g.atlas_dirty_bottom = @max(g.atlas_dirty_bottom, s.v + raster_h);
- g.glyphs.put(key, s) catch return null;
- g.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: GlyphDecoration) 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 (dp).
- const t: usize = @intFromFloat(dp(1));
- 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);
- }
-}
-
-/// Uploads only the atlas rows drawn into since the last upload. Glyphs fill
-/// the atlas pen-style, a band of rows at a time, so new glyphs are a band a
-/// cell or two tall, not the whole 4 MB texture. The band sits at the same
-/// offset in the transfer buffer as in the stage, and the texture keeps the
-/// rows outside it.
-fn uploadAtlas(g: *Gui, cmd: *c.SDL_GPUCommandBuffer) void {
- const top = g.atlas_dirty_top;
- const rows = g.atlas_dirty_bottom - top;
- const ptr = c.SDL_MapGPUTransferBuffer(g.device, g.atlas_xfer, false) orelse return;
- const dst: [*]u8 = @ptrCast(ptr);
- @memcpy(dst[top * atlas_w ..][0 .. rows * atlas_w], g.atlas_stage[top * atlas_w ..][0 .. rows * atlas_w]);
- c.SDL_UnmapGPUTransferBuffer(g.device, g.atlas_xfer);
-
- const copy = c.SDL_BeginGPUCopyPass(cmd);
- const src = c.SDL_GPUTextureTransferInfo{ .transfer_buffer = g.atlas_xfer, .offset = top * atlas_w, .pixels_per_row = atlas_w, .rows_per_layer = rows };
- const dstregion = c.SDL_GPUTextureRegion{ .texture = g.atlas_tex, .mip_level = 0, .layer = 0, .x = 0, .y = top, .z = 0, .w = atlas_w, .h = rows, .d = 1 };
- c.SDL_UploadToGPUTexture(copy, &src, &dstregion, false);
- c.SDL_EndGPUCopyPass(copy);
- g.atlas_dirty_top = atlas_h;
- g.atlas_dirty_bottom = 0;
-}
-
-/// A vertex buffer and its upload buffer holding at least `needed`
-/// elements of `stride` bytes: those there when they do, else twice as
-/// many again until they would (the old ones let go).
-fn growInstances(g: *Gui, buffer: *?*c.SDL_GPUBuffer, transfer: *?*c.SDL_GPUTransferBuffer, capacity: *u32, needed: u32, stride: u32) !void {
- if (needed <= capacity.* and buffer.* != null and transfer.* != null) return;
- var grown = @max(@as(u32, 1), capacity.*);
- while (grown < needed) grown = std.math.mul(u32, grown, 2) catch return error.GpuCapacity;
- const size = std.math.mul(u32, grown, stride) catch return error.GpuCapacity;
- var vb_info = c.SDL_GPUBufferCreateInfo{ .usage = c.SDL_GPU_BUFFERUSAGE_VERTEX, .size = size, .props = 0 };
- const next_buffer = c.SDL_CreateGPUBuffer(g.device, &vb_info) orelse return error.GpuCreate;
- errdefer c.SDL_ReleaseGPUBuffer(g.device, next_buffer);
- var xf_info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = size, .props = 0 };
- const next_transfer = c.SDL_CreateGPUTransferBuffer(g.device, &xf_info) orelse return error.GpuCreate;
- if (buffer.*) |old| c.SDL_ReleaseGPUBuffer(g.device, old);
- if (transfer.*) |old| c.SDL_ReleaseGPUTransferBuffer(g.device, old);
- buffer.* = next_buffer;
- transfer.* = next_transfer;
- capacity.* = grown;
-}
-
-/// One vertex buffer of a pipeline: `pitch` bytes an element, read per
-/// vertex or per instance through `attrs`.
-const VertexInput = struct { pitch: u32, rate: c.SDL_GPUVertexInputRate, attrs: []const c.SDL_GPUVertexAttribute };
-
-/// The cells' and the decor's instances (ui.vert.glsl).
-const cell_input: VertexInput = .{ .pitch = @sizeOf(CellInstance), .rate = c.SDL_GPU_VERTEXINPUTRATE_INSTANCE, .attrs = &.{
- .{ .location = 0, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(CellInstance, "x0") },
- .{ .location = 1, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(CellInstance, "u0") },
- .{ .location = 2, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT3, .offset = @offsetOf(CellInstance, "fr") },
- .{ .location = 3, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT3, .offset = @offsetOf(CellInstance, "br") },
- .{ .location = 4, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_UINT, .offset = @offsetOf(CellInstance, "effect") },
- .{ .location = 5, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(CellInstance, "clip_x0") },
-} };
-
-const overlay_input: VertexInput = .{ .pitch = @sizeOf(OverlayVertex), .rate = c.SDL_GPU_VERTEXINPUTRATE_VERTEX, .attrs = &.{
- .{ .location = 0, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2, .offset = @offsetOf(OverlayVertex, "x") },
- .{ .location = 1, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(OverlayVertex, "r") },
-} };
-
-const image_input: VertexInput = .{ .pitch = @sizeOf(ImageInstance), .rate = c.SDL_GPU_VERTEXINPUTRATE_INSTANCE, .attrs = &.{
- .{ .location = 0, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(ImageInstance, "x0") },
- .{ .location = 1, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(ImageInstance, "u0") },
-} };
-
-/// A pipeline drawing triangles into `color_format`: `vert`, and `frag`
-/// with its samplers and uniform buffers, over one vertex buffer of
-/// `input` (none: the post chain's triangle over the whole frame).
-pub fn makePipeline(
- device: *c.SDL_GPUDevice,
- color_format: c.SDL_GPUTextureFormat,
- vert: []const u8,
- frag: []const u8,
- samplers: u32,
- uniforms: u32,
- input: ?VertexInput,
- blend: c.SDL_GPUColorTargetBlendState,
-) !*c.SDL_GPUGraphicsPipeline {
- const vs = try makeShader(device, vert, c.SDL_GPU_SHADERSTAGE_VERTEX, 0, 0);
- defer c.SDL_ReleaseGPUShader(device, vs);
- const fs = try makeShader(device, frag, c.SDL_GPU_SHADERSTAGE_FRAGMENT, samplers, uniforms);
- defer c.SDL_ReleaseGPUShader(device, fs);
- var col_desc = c.SDL_GPUColorTargetDescription{ .format = color_format, .blend_state = blend };
- var vbuf_desc: c.SDL_GPUVertexBufferDescription = undefined;
- var info = std.mem.zeroes(c.SDL_GPUGraphicsPipelineCreateInfo);
- info.vertex_shader = vs;
- info.fragment_shader = fs;
- info.primitive_type = c.SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
- if (input) |in| {
- vbuf_desc = .{ .slot = 0, .pitch = in.pitch, .input_rate = in.rate, .instance_step_rate = 0 };
- info.vertex_input_state = .{
- .vertex_buffer_descriptions = &vbuf_desc,
- .num_vertex_buffers = 1,
- .vertex_attributes = in.attrs.ptr,
- .num_vertex_attributes = @intCast(in.attrs.len),
- };
- }
- info.rasterizer_state.fill_mode = c.SDL_GPU_FILLMODE_FILL;
- info.rasterizer_state.cull_mode = c.SDL_GPU_CULLMODE_NONE;
- info.multisample_state.sample_count = c.SDL_GPU_SAMPLECOUNT_1;
- info.target_info = .{ .color_target_descriptions = &col_desc, .num_color_targets = 1 };
- return c.SDL_CreateGPUGraphicsPipeline(device, &info) orelse error.GpuCreate;
-}
-
-fn backgroundLayerBlend() c.SDL_GPUColorTargetBlendState {
- var blend = std.mem.zeroes(c.SDL_GPUColorTargetBlendState);
- blend.src_color_blendfactor = c.SDL_GPU_BLENDFACTOR_SRC_ALPHA;
- blend.dst_color_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
- blend.color_blend_op = c.SDL_GPU_BLENDOP_ADD;
- blend.src_alpha_blendfactor = c.SDL_GPU_BLENDFACTOR_CONSTANT_COLOR;
- blend.dst_alpha_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
- blend.alpha_blend_op = c.SDL_GPU_BLENDOP_ADD;
- blend.enable_blend = true;
- return blend;
-}
-
-fn makeShader(device: *c.SDL_GPUDevice, code: []const u8, stage: c.SDL_GPUShaderStage, n_samplers: u32, n_uniform_buffers: u32) !*c.SDL_GPUShader {
- var info = std.mem.zeroes(c.SDL_GPUShaderCreateInfo);
- info.code = code.ptr;
- info.code_size = code.len;
- info.entrypoint = "main";
- info.format = c.SDL_GPU_SHADERFORMAT_SPIRV;
- info.stage = stage;
- info.num_samplers = n_samplers;
- info.num_uniform_buffers = n_uniform_buffers;
- return c.SDL_CreateGPUShader(device, &info) orelse error.GpuCreate;
-}
-
-/// A 2D texture of one level, one layer and one sample.
-pub fn texture2d(device: *c.SDL_GPUDevice, format: c.SDL_GPUTextureFormat, usage: c.SDL_GPUTextureUsageFlags, width: u32, height: u32) ?*c.SDL_GPUTexture {
- var info = std.mem.zeroes(c.SDL_GPUTextureCreateInfo);
- info.type = c.SDL_GPU_TEXTURETYPE_2D;
- info.format = format;
- info.usage = usage;
- info.width = width;
- info.height = height;
- info.layer_count_or_depth = 1;
- info.num_levels = 1;
- info.sample_count = c.SDL_GPU_SAMPLECOUNT_1;
- return c.SDL_CreateGPUTexture(device, &info);
-}
-
-fn ensureCaptureTexture(g: *Gui, width: u32, height: u32) !void {
- if (g.capture_tex != null and g.capture_tex_w == width and g.capture_tex_h == height) return;
- const next = texture2d(g.device, g.swapchain_format, c.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET, width, height) orelse return error.GpuCreate;
- if (g.capture_tex) |texture| c.SDL_ReleaseGPUTexture(g.device, texture);
- g.capture_tex = next;
- g.capture_tex_w = width;
- g.capture_tex_h = height;
-}
-
-fn softTargetFormat(device: *c.SDL_GPUDevice) c.SDL_GPUTextureFormat {
- const candidates = [_]c.SDL_GPUTextureFormat{
- c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM,
- c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM,
- };
- for (candidates) |format| {
- if (c.SDL_GPUTextureSupportsFormat(
- device,
- format,
- c.SDL_GPU_TEXTURETYPE_2D,
- c.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | c.SDL_GPU_TEXTUREUSAGE_SAMPLER,
- )) return format;
- }
- return c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM;
-}
-
-fn softPixelFormat(format: c.SDL_GPUTextureFormat) ?c.SDL_PixelFormat {
- return switch (format) {
- c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM,
- c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM_SRGB,
- => c.SDL_PIXELFORMAT_ARGB8888,
- c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM,
- c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM_SRGB,
- => c.SDL_PIXELFORMAT_ABGR8888,
- else => null,
- };
-}
-
-fn ensureSoftTexture(g: *Gui, width: u32, height: u32) !*c.SDL_Texture {
- if (g.soft_texture) |texture| {
- if (g.soft_tex_w == width and g.soft_tex_h == height) return texture;
- c.SDL_DestroyTexture(texture);
- g.soft_texture = null;
- }
- const renderer = g.soft_renderer orelse return error.GpuCreate;
- const pixel_format = softPixelFormat(g.swapchain_format) orelse return error.UnsupportedCaptureFormat;
- const next = c.SDL_CreateTexture(
- renderer,
- pixel_format,
- c.SDL_TEXTUREACCESS_STREAMING,
- @intCast(width),
- @intCast(height),
- ) orelse return error.GpuCreate;
- _ = c.SDL_SetTextureScaleMode(next, c.SDL_SCALEMODE_NEAREST);
- _ = c.SDL_SetTextureBlendMode(next, c.SDL_BLENDMODE_NONE);
- g.soft_texture = next;
- g.soft_tex_w = width;
- g.soft_tex_h = height;
- return next;
-}
-
-/// The frame in `target`, `size` bytes, copied down into `capture_xfer`
-/// (grown to it first) by `cmd`, which the caller submits and waits for.
-/// With no buffer to be had the command buffer is submitted as it is.
-fn downloadTarget(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTexture, sw: u32, sh: u32, size: u32) !*c.SDL_GPUTransferBuffer {
- if (g.capture_xfer == null or g.capture_xfer_size < size) {
- var info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_DOWNLOAD, .size = size, .props = 0 };
- const next = c.SDL_CreateGPUTransferBuffer(g.device, &info) orelse {
- _ = c.SDL_SubmitGPUCommandBuffer(cmd);
- return error.GpuCreate;
- };
- if (g.capture_xfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(g.device, transfer);
- g.capture_xfer = next;
- g.capture_xfer_size = size;
- }
- const xfer = g.capture_xfer.?;
- const copy = c.SDL_BeginGPUCopyPass(cmd);
- const src = c.SDL_GPUTextureRegion{ .texture = target, .mip_level = 0, .layer = 0, .x = 0, .y = 0, .z = 0, .w = sw, .h = sh, .d = 1 };
- const dst = c.SDL_GPUTextureTransferInfo{ .transfer_buffer = xfer, .offset = 0, .pixels_per_row = sw, .rows_per_layer = sh };
- c.SDL_DownloadFromGPUTexture(copy, &src, &dst);
- c.SDL_EndGPUCopyPass(copy);
- return xfer;
-}
-
-fn softPresentFrame(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTexture, sw: u32, sh: u32) !void {
- const bpp = c.SDL_GPUTextureFormatTexelBlockSize(g.swapchain_format);
- const size = c.SDL_CalculateGPUTextureFormatSize(g.swapchain_format, sw, sh, 1);
- if (size == 0 or bpp != 4) {
- _ = c.SDL_SubmitGPUCommandBuffer(cmd);
- return error.UnsupportedCaptureFormat;
- }
- const xfer = try downloadTarget(g, cmd, target, sw, sh, size);
-
- const fence = c.SDL_SubmitGPUCommandBufferAndAcquireFence(cmd) orelse return error.GpuSubmit;
- defer c.SDL_ReleaseGPUFence(g.device, fence);
- var fences = [_]*c.SDL_GPUFence{fence};
- const probe_wait = monoNs();
- if (!c.SDL_WaitForGPUFences(g.device, true, &fences, 1)) return error.GpuSubmit;
- if (frame_probe) |probe| probe.zone(.gui_wait, probe_wait);
-
- const mapped = c.SDL_MapGPUTransferBuffer(g.device, xfer, false) orelse return error.GpuMap;
- defer c.SDL_UnmapGPUTransferBuffer(g.device, xfer);
-
- const texture = try ensureSoftTexture(g, sw, sh);
- const renderer = g.soft_renderer orelse return error.GpuCreate;
- const probe_upload = monoNs();
- defer if (frame_probe) |probe| probe.zone(.gui_upload, probe_upload);
- if (!c.SDL_UpdateTexture(texture, null, mapped, @intCast(sw * bpp))) return error.GpuMap;
- // PARDES_FRAMES_CAPTURE: every presented frame's pixels as they went
- // out, and when, for a recording at the frames' own times. One write a
- // frame; nothing else.
- if (frame_capture_dir) |dir| captureSeries(dir, @as([*]const u8, @ptrCast(mapped))[0..size], sw, sh);
- // The cell shader already produced premultiplied backgrounds with opaque
- // foreground ink. Copy that alpha unchanged; never modulate the full frame.
- _ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_NONE);
- _ = c.SDL_SetRenderDrawColor(renderer, 0, 0, 0, if (g.surface_opacity) 0 else 255);
- _ = c.SDL_RenderClear(renderer);
- _ = c.SDL_RenderTexture(renderer, texture, null, null);
- const probe_flip = monoNs();
- _ = c.SDL_RenderPresent(renderer);
- if (frame_probe) |probe| probe.zone(.gui_flip, probe_flip);
-}
-
fn backgroundOpacity(percent: u8) f32 {
std.debug.assert(percent <= 100);
return @as(f32, @floatFromInt(percent)) / 100;
@@ -5808,27 +4950,14 @@ fn latencyNote(comptime fmt: []const u8, args: anytype) void {
/// Writes the frame to latest.ppm in the capture directory, and in a
/// series to frame-<n>.ppm too.
fn captureFrame(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTexture, sw: u32, sh: u32) !void {
- const size = c.SDL_CalculateGPUTextureFormatSize(g.swapchain_format, sw, sh, 1);
- if (size == 0) {
- _ = c.SDL_SubmitGPUCommandBuffer(cmd);
- return error.UnsupportedCaptureFormat;
- }
- const xfer = try downloadTarget(g, cmd, target, sw, sh, size);
+ const frame = try g.present.readFrame(cmd, target, sw, sh);
+ defer g.present.releaseFrame(frame);
+ latencyNote("F {d} {d} {d}\n", .{ frame_started_ns, frame.fence_ns, frame.submit_ns });
- const submit_ns = monoNs();
- const fence = c.SDL_SubmitGPUCommandBufferAndAcquireFence(cmd) orelse return error.GpuSubmit;
- defer c.SDL_ReleaseGPUFence(g.device, fence);
- var fences = [_]*c.SDL_GPUFence{fence};
- if (!c.SDL_WaitForGPUFences(g.device, true, &fences, 1)) return error.GpuSubmit;
- latencyNote("F {d} {d} {d}\n", .{ frame_started_ns, monoNs(), submit_ns });
-
- const mapped = c.SDL_MapGPUTransferBuffer(g.device, xfer, false) orelse return error.GpuMap;
- defer c.SDL_UnmapGPUTransferBuffer(g.device, xfer);
- const pixels: [*]const u8 = @ptrCast(mapped);
- try writeCapturePpm(g, gpa, pixels[0..size], sw, sh, "latest");
+ try writeCapturePpm(g, gpa, frame.pixels, sw, sh, "latest", false);
var name: [24]u8 = undefined;
// unreachable below: "frame-" and a u32 fit 24
- if (g.capture_series) try writeCapturePpm(g, gpa, pixels[0..size], sw, sh, std.fmt.bufPrint(&name, "frame-{d:0>5}", .{g.captured}) catch unreachable);
+ if (g.capture_series) try writeCapturePpm(g, gpa, frame.pixels, sw, sh, std.fmt.bufPrint(&name, "frame-{d:0>5}", .{g.captured}) catch unreachable, true);
g.captured +%= 1;
}
@@ -5858,41 +4987,44 @@ fn writeTestStatus(g: *const Gui, core: *const pardes.Pardes, presented: bool) v
_ = libc.rename(tmp_path, final_path);
}
-fn writeCapturePpm(g: *Gui, gpa: std.mem.Allocator, pixels: []const u8, width: u32, height: u32, name: []const u8) !void {
+/// `<name>.ppm`, RGB; with `alpha`, `<name>.pam` (P7 RGB_ALPHA) instead: a
+/// series keeps the alpha a blend writes, which the window's transparency
+/// shows and an RGB capture cannot.
+fn writeCapturePpm(g: *Gui, gpa: std.mem.Allocator, pixels: []const u8, width: u32, height: u32, name: []const u8, alpha: bool) !void {
// A latency trace times frames, and an 8 MB file write per frame would
// stall the loop it is timing.
if (g.capture_dir.len == 0 or latency_fd >= 0) return;
- const bpp = c.SDL_GPUTextureFormatTexelBlockSize(g.swapchain_format);
- if (bpp != 4) return error.UnsupportedCaptureFormat;
- const bgr = switch (g.swapchain_format) {
- c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM_SRGB => false,
- c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM, c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM_SRGB => true,
- else => return error.UnsupportedCaptureFormat,
- };
+ const bgr = try g.present.bgr();
var tmp_buf: [4096]u8 = undefined;
var final_buf: [4096]u8 = undefined;
- const tmp_path = std.fmt.bufPrintSentinel(&tmp_buf, "{s}/{s}.ppm.tmp", .{ g.capture_dir, name }, 0) catch return error.CapturePathTooLong;
- const final_path = std.fmt.bufPrintSentinel(&final_buf, "{s}/{s}.ppm", .{ g.capture_dir, name }, 0) catch return error.CapturePathTooLong;
+ const ext = if (alpha) "pam" else "ppm";
+ const tmp_path = std.fmt.bufPrintSentinel(&tmp_buf, "{s}/{s}.{s}.tmp", .{ g.capture_dir, name, ext }, 0) catch return error.CapturePathTooLong;
+ const final_path = std.fmt.bufPrintSentinel(&final_buf, "{s}/{s}.{s}", .{ g.capture_dir, name, ext }, 0) catch return error.CapturePathTooLong;
const fd = libc.open(tmp_path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644));
if (fd < 0) return error.CaptureWriteFailed;
defer _ = libc.close(fd);
- var header: [64]u8 = undefined;
- const hdr = std.fmt.bufPrint(&header, "P6\n{d} {d}\n255\n", .{ width, height }) catch unreachable; // two u32s fit 64
+ var header: [96]u8 = undefined;
+ const hdr = if (alpha)
+ std.fmt.bufPrint(&header, "P7\nWIDTH {d}\nHEIGHT {d}\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n", .{ width, height }) catch unreachable // two u32s fit 96
+ else
+ std.fmt.bufPrint(&header, "P6\n{d} {d}\n255\n", .{ width, height }) catch unreachable; // two u32s fit 96
_ = host_io.writeFd(fd, hdr);
- const row_rgb = try gpa.alloc(u8, @as(usize, width) * 3);
+ const depth: usize = if (alpha) 4 else 3;
+ const row_rgb = try gpa.alloc(u8, @as(usize, width) * depth);
defer gpa.free(row_rgb);
for (0..height) |row| {
const src = pixels[row * width * 4 ..][0 .. @as(usize, width) * 4];
for (0..width) |x| {
const si = x * 4;
- const di = x * 3;
+ const di = x * depth;
row_rgb[di + 0] = src[si + if (bgr) @as(usize, 2) else 0];
row_rgb[di + 1] = src[si + 1];
row_rgb[di + 2] = src[si + if (bgr) @as(usize, 0) else 2];
+ if (alpha) row_rgb[di + 3] = src[si + 3];
}
_ = host_io.writeFd(fd, row_rgb);
}
@@ -6727,40 +5859,6 @@ fn appendCursorGlide(g: *Gui, surface: *const pardes.Surface, now_ns: u64, build
builder.addTri(px[0][0], px[0][1], px[2][0], px[2][1], px[3][0], px[3][1], color);
}
-fn uploadOverlayGpu(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, vertex_count: u32) bool {
- const byte_len: u32 = vertex_count * @sizeOf(OverlayVertex);
- const ptr = c.SDL_MapGPUTransferBuffer(g.device, g.overlay_vxfer, false) orelse return false;
- const dst: [*]u8 = @ptrCast(ptr);
- const src: [*]const u8 = @ptrCast(g.overlay_vertices.ptr);
- @memcpy(dst[0..byte_len], src[0..byte_len]);
- c.SDL_UnmapGPUTransferBuffer(g.device, g.overlay_vxfer);
- const copy = c.SDL_BeginGPUCopyPass(cmd);
- const src_loc = c.SDL_GPUTransferBufferLocation{ .transfer_buffer = g.overlay_vxfer, .offset = 0 };
- const dst_region = c.SDL_GPUBufferRegion{ .buffer = g.overlay_vbuf, .offset = 0, .size = byte_len };
- c.SDL_UploadToGPUBuffer(copy, &src_loc, &dst_region, false);
- c.SDL_EndGPUCopyPass(copy);
- return true;
-}
-
-fn pushLayerOpacity(cmd: *c.SDL_GPUCommandBuffer, pass: ?*c.SDL_GPURenderPass, opacity: f32) void {
- const uniforms = [4]f32{ opacity, 0, 0, 0 };
- c.SDL_PushGPUFragmentUniformData(cmd, 0, &uniforms, @sizeOf(@TypeOf(uniforms)));
- // The source alpha is geometric/image coverage, not window opacity. Its
- // alpha contribution is multiplied by this constant separately, so a
- // rail repainted over a gutter still has alpha p, not p + p*(1-p).
- c.SDL_SetGPUBlendConstants(pass, .{ .r = opacity, .g = opacity, .b = opacity, .a = opacity });
-}
-
-fn drawOverlayGpu(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, rp: ?*c.SDL_GPURenderPass, vertex_count: u32) void {
- if (vertex_count == 0) return;
- const pass = rp orelse return;
- c.SDL_BindGPUGraphicsPipeline(pass, g.overlay_pipeline);
- const binding = c.SDL_GPUBufferBinding{ .buffer = g.overlay_vbuf, .offset = 0 };
- c.SDL_BindGPUVertexBuffers(pass, 0, &binding, 1);
- pushLayerOpacity(cmd, pass, backgroundOpacity(g.applied_window_opacity));
- c.SDL_DrawGPUPrimitives(pass, vertex_count, 1, 0, 0);
-}
-
const OverlayBuilder = struct {
vertices: []OverlayVertex,
len: usize = 0,
@@ -6835,25 +5933,24 @@ fn expectCoverIsScan(cover: []const Cover, cols: u16, rows: u16, body_layers: []
};
}
-/// A Gui that can shape and rasterize `font` at `px`, and nothing else. From
-/// here on the fonts allocate from std.testing.allocator (the caller puts
-/// font_allocator back), so the test counts what they leak.
-fn textTestGui(font: *c.UIFont, px: f32) !Gui {
- c.ui_font_prime(font);
+/// A Gui that can shape and rasterize the face in `bytes` at `px`, and
+/// nothing else. From here on the fonts allocate from std.testing.allocator
+/// (the caller puts font_allocator back), so the test counts what they leak.
+fn textTestGui(bytes: []const u8, px: f32) !Gui {
+ var atlas = try Atlas.init(std.testing.allocator, bytes);
+ atlas.prime();
font_allocator = std.testing.allocator;
var cw: c_int = 0;
var ch: c_int = 0;
var ascent: c_int = 0;
- c.ui_font_cell_metrics(font, px, &cw, &ch, &ascent);
- const tag = taglineRaster(font, px, @intCast(cw), @intCast(ch), 82);
+ atlas.cellMetrics(px, &cw, &ch, &ascent);
+ const tag = taglineRaster(&atlas, px, @intCast(cw), @intCast(ch), 82);
var g = testGui(@intCast(cw), @intCast(ch), tag.width, tag.height);
- g.font = font;
+ g.atlas = atlas;
g.px = px;
g.ascent = ascent;
g.tagline_px = tag.px;
g.tagline_baseline = tag.baseline;
- g.atlas_stage = try std.testing.allocator.alloc(u8, atlas_w * atlas_h);
- g.glyphs = std.AutoHashMap(GlyphKey, Slot).init(std.testing.allocator);
resetGlyphAtlas(&g);
return g;
}
@@ -6865,7 +5962,7 @@ fn textTestLine(comptime text: []const u8) [text.len]pardes.Cell {
}
fn glyphKeyAt(g: *Gui, slot: Slot) !GlyphKey {
- var it = g.glyphs.iterator();
+ var it = g.atlas.glyphs.iterator();
while (it.next()) |entry| if (std.meta.eql(entry.value_ptr.*, slot)) return entry.key_ptr.*;
return error.NoGlyph;
}
@@ -6927,37 +6024,39 @@ fn cursorColor(chrome: *const pardes.Chrome, cell: *const pardes.Cell, role: par
test "FreeType and HarfBuzz allocate from the gui allocator and give it all back" {
// HarfBuzz's process-wide objects come from the default heap, as in runNative.
- const primer = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?;
- c.ui_font_prime(primer);
- c.ui_font_free(primer);
+ var primer = try Atlas.init(std.testing.allocator, font_ttf);
+ primer.prime();
+ primer.deinit(std.testing.allocator);
font_allocator = std.testing.allocator;
defer font_allocator = std.heap.smp_allocator;
- const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?;
- defer c.ui_font_free(font);
- var mask: [64 * 64]u8 = undefined;
- try std.testing.expectEqual(@as(c_int, 1), c.ui_font_raster(font, 27, c.ui_font_glyph(font, 'g'), 1, &mask, 64, 32, 48, 0, 32, 30));
- try std.testing.expectEqual(@as(c_int, 0), c.ui_font_substitutes(font, c.ui_font_glyph(font, '-')));
+ var atlas = try Atlas.init(std.testing.allocator, font_ttf);
+ defer atlas.deinit(std.testing.allocator);
+ atlas.reset(32);
+ const size: Atlas.Size = .{ .px = 27, .cell_w = 32, .height = 48, .baseline = 30 };
+ const g_slot = atlas.cachedGlyph(.{ .face = 0, .glyph = atlas.glyphForCodepoint('g').glyph, .role = .body, .decoration = .{ .bold = true } }, size, size, config.GUTTER, 1).?;
+ try std.testing.expect(Atlas.inkBounds(atlas.atlas_stage[@as(usize, g_slot.v) * atlas_w + g_slot.u ..], atlas_w, 32, 48) != null);
+ try std.testing.expect(!atlas.substitutes(0, atlas.glyphForCodepoint('-').glyph));
// A font with ligatures runs the whole HarfBuzz pass.
const bytes = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf");
defer std.testing.allocator.free(bytes);
- const maple = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse return error.FontInit;
- defer c.ui_font_free(maple);
+ var maple = try Atlas.init(std.testing.allocator, bytes);
+ defer maple.deinit(std.testing.allocator);
var cell_w: c_int = 0;
var cell_h: c_int = 0;
var ascent: c_int = 0;
- c.ui_font_cell_metrics(maple, 27, &cell_w, &cell_h, &ascent);
+ maple.cellMetrics(27, &cell_w, &cell_h, &ascent);
const text = [_]u32{ 'a', '-', '>', 'b', '=', '=' };
var shaped: [text.len]c.UIShapedCell = undefined;
- c.ui_font_shape(maple, 27, cell_w, &text, text.len, &shaped);
+ maple.shape(0, 27, @intCast(cell_w), &text, &shaped);
try std.testing.expectEqual(@as(u8, 2), shaped[1].span);
try std.testing.expectEqual(@as(u8, 2), shaped[4].span);
}
test "every font size step moves the cell, and the ends are reachable exactly" {
- const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?;
- defer c.ui_font_free(font);
+ var atlas = try Atlas.init(std.testing.allocator, font_ttf);
+ defer atlas.deinit(std.testing.allocator);
var px = font_px_min + font_px_step;
while (px <= font_px_max) : (px += 1.0) {
var cw: c_int = 0;
@@ -6965,95 +6064,33 @@ test "every font size step moves the cell, and the ends are reachable exactly" {
var asc: c_int = 0;
var pw: c_int = 0;
var ph: c_int = 0;
- c.ui_font_cell_metrics(font, px, &cw, &ch, &asc);
- c.ui_font_cell_metrics(font, px - font_px_step, &pw, &ph, &asc);
+ atlas.cellMetrics(px, &cw, &ch, &asc);
+ atlas.cellMetrics(px - font_px_step, &pw, &ph, &asc);
try std.testing.expect(cw > pw and ch > ph);
}
try std.testing.expectEqual(font_px_max, std.math.clamp(font_px_max + font_px_step, font_px_min, font_px_max));
try std.testing.expectEqual(font_px_min, std.math.clamp(font_px_min - font_px_step, font_px_min, font_px_max));
}
-test "FreeType atlas raster is grayscale, bounded, and clears blank cells" {
- 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 "tagline glyph shrinks into its own cell and stays vertically centered" {
- const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?;
- defer c.ui_font_free(font);
-
const body_px: f32 = 27.0;
- var cell_w: c_int = 1;
- var cell_h: c_int = 1;
- var body_ascent: c_int = 1;
- c.ui_font_cell_metrics(font, body_px, &cell_w, &cell_h, &body_ascent);
- const tag = taglineRaster(font, body_px, @intCast(cell_w), @intCast(cell_h), config.gui_tagline_font_percent);
+ var g = try textTestGui(font_ttf, body_px);
+ defer font_allocator = std.heap.smp_allocator;
+ defer g.atlas.deinit(std.testing.allocator);
+ defer g.words.deinit(std.testing.allocator);
+ _ = fitTaglineFont(&g, config.gui_tagline_font_percent);
+ const cell_w: c_int = @intCast(g.cell_w);
+ const cell_h: c_int = @intCast(g.cell_h);
+ const tag = taglineRaster(&g.atlas, body_px, @intCast(cell_w), @intCast(cell_h), config.gui_tagline_font_percent);
try std.testing.expect(tag.px < body_px);
try std.testing.expect(tag.width < @as(u32, @intCast(cell_w)));
- const stride: c_int = 128;
- var body: [128 * 128]u8 = @splat(0);
- var tagline: [128 * 128]u8 = @splat(0);
- const h = c.ui_font_glyph(font, 'H');
- try std.testing.expectEqual(@as(c_int, 1), c.ui_font_raster(font, body_px, h, 0, &body, stride, cell_w, cell_h, 0, cell_w, body_ascent));
- try std.testing.expectEqual(@as(c_int, 1), c.ui_font_raster(font, tag.px, h, 0, &tagline, stride, @intCast(tag.width), @intCast(tag.height), 0, @intCast(tag.width), tag.baseline));
- const b = inkBounds(&body, @intCast(stride), @intCast(cell_w), @intCast(cell_h)).?;
- const t = inkBounds(&tagline, @intCast(stride), @intCast(tag.width), @intCast(tag.height)).?;
+ // Each at its role's size, as a frame draws it.
+ const h = g.atlas.glyphForCodepoint('H').glyph;
+ const body = cachedGlyph(&g, .{ .face = 0, .glyph = h, .role = .body }).?;
+ const tagline = cachedGlyph(&g, .{ .face = 0, .glyph = h, .role = .tagline }).?;
+ const b = Atlas.inkBounds(g.atlas.atlas_stage[@as(usize, body.v) * atlas_w + body.u ..], atlas_w, @intCast(cell_w), @intCast(cell_h)).?;
+ const t = Atlas.inkBounds(g.atlas.atlas_stage[@as(usize, tagline.v) * atlas_w + tagline.u ..], atlas_w, @intCast(tag.width), @intCast(tag.height)).?;
try std.testing.expect(t.max_x - t.min_x < b.max_x - b.min_x);
try std.testing.expect(t.max_y - t.min_y < b.max_y - b.min_y);
const body_center_x: isize = @intCast(b.min_x + b.max_x);
@@ -7069,15 +6106,15 @@ test "tagline glyph shrinks into its own cell and stays vertically centered" {
}
test "tagline percentage changes measured band height without body metrics" {
- const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?;
- defer c.ui_font_free(font);
+ var atlas = try Atlas.init(std.testing.allocator, font_ttf);
+ defer atlas.deinit(std.testing.allocator);
var cell_w: c_int = 1;
var cell_h: c_int = 1;
var ascent: c_int = 1;
- c.ui_font_cell_metrics(font, 27.0, &cell_w, &cell_h, &ascent);
- const small = taglineRaster(font, 27.0, @intCast(cell_w), @intCast(cell_h), 40);
- const configured = taglineRaster(font, 27.0, @intCast(cell_w), @intCast(cell_h), 82);
- const full = taglineRaster(font, 27.0, @intCast(cell_w), @intCast(cell_h), 100);
+ atlas.cellMetrics(27.0, &cell_w, &cell_h, &ascent);
+ const small = taglineRaster(&atlas, 27.0, @intCast(cell_w), @intCast(cell_h), 40);
+ const configured = taglineRaster(&atlas, 27.0, @intCast(cell_w), @intCast(cell_h), 82);
+ const full = taglineRaster(&atlas, 27.0, @intCast(cell_w), @intCast(cell_h), 100);
try std.testing.expect(small.width < configured.width);
try std.testing.expect(configured.width <= full.width);
try std.testing.expectEqual(@as(u32, @intCast(cell_w)), full.width);
@@ -7097,16 +6134,9 @@ test "installed Nerd Symbols fallback covers Yazi directory icons" {
const bytes = try filesystem.readFile(std.testing.allocator, candidate.path);
defer std.testing.allocator.free(bytes);
- const face = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse return error.FontInit;
- defer c.ui_font_free(face);
- try std.testing.expect(c.ui_font_glyph(face, 0xe5ff) != 0);
-}
-
-test "the shader instance ABI: the flags after the colours, the clip after them" {
- try std.testing.expectEqual(@as(usize, 76), @sizeOf(CellInstance));
- try std.testing.expectEqual(@as(usize, 56), @offsetOf(CellInstance, "effect"));
- try std.testing.expectEqual(@as(usize, 60), @offsetOf(CellInstance, "clip_x0"));
- try std.testing.expectEqual(@as(usize, 32), @sizeOf(ImageInstance));
+ var atlas = try Atlas.init(std.testing.allocator, bytes);
+ defer atlas.deinit(std.testing.allocator);
+ try std.testing.expect(atlas.glyphForCodepoint(0xe5ff).glyph != 0);
}
test "GUI PTY reader delivers a real shell tail before EOF and joins on close" {
@@ -8084,7 +7114,7 @@ test "concealed terminal text emits no ink on its ground" {
var cell: pardes.Cell = .{ .default = false, .style = .{ .invisible = true, .ul = .single } };
cell.text[0] = 'X';
const resolved = resolveCell(&g, (&cell)[0..1], 0, null, .body, false, bg_default);
- try std.testing.expectEqualDeep(g.space_slot, resolved.slot);
+ try std.testing.expectEqualDeep(g.atlas.space_slot, resolved.slot);
try std.testing.expectEqual(bg_default, resolved.bg);
}
@@ -8326,12 +7356,9 @@ test "insert cursor overlays without replacing the character beneath it" {
test "a ligature draws across its cells, one slice each, and comes apart under the cursor" {
const bytes = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf");
defer std.testing.allocator.free(bytes);
- const font = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse return error.FontInit;
- defer c.ui_font_free(font);
- var g = try textTestGui(font, 27);
+ var g = try textTestGui(bytes, 27);
defer font_allocator = std.heap.smp_allocator;
- defer std.testing.allocator.free(g.atlas_stage);
- defer g.glyphs.deinit();
+ defer g.atlas.deinit(std.testing.allocator);
defer g.words.deinit(std.testing.allocator);
const line = textTestLine("a->b");
@@ -8341,7 +7368,7 @@ test "a ligature draws across its cells, one slice each, and comes apart under t
try std.testing.expectEqual(slots[1].v, slots[2].v);
try std.testing.expectEqual(slots[1].u + g.cell_w, slots[2].u);
var strips: usize = 0;
- var it = g.glyphs.iterator();
+ var it = g.atlas.glyphs.iterator();
while (it.next()) |entry| if (entry.key_ptr.span == 2) {
strips += 1;
try std.testing.expectEqual(@as(u4, 1), entry.key_ptr.lead);
@@ -8349,7 +7376,7 @@ test "a ligature draws across its cells, one slice each, and comes apart under t
};
try std.testing.expectEqual(@as(usize, 1), strips);
// The arrow runs through the seam: both halves carry ink at it.
- const seam = g.atlas_stage[@as(usize, slots[2].v) * atlas_w ..];
+ const seam = g.atlas.atlas_stage[@as(usize, slots[2].v) * atlas_w ..];
var left_ink: usize = 0;
var right_ink: usize = 0;
for (0..g.cell_h) |y| {
@@ -8358,8 +7385,8 @@ test "a ligature draws across its cells, one slice each, and comes apart under t
}
try std.testing.expect(left_ink > 0 and right_ink > 0);
// `a` and `b` are their plain glyphs.
- try std.testing.expectEqual(g.glyphs.get(.{ .face = 0, .glyph = c.ui_font_glyph(font, 'a'), .role = .body }).?, slots[0]);
- try std.testing.expectEqual(g.glyphs.get(.{ .face = 0, .glyph = c.ui_font_glyph(font, 'b'), .role = .body }).?, slots[3]);
+ try std.testing.expectEqual(g.atlas.glyphs.get(.{ .face = 0, .glyph = g.atlas.glyphForCodepoint('a').glyph, .role = .body }).?, slots[0]);
+ try std.testing.expectEqual(g.atlas.glyphs.get(.{ .face = 0, .glyph = g.atlas.glyphForCodepoint('b').glyph, .role = .body }).?, slots[3]);
// A second line with the same word reuses the shaped slots.
const again = textTestLine("a->b");
@@ -8368,83 +7395,78 @@ test "a ligature draws across its cells, one slice each, and comes apart under t
try std.testing.expectEqual(text_len, g.words.text.items.len);
// The cursor on either half shows plain `-` and `>`.
- const plain_minus = cachedGlyph(&g, .{ .face = 0, .glyph = c.ui_font_glyph(font, '-'), .role = .body }).?;
- const plain_greater = cachedGlyph(&g, .{ .face = 0, .glyph = c.ui_font_glyph(font, '>'), .role = .body }).?;
+ const plain_minus = cachedGlyph(&g, .{ .face = 0, .glyph = g.atlas.glyphForCodepoint('-').glyph, .role = .body }).?;
+ const plain_greater = cachedGlyph(&g, .{ .face = 0, .glyph = g.atlas.glyphForCodepoint('>').glyph, .role = .body }).?;
for ([_]usize{ 1, 2 }) |cursor| {
try std.testing.expectEqual(plain_minus, cellSlot(&g, &line, 1, cursor, .body));
try std.testing.expectEqual(plain_greater, cellSlot(&g, &line, 2, cursor, .body));
}
// A tagline is never shaped.
- try std.testing.expectEqual(c.ui_font_glyph(font, '-'), (try glyphKeyAt(&g, cellSlot(&g, &line, 1, null, .tagline))).glyph);
+ try std.testing.expectEqual(g.atlas.glyphForCodepoint('-').glyph, (try glyphKeyAt(&g, cellSlot(&g, &line, 1, null, .tagline))).glyph);
}
test "a font without ligatures draws every cell as its own glyph, exactly as before shaping" {
- const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?;
- defer c.ui_font_free(font);
- var g = try textTestGui(font, 18);
+ var g = try textTestGui(font_ttf, 18);
defer font_allocator = std.heap.smp_allocator;
- defer std.testing.allocator.free(g.atlas_stage);
- defer g.glyphs.deinit();
+ defer g.atlas.deinit(std.testing.allocator);
defer g.words.deinit(std.testing.allocator);
+ // Each glyph as it is drawn unshaped, in an atlas of its own.
+ var plain = try textTestGui(font_ttf, 18);
+ defer plain.atlas.deinit(std.testing.allocator);
+ defer plain.words.deinit(std.testing.allocator);
const text = "a->b != c => d <= e |> www == :: 0x1F";
var line = textTestLine(text);
line[3].style.bold = true; // a style change inside a word
- var expected: [64 * 64]u8 = undefined;
for (line, 0..) |cell, i| {
if (text[i] == ' ') continue;
const slot = cellSlot(&g, &line, i, null, .body);
const key = try glyphKeyAt(&g, slot);
- try std.testing.expectEqual(c.ui_font_glyph(font, text[i]), key.glyph);
+ try std.testing.expectEqual(g.atlas.glyphForCodepoint(text[i]).glyph, key.glyph);
try std.testing.expectEqual(@as(u4, 1), key.span);
- _ = c.ui_font_raster(font, 18, key.glyph, @intFromBool(cell.style.bold), &expected, 64, @intCast(g.cell_w), @intCast(g.cell_h), 0, @intCast(g.cell_w), g.ascent);
+ const expected = cachedGlyph(&plain, .{ .face = 0, .glyph = key.glyph, .role = .body, .decoration = .{ .bold = cell.style.bold } }).?;
for (0..g.cell_h) |y|
- try std.testing.expectEqualSlices(u8, expected[y * 64 ..][0..g.cell_w], g.atlas_stage[(slot.v + y) * atlas_w + slot.u ..][0..g.cell_w]);
+ try std.testing.expectEqualSlices(u8, plain.atlas.atlas_stage[(expected.v + y) * atlas_w + expected.u ..][0..g.cell_w], g.atlas.atlas_stage[(slot.v + y) * atlas_w + slot.u ..][0..g.cell_w]);
}
}
test "pane indicator cached ink centers bearings styles and sizes" {
- const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?;
- defer c.ui_font_free(font);
var g = testGui(10, 20, 6, 12);
- g.font = font;
- g.atlas_stage = try std.testing.allocator.alloc(u8, atlas_w * atlas_h);
- defer std.testing.allocator.free(g.atlas_stage);
- g.glyphs = std.AutoHashMap(GlyphKey, Slot).init(std.testing.allocator);
- defer g.glyphs.deinit();
+ g.atlas = try Atlas.init(std.testing.allocator, font_ttf);
+ defer g.atlas.deinit(std.testing.allocator);
for ([_]f32{ 13, 27, 40 }) |px| {
g.px = px;
var cw: c_int = 0;
var ch: c_int = 0;
- c.ui_font_cell_metrics(font, px, &cw, &ch, &g.ascent);
+ g.atlas.cellMetrics(px, &cw, &ch, &g.ascent);
g.cell_w = @intCast(cw);
g.cell_h = @intCast(ch);
for ([_]u8{ 40, 82, 100 }) |percent| {
- const tag = taglineRaster(font, px, g.cell_w, g.cell_h, percent);
+ const tag = taglineRaster(&g.atlas, px, g.cell_w, g.cell_h, percent);
g.tagline_width = tag.width;
g.tagline_height = tag.height;
g.tagline_px = tag.px;
g.tagline_baseline = tag.baseline;
resetGlyphAtlas(&g);
- try std.testing.expectEqual(@as(usize, 0), g.glyphs.count());
+ try std.testing.expectEqual(@as(usize, 0), g.atlas.glyphs.count());
for ([_]u32{ '^', '$', 'j' }) |cp| for ([_]bool{ false, true }) |bold| {
- const key: GlyphKey = .{ .face = 0, .glyph = c.ui_font_glyph(font, @intCast(cp)), .role = .tagline, .decoration = .{ .bold = bold }, .centered = true };
+ const key: GlyphKey = .{ .face = 0, .glyph = g.atlas.glyphForCodepoint(cp).glyph, .role = .tagline, .decoration = .{ .bold = bold }, .centered = true };
const slot = cachedGlyph(&g, key).?;
- const bounds = inkBounds(g.atlas_stage[@as(usize, slot.v) * atlas_w + slot.u ..], atlas_w, g.cell_w * config.GUTTER, tag.height).?;
+ const bounds = Atlas.inkBounds(g.atlas.atlas_stage[@as(usize, slot.v) * atlas_w + slot.u ..], atlas_w, g.cell_w * config.GUTTER, tag.height).?;
const center_x: isize = @intCast(bounds.min_x + bounds.max_x);
const center_y: isize = @intCast(bounds.min_y + bounds.max_y);
try std.testing.expect(@abs(center_x - @as(isize, @intCast(g.cell_w * config.GUTTER - 1))) <= 1);
try std.testing.expect(@abs(center_y - @as(isize, @intCast(tag.height - 1))) <= 1);
- const count = g.glyphs.count();
- const pen = g.pen_x;
+ const count = g.atlas.glyphs.count();
+ const pen = g.atlas.pen_x;
try std.testing.expectEqualDeep(slot, cachedGlyph(&g, key).?);
- try std.testing.expectEqual(count, g.glyphs.count());
- try std.testing.expectEqual(pen, g.pen_x);
+ try std.testing.expectEqual(count, g.atlas.glyphs.count());
+ try std.testing.expectEqual(pen, g.atlas.pen_x);
};
}
}
resetGlyphAtlas(&g);
- g.pen_y = atlas_h;
- try std.testing.expectEqual(@as(?Slot, null), cachedGlyph(&g, .{ .face = 0, .glyph = c.ui_font_glyph(font, '^'), .role = .tagline, .centered = true }));
+ g.atlas.pen_y = atlas_h;
+ try std.testing.expectEqual(@as(?Slot, null), cachedGlyph(&g, .{ .face = 0, .glyph = g.atlas.glyphForCodepoint('^').glyph, .role = .tagline, .centered = true }));
}
test "pane indicator halves are safe on an exhausted atlas" {
@@ -8461,15 +7483,12 @@ test "pane indicator halves are safe on an exhausted atlas" {
coverFrame(&cover, 6, 2, &.{}, &.{}, &grip);
const chrome: pardes.Chrome = .{};
- const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?;
- defer c.ui_font_free(font);
var g = testGui(10, 20, 8, 16);
- g.font = font;
+ g.atlas = try Atlas.init(std.testing.allocator, font_ttf);
+ defer g.atlas.deinit(std.testing.allocator);
g.px = 20;
g.tagline_px = 16;
- g.pen_y = atlas_h;
- g.glyphs = std.AutoHashMap(GlyphKey, Slot).init(std.testing.allocator);
- defer g.glyphs.deinit();
+ g.atlas.pen_y = atlas_h;
defer g.words.deinit(std.testing.allocator);
var instances: [4]CellInstance = undefined;
var next: u32 = 0;
@@ -8480,94 +7499,13 @@ test "pane indicator halves are safe on an exhausted atlas" {
try std.testing.expectEqual(@as(u32, 4), next);
}
-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).?);
- // ┼: 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).?);
- 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 ([_]GlyphDecoration{
- .{ .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);
- 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 "a concealed cell's underline draws nothing of its own" {
const hidden: pardes.Cell = .{ .default = false, .style = .{ .invisible = true, .ul = .single } };
try std.testing.expect(!GlyphDecoration.fromCell(&hidden).drawsBlank());
}
-test "the atlas's dirty rows hold every row a new glyph draws into, and a reset dirties them all" {
- const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?;
- defer c.ui_font_free(font);
- var g = try textTestGui(font, 18);
- defer font_allocator = std.heap.smp_allocator;
- defer std.testing.allocator.free(g.atlas_stage);
- defer g.glyphs.deinit();
- defer g.words.deinit(std.testing.allocator);
- // The texture as uploadAtlas 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) resetGlyphAtlas(&g); // a font change
- // Plain glyphs, strips, taglines, grip glyphs and decorations.
- for (0..25) |_| {
- glyph += 1;
- const span: u4 = @intCast(1 + glyph % 3);
- _ = cachedGlyph(&g, .{
- .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,
- }) orelse return error.AtlasFull;
- }
- for (0..atlas_h) |row| {
- const stage = g.atlas_stage[row * atlas_w ..][0..atlas_w];
- const uploaded = texture[row * atlas_w ..][0..atlas_w];
- if (row >= g.atlas_dirty_top and row < g.atlas_dirty_bottom)
- @memcpy(uploaded, stage)
- else
- try std.testing.expect(std.mem.eql(u8, stage, uploaded));
- }
- g.atlas_dirty_top = atlas_h;
- g.atlas_dirty_bottom = 0;
- }
- try std.testing.expect(g.pen_y >= 2 * g.cell_h);
-}
-
test "overlapping background layers keep one uniform opacity" {
- const blend = backgroundLayerBlend();
+ const blend = Cells.backgroundLayerBlend();
try std.testing.expectEqual(@as(c.SDL_GPUBlendFactor, c.SDL_GPU_BLENDFACTOR_CONSTANT_COLOR), blend.src_alpha_blendfactor);
try std.testing.expectEqual(@as(c.SDL_GPUBlendFactor, c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA), blend.dst_alpha_blendfactor);
for ([_]f32{ 0, 0.25, 0.7, 1 }) |opacity| {
@@ -9160,7 +8098,7 @@ fn prepareAddonGpu(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer
};
const hash = std.hash.Wyhash.hash(frame.serial, frame.bytes);
if (g.addon_failed[id] == hash) continue;
- if (g.addon_gpu == null) g.addon_gpu = .init(gpa, g.device);
+ if (g.addon_gpu == null) g.addon_gpu = .init(gpa, g.cells.device);
const gpu = &g.addon_gpu.?;
const target: GpuScene.abi.Image = @fromBackingInt(@intCast(id + 1));
if (g.addon_hash[id] != hash or g.addon_serial[id] != frame.serial) {
@@ -9188,11 +8126,7 @@ fn prepareAddonGpu(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer
g.addon_serial[id] = frame.serial;
}
const out = gpu.output(target) orelse continue;
- if (g.addon_pipeline == null) {
- var blend = backgroundLayerBlend();
- blend.src_color_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE;
- g.addon_pipeline = makePipeline(g.device, g.swapchain_format, image_vert_spv, image_frag_spv, 1, 1, image_input, blend) catch continue;
- }
+ g.cells.makeAddonPipeline() catch continue;
g.prepared_images.append(gpa, .{
.premultiplied = true,
.texture = out.texture,
@@ -9201,3 +8135,81 @@ fn prepareAddonGpu(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer
}
if (g.addon_gpu) |*gpu| gpu.endFrame();
}
+
+test "the atlas's bytes: a fixed key list at 27 px and at 54 px (2x) rasterizes to the recorded stage and slots" {
+ // The glyph atlas the frames sample, byte for byte and on any machine:
+ // FreeType and HarfBuzz are the build's, the faces the repo's (the
+ // embedded Adwaita Mono, assets/MapleMono-NF for ligatures and Nerd
+ // icons). CJK has no face of the repo's and no fallback of pardes's
+ // list: the frame corpus draws its .notdef. Recorded before the GPU
+ // move (.scratch/sketch/briefs/gpu-s0.md); a change here is a change
+ // to every frame.
+ const want = [2][2]u64{ .{ 0xa03053f14e2c5472, 0x9029886b638b07d5 }, .{ 0xcbaa53a0103aaff5, 0x7563d69768f7d867 } };
+ const maple = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf");
+ defer std.testing.allocator.free(maple);
+ defer display_scale = 1;
+ var got: [2][2]u64 = undefined;
+ for ([_]f32{ 27, 54 }, [_]f32{ 1, 2 }, &got) |px, scale, *hashes| {
+ display_scale = scale;
+ var stage_hash = std.hash.Wyhash.init(0);
+ var slots_hash = std.hash.Wyhash.init(0);
+ // 0: Adwaita Mono, Maple its fallback; 1: Maple, whose ligatures shape.
+ for ([_][]const u8{ font_ttf, maple }) |primary| {
+ var g = try textTestGui(primary, px);
+ defer font_allocator = std.heap.smp_allocator;
+ defer g.atlas.deinit(std.testing.allocator);
+ defer g.words.deinit(std.testing.allocator);
+ try std.testing.expect(g.atlas.addFallback(std.testing.allocator, maple, false));
+ try std.testing.expect(fitTaglineFont(&g, 80));
+ const decorations = [_]Atlas.Decoration{
+ .{},
+ .{ .bold = true },
+ .{ .underline = .single },
+ .{ .underline = .double },
+ .{ .underline = .curly },
+ .{ .underline = .dotted },
+ .{ .underline = .dashed },
+ .{ .strikethrough = true },
+ };
+ for (0x21..0x7f) |cp| {
+ const drawn = g.atlas.glyphForCodepoint(@intCast(cp));
+ for (decorations) |decoration| _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .body, .decoration = decoration }) orelse return error.AtlasFull;
+ for (decorations[0..2]) |decoration| _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .tagline, .decoration = decoration }) orelse return error.AtlasFull;
+ }
+ const space = g.atlas.glyphForCodepoint(' ');
+ _ = cachedGlyph(&g, .{ .face = space.face, .glyph = space.glyph, .role = .body, .decoration = .{ .underline = .single } }) orelse return error.AtlasFull;
+ for ([_]u32{ 0x2500, 0x2502, 0x250c, 0x2510, 0x2514, 0x2518, 0x251c, 0x2524, 0x252c, 0x2534, 0x253c }) |cp| for ([_]Atlas.Role{ .body, .tagline }) |role| {
+ _ = cachedGlyph(&g, .{ .face = 0, .glyph = cp, .role = role, .rule = true }) orelse return error.AtlasFull;
+ };
+ for ([_]u32{ '$', '^', 'j' }) |cp| for ([_]bool{ false, true }) |bold| {
+ const drawn = g.atlas.glyphForCodepoint(cp);
+ _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .tagline, .decoration = .{ .bold = bold }, .centered = true }) orelse return error.AtlasFull;
+ };
+ // Nerd icons (Yazi's folder, a file, powerline's arrow): Maple's,
+ // the primary's or the fallback's.
+ for ([_]u32{ 0xe5ff, 0xf07b, 0xe0b0 }) |cp| {
+ const drawn = g.atlas.glyphForCodepoint(cp);
+ try std.testing.expect(drawn.glyph != 0);
+ _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .body }) orelse return error.AtlasFull;
+ }
+ // Ligature strips, shaped by the words' cache as a frame shapes them.
+ const line = textTestLine("a->b => != <= >= == === !== |> <| :: ++ -- www office");
+ for (0..line.len) |i| _ = cellSlot(&g, &line, i, null, .body);
+ stage_hash.update(g.atlas.atlas_stage);
+ const Entry = struct { key: u64, u: u32, v: u32 };
+ var entries: std.ArrayList(Entry) = .empty;
+ defer entries.deinit(std.testing.allocator);
+ var it = g.atlas.glyphs.iterator();
+ while (it.next()) |e| try entries.append(std.testing.allocator, .{ .key = @bitCast(e.key_ptr.*), .u = e.value_ptr.u, .v = e.value_ptr.v });
+ std.mem.sort(Entry, entries.items, {}, struct {
+ fn less(_: void, x: Entry, y: Entry) bool {
+ return x.key < y.key;
+ }
+ }.less);
+ for (entries.items) |e| slots_hash.update(std.mem.asBytes(&e));
+ }
+ hashes.* = .{ stage_hash.final(), slots_hash.final() };
+ }
+ if (!std.meta.eql(want, got)) std.debug.print("atlas hashes: .{{ .{{ 0x{x}, 0x{x} }}, .{{ 0x{x}, 0x{x} }} }}\n", .{ got[0][0], got[0][1], got[1][0], got[1][1] });
+ try std.testing.expectEqual(want, got);
+}
diff --git a/test/process.zig b/test/process.zig
index 67d883ca..126a7924 100644
--- a/test/process.zig
+++ b/test/process.zig
@@ -616,12 +616,22 @@ pub const Detached = struct {
try std.fmt.bufPrintSentinel(&bufs[1], "--9p={s}", .{opts.socket orelse name}, 0)
else
try std.fmt.bufPrintSentinel(&bufs[1], "--detach={s}", .{name}, 0);
+ // PARDES_TEST_WRAP: a command a window runs under (`perf stat ...`,
+ // a script), given the window's own argv; the binary made absolute,
+ // as the child runs elsewhere.
+ const wrap = if (gui) std.c.getenv("PARDES_TEST_WRAP") else null;
+ var exe_buf: [4096]u8 = undefined;
var argv: [24][:0]const u8 = undefined;
- if (opts.args.len + 3 > argv.len) return error.TooManyArgs;
- argv[0] = exe;
- argv[1] = first;
- for (opts.args, 0..) |a, k| argv[2 + k] = a;
- argv[2 + opts.args.len] = fixture;
+ if (opts.args.len + 4 > argv.len) return error.TooManyArgs;
+ var at: usize = 0;
+ if (wrap) |w| {
+ argv[0] = std.mem.span(w);
+ at = 1;
+ }
+ argv[at] = if (wrap != null) std.mem.span(realpath(exe, &exe_buf) orelse return error.NoBinary) else exe;
+ argv[at + 1] = first;
+ for (opts.args, 0..) |a, k| argv[at + 2 + k] = a;
+ argv[at + 2 + opts.args.len] = fixture;
var grid_buf: [2][8]u8 = undefined;
var env: [16][2][:0]const u8 = undefined;
var n: usize = 0;
@@ -641,7 +651,7 @@ pub const Detached = struct {
env[n] = kv;
n += 1;
}
- d.child = try Child.spawn(argv[0 .. 3 + opts.args.len], .{
+ d.child = try Child.spawn(argv[0 .. at + 3 + opts.args.len], .{
.root = dir,
.env = env[0..n],
// A window runs on a terminal of its own, as one started from a
diff --git a/test/process/window.zig b/test/process/window.zig
index 8d1afed8..687b9000 100644
--- a/test/process/window.zig
+++ b/test/process/window.zig
@@ -7,6 +7,7 @@ const process = @import("../process.zig");
pub const cases = .{
.{ "window: a monkey over the effects: random clicks, drags, wheels, keys, columns, looks and themes, then it settles, alive, with no crash record", monkey },
+ .{ "window: its frame corpus, every kept frame and its sha256 into PARDES_GUI_CORPUS, to compare two builds on one machine", corpus },
};
fn envOr(name: [*:0]const u8, default: []const u8) []const u8 {
@@ -157,3 +158,395 @@ fn firstPane(f: *process.Files) !?u32 {
const end = std.mem.indexOfScalar(u8, index, ' ') orelse return null;
return std.fmt.parseInt(u32, index[0..end], 10) catch null;
}
+
+/// The serial of the first pane whose tag holds `word`, waited for.
+fn paneWith(f: *process.Files, word: []const u8) !u32 {
+ const deadline = process.nowMs() + 10_000;
+ while (process.nowMs() < deadline) : (process.nap(50)) {
+ var rows = std.mem.tokenizeScalar(u8, try f.read("/index"), '\n');
+ while (rows.next()) |row| {
+ const serial = std.fmt.parseInt(u32, row[0 .. std.mem.indexOfScalar(u8, row, ' ') orelse continue], 10) catch continue;
+ if (process.has(try f.read(f.at("/pane/{d}/tag", .{serial})), word)) return serial;
+ }
+ }
+ std.debug.print("no pane's tag holds {s}\n", .{word});
+ return error.NoSuchPane;
+}
+
+/// The serial of a pane /index did not list in `before`, waited for.
+fn paneSince(f: *process.Files, before: []const u8) !u32 {
+ const deadline = process.nowMs() + 10_000;
+ while (process.nowMs() < deadline) : (process.nap(50)) {
+ var rows = std.mem.tokenizeScalar(u8, try f.read("/index"), '\n');
+ while (rows.next()) |row| {
+ const head = row[0 .. std.mem.indexOfScalar(u8, row, ' ') orelse continue];
+ if (std.mem.indexOf(u8, before, f.at("{s} ", .{head})) == null) return std.fmt.parseInt(u32, head, 10);
+ }
+ }
+ return error.NoNewPane;
+}
+
+/// Until the body of pane `serial` holds `word`.
+fn bodyHas(f: *process.Files, serial: u32, word: []const u8) !void {
+ const deadline = process.nowMs() + 10_000;
+ while (!process.has(try f.read(f.at("/pane/{d}/body", .{serial})), word)) : (process.nap(50))
+ if (process.nowMs() > deadline) return error.NoOutput;
+}
+
+extern "c" fn system(cmd: [*:0]const u8) c_int;
+extern "c" fn ioctl(fd: c_int, request: c_ulong, ...) c_int;
+
+/// The frames a corpus keeps (`corpus`): numbered in the order kept, each
+/// a PAM with its alpha (the window's series), with its sha256 (sha256sum's
+/// lines) and its scene.
+const Corpus = struct {
+ gpa: std.mem.Allocator,
+ a: std.mem.Allocator,
+ out: []const u8,
+ n: u32 = 0,
+ sums: std.ArrayList(u8) = .empty,
+ scenes: std.ArrayList(u8) = .empty,
+ /// The window's own series below this are read and gone: a frame is
+ /// megabytes, and /tmp is small.
+ pruned: u32 = 0,
+
+ /// The frames the window has captured, read from its status.
+ fn captured(k: *Corpus, d: *process.Detached) !u32 {
+ const text = try process.readWhole(k.a, k.at("{s}/status", .{d.captures()}));
+ var words = std.mem.tokenizeAny(u8, text, " \n");
+ _ = words.next();
+ return std.fmt.parseInt(u32, words.next() orelse return error.NoStatus, 10);
+ }
+
+ fn at(k: *Corpus, comptime fmt: []const u8, args: anytype) []const u8 {
+ return std.fmt.allocPrint(k.a, fmt, args) catch @panic("out of memory");
+ }
+
+ /// Once the window is idle, the frames it has captured: where a step's
+ /// own begin. What came before is let go.
+ fn mark(k: *Corpus, d: *process.Detached) !u32 {
+ try d.settle(k.a);
+ const to = try k.captured(d);
+ k.prune(d, to);
+ return to;
+ }
+
+ /// The step begun at `from`, once the window is idle again: every frame
+ /// it drew (a motion, one input on the virtual clock), or only the one
+ /// that stays (what more than one input or a worker's landing makes,
+ /// whose frames in between are the machine's timing).
+ fn keep(k: *Corpus, d: *process.Detached, from: u32, label: []const u8, every: bool) !void {
+ const to = try k.rest(d);
+ if (to == 0) return error.NoFrame;
+ try k.take(d, if (every and to > from) from else to - 1, to, label);
+ }
+
+ /// Idle, and still idle once a worker had time to land what it owes (a
+ /// PDF page, a highlighted file: their jobs are not the loop's, and the
+ /// window is idle while they run): the frames captured then.
+ fn rest(k: *Corpus, d: *process.Detached) !u32 {
+ try d.settle(k.a);
+ var last = try k.captured(d);
+ for (0..50) |_| {
+ process.nap(400);
+ try d.settle(k.a);
+ const now = try k.captured(d);
+ if (now == last) return now;
+ last = now;
+ }
+ return error.NeverRests;
+ }
+
+ /// The first `n` frames since `from` of a scene that never rests (the
+ /// pet, the snake: they animate while shown), as the virtual clock
+ /// steps them.
+ fn first(k: *Corpus, d: *process.Detached, from: u32, n: u32, label: []const u8) !void {
+ const deadline = process.nowMs() + 30_000;
+ while (try k.captured(d) < from + n) : (process.nap(5))
+ if (process.nowMs() > deadline) return error.NoFrames;
+ try k.take(d, from, from + n, label);
+ }
+
+ fn take(k: *Corpus, d: *process.Detached, lo: u32, hi: u32, label: []const u8) !void {
+ for (lo..hi) |i| {
+ const bytes = try process.readWhole(k.gpa, k.at("{s}/frame-{d:0>5}.pam", .{ d.captures(), i }));
+ defer k.gpa.free(bytes);
+ var digest: [32]u8 = undefined;
+ std.crypto.hash.sha2.Sha256.hash(bytes, &digest, .{});
+ const name = k.at("frame-{d:0>5}.pam", .{k.n});
+ try process.writeFile(k.a, k.at("{s}/{s}", .{ k.out, name }), bytes);
+ try k.sums.print(k.a, "{x} {s}\n", .{ digest, name });
+ try k.scenes.print(k.a, "{d:0>5} {s}\n", .{ k.n, label });
+ std.debug.print("{d:0>5} {x} {s}\n", .{ k.n, digest[0..6], label });
+ k.n += 1;
+ }
+ k.prune(d, hi);
+ }
+
+ fn prune(k: *Corpus, d: *process.Detached, below: u32) void {
+ while (k.pruned < below) : (k.pruned += 1) {
+ const path = std.fmt.allocPrintSentinel(k.a, "{s}/frame-{d:0>5}.pam", .{ d.captures(), k.pruned }, 0) catch return;
+ _ = std.c.unlink(path);
+ }
+ }
+
+ fn finish(k: *Corpus) !void {
+ try process.writeFile(k.a, k.at("{s}/frames.sha256", .{k.out}), k.sums.items);
+ try process.writeFile(k.a, k.at("{s}/scenes.txt", .{k.out}), k.scenes.items);
+ }
+};
+
+/// The window's frame size in pixels, from the frame it last captured.
+fn frameSize(a: std.mem.Allocator, d: *process.Detached) ![2]u32 {
+ const bytes = try d.frame(a);
+ var words = std.mem.tokenizeAny(u8, bytes[0..@min(bytes.len, 32)], " \n");
+ _ = words.next();
+ return .{ try std.fmt.parseInt(u32, words.next().?, 10), try std.fmt.parseInt(u32, words.next().?, 10) };
+}
+
+/// The corpus's files, in a root of their own (fixed: its paths are drawn
+/// in the tags), made anew for each window.
+const root = "/tmp/pardes-gui-corpus";
+fn corpusRoot(a: std.mem.Allocator) !void {
+ _ = system("rm -rf -- /tmp/pardes-gui-corpus");
+ if (std.c.mkdir(root, 0o700) != 0) return error.NoRoot;
+ var zig: std.ArrayList(u8) = .empty;
+ try zig.appendSlice(a,
+ \\const std = @import("std");
+ \\
+ \\pub const Shape = union(enum) {
+ \\ circle: f32,
+ \\ square: f32,
+ \\
+ \\ pub fn area(shape: Shape) f32 {
+ \\ return switch (shape) {
+ \\ .circle => |r| std.math.pi * r * r,
+ \\ .square => |s| s * s,
+ \\ };
+ \\ }
+ \\};
+ \\
+ \\pub fn main() void {
+ \\ var total: f32 = 0;
+ \\ const shapes = [_]Shape{ .{ .circle = 1 }, .{ .square = 2 } };
+ \\ for (shapes) |shape| {
+ \\ if (shape == .circle) {
+ \\
+ );
+ for (0..80) |n| try zig.print(a, " total += shape.area() * {d}; // line {d}\n", .{ n, n });
+ try zig.appendSlice(a, " }\n }\n std.debug.print(\"{d}\\n\", .{total});\n}\n");
+ try process.writeFile(a, root ++ "/shapes.zig", zig.items);
+ try process.writeFile(a, root ++ "/notes.md",
+ \\# Fallback faces and rules
+ \\
+ \\| name | glyphs |
+ \\|------|--------|
+ \\| cjk | 界面字 |
+ \\| nerd |
+ ++ "\u{e5ff} \u{f07b} \u{e0b0}" ++
+ \\ |
+ \\| sym | ∮ ≠ ★ ☃ ⚡ ⌘ |
+ \\
+ \\┌──┬──┐
+ \\│ a│ b│
+ \\├──┼──┤
+ \\│ c│ d│
+ \\└──┴──┘
+ \\
+ );
+ try process.writeFile(a, root ++ "/ligatures.zig",
+ \\const a = b -> c; // => != <= >= == === !== |> <| :: ++ --
+ \\const fi = "office flow staff"; // f|i f|l s|t stay apart
+ \\
+ );
+ var ppm: std.ArrayList(u8) = .empty;
+ try ppm.print(a, "P6\n{d} {d}\n255\n", .{ 96, 64 });
+ for (0..64) |yy| for (0..96) |xx| try ppm.appendSlice(a, &.{ @intCast(xx * 255 / 96), @intCast(yy * 255 / 64), 128 });
+ try process.writeFile(a, root ++ "/ramp.ppm", ppm.items);
+ try process.writeFile(a, root ++ "/doc.pdf", try process.readWhole(a, "docs/9p.pdf"));
+ // A face of the repo's with ligatures, where `Font` finds it by name.
+ for ([_][:0]const u8{ root ++ "/.local", root ++ "/.local/share", root ++ "/.local/share/fonts" }) |dir| _ = std.c.mkdir(dir, 0o755);
+ try process.writeFile(a, root ++ "/.local/share/fonts/MapleMono-NF-Regular.ttf", try process.readWhole(a, "assets/MapleMono-NF-Regular.ttf"));
+ try process.writeFile(a, root ++ "/sgr.sh",
+ \\printf '\033[1mbold\033[0m \033[2mdim\033[0m \033[7mreverse\033[0m [\033[8minvisible\033[0m]\n'
+ \\printf '\033[4:1msingle\033[0m \033[4:2mdouble\033[0m \033[4:3mcurly\033[0m \033[4:4mdotted\033[0m \033[4:5mdashed\033[0m \033[9mstrike\033[0m\n'
+ \\printf '\033[1;4:3;9mall\033[0m \033[38;2;255;128;0mrgb\033[0m \033[44mbg\033[0m\nEND\n'
+ \\
+ );
+ // A kitty image: 8x8 RGB, drawn 10 cells by 4.
+ var rgb: [8 * 8 * 3]u8 = undefined;
+ for (0..64) |i| rgb[i * 3 ..][0..3].* = .{ @intCast(i * 4), @intCast(255 - i * 4), @intCast((i % 8) * 32) };
+ var b64: [std.base64.standard.Encoder.calcSize(rgb.len)]u8 = undefined;
+ _ = std.base64.standard.Encoder.encode(&b64, &rgb);
+ try process.writeFile(a, root ++ "/kitty.sh", try std.fmt.allocPrint(a, "printf '\\033_Ga=T,f=24,s=8,v=8,c=10,r=4;{s}\\033\\\\'\nprintf '\\nKITTY\\n'\n", .{b64}));
+}
+
+/// S0 of the GPU move (.scratch/sketch/briefs/gpu-s0.md): the renderer's
+/// frame corpus. Twelve scenes on the hidden window under the virtual
+/// clock, each step one input (a 9P write, or one event on its terminal)
+/// and then idle; the frames a step keeps go to PARDES_GUI_CORPUS as
+/// frame-NNNNN.pam (RGBA: a blend's alpha too), their sha256 in
+/// frames.sha256 (sha256sum's lines), their scenes in scenes.txt. Two builds' corpora on one machine are the
+/// same bytes, or the renderer changed: a GPU and its driver draw their own
+/// pixels, so it gates a build against a build, never a machine.
+/// PARDES_GUI_CORPUS_SNAKE is the snake_shader addon (`zig build
+/// snake-shader`). Skipped without PARDES_GUI_CORPUS.
+fn corpus(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
+ try process.only(.gui);
+ const out = std.mem.span(std.c.getenv("PARDES_GUI_CORPUS") orelse return error.SkipZigTest);
+ const snake = std.mem.span(std.c.getenv("PARDES_GUI_CORPUS_SNAKE") orelse {
+ std.debug.print("PARDES_GUI_CORPUS_SNAKE: the snake_shader addon's library\n", .{});
+ return error.NoSnakeAddon;
+ });
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ defer _ = system("rm -rf -- /tmp/pardes-gui-corpus");
+ const init = "Shell /bin/sh\nTheme forge\nMessageLinger 0\nCursorBlink off\n";
+ var k: Corpus = .{ .gpa = gpa, .a = a, .out = out };
+ {
+ try corpusRoot(a);
+ var d = try process.Detached.start(gpa, exe, "corpus", .{ .root = root, .file = root ++ "/shapes.zig", .init = init, .grid = .{ 100, 22 }, .env = &.{
+ .{ "PARDES_TEST_CLOCK", "1" }, .{ "PARDES_TEST_SERIES", "1" }, .{ "PARDES_TEST_PAD", "7" },
+ } });
+ defer d.deinit();
+ const f = &d.files;
+ const first = try paneWith(f, "shapes.zig");
+ // 1. A Zig file: tags, the block cursor, the scrollbar.
+ try k.keep(&d, 0, "01 zig file: tags, block cursor, scrollbar", false);
+ const size = try frameSize(a, &d);
+ const cell_w = (size[0] - 7) / 100;
+ const cell_h = (size[1] - 7) / 22;
+ var from = try k.mark(&d);
+ try f.write(f.at("/pane/{d}/dot", .{first}), "45\n");
+ try k.keep(&d, from, "01 zig file: the cursor at line 45, the thumb mid-track", false);
+ // 11. Motion on the virtual clock: a wheel's glide (rows shifted,
+ // the scroll scissor), a jump's trail and the caret's glide quad.
+ from = try k.mark(&d);
+ try d.mouse("wheel", -3, cell_w * 40, cell_h * 12);
+ try k.keep(&d, from, "11 a wheel's glide, every frame", true);
+ from = try k.mark(&d);
+ try d.mouse("down", 1, cell_w * 20, cell_h * 10);
+ try d.mouse("up", 1, cell_w * 20, cell_h * 10);
+ try k.keep(&d, from, "11 a click moves the caret, every frame", true);
+ from = try k.mark(&d);
+ try d.typeKeys("gg");
+ try k.keep(&d, from, "11 a jump's trail and the caret's glide, every frame", true);
+ from = try k.mark(&d);
+ try f.write("/ctl", "Pet cat\n");
+ try k.keep(&d, from, "11 the pet, every frame", true);
+ try f.write("/ctl", "Pet off\n");
+ // 6. Taglines at 80% and the tree-sitter context rows.
+ from = try k.mark(&d);
+ try f.write("/ctl", "TaglineSize 80\n");
+ try k.keep(&d, from, "06 TaglineSize 80", false);
+ from = try k.mark(&d);
+ try f.write(f.at("/pane/{d}/ctl", .{first}), "TreeContext\n");
+ try k.keep(&d, from, "06 TreeContext on", false);
+ from = try k.mark(&d);
+ try f.write(f.at("/pane/{d}/dot", .{first}), "70\n");
+ try k.keep(&d, from, "06 context rows over a deep line", false);
+ // 3. A terminal's SGR: bold, dim, reverse, invisible, the five
+ // underlines, strike; 10. a kitty image in it.
+ const before = try f.read("/index");
+ try f.write(f.at("/pane/{d}/exec", .{first}), "Term\n");
+ const term = try paneSince(f, before);
+ try f.write(f.at("/pane/{d}/pty/data", .{term}), "PS1='$ '; clear; sh " ++ root ++ "/sgr.sh\r");
+ try bodyHas(f, term, "END");
+ try k.keep(&d, 0, "03 a terminal's SGR styles", false);
+ try f.write(f.at("/pane/{d}/pty/data", .{term}), "clear; sh " ++ root ++ "/kitty.sh\r");
+ try bodyHas(f, term, "KITTY");
+ try k.keep(&d, 0, "10 a kitty image in a terminal pane", false);
+ try f.write(f.at("/pane/{d}/exec", .{term}), "Del\n");
+ // 5. Fallback faces (CJK, Nerd icons), a markdown table, box rules.
+ try f.write(f.at("/pane/{d}/look", .{first}), root ++ "/notes.md\n");
+ const notes = try paneWith(f, "notes.md");
+ try k.keep(&d, 0, "05 fallback glyphs, a markdown table, box rules", false);
+ // 9. An image pane; a PDF pane and the pointer's word highlighted
+ // (its dirty rows uploaded).
+ try f.write(f.at("/pane/{d}/look", .{notes}), root ++ "/ramp.ppm\n");
+ const image = try paneWith(f, "ramp.ppm");
+ try k.keep(&d, 0, "09 an image pane", false);
+ try f.write(f.at("/pane/{d}/exec", .{image}), "Del\n");
+ try f.write(f.at("/pane/{d}/exec", .{notes}), "Del\n");
+ try f.write(f.at("/pane/{d}/look", .{first}), root ++ "/doc.pdf\n");
+ _ = try paneWith(f, "doc.pdf");
+ try k.keep(&d, 0, "09 a PDF pane", false);
+ _, const tag_row = try f.where("doc.pdf");
+ for ([_][2]usize{ .{ 26, 8 }, .{ 26, 3 }, .{ 40, 8 } }) |off| {
+ from = try k.mark(&d);
+ try d.mouse("motion", 0, @intCast(cell_w * off[0] + cell_w / 2), @intCast(cell_h * (tag_row + off[1]) + cell_h / 2));
+ try k.keep(&d, from, "09 the PDF's hovered word, its rows painted again", false);
+ }
+ // 7. Three columns, five panes, focus and dirty grips, InactiveDim.
+ try f.write("/ctl", "Newcol\n");
+ try f.write("/ctl", "Newcol\n");
+ const scratch = try f.newPane();
+ try f.write(f.at("/pane/{d}/body", .{scratch}), "a dirty pane\n");
+ try f.write("/ctl", "InactiveDim 40\n");
+ try k.keep(&d, 0, "07 three columns, a dirty pane, InactiveDim 40", false);
+ // 8. WindowOpacity at 71 and 0.
+ try f.write("/ctl", "WindowOpacity 71\n");
+ try k.keep(&d, 0, "08 WindowOpacity 71", false);
+ try f.write("/ctl", "WindowOpacity 0\n");
+ try k.keep(&d, 0, "08 WindowOpacity 0", false);
+ try f.write("/ctl", "WindowOpacity 100\n");
+ // 4. Ligatures in a face that has them; 12. the font changed (the
+ // atlas reset).
+ try f.write(f.at("/pane/{d}/look", .{first}), root ++ "/ligatures.zig\n");
+ _ = try paneWith(f, "ligatures.zig");
+ try k.keep(&d, 0, "04 ligatures.zig in the default face", false);
+ try f.write("/ctl", "Font MapleMono-NF-Regular:16\n");
+ try k.keep(&d, 0, "04 12 Font MapleMono 16: ligatures, the atlas reset", false);
+ // The window resized: its terminal's size, which a test window follows.
+ var ws: std.posix.winsize = .{ .row = 20, .col = 70, .xpixel = 0, .ypixel = 0 };
+ if (ioctl(d.child.master, 0x5414, &ws) != 0) return error.NoResize; // TIOCSWINSZ
+ try k.keep(&d, 0, "12 the window resized to 70x20", false);
+ // A translucent addon picture (test/veil.zig, beside the snake's
+ // library): the addon pipeline's colour factor, which the snake's
+ // opaque picture never shows.
+ try f.write("/ctl", f.at("Addon load {s}/libveil.so\n", .{std.fs.path.dirname(snake).?}));
+ try f.write(f.at("/pane/{d}/exec", .{first}), "Veil\n");
+ try k.keep(&d, 0, "12 a translucent addon picture over its pane", false);
+ }
+ // 12. The snake: an addon's GPU scene and its CRT post-process,
+ // through the premultiplied pipeline. A window of its own: its picture
+ // breathes on the clock, and a long session's clock has seen the
+ // machine's timing (a timer an input cancelled, or not yet).
+ k.pruned = 0;
+ {
+ try corpusRoot(a);
+ var d = try process.Detached.start(gpa, exe, "corpus-snake", .{ .root = root, .file = root ++ "/shapes.zig", .init = init, .grid = .{ 80, 24 }, .env = &.{
+ .{ "PARDES_TEST_CLOCK", "1" }, .{ "PARDES_TEST_SERIES", "1" }, .{ "PARDES_TEST_PAD", "7" },
+ } });
+ defer d.deinit();
+ const f = &d.files;
+ const first = try paneWith(f, "shapes.zig");
+ _ = try k.rest(&d);
+ try f.write("/ctl", f.at("Addon load {s}\n", .{snake}));
+ try k.keep(&d, 0, "12 the snake addon loaded", false);
+ const from = try k.mark(&d);
+ const before = try f.read("/index");
+ try f.write(f.at("/pane/{d}/exec", .{first}), "SnakeShader\n");
+ try k.first(&d, from, 10, "12 SnakeShader's CRT scene, its first frames");
+ // Then gone, and the window at rest: it ends having drawn as many
+ // frames every run (an instruction count's, perfwrap.sh).
+ try f.write(f.at("/pane/{d}/exec", .{try paneSince(f, before)}), "Del\n");
+ _ = try k.rest(&d);
+ }
+ // 2. Scene 1 at a 2x display.
+ k.pruned = 0;
+ {
+ try corpusRoot(a);
+ var d = try process.Detached.start(gpa, exe, "corpus2x", .{ .root = root, .file = root ++ "/shapes.zig", .init = init, .grid = .{ 50, 14 }, .env = &.{
+ .{ "PARDES_TEST_CLOCK", "1" }, .{ "PARDES_TEST_SERIES", "1" }, .{ "PARDES_TEST_PAD", "7" }, .{ "PARDES_TEST_SCALE", "2" },
+ } });
+ defer d.deinit();
+ const f = &d.files;
+ const first = try paneWith(f, "shapes.zig");
+ try k.keep(&d, 0, "02 the zig file at a 2x display", false);
+ try f.write(f.at("/pane/{d}/dot", .{first}), "20,22\n");
+ try k.keep(&d, 0, "02 a selection at a 2x display", false);
+ }
+ try k.finish();
+}
diff --git a/test/veil.zig b/test/veil.zig
new file mode 100644
index 00000000..ed49e1c3
--- /dev/null
+++ b/test/veil.zig
@@ -0,0 +1,37 @@
+//! A test addon whose GPU picture is translucent: its pass draws nothing
+//! and clears to a premultiplied half-alpha colour, so the window's addon
+//! pipeline blends it over the pane (the frame corpus's case for the
+//! pipeline's colour factor, which an opaque picture never shows).
+const std = @import("std");
+const addon = @import("addon");
+const scene = @import("gpu_scene");
+
+pub const Veil = extern struct {
+ painted: u32,
+
+ pub const head: addon.Head = .{ .name = "veil", .version = 1, .words = &.{
+ .{ .name = "Veil", .opens = true, .doc = "a translucent GPU picture over the pane (a test addon)" },
+ } };
+
+ pub fn open(v: *Veil, _: ?[]const u8, _: ?[]const u8) void {
+ v.painted = 0;
+ }
+
+ pub fn paint(_: *const Veil, w: addon.Window, out: addon.Paint) void {
+ w.put(0, 0, "veil over this", .{});
+ const width: u32 = @min(4096, @max(1, @as(u32, w.cols) * w.cell_w));
+ const height: u32 = @min(4096, @max(1, @as(u32, w.rows) * w.cell_h));
+ var buffer: [256]u8 = undefined;
+ var writer: std.Io.Writer = .fixed(&buffer);
+ scene.encode(&writer, .{ .image = .none, .width = width, .height = height, .clear = .{ 0.30, 0.10, 0.20, 0.5 }, .pipelines = &.{}, .draws = &.{} }) catch return;
+ _ = out.gpu(writer.buffered());
+ }
+
+ pub const dump = addon.dumpBytes;
+ pub const load = addon.loadBytes;
+};
+
+pub const pardes_addon = addon.ops(Veil);
+comptime {
+ addon.exportLib(&pardes_addon);
+}