diff options
Diffstat (limited to 'src/abi.zig')
| -rw-r--r-- | src/abi.zig | 105 |
1 files changed, 89 insertions, 16 deletions
diff --git a/src/abi.zig b/src/abi.zig index 7177f14..6411b0d 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; @@ -114,6 +116,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,6 +165,9 @@ 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. @@ -211,6 +221,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. @@ -296,13 +311,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 }, @@ -365,6 +385,15 @@ 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 @@ -625,12 +654,16 @@ pub const Host = struct { /// 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, @@ -689,12 +722,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); } @@ -714,12 +770,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), }; @@ -768,13 +820,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. @@ -796,8 +858,7 @@ pub const Sketch = struct { 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, @@ -813,8 +874,16 @@ pub const Sketch = struct { }; }; -/// 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, gpu.PostProcess, Host, Host.VTable, Context, Field, Layout, Info, Memory, Sketch }) |T| { @@ -823,6 +892,10 @@ pub const hash: u64 = blk: { 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); |
