//! 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 the compiler, backend //! and mode, and a host refuses a sketch built against different //! definitions or by another build instead of misreading its memory. //! //! Only `Event` and the reflected `Layout` are `extern`: they are written to disk. const std = @import("std"); const builtin = @import("builtin"); pub const layout = @import("layout.zig"); pub const Key = @import("keys.zig").Key; /// Bytes read back from a GPU buffer (see `Command.download`). pub const Download = struct { key: u32, bytes: []const u8 }; 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 }; /// `v` in all three channels, opaque: `.gray(127)`. pub fn gray(v: u8) Color { return .{ .r = v, .g = v, .b = v }; } 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 }; } /// `c` with alpha `a` in 0..1, saturating: below 0 (a spent /// lifespan) is transparent, above 1 opaque, NaN transparent. pub fn alphaFloat(c: Color, a: f32) Color { const clamped: f32 = if (a > 0) @min(a, 1) else 0; return c.alpha(@intFromFloat(@round(clamped * 255))); } }; /// The face a text is set in: the Go family, and JetBrains Mono NL (`code`, /// without ligatures; its medium weight for small sizes on a dark ground) /// for programs, all bundled with the native host. Mono is for data, sans /// for what is said about it. The web host has one face, the page's /// `monospace`. pub const Face = enum(u8) { mono, mono_bold, mono_italic, sans, sans_medium, sans_bold, code, code_bold, code_italic, code_medium }; /// How 2D drawing combines with what is already there (`Command.blend`). /// Both are fixed-function on both hosts and match: `alpha` is source /// over (canvas `source-over`, SDL `BLEND`), `add` adds the colour times /// its alpha, and the alphas (canvas `lighter`; natively a custom SDL /// blend mode, since SDL's `ADD` would keep the destination's alpha in a /// transparent target). pub const BlendMode = enum(u8) { alpha, add }; /// Where an image's corners land (`Command.image.corners`): any affine /// placement, rotated, sheared or mirrored. The fourth corner follows. pub const Corners = struct { top_left: [2]f32, top_right: [2]f32, bottom_left: [2]f32, }; /// 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, /// Horizontal wheel delta; appended to preserve recorded event values. wheel_horizontal, _, }; /// `flags` bit for a held key's auto-repeat. pub const repeat: u8 = 1; /// For mouse and wheel events: the modifier keys held as it happened, /// as `Key.Mod` bits. Read this rather than `Input.held`, which is the /// state after the frame's events, and misses modifiers that come with /// no key events at all (a trackpad's pinch is ctrl+wheel). pub fn modifiers(e: Event) u32 { return e.flags >> 4; } /// `flags` for an event with `mods` (`Key.Mod` bits) held. pub fn withModifiers(mods: u32) u8 { return @intCast((mods & 0xf) << 4); } pub fn wheel(e: Event) f32 { return @bitCast(e.value); } /// A frame's tick, `dt` nanoseconds after the previous one. pub fn tick(time: u64, dt: u64) Event { return .{ .kind = .tick, .time = time, .x = @floatCast(@as(f64, @floatFromInt(dt)) / std.time.ns_per_s) }; } /// A tick's `dt` in nanoseconds, from the seconds it records: what /// `Input.dt` is, live and replayed alike (nanoseconds do not survive /// the trip through f32, so live time must come through it too). pub fn tickDt(e: Event) u64 { return @intFromFloat(@round(@max(0, @as(f64, e.x)) * std.time.ns_per_s)); } comptime { std.debug.assert(@sizeOf(Event) == 24); } }; pub const Mode = enum { live, recording, playing, paused }; /// Mouse buttons by `Event.code`. pub const MouseButton = enum(u16) { left = 1, middle = 2, right = 3, _ }; /// 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 { /// In `update`, the frame's tick time (`Event.time`: since the /// recording began while recording or replaying); in `draw`, the host /// clock, or the playback position. Interactive native frames align /// this clock and dt to display refresh when feedback is available. now: u64 = 0, /// In `update`, the frame's tick `dt` (`Event.tickDt`), the same live /// and replayed; in `draw`, likewise for the frame just updated. 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, /// In `draw`: State did not come here by `update` from what the last /// `draw` saw. Set on the first frame, after a seek, step, snapshot /// load, `set`, `reset`, a recording's play or record start, a sketch /// command, and every reload (with `reloaded`). Pictures accumulated /// in Session (a trail in an offscreen image) are stale then: redraw /// them from State. `update` never sees it: it is not input. jumped: 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, /// The host is exporting frames (`--export`): nobody watches or clicks, /// so a player runs through once, without its controls, and quits. exporting: bool = false, /// The canvas. width: f32 = 0, height: f32 = 0, /// The room the host has for the canvas, in the canvas's units at 1:1: /// the window's size (CSS pixels on the web). A sketch that sets its /// canvas to it fills any window, a phone's included, at its own scale. window_width: f32 = 0, window_height: f32 = 0, /// Pointer, buttons and keys follow the events fed, one frame at a time. /// Restoring a snapshot (play, seek, step, load) clears them, and a /// recording begins with events that restore them, so a replay starts /// from the input its recording started from. 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) = .empty, streams: []const Stream = &.{}, sample_rate: u32 = 48_000, /// Mono samples at `sample_rate` recorded since the previous frame, while /// `draw` declares `Command.microphone`. Only `draw` sees them: they come /// from a device, not from events, so they do not replay. microphone: []const f32 = &.{}, /// Finished `Command.download`s, oldest first. Like the microphone, /// only `draw` sees them, and they do not replay. downloads: []const Download = &.{}, /// `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(@backingInt(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 == @backingInt(key) and e.flags & Event.repeat == 0) return true; } return false; } /// Held after this frame's events (`buttons` bit `button - 1`). pub fn mouseHeld(in: *const Input, button: MouseButton) bool { return in.buttons & (@as(u32, 1) << @intCast(@min(@backingInt(button) -| 1, 31))) != 0; } /// The first press of `button` this frame, with its position (`e.x`, /// `e.y`), or null. A sketch that needs every press reads `events`. pub fn mousePressed(in: *const Input, button: MouseButton) ?Event { for (in.events) |e| if (e.kind == .mouse_down and e.code == @backingInt(button)) return e; return null; } /// The first release of `button` this frame, or null. pub fn mouseReleased(in: *const Input, button: MouseButton) ?Event { for (in.events) |e| if (e.kind == .mouse_up and e.code == @backingInt(button)) return e; return null; } 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, .wheel_horizontal => { 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 = .empty; }, 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, _ }; /// GPU memory made by `Host.newBuffer`, filled by `Command.upload` or by /// compute shaders, and read by any shader. Contents stay on the GPU. pub const Buffer = 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. `sketch.Frame` copies the small ones (text, GPU /// descriptions, uniforms) into scratch memory itself; bulk data (vertices, /// samples, pixels, uploads) must already live in scratch, session or store /// memory, or be a literal. pub const Command = union(enum) { clear: Color, rect: struct { dst: Rect, color: Color }, /// Filled regions in one color, described twice over the same /// `points` (canvas coordinates). As subpaths, `points[ends[i - 1] .. /// ends[i]]` (from 0 for the first), which the web fills nonzero, one /// fill per positively wound subpath (clockwise on screen) together /// with the negatively wound ones after it, its holes. And as /// triangles, `indices` into `points` three at a time, which native /// draws with SDL_RenderGeometry. Each such group of subpaths and its /// triangles must cover the same region, the triangles without /// overlapping each other, or translucent colors blend twice natively /// where the web blends once; separate groups that overlap blend /// twice on both. `sketch.draw` makes shapes that keep this contract. /// /// `colors`, when not empty, gives each subpath its own colour /// (`colors[i]` for subpath `i`, `color` past the end), so shapes of /// many colours go in one command: the web fills each group in its /// first subpath's colour, native gives each point its subpath's /// colour, so a group (an outline and its holes) and the triangles /// between them must share one. /// /// Antialiased on both hosts: the web's canvas does it per shape; /// native takes 4x4 samples a pixel (a GPU renderer; without one, /// aliased), on the canvas through a layer that a run of consecutive /// shapes shares, in a target throughout (see `target`). shape: struct { color: Color, points: []const [2]f32, ends: []const u32, indices: []const u32, colors: []const Color = &.{} }, /// `src` empty: the whole image. `tint` multiplies it: colour per /// channel, alpha as a whole. `corners`, when set, places the image /// (any affine: `sketch.Frame.imageAt` centres and turns it) and `dst` /// is unused. Native samples nearest; the web antialiases the edges of /// a turned image. image: struct { image: Image, dst: Rect, src: Rect = .{}, tint: Color = .white, corners: ?Corners = null }, /// Filter the canvas underneath `dst`. Native GPU renderer only; other /// renderers leave the backdrop unchanged. The fragment shader receives /// color at location 0, UV at 1, sampler at set 2/binding 0 and uniforms at set 3. backdrop: struct { dst: Rect, fragment: []const u8, uniforms: []const u8 }, /// Where the 2D commands after it draw: an image made by /// `Host.newImage` (an offscreen target, kept between frames), or /// `.none` for the canvas. Each frame starts on the canvas. Switching /// clears the clip. Images start transparent. Natively a target is /// supersampled whole (4x4) and holds premultiplied colour, so it /// shows the same picture however its commands were split across /// frames, and draws as a canvas would. /// A target is a Session cache, never truth: redraw it when /// `Input.jumped`. target: Image, /// The blend for the 2D commands after it (`rect`, `shape`, `image`; /// `text` and `clear` ignore it). Each frame starts with `alpha`. blend: BlendMode, /// One line from its top left corner; scale 1 is a 13 px font. With /// `raster` (not 0) it is laid out and rasterized at that scale and /// drawn at `scale`: steady under a moving camera, where text shaped /// anew at every size would shift letter against letter. text: struct { x: f32, y: f32, scale: f32, color: Color, bytes: []const u8, face: Face = .mono, raster: f32 = 0 }, 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, /// Fullscreen pass sampling a completed GPU image, into a different image. post_process: struct { source: Image, target: Image, effect: gpu.PostProcess }, /// Bytes into a buffer made by `Host.newBuffer`, at `offset`. upload: struct { buffer: Buffer, offset: u32 = 0, bytes: []const u8 }, /// Runs a compute shader over buffers (see `abi.gpu`). compute: gpu.Dispatch, /// Keeps the default recording device open while declared, like a /// voice; what it hears arrives in `Input.microphone`. microphone, /// Asks the user for a file. The answer arrives later as the console /// line ` `, so it reaches the sketch's `command` (and /// the console log) like anything typed. `pattern` filters by extension: /// "wav;flac;ogg", or empty for any file. open_file: struct { command: []const u8, pattern: []const u8 = "" }, /// Copies `size` bytes of a buffer from `offset` back to the CPU. They /// arrive in `Input.downloads` under `key` once the GPU has got there, /// usually a frame or two later; the frame does not wait. download: struct { buffer: Buffer, offset: u32 = 0, size: u32, key: u32 = 0 }, /// Runs a console line after this frame, as if typed: the way `draw`, /// which cannot write State, hands it something only it learns. run: []const u8, 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 for native hosts and WGSL for the web host; the /// build makes both from GLSL (`addShaders` in build.zig), and a sketch /// passes whichever its build gave it. Resources follow SDL_GPU's SPIR-V /// convention, which the WGSL keeps: 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 { /// SPIR-V, or WGSL on the web. code: []const u8, uniform_buffers: u32 = 0, /// Read-only storage buffers: set 0 in a vertex shader, set 2 in a /// fragment shader. storage_buffers: u32 = 0, }; /// A compute shader. SDL_GPU's SPIR-V sets: read-only buffers in set 0, /// read-write buffers in set 1, uniforms in set 2. pub const Kernel = struct { /// SPIR-V, or WGSL on the web. code: []const u8, readonly_buffers: u32 = 0, readwrite_buffers: u32 = 0, uniform_buffers: u32 = 0, /// The shader's `local_size`. threads: [3]u32 = .{ 64, 1, 1 }, }; /// One run of a kernel, in a compute pass of its own: everything it /// writes is visible to the commands after it. pub const Dispatch = struct { /// Names it in GPU timings (`--profile-gpu`). label: []const u8 = "", kernel: Kernel, readonly: []const Buffer = &.{}, readwrite: []const Buffer = &.{}, /// Uniform slot 0, std140. uniforms: []const u8 = &.{}, groups: [3]u32 = .{ 1, 1, 1 }, }; 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, depth_test: ?Compare = null, depth_write: bool = false, /// 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, /// Empty for a pipeline without attributes, whose vertex shader /// makes its own vertices from `gl_VertexIndex`. vertices: []const u8 = &.{}, vertex_count: u32, stencil_reference: u8 = 0, /// Uniform slot 0 of each stage. vertex_uniforms: []const u8 = &.{}, fragment_uniforms: []const u8 = &.{}, /// Read-only storage buffers of each stage, binding = index. vertex_storage: []const Buffer = &.{}, fragment_storage: []const Buffer = &.{}, 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 s = @typeInfo(V).@"struct"; var out: [s.field_names.len]Attribute = undefined; for (s.field_names, s.field_types, 0..) |name, F, i| out[i] = .{ .location = i, .offset = @offsetOf(V, name), .format = formatOf(F) }; 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, depth_test: ?Compare = null, depth_write: bool = false, 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, .depth_test = p.depth_test, .depth_write = p.depth_write, .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 { /// Names it in GPU timings (`--profile-gpu`). label: []const u8 = "", /// 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, /// Clears depth to 1 each pass; pipelines choose comparison and writes. depth: bool = false, /// Premultiplied; null keeps the image's previous contents. clear: ?[4]f32 = .{ 0, 0, 0, 0 }, pipelines: []const Pipeline, draws: []const Draw, }; /// Fullscreen triangle: color at fragment binding 0, optional depth at 1. pub const PostProcess = struct { /// Requires a preceding single-sample pass with depth enabled. sample_depth: bool = false, vertex: Shader, fragment: Shader, fragment_uniforms: []const u8 = &.{}, }; }; /// 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` and `Command.compute` run here: the host /// has a GPU device. gpu: *const fn (*anyopaque) bool, /// A GPU buffer of `size` bytes, zeroed; `.none` without a GPU. newBuffer: *const fn (*anyopaque, u32) Buffer, freeBuffer: *const fn (*anyopaque, Buffer) void, /// Submits a copy now; source bytes may be released on return. writeBuffer: *const fn (*anyopaque, Buffer, u32, []const u8) anyerror!void, /// Zero while unknown. imageSize: *const fn (*anyopaque, Image) [2]u32, /// What `Command.text` gives the bytes at a scale: the width they /// advance and the height of their line, in canvas units. textSize: *const fn (*anyopaque, f32, []const u8, Face) [2]f32, /// `.none` if the file does not load. loadSound: *const fn (*anyopaque, []const u8) Audio, /// WAV, FLAC or Ogg Vorbis bytes in memory. Not cached. `.none` if /// they do not decode. decodeSound: *const fn (*anyopaque, []const u8) Audio, /// A loaded sound's samples: mono, at `Input.sample_rate`, alive as /// long as the host. Empty for `.none`. samples: *const fn (*anyopaque, Audio) []const f32, /// 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.mem.print(&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 newBuffer(h: Host, size: u32) Buffer { return h.vtable.newBuffer(h.ctx, size); } pub fn freeBuffer(h: Host, buffer: Buffer) void { h.vtable.freeBuffer(h.ctx, buffer); } /// Upload immediately, including during session setup. pub fn writeBuffer(h: Host, buffer: Buffer, offset: u32, bytes: []const u8) !void { try h.vtable.writeBuffer(h.ctx, buffer, offset, bytes); } pub fn imageSize(h: Host, image: Image) [2]u32 { return h.vtable.imageSize(h.ctx, image); } /// The size `f.text(x, y, scale, bytes, ...)` covers from `x, y`: width /// and line height in canvas units, for laying text out (in `draw`: /// `update` gets no host). Native text is shaped and hinted at the size /// it is drawn, so a width is not a multiple of the scale: measure at /// the scale drawn. pub fn textSize(h: Host, scale: f32, bytes: []const u8) [2]f32 { return h.vtable.textSize(h.ctx, scale, bytes, .mono); } /// `textSize` for `f.textIn(face, ...)`. pub fn textSizeIn(h: Host, face: Face, scale: f32, bytes: []const u8) [2]f32 { return h.vtable.textSize(h.ctx, scale, bytes, face); } 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 samples(h: Host, audio: Audio) []const f32 { return h.vtable.samples(h.ctx, audio); } 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: services, input, and memory by /// lifetime, shortest first. pub const Context = struct { host: Host, input: *const Input, /// Frame lifetime: all of it is released after the host consumes the /// frame. scratch: std.mem.Allocator, /// This process: survives reloads; frees one allocation at a time, and /// releases the rest when Session's layout changes. session: std.mem.Allocator, /// On disk, next to the state file: survives reloads and restarts, at /// the same addresses, so Store may point into it. store: std.mem.Allocator, /// The sketch's `Session` and `Store` values. session_root: [*]u8, store_root: [*]u8, /// Filled by `draw`, using `scratch`. commands: *std.ArrayList(Command), }; /// One leaf of a reflected layout. Nested structs are flattened into dotted /// paths, and arrays and vectors into element leaves (`boids[].pos[]`, one /// leaf for all elements, see `dims`). 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, /// How many `[]` the path has: one per array or vector it sits in. rank: u8 = 0, reserved: [2]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 = "", /// `rank` entries, outermost first: element count and byte stride of /// each `[]` in `path`. `offset` is element 0's. dims: [*]const Dim = &[_]Dim{}, /// `array` is a whole array or vector, kept for copying it in one piece /// when its type is unchanged; its elements follow as leaves of their /// own (`list[]`, `list[].x`). pub const Kind = enum(u8) { int, uint, float, bool, @"enum", array, bytes, _ }; pub const Dim = extern struct { count: u32, stride: u32 }; }; 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, store: Layout, /// Console completions offered by the sketch. commands: []const []const u8 = &.{}, }; /// Which memory `sketch_defaults` fills. pub const Memory = enum(u8) { state, session, store }; /// 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, /// Resource setup once per fresh Session; receives no State pointer. setup: *const fn (*const Context) callconv(.c) bool, /// Deterministic: new state from state and input, nothing else. update: *const fn (*const Context, [*]u8) callconv(.c) void, /// Presentation: reads state, may change session and store, appends /// commands. draw: *const fn (*const Context, [*]const u8) callconv(.c) void, /// A console line the host did not understand. command: *const fn (*const Context, [*]u8, *const []const u8) callconv(.c) Outcome, pub const symbols = .{ .info = "sketch_info", .defaults = "sketch_defaults", .init = "sketch_init", .setup = "sketch_setup", .update = "sketch_update", .draw = "sketch_draw", .command = "sketch_command", }; }; /// `layout_hash` and `build`: changes whenever a shared type does, or the /// compiler, backend or optimize mode, since Zig's own calling convention /// (`Host.VTable`, every `std.mem.Allocator`) differs between them. /// `layout_hash` costs half a second of comptime, so build.zig has /// `abi_hash.zig` compute it once per change of these files and hands it /// over as the module `abi_hash`, instead of every sketch's compile doing it. pub const hash: u64 = std.hash.Wyhash.hash(@import("abi_hash").layout, build); /// Hash of every shared type's name and layout. pub const layout_hash: u64 = blk: { @setEvalBranchQuota(1_000_000); var h: u64 = 0; for (.{ Rect, Color, BlendMode, Corners, Event, Mode, Stream, Input, Image, Audio, Cursor, Voice, Command, gpu.Pass, gpu.Pipeline, gpu.Draw, gpu.Dispatch, gpu.PostProcess, Host, Host.VTable, Context, Field, Layout, Info, Memory, Sketch }) |T| { h = std.hash.Wyhash.hash(h, @typeName(T) ++ layout.signature(T)); } break :blk h; }; /// The compiler, backend and mode of this build, exported by libraries as /// `sketch_build` so a host can say why it refuses one. pub const build = builtin.zig_version_string ++ " " ++ @tagName(builtin.zig_backend) ++ " " ++ @tagName(builtin.mode); 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 = .{ .code = "" }, .fragment = .{ .code = "" } }); try std.testing.expectEqual(@as(u32, 20), p.stride); } test { _ = layout; _ = @import("keys.zig"); }