1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
|
//! The sketch library: compiled into every app and reloaded with it.
//!
//! An app is an ordinary Zig module. Every declaration is optional:
//!
//! pub const name = "my sketch";
//! pub const width = 960;
//! pub const height = 600;
//! 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, store: *Store, f: *sk.Frame) void
//! pub fn command(state: *State, store: *Store, c: *sk.Console, line: []const u8) !bool
//!
//! 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");
/// Duck-typed points, rects and colors (named `shapes` inside this file,
/// where `Frame.shape` is the method).
pub const shape = shapes;
const shapes = @import("shape.zig");
pub const Key = abi.Key;
pub const Camera = @import("camera.zig").Camera;
pub const tween = @import("tween.zig");
/// Vectors (`@Vector(2, f32)`), affine transforms, Béziers and noise: the
/// geometry module the `vector` library uses too.
pub const math = @import("math");
/// Circles, lines and polygons as `Command.shape`s: a `Tessellation` to
/// build yourself (L1), or a `Pen` and `circle`/`line`/`polygon` (L2).
pub const draw = @import("draw.zig");
pub const Clock = @import("clock.zig").Clock;
pub const List = @import("list.zig").List;
/// Data computed in draw from a few State fields, kept in Session and rebuilt when they change (or after a reload).
pub const Derived = @import("derived.zig").Derived;
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;
pub const Event = abi.Event;
pub const Input = abi.Input;
pub const Mode = abi.Mode;
pub const MouseButton = abi.MouseButton;
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;
pub const BlendMode = abi.BlendMode;
pub const Face = abi.Face;
/// 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,
/// 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, .scratch = ctx.scratch, .session = ctx.session, .store = ctx.store };
}
pub fn emit(f: *Frame, command: abi.Command) void {
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 &.{};
}
/// Colour parameters take anything `shape.color` does (`0x202020`,
/// `sk.Color.gray(220)`, `.{ .r = 1, .g = 0, .b = 0 }`), and the
/// `Color` constants by name: `f.clear(.white)`.
pub fn clear(f: *Frame, color: anytype) void {
f.emit(.{ .clear = paint(color) });
}
pub fn fill(f: *Frame, r: anytype, color: anytype) void {
f.emit(.{ .rect = .{ .dst = shapes.rect(r), .color = paint(color) } });
}
/// `options` may set `.src` (a rect within the image) and `.tint` (a color).
pub fn image(f: *Frame, img: Image, dst: anytype, options: anytype) void {
const O = @TypeOf(options);
f.emit(.{ .image = .{
.image = img,
.dst = shapes.rect(dst),
.src = if (@hasField(O, "src")) shapes.rect(options.src) else .{},
.tint = if (@hasField(O, "tint")) paint(options.tint) else .white,
} });
}
/// Processing's `imageMode(CENTER)` under a transform: the image (or
/// `src` within it) centred on `xf`'s origin, along its axes, at
/// `size` (default: the image's, or `src`'s). `.place(at, radians)`
/// turns it, `.translate(x, y)` only moves it. Nothing is drawn while
/// the size is unknown (an image the web is still loading).
pub fn imageAt(f: *Frame, img: Image, xf: math.Affine, options: struct { src: Rect = .{}, size: ?[2]f32 = null, tint: Color = .white }) void {
const wh: [2]f32 = options.size orelse if (options.src.w > 0) .{ options.src.w, options.src.h } else blk: {
const px = f.host.imageSize(img);
break :blk .{ @floatFromInt(px[0]), @floatFromInt(px[1]) };
};
if (wh[0] == 0 or wh[1] == 0) return;
const hw = wh[0] / 2;
const hh = wh[1] / 2;
f.emit(.{ .image = .{
.image = img,
.dst = .{ .x = -hw, .y = -hh, .w = wh[0], .h = wh[1] },
.src = options.src,
.tint = options.tint,
.corners = .{
.top_left = xf.apply(.{ -hw, -hh }),
.top_right = xf.apply(.{ hw, -hh }),
.bottom_left = xf.apply(.{ -hw, hh }),
},
} });
}
/// Draws the 2D commands after it into `img` (made by
/// `host.newImage`), until `f.target(.none)` or the frame ends. The
/// image keeps what was drawn, across frames: a canvas that is never
/// cleared. It is a Session cache, so repaint it from State when
/// `f.in.jumped`.
pub fn target(f: *Frame, img: Image) void {
f.emit(.{ .target = img });
}
/// How the 2D commands after it blend, until the next `blend` or the
/// frame ends (which goes back to `.alpha`).
pub fn blend(f: *Frame, mode: BlendMode) void {
f.emit(.{ .blend = mode });
}
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 = paint(color), .bytes = f.keep(u8, bytes) } });
}
/// `text` in another face of the built-in family: bold or italic mono,
/// or the sans (`host.textSizeIn` measures it).
pub fn textIn(f: *Frame, face: Face, x: f32, y: f32, scale: f32, bytes: []const u8, color: anytype) void {
f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = paint(color), .bytes = f.keep(u8, bytes), .face = face } });
}
/// `textIn` laid out and rasterized at `raster` and drawn at `scale`,
/// its position not snapped to a pixel: for text under a moving
/// camera. Rasterize at the scale the move ends on (or the larger of
/// its two ends): the letters keep their places against each other
/// all the way, and one texture serves every frame of the move.
pub fn textScaled(f: *Frame, face: Face, x: f32, y: f32, scale: f32, raster: f32, bytes: []const u8, color: anytype) void {
f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = paint(color), .bytes = f.keep(u8, bytes), .face = face, .raster = raster } });
}
pub fn print(f: *Frame, x: f32, y: f32, scale: f32, color: anytype, comptime fmt: []const u8, args: anytype) void {
f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = paint(color), .bytes = f.format(fmt, args) } });
}
/// Formats into scratch memory.
pub fn format(f: *Frame, comptime fmt: []const u8, args: anytype) []const u8 {
return f.scratch.print(fmt, args) catch "?";
}
/// Fills `t`'s region in `color` (see `draw`). Its slices are not
/// copied: `t` must live until the frame is drawn (scratch memory, or
/// a session value not cleared before then).
pub fn shape(f: *Frame, t: *const draw.Tessellation, color: Color) void {
if (t.indices.items.len == 0) return;
f.emit(.{ .shape = .{ .color = color, .points = t.points.items, .ends = t.ends.items, .indices = t.indices.items } });
}
/// `t` with a colour per subpath: `colors[i]` for subpath `i` (one per
/// `t.ends` item; a stroked circle has two, its outline and its hole,
/// which must share one). Many shapes of many colours in one command,
/// like fading particles. Neither slice is copied (see `shape`).
pub fn shapeColors(f: *Frame, t: *const draw.Tessellation, colors: []const Color) void {
if (t.indices.items.len == 0) return;
f.emit(.{ .shape = .{ .color = if (colors.len > 0) colors[colors.len - 1] else .white, .points = t.points.items, .ends = t.ends.items, .indices = t.indices.items, .colors = colors } });
}
/// A rect, or `null` to stop clipping.
pub fn clip(f: *Frame, r: anytype) void {
f.emit(.{ .clip = if (@TypeOf(r) == @TypeOf(null)) null else shapes.rect(r) });
}
pub fn canvas(f: *Frame, w: u32, h: u32) void {
f.emit(.{ .canvas = .{ .w = w, .h = h } });
}
pub fn cursor(f: *Frame, kind: Cursor) void {
f.emit(.{ .cursor = kind });
}
pub fn voice(f: *Frame, v: Voice) void {
f.emit(.{ .voice = v });
}
pub fn audio(f: *Frame, key: u32, samples: []const f32, options: struct { clear: bool = false }) void {
f.emit(.{ .audio = .{ .key = key, .samples = samples, .clear = options.clear } });
}
pub fn pixels(f: *Frame, img: Image, w: u32, h: u32, rgba: []const u8, options: struct { premultiplied: bool = false }) void {
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 {
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);
}
};
/// A colour argument: `shape.color`'s forms, or a `Color` constant by
/// name (`.white`), which an `anytype` parameter cannot resolve itself.
fn paint(value: anytype) Color {
if (@TypeOf(value) == @EnumLiteral()) return @field(Color, @tagName(value));
return shapes.color(value);
}
/// 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);
}
pub fn print(c: *Console, comptime fmt: []const u8, args: anytype) void {
c.host.print(fmt, args);
}
};
/// The entry points of `App`, for a host that links it statically.
pub fn sketch(comptime App: type) abi.Sketch {
const G = Glue(App);
return .{ .info = G.info, .defaults = G.defaults, .init = G.init, .update = G.update, .draw = G.draw, .command = G.command };
}
/// Exports `App` under `abi.Sketch.symbols`, for a hot-reloaded library.
pub fn exportSketch(comptime App: type) void {
const G = Glue(App);
const names = abi.Sketch.symbols;
@export(&G.info, .{ .name = names.info });
@export(&G.defaults, .{ .name = names.defaults });
@export(&G.init, .{ .name = names.init });
@export(&G.update, .{ .name = names.update });
@export(&G.draw, .{ .name = names.draw });
@export(&G.command, .{ .name = names.command });
}
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, .state),
.session = abi.layout.of(Session, .session),
.store = abi.layout.of(Store, .store),
.commands = if (@hasDecl(App, "commands")) &App.commands else &.{},
};
/// 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 {
return &description;
}
pub fn defaults(which: abi.Memory, ptr: [*]u8) callconv(.c) void {
switch (which) {
.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")) call(App.init, "init", .{ .ctx = ctx, .state = s });
}
pub fn update(ctx: *const abi.Context, s: [*]u8) callconv(.c) void {
if (@hasDecl(App, "update")) call(App.update, "update", .{ .ctx = ctx, .state = s });
}
pub fn draw(ctx: *const abi.Context, s: [*]const u8) callconv(.c) void {
if (!@hasDecl(App, "draw")) return;
var f: Frame = .init(ctx);
call(App.draw, "draw", .{ .ctx = ctx, .state = @constCast(s), .frame = &f });
}
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, .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;
};
return if (taken) .done else .unknown;
}
};
}
test {
_ = request;
_ = abi.layout;
_ = shapes;
_ = @import("camera.zig");
_ = tween;
_ = draw;
_ = @import("clock.zig");
_ = @import("list.zig");
_ = @import("derived.zig");
}
|