diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-13 15:07:42 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-13 15:07:42 -0300 |
| commit | d3074636fff0fbcd5fd9b71c0c3b1c1f5c0c1285 (patch) | |
| tree | 918d67acc8f00f72cc4ae1ba444e41238a689c2b | |
| parent | 409c1accefeb7a775c0914c888b469a1e78fc69a (diff) | |
| download | sketchbook-d3074636fff0fbcd5fd9b71c0c3b1c1f5c0c1285.tar.gz sketchbook-d3074636fff0fbcd5fd9b71c0c3b1c1f5c0c1285.zip | |
| -rw-r--r-- | README.md | 18 | ||||
| -rw-r--r-- | build.zig | 35 | ||||
| -rw-r--r-- | src/host/Host.zig | 58 | ||||
| -rw-r--r-- | src/tracy.zig | 50 | ||||
| -rw-r--r-- | test/fonts.c | 12 | ||||
| -rw-r--r-- | vendor/fonts/README.md | 4 | ||||
| -rw-r--r-- | vendor/text.c | 8 |
7 files changed, 154 insertions, 31 deletions
@@ -889,3 +889,21 @@ canvas, in release mode, and fails if a simple one (30 shapes) takes 1 ms to parse and draw: an equation of 8 shapes parses in 0.02 ms, draws on the CPU in 0.25 ms, and is recorded as a GPU pass in 0.02 ms (the GPU's own time is not measured). + +### Optional native profiling + +Build the host with `zig build -Doptimize=ReleaseFast -Dtracy=/absolute/path/to/tracy`. +The checkout supplies `public/TracyClient.cpp`; no profiler is downloaded or +linked by default. Linked native apps pass their `-Dtracy` option to `sketchbook.init` as +`.tracy = path` and can import `sb.modules.tracy` for their own zones: +`const zone = tracy.zone(@src(), "work"); defer zone.end();`. +The host marks frames, input polling, drawing, command painting and presentation. +These are CPU wall times (presentation includes waits), not GPU timestamps. +Use a matching `tracy-capture` or the Tracy UI. Disabled builds compile the +calls out; tests disable their zones too. The wrapper follows Pardes's small +Zig Tracy binding. Forward the same option through dependencies that also +initialize Sketchbook so the build shares one host/client module. + +ASCII text caches coverage independently of animated ink. The pinned SDL Vulkan +patch keeps memory relocation disabled and lets small transfer buffers share +allocations, avoiding hundreds of dedicated allocation frees during presentation. @@ -37,13 +37,26 @@ pub fn build(b: *Build) void { const sketch_imports: []const Build.Module.Import = &.{ .{ .name = "abi", .module = abi }, .{ .name = "math", .module = math } }; const sketch = b.addModule("sketch", .{ .root_source_file = b.path("src/sketch/root.zig"), .imports = sketch_imports }); + const tracy_path = b.option([]const u8, "tracy", "Enable Tracy with this source checkout (disabled by default)") orelse ""; + const profile_options = b.addOptions(); + profile_options.addOption(bool, "enabled", tracy_path.len > 0); + const tracy = b.addModule("tracy", .{ .root_source_file = b.path("src/tracy.zig"), .target = target, .optimize = optimize }); + tracy.addOptions("profile_options", profile_options); + if (tracy_path.len > 0) { + tracy.addIncludePath(.{ .cwd_relative = tracy_path }); + tracy.addCSourceFile(.{ + .file = .{ .cwd_relative = b.pathJoin(&.{ tracy_path, "public", "TracyClient.cpp" }) }, + .flags = &.{ "-DTRACY_ENABLE=1", "-DTRACY_NO_SAMPLING", "-DTRACY_NO_CALLSTACK", "-DTRACY_NO_SYSTEM_TRACING", "-DTRACY_NO_CRASH_HANDLER", "-DTRACY_NO_CODE_TRANSFER", "-fno-sanitize=undefined" }, + }); + tracy.link_libcpp = true; + } const c = cModule(b, target, optimize); // No optimize mode of its own: the host's Zig code builds in the mode // of the executable it is part of (`script_optimize` makes use of it). const host = b.addModule("host", .{ .root_source_file = b.path("src/host/root.zig"), .target = target, - .imports = &.{ .{ .name = "abi", .module = abi }, .{ .name = "c", .module = c } }, + .imports = &.{ .{ .name = "abi", .module = abi }, .{ .name = "c", .module = c }, .{ .name = "tracy", .module = tracy } }, }); const host_exe = b.addExecutable(.{ @@ -68,7 +81,7 @@ pub fn build(b: *Build) void { }); b.installArtifact(probe); - var sb: Sketchbook = .{ .b = b, .target = target, .optimize = optimize, .modules = .{ .abi = abi, .sketch = sketch, .host = host, .vector = undefined, .scope = undefined, .anim = undefined }, .host_exe = host_exe, .probe_exe = probe, .web = b.path("web"), .glsl = b.path("src/glsl.zig"), .tools = b.path("tools"), .anim_dir = b.path("src/anim"), .script_optimize = optimize, .shared = .create(b) }; + var sb: Sketchbook = .{ .b = b, .target = target, .optimize = optimize, .modules = .{ .abi = abi, .sketch = sketch, .host = host, .tracy = tracy, .vector = undefined, .scope = undefined, .anim = undefined }, .host_exe = host_exe, .probe_exe = probe, .web = b.path("web"), .glsl = b.path("src/glsl.zig"), .tools = b.path("tools"), .anim_dir = b.path("src/anim"), .script_optimize = optimize, .shared = .create(b) }; // Vector graphics: built with the same shader step apps use. Both forms // of its shaders are exported, so apps' web builds can swap them too. @@ -124,7 +137,7 @@ pub fn build(b: *Build) void { b.createModule(.{ .root_source_file = b.path("src/abi.zig"), .target = target, .optimize = optimize }), b.createModule(.{ .root_source_file = b.path("src/sketch/root.zig"), .target = target, .optimize = optimize, .imports = sketch_imports }), b.createModule(.{ .root_source_file = b.path("src/math/root.zig"), .target = target, .optimize = optimize }), - b.createModule(.{ .root_source_file = b.path("src/host/root.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "abi", .module = abi }, .{ .name = "c", .module = c } } }), + b.createModule(.{ .root_source_file = b.path("src/host/root.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "abi", .module = abi }, .{ .name = "c", .module = c }, .{ .name = "tracy", .module = tracy } } }), }) |module| test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module })).step); // The noise tests again on wasm32 as the web builds it, under Node's @@ -362,7 +375,9 @@ fn fixSdlThreadCleanup(b: *Build, sdl: *Build.Module, source: Build.LazyPath) vo /// far went to the old texture and the rest to the copy, which shows the /// previous frame under it (seen after a large texture was freed, at /// 1920x1080 and up). Freed memory is still reused; it is only not -/// compacted. +/// compacted. With relocation disabled, small transfer buffers can also +/// suballocate safely instead of freeing hundreds of dedicated Vulkan +/// allocations during presentation. fn fixSdlVulkanAllocationLeak(b: *Build, sdl: *Build.Module, source: Build.LazyPath) void { const file = "src/gpu/vulkan/SDL_gpu_vulkan.c"; var found = false; @@ -388,6 +403,7 @@ fn fixSdlVulkanAllocationLeak(b: *Build, sdl: *Build.Module, source: Build.LazyP }) }); const edit = b.addRunArtifact(tool); edit.setName("patch SDL_gpu_vulkan.c"); + edit.addFileInput(source.path(b, "gpu/vulkan/SDL_gpu_vulkan.c")); edit.addDirectoryArg(source.path(b, "gpu/vulkan")); const out = edit.addOutputDirectoryArg("vulkan"); edit.addArgs(&.{ @@ -397,6 +413,9 @@ fn fixSdlVulkanAllocationLeak(b: *Build, sdl: *Build.Module, source: Build.LazyP "SDL_gpu_vulkan.c", " VULKAN_INTERNAL_MarkAllocationsForDefrag(renderer);\n", " (void)VULKAN_INTERNAL_MarkAllocationsForDefrag;\n", + "SDL_gpu_vulkan.c", + " VULKAN_BUFFER_TYPE_TRANSFER,\n true, // Dedicated allocations preserve the data even if a defrag is triggered.\n", + " VULKAN_BUFFER_TYPE_TRANSFER,\n false, // Sketchbook disables defrag, so small transfers can share allocations.\n", }); // The copy's relative includes (`../SDL_sysgpu.h`) resolve from the // original directory. @@ -413,6 +432,8 @@ pub const Options = struct { optimize: std.builtin.OptimizeMode, /// This package's name in the app's build.zig.zon. dependency: []const u8 = "sketchbook", + /// An existing Tracy checkout; null leaves native profiling compiled out. + tracy: ?[]const u8 = null, /// The optimize mode of the executables `e2e` plays scripts with /// (`App.addScriptExecutable`); `optimize` when null. Pass it a /// `b.option`, say `-Dscript-optimize=ReleaseSafe`, when Debug is too @@ -422,7 +443,7 @@ pub const Options = struct { }; pub fn init(b: *Build, options: Options) Sketchbook { - const dep = b.dependency(options.dependency, .{ .target = options.target, .optimize = options.optimize }); + const dep = b.dependency(options.dependency, .{ .target = options.target, .optimize = options.optimize, .tracy = options.tracy orelse "" }); const shared: *Shared = .create(b); for ([_][]const u8{ "vector_shaders", "scope_shaders" }) |name| { shared.web_twins.put(b.graph.arena, dep.module(name), dep.module(b.fmt("{s}_web", .{name}))) catch @panic("OOM"); @@ -431,7 +452,7 @@ pub fn init(b: *Build, options: Options) Sketchbook { .b = b, .target = options.target, .optimize = options.optimize, - .modules = .{ .abi = dep.module("abi"), .sketch = dep.module("sketch"), .host = dep.module("host"), .vector = dep.module("vector"), .scope = dep.module("scope"), .anim = dep.module("anim") }, + .modules = .{ .abi = dep.module("abi"), .sketch = dep.module("sketch"), .host = dep.module("host"), .tracy = dep.module("tracy"), .vector = dep.module("vector"), .scope = dep.module("scope"), .anim = dep.module("anim") }, .host_exe = dep.artifact("sketchbook"), .probe_exe = dep.artifact("sketchbook-probe"), .web = dep.path("web"), @@ -476,7 +497,7 @@ pub const Sketchbook = struct { /// `vector`: SVG, cubic geometry, and CPU and GPU renderers. `scope`: /// waveform, spectrogram, spectrum and oscilloscope views of a sound. /// `anim`: manim-style scenes as code (see `addScene`). - modules: struct { abi: *Build.Module, sketch: *Build.Module, host: *Build.Module, vector: *Build.Module, scope: *Build.Module, anim: *Build.Module }, + modules: struct { abi: *Build.Module, sketch: *Build.Module, host: *Build.Module, tracy: *Build.Module, vector: *Build.Module, scope: *Build.Module, anim: *Build.Module }, /// The generic host: loads and hot-reloads a sketch library. host_exe: *Build.Step.Compile, /// Prints any sketch's state file. diff --git a/src/host/Host.zig b/src/host/Host.zig index 43f030a..008d143 100644 --- a/src/host/Host.zig +++ b/src/host/Host.zig @@ -3,6 +3,7 @@ //! exercise exactly what a player does. const Host = @This(); const std = @import("std"); +const tracy = @import("tracy"); const c = @import("c"); const abi = @import("abi"); const memory = @import("memory.zig"); @@ -246,6 +247,9 @@ pub fn live(self: *Host) []u8 { /// One frame: reload if a build replaced the library, feed input through /// `update`, then `draw` and present. pub fn frame(self: *Host, now: u64) !void { + const zone = tracy.zone(@src(), "frame"); + tracy.frameMark(); + defer zone.end(); _ = self.frame_arena.reset(.retain_capacity); self.commands = .empty; if (self.watch) |w| if (w.changed()) self.reload() catch |err| self.print("reload failed: {t}", .{err}); @@ -318,6 +322,8 @@ fn restoredInput(self: *Host, now: u64) !void { } fn draw(self: *Host, now: u64) !void { + const zone = tracy.zone(@src(), "Host.zig:draw"); + defer zone.end(); const arena = self.frame_arena.allocator(); self.input.now = now; self.input.mode = self.timeline.mode; @@ -356,27 +362,31 @@ fn draw(self: *Host, now: u64) !void { self.audio.beginFrame(); self.painter.begin(self.offscreen, self.canvas, arena); var lines: std.ArrayList([]const u8) = .empty; - for (self.commands.items) |command| switch (command) { - .canvas => |size| { - self.painter.end(); - self.setCanvas(size.w, size.h); - self.painter.begin(self.offscreen, self.canvas, arena); - }, - .cursor => |kind| self.cursor = kind, - .voice => |voice| self.audio.declare(voice), - .audio => |a| self.audio.push(a.key, a.samples, a.clear), - .quit => self.quit = true, - .gpu => |pass| if (self.passes) |*g| g.run(&self.images, pass) catch |err| self.print("gpu pass: {t} ({s})", .{ err, c.SDL_GetError() }), - .upload => |u| if (self.passes) |*g| g.write(u.buffer, u.offset, u.bytes) catch |err| self.print("gpu upload: {t} ({s})", .{ err, c.SDL_GetError() }), - .compute => |d| if (self.passes) |*g| g.compute(d) catch |err| self.print("gpu compute: {t} ({s})", .{ err, c.SDL_GetError() }), - .microphone => self.audio.listen(), - .download => |d| if (self.passes) |*g| g.download(d) catch |err| self.print("gpu download: {t} ({s})", .{ err, c.SDL_GetError() }), - .open_file => |o| self.openFile(o.command, o.pattern), - .run => |line| try lines.append(arena, line), - else => self.painter.draw(command), - }; - self.painter.end(); - self.audio.endFrame(); + { + const paint_zone = tracy.zone(@src(), "paint commands"); + defer paint_zone.end(); + for (self.commands.items) |command| switch (command) { + .canvas => |size| { + self.painter.end(); + self.setCanvas(size.w, size.h); + self.painter.begin(self.offscreen, self.canvas, arena); + }, + .cursor => |kind| self.cursor = kind, + .voice => |voice| self.audio.declare(voice), + .audio => |a| self.audio.push(a.key, a.samples, a.clear), + .quit => self.quit = true, + .gpu => |pass| if (self.passes) |*g| g.run(&self.images, pass) catch |err| self.print("gpu pass: {t} ({s})", .{ err, c.SDL_GetError() }), + .upload => |u| if (self.passes) |*g| g.write(u.buffer, u.offset, u.bytes) catch |err| self.print("gpu upload: {t} ({s})", .{ err, c.SDL_GetError() }), + .compute => |d| if (self.passes) |*g| g.compute(d) catch |err| self.print("gpu compute: {t} ({s})", .{ err, c.SDL_GetError() }), + .microphone => self.audio.listen(), + .download => |d| if (self.passes) |*g| g.download(d) catch |err| self.print("gpu download: {t} ({s})", .{ err, c.SDL_GetError() }), + .open_file => |o| self.openFile(o.command, o.pattern), + .run => |line| try lines.append(arena, line), + else => self.painter.draw(command), + }; + self.painter.end(); + self.audio.endFrame(); + } for (lines.items) |line| self.runLine(line, now) catch {}; var extra: std.ArrayList(abi.Command) = .empty; @@ -404,7 +414,9 @@ fn draw(self: *Host, now: u64) !void { _ = c.SDL_SetTextureBlendMode(canvas, c.SDL_BLENDMODE_NONE); _ = c.SDL_RenderTexture(self.renderer, canvas, null, null); }; + const present_zone = tracy.zone(@src(), "present"); _ = c.SDL_RenderPresent(self.renderer); + present_zone.end(); if (self.passes) |*g| g.endFrame(); } @@ -535,6 +547,8 @@ pub fn route(self: *Host, e: abi.Event) !void { /// Runs a console line now, replaying whatever a seek asks for. An error is /// printed to the console, and returned for scripts to fail on. pub fn runLine(self: *Host, line: []const u8, now: u64) !void { + const zone = tracy.zone(@src(), "Host.zig:runLine"); + defer zone.end(); const replay = self.console.execute(self, line, now) catch |err| { // The sketch has printed its own error already. if (err != error.CommandFailed) self.console.print("{t}. Type help for usage.", .{err}); @@ -681,6 +695,8 @@ pub fn print(self: *Host, comptime fmt: []const u8, args: anytype) void { /// Translates SDL events into sketch events and routes them. pub fn poll(self: *Host) !void { + const zone = tracy.zone(@src(), "Host.zig:poll"); + defer zone.end(); var event: c.SDL_Event = undefined; while (c.SDL_PollEvent(&event)) { _ = c.SDL_ConvertEventToRenderCoordinates(self.renderer, &event); diff --git a/src/tracy.zig b/src/tracy.zig new file mode 100644 index 0000000..889ba56 --- /dev/null +++ b/src/tracy.zig @@ -0,0 +1,50 @@ +//! Minimal Tracy client (the Zig compiler's pattern): `zone(@src(), "name")` +//! ... `.end()`, plus `frameMark()`. Everything compiles to a no-op unless the +//! build sets -Dtracy=<path-to-tracy-checkout>, which also compiles and links +//! TracyClient.cpp. Capture with tracy-capture, inspect with tracy-csvexport. +const std = @import("std"); +const builtin = @import("builtin"); + +pub const enable = if (builtin.is_test) false else @import("profile_options").enabled; + +const SourceLocation = extern struct { + name: ?[*:0]const u8, + function: [*:0]const u8, + file: [*:0]const u8, + line: u32, + color: u32, +}; + +pub const Ctx = if (enable) extern struct { + id: u32, + active: i32, + + pub inline fn end(c: @This()) void { + ___tracy_emit_zone_end(c); + } +} else struct { + pub inline fn end(_: @This()) void {} +}; + +pub inline fn zone(comptime src: std.builtin.SourceLocation, comptime name: [:0]const u8) Ctx { + if (!enable) return .{}; + const static = struct { + const loc: SourceLocation = .{ + .name = name.ptr, + .function = src.fn_name.ptr, + .file = src.file.ptr, + .line = src.line, + .color = 0, + }; + }; + return ___tracy_emit_zone_begin(&static.loc, 1); +} + +pub inline fn frameMark() void { + if (!enable) return; + ___tracy_emit_frame_mark(null); +} + +extern fn ___tracy_emit_zone_begin(srcloc: *const SourceLocation, active: c_int) Ctx; +extern fn ___tracy_emit_zone_end(ctx: Ctx) void; +extern fn ___tracy_emit_frame_mark(name: ?[*:0]const u8) void; diff --git a/test/fonts.c b/test/fonts.c index 87a47bb..cd3b9ff 100644 --- a/test/fonts.c +++ b/test/fonts.c @@ -54,7 +54,19 @@ int main(int argc, char **argv) { SDL_Rect clip={30,620,400,30}; SDL_SetRenderClipRect(r,&clip); assert(sk_text_draw(r,30,617,1.6f,"Clipping preserves the baseline and glyph edges outside this box",strlen("Clipping preserves the baseline and glyph edges outside this box"),112,183,255,255)); SDL_SetRenderClipRect(r,NULL); + assert(sk_text_draw(r,30,680,1.6f,"animated ink",12,240,20,40,255)); + const size_t cached_bytes = c->bytes; + assert(sk_text_draw(r,30,730,1.6f,"animated ink",12,40,20,240,128)); + assert(c->bytes == cached_bytes); /* Color and opacity reuse the coverage mask. */ assert(SDL_RenderPresent(r)); + unsigned red_pixels = 0, blue_pixels = 0; + for (int y=680; y<780; ++y) for (int x=30; x<250; ++x) { + Uint8 red, green, blue, alpha; + assert(SDL_ReadSurfacePixel(surface,x,y,&red,&green,&blue,&alpha)); + if (y<710 && red>150 && blue<100) ++red_pixels; + if (y>=730 && blue>70 && red<70) ++blue_pixels; + } + assert(red_pixels>50 && blue_pixels>50); if(argc>1) assert(SDL_SavePNG(surface,argv[1])); assert(SDL_SetRenderLogicalPresentation(r,720,410,SDL_LOGICAL_PRESENTATION_LETTERBOX)); assert(fabsf(density(r)-2)<0.01f); diff --git a/vendor/fonts/README.md b/vendor/fonts/README.md index 41a51fc..b02fd51 100644 --- a/vendor/fonts/README.md +++ b/vendor/fonts/README.md @@ -46,7 +46,9 @@ environment, names an installed family to put before Go Mono. Text is rasterized at the renderer's physical pixel density (including logical presentation scale), and texture origins snap to physical pixels. Whole-run textures retain antialiasing and shaping; no scaled 8×8 bitmap text is involved. -The renderer-owned cache retains at most 512 strings / 16 MiB of pixel data. +The renderer-owned cache retains at most 4096 strings / 128 MiB of pixel data. +ASCII runs cache white coverage masks and tint at draw time, so animated ink +reuses the same pixels. Unicode retains painted glyphs, including color emoji. Only prior-frame textures can be evicted; exceptionally dense frames flush and release temporary textures rather than growing the cache. Renderer destruction releases the font map, descriptors and keys after SDL releases its textures. diff --git a/vendor/text.c b/vendor/text.c index 8b2a54e..a453067 100644 --- a/vendor/text.c +++ b/vendor/text.c @@ -277,7 +277,11 @@ bool sk_text_draw_scaled(SDL_Renderer *renderer, int face, float x, float y, flo const int size = font_size(raster, dpi); /* How much larger than rasterized it is drawn: 1 when it is drawn as it is. */ const float k = scale / raster; - const Uint32 color = ((Uint32)r << 16) | ((Uint32)g << 8) | b; + /* ASCII uses a reusable coverage mask; animated ink never rerasterizes it. + Keep the existing painted path for Unicode, including color emoji. */ + bool mask = true; + for (size_t i = 0; i < len; ++i) if ((unsigned char)utf8[i] >= 128) { mask = false; break; } + const Uint32 color = mask ? 0xffffff : ((Uint32)r << 16) | ((Uint32)g << 8) | b; const uint64_t hash = hash_text(utf8, len); Text *entry = NULL; for (size_t i = 0; i < CACHE_ENTRIES; ++i) { @@ -309,7 +313,7 @@ bool sk_text_draw_scaled(SDL_Renderer *renderer, int face, float x, float y, flo entry->used = c->frame; /* Cairo pixels are premultiplied; modulate RGB and alpha together. Color glyphs retain their intrinsic paint, while ordinary text uses its ink. */ - SDL_SetTextureColorMod(entry->texture, a, a, a); + SDL_SetTextureColorMod(entry->texture, mask ? r * a / 255 : a, mask ? g * a / 255 : a, mask ? b * a / 255 : a); SDL_SetTextureAlphaMod(entry->texture, a); SDL_FRect dest = {.x=(roundf(x*dpi)+entry->left)/dpi,.y=(roundf(y*dpi)+entry->top)/dpi, .w=entry->width/dpi,.h=entry->height/dpi}; |
