diff options
| author | Gabriel Schneider <[email protected]> | 2026-09-25 21:47:58 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-09-25 21:48:16 -0300 |
| commit | 9c33714591a2147f7e5879e77212ca9886d0c967 (patch) | |
| tree | d250be9d9bc365d7894d49455c0f6376966b58be /src/host | |
| download | sketchbook-9c33714591a2147f7e5879e77212ca9886d0c967.tar.gz sketchbook-9c33714591a2147f7e5879e77212ca9886d0c967.zip | |
Put the game first: lib/sketchbook, sketches/vecanim
The root is the game. The platform library moves to lib/sketchbook (with
serve_web.py, which serves any sketch's web build, as a tool of it), and
vecanim to sketches/vecanim, still its own package on the same library.
Diffstat (limited to 'src/host')
| -rw-r--r-- | src/host/Console.zig | 260 | ||||
| -rw-r--r-- | src/host/Host.zig | 545 | ||||
| -rw-r--r-- | src/host/audio.zig | 284 | ||||
| -rw-r--r-- | src/host/fields.zig | 116 | ||||
| -rw-r--r-- | src/host/gfx.zig | 177 | ||||
| -rw-r--r-- | src/host/gpu.zig | 346 | ||||
| -rw-r--r-- | src/host/library.zig | 83 | ||||
| -rw-r--r-- | src/host/memory.zig | 406 | ||||
| -rw-r--r-- | src/host/overlay.zig | 76 | ||||
| -rw-r--r-- | src/host/probe.zig | 64 | ||||
| -rw-r--r-- | src/host/root.zig | 138 | ||||
| -rw-r--r-- | src/host/script.zig | 139 | ||||
| -rw-r--r-- | src/host/timeline.zig | 208 |
13 files changed, 2842 insertions, 0 deletions
diff --git a/src/host/Console.zig b/src/host/Console.zig new file mode 100644 index 0000000..d9aa469 --- /dev/null +++ b/src/host/Console.zig @@ -0,0 +1,260 @@ +//! The developer console: a line editor, a short log, and the host commands +//! (snapshots, recordings, replay, field inspection). Lines the host does not +//! know go to the sketch's `command`. +const Console = @This(); +const std = @import("std"); +const abi = @import("abi"); +const Host = @import("Host.zig"); +const fields = @import("fields.zig"); +const memory = @import("memory.zig"); +const timeline = @import("timeline.zig"); + +pub const panel_height = 144; +pub const Key = enum { left, right, home, end, backspace, delete, clear, tab, submit }; +const Line = struct { bytes: [118]u8 = @splat(0), len: usize = 0 }; + +const host_commands = [_][]const u8{ + "help", "overlay memory", "overlay sound", "get", "set", "reset", "save", "load", "snapshot", "recording", + "record", "stop", "play", "pause", "step", "seek start", "seek end", "diff", "quit", "exit", +}; + +visible: bool = false, +buffer: [96]u8 = @splat(0), +len: usize = 0, +cursor: usize = 0, +lines: [5]Line = @splat(.{}), +snapshot: usize = 1, +recording: usize = 0, +overlay_memory: bool = false, +overlay_sound: bool = false, + +pub fn text(self: *const Console) []const u8 { + return self.buffer[0..self.len]; +} + +pub fn insert(self: *Console, typed: []const u8) void { + for (typed) |byte| { + // Commands and the built-in font only need printable ASCII. + if (byte < 32 or byte > 126 or byte == '`' or self.len == self.buffer.len) continue; + std.mem.copyBackwards(u8, self.buffer[self.cursor + 1 .. self.len + 1], self.buffer[self.cursor..self.len]); + self.buffer[self.cursor] = byte; + self.cursor += 1; + self.len += 1; + } +} + +/// Edits the line; `submit` returns it (valid until the next edit). +pub fn edit(self: *Console, key: Key, extra: []const []const u8) ?[]const u8 { + switch (key) { + .left => self.cursor -|= 1, + .right => self.cursor = @min(self.len, self.cursor + 1), + .home => self.cursor = 0, + .end => self.cursor = self.len, + .clear => { + self.len = 0; + self.cursor = 0; + }, + .backspace => if (self.cursor > 0) { + self.cursor -= 1; + self.erase(); + }, + .delete => self.erase(), + .tab => self.complete(extra), + .submit => { + const line = self.text(); + // The bytes stay put until the next edit; only the length resets. + self.len = 0; + self.cursor = 0; + if (std.mem.trim(u8, line, " ").len == 0) return null; + self.print("> {s}", .{line}); + return line; + }, + } + return null; +} + +fn erase(self: *Console) void { + if (self.cursor == self.len) return; + std.mem.copyForwards(u8, self.buffer[self.cursor .. self.len - 1], self.buffer[self.cursor + 1 .. self.len]); + self.len -= 1; +} + +fn complete(self: *Console, extra: []const []const u8) void { + var first: ?[]const u8 = null; + var common: usize = 0; + var matches: [256]u8 = undefined; + var used: usize = 0; + var count: usize = 0; + for ([_][]const []const u8{ &host_commands, extra }) |list| for (list) |candidate| { + if (!std.mem.startsWith(u8, candidate, self.text())) continue; + if (first) |previous| { + var i: usize = 0; + while (i < common and i < candidate.len and previous[i] == candidate[i]) : (i += 1) {} + common = i; + } else { + first = candidate; + common = candidate.len; + } + const match = std.fmt.bufPrint(matches[used..], "{s} ", .{candidate}) catch continue; + used += match.len; + count += 1; + }; + if (first) |candidate| { + self.cursor = self.len; + self.insert(candidate[self.len..common]); + if (count > 1) self.log(matches[0..used]); + } else self.log("No completion. Type help for commands."); +} + +pub fn log(self: *Console, message: []const u8) void { + var rest = message; + while (true) { + std.mem.copyForwards(Line, self.lines[0..4], self.lines[1..5]); + const line = &self.lines[4]; + line.len = @min(rest.len, line.bytes.len); + @memcpy(line.bytes[0..line.len], rest[0..line.len]); + rest = rest[line.len..]; + if (rest.len == 0) break; + } +} + +pub fn print(self: *Console, comptime fmt: []const u8, args: anytype) void { + var buf: [512]u8 = undefined; + self.log(std.fmt.bufPrint(&buf, fmt, args) catch "(message too long)"); +} + +/// Runs one line. Host commands first; anything else goes to the sketch. +/// Returns events to replay after a seek, already restored to the snapshot. +pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const abi.Event { + const h = &host.timeline; + var words = std.mem.tokenizeAny(u8, line, " \t"); + const command = words.next() orelse return &.{}; + const arg = words.next(); + const rest = words.rest(); + + if (eq(command, "help")) { + self.log("save|load [1..7] snapshot N | record|play [0..15] recording N | stop | pause | step N | seek start|end|<ms>"); + self.log("diff [N] | reset | get <field> | set <field> <value> | overlay memory|sound | quit"); + if (!host.forward(self, line, now)) self.log("Backtick hides the console. Tab completes."); + return &.{}; + } + if (eq(command, "overlay")) { + const name = arg orelse return error.ExpectedOverlay; + const flag = if (eq(name, "memory")) &self.overlay_memory else if (eq(name, "sound")) &self.overlay_sound else return error.UnknownOverlay; + flag.* = !flag.*; + self.print("{s} overlay: {s}", .{ name, if (flag.*) "on" else "off" }); + } else if (eq(command, "get")) { + const path = arg orelse return error.ExpectedField; + const leaf = host.state.layout.find(path) orelse return error.UnknownField; + var buf: [160]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + fields.format(leaf, host.live(), &w) catch {}; + self.print("{s} = {s}", .{ path, w.buffered() }); + } else if (eq(command, "set")) { + const path = arg orelse return error.ExpectedField; + const leaf = host.state.layout.find(path) orelse return error.UnknownField; + if (rest.len == 0) return error.ExpectedValue; + h.stop(now); + try fields.set(leaf, host.live(), std.mem.trim(u8, rest, " ")); + self.print("{s} = {s}", .{ path, std.mem.trim(u8, rest, " ") }); + } else if (eq(command, "quit") or eq(command, "exit")) { + h.stop(now); + host.quit = true; + } else if (eq(command, "reset")) { + h.stop(now); + host.resetState(); + self.log("Live state reset. Snapshots are kept."); + } else if (eq(command, "snapshot")) { + self.snapshot = try slot(arg orelse return error.ExpectedSlot, 1, memory.slot_count - 1); + } else if (eq(command, "recording")) { + self.recording = try slot(arg orelse return error.ExpectedSlot, 0, timeline.recording_count - 1); + } else if (eq(command, "save") or eq(command, "load")) { + const index = if (arg) |a| try slot(a, 1, memory.slot_count - 1) else self.snapshot; + if (eq(command, "load") and !h.bank.hasSnapshot(index)) return error.EmptySnapshot; + h.stop(now); + if (eq(command, "save")) { + h.bank.save(index); + self.print("Saved snapshot {d}. Recordings from its old contents are invalidated.", .{index}); + } else { + try h.bank.restore(index); + self.print("Loaded snapshot {d}.", .{index}); + } + } else if (eq(command, "record") or eq(command, "play")) { + const index = if (arg) |a| try slot(a, 0, timeline.recording_count - 1) else self.recording; + if (eq(command, "play")) _ = try h.bank.get(index); + h.stop(now); + if (eq(command, "record")) try h.startRecording(index, self.snapshot, now) else try h.play(index, now); + self.recording = index; + self.print("{s} recording {d} from snapshot {d}.", .{ if (eq(command, "record")) "Started" else "Playing", index, h.bank.recording(index).snapshot }); + } else if (eq(command, "stop")) { + h.stop(now); + } else if (eq(command, "pause")) { + if (h.mode != .playing and h.mode != .paused) return error.NotReplaying; + h.pause(now); + } else if (eq(command, "step") or eq(command, "seek")) { + const value = arg orelse return error.ExpectedPosition; + _ = try h.bank.get(if (h.mode == .live or h.mode == .recording) self.recording else h.selected); + if (h.mode == .recording) h.stop(now); + if (h.mode == .live) try h.play(self.recording, now); + const r = try h.bank.get(h.selected); + if (eq(command, "step")) return h.step(std.fmt.parseInt(i64, value, 10) catch return error.InvalidPosition); + if (eq(value, "start")) return h.seekCount(0); + if (eq(value, "end")) return h.seekCount(r.count); + const ms = std.fmt.parseInt(u64, value, 10) catch return error.InvalidPosition; + return h.seekTime(ms *| std.time.ns_per_ms); + } else if (eq(command, "diff")) { + const index = if (arg) |a| try slot(a, 1, memory.slot_count - 1) else self.snapshot; + if (!h.bank.hasSnapshot(index)) return error.EmptySnapshot; + const diff = h.bank.compare(0, index); + self.print("Live vs snapshot {d}: {d} differing bytes; first={any}, last={any}", .{ index, diff.count, diff.first, diff.last }); + } else { + // Sketch commands edit state outside the recorded input. + h.stop(now); + if (!host.forward(self, line, now)) return error.UnknownCommand; + } + return &.{}; +} + +pub fn draw(self: *const Console, host: *Host, out: *std.ArrayList(abi.Command), arena: std.mem.Allocator) !void { + const ink: abi.Color = .{ .r = 230, .g = 255, .b = 230 }; + const hint: abi.Color = .{ .r = 145, .g = 220, .b = 150 }; + const top = @as(f32, @floatFromInt(host.canvas[1])) - panel_height; + const width: f32 = @floatFromInt(host.canvas[0]); + const h = &host.timeline; + try out.append(arena, .{ .rect = .{ .dst = .{ .x = 0, .y = top, .w = width, .h = panel_height }, .color = .{ .r = 24, .g = 28, .b = 28 } } }); + const status = try std.fmt.allocPrint(arena, "{s} | {t} | snapshot {d} | recording {d} (active {d}) | event {d} | {d}ms", .{ + host.name, h.mode, self.snapshot, self.recording, h.selected, h.cursor, h.position / std.time.ns_per_ms, + }); + try out.append(arena, .{ .text = .{ .x = 12, .y = top + 8, .scale = 1, .color = hint, .bytes = status } }); + for (&self.lines, 0..) |*line, i| { + try out.append(arena, .{ .text = .{ .x = 12, .y = top + 28 + @as(f32, @floatFromInt(i)) * 18, .scale = 1, .color = ink, .bytes = line.bytes[0..line.len] } }); + } + try out.append(arena, .{ .text = .{ .x = 12, .y = top + 122, .scale = 1, .color = ink, .bytes = try std.fmt.allocPrint(arena, "> {s}", .{self.text()}) } }); + try out.append(arena, .{ .rect = .{ .dst = .{ .x = @floatFromInt(28 + self.cursor * 8), .y = top + 120, .w = 1, .h = 12 }, .color = hint } }); +} + +fn eq(a: []const u8, b: []const u8) bool { + return std.mem.eql(u8, a, b); +} + +fn slot(value: []const u8, min: usize, max: usize) !usize { + const index = std.fmt.parseInt(usize, value, 10) catch return error.InvalidSlot; + if (index < min or index > max) return error.InvalidSlot; + return index; +} + +test "line editing, completion and submission" { + var c: Console = .{}; + c.insert("scen"); + _ = c.edit(.tab, &.{ "scene room", "scene gallery" }); + try std.testing.expectEqualStrings("scene ", c.text()); + c.insert("`room"); + try std.testing.expectEqualStrings("scene room", c.text()); + _ = c.edit(.home, &.{}); + _ = c.edit(.delete, &.{}); + try std.testing.expectEqualStrings("cene room", c.text()); + const line = c.edit(.submit, &.{}).?; + try std.testing.expectEqualStrings("cene room", line); + try std.testing.expectEqualStrings("", c.text()); + try std.testing.expect(c.edit(.submit, &.{}) == null); +} diff --git a/src/host/Host.zig b/src/host/Host.zig new file mode 100644 index 0000000..41597a6 --- /dev/null +++ b/src/host/Host.zig @@ -0,0 +1,545 @@ +//! The runtime around a sketch: window, memory, audio, timeline and console. +//! One `frame` serves both the interactive loop and test scripts, so scripts +//! exercise exactly what a player does. +const Host = @This(); +const std = @import("std"); +const c = @import("c"); +const abi = @import("abi"); +const memory = @import("memory.zig"); +const Timeline = @import("timeline.zig").Timeline; +const mapRecordings = @import("timeline.zig").mapRecordings; +const gfx = @import("gfx.zig"); +const sound = @import("audio.zig"); +const Gpu = @import("gpu.zig"); +const overlay = @import("overlay.zig"); +const Console = @import("Console.zig"); +const Library = @import("library.zig").Library; +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", + /// 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. + fresh: bool = false, +}; + +gpa: std.mem.Allocator, +io: std.Io, +environ: *const std.process.Environ.Map, +options: Options, +window: *c.SDL_Window, +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, +passes: ?Gpu = null, +pointer_cursor: ?*c.SDL_Cursor = null, +images: gfx.Images, +audio: sound.Audio, +state: memory.StateFile, +session: memory.Session, +recordings: []align(memory.page) u8, +timeline: Timeline, +console: Console = .{}, +sketch: abi.Sketch, +library: ?Library = null, +watch: ?Watch = null, +reloads: usize = 0, +/// Copies of the sketch's info strings, replaced on every load. +info_arena: std.heap.ArenaAllocator, +name: []const u8 = "", +completions: []const []const u8 = &.{}, +/// Frame lifetime: sketch scratch and this frame's commands. +frame_arena: std.heap.ArenaAllocator, +commands: std.ArrayList(abi.Command) = .empty, +/// Events routed since the last frame, fed to `update` by the next one. +pending: std.ArrayList(abi.Event) = .empty, +input: abi.Input = .{}, +files: std.StringHashMapUnmanaged([]align(memory.page) const u8) = .empty, +canvas: [2]u32 = .{ 0, 0 }, +cursor: abi.Cursor = .arrow, +quit: bool = false, +reloaded: bool = true, +last_now: u64 = 0, +/// Saved after the next frame is drawn (scripts). +screenshot: ?[:0]const u8 = 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 { + if (options.headless) { + _ = c.SDL_SetHint(c.SDL_HINT_VIDEO_DRIVER, "offscreen"); + _ = c.SDL_SetHint(c.SDL_HINT_AUDIO_DRIVER, "dummy"); + _ = c.SDL_SetHint(c.SDL_HINT_RENDER_DRIVER, "software"); + } + if (!c.SDL_Init(c.SDL_INIT_VIDEO | c.SDL_INIT_EVENTS | c.SDL_INIT_AUDIO)) return sdlError("SDL_Init"); + errdefer c.SDL_Quit(); + + 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); + break :blk library.?.sketch; + }; + errdefer if (library) |*l| l.close(); + const info = sketch.info(); + + var title_buf: [256]u8 = undefined; + const title = std.fmt.bufPrintZ(&title_buf, "{s}", .{info.name}) catch "sketch"; + const window = c.SDL_CreateWindow(title.ptr, @intCast(info.width), @intCast(info.height), c.SDL_WINDOW_RESIZABLE) orelse return sdlError("SDL_CreateWindow"); + errdefer c.SDL_DestroyWindow(window); + // The 2D renderer runs on the GPU device that also runs sketches' GPU + // passes; without one, SDL picks whatever renderer works. + var gpu = c.SDL_CreateGPUDevice(c.SDL_GPU_SHADERFORMAT_SPIRV, false, null); + var renderer: ?*c.SDL_Renderer = if (gpu) |device| c.SDL_CreateGPURenderer(device, window) else null; + if (renderer == null) { + if (gpu) |device| c.SDL_DestroyGPUDevice(device); + gpu = null; + std.log.warn("no GPU renderer ({s}); drawing without one", .{c.SDL_GetError()}); + renderer = c.SDL_CreateRenderer(window, null) orelse return sdlError("SDL_CreateRenderer"); + } + errdefer c.SDL_DestroyRenderer(renderer); + errdefer if (gpu) |device| c.SDL_DestroyGPUDevice(device); + if (!options.headless) _ = c.SDL_SetRenderVSync(renderer, 1); + + 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.fmt.bufPrint(&inputs_buf, "{s}.inputs", .{options.state})); + errdefer std.posix.munmap(recordings); + + self.* = .{ + .gpa = gpa, + .io = io, + .environ = environ, + .options = options, + .window = window, + .renderer = renderer.?, + .gpu = gpu, + .images = .{ .gpa = gpa, .renderer = renderer.? }, + .audio = .{ .gpa = gpa }, + .state = state, + .session = .init(gpa), + .recordings = recordings, + .timeline = undefined, + .sketch = sketch, + .library = library, + .info_arena = .init(gpa), + .frame_arena = .init(gpa), + }; + self.timeline = .{ .bank = .{ .state = &self.state, .inputs = recordings } }; + if (gpu) |device| self.passes = .init(gpa, device); + self.audio.open() catch |err| std.log.warn("audio unavailable: {t}", .{err}); + if (options.library) |path| if (linked == null) { + self.watch = Watch.init(path) catch null; + }; + self.setCanvas(info.width, info.height); + _ = c.SDL_StartTextInput(self.window); + try self.adopt(sketch); + if (options.fresh) { + self.state.header().used = 0; + @memset(self.recordings, 0); + self.resetState(); + } +} + +pub fn deinit(self: *Host) void { + if (self.watch) |w| w.deinit(); + self.audio.deinit(); + if (self.passes) |*g| g.deinit(&self.images); + self.images.deinit(); + if (self.pointer_cursor) |cursor| c.SDL_DestroyCursor(cursor); + c.SDL_DestroyRenderer(self.renderer); + if (self.gpu) |device| c.SDL_DestroyGPUDevice(device); + c.SDL_DestroyWindow(self.window); + var files = self.files.iterator(); + while (files.next()) |entry| { + self.gpa.free(entry.key_ptr.*); + std.posix.munmap(entry.value_ptr.*); + } + self.files.deinit(self.gpa); + std.posix.munmap(self.recordings); + self.session.deinit(self.gpa); + self.state.close(); + self.pending.deinit(self.gpa); + self.frame_arena.deinit(); + self.info_arena.deinit(); + if (self.library) |*l| l.close(); + c.SDL_Quit(); +} + +/// The interactive loop. +pub fn run(self: *Host) !void { + while (!self.quit) { + try self.poll(); + try self.frame(c.SDL_GetTicksNS()); + } + self.timeline.stop(c.SDL_GetTicksNS()); +} + +pub fn live(self: *Host) []u8 { + return self.state.slot(0); +} + +/// 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 { + _ = 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}); + + const dt = if (self.last_now == 0) 0 else now -| self.last_now; + self.last_now = now; + const h = &self.timeline; + switch (h.mode) { + .playing => self.update(h.tick(now)), + .paused => {}, + .live, .recording => { + try self.pending.append(self.gpa, .{ .kind = .tick, .time = now, .x = @floatCast(@as(f64, @floatFromInt(dt)) / std.time.ns_per_s) }); + for (self.pending.items) |e| h.capture(e) catch |err| self.print("Recording stopped: {t}", .{err}); + self.input.now = now; + self.input.dt = dt; + self.update(self.pending.items); + }, + } + self.pending.clearRetainingCapacity(); + try self.draw(if (h.mode == .live or h.mode == .recording) now else h.position); +} + +/// Feeds events to the sketch's deterministic `update`. +pub fn update(self: *Host, events: []const abi.Event) void { + // Input follows the events actually fed, live or replayed. + for (events) |e| self.input.track(e); + if (events.len > 0 and self.timeline.mode != .live and self.timeline.mode != .recording) self.input.now = events[events.len - 1].time; + self.input.events = events; + self.input.mode = self.timeline.mode; + const ctx = self.context(); + self.sketch.update(&ctx, self.live().ptr); + self.input.events = &.{}; +} + +fn draw(self: *Host, now: u64) !void { + const arena = self.frame_arena.allocator(); + self.input.now = now; + self.input.mode = self.timeline.mode; + self.input.reloaded = self.reloaded; + self.reloaded = false; + self.input.console = self.console.visible; + self.input.width = @floatFromInt(self.canvas[0]); + self.input.height = @floatFromInt(self.canvas[1]); + self.input.streams = self.audio.streamStatus(); + self.input.sample_rate = sound.sample_rate; + self.input.frame += 1; + const ctx = self.context(); + self.sketch.draw(&ctx, self.live().ptr, self.session.bytes.ptr); + + _ = c.SDL_SetRenderClipRect(self.renderer, null); + _ = c.SDL_SetRenderDrawColor(self.renderer, 0, 0, 0, 255); + _ = c.SDL_RenderClear(self.renderer); + self.audio.beginFrame(); + for (self.commands.items) |command| switch (command) { + .canvas => |size| self.setCanvas(size.w, size.h), + .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() }), + else => gfx.draw(self.renderer, &self.images, command), + }; + self.audio.endFrame(); + _ = c.SDL_SetRenderClipRect(self.renderer, null); + + 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); + } + if (self.console.visible) try self.console.draw(self, &extra, arena); + for (extra.items) |command| gfx.draw(self.renderer, &self.images, command); + self.applyCursor(); + + if (self.screenshot) |path| { + self.screenshot = 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"); + } + _ = c.SDL_RenderPresent(self.renderer); + if (self.passes) |*g| g.endFrame(); +} + +fn context(self: *Host) abi.Context { + return .{ + .host = .{ .ctx = self, .vtable = &api }, + .input = &self.input, + .arena = self.frame_arena.allocator(), + .gpa = self.session.heap.allocator(), + .commands = &self.commands, + }; +} + +/// Sends one event to the console or towards the sketch. Backtick toggles the +/// console; while it is open it owns the keyboard, and pointer events over it +/// become a cancel, so a half-made click never lands behind it. +pub fn route(self: *Host, e: abi.Event) !void { + if (e.kind == .key_down and e.code == @intFromEnum(abi.Key.grave)) { + if (e.flags & abi.Event.repeat != 0) return; + self.console.visible = !self.console.visible; + return self.pending.append(self.gpa, .{ .kind = .cancel, .time = e.time }); + } + if (self.console.visible) switch (e.kind) { + .text => { + var buf: [4]u8 = undefined; + const len = std.unicode.utf8Encode(@intCast(@min(e.value, 0x10ffff)), &buf) catch return; + self.console.insert(buf[0..len]); + return; + }, + .key_down => { + const key = consoleKey(e) orelse return; + if (self.console.edit(key, self.completions)) |line| self.runLine(line, e.time); + return; + }, + .key_up => return, + .mouse_move, .mouse_down, .mouse_up, .wheel => if (e.y >= @as(f32, @floatFromInt(self.canvas[1])) - Console.panel_height) { + return self.pending.append(self.gpa, .{ .kind = .cancel, .time = e.time }); + }, + else => {}, + }; + try self.pending.append(self.gpa, e); +} + +/// Runs a console line now, replaying whatever a seek asks for. +pub fn runLine(self: *Host, line: []const u8, now: u64) void { + const replay = self.console.execute(self, line, now) catch |err| { + self.console.print("{t}. Type help for usage.", .{err}); + return; + }; + if (self.timeline.mode == .paused) self.update(replay); +} + +/// Offers a line to the sketch; false if it did not take it. +pub fn forward(self: *Host, _: *Console, line: []const u8, now: u64) bool { + self.input.now = now; + const ctx = self.context(); + return self.sketch.command(&ctx, self.live().ptr, self.session.bytes.ptr, &line); +} + +/// Fresh state: declared defaults, then the sketch's `init`. +pub fn resetState(self: *Host) void { + const bytes = self.live(); + @memset(bytes, 0); + 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. +pub fn reload(self: *Host) !void { + try self.load(self.options.library orelse return error.NoLibrary); +} + +/// 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); + errdefer library.close(); + try self.adopt(library.sketch); + if (self.library) |*old| old.close(); + self.library = library; + self.reloads += 1; + 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 session_reset = try self.session.adopt(self.gpa, info.session, sketch.defaults); + _ = self.info_arena.reset(.retain_capacity); + const arena = self.info_arena.allocator(); + self.name = try arena.dupe(u8, info.name); + 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.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 (!self.state.used(0)) self.resetState(); + if (session_reset and self.reloads > 0) self.print("session layout changed: session reset", .{}); +} + +fn setCanvas(self: *Host, w: u32, h: u32) void { + if (w == 0 or h == 0 or (self.canvas[0] == w and self.canvas[1] == h)) return; + self.canvas = .{ w, h }; + _ = c.SDL_SetRenderLogicalPresentation(self.renderer, @intCast(w), @intCast(h), c.SDL_LOGICAL_PRESENTATION_LETTERBOX); + _ = c.SDL_SetWindowSize(self.window, @intCast(w), @intCast(h)); +} + +fn applyCursor(self: *Host) void { + const kind: abi.Cursor = if (self.console.visible) .arrow else self.cursor; + switch (kind) { + .hidden => _ = c.SDL_HideCursor(), + .arrow => { + _ = c.SDL_SetCursor(c.SDL_GetDefaultCursor()); + _ = c.SDL_ShowCursor(); + }, + .pointer => { + if (self.pointer_cursor == null) self.pointer_cursor = c.SDL_CreateSystemCursor(c.SDL_SYSTEM_CURSOR_POINTER); + _ = c.SDL_SetCursor(self.pointer_cursor orelse c.SDL_GetDefaultCursor()); + _ = c.SDL_ShowCursor(); + }, + } +} + +pub fn print(self: *Host, comptime fmt: []const u8, args: anytype) void { + var buf: [512]u8 = undefined; + const message = std.fmt.bufPrint(&buf, fmt, args) catch "(message too long)"; + self.console.log(message); + // Headless runs are tests: they report through their own results. + if (!self.options.headless) std.debug.print("{s}\n", .{message}); +} + +/// Translates SDL events into sketch events and routes them. +pub fn poll(self: *Host) !void { + var event: c.SDL_Event = undefined; + while (c.SDL_PollEvent(&event)) { + _ = c.SDL_ConvertEventToRenderCoordinates(self.renderer, &event); + const time = event.common.timestamp; + switch (event.type) { + c.SDL_EVENT_QUIT => self.quit = true, + c.SDL_EVENT_WINDOW_FOCUS_LOST => try self.route(.{ .kind = .cancel, .time = time }), + c.SDL_EVENT_MOUSE_MOTION => try self.route(.{ .kind = .mouse_move, .time = time, .x = event.motion.x, .y = event.motion.y }), + c.SDL_EVENT_MOUSE_BUTTON_DOWN, c.SDL_EVENT_MOUSE_BUTTON_UP => try self.route(.{ + .kind = if (event.type == c.SDL_EVENT_MOUSE_BUTTON_DOWN) .mouse_down else .mouse_up, + .time = time, + .x = event.button.x, + .y = event.button.y, + .code = event.button.button, + }), + c.SDL_EVENT_MOUSE_WHEEL => { + const delta = event.wheel.y * @as(f32, if (event.wheel.direction == c.SDL_MOUSEWHEEL_FLIPPED) -1 else 1); + if (!std.math.isFinite(delta) or delta == 0) continue; + try self.route(.{ .kind = .wheel, .time = time, .x = event.wheel.mouse_x, .y = event.wheel.mouse_y, .value = @bitCast(delta) }); + }, + c.SDL_EVENT_KEY_DOWN, c.SDL_EVENT_KEY_UP => try self.route(.{ + .kind = if (event.type == c.SDL_EVENT_KEY_DOWN) .key_down else .key_up, + .time = time, + .code = @intCast(event.key.scancode), + .flags = if (event.key.repeat) abi.Event.repeat else 0, + .value = modifiers(event.key.mod), + }), + c.SDL_EVENT_TEXT_INPUT => { + var it = (std.unicode.Utf8View.init(std.mem.span(event.text.text)) catch continue).iterator(); + while (it.nextCodepoint()) |cp| try self.route(.{ .kind = .text, .time = time, .value = cp }); + }, + else => {}, + } + } +} + +fn modifiers(mod: c.SDL_Keymod) u32 { + var m: u32 = 0; + if (mod & c.SDL_KMOD_SHIFT != 0) m |= abi.Key.Mod.shift; + if (mod & c.SDL_KMOD_CTRL != 0) m |= abi.Key.Mod.ctrl; + if (mod & c.SDL_KMOD_ALT != 0) m |= abi.Key.Mod.alt; + if (mod & c.SDL_KMOD_GUI != 0) m |= abi.Key.Mod.gui; + return m; +} + +fn consoleKey(e: abi.Event) ?Console.Key { + const key: abi.Key = @enumFromInt(@as(u8, @truncate(e.code))); + if (key == .u and e.value & abi.Key.Mod.ctrl != 0) return .clear; + if (e.flags & abi.Event.repeat != 0 and key.isEnter()) return null; + if (key.isEnter()) return .submit; + return switch (key) { + .left => .left, + .right => .right, + .home => .home, + .end => .end, + .backspace => .backspace, + .delete => .delete, + .escape => .clear, + .tab => .tab, + else => null, + }; +} + +fn scratchDir(environ: *const std.process.Environ.Map) []const u8 { + return environ.get("XDG_RUNTIME_DIR") orelse "/tmp"; +} + +fn sdlError(what: []const u8) error{Sdl} { + std.log.err("{s}: {s}", .{ what, c.SDL_GetError() }); + return error.Sdl; +} + +// Host services, as seen by sketches. +const api: abi.Host.VTable = .{ + .log = apiLog, + .loadImage = apiLoadImage, + .decodeImage = apiDecodeImage, + .newImage = apiNewImage, + .freeImage = apiFreeImage, + .gpu = apiGpu, + .imageSize = apiImageSize, + .loadSound = apiLoadSound, + .decodeSound = apiDecodeSound, + .readFile = apiReadFile, + .env = apiEnv, + .clock = apiClock, +}; + +fn hostOf(ctx: *anyopaque) *Host { + return @ptrCast(@alignCast(ctx)); +} +fn apiLog(ctx: *anyopaque, message: []const u8) void { + hostOf(ctx).print("{s}", .{message}); +} +fn apiLoadImage(ctx: *anyopaque, path: []const u8) abi.Image { + return hostOf(ctx).images.load(path); +} +fn apiDecodeImage(ctx: *anyopaque, png: []const u8) abi.Image { + return hostOf(ctx).images.decode(png); +} +fn apiNewImage(ctx: *anyopaque, w: u32, h: u32) abi.Image { + return hostOf(ctx).images.new(w, h); +} +fn apiFreeImage(ctx: *anyopaque, image: abi.Image) void { + const self = hostOf(ctx); + if (self.passes) |*g| g.forget(&self.images, image); + self.images.free(image); +} +fn apiGpu(ctx: *anyopaque) bool { + return hostOf(ctx).gpu != null; +} +fn apiImageSize(ctx: *anyopaque, image: abi.Image) [2]u32 { + return hostOf(ctx).images.size(image); +} +fn apiLoadSound(ctx: *anyopaque, path: []const u8) abi.Audio { + return hostOf(ctx).audio.load(path); +} +fn apiDecodeSound(ctx: *anyopaque, wav: []const u8) abi.Audio { + return hostOf(ctx).audio.decode(wav); +} +fn apiReadFile(ctx: *anyopaque, path: []const u8) []const u8 { + const self = hostOf(ctx); + if (self.files.get(path)) |bytes| return bytes; + const bytes = memory.mapReadOnly(path); + if (bytes.len == 0) return &.{}; + const key = self.gpa.dupe(u8, path) catch return bytes; + self.files.put(self.gpa, key, bytes) catch self.gpa.free(key); + return bytes; +} +fn apiClock(_: *anyopaque) u64 { + return c.SDL_GetTicksNS(); +} +fn apiEnv(ctx: *anyopaque, name: []const u8) ?[]const u8 { + return hostOf(ctx).environ.get(name); +} diff --git a/src/host/audio.zig b/src/host/audio.zig new file mode 100644 index 0000000..fc8dcfb --- /dev/null +++ b/src/host/audio.zig @@ -0,0 +1,284 @@ +//! Sound output: decoded clips played by reconciled voices, plus raw streams +//! the sketch fills itself. The audio thread only ever sees SDL's own copies +//! of the samples; sketch code and memory never run on it. +const std = @import("std"); +const c = @import("c"); +const abi = @import("abi"); + +pub const sample_rate = 48_000; +const spec: c.SDL_AudioSpec = .{ .format = c.SDL_AUDIO_F32, .channels = 1, .freq = sample_rate }; +/// A device block plus the next frame; 512 samples can underrun at 60 Hz. +const queue_samples = 2048; + +pub const Audio = struct { + gpa: std.mem.Allocator, + device: c.SDL_AudioDeviceID = 0, + /// Mixed voices. + voices_out: ?*c.SDL_AudioStream = null, + clips: std.ArrayList([]f32) = .empty, + paths: std.StringHashMapUnmanaged(abi.Audio) = .empty, + voices: std.ArrayList(Playing) = .empty, + streams: std.ArrayList(Stream) = .empty, + status: std.ArrayList(abi.Stream) = .empty, + scope: Scope = .{}, + + const Playing = struct { voice: abi.Voice, cursor: usize = 0, done: bool = false, seen: bool = true }; + const Stream = struct { key: u32, out: *c.SDL_AudioStream, pushed: u64 = 0 }; + + pub fn open(self: *Audio) !void { + const device = c.SDL_OpenAudioDevice(c.SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &spec); + if (device == 0) return error.OpenAudio; + self.device = device; + self.voices_out = try self.bind(); + self.scope.attach(device) catch {}; + } + + pub fn deinit(self: *Audio) void { + self.scope.deinit(); + for (self.streams.items) |s| c.SDL_DestroyAudioStream(s.out); + if (self.voices_out) |s| c.SDL_DestroyAudioStream(s); + if (self.device != 0) c.SDL_CloseAudioDevice(self.device); + for (self.clips.items) |samples| self.gpa.free(samples); + var keys = self.paths.keyIterator(); + while (keys.next()) |key| self.gpa.free(key.*); + self.paths.deinit(self.gpa); + self.clips.deinit(self.gpa); + self.voices.deinit(self.gpa); + self.streams.deinit(self.gpa); + self.status.deinit(self.gpa); + } + + fn bind(self: *Audio) !*c.SDL_AudioStream { + const out = c.SDL_CreateAudioStream(&spec, &spec) orelse return error.OpenAudio; + errdefer c.SDL_DestroyAudioStream(out); + if (!c.SDL_BindAudioStream(self.device, out)) return error.OpenAudio; + return out; + } + + pub fn load(self: *Audio, path: []const u8) abi.Audio { + if (self.paths.get(path)) |audio| return audio; + const audio = self.add(decodeFile(self.gpa, path) catch |err| blk: { + std.log.warn("sound {s}: {t}", .{ path, err }); + break :blk &.{}; + }); + const key = self.gpa.dupe(u8, path) catch return audio; + self.paths.put(self.gpa, key, audio) catch self.gpa.free(key); + return audio; + } + + pub fn decode(self: *Audio, wav: []const u8) abi.Audio { + return self.add(decodeWav(self.gpa, wav) catch &.{}); + } + + fn add(self: *Audio, samples: []f32) abi.Audio { + self.clips.append(self.gpa, samples) catch { + self.gpa.free(samples); + return .none; + }; + return @enumFromInt(self.clips.items.len); + } + + fn samplesOf(self: *Audio, audio: abi.Audio) []const f32 { + const index = @intFromEnum(audio); + if (index == 0 or index > self.clips.items.len) return &.{}; + return self.clips.items[index - 1]; + } + + pub fn beginFrame(self: *Audio) void { + for (self.voices.items) |*v| v.seen = false; + } + + /// Reconciles one declared voice with what is playing. + pub fn declare(self: *Audio, voice: abi.Voice) void { + for (self.voices.items) |*playing| { + if (playing.voice.key != voice.key) continue; + const restart = playing.voice.serial != voice.serial or playing.voice.audio != voice.audio; + playing.voice = voice; + playing.seen = true; + if (restart) { + playing.cursor = 0; + playing.done = false; + } + return; + } + self.voices.append(self.gpa, .{ .voice = voice }) catch {}; + } + + pub fn push(self: *Audio, key: u32, samples: []const f32, clear: bool) void { + const s = self.streamFor(key) orelse return; + if (clear) { + _ = c.SDL_ClearAudioStream(s.out); + s.pushed = 0; + } + if (samples.len == 0) return; + if (c.SDL_PutAudioStreamData(s.out, samples.ptr, @intCast(samples.len * @sizeOf(f32)))) s.pushed += samples.len; + } + + fn streamFor(self: *Audio, key: u32) ?*Stream { + for (self.streams.items) |*s| if (s.key == key) return s; + if (self.device == 0) return null; + const out = self.bind() catch return null; + self.streams.append(self.gpa, .{ .key = key, .out = out }) catch { + c.SDL_DestroyAudioStream(out); + return null; + }; + return &self.streams.items[self.streams.items.len - 1]; + } + + /// Drops undeclared voices and keeps the voice mix queued ahead. + pub fn endFrame(self: *Audio) void { + var i: usize = 0; + while (i < self.voices.items.len) { + if (self.voices.items[i].seen) i += 1 else _ = self.voices.swapRemove(i); + } + const out = self.voices_out orelse return; + const queued = c.SDL_GetAudioStreamQueued(out); + if (queued < 0) return; + const needed = queue_samples -| @as(usize, @intCast(queued)) / @sizeOf(f32); + var buffer: [queue_samples]f32 = undefined; + const count = self.mix(buffer[0..needed]); + if (count != 0) _ = c.SDL_PutAudioStreamData(out, &buffer, @intCast(count * @sizeOf(f32))); + } + + /// Mixes live voices into `output`; returns how many samples were written, + /// stopping early once every voice has finished. + pub fn mix(self: *Audio, output: []f32) usize { + var count: usize = 0; + for (output) |*sample| { + var sum: f32 = 0; + var alive = false; + for (self.voices.items) |*playing| { + if (playing.done) continue; + const samples = self.samplesOf(playing.voice.audio); + if (playing.cursor >= samples.len) { + playing.done = true; + continue; + } + alive = true; + const v = playing.voice; + const edge = @min(playing.cursor + 1, samples.len - playing.cursor); + const fade: f32 = if (v.fade == 0) 1 else @as(f32, @floatFromInt(@min(edge, v.fade))) / @as(f32, @floatFromInt(v.fade)); + sum += samples[playing.cursor] * v.volume * fade; + playing.cursor += 1; + if (playing.cursor == samples.len and v.loop) playing.cursor = 0; + } + if (!alive) break; + // Bounded however many voices sound at once. + sample.* = sum / (1 + @abs(sum)); + count += 1; + } + return count; + } + + pub fn streamStatus(self: *Audio) []const abi.Stream { + self.status.clearRetainingCapacity(); + for (self.streams.items) |s| { + const queued = c.SDL_GetAudioStreamQueued(s.out); + self.status.append(self.gpa, .{ .key = s.key, .queued = @intCast(@divFloor(@max(queued, 0), @sizeOf(f32))), .pushed = s.pushed }) catch {}; + } + return self.status.items; + } +}; + +fn decodeWav(gpa: std.mem.Allocator, wav: []const u8) ![]f32 { + const io = c.SDL_IOFromConstMem(wav.ptr, wav.len) orelse return error.OpenWav; + var from: c.SDL_AudioSpec = undefined; + var data: [*c]u8 = null; + var len: u32 = 0; + if (!c.SDL_LoadWAV_IO(io, true, &from, &data, &len)) return error.DecodeWav; + defer c.SDL_free(data); + return convert(gpa, &from, data[0..len]); +} + +fn decodeFile(gpa: std.mem.Allocator, path: []const u8) ![]f32 { + var buf: [std.fs.max_path_bytes]u8 = undefined; + const z = try std.fmt.bufPrintZ(&buf, "{s}", .{path}); + var info: c.SF_INFO = std.mem.zeroes(c.SF_INFO); + const file = c.sf_open(z.ptr, c.SFM_READ, &info) orelse return error.OpenSoundFile; + defer _ = c.sf_close(file); + if (info.samplerate <= 0 or info.samplerate > 192000 or info.channels <= 0 or info.channels > 8 or info.frames <= 0 or info.frames > @as(i64, info.samplerate) * 600) return error.UnsupportedSoundFormat; + const raw = try gpa.alloc(f32, @intCast(info.frames * info.channels)); + defer gpa.free(raw); + if (c.sf_readf_float(file, raw.ptr, info.frames) != info.frames) return error.TruncatedAudio; + const from: c.SDL_AudioSpec = .{ .format = c.SDL_AUDIO_F32, .channels = info.channels, .freq = info.samplerate }; + return convert(gpa, &from, std.mem.sliceAsBytes(raw)); +} + +/// To host format: f32 mono at `sample_rate`, all finite. +fn convert(gpa: std.mem.Allocator, from: *const c.SDL_AudioSpec, data: []const u8) ![]f32 { + if (data.len == 0 or data.len > std.math.maxInt(c_int)) return error.InvalidAudioLength; + var out: [*c]u8 = null; + var out_len: c_int = 0; + if (!c.SDL_ConvertAudioSamples(from, data.ptr, @intCast(data.len), &spec, &out, &out_len)) return error.ConvertAudio; + defer c.SDL_free(out); + if (out_len <= 0 or @mod(out_len, 4) != 0) return error.InvalidAudioLength; + const samples = @as([*]const f32, @ptrCast(@alignCast(out)))[0..@intCast(@divExact(out_len, 4))]; + for (samples) |v| if (!std.math.isFinite(v)) return error.InvalidAudioSample; + return gpa.dupe(f32, samples); +} + +/// A read-only tap of the device's final mix, for the sound overlay. +pub const Scope = struct { + mutex: ?*c.SDL_Mutex = null, + device: c.SDL_AudioDeviceID = 0, + ring: [512]f32 = @splat(0), + cursor: usize = 0, + rate: u32 = sample_rate, + + pub fn attach(self: *Scope, device: c.SDL_AudioDeviceID) !void { + self.mutex = c.SDL_CreateMutex() orelse return error.ScopeMutex; + if (!c.SDL_SetAudioPostmixCallback(device, callback, self)) return error.ScopeCallback; + self.device = device; + } + pub fn deinit(self: *Scope) void { + // SDL waits for a callback in flight before removing it. + if (self.device != 0) _ = c.SDL_SetAudioPostmixCallback(self.device, null, null); + if (self.mutex) |m| c.SDL_DestroyMutex(m); + self.* = .{}; + } + /// Oldest first. + pub fn snapshot(self: *Scope) [512]f32 { + var result: [512]f32 = @splat(0); + const m = self.mutex orelse return result; + c.SDL_LockMutex(m); + defer c.SDL_UnlockMutex(m); + for (&result, 0..) |*s, i| s.* = self.ring[(self.cursor + i) % self.ring.len]; + return result; + } + fn callback(userdata: ?*anyopaque, s: [*c]const c.SDL_AudioSpec, buffer: [*c]f32, bytes: c_int) callconv(.c) void { + const self: *Scope = @ptrCast(@alignCast(userdata orelse return)); + if (s == null or s.*.channels <= 0 or bytes <= 0) return; + const m = self.mutex orelse return; + // Dropping one picture beats blocking the audio thread. + if (!c.SDL_TryLockMutex(m)) return; + defer c.SDL_UnlockMutex(m); + const channels: usize = @intCast(s.*.channels); + const frames = @as(usize, @intCast(bytes)) / @sizeOf(f32) / channels; + self.rate = @intCast(s.*.freq); + for (0..frames) |i| { + self.ring[self.cursor] = buffer[i * channels]; + self.cursor = (self.cursor + 1) % self.ring.len; + } + } +}; + +test "voices reconcile: one-shots finish and stay silent, new serials restart, undeclared keys stop" { + var audio: Audio = .{ .gpa = std.testing.allocator }; + defer audio.deinit(); + const clip = audio.add(try std.testing.allocator.dupe(f32, &.{ 0.5, 0.5, 0.5 })); + var out: [8]f32 = undefined; + audio.beginFrame(); + audio.declare(.{ .key = 1, .audio = clip }); + try std.testing.expectEqual(@as(usize, 3), audio.mix(&out)); + audio.beginFrame(); + audio.declare(.{ .key = 1, .audio = clip }); + try std.testing.expectEqual(@as(usize, 0), audio.mix(&out)); + audio.beginFrame(); + audio.declare(.{ .key = 1, .audio = clip, .serial = 1 }); + try std.testing.expectEqual(@as(usize, 3), audio.mix(&out)); + audio.beginFrame(); + audio.declare(.{ .key = 2, .audio = clip, .loop = true }); + audio.endFrame(); + try std.testing.expectEqual(@as(usize, 1), audio.voices.items.len); + try std.testing.expectEqual(@as(usize, 8), audio.mix(&out)); +} diff --git a/src/host/fields.zig b/src/host/fields.zig new file mode 100644 index 0000000..215f176 --- /dev/null +++ b/src/host/fields.zig @@ -0,0 +1,116 @@ +//! Reading and writing state by field path, from the reflected layout alone. +//! Shared by the console, the memory overlay, scripts and the probe. +const std = @import("std"); +const abi = @import("abi"); +const Leaf = @import("memory.zig").Layout.Leaf; + +pub fn format(leaf: Leaf, memory: []const u8, w: *std.Io.Writer) std.Io.Writer.Error!void { + const bytes = leaf.bytes(memory); + switch (leaf.kind) { + .int => try w.print("{d}", .{readInt(i64, bytes)}), + .uint => try w.print("{d}", .{readInt(u64, bytes)}), + .bool => try w.writeAll(if (bytes[0] != 0) "true" else "false"), + .float => switch (leaf.size) { + 4 => try w.print("{d}", .{@as(f32, @bitCast(bytes[0..4].*))}), + 8 => try w.print("{d}", .{@as(f64, @bitCast(bytes[0..8].*))}), + else => try w.writeAll("?"), + }, + .@"enum" => { + const value = readInt(i64, bytes); + if (tagName(leaf.tags, value)) |name| try w.print(".{s}", .{name}) else try w.print("{d}", .{value}); + }, + else => try w.print("<{d} bytes>", .{leaf.size}), + } +} + +/// Parses `text` as the field's kind (enums by name or number) and stores it. +pub fn set(leaf: Leaf, memory: []u8, text: []const u8) !void { + const bytes = memory[leaf.offset..][0..leaf.size]; + switch (leaf.kind) { + .int, .uint, .@"enum" => { + const name = std.mem.trimStart(u8, text, "."); + const value: i64 = if (leaf.kind == .@"enum" and tagValue(leaf.tags, name) != null) + tagValue(leaf.tags, name).? + else + std.fmt.parseInt(i64, text, 0) catch return error.InvalidValue; + writeInt(bytes, value); + }, + .bool => bytes[0] = if (std.mem.eql(u8, text, "true") or std.mem.eql(u8, text, "1")) 1 else if (std.mem.eql(u8, text, "false") or std.mem.eql(u8, text, "0")) 0 else return error.InvalidValue, + .float => { + const value = std.fmt.parseFloat(f64, text) catch return error.InvalidValue; + switch (leaf.size) { + 4 => bytes[0..4].* = @bitCast(@as(f32, @floatCast(value))), + 8 => bytes[0..8].* = @bitCast(value), + else => return error.UnsupportedField, + } + }, + else => return error.UnsupportedField, + } +} + +/// True when the field's formatted value equals `text` (enum names compare +/// with or without the leading dot). +pub fn matches(leaf: Leaf, memory: []const u8, text: []const u8) bool { + var buf: [128]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + format(leaf, memory, &w) catch return false; + const shown = w.buffered(); + if (std.mem.eql(u8, shown, text)) return true; + if (leaf.kind == .@"enum") { + if (std.mem.eql(u8, std.mem.trimStart(u8, shown, "."), std.mem.trimStart(u8, text, "."))) return true; + const value = std.fmt.parseInt(i64, text, 0) catch return false; + return value == readInt(i64, leaf.bytes(memory)); + } + return false; +} + +pub fn readInt(comptime T: type, bytes: []const u8) T { + const n: usize = @min(bytes.len, 8); + const value = std.mem.readVarInt(u64, bytes[0..n], .little); + if (T == u64) return value; + // Sign-extend from the field's own width. + const shift: u6 = @intCast(64 - n * 8); + return @as(i64, @bitCast(value << shift)) >> shift; +} + +pub fn writeInt(bytes: []u8, value: i64) void { + const raw: u64 = @bitCast(value); + for (bytes, 0..) |*b, i| b.* = if (i < 8) @truncate(raw >> @intCast(i * 8)) else 0; +} + +pub fn tagName(tags: []const u8, value: i64) ?[]const u8 { + var it = std.mem.tokenizeScalar(u8, tags, ','); + while (it.next()) |pair| { + const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; + if ((std.fmt.parseInt(i64, pair[eq + 1 ..], 10) catch continue) == value) return pair[0..eq]; + } + return null; +} + +pub fn tagValue(tags: []const u8, name: []const u8) ?i64 { + var it = std.mem.tokenizeScalar(u8, tags, ','); + while (it.next()) |pair| { + const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; + if (std.mem.eql(u8, pair[0..eq], name)) return std.fmt.parseInt(i64, pair[eq + 1 ..], 10) catch null; + } + return null; +} + +test "fields format, parse and compare by kind" { + const S = extern struct { mood: enum(u32) { calm, angry = 5 } = .calm, x: i16 = -3, speed: f32 = 1.5, on: bool = false }; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const layout = try @import("memory.zig").Layout.copy(arena.allocator(), abi.layout.of(S, .forbidden)); + var s: S = .{}; + const bytes = std.mem.asBytes(&s); + try std.testing.expect(matches(layout.find("x").?, bytes, "-3")); + try set(layout.find("mood").?, bytes, "angry"); + try std.testing.expectEqual(.angry, s.mood); + try std.testing.expect(matches(layout.find("mood").?, bytes, ".angry")); + try std.testing.expect(matches(layout.find("mood").?, bytes, "5")); + try set(layout.find("speed").?, bytes, "0.25"); + try std.testing.expectEqual(@as(f32, 0.25), s.speed); + try set(layout.find("on").?, bytes, "true"); + try std.testing.expect(s.on); + try std.testing.expectError(error.InvalidValue, set(layout.find("x").?, bytes, "banana")); +} diff --git a/src/host/gfx.zig b/src/host/gfx.zig new file mode 100644 index 0000000..e00d325 --- /dev/null +++ b/src/host/gfx.zig @@ -0,0 +1,177 @@ +//! Images and drawing. Textures have host lifetime; sketches hold handles. +const std = @import("std"); +const c = @import("c"); +const abi = @import("abi"); + +pub const Images = struct { + gpa: std.mem.Allocator, + renderer: *c.SDL_Renderer, + /// Handle `n` is `entries[n - 1]`. + entries: std.ArrayList(Entry) = .empty, + paths: std.StringHashMapUnmanaged(abi.Image) = .empty, + + const Entry = struct { + texture: ?*c.SDL_Texture = null, + w: u32 = 0, + h: u32 = 0, + }; + + pub fn deinit(self: *Images) void { + for (self.entries.items) |entry| if (entry.texture) |t| c.SDL_DestroyTexture(t); + self.entries.deinit(self.gpa); + var keys = self.paths.keyIterator(); + while (keys.next()) |key| self.gpa.free(key.*); + self.paths.deinit(self.gpa); + } + + pub fn load(self: *Images, path: []const u8) abi.Image { + if (self.paths.get(path)) |image| return image; + var buf: [std.fs.max_path_bytes]u8 = undefined; + const z = std.fmt.bufPrintZ(&buf, "{s}", .{path}) catch return .none; + const surface = c.SDL_LoadPNG(z.ptr); + if (surface == null) std.log.warn("image {s}: {s}", .{ path, c.SDL_GetError() }); + const image = self.add(surface); + const key = self.gpa.dupe(u8, path) catch return image; + self.paths.put(self.gpa, key, image) catch self.gpa.free(key); + return image; + } + + pub fn decode(self: *Images, png: []const u8) abi.Image { + const io = c.SDL_IOFromConstMem(png.ptr, png.len) orelse return .none; + return self.add(c.SDL_LoadPNG_IO(io, true)); + } + + pub fn new(self: *Images, w: u32, h: u32) abi.Image { + const texture = c.SDL_CreateTexture(self.renderer, c.SDL_PIXELFORMAT_RGBA32, c.SDL_TEXTUREACCESS_STREAMING, @intCast(w), @intCast(h)); + if (texture) |t| setup(t); + return self.append(.{ .texture = texture, .w = w, .h = h }); + } + + /// Makes `image` show a GPU render target (GPU renderer only). + pub fn wrap(self: *Images, image: abi.Image, gpu_texture: *anyopaque, w: u32, h: u32) !void { + const entry = self.get(image) orelse return error.UnknownImage; + const props = c.SDL_CreateProperties(); + defer c.SDL_DestroyProperties(props); + _ = c.SDL_SetPointerProperty(props, c.SDL_PROP_TEXTURE_CREATE_GPU_TEXTURE_POINTER, gpu_texture); + _ = c.SDL_SetNumberProperty(props, c.SDL_PROP_TEXTURE_CREATE_FORMAT_NUMBER, c.SDL_PIXELFORMAT_ABGR8888); + _ = c.SDL_SetNumberProperty(props, c.SDL_PROP_TEXTURE_CREATE_WIDTH_NUMBER, w); + _ = c.SDL_SetNumberProperty(props, c.SDL_PROP_TEXTURE_CREATE_HEIGHT_NUMBER, h); + const texture = c.SDL_CreateTextureWithProperties(self.renderer, props) orelse return error.WrapTexture; + // Rendered output: smooth scaling, and already premultiplied. + _ = c.SDL_SetTextureScaleMode(texture, c.SDL_SCALEMODE_LINEAR); + _ = c.SDL_SetTextureBlendMode(texture, c.SDL_BLENDMODE_BLEND_PREMULTIPLIED); + if (entry.texture) |old| c.SDL_DestroyTexture(old); + entry.* = .{ .texture = texture, .w = w, .h = h }; + } + + /// Stops showing a wrapped render target, before the target goes away. + pub fn unwrap(self: *Images, image: abi.Image) void { + const entry = self.get(image) orelse return; + if (entry.texture) |t| c.SDL_DestroyTexture(t); + entry.texture = null; + } + + pub fn free(self: *Images, image: abi.Image) void { + const entry = self.get(image) orelse return; + if (entry.texture) |t| c.SDL_DestroyTexture(t); + entry.* = .{}; + } + + pub fn size(self: *Images, image: abi.Image) [2]u32 { + const entry = self.get(image) orelse return .{ 0, 0 }; + return .{ entry.w, entry.h }; + } + + pub fn get(self: *Images, image: abi.Image) ?*Entry { + const index = @intFromEnum(image); + if (index == 0 or index > self.entries.items.len) return null; + return &self.entries.items[index - 1]; + } + + /// Takes ownership of `surface`, which may be null (a missing image). + fn add(self: *Images, surface: ?*c.SDL_Surface) abi.Image { + const s = surface orelse return self.append(.{}); + defer c.SDL_DestroySurface(s); + const texture = c.SDL_CreateTextureFromSurface(self.renderer, s); + if (texture) |t| setup(t); + return self.append(.{ .texture = texture, .w = @intCast(s.*.w), .h = @intCast(s.*.h) }); + } + + fn append(self: *Images, entry: Entry) abi.Image { + self.entries.append(self.gpa, entry) catch return .none; + return @enumFromInt(self.entries.items.len); + } + + fn setup(texture: *c.SDL_Texture) void { + _ = c.SDL_SetTextureScaleMode(texture, c.SDL_SCALEMODE_NEAREST); + _ = c.SDL_SetTextureBlendMode(texture, c.SDL_BLENDMODE_BLEND); + } +}; + +/// Draws one graphics command. Other commands are not graphics: ignored. +pub fn draw(renderer: *c.SDL_Renderer, images: *Images, command: abi.Command) void { + switch (command) { + .clear => |color| { + setColor(renderer, color); + _ = c.SDL_RenderClear(renderer); + }, + .rect => |r| { + setColor(renderer, r.color); + _ = c.SDL_RenderFillRect(renderer, &frect(r.dst)); + }, + .image => |img| { + const entry = images.get(img.image); + const texture = if (entry) |e| e.texture else null; + const t = texture orelse return missing(renderer, img.dst); + _ = c.SDL_SetTextureColorMod(t, img.tint.r, img.tint.g, img.tint.b); + _ = c.SDL_SetTextureAlphaMod(t, img.tint.a); + const src = frect(img.src); + _ = c.SDL_RenderTexture(renderer, t, if (img.src.w > 0) &src else null, &frect(img.dst)); + }, + .text => |text| drawText(renderer, text.x, text.y, text.scale, text.bytes, text.color), + .clip => |clip| { + if (clip) |r| { + const rect: c.SDL_Rect = .{ .x = @intFromFloat(r.x), .y = @intFromFloat(r.y), .w = @intFromFloat(r.w), .h = @intFromFloat(r.h) }; + _ = c.SDL_SetRenderClipRect(renderer, &rect); + } else _ = c.SDL_SetRenderClipRect(renderer, null); + }, + .pixels => |p| { + const entry = images.get(p.image) orelse return; + const texture = entry.texture orelse return; + if (p.w != entry.w or p.h != entry.h or p.rgba.len < @as(usize, p.w) * p.h * 4) return; + _ = c.SDL_SetTextureBlendMode(texture, if (p.premultiplied) c.SDL_BLENDMODE_BLEND_PREMULTIPLIED else c.SDL_BLENDMODE_BLEND); + _ = c.SDL_UpdateTexture(texture, null, p.rgba.ptr, @intCast(p.w * 4)); + }, + else => {}, + } +} + +/// SDL's built-in 8x8 font, `scale` times larger. Stops at the first NUL. +pub fn drawText(renderer: *c.SDL_Renderer, x: f32, y: f32, scale: f32, bytes: []const u8, color: abi.Color) void { + var buf: [1024]u8 = undefined; + const len = @min(std.mem.indexOfScalar(u8, bytes, 0) orelse bytes.len, buf.len - 1); + @memcpy(buf[0..len], bytes[0..len]); + buf[len] = 0; + setColor(renderer, color); + var sx: f32 = 1; + var sy: f32 = 1; + _ = c.SDL_GetRenderScale(renderer, &sx, &sy); + const s = @max(scale, 1); + _ = c.SDL_SetRenderScale(renderer, sx * s, sy * s); + _ = c.SDL_RenderDebugText(renderer, x / s, y / s, &buf); + _ = c.SDL_SetRenderScale(renderer, sx, sy); +} + +fn missing(renderer: *c.SDL_Renderer, dst: abi.Rect) void { + setColor(renderer, .{ .r = 110, .g = 30, .b = 70 }); + _ = c.SDL_RenderFillRect(renderer, &frect(dst)); + drawText(renderer, dst.x + 4, dst.y + 4, 1, "missing image", .{ .r = 255, .g = 210, .b = 240 }); +} + +fn setColor(renderer: *c.SDL_Renderer, color: abi.Color) void { + _ = c.SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a); +} + +fn frect(r: abi.Rect) c.SDL_FRect { + return .{ .x = r.x, .y = r.y, .w = r.w, .h = r.h }; +} diff --git a/src/host/gpu.zig b/src/host/gpu.zig new file mode 100644 index 0000000..34c817f --- /dev/null +++ b/src/host/gpu.zig @@ -0,0 +1,346 @@ +//! Runs `abi.gpu` passes with SDL_GPU: the translation from GPU work as data +//! to a real API. Shaders and pipelines are built on first use and cached by +//! the hash of their description; entries a sketch stops using (an edited +//! shader, after a reload) are released after a while. +const Gpu = @This(); +const std = @import("std"); +const c = @import("c"); +const abi = @import("abi"); +const gfx = @import("gfx.zig"); + +pub const color_format = c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM; +/// Frames an unused shader or pipeline survives. +const keep_frames = 300; + +gpa: std.mem.Allocator, +device: *c.SDL_GPUDevice, +stencil_format: c.SDL_GPUTextureFormat, +shaders: std.AutoHashMapUnmanaged(u64, Cached(c.SDL_GPUShader)) = .empty, +pipelines: std.AutoHashMapUnmanaged(u64, Cached(c.SDL_GPUGraphicsPipeline)) = .empty, +/// Render targets per image: the resolved texture the renderer shows, and +/// multisampled and stencil attachments as passes ask for them. +targets: std.AutoHashMapUnmanaged(abi.Image, Target) = .empty, +vertices: ?*c.SDL_GPUBuffer = null, +vertex_capacity: u32 = 0, +upload: ?*c.SDL_GPUTransferBuffer = null, +upload_capacity: u32 = 0, +frame: u64 = 0, + +fn Cached(comptime T: type) type { + return struct { object: *T, used: u64 }; +} + +const Target = struct { + width: u32, + height: u32, + texture: *c.SDL_GPUTexture, + samples: u8 = 1, + msaa: ?*c.SDL_GPUTexture = null, + stencil_samples: u8 = 0, + stencil: ?*c.SDL_GPUTexture = null, +}; + +pub fn init(gpa: std.mem.Allocator, device: *c.SDL_GPUDevice) Gpu { + const d24 = c.SDL_GPUTextureSupportsFormat(device, c.SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT, c.SDL_GPU_TEXTURETYPE_2D, c.SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET); + return .{ + .gpa = gpa, + .device = device, + .stencil_format = if (d24) c.SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT else c.SDL_GPU_TEXTUREFORMAT_D32_FLOAT_S8_UINT, + }; +} + +pub fn deinit(g: *Gpu, images: *gfx.Images) void { + var shaders = g.shaders.valueIterator(); + while (shaders.next()) |s| c.SDL_ReleaseGPUShader(g.device, s.object); + var pipelines = g.pipelines.valueIterator(); + while (pipelines.next()) |p| c.SDL_ReleaseGPUGraphicsPipeline(g.device, p.object); + var targets = g.targets.iterator(); + while (targets.next()) |entry| g.releaseTarget(images, entry.key_ptr.*, entry.value_ptr.*); + if (g.vertices) |b| c.SDL_ReleaseGPUBuffer(g.device, b); + if (g.upload) |b| c.SDL_ReleaseGPUTransferBuffer(g.device, b); + g.shaders.deinit(g.gpa); + g.pipelines.deinit(g.gpa); + g.targets.deinit(g.gpa); +} + +/// Releases what nothing has used for a while. +pub fn endFrame(g: *Gpu) void { + g.frame += 1; + inline for (.{ &g.pipelines, &g.shaders }) |map| { + var it = map.iterator(); + while (it.next()) |entry| { + if (g.frame - entry.value_ptr.used < keep_frames) continue; + if (@TypeOf(map) == @TypeOf(&g.pipelines)) c.SDL_ReleaseGPUGraphicsPipeline(g.device, entry.value_ptr.object) else c.SDL_ReleaseGPUShader(g.device, entry.value_ptr.object); + map.removeByPtr(entry.key_ptr); + // The iterator is invalid after a removal: the rest waits a frame. + break; + } + } +} + +pub fn run(g: *Gpu, images: *gfx.Images, pass: abi.gpu.Pass) !void { + if (pass.width == 0 or pass.height == 0 or pass.draws.len == 0 and pass.clear == null) return; + const samples = g.supportedSamples(pass.samples); + const t = try g.renderTarget(images, pass.image, pass.width, pass.height, samples, pass.stencil); + + // Every draw's vertices go up in one copy. + var total: u32 = 0; + for (pass.draws) |d| total += @intCast(std.mem.alignForward(usize, d.vertices.len, 4)); + const cmd = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return error.GpuCommandBuffer; + if (total > 0) { + try g.reserve(total); + const mapped: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, g.upload, true) orelse return error.GpuMap); + var offset: usize = 0; + for (pass.draws) |d| { + @memcpy(mapped[offset..][0..d.vertices.len], d.vertices); + offset += std.mem.alignForward(usize, d.vertices.len, 4); + } + c.SDL_UnmapGPUTransferBuffer(g.device, g.upload); + const copy = c.SDL_BeginGPUCopyPass(cmd); + c.SDL_UploadToGPUBuffer(copy, &.{ .transfer_buffer = g.upload, .offset = 0 }, &.{ .buffer = g.vertices, .offset = 0, .size = total }, true); + c.SDL_EndGPUCopyPass(copy); + } + + const clear = pass.clear orelse .{ 0, 0, 0, 0 }; + var color: c.SDL_GPUColorTargetInfo = std.mem.zeroes(c.SDL_GPUColorTargetInfo); + color.clear_color = .{ .r = clear[0], .g = clear[1], .b = clear[2], .a = clear[3] }; + // A multisampled pass cannot load resolved pixels: it always clears. + color.load_op = if (pass.clear != null or samples > 1) c.SDL_GPU_LOADOP_CLEAR else c.SDL_GPU_LOADOP_LOAD; + if (samples > 1) { + color.texture = t.msaa; + color.store_op = c.SDL_GPU_STOREOP_RESOLVE; + color.resolve_texture = t.texture; + } else { + color.texture = t.texture; + color.store_op = c.SDL_GPU_STOREOP_STORE; + } + var depth: c.SDL_GPUDepthStencilTargetInfo = std.mem.zeroes(c.SDL_GPUDepthStencilTargetInfo); + if (pass.stencil) { + depth.texture = t.stencil; + depth.load_op = c.SDL_GPU_LOADOP_DONT_CARE; + depth.store_op = c.SDL_GPU_STOREOP_DONT_CARE; + depth.stencil_load_op = c.SDL_GPU_LOADOP_CLEAR; + depth.stencil_store_op = c.SDL_GPU_STOREOP_DONT_CARE; + depth.clear_stencil = 0; + } + const rp = c.SDL_BeginGPURenderPass(cmd, &color, 1, if (pass.stencil) &depth else null) orelse return error.GpuRenderPass; + var bound: ?*c.SDL_GPUGraphicsPipeline = null; + var offset: u32 = 0; + for (pass.draws) |d| { + defer offset += @intCast(std.mem.alignForward(usize, d.vertices.len, 4)); + if (d.pipeline >= pass.pipelines.len or d.vertex_count == 0) continue; + const built = g.pipeline(pass.pipelines[d.pipeline], samples, pass.stencil) catch |err| { + std.log.warn("gpu pipeline {d}: {t} ({s})", .{ d.pipeline, err, c.SDL_GetError() }); + continue; + }; + if (bound != built) { + c.SDL_BindGPUGraphicsPipeline(rp, built); + bound = built; + } + c.SDL_BindGPUVertexBuffers(rp, 0, &.{ .buffer = g.vertices, .offset = offset }, 1); + if (d.vertex_uniforms.len > 0) c.SDL_PushGPUVertexUniformData(cmd, 0, d.vertex_uniforms.ptr, @intCast(d.vertex_uniforms.len)); + if (d.fragment_uniforms.len > 0) c.SDL_PushGPUFragmentUniformData(cmd, 0, d.fragment_uniforms.ptr, @intCast(d.fragment_uniforms.len)); + if (pass.stencil) c.SDL_SetGPUStencilReference(rp, d.stencil_reference); + const full: abi.Rect = .{ .w = @floatFromInt(pass.width), .h = @floatFromInt(pass.height) }; + const s = d.scissor orelse full; + c.SDL_SetGPUScissor(rp, &.{ .x = @intFromFloat(@max(s.x, 0)), .y = @intFromFloat(@max(s.y, 0)), .w = @intFromFloat(@max(s.w, 0)), .h = @intFromFloat(@max(s.h, 0)) }); + c.SDL_DrawGPUPrimitives(rp, d.vertex_count, 1, 0, 0); + } + c.SDL_EndGPURenderPass(rp); + if (!c.SDL_SubmitGPUCommandBuffer(cmd)) return error.GpuSubmit; +} + +fn supportedSamples(g: *Gpu, wanted: u8) u8 { + var s: u8 = if (wanted >= 8) 8 else if (wanted >= 4) 4 else if (wanted >= 2) 2 else 1; + while (s > 1 and !c.SDL_GPUTextureSupportsSampleCount(g.device, color_format, sampleCount(s))) s /= 2; + return s; +} + +fn sampleCount(s: u8) c.SDL_GPUSampleCount { + return switch (s) { + 8 => c.SDL_GPU_SAMPLECOUNT_8, + 4 => c.SDL_GPU_SAMPLECOUNT_4, + 2 => c.SDL_GPU_SAMPLECOUNT_2, + else => c.SDL_GPU_SAMPLECOUNT_1, + }; +} + +/// The image's render target, (re)created to fit the pass. +fn renderTarget(g: *Gpu, images: *gfx.Images, image: abi.Image, w: u32, h: u32, samples: u8, stencil: bool) !*Target { + var entry = try g.targets.getOrPut(g.gpa, image); + if (entry.found_existing and (entry.value_ptr.width != w or entry.value_ptr.height != h)) { + g.releaseTarget(images, image, entry.value_ptr.*); + entry.found_existing = false; + } + if (!entry.found_existing) { + errdefer _ = g.targets.remove(image); + const resolved = try g.texture(w, h, color_format, c.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | c.SDL_GPU_TEXTUREUSAGE_SAMPLER, 1); + errdefer c.SDL_ReleaseGPUTexture(g.device, resolved); + try images.wrap(image, resolved, w, h); + entry.value_ptr.* = .{ .width = w, .height = h, .texture = resolved }; + } + const t = entry.value_ptr; + if (samples > 1 and (t.msaa == null or t.samples != samples)) { + if (t.msaa) |m| c.SDL_ReleaseGPUTexture(g.device, m); + t.msaa = try g.texture(w, h, color_format, c.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET, samples); + t.samples = samples; + } + if (stencil and (t.stencil == null or t.stencil_samples != samples)) { + if (t.stencil) |s| c.SDL_ReleaseGPUTexture(g.device, s); + t.stencil = try g.texture(w, h, g.stencil_format, c.SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET, samples); + t.stencil_samples = samples; + } + return t; +} + +fn releaseTarget(g: *Gpu, images: *gfx.Images, image: abi.Image, t: Target) void { + images.unwrap(image); + c.SDL_ReleaseGPUTexture(g.device, t.texture); + if (t.msaa) |m| c.SDL_ReleaseGPUTexture(g.device, m); + if (t.stencil) |s| c.SDL_ReleaseGPUTexture(g.device, s); +} + +/// Forgets an image's target, when the image itself is freed. +pub fn forget(g: *Gpu, images: *gfx.Images, image: abi.Image) void { + const t = g.targets.fetchRemove(image) orelse return; + g.releaseTarget(images, image, t.value); +} + +fn texture(g: *Gpu, w: u32, h: u32, format: c.SDL_GPUTextureFormat, usage: c.SDL_GPUTextureUsageFlags, samples: u8) !*c.SDL_GPUTexture { + var info: c.SDL_GPUTextureCreateInfo = std.mem.zeroes(c.SDL_GPUTextureCreateInfo); + info.type = c.SDL_GPU_TEXTURETYPE_2D; + info.format = format; + info.usage = usage; + info.width = w; + info.height = h; + info.layer_count_or_depth = 1; + info.num_levels = 1; + info.sample_count = sampleCount(samples); + return c.SDL_CreateGPUTexture(g.device, &info) orelse error.GpuTexture; +} + +fn reserve(g: *Gpu, bytes: u32) !void { + if (bytes > g.vertex_capacity) { + const capacity = @max(bytes, g.vertex_capacity * 2, 64 * 1024); + if (g.vertices) |b| c.SDL_ReleaseGPUBuffer(g.device, b); + g.vertices = c.SDL_CreateGPUBuffer(g.device, &.{ .usage = c.SDL_GPU_BUFFERUSAGE_VERTEX, .size = capacity, .props = 0 }) orelse return error.GpuBuffer; + g.vertex_capacity = capacity; + } + if (bytes > g.upload_capacity) { + const capacity = @max(bytes, g.upload_capacity * 2, 64 * 1024); + if (g.upload) |b| c.SDL_ReleaseGPUTransferBuffer(g.device, b); + g.upload = c.SDL_CreateGPUTransferBuffer(g.device, &.{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = capacity, .props = 0 }) orelse return error.GpuBuffer; + g.upload_capacity = capacity; + } +} + +fn shader(g: *Gpu, s: abi.gpu.Shader, stage: c.SDL_GPUShaderStage) !struct { *c.SDL_GPUShader, u64 } { + var h = std.hash.Wyhash.init(stage); + h.update(s.spirv); + h.update(std.mem.asBytes(&s.uniform_buffers)); + const key = h.final(); + const entry = try g.shaders.getOrPut(g.gpa, key); + if (!entry.found_existing) { + errdefer _ = g.shaders.remove(key); + entry.value_ptr.object = c.SDL_CreateGPUShader(g.device, &.{ + .code_size = s.spirv.len, + .code = s.spirv.ptr, + .entrypoint = "main", + .format = c.SDL_GPU_SHADERFORMAT_SPIRV, + .stage = stage, + .num_samplers = 0, + .num_storage_textures = 0, + .num_storage_buffers = 0, + .num_uniform_buffers = s.uniform_buffers, + .props = 0, + }) orelse return error.GpuShader; + } + entry.value_ptr.used = g.frame; + return .{ entry.value_ptr.object, key }; +} + +fn pipeline(g: *Gpu, p: abi.gpu.Pipeline, samples: u8, stencil: bool) !*c.SDL_GPUGraphicsPipeline { + const vertex, const vertex_key = try g.shader(p.vertex, c.SDL_GPU_SHADERSTAGE_VERTEX); + const fragment, const fragment_key = try g.shader(p.fragment, c.SDL_GPU_SHADERSTAGE_FRAGMENT); + // Field by field: no padding bytes in the key. + var h = std.hash.Wyhash.init(vertex_key ^ (fragment_key *% 31)); + inline for (.{ p.stride, @intFromEnum(p.primitive), @intFromEnum(p.blend), @intFromBool(p.write_color), samples, @intFromBool(stencil) }) |v| h.update(std.mem.asBytes(&@as(u32, v))); + for (p.attributes) |a| inline for (.{ a.location, @intFromEnum(a.format), a.offset }) |v| h.update(std.mem.asBytes(&@as(u32, v))); + if (p.stencil) |st| inline for (.{ st.front, st.back }) |face| inline for (.{ @intFromEnum(face.compare), @intFromEnum(face.pass), @intFromEnum(face.fail) }) |v| h.update(std.mem.asBytes(&@as(u32, v))); + const key = h.final(); + const entry = try g.pipelines.getOrPut(g.gpa, key); + if (!entry.found_existing) { + errdefer _ = g.pipelines.remove(key); + var attributes: [16]c.SDL_GPUVertexAttribute = undefined; + const count = @min(p.attributes.len, attributes.len); + for (p.attributes[0..count], attributes[0..count]) |a, *out| out.* = .{ + .location = a.location, + .buffer_slot = 0, + .offset = a.offset, + .format = switch (a.format) { + .float => c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT, + .float2 => c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2, + .float3 => c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT3, + .float4 => c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, + .ubyte4_norm => c.SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4_NORM, + }, + }; + var blend: c.SDL_GPUColorTargetBlendState = std.mem.zeroes(c.SDL_GPUColorTargetBlendState); + blend.enable_blend = p.blend != .none; + blend.color_blend_op = c.SDL_GPU_BLENDOP_ADD; + blend.alpha_blend_op = c.SDL_GPU_BLENDOP_ADD; + blend.src_color_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE; + blend.src_alpha_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE; + const dst: c.SDL_GPUBlendFactor = if (p.blend == .additive) c.SDL_GPU_BLENDFACTOR_ONE else c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA; + blend.dst_color_blendfactor = dst; + blend.dst_alpha_blendfactor = dst; + blend.enable_color_write_mask = true; + blend.color_write_mask = if (p.write_color) c.SDL_GPU_COLORCOMPONENT_R | c.SDL_GPU_COLORCOMPONENT_G | c.SDL_GPU_COLORCOMPONENT_B | c.SDL_GPU_COLORCOMPONENT_A else 0; + const target_description: c.SDL_GPUColorTargetDescription = .{ .format = color_format, .blend_state = blend }; + var depth_stencil: c.SDL_GPUDepthStencilState = std.mem.zeroes(c.SDL_GPUDepthStencilState); + if (p.stencil) |st| { + depth_stencil.enable_stencil_test = true; + depth_stencil.compare_mask = 0xff; + depth_stencil.write_mask = 0xff; + depth_stencil.front_stencil_state = stencilFace(st.front); + depth_stencil.back_stencil_state = stencilFace(st.back); + } + var info: c.SDL_GPUGraphicsPipelineCreateInfo = std.mem.zeroes(c.SDL_GPUGraphicsPipelineCreateInfo); + info.vertex_shader = vertex; + info.fragment_shader = fragment; + info.vertex_input_state = .{ + .vertex_buffer_descriptions = &.{ .slot = 0, .pitch = p.stride, .input_rate = c.SDL_GPU_VERTEXINPUTRATE_VERTEX, .instance_step_rate = 0 }, + .num_vertex_buffers = 1, + .vertex_attributes = &attributes, + .num_vertex_attributes = @intCast(count), + }; + info.primitive_type = switch (p.primitive) { + .triangle_list => c.SDL_GPU_PRIMITIVETYPE_TRIANGLELIST, + .triangle_strip => c.SDL_GPU_PRIMITIVETYPE_TRIANGLESTRIP, + .line_list => c.SDL_GPU_PRIMITIVETYPE_LINELIST, + .line_strip => c.SDL_GPU_PRIMITIVETYPE_LINESTRIP, + }; + info.rasterizer_state.fill_mode = c.SDL_GPU_FILLMODE_FILL; + info.rasterizer_state.cull_mode = c.SDL_GPU_CULLMODE_NONE; + info.rasterizer_state.front_face = c.SDL_GPU_FRONTFACE_COUNTER_CLOCKWISE; + info.multisample_state.sample_count = sampleCount(samples); + info.depth_stencil_state = depth_stencil; + info.target_info.color_target_descriptions = &target_description; + info.target_info.num_color_targets = 1; + info.target_info.depth_stencil_format = g.stencil_format; + info.target_info.has_depth_stencil_target = stencil; + entry.value_ptr.object = c.SDL_CreateGPUGraphicsPipeline(g.device, &info) orelse return error.GpuPipeline; + } + entry.value_ptr.used = g.frame; + return entry.value_ptr.object; +} + +fn stencilFace(face: abi.gpu.StencilFace) c.SDL_GPUStencilOpState { + // Both enums follow SDL's order, after its INVALID. + return .{ + .compare_op = @as(u32, @intFromEnum(face.compare)) + 1, + .pass_op = @as(u32, @intFromEnum(face.pass)) + 1, + .fail_op = @as(u32, @intFromEnum(face.fail)) + 1, + .depth_fail_op = c.SDL_GPU_STENCILOP_KEEP, + }; +} diff --git a/src/host/library.zig b/src/host/library.zig new file mode 100644 index 0000000..6c9338f --- /dev/null +++ b/src/host/library.zig @@ -0,0 +1,83 @@ +//! Loading sketch libraries, and noticing when a build replaces one. +//! +//! `dlopen` returns the handle it already has for a path it loaded before, so +//! every load goes through a private copy with a fresh name. The copy is +//! deleted right after loading: the mapping keeps the code alive, and nothing +//! is left behind if the host dies. +const std = @import("std"); +const linux = std.os.linux; +const c = @import("c"); +const abi = @import("abi"); + +pub const Library = struct { + object: *c.SDL_SharedObject, + sketch: abi.Sketch, + + pub fn open(path: [:0]const u8) !Library { + const object = c.SDL_LoadObject(path.ptr) orelse return error.LoadLibrary; + errdefer c.SDL_UnloadObject(object); + var sketch: abi.Sketch = undefined; + inline for (@typeInfo(abi.Sketch).@"struct".fields) |field| { + const symbol = @field(abi.Sketch.symbols, field.name); + const address = c.SDL_LoadFunction(object, symbol) orelse return error.MissingEntryPoint; + @field(sketch, field.name) = @ptrCast(address); + } + if (sketch.info().abi != abi.hash) return error.AbiMismatch; + return .{ .object = object, .sketch = sketch }; + } + + /// Loads `source` through a uniquely named copy in `scratch_dir`. + pub fn openCopy(io: std.Io, source: []const u8, scratch_dir: []const u8, serial: usize) !Library { + var buf: [std.fs.max_path_bytes]u8 = undefined; + const copy = try std.fmt.bufPrintZ(&buf, "{s}/sketchbook-{d}-{d}.so", .{ scratch_dir, linux.getpid(), serial }); + const cwd = std.Io.Dir.cwd(); + try cwd.copyFile(source, cwd, copy, io, .{}); + defer cwd.deleteFile(io, copy) catch {}; + return open(copy); + } + + pub fn close(self: *Library) void { + c.SDL_UnloadObject(self.object); + } +}; + +/// inotify on a library's directory, filtered to its file name. Builds +/// replace files by renaming (`MOVED_TO`) or rewrite them (`CLOSE_WRITE`). +pub const Watch = struct { + fd: i32, + name: []const u8, + + pub fn init(path: []const u8) !Watch { + const fd: i32 = @intCast(@as(isize, @bitCast(linux.inotify_init1(linux.IN.NONBLOCK | linux.IN.CLOEXEC)))); + if (fd < 0) return error.WatchFailed; + errdefer _ = linux.close(fd); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const dir = std.fs.path.dirname(path) orelse "."; + const dir_z = try std.fmt.bufPrintZ(&buf, "{s}", .{dir}); + if (@as(isize, @bitCast(linux.inotify_add_watch(fd, dir_z, linux.IN.MOVED_TO | linux.IN.CLOSE_WRITE))) < 0) return error.WatchFailed; + return .{ .fd = fd, .name = std.fs.path.basename(path) }; + } + + pub fn deinit(self: Watch) void { + _ = linux.close(self.fd); + } + + /// Drains pending events; true if any named the library. + pub fn changed(self: Watch) bool { + var found = false; + var buf: [4096]u8 align(@alignOf(linux.inotify_event)) = undefined; + while (true) { + const rc = linux.read(self.fd, &buf, buf.len); + const len: isize = @bitCast(rc); + if (len <= 0) return found; + var off: usize = 0; + while (off + @sizeOf(linux.inotify_event) <= @as(usize, @intCast(len))) { + const event: *const linux.inotify_event = @ptrCast(@alignCast(&buf[off])); + off += @sizeOf(linux.inotify_event) + event.len; + if (event.getName()) |name| { + if (std.mem.eql(u8, name, self.name)) found = true; + } + } + } + } +}; diff --git a/src/host/memory.zig b/src/host/memory.zig new file mode 100644 index 0000000..dd9f632 --- /dev/null +++ b/src/host/memory.zig @@ -0,0 +1,406 @@ +//! Sketch memory by lifetime. +//! +//! `StateFile`: one `MAP_SHARED` file holding the live state and its snapshot +//! slots, plus a header describing the layout, so the state outlives restarts, +//! a probe can read it from another process, and a reload with a changed +//! layout can carry the old values over field by field. +const std = @import("std"); +const posix = std.posix; +const linux = std.os.linux; +const abi = @import("abi"); +const field_value = @import("fields.zig"); + +pub const page = std.heap.page_size_min; +/// Slot 0 is live; 1..7 are snapshots. +pub const slot_count = 8; +pub const header_len = 64 * 1024; +pub const file_magic = "SKETCH01".*; + +pub const Header = extern struct { + magic: [8]u8 = file_magic, + size: u64, + alignment: u64, + hash: u64, + /// Distance between slots, page aligned. + stride: u64, + /// Bit `i`: slot `i` holds state. + used: u32, + field_count: u32, + strings_len: u32, + reserved: u32 = 0, +}; + +/// A leaf as stored in the file: strings are offsets into the string table. +pub const StoredField = extern struct { + offset: u32, + size: u32, + hash: u64, + path: u32, + path_len: u16, + tags_len: u16, + tags: u32, + kind: abi.Field.Kind, + reserved: [3]u8 = @splat(0), +}; + +/// A layout the host owns: copied out of a sketch, or read from a file. +pub const Layout = struct { + size: usize = 0, + alignment: usize = 1, + hash: u64 = 0, + fields: []const Leaf = &.{}, + + pub const Leaf = struct { + path: []const u8, + offset: u32, + size: u32, + kind: abi.Field.Kind, + hash: u64, + tags: []const u8, + + pub fn bytes(leaf: Leaf, memory: []const u8) []const u8 { + return memory[leaf.offset..][0..leaf.size]; + } + }; + + pub fn copy(arena: std.mem.Allocator, l: abi.Layout) !Layout { + const fields = try arena.alloc(Leaf, l.fields.len); + for (fields, l.fields) |*to, from| to.* = .{ + .path = try arena.dupe(u8, std.mem.span(from.path)), + .offset = from.offset, + .size = from.size, + .kind = from.kind, + .hash = from.hash, + .tags = try arena.dupe(u8, std.mem.span(from.tags)), + }; + return .{ .size = l.size, .alignment = l.alignment, .hash = l.hash, .fields = fields }; + } + + pub fn find(self: Layout, path: []const u8) ?Leaf { + for (self.fields) |leaf| if (std.mem.eql(u8, leaf.path, path)) return leaf; + return null; + } +}; + +pub const Migration = struct { kept: usize = 0, reset: usize = 0 }; + +/// Copies every leaf of `from` whose path and type are unchanged into `to`, +/// which already holds the new defaults. +pub fn migrate(from: Layout, old: []const u8, to: Layout, new: []u8) Migration { + var result: Migration = .{}; + for (to.fields) |leaf| { + const before = from.find(leaf.path) orelse { + result.reset += 1; + continue; + }; + if (before.hash == leaf.hash and before.size == leaf.size) { + @memcpy(new[leaf.offset..][0..leaf.size], before.bytes(old)); + result.kept += 1; + } else if (before.kind == .@"enum" and leaf.kind == .@"enum" and remapEnum(before, old, leaf, new)) { + result.kept += 1; + } else result.reset += 1; + } + return result; +} + +/// Carries an enum over by tag name; false when its name no longer exists. +fn remapEnum(from: Layout.Leaf, old: []const u8, to: Layout.Leaf, new: []u8) bool { + const name = field_value.tagName(from.tags, field_value.readInt(i64, from.bytes(old))) orelse return false; + const value = field_value.tagValue(to.tags, name) orelse return false; + field_value.writeInt(new[to.offset..][0..to.size], value); + return true; +} + +pub const StateFile = struct { + fd: posix.fd_t, + map: []align(page) u8, + /// Layout of the bytes in the file, owned by `arena`. + layout: Layout, + arena: std.heap.ArenaAllocator, + + /// Opens or creates `path`. A missing or foreign file has no layout and no + /// used slots: the first `adopt` fills it. + pub fn open(gpa: std.mem.Allocator, path: []const u8) !StateFile { + const fd = try posix.openat(posix.AT.FDCWD, path, .{ .ACCMODE = .RDWR, .CREAT = true }, 0o600); + errdefer _ = posix.system.close(fd); + var self: StateFile = .{ .fd = fd, .map = &.{}, .layout = .{}, .arena = .init(gpa) }; + errdefer self.arena.deinit(); + const len = try fileSize(fd); + if (len >= header_len) { + self.map = try mapFile(fd, @intCast(len), .{ .READ = true, .WRITE = true }); + if (self.valid()) { + self.layout = try readLayout(self.arena.allocator(), self.map) orelse .{}; + return self; + } + posix.munmap(self.map); + self.map = &.{}; + } + try self.resize(0); + self.header().* = .{ .size = 0, .alignment = 1, .hash = 0, .stride = 0, .used = 0, .field_count = 0, .strings_len = 0 }; + return self; + } + + pub fn close(self: *StateFile) void { + if (self.map.len != 0) posix.munmap(self.map); + _ = posix.system.close(self.fd); + self.arena.deinit(); + } + + pub fn header(self: *StateFile) *Header { + return @ptrCast(self.map.ptr); + } + + pub fn slot(self: *StateFile, index: usize) []align(page) u8 { + std.debug.assert(index < slot_count); + const h = self.header(); + const start = header_len + index * h.stride; + return @alignCast(self.map[start..][0..h.size]); + } + + pub fn used(self: *StateFile, index: usize) bool { + return self.header().used & (@as(u32, 1) << @intCast(index)) != 0; + } + + pub fn markUsed(self: *StateFile, index: usize, value: bool) void { + const bit = @as(u32, 1) << @intCast(index); + if (value) self.header().used |= bit else self.header().used &= ~bit; + } + + pub const Adoption = union(enum) { + unchanged, + created, + migrated: Migration, + }; + + /// Makes the file hold `new`'s layout. Used slots are migrated: `defaults` + /// writes the new default values, then unchanged fields are copied over. + pub fn adopt(self: *StateFile, gpa: std.mem.Allocator, new: abi.Layout, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !Adoption { + if (self.layout.hash == new.hash and self.layout.size == new.size and self.header().used & 1 != 0) return .unchanged; + const had_state = self.header().used & 1 != 0; + + // Keep the old bytes and layout while the file is rebuilt. + var old_arena: std.heap.ArenaAllocator = .init(gpa); + defer old_arena.deinit(); + const old_layout = self.layout; + var old_slots: [slot_count]?[]u8 = @splat(null); + for (&old_slots, 0..) |*copy, i| { + if (self.used(i)) copy.* = try old_arena.allocator().dupe(u8, self.slot(i)); + } + const old_used = self.header().used; + // `old_layout` points into `self.arena`: move it aside before resetting. + var kept = self.arena; + defer kept.deinit(); + self.arena = .init(gpa); + + self.layout = try Layout.copy(self.arena.allocator(), new); + const stride = std.mem.alignForward(usize, @max(new.size, 1), page); + try self.resize(stride); + const h = self.header(); + h.* = .{ .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = stride, .used = old_used, .field_count = 0, .strings_len = 0 }; + try self.writeLayout(); + + var total: Migration = .{}; + for (old_slots, 0..) |maybe_old, i| { + const old = maybe_old orelse continue; + const bytes = self.slot(i); + @memset(bytes, 0); + defaults(.state, bytes.ptr); + const m = migrate(old_layout, old, self.layout, bytes); + total.kept += m.kept; + if (i == 0) total.reset = m.reset; + } + if (!had_state) { + self.markUsed(0, false); + return .created; + } + return .{ .migrated = total }; + } + + fn valid(self: *StateFile) bool { + const h = self.header(); + if (!std.mem.eql(u8, &h.magic, &file_magic)) return false; + return self.map.len >= header_len + slot_count * h.stride and h.size <= h.stride; + } + + fn resize(self: *StateFile, stride: usize) !void { + const len = header_len + slot_count * stride; + if (self.map.len != 0) posix.munmap(self.map); + self.map = &.{}; + switch (posix.errno(posix.system.ftruncate(self.fd, @intCast(len)))) { + .SUCCESS => {}, + else => |err| return posix.unexpectedErrno(err), + } + self.map = try mapFile(self.fd, len, .{ .READ = true, .WRITE = true }); + } + + fn writeLayout(self: *StateFile) !void { + const h = self.header(); + const fields: [*]StoredField = @ptrCast(@alignCast(self.map.ptr + @sizeOf(Header))); + const strings_start = @sizeOf(Header) + self.layout.fields.len * @sizeOf(StoredField); + var strings: usize = 0; + for (self.layout.fields, 0..) |leaf, i| { + if (strings_start + strings + leaf.path.len + leaf.tags.len > header_len) return error.LayoutTooLarge; + const base = strings_start + strings; + @memcpy(self.map[base..][0..leaf.path.len], leaf.path); + @memcpy(self.map[base + leaf.path.len ..][0..leaf.tags.len], leaf.tags); + fields[i] = .{ + .offset = leaf.offset, + .size = leaf.size, + .hash = leaf.hash, + .kind = leaf.kind, + .path = @intCast(strings), + .path_len = @intCast(leaf.path.len), + .tags = @intCast(strings + leaf.path.len), + .tags_len = @intCast(leaf.tags.len), + }; + strings += leaf.path.len + leaf.tags.len; + } + h.field_count = @intCast(self.layout.fields.len); + h.strings_len = @intCast(strings); + } +}; + +/// The layout stored in a state file's header, or null if it has none. +pub fn readLayout(arena: std.mem.Allocator, map: []const u8) !?Layout { + const h: *const Header = @ptrCast(@alignCast(map.ptr)); + if (h.hash == 0 and h.field_count == 0) return null; + const stored: [*]const StoredField = @ptrCast(@alignCast(map.ptr + @sizeOf(Header))); + const strings_start = @sizeOf(Header) + h.field_count * @sizeOf(StoredField); + if (strings_start + h.strings_len > header_len) return error.CorruptHeader; + const strings = map[strings_start..][0..h.strings_len]; + const leaves = try arena.alloc(Layout.Leaf, h.field_count); + for (leaves, stored[0..h.field_count]) |*leaf, f| { + if (f.path + f.path_len > strings.len or f.tags + f.tags_len > strings.len) return error.CorruptHeader; + // Copied: the mapping moves when the file is resized. + leaf.* = .{ + .path = try arena.dupe(u8, strings[f.path..][0..f.path_len]), + .offset = f.offset, + .size = f.size, + .kind = f.kind, + .hash = f.hash, + .tags = try arena.dupe(u8, strings[f.tags..][0..f.tags_len]), + }; + } + return .{ .size = h.size, .alignment = h.alignment, .hash = h.hash, .fields = leaves }; +} + +pub fn mapFile(fd: posix.fd_t, len: usize, prot: posix.PROT) ![]align(page) u8 { + return posix.mmap(null, len, prot, .{ .TYPE = .SHARED }, fd, 0); +} + +pub fn fileSize(fd: posix.fd_t) !u64 { + var stat: linux.Statx = undefined; + switch (linux.errno(linux.statx(fd, "", linux.AT.EMPTY_PATH, .{ .SIZE = true }, &stat))) { + .SUCCESS => {}, + else => |err| return posix.unexpectedErrno(err), + } + return stat.size; +} + +/// Maps a whole file read-only; empty when missing or empty. +pub fn mapReadOnly(path: []const u8) []align(page) const u8 { + const fd = posix.openat(posix.AT.FDCWD, path, .{ .ACCMODE = .RDONLY }, 0) catch return &.{}; + defer _ = posix.system.close(fd); + const len = fileSize(fd) catch return &.{}; + if (len == 0) return &.{}; + return posix.mmap(null, @intCast(len), .{ .READ = true }, .{ .TYPE = .SHARED }, fd, 0) catch &.{}; +} + +/// Session memory: survives reloads while its layout hash is unchanged. +/// `heap` is released with it. +pub const Session = struct { + bytes: []align(16) u8 = &.{}, + hash: u64 = 0, + heap: std.heap.ArenaAllocator, + + pub fn init(gpa: std.mem.Allocator) Session { + return .{ .heap = .init(gpa) }; + } + + pub fn deinit(self: *Session, gpa: std.mem.Allocator) void { + gpa.free(self.bytes); + self.heap.deinit(); + } + + /// True when the session was reset to `layout`'s defaults. + pub fn adopt(self: *Session, gpa: std.mem.Allocator, layout: abi.Layout, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !bool { + if (self.hash == layout.hash and self.bytes.len == @max(layout.size, 1)) return false; + if (layout.alignment > 16) return error.SessionOveraligned; + gpa.free(self.bytes); + self.bytes = &.{}; + _ = self.heap.reset(.free_all); + self.bytes = try gpa.alignedAlloc(u8, .@"16", @max(layout.size, 1)); + @memset(self.bytes, 0); + defaults(.session, self.bytes.ptr); + self.hash = layout.hash; + return true; + } +}; + +test "enums migrate by tag name" { + const V1 = struct { mood: enum(u8) { calm, lost, angry } = .calm, gone: enum(u8) { a, b } = .b }; + const V2 = struct { mood: enum(u16) { angry = 7, calm, sleepy } = .sleepy, gone: enum(u8) { c } = .c }; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const l1 = try Layout.copy(arena.allocator(), abi.layout.of(V1, .forbidden)); + const l2 = try Layout.copy(arena.allocator(), abi.layout.of(V2, .forbidden)); + for ([_]struct { @FieldType(V1, "mood"), @FieldType(V2, "mood") }{ .{ .calm, .calm }, .{ .angry, .angry }, .{ .lost, .sleepy } }) |case| { + const old: V1 = .{ .mood = case[0] }; + var new: V2 = .{}; + _ = migrate(l1, std.mem.asBytes(&old), l2, std.mem.asBytes(&new)); + try std.testing.expectEqual(case[1], new.mood); + try std.testing.expectEqual(.c, new.gone); + } +} + +test "migration keeps unchanged fields and defaults the rest" { + const V1 = extern struct { a: u32 = 1, b: f32 = 2, gone: u8 = 3 }; + const V2 = extern struct { b: f32 = 20, a: u32 = 10, b2: [2]u8 = .{ 7, 7 } }; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const l1 = try Layout.copy(arena.allocator(), abi.layout.of(V1, .forbidden)); + const l2 = try Layout.copy(arena.allocator(), abi.layout.of(V2, .forbidden)); + const old: V1 = .{ .a = 42, .b = 0.5 }; + var new: V2 = .{}; + const m = migrate(l1, std.mem.asBytes(&old), l2, std.mem.asBytes(&new)); + try std.testing.expectEqual(V2{ .a = 42, .b = 0.5 }, new); + try std.testing.expectEqual(@as(usize, 2), m.kept); + try std.testing.expectEqual(@as(usize, 1), m.reset); +} + +test "state file migrates live state and snapshots, and a reopen reads the layout back" { + const V1 = extern struct { score: u32 = 0, name: [4]u8 = "none".* }; + const V2 = extern struct { level: u16 = 1, score: u32 = 0 }; + const D = struct { + fn v1(_: abi.Memory, p: [*]u8) callconv(.c) void { + @as(*V1, @ptrCast(@alignCast(p))).* = .{}; + } + fn v2(_: abi.Memory, p: [*]u8) callconv(.c) void { + @as(*V2, @ptrCast(@alignCast(p))).* = .{}; + } + }; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try std.fmt.bufPrint(&buf, ".zig-cache/tmp/{s}/test.state", .{&tmp.sub_path}); + const gpa = std.testing.allocator; + { + var file = try StateFile.open(gpa, path); + defer file.close(); + try std.testing.expectEqual(StateFile.Adoption.created, try file.adopt(gpa, abi.layout.of(V1, .forbidden), D.v1)); + file.markUsed(0, true); + @as(*V1, @ptrCast(file.slot(0).ptr)).score = 99; + @memcpy(file.slot(3), file.slot(0)); + file.markUsed(3, true); + } + var file = try StateFile.open(gpa, path); + defer file.close(); + try std.testing.expectEqual(abi.layout.hash(V1), file.layout.hash); + const adoption = try file.adopt(gpa, abi.layout.of(V2, .forbidden), D.v2); + try std.testing.expectEqual(@as(usize, 1), adoption.migrated.reset); + for ([_]usize{ 0, 3 }) |i| { + const s: *V2 = @ptrCast(file.slot(i).ptr); + try std.testing.expectEqual(V2{ .level = 1, .score = 99 }, s.*); + } + try std.testing.expect(!file.used(1)); +} diff --git a/src/host/overlay.zig b/src/host/overlay.zig new file mode 100644 index 0000000..919fff6 --- /dev/null +++ b/src/host/overlay.zig @@ -0,0 +1,76 @@ +//! Debug overlays drawn by the host over any sketch: the live state's fields +//! and bytes, from the reflected layout, and the audio output waveform. +const std = @import("std"); +const abi = @import("abi"); +const memory = @import("memory.zig"); +const fields = @import("fields.zig"); + +const List = std.ArrayList(abi.Command); +const shown_bytes = 0x100; + +/// Each field hashes its path into a dark shade; bytes it owns wear the same +/// shade in the hex view below, and padding stays gray. +fn shade(path: []const u8) abi.Color { + const hash = std.hash.Wyhash.hash(0, path); + return .{ .r = @as(u8, @truncate(hash)) / 2, .g = @as(u8, @truncate(hash >> 8)) / 2, .b = @as(u8, @truncate(hash >> 16)) / 2 }; +} + +pub fn drawMemory(out: *List, arena: std.mem.Allocator, layout: memory.Layout, state: []const u8, width: f32) !void { + const rows = (layout.fields.len + 1) / 2; + const legend_top: f32 = 24; + const hex_top = legend_top + @as(f32, @floatFromInt(rows)) * 14 + 16; + const shown = @min(state.len, shown_bytes); + const height = hex_top + @as(f32, @floatFromInt((shown + 15) / 16)) * 14 + 10; + try out.append(arena, .{ .rect = .{ .dst = .{ .x = 12, .y = 4, .w = width - 24, .h = height }, .color = .{ .r = 230, .g = 254, .b = 242 } } }); + try out.append(arena, .{ .text = .{ .x = 30, .y = 8, .scale = 1, .color = .{ .r = 24, .g = 24, .b = 24 }, .bytes = "MEMORY / overlay memory to hide" } }); + + // Legend: two fixed-width columns filled down then across. + const column = (width - 60) / 2; + for (layout.fields, 0..) |leaf, i| { + var value: std.Io.Writer.Allocating = .init(arena); + try fields.format(leaf, state, &value.writer); + const name = if (leaf.path.len > 26) try std.fmt.allocPrint(arena, "{s}...", .{leaf.path[0..23]}) else leaf.path; + const line = try std.fmt.allocPrint(arena, "{x:0>4} {s: <26} {s}", .{ leaf.offset, name, value.written() }); + try out.append(arena, .{ .text = .{ + .x = 30 + @as(f32, @floatFromInt(i / rows)) * column, + .y = legend_top + @as(f32, @floatFromInt(i % rows)) * 14, + .scale = 1, + .color = shade(leaf.path), + .bytes = line[0..@min(line.len, @as(usize, @intFromFloat(column / 8)) - 1)], + } }); + } + + var colors: [shown_bytes]abi.Color = @splat(.{ .r = 0x9f, .g = 0x9f, .b = 0x9f }); + for (layout.fields) |leaf| { + if (leaf.offset >= shown) continue; + @memset(colors[leaf.offset..@min(shown, leaf.offset + leaf.size)], shade(leaf.path)); + } + for (state[0..shown], 0..) |byte, i| { + try out.append(arena, .{ .text = .{ + .x = 30 + @as(f32, @floatFromInt(i % 16)) * 24, + .y = hex_top + @as(f32, @floatFromInt(i / 16)) * 14, + .scale = 1, + .color = colors[i], + .bytes = try std.fmt.allocPrint(arena, "{X:0>2}", .{byte}), + } }); + } +} + +pub fn drawScope(out: *List, arena: std.mem.Allocator, samples: []const f32, rate: u32, canvas: [2]u32) !void { + const green: abi.Color = .{ .r = 105, .g = 245, .b = 160 }; + const x = @as(f32, @floatFromInt(canvas[0])) - 526; + const top = @as(f32, @floatFromInt(canvas[1])) - 130; + const mid = top + 72; + try out.append(arena, .{ .rect = .{ .dst = .{ .x = x, .y = top, .w = 514, .h = 118 }, .color = .{ .r = 24, .g = 24, .b = 24 } } }); + try out.append(arena, .{ .rect = .{ .dst = .{ .x = x + 1, .y = mid, .w = 512, .h = 1 }, .color = .{ .r = 60, .g = 85, .b = 65 } } }); + const ms = @as(f32, @floatFromInt(samples.len * 1000)) / @as(f32, @floatFromInt(@max(rate, 1))); + try out.append(arena, .{ .text = .{ .x = x + 8, .y = top + 10, .scale = 1, .color = green, .bytes = try std.fmt.allocPrint(arena, "OUTPUT ch1 / {d:.1}ms / overlay sound to hide", .{ms}) } }); + for (samples, 0..) |sample, i| { + const a = std.math.clamp(if (std.math.isFinite(sample)) sample else 0, -1, 1); + const previous = samples[i -| 1]; + const b = std.math.clamp(if (std.math.isFinite(previous)) previous else 0, -1, 1); + const y1 = mid - a * 36; + const y2 = mid - b * 36; + try out.append(arena, .{ .rect = .{ .dst = .{ .x = x + 1 + @as(f32, @floatFromInt(i)), .y = @min(y1, y2), .w = 1, .h = @max(1, @abs(y2 - y1)) }, .color = green } }); + } +} diff --git a/src/host/probe.zig b/src/host/probe.zig new file mode 100644 index 0000000..4a693ec --- /dev/null +++ b/src/host/probe.zig @@ -0,0 +1,64 @@ +//! sketchbook-probe: prints the live state of any running sketch, from its +//! state file alone. The file header carries the layout, so the probe needs +//! no knowledge of the sketch: it maps the same pages read-only. +const std = @import("std"); +const memory = @import("memory.zig"); +const fields = @import("fields.zig"); + +const usage = + \\usage: sketchbook-probe [--watch] [--interval MS] STATE_FILE + \\Prints every field of the live state; --watch prints again on change. + \\ +; + +pub fn main(init: std.process.Init) !void { + var path: ?[]const u8 = null; + var watch = false; + var interval_ms: i64 = 100; + var args = init.minimal.args.iterate(); + _ = args.skip(); + while (args.next()) |arg| { + if (std.mem.eql(u8, arg, "--watch")) { + watch = true; + } else if (std.mem.eql(u8, arg, "--interval")) { + interval_ms = std.fmt.parseInt(i64, args.next() orelse "", 10) catch fatal("--interval needs milliseconds"); + } else if (std.mem.startsWith(u8, arg, "-")) { + std.debug.print("{s}", .{usage}); + return; + } else path = arg; + } + const file = path orelse fatal("no state file given"); + const map = memory.mapReadOnly(file); + if (map.len < memory.header_len) fatal("not a sketchbook state file"); + defer std.posix.munmap(map); + var arena: std.heap.ArenaAllocator = .init(init.gpa); + defer arena.deinit(); + const layout = (try memory.readLayout(arena.allocator(), map)) orelse fatal("state file has no layout yet"); + const header: *const memory.Header = @ptrCast(@alignCast(map.ptr)); + const live = map[memory.header_len..][0..header.size]; + + const shown = try arena.allocator().dupe(u8, live); + show(file, layout, live); + while (watch) { + try std.Io.sleep(init.io, .fromMilliseconds(interval_ms), .awake); + if (std.mem.eql(u8, shown, live)) continue; + @memcpy(shown, live); + show(file, layout, live); + } +} + +fn show(path: []const u8, layout: memory.Layout, live: []const u8) void { + var buf: [4096]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + std.debug.print("{s}: {d} bytes, layout {x:0>16}\n", .{ path, live.len, layout.hash }); + for (layout.fields) |leaf| { + w.end = 0; + fields.format(leaf, live, &w) catch {}; + std.debug.print(" +0x{x:0>4} {s:<28} {s}\n", .{ leaf.offset, leaf.path, w.buffered() }); + } +} + +fn fatal(message: []const u8) noreturn { + std.debug.print("sketchbook-probe: {s}\n{s}", .{ message, usage }); + std.process.exit(2); +} diff --git a/src/host/root.zig b/src/host/root.zig new file mode 100644 index 0000000..637a325 --- /dev/null +++ b/src/host/root.zig @@ -0,0 +1,138 @@ +//! The sketchbook host: runs a sketch linked in, or loaded from a library +//! that it hot-reloads whenever a build replaces it. +//! +//! sketchbook [options] [LIBRARY] +//! --state FILE persistent state (default: <name>.state) +//! --headless offscreen video, silent audio +//! --script FILE play a script instead of reading devices +//! --fresh start from default state: no snapshots or recordings +//! --define NAME=VALUE substitute {NAME} in the script +const std = @import("std"); +const c = @import("c"); +const abi = @import("abi"); +pub const Host = @import("Host.zig"); +pub const memory = @import("memory.zig"); +pub const fields = @import("fields.zig"); +pub const script = @import("script.zig"); +pub const timeline = @import("timeline.zig"); + +/// Entry point for both the generic host (`linked == null`) and apps that +/// link their sketch in. +pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void { + const gpa = init.gpa; + var options: Host.Options = .{}; + var script_path: ?[]const u8 = null; + var defines: std.ArrayList([2][]const u8) = .empty; + defer defines.deinit(gpa); + + var args = init.minimal.args.iterate(); + _ = args.skip(); + while (args.next()) |arg| { + if (std.mem.eql(u8, arg, "--state")) { + options.state = args.next() orelse fatal("--state needs a file"); + } else if (std.mem.eql(u8, arg, "--fresh")) { + options.fresh = true; + } else if (std.mem.eql(u8, arg, "--headless")) { + options.headless = true; + } else if (std.mem.eql(u8, arg, "--script")) { + script_path = args.next() orelse fatal("--script needs a file"); + } else if (std.mem.eql(u8, arg, "--define")) { + 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, "-h") or std.mem.eql(u8, arg, "--help")) { + std.debug.print("{s}", .{usage}); + return; + } else if (std.mem.startsWith(u8, arg, "-")) { + fatal("unknown option (see --help)"); + } else { + options.library = arg; + } + } + if (linked == null and options.library == null) fatal("no sketch library given (see --help)"); + + sdl_heap.install(); + { + var host: Host = undefined; + try host.init(gpa, init.io, init.environ_map, options, linked); + defer host.deinit(); + if (script_path) |path| { + const source = try std.Io.Dir.cwd().readFileAlloc(init.io, path, gpa, .limited(1 << 20)); + defer gpa.free(source); + try script.run(&host, source, defines.items); + } else try host.run(); + } + if (sdl_heap.leaked()) return error.LeakedSdlMemory; +} + +const usage = + \\usage: sketchbook [options] [LIBRARY] + \\ --state FILE persistent state (default: sketch.state) + \\ --headless offscreen video, silent audio, no vsync + \\ --script FILE play a script instead of reading devices + \\ --fresh start from default state: no snapshots or recordings + \\ --define NAME=VALUE substitute {NAME} in the script + \\ +; + +fn fatal(message: []const u8) noreturn { + std.debug.print("sketchbook: {s}\n", .{message}); + std.process.exit(2); +} + +/// SDL's allocations go through a leak-checking allocator of their own, so a +/// session that leaks SDL memory fails loudly at exit. +const sdl_heap = struct { + var debug: std.heap.DebugAllocator(.{ .backing_allocator_zeroes = false }) = .{}; + const alignment: std.mem.Alignment = .of(std.c.max_align_t); + const header = alignment.forward(@sizeOf(usize)); + + fn install() void { + _ = c.SDL_SetMemoryFunctions(malloc, calloc, realloc, free); + } + fn leaked() bool { + return debug.deinit() == .leak; + } + fn block(size: usize) ?[*]u8 { + const total = std.math.add(usize, header, size) catch return null; + const base = debug.allocator().rawAlloc(total, alignment, @returnAddress()) orelse return null; + @as(*usize, @ptrCast(@alignCast(base))).* = total; + return base + header; + } + fn whole(mem: *anyopaque) []u8 { + const base: [*]u8 = @as([*]u8, @ptrCast(mem)) - header; + return base[0..@as(*const usize, @ptrCast(@alignCast(base))).*]; + } + fn malloc(size: usize) callconv(.c) ?*anyopaque { + return block(size); + } + fn calloc(n: usize, size: usize) callconv(.c) ?*anyopaque { + const bytes = std.math.mul(usize, n, size) catch return null; + const mem = block(bytes) orelse return null; + @memset(mem[0..bytes], 0); + return mem; + } + fn realloc(maybe: ?*anyopaque, size: usize) callconv(.c) ?*anyopaque { + const old = whole(maybe orelse return malloc(size)); + const total = std.math.add(usize, header, size) catch return null; + if (debug.allocator().rawRemap(old, alignment, total, @returnAddress())) |base| { + @as(*usize, @ptrCast(@alignCast(base))).* = total; + return base + header; + } + const new = block(size) orelse return null; + @memcpy(new[0..@min(size, old.len - header)], old[header..][0..@min(size, old.len - header)]); + debug.allocator().rawFree(old, alignment, @returnAddress()); + return new; + } + fn free(maybe: ?*anyopaque) callconv(.c) void { + debug.allocator().rawFree(whole(maybe orelse return), alignment, @returnAddress()); + } +}; + +test { + _ = memory; + _ = fields; + _ = timeline; + _ = @import("audio.zig"); + _ = @import("Console.zig"); +} diff --git a/src/host/script.zig b/src/host/script.zig new file mode 100644 index 0000000..4563a47 --- /dev/null +++ b/src/host/script.zig @@ -0,0 +1,139 @@ +//! End-to-end scripts: plain text that plays a sketch like a person would, +//! through the same routing and frames, on a fixed 60 Hz clock. +//! +//! # comment +//! click 710 320 move there, press and release the left button +//! move|down|up X Y one pointer event, then a frame +//! wheel X Y DELTA +//! cancel what losing focus sends +//! key NAME press and release a key (`sketch.Key` names) +//! type TEXT text input, as typed into a focused field +//! console LINE run a console command +//! frames N advance N frames without input +//! expect FIELD VALUE compare a state field (enums by name or number) +//! expect-audio KEY stream KEY has received samples +//! screenshot FILE save the next frame as PNG +//! load LIBRARY swap in another build of the sketch +//! reload load the watched library again +//! await-reload SECONDS run frames until a build replaces the library +//! +//! `{name}` is replaced by `--define name=value` from the command line. +const std = @import("std"); +const abi = @import("abi"); +const Host = @import("Host.zig"); +const fields = @import("fields.zig"); + +pub const frame_ns: u64 = std.time.ns_per_s / 60; + +pub fn run(host: *Host, source: []const u8, defines: []const [2][]const u8) !void { + var arena: std.heap.ArenaAllocator = .init(host.gpa); + defer arena.deinit(); + var now: u64 = std.time.ns_per_s; + var failures: usize = 0; + var lines = std.mem.splitScalar(u8, source, '\n'); + var number: usize = 0; + while (lines.next()) |raw| { + number += 1; + const line = try substitute(arena.allocator(), std.mem.trim(u8, raw, " \t\r"), defines); + if (line.len == 0 or line[0] == '#') continue; + var words = std.mem.tokenizeAny(u8, line, " \t"); + const command = words.next().?; + const rest = std.mem.trim(u8, words.rest(), " \t"); + step(host, arena.allocator(), command, rest, &words, &now) catch |err| { + failures += 1; + std.debug.print("script:{d}: {s}: {t}\n", .{ number, line, err }); + if (err != error.ExpectationFailed) break; + }; + if (host.quit) break; + } + if (failures > 0) return error.ScriptFailed; +} + +fn step(host: *Host, arena: std.mem.Allocator, command: []const u8, rest: []const u8, words: anytype, now: *u64) !void { + const eq = std.mem.eql; + if (eq(u8, command, "click")) { + const x, const y = try point(words); + try host.route(.{ .kind = .mouse_move, .time = now.*, .x = x, .y = y }); + try host.route(.{ .kind = .mouse_down, .time = now.*, .x = x, .y = y, .code = 1 }); + try host.route(.{ .kind = .mouse_up, .time = now.*, .x = x, .y = y, .code = 1 }); + } else if (eq(u8, command, "move") or eq(u8, command, "down") or eq(u8, command, "up")) { + const x, const y = try point(words); + const kind: abi.Event.Kind = if (eq(u8, command, "move")) .mouse_move else if (eq(u8, command, "down")) .mouse_down else .mouse_up; + try host.route(.{ .kind = kind, .time = now.*, .x = x, .y = y, .code = if (kind == .mouse_move) 0 else 1 }); + } else if (eq(u8, command, "wheel")) { + const x, const y = try point(words); + const delta = try std.fmt.parseFloat(f32, words.next() orelse return error.ExpectedDelta); + try host.route(.{ .kind = .wheel, .time = now.*, .x = x, .y = y, .value = @bitCast(delta) }); + } else if (eq(u8, command, "cancel")) { + try host.route(.{ .kind = .cancel, .time = now.* }); + } else if (eq(u8, command, "key")) { + const key = std.meta.stringToEnum(abi.Key, rest) orelse return error.UnknownKey; + try host.route(.{ .kind = .key_down, .time = now.*, .code = @intFromEnum(key) }); + try host.route(.{ .kind = .key_up, .time = now.*, .code = @intFromEnum(key) }); + } else if (eq(u8, command, "type")) { + for (rest) |byte| try host.route(.{ .kind = .text, .time = now.*, .value = byte }); + } else if (eq(u8, command, "console")) { + host.runLine(rest, now.*); + } else if (eq(u8, command, "frames")) { + const count = try std.fmt.parseInt(usize, rest, 10); + for (0..count) |_| try advance(host, now); + return; + } else if (eq(u8, command, "expect")) { + const path = words.next() orelse return error.ExpectedField; + const want = std.mem.trim(u8, words.rest(), " \t"); + const leaf = host.state.layout.find(path) orelse return error.UnknownField; + if (!fields.matches(leaf, host.live(), want)) { + var buf: [128]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + fields.format(leaf, host.live(), &w) catch {}; + std.debug.print(" {s}: expected {s}, found {s}\n", .{ path, want, w.buffered() }); + return error.ExpectationFailed; + } + return; + } else if (eq(u8, command, "expect-audio")) { + const key = try std.fmt.parseInt(u32, rest, 10); + if (host.input.stream(key).pushed == 0) return error.ExpectationFailed; + return; + } else if (eq(u8, command, "screenshot")) { + if (std.fs.path.dirname(rest)) |dir| try std.Io.Dir.cwd().createDirPath(host.io, dir); + host.screenshot = try arena.dupeZ(u8, rest); + } else if (eq(u8, command, "load")) { + try host.load(rest); + } else if (eq(u8, command, "reload")) { + try host.reload(); + } else if (eq(u8, command, "await-reload")) { + const seconds = try std.fmt.parseInt(u64, rest, 10); + const start = host.reloads; + const deadline = std.Io.Timestamp.now(host.io, .awake).nanoseconds + @as(i96, seconds) * std.time.ns_per_s; + while (host.reloads == start) { + if (std.Io.Timestamp.now(host.io, .awake).nanoseconds > deadline) return error.NoReload; + try advance(host, now); + try std.Io.sleep(host.io, .fromMilliseconds(10), .awake); + } + return; + } else if (eq(u8, command, "quit")) { + host.quit = true; + return; + } else return error.UnknownScriptCommand; + try advance(host, now); +} + +fn advance(host: *Host, now: *u64) !void { + try host.frame(now.*); + now.* += frame_ns; +} + +fn point(words: anytype) !struct { f32, f32 } { + const x = try std.fmt.parseFloat(f32, words.next() orelse return error.ExpectedPoint); + const y = try std.fmt.parseFloat(f32, words.next() orelse return error.ExpectedPoint); + return .{ x, y }; +} + +fn substitute(arena: std.mem.Allocator, line: []const u8, defines: []const [2][]const u8) ![]const u8 { + var out = line; + for (defines) |pair| { + const pattern = try std.fmt.allocPrint(arena, "{{{s}}}", .{pair[0]}); + out = try std.mem.replaceOwned(u8, arena, out, pattern, pair[1]); + } + return out; +} diff --git a/src/host/timeline.zig b/src/host/timeline.zig new file mode 100644 index 0000000..cd65478 --- /dev/null +++ b/src/host/timeline.zig @@ -0,0 +1,208 @@ +//! Snapshots, input recordings and replay: generic over state bytes and +//! `abi.Event`s, so any sketch gets time travel for free. +//! +//! Playback is host state, not sketch state: wall clocks, modes and cursors +//! must not contaminate byte comparisons between two runs of a sketch. +const std = @import("std"); +const posix = std.posix; +const abi = @import("abi"); +const memory = @import("memory.zig"); + +pub const recording_len = 4 * 1024 * 1024; +pub const recording_count = 16; +pub const recordings_len = recording_len * recording_count; +const recording_magic = 0x52454305; +pub const capacity = (recording_len - 32) / @sizeOf(abi.Event); + +pub const Recording = extern struct { + duration: u64, + count: u32, + snapshot: u32, + magic: u32, + reserved: [3]u32, + events: [capacity]abi.Event, + slack: [recording_len - 32 - capacity * @sizeOf(abi.Event)]u8, + + pub fn slice(r: *const Recording) []const abi.Event { + return r.events[0..r.count]; + } +}; + +comptime { + std.debug.assert(@sizeOf(Recording) == recording_len); +} + +/// Snapshot slots of a state file, and the recordings that start from them. +pub const Bank = struct { + state: *memory.StateFile, + inputs: []align(memory.page) u8, + + pub fn slot(self: Bank, index: usize) []u8 { + return self.state.slot(index); + } + pub fn recording(self: Bank, index: usize) *Recording { + std.debug.assert(index < recording_count); + return @ptrCast(@alignCast(self.inputs[index * recording_len ..].ptr)); + } + pub fn hasSnapshot(self: Bank, index: usize) bool { + return index > 0 and index < memory.slot_count and self.state.used(index); + } + pub fn save(self: Bank, index: usize) void { + std.debug.assert(index > 0 and index < memory.slot_count); + for (0..recording_count) |i| { + const r = self.recording(i); + if (r.snapshot == index) r.magic = 0; + } + @memcpy(self.slot(index), self.slot(0)); + self.state.markUsed(index, true); + } + pub fn restore(self: Bank, index: usize) !void { + if (!self.hasSnapshot(index)) return error.EmptySnapshot; + @memcpy(self.slot(0), self.slot(index)); + } + pub fn get(self: Bank, index: usize) !*Recording { + const r = self.recording(index); + if (r.magic != recording_magic or r.count > capacity or !self.hasSnapshot(r.snapshot)) return error.EmptyRecording; + return r; + } + pub const Diff = struct { count: usize = 0, first: ?usize = null, last: ?usize = null }; + pub fn compare(self: Bank, a: usize, b: usize) Diff { + var diff: Diff = .{}; + for (self.slot(a), self.slot(b), 0..) |x, y, i| { + if (x == y) continue; + diff.count += 1; + if (diff.first == null) diff.first = i; + diff.last = i; + } + return diff; + } +}; + +pub const Timeline = struct { + bank: Bank, + mode: abi.Mode = .live, + selected: usize = 0, + cursor: usize = 0, + position: u64 = 0, + clock: u64 = 0, + + pub fn startRecording(self: *Timeline, index: usize, snapshot: usize, now: u64) !void { + // An unused snapshot captures the current state; an existing one is + // restored, so several recordings can branch from exactly those bytes. + if (!self.bank.hasSnapshot(snapshot)) self.bank.save(snapshot); + try self.bank.restore(snapshot); + const r = self.bank.recording(index); + @memset(std.mem.asBytes(r)[0..32], 0); + r.magic = recording_magic; + r.snapshot = @intCast(snapshot); + self.selected = index; + self.cursor = 0; + self.position = 0; + self.clock = now; + self.mode = .recording; + } + pub fn capture(self: *Timeline, event: abi.Event) !void { + if (self.mode != .recording) return; + const r = self.bank.recording(self.selected); + if (r.count == capacity) { + self.mode = .live; + return error.RecordingFull; + } + var e = event; + // Queued events can predate the start command. Keep insertion order and + // nondecreasing times, including several events at the same timestamp. + e.time = @max(e.time -| self.clock, r.duration); + r.events[r.count] = e; + r.count += 1; + r.duration = e.time; + self.position = e.time; + self.cursor = r.count; + } + pub fn stop(self: *Timeline, now: u64) void { + if (self.mode == .recording) { + const r = self.bank.recording(self.selected); + r.duration = @max(r.duration, now -| self.clock); + self.position = r.duration; + } + self.mode = .live; + } + pub fn play(self: *Timeline, index: usize, now: u64) !void { + const r = try self.bank.get(index); + try self.bank.restore(r.snapshot); + self.selected = index; + self.cursor = 0; + self.position = 0; + self.clock = now; + self.mode = .playing; + } + pub fn pause(self: *Timeline, now: u64) void { + if (self.mode == .playing) { + self.mode = .paused; + } else if (self.mode == .paused) { + self.clock = now; + self.mode = .playing; + } + } + /// The recorded events due by `now`. Feed them to the same `update` that + /// live input goes through. + pub fn tick(self: *Timeline, now: u64) []const abi.Event { + if (self.mode != .playing) return &.{}; + const r = self.bank.recording(self.selected); + self.position = @min(r.duration, self.position +| (now -| self.clock)); + self.clock = now; + const start = self.cursor; + while (self.cursor < r.count and r.events[self.cursor].time <= self.position) self.cursor += 1; + if (self.position == r.duration) self.mode = .paused; + return r.events[start..self.cursor]; + } + /// Restores the snapshot and returns the first `count` events to replay, + /// so seeking backwards works too. + pub fn seekCount(self: *Timeline, count: usize) ![]const abi.Event { + const r = try self.bank.get(self.selected); + try self.bank.restore(r.snapshot); + self.cursor = @min(count, r.count); + self.position = if (self.cursor == 0) 0 else r.events[self.cursor - 1].time; + self.mode = .paused; + return r.events[0..self.cursor]; + } + pub fn seekTime(self: *Timeline, time: u64) ![]const abi.Event { + const r = try self.bank.get(self.selected); + const position = @min(time, r.duration); + var count: usize = 0; + while (count < r.count and r.events[count].time <= position) count += 1; + const events = try self.seekCount(count); + self.position = position; + return events; + } + /// Moves by `steps` input events, passing over frame ticks. + pub fn step(self: *Timeline, steps: i64) ![]const abi.Event { + const r = try self.bank.get(self.selected); + var cursor = self.cursor; + var remaining = @abs(steps); + while (remaining > 0) : (remaining -= 1) { + if (steps > 0) { + while (cursor < r.count and r.events[cursor].kind == .tick) cursor += 1; + if (cursor == r.count) break; + cursor += 1; + // Include the frame's tick so time-driven sketches advance too. + while (cursor < r.count and r.events[cursor].kind == .tick) cursor += 1; + } else { + while (cursor > 0 and r.events[cursor - 1].kind == .tick) cursor -= 1; + if (cursor == 0) break; + cursor -= 1; + } + } + return self.seekCount(cursor); + } +}; + +/// Maps the recordings file next to a state file, creating it when missing. +pub fn mapRecordings(path: []const u8) ![]align(memory.page) u8 { + const fd = try posix.openat(posix.AT.FDCWD, path, .{ .ACCMODE = .RDWR, .CREAT = true }, 0o600); + defer _ = posix.system.close(fd); + if (try memory.fileSize(fd) != recordings_len) switch (posix.errno(posix.system.ftruncate(fd, recordings_len))) { + .SUCCESS => {}, + else => |err| return posix.unexpectedErrno(err), + }; + return memory.mapFile(fd, recordings_len, .{ .READ = true, .WRITE = true }); +} |
