From 2348776791e9dd17afeb12a06ba42a4a71917bcf Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 30 Oct 2026 21:34:41 -0300 Subject: sketchbook: a drawing layer on top, host fixes for replay and migration --- src/abi.zig | 133 +++++- src/host/Console.zig | 26 +- src/host/Host.zig | 120 ++++- src/host/fields.zig | 137 +++++- src/host/gfx.zig | 475 +++++++++++++++++-- src/host/gpu.zig | 74 ++- src/host/gpu.zig.orig | 641 ++++++++++++++++++++++++++ src/host/memory.zig | 482 +++++++++++++++++-- src/host/overlay.zig | 13 +- src/host/probe.zig | 26 +- src/host/root.zig | 16 + src/host/script.zig | 200 +++++++- src/host/timeline.zig | 216 +++++++-- src/layout.zig | 147 +++++- src/math/noise.zig | 157 +++++++ src/math/root.zig | 327 +++++++++++++ src/sketch/clock.zig | 127 +++++ src/sketch/derived.zig | 56 +++ src/sketch/draw.zig | 1024 +++++++++++++++++++++++++++++++++++++++++ src/sketch/list.zig | 109 +++++ src/sketch/root.zig | 102 +++- src/sketch/web.zig | 46 +- src/vector/Cpu.zig | 2 +- src/vector/Drawing.zig | 2 +- src/vector/Gpu.zig | 381 ++++++++++++--- src/vector/Paint.zig | 2 +- src/vector/Polygons.zig | 59 ++- src/vector/geom.zig | 239 ---------- src/vector/layouts.zig | 22 +- src/vector/morph.zig | 2 +- src/vector/root.zig | 15 +- src/vector/shaders/cover.frag | 65 --- src/vector/shaders/paint.frag | 69 +++ src/vector/shaders/paint.vert | 15 + src/vector/svg.zig | 2 +- 35 files changed, 4923 insertions(+), 606 deletions(-) create mode 100644 src/host/gpu.zig.orig create mode 100644 src/math/noise.zig create mode 100644 src/math/root.zig create mode 100644 src/sketch/clock.zig create mode 100644 src/sketch/derived.zig create mode 100644 src/sketch/draw.zig create mode 100644 src/sketch/list.zig delete mode 100644 src/vector/geom.zig delete mode 100644 src/vector/shaders/cover.frag create mode 100644 src/vector/shaders/paint.frag create mode 100644 src/vector/shaders/paint.vert (limited to 'src') diff --git a/src/abi.zig b/src/abi.zig index ca1333e..03e2978 100644 --- a/src/abi.zig +++ b/src/abi.zig @@ -39,12 +39,38 @@ pub const Color = extern struct { 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))); + } +}; + +/// 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 @@ -97,6 +123,17 @@ pub const Event = extern struct { 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); } @@ -104,6 +141,9 @@ pub const Event = extern struct { 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, @@ -115,14 +155,25 @@ pub const Stream = struct { /// 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. now: u64 = 0, - /// Nanoseconds since the previous frame. + /// 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. @@ -137,6 +188,10 @@ pub const Input = struct { /// 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`. @@ -164,6 +219,21 @@ pub const Input = struct { } 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 }; @@ -225,8 +295,49 @@ pub const Voice = struct { 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 }, + /// 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 }, + /// 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, /// Fixed 8px cells, `scale` times larger. text: struct { x: f32, y: f32, scale: f32, color: Color, bytes: []const u8 }, clip: ?Rect, @@ -556,20 +667,30 @@ pub const Context = struct { }; /// One leaf of a reflected layout. Nested structs are flattened into dotted -/// paths; arrays stay whole. Hosts migrate state across layout changes, and +/// 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, - reserved: [3]u8 = @splat(0), + /// 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 { @@ -635,7 +756,7 @@ pub const Sketch = struct { 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, gpu.Dispatch, Host, Host.VTable, Context, Field, Layout, Info, Memory, Sketch }) |T| { + 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| { h = std.hash.Wyhash.hash(h, @typeName(T) ++ layout.signature(T)); } break :blk h; diff --git a/src/host/Console.zig b/src/host/Console.zig index b22facb..40845f7 100644 --- a/src/host/Console.zig +++ b/src/host/Console.zig @@ -133,7 +133,7 @@ pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const const rest = words.rest(); if (eq(command, "help")) { - self.log("save|load [1..7] snapshot N | record|play [0..15] recording N | stop | pause | step N | seek start|end|"); + self.log("save|load [1..7] snapshot N | record|play [0..15] recording N | stop | pause | step N (frames) | seek start|end|"); self.log("diff [N] | reset | get | set | overlay memory|sound | quit"); if (host.forward(self, line, now) == .unknown) self.log("Backtick hides the console. Tab completes."); return &.{}; @@ -145,10 +145,12 @@ pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const self.print("{s} overlay: {s}", .{ name, if (flag.*) "on" else "off" }); } else if (eq(command, "get")) { const path = arg orelse return error.ExpectedField; - const leaf = host.state.layout.find(path) orelse return error.UnknownField; var buf: [160]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); - fields.format(leaf, host.live(), &w) catch {}; + fields.formatPath(host.state.layout, host.live(), path, &w) catch |err| switch (err) { + error.UnknownField => return error.UnknownField, + error.WriteFailed => {}, // shown cut off + }; self.print("{s} = {s}", .{ path, w.buffered() }); } else if (eq(command, "set")) { const path = arg orelse return error.ExpectedField; @@ -176,16 +178,17 @@ pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const h.bank.save(index); self.print("Saved snapshot {d}. Recordings from its old contents are invalidated.", .{index}); } else { - try h.bank.restore(index); + try h.restore(index); self.print("Loaded snapshot {d}.", .{index}); } } else if (eq(command, "record") or eq(command, "play")) { const index = if (arg) |a| try slot(a, 0, timeline.recording_count - 1) else self.recording; if (eq(command, "play")) _ = try h.bank.get(index); h.stop(now); - if (eq(command, "record")) try h.startRecording(index, self.snapshot, now) else try h.play(index, now); + if (eq(command, "record")) try h.startRecording(index, self.snapshot, now, host.build) else try h.play(index, now); self.recording = index; self.print("{s} recording {d} from snapshot {d}.", .{ if (eq(command, "record")) "Started" else "Playing", index, h.bank.recording(index).snapshot }); + if (eq(command, "play")) self.warnBuild(host, h.bank.recording(index)); } else if (eq(command, "stop")) { h.stop(now); } else if (eq(command, "pause")) { @@ -197,6 +200,7 @@ pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const if (h.mode == .recording) h.stop(now); if (h.mode == .live) try h.play(self.recording, now); const r = try h.bank.get(h.selected); + if (h.mode == .playing and h.cursor == 0) self.warnBuild(host, r); if (eq(command, "step")) return h.step(std.fmt.parseInt(i64, value, 10) catch return error.InvalidPosition); if (eq(value, "start")) return h.seekCount(0); if (eq(value, "end")) return h.seekCount(r.count); @@ -206,7 +210,12 @@ pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const const index = if (arg) |a| try slot(a, 1, memory.slot_count - 1) else self.snapshot; if (!h.bank.hasSnapshot(index)) return error.EmptySnapshot; const diff = h.bank.compare(0, index); - self.print("Live vs snapshot {d}: {d} differing bytes; first={any}, last={any}", .{ index, diff.count, diff.first, diff.last }); + if (diff.first) |first| { + var buf: [96]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + first.leaf.name(first.offset, &w) catch {}; + self.print("Live vs snapshot {d}: {d} differing values, first {s}", .{ index, diff.count, w.buffered() }); + } else self.print("Live vs snapshot {d}: same", .{index}); } else { // Sketch commands edit state outside the recorded input. h.stop(now); @@ -237,6 +246,11 @@ pub fn draw(self: *const Console, host: *Host, out: *std.ArrayList(abi.Command), try out.append(arena, .{ .rect = .{ .dst = .{ .x = @floatFromInt(28 + self.cursor * 8), .y = top + 120, .w = 1, .h = 12 }, .color = hint } }); } +/// A replay of a recording made by other code may diverge: say so. +fn warnBuild(self: *Console, host: *const Host, r: *const timeline.Recording) void { + if (r.build() != 0 and host.build != 0 and r.build() != host.build) self.log("Warning: recorded by another build of the sketch; the replay may differ."); +} + fn eq(a: []const u8, b: []const u8) bool { return std.mem.eql(u8, a, b); } diff --git a/src/host/Host.zig b/src/host/Host.zig index 7ebe54a..de19b99 100644 --- a/src/host/Host.zig +++ b/src/host/Host.zig @@ -6,8 +6,9 @@ const std = @import("std"); const c = @import("c"); const abi = @import("abi"); const memory = @import("memory.zig"); -const Timeline = @import("timeline.zig").Timeline; -const mapRecordings = @import("timeline.zig").mapRecordings; +const playback = @import("timeline.zig"); +const Timeline = playback.Timeline; +const mapRecordings = playback.mapRecordings; const gfx = @import("gfx.zig"); const sound = @import("audio.zig"); const Gpu = @import("gpu.zig"); @@ -44,6 +45,8 @@ passes: ?Gpu = null, offscreen: ?*c.SDL_Texture = null, pointer_cursor: ?*c.SDL_Cursor = null, images: gfx.Images, +/// Plays the 2D commands: targets, blend, antialiased shapes. +painter: gfx.Painter, audio: sound.Audio, state: memory.StateFile, session: memory.Session, @@ -58,6 +61,9 @@ sketch: abi.Sketch, library: ?Library = null, watch: ?Watch = null, reloads: usize = 0, +/// Identifies the running build of the sketch (a hash of its library or +/// executable file): recordings carry it, and `play` warns on a mismatch. +build: u64 = 0, /// Copies of the sketch's info strings, replaced on every load. info_arena: std.heap.ArenaAllocator, name: []const u8 = "", @@ -73,6 +79,9 @@ canvas: [2]u32 = .{ 0, 0 }, cursor: abi.Cursor = .arrow, quit: bool = false, reloaded: bool = true, +/// For `Input.jumped`: state changed other than by `update` since the +/// last `draw` (a seek, a load, a `set`...). The first frame is one. +jumped: bool = true, started: bool = true, last_now: u64 = 0, /// Saved after the next frame is drawn (scripts). @@ -115,8 +124,10 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std std.log.warn("no GPU renderer ({s}); drawing without one", .{c.SDL_GetError()}); renderer = c.SDL_CreateRenderer(window, null) orelse return sdlError("SDL_CreateRenderer"); } - errdefer c.SDL_DestroyRenderer(renderer); + // Deferred in reverse: the renderer goes first, then the device it + // draws through (the other order crashed in SDL_DestroyRenderer). errdefer if (gpu) |device| c.SDL_DestroyGPUDevice(device); + errdefer c.SDL_DestroyRenderer(renderer); if (!options.headless) _ = c.SDL_SetRenderVSync(renderer, 1); // Colors carry alpha: fills blend, as they do on the web. _ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_BLEND); @@ -142,6 +153,7 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std .renderer = renderer.?, .gpu = gpu, .images = .{ .gpa = gpa, .renderer = renderer.? }, + .painter = .{ .renderer = renderer.?, .images = undefined, .smooth = gpu != null }, .audio = .{ .gpa = gpa }, .state = state, .session = .init(gpa), @@ -154,6 +166,7 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std .frame_arena = .init(gpa), }; self.timeline = .{ .bank = .{ .state = &self.state, .inputs = recordings } }; + self.painter.images = &self.images; if (gpu) |device| self.passes = .init(gpa, device); if (options.profile_gpu) if (self.passes) |*g| { g.profile = .init(gpa); @@ -164,6 +177,7 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std }; self.setCanvas(info.width, info.height); _ = c.SDL_StartTextInput(self.window); + self.build = fileHash(options.library orelse "/proc/self/exe"); try self.adopt(sketch); if (options.fresh) { self.state.header().used = 0; @@ -177,6 +191,7 @@ pub fn deinit(self: *Host) void { if (self.watch) |w| w.deinit(); self.audio.deinit(); if (self.passes) |*g| g.deinit(&self.images); + self.painter.deinit(); self.images.deinit(); if (self.pointer_cursor) |cursor| c.SDL_DestroyCursor(cursor); if (self.offscreen) |texture| c.SDL_DestroyTexture(texture); @@ -229,10 +244,10 @@ pub fn frame(self: *Host, now: u64) !void { .playing => self.update(h.tick(now)), .paused => {}, .live, .recording => { - try self.pending.append(self.gpa, .{ .kind = .tick, .time = now, .x = @floatCast(@as(f64, @floatFromInt(dt)) / std.time.ns_per_s) }); - for (self.pending.items) |e| h.capture(e) catch |err| self.print("Recording stopped: {t}", .{err}); - self.input.now = now; - self.input.dt = dt; + // One frame: what was routed since the last one, then its tick. + // Recorded first, so `update` sees the times a replay will. + try self.pending.append(self.gpa, abi.Event.tick(now, dt)); + h.capture(self.pending.items) catch |err| self.print("Recording stopped: {t}", .{err}); self.update(self.pending.items); }, } @@ -240,26 +255,60 @@ pub fn frame(self: *Host, now: u64) !void { try self.draw(if (h.mode == .live or h.mode == .recording) now else h.position); } -/// Feeds events to the sketch's deterministic `update`. +/// Feeds whole frames to the sketch's deterministic `update`, one call per +/// frame (events up to and including a tick), live or replayed alike. pub fn update(self: *Host, events: []const abi.Event) void { - // Input follows the events actually fed, live or replayed. - for (events) |e| self.input.track(e); - if (events.len > 0 and self.timeline.mode != .live and self.timeline.mode != .recording) self.input.now = events[events.len - 1].time; - self.input.events = events; - self.input.mode = self.timeline.mode; - self.input.started = self.started; - self.started = false; - const ctx = self.context(); - self.sketch.update(&ctx, self.live().ptr); + var frames = playback.frames(events); + while (frames.next()) |one| { + // Input follows the events actually fed, frame by frame. + for (one) |e| self.input.track(e); + const tick = one[one.len - 1]; + self.input.now = tick.time; + self.input.dt = tick.tickDt(); + self.input.events = one; + self.input.mode = self.timeline.mode; + self.input.started = self.started; + self.started = false; + const ctx = self.context(); + self.sketch.update(&ctx, self.live().ptr); + } self.input.events = &.{}; } +/// After live state was restored from a snapshot: the pointer, buttons and +/// keys tracked so far belong to other bytes, so they start over. A new +/// recording then begins with events that bring back what is held now, so +/// its replay starts from the same input (they are fed and recorded as the +/// first frame's first events). +fn restoredInput(self: *Host, now: u64) !void { + const h = &self.timeline; + if (!h.restored) return; + h.restored = false; + const was = self.input; + self.input.mouse_x = 0; + self.input.mouse_y = 0; + self.input.buttons = 0; + self.input.keys = .empty; + if (h.mode != .recording or h.bank.recording(h.selected).count != 0) return; + var seed: std.ArrayList(abi.Event) = .empty; + defer seed.deinit(self.gpa); + if (was.mouse_x != 0 or was.mouse_y != 0) try seed.append(self.gpa, .{ .kind = .mouse_move, .time = now, .x = was.mouse_x, .y = was.mouse_y }); + for (0..32) |bit| if (was.buttons & (@as(u32, 1) << @intCast(bit)) != 0) { + try seed.append(self.gpa, .{ .kind = .mouse_down, .time = now, .x = was.mouse_x, .y = was.mouse_y, .code = @intCast(bit + 1) }); + }; + var keys = was.keys.iterator(.{}); + while (keys.next()) |key| try seed.append(self.gpa, .{ .kind = .key_down, .time = now, .code = @intCast(key) }); + try self.pending.insertSlice(self.gpa, 0, seed.items); +} + fn draw(self: *Host, now: u64) !void { const arena = self.frame_arena.allocator(); self.input.now = now; self.input.mode = self.timeline.mode; self.input.reloaded = self.reloaded; + self.input.jumped = self.jumped or self.reloaded; self.reloaded = false; + self.jumped = false; self.input.console = self.console.visible; self.input.width = @floatFromInt(self.canvas[0]); self.input.height = @floatFromInt(self.canvas[1]); @@ -286,9 +335,14 @@ fn draw(self: *Host, now: u64) !void { _ = c.SDL_SetRenderDrawColor(self.renderer, 0, 0, 0, 255); _ = c.SDL_RenderClear(self.renderer); self.audio.beginFrame(); + self.painter.begin(self.offscreen, self.canvas, arena); var lines: std.ArrayList([]const u8) = .empty; for (self.commands.items) |command| switch (command) { - .canvas => |size| self.setCanvas(size.w, size.h), + .canvas => |size| { + self.painter.end(); + self.setCanvas(size.w, size.h); + self.painter.begin(self.offscreen, self.canvas, arena); + }, .cursor => |kind| self.cursor = kind, .voice => |voice| self.audio.declare(voice), .audio => |a| self.audio.push(a.key, a.samples, a.clear), @@ -300,11 +354,11 @@ fn draw(self: *Host, now: u64) !void { .download => |d| if (self.passes) |*g| g.download(d) catch |err| self.print("gpu download: {t} ({s})", .{ err, c.SDL_GetError() }), .open_file => |o| self.openFile(o.command, o.pattern), .run => |line| try lines.append(arena, line), - else => gfx.draw(self.renderer, &self.images, command), + else => self.painter.draw(command), }; + self.painter.end(); self.audio.endFrame(); for (lines.items) |line| self.runLine(line, now) catch {}; - _ = c.SDL_SetRenderClipRect(self.renderer, null); var extra: std.ArrayList(abi.Command) = .empty; if (self.console.overlay_memory) try overlay.drawMemory(&extra, arena, self.state.layout, self.live(), self.input.width); @@ -313,7 +367,8 @@ fn draw(self: *Host, now: u64) !void { try overlay.drawScope(&extra, arena, &samples, self.audio.scope.rate, self.canvas); } if (self.console.visible) try self.console.draw(self, &extra, arena); - for (extra.items) |command| gfx.draw(self.renderer, &self.images, command); + for (extra.items) |command| self.painter.draw(command); + self.painter.end(); self.applyCursor(); if (self.screenshot) |path| { @@ -432,11 +487,25 @@ pub fn runLine(self: *Host, line: []const u8, now: u64) !void { const replay = self.console.execute(self, line, now) catch |err| { // The sketch has printed its own error already. if (err != error.CommandFailed) self.console.print("{t}. Type help for usage.", .{err}); + if (self.timeline.restored) self.jumped = true; + try self.restoredInput(now); return err; }; + if (self.timeline.restored or movesState(line)) self.jumped = true; + try self.restoredInput(now); if (self.timeline.mode == .paused) self.update(replay); } +/// Whether a console line that succeeded may have changed State other than +/// through `update` (restoring a snapshot is caught apart from this). +fn movesState(line: []const u8) bool { + var words = std.mem.tokenizeAny(u8, line, " \t"); + const verb = words.next() orelse return false; + const still = [_][]const u8{ "help", "overlay", "get", "snapshot", "recording", "diff", "stop", "pause", "save", "quit", "exit" }; + for (still) |w| if (std.mem.eql(u8, verb, w)) return false; + return true; +} + /// Offers a line to the sketch. pub fn forward(self: *Host, _: *Console, line: []const u8, now: u64) abi.Outcome { self.input.now = now; @@ -467,6 +536,7 @@ pub fn load(self: *Host, path: []const u8) !void { if (self.library) |*old| old.close(); self.library = library; self.reloads += 1; + self.build = fileHash(path); self.print("reload {d}: {s}", .{ self.reloads, path }); } @@ -636,6 +706,14 @@ fn consoleKey(e: abi.Event) ?Console.Key { }; } +/// A hash of a file's bytes; 0 when it cannot be read. +fn fileHash(path: []const u8) u64 { + const bytes = memory.mapReadOnly(path); + if (bytes.len == 0) return 0; + defer std.posix.munmap(bytes); + return std.hash.Wyhash.hash(0, bytes) | 1; +} + fn scratchDir(environ: *const std.process.Environ.Map) []const u8 { return environ.get("XDG_RUNTIME_DIR") orelse "/tmp"; } diff --git a/src/host/fields.zig b/src/host/fields.zig index ba8fc03..2e70414 100644 --- a/src/host/fields.zig +++ b/src/host/fields.zig @@ -2,7 +2,82 @@ //! Shared by the console, the memory overlay, scripts and the probe. const std = @import("std"); const abi = @import("abi"); -const Leaf = @import("memory.zig").Layout.Leaf; +const Layout = @import("memory.zig").Layout; +const Leaf = Layout.Leaf; + +/// Writes what `path` names: one value for a number, bool or enum leaf, +/// or every leaf under it for an array, a vector or a struct, in memory +/// order (for a Zig struct not always the declared one): `{ 250, 3 }` +/// when they are its elements, otherwise `{ .count = 12, .hz = 60 }` or +/// `{ [0].x = 1, [1].x = 2 }`. +/// Shows the first `max_values`, then how many more there are. +pub fn formatPath(layout: Layout, memory: []const u8, path: []const u8, w: *std.Io.Writer) (std.Io.Writer.Error || error{UnknownField})!void { + if (layout.find(path)) |leaf| if (!leaf.whole()) return format(leaf, memory, w); + // Names under `path`, found leaf by leaf; sorted by offset afterwards. + const Found = struct { offset: usize, leaf: Leaf }; + var found: [max_values]Found = undefined; + var count: usize = 0; + var total: usize = 0; + var plain = true; + var name_buf: [256]u8 = undefined; + for (layout.fields) |leaf| { + if (leaf.whole()) continue; + var it = leaf.elements(); + while (it.next()) |offset| { + var nw: std.Io.Writer = .fixed(&name_buf); + leaf.name(offset, &nw) catch continue; + const name = nw.buffered(); + if (!under(name, path)) continue; + total += 1; + if (!isIndex(name[path.len..])) plain = false; + if (count < max_values) { + found[count] = .{ .offset = offset, .leaf = leaf }; + count += 1; + } else { + // Keep the lowest offsets. + var highest: usize = 0; + for (found[1..], 1..) |f, i| if (f.offset > found[highest].offset) { + highest = i; + }; + if (offset < found[highest].offset) found[highest] = .{ .offset = offset, .leaf = leaf }; + } + } + } + if (total == 0) return error.UnknownField; + std.mem.sortUnstable(Found, found[0..count], {}, struct { + fn less(_: void, a: Found, b: Found) bool { + return a.offset < b.offset; + } + }.less); + try w.writeAll("{ "); + for (found[0..count], 0..) |f, i| { + if (i > 0) try w.writeAll(", "); + if (!plain) { + var nw: std.Io.Writer = .fixed(&name_buf); + f.leaf.name(f.offset, &nw) catch {}; + try w.print("{s} = ", .{nw.buffered()[path.len..]}); + } + try format(f.leaf.at(f.offset), memory, w); + } + if (total > count) try w.print(", ... {d} more", .{total - count}); + try w.writeAll(" }"); +} + +pub const max_values = 64; + +/// `name` is `path` itself or a field or element inside it. +fn under(name: []const u8, path: []const u8) bool { + if (!std.mem.startsWith(u8, name, path)) return false; + if (name.len == path.len) return true; + return name[path.len] == '.' or name[path.len] == '['; +} + +/// `[3]`: one index and nothing more. +fn isIndex(suffix: []const u8) bool { + if (suffix.len < 3 or suffix[0] != '[' or suffix[suffix.len - 1] != ']') return false; + for (suffix[1 .. suffix.len - 1]) |ch| if (!std.ascii.isDigit(ch)) return false; + return true; +} pub fn format(leaf: Leaf, memory: []const u8, w: *std.Io.Writer) std.Io.Writer.Error!void { const bytes = leaf.bytes(memory); @@ -64,6 +139,22 @@ pub fn matches(leaf: Leaf, memory: []const u8, text: []const u8) bool { return false; } +/// A number, bool or enum leaf's value as a float; null for other kinds. +pub fn number(leaf: Leaf, memory: []const u8) ?f64 { + const bytes = leaf.bytes(memory); + return switch (leaf.kind) { + .int, .@"enum" => @floatFromInt(readInt(i64, bytes)), + .uint => @floatFromInt(readInt(u64, bytes)), + .bool => if (bytes[0] != 0) 1 else 0, + .float => switch (leaf.size) { + 4 => @as(f32, @bitCast(bytes[0..4].*)), + 8 => @as(f64, @bitCast(bytes[0..8].*)), + else => null, + }, + else => null, + }; +} + pub fn readInt(comptime T: type, bytes: []const u8) T { const n: usize = @min(bytes.len, 8); const value = std.mem.readVarInt(u64, bytes[0..n], .little); @@ -114,3 +205,47 @@ test "fields format, parse and compare by kind" { try std.testing.expect(s.on); try std.testing.expectError(error.InvalidValue, set(layout.find("x").?, bytes, "banana")); } + +test "indexed paths reach array elements and vector lanes" { + const S = struct { pos: @Vector(2, f32) = .{ 250, 3 }, boids: struct { buffer: [4]struct { pos: [2]f32 = .{ 0, 0 }, mood: enum(u8) { calm = 1, wild = 2 } = .calm } = @splat(.{}), len: u32 = 0 } = .{} }; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const layout = try @import("memory.zig").Layout.copy(arena.allocator(), abi.layout.of(S, .state)); + var s: S = .{}; + const bytes = std.mem.asBytes(&s); + try std.testing.expect(matches(layout.find("pos[0]").?, bytes, "250")); + try std.testing.expectEqual(@as(?f64, 3), number(layout.find("pos[1]").?, bytes)); + try set(layout.find("boids.buffer[3].pos[1]").?, bytes, "20.5"); + try std.testing.expectEqual(@as(f32, 20.5), s.boids.buffer[3].pos[1]); + try set(layout.find("boids.buffer[2].mood").?, bytes, "wild"); + try std.testing.expectEqual(.wild, s.boids.buffer[2].mood); + try std.testing.expect(layout.find("boids.buffer[4].mood") == null); + try std.testing.expect(layout.find("pos[2]") == null); +} + +test "paths to vectors, arrays and structs print every value under them" { + const S = struct { pos: @Vector(2, f32) = .{ 250, 3 }, clock: struct { hz: f32 = 60, count: u64 = 12 } = .{}, list: struct { buffer: [3]struct { x: i32 = 1, on: bool = true } = @splat(.{}), len: u32 = 2 } = .{}, big: [100]u8 = @splat(7) }; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const layout = try Layout.copy(arena.allocator(), abi.layout.of(S, .state)); + var s: S = .{}; + s.list.buffer[1].x = -4; + const bytes = std.mem.asBytes(&s); + var buf: [1024]u8 = undefined; + const cases = [_][2][]const u8{ + .{ "pos", "{ 250, 3 }" }, + .{ "pos[1]", "3" }, + .{ "clock", "{ .count = 12, .hz = 60 }" }, // memory order + .{ "list.buffer[1]", "{ .x = -4, .on = true }" }, + .{ "list.buffer", "{ [0].x = 1, [0].on = true, [1].x = -4, [1].on = true, [2].x = 1, [2].on = true }" }, + }; + for (cases) |case| { + var w: std.Io.Writer = .fixed(&buf); + try formatPath(layout, bytes, case[0], &w); + try std.testing.expectEqualStrings(case[1], w.buffered()); + } + var w: std.Io.Writer = .fixed(&buf); + try formatPath(layout, bytes, "big", &w); + try std.testing.expect(std.mem.endsWith(u8, w.buffered(), "7, 7, ... 36 more }")); + try std.testing.expectError(error.UnknownField, formatPath(layout, bytes, "po", &w)); +} diff --git a/src/host/gfx.zig b/src/host/gfx.zig index 16148a6..20b4dcc 100644 --- a/src/host/gfx.zig +++ b/src/host/gfx.zig @@ -14,10 +14,29 @@ pub const Images = struct { texture: ?*c.SDL_Texture = null, w: u32 = 0, h: u32 = 0, + /// Holds premultiplied colour: a target drawn into, a GPU pass's + /// output, or premultiplied `pixels`. + premultiplied: bool = false, + /// Made by `new`: a render target for `Command.target`. + target: bool = false, + /// Scales smoothly (GPU pass output), not nearest. + smooth: bool = false, + /// A target's supersampled self (`factor` times the size), which + /// 2D commands draw into; `texture` is its average, brought up to + /// date (`stale`) before the image is drawn. + big: ?*c.SDL_Texture = null, + factor: u32 = 1, + stale: bool = false, + + fn release(entry: *Entry) void { + if (entry.texture) |t| c.SDL_DestroyTexture(t); + if (entry.big) |t| c.SDL_DestroyTexture(t); + entry.* = .{}; + } }; pub fn deinit(self: *Images) void { - for (self.entries.items) |entry| if (entry.texture) |t| c.SDL_DestroyTexture(t); + for (self.entries.items) |*entry| entry.release(); self.entries.deinit(self.gpa); var keys = self.paths.keyIterator(); while (keys.next()) |key| self.gpa.free(key.*); @@ -41,10 +60,20 @@ pub const Images = struct { return self.add(c.SDL_LoadPNG_IO(io, true)); } + /// A blank (transparent) image, which `Command.pixels` fills and + /// `Command.target` draws into: a render target, cleared now, since a + /// new SDL texture's contents are undefined (a canvas starts clear). pub fn new(self: *Images, w: u32, h: u32) abi.Image { - const texture = c.SDL_CreateTexture(self.renderer, c.SDL_PIXELFORMAT_RGBA32, c.SDL_TEXTUREACCESS_STREAMING, @intCast(w), @intCast(h)); - if (texture) |t| setup(t); - return self.append(.{ .texture = texture, .w = w, .h = h }); + const texture = c.SDL_CreateTexture(self.renderer, c.SDL_PIXELFORMAT_RGBA32, c.SDL_TEXTUREACCESS_TARGET, @intCast(w), @intCast(h)); + if (texture) |t| { + setup(t); + const previous = c.SDL_GetRenderTarget(self.renderer); + _ = c.SDL_SetRenderTarget(self.renderer, t); + _ = c.SDL_SetRenderDrawColor(self.renderer, 0, 0, 0, 0); + _ = c.SDL_RenderClear(self.renderer); + _ = c.SDL_SetRenderTarget(self.renderer, previous); + } + return self.append(.{ .texture = texture, .w = w, .h = h, .premultiplied = true, .target = texture != null }); } /// Makes `image` show a GPU render target (GPU renderer only). @@ -59,9 +88,8 @@ pub const Images = struct { const texture = c.SDL_CreateTextureWithProperties(self.renderer, props) orelse return error.WrapTexture; // Rendered output: smooth scaling, and already premultiplied. _ = c.SDL_SetTextureScaleMode(texture, c.SDL_SCALEMODE_LINEAR); - _ = c.SDL_SetTextureBlendMode(texture, c.SDL_BLENDMODE_BLEND_PREMULTIPLIED); - if (entry.texture) |old| c.SDL_DestroyTexture(old); - entry.* = .{ .texture = texture, .w = w, .h = h }; + entry.release(); + entry.* = .{ .texture = texture, .w = w, .h = h, .premultiplied = true, .smooth = true }; } /// Stops showing a wrapped render target, before the target goes away. @@ -73,8 +101,7 @@ pub const Images = struct { pub fn free(self: *Images, image: abi.Image) void { const entry = self.get(image) orelse return; - if (entry.texture) |t| c.SDL_DestroyTexture(t); - entry.* = .{}; + entry.release(); } pub fn size(self: *Images, image: abi.Image) [2]u32 { @@ -104,47 +131,397 @@ pub const Images = struct { fn setup(texture: *c.SDL_Texture) void { _ = c.SDL_SetTextureScaleMode(texture, c.SDL_SCALEMODE_NEAREST); - _ = c.SDL_SetTextureBlendMode(texture, c.SDL_BLENDMODE_BLEND); } }; -/// Draws one graphics command. Other commands are not graphics: ignored. -pub fn draw(renderer: *c.SDL_Renderer, images: *Images, command: abi.Command) void { - switch (command) { - .clear => |color| { - if (@import("builtin").os.tag == .linux) c.sk_text_begin_frame(renderer); - setColor(renderer, color); - _ = c.SDL_RenderClear(renderer); - }, - .rect => |r| { - setColor(renderer, r.color); - _ = c.SDL_RenderFillRect(renderer, &frect(r.dst)); - }, - .image => |img| { - const entry = images.get(img.image); - const texture = if (entry) |e| e.texture else null; - const t = texture orelse return missing(renderer, img.dst); - _ = c.SDL_SetTextureColorMod(t, img.tint.r, img.tint.g, img.tint.b); - _ = c.SDL_SetTextureAlphaMod(t, img.tint.a); - const src = frect(img.src); - _ = c.SDL_RenderTexture(renderer, t, if (img.src.w > 0) &src else null, &frect(img.dst)); - }, - .text => |text| drawText(renderer, text.x, text.y, text.scale, text.bytes, text.color), - .clip => |clip| { - if (clip) |r| { - const rect: c.SDL_Rect = .{ .x = @intFromFloat(r.x), .y = @intFromFloat(r.y), .w = @intFromFloat(r.w), .h = @intFromFloat(r.h) }; - _ = c.SDL_SetRenderClipRect(renderer, &rect); - } else _ = c.SDL_SetRenderClipRect(renderer, null); - }, - .pixels => |p| { - const entry = images.get(p.image) orelse return; - const texture = entry.texture orelse return; - if (p.w != entry.w or p.h != entry.h or p.rgba.len < @as(usize, p.w) * p.h * 4) return; - _ = c.SDL_SetTextureBlendMode(texture, if (p.premultiplied) c.SDL_BLENDMODE_BLEND_PREMULTIPLIED else c.SDL_BLENDMODE_BLEND); - _ = c.SDL_UpdateTexture(texture, null, p.rgba.ptr, @intCast(p.w * 4)); - }, - else => {}, +/// Plays 2D commands into the renderer, keeping what they leave behind +/// (target, blend) and the antialiasing textures. One per host; `begin` +/// and `end` bracket a frame. +/// +/// Antialiasing (with a GPU renderer) is supersampling, 4x4 samples a +/// pixel, averaged by halving twice (bilinear sampling at the centre of a +/// 2x2 block is their exact mean), so coverage resolves per sample: +/// - On the canvas, consecutive shapes are drawn into `layer` and +/// composited together, premultiplied, when another command comes. +/// - A target is supersampled whole (`Entry.big`): everything drawn into +/// it is, and it is averaged when drawn. Its picture is therefore the +/// same however its commands were split into frames, so a trail +/// repainted at once after a seek equals the one painted step by step. +pub const Painter = struct { + renderer: *c.SDL_Renderer, + images: *Images, + /// The canvas's render target: null for the window, or the headless + /// host's offscreen texture. + canvas: ?*c.SDL_Texture = null, + canvas_size: [2]u32 = .{ 0, 0 }, + /// Antialias (a GPU renderer); false draws everything aliased. + smooth: bool = false, + /// Per-vertex colours, for one frame. + arena: std.mem.Allocator = undefined, + target: abi.Image = .none, + blend: abi.BlendMode = .alpha, + layer: Layer = .{}, + /// Half-way through averaging (2x), shared; `half_size` in its pixels. + half: ?*c.SDL_Texture = null, + half_size: [2]u32 = .{ 0, 0 }, + + const Layer = struct { + big: ?*c.SDL_Texture = null, + /// Room in `big`, in its pixels. + w: u32 = 0, + h: u32 = 0, + /// Open: shapes went into it since the last composite. + open: bool = false, + blend: abi.BlendMode = .alpha, + factor: u32 = 4, + /// What the open layer's shapes cover, in canvas pixels (x0, y0, + /// x1, y1); after a composite, what still holds them, cleared + /// when the next layer opens. + dirty: [4]u32 = .{ 0, 0, 0, 0 }, + }; + + /// 16 samples a pixel, unless that takes more than 16 Mi of them; 4, + /// then; else none. + const max_samples = 16 << 20; + + fn factorFor(size: [2]u32) u32 { + const pixels = @as(u64, size[0]) * size[1]; + return if (pixels * 16 <= max_samples) 4 else if (pixels * 4 <= max_samples) 2 else 1; + } + + pub fn deinit(p: *Painter) void { + if (p.layer.big) |t| c.SDL_DestroyTexture(t); + if (p.half) |t| c.SDL_DestroyTexture(t); + p.layer = .{}; + p.half = null; + p.half_size = .{ 0, 0 }; + } + + pub fn begin(p: *Painter, canvas: ?*c.SDL_Texture, size: [2]u32, arena: std.mem.Allocator) void { + p.canvas = canvas; + p.canvas_size = size; + p.arena = arena; + p.target = .none; + p.blend = .alpha; + } + + /// Back to the canvas, blending alpha, unclipped: where overlays draw + /// and screenshots read. + pub fn end(p: *Painter) void { + p.flush(); + if (p.target != .none) { + p.target = .none; + _ = c.SDL_SetRenderTarget(p.renderer, p.canvas); + } + p.blend = .alpha; + _ = c.SDL_SetRenderClipRect(p.renderer, null); + } + + /// Draws one graphics command. Other commands are not graphics: ignored. + pub fn draw(p: *Painter, command: abi.Command) void { + if (command != .shape) p.flush(); + const renderer = p.renderer; + switch (command) { + .clear => |color| { + if (@import("builtin").os.tag == .linux and p.target == .none) c.sk_text_begin_frame(renderer); + // A target holds premultiplied colour, as a canvas cleared + // to a translucent colour does. + setColor(renderer, if (p.target == .none) color else premultiply(color)); + _ = c.SDL_RenderClear(renderer); + }, + .rect => |r| { + setColor(renderer, r.color); + _ = c.SDL_SetRenderDrawBlendMode(renderer, drawBlend(p.blend)); + _ = c.SDL_RenderFillRect(renderer, &frect(r.dst)); + }, + .shape => |s| p.shape(s.color, s.points, s.ends, s.indices, s.colors), + .image => |img| p.drawImage(img.image, img.dst, img.src, img.tint, img.corners), + .text => |text| { + _ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_BLEND); + drawText(renderer, text.x, text.y, text.scale, text.bytes, text.color); + }, + .clip => |clip| { + if (clip) |r| { + const rect: c.SDL_Rect = .{ .x = @intFromFloat(r.x), .y = @intFromFloat(r.y), .w = @intFromFloat(r.w), .h = @intFromFloat(r.h) }; + _ = c.SDL_SetRenderClipRect(renderer, &rect); + } else _ = c.SDL_SetRenderClipRect(renderer, null); + }, + .pixels => |px| { + const entry = p.images.get(px.image) orelse return; + const texture = entry.texture orelse return; + if (px.w != entry.w or px.h != entry.h or px.rgba.len < @as(usize, px.w) * px.h * 4) return; + entry.premultiplied = px.premultiplied; + _ = c.SDL_UpdateTexture(texture, null, px.rgba.ptr, @intCast(px.w * 4)); + if (entry.big != null) p.spread(entry); + }, + .target => |img| p.setTarget(img), + .blend => |mode| p.blend = mode, + else => {}, + } + } + + fn setTarget(p: *Painter, handle: abi.Image) void { + const texture = if (handle == .none) p.canvas else blk: { + const entry = p.images.get(handle) orelse return; + if (!entry.target or entry.texture == null) return; + if (entry.big == null and p.smooth) p.supersample(entry); + entry.stale = entry.big != null; + break :blk entry.big orelse entry.texture; + }; + p.target = handle; + _ = c.SDL_SetRenderTarget(p.renderer, texture); + _ = c.SDL_SetRenderClipRect(p.renderer, null); + } + + /// Gives a target its supersampled self, holding what it shows now. + fn supersample(p: *Painter, entry: *Images.Entry) void { + const factor = factorFor(.{ entry.w, entry.h }); + if (factor == 1) return; + const big = c.SDL_CreateTexture(p.renderer, c.SDL_PIXELFORMAT_RGBA32, c.SDL_TEXTUREACCESS_TARGET, @intCast(entry.w * factor), @intCast(entry.h * factor)) orelse return; + _ = c.SDL_SetTextureScaleMode(big, c.SDL_SCALEMODE_LINEAR); + entry.big = big; + entry.factor = factor; + const f: f32 = @floatFromInt(factor); + const previous = c.SDL_GetRenderTarget(p.renderer); + _ = c.SDL_SetRenderTarget(p.renderer, big); + _ = c.SDL_SetRenderScale(p.renderer, f, f); + _ = c.SDL_SetRenderTarget(p.renderer, previous); + p.spread(entry); + } + + /// Copies a target's `texture` into its supersampled self (after + /// `pixels` replaced it), each pixel into its samples. + fn spread(p: *Painter, entry: *Images.Entry) void { + const previous = c.SDL_GetRenderTarget(p.renderer); + _ = c.SDL_SetRenderTarget(p.renderer, entry.big); + const t = entry.texture.?; + _ = c.SDL_SetTextureBlendMode(t, c.SDL_BLENDMODE_NONE); + _ = c.SDL_SetTextureColorMod(t, 255, 255, 255); + _ = c.SDL_SetTextureAlphaMod(t, 255); + _ = c.SDL_RenderTexture(p.renderer, t, null, &.{ .x = 0, .y = 0, .w = @floatFromInt(entry.w), .h = @floatFromInt(entry.h) }); + _ = c.SDL_SetRenderTarget(p.renderer, previous); + entry.stale = false; + } + + /// Brings a target's `texture` up to date: its samples averaged. + fn resolve(p: *Painter, entry: *Images.Entry) void { + entry.stale = false; + const previous = c.SDL_GetRenderTarget(p.renderer); + p.average(entry.big.?, entry.factor, .{ 0, 0, entry.w, entry.h }, entry.texture.?, c.SDL_BLENDMODE_NONE); + _ = c.SDL_SetRenderTarget(p.renderer, previous); + } + + /// Draws `box` (destination pixels) of `from`, `factor` times larger, + /// averaged into `to` with `blend`. Leaves `to` the render target. + fn average(p: *Painter, from: *c.SDL_Texture, factor: u32, box: [4]u32, to: ?*c.SDL_Texture, blend: c.SDL_BlendMode) void { + var source = from; + var k: f32 = @floatFromInt(factor); + if (factor == 4) half: { + const need: [2]u32 = .{ box[2] * 2, box[3] * 2 }; + if (p.half == null or p.half_size[0] < need[0] or p.half_size[1] < need[1]) { + if (p.half) |t| c.SDL_DestroyTexture(t); + const size: [2]u32 = .{ @max(need[0], p.half_size[0]), @max(need[1], p.half_size[1]) }; + p.half = c.SDL_CreateTexture(p.renderer, c.SDL_PIXELFORMAT_RGBA32, c.SDL_TEXTUREACCESS_TARGET, @intCast(size[0]), @intCast(size[1])); + p.half_size = if (p.half != null) size else .{ 0, 0 }; + if (p.half) |t| _ = c.SDL_SetTextureScaleMode(t, c.SDL_SCALEMODE_LINEAR) else break :half; + } + _ = c.SDL_SetRenderTarget(p.renderer, p.half); + plain(from, c.SDL_BLENDMODE_NONE); + _ = c.SDL_RenderTexture(p.renderer, from, &frect(scaledBox(box, 4)), &frect(scaledBox(box, 2))); + source = p.half.?; + k = 2; + } + _ = c.SDL_SetRenderTarget(p.renderer, to); + plain(source, blend); + _ = c.SDL_RenderTexture(p.renderer, source, &frect(scaledBox(box, k)), &frect(scaledBox(box, 1))); + } + + /// The current destination's size in its own pixels. + fn destinationSize(p: *Painter) [2]u32 { + if (p.target == .none) return p.canvas_size; + const entry = p.images.get(p.target) orelse return p.canvas_size; + return .{ entry.w, entry.h }; + } + + fn drawImage(p: *Painter, handle: abi.Image, dst: abi.Rect, src_rect: abi.Rect, tint: abi.Color, corners: ?abi.Corners) void { + const renderer = p.renderer; + const entry = p.images.get(handle); + const texture = if (entry) |e| e.texture else null; + const t = texture orelse return missing(renderer, dst); + const e = entry.?; + if (handle == p.target) return; // Drawing into itself: nothing. + if (e.stale) p.resolve(e); + // A premultiplied texture needs its colour scaled by the tint's + // alpha too, which SDL's alpha mod does not do. + const scale: u32 = if (e.premultiplied) tint.a else 255; + _ = c.SDL_SetTextureColorMod(t, @intCast(@as(u32, tint.r) * scale / 255), @intCast(@as(u32, tint.g) * scale / 255), @intCast(@as(u32, tint.b) * scale / 255)); + _ = c.SDL_SetTextureAlphaMod(t, tint.a); + _ = c.SDL_SetTextureBlendMode(t, textureBlend(p.blend, e.premultiplied)); + const src = frect(src_rect); + const srcp = if (src_rect.w > 0) &src else null; + if (corners) |q| { + const origin: c.SDL_FPoint = .{ .x = q.top_left[0], .y = q.top_left[1] }; + const right: c.SDL_FPoint = .{ .x = q.top_right[0], .y = q.top_right[1] }; + const down: c.SDL_FPoint = .{ .x = q.bottom_left[0], .y = q.bottom_left[1] }; + _ = c.SDL_RenderTextureAffine(renderer, t, srcp, &origin, &right, &down); + } else _ = c.SDL_RenderTexture(renderer, t, srcp, &frect(dst)); + } + + /// `Command.shape`: its triangles in one geometry call, one colour for + /// every vertex (stride 0, nothing copied) or each subpath's. The + /// subpaths are for the web; native needs only the triangles. + fn shape(p: *Painter, color: abi.Color, points: []const [2]f32, ends: []const u32, indices: []const u32, colors: []const abi.Color) void { + const count = indices.len - indices.len % 3; + if (count == 0 or points.len == 0 or points.len > std.math.maxInt(c_int) or count > std.math.maxInt(c_int)) return; + for (indices[0..count]) |i| if (i >= points.len) return; + var one = fcolor(color); + var vertex_colors: []const c.SDL_FColor = (&one)[0..1]; + var stride: c_int = 0; + if (colors.len > 0) { + const each = p.arena.alloc(c.SDL_FColor, points.len) catch return; + @memset(each, one); + var start: usize = 0; + for (ends, 0..) |subpath_end, i| { + if (i >= colors.len) break; + const stop = @min(subpath_end, points.len); + if (stop > start) @memset(each[start..stop], fcolor(colors[i])); + start = @max(start, stop); + } + vertex_colors = each; + stride = @sizeOf(c.SDL_FColor); + } + // A supersampled target takes shapes as they are; the canvas + // through the layer. + if (p.target == .none and p.smooth) { + const box = bounds(points, indices[0..count], p.canvas_size) orelse return; + if (!p.openLayer(box)) return; + } + _ = c.SDL_SetRenderDrawBlendMode(p.renderer, drawBlend(p.blend)); + _ = c.SDL_RenderGeometryRaw(p.renderer, null, @ptrCast(points.ptr), @sizeOf([2]f32), vertex_colors.ptr, stride, null, 0, @intCast(points.len), indices.ptr, @intCast(count), @sizeOf(u32)); + } + + /// Makes the layer the render target for a shape covering `box` + /// (canvas pixels): the open one, if for this blend, else a new one. + /// False if there is no room for one (the shape is then drawn on the + /// canvas, aliased). + fn openLayer(p: *Painter, box: [4]u32) bool { + const l = &p.layer; + if (l.open and l.blend == p.blend) { + l.dirty = .{ @min(l.dirty[0], box[0]), @min(l.dirty[1], box[1]), @max(l.dirty[2], box[2]), @max(l.dirty[3], box[3]) }; + return true; + } + p.flush(); + const size = p.canvas_size; + const factor = factorFor(size); + if (factor == 1) return true; + const w = size[0] * factor; + const h = size[1] * factor; + if (l.big == null or l.w < w or l.h < h) { + if (l.big) |t| c.SDL_DestroyTexture(t); + l.* = .{ .w = w, .h = h }; + l.big = c.SDL_CreateTexture(p.renderer, c.SDL_PIXELFORMAT_RGBA32, c.SDL_TEXTUREACCESS_TARGET, @intCast(w), @intCast(h)); + const big = l.big orelse { + std.log.warn("no antialiasing layer: {s}", .{c.SDL_GetError()}); + p.smooth = false; + return true; + }; + _ = c.SDL_SetTextureScaleMode(big, c.SDL_SCALEMODE_LINEAR); + // Cleared whole once; afterwards only what a composite left. + _ = c.SDL_SetRenderTarget(p.renderer, big); + _ = c.SDL_SetRenderDrawColor(p.renderer, 0, 0, 0, 0); + _ = c.SDL_RenderClear(p.renderer); + } + _ = c.SDL_SetRenderTarget(p.renderer, l.big); + const f: f32 = @floatFromInt(factor); + _ = c.SDL_SetRenderScale(p.renderer, f, f); + if (l.dirty[2] > l.dirty[0]) { + // The last layer's shapes, gone: at the scale it drew them. + const old: f32 = @floatFromInt(l.factor); + _ = c.SDL_SetRenderDrawBlendMode(p.renderer, c.SDL_BLENDMODE_NONE); + _ = c.SDL_SetRenderDrawColor(p.renderer, 0, 0, 0, 0); + _ = c.SDL_RenderFillRect(p.renderer, &frect(scaledBox(l.dirty, old / f))); + } + l.factor = factor; + l.blend = p.blend; + l.open = true; + l.dirty = box; + return true; + } + + /// Composites an open layer onto the canvas: the rect its shapes + /// cover, nothing else. + fn flush(p: *Painter) void { + const l = &p.layer; + if (!l.open) return; + l.open = false; + p.average(l.big.?, l.factor, l.dirty, p.canvas, textureBlend(l.blend, true)); + } +}; + +/// A texture drawn as it is: no tint, `blend`. +fn plain(t: *c.SDL_Texture, blend: c.SDL_BlendMode) void { + _ = c.SDL_SetTextureBlendMode(t, blend); + _ = c.SDL_SetTextureColorMod(t, 255, 255, 255); + _ = c.SDL_SetTextureAlphaMod(t, 255); +} + +/// The pixels a shape's triangles may touch, one pixel around, clamped to +/// the destination: null if none. +fn bounds(points: []const [2]f32, indices: []const u32, size: [2]u32) ?[4]u32 { + var lo: [2]f32 = .{ std.math.inf(f32), std.math.inf(f32) }; + var hi: [2]f32 = .{ -std.math.inf(f32), -std.math.inf(f32) }; + for (indices) |i| for (0..2) |axis| { + lo[axis] = @min(lo[axis], points[i][axis]); + hi[axis] = @max(hi[axis], points[i][axis]); + }; + var box: [4]u32 = undefined; + for (0..2) |axis| { + const limit: f32 = @floatFromInt(size[axis]); + const a = std.math.clamp(@floor(lo[axis]) - 1, 0, limit); + const b = std.math.clamp(@ceil(hi[axis]) + 1, 0, limit); + if (!(b > a)) return null; // off the destination, or NaN + box[axis] = @intFromFloat(a); + box[axis + 2] = @intFromFloat(b); } + return box; +} + +/// `box` (x0, y0, x1, y1) times `k`, as a rect. +fn scaledBox(box: [4]u32, k: f32) abi.Rect { + const x: f32 = @floatFromInt(box[0]); + const y: f32 = @floatFromInt(box[1]); + return .{ .x = x * k, .y = y * k, .w = @as(f32, @floatFromInt(box[2] - box[0])) * k, .h = @as(f32, @floatFromInt(box[3] - box[1])) * k }; +} + +/// Adds colour times alpha, and alpha, as canvas `lighter` does (SDL's +/// `ADD` keeps the destination's alpha). +fn addBlend(premultiplied: bool) c.SDL_BlendMode { + const src: c.SDL_BlendFactor = if (premultiplied) c.SDL_BLENDFACTOR_ONE else c.SDL_BLENDFACTOR_SRC_ALPHA; + return c.SDL_ComposeCustomBlendMode(src, c.SDL_BLENDFACTOR_ONE, c.SDL_BLENDOPERATION_ADD, c.SDL_BLENDFACTOR_ONE, c.SDL_BLENDFACTOR_ONE, c.SDL_BLENDOPERATION_ADD); +} + +/// Solid colours (straight alpha) onto the destination. +fn drawBlend(blend: abi.BlendMode) c.SDL_BlendMode { + return switch (blend) { + .alpha => c.SDL_BLENDMODE_BLEND, + .add => addBlend(false), + }; +} + +fn textureBlend(blend: abi.BlendMode, premultiplied: bool) c.SDL_BlendMode { + return switch (blend) { + .alpha => if (premultiplied) c.SDL_BLENDMODE_BLEND_PREMULTIPLIED else c.SDL_BLENDMODE_BLEND, + .add => addBlend(premultiplied), + }; +} + +fn fcolor(color: abi.Color) c.SDL_FColor { + return .{ + .r = @as(f32, @floatFromInt(color.r)) / 255, + .g = @as(f32, @floatFromInt(color.g)) / 255, + .b = @as(f32, @floatFromInt(color.b)) / 255, + .a = @as(f32, @floatFromInt(color.a)) / 255, + }; } /// Native shaped text on Linux, using a 13px monospace face at scale 1. @@ -178,7 +555,13 @@ pub fn drawText(renderer: *c.SDL_Renderer, x: f32, y: f32, scale: f32, bytes: [] if (clipped and s != 1) _ = c.SDL_SetRenderClipRect(renderer, &clip); } +fn premultiply(color: abi.Color) abi.Color { + const a: u32 = color.a; + return .{ .r = @intCast((color.r * a + 127) / 255), .g = @intCast((color.g * a + 127) / 255), .b = @intCast((color.b * a + 127) / 255), .a = color.a }; +} + fn missing(renderer: *c.SDL_Renderer, dst: abi.Rect) void { + _ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_BLEND); setColor(renderer, .{ .r = 110, .g = 30, .b = 70 }); _ = c.SDL_RenderFillRect(renderer, &frect(dst)); drawText(renderer, dst.x + 4, dst.y + 4, 1, "missing image", .{ .r = 255, .g = 210, .b = 240 }); diff --git a/src/host/gpu.zig b/src/host/gpu.zig index 9c77205..94b2e39 100644 --- a/src/host/gpu.zig +++ b/src/host/gpu.zig @@ -119,6 +119,10 @@ const Target = struct { texture: *c.SDL_GPUTexture, samples: u8 = 1, msaa: ?*c.SDL_GPUTexture = null, + /// Not rendered into yet: undefined natively, so the first pass that + /// would load clears to zero (WebGPU's starting contents). + fresh: bool = true, + msaa_fresh: bool = true, stencil_samples: u8 = 0, stencil: ?*c.SDL_GPUTexture = null, }; @@ -187,6 +191,12 @@ pub fn run(g: *Gpu, images: *gfx.Images, pass: abi.gpu.Pass) !void { if (pass.width == 0 or pass.height == 0 or pass.draws.len == 0 and pass.clear == null) return; const samples = g.supportedSamples(pass.samples); const t = try g.renderTarget(images, pass.image, pass.width, pass.height, samples, pass.stencil); + // Each pipeline is looked up on first use in the pass, not per draw: + // the lookup hashes the shaders' code. Outer null: not looked up yet; + // inner null: it failed (warned once). + const built = try g.gpa.alloc(??*c.SDL_GPUGraphicsPipeline, pass.pipelines.len); + defer g.gpa.free(built); + @memset(built, null); const start = g.startTiming(); // Every draw's vertices go up in one copy. @@ -210,16 +220,23 @@ pub fn run(g: *Gpu, images: *gfx.Images, pass: abi.gpu.Pass) !void { const clear = pass.clear orelse .{ 0, 0, 0, 0 }; var color: c.SDL_GPUColorTargetInfo = std.mem.zeroes(c.SDL_GPUColorTargetInfo); color.clear_color = .{ .r = clear[0], .g = clear[1], .b = clear[2], .a = clear[3] }; - // A multisampled pass cannot load resolved pixels: it always clears. - color.load_op = if (pass.clear != null or samples > 1) c.SDL_GPU_LOADOP_CLEAR else c.SDL_GPU_LOADOP_LOAD; + // `clear = null` keeps what the attachment holds, as on the web: a + // multisampled pass loads its multisampled attachment, which every + // pass therefore stores as well as resolves. A new attachment is + // cleared to zero instead, since Vulkan starts it undefined where + // WebGPU starts it zeroed. + const fresh = if (samples > 1) &t.msaa_fresh else &t.fresh; + color.load_op = if (pass.clear != null or fresh.*) c.SDL_GPU_LOADOP_CLEAR else c.SDL_GPU_LOADOP_LOAD; + fresh.* = false; if (samples > 1) { color.texture = t.msaa; - color.store_op = c.SDL_GPU_STOREOP_RESOLVE; + color.store_op = c.SDL_GPU_STOREOP_RESOLVE_AND_STORE; color.resolve_texture = t.texture; } else { color.texture = t.texture; color.store_op = c.SDL_GPU_STOREOP_STORE; } + t.fresh = false; var depth: c.SDL_GPUDepthStencilTargetInfo = std.mem.zeroes(c.SDL_GPUDepthStencilTargetInfo); if (pass.stencil) { depth.texture = t.stencil; @@ -231,29 +248,59 @@ pub fn run(g: *Gpu, images: *gfx.Images, pass: abi.gpu.Pass) !void { } const rp = c.SDL_BeginGPURenderPass(cmd, &color, 1, if (pass.stencil) &depth else null) orelse return error.GpuRenderPass; var bound: ?*c.SDL_GPUGraphicsPipeline = null; + // State already set in this pass, so draws that repeat it skip the call. + var vertex_uniforms: ?[]const u8 = null; + var stencil_reference: ?u8 = null; + var scissor: ?c.SDL_Rect = null; + var vertex_base: ?u32 = null; var offset: u32 = 0; for (pass.draws) |d| { defer offset += @intCast(std.mem.alignForward(usize, d.vertices.len, 4)); if (d.pipeline >= pass.pipelines.len or d.vertex_count == 0) continue; - const built = g.pipeline(pass.pipelines[d.pipeline], samples, pass.stencil) catch |err| { + const slot = &built[d.pipeline]; + if (slot.* == null) slot.* = g.pipeline(pass.pipelines[d.pipeline], samples, pass.stencil) catch |err| blk: { std.log.warn("gpu pipeline {d}: {t} ({s})", .{ d.pipeline, err, c.SDL_GetError() }); - continue; + break :blk @as(?*c.SDL_GPUGraphicsPipeline, null); }; - if (bound != built) { - c.SDL_BindGPUGraphicsPipeline(rp, built); - bound = built; + const chosen = slot.*.? orelse continue; + if (bound != chosen) { + c.SDL_BindGPUGraphicsPipeline(rp, chosen); + bound = chosen; + } + // Vertices at a multiple of the stride are reached from one binding + // at 0 by the draw's first vertex; others get a binding of their own. + var first: u32 = 0; + if (d.vertices.len > 0) { + const stride = pass.pipelines[d.pipeline].stride; + const base = if (stride > 0 and offset % stride == 0) 0 else offset; + if (base == 0 and stride > 0) first = offset / stride; + if (vertex_base != base) { + c.SDL_BindGPUVertexBuffers(rp, 0, &.{ .buffer = g.vertices, .offset = base }, 1); + vertex_base = base; + } } - if (d.vertices.len > 0) c.SDL_BindGPUVertexBuffers(rp, 0, &.{ .buffer = g.vertices, .offset = offset }, 1); var bound_storage: [8]*c.SDL_GPUBuffer = undefined; if (d.vertex_storage.len > 0) c.SDL_BindGPUVertexStorageBuffers(rp, 0, &bound_storage, g.resolve(d.vertex_storage, &bound_storage) catch continue); if (d.fragment_storage.len > 0) c.SDL_BindGPUFragmentStorageBuffers(rp, 0, &bound_storage, g.resolve(d.fragment_storage, &bound_storage) catch continue); - if (d.vertex_uniforms.len > 0) c.SDL_PushGPUVertexUniformData(cmd, 0, d.vertex_uniforms.ptr, @intCast(d.vertex_uniforms.len)); + // Pushed uniforms stay for later draws: the same bytes (sketches + // share one slice for a pass's viewport) need no second push. + if (d.vertex_uniforms.len > 0) if (vertex_uniforms == null or vertex_uniforms.?.ptr != d.vertex_uniforms.ptr or vertex_uniforms.?.len != d.vertex_uniforms.len) { + c.SDL_PushGPUVertexUniformData(cmd, 0, d.vertex_uniforms.ptr, @intCast(d.vertex_uniforms.len)); + vertex_uniforms = d.vertex_uniforms; + }; if (d.fragment_uniforms.len > 0) c.SDL_PushGPUFragmentUniformData(cmd, 0, d.fragment_uniforms.ptr, @intCast(d.fragment_uniforms.len)); - if (pass.stencil) c.SDL_SetGPUStencilReference(rp, d.stencil_reference); + if (pass.stencil and stencil_reference != d.stencil_reference) { + c.SDL_SetGPUStencilReference(rp, d.stencil_reference); + stencil_reference = d.stencil_reference; + } const full: abi.Rect = .{ .w = @floatFromInt(pass.width), .h = @floatFromInt(pass.height) }; const s = d.scissor orelse full; - c.SDL_SetGPUScissor(rp, &.{ .x = @intFromFloat(@max(s.x, 0)), .y = @intFromFloat(@max(s.y, 0)), .w = @intFromFloat(@max(s.w, 0)), .h = @intFromFloat(@max(s.h, 0)) }); - c.SDL_DrawGPUPrimitives(rp, d.vertex_count, 1, 0, 0); + const rect: c.SDL_Rect = .{ .x = @intFromFloat(@max(s.x, 0)), .y = @intFromFloat(@max(s.y, 0)), .w = @intFromFloat(@max(s.w, 0)), .h = @intFromFloat(@max(s.h, 0)) }; + if (scissor == null or !std.meta.eql(scissor.?, rect)) { + c.SDL_SetGPUScissor(rp, &rect); + scissor = rect; + } + c.SDL_DrawGPUPrimitives(rp, d.vertex_count, 1, first, 0); } c.SDL_EndGPURenderPass(rp); try g.submit(cmd, if (pass.label.len > 0) pass.label else "pass", start); @@ -457,6 +504,7 @@ fn renderTarget(g: *Gpu, images: *gfx.Images, image: abi.Image, w: u32, h: u32, if (t.msaa) |m| c.SDL_ReleaseGPUTexture(g.device, m); t.msaa = try g.texture(w, h, color_format, c.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET, samples); t.samples = samples; + t.msaa_fresh = true; } if (stencil and (t.stencil == null or t.stencil_samples != samples)) { if (t.stencil) |s| c.SDL_ReleaseGPUTexture(g.device, s); diff --git a/src/host/gpu.zig.orig b/src/host/gpu.zig.orig new file mode 100644 index 0000000..7854c99 --- /dev/null +++ b/src/host/gpu.zig.orig @@ -0,0 +1,641 @@ +//! Runs `abi.gpu` passes and dispatches with SDL_GPU: the translation from +//! GPU work as data to a real API. Shaders and pipelines are built on first +//! use and cached by the hash of their description; entries a sketch stops +//! using (an edited shader, after a reload) are released after a while. +const Gpu = @This(); +const std = @import("std"); +const c = @import("c"); +const abi = @import("abi"); +const gfx = @import("gfx.zig"); + +pub const color_format = c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM; +/// Frames an unused shader or pipeline survives. +const keep_frames = 300; + +gpa: std.mem.Allocator, +device: *c.SDL_GPUDevice, +stencil_format: c.SDL_GPUTextureFormat, +shaders: std.AutoHashMapUnmanaged(u64, Cached(c.SDL_GPUShader)) = .empty, +pipelines: std.AutoHashMapUnmanaged(u64, Cached(c.SDL_GPUGraphicsPipeline)) = .empty, +kernels: std.AutoHashMapUnmanaged(u64, Cached(c.SDL_GPUComputePipeline)) = .empty, +/// Storage buffers by handle: `Buffer` n is `buffers[n - 1]`, null once freed. +buffers: std.ArrayList(?Storage) = .empty, +/// Uploads to storage buffers go through this, in chunks of its size. +staging: ?*c.SDL_GPUTransferBuffer = null, +/// Render targets per image: the resolved texture the renderer shows, and +/// multisampled and stencil attachments as passes ask for them. +targets: std.AutoHashMapUnmanaged(abi.Image, Target) = .empty, +vertices: ?*c.SDL_GPUBuffer = null, +vertex_capacity: u32 = 0, +upload: ?*c.SDL_GPUTransferBuffer = null, +upload_capacity: u32 = 0, +frame: u64 = 0, +/// Set by `--profile-gpu`: every command is timed alone (see `Profile`). +profile: ?Profile = null, +/// Downloads in flight, oldest first, and transfer buffers to reuse. +downloads: std.ArrayList(Download) = .empty, +spare: std.ArrayList(Transfer) = .empty, + +const Transfer = struct { buffer: *c.SDL_GPUTransferBuffer, size: u32 }; +const Download = struct { key: u32, size: u32, transfer: Transfer, fence: *c.SDL_GPUFence }; + +/// GPU time per labelled command. Each command starts on an idle GPU and is +/// waited for, so its time is its own: the total of a frame is what the +/// GPU spends on it, though the waiting makes the frame itself slower. +pub const Profile = struct { + entries: std.StringArrayHashMapUnmanaged(Entry) = .empty, + arena: std.heap.ArenaAllocator, + + const Entry = struct { count: u64 = 0, total: u64 = 0, worst: u64 = 0 }; + + pub fn init(gpa: std.mem.Allocator) Profile { + return .{ .arena = .init(gpa) }; + } + + pub fn deinit(p: *Profile) void { + p.arena.deinit(); + } + + fn add(p: *Profile, label: []const u8, ns: u64) void { + const a = p.arena.allocator(); + const entry = p.entries.getOrPut(a, label) catch return; + if (!entry.found_existing) { + entry.key_ptr.* = a.dupe(u8, label) catch "?"; + entry.value_ptr.* = .{}; + } + entry.value_ptr.count += 1; + entry.value_ptr.total += ns; + entry.value_ptr.worst = @max(entry.value_ptr.worst, ns); + } + + pub fn report(p: *Profile, frames: u64) void { + std.debug.print("gpu time over {d} frames (ms)\n{s: <24} {s: >7} {s: >9} {s: >9} {s: >11}\n", .{ frames, "command", "count", "mean", "worst", "per frame" }); + var sum: u64 = 0; + var it = p.entries.iterator(); + while (it.next()) |e| { + const v = e.value_ptr.*; + sum += v.total; + std.debug.print("{s: <24} {d: >7} {d: >9.3} {d: >9.3} {d: >11.3}\n", .{ e.key_ptr.*, v.count, ms(v.total) / @as(f64, @floatFromInt(v.count)), ms(v.worst), ms(v.total) / @as(f64, @floatFromInt(@max(frames, 1))) }); + } + std.debug.print("{s: <24} {s: >7} {s: >9} {s: >9} {d: >11.3}\n", .{ "all", "", "", "", ms(sum) / @as(f64, @floatFromInt(@max(frames, 1))) }); + } + + fn ms(ns: u64) f64 { + return @as(f64, @floatFromInt(ns)) / std.time.ns_per_ms; + } +}; + +/// Submits `cmd`; when profiling, waits for it and books its time from +/// `start` (taken on an idle GPU, before recording) under `label`. +fn submit(g: *Gpu, cmd: *c.SDL_GPUCommandBuffer, label: []const u8, start: u64) !void { + const p = &(g.profile orelse { + if (!c.SDL_SubmitGPUCommandBuffer(cmd)) return error.GpuSubmit; + return; + }); + const fence = c.SDL_SubmitGPUCommandBufferAndAcquireFence(cmd) orelse return error.GpuSubmit; + defer c.SDL_ReleaseGPUFence(g.device, fence); + _ = c.SDL_WaitForGPUFences(g.device, true, &fence, 1); + p.add(label, c.SDL_GetTicksNS() - start); +} + +/// When profiling: waits for the GPU to be idle, then the time to start from. +fn startTiming(g: *Gpu) u64 { + if (g.profile != null) _ = c.SDL_WaitForGPUIdle(g.device); + return c.SDL_GetTicksNS(); +} + +/// The most bytes one buffer upload stages at a time. +const staging_size = 4 << 20; + +fn Cached(comptime T: type) type { + return struct { object: *T, used: u64 }; +} + +const Storage = struct { buffer: *c.SDL_GPUBuffer, size: u32 }; + +const Target = struct { + width: u32, + height: u32, + texture: *c.SDL_GPUTexture, + samples: u8 = 1, + msaa: ?*c.SDL_GPUTexture = null, + /// Not rendered into yet: undefined natively, so the first pass that + /// would load clears to zero (WebGPU's starting contents). + fresh: bool = true, + msaa_fresh: bool = true, + stencil_samples: u8 = 0, + stencil: ?*c.SDL_GPUTexture = null, +}; + +pub fn init(gpa: std.mem.Allocator, device: *c.SDL_GPUDevice) Gpu { + const d24 = c.SDL_GPUTextureSupportsFormat(device, c.SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT, c.SDL_GPU_TEXTURETYPE_2D, c.SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET); + return .{ + .gpa = gpa, + .device = device, + .stencil_format = if (d24) c.SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT else c.SDL_GPU_TEXTUREFORMAT_D32_FLOAT_S8_UINT, + }; +} + +pub fn deinit(g: *Gpu, images: *gfx.Images) void { + if (g.profile) |*p| { + p.report(g.frame); + p.deinit(); + } + var shaders = g.shaders.valueIterator(); + while (shaders.next()) |s| c.SDL_ReleaseGPUShader(g.device, s.object); + var pipelines = g.pipelines.valueIterator(); + while (pipelines.next()) |p| c.SDL_ReleaseGPUGraphicsPipeline(g.device, p.object); + var kernels = g.kernels.valueIterator(); + while (kernels.next()) |k| c.SDL_ReleaseGPUComputePipeline(g.device, k.object); + for (g.buffers.items) |entry| if (entry) |b| c.SDL_ReleaseGPUBuffer(g.device, b.buffer); + for (g.downloads.items) |d| { + _ = c.SDL_WaitForGPUFences(g.device, true, &d.fence, 1); + c.SDL_ReleaseGPUFence(g.device, d.fence); + c.SDL_ReleaseGPUTransferBuffer(g.device, d.transfer.buffer); + } + for (g.spare.items) |t| c.SDL_ReleaseGPUTransferBuffer(g.device, t.buffer); + g.downloads.deinit(g.gpa); + g.spare.deinit(g.gpa); + if (g.staging) |b| c.SDL_ReleaseGPUTransferBuffer(g.device, b); + var targets = g.targets.iterator(); + while (targets.next()) |entry| g.releaseTarget(images, entry.key_ptr.*, entry.value_ptr.*); + if (g.vertices) |b| c.SDL_ReleaseGPUBuffer(g.device, b); + if (g.upload) |b| c.SDL_ReleaseGPUTransferBuffer(g.device, b); + g.shaders.deinit(g.gpa); + g.pipelines.deinit(g.gpa); + g.kernels.deinit(g.gpa); + g.buffers.deinit(g.gpa); + g.targets.deinit(g.gpa); +} + +/// Releases what nothing has used for a while. +pub fn endFrame(g: *Gpu) void { + g.frame += 1; + inline for (.{ &g.pipelines, &g.shaders, &g.kernels }) |map| { + var it = map.iterator(); + while (it.next()) |entry| { + if (g.frame - entry.value_ptr.used < keep_frames) continue; + switch (@TypeOf(map)) { + @TypeOf(&g.pipelines) => c.SDL_ReleaseGPUGraphicsPipeline(g.device, entry.value_ptr.object), + @TypeOf(&g.kernels) => c.SDL_ReleaseGPUComputePipeline(g.device, entry.value_ptr.object), + else => c.SDL_ReleaseGPUShader(g.device, entry.value_ptr.object), + } + map.removeByPtr(entry.key_ptr); + // The iterator is invalid after a removal: the rest waits a frame. + break; + } + } +} + +pub fn run(g: *Gpu, images: *gfx.Images, pass: abi.gpu.Pass) !void { + if (pass.width == 0 or pass.height == 0 or pass.draws.len == 0 and pass.clear == null) return; + const samples = g.supportedSamples(pass.samples); + const t = try g.renderTarget(images, pass.image, pass.width, pass.height, samples, pass.stencil); + // Each pipeline is looked up on first use in the pass, not per draw: + // the lookup hashes the shaders' code. Outer null: not looked up yet; + // inner null: it failed (warned once). + const built = try g.gpa.alloc(??*c.SDL_GPUGraphicsPipeline, pass.pipelines.len); + defer g.gpa.free(built); + @memset(built, null); + + const start = g.startTiming(); + // Every draw's vertices go up in one copy. + var total: u32 = 0; + for (pass.draws) |d| total += @intCast(std.mem.alignForward(usize, d.vertices.len, 4)); + const cmd = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return error.GpuCommandBuffer; + if (total > 0) { + try g.reserve(total); + const mapped: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, g.upload, true) orelse return error.GpuMap); + var offset: usize = 0; + for (pass.draws) |d| { + @memcpy(mapped[offset..][0..d.vertices.len], d.vertices); + offset += std.mem.alignForward(usize, d.vertices.len, 4); + } + c.SDL_UnmapGPUTransferBuffer(g.device, g.upload); + const copy = c.SDL_BeginGPUCopyPass(cmd); + c.SDL_UploadToGPUBuffer(copy, &.{ .transfer_buffer = g.upload, .offset = 0 }, &.{ .buffer = g.vertices, .offset = 0, .size = total }, true); + c.SDL_EndGPUCopyPass(copy); + } + + const clear = pass.clear orelse .{ 0, 0, 0, 0 }; + var color: c.SDL_GPUColorTargetInfo = std.mem.zeroes(c.SDL_GPUColorTargetInfo); + color.clear_color = .{ .r = clear[0], .g = clear[1], .b = clear[2], .a = clear[3] }; + // `clear = null` keeps what the attachment holds, as on the web: a + // multisampled pass loads its multisampled attachment, which every + // pass therefore stores as well as resolves. A new attachment is + // cleared to zero instead, since Vulkan starts it undefined where + // WebGPU starts it zeroed. + const fresh = if (samples > 1) &t.msaa_fresh else &t.fresh; + color.load_op = if (pass.clear != null or fresh.*) c.SDL_GPU_LOADOP_CLEAR else c.SDL_GPU_LOADOP_LOAD; + fresh.* = false; + if (samples > 1) { + color.texture = t.msaa; + color.store_op = c.SDL_GPU_STOREOP_RESOLVE_AND_STORE; + color.resolve_texture = t.texture; + } else { + color.texture = t.texture; + color.store_op = c.SDL_GPU_STOREOP_STORE; + } + t.fresh = false; + var depth: c.SDL_GPUDepthStencilTargetInfo = std.mem.zeroes(c.SDL_GPUDepthStencilTargetInfo); + if (pass.stencil) { + depth.texture = t.stencil; + depth.load_op = c.SDL_GPU_LOADOP_DONT_CARE; + depth.store_op = c.SDL_GPU_STOREOP_DONT_CARE; + depth.stencil_load_op = c.SDL_GPU_LOADOP_CLEAR; + depth.stencil_store_op = c.SDL_GPU_STOREOP_DONT_CARE; + depth.clear_stencil = 0; + } + const rp = c.SDL_BeginGPURenderPass(cmd, &color, 1, if (pass.stencil) &depth else null) orelse return error.GpuRenderPass; + var bound: ?*c.SDL_GPUGraphicsPipeline = null; + var offset: u32 = 0; + for (pass.draws) |d| { + defer offset += @intCast(std.mem.alignForward(usize, d.vertices.len, 4)); + if (d.pipeline >= pass.pipelines.len or d.vertex_count == 0) continue; + const slot = &built[d.pipeline]; + if (slot.* == null) slot.* = g.pipeline(pass.pipelines[d.pipeline], samples, pass.stencil) catch |err| blk: { + std.log.warn("gpu pipeline {d}: {t} ({s})", .{ d.pipeline, err, c.SDL_GetError() }); + break :blk @as(?*c.SDL_GPUGraphicsPipeline, null); + }; + const chosen = slot.*.? orelse continue; + if (bound != chosen) { + c.SDL_BindGPUGraphicsPipeline(rp, chosen); + bound = chosen; + } + if (d.vertices.len > 0) c.SDL_BindGPUVertexBuffers(rp, 0, &.{ .buffer = g.vertices, .offset = offset }, 1); + var bound_storage: [8]*c.SDL_GPUBuffer = undefined; + if (d.vertex_storage.len > 0) c.SDL_BindGPUVertexStorageBuffers(rp, 0, &bound_storage, g.resolve(d.vertex_storage, &bound_storage) catch continue); + if (d.fragment_storage.len > 0) c.SDL_BindGPUFragmentStorageBuffers(rp, 0, &bound_storage, g.resolve(d.fragment_storage, &bound_storage) catch continue); + if (d.vertex_uniforms.len > 0) c.SDL_PushGPUVertexUniformData(cmd, 0, d.vertex_uniforms.ptr, @intCast(d.vertex_uniforms.len)); + if (d.fragment_uniforms.len > 0) c.SDL_PushGPUFragmentUniformData(cmd, 0, d.fragment_uniforms.ptr, @intCast(d.fragment_uniforms.len)); + if (pass.stencil) c.SDL_SetGPUStencilReference(rp, d.stencil_reference); + const full: abi.Rect = .{ .w = @floatFromInt(pass.width), .h = @floatFromInt(pass.height) }; + const s = d.scissor orelse full; + c.SDL_SetGPUScissor(rp, &.{ .x = @intFromFloat(@max(s.x, 0)), .y = @intFromFloat(@max(s.y, 0)), .w = @intFromFloat(@max(s.w, 0)), .h = @intFromFloat(@max(s.h, 0)) }); + c.SDL_DrawGPUPrimitives(rp, d.vertex_count, 1, 0, 0); + } + c.SDL_EndGPURenderPass(rp); + try g.submit(cmd, if (pass.label.len > 0) pass.label else "pass", start); +} + +/// Runs one dispatch in a compute pass of its own. +pub fn compute(g: *Gpu, d: abi.gpu.Dispatch) !void { + if (d.groups[0] == 0 or d.groups[1] == 0 or d.groups[2] == 0) return; + const built = try g.kernel(d.kernel); + const start = g.startTiming(); + var readonly: [8]*c.SDL_GPUBuffer = undefined; + const readonly_count = try g.resolve(d.readonly, &readonly); + var readwrite: [8]*c.SDL_GPUBuffer = undefined; + const readwrite_count = try g.resolve(d.readwrite, &readwrite); + var bindings: [8]c.SDL_GPUStorageBufferReadWriteBinding = undefined; + for (readwrite[0..readwrite_count], bindings[0..readwrite_count]) |b, *binding| binding.* = std.mem.zeroInit(c.SDL_GPUStorageBufferReadWriteBinding, .{ .buffer = b }); + const cmd = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return error.GpuCommandBuffer; + const pass = c.SDL_BeginGPUComputePass(cmd, null, 0, &bindings, readwrite_count) orelse { + _ = c.SDL_CancelGPUCommandBuffer(cmd); + return error.GpuComputePass; + }; + c.SDL_BindGPUComputePipeline(pass, built); + if (readonly_count > 0) c.SDL_BindGPUComputeStorageBuffers(pass, 0, &readonly, readonly_count); + if (d.uniforms.len > 0) c.SDL_PushGPUComputeUniformData(cmd, 0, d.uniforms.ptr, @intCast(d.uniforms.len)); + c.SDL_DispatchGPUCompute(pass, d.groups[0], d.groups[1], d.groups[2]); + c.SDL_EndGPUComputePass(pass); + try g.submit(cmd, if (d.label.len > 0) d.label else "compute", start); +} + +/// A zeroed storage buffer, readable by every stage and writable by compute. +pub fn newBuffer(g: *Gpu, size: u32) !abi.Buffer { + if (size == 0) return error.EmptyBuffer; + const usage = c.SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ | c.SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_READ | c.SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_WRITE; + const buffer = c.SDL_CreateGPUBuffer(g.device, &.{ .usage = usage, .size = size, .props = 0 }) orelse return error.GpuBuffer; + errdefer c.SDL_ReleaseGPUBuffer(g.device, buffer); + try g.buffers.append(g.gpa, .{ .buffer = buffer, .size = size }); + const handle: abi.Buffer = @fromBackingInt(@intCast(g.buffers.items.len)); + // Vulkan leaves new memory undefined; sketches get zeroes, copied from + // one zeroed staging block as many times as it takes. + const staging = try g.stagingBuffer(); + const block: u32 = @min(size, staging_size); + const mapped: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, staging, true) orelse return error.GpuMap); + @memset(mapped[0..block], 0); + c.SDL_UnmapGPUTransferBuffer(g.device, staging); + const cmd = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return error.GpuCommandBuffer; + const copy = c.SDL_BeginGPUCopyPass(cmd); + var offset: u32 = 0; + while (offset < size) : (offset += block) { + c.SDL_UploadToGPUBuffer(copy, &.{ .transfer_buffer = staging, .offset = 0 }, &.{ .buffer = buffer, .offset = offset, .size = @min(block, size - offset) }, false); + } + c.SDL_EndGPUCopyPass(copy); + if (!c.SDL_SubmitGPUCommandBuffer(cmd)) return error.GpuSubmit; + return handle; +} + +fn stagingBuffer(g: *Gpu) !*c.SDL_GPUTransferBuffer { + if (g.staging == null) g.staging = c.SDL_CreateGPUTransferBuffer(g.device, &.{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = staging_size, .props = 0 }) orelse return error.GpuBuffer; + return g.staging.?; +} + +pub fn freeBuffer(g: *Gpu, handle: abi.Buffer) void { + const index = @backingInt(handle); + if (index == 0 or index > g.buffers.items.len) return; + const entry = &g.buffers.items[index - 1]; + if (entry.*) |b| c.SDL_ReleaseGPUBuffer(g.device, b.buffer); + entry.* = null; +} + +/// Copies `bytes` into a buffer at `offset`, through the staging buffer. +pub fn write(g: *Gpu, handle: abi.Buffer, offset: u32, bytes: []const u8) !void { + const target = g.storage(handle) orelse return error.UnknownBuffer; + if (@as(u64, offset) + bytes.len > target.size) return error.UploadOutOfBounds; + const staging = try g.stagingBuffer(); + var done: usize = 0; + while (done < bytes.len) { + const chunk = bytes[done..][0..@min(staging_size, bytes.len - done)]; + const start = g.startTiming(); + // Cycling: a chunk still in flight keeps its own memory. + const mapped: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, staging, true) orelse return error.GpuMap); + @memcpy(mapped[0..chunk.len], chunk); + c.SDL_UnmapGPUTransferBuffer(g.device, staging); + const cmd = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return error.GpuCommandBuffer; + const copy = c.SDL_BeginGPUCopyPass(cmd); + c.SDL_UploadToGPUBuffer(copy, &.{ .transfer_buffer = staging, .offset = 0 }, &.{ .buffer = target.buffer, .offset = offset + @as(u32, @intCast(done)), .size = @intCast(chunk.len) }, false); + c.SDL_EndGPUCopyPass(copy); + try g.submit(cmd, "upload", start); + done += chunk.len; + } +} + +/// Starts copying `size` bytes of a buffer from `offset` back to the CPU; +/// `collect` hands them over once the GPU is done, a frame or more later. +pub fn download(g: *Gpu, d: @FieldType(abi.Command, "download")) !void { + const source = g.storage(d.buffer) orelse return error.UnknownBuffer; + if (d.size == 0 or @as(u64, d.offset) + d.size > source.size) return error.DownloadOutOfBounds; + const transfer = for (g.spare.items, 0..) |t, i| { + if (t.size >= d.size) break g.spare.swapRemove(i); + } else Transfer{ + .buffer = c.SDL_CreateGPUTransferBuffer(g.device, &.{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_DOWNLOAD, .size = d.size, .props = 0 }) orelse return error.GpuBuffer, + .size = d.size, + }; + errdefer g.spare.append(g.gpa, transfer) catch c.SDL_ReleaseGPUTransferBuffer(g.device, transfer.buffer); + const cmd = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return error.GpuCommandBuffer; + const copy = c.SDL_BeginGPUCopyPass(cmd); + c.SDL_DownloadFromGPUBuffer(copy, &.{ .buffer = source.buffer, .offset = d.offset, .size = d.size }, &.{ .transfer_buffer = transfer.buffer, .offset = 0 }); + c.SDL_EndGPUCopyPass(copy); + const fence = c.SDL_SubmitGPUCommandBufferAndAcquireFence(cmd) orelse return error.GpuSubmit; + g.downloads.append(g.gpa, .{ .key = d.key, .size = d.size, .transfer = transfer, .fence = fence }) catch |err| { + _ = c.SDL_WaitForGPUFences(g.device, true, &fence, 1); + c.SDL_ReleaseGPUFence(g.device, fence); + return err; + }; +} + +/// The downloads the GPU has finished, copied into `arena`, in the order +/// they were asked for. +pub fn collect(g: *Gpu, arena: std.mem.Allocator) ![]const abi.Download { + var done: std.ArrayList(abi.Download) = .empty; + while (g.downloads.items.len > 0) { + const d = g.downloads.items[0]; + if (!c.SDL_QueryGPUFence(g.device, d.fence)) break; + _ = g.downloads.orderedRemove(0); + c.SDL_ReleaseGPUFence(g.device, d.fence); + defer g.spare.append(g.gpa, d.transfer) catch c.SDL_ReleaseGPUTransferBuffer(g.device, d.transfer.buffer); + const mapped: [*]const u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, d.transfer.buffer, false) orelse return error.GpuMap); + defer c.SDL_UnmapGPUTransferBuffer(g.device, d.transfer.buffer); + try done.append(arena, .{ .key = d.key, .bytes = try arena.dupe(u8, mapped[0..d.size]) }); + } + return done.items; +} + +fn storage(g: *Gpu, handle: abi.Buffer) ?Storage { + const index = @backingInt(handle); + if (index == 0 or index > g.buffers.items.len) return null; + return g.buffers.items[index - 1]; +} + +/// The SDL buffers behind `handles`, into `out`; returns how many. +fn resolve(g: *Gpu, handles: []const abi.Buffer, out: []*c.SDL_GPUBuffer) !u32 { + if (handles.len > out.len) return error.TooManyBuffers; + for (handles, out[0..handles.len]) |handle, *b| b.* = (g.storage(handle) orelse return error.UnknownBuffer).buffer; + return @intCast(handles.len); +} + +fn kernel(g: *Gpu, k: abi.gpu.Kernel) !*c.SDL_GPUComputePipeline { + var h = std.hash.Wyhash.init(0); + h.update(k.code); + inline for (.{ k.readonly_buffers, k.readwrite_buffers, k.uniform_buffers, k.threads[0], k.threads[1], k.threads[2] }) |v| h.update(std.mem.asBytes(&@as(u32, v))); + const key = h.final(); + const entry = try g.kernels.getOrPut(g.gpa, key); + if (!entry.found_existing) { + errdefer _ = g.kernels.remove(key); + var info: c.SDL_GPUComputePipelineCreateInfo = std.mem.zeroes(c.SDL_GPUComputePipelineCreateInfo); + info.code_size = k.code.len; + info.code = k.code.ptr; + info.entrypoint = "main"; + info.format = c.SDL_GPU_SHADERFORMAT_SPIRV; + info.num_readonly_storage_buffers = k.readonly_buffers; + info.num_readwrite_storage_buffers = k.readwrite_buffers; + info.num_uniform_buffers = k.uniform_buffers; + info.threadcount_x = k.threads[0]; + info.threadcount_y = k.threads[1]; + info.threadcount_z = k.threads[2]; + entry.value_ptr.object = c.SDL_CreateGPUComputePipeline(g.device, &info) orelse return error.GpuComputePipeline; + } + entry.value_ptr.used = g.frame; + return entry.value_ptr.object; +} + +fn supportedSamples(g: *Gpu, wanted: u8) u8 { + var s: u8 = if (wanted >= 8) 8 else if (wanted >= 4) 4 else if (wanted >= 2) 2 else 1; + while (s > 1 and !c.SDL_GPUTextureSupportsSampleCount(g.device, color_format, sampleCount(s))) s /= 2; + return s; +} + +fn sampleCount(s: u8) c.SDL_GPUSampleCount { + return switch (s) { + 8 => c.SDL_GPU_SAMPLECOUNT_8, + 4 => c.SDL_GPU_SAMPLECOUNT_4, + 2 => c.SDL_GPU_SAMPLECOUNT_2, + else => c.SDL_GPU_SAMPLECOUNT_1, + }; +} + +/// The image's render target, (re)created to fit the pass. +fn renderTarget(g: *Gpu, images: *gfx.Images, image: abi.Image, w: u32, h: u32, samples: u8, stencil: bool) !*Target { + var entry = try g.targets.getOrPut(g.gpa, image); + if (entry.found_existing and (entry.value_ptr.width != w or entry.value_ptr.height != h)) { + g.releaseTarget(images, image, entry.value_ptr.*); + entry.found_existing = false; + } + if (!entry.found_existing) { + errdefer _ = g.targets.remove(image); + const resolved = try g.texture(w, h, color_format, c.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | c.SDL_GPU_TEXTUREUSAGE_SAMPLER, 1); + errdefer c.SDL_ReleaseGPUTexture(g.device, resolved); + try images.wrap(image, resolved, w, h); + entry.value_ptr.* = .{ .width = w, .height = h, .texture = resolved }; + } + const t = entry.value_ptr; + if (samples > 1 and (t.msaa == null or t.samples != samples)) { + if (t.msaa) |m| c.SDL_ReleaseGPUTexture(g.device, m); + t.msaa = try g.texture(w, h, color_format, c.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET, samples); + t.samples = samples; + t.msaa_fresh = true; + } + if (stencil and (t.stencil == null or t.stencil_samples != samples)) { + if (t.stencil) |s| c.SDL_ReleaseGPUTexture(g.device, s); + t.stencil = try g.texture(w, h, g.stencil_format, c.SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET, samples); + t.stencil_samples = samples; + } + return t; +} + +fn releaseTarget(g: *Gpu, images: *gfx.Images, image: abi.Image, t: Target) void { + images.unwrap(image); + c.SDL_ReleaseGPUTexture(g.device, t.texture); + if (t.msaa) |m| c.SDL_ReleaseGPUTexture(g.device, m); + if (t.stencil) |s| c.SDL_ReleaseGPUTexture(g.device, s); +} + +/// Forgets an image's target, when the image itself is freed. +pub fn forget(g: *Gpu, images: *gfx.Images, image: abi.Image) void { + const t = g.targets.fetchRemove(image) orelse return; + g.releaseTarget(images, image, t.value); +} + +fn texture(g: *Gpu, w: u32, h: u32, format: c.SDL_GPUTextureFormat, usage: c.SDL_GPUTextureUsageFlags, samples: u8) !*c.SDL_GPUTexture { + var info: c.SDL_GPUTextureCreateInfo = std.mem.zeroes(c.SDL_GPUTextureCreateInfo); + info.type = c.SDL_GPU_TEXTURETYPE_2D; + info.format = format; + info.usage = usage; + info.width = w; + info.height = h; + info.layer_count_or_depth = 1; + info.num_levels = 1; + info.sample_count = sampleCount(samples); + return c.SDL_CreateGPUTexture(g.device, &info) orelse error.GpuTexture; +} + +fn reserve(g: *Gpu, bytes: u32) !void { + if (bytes > g.vertex_capacity) { + const capacity = @max(bytes, g.vertex_capacity * 2, 64 * 1024); + if (g.vertices) |b| c.SDL_ReleaseGPUBuffer(g.device, b); + g.vertices = c.SDL_CreateGPUBuffer(g.device, &.{ .usage = c.SDL_GPU_BUFFERUSAGE_VERTEX, .size = capacity, .props = 0 }) orelse return error.GpuBuffer; + g.vertex_capacity = capacity; + } + if (bytes > g.upload_capacity) { + const capacity = @max(bytes, g.upload_capacity * 2, 64 * 1024); + if (g.upload) |b| c.SDL_ReleaseGPUTransferBuffer(g.device, b); + g.upload = c.SDL_CreateGPUTransferBuffer(g.device, &.{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = capacity, .props = 0 }) orelse return error.GpuBuffer; + g.upload_capacity = capacity; + } +} + +fn shader(g: *Gpu, s: abi.gpu.Shader, stage: c.SDL_GPUShaderStage) !struct { *c.SDL_GPUShader, u64 } { + var h = std.hash.Wyhash.init(stage); + h.update(s.code); + h.update(std.mem.asBytes(&s.uniform_buffers)); + h.update(std.mem.asBytes(&s.storage_buffers)); + const key = h.final(); + const entry = try g.shaders.getOrPut(g.gpa, key); + if (!entry.found_existing) { + errdefer _ = g.shaders.remove(key); + entry.value_ptr.object = c.SDL_CreateGPUShader(g.device, &.{ + .code_size = s.code.len, + .code = s.code.ptr, + .entrypoint = "main", + .format = c.SDL_GPU_SHADERFORMAT_SPIRV, + .stage = stage, + .num_samplers = 0, + .num_storage_textures = 0, + .num_storage_buffers = s.storage_buffers, + .num_uniform_buffers = s.uniform_buffers, + .props = 0, + }) orelse return error.GpuShader; + } + entry.value_ptr.used = g.frame; + return .{ entry.value_ptr.object, key }; +} + +fn pipeline(g: *Gpu, p: abi.gpu.Pipeline, samples: u8, stencil: bool) !*c.SDL_GPUGraphicsPipeline { + const vertex, const vertex_key = try g.shader(p.vertex, c.SDL_GPU_SHADERSTAGE_VERTEX); + const fragment, const fragment_key = try g.shader(p.fragment, c.SDL_GPU_SHADERSTAGE_FRAGMENT); + // Field by field: no padding bytes in the key. + var h = std.hash.Wyhash.init(vertex_key ^ (fragment_key *% 31)); + inline for (.{ p.stride, @backingInt(p.primitive), @backingInt(p.blend), @intFromBool(p.write_color), samples, @intFromBool(stencil) }) |v| h.update(std.mem.asBytes(&@as(u32, v))); + for (p.attributes) |a| inline for (.{ a.location, @backingInt(a.format), a.offset }) |v| h.update(std.mem.asBytes(&@as(u32, v))); + if (p.stencil) |st| inline for (.{ st.front, st.back }) |face| inline for (.{ @backingInt(face.compare), @backingInt(face.pass), @backingInt(face.fail) }) |v| h.update(std.mem.asBytes(&@as(u32, v))); + const key = h.final(); + const entry = try g.pipelines.getOrPut(g.gpa, key); + if (!entry.found_existing) { + errdefer _ = g.pipelines.remove(key); + var attributes: [16]c.SDL_GPUVertexAttribute = undefined; + const count = @min(p.attributes.len, attributes.len); + for (p.attributes[0..count], attributes[0..count]) |a, *out| out.* = .{ + .location = a.location, + .buffer_slot = 0, + .offset = a.offset, + .format = switch (a.format) { + .float => c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT, + .float2 => c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2, + .float3 => c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT3, + .float4 => c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, + .ubyte4_norm => c.SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4_NORM, + }, + }; + var blend: c.SDL_GPUColorTargetBlendState = std.mem.zeroes(c.SDL_GPUColorTargetBlendState); + blend.enable_blend = p.blend != .none; + blend.color_blend_op = c.SDL_GPU_BLENDOP_ADD; + blend.alpha_blend_op = c.SDL_GPU_BLENDOP_ADD; + blend.src_color_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE; + blend.src_alpha_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE; + const dst: c.SDL_GPUBlendFactor = if (p.blend == .additive) c.SDL_GPU_BLENDFACTOR_ONE else c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA; + blend.dst_color_blendfactor = dst; + blend.dst_alpha_blendfactor = dst; + blend.enable_color_write_mask = true; + blend.color_write_mask = if (p.write_color) c.SDL_GPU_COLORCOMPONENT_R | c.SDL_GPU_COLORCOMPONENT_G | c.SDL_GPU_COLORCOMPONENT_B | c.SDL_GPU_COLORCOMPONENT_A else 0; + const target_description: c.SDL_GPUColorTargetDescription = .{ .format = color_format, .blend_state = blend }; + var depth_stencil: c.SDL_GPUDepthStencilState = std.mem.zeroes(c.SDL_GPUDepthStencilState); + if (p.stencil) |st| { + depth_stencil.enable_stencil_test = true; + depth_stencil.compare_mask = 0xff; + depth_stencil.write_mask = 0xff; + depth_stencil.front_stencil_state = stencilFace(st.front); + depth_stencil.back_stencil_state = stencilFace(st.back); + } + var info: c.SDL_GPUGraphicsPipelineCreateInfo = std.mem.zeroes(c.SDL_GPUGraphicsPipelineCreateInfo); + info.vertex_shader = vertex; + info.fragment_shader = fragment; + info.vertex_input_state = .{ + .vertex_buffer_descriptions = &.{ .slot = 0, .pitch = p.stride, .input_rate = c.SDL_GPU_VERTEXINPUTRATE_VERTEX, .instance_step_rate = 0 }, + // No attributes: the vertex shader makes its own vertices. + .num_vertex_buffers = @intFromBool(count > 0), + .vertex_attributes = &attributes, + .num_vertex_attributes = @intCast(count), + }; + info.primitive_type = switch (p.primitive) { + .triangle_list => c.SDL_GPU_PRIMITIVETYPE_TRIANGLELIST, + .triangle_strip => c.SDL_GPU_PRIMITIVETYPE_TRIANGLESTRIP, + .line_list => c.SDL_GPU_PRIMITIVETYPE_LINELIST, + .line_strip => c.SDL_GPU_PRIMITIVETYPE_LINESTRIP, + }; + info.rasterizer_state.fill_mode = c.SDL_GPU_FILLMODE_FILL; + info.rasterizer_state.cull_mode = c.SDL_GPU_CULLMODE_NONE; + info.rasterizer_state.front_face = c.SDL_GPU_FRONTFACE_COUNTER_CLOCKWISE; + info.multisample_state.sample_count = sampleCount(samples); + info.depth_stencil_state = depth_stencil; + info.target_info.color_target_descriptions = &target_description; + info.target_info.num_color_targets = 1; + info.target_info.depth_stencil_format = g.stencil_format; + info.target_info.has_depth_stencil_target = stencil; + entry.value_ptr.object = c.SDL_CreateGPUGraphicsPipeline(g.device, &info) orelse return error.GpuPipeline; + } + entry.value_ptr.used = g.frame; + return entry.value_ptr.object; +} + +fn stencilFace(face: abi.gpu.StencilFace) c.SDL_GPUStencilOpState { + // Both enums follow SDL's order, after its INVALID. + return .{ + .compare_op = @as(u32, @backingInt(face.compare)) + 1, + .pass_op = @as(u32, @backingInt(face.pass)) + 1, + .fail_op = @as(u32, @backingInt(face.fail)) + 1, + .depth_fail_op = c.SDL_GPU_STENCILOP_KEEP, + }; +} diff --git a/src/host/memory.zig b/src/host/memory.zig index fc44e50..5fbb88f 100644 --- a/src/host/memory.zig +++ b/src/host/memory.zig @@ -20,7 +20,11 @@ pub const page = std.heap.page_size_min; /// Slot 0 is live; 1..7 are snapshots. pub const slot_count = 8; pub const header_len = 64 * 1024; -pub const file_magic = "SKETCH01".*; +/// Layouts with element leaves (`list[].x`, `StoredField` with `dims`). +pub const file_magic = "SKETCH02".*; +/// What hosts before element leaves wrote: arrays are whole leaves +/// (`StoredFieldV1`). Read, and rewritten as `file_magic` on adopt. +pub const file_magic_v1 = "SKETCH01".*; pub const Header = extern struct { magic: [8]u8 = file_magic, @@ -36,8 +40,25 @@ pub const Header = extern struct { reserved: u32 = 0, }; -/// A leaf as stored in the file: strings are offsets into the string table. +/// A leaf as stored in the file: strings are offsets into the string table, +/// and so is `dims`, `rank` little-endian (count, stride) u32 pairs. pub const StoredField = extern struct { + offset: u32, + size: u32, + hash: u64, + path: u32, + path_len: u16, + tags_len: u16, + tags: u32, + kind: abi.Field.Kind, + rank: u8 = 0, + reserved: [2]u8 = @splat(0), + dims: u32 = 0, + reserved2: u32 = 0, +}; + +/// A leaf as `file_magic_v1` files store it: no element leaves. +pub const StoredFieldV1 = extern struct { offset: u32, size: u32, hash: u64, @@ -49,6 +70,8 @@ pub const StoredField = extern struct { reserved: [3]u8 = @splat(0), }; +const Dim = abi.Field.Dim; + /// A layout the host owns: copied out of a sketch, or read from a file. pub const Layout = struct { size: usize = 0, @@ -56,6 +79,8 @@ pub const Layout = struct { hash: u64 = 0, fields: []const Leaf = &.{}, + /// A leaf with `dims` stands for all its elements (`list[].x`), at + /// `offset` plus index times stride per dimension. `find` resolves one. pub const Leaf = struct { path: []const u8, offset: u32, @@ -63,10 +88,38 @@ pub const Layout = struct { kind: abi.Field.Kind, hash: u64, tags: []const u8, + dims: []const Dim = &.{}, pub fn bytes(leaf: Leaf, memory: []const u8) []const u8 { return memory[leaf.offset..][0..leaf.size]; } + /// The leaf at `offset` (from `elements`), as a leaf of its own. + pub fn at(leaf: Leaf, offset: usize) Leaf { + var one = leaf; + one.offset = @intCast(offset); + one.dims = &.{}; + return one; + } + /// A whole array, kept for copying in one piece; its elements are + /// leaves of their own. + pub fn whole(leaf: Leaf) bool { + return leaf.kind == .array; + } + /// Offsets of every element, first index slowest. + pub fn elements(leaf: Leaf) Elements { + return .init(leaf.offset, leaf.dims, leaf.dims, null); + } + /// Writes the path naming the element at `offset`, indices filled in. + pub fn name(leaf: Leaf, offset: usize, w: *std.Io.Writer) std.Io.Writer.Error!void { + var rest = offset - leaf.offset; + var parts = std.mem.splitSequence(u8, leaf.path, "[]"); + try w.writeAll(parts.first()); + for (leaf.dims) |d| { + try w.print("[{d}]", .{rest / d.stride}); + rest %= d.stride; + try w.writeAll(parts.next() orelse ""); + } + } }; pub fn copy(arena: std.mem.Allocator, l: abi.Layout) !Layout { @@ -78,37 +131,149 @@ pub const Layout = struct { .kind = from.kind, .hash = from.hash, .tags = try arena.dupe(u8, std.mem.span(from.tags)), + .dims = try arena.dupe(Dim, from.dims[0..from.rank]), }; return .{ .size = l.size, .alignment = l.alignment, .hash = l.hash, .fields = fields }; } + /// The leaf `path` names, with indices for every array it is in + /// (`list[3].pos[0]`), as a leaf of its own; null when there is none + /// or an index is out of range. pub fn find(self: Layout, path: []const u8) ?Leaf { + for (self.fields) |leaf| { + const delta = abi.layout.match(leaf.path, leaf.dims, path) orelse continue; + return leaf.at(leaf.offset + delta); + } + return null; + } + + /// The leaf whose pattern is exactly `pattern` (`list[].x`). + pub fn pattern(self: Layout, path: []const u8) ?Leaf { for (self.fields) |leaf| if (std.mem.eql(u8, leaf.path, path)) return leaf; return null; } }; +/// Walks element offsets of one leaf, or of the elements two layouts of a +/// leaf share (`limit`, the smaller count per dimension), with offsets in +/// both. +pub const Elements = struct { + index: [abi.layout.max_rank]u32 = @splat(0), + limit: [abi.layout.max_rank]u32 = @splat(0), + rank: usize, + a: Side, + b: Side, + done: bool, + + const Side = struct { base: usize, dims: []const Dim }; + + pub fn init(base: usize, dims: []const Dim, other_dims: []const Dim, other_base: ?usize) Elements { + var e: Elements = .{ .rank = dims.len, .a = .{ .base = base, .dims = dims }, .b = .{ .base = other_base orelse base, .dims = other_dims }, .done = false }; + for (dims, other_dims, 0..) |x, y, i| { + e.limit[i] = @min(x.count, y.count); + if (e.limit[i] == 0) e.done = true; + } + return e; + } + + fn offset(e: *const Elements, side: Side) usize { + var at = side.base; + for (side.dims, 0..) |d, i| at += @as(usize, e.index[i]) * d.stride; + return at; + } + + pub fn next(e: *Elements) ?usize { + const pair = e.nextPair() orelse return null; + return pair[0]; + } + + pub fn nextPair(e: *Elements) ?[2]usize { + if (e.done) return null; + const pair: [2]usize = .{ e.offset(e.a), e.offset(e.b) }; + var i = e.rank; + while (true) { + if (i == 0) { + e.done = true; + break; + } + i -= 1; + e.index[i] += 1; + if (e.index[i] < e.limit[i]) break; + e.index[i] = 0; + } + return pair; + } +}; + pub const Migration = struct { kept: usize = 0, reset: usize = 0 }; /// Copies every leaf of `from` whose path and type are unchanged into `to`, -/// which already holds the new defaults. +/// which already holds the new defaults. Arrays copy element by element: +/// the elements both layouts have (the common prefix of each dimension; a +/// shrink drops the rest, a growth keeps the new defaults), field by field +/// inside each, enums by tag name. An array whose type is unchanged copies +/// in one piece. Counts are of leaves, not elements. pub fn migrate(from: Layout, old: []const u8, to: Layout, new: []u8) Migration { var result: Migration = .{}; + // The array copied whole most recently: its elements' leaves follow it. + var copied: ?[]const u8 = null; for (to.fields) |leaf| { - const before = from.find(leaf.path) orelse { - result.reset += 1; + if (copied) |prefix| { + if (leaf.path.len > prefix.len and std.mem.startsWith(u8, leaf.path, prefix) and leaf.path[prefix.len] == '[') continue; + copied = null; + } + const before = from.pattern(leaf.path) orelse { + if (!leaf.whole()) result.reset += 1; continue; }; + if (before.dims.len != leaf.dims.len) { + if (!leaf.whole()) result.reset += 1; + continue; + } if (before.hash == leaf.hash and before.size == leaf.size) { - @memcpy(new[leaf.offset..][0..leaf.size], before.bytes(old)); - result.kept += 1; - } else if (before.kind == .@"enum" and leaf.kind == .@"enum" and remapEnum(before, old, leaf, new)) { + var it: Elements = .init(leaf.offset, leaf.dims, before.dims, before.offset); + while (it.nextPair()) |pair| @memcpy(new[pair[0]..][0..leaf.size], old[pair[1]..][0..leaf.size]); + if (leaf.whole()) copied = leaf.path; result.kept += 1; - } else result.reset += 1; + } else if (before.kind == .@"enum" and leaf.kind == .@"enum") { + var it: Elements = .init(leaf.offset, leaf.dims, before.dims, before.offset); + var any = false; + var seen: usize = 0; + while (it.nextPair()) |pair| : (seen += 1) { + if (remapEnum(before.at(pair[1]), old, leaf.at(pair[0]), new)) any = true; + } + if (any or seen == 0) result.kept += 1 else result.reset += 1; + } else if (!leaf.whole()) result.reset += 1; } return result; } +pub const Diff = struct { + /// Leaf values (elements counted one by one) that differ. + count: usize = 0, + first: ?Place = null, + last: ?Place = null, + + pub const Place = struct { leaf: Layout.Leaf, offset: usize }; +}; + +/// Compares two copies of state leaf by leaf, so padding (a Debug +/// `@Vector`'s spare lane, the gaps between fields) never differs. +pub fn compare(layout: Layout, a: []const u8, b: []const u8) Diff { + var diff: Diff = .{}; + for (layout.fields) |leaf| { + if (leaf.whole()) continue; + var it = leaf.elements(); + while (it.next()) |offset| { + if (std.mem.eql(u8, a[offset..][0..leaf.size], b[offset..][0..leaf.size])) continue; + diff.count += 1; + if (diff.first == null) diff.first = .{ .leaf = leaf, .offset = offset }; + diff.last = .{ .leaf = leaf, .offset = offset }; + } + } + return diff; +} + /// Carries an enum over by tag name; false when its name no longer exists. fn remapEnum(from: Layout.Leaf, old: []const u8, to: Layout.Leaf, new: []u8) bool { const name = field_value.tagName(from.tags, field_value.readInt(i64, from.bytes(old))) orelse return false; @@ -124,22 +289,23 @@ pub const StateFile = struct { layout: Layout, arena: std.heap.ArenaAllocator, - /// Opens or creates `path`. A missing or foreign file has no layout and no - /// used slots: the first `adopt` fills it. + /// Opens or creates `path`. A new (empty) file has no layout and no used + /// slots: the first `adopt` fills it. A file that is not a state file + /// this host can read is refused, never truncated: it may be someone's + /// work, written by another build. pub fn open(gpa: std.mem.Allocator, path: []const u8) !StateFile { const fd = try posix.openat(posix.AT.FDCWD, path, .{ .ACCMODE = .RDWR, .CREAT = true }, 0o600); errdefer _ = posix.system.close(fd); var self: StateFile = .{ .fd = fd, .map = &.{}, .layout = .{}, .arena = .init(gpa) }; errdefer self.arena.deinit(); const len = try fileSize(fd); - if (len >= header_len) { + if (len > 0) { + if (len < header_len) return error.NotAStateFile; self.map = try mapFile(fd, @intCast(len), .{ .READ = true, .WRITE = true }); - if (self.valid()) { - self.layout = try readLayout(self.arena.allocator(), self.map) orelse .{}; - return self; - } - posix.munmap(self.map); - self.map = &.{}; + errdefer posix.munmap(self.map); + try self.check(); + self.layout = try readLayout(self.arena.allocator(), self.map) orelse .{}; + return self; } try self.resize(0); self.header().* = .{ .size = 0, .alignment = 1, .hash = 0, .stride = 0, .used = 0, .field_count = 0, .strings_len = 0 }; @@ -181,7 +347,18 @@ pub const StateFile = struct { /// Makes the file hold `new`'s layout. Used slots are migrated: `defaults` /// writes the new default values, then unchanged fields are copied over. pub fn adopt(self: *StateFile, gpa: std.mem.Allocator, new: abi.Layout, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !Adoption { - if (self.layout.hash == new.hash and self.layout.size == new.size and self.header().used & 1 != 0) return .unchanged; + if (self.layout.hash == new.hash and self.layout.size == new.size and self.header().used & 1 != 0) { + // Same type, older header: describe it again, bytes untouched. + if (std.mem.eql(u8, &self.header().magic, &file_magic_v1)) { + var kept = self.arena; + defer kept.deinit(); + self.arena = .init(gpa); + self.layout = try Layout.copy(self.arena.allocator(), new); + try writeLayout(self.map[0..header_len], self.layout); + self.header().magic = file_magic; + } + return .unchanged; + } const had_state = self.header().used & 1 != 0; // Keep the old bytes and layout while the file is rebuilt. @@ -202,7 +379,7 @@ pub const StateFile = struct { const stride = std.mem.alignForward(usize, @max(new.size, 1), page); try self.resize(stride); const h = self.header(); - h.* = .{ .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = stride, .used = old_used, .field_count = 0, .strings_len = 0 }; + h.* = .{ .magic = file_magic, .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = stride, .used = old_used, .field_count = 0, .strings_len = 0 }; try writeLayout(self.map[0..header_len], self.layout); var total: Migration = .{}; @@ -222,10 +399,10 @@ pub const StateFile = struct { return .{ .migrated = total }; } - fn valid(self: *StateFile) bool { + fn check(self: *StateFile) !void { const h = self.header(); - if (!std.mem.eql(u8, &h.magic, &file_magic)) return false; - return self.map.len >= header_len + slot_count * h.stride and h.size <= h.stride; + if (!std.mem.eql(u8, &h.magic, &file_magic) and !std.mem.eql(u8, &h.magic, &file_magic_v1)) return error.NotAStateFile; + if (self.map.len < header_len + slot_count * h.stride or h.size > h.stride) return error.CorruptStateFile; } fn resize(self: *StateFile, stride: usize) !void { @@ -240,17 +417,24 @@ pub const StateFile = struct { } }; -/// Writes `layout`'s leaves after the `Header` at the start of `region`. +/// Writes `layout`'s leaves after the `Header` at the start of `region`, +/// in the current format (`StoredField`); the caller sets the magic. fn writeLayout(region: []u8, layout: Layout) !void { const h: *Header = @ptrCast(@alignCast(region.ptr)); const fields: [*]StoredField = @ptrCast(@alignCast(region.ptr + @sizeOf(Header))); const strings_start = @sizeOf(Header) + layout.fields.len * @sizeOf(StoredField); var strings: usize = 0; for (layout.fields, 0..) |leaf, i| { - if (strings_start + strings + leaf.path.len + leaf.tags.len > region.len) return error.LayoutTooLarge; + const dims_len = leaf.dims.len * @sizeOf(Dim); + if (strings_start + strings + leaf.path.len + leaf.tags.len + dims_len > region.len) return error.LayoutTooLarge; const base = strings_start + strings; @memcpy(region[base..][0..leaf.path.len], leaf.path); @memcpy(region[base + leaf.path.len ..][0..leaf.tags.len], leaf.tags); + for (leaf.dims, 0..) |d, j| { + const at = base + leaf.path.len + leaf.tags.len + j * @sizeOf(Dim); + std.mem.writeInt(u32, region[at..][0..4], d.count, .little); + std.mem.writeInt(u32, region[at + 4 ..][0..4], d.stride, .little); + } fields[i] = .{ .offset = leaf.offset, .size = leaf.size, @@ -260,24 +444,42 @@ fn writeLayout(region: []u8, layout: Layout) !void { .path_len = @intCast(leaf.path.len), .tags = @intCast(strings + leaf.path.len), .tags_len = @intCast(leaf.tags.len), + .rank = @intCast(leaf.dims.len), + .dims = @intCast(strings + leaf.path.len + leaf.tags.len), }; - strings += leaf.path.len + leaf.tags.len; + strings += leaf.path.len + leaf.tags.len + dims_len; } h.field_count = @intCast(layout.fields.len); h.strings_len = @intCast(strings); } -/// The layout stored in a state file's header, or null if it has none. +/// The layout stored in a state or store file's header, or null if it has +/// none. Reads both formats, by magic: a v1 header (`file_magic_v1`, +/// `store_layout_magic_v1`) has no element leaves, so its arrays are whole +/// leaves only, which migrate while their type is unchanged. pub fn readLayout(arena: std.mem.Allocator, map: []const u8) !?Layout { const h: *const Header = @ptrCast(@alignCast(map.ptr)); if (h.hash == 0 and h.field_count == 0) return null; - const stored: [*]const StoredField = @ptrCast(@alignCast(map.ptr + @sizeOf(Header))); - const strings_start = @sizeOf(Header) + h.field_count * @sizeOf(StoredField); - if (strings_start + h.strings_len > header_len) return error.CorruptHeader; + const v1 = std.mem.eql(u8, &h.magic, &file_magic_v1) or std.mem.eql(u8, &h.magic, &store_layout_magic_v1); + const stride: usize = if (v1) @sizeOf(StoredFieldV1) else @sizeOf(StoredField); + const strings_start = @sizeOf(Header) + @as(usize, h.field_count) * stride; + if (strings_start + h.strings_len > header_len or map.len < header_len) return error.CorruptHeader; const strings = map[strings_start..][0..h.strings_len]; const leaves = try arena.alloc(Layout.Leaf, h.field_count); - for (leaves, stored[0..h.field_count]) |*leaf, f| { - if (f.path + f.path_len > strings.len or f.tags + f.tags_len > strings.len) return error.CorruptHeader; + for (leaves, 0..) |*leaf, i| { + const at = @sizeOf(Header) + i * stride; + const f: StoredField = if (v1) blk: { + const old: *const StoredFieldV1 = @ptrCast(@alignCast(map[at..].ptr)); + break :blk .{ .offset = old.offset, .size = old.size, .hash = old.hash, .path = old.path, .path_len = old.path_len, .tags = old.tags, .tags_len = old.tags_len, .kind = old.kind }; + } else @as(*const StoredField, @ptrCast(@alignCast(map[at..].ptr))).*; + const dims_len = @as(usize, f.rank) * @sizeOf(Dim); + if (f.path + f.path_len > strings.len or f.tags + f.tags_len > strings.len or f.dims + dims_len > strings.len) return error.CorruptHeader; + if (f.rank > abi.layout.max_rank) return error.CorruptHeader; + const dims = try arena.alloc(Dim, f.rank); + for (dims, 0..) |*d, j| { + const raw = strings[f.dims + j * @sizeOf(Dim) ..]; + d.* = .{ .count = std.mem.readInt(u32, raw[0..4], .little), .stride = std.mem.readInt(u32, raw[4..8], .little) }; + } // Copied: the mapping moves when the file is resized. leaf.* = .{ .path = try arena.dupe(u8, strings[f.path..][0..f.path_len]), @@ -286,7 +488,12 @@ pub fn readLayout(arena: std.mem.Allocator, map: []const u8) !?Layout { .kind = f.kind, .hash = f.hash, .tags = try arena.dupe(u8, strings[f.tags..][0..f.tags_len]), + .dims = dims, }; + // Every element must lie inside the state. + var end: usize = @as(usize, leaf.offset) + leaf.size; + for (dims) |d| end += @as(usize, d.stride) * (d.count -| 1); + if (end > h.size) return error.CorruptHeader; } return .{ .size = h.size, .alignment = h.alignment, .hash = h.hash, .fields = leaves }; } @@ -318,7 +525,11 @@ pub fn mapReadOnly(path: []const u8) []align(page) const u8 { pub const store_base: usize = 0x2000_0000_0000; /// The most a store can grow to. Only reserved: pages exist as they are used. pub const store_reserve: usize = 64 << 30; +/// The allocator's record (`Meta`); unchanged by the layout format. pub const store_magic = "SKSTORE1".*; +/// The store's layout header, like `file_magic` and `file_magic_v1`. +pub const store_layout_magic = "SKSTORE2".*; +pub const store_layout_magic_v1 = "SKSTORE1".*; /// The layout region is a state file header; the allocator's own record /// follows, then the heap. const meta_offset = header_len; @@ -368,13 +579,15 @@ pub const StoreFile = struct { var self: StoreFile = .{ .fd = fd, .len = 0, .layout = .{}, .arena = .init(gpa) }; errdefer self.arena.deinit(); const size: usize = @intCast(try fileSize(fd)); - if (!fresh and size >= heap_offset) { + if (!fresh and size > 0) { + // Checked before mapping, which may lengthen the file: a file + // that is not a store is refused untouched, never wiped. + var m: Meta = undefined; + const read = linux.pread(fd, std.mem.asBytes(&m), @sizeOf(Meta), meta_offset); + if (size < heap_offset or read != @sizeOf(Meta) or !std.mem.eql(u8, &m.magic, &store_magic) or m.base != store_base or m.top > size) return error.NotAStoreFile; try self.grow(size); - const m = self.meta(); - if (std.mem.eql(u8, &m.magic, &store_magic) and m.base == store_base and m.top <= size) { - self.layout = try readLayout(self.arena.allocator(), self.region()) orelse .{}; - return self; - } + self.layout = try readLayout(self.arena.allocator(), self.region()) orelse .{}; + return self; } try self.wipe(); return self; @@ -396,7 +609,7 @@ pub const StoreFile = struct { try truncate(self.fd, heap_offset); try self.grow(heap_offset); @memset(self.region(), 0); - self.header().* = .{ .magic = store_magic, .size = 0, .alignment = 1, .hash = 0, .stride = 0, .used = 0, .field_count = 0, .strings_len = 0 }; + self.header().* = .{ .magic = store_layout_magic, .size = 0, .alignment = 1, .hash = 0, .stride = 0, .used = 0, .field_count = 0, .strings_len = 0 }; self.meta().* = .{}; self.layout = .{}; } @@ -452,7 +665,7 @@ pub const StoreFile = struct { result = .{ .migrated = migrate(old_layout, old[0..old_layout.size], self.layout, fresh[0..new.size]) }; a.rawFree(old[0..@max(old_layout.size, 1)], .fromByteUnits(@max(old_layout.alignment, 1)), @returnAddress()); } - self.header().* = .{ .magic = store_magic, .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = 0, .used = 1, .field_count = 0, .strings_len = 0 }; + self.header().* = .{ .magic = store_layout_magic, .size = new.size, .alignment = new.alignment, .hash = new.hash, .stride = 0, .used = 1, .field_count = 0, .strings_len = 0 }; try writeLayout(self.region(), self.layout); m.root = @intFromPtr(fresh) - store_base; return result; @@ -723,3 +936,192 @@ test "a store keeps its root and what it points to across a reopen, and migrates defer store.close(); try std.testing.expectEqual(StoreFile.Adoption.created, try store.adopt(gpa, abi.layout.of(V2, .store), D.v2)); } + +test "arrays migrate element by element: fields, enums by name, shrink and growth" { + const E1 = struct { x: f32 = 0, mood: enum(u8) { calm = 1, wild = 2 } = .calm }; + const E2 = struct { added: u8 = 9, mood: enum(u8) { wild = 5, calm = 6, sleepy = 7 } = .sleepy, x: f32 = 0 }; + const V1 = struct { list: struct { buffer: [4]E1 = @splat(.{}), len: u32 = 0 } = .{}, samples: [4]u16 = @splat(0), pos: [2]f32 = @splat(0), grid: [2][3]u8 = @splat(@splat(0)) }; + const V2 = struct { list: struct { buffer: [2]E2 = @splat(.{}), len: u32 = 0 } = .{}, samples: [6]u16 = @splat(5), pos: @Vector(2, f32) = @splat(0), grid: [3][2]u8 = @splat(@splat(0)) }; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const l1 = try Layout.copy(arena.allocator(), abi.layout.of(V1, .state)); + const l2 = try Layout.copy(arena.allocator(), abi.layout.of(V2, .state)); + var old: V1 = .{ .samples = .{ 1, 2, 3, 4 }, .pos = .{ 3, 4 }, .grid = .{ .{ 1, 2, 3 }, .{ 4, 5, 6 } } }; + for (&old.list.buffer, 0..) |*e, i| e.* = .{ .x = @floatFromInt(i + 1), .mood = if (i % 2 == 0) .calm else .wild }; + old.list.len = 4; + var new: V2 = .{}; + _ = migrate(l1, std.mem.asBytes(&old), l2, std.mem.asBytes(&new)); + try std.testing.expectEqual(E2{ .added = 9, .mood = .calm, .x = 1 }, new.list.buffer[0]); + try std.testing.expectEqual(E2{ .added = 9, .mood = .wild, .x = 2 }, new.list.buffer[1]); + // `len` is kept as it was: a List clamps it where it is read. + try std.testing.expectEqual(@as(u32, 4), new.list.len); + try std.testing.expectEqual([6]u16{ 1, 2, 3, 4, 5, 5 }, new.samples); + try std.testing.expectEqual(@as(f32, 4), new.pos[1]); + try std.testing.expectEqual([3][2]u8{ .{ 1, 2 }, .{ 4, 5 }, .{ 0, 0 } }, new.grid); + + // Growing back: the kept elements return, new ones take defaults. + var back: V1 = .{}; + _ = migrate(l2, std.mem.asBytes(&new), l1, std.mem.asBytes(&back)); + try std.testing.expectEqual(@as(f32, 2), back.list.buffer[1].x); + try std.testing.expectEqual(@as(f32, 0), back.list.buffer[2].x); + try std.testing.expectEqual(.wild, back.list.buffer[1].mood); +} + +test "an array of songs keeps its songs when a song gains a field" { + const Note = struct { pitch: u8 = 0, length: u8 = 1 }; + const Song1 = struct { name: [8]u8 = @splat(0), notes: [16]Note = @splat(.{}), tempo: u16 = 120 }; + const Song2 = struct { tempo: u16 = 120, swing: f32 = 0.5, notes: [16]Note = @splat(.{}), name: [8]u8 = @splat(0) }; + const V1 = struct { songs: [8]Song1 = @splat(.{}), other: u32 = 0 }; + const V2 = struct { added: u8 = 1, songs: [8]Song2 = @splat(.{}) }; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const l1 = try Layout.copy(arena.allocator(), abi.layout.of(V1, .state)); + const l2 = try Layout.copy(arena.allocator(), abi.layout.of(V2, .state)); + var old: V1 = .{}; + for (&old.songs, 0..) |*song, i| { + song.name = "song 0".*; + song.name[7] = '0' + @as(u8, @intCast(i)); + song.tempo = @intCast(100 + i); + for (&song.notes, 0..) |*n, j| n.* = .{ .pitch = @intCast(i * 16 + j), .length = 2 }; + } + var new: V2 = .{}; + const m = migrate(l1, std.mem.asBytes(&old), l2, std.mem.asBytes(&new)); + for (old.songs, new.songs) |a, b| { + try std.testing.expectEqualSlices(u8, &a.name, &b.name); + try std.testing.expectEqual(a.tempo, b.tempo); + try std.testing.expectEqual(@as(f32, 0.5), b.swing); + for (a.notes, b.notes) |x, y| try std.testing.expectEqual(x, y); + } + // songs[].notes is unchanged, so it copies whole; swing and added are new. + try std.testing.expectEqual(@as(usize, 2), m.reset); + // The same type on both sides copies in one piece. + var same: V1 = .{}; + try std.testing.expectEqual(@as(usize, 2), migrate(l1, std.mem.asBytes(&old), l1, std.mem.asBytes(&same)).kept); + try std.testing.expectEqualDeep(old, same); +} + +test "compare goes leaf by leaf: padding never differs" { + const S = struct { a: u8 = 1, b: u32 = 2, v: @Vector(3, f32) = .{ 1, 2, 3 }, list: [2]struct { c: u8 = 0, d: u16 = 0 } = @splat(.{}) }; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const layout = try Layout.copy(arena.allocator(), abi.layout.of(S, .state)); + var x: S = .{}; + var y: S = .{}; + const a = std.mem.asBytes(&x); + const b = std.mem.asBytes(&y); + @memcpy(b, a); + // Every byte no leaf covers. + var covered: [@sizeOf(S)]bool = @splat(false); + for (layout.fields) |leaf| { + if (leaf.whole()) continue; + var it = leaf.elements(); + while (it.next()) |offset| @memset(covered[offset..][0..leaf.size], true); + } + var padding: usize = 0; + for (covered, 0..) |c, i| if (!c) { + b[i] ^= 0xff; + padding += 1; + }; + try std.testing.expect(padding >= 4); + try std.testing.expectEqual(@as(usize, 0), compare(layout, a, b).count); + y.list[1].d = 7; + y.v[2] = 0; + const diff = compare(layout, a, b); + try std.testing.expectEqual(@as(usize, 2), diff.count); + var buf: [64]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + try diff.last.?.leaf.name(diff.last.?.offset, &w); + try std.testing.expectEqualStrings("list[1].d", w.buffered()); +} + +fn testPath(buf: []u8, tmp: anytype, name: []const u8) ![]const u8 { + return std.mem.print(buf, ".zig-cache/tmp/{s}/{s}", .{ &tmp.sub_path, name }); +} + +test "a file that is not a state file is refused, untouched" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const io = std.testing.io; + var buf: [std.fs.max_path_bytes]u8 = undefined; + for ([_]usize{ 100, 3 * header_len }) |len| { + const path = try testPath(&buf, tmp, "notes.state"); + const text = try std.testing.allocator.alloc(u8, len); + defer std.testing.allocator.free(text); + @memset(text, 'x'); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = text }); + try std.testing.expectError(error.NotAStateFile, StateFile.open(std.testing.allocator, path)); + const after = try std.Io.Dir.cwd().readFileAlloc(io, path, std.testing.allocator, .unlimited); + defer std.testing.allocator.free(after); + try std.testing.expectEqualSlices(u8, text, after); + } +} + +test "a state file from before element leaves (drat-meout's) keeps every value" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const path = try testPath(&buf, tmp, "game.state"); + const original = try std.Io.Dir.cwd().readFileAlloc(io, "test/fixtures/drat-meout-v1.state-fixture", gpa, .unlimited); + defer gpa.free(original); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = original }); + try std.testing.expectEqualStrings(&file_magic_v1, original[0..8]); + + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const old = (try readLayout(a, original)).?; + try std.testing.expect(old.find("tracker.songs") != null); + const h: *const Header = @ptrCast(@alignCast(original.ptr)); + const live = original[header_len..][0..h.size]; + + // The layout the game had when it wrote the file, as a sketch would + // describe it: unchanged, so nothing migrates and the header is + // rewritten in the new format. + const same = try asSketchLayout(a, old, &.{}); + { + var file = try StateFile.open(gpa, path); + defer file.close(); + try std.testing.expectEqual(StateFile.Adoption.unchanged, try file.adopt(gpa, same, NoDefaults.f)); + try std.testing.expectEqualStrings(&file_magic, &file.header().magic); + } + var file = try StateFile.open(gpa, path); + defer file.close(); + try std.testing.expectEqual(old.fields.len, file.layout.fields.len); + try std.testing.expectEqualSlices(u8, live, file.slot(0)); + + // A changed layout (one field gone, one new): every other leaf keeps + // its value, the songs included (an unchanged array type, so whole). + const changed = try asSketchLayout(a, old, "scene"); + _ = try file.adopt(gpa, changed, NoDefaults.f); + for (old.fields) |leaf| { + if (std.mem.eql(u8, leaf.path, "scene")) continue; + try std.testing.expectEqualSlices(u8, leaf.bytes(live), leaf.bytes(file.slot(0))); + } + try std.testing.expectEqual(@as(u8, 0), file.slot(0)[h.size]); +} + +const NoDefaults = struct { + fn f(_: abi.Memory, _: [*]u8) callconv(.c) void {} +}; + +/// `l` as `abi.Layout`, without the leaf at `drop` and with a new byte +/// leaf `added` past the end, the type hash changed accordingly. +fn asSketchLayout(a: std.mem.Allocator, l: Layout, drop: []const u8) !abi.Layout { + var fields: std.ArrayList(abi.Field) = .empty; + for (l.fields) |leaf| { + if (std.mem.eql(u8, leaf.path, drop)) continue; + try fields.append(a, .{ + .path = try a.dupeSentinel(u8, leaf.path, 0), + .offset = leaf.offset, + .size = leaf.size, + .kind = leaf.kind, + .hash = leaf.hash, + .tags = try a.dupeSentinel(u8, leaf.tags, 0), + }); + } + if (drop.len == 0) return .{ .size = l.size, .alignment = l.alignment, .hash = l.hash, .fields = fields.items }; + try fields.append(a, .{ .path = "added", .offset = @intCast(l.size), .size = 1, .kind = .uint, .hash = abi.layout.hash(u8) }); + return .{ .size = l.size + 1, .alignment = l.alignment, .hash = l.hash ^ 1, .fields = fields.items }; +} diff --git a/src/host/overlay.zig b/src/host/overlay.zig index 919fff6..5219a83 100644 --- a/src/host/overlay.zig +++ b/src/host/overlay.zig @@ -16,7 +16,10 @@ fn shade(path: []const u8) abi.Color { } pub fn drawMemory(out: *List, arena: std.mem.Allocator, layout: memory.Layout, state: []const u8, width: f32) !void { - const rows = (layout.fields.len + 1) / 2; + // Arrays show as wholes: their element leaves (`list[].x`) are left out. + var top_level: usize = 0; + for (layout.fields) |leaf| top_level += @intFromBool(leaf.dims.len == 0); + const rows = (top_level + 1) / 2; const legend_top: f32 = 24; const hex_top = legend_top + @as(f32, @floatFromInt(rows)) * 14 + 16; const shown = @min(state.len, shown_bytes); @@ -26,7 +29,11 @@ pub fn drawMemory(out: *List, arena: std.mem.Allocator, layout: memory.Layout, s // Legend: two fixed-width columns filled down then across. const column = (width - 60) / 2; - for (layout.fields, 0..) |leaf, i| { + var row: usize = 0; + for (layout.fields) |leaf| { + if (leaf.dims.len != 0) continue; + const i = row; + row += 1; var value: std.Io.Writer.Allocating = .init(arena); try fields.format(leaf, state, &value.writer); const name = if (leaf.path.len > 26) try std.fmt.allocPrint(arena, "{s}...", .{leaf.path[0..23]}) else leaf.path; @@ -42,7 +49,7 @@ pub fn drawMemory(out: *List, arena: std.mem.Allocator, layout: memory.Layout, s var colors: [shown_bytes]abi.Color = @splat(.{ .r = 0x9f, .g = 0x9f, .b = 0x9f }); for (layout.fields) |leaf| { - if (leaf.offset >= shown) continue; + if (leaf.offset >= shown or leaf.dims.len != 0) continue; @memset(colors[leaf.offset..@min(shown, leaf.offset + leaf.size)], shade(leaf.path)); } for (state[0..shown], 0..) |byte, i| { diff --git a/src/host/probe.zig b/src/host/probe.zig index 4a693ec..d8ed166 100644 --- a/src/host/probe.zig +++ b/src/host/probe.zig @@ -30,6 +30,8 @@ pub fn main(init: std.process.Init) !void { const file = path orelse fatal("no state file given"); const map = memory.mapReadOnly(file); if (map.len < memory.header_len) fatal("not a sketchbook state file"); + const magic = map[0..8]; + if (!std.mem.eql(u8, magic, &memory.file_magic) and !std.mem.eql(u8, magic, &memory.file_magic_v1)) fatal("not a sketchbook state file"); defer std.posix.munmap(map); var arena: std.heap.ArenaAllocator = .init(init.gpa); defer arena.deinit(); @@ -52,9 +54,29 @@ fn show(path: []const u8, layout: memory.Layout, live: []const u8) void { var w: std.Io.Writer = .fixed(&buf); std.debug.print("{s}: {d} bytes, layout {x:0>16}\n", .{ path, live.len, layout.hash }); for (layout.fields) |leaf| { + // Whole arrays are shown by their elements' leaves. + if (leaf.whole()) continue; w.end = 0; - fields.format(leaf, live, &w) catch {}; - std.debug.print(" +0x{x:0>4} {s:<28} {s}\n", .{ leaf.offset, leaf.path, w.buffered() }); + if (leaf.dims.len == 0) { + fields.format(leaf, live, &w) catch {}; + } else { + // Elements in index order, the first few. + var it = leaf.elements(); + var n: usize = 0; + while (it.next()) |offset| : (n += 1) { + if (n == 8) { + w.writeAll(" ...") catch {}; + break; + } + if (n > 0) w.writeAll(" ") catch {}; + fields.format(leaf.at(offset), live, &w) catch {}; + } + } + var name: [128]u8 = undefined; + var nw: std.Io.Writer = .fixed(&name); + nw.writeAll(leaf.path) catch {}; + for (leaf.dims) |d| nw.print(" [{d}]", .{d.count}) catch {}; + std.debug.print(" +0x{x:0>4} {s:<28} {s}\n", .{ leaf.offset, nw.buffered(), w.buffered() }); } } diff --git a/src/host/root.zig b/src/host/root.zig index 2876c0f..8cc15e1 100644 --- a/src/host/root.zig +++ b/src/host/root.zig @@ -59,6 +59,22 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void { } if (linked == null and options.library == null) fatal("no sketch library given (see --help)"); + // A scripted run from fresh state works on files of its own, moved to + // the given path at exit: two runs of one build step (two `zig build`s + // at once share its output path) never share a state, store or + // recordings file, nor fail on the store's lock. + var private_buf: [std.fs.max_path_bytes]u8 = undefined; + const given = options.state; + const private = script_path != null and options.fresh; + if (private) options.state = std.mem.print(&private_buf, "{s}.{d}", .{ given, std.os.linux.getpid() }) catch fatal("--state path too long"); + defer if (private) for ([_][]const u8{ "", ".inputs", ".store" }) |suffix| { + var from: [std.fs.max_path_bytes + 16]u8 = undefined; + var to: [std.fs.max_path_bytes + 16]u8 = undefined; + const a = std.mem.printSentinel(&from, "{s}{s}", .{ options.state, suffix }, 0) catch continue; + const b = std.mem.printSentinel(&to, "{s}{s}", .{ given, suffix }, 0) catch continue; + _ = std.os.linux.rename(a.ptr, b.ptr); + }; + sdl_heap.install(); { var host: Host = undefined; diff --git a/src/host/script.zig b/src/host/script.zig index cf551cd..7818c6b 100644 --- a/src/host/script.zig +++ b/src/host/script.zig @@ -8,21 +8,46 @@ //! cancel what losing focus sends //! key NAME press and release a key (`sketch.Key` names) //! type TEXT text input, as typed into a focused field -//! console LINE run a console command +//! console LINE run a console command (`console get` +//! takes no frame: it only reads) //! frames N advance N frames without input -//! expect FIELD VALUE compare a state field (enums by name or number) -//! await FIELD VALUE run frames until it holds (a minute at most) +//! expect FIELD VALUE compare a state field (enums by name or number); +//! FIELD may index arrays and vector lanes, +//! `boids.buffer[3].pos[0]` +//! expect FIELD VALUE ~T numbers within T of VALUE +//! await FIELD VALUE [~T] run frames until it holds (a minute at most) +//! print FIELD write a field's value to stderr (a vector, +//! array or struct: every value in it), no frame +//! expect-snapshot N live state equals snapshot N, leaf by leaf +//! (padding ignored), exactly +//! expect-log TEXT a recent console line contains TEXT +//! expect-no-log TEXT no recent console line does //! expect-audio KEY stream KEY has received samples //! screenshot FILE save the next frame as PNG +//! expect-same-screenshot A B [MAX [X Y W H]] +//! two saved PNGs match, every channel within MAX +//! (default 0), in the rect if given (pixels) +//! expect-different-screenshot A B [X Y W H] +//! two saved PNGs differ somewhere (in the rect) +//! expect-pixel FILE X Y R G B A [TOL] +//! a saved PNG's pixel, every channel within TOL //! load LIBRARY swap in another build of the sketch //! reload load the watched library again //! await-reload SECONDS run frames until a build replaces the library //! //! `{name}` is replaced by `--define name=value` from the command line. +//! +//! Each line but `frames`, `print`, `console get`, the expectations and +//! `await-reload` is followed by one frame; `update` gets one call per +//! frame, live or replayed, so +//! `console play` then `frames N` replays N recorded frames at the +//! script's 60 Hz. const std = @import("std"); +const c = @import("c"); const abi = @import("abi"); const Host = @import("Host.zig"); const fields = @import("fields.zig"); +const memory = @import("memory.zig"); pub const frame_ns: u64 = std.time.ns_per_s / 60; /// The most frames `await` plays: a minute. @@ -84,28 +109,102 @@ fn step(host: *Host, arena: std.mem.Allocator, command: []const u8, rest: []cons std.debug.print(" console {s}: {t}\n", .{ rest, err }); return err; }; + if (std.mem.startsWith(u8, rest, "get ")) return; + } else if (eq(u8, command, "print")) { + const path = words.next() orelse return error.ExpectedField; + var buf: [4096]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + fields.formatPath(host.state.layout, host.live(), path, &w) catch |err| switch (err) { + error.UnknownField => return error.UnknownField, + error.WriteFailed => {}, + }; + std.debug.print("{s} = {s}\n", .{ path, w.buffered() }); + return; } else if (eq(u8, command, "frames")) { const count = try std.fmt.parseInt(usize, rest, 10); for (0..count) |_| try advance(host, now); return; } else if (eq(u8, command, "expect") or eq(u8, command, "await")) { const path = words.next() orelse return error.ExpectedField; - const want = std.mem.trim(u8, words.rest(), " \t"); - const leaf = host.state.layout.find(path) orelse return error.UnknownField; + const want, const tolerance = try expected(std.mem.trim(u8, words.rest(), " \t")); + // Looked up again after each frame: a reload may move the field. + _ = host.state.layout.find(path) orelse return error.UnknownField; // `await` plays frames until the field holds the value, for up to a // minute: for waits whose length is the sketch's business. if (eq(u8, command, "await")) { var waited: usize = 0; - while (!fields.matches(leaf, host.live(), want) and waited < await_limit) : (waited += 1) try advance(host, now); + while (!holds(host, path, want, tolerance) and waited < await_limit) : (waited += 1) try advance(host, now); } - if (!fields.matches(leaf, host.live(), want)) { + if (!holds(host, path, want, tolerance)) { var buf: [128]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); - fields.format(leaf, host.live(), &w) catch {}; - std.debug.print(" {s}: expected {s}, found {s}\n", .{ path, want, w.buffered() }); + fields.formatPath(host.state.layout, host.live(), path, &w) catch |err| switch (err) { + error.UnknownField => w.writeAll("no such field") catch {}, + error.WriteFailed => {}, + }; + if (tolerance) |t| { + std.debug.print(" {s}: expected {s} ~{d}, found {s}\n", .{ path, want, t, w.buffered() }); + } else std.debug.print(" {s}: expected {s}, found {s}\n", .{ path, want, w.buffered() }); + return error.ExpectationFailed; + } + return; + } else if (eq(u8, command, "expect-snapshot")) { + const index = std.fmt.parseInt(usize, rest, 10) catch return error.InvalidSlot; + if (!host.timeline.bank.hasSnapshot(index)) return error.EmptySnapshot; + if (!same(host, index)) return error.ExpectationFailed; + return; + } else if (eq(u8, command, "expect-log") or eq(u8, command, "expect-no-log")) { + var found = false; + for (&host.console.lines) |*l| { + if (std.mem.indexOf(u8, l.bytes[0..l.len], rest) != null) found = true; + } + if (found != eq(u8, command, "expect-log")) { + std.debug.print(" console log:\n", .{}); + for (&host.console.lines) |*l| std.debug.print(" {s}\n", .{l.bytes[0..l.len]}); return error.ExpectationFailed; } return; + } else if (eq(u8, command, "expect-same-screenshot") or eq(u8, command, "expect-different-screenshot")) { + const a = words.next() orelse return error.ExpectedFile; + const b = words.next() orelse return error.ExpectedFile; + const want_same = eq(u8, command, "expect-same-screenshot"); + const max: u8 = if (!want_same) 0 else if (words.next()) |m| std.fmt.parseInt(u8, m, 10) catch return error.InvalidValue else 0; + var rect: ?[4]usize = null; + if (words.next()) |x| { + var r: [4]usize = undefined; + r[0] = std.fmt.parseInt(usize, x, 10) catch return error.InvalidRect; + for (r[1..]) |*v| v.* = std.fmt.parseInt(usize, words.next() orelse return error.InvalidRect, 10) catch return error.InvalidRect; + rect = r; + } + const diff = try comparePng(arena, a, b, max, rect); + if ((diff.count == 0) != want_same) { + if (want_same) { + std.debug.print(" {s} vs {s}: {d} pixels differ by more than {d}, first at {d},{d}\n", .{ a, b, diff.count, max, diff.first[0], diff.first[1] }); + } else std.debug.print(" {s} and {s} are the same\n", .{ a, b }); + return error.ExpectationFailed; + } + return; + } else if (eq(u8, command, "expect-pixel")) { + const file = words.next() orelse return error.ExpectedFile; + var n: [7]u8 = .{ 0, 0, 0, 0, 0, 0, 0 }; + var x: usize = 0; + var y: usize = 0; + for (0..7) |i| { + const word = words.next() orelse if (i == 6) break else return error.ExpectedPixel; + if (i < 2) { + (if (i == 0) &x else &y).* = std.fmt.parseInt(usize, word, 10) catch return error.ExpectedPixel; + } else n[i - 2] = std.fmt.parseInt(u8, word, 0) catch return error.ExpectedPixel; + } + const tol = n[4]; + const surface = try loadPng(arena, file); + defer c.SDL_DestroySurface(surface); + if (x >= surface.*.w or y >= surface.*.h) return error.OutsideScreenshot; + const p = (@as([*]const u8, @ptrCast(surface.*.pixels.?)) + y * @as(usize, @intCast(surface.*.pitch)) + x * 4)[0..4]; + for (p, n[0..4]) |got, want| if (@max(got, want) - @min(got, want) > tol) { + std.debug.print(" {s} at {d},{d}: expected {d} {d} {d} {d}, found {d} {d} {d} {d}\n", .{ file, x, y, n[0], n[1], n[2], n[3], p[0], p[1], p[2], p[3] }); + return error.ExpectationFailed; + }; + return; } else if (eq(u8, command, "expect-audio")) { const key = try std.fmt.parseInt(u32, rest, 10); if (host.input.stream(key).pushed == 0) return error.ExpectationFailed; @@ -144,6 +243,89 @@ fn held(host: *const Host) u8 { return abi.Event.withModifiers(mods); } +/// "VALUE" or "VALUE ~TOLERANCE". +fn expected(text: []const u8) !struct { []const u8, ?f64 } { + const tilde = std.mem.lastIndexOfScalar(u8, text, '~') orelse return .{ text, null }; + const tolerance = std.fmt.parseFloat(f64, std.mem.trim(u8, text[tilde + 1 ..], " \t")) catch return error.InvalidTolerance; + return .{ std.mem.trim(u8, text[0..tilde], " \t"), tolerance }; +} + +fn holds(host: *Host, path: []const u8, want: []const u8, tolerance: ?f64) bool { + const leaf = host.state.layout.find(path) orelse return false; + const t = tolerance orelse return fields.matches(leaf, host.live(), want); + const value = fields.number(leaf, host.live()) orelse return false; + const target = std.fmt.parseFloat(f64, want) catch return false; + return @abs(value - target) <= t; +} + +/// Live state against snapshot `index`, leaf by leaf; prints the first few +/// differences. +fn same(host: *Host, index: usize) bool { + const layout = host.state.layout; + const live = host.live(); + const saved = host.timeline.bank.slot(index); + var count: usize = 0; + for (layout.fields) |leaf| { + if (leaf.whole()) continue; + var it = leaf.elements(); + while (it.next()) |offset| { + if (std.mem.eql(u8, live[offset..][0..leaf.size], saved[offset..][0..leaf.size])) continue; + count += 1; + if (count > 5) continue; + var buf: [256]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + leaf.name(offset, &w) catch {}; + w.writeAll(": live ") catch {}; + fields.format(leaf.at(offset), live, &w) catch {}; + w.print(", snapshot {d} ", .{index}) catch {}; + fields.format(leaf.at(offset), saved, &w) catch {}; + std.debug.print(" {s}\n", .{w.buffered()}); + } + } + if (count > 5) std.debug.print(" ... {d} differing values in all\n", .{count}); + return count == 0; +} + +const PngDiff = struct { count: usize = 0, first: [2]usize = .{ 0, 0 } }; + +/// Pixels whose channels differ by more than `max`; a size mismatch +/// counts every pixel. +fn comparePng(arena: std.mem.Allocator, a: []const u8, b: []const u8, max: u8, rect: ?[4]usize) !PngDiff { + const sa = try loadPng(arena, a); + defer c.SDL_DestroySurface(sa); + const sb = try loadPng(arena, b); + defer c.SDL_DestroySurface(sb); + if (sa.*.w != sb.*.w or sa.*.h != sb.*.h) return .{ .count = @intCast(@max(sa.*.w * sa.*.h, sb.*.w * sb.*.h, 1)) }; + var diff: PngDiff = .{}; + const w: usize = @intCast(sa.*.w); + const h: usize = @intCast(sa.*.h); + const r = rect orelse [4]usize{ 0, 0, w, h }; + for (@min(r[1], h)..@min(r[1] + r[3], h)) |y| { + const ra: [*]const u8 = @as([*]const u8, @ptrCast(sa.*.pixels.?)) + y * @as(usize, @intCast(sa.*.pitch)); + const rb: [*]const u8 = @as([*]const u8, @ptrCast(sb.*.pixels.?)) + y * @as(usize, @intCast(sb.*.pitch)); + for (@min(r[0], w)..@min(r[0] + r[2], w)) |x| { + const differs = for (0..4) |i| { + const p = ra[x * 4 + i]; + const q = rb[x * 4 + i]; + if (@max(p, q) - @min(p, q) > max) break true; + } else false; + if (!differs) continue; + if (diff.count == 0) diff.first = .{ x, y }; + diff.count += 1; + } + } + return diff; +} + +fn loadPng(arena: std.mem.Allocator, path: []const u8) !*c.SDL_Surface { + const loaded = c.SDL_LoadPNG((try arena.dupeSentinel(u8, path, 0)).ptr) orelse { + std.debug.print(" {s}: {s}\n", .{ path, c.SDL_GetError() }); + return error.ScreenshotUnreadable; + }; + defer c.SDL_DestroySurface(loaded); + return c.SDL_ConvertSurface(loaded, c.SDL_PIXELFORMAT_RGBA32) orelse error.ScreenshotUnreadable; +} + fn advance(host: *Host, now: *u64) !void { try host.frame(now.*); now.* += frame_ns; diff --git a/src/host/timeline.zig b/src/host/timeline.zig index cd65478..8a5448a 100644 --- a/src/host/timeline.zig +++ b/src/host/timeline.zig @@ -3,6 +3,11 @@ //! //! Playback is host state, not sketch state: wall clocks, modes and cursors //! must not contaminate byte comparisons between two runs of a sketch. +//! +//! Recordings are frames: each frame's events, then its `tick`. Playback, +//! seek and step only ever stop between frames, and `frames` cuts a run of +//! events into them, so `update` sees exactly the frames it saw live, one +//! call each. const std = @import("std"); const posix = std.posix; const abi = @import("abi"); @@ -19,13 +24,52 @@ pub const Recording = extern struct { count: u32, snapshot: u32, magic: u32, - reserved: [3]u32, + /// The build that recorded it (`build`, two halves), 0 when unknown. + build_low: u32, + build_high: u32, + reserved: u32, events: [capacity]abi.Event, slack: [recording_len - 32 - capacity * @sizeOf(abi.Event)]u8, pub fn slice(r: *const Recording) []const abi.Event { return r.events[0..r.count]; } + pub fn build(r: *const Recording) u64 { + return @as(u64, r.build_high) << 32 | r.build_low; + } + /// Events up to the end of the last whole frame. + pub fn whole(r: *const Recording) usize { + return frameStart(r.slice(), r.count); + } +}; + +/// The largest frame boundary at or before `index`: 0, or just after a tick. +pub fn frameStart(events: []const abi.Event, index: usize) usize { + var i = @min(index, events.len); + while (i > 0 and events[i - 1].kind != .tick) i -= 1; + return i; +} + +/// Cuts events into frames, each ending with its tick. Events after the +/// last tick (a frame not finished) are never returned. +pub fn frames(events: []const abi.Event) Frames { + return .{ .events = events }; +} + +pub const Frames = struct { + events: []const abi.Event, + start: usize = 0, + + pub fn next(f: *Frames) ?[]const abi.Event { + var i = f.start; + while (i < f.events.len) : (i += 1) { + if (f.events[i].kind != .tick) continue; + const frame = f.events[f.start .. i + 1]; + f.start = i + 1; + return frame; + } + return null; + } }; comptime { @@ -65,16 +109,9 @@ pub const Bank = struct { if (r.magic != recording_magic or r.count > capacity or !self.hasSnapshot(r.snapshot)) return error.EmptyRecording; return r; } - pub const Diff = struct { count: usize = 0, first: ?usize = null, last: ?usize = null }; - pub fn compare(self: Bank, a: usize, b: usize) Diff { - var diff: Diff = .{}; - for (self.slot(a), self.slot(b), 0..) |x, y, i| { - if (x == y) continue; - diff.count += 1; - if (diff.first == null) diff.first = i; - diff.last = i; - } - return diff; + /// Leaf by leaf (`memory.compare`): padding never differs. + pub fn compare(self: Bank, a: usize, b: usize) memory.Diff { + return memory.compare(self.state.layout, self.slot(a), self.slot(b)); } }; @@ -85,37 +122,55 @@ pub const Timeline = struct { cursor: usize = 0, position: u64 = 0, clock: u64 = 0, + /// Set whenever live state is restored from a snapshot, for the host + /// to reset the input state that went with the old bytes. + restored: bool = false, + + /// Restores a snapshot into live state. + pub fn restore(self: *Timeline, index: usize) !void { + try self.bank.restore(index); + self.restored = true; + } - pub fn startRecording(self: *Timeline, index: usize, snapshot: usize, now: u64) !void { + /// `build` identifies the code recording (0: unknown); `play` warns + /// when it differs. + pub fn startRecording(self: *Timeline, index: usize, snapshot: usize, now: u64, build: u64) !void { // An unused snapshot captures the current state; an existing one is // restored, so several recordings can branch from exactly those bytes. if (!self.bank.hasSnapshot(snapshot)) self.bank.save(snapshot); - try self.bank.restore(snapshot); + try self.restore(snapshot); const r = self.bank.recording(index); @memset(std.mem.asBytes(r)[0..32], 0); r.magic = recording_magic; r.snapshot = @intCast(snapshot); + r.build_low = @truncate(build); + r.build_high = @truncate(build >> 32); self.selected = index; self.cursor = 0; self.position = 0; self.clock = now; self.mode = .recording; } - pub fn capture(self: *Timeline, event: abi.Event) !void { + /// Records one frame (its events, then its tick) and rewrites their + /// times as recorded, so live `update` sees exactly what a replay will. + /// A frame that does not fit ends the recording before it. + pub fn capture(self: *Timeline, frame: []abi.Event) !void { if (self.mode != .recording) return; const r = self.bank.recording(self.selected); - if (r.count == capacity) { + if (frame.len > capacity - r.count) { self.mode = .live; return error.RecordingFull; } - var e = event; - // Queued events can predate the start command. Keep insertion order and - // nondecreasing times, including several events at the same timestamp. - e.time = @max(e.time -| self.clock, r.duration); - r.events[r.count] = e; - r.count += 1; - r.duration = e.time; - self.position = e.time; + for (frame) |*e| { + // Queued events can predate the start command. Keep insertion + // order and nondecreasing times, including several events at the + // same timestamp. + e.time = @max(e.time -| self.clock, r.duration); + r.events[r.count] = e.*; + r.count += 1; + r.duration = e.time; + } + self.position = r.duration; self.cursor = r.count; } pub fn stop(self: *Timeline, now: u64) void { @@ -128,7 +183,7 @@ pub const Timeline = struct { } pub fn play(self: *Timeline, index: usize, now: u64) !void { const r = try self.bank.get(index); - try self.bank.restore(r.snapshot); + try self.restore(r.snapshot); self.selected = index; self.cursor = 0; self.position = 0; @@ -143,53 +198,61 @@ pub const Timeline = struct { self.mode = .playing; } } - /// The recorded events due by `now`. Feed them to the same `update` that - /// live input goes through. + /// The recorded frames due by `now`: whole frames, whose ticks are due + /// (a frame's input comes before its tick, so input alone is never + /// due). Feed them to the same `update` that live input goes through. pub fn tick(self: *Timeline, now: u64) []const abi.Event { if (self.mode != .playing) return &.{}; const r = self.bank.recording(self.selected); self.position = @min(r.duration, self.position +| (now -| self.clock)); self.clock = now; const start = self.cursor; - while (self.cursor < r.count and r.events[self.cursor].time <= self.position) self.cursor += 1; + var i = self.cursor; + while (i < r.count and r.events[i].time <= self.position) : (i += 1) { + if (r.events[i].kind == .tick) self.cursor = i + 1; + } if (self.position == r.duration) self.mode = .paused; return r.events[start..self.cursor]; } - /// Restores the snapshot and returns the first `count` events to replay, - /// so seeking backwards works too. + /// Restores the snapshot and returns the frames that make up the first + /// `count` events (rounded down to a whole frame) to replay, so seeking + /// backwards works too. pub fn seekCount(self: *Timeline, count: usize) ![]const abi.Event { const r = try self.bank.get(self.selected); - try self.bank.restore(r.snapshot); - self.cursor = @min(count, r.count); + try self.restore(r.snapshot); + self.cursor = frameStart(r.slice(), count); self.position = if (self.cursor == 0) 0 else r.events[self.cursor - 1].time; self.mode = .paused; return r.events[0..self.cursor]; } + /// To the last frame whose tick is at or before `time`. pub fn seekTime(self: *Timeline, time: u64) ![]const abi.Event { const r = try self.bank.get(self.selected); const position = @min(time, r.duration); var count: usize = 0; - while (count < r.count and r.events[count].time <= position) count += 1; + for (r.slice(), 0..) |e, i| { + if (e.time > position) break; + if (e.kind == .tick) count = i + 1; + } const events = try self.seekCount(count); self.position = position; return events; } - /// Moves by `steps` input events, passing over frame ticks. + /// Moves by `steps` frames, forwards or back. pub fn step(self: *Timeline, steps: i64) ![]const abi.Event { const r = try self.bank.get(self.selected); - var cursor = self.cursor; + const events = r.slice(); + var cursor = frameStart(events, self.cursor); var remaining = @abs(steps); while (remaining > 0) : (remaining -= 1) { if (steps > 0) { - while (cursor < r.count and r.events[cursor].kind == .tick) cursor += 1; - if (cursor == r.count) break; + const end = r.whole(); + if (cursor == end) break; cursor += 1; - // Include the frame's tick so time-driven sketches advance too. - while (cursor < r.count and r.events[cursor].kind == .tick) cursor += 1; + while (cursor < end and events[cursor - 1].kind != .tick) cursor += 1; } else { - while (cursor > 0 and r.events[cursor - 1].kind == .tick) cursor -= 1; if (cursor == 0) break; - cursor -= 1; + cursor = frameStart(events, cursor - 1); } } return self.seekCount(cursor); @@ -206,3 +269,76 @@ pub fn mapRecordings(path: []const u8) ![]align(memory.page) u8 { }; return memory.mapFile(fd, recordings_len, .{ .READ = true, .WRITE = true }); } + +test "frames are whole: input waits for its tick, live and in playback" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + // A bank on plain memory: one slot of 8 bytes, snapshot 1 used. + var file: memory.StateFile = undefined; + file.map = try a.alignedAlloc(u8, .fromByteUnits(memory.page), memory.header_len + memory.slot_count * memory.page); + @memset(file.map, 0); + file.header().* = .{ .size = 8, .alignment = 1, .hash = 1, .stride = memory.page, .used = 0b11, .field_count = 0, .strings_len = 0 }; + file.layout = .{}; + const inputs = try a.alignedAlloc(u8, .fromByteUnits(memory.page), recording_len); + @memset(inputs, 0); + var t: Timeline = .{ .bank = .{ .state = &file, .inputs = inputs } }; + // Frame k: a move at 10k ms, its tick at 10k + 5 ms; then a move with + // no tick (a frame cut off). + try t.startRecording(0, 1, 1000, 7); + try std.testing.expect(t.restored); + for (0..4) |k| { + var frame = [_]abi.Event{ + .{ .kind = .mouse_move, .time = 1000 + k * 10_000_000, .x = @floatFromInt(k) }, + abi.Event.tick(1000 + k * 10_000_000 + 5_000_000, 16_666_667), + }; + try t.capture(&frame); + // Live update sees the recorded times. + try std.testing.expectEqual(@as(u64, k * 10_000_000 + 5_000_000), frame[1].time); + } + const r = t.bank.recording(0); + r.events[r.count] = .{ .kind = .mouse_move, .time = 40_000_000 }; + r.count += 1; + t.stop(1000 + 41_000_000); + try std.testing.expectEqual(@as(u64, 7), r.build()); + + try t.play(0, 0); + var delivered: usize = 0; + // Every moment between 0 and the end, 1 ms apart. + var now: u64 = 0; + while (t.mode == .playing) : (now += 1_000_000) { + const events = t.tick(now); + if (events.len == 0) continue; + try std.testing.expectEqual(abi.Event.Kind.tick, events[events.len - 1].kind); + var it = frames(events); + while (it.next()) |frame| { + try std.testing.expectEqual(@as(usize, 2), frame.len); + delivered += 1; + } + } + try std.testing.expectEqual(@as(usize, 4), delivered); + try std.testing.expectEqual(@as(usize, 8), t.cursor); + + // A seek between a frame's input and its tick stops before the frame. + try std.testing.expectEqual(@as(usize, 4), (try t.seekTime(22_000_000)).len); + try std.testing.expectEqual(@as(usize, 8), (try t.seekCount(r.count)).len); + try std.testing.expectEqual(@as(usize, 6), (try t.step(-1)).len); + try std.testing.expectEqual(@as(usize, 8), (try t.step(5)).len); + try std.testing.expectEqual(@as(usize, 2), (try t.step(-3)).len); + // The cut-off frame is never fed. + var it = frames(r.slice()); + var n: usize = 0; + while (it.next()) |_| n += 1; + try std.testing.expectEqual(@as(usize, 4), n); +} + +test "a tick's dt reads back the same live and replayed" { + // E4: nanoseconds do not survive f32 seconds; both sides read the f32. + for ([_]u64{ 16_666_667, 16_666_666, 15_000_001, 33_333_333, 0, 1 }) |dt| { + const live = abi.Event.tick(5, dt); + var recorded = live; + recorded.time = 0; + try std.testing.expectEqual(live.tickDt(), recorded.tickDt()); + try std.testing.expect(@abs(@as(i64, @intCast(live.tickDt())) - @as(i64, @intCast(dt))) < 8); + } +} diff --git a/src/layout.zig b/src/layout.zig index 5c97ca1..3fb381b 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -1,9 +1,16 @@ //! Comptime reflection of a sketch's memory into `abi.Layout`. //! -//! Structs are flattened into dotted leaf paths; everything else (arrays, -//! optionals, unions) is one leaf. Each leaf carries a structural hash of its -//! type, so a host can tell, across a reload, which bytes still mean the same -//! thing. +//! Structs are flattened into dotted leaf paths, and arrays and vectors into +//! element leaves: `boids: [64]Boid` gives one leaf `boids[].pos[]` for every +//! boid's every lane, with each `[]`'s count and stride in `dims`, rather +//! than 128 leaves. Each array also stays as a whole (`boids`, kind +//! `array`), which a host copies in one piece while its type is unchanged. +//! Optionals, unions and packed structs are one leaf. Each leaf carries a +//! structural hash of its type, so a host can tell, across a reload, which +//! bytes still mean the same thing. Padding is in no leaf. +//! +//! A concrete path names indices (`boids[3].pos[1]`); `match` resolves one +//! against a leaf's pattern at lookup time. //! //! What each kind of sketch memory may hold: //! - State is saved to disk and snapshotted: no pointers, and no host @@ -26,7 +33,7 @@ pub fn of(comptime T: type, comptime memory: abi.Memory) abi.Layout { .session => {}, } const Leaves = struct { - const list = flatten(T, "", 0); + const list = flatten(T, "", 0, &.{}); const fields: [list.len]abi.Field = list[0..list.len].*; }; break :blk .{ @@ -38,25 +45,50 @@ pub fn of(comptime T: type, comptime memory: abi.Memory) abi.Layout { }; } -fn flatten(comptime T: type, comptime prefix: []const u8, comptime base: usize) []const abi.Field { +pub const Dim = abi.Field.Dim; +/// The most arrays a leaf may sit in. +pub const max_rank = 8; + +fn flatten(comptime T: type, comptime prefix: []const u8, comptime base: usize, comptime dims: []const Dim) []const abi.Field { comptime { - if (@typeInfo(T) != .@"struct") return &.{leaf(T, if (prefix.len == 0) "value" else prefix, base)}; - var leaves: []const abi.Field = &.{}; - const s = @typeInfo(T).@"struct"; - for (s.field_names, s.field_types, s.field_attrs) |name, F, attrs| { - if (attrs.@"comptime" or @sizeOf(F) == 0) continue; - const path = if (prefix.len == 0) name else prefix ++ "." ++ name; - const offset = base + @offsetOf(T, name); - leaves = leaves ++ if (@typeInfo(F) == .@"struct" and @typeInfo(F).@"struct".backing_integer == null) - flatten(F, path, offset) - else - &[_]abi.Field{leaf(F, path, offset)}; + const here = if (prefix.len == 0) "value" else prefix; + switch (@typeInfo(T)) { + .@"struct" => |s| if (s.backing_integer == null) { + var leaves: []const abi.Field = &.{}; + for (s.field_names, s.field_types, s.field_attrs) |name, F, attrs| { + if (attrs.@"comptime" or @sizeOf(F) == 0) continue; + const path = if (prefix.len == 0) name else prefix ++ "." ++ name; + leaves = leaves ++ flatten(F, path, base + @offsetOf(T, name), dims); + } + return leaves; + }, + .array => |a| return elements(T, a.child, a.len, here, base, dims), + .vector => |v| if (lanes(v.child)) return elements(T, v.child, v.len, here, base, dims), + else => {}, } - return leaves; + return &.{leaf(T, here, base, dims)}; + } +} + +/// The whole array, then its elements' leaves. +fn elements(comptime T: type, comptime Child: type, comptime len: usize, comptime path: []const u8, comptime base: usize, comptime dims: []const Dim) []const abi.Field { + comptime { + if (dims.len == max_rank) @compileError("arrays nested deeper than " ++ std.fmt.comptimePrint("{d}", .{max_rank}) ++ " in sketch memory: " ++ path); + const whole = &[_]abi.Field{leaf(T, path, base, dims)}; + if (@sizeOf(Child) == 0) return whole; + return whole ++ flatten(Child, path ++ "[]", base, dims ++ &[_]Dim{.{ .count = len, .stride = @sizeOf(Child) }}); } } -fn leaf(comptime T: type, comptime path: []const u8, comptime offset: usize) abi.Field { +/// Vector lanes are addressable bytes only for whole-byte numbers. +fn lanes(comptime Child: type) bool { + return switch (@typeInfo(Child)) { + .int, .float => @bitSizeOf(Child) == 8 * @sizeOf(Child), + else => false, + }; +} + +fn leaf(comptime T: type, comptime path: []const u8, comptime offset: usize, comptime dims: []const Dim) abi.Field { comptime { const kind: abi.Field.Kind = switch (@typeInfo(T)) { .int => |i| if (i.signedness == .signed) .int else .uint, @@ -64,8 +96,10 @@ fn leaf(comptime T: type, comptime path: []const u8, comptime offset: usize) abi .bool => .bool, .@"enum" => .@"enum", .array => .array, + .vector => |v| if (lanes(v.child)) .array else .bytes, else => .bytes, }; + const stored = dims[0..dims.len].*; return .{ .path = std.fmt.comptimePrint("{s}", .{path}), .offset = offset, @@ -73,10 +107,54 @@ fn leaf(comptime T: type, comptime path: []const u8, comptime offset: usize) abi .kind = kind, .hash = hash(T), .tags = if (kind == .@"enum") tags(T) else "", + .rank = dims.len, + .dims = &stored, }; } } +/// The byte offset of `path`, which names indices (`list[3].pos[1]`), from +/// a leaf's own offset, when it is an element of the leaf with `pattern` +/// (`list[].pos[]`) and `dims`; null when it is not, or out of range. +pub fn match(pattern: []const u8, dims: []const Dim, path: []const u8) ?usize { + var p: usize = 0; + var q: usize = 0; + var d: usize = 0; + var offset: usize = 0; + while (p < pattern.len) { + if (pattern[p] == '[' and p + 1 < pattern.len and pattern[p + 1] == ']') { + if (q >= path.len or path[q] != '[') return null; + const start = q + 1; + q = start; + while (q < path.len and std.ascii.isDigit(path[q])) q += 1; + if (q == start or q >= path.len or path[q] != ']' or d >= dims.len) return null; + const index = std.fmt.parseInt(u32, path[start..q], 10) catch return null; + if (index >= dims[d].count) return null; + offset += @as(usize, index) * dims[d].stride; + d += 1; + q += 1; + p += 2; + } else { + if (q >= path.len or path[q] != pattern[p]) return null; + p += 1; + q += 1; + } + } + return if (q == path.len) offset else null; +} + +pub const Resolved = struct { field: abi.Field, offset: usize }; + +/// The field `path` names, indices resolved: for readers of a sketch's own +/// reflected layout (the web host's `sk_field`). +pub fn resolve(fields: []const abi.Field, path: []const u8) ?Resolved { + for (fields) |f| { + const delta = match(std.mem.span(f.path), f.dims[0..f.rank], path) orelse continue; + return .{ .field = f, .offset = f.offset + delta }; + } + return null; +} + fn check(comptime T: type, comptime memory: []const u8, comptime path: []const u8, comptime pointers: bool) void { comptime { if (T == abi.Image or T == abi.Audio or T == abi.Buffer) @compileError(memory ++ " cannot hold host handles (" ++ path ++ "): they mean nothing to the next process. Keep them in Session."); @@ -146,17 +224,44 @@ pub fn signature(comptime T: type) []const u8 { } } -test "leaves flatten structs, keep arrays whole and reject nothing pointer-free" { +test "leaves flatten structs, and arrays into element leaves" { const Inner = extern struct { a: u8 = 0, b: enum(u8) { x, y = 5 } = .x }; const S = extern struct { inner: Inner = .{}, list: [4]f32 = @splat(0), flag: bool = false }; const l = of(S, .state); const fields = l.fields; - try std.testing.expectEqual(4, fields.len); + try std.testing.expectEqual(5, fields.len); try std.testing.expectEqualStrings("inner.a", std.mem.span(fields[0].path)); try std.testing.expectEqualStrings("inner.b", std.mem.span(fields[1].path)); try std.testing.expectEqualStrings("x=0,y=5", std.mem.span(fields[1].tags)); try std.testing.expectEqual(abi.Field.Kind.array, fields[2].kind); + try std.testing.expectEqualStrings("list", std.mem.span(fields[2].path)); try std.testing.expectEqual(@as(u32, 4), fields[2].offset); + try std.testing.expectEqualStrings("list[]", std.mem.span(fields[3].path)); + try std.testing.expectEqual(abi.Field.Kind.float, fields[3].kind); + try std.testing.expectEqual(@as(u8, 1), fields[3].rank); + try std.testing.expectEqual(Dim{ .count = 4, .stride = 4 }, fields[3].dims[0]); try std.testing.expect(hash([4]f32) != hash([5]f32)); try std.testing.expect(hash(enum(u8) { a }) != hash(enum(u8) { a, b })); } + +test "vector lanes and nested array elements resolve by index" { + const Boid = struct { pos: @Vector(2, f32) = @splat(0), mood: enum(u8) { calm = 1, wild = 2 } = .calm }; + const S = struct { boids: struct { buffer: [8]Boid = @splat(.{}), len: u32 = 0 } = .{}, grid: [3][2]u16 = @splat(@splat(0)), mask: @Vector(4, bool) = @splat(false) }; + var s: S = .{}; + s.boids.buffer[3].pos[1] = 7.5; + s.grid[2][1] = 9; + const fields = of(S, .state).fields; + const bytes = std.mem.asBytes(&s); + const pos = resolve(fields, "boids.buffer[3].pos[1]").?; + try std.testing.expectEqualStrings("boids.buffer[].pos[]", std.mem.span(pos.field.path)); + try std.testing.expectEqual(@as(f32, 7.5), @as(f32, @bitCast(bytes[pos.offset..][0..4].*))); + const cell = resolve(fields, "grid[2][1]").?; + try std.testing.expectEqual(@as(u16, 9), std.mem.readInt(u16, bytes[cell.offset..][0..2], .little)); + try std.testing.expect(resolve(fields, "boids.buffer[8].pos[0]") == null); + try std.testing.expect(resolve(fields, "boids.buffer[1].pos[2]") == null); + try std.testing.expect(resolve(fields, "boids.buffer[].pos[0]") == null); + try std.testing.expect(resolve(fields, "boids.buffer[1]x") == null); + try std.testing.expectEqual(abi.Field.Kind.@"enum", resolve(fields, "boids.buffer[0].mood").?.field.kind); + try std.testing.expectEqual(abi.Field.Kind.bytes, resolve(fields, "mask").?.field.kind); + try std.testing.expectEqual(abi.Field.Kind.array, resolve(fields, "boids.buffer[2].pos").?.field.kind); +} diff --git a/src/math/noise.zig b/src/math/noise.zig new file mode 100644 index 0000000..07764cf --- /dev/null +++ b/src/math/noise.zig @@ -0,0 +1,157 @@ +//! Noise, without a table: see `noise`. +const std = @import("std"); + +/// Smooth noise in 0..1, like Processing's and p5's `noise()`: four octaves +/// of gradient noise, each at twice the frequency and half the weight of the +/// one before, around 0.5. Neighbouring inputs give neighbouring values; one +/// unit is roughly one bump. Pass 0 for unused axes (`noise(seed, t, 0, 0)` +/// is 1D noise). +/// +/// Its spread is Processing's: standard deviation about 0.11 (0.12 in 1D), +/// almost all of it within 0.1..0.9, so `noise → angle` turns all the way +/// round as in the book. Each octave is shifted by an irrational offset, +/// so integer inputs are not special (plain Perlin noise is 0 at every +/// lattice point). The mean is 0.5 (Processing's is about 0.47). +/// +/// No table and no state: the lattice gradients come from hashing the +/// integer coordinates with `seed`, so the seed can be a State field and +/// changing it is free. Only f32 arithmetic and integer hashing, no +/// library calls, so the bits are the same on every target (native and +/// wasm32, Debug and release; tested). Coordinates are clamped to ±1e9. +pub fn noise(seed: u32, x: f32, y: f32, z: f32) f32 { + var sum: f32 = 0; + var weight: f32 = 0.5; + var frequency: f32 = 1; + for (octave_offsets, 0..) |o, octave| { + const s = seed +% @as(u32, @intCast(octave)) *% 0x9e3779b9; + sum += weight * gradient(s, x * frequency + o[0], y * frequency + o[1], z * frequency + o[2]); + weight *= 0.5; + frequency *= 2; + } + // One octave of 3D gradient noise has a deviation of about 0.2; the + // octaves together about 0.16, scaled here to Processing's 0.11. + return std.math.clamp(0.5 + 0.7 * sum, 0, 1); +} + +/// Fractions of multiples of the golden ratio (and of the plastic number, +/// for z): far from every lattice point and from each other. +const octave_offsets = [4][3]f32{ + .{ 0.6180340, 0.3819660, 0.7548777 }, + .{ 0.2360680, 0.7639320, 0.5097553 }, + .{ 0.8541020, 0.1458980, 0.2646330 }, + .{ 0.4721360, 0.5278640, 0.0195106 }, +}; + +/// Ken Perlin's improved noise at one octave, about -1..1, with the +/// permutation table replaced by a hash. +fn gradient(seed: u32, x: f32, y: f32, z: f32) f32 { + const fx = @floor(std.math.clamp(x, -1e9, 1e9)); + const fy = @floor(std.math.clamp(y, -1e9, 1e9)); + const fz = @floor(std.math.clamp(z, -1e9, 1e9)); + const ix: u32 = @bitCast(@as(i32, @intFromFloat(fx))); + const iy: u32 = @bitCast(@as(i32, @intFromFloat(fy))); + const iz: u32 = @bitCast(@as(i32, @intFromFloat(fz))); + const dx = clampUnit(x - fx); + const dy = clampUnit(y - fy); + const dz = clampUnit(z - fz); + const u = fade(dx); + const v = fade(dy); + const w = fade(dz); + const x0 = lerp(grad(lattice(seed, ix, iy, iz), dx, dy, dz), grad(lattice(seed, ix +% 1, iy, iz), dx - 1, dy, dz), u); + const x1 = lerp(grad(lattice(seed, ix, iy +% 1, iz), dx, dy - 1, dz), grad(lattice(seed, ix +% 1, iy +% 1, iz), dx - 1, dy - 1, dz), u); + const x2 = lerp(grad(lattice(seed, ix, iy, iz +% 1), dx, dy, dz - 1), grad(lattice(seed, ix +% 1, iy, iz +% 1), dx - 1, dy, dz - 1), u); + const x3 = lerp(grad(lattice(seed, ix, iy +% 1, iz +% 1), dx, dy - 1, dz - 1), grad(lattice(seed, ix +% 1, iy +% 1, iz +% 1), dx - 1, dy - 1, dz - 1), u); + return lerp(lerp(x0, x1, v), lerp(x2, x3, v), w); +} + +/// Past ±2^24 a float has no fraction left, and rounding may give 1. +fn clampUnit(t: f32) f32 { + return @min(@max(t, 0), 1); +} + +fn fade(t: f32) f32 { + return t * t * t * (t * (t * 6 - 15) + 10); +} + +fn lerp(a: f32, b: f32, t: f32) f32 { + return a + t * (b - a); +} + +/// A well-mixed 32-bit hash of a lattice point (lowbias32's finalizer). +fn lattice(seed: u32, x: u32, y: u32, z: u32) u32 { + var h = seed ^ (x *% 0x8da6b343) ^ (y *% 0xd8163841) ^ (z *% 0xcb1ab31f); + h ^= h >> 16; + h *%= 0x7feb352d; + h ^= h >> 15; + h *%= 0x846ca68b; + h ^= h >> 16; + return h; +} + +/// One of Perlin's 12 edge gradients (4 of them twice), dotted with the +/// offset. +fn grad(hash: u32, x: f32, y: f32, z: f32) f32 { + const h = hash >> 28; + const u = if (h < 8) x else y; + const v = if (h < 4) y else if (h == 12 or h == 14) x else z; + return (if (h & 1 == 0) u else -u) + (if (h & 2 == 0) v else -v); +} + +/// Golden values, as bits: the test runs on native targets and, through +/// `zig build test`, on wasm32-wasi too, so a change in either shows. +const noise_goldens = [_]struct { seed: u32, p: [3]f32, bits: u32 }{ + .{ .seed = 0, .p = .{ 0, 0, 0 }, .bits = 0x3f14f2bf }, + .{ .seed = 0, .p = .{ 0.5, 0, 0 }, .bits = 0x3ef55b7e }, + .{ .seed = 1, .p = .{ 0.3, 0.7, 0 }, .bits = 0x3f01da7c }, + .{ .seed = 7, .p = .{ 12.25, -3.5, 0.125 }, .bits = 0x3efb37d9 }, + .{ .seed = 42, .p = .{ 1000.1, 2000.2, 3.3 }, .bits = 0x3f142994 }, + .{ .seed = 0xdeadbeef, .p = .{ -0.01, 5.5, 99.9 }, .bits = 0x3edcff5c }, +}; + +test "noise is smooth, in 0..1, and the same bits everywhere" { + var lo: f32 = 1; + var hi: f32 = 0; + var previous = noise(3, 0, 0, 1.5); + for (1..4000) |i| { + const t = @as(f32, @floatFromInt(i)) * 0.01; + const n = noise(3, t, t * 0.5, 1.5); + try std.testing.expect(n >= 0 and n <= 1); + try std.testing.expect(@abs(n - previous) < 0.1); + lo = @min(lo, n); + hi = @max(hi, n); + previous = n; + } + try std.testing.expect(hi - lo > 0.5); + try std.testing.expect(noise(1, 0.3, 0.7, 0) != noise(2, 0.3, 0.7, 0)); + for (noise_goldens) |g| { + const n = noise(g.seed, g.p[0], g.p[1], g.p[2]); + std.testing.expectEqual(g.bits, @as(u32, @bitCast(n))) catch |err| { + std.debug.print("noise({d}, {d}, {d}, {d}) = {d} (0x{x})\n", .{ g.seed, g.p[0], g.p[1], g.p[2], n, @as(u32, @bitCast(n)) }); + return err; + }; + } +} + +test "noise has Processing's spread, and lattice points are not special" { + // Processing's noise() on this grid (flow_field's, 0.1 apart, z = 0): + // deviation 0.111, range 0.08..0.81, over 50 seeds. + var sum: f64 = 0; + var squares: f64 = 0; + var count: f64 = 0; + for (0..50) |seed| for (0..32) |i| for (0..18) |j| { + const v: f64 = noise(@intCast(seed), @as(f32, @floatFromInt(i)) * 0.1, @as(f32, @floatFromInt(j)) * 0.1, 0); + sum += v; + squares += v * v; + count += 1; + }; + const mean = sum / count; + const deviation = @sqrt(squares / count - mean * mean); + try std.testing.expect(@abs(mean - 0.5) < 0.02); + try std.testing.expect(deviation > 0.095 and deviation < 0.13); + var at_half: u32 = 0; + for (0..100) |i| { + const v = noise(9, @floatFromInt(i), @floatFromInt(i * 7 % 13), 0); + if (v == 0.5) at_half += 1; + } + try std.testing.expectEqual(@as(u32, 0), at_half); +} diff --git a/src/math/root.zig b/src/math/root.zig new file mode 100644 index 0000000..f9f2ffe --- /dev/null +++ b/src/math/root.zig @@ -0,0 +1,327 @@ +//! Points, vectors, affine transforms, cubic Béziers and noise: the one +//! geometry module, `sk.math` in sketches and `vector.geom` in the vector +//! library. Pure functions over `@Vector(2, f32)`, so `+`, `-`, `*` and +//! `+=` work on points directly, as on a shader's `vec2`. +//! +//! In the vector library every path is a list of cubics, lines included, as +//! in manim: one shape of data makes morphing and partial drawing plain +//! arithmetic. +const std = @import("std"); + +pub const Vec = @Vector(2, f32); + +pub fn vec(x: f32, y: f32) Vec { + return .{ x, y }; +} +pub fn dot(a: Vec, b: Vec) f32 { + return @reduce(.Add, a * b); +} +pub fn cross(a: Vec, b: Vec) f32 { + return a[0] * b[1] - a[1] * b[0]; +} +pub fn length(a: Vec) f32 { + return @sqrt(dot(a, a)); +} +pub fn splat(s: f32) Vec { + return @splat(s); +} +pub fn mix(a: Vec, b: Vec, t: f32) Vec { + return a + (b - a) * splat(t); +} +/// Perpendicular, rotated a quarter turn counterclockwise in y-down space. +pub fn perp(a: Vec) Vec { + return .{ a[1], -a[0] }; +} +pub fn normalize(a: Vec) Vec { + const l = length(a); + return if (l > 0) a / splat(l) else a; +} +/// `a` times `k`: Zig does not broadcast a scalar over a vector. +pub fn scale(a: Vec, k: f32) Vec { + return a * splat(k); +} +pub fn distance(a: Vec, b: Vec) f32 { + return length(b - a); +} +/// `a` in the same direction, `len` long; zero stays zero. PVector's `setMag`. +pub fn withLength(a: Vec, len: f32) Vec { + return scale(normalize(a), len); +} +/// `a`, shortened to `max` if longer. PVector's `limit`. +pub fn clampLength(a: Vec, max: f32) Vec { + const l2 = dot(a, a); + return if (l2 > max * max) scale(a, max / @sqrt(l2)) else a; +} +/// The direction of `a` in radians, from +x toward +y (clockwise on a +/// y-down screen). PVector's `heading`. Not for shader code: `atan2` is +/// table-driven, which SPIR-V's logical addressing forbids. +pub fn angle(a: Vec) f32 { + return std.math.atan2(a[1], a[0]); +} +/// The unit vector at `radians`. PVector's `fromAngle`. +pub fn unit(radians: f32) Vec { + return .{ @cos(radians), @sin(radians) }; +} + +/// `[a c e; b d f]`, SVG's `matrix(a b c d e f)`. +pub const Affine = struct { + a: f32 = 1, + b: f32 = 0, + c: f32 = 0, + d: f32 = 1, + e: f32 = 0, + f: f32 = 0, + + pub const identity: Affine = .{}; + + pub fn translate(x: f32, y: f32) Affine { + return .{ .e = x, .f = y }; + } + pub fn scale(sx: f32, sy: f32) Affine { + return .{ .a = sx, .d = sy }; + } + pub fn rotate(radians: f32) Affine { + const c = @cos(radians); + const s = @sin(radians); + return .{ .a = c, .b = s, .c = -s, .d = c }; + } + /// Moves the origin to `at`, turned by `radians`: Processing's + /// `translate(at); rotate(radians)`. + pub fn place(at: Vec, radians: f32) Affine { + var m = rotate(radians); + m.e = at[0]; + m.f = at[1]; + return m; + } + pub fn skew(x: f32, y: f32) Affine { + return .{ .b = @tan(y), .c = @tan(x) }; + } + /// `self` after `inner`: apply `inner` first. + pub fn mul(self: Affine, inner: Affine) Affine { + return .{ + .a = self.a * inner.a + self.c * inner.b, + .b = self.b * inner.a + self.d * inner.b, + .c = self.a * inner.c + self.c * inner.d, + .d = self.b * inner.c + self.d * inner.d, + .e = self.a * inner.e + self.c * inner.f + self.e, + .f = self.b * inner.e + self.d * inner.f + self.f, + }; + } + pub fn apply(m: Affine, p: Vec) Vec { + return .{ m.a * p[0] + m.c * p[1] + m.e, m.b * p[0] + m.d * p[1] + m.f }; + } + pub fn applyVector(m: Affine, p: Vec) Vec { + return .{ m.a * p[0] + m.c * p[1], m.b * p[0] + m.d * p[1] }; + } + pub fn determinant(m: Affine) f32 { + return m.a * m.d - m.b * m.c; + } + /// How much the transform scales lengths, on average. + pub fn scaleFactor(m: Affine) f32 { + return @sqrt(@abs(m.determinant())); + } + /// How much the transform stretches lengths at most, nearly: the + /// longer of its two axes. + pub fn maxScale(m: Affine) f32 { + return @max(@sqrt(m.a * m.a + m.b * m.b), @sqrt(m.c * m.c + m.d * m.d)); + } + pub fn invert(m: Affine) Affine { + const det = m.determinant(); + if (det == 0) return .{}; + const i = 1 / det; + return .{ + .a = m.d * i, + .b = -m.b * i, + .c = -m.c * i, + .d = m.a * i, + .e = (m.c * m.f - m.d * m.e) * i, + .f = (m.b * m.e - m.a * m.f) * i, + }; + } +}; + +pub const Rect = struct { + x: f32 = 0, + y: f32 = 0, + w: f32 = 0, + h: f32 = 0, + + pub fn center(r: Rect) Vec { + return .{ r.x + r.w / 2, r.y + r.h / 2 }; + } +}; + +/// Growing bounds over points. +pub const Bounds = struct { + min: Vec = splat(std.math.inf(f32)), + max: Vec = splat(-std.math.inf(f32)), + + pub fn add(b: *Bounds, p: Vec) void { + b.min = @min(b.min, p); + b.max = @max(b.max, p); + } + pub fn empty(b: Bounds) bool { + return b.min[0] > b.max[0]; + } + pub fn rect(b: Bounds) Rect { + if (b.empty()) return .{}; + return .{ .x = b.min[0], .y = b.min[1], .w = b.max[0] - b.min[0], .h = b.max[1] - b.min[1] }; + } +}; + +/// A cubic's four control points. +pub const Cubic = [4]Vec; + +pub fn line(a: Vec, b: Vec) Cubic { + return .{ a, mix(a, b, 1.0 / 3.0), mix(a, b, 2.0 / 3.0), b }; +} + +pub fn quad(a: Vec, c: Vec, b: Vec) Cubic { + return .{ a, mix(a, c, 2.0 / 3.0), mix(b, c, 2.0 / 3.0), b }; +} + +pub fn eval(c: Cubic, t: f32) Vec { + const u = 1 - t; + return c[0] * splat(u * u * u) + c[1] * splat(3 * u * u * t) + c[2] * splat(3 * u * t * t) + c[3] * splat(t * t * t); +} + +/// de Casteljau: the two halves of `c` at `t`. +pub fn split(c: Cubic, t: f32) [2]Cubic { + const ab = mix(c[0], c[1], t); + const bc = mix(c[1], c[2], t); + const cd = mix(c[2], c[3], t); + const abc = mix(ab, bc, t); + const bcd = mix(bc, cd, t); + const p = mix(abc, bcd, t); + return .{ .{ c[0], ab, abc, p }, .{ p, bcd, cd, c[3] } }; +} + +/// Line segments needed to stay within `tolerance` of the curve. +pub fn flattenCount(c: Cubic, tolerance: f32) u32 { + const d1 = c[0] - splat(2) * c[1] + c[2]; + const d2 = c[1] - splat(2) * c[2] + c[3]; + const dd = @max(length(d1), length(d2)); + const n = @ceil(@sqrt(0.75 * dd / tolerance)); + return @intFromFloat(std.math.clamp(n, 1, 256)); +} + +/// A cheap length estimate: between chord and control polygon. +pub fn roughLength(c: Cubic) f32 { + const chord = length(c[3] - c[0]); + const polygon = length(c[1] - c[0]) + length(c[2] - c[1]) + length(c[3] - c[2]); + return (chord + polygon) / 2; +} + +/// Cubics for an SVG elliptical arc from `p0` to `p1` (endpoint form). +pub fn arc(out: *std.ArrayList(Cubic), gpa: std.mem.Allocator, p0: Vec, radii: Vec, x_rotation_degrees: f32, large: bool, sweep: bool, p1: Vec) !void { + var rx = @abs(radii[0]); + var ry = @abs(radii[1]); + if (rx == 0 or ry == 0 or @reduce(.And, p0 == p1)) { + if (!@reduce(.And, p0 == p1)) try out.append(gpa, line(p0, p1)); + return; + } + const phi = x_rotation_degrees * std.math.pi / 180; + const cos_phi = @cos(phi); + const sin_phi = @sin(phi); + const half = (p0 - p1) / splat(2); + const x1 = cos_phi * half[0] + sin_phi * half[1]; + const y1 = -sin_phi * half[0] + cos_phi * half[1]; + // Radii too small to reach are scaled up, as the SVG spec says. + const lambda = (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry); + if (lambda > 1) { + rx *= @sqrt(lambda); + ry *= @sqrt(lambda); + } + const num = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1; + const den = rx * rx * y1 * y1 + ry * ry * x1 * x1; + var coef = @sqrt(@max(0, num / den)); + if (large == sweep) coef = -coef; + const cx1 = coef * rx * y1 / ry; + const cy1 = -coef * ry * x1 / rx; + const mid = (p0 + p1) / splat(2); + const center: Vec = .{ cos_phi * cx1 - sin_phi * cy1 + mid[0], sin_phi * cx1 + cos_phi * cy1 + mid[1] }; + const start = std.math.atan2((y1 - cy1) / ry, (x1 - cx1) / rx); + var delta = std.math.atan2((-y1 - cy1) / ry, (-x1 - cx1) / rx) - start; + if (sweep and delta < 0) delta += 2 * std.math.pi; + if (!sweep and delta > 0) delta -= 2 * std.math.pi; + const pieces: u32 = @intFromFloat(@max(1, @ceil(@abs(delta) / (std.math.pi / 2.0) - 1e-4))); + const step = delta / @as(f32, @floatFromInt(pieces)); + const k = 4.0 / 3.0 * @tan(step / 4); + const m: Affine = (Affine{ .a = cos_phi, .b = sin_phi, .c = -sin_phi, .d = cos_phi, .e = center[0], .f = center[1] }).mul(.scale(rx, ry)); + var theta = start; + var from = p0; + for (0..pieces) |i| { + const next = theta + step; + const a: Vec = .{ @cos(theta), @sin(theta) }; + const b: Vec = .{ @cos(next), @sin(next) }; + const to = if (i + 1 == pieces) p1 else m.apply(b); + try out.append(gpa, .{ from, m.apply(a + perp(a) * splat(-k)), m.apply(b - perp(b) * splat(-k)), to }); + from = to; + theta = next; + } +} + +pub const noise = @import("noise.zig").noise; + +/// A float in `lo..hi`: Processing's `random(lo, hi)`. `r` is any +/// `std.Random` (keep a concrete `std.Random.Xoshiro256` in State and pass +/// `s.rng.random()`); this only saves spelling out the lerp. +pub fn uniform(r: std.Random, lo: f32, hi: f32) f32 { + return std.math.lerp(lo, hi, r.float(f32)); +} + +/// A unit vector in a uniformly random direction: `PVector.random2D()`. +pub fn randomUnit(r: std.Random) Vec { + return unit(uniform(r, 0, std.math.tau)); +} + +test "affine composition and inversion round trip" { + const m = Affine.translate(10, 5).mul(.rotate(0.7)).mul(.scale(2, 3)); + const p = vec(3, -4); + const q = m.invert().apply(m.apply(p)); + try std.testing.expectApproxEqAbs(p[0], q[0], 1e-4); + try std.testing.expectApproxEqAbs(p[1], q[1], 1e-4); +} + +test "a half-circle arc stays on the circle" { + var cubics: std.ArrayList(Cubic) = .empty; + defer cubics.deinit(std.testing.allocator); + try arc(&cubics, std.testing.allocator, vec(-10, 0), vec(10, 10), 0, false, true, vec(10, 0)); + try std.testing.expectEqual(@as(usize, 2), cubics.items.len); + for (cubics.items) |c| for (0..9) |i| { + const r = length(eval(c, @as(f32, @floatFromInt(i)) / 8)); + try std.testing.expectApproxEqAbs(@as(f32, 10), r, 0.03); + }; + // Sweep flag 1 in y-down space goes through negative y. + try std.testing.expect(eval(cubics.items[0], 1)[1] < -9.9); +} + +test "vector helpers" { + const v = vec(3, 4); + try std.testing.expectEqual(@as(f32, 5), length(v)); + try std.testing.expectEqual(vec(6, 8), scale(v, 2)); + try std.testing.expectEqual(@as(f32, 5), distance(.{ 0, 0 }, v)); + try std.testing.expectApproxEqAbs(@as(f32, 10), length(withLength(v, 10)), 1e-5); + try std.testing.expectEqual(vec(0, 0), withLength(.{ 0, 0 }, 3)); + try std.testing.expectApproxEqAbs(@as(f32, 2.5), length(clampLength(v, 2.5)), 1e-5); + try std.testing.expectEqual(v, clampLength(v, 7)); + try std.testing.expectApproxEqAbs(@as(f32, std.math.pi / 2.0), angle(.{ 0, 1 }), 1e-6); + const u = unit(angle(v)); + try std.testing.expectApproxEqAbs(@as(f32, 0.6), u[0], 1e-6); + const p = Affine.place(.{ 10, 20 }, std.math.pi / 2.0).apply(.{ 1, 0 }); + try std.testing.expectApproxEqAbs(@as(f32, 10), p[0], 1e-5); + try std.testing.expectApproxEqAbs(@as(f32, 21), p[1], 1e-5); +} + +test "uniform stays in range and randomUnit is unit length" { + var prng: std.Random.Xoshiro256 = .init(3); + for (0..1000) |_| { + const x = uniform(prng.random(), -2, 5); + try std.testing.expect(x >= -2 and x < 5); + try std.testing.expectApproxEqAbs(@as(f32, 1), length(randomUnit(prng.random())), 1e-5); + } +} + +test { + _ = @import("noise.zig"); +} diff --git a/src/sketch/clock.zig b/src/sketch/clock.zig new file mode 100644 index 0000000..e64e2a8 --- /dev/null +++ b/src/sketch/clock.zig @@ -0,0 +1,127 @@ +//! A fixed-step clock: how many steps of `1 / hz` seconds the frame's ticks +//! owe. Keep it in State, so it migrates and replays with the rest. +const std = @import("std"); +const abi = @import("abi"); + +/// `for (0..s.clock.steps(in)) |_| step(s);` in `update`. +/// +/// It reads only the `tick` events in `in.events`, never the host's clock, +/// so a replay gives the same steps. The steps of each tick are counted on +/// their own, so an update with N ticks gives exactly the steps of N +/// updates with one tick each (the host feeds one tick per update anyway). +/// A tick owes at most `max_steps`: after a stall the simulation slows down +/// instead of trying to catch up forever; the rest of that debt is dropped. +/// `set clock.hz 30` from the console is slow motion. +/// +/// Time is counted in integer nanoseconds, from `Event.tickDt`, so it adds +/// up the same everywhere. Two allowances keep a clock at the display's +/// rate from juddering (0 steps one frame, 2 the next): +/// - a tick within `slack` of a whole number of steps counts as exactly +/// that many (a 60 Hz frame is 16 666 666 ns, a step at 60 Hz +/// 16 666 667 ns: 60 frames are 60 steps, not 59); +/// - a step is taken once `owed` is within `slack` of it, so `owed` may +/// end a little below zero, and a frame that comes a little early still +/// steps. +/// `slack` is an eighth of a step (2 ms at 60 Hz), which covers the jitter +/// of a live frame clock. +pub const Clock = struct { + hz: f32 = 60, + /// Nanoseconds received and not yet stepped; down to `-slack` after + /// an early step. + owed: i64 = 0, + /// Steps taken since the clock was made: a frame counter for the + /// simulation (Processing's `frameCount`). + count: u64 = 0, + + pub const max_steps = 8; + + /// Steps to take now; adds them to `count`. + pub fn steps(c: *Clock, in: *const abi.Input) u32 { + var n: u32 = 0; + for (in.events) |e| if (e.kind == .tick) { + n += c.tick(e.tickDt()); + }; + return n; + } + + /// The steps one tick of `dt` nanoseconds owes: the per-event form, for + /// an update that handles its events in order (`c.tick(e.tickDt())`). + pub fn tick(c: *Clock, dt: u64) u32 { + const step = c.stepNs(); + if (step == 0 or dt == 0) return 0; + const slack = @divTrunc(step, 8); + var t: i64 = @intCast(@min(dt, std.time.ns_per_hour)); + const whole = @divTrunc(t + @divTrunc(step, 2), step) * step; + if (whole > 0 and @abs(t - whole) <= slack) t = whole; + c.owed = @max(c.owed, -slack) + t; + var n: u32 = 0; + while (c.owed >= step - slack and n < max_steps) : (n += 1) c.owed -= step; + if (n == max_steps and c.owed > 0) c.owed = @rem(c.owed, step); + c.count += n; + return n; + } + + /// One step in nanoseconds; 0 when `hz` is not a positive rate. + pub fn stepNs(c: *const Clock) i64 { + if (!(c.hz > 1e-3) or !(c.hz < 1e9)) return 0; + return @intFromFloat(@round(std.time.ns_per_s / @as(f64, c.hz))); + } +}; + +fn tickEvent(dt_ns: u64) abi.Event { + return abi.Event.tick(0, dt_ns); +} + +test "N updates of one tick each step exactly as one update of N ticks" { + var events: [600]abi.Event = undefined; + var prng: std.Random.Xoshiro256 = .init(1); + for (&events) |*e| e.* = tickEvent(prng.random().uintLessThan(u64, 50_000_000)); + events[300] = tickEvent(2 * std.time.ns_per_s); // a stall: capped + var one: Clock = .{}; + var per: [events.len]u32 = undefined; + for (&events, &per) |*e, *n| n.* = one.steps(&.{ .events = e[0..1] }); + var all: Clock = .{}; + const total = all.steps(&.{ .events = &events }); + var sum: u32 = 0; + for (per) |n| sum += n; + try std.testing.expectEqual(sum, total); + try std.testing.expectEqual(std.mem.toBytes(one), std.mem.toBytes(all)); + try std.testing.expectEqual(@as(u32, Clock.max_steps), per[300]); + try std.testing.expectEqual(@as(u64, total), all.count); +} + +test "sixty script frames are sixty steps at 60 Hz, one each" { + var c: Clock = .{}; + // What the host and scripts send: ns_per_s / 60, through the f32 tick. + const events = [_]abi.Event{ .{ .kind = .mouse_move, .x = 5 }, tickEvent(std.time.ns_per_s / 60) }; + for (0..6000) |_| try std.testing.expectEqual(@as(u32, 1), c.steps(&.{ .events = &events })); + try std.testing.expectEqual(@as(u64, 6000), c.count); + c.hz = 0; + try std.testing.expectEqual(@as(u32, 0), c.steps(&.{ .events = &events })); +} + +test "a jittery 60 Hz frame clock gives one step a frame; slower rates divide evenly" { + var prng: std.Random.Xoshiro256 = .init(7); + var c: Clock = .{}; + var half: Clock = .{ .hz = 30 }; + var halves: u32 = 0; + // Frames shown at vsync, each measured up to 1.5 ms late. + var last: u64 = 0; + for (0..1200) |i| { + const shown = (i + 1) * std.time.ns_per_s / 60 + prng.random().uintLessThan(u64, 1_500_000); + const dt = shown - last; + last = shown; + try std.testing.expectEqual(@as(u32, 1), c.tick(dt)); + const h = half.tick(dt); + try std.testing.expectEqual(@as(u32, @intFromBool(i % 2 == 1)), h); + halves += h; + } + try std.testing.expectEqual(@as(u32, 600), halves); + // A dropped frame is two steps. + try std.testing.expectEqual(@as(u32, 2), c.tick(33_333_333)); + // 144 Hz on a 60 Hz display: 2.4 steps a frame on average, exactly. + var fast: Clock = .{ .hz = 144 }; + var n: u32 = 0; + for (0..600) |_| n += fast.tick(16_666_667); + try std.testing.expect(n >= 1439 and n <= 1441); +} diff --git a/src/sketch/derived.zig b/src/sketch/derived.zig new file mode 100644 index 0000000..c42a322 --- /dev/null +++ b/src/sketch/derived.zig @@ -0,0 +1,56 @@ +//! Data computed from State, kept out of it. +const std = @import("std"); +const abi = @import("abi"); + +/// A `T` computed in `draw` from a few State fields, kept in Session: the +/// segments of a Koch curve from its generation, an L-system's sentence, +/// a tessellation too big to redo every frame. State keeps what `update` +/// changes (the generation, one byte), so snapshots and replays stay +/// small; this keeps what follows from it, however big it grows. +/// +/// `key` says what the value was built from: pass the State fields it +/// depends on, as a number (`s.generation`) or a hash. `stale` is true when +/// the key differs, and on the first frame after a reload, since new code +/// may compute it differently; then rebuild `value`. A seek or a replay +/// changes the key like an update does, so what is drawn always follows +/// State, and the timeline needs nothing more. +/// +/// pub const Session = struct { curve: sk.Derived(std.ArrayList(Segment)) = .{ .value = .empty } }; +/// if (ss.curve.stale(s.generation, f.in)) try koch(&ss.curve.value, f.session, s.generation); +/// +/// After a failed rebuild call `forget`, so the next frame tries again. +pub fn Derived(comptime T: type) type { + return struct { + const Self = @This(); + + value: T, + /// The key `value` was built for; null before the first build or + /// after `forget`. + key: ?u64 = null, + + /// True when `value` must be rebuilt for `key`; it is then taken + /// as built for `key`. + pub fn stale(d: *Self, key: u64, in: *const abi.Input) bool { + if (d.key == key and !in.reloaded) return false; + d.key = key; + return true; + } + + /// The next `stale` is true whatever its key. + pub fn forget(d: *Self) void { + d.key = null; + } + }; +} + +test "stale when the key changes, after a reload, and after forget" { + var d: Derived(u32) = .{ .value = 0 }; + const live: abi.Input = .{}; + try std.testing.expect(d.stale(3, &live)); + try std.testing.expect(!d.stale(3, &live)); + try std.testing.expect(d.stale(4, &live)); + try std.testing.expect(d.stale(4, &.{ .reloaded = true })); + try std.testing.expect(!d.stale(4, &live)); + d.forget(); + try std.testing.expect(d.stale(4, &live)); +} diff --git a/src/sketch/draw.zig b/src/sketch/draw.zig new file mode 100644 index 0000000..c151ab2 --- /dev/null +++ b/src/sketch/draw.zig @@ -0,0 +1,1024 @@ +//! Circles, lines and polygons, filled and stroked, as `Command.shape`s. +//! +//! Two levels, both plain functions with no state of their own: +//! +//! - **L1, tessellation.** A `Tessellation` is a caller-owned value: points, +//! subpath ends and triangle indices, appended to by `fillCircle`, +//! `strokeCircle`, `fillPolygon`, `strokePolygon`, `strokePolyline` and +//! `strokeLine` with the caller's allocator, each under an `Affine`. Emit +//! it with `f.shape(&t, color)`, batch many shapes into one, inspect it, +//! or upload its triangles to a GPU pass of your own. +//! - **L2, a Pen.** `Pen` is plain data (fill, stroke, width, transform); +//! `circle`, `line` and `polygon` tessellate into `f.scratch` and emit one +//! shape for the fill and one for the stroke. On out-of-memory they log +//! and drop the shape, as `Frame.emit` does. +//! +//! What a shape guarantees, so both hosts draw the same pixels: its +//! triangles are disjoint and positively wound (clockwise on a y-down +//! screen, after the transform, mirrored or not), and its subpaths cover +//! exactly their union: one positively wound outline, followed by its +//! holes wound the other way (a ring's inside). The web fills each such +//! group as one nonzero path, native draws the triangles, so each shape +//! blends once on both. Shapes batched into one `Tessellation` are drawn +//! one after another by both hosts, so where they overlap translucent +//! colours blend twice on both. The one known difference: a stroke that +//! overlaps itself (a self-crossing polyline, or segments shorter than the +//! stroke is wide at an acute turn) blends twice natively where it +//! overlaps, and once on the web. +//! +//! Curves are flattened to within `tolerance` canvas pixels, measured after +//! the transform, so a circle scaled up gets more segments. Native shapes +//! are not antialiased (like `rect`); the web canvas antialiases edges. +const std = @import("std"); +const abi = @import("abi"); +const math = @import("math"); +const root = @import("root.zig"); + +const Allocator = std.mem.Allocator; +const Vec = math.Vec; +const Affine = math.Affine; +const Color = abi.Color; +const splat = math.splat; + +/// How a stroke turns a corner (Processing's `strokeJoin`). +pub const Join = enum { miter, round, bevel }; +/// How an open stroke ends (Processing's `strokeCap`). +pub const Cap = enum { butt, round, square }; + +/// A stroke's shape, for `strokePath`. +pub const Stroke = struct { + width: f32 = 1, + join: Join = .miter, + cap: Cap = .butt, + /// Joined back to the first point, with no caps. + closed: bool = false, + /// Mitered corners reach at most this many half-widths from the + /// vertex, and are bevelled beyond. + miter_limit: f32 = miter_limit, +}; + +/// How far, in canvas pixels, a flattened circle may stray from the true +/// one. +pub const tolerance: f32 = 0.25; +/// A stroke's outer corner is mitered up to this many half-widths from the +/// vertex, and bevelled beyond (SVG's default). +pub const miter_limit: f32 = 4; + +pub const Error = Allocator.Error; + +/// Shapes as data: `points` in canvas coordinates, the subpaths +/// `points[ends[i - 1] .. ends[i]]`, and triangles, `indices` into `points` +/// three at a time. The fields of `Command.shape`; see the module comment +/// for what the functions here guarantee about them. +pub const Tessellation = struct { + points: std.ArrayList([2]f32) = .empty, + ends: std.ArrayList(u32) = .empty, + indices: std.ArrayList(u32) = .empty, + + pub const empty: Tessellation = .{}; + + pub fn deinit(t: *Tessellation, gpa: Allocator) void { + t.points.deinit(gpa); + t.ends.deinit(gpa); + t.indices.deinit(gpa); + t.* = .empty; + } + + pub fn clearRetainingCapacity(t: *Tessellation) void { + t.points.clearRetainingCapacity(); + t.ends.clearRetainingCapacity(); + t.indices.clearRetainingCapacity(); + } + + /// The triangles as a flat vertex list (three points each), for a GPU + /// pass of your own. + pub fn triangles(t: *const Tessellation, gpa: Allocator) Error![][2]f32 { + const out = try gpa.alloc([2]f32, t.indices.items.len); + for (out, t.indices.items) |*v, i| v.* = t.points.items[i]; + return out; + } + + // -- The append API: the pieces the shape functions are made of. -- + + /// Appends a point already in canvas coordinates; returns its index. + pub fn appendPoint(t: *Tessellation, gpa: Allocator, p: Vec) Error!u32 { + const index: u32 = @intCast(t.points.items.len); + try t.points.append(gpa, .{ p[0], p[1] }); + return index; + } + + /// Ends the current subpath at the last point appended. + pub fn endSubpath(t: *Tessellation, gpa: Allocator) Error!void { + try t.ends.append(gpa, @intCast(t.points.items.len)); + } + + /// Appends the triangle `a`, `b`, `c` (point indices), wound + /// positively whatever order they come in. A triangle with no area is + /// left out. + pub fn appendTriangle(t: *Tessellation, gpa: Allocator, a: u32, b: u32, c: u32) Error!void { + const pa = vec(t.points.items[a]); + const area = math.cross(vec(t.points.items[b]) - pa, vec(t.points.items[c]) - pa); + if (area == 0 or std.math.isNan(area)) return; + try t.indices.appendSlice(gpa, if (area > 0) &.{ a, b, c } else &.{ a, c, b }); + } + + // -- Shapes -- + + /// A disc of `radius` around `center`. + pub fn fillCircle(t: *Tessellation, gpa: Allocator, center: Vec, radius: f32, xf: Affine) Error!void { + if (!(radius > 0)) return; + const mark = t.begin(); + const n = circleSegments(radius, xf); + const first = try t.ring(gpa, center, radius, n, xf); + try t.endSubpath(gpa); + for (1..n - 1) |i| try t.appendTriangle(gpa, first, first + @as(u32, @intCast(i)), first + @as(u32, @intCast(i + 1))); + t.finish(mark); + } + + /// A ring `width` wide centred on the circle of `radius`: a disc when + /// the width reaches the centre. + pub fn strokeCircle(t: *Tessellation, gpa: Allocator, center: Vec, radius: f32, width: f32, xf: Affine) Error!void { + const hw = width / 2; + if (!(hw > 0) or !(radius >= 0)) return; + if (radius - hw <= 0) return t.fillCircle(gpa, center, radius + hw, xf); + const mark = t.begin(); + const n = circleSegments(radius + hw, xf); + const outer = try t.ring(gpa, center, radius + hw, n, xf); + try t.endSubpath(gpa); + // The hole, wound the other way: the same angles, backwards. + const inner: u32 = @intCast(t.points.items.len); + for (0..n) |k| _ = try t.appendPoint(gpa, xf.apply(center + math.scale(math.unit(angleOf(n - 1 - k, n)), radius - hw))); + try t.endSubpath(gpa); + for (0..n) |k| { + const o0 = outer + @as(u32, @intCast(k)); + const o1 = outer + @as(u32, @intCast((k + 1) % n)); + const in_0 = inner + @as(u32, @intCast(n - 1 - k)); + const in_1 = inner + @as(u32, @intCast((2 * n - 2 - k) % n)); + try t.appendTriangle(gpa, o0, o1, in_1); + try t.appendTriangle(gpa, o0, in_1, in_0); + } + t.finish(mark); + } + + /// The inside of a simple polygon, convex or not (ear clipping), in + /// either winding. A polygon that crosses itself is filled as a fan + /// where clipping finds no ear, which may not match the web. + pub fn fillPolygon(t: *Tessellation, gpa: Allocator, points: []const Vec, xf: Affine) Error!void { + if (points.len < 3) return; + const mark = t.begin(); + const first: u32 = @intCast(t.points.items.len); + for (points) |p| _ = try t.appendPoint(gpa, xf.apply(p)); + // Repeated points (a closing copy of the first, say) clip badly. + var n: u32 = @intCast(points.len); + while (n > 1 and std.meta.eql(t.points.items[first + n - 1], t.points.items[first])) n -= 1; + t.points.shrinkRetainingCapacity(first + n); + try t.endSubpath(gpa); + if (n >= 3) try t.clip(gpa, first, n); + t.finish(mark); + } + + /// The outline of a closed polygon, `width` wide, with mitered corners + /// (bevelled past `miter_limit`): `strokePath` with `.closed = true`. + pub fn strokePolygon(t: *Tessellation, gpa: Allocator, points: []const Vec, width: f32, xf: Affine) Error!void { + return t.stroke(gpa, points, .{ .width = width, .closed = true }, xf); + } + + /// A line through `points`, `width` wide, with mitered corners (bevelled + /// past `miter_limit`) and square-cut ends: `strokePath` with the + /// defaults. + pub fn strokePolyline(t: *Tessellation, gpa: Allocator, points: []const Vec, width: f32, xf: Affine) Error!void { + return t.stroke(gpa, points, .{ .width = width }, xf); + } + + /// A line through `points`, open or closed, with the joins and caps + /// `style` asks for. Its triangles stay disjoint as everywhere here: a + /// round join is the circular segment beyond the bevel, a round cap the + /// half disc beyond the end, a square cap a butt cap moved out by half + /// the width. A zero-length open path is a dot (round or square caps) + /// or nothing (butt), as in SVG. + pub fn strokePath(t: *Tessellation, gpa: Allocator, points: []const Vec, style: Stroke, xf: Affine) Error!void { + return t.stroke(gpa, points, style, xf); + } + + /// The rect's area. + pub fn fillRect(t: *Tessellation, gpa: Allocator, r: math.Rect, xf: Affine) Error!void { + if (!(r.w > 0) or !(r.h > 0)) return; + const mark = t.begin(); + const first: u32 = @intCast(t.points.items.len); + for (rectCorners(r)) |p| _ = try t.appendPoint(gpa, xf.apply(p)); + try t.endSubpath(gpa); + try t.appendTriangle(gpa, first, first + 1, first + 2); + try t.appendTriangle(gpa, first, first + 2, first + 3); + t.finish(mark); + } + + /// The rect's outline, `width` wide, centred on its edge, with mitered + /// corners (Processing's `rect` with `noFill`). + pub fn strokeRect(t: *Tessellation, gpa: Allocator, r: math.Rect, width: f32, xf: Affine) Error!void { + if (!(r.w > 0) or !(r.h > 0)) return; + const cs = rectCorners(r); + return t.stroke(gpa, &cs, .{ .width = width, .closed = true }, xf); + } + + /// The segment from `a` to `b`, `width` wide, with round ends; a dot + /// when `a` is `b`. + pub fn strokeLine(t: *Tessellation, gpa: Allocator, a: Vec, b: Vec, width: f32, xf: Affine) Error!void { + const hw = width / 2; + if (!(hw > 0)) return; + const d = b - a; + if (math.length(d) == 0) return t.fillCircle(gpa, a, hw, xf); + const mark = t.begin(); + // A convex stadium: half a circle around each end. + const half = @max(circleSegments(hw, xf) / 2, 2); + const heading = math.angle(d); + const first: u32 = @intCast(t.points.items.len); + for ([_]Vec{ b, a }, 0..) |end, side| { + const start = heading - std.math.pi / 2.0 + @as(f32, @floatFromInt(side)) * std.math.pi; + for (0..half + 1) |k| { + const theta = start + std.math.pi * @as(f32, @floatFromInt(k)) / @as(f32, @floatFromInt(half)); + _ = try t.appendPoint(gpa, xf.apply(end + math.scale(math.unit(theta), hw))); + } + } + try t.endSubpath(gpa); + const count: u32 = 2 * (half + 1); + for (1..count - 1) |i| try t.appendTriangle(gpa, first, first + @as(u32, @intCast(i)), first + @as(u32, @intCast(i + 1))); + t.finish(mark); + } + + // -- Internals -- + + const Mark = struct { points: u32, ends: u32 }; + + fn begin(t: *const Tessellation) Mark { + return .{ .points = @intCast(t.points.items.len), .ends = @intCast(t.ends.items.len) }; + } + + /// Winds the subpaths added since `mark` positively: if the one that + /// encloses most area runs the wrong way (a mirroring transform, or + /// points given counterclockwise), every one of them is reversed, which + /// keeps holes holes. Triangles keep their geometry, so their indices + /// are remapped. + fn finish(t: *Tessellation, mark: Mark) void { + var largest: f32 = 0; + var start = mark.points; + for (t.ends.items[mark.ends..]) |end| { + const a = signedArea(t.points.items[start..end]); + if (@abs(a) > @abs(largest)) largest = a; + start = end; + } + if (largest >= 0) return; + start = mark.points; + for (t.ends.items[mark.ends..]) |end| { + std.mem.reverse([2]f32, t.points.items[start..end]); + start = end; + } + // Indices that point into this shape's subpaths follow the flip. + for (t.indices.items) |*i| { + if (i.* < mark.points) continue; + var s = mark.points; + for (t.ends.items[mark.ends..]) |end| { + if (i.* < end) { + i.* = end - 1 - (i.* - s); + break; + } + s = end; + } + } + } + + /// `n` points around a circle, at increasing angles; returns the first. + fn ring(t: *Tessellation, gpa: Allocator, center: Vec, radius: f32, n: u32, xf: Affine) Error!u32 { + const first: u32 = @intCast(t.points.items.len); + try t.points.ensureUnusedCapacity(gpa, n); + for (0..n) |k| _ = try t.appendPoint(gpa, xf.apply(center + math.scale(math.unit(angleOf(k, n)), radius))); + return first; + } + + /// Triangulates the polygon `points[first..][0..n]` by ear clipping + /// (a fan when it is convex). + fn clip(t: *Tessellation, gpa: Allocator, first: u32, n: u32) Error!void { + const pts = t.points.items[first..][0..n]; + const sign: f32 = if (signedArea(pts) >= 0) 1 else -1; + const P = struct { + fn at(all: []const [2]f32, i: u32) Vec { + return vec(all[i]); + } + }; + var convex = true; + for (0..n) |i| { + const a = P.at(pts, @intCast(i)); + const b = P.at(pts, @intCast((i + 1) % n)); + const c = P.at(pts, @intCast((i + 2) % n)); + if (sign * math.cross(b - a, c - b) < 0) convex = false; + } + if (convex) { + for (1..n - 1) |i| try t.appendTriangle(gpa, first, first + @as(u32, @intCast(i)), first + @as(u32, @intCast(i + 1))); + return; + } + const remaining = try gpa.alloc(u32, n); + defer gpa.free(remaining); + for (remaining, 0..) |*r, i| r.* = @intCast(i); + var len: usize = n; + var guard: usize = 0; + var i: usize = 0; + while (len > 3) { + const ia = remaining[(i + len - 1) % len]; + const ib = remaining[i % len]; + const ic = remaining[(i + 1) % len]; + const a = P.at(pts, ia); + const b = P.at(pts, ib); + const c = P.at(pts, ic); + const turn = sign * math.cross(b - a, c - b); + var ear = turn > 0; + if (ear) for (remaining[0..len]) |j| { + if (j == ia or j == ib or j == ic) continue; + const p = P.at(pts, j); + if (@reduce(.And, p == a) or @reduce(.And, p == b) or @reduce(.And, p == c)) continue; + if (inTriangle(p, a, b, c, sign)) { + ear = false; + break; + } + }; + // A straight or zero-length corner is cut without a triangle. + if (ear or turn == 0 or guard > len) { + if (turn != 0) try t.appendTriangle(gpa, first + ia, first + ib, first + ic); + const at = i % len; + std.mem.copyForwards(u32, remaining[at .. len - 1], remaining[at + 1 .. len]); + len -= 1; + guard = 0; + if (at < i) i -= 1; + i %= len; + } else { + i = (i + 1) % len; + guard += 1; + } + } + try t.appendTriangle(gpa, first + remaining[0], first + remaining[1], first + remaining[2]); + } + + const Joint = struct { + /// The inner corners meet at one point (`inner`), and the bodies are + /// cut back to it: disjoint. Otherwise the bodies overlap on the + /// inner side, around the vertex. + clean: bool, + /// Which side (+1 along the segment normal, -1 against it) is outer. + outer: f32, + inner: Vec, + miter: ?Vec, + vertex: Vec, + }; + + const Body = struct { start: [2]Vec, end: [2]Vec }; + + /// Points appended on an arc, between two corners already in the + /// outline: `count` of them from `first`, starting next to `from`. + const Arc = struct { first: u32 = 0, count: u32 = 0, from: u32 = 0 }; + + /// The arc around `center` from `center + from` turning by `sweep` + /// radians, its end points left out (they are corners already). + fn appendArc(t: *Tessellation, gpa: Allocator, center: Vec, from: Vec, sweep: f32, from_index: u32, xf: Affine) Error!Arc { + const radius = math.length(from); + const whole: f32 = @floatFromInt(circleSegments(radius, xf)); + const pieces: u32 = @intFromFloat(@max(1, @ceil(@abs(sweep) / std.math.tau * whole))); + const arc: Arc = .{ .first = @intCast(t.points.items.len), .count = pieces - 1, .from = from_index }; + for (1..pieces) |i| { + const theta = sweep * @as(f32, @floatFromInt(i)) / @as(f32, @floatFromInt(pieces)); + const c = @cos(theta); + const s = @sin(theta); + _ = try t.appendPoint(gpa, xf.apply(center + Vec{ from[0] * c - from[1] * s, from[0] * s + from[1] * c })); + } + return arc; + } + + /// The circular segment between an arc and its chord, as a fan from + /// the arc's first corner to `to`. + fn fanArc(t: *Tessellation, gpa: Allocator, arc: Arc, to: u32) Error!void { + var previous = arc.first; + if (arc.count == 0) return; + for (1..arc.count) |i| { + const next = arc.first + @as(u32, @intCast(i)); + try t.appendTriangle(gpa, arc.from, previous, next); + previous = next; + } + try t.appendTriangle(gpa, arc.from, previous, to); + } + + fn stroke(t: *Tessellation, gpa: Allocator, input: []const Vec, style: Stroke, xf: Affine) Error!void { + const hw = style.width / 2; + if (!(hw > 0) or input.len == 0) return; + // Consecutive repeats make no direction. + const pts = try gpa.alloc(Vec, input.len); + defer gpa.free(pts); + var n: usize = 0; + for (input) |p| { + if (n > 0 and @reduce(.And, p == pts[n - 1])) continue; + pts[n] = p; + n += 1; + } + if (style.closed) while (n > 1 and @reduce(.And, pts[n - 1] == pts[0])) { + n -= 1; + }; + if (n < 2) { + // A zero-length open path: a dot where its caps have area (SVG). + if (style.closed) return; + return switch (style.cap) { + .butt => {}, + .round => t.fillCircle(gpa, pts[0], hw, xf), + .square => t.fillPolygon(gpa, &.{ pts[0] + Vec{ -hw, -hw }, pts[0] + Vec{ hw, -hw }, pts[0] + Vec{ hw, hw }, pts[0] + Vec{ -hw, hw } }, xf), + }; + } + if (n == 2 and style.closed) { + var open = style; + open.closed = false; + open.cap = .butt; + return t.stroke(gpa, pts[0..2], open, xf); + } + const closed = style.closed; + if (!closed and style.cap == .square) { + // Square caps are butt caps half a width further out. + pts[0] -= math.withLength(pts[1] - pts[0], hw); + pts[n - 1] += math.withLength(pts[n - 1] - pts[n - 2], hw); + } + const segments = if (closed) n else n - 1; + const joints = if (closed) n else n - 2; + + const dirs = try gpa.alloc(Vec, segments); + defer gpa.free(dirs); + const lens = try gpa.alloc(f32, segments); + defer gpa.free(lens); + for (dirs, lens, 0..) |*d, *l, i| { + const v = pts[(i + 1) % n] - pts[i]; + l.* = math.length(v); + d.* = v / splat(l.*); + } + const bodies = try gpa.alloc(Body, segments); + defer gpa.free(bodies); + for (bodies, dirs, 0..) |*body, d, i| { + const nrm = math.scale(math.perp(d), hw); + body.* = .{ .start = .{ pts[i] + nrm, pts[i] - nrm }, .end = .{ pts[(i + 1) % n] + nrm, pts[(i + 1) % n] - nrm } }; + } + const limit = @max(style.miter_limit, 1); + const js = try gpa.alloc(Joint, joints); + defer gpa.free(js); + for (js, 0..) |*j, k| { + // Joint k joins segment a = k (open: k) to b = k + 1. + const a = if (closed) (k + segments - 1) % segments else k; + const b = (a + 1) % segments; + const v = pts[(a + 1) % n]; + const na = math.perp(dirs[a]); + const nb = math.perp(dirs[b]); + const turn = math.cross(dirs[a], dirs[b]); + const outer: f32 = if (turn > 0) 1 else -1; + const cos1 = 1 + math.dot(na, nb); + // How far back along each segment the inner corners meet. + const back = if (cos1 > 1e-6) hw * @abs(turn) / cos1 else std.math.inf(f32); + const budget_a = if (closed or a > 0) lens[a] / 2 else lens[a]; + const budget_b = if (closed or b + 1 < segments) lens[b] / 2 else lens[b]; + const miter_vec = if (cos1 > 1e-6) math.scale(na + nb, hw / cos1) else splat(0); + const mitered = style.join == .miter and cos1 >= 2 / (limit * limit) and @abs(turn) > 1e-6; + j.* = .{ + .clean = back <= budget_a and back <= budget_b, + .outer = outer, + .inner = v - math.scale(miter_vec, outer), + .miter = if (mitered) v + math.scale(miter_vec, outer) else null, + .vertex = v, + }; + const side: usize = if (outer > 0) 1 else 0; // the inner side's corner index + if (j.clean) { + bodies[a].end[side] = j.inner; + bodies[b].start[side] = j.inner; + } + } + + const mark = t.begin(); + // Corner indices per body: [start+, end+, end-, start-]. + const corners = try gpa.alloc([4]u32, segments); + defer gpa.free(corners); + const joint_points = try gpa.alloc([2]?u32, joints); // miter, pivot + defer gpa.free(joint_points); + for (joint_points) |*jp| jp.* = .{ null, null }; + const arcs = try gpa.alloc(Arc, joints); + defer gpa.free(arcs); + @memset(arcs, .{}); + var caps: [2]Arc = .{ .{}, .{} }; // end, start + const round_join = style.join == .round; + + // The `+` side forward, then the `-` side backward: one outline + // when open, two loops (outer and inner) when closed. A clean inner + // corner is one point shared by the bodies on either side of it. + for ([_]f32{ 1, -1 }) |side| { + const c: usize = if (side > 0) 0 else 1; + const loop_start: u32 = @intCast(t.points.items.len); + var previous: ?u32 = null; + for (0..segments) |s_| { + const s = if (side > 0) s_ else segments - 1 - s_; + const body = bodies[s]; + const first_corner = xf.apply(if (side > 0) body.start[c] else body.end[c]); + const last_corner = xf.apply(if (side > 0) body.end[c] else body.start[c]); + const fi = if (previous != null and std.meta.eql(t.points.items[previous.?], xy(first_corner))) previous.? else try t.appendPoint(gpa, first_corner); + const closing = closed and s_ + 1 == segments and std.meta.eql(t.points.items[loop_start], xy(last_corner)); + const li = if (closing) loop_start else try t.appendPoint(gpa, last_corner); + if (side > 0) { + corners[s][0] = fi; + corners[s][1] = li; + } else { + corners[s][2] = fi; + corners[s][3] = li; + } + previous = li; + // The joint after this body, in travel order. + const has_joint = if (side > 0) (closed or s + 1 < segments) else (closed or s > 0); + if (!has_joint) continue; + const k = if (side > 0) (if (closed) (s + 1) % segments else s) else (if (closed) s else s - 1); + const j = js[k]; + if (j.outer == side) { + if (j.miter) |m| joint_points[k][0] = try t.appendPoint(gpa, xf.apply(m)); + if (round_join) { + // From this body's corner to the next body's, around the vertex. + const next = if (side > 0) (s + 1) % segments else (s + segments - 1) % segments; + const from = (if (side > 0) body.end[c] else body.start[c]) - j.vertex; + const to = (if (side > 0) bodies[next].start[c] else bodies[next].end[c]) - j.vertex; + const sweep = std.math.atan2(math.cross(from, to), math.dot(from, to)); + arcs[k] = try t.appendArc(gpa, j.vertex, from, sweep, li, xf); + } + } else if (!j.clean) { + joint_points[k][1] = try t.appendPoint(gpa, xf.apply(j.vertex)); + } + } + if (!closed and style.cap == .round) { + // Half a turn from this side's last corner to the other side's. + const at = if (side > 0) pts[n - 1] else pts[0]; + const corner = if (side > 0) bodies[segments - 1].end[0] else bodies[0].start[1]; + caps[c] = try t.appendArc(gpa, at, corner - at, std.math.pi, previous.?, xf); + previous = null; + } + if (closed) try t.endSubpath(gpa); + } + if (!closed) try t.endSubpath(gpa); + + for (corners) |cs| { + try t.appendTriangle(gpa, cs[0], cs[1], cs[2]); + try t.appendTriangle(gpa, cs[0], cs[2], cs[3]); + } + for (js, joint_points, arcs, 0..) |j, jp, arc, k| { + const a = if (closed) (k + segments - 1) % segments else k; + const b = (a + 1) % segments; + const outer_end = if (j.outer > 0) corners[a][1] else corners[a][2]; + const outer_start = if (j.outer > 0) corners[b][0] else corners[b][3]; + const inner = if (j.clean) (if (j.outer > 0) corners[a][2] else corners[a][1]) else jp[1].?; + try t.appendTriangle(gpa, inner, outer_end, outer_start); + if (jp[0]) |m| try t.appendTriangle(gpa, outer_end, m, outer_start); + if (round_join) try t.fanArc(gpa, arc, if (arc.from == outer_end) outer_start else outer_end); + } + if (!closed and style.cap == .round) { + try t.fanArc(gpa, caps[0], corners[segments - 1][2]); + try t.fanArc(gpa, caps[1], corners[0][0]); + } + t.finish(mark); + } +}; + +fn vec(p: [2]f32) Vec { + return .{ p[0], p[1] }; +} + +fn xy(p: Vec) [2]f32 { + return .{ p[0], p[1] }; +} + +fn rectCorners(r: math.Rect) [4]Vec { + return .{ .{ r.x, r.y }, .{ r.x + r.w, r.y }, .{ r.x + r.w, r.y + r.h }, .{ r.x, r.y + r.h } }; +} + +fn angleOf(k: usize, n: u32) f32 { + return 2 * std.math.pi * @as(f32, @floatFromInt(k)) / @as(f32, @floatFromInt(n)); +} + +/// Twice nothing: the shoelace sum, positive for clockwise on a y-down +/// screen. +fn signedArea(points: []const [2]f32) f32 { + var sum: f32 = 0; + for (points, 0..) |p, i| { + const q = points[(i + 1) % points.len]; + sum += p[0] * q[1] - q[0] * p[1]; + } + return sum / 2; +} + +fn inTriangle(p: Vec, a: Vec, b: Vec, c: Vec, sign: f32) bool { + return sign * math.cross(b - a, p - a) >= 0 and sign * math.cross(c - b, p - b) >= 0 and sign * math.cross(a - c, p - c) >= 0; +} + +/// Segments for a whole circle of `radius` under `xf`, so that no point of +/// the polygon is more than `tolerance` canvas pixels inside the circle. +pub fn circleSegments(radius: f32, xf: Affine) u32 { + const r = radius * xf.maxScale(); + if (!(r > tolerance)) return 8; + const n = @ceil(std.math.pi / std.math.acos(1 - tolerance / r)); + return @intFromFloat(std.math.clamp(n, 8, 1024)); +} + +// --------------------------------------------------------------------------- +// L2: a Pen + +/// How `circle`, `line`, `polyline`, `polygon`, `rect` and `point` draw: +/// plain data, so it can be a `const`, a State field, or a copy changed +/// for one call. `transformed` is Processing's push-translate-rotate; the +/// copy going out of scope is the pop. `fill = null` is `noFill()`, +/// `stroke = null` is `noStroke()`. +pub const Pen = struct { + fill: ?Color = null, + stroke: ?Color = null, + /// The stroke's width, in the pen's (transformed) units. + width: f32 = 1, + /// Corners of `polyline`, `polygon` and `rect` strokes. + join: Join = .miter, + /// Ends of `line` and `polyline`; a `point` is round with `.round`, + /// square otherwise. Processing's defaults, both. + cap: Cap = .round, + xf: Affine = .identity, + + /// This pen, drawing in a space placed by `m` inside its own. + pub fn transformed(p: Pen, m: Affine) Pen { + var q = p; + q.xf = p.xf.mul(m); + return q; + } + + /// The stroke shape `strokePath` takes, for a path open or `closed`. + pub fn outline(p: Pen, closed: bool) Stroke { + return .{ .width = p.width, .join = p.join, .cap = p.cap, .closed = closed }; + } +}; + +/// A circle of `radius` around `center`: the fill, then the stroke over it, +/// centred on the edge. +pub fn circle(f: *root.Frame, center: Vec, radius: f32, pen: Pen) void { + if (pen.fill) |color| { + var t: Tessellation = .empty; + t.fillCircle(f.scratch, center, radius, pen.xf) catch return dropped(f); + f.shape(&t, color); + } + if (pen.stroke) |color| { + var t: Tessellation = .empty; + t.strokeCircle(f.scratch, center, radius, pen.width, pen.xf) catch return dropped(f); + f.shape(&t, color); + } +} + +/// A segment from `a` to `b` in the stroke colour, with the pen's caps. +pub fn line(f: *root.Frame, a: Vec, b: Vec, pen: Pen) void { + const color = pen.stroke orelse return; + var t: Tessellation = .empty; + const done = if (pen.cap == .round) + t.strokeLine(f.scratch, a, b, pen.width, pen.xf) + else + t.strokePath(f.scratch, &.{ a, b }, pen.outline(false), pen.xf); + done catch return dropped(f); + f.shape(&t, color); +} + +/// An open path through `points`: Processing's `beginShape()` ... +/// `endShape()`. The fill, if any, is the polygon the points close (as +/// Processing fills it), then the stroke along the open path, with the +/// pen's joins and caps. +pub fn polyline(f: *root.Frame, points: []const Vec, pen: Pen) void { + path(f, points, pen, false); +} + +/// A closed polygon (simple: convex or not): the fill, then the stroke, +/// with the pen's joins. `endShape(CLOSE)`. +pub fn polygon(f: *root.Frame, points: []const Vec, pen: Pen) void { + path(f, points, pen, true); +} + +/// A rect: the fill, then the stroke centred on its edge. +pub fn rect(f: *root.Frame, r: math.Rect, pen: Pen) void { + const cs = rectCorners(r); + if (r.w > 0 and r.h > 0) path(f, &cs, pen, true); +} + +/// A dot `pen.width` across in the stroke colour, round or square by the +/// pen's cap: Processing's `point`. +pub fn point(f: *root.Frame, at: Vec, pen: Pen) void { + const color = pen.stroke orelse return; + var t: Tessellation = .empty; + const done = if (pen.cap == .round) + t.fillCircle(f.scratch, at, pen.width / 2, pen.xf) + else + t.fillRect(f.scratch, .{ .x = at[0] - pen.width / 2, .y = at[1] - pen.width / 2, .w = pen.width, .h = pen.width }, pen.xf); + done catch return dropped(f); + f.shape(&t, color); +} + +fn path(f: *root.Frame, points: []const Vec, pen: Pen, closed: bool) void { + if (pen.fill) |color| { + var t: Tessellation = .empty; + t.fillPolygon(f.scratch, points, pen.xf) catch return dropped(f); + f.shape(&t, color); + } + if (pen.stroke) |color| { + var t: Tessellation = .empty; + t.strokePath(f.scratch, points, pen.outline(closed), pen.xf) catch return dropped(f); + f.shape(&t, color); + } +} + +fn dropped(f: *root.Frame) void { + f.host.log("out of scratch memory: shape dropped"); +} + +// --------------------------------------------------------------------------- +// Tests: every shape keeps the contract. + +const testing = std.testing; + +/// Checks the contract: indices in range, every triangle positively +/// wound, no two triangles overlapping (beyond touching), the triangles' +/// area equal to the subpaths' nonzero area, and subpath ends in order. +fn expectValid(t: *const Tessellation) !void { + return expectShape(t, .{}); +} + +/// `expectValid` with knobs: `disjoint = false` allows triangles to +/// overlap, for the documented exceptions, and then checks only that +/// triangles and subpaths cover the same region (no holes on the web). +fn expectShape(t: *const Tessellation, options: struct { disjoint: bool = true }) !void { + const pts = t.points.items; + try testing.expect(t.indices.items.len % 3 == 0); + var previous: u32 = 0; + for (t.ends.items) |e| { + try testing.expect(e >= previous and e <= pts.len); + previous = e; + } + try testing.expectEqual(@as(usize, previous), pts.len); + var total: f64 = 0; + const tris = t.indices.items; + var i: usize = 0; + while (i < tris.len) : (i += 3) { + for (tris[i..][0..3]) |k| try testing.expect(k < pts.len); + const a = vec(pts[tris[i]]); + const b = vec(pts[tris[i + 1]]); + const c = vec(pts[tris[i + 2]]); + const area = math.cross(b - a, c - a) / 2; + try testing.expect(area > 0); + total += area; + } + // Disjoint: sampled, since exact polygon intersection is a lot of code + // for a test. Every sample point lies in at most one triangle's + // interior, and in one exactly when the subpaths' winding is nonzero. + var lo: Vec = splat(std.math.inf(f32)); + var hi: Vec = splat(-std.math.inf(f32)); + for (pts) |p| { + lo = @min(lo, vec(p)); + hi = @max(hi, vec(p)); + } + const steps = 160; + for (0..steps) |yi| for (0..steps) |xi| { + // Off-grid offsets, so samples rarely land on an edge. + const fx = (@as(f32, @floatFromInt(xi)) + 0.3711) / steps; + const fy = (@as(f32, @floatFromInt(yi)) + 0.6173) / steps; + const p = lo + (hi - lo) * Vec{ fx, fy }; + var inside: u32 = 0; + i = 0; + while (i < tris.len) : (i += 3) { + const a = vec(pts[tris[i]]); + const b = vec(pts[tris[i + 1]]); + const c = vec(pts[tris[i + 2]]); + if (strictlyInside(p, a, b, c)) inside += 1; + } + if (options.disjoint) try testing.expect(inside <= 1); + const wind = winding(t, p); + if (inside >= 1) try testing.expect(wind != 0); + if (wind != 0 and inside == 0) try testing.expect(onAnyEdge(t, p)); + }; + // And the areas agree: the triangles tile the filled region. + var region: f64 = 0; + var start: u32 = 0; + for (t.ends.items) |e| { + region += signedArea(pts[start..e]); + start = e; + } + if (options.disjoint) try testing.expectApproxEqRel(region, total, 1e-3); +} + +fn strictlyInside(p: Vec, a: Vec, b: Vec, c: Vec) bool { + const eps = 1e-4; + return math.cross(b - a, p - a) > eps and math.cross(c - b, p - b) > eps and math.cross(a - c, p - c) > eps; +} + +fn onAnyEdge(t: *const Tessellation, p: Vec) bool { + const tris = t.indices.items; + var i: usize = 0; + while (i < tris.len) : (i += 3) { + for (0..3) |e| { + const a = vec(t.points.items[tris[i + e]]); + const b = vec(t.points.items[tris[i + (e + 1) % 3]]); + const ab = b - a; + const l2 = math.dot(ab, ab); + if (l2 == 0) continue; + const u = std.math.clamp(math.dot(p - a, ab) / l2, 0, 1); + if (math.length(a + math.scale(ab, u) - p) < 1e-2) return true; + } + } + return false; +} + +/// The subpaths' winding number around `p`. +fn winding(t: *const Tessellation, p: Vec) i32 { + var w: i32 = 0; + var start: u32 = 0; + for (t.ends.items) |e| { + const ring_pts = t.points.items[start..e]; + for (ring_pts, 0..) |a_, k| { + const a = vec(a_); + const b = vec(ring_pts[(k + 1) % ring_pts.len]); + if (a[1] <= p[1]) { + if (b[1] > p[1] and math.cross(b - a, p - a) > 0) w += 1; + } else { + if (b[1] <= p[1] and math.cross(b - a, p - a) < 0) w -= 1; + } + } + start = e; + } + return w; +} + +test "circles: positive, disjoint, and as many segments as the scale needs" { + const gpa = testing.allocator; + var t: Tessellation = .empty; + defer t.deinit(gpa); + try t.fillCircle(gpa, .{ 50, 40 }, 20, .identity); + try expectValid(&t); + try testing.expectEqual(@as(usize, 1), t.ends.items.len); + const n = t.points.items.len; + try testing.expectEqual(@as(usize, 3 * (n - 2)), t.indices.items.len); + try testing.expect(circleSegments(20, .scale(4, 4)) > circleSegments(20, .identity)); + try testing.expectEqual(circleSegments(80, .identity), circleSegments(20, .scale(4, 4))); + + t.clearRetainingCapacity(); + try t.strokeCircle(gpa, .{ 0, 0 }, 30, 6, .identity); + try expectValid(&t); + try testing.expectEqual(@as(usize, 2), t.ends.items.len); + try testing.expectEqual(@as(usize, 3 * t.points.items.len), t.indices.items.len); + + // A mirroring transform still winds positively. + t.clearRetainingCapacity(); + try t.strokeCircle(gpa, .{ 10, 0 }, 30, 6, Affine.scale(-1, 1).mul(.rotate(0.3))); + try expectValid(&t); + t.clearRetainingCapacity(); + try t.fillCircle(gpa, .{ 10, 0 }, 3, .scale(1, -2)); + try expectValid(&t); +} + +test "polygons: convex, concave, either winding, mirrored" { + const gpa = testing.allocator; + var t: Tessellation = .empty; + defer t.deinit(gpa); + const triangle = [_]Vec{ .{ 20, 0 }, .{ -10, -8 }, .{ -10, 8 } }; + const arrow = [_]Vec{ .{ 0, 0 }, .{ 60, 0 }, .{ 60, 60 }, .{ 30, 20 }, .{ 0, 60 } }; + const star = blk: { + var s: [10]Vec = undefined; + for (&s, 0..) |*p, i| p.* = math.scale(math.unit(@as(f32, @floatFromInt(i)) * std.math.pi / 5.0), if (i % 2 == 0) 50 else 20); + break :blk s; + }; + var backwards = arrow; + std.mem.reverse(Vec, &backwards); + for ([_][]const Vec{ &triangle, &arrow, &backwards, &star }) |shape| { + for ([_]Affine{ .identity, .place(.{ 100, 50 }, 1.1), .scale(-2, 1) }) |xf| { + t.clearRetainingCapacity(); + try t.fillPolygon(gpa, shape, xf); + try expectValid(&t); + try testing.expectEqual(3 * (shape.len - 2), t.indices.items.len); + t.clearRetainingCapacity(); + try t.strokePolygon(gpa, shape, 3, xf); + try expectValid(&t); + } + } +} + +test "strokes: lines with round ends, acute zig-zags without overlap" { + const gpa = testing.allocator; + var t: Tessellation = .empty; + defer t.deinit(gpa); + try t.strokeLine(gpa, .{ 10, 10 }, .{ 200, 60 }, 9, .identity); + try expectValid(&t); + t.clearRetainingCapacity(); + try t.strokeLine(gpa, .{ 10, 10 }, .{ 10, 10 }, 4, .identity); + try expectValid(&t); + t.clearRetainingCapacity(); + try t.strokeLine(gpa, .{ 0, 0.5 }, .{ 100, 0.5 }, 1, .identity); + try expectValid(&t); + + const zigzag = [_]Vec{ .{ 20, 200 }, .{ 70, 60 }, .{ 120, 200 }, .{ 170, 60 }, .{ 220, 200 }, .{ 240, 190 } }; + for ([_]f32{ 2, 12, 30 }) |w| { + t.clearRetainingCapacity(); + try t.strokePolyline(gpa, &zigzag, w, .identity); + try expectValid(&t); + t.clearRetainingCapacity(); + try t.strokePolyline(gpa, &zigzag, w, .scale(-1, 1)); + try expectValid(&t); + } + // Segments shorter than an acute turn needs: the bodies overlap (the + // documented exception), but the web's outline still has no holes. + const tight = [_]Vec{ .{ 0, 100 }, .{ 10, 0 }, .{ 20, 100 }, .{ 25, 95 }, .{ 30, 100 } }; + t.clearRetainingCapacity(); + try t.strokePolyline(gpa, &tight, 16, .identity); + try expectShape(&t, .{ .disjoint = false }); + t.clearRetainingCapacity(); + try t.strokePolygon(gpa, &tight, 16, .identity); + try expectShape(&t, .{ .disjoint = false }); + // Straight runs and repeated points. + const straight = [_]Vec{ .{ 0, 0 }, .{ 10, 0 }, .{ 10, 0 }, .{ 20, 0 }, .{ 30, 10 } }; + t.clearRetainingCapacity(); + try t.strokePolyline(gpa, &straight, 4, .identity); + try expectValid(&t); + // A square's outline: a ring with a hole. + const square = [_]Vec{ .{ 0, 0 }, .{ 50, 0 }, .{ 50, 50 }, .{ 0, 50 } }; + t.clearRetainingCapacity(); + try t.strokePolygon(gpa, &square, 6, .identity); + try expectValid(&t); + try testing.expectEqual(@as(usize, 2), t.ends.items.len); +} + +test "nothing to draw draws nothing" { + const gpa = testing.allocator; + var t: Tessellation = .empty; + defer t.deinit(gpa); + try t.fillCircle(gpa, .{ 0, 0 }, 0, .identity); + try t.strokeCircle(gpa, .{ 0, 0 }, 10, 0, .identity); + try t.fillPolygon(gpa, &.{ .{ 0, 0 }, .{ 1, 1 } }, .identity); + try t.strokePolyline(gpa, &.{.{ 0, 0 }}, 3, .identity); + try testing.expectEqual(@as(usize, 0), t.points.items.len + t.indices.items.len + t.ends.items.len); +} + +test "joins and caps: every combination keeps the contract" { + const gpa = testing.allocator; + var t: Tessellation = .empty; + defer t.deinit(gpa); + const zigzag = [_]Vec{ .{ 20, 200 }, .{ 70, 60 }, .{ 120, 200 }, .{ 170, 60 }, .{ 220, 200 }, .{ 240, 190 } }; + const path_like = [_]Vec{ .{ -20, 180 }, .{ 150, 40 }, .{ 450, 300 }, .{ 660, 180 } }; + const square = [_]Vec{ .{ 0, 0 }, .{ 50, 0 }, .{ 50, 50 }, .{ 0, 50 } }; + for ([_]Join{ .miter, .round, .bevel }) |join| for ([_]Cap{ .butt, .round, .square }) |cap| { + for ([_]f32{ 2, 12, 30 }) |w| for ([_]Affine{ .identity, .scale(-1, 1), .place(.{ 30, 40 }, 0.7) }) |xf| { + t.clearRetainingCapacity(); + try t.strokePath(gpa, &zigzag, .{ .width = w, .join = join, .cap = cap }, xf); + try expectValid(&t); + t.clearRetainingCapacity(); + try t.strokePath(gpa, &square, .{ .width = w, .join = join, .closed = true }, xf); + try expectValid(&t); + }; + t.clearRetainingCapacity(); + try t.strokePath(gpa, &path_like, .{ .width = 40, .join = join, .cap = cap }, .identity); + try expectValid(&t); + }; + // Round caps and joins add area: a round-capped segment is the stadium. + t.clearRetainingCapacity(); + try t.strokePath(gpa, &.{ .{ 10, 10 }, .{ 110, 10 } }, .{ .width = 20, .cap = .round }, .identity); + try expectValid(&t); + const stadium = triangleArea(&t); + try testing.expectApproxEqRel(@as(f32, 100 * 20 + std.math.pi * 100), stadium, 0.01); + t.clearRetainingCapacity(); + try t.strokePath(gpa, &.{ .{ 10, 10 }, .{ 110, 10 } }, .{ .width = 20, .cap = .square }, .identity); + try testing.expectApproxEqRel(@as(f32, 120 * 20), triangleArea(&t), 1e-4); + // A zero-length path is a dot with round or square caps. + t.clearRetainingCapacity(); + try t.strokePath(gpa, &.{ .{ 5, 5 }, .{ 5, 5 } }, .{ .width = 4, .cap = .square }, .identity); + try testing.expectApproxEqRel(@as(f32, 16), triangleArea(&t), 1e-4); + t.clearRetainingCapacity(); + try t.strokePath(gpa, &.{.{ 5, 5 }}, .{ .width = 4 }, .identity); + try testing.expectEqual(@as(usize, 0), t.indices.items.len); +} + +test "rects: filled and stroked, many in one tessellation" { + const gpa = testing.allocator; + var t: Tessellation = .empty; + defer t.deinit(gpa); + try t.fillRect(gpa, .{ .x = 10, .y = 20, .w = 30, .h = 40 }, .identity); + try expectValid(&t); + try testing.expectApproxEqRel(@as(f32, 1200), triangleArea(&t), 1e-5); + t.clearRetainingCapacity(); + try t.strokeRect(gpa, .{ .x = 10, .y = 20, .w = 30, .h = 40 }, 2, .identity); + try expectValid(&t); + try testing.expectApproxEqRel(@as(f32, 32 * 42 - 28 * 38), triangleArea(&t), 1e-4); + t.clearRetainingCapacity(); + for (0..4) |i| { + const x: f32 = @floatFromInt(i * 40); + try t.strokeRect(gpa, .{ .x = x, .y = 0, .w = 30, .h = 30 }, 1, .identity); + } + try testing.expectEqual(@as(usize, 8), t.ends.items.len); + try t.fillRect(gpa, .{ .x = 0, .y = 0, .w = 0, .h = 5 }, .identity); + try testing.expectEqual(@as(usize, 8), t.ends.items.len); +} + +fn triangleArea(t: *const Tessellation) f32 { + var sum: f32 = 0; + var i: usize = 0; + while (i < t.indices.items.len) : (i += 3) { + const a = vec(t.points.items[t.indices.items[i]]); + const b = vec(t.points.items[t.indices.items[i + 1]]); + const c = vec(t.points.items[t.indices.items[i + 2]]); + sum += math.cross(b - a, c - a) / 2; + } + return sum; +} diff --git a/src/sketch/list.zig b/src/sketch/list.zig new file mode 100644 index 0000000..8040a5d --- /dev/null +++ b/src/sketch/list.zig @@ -0,0 +1,109 @@ +//! A list with its capacity in its type: plain data, so it can live in +//! State (no pointers) and migrate there element by element. +const std = @import("std"); + +/// `buffer` and `len` are public fields, so the host's console and scripts +/// reach elements by path (`boids.buffer[3].pos[0]`, `boids.len`). +/// +/// Every method clamps `len` to the capacity: after a reload that shrinks +/// the capacity, a saved `len` may be larger than the new buffer, and the +/// list then holds `capacity` elements rather than indexing out of bounds. +/// The names and errors are std's (`ArrayList`'s bounded methods). +pub fn List(comptime T: type, comptime cap: u32) type { + return struct { + const Self = @This(); + pub const capacity = cap; + + buffer: [cap]T = default_buffer, + len: u32 = 0, + + /// T's own defaults when it has them for every field, zeroes for + /// numbers, the first tag for enums; otherwise undefined. Never + /// `std.mem.zeroes`, which fails on enums with no 0 tag. + const default_buffer: [cap]T = if (defaultOf(T)) |d| @splat(d) else undefined; + + pub fn slice(l: *Self) []T { + return l.buffer[0..l.count()]; + } + pub fn constSlice(l: *const Self) []const T { + return l.buffer[0..l.count()]; + } + /// `len`, clamped to the capacity. + pub fn count(l: *const Self) u32 { + return @min(l.len, cap); + } + pub fn appendBounded(l: *Self, item: T) error{OutOfMemory}!void { + const n = l.count(); + if (n == cap) return error.OutOfMemory; + l.buffer[n] = item; + l.len = n + 1; + } + /// Removes the element at `i`, keeping the order of the rest. + pub fn orderedRemove(l: *Self, i: u32) T { + const n = l.count(); + const item = l.buffer[i]; + std.mem.copyForwards(T, l.buffer[i .. n - 1], l.buffer[i + 1 .. n]); + l.len = n - 1; + return item; + } + /// Removes the element at `i`, moving the last one into its place. + pub fn swapRemove(l: *Self, i: u32) T { + const n = l.count(); + const item = l.buffer[i]; + l.buffer[i] = l.buffer[n - 1]; + l.len = n - 1; + return item; + } + pub fn clear(l: *Self) void { + l.len = 0; + } + }; +} + +fn defaultOf(comptime T: type) ?T { + return switch (@typeInfo(T)) { + .int, .float, .vector => std.mem.zeroes(T), + .bool => false, + .optional => null, + .array => |a| if (defaultOf(a.child)) |d| @splat(d) else null, + .@"enum" => |e| if (e.mode == .exhaustive) @field(T, e.field_names[0]) else @enumFromInt(0), + .@"struct" => |s| { + for (s.field_attrs) |attrs| if (attrs.default_value_ptr == null) return null; + return .{}; + }, + else => null, + }; +} + +test "append, remove, clamp after a capacity shrink" { + const Kind = enum(u8) { a = 1, b = 2 }; + const Item = struct { kind: Kind = .b, x: f32 = 1 }; + var l: List(Item, 4) = .{}; + try std.testing.expectEqual(Kind.b, l.buffer[3].kind); + for (0..4) |i| try l.appendBounded(.{ .x = @floatFromInt(i) }); + try std.testing.expectError(error.OutOfMemory, l.appendBounded(.{})); + try std.testing.expectEqual(@as(f32, 1), l.orderedRemove(1).x); + try std.testing.expectEqual(@as(f32, 2), l.constSlice()[1].x); + try std.testing.expectEqual(@as(f32, 0), l.swapRemove(0).x); + try std.testing.expectEqual(@as(f32, 3), l.slice()[0].x); + try std.testing.expectEqual(@as(usize, 2), l.slice().len); + // A saved len from a bigger list. + l.len = 10; + try std.testing.expectEqual(@as(usize, 4), l.constSlice().len); + try std.testing.expectError(error.OutOfMemory, l.appendBounded(.{})); + _ = l.swapRemove(0); + try std.testing.expectEqual(@as(u32, 3), l.len); +} + +test "defaults for element types without struct defaults" { + const E = enum(u8) { one = 1, two = 2 }; + const a: List(E, 3) = .{}; + try std.testing.expectEqual(E.one, a.buffer[2]); + const b: List(f32, 3) = .{}; + try std.testing.expectEqual(@as(f32, 0), b.buffer[1]); + const c: List(@Vector(2, f32), 2) = .{}; + try std.testing.expectEqual(@as(f32, 0), c.buffer[1][0]); + const NoDefault = struct { x: f32 }; + const d: List(NoDefault, 2) = .{}; + try std.testing.expectEqual(@as(u32, 0), d.len); +} diff --git a/src/sketch/root.zig b/src/sketch/root.zig index 94ce617..33c9ba7 100644 --- a/src/sketch/root.zig +++ b/src/sketch/root.zig @@ -22,10 +22,23 @@ //! see `shape`. const std = @import("std"); pub const abi = @import("abi"); -pub const shape = @import("shape.zig"); +/// 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; @@ -36,12 +49,14 @@ 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; /// What `draw` receives: input, host services, memory by lifetime and the /// command list. Commands may be built from anything: the methods copy what @@ -71,35 +86,91 @@ pub const Frame = struct { 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 = shape.color(color) }); + f.emit(.{ .clear = paint(color) }); } pub fn fill(f: *Frame, r: anytype, color: anytype) void { - f.emit(.{ .rect = .{ .dst = shape.rect(r), .color = shape.color(color) } }); + 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 = shape.rect(dst), - .src = if (@hasField(O, "src")) shape.rect(options.src) else .{}, - .tint = if (@hasField(O, "tint")) shape.color(options.tint) else .white, + .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 = shape.color(color), .bytes = f.keep(u8, bytes) } }); + f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = paint(color), .bytes = f.keep(u8, bytes) } }); } 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 = shape.color(color), .bytes = f.format(fmt, args) } }); + 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 shape.rect(r) }); + 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 } }); @@ -171,6 +242,13 @@ pub const Frame = struct { } }; +/// 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 { @@ -305,7 +383,11 @@ pub fn Glue(comptime App: type) type { test { _ = request; _ = abi.layout; - _ = shape; + _ = shapes; _ = @import("camera.zig"); _ = tween; + _ = draw; + _ = @import("clock.zig"); + _ = @import("list.zig"); + _ = @import("derived.zig"); } diff --git a/src/sketch/web.zig b/src/sketch/web.zig index bc7fead..27313a6 100644 --- a/src/sketch/web.zig +++ b/src/sketch/web.zig @@ -18,7 +18,18 @@ const js = struct { extern "host" fn openFile(command: [*]const u8, command_len: usize, pattern: [*]const u8, pattern_len: usize) void; extern "canvas" fn clear(r: u32, g: u32, b: u32, a: u32) void; extern "canvas" fn fill(x: f32, y: f32, w: f32, h: f32, r: u32, g: u32, b: u32, a: u32) void; - extern "canvas" fn image(id: u32, x: f32, y: f32, w: f32, h: f32, sx: f32, sy: f32, sw: f32, sh: f32, alpha: u32) void; + extern "canvas" fn image(id: u32, x: f32, y: f32, w: f32, h: f32, sx: f32, sy: f32, sw: f32, sh: f32, r: u32, g: u32, b: u32, a: u32) void; + /// The image (or `sw` x `sh` at `sx`, `sy`) with its corners at the + /// three points: top left, top right, bottom left. + extern "canvas" fn imageCorners(id: u32, x0: f32, y0: f32, x1: f32, y1: f32, x2: f32, y2: f32, sx: f32, sy: f32, sw: f32, sh: f32, r: u32, g: u32, b: u32, a: u32) void; + /// Fills the subpaths `points[ends[i - 1] .. ends[i]]` nonzero: + /// `points` is `len` pairs of f32, `ends` `ends_len` u32s, `colors` + /// `colors_len` RGBA quadruples, one per subpath (else `r, g, b, a`). + extern "canvas" fn shape(points: [*]const [2]f32, len: usize, ends: [*]const u32, ends_len: usize, colors: [*]const abi.Color, colors_len: usize, r: u32, g: u32, b: u32, a: u32) void; + /// Draws into image `id`, or the canvas for 0. + extern "canvas" fn target(id: u32) void; + /// `abi.BlendMode` by value. + extern "canvas" fn blend(mode: u32) void; extern "canvas" fn text(x: f32, y: f32, scale: f32, ptr: [*]const u8, len: usize, r: u32, g: u32, b: u32, a: u32) void; extern "canvas" fn clip(enabled: u32, x: f32, y: f32, w: f32, h: f32) void; extern "canvas" fn canvas(w: u32, h: u32) void; @@ -136,8 +147,11 @@ fn Driver(comptime App: type) type { const now: u64 = @intFromFloat(@max(0, ms) * std.time.ns_per_ms); const dt = if (last == 0) 0 else now -| last; last = now; + // `in.dt` comes from the tick, as on native, so it is what a + // replay of the tick would give. + const tick = abi.Event.tick(now, dt); if (event_count < events.len) { - events[event_count] = .{ .kind = .tick, .x = @floatCast(@as(f64, @floatFromInt(dt)) / std.time.ns_per_s) }; + events[event_count] = tick; event_count += 1; } for (events[0..event_count]) |*e| { @@ -147,7 +161,7 @@ fn Driver(comptime App: type) type { _ = scratch.reset(.retain_capacity); commands = .empty; input.now = now; - input.dt = dt; + input.dt = tick.tickDt(); input.frame += 1; input.events = events[0..event_count]; input.started = input.frame == 1; @@ -159,9 +173,15 @@ fn Driver(comptime App: type) type { G.update(&ctx, std.mem.asBytes(&state)); input.events = &.{}; event_count = 0; + // No timeline here: only the first frame comes from nowhere. + input.jumped = input.frame == 1; G.draw(&ctx, std.mem.asBytes(&state)); + js.target(0); + js.blend(0); js.clip(0, 0, 0, 0, 0); for (commands.items) |c| submit(c); + js.target(0); + js.blend(0); // After the frame, as on native: lines `draw` asked to run. for (commands.items) |c| if (c == .run) run(c.run); @@ -176,7 +196,13 @@ fn Driver(comptime App: type) type { switch (c) { .clear => |v| js.clear(v.r, v.g, v.b, v.a), .rect => |v| js.fill(v.dst.x, v.dst.y, v.dst.w, v.dst.h, v.color.r, v.color.g, v.color.b, v.color.a), - .image => |v| js.image(@backingInt(v.image), v.dst.x, v.dst.y, v.dst.w, v.dst.h, v.src.x, v.src.y, v.src.w, v.src.h, v.tint.a), + .image => |v| if (v.corners) |q| + js.imageCorners(@backingInt(v.image), q.top_left[0], q.top_left[1], q.top_right[0], q.top_right[1], q.bottom_left[0], q.bottom_left[1], v.src.x, v.src.y, v.src.w, v.src.h, v.tint.r, v.tint.g, v.tint.b, v.tint.a) + else + js.image(@backingInt(v.image), v.dst.x, v.dst.y, v.dst.w, v.dst.h, v.src.x, v.src.y, v.src.w, v.src.h, v.tint.r, v.tint.g, v.tint.b, v.tint.a), + .shape => |v| js.shape(v.points.ptr, v.points.len, v.ends.ptr, v.ends.len, v.colors.ptr, v.colors.len, v.color.r, v.color.g, v.color.b, v.color.a), + .target => |v| js.target(@backingInt(v)), + .blend => |v| js.blend(@backingInt(v)), .text => |v| js.text(v.x, v.y, v.scale, v.bytes.ptr, v.bytes.len, v.color.r, v.color.g, v.color.b, v.color.a), .clip => |v| if (v) |r| js.clip(1, r.x, r.y, r.w, r.h) else js.clip(0, 0, 0, 0, 0), .canvas => |v| { @@ -320,8 +346,10 @@ fn Driver(comptime App: type) type { /// it, and returns its length; -1 when there is no such enum field. fn tag(len: usize) callconv(.c) i32 { const name = path[0..@min(len, path.len)]; - for (G.description.state.fields) |f| { - if (f.kind != .@"enum" or !std.mem.eql(u8, std.mem.span(f.path), name)) continue; + // Paths may index arrays and vector lanes (`list[2].mood`). + if (abi.layout.resolve(G.description.state.fields, name)) |r| { + const f = r.field; + if (f.kind != .@"enum") return -1; const value: u64 = @intFromFloat(field(len)); var pairs = std.mem.tokenizeScalar(u8, std.mem.span(f.tags), ','); while (pairs.next()) |pair| { @@ -339,9 +367,9 @@ fn Driver(comptime App: type) type { fn field(len: usize) callconv(.c) f64 { const name = path[0..@min(len, path.len)]; const bytes = std.mem.asBytes(&state); - for (G.description.state.fields) |f| { - if (!std.mem.eql(u8, std.mem.span(f.path), name)) continue; - const raw = bytes[f.offset..][0..f.size]; + if (abi.layout.resolve(G.description.state.fields, name)) |r| { + const f = r.field; + const raw = bytes[r.offset..][0..f.size]; var value: u64 = 0; for (raw[0..@min(raw.len, 8)], 0..) |b, i| value |= @as(u64, b) << @intCast(i * 8); return switch (f.kind) { diff --git a/src/vector/Cpu.zig b/src/vector/Cpu.zig index c17366f..ac5c6ea 100644 --- a/src/vector/Cpu.zig +++ b/src/vector/Cpu.zig @@ -6,7 +6,7 @@ //! wasm included, and is the reference the GPU backend is tested against. const Cpu = @This(); const std = @import("std"); -const geom = @import("geom.zig"); +const geom = @import("math"); const Drawing = @import("Drawing.zig"); const Polygons = @import("Polygons.zig"); const Paint = @import("Paint.zig"); diff --git a/src/vector/Drawing.zig b/src/vector/Drawing.zig index 0a3b77b..339f1ce 100644 --- a/src/vector/Drawing.zig +++ b/src/vector/Drawing.zig @@ -3,7 +3,7 @@ //! read and recombine them. const Drawing = @This(); const std = @import("std"); -const geom = @import("geom.zig"); +const geom = @import("math"); const Vec = geom.Vec; const Cubic = geom.Cubic; diff --git a/src/vector/Gpu.zig b/src/vector/Gpu.zig index 5853145..3c9d48c 100644 --- a/src/vector/Gpu.zig +++ b/src/vector/Gpu.zig @@ -1,16 +1,33 @@ -//! The GPU backend, as data: every fill becomes a stencil draw and a cover -//! draw in an `abi.gpu.Pass` that the host runs. Stencil-then-cover: -//! - stencil: the contours as triangle fans, counting windings in the -//! stencil buffer (increment/decrement by facing for nonzero, invert for -//! even-odd), color writes off; -//! - cover: the bounding box, painted where the stencil is set, zeroing the -//! stencil as it goes so the next fill starts clean. -//! Anti-aliasing is 8x multisampling. Paint runs in `cover.frag`, the GPU -//! twin of `Paint.zig`. +//! The GPU backend, as data: fills become draws in an `abi.gpu.Pass` that +//! the host runs. A fill is drawn one of two ways: +//! - direct, when its polygons are one convex contour: its triangle fan, +//! painted, covers each inside sample exactly once; +//! - stencil-then-cover otherwise: the contours as triangle fans count +//! windings in the stencil buffer (increment/decrement by facing for +//! nonzero, invert for even-odd), color writes off; then its bounding box +//! is painted where the stencil is set, zeroing the stencil as it goes so +//! the next fill starts clean. +//! +//! Fills are batched into layers, so the draw count follows how deep fills +//! pile up, not how many there are. A layer draws its stencil fans (one +//! draw per fill rule), then its cover boxes, then its direct fans, each in +//! one draw. A fill goes into the lowest layer that keeps the picture as if +//! every fill were drawn alone, in order: above every layer holding an +//! earlier fill whose box overlaps its own, except that a direct fill may +//! share the layer of what it overlaps (it is drawn after that layer's +//! covers, and after earlier direct fans in order). Stencilled fills in one +//! layer never overlap, so their stencils and covers cannot mix. Overlap is +//! judged on a coarse grid of the image, conservatively: neighbours in a +//! cell count as overlapping. +//! +//! Each vertex of a painted triangle carries its fill's paint: a solid +//! color, or the index of a gradient in a storage buffer of `Paint` blocks +//! uploaded with the pass. Anti-aliasing is 8x multisampling. Gradients run +//! in `paint.frag`, the GPU twin of `Paint.zig`. const Gpu = @This(); const std = @import("std"); const abi = @import("abi"); -const geom = @import("geom.zig"); +const geom = @import("math"); const Drawing = @import("Drawing.zig"); const Polygons = @import("Polygons.zig"); const Paint = @import("Paint.zig"); @@ -21,9 +38,13 @@ pub const samples = 8; const vertex: abi.gpu.Shader = .{ .code = shaders.path_vert, .uniform_buffers = 1 }; const stencil_only: abi.gpu.Shader = .{ .code = shaders.stencil_frag }; +const painted_vertex: abi.gpu.Shader = .{ .code = shaders.paint_vert, .uniform_buffers = 1 }; +const painted_fragment: abi.gpu.Shader = .{ .code = shaders.paint_frag, .storage_buffers = 1 }; + +pub const Pipeline = enum(u32) { nonzero, evenodd, cover, direct }; const pipelines = [_]abi.gpu.Pipeline{ - // 0: nonzero winding. + // Stencil fans, nonzero winding. abi.gpu.pipeline(layouts.Vertex, .{ .vertex = vertex, .fragment = stencil_only, @@ -31,7 +52,7 @@ const pipelines = [_]abi.gpu.Pipeline{ .write_color = false, .stencil = .{ .front = .{ .pass = .increment_and_wrap }, .back = .{ .pass = .decrement_and_wrap } }, }), - // 1: even-odd. + // Stencil fans, even-odd. abi.gpu.pipeline(layouts.Vertex, .{ .vertex = vertex, .fragment = stencil_only, @@ -39,30 +60,58 @@ const pipelines = [_]abi.gpu.Pipeline{ .write_color = false, .stencil = .{ .front = .{ .pass = .invert }, .back = .{ .pass = .invert } }, }), - // 2: cover. - abi.gpu.pipeline(layouts.Vertex, .{ - .vertex = vertex, - .fragment = .{ .code = shaders.cover_frag, .uniform_buffers = 1 }, + // Cover boxes. + abi.gpu.pipeline(layouts.Painted, .{ + .vertex = painted_vertex, + .fragment = painted_fragment, .stencil = .{ .front = .{ .compare = .not_equal, .pass = .zero }, .back = .{ .compare = .not_equal, .pass = .zero }, }, }), + // Convex fills, drawn directly. + abi.gpu.pipeline(layouts.Painted, .{ .vertex = painted_vertex, .fragment = painted_fragment }), +}; + +/// One layer's triangles, one draw each. +const Layer = struct { + /// Stencil fans by fill rule. + stencil: [2]std.ArrayList(layouts.Vertex) = .{ .empty, .empty }, + cover: std.ArrayList(layouts.Painted) = .empty, + direct: std.ArrayList(layouts.Painted) = .empty, }; +/// The overlap grid's cells are 2^shift pixels square. +const min_shift = 2; +const max_cells = 1 << 16; + width: u32, height: u32, image: abi.Image, /// Frame lifetime: the pass's vertices and uniforms live here until the /// host consumes the frame. arena: std.mem.Allocator = undefined, -draws: std.ArrayList(abi.gpu.Draw) = .empty, clear_color: [4]f32 = .{ 0, 0, 0, 0 }, viewport: []const u8 = &.{}, +layers: std.ArrayList(Layer) = .empty, +/// The gradients of this pass's fills, uploaded by `upload`. +paints: std.ArrayList(layouts.Paint) = .empty, +/// Per grid cell: 1 + the highest layer of a fill touching it; 0 if none. +grid: []u32 = &.{}, +shift: u5 = min_shift, +columns: u32 = 0, +draws: std.ArrayList(abi.gpu.Draw) = .empty, +/// GPU memory for `paints`, kept across frames: made, and remade larger, +/// by `upload`; freed by the renderer's `deinit`. +paint_buffer: abi.Buffer = .none, +paint_capacity: u32 = 0, pub fn begin(g: *Gpu, arena: std.mem.Allocator, clear: Drawing.Color) void { g.arena = arena; g.draws = .empty; + g.layers = .empty; + g.paints = .empty; + g.grid = &.{}; g.clear_color = Paint.premultiply(clear); g.viewport = abi.gpu.uniform(arena, layouts.Viewport{ .size = .{ @floatFromInt(g.width), @floatFromInt(g.height) } }); } @@ -73,45 +122,97 @@ pub fn fill(g: *Gpu, polys: *const Polygons, rule: Drawing.FillRule, paint: *con } fn record(g: *Gpu, polys: *const Polygons, rule: Drawing.FillRule, paint: *const Paint, alpha: f32) !void { + const b = polys.bounds(); + const lo = @max(@floor(b.min), geom.splat(0)); + const hi = @min(@ceil(b.max), geom.Vec{ @floatFromInt(g.width), @floatFromInt(g.height) }); + if (!(lo[0] < hi[0] and lo[1] < hi[1])) return; + const direct = polys.contours.items.len == 1 and Polygons.convex(polys.points.items); + const layer = try g.place(lo, hi, direct); + const p = try g.painted(paint, alpha); + if (direct) { + // A convex polygon's fan from its first point: no triangle overlaps + // another, so each sample inside is painted once. + const pts = polys.points.items; + const out = try layer.direct.addManyAsSlice(g.arena, (pts.len - 2) * 3); + for (1..pts.len - 1) |k| { + const tri = out[(k - 1) * 3 ..][0..3]; + tri.* = .{ p.at(pts[0]), p.at(pts[k]), p.at(pts[k + 1]) }; + } + return; + } // Fans from each contour's first point. Their overlaps cancel or add // exactly as the winding rule needs, so no triangulation is required. var triangles: usize = 0; var it = polys.iterator(); while (it.next()) |pts| triangles += pts.len - 2; - const fan = try g.arena.alloc(layouts.Vertex, triangles * 3); + const fan = try layer.stencil[@backingInt(rule)].addManyAsSlice(g.arena, triangles * 3); var i: usize = 0; it = polys.iterator(); while (it.next()) |pts| for (1..pts.len - 1) |k| { - fan[i + 0] = .{ .position = pts[0] }; - fan[i + 1] = .{ .position = pts[k] }; - fan[i + 2] = .{ .position = pts[k + 1] }; + fan[i..][0..3].* = .{ .{ .position = pts[0] }, .{ .position = pts[k] }, .{ .position = pts[k + 1] } }; i += 3; }; - const b = polys.bounds(); - const lo = @max(@floor(b.min), geom.splat(0)); - const hi = @min(@ceil(b.max), geom.Vec{ @floatFromInt(g.width), @floatFromInt(g.height) }); - if (lo[0] >= hi[0] or lo[1] >= hi[1]) return; - const quad = try g.arena.dupe(layouts.Vertex, &.{ - .{ .position = .{ lo[0], lo[1] } }, .{ .position = .{ hi[0], lo[1] } }, .{ .position = .{ hi[0], hi[1] } }, - .{ .position = .{ lo[0], lo[1] } }, .{ .position = .{ hi[0], hi[1] } }, .{ .position = .{ lo[0], hi[1] } }, - }); - try g.draws.append(g.arena, .{ - .pipeline = if (rule == .nonzero) 0 else 1, - .vertices = std.mem.sliceAsBytes(fan), - .vertex_count = @intCast(fan.len), - .vertex_uniforms = g.viewport, - }); - try g.draws.append(g.arena, .{ - .pipeline = 2, - .vertices = std.mem.sliceAsBytes(quad), - .vertex_count = 6, - .vertex_uniforms = g.viewport, - .fragment_uniforms = abi.gpu.uniform(g.arena, block(paint, alpha)), + try layer.cover.appendSlice(g.arena, &.{ + p.at(.{ lo[0], lo[1] }), p.at(.{ hi[0], lo[1] }), p.at(.{ hi[0], hi[1] }), + p.at(.{ lo[0], lo[1] }), p.at(.{ hi[0], hi[1] }), p.at(.{ lo[0], hi[1] }), }); } -/// `Paint` as the shader's uniform block. More stops than the block holds -/// are resampled evenly. +/// The layer for a fill covering pixels `lo` to `hi`, its cells marked. +fn place(g: *Gpu, lo: geom.Vec, hi: geom.Vec, direct: bool) !*Layer { + if (g.grid.len == 0) { + g.shift = min_shift; + while (cells(g.width, g.shift) * cells(g.height, g.shift) > max_cells) g.shift += 1; + g.columns = cells(g.width, g.shift); + g.grid = try g.arena.alloc(u32, g.columns * cells(g.height, g.shift)); + @memset(g.grid, 0); + } + const x0: u32 = @as(u32, @intFromFloat(lo[0])) >> g.shift; + const y0: u32 = @as(u32, @intFromFloat(lo[1])) >> g.shift; + const x1: u32 = (@as(u32, @intFromFloat(hi[0])) - 1) >> g.shift; + const y1: u32 = (@as(u32, @intFromFloat(hi[1])) - 1) >> g.shift; + var top: u32 = 0; + for (y0..y1 + 1) |y| for (g.grid[y * g.columns ..][x0 .. x1 + 1]) |cell| { + top = @max(top, cell); + }; + const index = layerFor(top, direct); + for (y0..y1 + 1) |y| for (g.grid[y * g.columns ..][x0 .. x1 + 1]) |*cell| { + cell.* = @max(cell.*, index + 1); + }; + while (g.layers.items.len <= index) try g.layers.append(g.arena, .{}); + return &g.layers.items[index]; +} + +/// The layer for a fill whose box overlaps fills up to layer `top - 1` +/// (`top` 0: none). A direct fill may join that layer; a stencilled one +/// goes above it. +pub fn layerFor(top: u32, direct: bool) u32 { + if (top == 0) return 0; + return if (direct) top - 1 else top; +} + +fn cells(pixels: u32, shift: u5) u32 { + return @max((pixels + (@as(u32, 1) << shift) - 1) >> shift, 1); +} + +/// A fill's paint, as its vertices carry it. +const Painted = struct { + color: [4]f32, + gradient: f32, + + fn at(p: Painted, q: geom.Vec) layouts.Painted { + return .{ .position = q, .color = p.color, .gradient = p.gradient }; + } +}; + +fn painted(g: *Gpu, paint: *const Paint, alpha: f32) !Painted { + if (paint.kind == .solid) return .{ .color = paint.color * @as(@Vector(4, f32), @splat(alpha)), .gradient = -1 }; + try g.paints.append(g.arena, block(paint, alpha)); + return .{ .color = @splat(alpha), .gradient = @floatFromInt(g.paints.items.len - 1) }; +} + +/// `Paint` as the shader's block. More stops than the block holds are +/// resampled evenly. fn block(paint: *const Paint, alpha: f32) layouts.Paint { const m = paint.to_gradient; var out: layouts.Paint = .{ @@ -140,8 +241,36 @@ fn unpremultiply(c: @Vector(4, f32)) [4]f32 { return .{ c[0] / c[3], c[1] / c[3], c[2] / c[3], c[3] }; } +/// Puts this pass's gradients in GPU memory, before `pass`. `f` is a +/// `sketch.Frame`. Painted draws bind the buffer even when no fill has a +/// gradient, so there always is one. +pub fn upload(g: *Gpu, f: anytype) void { + const count: u32 = @intCast(@max(g.paints.items.len, 1)); + if (count > g.paint_capacity) { + if (g.paint_buffer != .none) f.host.freeBuffer(g.paint_buffer); + const capacity = std.math.ceilPowerOfTwo(u32, count) catch count; + g.paint_buffer = f.host.newBuffer(capacity * @sizeOf(layouts.Paint)); + g.paint_capacity = if (g.paint_buffer == .none) 0 else capacity; + } + if (g.paints.items.len > 0 and g.paint_buffer != .none) f.upload(g.paint_buffer, 0, std.mem.sliceAsBytes(g.paints.items)); +} + +/// Frees what `upload` made. `host` is a `sketch.Host`. +pub fn deinit(g: *Gpu, host: anytype) void { + if (g.paint_buffer != .none) host.freeBuffer(g.paint_buffer); + g.paint_buffer = .none; + g.paint_capacity = 0; +} + /// The pass that draws everything recorded since `begin`. -pub fn pass(g: *const Gpu) abi.gpu.Pass { +pub fn pass(g: *Gpu) abi.gpu.Pass { + g.draws = .empty; + const storage = g.arena.dupe(abi.Buffer, &.{g.paint_buffer}) catch &.{}; + for (g.layers.items) |*layer| { + for (layer.stencil, [_]Pipeline{ .nonzero, .evenodd }) |fans, pipeline| g.add(pipeline, std.mem.sliceAsBytes(fans.items), fans.items.len, storage); + g.add(.cover, std.mem.sliceAsBytes(layer.cover.items), layer.cover.items.len, storage); + g.add(.direct, std.mem.sliceAsBytes(layer.direct.items), layer.direct.items.len, storage); + } return .{ .image = g.image, .width = g.width, @@ -154,21 +283,151 @@ pub fn pass(g: *const Gpu) abi.gpu.Pass { }; } -test "a fill is a stencil fan and a covering quad with its paint" { - var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); - defer arena.deinit(); - var g: Gpu = .{ .width = 100, .height = 50, .image = @fromBackingInt(@intCast(1)) }; - g.begin(arena.allocator(), .{ 0, 0, 0, 1 }); - var p: Polygons = .init(arena.allocator()); - try p.points.appendSlice(arena.allocator(), &.{ .{ 10, 10 }, .{ 40, 10 }, .{ 40, 30 }, .{ 10, 30 } }); - try p.contours.append(arena.allocator(), 4); - const red: Paint = .solid(.{ 1, 0, 0, 1 }); - g.fill(&p, .evenodd, &red, 0.5); - const pass_ = g.pass(); - try std.testing.expectEqual(@as(usize, 2), pass_.draws.len); - try std.testing.expectEqual(@as(u32, 1), pass_.draws[0].pipeline); - try std.testing.expectEqual(@as(u32, 6), pass_.draws[0].vertex_count); - const block_ = std.mem.bytesAsValue(layouts.Paint, pass_.draws[1].fragment_uniforms); - try std.testing.expectEqual(@as(f32, 0.5), block_.extra[1]); - try std.testing.expectEqual(@as(f32, 1), block_.color[0]); +fn add(g: *Gpu, pipeline: Pipeline, vertices: []const u8, count: usize, storage: []const abi.Buffer) void { + if (count == 0) return; + const painted_ = pipeline == .cover or pipeline == .direct; + g.draws.append(g.arena, .{ + .pipeline = @backingInt(pipeline), + .vertices = vertices, + .vertex_count = @intCast(count), + .vertex_uniforms = g.viewport, + .fragment_storage = if (painted_) storage else &.{}, + }) catch {}; +} + +// --------------------------------------------------------------------------- +// Tests + +const Test = struct { + arena: std.heap.ArenaAllocator, + g: Gpu, + p: Polygons, + + fn init(t: *Test) void { + t.arena = .init(std.testing.allocator); + t.g = .{ .width = 100, .height = 50, .image = @fromBackingInt(@intCast(1)) }; + t.g.begin(t.arena.allocator(), .{ 0, 0, 0, 1 }); + t.p = .init(t.arena.allocator()); + } + + fn deinit(t: *Test) void { + t.arena.deinit(); + } + + /// Fills the contours `shape`, offset by `at`. + fn fill(t: *Test, shape: []const []const geom.Vec, at: geom.Vec, rule: Drawing.FillRule, paint: Paint) !void { + t.p.clear(); + for (shape) |pts| { + for (pts) |q| try t.p.points.append(t.arena.allocator(), q + at); + try t.p.contours.append(t.arena.allocator(), @intCast(pts.len)); + } + t.g.fill(&t.p, rule, &paint, 1); + } + + fn pipelinesOf(t: *Test) ![]const Pipeline { + const draws = t.g.pass().draws; + const out = try t.arena.allocator().alloc(Pipeline, draws.len); + for (draws, out) |d, *o| o.* = @fromBackingInt(@intCast(d.pipeline)); + return out; + } +}; + +const square: []const []const geom.Vec = &.{&.{ .{ 0, 0 }, .{ 10, 0 }, .{ 10, 10 }, .{ 0, 10 } }}; +/// Not convex: two contours. +const ring: []const []const geom.Vec = &.{ &.{ .{ 0, 0 }, .{ 10, 0 }, .{ 10, 10 }, .{ 0, 10 } }, &.{ .{ 3, 3 }, .{ 3, 7 }, .{ 7, 7 }, .{ 7, 3 } } }; +const red: Paint = .solid(.{ 1, 0, 0, 1 }); + +test "a convex fill is one painted fan, no stencil" { + var t: Test = undefined; + t.init(); + defer t.deinit(); + try t.fill(square, .{ 10, 10 }, .evenodd, red); + const draws = t.g.pass().draws; + try std.testing.expectEqual(@as(usize, 1), draws.len); + try std.testing.expectEqual(@backingInt(Pipeline.direct), draws[0].pipeline); + try std.testing.expectEqual(@as(u32, 6), draws[0].vertex_count); + const v = std.mem.bytesAsSlice(layouts.Painted, draws[0].vertices); + try std.testing.expectEqual([4]f32{ 1, 0, 0, 1 }, v[0].color); + try std.testing.expectEqual(@as(f32, -1), v[0].gradient); +} + +test "a fill that is not convex is a stencil fan and a covering quad with its paint" { + var t: Test = undefined; + t.init(); + defer t.deinit(); + t.p.clear(); + const half: Paint = .solid(.{ 1, 0, 0, 0.5 }); + try t.fill(ring, .{ 10, 10 }, .evenodd, half); + const draws = t.g.pass().draws; + try std.testing.expectEqualSlices(Pipeline, &.{ .evenodd, .cover }, try t.pipelinesOf()); + try std.testing.expectEqual(@as(u32, 12), draws[0].vertex_count); + try std.testing.expectEqual(@as(u32, 6), draws[1].vertex_count); + const v = std.mem.bytesAsSlice(layouts.Painted, draws[1].vertices); + try std.testing.expectEqual([4]f32{ 0.5, 0, 0, 0.5 }, v[0].color); + try std.testing.expectEqual(geom.Vec{ 10, 10 }, v[0].position); + try std.testing.expectEqual(geom.Vec{ 20, 20 }, v[2].position); +} + +test "fills batch into layers: disjoint ones share draws, overlapping ones keep their order" { + var t: Test = undefined; + t.init(); + defer t.deinit(); + // Three disjoint rings, both rules: one layer, a stencil draw per rule + // and one cover draw for all three. + try t.fill(ring, .{ 0, 0 }, .nonzero, red); + try t.fill(ring, .{ 30, 0 }, .evenodd, red); + try t.fill(ring, .{ 60, 0 }, .nonzero, red); + try std.testing.expectEqualSlices(Pipeline, &.{ .nonzero, .evenodd, .cover }, try t.pipelinesOf()); + try std.testing.expectEqual(@as(u32, 18), t.g.pass().draws[2].vertex_count); + // A convex fill over the first ring joins its layer, drawn after the + // covers; a second one over it too, after it. + try t.fill(square, .{ 5, 5 }, .nonzero, red); + try t.fill(square, .{ 8, 8 }, .nonzero, red); + try std.testing.expectEqualSlices(Pipeline, &.{ .nonzero, .evenodd, .cover, .direct }, try t.pipelinesOf()); + // A ring over those goes above them; so does a convex fill over it. + try t.fill(ring, .{ 10, 10 }, .nonzero, red); + try t.fill(square, .{ 12, 12 }, .nonzero, red); + try std.testing.expectEqualSlices(Pipeline, &.{ .nonzero, .evenodd, .cover, .direct, .nonzero, .cover, .direct }, try t.pipelinesOf()); + // Far from everything: the bottom layer again. + try t.fill(ring, .{ 80, 30 }, .evenodd, red); + try std.testing.expectEqualSlices(Pipeline, &.{ .nonzero, .evenodd, .cover, .direct, .nonzero, .cover, .direct }, try t.pipelinesOf()); + try std.testing.expectEqual(@as(u32, 24), t.g.pass().draws[2].vertex_count); +} + +test "layers: stencilled fills go above what they overlap, direct ones join it" { + try std.testing.expectEqual(@as(u32, 0), layerFor(0, false)); + try std.testing.expectEqual(@as(u32, 0), layerFor(0, true)); + try std.testing.expectEqual(@as(u32, 3), layerFor(3, false)); + try std.testing.expectEqual(@as(u32, 2), layerFor(3, true)); +} + +test "gradients go to the paint buffer, their vertices carry the index and alpha" { + var t: Test = undefined; + t.init(); + defer t.deinit(); + const stops = [_]Drawing.Gradient.Stop{ .{ .offset = 0, .color = .{ 1, 0, 0, 1 } }, .{ .offset = 1, .color = .{ 0, 0, 1, 1 } } }; + const gradient: Paint = .{ .kind = .linear, .p1 = .{ 1, 0 }, .stops = &stops }; + try t.fill(square, .{ 0, 0 }, .nonzero, red); + t.p.clear(); + try t.p.points.appendSlice(t.arena.allocator(), &.{ .{ 30, 0 }, .{ 40, 0 }, .{ 40, 10 }, .{ 30, 10 } }); + try t.p.contours.append(t.arena.allocator(), 4); + t.g.fill(&t.p, .nonzero, &gradient, 0.25); + try std.testing.expectEqual(@as(usize, 1), t.g.paints.items.len); + try std.testing.expectEqual(@as(f32, 2), t.g.paints.items[0].extra[2]); + const draws = t.g.pass().draws; + try std.testing.expectEqual(@as(usize, 1), draws.len); + try std.testing.expectEqual(@as(usize, 1), draws[0].fragment_storage.len); + const v = std.mem.bytesAsSlice(layouts.Painted, draws[0].vertices); + try std.testing.expectEqual(@as(f32, -1), v[0].gradient); + try std.testing.expectEqual(@as(f32, 0), v[6].gradient); + try std.testing.expectEqual([4]f32{ 0.25, 0.25, 0.25, 0.25 }, v[6].color); +} + +test "fills outside the image draw nothing" { + var t: Test = undefined; + t.init(); + defer t.deinit(); + try t.fill(square, .{ 200, 0 }, .nonzero, red); + try t.fill(ring, .{ -50, 0 }, .nonzero, red); + try std.testing.expectEqual(@as(usize, 0), t.g.pass().draws.len); } diff --git a/src/vector/Paint.zig b/src/vector/Paint.zig index fb838d0..0c56588 100644 --- a/src/vector/Paint.zig +++ b/src/vector/Paint.zig @@ -4,7 +4,7 @@ //! which mirrors `param` and `stopColor`. const Paint = @This(); const std = @import("std"); -const geom = @import("geom.zig"); +const geom = @import("math"); const Drawing = @import("Drawing.zig"); const Vec = geom.Vec; diff --git a/src/vector/Polygons.zig b/src/vector/Polygons.zig index c0ed335..c64db3d 100644 --- a/src/vector/Polygons.zig +++ b/src/vector/Polygons.zig @@ -4,7 +4,7 @@ //! the same way, so the nonzero rule unions them. const Polygons = @This(); const std = @import("std"); -const geom = @import("geom.zig"); +const geom = @import("math"); const Drawing = @import("Drawing.zig"); const Vec = geom.Vec; const Affine = geom.Affine; @@ -97,6 +97,44 @@ pub fn bounds(p: *const Polygons) geom.Bounds { return b; } +/// Whether `pts`, as a closed contour, is a convex polygon going around once: +/// every turn the same way (straight runs and repeated points allowed), and +/// the edge direction's x flips sign at most twice, which rules out +/// spirals. Its fan from any point then covers each inside point once and +/// nothing outside, under either fill rule. Exact: the slightest reflex +/// turn says no. +pub fn convex(pts: []const Vec) bool { + var turn: f32 = 0; + var flips: u32 = 0; + var first: ?Vec = null; + var prev: Vec = undefined; + var first_sign: f32 = 0; + var last_sign: f32 = 0; + for (0..pts.len) |i| { + const e = pts[(i + 1) % pts.len] - pts[i]; + if (e[0] == 0 and e[1] == 0) continue; + if (first == null) first = e else if (!turns(prev, e, &turn)) return false; + prev = e; + if (e[0] != 0) { + const sign = std.math.sign(e[0]); + if (first_sign == 0) first_sign = sign else if (sign != last_sign) flips += 1; + last_sign = sign; + } + } + if (!turns(prev, first orelse return false, &turn)) return false; + if (last_sign != first_sign) flips += 1; + return turn != 0 and flips <= 2; +} + +/// Whether the corner from edge `a` to edge `b` turns the way `turn` (the +/// first nonzero cross product so far) does, or goes straight on. +fn turns(a: Vec, b: Vec, turn: *f32) bool { + const cross = geom.cross(a, b); + if (cross == 0) return geom.dot(a, b) > 0; + if (turn.* == 0) turn.* = cross; + return (cross > 0) == (turn.* > 0); +} + /// Iterates contours as point slices. pub fn iterator(p: *const Polygons) Iterator { return .{ .p = p }; @@ -368,6 +406,25 @@ fn truncate(list: *std.ArrayList(Vec), len: f32) []const Vec { return pts; } +test "convex contours" { + const square = [_]Vec{ .{ 0, 0 }, .{ 10, 0 }, .{ 10, 10 }, .{ 0, 10 } }; + try std.testing.expect(convex(&square)); + // Either orientation, repeated points, a closing point equal to the + // first, straight runs. + try std.testing.expect(convex(&.{ .{ 0, 10 }, .{ 10, 10 }, .{ 10, 0 }, .{ 0, 0 } })); + try std.testing.expect(convex(&.{ .{ 0, 0 }, .{ 5, 0 }, .{ 5, 0 }, .{ 10, 0 }, .{ 10, 10 }, .{ 0, 10 }, .{ 0, 0 } })); + // A reflex corner (an L), a bow tie, a pentagram, a square wound twice, + // a line and a point. + try std.testing.expect(!convex(&.{ .{ 0, 0 }, .{ 10, 0 }, .{ 10, 5 }, .{ 5, 5 }, .{ 5, 10 }, .{ 0, 10 } })); + try std.testing.expect(!convex(&.{ .{ 0, 0 }, .{ 10, 10 }, .{ 10, 0 }, .{ 0, 10 } })); + var star: [5]Vec = undefined; + for (&star, 0..) |*q, i| q.* = geom.unit(@as(f32, @floatFromInt(i * 2)) * std.math.tau / 5) * geom.splat(10); + try std.testing.expect(!convex(&star)); + try std.testing.expect(!convex(&(square ++ square))); + try std.testing.expect(!convex(&.{ .{ 0, 0 }, .{ 10, 0 }, .{ 20, 0 } })); + try std.testing.expect(!convex(&.{ .{ 1, 1 }, .{ 1, 1 }, .{ 1, 1 } })); +} + test "a square stroke is four quads and four miters, all wound one way" { var p: Polygons = .init(std.testing.allocator); defer p.deinit(); diff --git a/src/vector/geom.zig b/src/vector/geom.zig deleted file mode 100644 index b80c55a..0000000 --- a/src/vector/geom.zig +++ /dev/null @@ -1,239 +0,0 @@ -//! Points, affine transforms and cubic Béziers: the only geometry there is. -//! Every path is a list of cubics, lines included, as in manim: one shape of -//! data makes morphing and partial drawing plain arithmetic. -const std = @import("std"); - -pub const Vec = @Vector(2, f32); - -pub fn vec(x: f32, y: f32) Vec { - return .{ x, y }; -} -pub fn dot(a: Vec, b: Vec) f32 { - return @reduce(.Add, a * b); -} -pub fn cross(a: Vec, b: Vec) f32 { - return a[0] * b[1] - a[1] * b[0]; -} -pub fn length(a: Vec) f32 { - return @sqrt(dot(a, a)); -} -pub fn splat(s: f32) Vec { - return @splat(s); -} -pub fn mix(a: Vec, b: Vec, t: f32) Vec { - return a + (b - a) * splat(t); -} -/// Perpendicular, rotated a quarter turn counterclockwise in y-down space. -pub fn perp(a: Vec) Vec { - return .{ a[1], -a[0] }; -} -pub fn normalize(a: Vec) Vec { - const l = length(a); - return if (l > 0) a / splat(l) else a; -} - -/// `[a c e; b d f]`, SVG's `matrix(a b c d e f)`. -pub const Affine = struct { - a: f32 = 1, - b: f32 = 0, - c: f32 = 0, - d: f32 = 1, - e: f32 = 0, - f: f32 = 0, - - pub const identity: Affine = .{}; - - pub fn translate(x: f32, y: f32) Affine { - return .{ .e = x, .f = y }; - } - pub fn scale(sx: f32, sy: f32) Affine { - return .{ .a = sx, .d = sy }; - } - pub fn rotate(radians: f32) Affine { - const c = @cos(radians); - const s = @sin(radians); - return .{ .a = c, .b = s, .c = -s, .d = c }; - } - pub fn skew(x: f32, y: f32) Affine { - return .{ .b = @tan(y), .c = @tan(x) }; - } - /// `self` after `inner`: apply `inner` first. - pub fn mul(self: Affine, inner: Affine) Affine { - return .{ - .a = self.a * inner.a + self.c * inner.b, - .b = self.b * inner.a + self.d * inner.b, - .c = self.a * inner.c + self.c * inner.d, - .d = self.b * inner.c + self.d * inner.d, - .e = self.a * inner.e + self.c * inner.f + self.e, - .f = self.b * inner.e + self.d * inner.f + self.f, - }; - } - pub fn apply(m: Affine, p: Vec) Vec { - return .{ m.a * p[0] + m.c * p[1] + m.e, m.b * p[0] + m.d * p[1] + m.f }; - } - pub fn applyVector(m: Affine, p: Vec) Vec { - return .{ m.a * p[0] + m.c * p[1], m.b * p[0] + m.d * p[1] }; - } - pub fn determinant(m: Affine) f32 { - return m.a * m.d - m.b * m.c; - } - /// How much the transform scales lengths, on average. - pub fn scaleFactor(m: Affine) f32 { - return @sqrt(@abs(m.determinant())); - } - pub fn invert(m: Affine) Affine { - const det = m.determinant(); - if (det == 0) return .{}; - const i = 1 / det; - return .{ - .a = m.d * i, - .b = -m.b * i, - .c = -m.c * i, - .d = m.a * i, - .e = (m.c * m.f - m.d * m.e) * i, - .f = (m.b * m.e - m.a * m.f) * i, - }; - } -}; - -pub const Rect = struct { - x: f32 = 0, - y: f32 = 0, - w: f32 = 0, - h: f32 = 0, - - pub fn center(r: Rect) Vec { - return .{ r.x + r.w / 2, r.y + r.h / 2 }; - } -}; - -/// Growing bounds over points. -pub const Bounds = struct { - min: Vec = splat(std.math.inf(f32)), - max: Vec = splat(-std.math.inf(f32)), - - pub fn add(b: *Bounds, p: Vec) void { - b.min = @min(b.min, p); - b.max = @max(b.max, p); - } - pub fn empty(b: Bounds) bool { - return b.min[0] > b.max[0]; - } - pub fn rect(b: Bounds) Rect { - if (b.empty()) return .{}; - return .{ .x = b.min[0], .y = b.min[1], .w = b.max[0] - b.min[0], .h = b.max[1] - b.min[1] }; - } -}; - -/// A cubic's four control points. -pub const Cubic = [4]Vec; - -pub fn line(a: Vec, b: Vec) Cubic { - return .{ a, mix(a, b, 1.0 / 3.0), mix(a, b, 2.0 / 3.0), b }; -} - -pub fn quad(a: Vec, c: Vec, b: Vec) Cubic { - return .{ a, mix(a, c, 2.0 / 3.0), mix(b, c, 2.0 / 3.0), b }; -} - -pub fn eval(c: Cubic, t: f32) Vec { - const u = 1 - t; - return c[0] * splat(u * u * u) + c[1] * splat(3 * u * u * t) + c[2] * splat(3 * u * t * t) + c[3] * splat(t * t * t); -} - -/// de Casteljau: the two halves of `c` at `t`. -pub fn split(c: Cubic, t: f32) [2]Cubic { - const ab = mix(c[0], c[1], t); - const bc = mix(c[1], c[2], t); - const cd = mix(c[2], c[3], t); - const abc = mix(ab, bc, t); - const bcd = mix(bc, cd, t); - const p = mix(abc, bcd, t); - return .{ .{ c[0], ab, abc, p }, .{ p, bcd, cd, c[3] } }; -} - -/// Line segments needed to stay within `tolerance` of the curve. -pub fn flattenCount(c: Cubic, tolerance: f32) u32 { - const d1 = c[0] - splat(2) * c[1] + c[2]; - const d2 = c[1] - splat(2) * c[2] + c[3]; - const dd = @max(length(d1), length(d2)); - const n = @ceil(@sqrt(0.75 * dd / tolerance)); - return @intFromFloat(std.math.clamp(n, 1, 256)); -} - -/// A cheap length estimate: between chord and control polygon. -pub fn roughLength(c: Cubic) f32 { - const chord = length(c[3] - c[0]); - const polygon = length(c[1] - c[0]) + length(c[2] - c[1]) + length(c[3] - c[2]); - return (chord + polygon) / 2; -} - -/// Cubics for an SVG elliptical arc from `p0` to `p1` (endpoint form). -pub fn arc(out: *std.ArrayList(Cubic), gpa: std.mem.Allocator, p0: Vec, radii: Vec, x_rotation_degrees: f32, large: bool, sweep: bool, p1: Vec) !void { - var rx = @abs(radii[0]); - var ry = @abs(radii[1]); - if (rx == 0 or ry == 0 or @reduce(.And, p0 == p1)) { - if (!@reduce(.And, p0 == p1)) try out.append(gpa, line(p0, p1)); - return; - } - const phi = x_rotation_degrees * std.math.pi / 180; - const cos_phi = @cos(phi); - const sin_phi = @sin(phi); - const half = (p0 - p1) / splat(2); - const x1 = cos_phi * half[0] + sin_phi * half[1]; - const y1 = -sin_phi * half[0] + cos_phi * half[1]; - // Radii too small to reach are scaled up, as the SVG spec says. - const lambda = (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry); - if (lambda > 1) { - rx *= @sqrt(lambda); - ry *= @sqrt(lambda); - } - const num = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1; - const den = rx * rx * y1 * y1 + ry * ry * x1 * x1; - var coef = @sqrt(@max(0, num / den)); - if (large == sweep) coef = -coef; - const cx1 = coef * rx * y1 / ry; - const cy1 = -coef * ry * x1 / rx; - const mid = (p0 + p1) / splat(2); - const center: Vec = .{ cos_phi * cx1 - sin_phi * cy1 + mid[0], sin_phi * cx1 + cos_phi * cy1 + mid[1] }; - const start = std.math.atan2((y1 - cy1) / ry, (x1 - cx1) / rx); - var delta = std.math.atan2((-y1 - cy1) / ry, (-x1 - cx1) / rx) - start; - if (sweep and delta < 0) delta += 2 * std.math.pi; - if (!sweep and delta > 0) delta -= 2 * std.math.pi; - const pieces: u32 = @intFromFloat(@max(1, @ceil(@abs(delta) / (std.math.pi / 2.0) - 1e-4))); - const step = delta / @as(f32, @floatFromInt(pieces)); - const k = 4.0 / 3.0 * @tan(step / 4); - const m: Affine = (Affine{ .a = cos_phi, .b = sin_phi, .c = -sin_phi, .d = cos_phi, .e = center[0], .f = center[1] }).mul(.scale(rx, ry)); - var angle = start; - var from = p0; - for (0..pieces) |i| { - const next = angle + step; - const a: Vec = .{ @cos(angle), @sin(angle) }; - const b: Vec = .{ @cos(next), @sin(next) }; - const to = if (i + 1 == pieces) p1 else m.apply(b); - try out.append(gpa, .{ from, m.apply(a + perp(a) * splat(-k)), m.apply(b - perp(b) * splat(-k)), to }); - from = to; - angle = next; - } -} - -test "affine composition and inversion round trip" { - const m = Affine.translate(10, 5).mul(.rotate(0.7)).mul(.scale(2, 3)); - const p = vec(3, -4); - const q = m.invert().apply(m.apply(p)); - try std.testing.expectApproxEqAbs(p[0], q[0], 1e-4); - try std.testing.expectApproxEqAbs(p[1], q[1], 1e-4); -} - -test "a half-circle arc stays on the circle" { - var cubics: std.ArrayList(Cubic) = .empty; - defer cubics.deinit(std.testing.allocator); - try arc(&cubics, std.testing.allocator, vec(-10, 0), vec(10, 10), 0, false, true, vec(10, 0)); - try std.testing.expectEqual(@as(usize, 2), cubics.items.len); - for (cubics.items) |c| for (0..9) |i| { - const r = length(eval(c, @as(f32, @floatFromInt(i)) / 8)); - try std.testing.expectApproxEqAbs(@as(f32, 10), r, 0.03); - }; - // Sweep flag 1 in y-down space goes through negative y. - try std.testing.expect(eval(cubics.items[0], 1)[1] < -9.9); -} diff --git a/src/vector/layouts.zig b/src/vector/layouts.zig index 097e682..5d17568 100644 --- a/src/vector/layouts.zig +++ b/src/vector/layouts.zig @@ -4,13 +4,26 @@ pub const max_stops = 32; -/// A path point in device pixels. +/// A path point in device pixels, for stencil fans. pub const Vertex = extern struct { position: [2]f32, pub const glsl = .vertex; }; +/// A point of a painted triangle (a cover quad, or a convex fill's fan), +/// carrying its fill's paint, so fills of any paint share one draw. +pub const Painted = extern struct { + position: [2]f32, + /// Solid paints: the premultiplied color times the fill's alpha. + /// Gradients: the alpha, in all four. + color: [4]f32, + /// The gradient's index in the pass's `Paint` buffer; -1 for solid. + gradient: f32, + + pub const glsl = .vertex; +}; + pub const Viewport = extern struct { size: [2]f32, pad: [2]f32 = .{ 0, 0 }, @@ -18,7 +31,8 @@ pub const Viewport = extern struct { pub const glsl = .{ .uniform = .{ .set = 1, .instance = "viewport" } }; }; -/// A resolved `Paint`, as `cover.frag` reads it. +/// A resolved gradient `Paint`, as `paint.frag` reads it from a storage +/// buffer (all members are vec4s, so std430 lays it out as std140 would). pub const Paint = extern struct { /// Premultiplied solid color. color: [4]f32, @@ -29,12 +43,12 @@ pub const Paint = extern struct { row1: [4]f32, /// p0 then p1. points: [4]f32, - /// Radius, alpha, stop count. + /// Radius, alpha (unused: the vertices carry it), stop count. extra: [4]f32, /// Stop offsets, four per element. offsets: [max_stops / 4][4]f32, /// Straight stop colors. colors: [max_stops][4]f32, - pub const glsl = .{ .uniform = .{ .set = 3, .instance = "paint" } }; + pub const glsl = .plain; }; diff --git a/src/vector/morph.zig b/src/vector/morph.zig index 319eccf..f285c7e 100644 --- a/src/vector/morph.zig +++ b/src/vector/morph.zig @@ -4,7 +4,7 @@ //! color is interpolated. A shape without a partner collapses to (or grows //! from) the other drawing's center. const std = @import("std"); -const geom = @import("geom.zig"); +const geom = @import("math"); const Drawing = @import("Drawing.zig"); const Vec = geom.Vec; const Cubic = geom.Cubic; diff --git a/src/vector/root.zig b/src/vector/root.zig index 0414286..e5e9975 100644 --- a/src/vector/root.zig +++ b/src/vector/root.zig @@ -1,11 +1,12 @@ //! Vector graphics for sketches: SVG in, cubic geometry as data, and two //! interchangeable renderers. The CPU backend computes exact coverage and //! runs anywhere (it is also the reference in tests); the GPU backend -//! describes stencil-then-cover passes for the host to run. The backend is +//! describes passes for the host to run: convex fills drawn directly, the +//! rest stencil-then-cover, batched into a few draws (see `Gpu.zig`). The backend is //! a comptime choice: `vector.Renderer(.gpu)` or `vector.Renderer(.cpu)`. const std = @import("std"); const abi = @import("abi"); -pub const geom = @import("geom.zig"); +pub const geom = @import("math"); pub const Drawing = @import("Drawing.zig"); pub const svg = @import("svg.zig"); pub const Polygons = @import("Polygons.zig"); @@ -57,7 +58,10 @@ pub fn Renderer(comptime backend: Backend) type { } pub fn deinit(r: *Self, host: anytype) void { - if (backend == .cpu) r.target.deinit(); + switch (backend) { + .cpu => r.target.deinit(), + .gpu => r.target.deinit(host), + } r.polys.deinit(); host.freeImage(r.image); } @@ -118,7 +122,10 @@ pub fn Renderer(comptime backend: Backend) type { pub fn present(r: *Self, f: anytype, dst: anytype) void { switch (backend) { .cpu => f.pixels(r.image, r.target.width, r.target.height, r.target.pixels, .{ .premultiplied = true }), - .gpu => f.gpu(r.target.pass()), + .gpu => { + r.target.upload(f); + f.gpu(r.target.pass()); + }, } f.image(r.image, dst, .{}); } diff --git a/src/vector/shaders/cover.frag b/src/vector/shaders/cover.frag deleted file mode 100644 index a57a916..0000000 --- a/src/vector/shaders/cover.frag +++ /dev/null @@ -1,65 +0,0 @@ -#version 450 -#extension GL_GOOGLE_include_directive : require -// Paints the covered pixels. Mirrors vector/Paint.zig: `param` gives the -// gradient parameter, `stop_color` the color at it. The uniform block is -// generated from vector/layouts.zig. -layout(location = 0) out vec4 out_color; - -#include "Paint.glsl" - -float offset_at(int i) { - return paint.offsets[i / 4][i % 4]; -} - -vec4 premultiply(vec4 c) { - return vec4(c.rgb * c.a, c.a); -} - -float param(vec2 q) { - vec2 g = vec2(dot(paint.row0.xyz, vec3(q, 1.0)), dot(paint.row1.xyz, vec3(q, 1.0))); - vec2 p0 = paint.points.xy; - vec2 p1 = paint.points.zw; - float t = 0.0; - if (paint.row0.w < 1.5) { - vec2 dir = p1 - p0; - float len2 = dot(dir, dir); - t = len2 > 0.0 ? dot(g - p0, dir) / len2 : 0.0; - } else { - // Where the ray from the focus through g meets the circle. - vec2 dq = g - p1; - vec2 cf = p1 - p0; - float a = dot(dq, dq); - if (a > 0.0) { - float b = dot(dq, cf); - float c = dot(cf, cf) - paint.extra.x * paint.extra.x; - float s = (-b + sqrt(max(b * b - a * c, 0.0))) / a; - t = s > 0.0 ? 1.0 / s : 1.0; - } - } - if (paint.row1.w < 0.5) return clamp(t, 0.0, 1.0); - if (paint.row1.w < 1.5) { - float r = mod(t, 2.0); - return r > 1.0 ? 2.0 - r : r; - } - return t - floor(t); -} - -vec4 stop_color(float t) { - int count = int(paint.extra.z); - if (count == 0) return vec4(0.0); - if (t <= offset_at(0)) return premultiply(paint.colors[0]); - for (int i = 1; i < count; i++) { - float b = offset_at(i); - if (t <= b) { - float a = offset_at(i - 1); - float u = b > a ? (t - a) / (b - a) : 1.0; - return premultiply(mix(paint.colors[i - 1], paint.colors[i], u)); - } - } - return premultiply(paint.colors[count - 1]); -} - -void main() { - vec4 c = paint.row0.w < 0.5 ? paint.color : stop_color(param(gl_FragCoord.xy)); - out_color = c * paint.extra.y; -} diff --git a/src/vector/shaders/paint.frag b/src/vector/shaders/paint.frag new file mode 100644 index 0000000..97eb551 --- /dev/null +++ b/src/vector/shaders/paint.frag @@ -0,0 +1,69 @@ +#version 450 +#extension GL_GOOGLE_include_directive : require +// Paints a fill: its solid color, or its gradient times its alpha. A draw +// holds many fills, so each vertex says which (paint.vert). Mirrors +// vector/Paint.zig: `param` gives the gradient parameter, `stop_color` the +// color at it. The Paint struct is generated from vector/layouts.zig. +layout(location = 0) flat in vec4 fill_color; +layout(location = 1) flat in int fill_gradient; +layout(location = 0) out vec4 out_color; + +#include "Paint.glsl" +layout(set = 2, binding = 0, std430) readonly buffer Paints { Paint paints[]; }; +#define paint paints[fill_gradient] + +float offset_at(int i) { + return paint.offsets[i / 4][i % 4]; +} + +vec4 premultiply(vec4 c) { + return vec4(c.rgb * c.a, c.a); +} + +float param(vec2 q) { + vec2 g = vec2(dot(paint.row0.xyz, vec3(q, 1.0)), dot(paint.row1.xyz, vec3(q, 1.0))); + vec2 p0 = paint.points.xy; + vec2 p1 = paint.points.zw; + float t = 0.0; + if (paint.row0.w < 1.5) { + vec2 dir = p1 - p0; + float len2 = dot(dir, dir); + t = len2 > 0.0 ? dot(g - p0, dir) / len2 : 0.0; + } else { + // Where the ray from the focus through g meets the circle. + vec2 dq = g - p1; + vec2 cf = p1 - p0; + float a = dot(dq, dq); + if (a > 0.0) { + float b = dot(dq, cf); + float c = dot(cf, cf) - paint.extra.x * paint.extra.x; + float s = (-b + sqrt(max(b * b - a * c, 0.0))) / a; + t = s > 0.0 ? 1.0 / s : 1.0; + } + } + if (paint.row1.w < 0.5) return clamp(t, 0.0, 1.0); + if (paint.row1.w < 1.5) { + float r = mod(t, 2.0); + return r > 1.0 ? 2.0 - r : r; + } + return t - floor(t); +} + +vec4 stop_color(float t) { + int count = int(paint.extra.z); + if (count == 0) return vec4(0.0); + if (t <= offset_at(0)) return premultiply(paint.colors[0]); + for (int i = 1; i < count; i++) { + float b = offset_at(i); + if (t <= b) { + float a = offset_at(i - 1); + float u = b > a ? (t - a) / (b - a) : 1.0; + return premultiply(mix(paint.colors[i - 1], paint.colors[i], u)); + } + } + return premultiply(paint.colors[count - 1]); +} + +void main() { + out_color = fill_gradient < 0 ? fill_color : stop_color(param(gl_FragCoord.xy)) * fill_color; +} diff --git a/src/vector/shaders/paint.vert b/src/vector/shaders/paint.vert new file mode 100644 index 0000000..89c2c82 --- /dev/null +++ b/src/vector/shaders/paint.vert @@ -0,0 +1,15 @@ +#version 450 +#extension GL_GOOGLE_include_directive : require +// Painted triangles: device pixels (y down) to normalized device +// coordinates (y up), as in path.vert, with the fill's paint passed on. +#include "Painted.glsl" +#include "Viewport.glsl" + +layout(location = 0) flat out vec4 fill_color; +layout(location = 1) flat out int fill_gradient; + +void main() { + gl_Position = vec4(position.x / viewport.size.x * 2.0 - 1.0, 1.0 - position.y / viewport.size.y * 2.0, 0.0, 1.0); + fill_color = color; + fill_gradient = int(gradient); +} diff --git a/src/vector/svg.zig b/src/vector/svg.zig index 9c0ec53..31d9b15 100644 --- a/src/vector/svg.zig +++ b/src/vector/svg.zig @@ -10,7 +10,7 @@ //! patterns, markers, images, CSS stylesheets. Group opacity is approximated //! by multiplying it into each shape. const std = @import("std"); -const geom = @import("geom.zig"); +const geom = @import("math"); const Drawing = @import("Drawing.zig"); const Vec = geom.Vec; const Affine = geom.Affine; -- cgit v1.3