diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-10 11:13:20 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-12 13:22:02 -0300 |
| commit | 86ffca0024326110962f0880727f4eb84e6a48d1 (patch) | |
| tree | 055f489341053c1db258606bb63b282bc7345a89 /src/host | |
| parent | a62a6aa896adda901d335ef38814a13b8839545c (diff) | |
| download | sketchbook-86ffca0024326110962f0880727f4eb84e6a48d1.tar.gz sketchbook-86ffca0024326110962f0880727f4eb84e6a48d1.zip | |
sketchbook: frames for ffmpeg (--export, on a clock of its own), text sizes, a font from the environment
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Diffstat (limited to 'src/host')
| -rw-r--r-- | src/host/Host.zig | 70 | ||||
| -rw-r--r-- | src/host/gfx.zig | 10 | ||||
| -rw-r--r-- | src/host/root.zig | 40 |
3 files changed, 107 insertions, 13 deletions
diff --git a/src/host/Host.zig b/src/host/Host.zig index de19b99..4b5f2a4 100644 --- a/src/host/Host.zig +++ b/src/host/Host.zig @@ -28,6 +28,15 @@ pub const Options = struct { fresh: bool = false, /// Time every GPU command alone and print the times at exit. profile_gpu: bool = false, + /// Export every frame: PNGs `<dir>/000000.png`, ..., or for "-" raw RGBA + /// rows on stdout. Frames run on a clock of their own (see `fps`). + export_to: ?[]const u8 = null, + /// Export: frame k is k/fps seconds in, each tick exactly 1/fps. + fps: u32 = 60, + /// Export: stop after this many frames; null: when the sketch quits. + frames: ?u64 = null, + /// The first canvas and, headless, the room for it (`window_width`). + size: ?[2]u32 = null, }; gpa: std.mem.Allocator, @@ -86,6 +95,8 @@ started: bool = true, last_now: u64 = 0, /// Saved after the next frame is drawn (scripts). screenshot: ?[:0]const u8 = null, +/// Frames exported so far (`Options.export_to`). +exported: u64 = 0, dialog: Dialog = .{}, pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, options: Options, linked: ?abi.Sketch) !void { @@ -164,6 +175,7 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std .library = library, .info_arena = .init(gpa), .frame_arena = .init(gpa), + .input = .{ .exporting = options.export_to != null }, }; self.timeline = .{ .bank = .{ .state = &self.state, .inputs = recordings } }; self.painter.images = &self.images; @@ -175,7 +187,8 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std if (options.library) |path| if (linked == null) { self.watch = Watch.init(path) catch null; }; - self.setCanvas(info.width, info.height); + const size = options.size orelse [2]u32{ info.width, info.height }; + self.setCanvas(size[0], size[1]); _ = c.SDL_StartTextInput(self.window); self.build = fileHash(options.library orelse "/proc/self/exe"); try self.adopt(sketch); @@ -217,11 +230,12 @@ pub fn deinit(self: *Host) void { c.SDL_Quit(); } -/// The interactive loop. +/// The interactive loop. An export runs it on a clock of its own, frame k +/// at k/fps seconds (from 1 s, as scripts do), whatever the wall clock says. pub fn run(self: *Host) !void { while (!self.quit) { try self.poll(); - try self.frame(c.SDL_GetTicksNS()); + try self.frame(if (self.options.export_to == null) c.SDL_GetTicksNS() else std.time.ns_per_s + self.exported * std.time.ns_per_s / self.options.fps); } self.timeline.stop(c.SDL_GetTicksNS()); } @@ -246,7 +260,10 @@ pub fn frame(self: *Host, now: u64) !void { .live, .recording => { // One frame: what was routed since the last one, then its tick. // Recorded first, so `update` sees the times a replay will. - try self.pending.append(self.gpa, abi.Event.tick(now, dt)); + var tick = abi.Event.tick(now, dt); + // An export's tick is 1/fps itself, not whole nanoseconds of it. + if (self.options.export_to != null and dt != 0) tick.x = 1 / @as(f32, @floatFromInt(self.options.fps)); + try self.pending.append(self.gpa, tick); h.capture(self.pending.items) catch |err| self.print("Recording stopped: {t}", .{err}); self.update(self.pending.items); }, @@ -312,9 +329,11 @@ fn draw(self: *Host, now: u64) !void { self.input.console = self.console.visible; self.input.width = @floatFromInt(self.canvas[0]); self.input.height = @floatFromInt(self.canvas[1]); - // Headless runs have no window to fill: the canvas is all the room. - self.input.window_width = self.input.width; - self.input.window_height = self.input.height; + // Headless runs have no window to fill: the canvas is all the room, + // unless `--size` gives one. + const room = if (self.options.size) |size| size else self.canvas; + self.input.window_width = @floatFromInt(room[0]); + self.input.window_height = @floatFromInt(room[1]); if (!self.options.headless) { var w: c_int = 0; var h: c_int = 0; @@ -371,16 +390,43 @@ fn draw(self: *Host, now: u64) !void { self.painter.end(); self.applyCursor(); - if (self.screenshot) |path| { - self.screenshot = null; + if (self.screenshot != null or self.options.export_to != null) { const surface = c.SDL_RenderReadPixels(self.renderer, null) orelse return sdlError("SDL_RenderReadPixels"); defer c.SDL_DestroySurface(surface); - if (!c.SDL_SavePNG(surface, path.ptr)) return sdlError("SDL_SavePNG"); + if (self.screenshot) |path| { + self.screenshot = null; + if (!c.SDL_SavePNG(surface, path.ptr)) return sdlError("SDL_SavePNG"); + } + if (self.options.export_to) |to| try self.exportFrame(surface, to); } _ = c.SDL_RenderPresent(self.renderer); if (self.passes) |*g| g.endFrame(); } +/// One exported frame: `<to>/<its number, six digits>.png`, or for "-" its +/// RGBA rows on stdout (`ffmpeg -f rawvideo -pix_fmt rgba`). +fn exportFrame(self: *Host, surface: *c.SDL_Surface, to: []const u8) !void { + if (std.mem.eql(u8, to, "-")) { + // The offscreen canvas is RGBA already; a renderer without a GPU may not be. + const rgba = if (surface.*.format == c.SDL_PIXELFORMAT_RGBA32) surface else c.SDL_ConvertSurface(surface, c.SDL_PIXELFORMAT_RGBA32) orelse return sdlError("SDL_ConvertSurface"); + defer if (rgba != surface) c.SDL_DestroySurface(rgba); + const pixels: [*]const u8 = @ptrCast(rgba.*.pixels.?); + const row: usize = @intCast(rgba.*.w * 4); + const pitch: usize = @intCast(rgba.*.pitch); + const rows: usize = @intCast(rgba.*.h); + const out = std.Io.File.stdout(); + if (pitch == row) try out.writeStreamingAll(self.io, pixels[0 .. row * rows]) else for (0..rows) |y| try out.writeStreamingAll(self.io, pixels[y * pitch ..][0..row]); + } else { + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = std.mem.printSentinel(&buf, "{s}/{d:0>6}.png", .{ to, self.exported }, 0) catch return error.NameTooLong; + if (!c.SDL_SavePNG(surface, path.ptr)) return sdlError("SDL_SavePNG"); + } + self.exported += 1; + if (self.options.frames) |n| if (self.exported >= n) { + self.quit = true; + }; +} + /// A file dialog: shown on request, its answer run as a console line from /// the main loop. SDL may answer on another thread. const Dialog = struct { @@ -734,6 +780,7 @@ const api: abi.Host.VTable = .{ .newBuffer = apiNewBuffer, .freeBuffer = apiFreeBuffer, .imageSize = apiImageSize, + .textSize = apiTextSize, .loadSound = apiLoadSound, .decodeSound = apiDecodeSound, .samples = apiSamples, @@ -787,6 +834,9 @@ fn apiSamples(ctx: *anyopaque, audio: abi.Audio) []const f32 { fn apiImageSize(ctx: *anyopaque, image: abi.Image) [2]u32 { return hostOf(ctx).images.size(image); } +fn apiTextSize(ctx: *anyopaque, scale: f32, bytes: []const u8) [2]f32 { + return gfx.textSize(hostOf(ctx).renderer, scale, bytes); +} fn apiLoadSound(ctx: *anyopaque, path: []const u8) abi.Audio { return hostOf(ctx).audio.load(path); } diff --git a/src/host/gfx.zig b/src/host/gfx.zig index 20b4dcc..3affa6e 100644 --- a/src/host/gfx.zig +++ b/src/host/gfx.zig @@ -555,6 +555,16 @@ pub fn drawText(renderer: *c.SDL_Renderer, x: f32, y: f32, scale: f32, bytes: [] if (clipped and s != 1) _ = c.SDL_SetRenderClipRect(renderer, &clip); } +/// What `drawText` gives `bytes` at `scale`: its width and the height of +/// its line, in canvas units (`Host.textSize`). +pub fn textSize(renderer: *c.SDL_Renderer, scale: f32, bytes: []const u8) [2]f32 { + var size: [2]f32 = .{ 0, 0 }; + if (@import("builtin").os.tag == .linux and c.sk_text_measure(renderer, scale, bytes.ptr, bytes.len, &size[0], &size[1])) return size; + // The debug font's 8 px cells. + const s = @max(scale, 1); + return .{ @as(f32, @floatFromInt(bytes.len)) * 8 * s, 8 * s }; +} + fn premultiply(color: abi.Color) abi.Color { const a: u32 = color.a; return .{ .r = @intCast((color.r * a + 127) / 255), .g = @intCast((color.g * a + 127) / 255), .b = @intCast((color.b * a + 127) / 255), .a = color.a }; diff --git a/src/host/root.zig b/src/host/root.zig index 8cc15e1..d01a63f 100644 --- a/src/host/root.zig +++ b/src/host/root.zig @@ -9,6 +9,11 @@ //! --profile-gpu time each GPU command alone, print the times at exit //! --console LINE run a console line once the sketch is loaded (repeatable) //! --define NAME=VALUE substitute {NAME} in the script +//! --export DIR|- headless, from fresh state: every frame as DIR/000000.png, ... +//! or for - as raw RGBA on stdout, until the sketch quits +//! --fps N export: frames a second (60); each tick is exactly 1/N s +//! --frames N export: stop after N frames +//! --size WxH the first canvas and, headless, the room for it const std = @import("std"); const c = @import("c"); const abi = @import("abi"); @@ -48,6 +53,22 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void { const pair = args.next() orelse fatal("--define needs NAME=VALUE"); const eq = std.mem.indexOfScalar(u8, pair, '=') orelse fatal("--define needs NAME=VALUE"); try defines.append(gpa, .{ pair[0..eq], pair[eq + 1 ..] }); + } else if (std.mem.eql(u8, arg, "--export")) { + options.export_to = args.next() orelse fatal("--export needs a directory, or - for stdout"); + options.headless = true; + options.fresh = true; + } else if (std.mem.eql(u8, arg, "--fps")) { + options.fps = std.fmt.parseInt(u32, args.next() orelse "", 10) catch 0; + if (options.fps == 0) fatal("--fps needs a whole number of frames a second"); + } else if (std.mem.eql(u8, arg, "--frames")) { + options.frames = std.fmt.parseInt(u64, args.next() orelse "", 10) catch fatal("--frames needs a number"); + } else if (std.mem.eql(u8, arg, "--size")) { + const size = args.next() orelse ""; + const x = std.mem.indexOfScalar(u8, size, 'x') orelse fatal("--size needs WxH"); + const w = std.fmt.parseInt(u32, size[0..x], 10) catch 0; + const h = std.fmt.parseInt(u32, size[x + 1 ..], 10) catch 0; + if (w == 0 or h == 0) fatal("--size needs WxH"); + options.size = .{ w, h }; } else if (std.mem.eql(u8, arg, "-h") or std.mem.eql(u8, arg, "--help")) { std.debug.print("{s}", .{usage}); return; @@ -58,21 +79,29 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void { } } if (linked == null and options.library == null) fatal("no sketch library given (see --help)"); + if (options.export_to) |to| { + if (script_path != null) fatal("--export plays no script: it runs the sketch on its own"); + if (!std.mem.eql(u8, to, "-")) { + try std.Io.Dir.cwd().createDirPath(init.io, to); + } else if (try std.Io.File.stdout().isTty(init.io)) fatal("--export -: stdout is a terminal; pipe it to ffmpeg"); + } // A scripted run from fresh state works on files of its own, moved to // the given path at exit: two runs of one build step (two `zig build`s // at once share its output path) never share a state, store or - // recordings file, nor fail on the store's lock. + // recordings file, nor fail on the store's lock. An export's are + // removed instead: nothing reads them, and a player may have the given + // ones open. var private_buf: [std.fs.max_path_bytes]u8 = undefined; const given = options.state; - const private = script_path != null and options.fresh; + const private = (script_path != null or options.export_to != null) and options.fresh; if (private) options.state = std.mem.print(&private_buf, "{s}.{d}", .{ given, std.os.linux.getpid() }) catch fatal("--state path too long"); defer if (private) for ([_][]const u8{ "", ".inputs", ".store" }) |suffix| { var from: [std.fs.max_path_bytes + 16]u8 = undefined; var to: [std.fs.max_path_bytes + 16]u8 = undefined; const a = std.mem.printSentinel(&from, "{s}{s}", .{ options.state, suffix }, 0) catch continue; const b = std.mem.printSentinel(&to, "{s}{s}", .{ given, suffix }, 0) catch continue; - _ = std.os.linux.rename(a.ptr, b.ptr); + _ = if (options.export_to != null) std.os.linux.unlink(a.ptr) else std.os.linux.rename(a.ptr, b.ptr); }; sdl_heap.install(); @@ -99,6 +128,11 @@ const usage = \\ --profile-gpu time each GPU command alone, print the times at exit \\ --console LINE run a console line once the sketch is loaded (repeatable) \\ --define NAME=VALUE substitute {NAME} in the script + \\ --export DIR|- headless, from fresh state: every frame as DIR/000000.png, ... + \\ or for - as raw RGBA on stdout, until the sketch quits + \\ --fps N export: frames a second (60); each tick is exactly 1/N s + \\ --frames N export: stop after N frames + \\ --size WxH the first canvas and, headless, the room for it \\ ; |
