summaryrefslogtreecommitdiff
path: root/src/host/Host.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/host/Host.zig')
-rw-r--r--src/host/Host.zig751
1 files changed, 645 insertions, 106 deletions
diff --git a/src/host/Host.zig b/src/host/Host.zig
index 43f030a..9a2c0fa 100644
--- a/src/host/Host.zig
+++ b/src/host/Host.zig
@@ -3,31 +3,46 @@
//! 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");
const playback = @import("timeline.zig");
const Timeline = playback.Timeline;
-const mapRecordings = playback.mapRecordings;
const gfx = @import("gfx.zig");
const sound = @import("audio.zig");
-const Gpu = @import("gpu.zig");
+const Gpu = @import("gpu");
const overlay = @import("overlay.zig");
const Console = @import("Console.zig");
+const Timing = @import("Timing.zig");
+const Presentation = @import("Presentation.zig");
+const timing_marker = @import("timing_marker.zig");
+const Control = @import("control.zig").Control;
const Library = @import("library.zig").Library;
+const Sessions = @import("Sessions.zig");
const Watch = @import("library.zig").Watch;
pub const Options = struct {
/// A hot-reloaded sketch library. Unused when a sketch is linked in.
library: ?[]const u8 = null,
- /// State file; recordings go next to it with an `.inputs` suffix.
- state: []const u8 = "sketch.state",
+ /// Local 9P control socket, opt-in.
+ ninep: ?[]const u8 = null,
+ /// The save, a sessions database: `<stem>.xitdb`, for a path
+ /// `<stem>.xitdb`, `<stem>.state` (where a state file from before is
+ /// imported from) or `<stem>`. Empty: `$XDG_DATA_HOME/<name>/<name>.xitdb`
+ /// (`~/.local/share` without it), for a shipped game.
+ state: []const u8 = "",
+ /// Playing a script: from fresh state, sessions go to memory only.
+ script: bool = false,
/// Offscreen video, silent audio, no vsync: for scripts and CI.
headless: bool = false,
- /// Forget the state file's contents: scripts start from a known place.
+ /// Start from State's defaults, not the save's present: scripts start
+ /// from a known place.
fresh: bool = false,
/// Time every GPU command alone and print the times at exit.
profile_gpu: bool = false,
+ /// Binary frame/time marker for external video measurements.
+ timing_marker: 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,
@@ -48,6 +63,7 @@ renderer: *c.SDL_Renderer,
/// Runs sketches' GPU passes, and the 2D renderer draws through it too.
/// Null when the machine has no usable GPU driver.
gpu: ?*c.SDL_GPUDevice,
+presentation: ?*Presentation = null,
passes: ?Gpu = null,
/// GPU canvas, shared by native/headless drawing, backdrop filters and screenshots.
offscreen: ?*c.SDL_Texture = null,
@@ -56,25 +72,37 @@ images: gfx.Images,
/// Plays the 2D commands: targets, blend, antialiased shapes.
painter: gfx.Painter,
audio: sound.Audio,
-state: memory.StateFile,
+state: memory.State,
session: memory.Session,
-store: memory.StoreFile,
+/// A failed resource setup disables app callbacks while keeping host controls alive.
+session_ready: bool = false,
/// Images and buffers the sketch made (`newImage`, `decodeImage`,
/// `newBuffer`): Session holds their handles, so they go when it resets.
made: struct { images: std.ArrayList(abi.Image) = .empty, buffers: std.ArrayList(abi.Buffer) = .empty } = .{},
-recordings: []align(memory.page) u8,
timeline: Timeline,
+/// This run's session and the ones before it (Sessions.zig).
+sessions: Sessions,
console: Console = .{},
+timing: Timing = .{},
+timing_atlas: overlay.TimingAtlas = .{},
sketch: abi.Sketch,
library: ?Library = null,
watch: ?Watch = null,
reloads: usize = 0,
-/// Identifies the running build of the sketch (a hash of its library or
-/// executable file): recordings carry it, and `play` warns on a mismatch.
+/// Identifies the running build of the sketch (its library or executable
+/// file's inode, size and modification time): sessions' stretches carry it,
+/// and `play` warns on a mismatch.
build: u64 = 0,
+/// The save's path when the host chose it (`Options.state`), `gpa`'s.
+state_path: []const u8 = "",
+/// `Options.state` without `.xitdb` or `.state`: the save is
+/// `<stem>.xitdb`, the sketch's own files `<stem>.<name>`.
+stem: []const u8 = "",
/// Copies of the sketch's info strings, replaced on every load.
info_arena: std.heap.ArenaAllocator,
name: []const u8 = "",
+/// The sketch's `Info.source`, for the session's stretches.
+source: []const u8 = "",
completions: []const []const u8 = &.{},
/// Frame lifetime: sketch scratch and this frame's commands.
frame_arena: std.heap.ArenaAllocator,
@@ -83,6 +111,11 @@ commands: std.ArrayList(abi.Command) = .empty,
pending: std.ArrayList(abi.Event) = .empty,
input: abi.Input = .{},
files: std.StringHashMapUnmanaged([]align(memory.page) const u8) = .empty,
+/// Mappings of files `writeFile` replaced: the sketch may still hold them.
+retired: std.ArrayList([]align(memory.page) const u8) = .empty,
+/// The paths `appendFile` wrote, each once, 0-terminated: the sketch keeps
+/// them.
+written: std.StringHashMapUnmanaged(void) = .empty,
canvas: [2]u32 = .{ 0, 0 },
cursor: abi.Cursor = .arrow,
quit: bool = false,
@@ -92,13 +125,16 @@ reloaded: bool = true,
jumped: bool = true,
started: bool = true,
last_now: u64 = 0,
+last_frame_end: 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 = .{},
+control: ?*Control = null,
-pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, options: Options, linked: ?abi.Sketch) !void {
+pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, given: Options, linked: ?abi.Sketch) !void {
+ var options = given;
if (options.headless) {
// Overriding: a plain hint loses to the environment, and a user's
// SDL_VIDEO_DRIVER=wayland would open real windows during tests.
@@ -112,7 +148,7 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std
var library: ?Library = null;
const sketch = linked orelse blk: {
const path = options.library orelse return error.NoSketch;
- library = try Library.openCopy(io, path, scratchDir(environ), 0);
+ library = try Library.openFresh(io, path, scratchDir(environ), 0);
break :blk library.?.sketch;
};
errdefer if (library) |*l| l.close();
@@ -142,17 +178,16 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std
// Colors carry alpha: fills blend, as they do on the web.
_ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_BLEND);
- var state = try memory.StateFile.open(gpa, options.state);
- errdefer state.close();
- var inputs_buf: [std.fs.max_path_bytes]u8 = undefined;
- const recordings = try mapRecordings(try std.mem.print(&inputs_buf, "{s}.inputs", .{options.state}));
- errdefer std.posix.munmap(recordings);
- var store_buf: [std.fs.max_path_bytes]u8 = undefined;
- var store = memory.StoreFile.open(gpa, try std.mem.print(&store_buf, "{s}.store", .{options.state}), options.fresh) catch |err| {
- if (err == error.StoreInUse) std.log.err("{s}.store is open in another process", .{options.state});
- return err;
+ var data_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const state_path = if (given.state.len > 0) "" else blk: {
+ const data = environ.get("XDG_DATA_HOME") orelse try std.fmt.bufPrint(&data_buf, "{s}/.local/share", .{environ.get("HOME") orelse "."});
+ const path = try std.fmt.allocPrint(gpa, "{s}/{s}/{s}.xitdb", .{ data, info.name, info.name });
+ errdefer gpa.free(path);
+ try std.Io.Dir.cwd().createDirPath(io, std.fs.path.dirname(path).?);
+ break :blk path;
};
- errdefer store.close();
+ errdefer gpa.free(state_path);
+ if (state_path.len > 0) options.state = state_path;
self.* = .{
.gpa = gpa,
@@ -163,50 +198,57 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std
.renderer = renderer.?,
.gpu = gpu,
.images = .{ .gpa = gpa, .renderer = renderer.? },
- .painter = .{ .renderer = renderer.?, .images = undefined, .smooth = gpu != null },
+ .painter = .{ .renderer = renderer.?, .images = undefined, .smooth = gpu != null, .glyphs = .{ .gpa = gpa } },
.audio = .{ .gpa = gpa },
- .state = state,
+ .state = .init(gpa),
.session = .init(gpa),
- .store = store,
- .recordings = recordings,
.timeline = undefined,
+ .sessions = .{ .gpa = gpa, .io = io },
.sketch = sketch,
.library = library,
+ .state_path = state_path,
+ .stem = stemOf(options.state),
.info_arena = .init(gpa),
.frame_arena = .init(gpa),
.input = .{ .exporting = options.export_to != null },
};
- self.timeline = .{ .bank = .{ .state = &self.state, .inputs = recordings } };
+ self.timeline = .{ .gpa = gpa, .state = &self.state, .defaults = sketch.defaults };
self.painter.images = &self.images;
if (gpu) |device| self.passes = .init(gpa, device);
if (options.profile_gpu) if (self.passes) |*g| {
g.profile = .init(gpa);
};
- self.audio.open() catch |err| std.log.warn("audio unavailable: {t}", .{err});
+ self.audio.open(info.audio_pull) catch |err| std.log.warn("audio unavailable: {t}", .{err});
if (options.library) |path| if (linked == null) {
self.watch = Watch.init(path) catch null;
};
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");
+ self.build = fileId(io, options.library orelse "/proc/self/exe");
try self.adopt(sketch);
- if (options.fresh) {
- self.state.header().used = 0;
- @memset(self.recordings, 0);
- self.resetState();
+ self.openSessions(info.record);
+ // Before --fresh, which never touches the save.
+ self.openPresent();
+ if (options.fresh) self.resetState();
+ if (!options.headless and options.export_to == null) {
+ self.presentation = Presentation.init(gpa, self.window) catch null;
+ if (options.timing_marker) self.print("presentation tracing: {s}", .{if (self.presentation) |p| p.status else "disabled_or_allocation_failed"});
}
}
pub fn deinit(self: *Host) void {
+ self.sessions.close(self.live(), wallClock(self.io));
+ if (self.control) |control| control.deinit();
self.dialog.deinit();
if (self.watch) |w| w.deinit();
self.audio.deinit();
- if (self.passes) |*g| g.deinit(&self.images);
self.painter.deinit();
self.images.deinit();
+ if (self.passes) |*g| g.deinit();
if (self.pointer_cursor) |cursor| c.SDL_DestroyCursor(cursor);
if (self.offscreen) |texture| c.SDL_DestroyTexture(texture);
+ if (self.presentation) |p| p.deinit(self.gpa);
c.SDL_DestroyRenderer(self.renderer);
if (self.gpu) |device| c.SDL_DestroyGPUDevice(device);
c.SDL_DestroyWindow(self.window);
@@ -216,15 +258,25 @@ pub fn deinit(self: *Host) void {
std.posix.munmap(entry.value_ptr.*);
}
self.files.deinit(self.gpa);
- std.posix.munmap(self.recordings);
+ for (self.retired.items) |bytes| std.posix.munmap(bytes);
+ self.retired.deinit(self.gpa);
+ // A scripted run from fresh state, or an export, leaves no files.
+ const private = (self.options.script or self.options.export_to != null) and self.options.fresh;
+ var written = self.written.keyIterator();
+ while (written.next()) |path| {
+ if (private) std.Io.Dir.cwd().deleteFile(self.io, path.*) catch {};
+ self.gpa.free(path.ptr[0 .. path.len + 1]);
+ }
+ self.written.deinit(self.gpa);
+ self.timeline.deinit();
self.session.deinit(self.gpa);
- self.store.close();
self.made.images.deinit(self.gpa);
self.made.buffers.deinit(self.gpa);
- self.state.close();
+ self.state.deinit(self.gpa);
self.pending.deinit(self.gpa);
self.frame_arena.deinit();
self.info_arena.deinit();
+ self.gpa.free(self.state_path);
if (self.library) |*l| l.close();
c.SDL_Quit();
}
@@ -232,20 +284,77 @@ pub fn deinit(self: *Host) void {
/// 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 {
+ // A run a person watches posts its tree as sketchbook/<name>; --9p
+ // names another, or a socket path.
+ const o = self.options;
+ const ninep = o.ninep orelse if (o.headless or o.script or o.export_to != null) null else self.name;
+ if (ninep) |where| self.control = Control.open(self.gpa, self.environ, where) catch |err| blk: {
+ if (o.ninep != null) return err;
+ self.print("not posted as sketchbook/{s}: {t}", .{ where, err });
+ break :blk null;
+ };
while (!self.quit) {
+ if (self.control) |control| control.poll(self);
try self.poll();
- 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);
+ if (self.presentation) |p| p.poll();
+ if (!self.options.headless and self.options.export_to == null and
+ c.SDL_GetWindowFlags(self.window) & (c.SDL_WINDOW_OCCLUDED | c.SDL_WINDOW_MINIMIZED | c.SDL_WINDOW_HIDDEN) != 0 and
+ self.screenshot == null and !(self.control != null and self.control.?.capture_pending))
+ {
+ // Occluded Wayland presentation can block for a second; keep controls alive and resume without a camera jump.
+ self.last_now = 0;
+ self.last_frame_end = 0;
+ _ = c.SDL_Delay(10);
+ continue;
+ }
+ // GPU fences do not limit presentation rate; follow the measured display clock.
+ const wait_ns = if (self.presentation) |p| p.waitNs() else 0;
+ if (wait_ns != 0) {
+ c.SDL_DelayPrecise(@min(wait_ns, std.time.ns_per_ms));
+ continue;
+ }
+ const wall = c.SDL_GetTicksNS();
+ const now = if (self.options.export_to != null)
+ std.time.ns_per_s + self.exported * std.time.ns_per_s / self.options.fps
+ else
+ frameTime(wall, if (self.presentation) |p| p.sampleNs(wall) else wall, self.last_now, self.timeline.mode, self.pending.items);
+ try self.frame(now);
}
- self.timeline.stop(c.SDL_GetTicksNS());
+ self.timeline.stop();
+}
+
+// Live animation uses the display clock, but a tick must not predate its input.
+fn frameTime(wall: u64, scheduled: u64, previous: u64, mode: abi.Mode, events: []const abi.Event) u64 {
+ if (mode != .live and mode != .recording) return wall;
+ var now = @max(scheduled, previous);
+ for (events) |event| now = @max(now, event.time);
+ return now;
+}
+
+test "timing clock drives ordinary ticks without moving input or replay time" {
+ const expectEqual = std.testing.expectEqual;
+ try expectEqual(@as(u64, 100), frameTime(103, 100, 80, .live, &.{}));
+ try expectEqual(@as(u64, 120), frameTime(127, 120, 100, .recording, &.{}));
+ const events = [_]abi.Event{ .{ .kind = .key_down, .time = 102 }, .{ .kind = .key_up, .time = 101 } };
+ try expectEqual(@as(u64, 102), frameTime(103, 100, 80, .live, &events));
+ try expectEqual(@as(u64, 102), events[0].time);
+ try expectEqual(@as(u64, 101), events[1].time);
+ try expectEqual(@as(u64, 103), frameTime(103, 103, 80, .live, &.{})); // No feedback.
+ try expectEqual(@as(u64, 110), frameTime(103, 100, 110, .live, &.{})); // Clock reversal.
+ for ([_]abi.Mode{ .playing, .paused }) |mode| try expectEqual(@as(u64, 103), frameTime(103, 100, 110, mode, &events));
}
pub fn live(self: *Host) []u8 {
- return self.state.slot(0);
+ return self.state.live();
}
/// 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 started = c.SDL_GetTicksNS();
+ 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});
@@ -254,8 +363,11 @@ pub fn frame(self: *Host, now: u64) !void {
self.last_now = now;
const h = &self.timeline;
switch (h.mode) {
- .playing => self.update(h.tick(now)),
- .paused => {},
+ .playing => {
+ self.sessions.away = true;
+ self.update(h.tick(now));
+ },
+ .paused => self.sessions.away = true,
.live, .recording => {
// One frame: what was routed since the last one, then its tick.
// Recorded first, so `update` sees the times a replay will.
@@ -263,17 +375,23 @@ pub fn frame(self: *Host, now: u64) !void {
// 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});
+ const why: ?Sessions.Why = if (self.sessions.frames == 0) .start else if (self.reloaded) .after_reload else if (self.jumped or self.sessions.away) .jump else null;
+ self.sessions.away = false;
+ self.sessions.frame(self.pending.items, self.live(), why) catch |err| self.print("session: {t}", .{err});
self.update(self.pending.items);
},
}
self.pending.clearRetainingCapacity();
- try self.draw(if (h.mode == .live or h.mode == .recording) now else h.position);
+ const work = try self.draw(if (h.mode == .live or h.mode == .recording) now else h.base + h.position, started);
+ const ended = c.SDL_GetTicksNS();
+ self.timing.add(.{ .frame = ended - (if (self.last_frame_end == 0) started else self.last_frame_end), .work = work });
+ self.last_frame_end = ended;
}
/// Feeds whole frames to the sketch's deterministic `update`, one call per
/// frame (events up to and including a tick), live or replayed alike.
pub fn update(self: *Host, events: []const abi.Event) void {
+ if (!self.session_ready) return;
var frames = playback.frames(events);
while (frames.next()) |one| {
// Input follows the events actually fed, frame by frame.
@@ -287,10 +405,42 @@ pub fn update(self: *Host, events: []const abi.Event) void {
self.started = false;
const ctx = self.context();
self.sketch.update(&ctx, self.live().ptr);
+ if (self.timeline.mode == .playing or self.timeline.mode == .paused) self.resync();
}
self.input.events = &.{};
}
+/// After a replayed frame of a past session: at each keyframe it reaches,
+/// live state is compared with the keyframe (over the leaves migration
+/// kept), any difference said, and the keyframe restored.
+fn resync(self: *Host) void {
+ const h = &self.timeline;
+ h.fed += 1;
+ const session = h.session orelse return;
+ const reached = h.key.?.frame + h.fed;
+ while (h.next_check < h.checks.items.len and h.checks.items[h.next_check].frame <= reached) {
+ const check = h.checks.items[h.next_check];
+ h.next_check += 1;
+ if (check.frame < reached) continue;
+ const key = self.sessions.load(session, check.key) catch |err| return self.print("session {d} keyframe {d}: {t}", .{ session, check.key, err });
+ defer key.free(self.gpa);
+ var arena: std.heap.ArenaAllocator = .init(self.gpa);
+ defer arena.deinit();
+ const saved = arena.allocator().alignedAlloc(u8, .fromByteUnits(memory.page), self.state.layout.size) catch return;
+ const from = memory.restore(arena.allocator(), key.layout, key.state, self.state.layout, saved, self.sketch.defaults) catch |err| return self.print("session {d} keyframe {d}: {t}", .{ session, check.key, err });
+ if (check.observed) {
+ const diff = memory.compareKept(from, self.state.layout, self.live(), saved);
+ if (diff.first) |first| {
+ var buf: [96]u8 = undefined;
+ var w: std.Io.Writer = .fixed(&buf);
+ first.leaf.name(first.offset, &w) catch {};
+ self.print("diverged before frame {d}: {d} values, first {s}", .{ reached, diff.count, w.buffered() });
+ }
+ }
+ @memcpy(self.live(), saved);
+ }
+}
+
/// After live state was restored from a snapshot: the pointer, buttons and
/// keys tracked so far belong to other bytes, so they start over. A new
/// recording then begins with events that bring back what is held now, so
@@ -305,7 +455,7 @@ fn restoredInput(self: *Host, now: u64) !void {
self.input.mouse_y = 0;
self.input.buttons = 0;
self.input.keys = .empty;
- if (h.mode != .recording or h.bank.recording(h.selected).count != 0) return;
+ if (h.mode != .recording) return;
var seed: std.ArrayList(abi.Event) = .empty;
defer seed.deinit(self.gpa);
if (was.mouse_x != 0 or was.mouse_y != 0) try seed.append(self.gpa, .{ .kind = .mouse_move, .time = now, .x = was.mouse_x, .y = was.mouse_y });
@@ -317,7 +467,9 @@ fn restoredInput(self: *Host, now: u64) !void {
try self.pending.insertSlice(self.gpa, 0, seed.items);
}
-fn draw(self: *Host, now: u64) !void {
+fn draw(self: *Host, now: u64, started: u64) !u64 {
+ 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;
@@ -342,12 +494,13 @@ fn draw(self: *Host, now: u64) !void {
}
}
self.input.streams = self.audio.streamStatus();
+ self.input.lead = self.audio.lead;
self.input.sample_rate = sound.sample_rate;
self.input.microphone = self.audio.record(arena);
self.input.downloads = if (self.passes) |*g| try g.collect(arena) else &.{};
self.input.frame += 1;
const ctx = self.context();
- self.sketch.draw(&ctx, self.live().ptr);
+ if (self.session_ready) self.sketch.draw(&ctx, self.live().ptr);
_ = c.SDL_SetRenderTarget(self.renderer, self.offscreen);
_ = c.SDL_SetRenderClipRect(self.renderer, null);
@@ -356,47 +509,65 @@ 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),
+ .gain => |g| self.audio.gains[g.group] = g.gain,
+ .audio => |a| self.audio.push(a.key, a.samples, a.clear),
+ .audio_buffer => |a| if (self.passes) |*g| if (a.count > 0) {
+ const samples = try arena.alloc(f32, a.count);
+ if (g.read(a.buffer, a.offset, std.mem.sliceAsBytes(samples))) self.audio.push(a.key, samples, false) else |err| self.print("gpu audio: {t} ({s})", .{ err, c.SDL_GetError() });
+ },
+ .quit => self.quit = true,
+ .gpu => |pass| if (self.passes) |*g| self.runGpu(g, pass) catch |err| self.print("gpu pass: {t} ({s})", .{ err, c.SDL_GetError() }),
+ .post_process => |p| if (self.passes) |*g| self.runPostProcess(g, p.source, p.target, p.effect) catch |err| self.print("gpu postprocess: {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;
if (self.console.overlay_memory) try overlay.drawMemory(&extra, arena, self.state.layout, self.live(), self.input.width);
if (self.console.overlay_sound) {
const samples = self.audio.scope.snapshot();
- try overlay.drawScope(&extra, arena, &samples, self.audio.scope.rate, self.canvas);
+ try overlay.drawScope(&extra, arena, &samples, self.audio.scope.rate, self.audio.pull, self.canvas);
+ }
+ if (self.timing.visible) {
+ if (self.timing_atlas.image == .none) self.timing_atlas = try overlay.TimingAtlas.init(&self.images, &self.painter);
+ for (extra.items) |command| self.painter.draw(command);
+ extra.clearRetainingCapacity();
+ try overlay.drawTiming(&self.painter, &self.timing, self.canvas, self.timing_atlas);
}
if (self.console.visible) try self.console.draw(self, &extra, arena);
+ if (self.options.timing_marker) try timing_marker.draw(&extra, arena, self.canvas, self.input.frame, self.input.now);
for (extra.items) |command| self.painter.draw(command);
self.painter.end();
self.applyCursor();
- if (self.screenshot != null or self.options.export_to != null) {
+ if (self.screenshot != null or self.options.export_to != null or (self.control != null and self.control.?.capture_pending)) {
const surface = c.SDL_RenderReadPixels(self.renderer, null) orelse return sdlError("SDL_RenderReadPixels");
defer c.SDL_DestroySurface(surface);
if (self.screenshot) |path| {
self.screenshot = null;
if (!c.SDL_SavePNG(surface, path.ptr)) return sdlError("SDL_SavePNG");
}
+ if (self.control) |control| if (control.capture_pending) control.capture(surface);
if (self.options.export_to) |to| try self.exportFrame(surface, to);
}
if (!self.options.headless) if (self.offscreen) |canvas| {
@@ -404,8 +575,15 @@ fn draw(self: *Host, now: u64) !void {
_ = c.SDL_SetTextureBlendMode(canvas, c.SDL_BLENDMODE_NONE);
_ = c.SDL_RenderTexture(self.renderer, canvas, null, null);
};
+ // Present otherwise encodes the deferred 2D commands after the work timestamp.
+ if (!c.SDL_FlushRenderer(self.renderer)) return sdlError("SDL_FlushRenderer");
+ const work = c.SDL_GetTicksNS() - started;
+ const present_zone = tracy.zone(@src(), "present");
+ if (self.presentation) |p| p.request(self.input.frame, self.input.now);
_ = c.SDL_RenderPresent(self.renderer);
+ present_zone.end();
if (self.passes) |*g| g.endFrame();
+ return work;
}
/// One exported frame: `<to>/<its number, six digits>.png`, or for "-" its
@@ -495,9 +673,7 @@ fn context(self: *Host) abi.Context {
.input = &self.input,
.scratch = self.frame_arena.allocator(),
.session = self.session.heap.allocator(),
- .store = self.store.allocator(),
.session_root = self.session.bytes.ptr,
- .store_root = self.store.root(),
.commands = &self.commands,
};
}
@@ -535,30 +711,44 @@ 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});
+ if (err == error.NotRecording) {
+ self.console.log("Not recording (an export): no marks or clips.");
+ } else if (err == error.HistoryDropped) {
+ self.console.log("That part of the history is gone: a save keeps 64 MiB, the newest.");
+ } else if (err == error.SaveFull) {
+ self.console.log("No room for a new mark: marks and the present fill the save. Save over a mark's name (its older one goes with history), or start another save (--state).");
+ } else if (err != error.CommandFailed) self.console.print("{t}. Type help for usage.", .{err});
if (self.timeline.restored) self.jumped = true;
try self.restoredInput(now);
return err;
};
- if (self.timeline.restored or movesState(line)) self.jumped = true;
+ if (self.timeline.restored or movesState(line)) {
+ self.jumped = true;
+ self.sessions.noteLine(line);
+ }
try self.restoredInput(now);
if (self.timeline.mode == .paused) self.update(replay);
}
/// Whether a console line that succeeded may have changed State other than
-/// through `update` (restoring a snapshot is caught apart from this).
+/// through `update` (restoring a snapshot is caught apart from this): a
+/// sketch's command may.
fn movesState(line: []const u8) bool {
var words = std.mem.tokenizeAny(u8, line, " \t");
- const verb = words.next() orelse return false;
- const still = [_][]const u8{ "help", "overlay", "get", "snapshot", "recording", "diff", "stop", "pause", "save", "quit", "exit" };
- for (still) |w| if (std.mem.eql(u8, verb, w)) return false;
- return true;
+ const verb = std.meta.stringToEnum(Console.Verb, words.next() orelse return false) orelse return true;
+ return Console.verbs.get(verb).moves_state;
}
/// Offers a line to the sketch.
pub fn forward(self: *Host, _: *Console, line: []const u8, now: u64) abi.Outcome {
+ if (!self.session_ready) {
+ self.print("session setup failed; restart after fixing the resource error", .{});
+ return .failed;
+ }
self.input.now = now;
const ctx = self.context();
return self.sketch.command(&ctx, self.live().ptr, &line);
@@ -571,7 +761,6 @@ pub fn resetState(self: *Host) void {
self.sketch.defaults(.state, bytes.ptr);
const ctx = self.context();
self.sketch.init(&ctx, bytes.ptr);
- self.state.markUsed(0, true);
}
/// Loads the watched library again.
@@ -581,48 +770,49 @@ pub fn reload(self: *Host) !void {
/// Replaces the running sketch with the library at `path`, keeping state.
pub fn load(self: *Host, path: []const u8) !void {
- var library = try Library.openCopy(self.io, path, scratchDir(self.environ), self.reloads + 1);
+ var library = try Library.openFresh(self.io, path, scratchDir(self.environ), self.reloads + 1);
errdefer library.close();
+ // The State in the layout it is leaving, before migration drops any of it.
+ if (self.sessions.mode() != .off) _ = self.sessions.keyframe(.before_reload, self.live()) catch |err| self.print("session: {t}", .{err});
try self.adopt(library.sketch);
if (self.library) |*old| old.close();
self.library = library;
self.reloads += 1;
- self.build = fileHash(path);
+ self.build = fileId(self.io, path);
+ self.sessions.stretch(.{ .build = self.build, .source = self.source, .layout = self.state.header }) catch |err| self.print("session: {t}", .{err});
self.print("reload {d}: {s}", .{ self.reloads, path });
}
fn adopt(self: *Host, sketch: abi.Sketch) !void {
const info = sketch.info();
if (info.abi != abi.hash) return error.AbiMismatch;
- const adoption = try self.state.adopt(self.gpa, info.state, sketch.defaults);
+ const migrated = try self.state.adopt(self.gpa, info.state, sketch.defaults);
const session_reset = try self.session.adopt(self.gpa, info.session, sketch.defaults);
if (session_reset) self.releaseMade();
- const stored = try self.store.adopt(self.gpa, info.store, sketch.defaults);
_ = self.info_arena.reset(.retain_capacity);
const arena = self.info_arena.allocator();
self.name = try arena.dupe(u8, info.name);
+ self.source = try arena.dupe(u8, info.source);
const completions = try arena.alloc([]const u8, info.commands.len);
for (completions, info.commands) |*to, from| to.* = try arena.dupe(u8, from);
self.completions = completions;
self.sketch = sketch;
+ self.timeline.defaults = sketch.defaults;
self.reloaded = true;
- switch (adoption) {
- .unchanged => {},
- .created => {},
- .migrated => |m| self.print("state layout changed: kept {d} fields, reset {d} to defaults", .{ m.kept, m.reset }),
+ if (migrated) |m| self.print("state layout changed: kept {d} fields, reset {d} to defaults", .{ m.kept, m.reset });
+ if (session_reset) {
+ const ctx = self.context();
+ self.session_ready = self.sketch.setup(&ctx);
+ if (!self.session_ready) self.console.visible = true;
}
- if (!self.state.used(0)) self.resetState();
if (session_reset and self.reloads > 0) self.print("session layout changed: session reset", .{});
- switch (stored) {
- .unchanged, .created => {},
- .migrated => |m| self.print("store layout changed: kept {d} fields, reset {d} to defaults", .{ m.kept, m.reset }),
- }
}
/// Frees what the old Session made: its handles are gone with it.
fn releaseMade(self: *Host) void {
for (self.made.images.items) |image| {
- if (self.passes) |*g| g.forget(&self.images, image);
+ self.images.unwrap(image);
+ if (self.passes) |*g| g.forget(image);
self.images.free(image);
}
if (self.passes) |*g| for (self.made.buffers.items) |buffer| g.freeBuffer(buffer);
@@ -681,6 +871,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);
@@ -757,15 +949,102 @@ fn consoleKey(e: abi.Event) ?Console.Key {
};
}
-/// A hash of a file's bytes; 0 when it cannot be read.
-fn fileHash(path: []const u8) u64 {
- const bytes = memory.mapReadOnly(path);
- if (bytes.len == 0) return 0;
- defer std.posix.munmap(bytes);
- return std.hash.Wyhash.hash(0, bytes) | 1;
+/// Opens the save (Sessions.zig) and starts this run's session in it: a
+/// file, `<stem>.xitdb`; in memory for a script from fresh state; nowhere
+/// for an export. A save that cannot be opened is said, and the run goes
+/// on unsaved.
+fn openSessions(self: *Host, record: bool) void {
+ const o = self.options;
+ const mode: Sessions.Mode = if (o.export_to != null) .off else if (o.script and o.fresh) .memory else .file;
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = std.fmt.bufPrint(&buf, "{s}.xitdb", .{self.stem}) catch "sketch.xitdb";
+ const first: Sessions.Stretch = .{ .build = self.build, .source = self.source, .layout = self.state.header };
+ self.sessions = Sessions.open(self.gpa, self.io, mode, path, first, wallClock(self.io)) catch |err| blk: {
+ self.print("not saved: {s}: {t}", .{ path, err });
+ break :blk .{ .gpa = self.gpa, .io = self.io };
+ };
+ // Without `.record`, history is trimmed to the present and the marks.
+ self.sessions.history = record;
+ if (o.headless or self.sessions.mode() != .file) return;
+ self.print("{s} to {s}", .{ if (record) "recording" else "saving", path });
+}
+
+/// The State this run starts from: the save's present, its newest keyframe
+/// and the frames logged after it, replayed; in a new save, a state file
+/// from before (`<stem>.state`), imported once and left as it was; else
+/// `init`'s.
+fn openPresent(self: *Host) void {
+ var events: std.ArrayList(abi.Event) = .empty;
+ defer events.deinit(self.gpa);
+ const found = self.sessions.present(&events) catch |err| blk: {
+ self.print("the save's present did not read ({t}): starting from defaults", .{err});
+ break :blk null;
+ };
+ const key = found orelse {
+ if (self.sessions.session != 0 or self.sessions.mode() != .file) return self.resetState();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const old = std.fmt.bufPrint(&buf, "{s}.state", .{self.stem}) catch return self.resetState();
+ const n = importOld(self.gpa, old, &self.state, &self.sessions, self.sketch.defaults) catch |err| {
+ if (err != error.FileNotFound) self.print("{s} not imported ({t}): kept as it was", .{ old, err });
+ return self.resetState();
+ };
+ return self.print("{s} imported: its State, and {d} snapshots as marks; the file is kept as it was", .{ old, n });
+ };
+ defer key.free(self.gpa);
+ self.timeline.restore(key) catch |err| {
+ self.print("the save's present did not restore ({t}): starting from defaults", .{err});
+ return self.resetState();
+ };
+ self.timeline.restored = false;
+ var frames: usize = 0;
+ for (events.items) |e| frames += @intFromBool(e.kind == .tick);
+ if (frames == 0) return;
+ if (key.build != self.build) return self.print("{d} frames played after the save's last keyframe not replayed: another build", .{frames});
+ // As they were fed: `started` only for a run's first frame.
+ self.started = key.frame == 0;
+ self.update(events.items);
+ self.started = true;
+}
+
+/// A state file from before (`path`) into a new save: its live State into
+/// `state`, its snapshots (slots 1..7) marks "1".."7", in `state`'s layout;
+/// the file is left as it was. Returns the number of marks.
+fn importOld(gpa: std.mem.Allocator, path: []const u8, state: *memory.State, sessions: *Sessions, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !usize {
+ const old = try memory.OldState.open(path);
+ defer old.close();
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const scratch = try arena.allocator().alignedAlloc(u8, .fromByteUnits(memory.page), state.layout.size);
+ var n: usize = 0;
+ for (1..old.slots) |i| if (old.slot(i)) |image| {
+ _ = try memory.restore(arena.allocator(), old.layoutBytes(), image, state.layout, scratch, defaults);
+ _ = try sessions.mark(&.{'0' + @as(u8, @intCast(i))}, .import, scratch);
+ n += 1;
+ };
+ _ = try memory.restore(arena.allocator(), old.layoutBytes(), old.slot(0) orelse return error.CorruptStateFile, state.layout, state.live(), defaults);
+ return n;
+}
+
+/// `path` without `.xitdb` or `.state`.
+pub fn stemOf(path: []const u8) []const u8 {
+ for ([_][]const u8{ ".xitdb", ".state" }) |suffix| if (std.mem.endsWith(u8, path, suffix)) return path[0 .. path.len - suffix.len];
+ return path;
+}
+
+fn wallClock(io: std.Io) u64 {
+ return @intCast(@max(0, std.Io.Timestamp.now(io, .real).nanoseconds));
+}
+
+/// Identifies the file at `path` without reading it (a Debug library is tens
+/// of megabytes): a hash of its inode, size and modification time; 0 when
+/// there is none. A build replaces the file, so each build gets a new one.
+fn fileId(io: std.Io, path: []const u8) u64 {
+ const stat = std.Io.Dir.cwd().statFile(io, path, .{}) catch return 0;
+ const id = [3]u64{ stat.inode, stat.size, @truncate(@as(u96, @bitCast(stat.mtime.nanoseconds))) };
+ return std.hash.Wyhash.hash(0, std.mem.asBytes(&id)) | 1;
}
-fn scratchDir(environ: *const std.process.Environ.Map) []const u8 {
+pub fn scratchDir(environ: *const std.process.Environ.Map) []const u8 {
return environ.get("XDG_RUNTIME_DIR") orelse "/tmp";
}
@@ -784,12 +1063,16 @@ const api: abi.Host.VTable = .{
.gpu = apiGpu,
.newBuffer = apiNewBuffer,
.freeBuffer = apiFreeBuffer,
+ .writeBuffer = apiWriteBuffer,
.imageSize = apiImageSize,
- .textSize = apiTextSize,
+ .textRun = apiTextRun,
+ .font = apiFont,
.loadSound = apiLoadSound,
.decodeSound = apiDecodeSound,
+ .newSound = apiNewSound,
.samples = apiSamples,
.readFile = apiReadFile,
+ .appendFile = apiAppendFile,
.env = apiEnv,
.clock = apiClock,
};
@@ -814,7 +1097,8 @@ fn apiNewImage(ctx: *anyopaque, w: u32, h: u32) abi.Image {
fn apiFreeImage(ctx: *anyopaque, image: abi.Image) void {
const self = hostOf(ctx);
forget(&self.made.images, image);
- if (self.passes) |*g| g.forget(&self.images, image);
+ self.images.unwrap(image);
+ if (self.passes) |*g| g.forget(image);
self.images.free(image);
}
fn apiGpu(ctx: *anyopaque) bool {
@@ -822,12 +1106,17 @@ fn apiGpu(ctx: *anyopaque) bool {
}
fn apiNewBuffer(ctx: *anyopaque, size: u32) abi.Buffer {
const self = hostOf(ctx);
- const g = &(self.passes orelse return .none);
+ const g = if (self.passes) |*passes| passes else return .none;
return self.remember(.buffers, g.newBuffer(size) catch |err| blk: {
self.print("gpu buffer: {t} ({s})", .{ err, c.SDL_GetError() });
break :blk .none;
});
}
+fn apiWriteBuffer(ctx: *anyopaque, buffer: abi.Buffer, offset: u32, bytes: []const u8) !void {
+ const self = hostOf(ctx);
+ const gpu = if (self.passes) |*passes| passes else return error.GpuUnavailable;
+ try gpu.write(buffer, offset, bytes);
+}
fn apiFreeBuffer(ctx: *anyopaque, buffer: abi.Buffer) void {
const self = hostOf(ctx);
forget(&self.made.buffers, buffer);
@@ -839,8 +1128,12 @@ 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, face: abi.Face) [2]f32 {
- return gfx.textSize(hostOf(ctx).renderer, scale, bytes, face);
+fn apiTextRun(_: *anyopaque, face: abi.Face, scale: f32, bytes: []const u8, xs: []f32) abi.TextRun {
+ return gfx.textRun(face, scale, bytes, xs);
+}
+fn apiFont(_: *anyopaque, bytes: []const u8) ?abi.Face {
+ const face = c.sk_text_font(bytes.ptr, bytes.len);
+ return if (face < 0) null else @enumFromInt(face);
}
fn apiLoadSound(ctx: *anyopaque, path: []const u8) abi.Audio {
return hostOf(ctx).audio.load(path);
@@ -848,6 +1141,9 @@ fn apiLoadSound(ctx: *anyopaque, path: []const u8) abi.Audio {
fn apiDecodeSound(ctx: *anyopaque, wav: []const u8) abi.Audio {
return hostOf(ctx).audio.decode(wav);
}
+fn apiNewSound(ctx: *anyopaque, samples: [*]const f32, len: usize) callconv(.c) abi.Audio {
+ return hostOf(ctx).audio.new(samples[0..len]);
+}
fn apiReadFile(ctx: *anyopaque, path: []const u8) []const u8 {
const self = hostOf(ctx);
if (self.files.get(path)) |bytes| return bytes;
@@ -857,9 +1153,252 @@ fn apiReadFile(ctx: *anyopaque, path: []const u8) []const u8 {
self.files.put(self.gpa, key, bytes) catch self.gpa.free(key);
return bytes;
}
+fn apiAppendFile(ctx: *anyopaque, name_ptr: [*]const u8, name_len: usize, bytes: [*]const u8, len: usize, replace: bool) callconv(.c) [*:0]const u8 {
+ const self = hostOf(ctx);
+ const name = name_ptr[0..name_len];
+ if (name.len == 0 or std.mem.indexOfScalar(u8, name, '/') != null) {
+ self.print("appendFile: {s}: a name, not a path", .{name});
+ return "";
+ }
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const o = self.options;
+ const private = (o.script or o.export_to != null) and o.fresh;
+ // A scripted run from fresh state, or an export, writes files of its own
+ // (two runs of one build step may share a directory), gone at exit.
+ const path = (if (private) std.mem.print(&buf, "{s}.{d}.{s}", .{ self.stem, std.os.linux.getpid(), name }) else std.mem.print(&buf, "{s}.{s}", .{ self.stem, name })) catch return "";
+ if (replace) {
+ // A new file: a mapping of the old one stays valid.
+ std.Io.Dir.cwd().deleteFile(self.io, path) catch {};
+ if (self.files.fetchRemove(path)) |old| {
+ self.gpa.free(old.key);
+ self.retired.append(self.gpa, old.value) catch {};
+ }
+ }
+ const file = std.Io.Dir.cwd().createFile(self.io, path, .{ .truncate = false }) catch |err| {
+ self.print("appendFile: {s}: {t}", .{ path, err });
+ return "";
+ };
+ defer file.close(self.io);
+ const end = file.length(self.io) catch return "";
+ file.writePositionalAll(self.io, bytes[0..len], end) catch |err| {
+ self.print("appendFile: {s}: {t}", .{ path, err });
+ return "";
+ };
+ const kept = self.written.getOrPut(self.gpa, path) catch return "";
+ if (!kept.found_existing) {
+ const copy = self.gpa.dupeSentinel(u8, path, 0) catch {
+ self.written.removeByPtr(kept.key_ptr);
+ return "";
+ };
+ kept.key_ptr.* = copy;
+ }
+ return @ptrCast(kept.key_ptr.*.ptr);
+}
fn apiClock(_: *anyopaque) u64 {
return c.SDL_GetTicksNS();
}
fn apiEnv(ctx: *anyopaque, name: []const u8) ?[]const u8 {
return hostOf(ctx).environ.get(name);
}
+
+fn runPostProcess(self: *Host, g: *Gpu, source: abi.Image, target: abi.Image, post: abi.gpu.PostProcess) !void {
+ const input = g.output(source) orelse return error.MissingImage;
+ const before = g.output(target);
+ const changed = if (before) |t| t.width != input.width or t.height != input.height else true;
+ if (changed) self.images.unwrap(target);
+ try g.runPostProcess(source, target, post);
+ if (g.output(target)) |t| try self.images.wrap(target, t.texture, t.width, t.height);
+}
+
+fn runGpu(self: *Host, g: *Gpu, pass: abi.gpu.Pass) !void {
+ const before = g.output(pass.image);
+ const changed = if (before) |t| t.width != pass.width or t.height != pass.height else true;
+ if (changed) self.images.unwrap(pass.image);
+ try g.run(pass);
+ if (g.output(pass.image)) |t| try self.images.wrap(pass.image, t.texture, t.width, t.height);
+}
+
+test "session setup runs for restored state and layout reset, not same-layout reload or state reset" {
+ const Fixture = struct {
+ const State = extern struct { value: u32 = 1 };
+ const Session1 = extern struct { ready: u32 = 0 };
+ const Session2 = extern struct { ready: u32 = 0, extra: u32 = 0 };
+ var setup_calls: usize = 0;
+ var init_calls: usize = 0;
+ var fail_setup = false;
+ const description: abi.Info = .{ .abi = abi.hash, .name = "setup-test", .width = 1, .height = 1, .state = abi.layout.of(State, .state), .session = abi.layout.of(Session1, .session) };
+ const changed: abi.Info = blk: {
+ var value = description;
+ value.session = abi.layout.of(Session2, .session);
+ break :blk value;
+ };
+ fn info() callconv(.c) *const abi.Info {
+ return &description;
+ }
+ fn info2() callconv(.c) *const abi.Info {
+ return &changed;
+ }
+ fn defaults(kind: abi.Memory, ptr: [*]u8) callconv(.c) void {
+ switch (kind) {
+ .state => @as(*State, @ptrCast(@alignCast(ptr))).* = .{},
+ .session => @as(*Session1, @ptrCast(@alignCast(ptr))).* = .{},
+ }
+ }
+ fn defaults2(kind: abi.Memory, ptr: [*]u8) callconv(.c) void {
+ if (kind == .session) @as(*Session2, @ptrCast(@alignCast(ptr))).* = .{} else defaults(kind, ptr);
+ }
+ fn init(_: *const abi.Context, _: [*]u8) callconv(.c) void {
+ init_calls += 1;
+ }
+ fn setup(ctx: *const abi.Context) callconv(.c) bool {
+ setup_calls += 1;
+ @as(*u32, @ptrCast(@alignCast(ctx.session_root))).* += 1;
+ return !fail_setup;
+ }
+ fn update(_: *const abi.Context, _: [*]u8) callconv(.c) void {}
+ fn draw(_: *const abi.Context, _: [*]const u8) callconv(.c) void {}
+ fn command(_: *const abi.Context, _: [*]u8, _: *const []const u8) callconv(.c) abi.Outcome {
+ return .unknown;
+ }
+ const sketch: abi.Sketch = .{ .info = info, .defaults = defaults, .init = @This().init, .setup = setup, .update = @This().update, .draw = @This().draw, .command = command };
+ };
+ Fixture.setup_calls = 0;
+ Fixture.init_calls = 0;
+ Fixture.fail_setup = false;
+ const a = std.testing.allocator;
+ // Exercise adoption without opening SDL devices.
+ var host: Host = undefined;
+ host.gpa = a;
+ host.state = .init(a);
+ defer host.state.deinit(a);
+ host.session = .init(a);
+ defer host.session.deinit(a);
+ host.info_arena = .init(a);
+ defer host.info_arena.deinit();
+ host.frame_arena = .init(a);
+ defer host.frame_arena.deinit();
+ host.options = .{ .headless = true };
+ host.console = .{};
+ host.reloads = 0;
+ host.made = .{};
+ host.passes = null;
+ host.input = .{};
+ host.commands = .empty;
+ try host.adopt(Fixture.sketch);
+ // Defaults: the present or `init` comes after (openPresent).
+ try std.testing.expectEqual(@as(u32, 1), @as(*Fixture.State, @ptrCast(@alignCast(host.live().ptr))).value);
+ try std.testing.expectEqual(@as(usize, 0), Fixture.init_calls);
+ try std.testing.expectEqual(@as(usize, 1), Fixture.setup_calls);
+ const session_ptr = host.session.bytes.ptr;
+ try host.adopt(Fixture.sketch);
+ try std.testing.expectEqual(session_ptr, host.session.bytes.ptr);
+ try std.testing.expectEqual(@as(usize, 1), Fixture.setup_calls);
+ host.resetState();
+ try std.testing.expectEqual(@as(usize, 1), Fixture.init_calls);
+ try std.testing.expectEqual(@as(usize, 1), Fixture.setup_calls);
+ var changed = Fixture.sketch;
+ changed.info = Fixture.info2;
+ changed.defaults = Fixture.defaults2;
+ try host.adopt(changed);
+ try std.testing.expectEqual(@as(usize, 2), Fixture.setup_calls);
+ try std.testing.expectEqual(@as(u32, 1), @as(*Fixture.Session2, @ptrCast(host.session.bytes.ptr)).ready);
+ try std.testing.expect(host.session_ready);
+ Fixture.fail_setup = true;
+ defer Fixture.fail_setup = false;
+ try host.adopt(Fixture.sketch);
+ try std.testing.expect(!host.session_ready);
+ try std.testing.expect(host.console.visible);
+ try std.testing.expectEqual(abi.Outcome.failed, host.forward(&host.console, "anything", 0));
+ try host.adopt(Fixture.sketch);
+ try std.testing.expect(!host.session_ready); // A compatible reload cannot bless partial resources.
+ try std.testing.expectEqual(@as(usize, 3), Fixture.setup_calls);
+}
+
+test "setup writeBuffer propagates unavailable, unknown and out-of-bounds upload errors" {
+ const a = std.testing.allocator;
+ var host: Host = undefined;
+ host.passes = null;
+ const client: abi.Host = .{ .ctx = &host, .vtable = &api };
+ try std.testing.expectError(error.GpuUnavailable, client.writeBuffer(.none, 0, "data"));
+ host.passes = .{ .gpa = a, .device = undefined, .stencil_format = undefined };
+ defer host.passes.?.buffers.deinit(a);
+ try std.testing.expectError(error.UnknownBuffer, client.writeBuffer(.none, 0, "data"));
+ try host.passes.?.buffers.append(a, .{ .buffer = undefined, .size = 4 });
+ try std.testing.expectError(error.UploadOutOfBounds, client.writeBuffer(@fromBackingInt(@intCast(1)), 2, "data"));
+}
+
+test "a state file from before imports into a new save: its State live, its snapshots marks, the file as it was" {
+ const State = extern struct { v: u32 = 0 };
+ const D = struct {
+ fn f(_: abi.Memory, p: [*]u8) callconv(.c) void {
+ @as(*State, @ptrCast(@alignCast(p))).* = .{};
+ }
+ };
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = try std.mem.print(&buf, ".zig-cache/tmp/{s}/old.state", .{&tmp.sub_path});
+ var state: memory.State = .init(gpa);
+ defer state.deinit(gpa);
+ _ = try state.adopt(gpa, abi.layout.of(State, .state), D.f);
+ // An eight-slot SKETCH02 file, slots 0, 1 and 3 used, its header State's.
+ const stride = memory.page;
+ const old = try gpa.alloc(u8, memory.header_len + memory.old_slot_count * stride);
+ defer gpa.free(old);
+ @memset(old, 0);
+ @memcpy(old[0..state.header.len], state.header);
+ const h: *memory.Header = @ptrCast(@alignCast(old.ptr));
+ h.magic = memory.file_magic_v2;
+ h.used = 0b1011;
+ for ([_][2]u32{ .{ 0, 5 }, .{ 1, 11 }, .{ 3, 33 } }) |slot| std.mem.writeInt(u32, old[memory.header_len + slot[0] * stride ..][0..4], slot[1], .little);
+ try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = old });
+
+ var sessions = try Sessions.open(gpa, io, .memory, "", .{ .build = 1, .source = "", .layout = state.header }, 0);
+ defer sessions.deinit();
+ try std.testing.expectEqual(@as(usize, 2), try importOld(gpa, path, &state, &sessions, D.f));
+ for ([_][2]u32{ .{ '1', 11 }, .{ '3', 33 } }) |want| {
+ const m = (try sessions.findMark(&.{@intCast(want[0])})).?;
+ const key = try sessions.load(m.session, m.key);
+ defer key.free(gpa);
+ try std.testing.expectEqual(Sessions.Why.import, key.why);
+ try std.testing.expectEqual(want[1], std.mem.readInt(u32, key.state[0..4], .little));
+ }
+ try std.testing.expectEqual(@as(?Sessions.Entry, null), try sessions.findMark("2"));
+ try std.testing.expectEqual(@as(u32, 5), std.mem.readInt(u32, state.live()[0..4], .little));
+ const after = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .unlimited);
+ defer gpa.free(after);
+ try std.testing.expectEqualSlices(u8, old, after);
+}
+
+test "appendFile appends to a file beside the save and names it for readFile" {
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ var host: Host = undefined;
+ host.gpa = std.testing.allocator;
+ host.io = io;
+ host.written = .empty;
+ host.files = .empty;
+ host.options = .{};
+ host.stem = try std.mem.print(&buf, ".zig-cache/tmp/{s}/t", .{&tmp.sub_path});
+ defer {
+ var written = host.written.keyIterator();
+ while (written.next()) |path| host.gpa.free(path.ptr[0 .. path.len + 1]);
+ host.written.deinit(host.gpa);
+ }
+ const name = "take-1.f32";
+ const path = std.mem.span(apiAppendFile(&host, name, name.len, "ab", 2, false));
+ try std.testing.expect(std.mem.endsWith(u8, path, "/t.take-1.f32"));
+ try std.testing.expectEqual(path.ptr, apiAppendFile(&host, name, name.len, "cd", 2, false));
+ const bytes = try tmp.dir.readFileAlloc(io, "t.take-1.f32", host.gpa, .unlimited);
+ defer host.gpa.free(bytes);
+ try std.testing.expectEqualStrings("abcd", bytes);
+ // writeFile: a new file, its old bytes gone.
+ _ = apiAppendFile(&host, name, name.len, "e", 1, true);
+ const again = try tmp.dir.readFileAlloc(io, "t.take-1.f32", host.gpa, .unlimited);
+ defer host.gpa.free(again);
+ try std.testing.expectEqualStrings("e", again);
+}