summaryrefslogtreecommitdiff
path: root/src/sketch
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-10-28 21:07:13 -0300
committerGabriel Schneider <[email protected]>2026-11-12 13:22:02 -0300
commit590ba7b9b579b97e34b51ab7e3460ebc85713343 (patch)
tree6a73a7570ff4f79f41deff078455877b9bc6571b /src/sketch
parentbc8e6eb1bfef0c5e9b3c40fc1e4fd5a1659e2b03 (diff)
downloadsketchbook-590ba7b9b579b97e34b51ab7e3460ebc85713343.tar.gz
sketchbook-590ba7b9b579b97e34b51ab7e3460ebc85713343.zip
sketchbook: Zig 0.17, a Store on disk, requests, a scope (waveform, spectrum, spectrogram), audio codecs and fonts, web host
Diffstat (limited to 'src/sketch')
-rw-r--r--src/sketch/request.zig59
-rw-r--r--src/sketch/root.zig199
-rw-r--r--src/sketch/shape.zig25
-rw-r--r--src/sketch/tween.zig14
-rw-r--r--src/sketch/web.zig267
5 files changed, 462 insertions, 102 deletions
diff --git a/src/sketch/request.zig b/src/sketch/request.zig
new file mode 100644
index 0000000..0b8b400
--- /dev/null
+++ b/src/sketch/request.zig
@@ -0,0 +1,59 @@
+//! Requests from `update` that `draw` carries out once. `update` sees only
+//! State and input, so when a key should do something to Session or Store
+//! (start the microphone, open a dialog, seek a stream), State holds the
+//! request and Session remembers which ones it has handled:
+//!
+//! // State
+//! seek: sk.Request(f32) = .{},
+//! // Session
+//! seek: sk.Handled = .{},
+//!
+//! // update
+//! if (in.pressed(.home)) s.seek.send(0);
+//! // draw
+//! if (ss.seek.take(s.seek)) |to| cursor = to * len;
+const std = @import("std");
+
+/// A request carrying `T`, starting at `T`'s zero value.
+pub fn Request(comptime T: type) type {
+ return struct {
+ value: T = std.mem.zeroes(T),
+ /// Bumped by every `send`, so the same value can be asked for twice.
+ serial: u32 = 0,
+
+ pub const Value = T;
+
+ pub fn send(r: *@This(), value: T) void {
+ r.value = value;
+ r.serial +%= 1;
+ }
+ };
+}
+
+/// Which request a Session has carried out.
+pub const Handled = struct {
+ serial: ?u32 = null,
+
+ /// The request's value if it is new to this Session. A fresh Session (a
+ /// restart, or Session's layout changed) counts earlier requests as
+ /// handled: nothing re-fires from saved state, as `Input.started` asks
+ /// of `update`. So take every request on every frame, even when its
+ /// value will be ignored: the first take only catches up.
+ pub fn take(h: *Handled, request: anytype) ?@TypeOf(request).Value {
+ defer h.serial = request.serial;
+ const last = h.serial orelse return null;
+ return if (last == request.serial) null else request.value;
+ }
+};
+
+test "a request is taken once, and none from before the session" {
+ var r: Request(f32) = .{};
+ r.send(0.5);
+ var h: Handled = .{};
+ try std.testing.expectEqual(@as(?f32, null), h.take(r));
+ r.send(0.25);
+ try std.testing.expectEqual(@as(?f32, 0.25), h.take(r));
+ try std.testing.expectEqual(@as(?f32, null), h.take(r));
+ r.send(0.25);
+ try std.testing.expectEqual(@as(?f32, 0.25), h.take(r));
+}
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");
diff --git a/src/sketch/shape.zig b/src/sketch/shape.zig
index 9bd4cee..e7575e1 100644
--- a/src/sketch/shape.zig
+++ b/src/sketch/shape.zig
@@ -52,7 +52,7 @@ pub const Point = struct { x: f32 = 0, y: f32 = 0 };
/// `abi.Rect`.
pub fn Out(comptime T: type) type {
if (@typeInfo(T) != .@"struct") return T;
- for (@typeInfo(T).@"struct".fields) |field| switch (@typeInfo(field.type)) {
+ for (@typeInfo(T).@"struct".field_types) |F| switch (@typeInfo(F)) {
.comptime_int, .comptime_float => return if (isRect(T)) abi.Rect else Point,
else => {},
};
@@ -84,19 +84,20 @@ pub fn make(comptime T: type, x: f32, y: f32, w: f32, h: f32) T {
.array => |a| return if (a.len == 2) .{ cast(a.child, x), cast(a.child, y) } else .{ cast(a.child, x), cast(a.child, y), cast(a.child, w), cast(a.child, h) },
.@"struct" => {
var result: T = undefined;
- inline for (@typeInfo(T).@"struct".fields) |field| {
- @field(result, field.name) = if (comptime eql(field.name, "x"))
- cast(field.type, x)
- else if (comptime eql(field.name, "y"))
- cast(field.type, y)
- else if (comptime eql(field.name, "w") or eql(field.name, "width"))
- cast(field.type, w)
- else if (comptime eql(field.name, "h") or eql(field.name, "height"))
- cast(field.type, h)
- else if (field.defaultValue()) |default|
+ const s = @typeInfo(T).@"struct";
+ inline for (s.field_names, s.field_types, s.field_attrs) |name, F, attrs| {
+ @field(result, name) = if (comptime eql(name, "x"))
+ cast(F, x)
+ else if (comptime eql(name, "y"))
+ cast(F, y)
+ else if (comptime eql(name, "w") or eql(name, "width"))
+ cast(F, w)
+ else if (comptime eql(name, "h") or eql(name, "height"))
+ cast(F, h)
+ else if (comptime attrs.defaultValue(F)) |default|
default
else
- @compileError(@typeName(T) ++ "." ++ field.name ++ " has no default");
+ @compileError(@typeName(T) ++ "." ++ name ++ " has no default");
}
return result;
},
diff --git a/src/sketch/tween.zig b/src/sketch/tween.zig
index d3b53a1..6d1cef1 100644
--- a/src/sketch/tween.zig
+++ b/src/sketch/tween.zig
@@ -25,7 +25,7 @@ pub fn lerp(a: anytype, b: @TypeOf(a), t: f32) @TypeOf(a) {
},
.@"struct" => |s| blk: {
var out: T = undefined;
- inline for (s.fields) |field| @field(out, field.name) = lerp(@field(a, field.name), @field(b, field.name), t);
+ inline for (s.field_names) |name| @field(out, name) = lerp(@field(a, name), @field(b, name), t);
break :blk out;
},
else => if (t >= 1) b else a,
@@ -49,14 +49,14 @@ pub fn lerpFields(a: anytype, b: @TypeOf(a), t: f32, comptime names: anytype) @T
pub fn toward(a: anytype, target: anytype, t: f32) @TypeOf(a) {
const T = @TypeOf(a);
var out = a;
- inline for (@typeInfo(@TypeOf(target)).@"struct".fields) |field| {
- if (!@hasField(T, field.name)) @compileError(@typeName(T) ++ " has no field '" ++ field.name ++ "' to animate");
- const F = @FieldType(T, field.name);
+ inline for (@typeInfo(@TypeOf(target)).@"struct".field_names) |name| {
+ if (!@hasField(T, name)) @compileError(@typeName(T) ++ " has no field '" ++ name ++ "' to animate");
+ const F = @FieldType(T, name);
const goal: F = switch (@typeInfo(F)) {
- .@"struct" => toward(@field(a, field.name), @field(target, field.name), 1),
- else => @field(target, field.name),
+ .@"struct" => toward(@field(a, name), @field(target, name), 1),
+ else => @field(target, name),
};
- @field(out, field.name) = lerp(@field(a, field.name), goal, t);
+ @field(out, name) = lerp(@field(a, name), goal, t);
}
return out;
}
diff --git a/src/sketch/web.zig b/src/sketch/web.zig
index e91a0ad..bc7fead 100644
--- a/src/sketch/web.zig
+++ b/src/sketch/web.zig
@@ -1,6 +1,8 @@
-//! Runs a sketch in a browser. `web/host.js` forwards input and implements a
-//! handful of drawing imports; state, `update` and `draw` are the same Zig as
-//! on native. There is no console, timeline or persistence on the web.
+//! Runs a sketch in a browser. `web/host.js` forwards input and implements
+//! the imports below: drawing on a 2D canvas, GPU work on WebGPU, sound and
+//! the microphone on Web Audio, files through the page. State, `update` and
+//! `draw` are the same Zig as on native. There is no timeline, and nothing
+//! persists: Store lasts as long as the page.
const std = @import("std");
const abi = @import("abi");
const root = @import("root.zig");
@@ -11,7 +13,9 @@ const js = struct {
extern "host" fn imageWidth(image: u32) u32;
extern "host" fn imageHeight(image: u32) u32;
extern "host" fn newImage(w: u32, h: u32) u32;
+ extern "host" fn freeImage(image: u32) void;
extern "host" fn clock() f64;
+ extern "host" fn openFile(command: [*]const u8, command_len: usize, pattern: [*]const u8, pattern_len: usize) void;
extern "canvas" fn clear(r: u32, g: u32, b: u32, a: u32) void;
extern "canvas" fn fill(x: f32, y: f32, w: f32, h: f32, r: u32, g: u32, b: u32, a: u32) void;
extern "canvas" fn image(id: u32, x: f32, y: f32, w: f32, h: f32, sx: f32, sy: f32, sw: f32, sh: f32, alpha: u32) void;
@@ -20,16 +24,40 @@ const js = struct {
extern "canvas" fn canvas(w: u32, h: u32) void;
extern "canvas" fn cursor(kind: u32) void;
extern "canvas" fn pixels(id: u32, w: u32, h: u32, ptr: [*]const u8, len: usize, premultiplied: u32) void;
+ /// Nonzero once the page has a WebGPU device.
+ extern "gpu" fn available() u32;
+ extern "gpu" fn newBuffer(size: u32) u32;
+ extern "gpu" fn freeBuffer(id: u32) void;
+ extern "gpu" fn write(id: u32, offset: u32, ptr: [*]const u8, len: usize) void;
+ /// A `Dispatch` or a `Pass`, described in JSON (see `describe`).
+ extern "gpu" fn compute(ptr: [*]const u8, len: usize) void;
+ extern "gpu" fn pass(ptr: [*]const u8, len: usize) void;
+ /// Answers through `sk_download`.
+ extern "gpu" fn download(id: u32, offset: u32, size: u32, key: u32) void;
+ extern "audio" fn rate() u32;
+ extern "audio" fn push(key: u32, ptr: [*]const f32, len: usize, clear: u32) void;
+ extern "audio" fn queued(key: u32) u32;
+ /// Keeps the microphone open; it answers through `sk_microphone`.
+ extern "audio" fn listen() void;
};
-/// Exports `App` for `web/host.js`: `sk_init`, `sk_event`, `sk_frame`, and
-/// for tests to read state by path, `sk_field` (a number) and `sk_tag` (an
-/// enum's tag name).
+/// Exports `App` for `web/host.js`: `sk_init`, `sk_event`, `sk_frame`,
+/// `sk_window` (the room for the canvas);
+/// `sk_alloc` and the deliveries into what it returns (`sk_microphone`,
+/// `sk_download`, `sk_sound`, `sk_command`); and for tests to read state by
+/// path, `sk_buffer`, `sk_field` (a number) and `sk_tag` (an enum's tag
+/// name).
pub fn exportWeb(comptime App: type) void {
const D = Driver(App);
@export(&D.init, .{ .name = "sk_init" });
@export(&D.event, .{ .name = "sk_event" });
@export(&D.frame, .{ .name = "sk_frame" });
+ @export(&D.window, .{ .name = "sk_window" });
+ @export(&D.alloc, .{ .name = "sk_alloc" });
+ @export(&D.microphone, .{ .name = "sk_microphone" });
+ @export(&D.download, .{ .name = "sk_download" });
+ @export(&D.sound, .{ .name = "sk_sound" });
+ @export(&D.command, .{ .name = "sk_command" });
@export(&D.buffer, .{ .name = "sk_buffer" });
@export(&D.field, .{ .name = "sk_field" });
@export(&D.tag, .{ .name = "sk_tag" });
@@ -37,24 +65,36 @@ pub fn exportWeb(comptime App: type) void {
fn Driver(comptime App: type) type {
const G = root.Glue(App);
+ const gpa = std.heap.wasm_allocator;
return struct {
var state: G.State = undefined;
var session: G.Session = undefined;
+ // No disk on the web: the store lasts as long as the page.
+ var store: G.Store = undefined;
var events: [1024]abi.Event = undefined;
var event_count: usize = 0;
var input: abi.Input = .{};
var commands: std.ArrayList(abi.Command) = .empty;
- var arena: std.heap.ArenaAllocator = .init(std.heap.wasm_allocator);
- var session_heap: std.heap.ArenaAllocator = .init(std.heap.wasm_allocator);
+ var scratch: std.heap.ArenaAllocator = .init(gpa);
var last: u64 = 0;
var path: [256]u8 = undefined;
+ /// What arrived since the last frame, handed to the next one.
+ var heard: std.ArrayList(f32) = .empty;
+ var downloads: std.ArrayList(abi.Download) = .empty;
+ /// Streams the sketch has pushed to, by key.
+ var streams: std.ArrayList(abi.Stream) = .empty;
+ /// Sounds the page decoded, by name: `Audio` n is `sounds[n - 1]`.
+ var sounds: std.ArrayList(struct { name: []const u8, samples: []const f32 }) = .empty;
fn context() abi.Context {
return .{
.host = .{ .ctx = @ptrCast(&input), .vtable = &vtable },
.input = &input,
- .arena = arena.allocator(),
- .gpa = session_heap.allocator(),
+ .scratch = scratch.allocator(),
+ .session = gpa,
+ .store = gpa,
+ .session_root = std.mem.asBytes(&session),
+ .store_root = std.mem.asBytes(&store),
.commands = &commands,
};
}
@@ -62,21 +102,33 @@ fn Driver(comptime App: type) type {
fn init() callconv(.c) void {
G.defaults(.state, std.mem.asBytes(&state));
G.defaults(.session, std.mem.asBytes(&session));
+ G.defaults(.store, std.mem.asBytes(&store));
input.width = G.description.width;
input.height = G.description.height;
+ if (input.window_width == 0) {
+ input.window_width = input.width;
+ input.window_height = input.height;
+ }
+ input.sample_rate = js.rate();
js.canvas(G.description.width, G.description.height);
const ctx = context();
G.init(&ctx, std.mem.asBytes(&state));
}
- fn event(kind: u32, code: u32, x: f32, y: f32, value: u32) callconv(.c) void {
+ /// The page's room for the canvas, in CSS pixels.
+ fn window(w: f32, h: f32) callconv(.c) void {
+ input.window_width = w;
+ input.window_height = h;
+ }
+
+ fn event(kind: u32, code: u32, x: f32, y: f32, value: u32, flags: u32) callconv(.c) void {
const k = std.enums.fromInt(abi.Event.Kind, kind) orelse return;
if (event_count == events.len) {
// Never leave a gesture armed when the queue overflows.
events[0] = .{ .kind = .cancel };
event_count = 1;
}
- events[event_count] = .{ .kind = k, .code = @intCast(code), .x = x, .y = y, .value = value };
+ events[event_count] = .{ .kind = k, .code = @intCast(code), .x = x, .y = y, .value = value, .flags = @truncate(flags) };
event_count += 1;
}
@@ -92,27 +144,39 @@ fn Driver(comptime App: type) type {
e.time = now;
input.track(e.*);
}
- _ = arena.reset(.retain_capacity);
+ _ = scratch.reset(.retain_capacity);
commands = .empty;
input.now = now;
input.dt = dt;
input.frame += 1;
input.events = events[0..event_count];
input.started = input.frame == 1;
+ for (streams.items) |*s| s.queued = js.queued(s.key);
+ input.streams = streams.items;
+ input.microphone = heard.items;
+ input.downloads = downloads.items;
const ctx = context();
G.update(&ctx, std.mem.asBytes(&state));
input.events = &.{};
event_count = 0;
- G.draw(&ctx, std.mem.asBytes(&state), std.mem.asBytes(&session));
+ G.draw(&ctx, std.mem.asBytes(&state));
js.clip(0, 0, 0, 0, 0);
- for (commands.items) |command| submit(command);
+ for (commands.items) |c| submit(c);
+ // After the frame, as on native: lines `draw` asked to run.
+ for (commands.items) |c| if (c == .run) run(c.run);
+
+ heard.clearRetainingCapacity();
+ for (downloads.items) |d| gpa.free(d.bytes);
+ downloads.clearRetainingCapacity();
+ input.microphone = &.{};
+ input.downloads = &.{};
}
- fn submit(command: abi.Command) void {
- switch (command) {
+ fn submit(c: abi.Command) void {
+ switch (c) {
.clear => |v| js.clear(v.r, v.g, v.b, v.a),
.rect => |v| js.fill(v.dst.x, v.dst.y, v.dst.w, v.dst.h, v.color.r, v.color.g, v.color.b, v.color.a),
- .image => |v| js.image(@intFromEnum(v.image), v.dst.x, v.dst.y, v.dst.w, v.dst.h, v.src.x, v.src.y, v.src.w, v.src.h, v.tint.a),
+ .image => |v| js.image(@backingInt(v.image), v.dst.x, v.dst.y, v.dst.w, v.dst.h, v.src.x, v.src.y, v.src.w, v.src.h, v.tint.a),
.text => |v| js.text(v.x, v.y, v.scale, v.bytes.ptr, v.bytes.len, v.color.r, v.color.g, v.color.b, v.color.a),
.clip => |v| if (v) |r| js.clip(1, r.x, r.y, r.w, r.h) else js.clip(0, 0, 0, 0, 0),
.canvas => |v| {
@@ -120,20 +184,138 @@ fn Driver(comptime App: type) type {
input.height = @floatFromInt(v.h);
js.canvas(v.w, v.h);
},
- .cursor => |v| js.cursor(@intFromEnum(v)),
- .pixels => |v| js.pixels(@intFromEnum(v.image), v.w, v.h, v.rgba.ptr, v.rgba.len, @intFromBool(v.premultiplied)),
- // No sound or GPU passes on the web yet (Host.gpu says so);
- // quitting a page means nothing.
- .voice, .audio, .gpu, .quit => {},
+ .cursor => |v| js.cursor(@backingInt(v)),
+ .pixels => |v| js.pixels(@backingInt(v.image), v.w, v.h, v.rgba.ptr, v.rgba.len, @intFromBool(v.premultiplied)),
+ .audio => |v| {
+ const s = stream(v.key);
+ if (v.clear) s.pushed = 0;
+ s.pushed += v.samples.len;
+ js.push(v.key, v.samples.ptr, v.samples.len, @intFromBool(v.clear));
+ },
+ .microphone => js.listen(),
+ .upload => |v| js.write(@backingInt(v.buffer), v.offset, v.bytes.ptr, v.bytes.len),
+ .compute => |v| {
+ const json = describe(v);
+ js.compute(json.ptr, json.len);
+ },
+ .gpu => |v| {
+ const json = describe(v);
+ js.pass(json.ptr, json.len);
+ },
+ .download => |v| js.download(@backingInt(v.buffer), v.offset, v.size, v.key),
+ .open_file => |v| js.openFile(v.command.ptr, v.command.len, v.pattern.ptr, v.pattern.len),
+ // Synthesised voices are not on the web yet; quitting a page
+ // means nothing; `run` lines go after the frame.
+ .voice, .quit, .run => {},
}
}
+ fn stream(key: u32) *abi.Stream {
+ for (streams.items) |*s| if (s.key == key) return s;
+ streams.append(gpa, .{ .key = key }) catch return &streams.items[0];
+ return &streams.items[streams.items.len - 1];
+ }
+
+ fn run(line: []const u8) void {
+ const ctx = context();
+ if (G.command(&ctx, std.mem.asBytes(&state), &line) == .unknown) {
+ var buf: [160]u8 = undefined;
+ const message = std.fmt.bufPrint(&buf, "unknown command: {s}", .{line[0..@min(line.len, 120)]}) catch return;
+ js.log(message.ptr, message.len);
+ }
+ }
+
+ /// GPU work as JSON for host.js: buffers by handle, bytes (code,
+ /// uniforms, vertices) as `[pointer, length]` into wasm memory, and
+ /// each shader with a hash of its code to cache it by.
+ fn describe(value: anytype) []const u8 {
+ var out: std.Io.Writer.Allocating = .init(scratch.allocator());
+ var json: std.json.Stringify = .{ .writer = &out.writer };
+ write(&json, value) catch return "{}";
+ return out.written();
+ }
+
+ fn write(json: *std.json.Stringify, value: anytype) !void {
+ const T = @TypeOf(value);
+ if (T == []const u8) {
+ try json.beginArray();
+ try json.write(@intFromPtr(value.ptr));
+ try json.write(value.len);
+ return json.endArray();
+ }
+ if (T == abi.gpu.Shader or T == abi.gpu.Kernel) {
+ // The code once more, by hash: compiled modules are cached.
+ try json.beginObject();
+ try json.objectField("hash");
+ try json.print("\"{x}\"", .{std.hash.Wyhash.hash(0, value.code)});
+ inline for (@typeInfo(T).@"struct".field_names) |name| {
+ try json.objectField(name);
+ try write(json, @field(value, name));
+ }
+ return json.endObject();
+ }
+ switch (@typeInfo(T)) {
+ .@"struct" => |s| {
+ try json.beginObject();
+ inline for (s.field_names) |name| {
+ try json.objectField(name);
+ try write(json, @field(value, name));
+ }
+ try json.endObject();
+ },
+ .pointer => {
+ try json.beginArray();
+ for (value) |item| try write(json, item);
+ try json.endArray();
+ },
+ .array => {
+ try json.beginArray();
+ for (value) |item| try write(json, item);
+ try json.endArray();
+ },
+ .optional => if (value) |v| try write(json, v) else try json.write(null),
+ .@"enum" => |e| if (e.mode == .exhaustive) try json.write(@tagName(value)) else try json.write(@backingInt(value)),
+ else => try json.write(value),
+ }
+ }
+
+ /// Memory for host.js to write a delivery into; the delivery takes
+ /// it over.
+ fn alloc(len: usize) callconv(.c) ?[*]u8 {
+ const bytes = gpa.alloc(u8, len) catch return null;
+ return bytes.ptr;
+ }
+
+ fn microphone(ptr: [*]f32, len: usize) callconv(.c) void {
+ heard.appendSlice(gpa, ptr[0..len]) catch {};
+ gpa.free(std.mem.sliceAsBytes(ptr[0..len]));
+ }
+
+ fn download(key: u32, ptr: [*]u8, len: usize) callconv(.c) void {
+ downloads.append(gpa, .{ .key = key, .bytes = ptr[0..len] }) catch gpa.free(ptr[0..len]);
+ }
+
+ /// A decoded sound for `loadSound(name)`; a name seen before is
+ /// replaced.
+ fn sound(name: [*]u8, name_len: usize, decoded: [*]f32, len: usize) callconv(.c) void {
+ for (sounds.items) |*s| if (std.mem.eql(u8, s.name, name[0..name_len])) {
+ gpa.free(name[0..name_len]);
+ s.samples = decoded[0..len];
+ return;
+ };
+ sounds.append(gpa, .{ .name = name[0..name_len], .samples = decoded[0..len] }) catch {};
+ }
+
+ /// Runs a console line through the sketch's `command`.
+ fn command(ptr: [*]u8, len: usize) callconv(.c) void {
+ run(ptr[0..len]);
+ gpa.free(ptr[0..len]);
+ }
+
fn buffer() callconv(.c) [*]u8 {
return &path;
}
- /// The state field at the path written into `sk_buffer`, as a number
- /// (enums by value); NaN when there is no such scalar field.
/// Writes the tag name of the enum field at the path in `buffer` over
/// it, and returns its length; -1 when there is no such enum field.
fn tag(len: usize) callconv(.c) i32 {
@@ -152,6 +334,8 @@ fn Driver(comptime App: type) type {
return -1;
}
+ /// The state field at the path written into `sk_buffer`, as a number
+ /// (enums by value); NaN when there is no such scalar field.
fn field(len: usize) callconv(.c) f64 {
const name = path[0..@min(len, path.len)];
const bytes = std.mem.asBytes(&state);
@@ -180,9 +364,12 @@ fn Driver(comptime App: type) type {
.newImage = newImage,
.freeImage = freeImage,
.gpu = gpu,
+ .newBuffer = newBuffer,
+ .freeBuffer = freeBuffer,
.imageSize = imageSize,
- .loadSound = unsupportedSound,
+ .loadSound = loadSound,
.decodeSound = unsupportedSound,
+ .samples = samples,
.readFile = readFile,
.env = env,
.clock = clock,
@@ -191,24 +378,42 @@ fn Driver(comptime App: type) type {
js.log(message.ptr, message.len);
}
fn loadImage(_: *anyopaque, p: []const u8) abi.Image {
- return @enumFromInt(js.loadImage(p.ptr, p.len));
+ return @fromBackingInt(@intCast(js.loadImage(p.ptr, p.len)));
}
fn unsupportedImage(_: *anyopaque, _: []const u8) abi.Image {
return .none;
}
fn newImage(_: *anyopaque, w: u32, h: u32) abi.Image {
- return @enumFromInt(js.newImage(w, h));
+ return @fromBackingInt(@intCast(js.newImage(w, h)));
+ }
+ fn freeImage(_: *anyopaque, img: abi.Image) void {
+ js.freeImage(@backingInt(img));
}
- fn freeImage(_: *anyopaque, _: abi.Image) void {}
fn gpu(_: *anyopaque) bool {
- return false;
+ return js.available() != 0;
+ }
+ fn newBuffer(_: *anyopaque, size: u32) abi.Buffer {
+ return @fromBackingInt(js.newBuffer(size));
+ }
+ fn freeBuffer(_: *anyopaque, b: abi.Buffer) void {
+ js.freeBuffer(@backingInt(b));
}
fn imageSize(_: *anyopaque, img: abi.Image) [2]u32 {
- return .{ js.imageWidth(@intFromEnum(img)), js.imageHeight(@intFromEnum(img)) };
+ return .{ js.imageWidth(@backingInt(img)), js.imageHeight(@backingInt(img)) };
+ }
+ /// Only sounds the page has decoded (opened or dropped files): the
+ /// browser decodes asynchronously, so there is no reading on demand.
+ fn loadSound(_: *anyopaque, name: []const u8) abi.Audio {
+ for (sounds.items, 1..) |s, i| if (std.mem.eql(u8, s.name, name)) return @fromBackingInt(@intCast(i));
+ return .none;
}
fn unsupportedSound(_: *anyopaque, _: []const u8) abi.Audio {
return .none;
}
+ fn samples(_: *anyopaque, a: abi.Audio) []const f32 {
+ const i = @backingInt(a);
+ return if (i == 0 or i > sounds.items.len) &.{} else sounds.items[i - 1].samples;
+ }
fn readFile(_: *anyopaque, _: []const u8) []const u8 {
return &.{};
}