diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-16 18:04:21 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-16 18:04:21 -0300 |
| commit | e77b01d4b5504cea08a3f88cf8502897d868a1d3 (patch) | |
| tree | c8e643d234dd26d920cbc563bfa7f740febf1fc7 /src/host/Host.zig | |
| parent | d3074636fff0fbcd5fd9b71c0c3b1c1f5c0c1285 (diff) | |
| download | sketchbook-e77b01d4b5504cea08a3f88cf8502897d868a1d3.tar.gz sketchbook-e77b01d4b5504cea08a3f88cf8502897d868a1d3.zip | |
Add glTF scene rendering, resource setup and 9P controls
Diffstat (limited to 'src/host/Host.zig')
| -rw-r--r-- | src/host/Host.zig | 177 |
1 files changed, 169 insertions, 8 deletions
diff --git a/src/host/Host.zig b/src/host/Host.zig index 008d143..02a88c7 100644 --- a/src/host/Host.zig +++ b/src/host/Host.zig @@ -12,15 +12,18 @@ const Timeline = playback.Timeline; const mapRecordings = playback.mapRecordings; const gfx = @import("gfx.zig"); const sound = @import("audio.zig"); -const Gpu = @import("gpu.zig"); +const Gpu = @import("gpu"); const overlay = @import("overlay.zig"); const Console = @import("Console.zig"); +const Control = @import("control.zig").Control; 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, + /// Local 9P control socket, opt-in. + ninep: ?[]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. @@ -59,6 +62,8 @@ painter: gfx.Painter, audio: sound.Audio, state: memory.StateFile, session: memory.Session, +/// A failed resource setup disables app callbacks while keeping host controls alive. +session_ready: bool = false, store: memory.StoreFile, /// Images and buffers the sketch made (`newImage`, `decodeImage`, /// `newBuffer`): Session holds their handles, so they go when it resets. @@ -98,6 +103,7 @@ screenshot: ?[:0]const u8 = null, /// Frames exported so far (`Options.export_to`). exported: u64 = 0, dialog: Dialog = .{}, +control: ?*Control = null, pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, options: Options, linked: ?abi.Sketch) !void { if (options.headless) { @@ -200,12 +206,13 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std } pub fn deinit(self: *Host) void { + if (self.control) |control| control.deinit(); self.dialog.deinit(); if (self.watch) |w| w.deinit(); self.audio.deinit(); - if (self.passes) |*g| g.deinit(&self.images); self.painter.deinit(); self.images.deinit(); + if (self.passes) |*g| g.deinit(); if (self.pointer_cursor) |cursor| c.SDL_DestroyCursor(cursor); if (self.offscreen) |texture| c.SDL_DestroyTexture(texture); c.SDL_DestroyRenderer(self.renderer); @@ -233,7 +240,9 @@ pub fn deinit(self: *Host) void { /// The interactive loop. An export runs it on a clock of its own, frame k /// at k/fps seconds (from 1 s, as scripts do), whatever the wall clock says. pub fn run(self: *Host) !void { + if (self.options.ninep) |path| self.control = try Control.init(self.gpa, path); while (!self.quit) { + if (self.control) |control| control.poll(self); try self.poll(); try self.frame(if (self.options.export_to == null) c.SDL_GetTicksNS() else std.time.ns_per_s + self.exported * std.time.ns_per_s / self.options.fps); } @@ -278,6 +287,7 @@ pub fn frame(self: *Host, now: u64) !void { /// Feeds whole frames to the sketch's deterministic `update`, one call per /// frame (events up to and including a tick), live or replayed alike. pub fn update(self: *Host, events: []const abi.Event) void { + if (!self.session_ready) return; var frames = playback.frames(events); while (frames.next()) |one| { // Input follows the events actually fed, frame by frame. @@ -353,7 +363,7 @@ fn draw(self: *Host, now: u64) !void { self.input.downloads = if (self.passes) |*g| try g.collect(arena) else &.{}; self.input.frame += 1; const ctx = self.context(); - self.sketch.draw(&ctx, self.live().ptr); + if (self.session_ready) self.sketch.draw(&ctx, self.live().ptr); _ = c.SDL_SetRenderTarget(self.renderer, self.offscreen); _ = c.SDL_SetRenderClipRect(self.renderer, null); @@ -375,7 +385,7 @@ fn draw(self: *Host, now: u64) !void { .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() }), + .gpu => |pass| if (self.passes) |*g| self.runGpu(g, pass) catch |err| self.print("gpu pass: {t} ({s})", .{ err, c.SDL_GetError() }), .upload => |u| if (self.passes) |*g| g.write(u.buffer, u.offset, u.bytes) catch |err| self.print("gpu upload: {t} ({s})", .{ err, c.SDL_GetError() }), .compute => |d| if (self.passes) |*g| g.compute(d) catch |err| self.print("gpu compute: {t} ({s})", .{ err, c.SDL_GetError() }), .microphone => self.audio.listen(), @@ -400,13 +410,14 @@ fn draw(self: *Host, now: u64) !void { self.painter.end(); self.applyCursor(); - if (self.screenshot != null or self.options.export_to != null) { + if (self.screenshot != null or self.options.export_to != null or (self.control != null and self.control.?.capture_pending)) { const surface = c.SDL_RenderReadPixels(self.renderer, null) orelse return sdlError("SDL_RenderReadPixels"); defer c.SDL_DestroySurface(surface); if (self.screenshot) |path| { self.screenshot = null; if (!c.SDL_SavePNG(surface, path.ptr)) return sdlError("SDL_SavePNG"); } + if (self.control) |control| if (control.capture_pending) control.capture(surface); if (self.options.export_to) |to| try self.exportFrame(surface, to); } if (!self.options.headless) if (self.offscreen) |canvas| { @@ -573,6 +584,10 @@ fn movesState(line: []const u8) bool { /// Offers a line to the sketch. pub fn forward(self: *Host, _: *Console, line: []const u8, now: u64) abi.Outcome { + if (!self.session_ready) { + self.print("session setup failed; restart after fixing the resource error", .{}); + return .failed; + } self.input.now = now; const ctx = self.context(); return self.sketch.command(&ctx, self.live().ptr, &line); @@ -626,6 +641,11 @@ fn adopt(self: *Host, sketch: abi.Sketch) !void { .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) { + const ctx = self.context(); + self.session_ready = self.sketch.setup(&ctx); + if (!self.session_ready) self.console.visible = true; + } if (session_reset and self.reloads > 0) self.print("session layout changed: session reset", .{}); switch (stored) { .unchanged, .created => {}, @@ -636,7 +656,8 @@ fn adopt(self: *Host, sketch: abi.Sketch) !void { /// Frees what the old Session made: its handles are gone with it. fn releaseMade(self: *Host) void { for (self.made.images.items) |image| { - if (self.passes) |*g| g.forget(&self.images, image); + self.images.unwrap(image); + if (self.passes) |*g| g.forget(image); self.images.free(image); } if (self.passes) |*g| for (self.made.buffers.items) |buffer| g.freeBuffer(buffer); @@ -800,6 +821,7 @@ const api: abi.Host.VTable = .{ .gpu = apiGpu, .newBuffer = apiNewBuffer, .freeBuffer = apiFreeBuffer, + .writeBuffer = apiWriteBuffer, .imageSize = apiImageSize, .textSize = apiTextSize, .loadSound = apiLoadSound, @@ -830,7 +852,8 @@ fn apiNewImage(ctx: *anyopaque, w: u32, h: u32) abi.Image { fn apiFreeImage(ctx: *anyopaque, image: abi.Image) void { const self = hostOf(ctx); forget(&self.made.images, image); - if (self.passes) |*g| g.forget(&self.images, image); + self.images.unwrap(image); + if (self.passes) |*g| g.forget(image); self.images.free(image); } fn apiGpu(ctx: *anyopaque) bool { @@ -838,12 +861,17 @@ fn apiGpu(ctx: *anyopaque) bool { } fn apiNewBuffer(ctx: *anyopaque, size: u32) abi.Buffer { const self = hostOf(ctx); - const g = &(self.passes orelse return .none); + const g = if (self.passes) |*passes| passes else return .none; return self.remember(.buffers, g.newBuffer(size) catch |err| blk: { self.print("gpu buffer: {t} ({s})", .{ err, c.SDL_GetError() }); break :blk .none; }); } +fn apiWriteBuffer(ctx: *anyopaque, buffer: abi.Buffer, offset: u32, bytes: []const u8) !void { + const self = hostOf(ctx); + const gpu = if (self.passes) |*passes| passes else return error.GpuUnavailable; + try gpu.write(buffer, offset, bytes); +} fn apiFreeBuffer(ctx: *anyopaque, buffer: abi.Buffer) void { const self = hostOf(ctx); forget(&self.made.buffers, buffer); @@ -879,3 +907,136 @@ fn apiClock(_: *anyopaque) u64 { fn apiEnv(ctx: *anyopaque, name: []const u8) ?[]const u8 { return hostOf(ctx).environ.get(name); } + +fn runGpu(self: *Host, g: *Gpu, pass: abi.gpu.Pass) !void { + const before = g.output(pass.image); + const changed = if (before) |t| t.width != pass.width or t.height != pass.height else true; + if (changed) self.images.unwrap(pass.image); + try g.run(pass); + if (g.output(pass.image)) |t| try self.images.wrap(pass.image, t.texture, t.width, t.height); +} + +test "session setup runs for restored state and layout reset, not same-layout reload or state reset" { + const Fixture = struct { + const State = extern struct { value: u32 = 1 }; + const Session1 = extern struct { ready: u32 = 0 }; + const Session2 = extern struct { ready: u32 = 0, extra: u32 = 0 }; + const Store = struct {}; + var setup_calls: usize = 0; + var init_calls: usize = 0; + var fail_setup = false; + const description: abi.Info = .{ .abi = abi.hash, .name = "setup-test", .width = 1, .height = 1, .state = abi.layout.of(State, .state), .session = abi.layout.of(Session1, .session), .store = abi.layout.of(Store, .store) }; + const changed: abi.Info = blk: { + var value = description; + value.session = abi.layout.of(Session2, .session); + break :blk value; + }; + fn info() callconv(.c) *const abi.Info { + return &description; + } + fn info2() callconv(.c) *const abi.Info { + return &changed; + } + fn defaults(kind: abi.Memory, ptr: [*]u8) callconv(.c) void { + switch (kind) { + .state => @as(*State, @ptrCast(@alignCast(ptr))).* = .{}, + .session => @as(*Session1, @ptrCast(@alignCast(ptr))).* = .{}, + .store => {}, + } + } + fn defaults2(kind: abi.Memory, ptr: [*]u8) callconv(.c) void { + if (kind == .session) @as(*Session2, @ptrCast(@alignCast(ptr))).* = .{} else defaults(kind, ptr); + } + fn init(_: *const abi.Context, _: [*]u8) callconv(.c) void { + init_calls += 1; + } + fn setup(ctx: *const abi.Context) callconv(.c) bool { + setup_calls += 1; + @as(*u32, @ptrCast(@alignCast(ctx.session_root))).* += 1; + return !fail_setup; + } + fn update(_: *const abi.Context, _: [*]u8) callconv(.c) void {} + fn draw(_: *const abi.Context, _: [*]const u8) callconv(.c) void {} + fn command(_: *const abi.Context, _: [*]u8, _: *const []const u8) callconv(.c) abi.Outcome { + return .unknown; + } + const sketch: abi.Sketch = .{ .info = info, .defaults = defaults, .init = @This().init, .setup = setup, .update = @This().update, .draw = @This().draw, .command = command }; + }; + Fixture.setup_calls = 0; + Fixture.init_calls = 0; + Fixture.fail_setup = false; + const a = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var state_buf: [std.fs.max_path_bytes]u8 = undefined; + var store_buf: [std.fs.max_path_bytes]u8 = undefined; + const state_path = try std.mem.print(&state_buf, ".zig-cache/tmp/{s}/setup.state", .{&tmp.sub_path}); + const store_path = try std.mem.print(&store_buf, ".zig-cache/tmp/{s}/setup.store", .{&tmp.sub_path}); + { + var state = try memory.StateFile.open(a, state_path); + defer state.close(); + _ = try state.adopt(a, Fixture.description.state, Fixture.defaults); + @as(*Fixture.State, @ptrCast(state.slot(0).ptr)).value = 77; + state.markUsed(0, true); + } + // Exercise adoption with real persisted memory, without opening SDL devices. + var host: Host = undefined; + host.gpa = a; + host.state = try memory.StateFile.open(a, state_path); + defer host.state.close(); + host.store = try memory.StoreFile.open(a, store_path, false); + defer host.store.close(); + host.session = .init(a); + defer host.session.deinit(a); + host.info_arena = .init(a); + defer host.info_arena.deinit(); + host.frame_arena = .init(a); + defer host.frame_arena.deinit(); + host.options = .{ .headless = true }; + host.console = .{}; + host.reloads = 0; + host.made = .{}; + host.passes = null; + host.input = .{}; + host.commands = .empty; + try host.adopt(Fixture.sketch); + try std.testing.expectEqual(@as(u32, 77), @as(*Fixture.State, @ptrCast(@alignCast(host.live().ptr))).value); + try std.testing.expectEqual(@as(usize, 0), Fixture.init_calls); + try std.testing.expectEqual(@as(usize, 1), Fixture.setup_calls); + const session_ptr = host.session.bytes.ptr; + try host.adopt(Fixture.sketch); + try std.testing.expectEqual(session_ptr, host.session.bytes.ptr); + try std.testing.expectEqual(@as(usize, 1), Fixture.setup_calls); + host.resetState(); + try std.testing.expectEqual(@as(usize, 1), Fixture.init_calls); + try std.testing.expectEqual(@as(usize, 1), Fixture.setup_calls); + var changed = Fixture.sketch; + changed.info = Fixture.info2; + changed.defaults = Fixture.defaults2; + try host.adopt(changed); + try std.testing.expectEqual(@as(usize, 2), Fixture.setup_calls); + try std.testing.expectEqual(@as(u32, 1), @as(*Fixture.Session2, @ptrCast(host.session.bytes.ptr)).ready); + try std.testing.expect(host.session_ready); + Fixture.fail_setup = true; + defer Fixture.fail_setup = false; + try host.adopt(Fixture.sketch); + try std.testing.expect(!host.session_ready); + try std.testing.expect(host.console.visible); + try std.testing.expectEqual(abi.Outcome.failed, host.forward(&host.console, "anything", 0)); + try host.adopt(Fixture.sketch); + try std.testing.expect(!host.session_ready); // A compatible reload cannot bless partial resources. + try std.testing.expectEqual(@as(usize, 3), Fixture.setup_calls); +} + +test "setup writeBuffer propagates unavailable, unknown and out-of-bounds upload errors" { + const a = std.testing.allocator; + var host: Host = undefined; + host.passes = null; + const client: abi.Host = .{ .ctx = &host, .vtable = &api }; + try std.testing.expectError(error.GpuUnavailable, client.writeBuffer(.none, 0, "data")); + host.passes = .{ .gpa = a, .device = undefined, .stencil_format = undefined }; + defer host.passes.?.buffers.deinit(a); + try std.testing.expectError(error.UnknownBuffer, client.writeBuffer(.none, 0, "data")); + try host.passes.?.buffers.append(a, .{ .buffer = undefined, .size = 4 }); + try std.testing.expectError(error.UploadOutOfBounds, client.writeBuffer(@fromBackingInt(@intCast(1)), 2, "data")); +} |
