From 86ffca0024326110962f0880727f4eb84e6a48d1 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 10 Nov 2026 11:13:20 -0300 Subject: 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 --- src/host/Host.zig | 70 +++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 60 insertions(+), 10 deletions(-) (limited to 'src/host/Host.zig') 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 `/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: `/.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); } -- cgit v1.3