summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--README.md40
-rw-r--r--build.zig74
-rw-r--r--src/abi.zig14
-rw-r--r--src/host/Host.zig70
-rw-r--r--src/host/gfx.zig10
-rw-r--r--src/host/root.zig40
-rw-r--r--src/sketch/web.zig6
-rw-r--r--test/export.script11
-rw-r--r--test/export.zig23
-rw-r--r--test/text.script7
-rw-r--r--test/text.zig26
-rw-r--r--vendor/text.c38
-rw-r--r--vendor/text.h4
13 files changed, 341 insertions, 22 deletions
diff --git a/README.md b/README.md
index e364c30..181493b 100644
--- a/README.md
+++ b/README.md
@@ -93,11 +93,23 @@ State.
`imageAt`, `target`, `blend`, `text`, `print`, `clip`, `canvas`, `cursor`, `voice`, `audio`, `microphone`, `pixels`, `gpu`,
`compute`, `upload`, `download`, `openFile`, `run`, `quit`, plus the three allocators and
`f.host` (`loadImage`, `decodeImage`, `newImage`, `newBuffer`, `loadSound`,
-`decodeSound`, `samples`, `readFile`, `env`, `log`). Commands may be built
+`decodeSound`, `samples`, `readFile`, `env`, `log`, `textSize`). Commands may be built
from locals: the methods copy what they keep (text, GPU descriptions,
uniforms) into scratch. Bulk data (vertices, samples, pixels, uploads) is
not copied and must outlive the frame: scratch, session or store memory.
+`f.text(x, y, scale, bytes, color)` draws one line from its top left
+corner; scale 1 is a 13 px monospace face (8 px a character on a 16 px
+line), and any scale works, 1.5 or 7.25. `f.host.textSize(scale, bytes)`
+is the width and line height it covers, for laying out tables and code.
+Natively the text is shaped by Pango and drawn at the canvas's own pixels,
+with advances rounded to whole pixels at that size: sharp at any size, but
+a width is not a multiple of the scale (ten digits are 80 px at scale 1,
+230 at scale 3), so measure at the scale drawn. The font is Go Mono, built
+in; `SKETCHBOOK_FONT="JetBrains Mono"` in the environment puts an
+installed family before it. On the web it is the page's `monospace`, 8 px a
+character.
+
`f.openFile("open", .{ .pattern = "wav;flac" })` shows the system's file
dialog; the answer comes back as the console line `open <path>`, so it
reaches the sketch's `command` like anything typed there. `f.run(line)`
@@ -425,6 +437,27 @@ stb_vorbis): WAV, FLAC and Ogg Vorbis, chosen by content.
scripted `--fresh` run works on files of its own (`<state>.<pid>`),
renamed to the given `--state` at exit, so two builds running the same
script at once do not share them.
+- **Export.** `--export DIR` plays the sketch headless, from fresh state,
+ and saves every frame as `DIR/000000.png`, `000001.png`, ...;
+ `--export -` writes them to stdout instead, as raw RGBA:
+
+ ```sh
+ demo --export frames --size 1920x1080 --frames 600
+ demo --export - --size 3840x2160 --fps 60 --frames 600 |
+ ffmpeg -f rawvideo -pix_fmt rgba -s 3840x2160 -r 60 -i - -pix_fmt yuv420p out.mp4
+ ```
+
+ The frames run on a clock of their own: frame k is k/fps seconds in
+ (`--fps N`, 60 unless given) and its tick is exactly 1/N s (frame 0's
+ is 0, as any run's first), however long a frame takes to draw. A sketch
+ that takes its time from the ticks exports the same frames every time.
+ It ends after `--frames N`, or when the sketch calls `f.quit()`;
+ `in.exporting` tells a sketch that nobody is watching, so a player
+ hides its controls, plays through and quits. `--size WxH` is the room
+ for the canvas (`in.window_width`/`height`, and the first canvas): a
+ sketch that sets its canvas to the room exports at any size. An export
+ keeps state files of its own and removes them, so it can run beside a
+ player. `--export` plays no script.
- **GPU.** The host's 2D renderer runs on an SDL GPU device, which also
runs sketches' GPU passes. Without a GPU it falls back to any renderer.
`--profile-gpu` times every upload, dispatch and pass alone on an idle
@@ -478,7 +511,9 @@ pub fn build(b: *std.Build) void {
}
```
-`addSteps` installs the executable and adds `run`, `lib`, `probe`, `e2e` and
+`addSteps` installs the executable and adds `run`, `lib`, `probe`,
+`export` (`zig build export -- frames --size 1920x1080`: what follows `--`
+is `--export`'s directory, or `-`, then its options), `e2e` and
`test`, and with `.web = .{}` also `web` (the page into `zig-out/web`) and
`serve` (it, over https on port 8042, to the local network too; `zig build
web --watch` alongside rebuilds it for the next reload). Every piece is also available on its own
@@ -493,6 +528,7 @@ and returns plain `std.Build` objects:
| `app.addServe(install)` | `miniserve` serving an installed web directory over https, on every interface, with a self-signed certificate made once by `openssl`: https makes the page a secure context on any device, which WebGPU and the microphone need. Its defaults are environment variables, so miniserve options after `--` replace them |
| `app.addRun(lib, .{})` | the generic host running the installed library |
| `app.addScript(exe_or_lib, file, .{})` | a headless, fresh-state scripted run, of the executable or of the library through the host (so the script can `reload` it) |
+| `app.addExport(exe, .{ .fps, .frames, .size })` | a headless export of the executable's frames, as PNGs in `.frames`, a directory of the cache |
| `app.addProbe(state)` | the probe on a state file |
| `app.addTest(.{})` | tests with the app importable as `app` |
| `app.addReloadCheck(.{ .script, .edits })` | a check that the app hot-reloads with State kept (below) |
diff --git a/build.zig b/build.zig
index ef6bc0c..b980c91 100644
--- a/build.zig
+++ b/build.zig
@@ -176,6 +176,9 @@ pub fn build(b: *Build) void {
render_web.has_side_effects = true;
render_web.expectExitCode(0);
test_web.dependOn(&render_web.step);
+ // `Host.textSize` against the text drawn (test/text.zig).
+ const text = sb.app(.{ .name = "text", .root_source_file = b.path("test/text.zig") });
+ test_step.dependOn(&text.addScript(text.addExecutable(), b.path("test/text.script"), .{}).step);
// The examples, so they always compile.
for ([_][]const u8{ "pen", "flock" }) |example| {
test_step.dependOn(&sb.app(.{ .name = example, .root_source_file = b.path(b.fmt("examples/{s}.zig", .{example})) }).addLibrary().step);
@@ -183,6 +186,33 @@ pub fn build(b: *Build) void {
// The README's example, so the documentation always compiles.
test_step.dependOn(&sb.app(.{ .name = "readme", .root_source_file = b.path("test/readme.zig") }).addLibrary().step);
+ // Export: two builds of one sketch export the same frames, on the
+ // export's own clock (test/export.script); the raw stream is as long as
+ // its frames, up to where the sketch quits; and ffmpeg, if there is
+ // one, makes a video of it with as many.
+ const export_a = sb.app(.{ .name = "export-a", .root_source_file = b.path("test/export.zig") });
+ const export_b = sb.app(.{ .name = "export-b", .root_source_file = b.path("test/export.zig") });
+ const export_exe = export_a.addExecutable();
+ const export_options: App.ExportOptions = .{ .fps = 30, .frames = 5, .size = .{ 320, 180 } };
+ const exported = export_a.addScript(export_exe, b.path("test/export.script"), .{});
+ exported.addArg("--define");
+ exported.addPrefixedDirectoryArg("a=", export_a.addExport(export_exe, export_options).frames);
+ exported.addArg("--define");
+ exported.addPrefixedDirectoryArg("b=", export_b.addExport(export_b.addExecutable(), export_options).frames);
+ test_step.dependOn(&exported.step);
+ const raw = b.addSystemCommand(&.{ "sh", "-c",
+ \\set -e
+ \\test "$("$0" --state "$1" --export - --fps 30 --size 320x180 | wc -c)" = $((320 * 180 * 4 * 8))
+ \\command -v ffmpeg >/dev/null && command -v ffprobe >/dev/null || exit 0
+ \\"$0" --state "$1" --export - --fps 30 --size 320x180 | ffmpeg -loglevel error -y -f rawvideo -pix_fmt rgba -s 320x180 -r 30 -i - -pix_fmt yuv420p "$2"
+ \\test "$(ffprobe -v error -count_frames -select_streams v:0 -show_entries stream=nb_read_frames -of csv=p=0 "$2")" = 8
+ });
+ raw.addArtifactArg(export_exe);
+ _ = raw.addOutputFileArg("raw.state");
+ _ = raw.addOutputFileArg("raw.mp4");
+ raw.expectExitCode(0);
+ test_step.dependOn(&raw.step);
+
const reload = b.addRunArtifact(host_exe);
reload.addArgs(&.{ "--headless", "--fresh", "--script" });
reload.addFileArg(b.path("test/reload.script"));
@@ -946,6 +976,38 @@ pub const App = struct {
return run;
}
+ pub const ExportOptions = struct {
+ fps: u32 = 60,
+ /// Null: until the sketch quits (`f.quit()`).
+ frames: ?u64 = null,
+ /// The canvas of a sketch that takes the room it is given.
+ size: ?[2]u32 = null,
+ };
+
+ pub const Export = struct {
+ run: *Build.Step.Run,
+ /// `000000.png`, `000001.png`, ...
+ frames: Build.LazyPath,
+ };
+
+ /// Exports the frames of `exe` (`addExecutable`) as PNGs into a
+ /// directory of the cache: headless, from fresh state, frame k at
+ /// k/fps seconds whatever the wall clock does.
+ pub fn addExport(app: App, exe: *Build.Step.Compile, options: ExportOptions) Export {
+ const b = app.sb.b;
+ const run = b.addRunArtifact(exe);
+ run.addArg("--state");
+ _ = run.addOutputFileArg(b.fmt("{s}-export.state", .{app.name}));
+ run.addArg("--export");
+ const frames = run.addOutputDirectoryArg("frames");
+ run.addArgs(&.{ "--fps", b.fmt("{d}", .{options.fps}) });
+ if (options.frames) |n| run.addArgs(&.{ "--frames", b.fmt("{d}", .{n}) });
+ if (options.size) |size| run.addArgs(&.{ "--size", b.fmt("{d}x{d}", .{ size[0], size[1] }) });
+ run.setCwd(b.path("."));
+ run.expectExitCode(0);
+ return .{ .run = run, .frames = frames };
+ }
+
/// Prints the app's live state; `zig build probe -- --watch` follows it.
pub fn addProbe(app: App, state: ?[]const u8) *Build.Step.Run {
const b = app.sb.b;
@@ -1201,8 +1263,8 @@ pub const App = struct {
/// The conventional wiring. Installs the executable, and adds:
/// `run` (host + hot reload), `lib` (rebuild the library; use `--watch`),
- /// `web` and `serve` (with `web` options), `probe`, `e2e` (scripts) and
- /// `test`.
+ /// `web` and `serve` (with `web` options), `probe`, `export` (frames
+ /// for ffmpeg), `e2e` (scripts) and `test`.
pub fn addSteps(app: App, options: StepsOptions) Steps {
const b = app.sb.b;
const library = app.addLibrary();
@@ -1222,6 +1284,14 @@ pub const App = struct {
break :blk web;
} else null;
+ // `--export` takes the first argument after `--`.
+ const exporting = b.addRunArtifact(exe);
+ exporting.addArgs(&.{ "--state", b.fmt("{s}.state", .{app.name}), "--export" });
+ exporting.addPassthruArgs();
+ exporting.setCwd(b.path("."));
+ exporting.stdio = .inherit;
+ b.step("export", "Export frames: -- DIR for PNGs, or - for raw RGBA on stdout; then --fps N, --frames N, --size WxH").dependOn(&exporting.step);
+
const e2e = b.step("e2e", "Play the end-to-end scripts headless");
const script_exe = if (app.sb.script_optimize == app.sb.optimize) exe else app.addScriptExecutable();
for (options.scripts) |script| e2e.dependOn(&app.addScript(script_exe, script, .{}).step);
diff --git a/src/abi.zig b/src/abi.zig
index 03e2978..b30b7ae 100644
--- a/src/abi.zig
+++ b/src/abi.zig
@@ -180,6 +180,9 @@ pub const Input = struct {
started: bool = false,
/// The console is open and owns the keyboard.
console: bool = false,
+ /// The host is exporting frames (`--export`): nobody watches or clicks,
+ /// so a player runs through once, without its controls, and quits.
+ exporting: bool = false,
/// The canvas.
width: f32 = 0,
height: f32 = 0,
@@ -578,6 +581,9 @@ pub const Host = struct {
freeBuffer: *const fn (*anyopaque, Buffer) void,
/// Zero while unknown.
imageSize: *const fn (*anyopaque, Image) [2]u32,
+ /// What `Command.text` gives the bytes at a scale: the width they
+ /// advance and the height of their line, in canvas units.
+ textSize: *const fn (*anyopaque, f32, []const u8) [2]f32,
/// `.none` if the file does not load.
loadSound: *const fn (*anyopaque, []const u8) Audio,
/// WAV, FLAC or Ogg Vorbis bytes in memory. Not cached. `.none` if
@@ -625,6 +631,14 @@ pub const Host = struct {
pub fn imageSize(h: Host, image: Image) [2]u32 {
return h.vtable.imageSize(h.ctx, image);
}
+ /// The size `f.text(x, y, scale, bytes, ...)` covers from `x, y`: width
+ /// and line height in canvas units, for laying text out (in `draw`:
+ /// `update` gets no host). Native text is shaped and hinted at the size
+ /// it is drawn, so a width is not a multiple of the scale: measure at
+ /// the scale drawn.
+ pub fn textSize(h: Host, scale: f32, bytes: []const u8) [2]f32 {
+ return h.vtable.textSize(h.ctx, scale, bytes);
+ }
pub fn loadSound(h: Host, path: []const u8) Audio {
return h.vtable.loadSound(h.ctx, path);
}
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
\\
;
diff --git a/src/sketch/web.zig b/src/sketch/web.zig
index 27313a6..4445e8d 100644
--- a/src/sketch/web.zig
+++ b/src/sketch/web.zig
@@ -395,6 +395,7 @@ fn Driver(comptime App: type) type {
.newBuffer = newBuffer,
.freeBuffer = freeBuffer,
.imageSize = imageSize,
+ .textSize = textSize,
.loadSound = loadSound,
.decodeSound = unsupportedSound,
.samples = samples,
@@ -429,6 +430,11 @@ fn Driver(comptime App: type) type {
fn imageSize(_: *anyopaque, img: abi.Image) [2]u32 {
return .{ js.imageWidth(@backingInt(img)), js.imageHeight(@backingInt(img)) };
}
+ /// As host.js draws text: 8 px a character and a 16 px line at scale 1.
+ fn textSize(_: *anyopaque, scale: f32, bytes: []const u8) [2]f32 {
+ const count = std.unicode.utf8CountCodepoints(bytes) catch bytes.len;
+ return .{ @as(f32, @floatFromInt(count)) * 8 * scale, 16 * scale };
+ }
/// Only sounds the page has decoded (opened or dropped files): the
/// browser decodes asynchronously, so there is no reading on demand.
fn loadSound(_: *anyopaque, name: []const u8) abi.Audio {
diff --git a/test/export.script b/test/export.script
new file mode 100644
index 0000000..bd238e7
--- /dev/null
+++ b/test/export.script
@@ -0,0 +1,11 @@
+# Two exports of the same sketch ({a}, {b}: directories of PNGs, 30 fps,
+# 320x180, five frames) are the same pictures, and frame k is k/30 s in.
+expect-same-screenshot {a}/000000.png {b}/000000.png
+expect-same-screenshot {a}/000004.png {b}/000004.png
+expect-different-screenshot {a}/000000.png {a}/000004.png
+# Frame 0 is before any time passed; frame 4 has the bar 40 px wide.
+expect-pixel {a}/000000.png 0 0 32 32 32 255
+expect-pixel {a}/000004.png 39 0 255 128 64 255
+expect-pixel {a}/000004.png 41 0 32 32 32 255
+# The canvas is the size asked for.
+expect-pixel {a}/000004.png 319 179 32 32 32 255
diff --git a/test/export.zig b/test/export.zig
new file mode 100644
index 0000000..d8b35ad
--- /dev/null
+++ b/test/export.zig
@@ -0,0 +1,23 @@
+//! Export's test: time comes from the ticks alone and moves a bar, the
+//! canvas is the room the host gives (`--size`), and it quits by itself.
+const sk = @import("sketch");
+
+pub const State = struct { t: f32 = 0, frames: u32 = 0 };
+
+pub fn update(s: *State, in: *const sk.Input) void {
+ for (in.events) |e| if (e.kind == .tick) {
+ s.t += e.x;
+ s.frames += 1;
+ };
+}
+
+pub fn draw(s: *const State, f: *sk.Frame) void {
+ const w = f.in.window_width;
+ const h = f.in.window_height;
+ f.canvas(@intFromFloat(w), @intFromFloat(h));
+ f.clear(0x202020);
+ // 300 px a second: 10 px a frame at 30 fps, whatever the wall clock did.
+ f.fill(sk.Rect{ .w = s.t * 300, .h = h / 2 }, 0xff8040);
+ f.print(8, h - 24, 1, 0xffffff, "frame {d} of {d:.0}x{d:.0}", .{ s.frames, w, h });
+ if (s.frames == 8) f.quit();
+}
diff --git a/test/text.script b/test/text.script
new file mode 100644
index 0000000..5bea6f5
--- /dev/null
+++ b/test/text.script
@@ -0,0 +1,7 @@
+# `textSize` is what `text` draws: at scale 1 ten digits of the built-in
+# font advance about 80 px on a 16 px line, and the box under them is that.
+screenshot .zig-cache/text/native.png
+expect-pixel .zig-cache/text/native.png 84 11 32 64 96 255
+expect-pixel .zig-cache/text/native.png 84 24 32 64 96 255
+expect-pixel .zig-cache/text/native.png 97 11 16 16 16 255
+expect-pixel .zig-cache/text/native.png 84 27 16 16 16 255
diff --git a/test/text.zig b/test/text.zig
new file mode 100644
index 0000000..b570435
--- /dev/null
+++ b/test/text.zig
@@ -0,0 +1,26 @@
+//! Text for layout: each line sits on a box of the size `textSize` gives
+//! it, at whole and fractional scales, the same picture at any canvas size.
+const sk = @import("sketch");
+
+pub const width = 640;
+pub const height = 360;
+
+const lines = [_]struct { scale: f32, text: []const u8 }{
+ .{ .scale = 1, .text = "0123456789" },
+ .{ .scale = 1.5, .text = "mov rax, [rbp-0x18] ; 1.5" },
+ .{ .scale = 2.25, .text = "0x7ffed849acf0 i -> W" },
+ .{ .scale = 4, .text = "fn main() !void {}" },
+};
+
+pub fn draw(f: *sk.Frame) void {
+ f.canvas(@intFromFloat(f.in.window_width), @intFromFloat(f.in.window_height));
+ f.clear(0x101010);
+ const k = f.in.window_height / height;
+ var y: f32 = 10 * k;
+ for (lines) |line| {
+ const size = f.host.textSize(line.scale * k, line.text);
+ f.fill(sk.Rect{ .x = 10 * k, .y = y, .w = size[0], .h = size[1] }, 0x204060);
+ f.text(10 * k, y, line.scale * k, line.text, 0xffffff);
+ y += size[1] + 6 * k;
+ }
+}
diff --git a/vendor/text.c b/vendor/text.c
index 9a81558..172b61e 100644
--- a/vendor/text.c
+++ b/vendor/text.c
@@ -85,7 +85,12 @@ static TextCache *cache_for(SDL_Renderer *renderer) {
pango_fc_font_map_set_config(PANGO_FC_FONT_MAP(c->map), c->config);
c->context = pango_font_map_create_context(c->map);
c->layout = pango_layout_new(c->context);
- c->font = pango_font_description_from_string("Go Mono, Noto Sans Mono, DejaVu Sans Mono, Noto Sans Arabic, Noto Sans Hebrew, IBM Plex Sans JP, Noto Color Emoji, Noto Sans Symbols 2, DejaVu Sans, monospace");
+ /* SKETCHBOOK_FONT names an installed family to use before the built-in one. */
+ const char *first = getenv("SKETCHBOOK_FONT");
+ char families[512];
+ snprintf(families, sizeof(families), "%s%sGo Mono, Noto Sans Mono, DejaVu Sans Mono, Noto Sans Arabic, Noto Sans Hebrew, IBM Plex Sans JP, Noto Color Emoji, Noto Sans Symbols 2, DejaVu Sans, monospace",
+ first ? first : "", first ? ", " : "");
+ c->font = pango_font_description_from_string(families);
cairo_font_options_t *options = cairo_font_options_create();
cairo_font_options_set_antialias(options, CAIRO_ANTIALIAS_GRAY);
cairo_font_options_set_hint_style(options, CAIRO_HINT_STYLE_SLIGHT);
@@ -131,14 +136,24 @@ static uint64_t hash_text(const char *bytes, size_t len) {
for (size_t i = 0; i < len; ++i) hash = (hash ^ (unsigned char)bytes[i]) * UINT64_C(1099511628211);
return hash;
}
-static bool rasterize(TextCache *c, SDL_Renderer *renderer, Text *out,
- const char *bytes, size_t len, int size, Uint32 color) {
+/* The font size, in 64ths of a physical pixel, that `scale` asks for. */
+static int font_size(float scale, float dpi) {
+ return (int)lroundf(fminf(512, 13.0f * scale * dpi) * 64);
+}
+/* Lays `bytes` out at `size`: its extents in physical pixels (`ink` may be NULL). */
+static bool lay_out(TextCache *c, const char *bytes, size_t len, int size,
+ PangoRectangle *ink, PangoRectangle *logical) {
if (len > INT_MAX || !g_utf8_validate(bytes, (gssize)len, NULL)) return false;
pango_font_description_set_absolute_size(c->font, (double)size * PANGO_SCALE / 64.0);
pango_layout_set_font_description(c->layout, c->font);
pango_layout_set_text(c->layout, bytes, (int)len);
+ pango_layout_get_pixel_extents(c->layout, ink, logical);
+ return true;
+}
+static bool rasterize(TextCache *c, SDL_Renderer *renderer, Text *out,
+ const char *bytes, size_t len, int size, Uint32 color) {
PangoRectangle ink, logical;
- pango_layout_get_pixel_extents(c->layout, &ink, &logical);
+ if (!lay_out(c, bytes, len, size, &ink, &logical)) return false;
const int left = MIN(0, ink.x) - 1;
const int top = MIN(0, ink.y) - 1;
const int width = MAX(logical.x + logical.width, ink.x + ink.width) - left + 1;
@@ -173,6 +188,19 @@ static bool rasterize(TextCache *c, SDL_Renderer *renderer, Text *out,
return true;
}
+bool sk_text_measure(SDL_Renderer *renderer, float scale, const char *utf8, size_t len,
+ float *width, float *height) {
+ if (!isfinite(scale) || scale <= 0) return false;
+ TextCache *c = cache_for(renderer);
+ if (!c) return false;
+ const float dpi = density(renderer);
+ PangoRectangle logical;
+ if (!lay_out(c, utf8, len, font_size(scale, dpi), NULL, &logical)) return false;
+ *width = logical.width / dpi;
+ *height = logical.height / dpi;
+ return true;
+}
+
bool sk_text_draw(SDL_Renderer *renderer, float x, float y, float scale,
const char *utf8, size_t len, Uint8 r, Uint8 g, Uint8 b, Uint8 a) {
if (!len || !a) return true;
@@ -180,7 +208,7 @@ bool sk_text_draw(SDL_Renderer *renderer, float x, float y, float scale,
TextCache *c = cache_for(renderer);
if (!c) return false;
const float dpi = density(renderer);
- const int size = (int)lroundf(fminf(512, 13.0f * scale * dpi) * 64);
+ const int size = font_size(scale, dpi);
const Uint32 color = ((Uint32)r << 16) | ((Uint32)g << 8) | b;
const uint64_t hash = hash_text(utf8, len);
Text *entry = NULL;
diff --git a/vendor/text.h b/vendor/text.h
index bf4f363..9cd445a 100644
--- a/vendor/text.h
+++ b/vendor/text.h
@@ -6,5 +6,9 @@
eight-pixel ASCII advance and a 16-pixel line box); fallback uses Fontconfig. */
bool sk_text_draw(SDL_Renderer *, float x, float y, float scale,
const char *utf8, size_t len, Uint8 r, Uint8 g, Uint8 b, Uint8 a);
+/* What sk_text_draw gives the text at `scale`: its advance width and the
+ height of its line box, in logical units. False if it cannot be laid out. */
+bool sk_text_measure(SDL_Renderer *, float scale, const char *utf8, size_t len,
+ float *width, float *height);
void sk_text_begin_frame(SDL_Renderer *);
#endif