diff options
Diffstat (limited to 'src/abi.zig')
| -rw-r--r-- | src/abi.zig | 176 |
1 files changed, 146 insertions, 30 deletions
diff --git a/src/abi.zig b/src/abi.zig index 77a737d..e5fe372 100644 --- a/src/abi.zig +++ b/src/abi.zig @@ -5,11 +5,13 @@ //! 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. +//! - `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; @@ -60,9 +62,15 @@ pub const Color = extern struct { /// 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 }; +/// for what is said about it. Past these ten, a sketch's own fonts +/// (`Host.VTable.font`). The web host draws them in the page's +/// `monospace` and `sans-serif`. +pub const Face = enum(u8) { mono, mono_bold, mono_italic, sans, sans_medium, sans_bold, code, code_bold, code_italic, code_medium, _ }; + +/// A run of text in one face at one scale, measured (`Host.VTable.textRun`): +/// its advance, and its line box (the ascent, the baseline from the top, and +/// the height), in canvas units. +pub const TextRun = struct { width: f32 = 0, ascent: f32 = 0, height: f32 = 0 }; /// How 2D drawing combines with what is already there (`Command.blend`). /// Both are fixed-function on both hosts and match: `alpha` is source @@ -114,6 +122,11 @@ pub const Event = extern struct { /// `flags` bit for a held key's auto-repeat. pub const repeat: u8 = 1; + /// The key of a `key_down` or `key_up`. + pub fn key(e: Event) Key { + return @fromBackingInt(@intCast(@as(u8, @truncate(e.code)))); + } + /// 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 @@ -158,13 +171,17 @@ pub const Stream = struct { queued: u32 = 0, /// Samples pushed since the stream was last cleared. pushed: u64 = 0, + /// Pushes that found it empty though the frame before had pushed to + /// it: each a gap in its sound. + underruns: u32 = 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. + /// 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. @@ -210,6 +227,11 @@ pub const Input = struct { keys: std.StaticBitSet(256) = .empty, streams: []const Stream = &.{}, sample_rate: u32 = 48_000, + /// How many samples a stream should hold after this frame's push, as + /// the host measures it: enough to outlast the slowest recent frame and + /// the device's next pull, and more after an underrun. A sketch that + /// makes its sound as it goes pushes `lead -| stream(key).queued`. + lead: u32 = 4800, /// 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. @@ -295,13 +317,18 @@ pub const Voice = struct { volume: f32 = 1, /// Linear fade at both ends, in samples. fade: u32 = 0, + /// Playback speed, as pitch: 2 is an octave up and half as long, 0 + /// holds it. Changing it does not restart the voice. + rate: f32 = 1, + /// Whose gain (`Command.gain`) also scales it: music, speech, effects. + group: u3 = 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. +/// samples, pixels, uploads) must already live in scratch or session memory, +/// or be a literal. pub const Command = union(enum) { clear: Color, rect: struct { dst: Rect, color: Color }, @@ -364,11 +391,22 @@ pub const Command = union(enum) { voice: Voice, /// Mono samples at `Input.sample_rate` for stream `key`. audio: struct { key: u32, samples: []const f32, clear: bool = false }, + /// `count` mono samples (f32) that a compute shader left in `buffer` + /// at `offset`, for stream `key`: queued like `audio`'s once the GPU + /// has made them. Natively that is within this frame (the host waits + /// for the GPU's work so far); on the web they arrive a frame or two + /// later and count as queued meanwhile. + audio_buffer: struct { key: u32, buffer: Buffer, offset: u32 = 0, count: u32 }, + /// The gain of a group of voices (`Voice.group`) this frame; a group + /// not given one plays at 1. Declared like a voice, so it replays. + gain: struct { group: u3, gain: f32 }, /// 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`). @@ -464,6 +502,8 @@ pub const gpu = struct { 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, @@ -527,6 +567,8 @@ pub const gpu = struct { 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 .{ @@ -537,6 +579,8 @@ pub const gpu = struct { .primitive = p.primitive, .blend = p.blend, .write_color = p.write_color, + .depth_test = p.depth_test, + .depth_write = p.depth_write, .stencil = p.stencil, }; } @@ -564,11 +608,22 @@ pub const gpu = struct { /// 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. @@ -593,22 +648,34 @@ pub const Host = struct { /// 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, + /// What `Command.text` gives the bytes in a face at a scale, as data: + /// a pure function of the font, the scale and the bytes, never of the + /// display. With the last slice (empty, or one a byte), each byte's x + /// from the run's start; a byte inside a cluster has its cluster's. + /// `sketch.text` lays paragraphs out over it. + textRun: *const fn (*anyopaque, Face, f32, []const u8, []f32) TextRun, + /// A face for TTF or OTF bytes, copied: the same face for the same + /// bytes. Null when they are not a font. + font: *const fn (*anyopaque, []const u8) ?Face, /// `.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, + /// Samples a sketch made, copied: see `Host.newSound`. + newSound: *const fn (*anyopaque, [*]const f32, usize) callconv(.c) 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, + /// See `Host.appendFile`: name, then bytes; `replace` for `writeFile`. + appendFile: *const fn (*anyopaque, [*]const u8, usize, [*]const u8, usize, bool) callconv(.c) [*:0]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, @@ -642,20 +709,26 @@ pub const Host = struct { 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. + /// and line height in canvas units, of one line (`sketch.text.size` + /// measures lines, anywhere, `update` too). Advances are whole pixels + /// at the size 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); + const run = h.vtable.textRun(h.ctx, .mono, scale, bytes, &.{}); + return .{ run.width, run.height }; } /// `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); + const run = h.vtable.textRun(h.ctx, face, scale, bytes, &.{}); + return .{ run.width, run.height }; } pub fn loadSound(h: Host, path: []const u8) Audio { return h.vtable.loadSound(h.ctx, path); @@ -663,12 +736,35 @@ pub const Host = struct { pub fn decodeSound(h: Host, wav: []const u8) Audio { return h.vtable.decodeSound(h.ctx, wav); } + /// Mono samples at `Input.sample_rate`, copied into the host: a sound + /// for `Voice.audio` like a loaded one (synthesised one-shots become + /// voices, reconciled and replay-safe). Kept for the life of the host, + /// like every sound: make each once (in `setup`, or cached in Session). + /// `.none` if a sample is not finite. + pub fn newSound(h: Host, sound: []const f32) Audio { + return h.vtable.newSound(h.ctx, sound.ptr, sound.len); + } 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); } + /// Appends `bytes` to the sketch's file `name` (no `/` in it), + /// creating it: `<stem>.<name>`, beside the save `<stem>.xitdb` (in + /// `.sketchbook/` under `zig build run`). Returns the file's path, for + /// `readFile`, or "" when nothing was written, which on the web is + /// always. Only `draw` and `command` can write, and a write is not + /// replayed, like sound. `readFile` maps a file once: what is appended + /// to it afterwards is not in what it returned. + pub fn appendFile(h: Host, name: []const u8, bytes: []const u8) []const u8 { + return std.mem.span(h.vtable.appendFile(h.ctx, name.ptr, name.len, bytes.ptr, bytes.len, false)); + } + /// `appendFile` to a new, empty file of that name: what the old one + /// held is gone (a `readFile` of it keeps its bytes). + pub fn writeFile(h: Host, name: []const u8, bytes: []const u8) []const u8 { + return std.mem.span(h.vtable.appendFile(h.ctx, name.ptr, name.len, bytes.ptr, bytes.len, true)); + } pub fn env(h: Host, name: []const u8) ?[]const u8 { return h.vtable.env(h.ctx, name); } @@ -688,12 +784,8 @@ pub const Context = struct { /// 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. + /// The sketch's `Session` value. session_root: [*]u8, - store_root: [*]u8, /// Filled by `draw`, using `scratch`. commands: *std.ArrayList(Command), }; @@ -742,13 +834,23 @@ pub const Info = struct { height: u32, state: Layout, session: Layout, - store: Layout, /// Console completions offered by the sketch. commands: []const []const u8 = &.{}, + /// What the sketch was built from: its repository's revision ("jj:<commit> + /// <change>", "git:<sha>[+dirty]", or nothing), then `build`. Each + /// stretch of a recorded session keeps it. + source: []const u8 = "", + /// Whether the save keeps history, or only the present and the marks + /// (`App.Options.record`; Debug builds keep it unless told otherwise). + record: bool = false, + /// Samples the sound device takes at once, asked of SDL when the host + /// opens it (`SDL_AUDIO_DEVICE_SAMPLE_FRAMES` in the environment wins); + /// 0 is SDL's own, 1024 at 48 kHz. The app's `audio_pull`. + audio_pull: u32 = 0, }; /// Which memory `sketch_defaults` fills. -pub const Memory = enum(u8) { state, session, store }; +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. @@ -766,10 +868,11 @@ pub const Sketch = struct { 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. + /// Presentation: reads state, may change session, 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, @@ -778,22 +881,35 @@ pub const Sketch = struct { .info = "sketch_info", .defaults = "sketch_defaults", .init = "sketch_init", + .setup = "sketch_setup", .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: { +/// `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, Host, Host.VTable, Context, Field, Layout, Info, Memory, Sketch }) |T| { + for (.{ Rect, Color, Face, TextRun, 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); |
