summaryrefslogtreecommitdiff
path: root/src/sketch/root.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/sketch/root.zig')
-rw-r--r--src/sketch/root.zig199
1 files changed, 147 insertions, 52 deletions
diff --git a/src/sketch/root.zig b/src/sketch/root.zig
index 0567839..94ce617 100644
--- a/src/sketch/root.zig
+++ b/src/sketch/root.zig
@@ -5,17 +5,21 @@
//! pub const name = "my sketch";
//! pub const width = 960;
//! pub const height = 600;
-//! pub const State = struct { ... }; // persisted and snapshotted: no pointers
-//! pub const Session = struct { ... }; // survives reloads, never saved
+//! pub const State = struct { ... }; // saved, snapshotted, replayed: no pointers
+//! pub const Session = struct { ... }; // this process: survives reloads
+//! pub const Store = struct { ... }; // on disk: survives restarts too
//! pub const commands = .{"hello"}; // console completions
//! pub fn init(state: *State, host: sk.Host) void
//! pub fn update(state: *State, in: *const sk.Input) void
-//! pub fn draw(state: *const State, session: *Session, f: *sk.Frame) void
-//! pub fn command(state: *State, session: *Session, c: *sk.Console, line: []const u8) !bool
+//! pub fn draw(state: *const State, session: *Session, store: *Store, f: *sk.Frame) void
+//! pub fn command(state: *State, store: *Store, c: *sk.Console, line: []const u8) !bool
//!
-//! `update` must be deterministic: the host replays recorded input through it.
-//! `draw` presents state as pictures and sound, and may only change `Session`.
-//! Geometry and colors are duck-typed: see `shape`.
+//! Functions take the parameters they name, by type, in any order: `draw`
+//! may ask for `*Session`, `*Store`, both or neither. `update` must be
+//! deterministic, so it gets `State` and `Input` only: the host replays
+//! recorded input through it. `draw` presents state as pictures and sound,
+//! and changes only Session and Store. Geometry and colors are duck-typed:
+//! see `shape`.
const std = @import("std");
pub const abi = @import("abi");
pub const shape = @import("shape.zig");
@@ -23,6 +27,9 @@ pub const Key = abi.Key;
pub const Camera = @import("camera.zig").Camera;
pub const tween = @import("tween.zig");
pub const web = @import("web.zig");
+const request = @import("request.zig");
+pub const Request = request.Request;
+pub const Handled = request.Handled;
pub const Rect = abi.Rect;
pub const Color = abi.Color;
@@ -32,25 +39,36 @@ pub const Mode = abi.Mode;
pub const Host = abi.Host;
pub const Image = abi.Image;
pub const Audio = abi.Audio;
+pub const Buffer = abi.Buffer;
pub const Cursor = abi.Cursor;
pub const Voice = abi.Voice;
-/// What `draw` receives: input, host services, allocators and the command list.
+/// What `draw` receives: input, host services, memory by lifetime and the
+/// command list. Commands may be built from anything: the methods copy what
+/// they keep (text, GPU descriptions) into `scratch`, except bulk data
+/// (vertices, samples, pixels, uploads), which must outlive the frame.
pub const Frame = struct {
ctx: *const abi.Context,
in: *const Input,
host: Host,
- /// Frame lifetime.
- arena: std.mem.Allocator,
- /// Session lifetime; survives reloads.
- gpa: std.mem.Allocator,
+ /// Released once the frame is drawn.
+ scratch: std.mem.Allocator,
+ /// For Session: this process.
+ session: std.mem.Allocator,
+ /// For Store: on disk, across restarts.
+ store: std.mem.Allocator,
pub fn init(ctx: *const abi.Context) Frame {
- return .{ .ctx = ctx, .in = ctx.input, .host = ctx.host, .arena = ctx.arena, .gpa = ctx.gpa };
+ return .{ .ctx = ctx, .in = ctx.input, .host = ctx.host, .scratch = ctx.scratch, .session = ctx.session, .store = ctx.store };
}
pub fn emit(f: *Frame, command: abi.Command) void {
- f.ctx.commands.append(f.arena, command) catch f.host.log("frame arena full: command dropped");
+ f.ctx.commands.append(f.scratch, command) catch f.host.log("out of scratch memory: command dropped");
+ }
+
+ /// A scratch copy of `items`.
+ pub fn keep(f: *Frame, comptime T: type, items: []const T) []const T {
+ return f.scratch.dupe(T, items) catch &.{};
}
pub fn clear(f: *Frame, color: anytype) void {
@@ -69,17 +87,15 @@ pub const Frame = struct {
.tint = if (@hasField(O, "tint")) shape.color(options.tint) else .white,
} });
}
- /// `bytes` must live until the frame is consumed: literals, `arena` and
- /// session memory all do.
pub fn text(f: *Frame, x: f32, y: f32, scale: f32, bytes: []const u8, color: anytype) void {
- f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = shape.color(color), .bytes = bytes } });
+ f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = shape.color(color), .bytes = f.keep(u8, bytes) } });
}
pub fn print(f: *Frame, x: f32, y: f32, scale: f32, color: anytype, comptime fmt: []const u8, args: anytype) void {
- f.text(x, y, scale, f.format(fmt, args), color);
+ f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = shape.color(color), .bytes = f.format(fmt, args) } });
}
- /// Formats into the frame arena.
+ /// Formats into scratch memory.
pub fn format(f: *Frame, comptime fmt: []const u8, args: anytype) []const u8 {
- return std.fmt.allocPrint(f.arena, fmt, args) catch "?";
+ return f.scratch.print(fmt, args) catch "?";
}
/// A rect, or `null` to stop clipping.
pub fn clip(f: *Frame, r: anytype) void {
@@ -101,18 +117,67 @@ pub const Frame = struct {
f.emit(.{ .pixels = .{ .image = img, .w = w, .h = h, .rgba = rgba, .premultiplied = options.premultiplied } });
}
/// Runs GPU work described as data (see `abi.gpu`) into `pass.image`.
+ /// Vertices must outlive the frame; the rest is copied.
pub fn gpu(f: *Frame, pass: abi.gpu.Pass) void {
- f.emit(.{ .gpu = pass });
+ var kept = pass;
+ kept.label = f.keep(u8, pass.label);
+ kept.pipelines = f.keep(abi.gpu.Pipeline, pass.pipelines);
+ const draws = f.scratch.dupe(abi.gpu.Draw, pass.draws) catch return;
+ for (draws) |*d| {
+ d.vertex_uniforms = f.keep(u8, d.vertex_uniforms);
+ d.fragment_uniforms = f.keep(u8, d.fragment_uniforms);
+ d.vertex_storage = f.keep(abi.Buffer, d.vertex_storage);
+ d.fragment_storage = f.keep(abi.Buffer, d.fragment_storage);
+ }
+ kept.draws = draws;
+ f.emit(.{ .gpu = kept });
+ }
+ /// `bytes` into a buffer made by `Host.newBuffer`.
+ pub fn upload(f: *Frame, buffer: abi.Buffer, offset: u32, bytes: []const u8) void {
+ f.emit(.{ .upload = .{ .buffer = buffer, .offset = offset, .bytes = bytes } });
+ }
+ /// Runs a compute shader; later commands see what it wrote.
+ pub fn compute(f: *Frame, dispatch: abi.gpu.Dispatch) void {
+ var kept = dispatch;
+ kept.label = f.keep(u8, dispatch.label);
+ kept.readonly = f.keep(abi.Buffer, dispatch.readonly);
+ kept.readwrite = f.keep(abi.Buffer, dispatch.readwrite);
+ kept.uniforms = f.keep(u8, dispatch.uniforms);
+ f.emit(.{ .compute = kept });
+ }
+ /// Keeps the microphone open this frame: next frame's `in.microphone`
+ /// holds what it heard.
+ pub fn microphone(f: *Frame) void {
+ f.emit(.microphone);
+ }
+ /// Reads `size` bytes of a GPU buffer back: they arrive in a later
+ /// frame's `in.downloads` under `key`. Results lag a frame or two, so
+ /// it suits measurements (a detected pitch, a level), not every pixel.
+ pub fn download(f: *Frame, buffer: abi.Buffer, options: struct { offset: u32 = 0, size: u32, key: u32 = 0 }) void {
+ f.emit(.{ .download = .{ .buffer = buffer, .offset = options.offset, .size = options.size, .key = options.key } });
+ }
+ /// Asks the user for a file; the answer comes back as the console line
+ /// `<command> <path>`. Emit it once per request, not every frame.
+ pub fn openFile(f: *Frame, command: []const u8, options: struct { pattern: []const u8 = "" }) void {
+ f.emit(.{ .open_file = .{ .command = f.keep(u8, command), .pattern = f.keep(u8, options.pattern) } });
+ }
+ /// Runs `line` through the console (and so the sketch's `command`)
+ /// after this frame, before the next update.
+ pub fn run(f: *Frame, line: []const u8) void {
+ f.emit(.{ .run = f.keep(u8, line) });
}
pub fn quit(f: *Frame) void {
f.emit(.quit);
}
};
-/// What `command` receives: somewhere to answer, and the current input.
+/// What `command` receives: somewhere to answer, the current input, and the
+/// allocators for Session and Store.
pub const Console = struct {
host: Host,
in: *const Input,
+ session: std.mem.Allocator,
+ store: std.mem.Allocator,
pub fn log(c: *Console, message: []const u8) void {
c.host.log(message);
@@ -144,25 +209,64 @@ pub fn Glue(comptime App: type) type {
return struct {
pub const State = if (@hasDecl(App, "State")) App.State else struct {};
pub const Session = if (@hasDecl(App, "Session")) App.Session else struct {};
+ pub const Store = if (@hasDecl(App, "Store")) App.Store else struct {};
pub const description: abi.Info = .{
.abi = abi.hash,
.name = if (@hasDecl(App, "name")) App.name else "sketch",
.width = if (@hasDecl(App, "width")) App.width else 960,
.height = if (@hasDecl(App, "height")) App.height else 600,
- .state = abi.layout.of(State, .forbidden),
- .session = abi.layout.of(Session, .host_only),
+ .state = abi.layout.of(State, .state),
+ .session = abi.layout.of(Session, .session),
+ .store = abi.layout.of(Store, .store),
.commands = if (@hasDecl(App, "commands")) &App.commands else &.{},
};
- fn state(ptr: [*]u8) *State {
- return @ptrCast(@alignCast(ptr));
- }
- fn session(ptr: [*]u8) *Session {
- return @ptrCast(@alignCast(ptr));
- }
- fn arity(comptime func: anytype) usize {
- return @typeInfo(@TypeOf(func)).@"fn".params.len;
+ /// What a call can offer, by type.
+ const Offer = struct {
+ ctx: *const abi.Context,
+ state: [*]u8,
+ frame: ?*Frame = null,
+ console: ?*Console = null,
+ line: []const u8 = "",
+ };
+
+ /// Calls `func` with the arguments its parameter types ask for.
+ fn call(comptime func: anytype, comptime name: []const u8, offer: Offer) @typeInfo(@TypeOf(func)).@"fn".return_type.? {
+ const F = @TypeOf(func);
+ var args: std.meta.ArgsTuple(F) = undefined;
+ inline for (@typeInfo(F).@"fn".param_types, 0..) |P, i| {
+ const T = P orelse @compileError(name ++ ": generic parameters are not supported");
+ const is = struct {
+ fn named(comptime n: []const u8) bool {
+ return std.mem.eql(u8, name, n);
+ }
+ };
+ if (comptime is.named("update") and (T == *Session or T == *Store))
+ @compileError("update must be deterministic: it gets State and Input only, so a replay reproduces it");
+ if (comptime is.named("draw") and T == *State) @compileError("draw only reads State: take *const State");
+ if (comptime T == *Frame and !is.named("draw")) @compileError(name ++ " gets no Frame: only draw does");
+ if (comptime T == *Console and !is.named("command")) @compileError(name ++ " gets no Console: only command does");
+ args[i] = if (T == *State or T == *const State)
+ @ptrCast(@alignCast(offer.state))
+ else if (T == *Session or T == *const Session)
+ @ptrCast(@alignCast(offer.ctx.session_root))
+ else if (T == *Store or T == *const Store)
+ @ptrCast(@alignCast(offer.ctx.store_root))
+ else if (T == *const Input)
+ offer.ctx.input
+ else if (T == Host)
+ offer.ctx.host
+ else if (T == *Frame)
+ offer.frame.?
+ else if (T == *Console)
+ offer.console.?
+ else if (T == []const u8)
+ offer.line
+ else
+ @compileError(name ++ ": no argument of type " ++ @typeName(T));
+ }
+ return @call(.auto, func, args);
}
pub fn info() callconv(.c) *const abi.Info {
@@ -170,36 +274,26 @@ pub fn Glue(comptime App: type) type {
}
pub fn defaults(which: abi.Memory, ptr: [*]u8) callconv(.c) void {
switch (which) {
- .state => state(ptr).* = .{},
- .session => session(ptr).* = .{},
+ .state => @as(*State, @ptrCast(@alignCast(ptr))).* = .{},
+ .session => @as(*Session, @ptrCast(@alignCast(ptr))).* = .{},
+ .store => @as(*Store, @ptrCast(@alignCast(ptr))).* = .{},
}
}
pub fn init(ctx: *const abi.Context, s: [*]u8) callconv(.c) void {
- if (!@hasDecl(App, "init")) return;
- switch (comptime arity(App.init)) {
- 1 => App.init(state(s)),
- else => App.init(state(s), ctx.host),
- }
+ if (@hasDecl(App, "init")) call(App.init, "init", .{ .ctx = ctx, .state = s });
}
pub fn update(ctx: *const abi.Context, s: [*]u8) callconv(.c) void {
- if (@hasDecl(App, "update")) App.update(state(s), ctx.input);
+ if (@hasDecl(App, "update")) call(App.update, "update", .{ .ctx = ctx, .state = s });
}
- pub fn draw(ctx: *const abi.Context, s: [*]const u8, ss: [*]u8) callconv(.c) void {
+ pub fn draw(ctx: *const abi.Context, s: [*]const u8) callconv(.c) void {
if (!@hasDecl(App, "draw")) return;
var f: Frame = .init(ctx);
- const current: *const State = @ptrCast(@alignCast(s));
- switch (comptime arity(App.draw)) {
- 2 => App.draw(current, &f),
- else => App.draw(current, session(ss), &f),
- }
+ call(App.draw, "draw", .{ .ctx = ctx, .state = @constCast(s), .frame = &f });
}
- pub fn command(ctx: *const abi.Context, s: [*]u8, ss: [*]u8, line: *const []const u8) callconv(.c) abi.Outcome {
+ pub fn command(ctx: *const abi.Context, s: [*]u8, line: *const []const u8) callconv(.c) abi.Outcome {
if (!@hasDecl(App, "command")) return .unknown;
- var c: Console = .{ .host = ctx.host, .in = ctx.input };
- const taken = switch (comptime arity(App.command)) {
- 3 => App.command(state(s), &c, line.*),
- else => App.command(state(s), session(ss), &c, line.*),
- } catch |err| {
+ var c: Console = .{ .host = ctx.host, .in = ctx.input, .session = ctx.session, .store = ctx.store };
+ const taken = call(App.command, "command", .{ .ctx = ctx, .state = s, .console = &c, .line = line.* }) catch |err| {
c.print("{t}. Type help for usage.", .{err});
return .failed;
};
@@ -209,6 +303,7 @@ pub fn Glue(comptime App: type) type {
}
test {
+ _ = request;
_ = abi.layout;
_ = shape;
_ = @import("camera.zig");