//! Types shared by a host and the sketches it loads. //! //! Host and sketch are built by the same `zig build`, with the same compiler //! and standard library, so ordinary Zig types cross the boundary: slices, //! tagged unions, `std.mem.Allocator`. Two rules keep reloads safe: //! - whatever outlives a call lives in host memory (host code is never //! unloaded, so host allocators and function pointers stay valid); //! - `hash` covers the layout of every type here, and a host refuses a sketch //! built against different definitions instead of misreading its memory. //! //! Only `Event` and the reflected `Layout` are `extern`: they are written to disk. const std = @import("std"); pub const layout = @import("layout.zig"); pub const Key = @import("keys.zig").Key; pub const Rect = extern struct { x: f32 = 0, y: f32 = 0, w: f32 = 0, h: f32 = 0, pub fn contains(r: Rect, x: f32, y: f32) bool { return x >= r.x and y >= r.y and x < r.x + r.w and y < r.y + r.h; } pub fn inset(r: Rect, d: f32) Rect { return .{ .x = r.x + d, .y = r.y + d, .w = r.w - 2 * d, .h = r.h - 2 * d }; } }; pub const Color = extern struct { r: u8, g: u8, b: u8, a: u8 = 0xff, pub const white: Color = .{ .r = 255, .g = 255, .b = 255 }; pub const black: Color = .{ .r = 0, .g = 0, .b = 0 }; pub fn hex(rgb: u24) Color { return .{ .r = @truncate(rgb >> 16), .g = @truncate(rgb >> 8), .b = @truncate(rgb) }; } pub fn alpha(c: Color, a: u8) Color { return .{ .r = c.r, .g = c.g, .b = c.b, .a = a }; } }; /// One input event. Recordings are arrays of these on disk, so the layout is /// frozen: 24 bytes, no padding, no pointers. pub const Event = extern struct { /// Nanoseconds. Live: host clock. Replay: time since the recording began. time: u64 = 0, /// Canvas coordinates for pointer events; `tick` stores dt seconds in `x`. x: f32 = 0, y: f32 = 0, kind: Kind, flags: u8 = 0, /// Mouse button (1 left, 2 middle, 3 right) or USB HID scancode. code: u16 = 0, /// Unicode codepoint for `text`, key modifiers, or `@bitCast` wheel delta. value: u32 = 0, pub const Kind = enum(u8) { /// Once per frame, after that frame's other events. tick, mouse_move, mouse_down, mouse_up, wheel, key_down, key_up, text, /// Focus loss, or the console took the pointer: drop armed gestures. cancel, _, }; /// `flags` bit for a held key's auto-repeat. pub const repeat: u8 = 1; pub fn wheel(e: Event) f32 { return @bitCast(e.value); } comptime { std.debug.assert(@sizeOf(Event) == 24); } }; pub const Mode = enum { live, recording, playing, paused }; /// A host audio stream, as last observed by the host. pub const Stream = struct { key: u32, /// Samples waiting to be played. queued: u32 = 0, /// Samples pushed since the stream was last cleared. pushed: u64 = 0, }; /// Everything a sketch learns about the world for one call. pub const Input = struct { now: u64 = 0, /// Nanoseconds since the previous frame. dt: u64 = 0, frame: u64 = 0, events: []const Event = &.{}, mode: Mode = .live, /// First frame after new code, or a new layout, was loaded. reloaded: bool = false, /// First update since the program started (never after a hot reload): /// the place to stop what should not resume from saved state, like a /// song that was playing when the program quit. started: bool = false, /// The console is open and owns the keyboard. console: bool = false, width: f32 = 0, height: f32 = 0, mouse_x: f32 = 0, mouse_y: f32 = 0, /// Held mouse buttons, bit `button - 1`. buttons: u32 = 0, /// Held keys by USB HID scancode, maintained from the events fed so far. keys: std.StaticBitSet(256) = .initEmpty(), streams: []const Stream = &.{}, sample_rate: u32 = 48_000, /// `key` is any enum whose values are HID scancodes, like `sketch.Key`. pub fn held(in: *const Input, key: anytype) bool { return in.keys.isSet(@intFromEnum(key)); } /// Went down this frame; auto-repeats excluded. pub fn pressed(in: *const Input, key: anytype) bool { for (in.events) |e| { if (e.kind == .key_down and e.code == @intFromEnum(key) and e.flags & Event.repeat == 0) return true; } return false; } pub fn stream(in: *const Input, key: u32) Stream { for (in.streams) |s| if (s.key == key) return s; return .{ .key = key }; } /// Follows mouse, button and key state through one fed event. pub fn track(in: *Input, e: Event) void { switch (e.kind) { .mouse_move, .wheel => { in.mouse_x = e.x; in.mouse_y = e.y; }, .mouse_down, .mouse_up => { in.mouse_x = e.x; in.mouse_y = e.y; const bit = @as(u32, 1) << @intCast(@min(e.code -| 1, 31)); if (e.kind == .mouse_down) in.buttons |= bit else in.buttons &= ~bit; }, .key_down => in.keys.set(@min(e.code, 255)), .key_up => in.keys.unset(@min(e.code, 255)), .cancel => { in.buttons = 0; in.keys = .initEmpty(); }, else => {}, } } pub fn seconds(in: *const Input) f64 { return @as(f64, @floatFromInt(in.now)) / std.time.ns_per_s; } }; pub const Image = enum(u32) { none = 0, _ }; pub const Audio = enum(u32) { none = 0, _ }; pub const Cursor = enum { hidden, arrow, pointer }; /// Voices are reconciled, not triggered: `draw` declares every voice that /// should sound this frame, keyed by a number of its choosing. A new key, or /// a new serial for a key, starts the sound from its beginning; an undeclared /// key stops. A finished one-shot stays silent while its key and serial are /// still declared, so replaying or scrubbing state never re-fires sounds. pub const Voice = struct { key: u32, audio: Audio, serial: u32 = 0, loop: bool = false, volume: f32 = 1, /// Linear fade at both ends, in samples. fade: u32 = 0, }; /// Slices must stay alive until the host consumes the frame, right after /// `draw` returns: literals, the frame arena and session memory all qualify. pub const Command = union(enum) { clear: Color, rect: struct { dst: Rect, color: Color }, /// `src` empty: the whole image. `tint` multiplies it. image: struct { image: Image, dst: Rect, src: Rect = .{}, tint: Color = .white }, /// Fixed 8px cells, `scale` times larger. text: struct { x: f32, y: f32, scale: f32, color: Color, bytes: []const u8 }, clip: ?Rect, /// Logical canvas size; the host scales the window to fit. canvas: struct { w: u32, h: u32 }, cursor: Cursor, voice: Voice, /// Mono samples at `Input.sample_rate` for stream `key`. audio: struct { key: u32, samples: []const f32, clear: bool = false }, /// RGBA8 rows of `w * 4` bytes into an image made by `Host.newImage`. pixels: struct { image: Image, w: u32, h: u32, rgba: []const u8, premultiplied: bool = false }, /// Renders a GPU pass into an image made by `Host.newImage`, when /// `Host.gpu` says the host can. gpu: gpu.Pass, quit, }; /// GPU work described as data. A sketch declares its pipelines and draws; /// the host builds the real objects, caches them by the hash of their /// description (so an edited shader simply becomes a new pipeline after a /// reload), and runs the pass. Sketches never touch a graphics API. /// /// Shaders are SPIR-V. Resources follow SDL_GPU's SPIR-V convention: /// vertex uniforms in set 1, fragment uniforms in set 3, binding = slot. /// Uniform bytes must follow std140. pub const gpu = struct { pub const Shader = struct { spirv: []const u8, uniform_buffers: u32 = 0, }; pub const Format = enum { float, float2, float3, float4, ubyte4_norm }; pub const Attribute = struct { location: u32, format: Format, offset: u32 }; pub const Blend = enum { /// Overwrite. none, /// Source over, premultiplied colors. premultiplied, additive, }; pub const Compare = enum { never, less, equal, less_or_equal, greater, not_equal, greater_or_equal, always }; pub const StencilOp = enum { keep, zero, replace, increment_and_clamp, decrement_and_clamp, invert, increment_and_wrap, decrement_and_wrap }; pub const StencilFace = struct { compare: Compare = .always, pass: StencilOp = .keep, fail: StencilOp = .keep, }; pub const Pipeline = struct { vertex: Shader, fragment: Shader, /// Bytes per vertex. stride: u32, attributes: []const Attribute, primitive: enum { triangle_list, triangle_strip, line_list, line_strip } = .triangle_list, blend: Blend = .premultiplied, write_color: bool = true, /// Stencil test and update, per triangle facing. Needs a pass with /// a stencil buffer. stencil: ?struct { front: StencilFace, back: StencilFace } = null, }; pub const Draw = struct { /// Index into `Pass.pipelines`. pipeline: u32, vertices: []const u8, vertex_count: u32, stencil_reference: u8 = 0, /// Uniform slot 0 of each stage. vertex_uniforms: []const u8 = &.{}, fragment_uniforms: []const u8 = &.{}, scissor: ?Rect = null, }; // Layouts from types: Zig knows every offset at comptime, so vertex // formats and uniform layouts come from plain structs, never by hand. /// Vertex attributes for `V`: one per field, locations in field order, /// formats from the field types (`f32`, `[2..4]f32` or vectors, `[4]u8` /// normalized). pub fn attributes(comptime V: type) []const Attribute { return comptime blk: { if (@typeInfo(V).@"struct".layout != .@"extern") @compileError(@typeName(V) ++ " must be extern to be a vertex"); const fields = @typeInfo(V).@"struct".fields; var out: [fields.len]Attribute = undefined; for (fields, 0..) |f, i| out[i] = .{ .location = i, .offset = @offsetOf(V, f.name), .format = formatOf(f.type) }; const frozen = out; break :blk &frozen; }; } fn formatOf(comptime T: type) Format { if (T == f32) return .float; if (T == [4]u8 or T == @Vector(4, u8)) return .ubyte4_norm; const len, const child = switch (@typeInfo(T)) { .array => |a| .{ a.len, a.child }, .vector => |v| .{ v.len, v.child }, else => @compileError("no vertex format for " ++ @typeName(T)), }; if (child != f32) @compileError("no vertex format for " ++ @typeName(T)); return switch (len) { 2 => .float2, 3 => .float3, 4 => .float4, else => @compileError("no vertex format for " ++ @typeName(T)), }; } /// A pipeline drawing vertices of type `V`: stride and attributes filled in. pub fn pipeline(comptime V: type, p: struct { vertex: Shader, fragment: Shader, primitive: @FieldType(Pipeline, "primitive") = .triangle_list, blend: Blend = .premultiplied, write_color: bool = true, stencil: @FieldType(Pipeline, "stencil") = null, }) Pipeline { return .{ .vertex = p.vertex, .fragment = p.fragment, .stride = @sizeOf(V), .attributes = attributes(V), .primitive = p.primitive, .blend = p.blend, .write_color = p.write_color, .stencil = p.stencil, }; } /// Fails to compile unless `U` lays out as the std140 uniform block /// GLSL would declare for it (see `glsl.zig`). pub const assertStd140 = @import("glsl.zig").assertStd140; /// `value`'s bytes, checked against std140, copied into `arena` so they /// outlive the caller until the frame is consumed. pub fn uniform(arena: std.mem.Allocator, value: anytype) []const u8 { comptime assertStd140(@TypeOf(value)); const copy = arena.create(@TypeOf(value)) catch return &.{}; copy.* = value; return std.mem.asBytes(copy); } pub const Pass = struct { /// The target; its size is the image's. image: Image, width: u32, height: u32, /// 1, 2, 4 or 8. More than one renders multisampled and resolves. samples: u8 = 1, stencil: bool = false, /// Premultiplied; null keeps the image's previous contents. clear: ?[4]f32 = .{ 0, 0, 0, 0 }, pipelines: []const Pipeline, draws: []const Draw, }; }; /// Host services. Handles and loaded data outlive reloads. pub const Host = struct { ctx: *anyopaque, vtable: *const VTable, pub const VTable = struct { log: *const fn (*anyopaque, []const u8) void, /// Cached by path. A missing file still gets a handle: it draws as a /// placeholder, and starts working when the file appears. loadImage: *const fn (*anyopaque, []const u8) Image, /// PNG bytes in memory. Not cached. decodeImage: *const fn (*anyopaque, []const u8) Image, /// A blank image for `Command.pixels`. newImage: *const fn (*anyopaque, u32, u32) Image, /// Releases an image; its handle draws nothing afterwards. freeImage: *const fn (*anyopaque, Image) void, /// Whether `Command.gpu` runs here: the host has a GPU device. gpu: *const fn (*anyopaque) bool, /// Zero while unknown. imageSize: *const fn (*anyopaque, Image) [2]u32, /// `.none` if the file does not load. loadSound: *const fn (*anyopaque, []const u8) Audio, /// WAV bytes in memory. Not cached. `.none` if they do not decode. decodeSound: *const fn (*anyopaque, []const u8) Audio, /// The whole file, mapped for the life of the host; empty if missing. readFile: *const fn (*anyopaque, []const u8) []const u8, env: *const fn (*anyopaque, []const u8) ?[]const u8, /// A monotonic clock in nanoseconds, for measuring, not for state: /// `update` must use `Input` time to stay replayable. clock: *const fn (*anyopaque) u64, }; pub fn log(h: Host, message: []const u8) void { h.vtable.log(h.ctx, message); } pub fn print(h: Host, comptime fmt: []const u8, args: anytype) void { var buf: [512]u8 = undefined; h.log(std.fmt.bufPrint(&buf, fmt, args) catch "(message too long)"); } pub fn loadImage(h: Host, path: []const u8) Image { return h.vtable.loadImage(h.ctx, path); } pub fn decodeImage(h: Host, png: []const u8) Image { return h.vtable.decodeImage(h.ctx, png); } pub fn newImage(h: Host, w: u32, height: u32) Image { return h.vtable.newImage(h.ctx, w, height); } pub fn freeImage(h: Host, image: Image) void { h.vtable.freeImage(h.ctx, image); } pub fn gpu(h: Host) bool { return h.vtable.gpu(h.ctx); } pub fn imageSize(h: Host, image: Image) [2]u32 { return h.vtable.imageSize(h.ctx, image); } pub fn loadSound(h: Host, path: []const u8) Audio { return h.vtable.loadSound(h.ctx, path); } pub fn decodeSound(h: Host, wav: []const u8) Audio { return h.vtable.decodeSound(h.ctx, wav); } pub fn readFile(h: Host, path: []const u8) []const u8 { return h.vtable.readFile(h.ctx, path); } pub fn env(h: Host, name: []const u8) ?[]const u8 { return h.vtable.env(h.ctx, name); } pub fn clock(h: Host) u64 { return h.vtable.clock(h.ctx); } }; /// What the host passes to every call. pub const Context = struct { host: Host, input: *const Input, /// Frame lifetime: reset after the host consumes the frame. arena: std.mem.Allocator, /// Session lifetime: survives reloads, released when the session resets. gpa: std.mem.Allocator, /// Filled by `draw`, using `arena`. commands: *std.ArrayList(Command), }; /// One leaf of a reflected layout. Nested structs are flattened into dotted /// paths; arrays stay whole. Hosts migrate state across layout changes, and /// inspect or edit it by name, from these. Stored in the state file header. pub const Field = extern struct { path: [*:0]const u8, offset: u32, size: u32, kind: Kind, reserved: [3]u8 = @splat(0), /// Structural hash of the field's type: equal hashes copy byte for byte. hash: u64, /// Enums: "name=value" pairs separated by commas. Empty otherwise. tags: [*:0]const u8 = "", pub const Kind = enum(u8) { int, uint, float, bool, @"enum", array, bytes, _ }; }; pub const Layout = struct { size: usize = 0, alignment: usize = 1, hash: u64 = 0, fields: []const Field = &.{}, }; /// Returned by `sketch_info`. The host copies what it keeps, since a /// sketch's read-only data disappears with the library. pub const Info = struct { /// The sketch's `abi.hash`: a host refuses one that differs from its own. abi: u64, name: []const u8, width: u32, height: u32, state: Layout, session: Layout, /// Console completions offered by the sketch. commands: []const []const u8 = &.{}, }; /// Which memory `sketch_defaults` fills. pub const Memory = enum(u8) { state, session }; /// The entry points of a sketch, exported from libraries under these names. /// What became of a console line offered to a sketch. pub const Outcome = enum(u8) { /// Not one of its commands. unknown, done, /// It returned an error, already printed to the console. failed, }; pub const Sketch = struct { info: *const fn () callconv(.c) *const Info, /// Declared default values, and nothing else. defaults: *const fn (Memory, [*]u8) callconv(.c) void, /// Setup for brand new state, after its defaults. init: *const fn (*const Context, [*]u8) callconv(.c) void, /// Deterministic: new state from state and input, nothing else. update: *const fn (*const Context, [*]u8) callconv(.c) void, /// Presentation: reads state, may change session, appends commands. draw: *const fn (*const Context, [*]const u8, [*]u8) callconv(.c) void, /// A console line the host did not understand; true when handled. command: *const fn (*const Context, [*]u8, [*]u8, *const []const u8) callconv(.c) Outcome, pub const symbols = .{ .info = "sketch_info", .defaults = "sketch_defaults", .init = "sketch_init", .update = "sketch_update", .draw = "sketch_draw", .command = "sketch_command", }; }; /// Layout hash of everything above. Changes whenever a shared type does. pub const hash: u64 = blk: { @setEvalBranchQuota(1_000_000); var h: u64 = 0; for (.{ Rect, Color, Event, Mode, Stream, Input, Image, Audio, Cursor, Voice, Command, gpu.Pass, gpu.Pipeline, gpu.Draw, Host, Host.VTable, Context, Field, Layout, Info, Memory, Sketch }) |T| { h = std.hash.Wyhash.hash(h, @typeName(T) ++ layout.signature(T)); } break :blk h; }; test "vertex attributes and std140 checks come from the types" { const Vertex = extern struct { position: [2]f32, color: [4]u8, uv: [2]f32 }; const attrs = gpu.attributes(Vertex); try std.testing.expectEqual(@as(usize, 3), attrs.len); try std.testing.expectEqual(gpu.Format.ubyte4_norm, attrs[1].format); try std.testing.expectEqual(@as(u32, 12), attrs[2].offset); const Block = extern struct { color: [4]f32, size: [2]f32, pad: [2]f32, stops: [4][4]f32 }; comptime gpu.assertStd140(Block); const p = gpu.pipeline(Vertex, .{ .vertex = .{ .spirv = "" }, .fragment = .{ .spirv = "" } }); try std.testing.expectEqual(@as(u32, 20), p.stride); } test { _ = layout; _ = @import("keys.zig"); }